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 saved task searches to spaces (#83522)

Shy Alter5c28edaea73c
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index e9cf38793c7d..2c18faa9f535 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -1,3 +1,4 @@
+import type { Task } from "@posthog/shared/domain-types";
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "./fetcher";
import {
@@ -9,6 +10,58 @@ import {
} from "./posthog-client";
describe("PostHogAPIClient", () => {
+ it("fetches later task pages before reporting complete results", async () => {
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ );
+ const getTasksPage = vi
+ .spyOn(client, "getTasksPage")
+ .mockResolvedValueOnce({ tasks: [{ id: "task-1" } as Task], count: 2 })
+ .mockResolvedValueOnce({ tasks: [{ id: "task-2" } as Task], count: 2 });
+
+ await expect(
+ client.getTasksWithStatus(
+ { repository: "posthog/posthog" },
+ { maxPages: 2 },
+ ),
+ ).resolves.toMatchObject({
+ isComplete: true,
+ tasks: [{ id: "task-1" }, { id: "task-2" }],
+ });
+ expect(getTasksPage).toHaveBeenNthCalledWith(1, {
+ limit: 100,
+ offset: 0,
+ repository: "posthog/posthog",
+ });
+ expect(getTasksPage).toHaveBeenNthCalledWith(2, {
+ limit: 100,
+ offset: 1,
+ repository: "posthog/posthog",
+ });
+ });
+
+ it("reports partial task results after reaching the page cap", async () => {
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ );
+ vi.spyOn(client, "getTasksPage")
+ .mockResolvedValueOnce({ tasks: [{ id: "task-1" } as Task], count: 3 })
+ .mockResolvedValueOnce({ tasks: [{ id: "task-2" } as Task], count: 3 });
+
+ await expect(
+ client.getTasksWithStatus(undefined, { maxPages: 2 }),
+ ).resolves.toMatchObject({
+ isComplete: false,
+ tasks: [{ id: "task-1" }, { id: "task-2" }],
+ });
+ });
+
it.each([
"user_message",
"permission_response",
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index d0689209cca5..b53b4079d2b2 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -242,6 +242,16 @@ export interface TaskListOptions {
originProduct?: string;
internal?: boolean;
channel?: string;
+ /** Case-insensitive substring match over task title, description, and number. */
+ search?: string;
+ /** Filter by the status of the task's most recent run. */
+ status?: string;
+ /** Filter by the state of the latest run's pull request (open/draft/merged/closed). */
+ prState?: string;
+ /** Filter by the CI rollup on the latest run's pull request (passing/failing/pending/none). */
+ ciStatus?: string;
+ /** List only archived tasks; the server excludes them by default. */
+ archived?: boolean;
/** Caller-side cap for surfaces that only show the newest few. */
limit?: number;
/**
@@ -250,6 +260,8 @@ export interface TaskListOptions {
* few and a long-running session never makes the page.
*/
ordering?: "-last_activity_at" | "-created_at";
+ /** Zero-based offset for fetching a later task-list page. */
+ offset?: number;
}
export interface TaskSearchResult {
@@ -2311,6 +2323,30 @@ export class PostHogAPIClient {
return (await this.getTasksPage(options)).tasks;
}
+ async getTasksWithStatus(
+ options?: TaskListOptions,
+ pagination?: { maxPages?: number },
+ ): Promise<{ tasks: Task[]; isComplete: boolean }> {
+ const maxPages = pagination?.maxPages ?? 1;
+ const pageSize = Math.min(options?.limit ?? 100, 100);
+ const tasks: Task[] = [];
+ let count = 0;
+
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
+ const page = await this.getTasksPage({
+ ...options,
+ limit: pageSize,
+ offset: tasks.length,
+ });
+ tasks.push(...page.tasks);
+ count = page.count;
+ if (tasks.length >= count) return { tasks, isComplete: true };
+ if (page.tasks.length === 0) break;
+ }
+
+ return { tasks, isComplete: tasks.length >= count };
+ }
+
async searchTasks(query: string, limit = 20): Promise<TaskSearchResult[]> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/tasks/search/`;
@@ -2336,6 +2372,10 @@ export class PostHogAPIClient {
limit: options?.limit ?? 500,
};
+ if (options?.offset !== undefined) {
+ params.offset = options.offset;
+ }
+
if (options?.repository) {
params.repository = options.repository;
}
@@ -2356,6 +2396,26 @@ export class PostHogAPIClient {
params.channel = options.channel;
}
+ if (options?.search) {
+ params.search = options.search;
+ }
+
+ if (options?.status) {
+ params.status = options.status;
+ }
+
+ if (options?.prState) {
+ params.pr_state = options.prState;
+ }
+
+ if (options?.ciStatus) {
+ params.ci_status = options.ciStatus;
+ }
+
+ if (options?.archived) {
+ params.archived = "true";
+ }
+
if (options?.ordering) {
params.ordering = options.ordering;
}
diff --git a/products/desktop/packages/core/src/tasks/feedQuery.test.ts b/products/desktop/packages/core/src/tasks/feedQuery.test.ts
new file mode 100644
index 000000000000..13ff5685e6cf
--- /dev/null
+++ b/products/desktop/packages/core/src/tasks/feedQuery.test.ts
@@ -0,0 +1,501 @@
+import { describe, expect, it } from "vitest";
+import {
+ type FeedQueryPlanContext,
+ type FeedQueryTask,
+ lexFeedQuery,
+ parseFeedQuery,
+ planFeedQuery,
+ suggestFeedName,
+} 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,
+};
+
+function task(overrides: Partial<FeedQueryTask> = {}): FeedQueryTask {
+ return {
+ created_by: { uuid: "uuid-shy" },
+ channel: "space-mobile",
+ repository: "example-org/webapp",
+ origin_product: "user_created",
+ latest_run: { status: "completed", output: null },
+ ...overrides,
+ };
+}
+
+describe("feedQuery", () => {
+ describe("parseFeedQuery", () => {
+ it("splits filter tokens from free text", () => {
+ const parsed = parseFeedQuery("fix billing created-by:shy status:failed");
+ expect(parsed.text).toBe("fix billing");
+ expect(parsed.tokens).toEqual([
+ {
+ raw: "created-by:shy",
+ key: "created-by",
+ value: "shy",
+ negated: false,
+ },
+ {
+ raw: "status:failed",
+ key: "status",
+ value: "failed",
+ negated: false,
+ },
+ ]);
+ expect(parsed.issues).toEqual([]);
+ });
+
+ it.each([
+ ["-pr:merged", true],
+ ["pr:not:merged", true],
+ ["pr:merged", false],
+ ])("reads negation in %s", (query, negated) => {
+ const parsed = parseFeedQuery(query);
+ expect(parsed.tokens[0]).toMatchObject({ value: "merged", negated });
+ });
+
+ it("maps aliases onto canonical keys", () => {
+ const parsed = parseFeedQuery(
+ "author:shy channel:mobile repository:web commenter:shy mentioned:shy",
+ );
+ expect(parsed.tokens.map((t) => t.key)).toEqual([
+ "created-by",
+ "space",
+ "repo",
+ "commented-by",
+ "mentions",
+ ]);
+ });
+
+ it("carries spaces through quoted values", () => {
+ const parsed = parseFeedQuery('space:"desktop app" "exact phrase"');
+ expect(parsed.tokens[0].value).toBe("desktop app");
+ expect(parsed.text).toBe("exact phrase");
+ });
+
+ it("treats unknown keys as free text so URLs survive", () => {
+ const parsed = parseFeedQuery("see https://example.com/x foo:bar");
+ expect(parsed.tokens).toEqual([]);
+ expect(parsed.text).toBe("see https://example.com/x foo:bar");
+ });
+
+ it("drops a dangling key someone is mid-typing", () => {
+ const parsed = parseFeedQuery("status:");
+ expect(parsed.tokens).toEqual([]);
+ expect(parsed.issues).toEqual([]);
+ });
+
+ it.each([
+ ["status:sideways", "unknown-value"],
+ ["is:sideways", "unknown-value"],
+ ["pr:sideways", "unknown-value"],
+ ["ci:sideways", "unknown-value"],
+ ["type:canvas", "unknown-value"],
+ ])("flags %s as %s", (query, kind) => {
+ const parsed = parseFeedQuery(query);
+ expect(parsed.issues).toHaveLength(1);
+ expect(parsed.issues[0].kind).toBe(kind);
+ });
+ });
+
+ describe("lexFeedQuery", () => {
+ it.each([
+ "fix billing created-by:shy -status:failed",
+ ' space:"desktop app" trailing ',
+ "https://example.com/x pr:not:merged",
+ ])("reproduces %j exactly from its segments", (query) => {
+ const segments = lexFeedQuery(query);
+ expect(segments.map((segment) => segment.raw).join("")).toBe(query);
+
+ let start = 0;
+ for (const segment of segments) {
+ expect(segment.start).toBe(start);
+ start += segment.raw.length;
+ }
+ });
+
+ it("classifies tokens, text, and mid-typing fragments", () => {
+ const segments = lexFeedQuery("fix -status:failed status:");
+ expect(segments.map((s) => s.kind)).toEqual([
+ "text",
+ "whitespace",
+ "token",
+ "whitespace",
+ // A dangling `status:` renders as plain text to avoid a red flash mid-type.
+ "text",
+ ]);
+ expect(segments[2].token).toMatchObject({
+ key: "status",
+ value: "failed",
+ negated: true,
+ invalid: false,
+ unsupported: false,
+ });
+ });
+
+ it("flags invalid values for the highlighter", () => {
+ const segments = lexFeedQuery("status:sideways ci:red");
+ expect(segments[0].token).toMatchObject({ invalid: true });
+ expect(segments[2].token).toMatchObject({
+ invalid: false,
+ unsupported: false,
+ });
+ });
+ });
+
+ describe("planFeedQuery", () => {
+ it("compiles single positive filters into one server request", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery(
+ "billing created-by:shy space:mobile repo:webapp status:failed origin:slack is:archived",
+ ),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ {
+ search: "billing",
+ createdBy: 1,
+ channel: "space-mobile",
+ repository: "webapp",
+ status: "failed",
+ originProduct: "slack",
+ archived: true,
+ },
+ ]);
+ expect(plan.matches(task())).toBe(true);
+ });
+
+ it("resolves created-by:@me through the viewer", () => {
+ const plan = planFeedQuery(parseFeedQuery("created-by:@me"), context);
+ expect(plan.requests).toEqual([{ createdBy: shy.id }]);
+ });
+
+ // The regression this guards: with the OR filtered client-side over one
+ // unfiltered page, both authors' tasks vanished the moment they aged out
+ // of the most recent page, which made two working filters produce zero rows.
+ it("fans a repeated key out into one server request per value", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("created-by:shy created-by:moshe"),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ { createdBy: shy.id },
+ { createdBy: moshe.id },
+ ]);
+ expect(plan.matches(task({ created_by: { uuid: "uuid-shy" } }))).toBe(
+ true,
+ );
+ expect(plan.matches(task({ created_by: { uuid: "uuid-moshe" } }))).toBe(
+ true,
+ );
+ expect(plan.matches(task({ created_by: { uuid: "uuid-else" } }))).toBe(
+ false,
+ );
+ });
+
+ it("carries shared filters into every fanned-out request", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("created-by:shy created-by:moshe status:failed"),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ { createdBy: shy.id, status: "failed" },
+ { createdBy: moshe.id, status: "failed" },
+ ]);
+ });
+
+ it("folds duplicate spellings of one person into one request", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("created-by:shy author:[email protected]"),
+ context,
+ );
+ expect(plan.requests).toEqual([{ createdBy: shy.id }]);
+ });
+
+ it("keeps negations out of server params and filters them client-side", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("-created-by:moshe -status:failed"),
+ context,
+ );
+ expect(plan.requests).toEqual([{}]);
+ expect(plan.matches(task())).toBe(true);
+ expect(plan.matches(task({ created_by: { uuid: "uuid-moshe" } }))).toBe(
+ false,
+ );
+ expect(
+ plan.matches(task({ latest_run: { status: "failed", output: null } })),
+ ).toBe(false);
+ });
+
+ it("folds is: sugar into the status group", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("is:running status:failed"),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ { status: "in_progress" },
+ { status: "failed" },
+ ]);
+ expect(
+ plan.matches(
+ task({ latest_run: { status: "in_progress", output: null } }),
+ ),
+ ).toBe(true);
+ expect(
+ plan.matches(task({ latest_run: { status: "failed", output: null } })),
+ ).toBe(true);
+ expect(
+ plan.matches(
+ task({ latest_run: { status: "completed", output: null } }),
+ ),
+ ).toBe(false);
+ });
+
+ it.each([
+ ["pr:any", true, false],
+ ["pr:none", false, true],
+ ["-pr:none", true, false],
+ ["-pr:any", false, true],
+ ])("%s filters on PR presence", (query, withPr, withoutPr) => {
+ const plan = planFeedQuery(parseFeedQuery(query), context);
+ const prTask = task({
+ latest_run: {
+ status: "completed",
+ output: { pr_url: "https://github.com/example-org/webapp/pull/1" },
+ },
+ });
+ expect(plan.matches(prTask)).toBe(withPr);
+ expect(plan.matches(task())).toBe(withoutPr);
+ });
+
+ it("compiles pr states and ci status into server params", () => {
+ const plan = planFeedQuery(parseFeedQuery("pr:merged ci:red"), context);
+ expect(plan.requests).toEqual([
+ { prState: "merged", ciStatus: "failing" },
+ ]);
+ expect(plan.issues).toEqual([]);
+ });
+
+ it("fans repeated pr states out into one request per state", () => {
+ const plan = planFeedQuery(parseFeedQuery("pr:open pr:draft"), context);
+ expect(plan.requests).toEqual([
+ { prState: "open" },
+ { prState: "draft" },
+ ]);
+ const openTask = task({
+ latest_run: {
+ status: "completed",
+ output: { pr_url: "https://github.com/x/y/pull/1", pr_state: "open" },
+ },
+ });
+ expect(plan.matches(openTask)).toBe(true);
+ expect(plan.matches(task())).toBe(false);
+ });
+
+ it("matches pr:merged on the legacy pr_merged flag client-side", () => {
+ // Two values force the client predicate; a legacy run carries only
+ // pr_merged, and must still count as merged.
+ const plan = planFeedQuery(
+ parseFeedQuery("pr:merged pr:closed"),
+ context,
+ );
+ const legacyMerged = task({
+ latest_run: {
+ status: "completed",
+ output: { pr_url: "https://github.com/x/y/pull/1", pr_merged: true },
+ },
+ });
+ expect(plan.matches(legacyMerged)).toBe(true);
+ expect(plan.matches(task())).toBe(false);
+ });
+
+ it("keeps pr presence values client-side", () => {
+ const plan = planFeedQuery(parseFeedQuery("pr:any pr:merged"), context);
+ expect(plan.requests).toEqual([{}]);
+ const prTask = task({
+ latest_run: {
+ status: "completed",
+ output: { pr_url: "https://github.com/x/y/pull/1" },
+ },
+ });
+ expect(plan.matches(prTask)).toBe(true);
+ expect(plan.matches(task())).toBe(false);
+ });
+
+ it("filters ci status client-side when negated", () => {
+ const plan = planFeedQuery(parseFeedQuery("-ci:red"), context);
+ expect(plan.requests).toEqual([{}]);
+ const failing = task({
+ latest_run: {
+ status: "completed",
+ output: {
+ pr_url: "https://github.com/x/y/pull/1",
+ ci_status: "failing",
+ },
+ },
+ });
+ expect(plan.matches(failing)).toBe(false);
+ expect(plan.matches(task())).toBe(true);
+ });
+
+ it("takes no predicate from an unknown pr value", () => {
+ const plan = planFeedQuery(parseFeedQuery("pr:sideways"), context);
+ expect(plan.matches(task())).toBe(true);
+ expect(plan.issues.map((i) => i.kind)).toEqual(["unknown-value"]);
+ });
+
+ it.each([
+ ["origin:desktop", "user_created"],
+ ["origin:scout", "signals_scout"],
+ ["origin:ai", "posthog_ai"],
+ ["origin:slack", "slack"],
+ ["origin:hogdesk", "hogdesk"],
+ ])("aliases %s onto the origin enum", (query, expected) => {
+ const plan = planFeedQuery(parseFeedQuery(query), context);
+ expect(plan.requests).toEqual([{ originProduct: expected }]);
+ });
+
+ it("aliases origins inside OR groups and negations", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("origin:scout origin:desktop"),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ { originProduct: "signals_scout" },
+ { originProduct: "user_created" },
+ ]);
+ expect(plan.matches(task({ origin_product: "signals_scout" }))).toBe(
+ true,
+ );
+ expect(plan.matches(task({ origin_product: "slack" }))).toBe(false);
+
+ const negated = planFeedQuery(parseFeedQuery("-origin:scout"), context);
+ expect(negated.matches(task({ origin_product: "signals_scout" }))).toBe(
+ false,
+ );
+ expect(negated.matches(task({ origin_product: "slack" }))).toBe(true);
+ });
+
+ it("compiles is:pinned into the pinned request param", () => {
+ const plan = planFeedQuery(parseFeedQuery("is:pinned"), context);
+ expect(plan.requests).toEqual([{ pinned: true }]);
+ });
+
+ it("flags -is:pinned as unsupported instead of silently ignoring it", () => {
+ const plan = planFeedQuery(parseFeedQuery("-is:pinned"), context);
+ expect(plan.requests).toEqual([{}]);
+ expect(plan.issues.map((i) => i.kind)).toEqual(["unsupported"]);
+ });
+
+ it("flags -type:task as ignored instead of returning every task", () => {
+ const plan = planFeedQuery(parseFeedQuery("-type:task"), context);
+ expect(plan.requests).toEqual([{}]);
+ expect(plan.matches(task())).toBe(true);
+ expect(plan.issues.map((i) => i.kind)).toEqual(["unsupported"]);
+ });
+
+ it.each([
+ ["commented-by:shy", { commentedBy: shy.id }],
+ ["mentions:@me", { mentions: shy.id }],
+ ])("compiles %s into a server param", (query, expected) => {
+ const plan = planFeedQuery(parseFeedQuery(query), context);
+ expect(plan.requests).toEqual([expected]);
+ expect(plan.issues).toEqual([]);
+ });
+
+ it("fans repeated commented-by out into one request per person", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("commented-by:shy commented-by:moshe"),
+ context,
+ );
+ expect(plan.requests).toEqual([
+ { commentedBy: shy.id },
+ { commentedBy: moshe.id },
+ ]);
+ });
+
+ it("spells involves as one request per leg", () => {
+ const plan = planFeedQuery(parseFeedQuery("involves:shy"), context);
+ expect(plan.requests).toEqual([
+ { createdBy: shy.id },
+ { commentedBy: shy.id },
+ ]);
+ });
+
+ it("reports involves combined with created-by instead of widening", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("created-by:moshe involves:shy"),
+ context,
+ );
+ expect(plan.requests).toEqual([{ createdBy: moshe.id }]);
+ expect(plan.issues.map((i) => i.kind)).toEqual(["unsupported"]);
+ });
+
+ it("flags a negated comment filter instead of silently ignoring it", () => {
+ const plan = planFeedQuery(parseFeedQuery("-commented-by:shy"), context);
+ expect(plan.requests).toEqual([{}]);
+ expect(plan.matches(task())).toBe(true);
+ expect(plan.issues.map((i) => i.kind)).toEqual(["unsupported"]);
+ });
+
+ it("matches nothing when a comment filter names nobody", () => {
+ const plan = planFeedQuery(
+ parseFeedQuery("commented-by:nobody"),
+ context,
+ );
+ expect(plan.matches(task())).toBe(false);
+ expect(plan.issues.some((i) => i.message.includes("nobody"))).toBe(true);
+ });
+
+ it("reports an unresolved teammate and matches nothing", () => {
+ const plan = planFeedQuery(parseFeedQuery("created-by:nobody"), context);
+ expect(plan.issues.some((i) => i.message.includes("nobody"))).toBe(true);
+ expect(plan.matches(task())).toBe(false);
+ });
+
+ it("reports an unknown space name", () => {
+ const plan = planFeedQuery(parseFeedQuery("space:missing"), context);
+ expect(plan.requests).toEqual([{}]);
+ expect(plan.issues.some((i) => i.message.includes("missing"))).toBe(true);
+ });
+ });
+
+ describe("suggestFeedName", () => {
+ it.each([
+ ["created-by:@me pr:any", "My tasks with a PR"],
+ ["created-by:shy created-by:adam", "Shy & Adam's tasks"],
+ ["billing status:failed", "Failed billing tasks"],
+ ["is:archived space:mobile", "Archived tasks in mobile"],
+ ["repo:webapp pr:none", "Tasks in webapp without a PR"],
+ ["is:running is:failed", "Running or failed tasks"],
+ ["billing", "Billing tasks"],
+ ["is:pinned", "Pinned tasks"],
+ ["mentions:@me", "Tasks mentioning me"],
+ ["involves:shy status:failed", "Failed tasks involving Shy"],
+ ["commented-by:adam", "Tasks commented on by Adam"],
+ ["", ""],
+ ])("suggests a name for %j", (query, expected) => {
+ expect(suggestFeedName(query)).toBe(expected);
+ });
+ });
+});
diff --git a/products/desktop/packages/core/src/tasks/feedQuery.ts b/products/desktop/packages/core/src/tasks/feedQuery.ts
new file mode 100644
index 000000000000..63cd135860ea
--- /dev/null
+++ b/products/desktop/packages/core/src/tasks/feedQuery.ts
@@ -0,0 +1,983 @@
+import type { TaskRunStatus } from "@posthog/shared/domain-types";
+
+// Unknown keys remain free text so pasted URLs and incomplete filters still search.
+export type FeedQueryKey =
+ | "created-by"
+ | "commented-by"
+ | "mentions"
+ | "involves"
+ | "space"
+ | "repo"
+ | "status"
+ | "origin"
+ | "is"
+ | "pr"
+ | "ci"
+ | "type"
+ | "saved";
+
+const KEY_ALIASES: Record<string, FeedQueryKey> = {
+ "created-by": "created-by",
+ author: "created-by",
+ by: "created-by",
+ "commented-by": "commented-by",
+ commenter: "commented-by",
+ mentions: "mentions",
+ mentioned: "mentions",
+ involves: "involves",
+ space: "space",
+ channel: "space",
+ repo: "repo",
+ repository: "repo",
+ status: "status",
+ origin: "origin",
+ is: "is",
+ pr: "pr",
+ ci: "ci",
+ type: "type",
+ saved: "saved",
+};
+
+export const TASK_RUN_STATUSES: readonly TaskRunStatus[] = [
+ "not_started",
+ "queued",
+ "in_progress",
+ "completed",
+ "failed",
+ "cancelled",
+];
+
+const STATUS_ALIASES: Record<string, TaskRunStatus> = {
+ running: "in_progress",
+ done: "completed",
+};
+
+const IS_STATUS_SUGAR: Record<string, TaskRunStatus> = {
+ running: "in_progress",
+ done: "completed",
+ failed: "failed",
+};
+
+const IS_FLAG_VALUES: ReadonlySet<string> = new Set(["archived", "pinned"]);
+
+export const PR_VALUES = [
+ "any",
+ "none",
+ "open",
+ "draft",
+ "merged",
+ "closed",
+] as const;
+export type PrValue = (typeof PR_VALUES)[number];
+
+const PR_STATE_VALUES: ReadonlySet<string> = new Set([
+ "open",
+ "draft",
+ "merged",
+ "closed",
+]);
+
+export const CI_VALUES = [
+ "red",
+ "failing",
+ "green",
+ "passing",
+ "pending",
+ "none",
+] as const;
+
+export const TYPE_VALUES = ["task", "space", "command", "saved"] as const;
+export type TypeValue = (typeof TYPE_VALUES)[number];
+
+const CI_ALIASES: Record<string, string> = {
+ red: "failing",
+ green: "passing",
+};
+
+// Keep unknown origins unchanged so new server-side enum values remain searchable.
+export const ORIGIN_ALIASES: Record<string, string> = {
+ desktop: "user_created",
+ user: "user_created",
+ scout: "signals_scout",
+ signals: "signal_report",
+ ai: "posthog_ai",
+ max: "posthog_ai",
+ errors: "error_tracking",
+ support: "support_queue",
+ replay: "session_summaries",
+};
+
+export interface FeedQueryToken {
+ raw: string;
+ key: FeedQueryKey;
+ value: string;
+ negated: boolean;
+}
+
+export type FeedQueryIssueKind = "unknown-value" | "unsupported";
+
+export interface FeedQueryIssue {
+ raw: string;
+ kind: FeedQueryIssueKind;
+ message: string;
+}
+
+export interface ParsedFeedQuery {
+ text: string;
+ tokens: FeedQueryToken[];
+ issues: FeedQueryIssue[];
+}
+
+// A quoted value remains part of its token when it contains spaces.
+const CHUNK_RE = /(?:[^\s"]+|"[^"]*")+/g;
+const TOKEN_RE = /^(-)?([A-Za-z][A-Za-z-]*):(.*)$/;
+
+function unquote(value: string): string {
+ return value.replace(/"([^"]*)"/g, "$1");
+}
+
+export function parseFeedQuery(query: string): ParsedFeedQuery {
+ const words: string[] = [];
+ const tokens: FeedQueryToken[] = [];
+ const issues: FeedQueryIssue[] = [];
+
+ for (const raw of query.match(CHUNK_RE) ?? []) {
+ const match = TOKEN_RE.exec(raw);
+ const key = match ? KEY_ALIASES[match[2].toLowerCase()] : undefined;
+ if (!match || !key) {
+ words.push(unquote(raw));
+ continue;
+ }
+ let negated = match[1] === "-";
+ let value = unquote(match[3]);
+ if (value.toLowerCase().startsWith("not:")) {
+ negated = true;
+ value = value.slice("not:".length);
+ }
+ if (value === "") {
+ continue;
+ }
+ tokens.push({ raw, key, value, negated });
+ validateToken({ raw, key, value, negated }, issues);
+ }
+
+ return { text: words.join(" "), tokens, issues };
+}
+
+function validateToken(token: FeedQueryToken, issues: FeedQueryIssue[]): void {
+ const value = token.value.toLowerCase();
+ switch (token.key) {
+ case "status": {
+ if (
+ !STATUS_ALIASES[value] &&
+ !TASK_RUN_STATUSES.includes(value as TaskRunStatus)
+ ) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `Unknown status "${token.value}". Expected one of: ${TASK_RUN_STATUSES.join(", ")}`,
+ });
+ }
+ return;
+ }
+ case "is": {
+ if (!IS_FLAG_VALUES.has(value) && !IS_STATUS_SUGAR[value]) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `Unknown "is:" value "${token.value}". Expected one of: archived, pinned, running, done, failed`,
+ });
+ }
+ return;
+ }
+ case "pr": {
+ if (!PR_VALUES.includes(value as PrValue)) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `Unknown "pr:" value "${token.value}". Expected one of: ${PR_VALUES.join(", ")}`,
+ });
+ }
+ return;
+ }
+ case "ci": {
+ if (!CI_VALUES.includes(value as (typeof CI_VALUES)[number])) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `Unknown "ci:" value "${token.value}". Expected one of: ${CI_VALUES.join(", ")}`,
+ });
+ }
+ return;
+ }
+ case "type": {
+ if (!TYPE_VALUES.includes(value as (typeof TYPE_VALUES)[number])) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `Unknown "type:" value "${token.value}". Expected one of: ${TYPE_VALUES.join(", ")}`,
+ });
+ }
+ return;
+ }
+ default:
+ return;
+ }
+}
+
+export interface FeedQuerySegment {
+ start: number;
+ raw: string;
+ kind: "whitespace" | "text" | "token";
+ token?: {
+ key: FeedQueryKey;
+ value: string;
+ negated: boolean;
+ invalid: boolean;
+ unsupported: boolean;
+ };
+}
+
+export function lexFeedQuery(query: string): FeedQuerySegment[] {
+ const segments: FeedQuerySegment[] = [];
+ let cursor = 0;
+ for (const match of query.matchAll(CHUNK_RE)) {
+ const start = match.index;
+ if (start > cursor) {
+ segments.push({
+ start: cursor,
+ raw: query.slice(cursor, start),
+ kind: "whitespace",
+ });
+ }
+ const raw = match[0];
+ cursor = start + raw.length;
+
+ const tokenMatch = TOKEN_RE.exec(raw);
+ const key = tokenMatch
+ ? KEY_ALIASES[tokenMatch[2].toLowerCase()]
+ : undefined;
+ if (!tokenMatch || !key || tokenMatch[3] === "") {
+ segments.push({ start, raw, kind: "text" });
+ continue;
+ }
+ let negated = tokenMatch[1] === "-";
+ let value = unquote(tokenMatch[3]);
+ if (value.toLowerCase().startsWith("not:")) {
+ negated = true;
+ value = value.slice("not:".length);
+ }
+ const issues: FeedQueryIssue[] = [];
+ validateToken({ raw, key, value, negated }, issues);
+ segments.push({
+ start,
+ raw,
+ kind: "token",
+ token: {
+ key,
+ value,
+ negated,
+ invalid: issues.some((issue) => issue.kind === "unknown-value"),
+ unsupported: issues.some((issue) => issue.kind === "unsupported"),
+ },
+ });
+ }
+ if (cursor < query.length) {
+ segments.push({
+ start: cursor,
+ raw: query.slice(cursor),
+ kind: "whitespace",
+ });
+ }
+ return segments;
+}
+
+export interface FeedQueryMember {
+ id: number;
+ uuid: string;
+ email: string;
+ first_name?: string;
+ last_name?: string;
+}
+
+export interface FeedQuerySpace {
+ id: string;
+ name: string;
+}
+
+export interface FeedQueryPlanContext {
+ members: readonly FeedQueryMember[];
+ spaces: readonly FeedQuerySpace[];
+ me?: FeedQueryMember | null;
+}
+
+export interface FeedQueryServerParams {
+ search?: string;
+ createdBy?: number;
+ channel?: string;
+ repository?: string;
+ status?: TaskRunStatus;
+ originProduct?: string;
+ archived?: boolean;
+ prState?: string;
+ ciStatus?: string;
+ pinned?: boolean;
+ commentedBy?: number;
+ mentions?: number;
+}
+
+export interface FeedQueryTask {
+ created_by?: { uuid: string } | null;
+ channel?: string | null;
+ repository?: string | null;
+ origin_product?: string;
+ latest_run?: {
+ status: TaskRunStatus;
+ output?: Record<string, unknown> | null;
+ } | null;
+}
+
+export interface FeedQueryPlan {
+ /** Requests to union for this query. Repeated values create one request per value. */
+ requests: FeedQueryServerParams[];
+ matches: (task: FeedQueryTask) => boolean;
+ issues: FeedQueryIssue[];
+}
+
+function normalize(value: string): string {
+ return value.trim().toLowerCase();
+}
+
+export function feedQueryTypeScope(parsed: ParsedFeedQuery): TypeValue | null {
+ const token = parsed.tokens.find(
+ (t) =>
+ t.key === "type" &&
+ !t.negated &&
+ TYPE_VALUES.includes(normalize(t.value) as TypeValue),
+ );
+ return token ? (normalize(token.value) as TypeValue) : null;
+}
+
+const MAX_SUGGESTED_NAME_LENGTH = 80;
+
+const STATUS_WORDS: Partial<Record<string, string>> = {
+ in_progress: "running",
+ completed: "done",
+ not_started: "not started",
+};
+
+function capitalize(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+export function suggestFeedName(query: string): string {
+ const parsed = parseFeedQuery(query);
+ const positives = (key: FeedQueryKey) =>
+ parsed.tokens.filter((t) => t.key === key && !t.negated);
+
+ const authors = positives("created-by").map((t) => normalize(t.value));
+ const uniqueAuthors = [...new Set(authors)];
+ let possessive = "";
+ if (
+ uniqueAuthors.length === 1 &&
+ (uniqueAuthors[0] === "@me" || uniqueAuthors[0] === "me")
+ ) {
+ possessive = "my";
+ } else if (uniqueAuthors.length > 0) {
+ const names = uniqueAuthors.map((a) =>
+ a === "@me" || a === "me" ? "my" : capitalize(a),
+ );
+ possessive = `${names.join(" & ")}'s`;
+ }
+
+ const statusValues = [
+ ...positives("status").map((t) => {
+ const value = normalize(t.value);
+ return STATUS_ALIASES[value] ?? value;
+ }),
+ ...positives("is")
+ .map((t) => IS_STATUS_SUGAR[normalize(t.value)])
+ .filter((v): v is TaskRunStatus => !!v),
+ ];
+ const statusWords = [...new Set(statusValues)].map(
+ (value) => STATUS_WORDS[value] ?? value,
+ );
+
+ const archived = positives("is").some(
+ (t) => normalize(t.value) === "archived",
+ );
+ const pinned = positives("is").some((t) => normalize(t.value) === "pinned");
+
+ const personWord = (value: string) =>
+ value === "@me" || value === "me" ? "me" : capitalize(value);
+ const peoplePhrase = (key: FeedQueryKey, lead: string) => {
+ const names = [
+ ...new Set(positives(key).map((t) => personWord(normalize(t.value)))),
+ ];
+ return names.length > 0 ? `${lead} ${names.join(" or ")}` : "";
+ };
+ const repos = positives("repo").map((t) => t.value);
+ const spaces = positives("space").map((t) => t.value.replace(/^#/, ""));
+ const prValue = positives("pr")
+ .map((t) => normalize(t.value))
+ .find((v) => PR_VALUES.includes(v as PrValue));
+ const ciValue = positives("ci")
+ .map((t) => CI_ALIASES[normalize(t.value)] ?? normalize(t.value))
+ .find((v) => v === "failing" || v === "passing" || v === "pending");
+
+ const head = [
+ possessive,
+ pinned ? "pinned" : "",
+ archived ? "archived" : "",
+ statusWords.join(" or "),
+ parsed.text,
+ ]
+ .filter(Boolean)
+ .join(" ");
+ const places = [...spaces, ...repos];
+ const prPhrase =
+ prValue === "any"
+ ? "with a PR"
+ : prValue === "none"
+ ? "without a PR"
+ : prValue
+ ? `with ${/^[aeiou]/.test(prValue) ? "an" : "a"} ${prValue} PR`
+ : "";
+ const tail = [
+ peoplePhrase("involves", "involving"),
+ peoplePhrase("commented-by", "commented on by"),
+ peoplePhrase("mentions", "mentioning"),
+ places.length > 0 ? `in ${places.join(" or ")}` : "",
+ prPhrase,
+ ciValue ? `with ${ciValue} CI` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ const name = [head, "tasks", tail].filter(Boolean).join(" ").trim();
+ if (name === "tasks") return "";
+ return capitalize(name).slice(0, MAX_SUGGESTED_NAME_LENGTH);
+}
+
+function memberMatches(member: FeedQueryMember, value: string): boolean {
+ const needle = normalize(value);
+ const first = normalize(member.first_name ?? "");
+ const last = normalize(member.last_name ?? "");
+ const full = `${first} ${last}`.trim();
+ const email = normalize(member.email);
+ const emailUser = email.split("@")[0];
+ return (
+ first.startsWith(needle) ||
+ last.startsWith(needle) ||
+ full.startsWith(needle) ||
+ email === needle ||
+ emailUser === needle
+ );
+}
+
+interface Group {
+ positives: FeedQueryToken[];
+ negatives: FeedQueryToken[];
+}
+
+function groupOf(map: Map<string, Group>, key: string): Group {
+ let group = map.get(key);
+ if (!group) {
+ group = { positives: [], negatives: [] };
+ map.set(key, group);
+ }
+ return group;
+}
+
+const MATCH_ALL = () => true;
+const MATCH_NONE = () => false;
+
+/** Limit fan-out requests so one query cannot overload the task-list API. */
+const MAX_PLAN_REQUESTS = 8;
+
+/** Per-value request parameters for one OR group. */
+interface PlanFanout {
+ params: Partial<FeedQueryServerParams>[];
+ /** True when the task payload can recheck this group after fetching. */
+ verified: boolean;
+ /** Token to show when the fan-out limit skips this group. */
+ raw: string;
+}
+
+/** Compiles a parsed query into task-list requests and a client-side predicate. */
+export function planFeedQuery(
+ parsed: ParsedFeedQuery,
+ context: FeedQueryPlanContext,
+): FeedQueryPlan {
+ const server: FeedQueryServerParams = {};
+ // Combine the base request with every OR group's request parameters.
+ const fanouts: PlanFanout[] = [];
+ const predicates: ((task: FeedQueryTask) => boolean)[] = [];
+ const issues: FeedQueryIssue[] = [...parsed.issues];
+
+ 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;
+ };
+ // Equivalent names for one person must not create duplicate requests.
+ const uniqueMembers = (tokens: FeedQueryToken[]): FeedQueryMember[] => [
+ ...new Map(
+ tokens.flatMap(resolveMembers).map((member) => [member.uuid, member]),
+ ).values(),
+ ];
+
+ // Normalize aliases before grouping so equivalent filters do not become AND conditions.
+ const groups = new Map<string, Group>();
+ for (const token of parsed.tokens) {
+ let key: string = token.key;
+ let value = token.value;
+ if (token.key === "is") {
+ const sugar = IS_STATUS_SUGAR[normalize(token.value)];
+ if (sugar) {
+ key = "status";
+ value = sugar;
+ } else if (IS_FLAG_VALUES.has(normalize(token.value))) {
+ key = normalize(token.value);
+ value = key;
+ } else {
+ continue; // flagged by the parser already
+ }
+ }
+ if (key === "status") {
+ value = STATUS_ALIASES[normalize(value)] ?? normalize(value);
+ if (!TASK_RUN_STATUSES.includes(value as TaskRunStatus)) continue;
+ }
+ const group = groupOf(groups, key);
+ (token.negated ? group.negatives : group.positives).push({
+ ...token,
+ value,
+ });
+ }
+
+ const createdBy = groups.get("created-by");
+ if (createdBy) {
+ const wantedMembers = uniqueMembers(createdBy.positives);
+ const wanted = new Set(wantedMembers.map((member) => member.uuid));
+ const excluded = new Set(
+ createdBy.negatives.flatMap(resolveMembers).map((member) => member.uuid),
+ );
+ if (createdBy.negatives.length === 0 && wanted.size === 1) {
+ server.createdBy = wantedMembers[0].id;
+ } else {
+ if (createdBy.positives.length > 0) {
+ if (createdBy.negatives.length === 0 && wanted.size > 1) {
+ fanouts.push({
+ params: wantedMembers.map((member) => ({ createdBy: member.id })),
+ verified: true,
+ raw: createdBy.positives[0].raw,
+ });
+ }
+ predicates.push(
+ wanted.size === 0
+ ? MATCH_NONE
+ : (task) => !!task.created_by && wanted.has(task.created_by.uuid),
+ );
+ }
+ if (excluded.size > 0) {
+ predicates.push(
+ (task) => !task.created_by || !excluded.has(task.created_by.uuid),
+ );
+ }
+ }
+ }
+
+ // Thread comments and mentions are absent from the task payload, so only the API can filter them.
+ const serverOnlyPeopleGroup = (
+ groupKey: "commented-by" | "mentions",
+ param: "commentedBy" | "mentions",
+ ) => {
+ const group = groups.get(groupKey);
+ if (!group) return;
+ for (const token of group.negatives) {
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `"-${groupKey}:" can't exclude yet, so it is ignored`,
+ });
+ }
+ if (group.positives.length === 0) return;
+ const members = uniqueMembers(group.positives);
+ if (members.length === 0) {
+ predicates.push(MATCH_NONE);
+ } else if (members.length === 1) {
+ server[param] = members[0].id;
+ } else {
+ fanouts.push({
+ params: members.map((member) => ({ [param]: member.id })),
+ verified: false,
+ raw: group.positives[0].raw,
+ });
+ }
+ };
+ serverOnlyPeopleGroup("commented-by", "commentedBy");
+ serverOnlyPeopleGroup("mentions", "mentions");
+
+ const involves = groups.get("involves");
+ if (involves) {
+ for (const token of involves.negatives) {
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `"-involves:" can't exclude yet, so it is ignored`,
+ });
+ }
+ if (involves.positives.length > 0) {
+ // This expands to creator and commenter requests, which conflict with either explicit filter.
+ if (groups.has("created-by") || groups.has("commented-by")) {
+ issues.push({
+ raw: involves.positives[0].raw,
+ kind: "unsupported",
+ message: `"involves:" can't combine with "created-by:" or "commented-by:" yet, so it is ignored`,
+ });
+ } else {
+ const members = uniqueMembers(involves.positives);
+ if (members.length === 0) {
+ predicates.push(MATCH_NONE);
+ } else {
+ fanouts.push({
+ params: members.flatMap((member) => [
+ { createdBy: member.id },
+ { commentedBy: member.id },
+ ]),
+ verified: false,
+ raw: involves.positives[0].raw,
+ });
+ }
+ }
+ }
+ }
+
+ const typeGroup = groups.get("type");
+ if (typeGroup) {
+ // Feed results contain tasks only, so `type:` carries no meaning here. A
+ // negated `-type:task` is self-contradictory rather than the identity, so
+ // it is reported as ignored too instead of silently dropping to MATCH_ALL.
+ for (const token of [...typeGroup.positives, ...typeGroup.negatives]) {
+ if (token.negated || normalize(token.value) !== "task") {
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `Feeds only carry tasks, so "${token.raw}" is ignored here`,
+ });
+ }
+ }
+ }
+
+ const savedGroup = groups.get("saved");
+ if (savedGroup) {
+ // `saved:` selects a saved search in the command palette, not its task results.
+ for (const token of [...savedGroup.positives, ...savedGroup.negatives]) {
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `"saved:" opens saved searches from the command palette, so it is ignored here`,
+ });
+ }
+ }
+
+ const pinnedGroup = groups.get("pinned");
+ if (pinnedGroup) {
+ // Pin data is per-user and absent from task payloads, so a negation cannot be rechecked.
+ if (pinnedGroup.positives.length > 0) server.pinned = true;
+ for (const token of pinnedGroup.negatives) {
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `"-is:pinned" can't exclude yet, so it is ignored`,
+ });
+ }
+ }
+
+ 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 wanted = new Set(
+ space.positives.map(resolve).flatMap((s) => (s ? [s.id] : [])),
+ );
+ const excluded = new Set(
+ space.negatives.map(resolve).flatMap((s) => (s ? [s.id] : [])),
+ );
+ if (space.negatives.length === 0 && wanted.size === 1) {
+ server.channel = [...wanted][0];
+ } else {
+ if (space.positives.length > 0) {
+ if (space.negatives.length === 0 && wanted.size > 1) {
+ fanouts.push({
+ params: [...wanted].map((channel) => ({ channel })),
+ verified: true,
+ raw: space.positives[0].raw,
+ });
+ }
+ predicates.push(
+ wanted.size === 0
+ ? MATCH_NONE
+ : (task) => !!task.channel && wanted.has(task.channel),
+ );
+ }
+ if (excluded.size > 0) {
+ predicates.push((task) => !task.channel || !excluded.has(task.channel));
+ }
+ }
+ }
+
+ const repo = groups.get("repo");
+ if (repo) {
+ const matchesRepo = (task: FeedQueryTask, value: string) =>
+ !!task.repository &&
+ normalize(task.repository).includes(normalize(value));
+ const values = [...new Set(repo.positives.map((t) => normalize(t.value)))];
+ if (repo.negatives.length === 0 && values.length === 1) {
+ server.repository = values[0];
+ } else {
+ if (values.length > 0) {
+ if (repo.negatives.length === 0 && values.length > 1) {
+ fanouts.push({
+ params: values.map((repository) => ({ repository })),
+ verified: true,
+ raw: repo.positives[0].raw,
+ });
+ }
+ predicates.push((task) =>
+ values.some((value) => matchesRepo(task, value)),
+ );
+ }
+ for (const token of repo.negatives) {
+ predicates.push((task) => !matchesRepo(task, token.value));
+ }
+ }
+ }
+
+ const status = groups.get("status");
+ if (status) {
+ const values = new Set(status.positives.map((t) => t.value));
+ if (status.negatives.length === 0 && values.size === 1) {
+ server.status = [...values][0] as TaskRunStatus;
+ } else {
+ if (values.size > 0) {
+ if (status.negatives.length === 0 && values.size > 1) {
+ fanouts.push({
+ params: [...values].map((value) => ({
+ status: value as TaskRunStatus,
+ })),
+ verified: true,
+ raw: status.positives[0].raw,
+ });
+ }
+ predicates.push(
+ (task) => !!task.latest_run && values.has(task.latest_run.status),
+ );
+ }
+ if (status.negatives.length > 0) {
+ const negated = new Set(status.negatives.map((t) => t.value));
+ predicates.push(
+ (task) => !task.latest_run || !negated.has(task.latest_run.status),
+ );
+ }
+ }
+ }
+
+ const originValue = (token: FeedQueryToken): string => {
+ const value = normalize(token.value);
+ return ORIGIN_ALIASES[value] ?? value;
+ };
+ const origin = groups.get("origin");
+ if (origin) {
+ const values = new Set(origin.positives.map(originValue));
+ if (origin.negatives.length === 0 && values.size === 1) {
+ server.originProduct = [...values][0];
+ } else {
+ if (values.size > 0) {
+ if (origin.negatives.length === 0 && values.size > 1) {
+ fanouts.push({
+ params: [...values].map((value) => ({ originProduct: value })),
+ verified: true,
+ raw: origin.positives[0].raw,
+ });
+ }
+ predicates.push(
+ (task) =>
+ !!task.origin_product && values.has(normalize(task.origin_product)),
+ );
+ }
+ if (origin.negatives.length > 0) {
+ const negated = new Set(origin.negatives.map(originValue));
+ predicates.push(
+ (task) =>
+ !task.origin_product ||
+ !negated.has(normalize(task.origin_product)),
+ );
+ }
+ }
+ }
+
+ const archived = groups.get("archived");
+ if (archived && archived.positives.length > 0) {
+ // Task lists exclude archived tasks unless the query includes them.
+ server.archived = true;
+ }
+
+ const pr = groups.get("pr");
+ if (pr) {
+ // The state the API last observed for the run's PR. Runs merged before
+ // pr_state existed only carry the older pr_merged flag; honor both.
+ const prStateOf = (task: FeedQueryTask): string | undefined => {
+ const output = task.latest_run?.output;
+ const state = output?.pr_state;
+ if (typeof state === "string") return state;
+ return output?.pr_merged === true ? "merged" : undefined;
+ };
+ const hasPr = (task: FeedQueryTask) =>
+ typeof task.latest_run?.output?.pr_url === "string" ||
+ prStateOf(task) !== undefined;
+ const testFor = (value: string) =>
+ value === "any"
+ ? hasPr
+ : value === "none"
+ ? (task: FeedQueryTask) => !hasPr(task)
+ : (task: FeedQueryTask) => prStateOf(task) === value;
+
+ // Ignore values the parser already marked invalid to avoid an empty result.
+ const valid = (values: FeedQueryToken[]) => [
+ ...new Set(
+ values
+ .map((t) => normalize(t.value))
+ .filter((v) => PR_VALUES.includes(v as PrValue)),
+ ),
+ ];
+ const positives = valid(pr.positives);
+ const negatives = valid(pr.negatives);
+ const states = positives.filter((v) => PR_STATE_VALUES.has(v));
+
+ if (
+ negatives.length === 0 &&
+ positives.length === 1 &&
+ states.length === 1
+ ) {
+ server.prState = states[0];
+ } else {
+ // PR presence has no API filter, so it remains a client-side predicate.
+ if (
+ negatives.length === 0 &&
+ states.length > 1 &&
+ states.length === positives.length
+ ) {
+ fanouts.push({
+ params: states.map((prState) => ({ prState })),
+ verified: true,
+ raw: pr.positives[0].raw,
+ });
+ }
+ if (positives.length > 0) {
+ const tests = positives.map(testFor);
+ predicates.push((task) => tests.some((test) => test(task)));
+ }
+ for (const value of negatives) {
+ const test = testFor(value);
+ predicates.push((task) => !test(task));
+ }
+ }
+ }
+
+ const ci = groups.get("ci");
+ if (ci) {
+ const ciStatusOf = (task: FeedQueryTask): string | undefined => {
+ const status = task.latest_run?.output?.ci_status;
+ return typeof status === "string" ? status : undefined;
+ };
+ const valid = (values: FeedQueryToken[]) => [
+ ...new Set(
+ values
+ .map((t) => normalize(t.value))
+ .filter((v) => CI_VALUES.includes(v as (typeof CI_VALUES)[number]))
+ .map((v) => CI_ALIASES[v] ?? v),
+ ),
+ ];
+ const positives = valid(ci.positives);
+ const negatives = valid(ci.negatives);
+
+ if (negatives.length === 0 && positives.length === 1) {
+ server.ciStatus = positives[0];
+ } else {
+ if (negatives.length === 0 && positives.length > 1) {
+ fanouts.push({
+ params: positives.map((ciStatus) => ({ ciStatus })),
+ verified: true,
+ raw: ci.positives[0].raw,
+ });
+ }
+ if (positives.length > 0) {
+ const wanted = new Set(positives);
+ predicates.push((task) => {
+ const status = ciStatusOf(task);
+ return status !== undefined && wanted.has(status);
+ });
+ }
+ if (negatives.length > 0) {
+ const excluded = new Set(negatives);
+ predicates.push((task) => {
+ const status = ciStatusOf(task);
+ return status === undefined || !excluded.has(status);
+ });
+ }
+ }
+ }
+
+ const matches =
+ predicates.length === 0
+ ? MATCH_ALL
+ : (task: FeedQueryTask) => predicates.every((p) => p(task));
+
+ // Expand unverified groups first because the task payload cannot recheck them.
+ const ordered = [...fanouts].sort(
+ (a, b) => Number(a.verified) - Number(b.verified),
+ );
+ let requests: FeedQueryServerParams[] = [server];
+ for (const fanout of ordered) {
+ if (requests.length * fanout.params.length > MAX_PLAN_REQUESTS) {
+ if (!fanout.verified) {
+ issues.push({
+ raw: fanout.raw,
+ kind: "unsupported",
+ message:
+ "Use fewer filter values. This query requires too many searches.",
+ });
+ }
+ continue;
+ }
+ requests = requests.flatMap((request) =>
+ fanout.params.map((params) => ({ ...request, ...params })),
+ );
+ }
+
+ return { requests, matches, issues };
+}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index a5806ff19dcf..8156a26e8f98 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -985,6 +985,16 @@ export type ChannelActionType =
| "open_mention"
| "activity_tab_change";
+export type TaskFeedActionType = "create" | "update" | "delete" | "open";
+
+export interface TaskFeedActionProperties {
+ action_type: TaskFeedActionType;
+ surface: "sidebar" | "feed_home" | "command_menu";
+ feed_id: string;
+ /** Length of the saved query. Do not record its text. */
+ query_length?: number;
+}
+
export interface ChannelActionProperties {
action_type: ChannelActionType;
surface: ChannelsSurface;
@@ -1473,6 +1483,7 @@ export const ANALYTICS_EVENTS = {
// Project Bluebird (Channels) events
CHANNELS_SPACE_VIEWED: "Channels space viewed",
CHANNEL_ACTION: "Channel action",
+ TASK_FEED_ACTION: "Task feed action",
DASHBOARD_ACTION: "Dashboard action",
CANVAS_PROMPT_SENT: "Canvas prompt sent",
CANVAS_RENDERED: "Canvas rendered",
@@ -1655,6 +1666,7 @@ export type EventPropertyMap = {
// Project Bluebird (Channels) events
[ANALYTICS_EVENTS.CHANNELS_SPACE_VIEWED]: ChannelsSpaceViewedProperties;
[ANALYTICS_EVENTS.CHANNEL_ACTION]: ChannelActionProperties;
+ [ANALYTICS_EVENTS.TASK_FEED_ACTION]: TaskFeedActionProperties;
[ANALYTICS_EVENTS.DASHBOARD_ACTION]: DashboardActionProperties;
[ANALYTICS_EVENTS.CANVAS_PROMPT_SENT]: CanvasPromptSentProperties;
[ANALYTICS_EVENTS.CANVAS_RENDERED]: CanvasRenderedProperties;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
index 99105eb6c711..646024aee4cf 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
@@ -187,6 +187,14 @@ export const PendingKickoff: Story = {
},
};
+export const Loading: Story = {
+ args: {
+ tasks: [],
+ isLoading: true,
+ composer: <MockComposer />,
+ },
+};
+
export const EmptyChannel: Story = {
args: {
tasks: [],
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
index 0484632ff588..ad8644ca0b29 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
@@ -33,12 +33,8 @@ vi.mock("@posthog/ui/features/browser-tabs/TaskTabIcon", () => ({
TaskTabIcon: () => <span />,
}));
-import {
- ExpandablePrompt,
- mergeFeedEntries,
- stripContextBlocks,
- TaskCard,
-} from "./ChannelFeedView";
+import { ChannelFeedView, ExpandablePrompt, TaskCard } from "./ChannelFeedView";
+import { mergeFeedEntries, stripContextBlocks } from "./channelFeedDisplay";
const task = {
id: "task-1",
@@ -85,6 +81,23 @@ function mockLayout(charsPerLine: number) {
}
describe("ChannelFeedView", () => {
+ it("announces when tasks are loading", () => {
+ const { container } = render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[]}
+ isLoading
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument();
+ expect(screen.getByRole("status")).toHaveTextContent("Loading tasks");
+ });
+
it("reports when its task is opened", async () => {
const user = userEvent.setup();
const onOpen = vi.fn();
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
index f8b3633b5988..300adcbbe23b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
@@ -25,6 +25,7 @@ import {
Popover,
PopoverContent,
PopoverTrigger,
+ Skeleton,
Spinner,
} from "@posthog/quill";
import {
@@ -39,6 +40,11 @@ import type {
} from "@posthog/shared/domain-types";
import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
import { TaskTabIcon } from "@posthog/ui/features/browser-tabs/TaskTabIcon";
+import {
+ type FeedEntry,
+ mergeFeedEntries,
+ stripContextBlocks,
+} from "@posthog/ui/features/canvas/components/channelFeedDisplay";
import { buildRows } from "@posthog/ui/features/canvas/components/taskArtifactRows";
import type { ChannelFeedSystemMessage } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
import { useChannelTaskData } from "@posthog/ui/features/canvas/hooks/useChannelTaskData";
@@ -79,20 +85,6 @@ import {
// shared query key means an open panel naturally speeds the row up too.
const FEED_REPLIES_POLL_INTERVAL_MS = 15_000;
-// Injected context wrappers a prompt may carry (Slack thread history, a
-// channel's CONTEXT.md, canvas instructions, saved personalization). The feed
-// shows what the user actually asked, so these are stripped — the timeline
-// renders them as their own collapsible surfaces.
-const CONTEXT_BLOCK_REGEX =
- /<(slack_thread_context|channel_context|canvas_generation_instructions|user_custom_instructions)\b[^>]*>[\s\S]*?<\/\1>/g;
-
-export function stripContextBlocks(text: string): string {
- return text
- .replace(CONTEXT_BLOCK_REGEX, "")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-}
-
// Once a PR exists its GitHub state is the truest top-line status — more
// accurate than the run status, which routinely lingers on "in_progress"
// (or a stale cloud status) after the agent opens the PR. Mirrors the PR
@@ -1093,48 +1085,6 @@ function SystemFeedRow({ message }: { message: ChannelFeedSystemMessage }) {
);
}
-// A single feed entry, either a real task card or a synthetic system row, tagged
-// with the timestamp used to interleave the two.
-export type FeedEntry =
- | { kind: "task"; id: string; createdAt: string; task: Task }
- | {
- kind: "system";
- id: string;
- createdAt: string;
- message: ChannelFeedSystemMessage;
- };
-
-// Merge tasks + system rows into one newest-first list. ISO timestamps sort
-// lexically, so a plain string compare is chronological. Announcements are
-// posted 1ms before the task they describe; if the backend truncates that
-// sub-second offset the timestamps tie, so break ties task-first to keep the
-// announcement directly under its card.
-export function mergeFeedEntries(
- tasks: Task[],
- systemMessages: ChannelFeedSystemMessage[],
-): FeedEntry[] {
- const merged: FeedEntry[] = [
- ...tasks.map((task) => ({
- kind: "task" as const,
- id: task.id,
- createdAt: task.created_at,
- task,
- })),
- ...systemMessages.map((message) => ({
- kind: "system" as const,
- id: message.id,
- createdAt: message.createdAt,
- message,
- })),
- ];
- merged.sort(
- (a, b) =>
- b.createdAt.localeCompare(a.createdAt) ||
- (a.kind === b.kind ? 0 : a.kind === "task" ? -1 : 1),
- );
- return merged;
-}
-
const DAY_MS = 86_400_000;
// "Today" / "Yesterday" / "Aug 8" (with the year once it differs) for the
@@ -1153,6 +1103,62 @@ function feedDayLabel(iso: string, now: Date): string {
});
}
+/**
+ * The loading stand-in for one feed card: the card frame with the title,
+ * prompt lines, and footer facepile as pulsing bars, so the page keeps the
+ * feed's shape while the query runs instead of collapsing to a spinner.
+ */
+function FeedRowSkeleton({ wide }: { wide?: boolean }) {
+ return (
+ <Card
+ size="sm"
+ className="mx-auto my-1.5 w-full max-w-[660px] rounded-xl py-0"
+ >
+ <CardContent className="flex flex-col px-4 pt-3.5 pb-3">
+ <div className="flex items-start gap-3">
+ <Skeleton className={cn("h-4", wide ? "w-3/5" : "w-2/5")} />
+ <Skeleton className="ml-auto h-5 w-16 shrink-0 rounded-full" />
+ </div>
+ <div className="mt-2 flex flex-col gap-1.5">
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className={cn("h-3", wide ? "w-1/2" : "w-3/4")} />
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <Skeleton className="size-5 rounded-full" />
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+/**
+ * The loading feed: a faded stack of card skeletons under a separator-shaped
+ * bar. Each card fainter than the one above, so the stack reads as content
+ * arriving rather than a wall of grey.
+ */
+function FeedSkeleton() {
+ return (
+ <div aria-hidden className="flex flex-col">
+ <div className="mx-auto flex w-full max-w-[660px] items-center gap-3 pt-5 pb-2">
+ <span className="h-px flex-1 bg-(--gray-5)" />
+ <Skeleton className="h-3 w-12" />
+ <span className="h-px flex-1 bg-(--gray-5)" />
+ </div>
+ <FeedRowSkeleton wide />
+ <div className="opacity-70">
+ <FeedRowSkeleton />
+ </div>
+ <div className="opacity-40">
+ <FeedRowSkeleton wide />
+ </div>
+ <div className="opacity-15">
+ <FeedRowSkeleton />
+ </div>
+ </div>
+ );
+}
+
function DaySeparator({ label }: { label: string }) {
return (
<div className="mx-auto flex w-full max-w-[660px] items-center gap-3 pt-5 pb-2 font-semibold text-(--gray-9) text-[11px] uppercase tracking-wider">
@@ -1246,13 +1252,16 @@ export function ChannelFeedView({
);
if (isLoading && pending.length === 0) {
+ // Everything already known renders now. The skeleton cards hold the
+ // feed's shape while keeping the intro and composer available.
+ // feed's shape where the results are about to land.
return (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto flex w-full flex-col px-4 pt-4">
+ <div className="min-h-0 flex-1 overflow-y-auto" aria-busy="true">
+ <output className="sr-only">Loading tasks</output>
+ <div className="mx-auto w-full px-4 pt-4 pb-10">
+ {intro && <div className="mx-auto w-full max-w-[660px]">{intro}</div>}
{composerBlock}
- <div className="flex justify-center py-16">
- <Spinner />
- </div>
+ <FeedSkeleton />
</div>
</div>
);
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index dc6f0153ea4a..143ea229a7da 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -1477,7 +1477,7 @@ const sectionValue = (sectionId: string) => `section:${sectionId}`;
// long). Unstyled parts give a plain label row that snaps.
//
// The whole header row is the trigger, and the label is all of it: the headings
-// are two, named, and always in the same order, so a glyph beside each was
+// are few, named, and always in the same order, so a glyph beside each was
// decoration rather than a way of telling them apart.
function ChannelGroup({
sectionId,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.test.tsx
new file mode 100644
index 000000000000..ba67af7bc2bb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.test.tsx
@@ -0,0 +1,209 @@
+import { Theme } from "@radix-ui/themes";
+import { fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useState } from "react";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
+ useOrgMembers: () => ({
+ members: [
+ {
+ id: 1,
+ uuid: "uuid-shy",
+ email: "[email protected]",
+ first_name: "Shy",
+ last_name: "Levi",
+ },
+ {
+ id: 2,
+ uuid: "uuid-moshe",
+ email: "[email protected]",
+ first_name: "Moshe",
+ last_name: "Katz",
+ },
+ {
+ id: 3,
+ uuid: "uuid-alex-one",
+ email: "[email protected]",
+ first_name: "Alex",
+ last_name: "One",
+ },
+ {
+ id: 4,
+ uuid: "uuid-alex-two",
+ email: "[email protected]",
+ first_name: "Alex",
+ last_name: "Two",
+ },
+ ],
+ isLoading: false,
+ isError: false,
+ isComplete: true,
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
+ useChannels: () => ({
+ channels: [
+ {
+ id: "space-app",
+ name: "desktop app",
+ channelType: "public",
+ starred: false,
+ repositories: ["example-org/webapp"],
+ createdBy: null,
+ },
+ ],
+ isLoading: false,
+ }),
+}));
+
+import { FeedQueryHighlight, FeedQueryInput } from "./FeedQueryInput";
+
+function Harness({ initial = "" }: { initial?: string }) {
+ const [value, setValue] = useState(initial);
+ return (
+ <Theme>
+ <FeedQueryInput aria-label="Query" value={value} onChange={setValue} />
+ <output>{value}</output>
+ </Theme>
+ );
+}
+
+describe("FeedQueryInput", () => {
+ it("completes a key, then a teammate, into one token", async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ const input = screen.getByRole("combobox");
+
+ await user.type(input, "cre");
+ // The bolded match prefix splits the label across spans, and accessible
+ // name computation joins them with a space, so match loosely.
+ await user.click(screen.getByRole("option", { name: /ated-by:/ }));
+ // The key completion keeps the list open on its values.
+ await user.type(input, "sh");
+ await user.click(screen.getByRole("option", { name: /shy@example\.com/ }));
+
+ expect(screen.getByRole("status")).toHaveTextContent("created-by:shy");
+ });
+
+ it("uses full emails to distinguish teammates with matching names", async () => {
+ const user = userEvent.setup();
+ render(<Harness initial="created-by:alex" />);
+ const input = screen.getByRole("combobox");
+
+ await user.click(input);
+ await user.click(screen.getByRole("option", { name: /alex@example\.org/ }));
+
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "created-by:[email protected]",
+ );
+ });
+
+ it("keeps the negation prefix through a completion", async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ const input = screen.getByRole("combobox");
+
+ await user.type(input, "-sta");
+ await user.keyboard("{Enter}");
+ await user.keyboard("{Enter}");
+
+ expect(screen.getByRole("status").textContent).toMatch(/^-status:/);
+ });
+
+ it("keeps a not: value negation through a completion", async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ const input = screen.getByRole("combobox");
+
+ await user.type(input, "status:not:f");
+ await user.keyboard("{Enter}");
+
+ // Completing the value must not drop `not:` and flip the filter to positive.
+ expect(screen.getByRole("status")).toHaveTextContent("status:not:failed");
+ });
+
+ it("does not submit while IME text composition is active", () => {
+ const onSubmit = vi.fn();
+ render(
+ <Theme>
+ <FeedQueryInput
+ aria-label="Query"
+ value="billing"
+ onChange={vi.fn()}
+ onSubmit={onSubmit}
+ />
+ </Theme>,
+ );
+
+ fireEvent.keyDown(screen.getByRole("combobox"), {
+ key: "Enter",
+ isComposing: true,
+ });
+
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("links keyboard selection to the active suggestion", async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ const input = screen.getByRole("combobox");
+
+ await user.type(input, "s");
+ const listbox = screen.getByRole("listbox", {
+ name: "Query suggestions",
+ });
+ expect(input).toHaveAttribute("aria-expanded", "true");
+ expect(input).toHaveAttribute("aria-controls", listbox.id);
+
+ await user.keyboard("{ArrowDown}");
+ expect(input).toHaveAttribute(
+ "aria-activedescendant",
+ screen.getAllByRole("option")[1].id,
+ );
+ });
+
+ it("quotes a suggested value that carries spaces", async () => {
+ const user = userEvent.setup();
+ render(<Harness initial="space:" />);
+ const input = screen.getByRole("combobox");
+
+ await user.click(input);
+ await user.click(screen.getByRole("option", { name: "desktop app" }));
+
+ expect(screen.getByRole("status")).toHaveTextContent('space:"desktop app"');
+ });
+});
+
+describe("FeedQueryHighlight", () => {
+ // The editor overlays this on a transparent input, so any drift between the
+ // rendered text and the raw string shears the caret off the colored glyphs.
+ it("round-trips the query text exactly", () => {
+ const query = ' fix space:"desktop app" -status:failed x ';
+ const { container } = render(
+ <Theme>
+ <FeedQueryHighlight query={query} />
+ </Theme>,
+ );
+ expect(container.textContent).toBe(query);
+ });
+
+ it("marks invalid values with the wavy underline", () => {
+ const { container } = render(
+ <Theme>
+ <FeedQueryHighlight query="status:sideways" />
+ </Theme>,
+ );
+ expect(container.querySelector(".decoration-wavy")).toBeTruthy();
+ });
+
+ it("renders a now-supported ci value without warning marks", () => {
+ const { container } = render(
+ <Theme>
+ <FeedQueryHighlight query="ci:red" />
+ </Theme>,
+ );
+ expect(container.querySelector(".decoration-dotted")).toBeNull();
+ expect(container.querySelector(".decoration-wavy")).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.tsx b/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.tsx
new file mode 100644
index 000000000000..27d0d68ad63f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/FeedQueryInput.tsx
@@ -0,0 +1,300 @@
+import {
+ type FeedQuerySegment,
+ lexFeedQuery,
+} from "@posthog/core/tasks/feedQuery";
+import { cn, Kbd } from "@posthog/quill";
+import {
+ FeedQueryMatchedLabel,
+ useFeedQuerySuggestions,
+} from "@posthog/ui/features/canvas/components/feedQuerySuggestions";
+import { applyFeedQuerySuggestion } from "@posthog/ui/features/canvas/components/feedQuerySuggestionUtils";
+import {
+ Fragment,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type ReactNode,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+// Keep the input and syntax mirror on the same text metrics.
+export const EDITOR_TEXT_CLASS =
+ "whitespace-pre font-mono text-[13px] leading-none tracking-normal";
+
+export function FeedQueryHighlight({
+ query,
+ className,
+}: {
+ query: string;
+ className?: string;
+}) {
+ const segments = useMemo(() => lexFeedQuery(query), [query]);
+ return (
+ <span className={cn(EDITOR_TEXT_CLASS, className)}>
+ {segments.map((segment) => (
+ <Fragment key={segment.start}>{renderSegment(segment)}</Fragment>
+ ))}
+ </span>
+ );
+}
+
+function renderSegment(segment: FeedQuerySegment): ReactNode {
+ if (segment.kind !== "token" || !segment.token) {
+ return <span className="text-(--gray-12)">{segment.raw}</span>;
+ }
+ const { token, raw } = segment;
+ const negPrefix = raw.startsWith("-") ? "-" : "";
+ const rest = raw.slice(negPrefix.length);
+ const colon = rest.indexOf(":");
+ const keyText = rest.slice(0, colon + 1);
+ let valueText = rest.slice(colon + 1);
+ let notPrefix = "";
+ if (valueText.toLowerCase().startsWith("not:")) {
+ notPrefix = valueText.slice(0, 4);
+ valueText = valueText.slice(4);
+ }
+ const negated = token.negated;
+ return (
+ <span
+ className={cn(
+ "rounded-[3px]",
+ negated ? "bg-(--red-a3)" : "bg-(--gray-a3)",
+ )}
+ >
+ {negPrefix && <span className="text-(--red-11)">{negPrefix}</span>}
+ <span className={negated ? "text-(--red-11)" : "text-(--blue-11)"}>
+ {keyText}
+ </span>
+ {notPrefix && <span className="text-(--red-11)">{notPrefix}</span>}
+ <span
+ className={cn(
+ token.invalid
+ ? "text-(--red-11) underline decoration-(--red-8) decoration-wavy underline-offset-2"
+ : token.unsupported
+ ? "text-(--amber-11) underline decoration-(--amber-8) decoration-dotted underline-offset-2"
+ : negated
+ ? "text-(--red-12)"
+ : "text-(--gray-12)",
+ )}
+ >
+ {valueText}
+ </span>
+ </span>
+ );
+}
+
+export function FeedQueryInput({
+ id,
+ value,
+ onChange,
+ onSubmit,
+ placeholder,
+ autoFocus,
+ openOnFocus = true,
+ "aria-label": ariaLabel,
+}: {
+ id?: string;
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit?: () => void;
+ placeholder?: string;
+ autoFocus?: boolean;
+ openOnFocus?: boolean;
+ "aria-label"?: string;
+}) {
+ const generatedId = useId();
+ const inputId = id ?? generatedId;
+ const listboxId = `${inputId}-suggestions`;
+ const inputRef = useRef<HTMLInputElement>(null);
+ const mirrorRef = useRef<HTMLDivElement>(null);
+ const [caret, setCaret] = useState(0);
+ const [open, setOpen] = useState(false);
+ const [highlighted, setHighlighted] = useState(0);
+
+ // Restore the caret after React applies a completed suggestion.
+ const pendingCaret = useRef<number | null>(null);
+ useLayoutEffect(() => {
+ if (pendingCaret.current == null) return;
+ inputRef.current?.setSelectionRange(
+ pendingCaret.current,
+ pendingCaret.current,
+ );
+ inputRef.current?.focus();
+ pendingCaret.current = null;
+ });
+
+ // Keep the syntax mirror aligned with a horizontally scrolled input.
+ const syncScroll = () => {
+ if (mirrorRef.current && inputRef.current) {
+ mirrorRef.current.scrollLeft = inputRef.current.scrollLeft;
+ }
+ };
+ useLayoutEffect(syncScroll);
+
+ const { group, context } = useFeedQuerySuggestions(value, caret);
+ const suggestions = group.items;
+ const visible = open && suggestions.length > 0;
+ const highlightedIndex = Math.min(highlighted, suggestions.length - 1);
+
+ const apply = (suggestion: (typeof suggestions)[number]) => {
+ const edit = applyFeedQuerySuggestion(value, context, suggestion);
+ onChange(edit.next);
+ setCaret(edit.caret);
+ pendingCaret.current = edit.caret;
+ setHighlighted(0);
+ setOpen(edit.completedKey);
+ };
+
+ const onKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
+ if (event.nativeEvent.isComposing) return;
+ if (visible) {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setHighlighted((h) => (h + 1) % suggestions.length);
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setHighlighted(
+ (h) => (h - 1 + suggestions.length) % suggestions.length,
+ );
+ return;
+ }
+ if (event.key === "Enter" || event.key === "Tab") {
+ event.preventDefault();
+ apply(suggestions[highlightedIndex]);
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ return;
+ }
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ onSubmit?.();
+ }
+ };
+
+ const trackCaret = () => {
+ const position = inputRef.current?.selectionStart;
+ if (position != null) setCaret(position);
+ };
+
+ return (
+ <div className="relative">
+ <div
+ className={cn(
+ "relative h-9 overflow-hidden rounded-md border border-(--gray-a7) bg-(--color-surface)",
+ "focus-within:-outline-offset-1 focus-within:outline focus-within:outline-(--focus-8) focus-within:outline-2",
+ )}
+ >
+ <div
+ ref={mirrorRef}
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-0 flex items-center overflow-x-hidden px-2.5",
+ EDITOR_TEXT_CLASS,
+ )}
+ >
+ <FeedQueryHighlight query={value} />
+ </div>
+ <input
+ ref={inputRef}
+ id={inputId}
+ role="combobox"
+ aria-label={ariaLabel}
+ aria-autocomplete="list"
+ aria-expanded={visible}
+ aria-controls={visible ? listboxId : undefined}
+ aria-activedescendant={
+ visible ? `${listboxId}-${highlightedIndex}` : undefined
+ }
+ type="text"
+ value={value}
+ placeholder={placeholder}
+ autoComplete="off"
+ // biome-ignore lint/a11y/noAutofocus: the modal opens to type a query
+ autoFocus={autoFocus}
+ autoCorrect="off"
+ autoCapitalize="off"
+ spellCheck={false}
+ className={cn(
+ "absolute inset-0 w-full bg-transparent px-2.5 outline-none",
+ EDITOR_TEXT_CLASS,
+ "text-transparent caret-(--gray-12) placeholder:text-(--gray-9)",
+ "selection:bg-(--blue-a4) selection:text-transparent",
+ )}
+ onChange={(e) => {
+ onChange(e.target.value);
+ setOpen(true);
+ setHighlighted(0);
+ trackCaret();
+ }}
+ onScroll={syncScroll}
+ onClick={() => setOpen(true)}
+ onSelect={trackCaret}
+ onKeyDown={onKeyDown}
+ onFocus={() => {
+ if (openOnFocus) setOpen(true);
+ }}
+ onBlur={() => setTimeout(() => setOpen(false), 120)}
+ />
+ </div>
+ {visible && (
+ <div className="absolute top-full right-0 left-0 z-50 mt-1.5 overflow-hidden rounded-lg border border-(--gray-a6) bg-(--color-panel-solid) shadow-lg">
+ {group.heading !== "" && (
+ <div className="px-3 pt-2 pb-1 font-medium text-(--gray-9) text-[11px] uppercase tracking-wider">
+ {group.heading}
+ </div>
+ )}
+ <div
+ id={listboxId}
+ role="listbox"
+ aria-label="Query suggestions"
+ className="max-h-60 overflow-y-auto px-1 pb-1"
+ >
+ {suggestions.map((suggestion, index) => (
+ <button
+ id={`${listboxId}-${index}`}
+ key={`${context.activeKey ?? "key"}:${suggestion.label}`}
+ type="button"
+ role="option"
+ aria-selected={index === highlightedIndex}
+ className={cn(
+ "flex h-7 w-full items-center gap-2 rounded-md px-2 text-left text-[13px]",
+ index === highlightedIndex
+ ? "bg-fill-hover text-foreground"
+ : "text-(--gray-11)",
+ )}
+ onMouseDown={(e) => e.preventDefault()}
+ onMouseEnter={() => setHighlighted(index)}
+ onClick={() => apply(suggestion)}
+ >
+ {suggestion.icon}
+ <FeedQueryMatchedLabel
+ label={suggestion.label}
+ typed={context.typed}
+ />
+ {suggestion.hint && (
+ <span className="min-w-0 flex-1 truncate text-right text-(--gray-9) text-xs">
+ {suggestion.hint}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-2 border-(--gray-a5) border-t px-3 py-1.5 text-(--gray-9) text-xs">
+ <Kbd>↑↓</Kbd> navigate
+ <Kbd>⏎</Kbd> select
+ <Kbd>tab</Kbd> complete
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.stories.tsx
new file mode 100644
index 000000000000..36b3202aed4a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.stories.tsx
@@ -0,0 +1,163 @@
+import type { Task, TaskRun, UserBasic } from "@posthog/shared/domain-types";
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import { authKeys } from "@posthog/ui/features/auth/useCurrentUser";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useQueryClient } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { taskFeedResultsQueryKey } from "../hooks/useTaskFeedResults";
+import { type TaskFeed, useTaskFeedsStore } from "../stores/taskFeedsStore";
+import { TaskFeedHome } from "./TaskFeedHome";
+
+const adam: UserBasic = {
+ id: 1,
+ uuid: "user-adam",
+ email: "[email protected]",
+ first_name: "Adam",
+ last_name: "Bowker",
+};
+
+function run(overrides: Partial<TaskRun>): TaskRun {
+ return {
+ id: "run-1",
+ task: "task-1",
+ team: 1,
+ branch: null,
+ status: "completed",
+ environment: "cloud",
+ log_url: "",
+ error_message: null,
+ output: null,
+ state: {},
+ created_at: "2026-07-01T09:00:00Z",
+ updated_at: "2026-07-01T09:05:00Z",
+ completed_at: null,
+ ...overrides,
+ };
+}
+
+function task(overrides: Partial<Task>): Task {
+ return {
+ id: "task-1",
+ task_number: 1,
+ slug: "task-1",
+ title: "Reconcile invoice line items",
+ description:
+ "Reconcile invoice line items against the ledger and flag mismatches",
+ created_at: "2026-07-01T09:00:00Z",
+ updated_at: "2026-07-01T09:05:00Z",
+ origin_product: "user_created",
+ created_by: adam,
+ repository: "example-org/webapp",
+ ...overrides,
+ };
+}
+
+const FEED: TaskFeed = {
+ id: "feed-1",
+ projectId: 1,
+ ownerId: "user-1",
+ name: "Billing work",
+ query: "billing -status:failed pr:any",
+ createdAt: "2026-07-01T08:00:00Z",
+};
+
+// Dates sit around the frozen test-runner clock (2026-07-01T10:30Z) so the
+// day separators read Today and the relative times stay stable.
+const results: Task[] = [
+ task({
+ id: "task-billing-1",
+ title: "Fix billing address validation",
+ description: "Billing address validation rejects valid postcodes",
+ created_at: "2026-07-01T10:00:00Z",
+ updated_at: "2026-07-01T10:20:00Z",
+ latest_run: run({
+ id: "run-b1",
+ task: "task-billing-1",
+ status: "in_progress",
+ output: { pr_url: "https://github.com/example-org/webapp/pull/62" },
+ }),
+ }),
+ task({
+ id: "task-billing-2",
+ title: "Add billing period picker to invoices",
+ created_at: "2026-07-01T09:30:00Z",
+ updated_at: "2026-07-01T09:45:00Z",
+ latest_run: run({
+ id: "run-b2",
+ task: "task-billing-2",
+ output: { pr_url: "https://github.com/example-org/webapp/pull/58" },
+ }),
+ }),
+];
+
+// The feed's query never runs in a story (no authenticated client), so the
+// results come from the cache the hook reads through.
+function SeedResults({
+ tasks,
+ children,
+}: {
+ tasks: Task[];
+ children: ReactNode;
+}) {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(taskFeedResultsQueryKey(FEED.query), {
+ tasks,
+ isComplete: true,
+ });
+ return <>{children}</>;
+}
+
+const meta: Meta<typeof TaskFeedHome> = {
+ title: "Spaces/TaskFeedHome",
+ component: TaskFeedHome,
+ parameters: { layout: "fullscreen" },
+ decorators: [
+ (Story) => {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(authKeys.currentUser(null), { uuid: "user-1" });
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ currentProjectId: FEED.projectId,
+ },
+ });
+ useTaskFeedsStore.setState({ feeds: [FEED] });
+ return (
+ <div className="flex h-[720px] flex-col">
+ <Story />
+ </div>
+ );
+ },
+ ],
+ args: { feedId: FEED.id },
+};
+
+export default meta;
+type Story = StoryObj<typeof TaskFeedHome>;
+
+export const WithResults: Story = {
+ decorators: [
+ (Story) => (
+ <SeedResults tasks={results}>
+ <Story />
+ </SeedResults>
+ ),
+ ],
+};
+
+export const Empty: Story = {
+ decorators: [
+ (Story) => (
+ <SeedResults tasks={[]}>
+ <Story />
+ </SeedResults>
+ ),
+ ],
+};
+
+export const NotFound: Story = {
+ args: { feedId: "feed-missing" },
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.test.tsx
new file mode 100644
index 000000000000..ef7b7d8dc539
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.test.tsx
@@ -0,0 +1,109 @@
+import { Theme } from "@radix-ui/themes";
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+let taskResultsError: Error | null = null;
+const refetch = vi.fn();
+
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
+vi.mock("@posthog/ui/hooks/useSetHeaderContent", () => ({
+ useSetHeaderContent: vi.fn(),
+}));
+vi.mock("@posthog/ui/features/canvas/components/ChannelBreadcrumb", () => ({
+ ChannelBreadcrumb: () => null,
+}));
+vi.mock("@posthog/ui/features/canvas/components/ChannelFeedView", () => ({
+ ChannelFeedView: ({ intro }: { intro?: ReactNode }) => intro,
+}));
+vi.mock("@posthog/ui/features/canvas/components/TaskFeedModal", () => ({
+ TaskFeedModal: () => null,
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useProjectTaskFeeds", () => ({
+ useProjectTaskFeed: () => ({
+ id: "feed-1",
+ projectId: 1,
+ ownerId: "user-1",
+ name: "Billing work",
+ query: "billing",
+ createdAt: "2026-08-01T00:00:00Z",
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskFeedResults", () => ({
+ useTaskFeedResults: () => ({
+ canRetry: true,
+ error: taskResultsError,
+ errorMessage: taskResultsError
+ ? "Couldn't load matching tasks. Try again."
+ : null,
+ isComplete: true,
+ isFetching: false,
+ isLoading: false,
+ issues: [],
+ refetch,
+ tasks: [],
+ }),
+}));
+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));
+
+import { useTaskFeedsStore } from "@posthog/ui/features/canvas/stores/taskFeedsStore";
+import { TaskFeedHome } from "./TaskFeedHome";
+
+describe("TaskFeedHome", () => {
+ beforeEach(() => {
+ taskResultsError = null;
+ refetch.mockClear();
+ useTaskFeedsStore.setState({
+ feeds: [
+ {
+ id: "feed-1",
+ projectId: 1,
+ ownerId: "user-1",
+ name: "Billing work",
+ query: "billing",
+ createdAt: "2026-08-01T00:00:00Z",
+ },
+ ],
+ });
+ });
+
+ it("shows task request failures instead of an empty result", async () => {
+ taskResultsError = new Error("Network error");
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <TaskFeedHome feedId="feed-1" />
+ </Theme>,
+ );
+
+ expect(
+ screen.getByText("Couldn't load matching tasks. Try again."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("No tasks match this saved search"),
+ ).not.toBeInTheDocument();
+ await user.click(screen.getByText("Try again"));
+ expect(refetch).toHaveBeenCalledOnce();
+ });
+
+ it("requires confirmation before deleting a saved search", async () => {
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <TaskFeedHome feedId="feed-1" />
+ </Theme>,
+ );
+
+ await user.click(screen.getByText("Delete…"));
+ expect(useTaskFeedsStore.getState().feeds).toHaveLength(1);
+
+ const dialog = screen.getByRole("alertdialog");
+ expect(
+ within(dialog).getByText("Delete saved search?"),
+ ).toBeInTheDocument();
+ await user.click(within(dialog).getByText("Delete"));
+
+ expect(useTaskFeedsStore.getState().feeds).toEqual([]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.tsx
new file mode 100644
index 000000000000..c7e7ca733211
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedHome.tsx
@@ -0,0 +1,233 @@
+import {
+ MagnifyingGlassIcon,
+ PencilSimpleIcon,
+ TrashIcon,
+} from "@phosphor-icons/react";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ Heading,
+ Skeleton,
+ Text,
+} from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import type { Task } from "@posthog/shared/domain-types";
+import { ChannelBreadcrumb } from "@posthog/ui/features/canvas/components/ChannelBreadcrumb";
+import { ChannelFeedView } from "@posthog/ui/features/canvas/components/ChannelFeedView";
+import { FeedQueryHighlight } from "@posthog/ui/features/canvas/components/FeedQueryInput";
+import { TaskFeedModal } from "@posthog/ui/features/canvas/components/TaskFeedModal";
+import { useProjectTaskFeed } from "@posthog/ui/features/canvas/hooks/useProjectTaskFeeds";
+import { useTaskFeedResults } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";
+import { useTaskFeedsStore } from "@posthog/ui/features/canvas/stores/taskFeedsStore";
+import type { ThreadPanelTab } from "@posthog/ui/features/canvas/stores/threadPanelStore";
+import { openRightPanelSide } from "@posthog/ui/features/navigation/rightPanelSide";
+import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
+import { toast } from "@posthog/ui/primitives/toast";
+import { openTask } from "@posthog/ui/router/useOpenTask";
+import { track } from "@posthog/ui/shell/analytics";
+import { useNavigate } from "@tanstack/react-router";
+import { useCallback, useEffect, useMemo, useState } from "react";
+
+export function TaskFeedHome({ feedId }: { feedId: string }) {
+ const navigate = useNavigate();
+ const feed = useProjectTaskFeed(feedId);
+ const removeFeed = useTaskFeedsStore((s) => s.removeFeed);
+ const {
+ canRetry,
+ error,
+ errorMessage,
+ isComplete,
+ isFetching,
+ isLoading,
+ issues,
+ refetch,
+ tasks,
+ } = useTaskFeedResults(feed?.query);
+ const [editOpen, setEditOpen] = useState(false);
+ const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
+
+ const trackedFeedId = feed?.id;
+ useEffect(() => {
+ if (!trackedFeedId) return;
+ track(ANALYTICS_EVENTS.TASK_FEED_ACTION, {
+ action_type: "open",
+ surface: "feed_home",
+ feed_id: trackedFeedId,
+ });
+ }, [trackedFeedId]);
+
+ useSetHeaderContent(
+ useMemo(
+ () => <ChannelBreadcrumb channelName={feed?.name ?? "Feed"} />,
+ [feed?.name],
+ ),
+ );
+
+ const handleOpenTask = useCallback((task: Task) => {
+ void openTask(task, { channelId: task.channel ?? undefined });
+ }, []);
+
+ const handleOpenThread = useCallback(
+ (task: Task, tab?: ThreadPanelTab) => {
+ if (tab) openRightPanelSide(tab, task.id);
+ handleOpenTask(task);
+ },
+ [handleOpenTask],
+ );
+
+ const handleDelete = useCallback(() => {
+ if (!feed) return;
+ removeFeed(feed.id);
+ track(ANALYTICS_EVENTS.TASK_FEED_ACTION, {
+ action_type: "delete",
+ surface: "feed_home",
+ feed_id: feed.id,
+ });
+ toast.success("Saved search deleted");
+ void navigate({ to: "/website" });
+ }, [feed, removeFeed, navigate]);
+
+ if (!feed) {
+ return (
+ <div className="flex h-full min-w-0 flex-col items-center justify-center gap-2 bg-gray-1 px-4 text-center">
+ <Heading className="font-bold text-xl">Saved search not found</Heading>
+ <Text className="max-w-md text-muted-foreground">
+ This saved search is not in this project. Searches are saved per
+ project on this device. A search saved in another project or on
+ another device does not appear here.
+ </Text>
+ </div>
+ );
+ }
+
+ const queryBar = (
+ <div className="mb-2 flex w-full items-center gap-2 rounded-xl border border-(--gray-4) bg-(--gray-2) px-4 py-3">
+ <MagnifyingGlassIcon size={14} className="shrink-0 text-(--gray-9)" />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <FeedQueryHighlight query={feed.query} className="min-w-0 truncate" />
+ {isLoading ? (
+ <Skeleton className="h-3 w-12 shrink-0 self-center" />
+ ) : error ? (
+ canRetry ? (
+ <Button
+ variant="link-muted"
+ size="xs"
+ loading={isFetching}
+ disabled={isFetching}
+ onClick={refetch}
+ >
+ Try again
+ </Button>
+ ) : null
+ ) : (
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {isComplete
+ ? `${tasks.length} ${tasks.length === 1 ? "task" : "tasks"}`
+ : "Partial results"}
+ </span>
+ )}
+ </div>
+ {error ? (
+ <span className="text-(--red-11) text-xs">{errorMessage}</span>
+ ) : (
+ !isLoading &&
+ !isComplete && (
+ <span className="text-muted-foreground text-xs">
+ Some matching tasks may not be shown.
+ </span>
+ )
+ )}
+ {issues.map((issue) => (
+ <span
+ key={`${issue.raw}-${issue.message}`}
+ className={
+ issue.kind === "unsupported"
+ ? "text-(--amber-11) text-xs"
+ : "text-(--red-11) text-xs"
+ }
+ >
+ {issue.message}
+ </span>
+ ))}
+ </div>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => setEditOpen(true)}
+ aria-label="Edit saved search"
+ >
+ <PencilSimpleIcon size={12} />
+ Edit
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => setConfirmDeleteOpen(true)}
+ aria-label="Delete saved search…"
+ >
+ <TrashIcon size={12} />
+ Delete…
+ </Button>
+ </div>
+ );
+
+ const intro = (
+ <div>
+ {queryBar}
+ {!isLoading && !error && isComplete && tasks.length === 0 && (
+ <div className="flex flex-col items-center gap-1 px-4 py-16 text-center">
+ <Text className="font-medium">No tasks match this saved search</Text>
+ <Text className="text-muted-foreground text-sm">
+ Tasks appear here when they match the query.
+ </Text>
+ </div>
+ )}
+ </div>
+ );
+
+ return (
+ <div className="flex h-full min-w-0 bg-gray-1">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <ChannelFeedView
+ channelId={feed.id}
+ tasks={tasks}
+ isLoading={isLoading}
+ intro={intro}
+ onOpenTask={handleOpenTask}
+ onOpenThread={handleOpenThread}
+ />
+ </div>
+ <TaskFeedModal open={editOpen} onOpenChange={setEditOpen} feed={feed} />
+ <AlertDialog open={confirmDeleteOpen} onOpenChange={setConfirmDeleteOpen}>
+ <AlertDialogContent className="max-w-md">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete saved search?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Delete <span className="font-medium">{feed.name}</span>? You
+ cannot undo this action.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ render={
+ <Button variant="outline" size="sm">
+ Cancel
+ </Button>
+ }
+ />
+ <Button variant="destructive" size="sm" onClick={handleDelete}>
+ Delete
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.stories.tsx
new file mode 100644
index 000000000000..2adafbe40193
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.stories.tsx
@@ -0,0 +1,96 @@
+import type { Task } from "@posthog/shared/domain-types";
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import { authKeys } from "@posthog/ui/features/auth/useCurrentUser";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useQueryClient } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { taskFeedResultsQueryKey } from "../hooks/useTaskFeedResults";
+import type { TaskFeed } from "../stores/taskFeedsStore";
+import { TaskFeedModal } from "./TaskFeedModal";
+
+const FEED: TaskFeed = {
+ id: "feed-1",
+ projectId: 1,
+ ownerId: "user-1",
+ name: "Billing work",
+ query: "billing -status:failed pr:any",
+ createdAt: "2026-07-01T08:00:00Z",
+};
+
+function task(id: string, title: string): Task {
+ return {
+ id,
+ task_number: 1,
+ slug: id,
+ title,
+ description: title,
+ created_at: "2026-07-01T09:00:00Z",
+ updated_at: "2026-07-01T09:05:00Z",
+ origin_product: "user_created",
+ repository: "example-org/webapp",
+ };
+}
+
+// The query never runs in a story (no authenticated client), so the match
+// count comes from the cache the preview hook reads through.
+function SeedResults({
+ query,
+ tasks,
+ children,
+}: {
+ query: string;
+ tasks: Task[];
+ children: ReactNode;
+}) {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(taskFeedResultsQueryKey(query), {
+ tasks,
+ isComplete: true,
+ });
+ return <>{children}</>;
+}
+
+const meta: Meta<typeof TaskFeedModal> = {
+ title: "Spaces/TaskFeedModal",
+ component: TaskFeedModal,
+ parameters: { layout: "fullscreen" },
+ decorators: [
+ (Story) => {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(authKeys.currentUser(null), { uuid: "user-1" });
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ currentProjectId: FEED.projectId,
+ },
+ });
+ return <Story />;
+ },
+ ],
+ args: { open: true, onOpenChange: () => {} },
+};
+
+export default meta;
+type Story = StoryObj<typeof TaskFeedModal>;
+
+export const Create: Story = {};
+
+export const Edit: Story = {
+ args: { feed: FEED },
+ decorators: [
+ (Story) => (
+ <SeedResults
+ query={FEED.query}
+ tasks={[
+ task("t1", "Fix billing address validation"),
+ task("t2", "Add billing period picker to invoices"),
+ ]}
+ >
+ <Story />
+ </SeedResults>
+ ),
+ ],
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.test.tsx
new file mode 100644
index 000000000000..3a1e666b7038
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.test.tsx
@@ -0,0 +1,93 @@
+import { Theme } from "@radix-ui/themes";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+let taskQueryCanRetry = true;
+let taskQueryError: Error | null = null;
+let taskQueryErrorMessage: string | null = null;
+const refetch = 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/ui/features/canvas/hooks/useTaskFeedResults", () => ({
+ useFeedQueryPlan: () => ({ plan: undefined }),
+ useTaskFeedResults: () => ({
+ tasks: [{ id: "task-1" }],
+ canRetry: taskQueryCanRetry,
+ error: taskQueryError,
+ errorMessage: taskQueryErrorMessage,
+ isComplete: true,
+ isFetching: false,
+ isLoading: false,
+ issues: [],
+ refetch,
+ }),
+}));
+vi.mock("@posthog/ui/primitives/hooks/useDebouncedValue", () => ({
+ useDebouncedValue: () => ({ debounced: "billing", isPending: false }),
+}));
+vi.mock("./FeedQueryInput", () => ({
+ FeedQueryInput: () => <input />,
+}));
+
+import { TaskFeedModal } from "./TaskFeedModal";
+
+describe("TaskFeedModal", () => {
+ afterEach(() => {
+ taskQueryCanRetry = true;
+ taskQueryError = null;
+ taskQueryErrorMessage = null;
+ refetch.mockClear();
+ });
+
+ it("hides stale preview results when the query is empty", () => {
+ render(
+ <Theme>
+ <TaskFeedModal open onOpenChange={vi.fn()} />
+ </Theme>,
+ );
+
+ expect(screen.queryByText("1 task matches")).not.toBeInTheDocument();
+ });
+
+ it("shows task preview failures and lets a person retry", async () => {
+ taskQueryError = new Error("Network error");
+ taskQueryErrorMessage = "Couldn't load matching tasks. Try again.";
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <TaskFeedModal open initialQuery="billing" onOpenChange={vi.fn()} />
+ </Theme>,
+ );
+
+ expect(
+ screen.getByText("Couldn't load matching tasks. Try again."),
+ ).toBeInTheDocument();
+ await user.click(screen.getByText("Try again"));
+ expect(refetch).toHaveBeenCalledOnce();
+ });
+
+ it("explains when member lookup cannot verify the query", () => {
+ taskQueryCanRetry = false;
+ taskQueryError = new Error("Member lookup incomplete");
+ taskQueryErrorMessage =
+ "Organization member lookup is incomplete. This search cannot verify every teammate.";
+ render(
+ <Theme>
+ <TaskFeedModal
+ open
+ initialQuery="created-by:alex"
+ onOpenChange={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ expect(screen.getByText(taskQueryErrorMessage)).toBeInTheDocument();
+ expect(screen.queryByText("Try again")).not.toBeInTheDocument();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.tsx
new file mode 100644
index 000000000000..7c6febc4144d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedModal.tsx
@@ -0,0 +1,231 @@
+import { parseFeedQuery, suggestFeedName } from "@posthog/core/tasks/feedQuery";
+import {
+ Button,
+ cn,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Input,
+ Spinner,
+} from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
+import { FeedQueryInput } from "@posthog/ui/features/canvas/components/FeedQueryInput";
+import { unfinishedFilterKeys } from "@posthog/ui/features/canvas/components/feedQuerySuggestionUtils";
+import {
+ useFeedQueryPlan,
+ useTaskFeedResults,
+} from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";
+import {
+ type TaskFeed,
+ useTaskFeedsStore,
+} from "@posthog/ui/features/canvas/stores/taskFeedsStore";
+import { useDebouncedValue } from "@posthog/ui/primitives/hooks/useDebouncedValue";
+import { track } from "@posthog/ui/shell/analytics";
+import { useEffect, useMemo, useRef, useState } from "react";
+
+const MAX_FEED_NAME_LENGTH = 80;
+const PREVIEW_DEBOUNCE_MS = 400;
+
+export function TaskFeedModal({
+ open,
+ onOpenChange,
+ feed,
+ initialQuery,
+ surface = "sidebar",
+ onCreated,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ feed?: TaskFeed;
+ initialQuery?: string;
+ surface?: "sidebar" | "command_menu";
+ onCreated?: (feed: TaskFeed) => void;
+}) {
+ const addFeed = useTaskFeedsStore((s) => s.addFeed);
+ const updateFeed = useTaskFeedsStore((s) => s.updateFeed);
+ const projectId = useAuthStateValue((s) => s.currentProjectId);
+ const client = useOptionalAuthenticatedClient();
+ const { data: currentUser } = useCurrentUser({ client });
+ const ownerId = currentUser?.uuid ?? null;
+ const seedQuery = feed?.query ?? initialQuery ?? "";
+ const [name, setName] = useState(
+ feed?.name ?? (seedQuery ? suggestFeedName(seedQuery) : ""),
+ );
+ const [query, setQuery] = useState(seedQuery);
+ const nameEdited = useRef(!!feed);
+
+ useEffect(() => {
+ if (!open) return;
+ const nextQuery = feed?.query ?? initialQuery ?? "";
+ setName(feed?.name ?? (nextQuery ? suggestFeedName(nextQuery) : ""));
+ setQuery(nextQuery);
+ nameEdited.current = !!feed;
+ }, [open, feed, initialQuery]);
+
+ const setQueryAndSuggestName = (next: string) => {
+ setQuery(next);
+ if (!nameEdited.current) setName(suggestFeedName(next));
+ };
+
+ const trimmedName = name.trim();
+ const trimmedQuery = query.trim();
+ const canSubmit =
+ trimmedName !== "" &&
+ trimmedQuery !== "" &&
+ (feed !== undefined || (projectId !== null && ownerId !== null));
+
+ const { debounced: previewQuery, isPending } = useDebouncedValue(
+ open ? trimmedQuery : "",
+ PREVIEW_DEBOUNCE_MS,
+ );
+ const preview = useTaskFeedResults(previewQuery);
+ const { plan } = useFeedQueryPlan(open ? trimmedQuery : "");
+ const issue = plan?.issues[0];
+ const unfinished = useMemo(() => {
+ const parsedText = parseFeedQuery(trimmedQuery).text;
+ return unfinishedFilterKeys(parsedText)[0];
+ }, [trimmedQuery]);
+ const counting = trimmedQuery !== "" && (isPending || preview.isLoading);
+
+ const submit = () => {
+ if (!canSubmit) return;
+ if (feed) {
+ updateFeed(feed.id, { name: trimmedName, query: trimmedQuery });
+ track(ANALYTICS_EVENTS.TASK_FEED_ACTION, {
+ action_type: "update",
+ surface,
+ feed_id: feed.id,
+ query_length: trimmedQuery.length,
+ });
+ } else {
+ if (projectId === null || ownerId === null) return;
+ const created = addFeed({
+ name: trimmedName,
+ query: trimmedQuery,
+ projectId,
+ ownerId,
+ });
+ track(ANALYTICS_EVENTS.TASK_FEED_ACTION, {
+ action_type: "create",
+ surface,
+ feed_id: created.id,
+ query_length: trimmedQuery.length,
+ });
+ onCreated?.(created);
+ }
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="overflow-visible sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {feed ? "Edit saved search" : "Save search"}
+ </DialogTitle>
+ <DialogDescription>
+ A saved search updates when tasks match its query. Reopen it from
+ the command palette.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-3">
+ <label htmlFor="task-feed-query" className="font-medium text-sm">
+ Query
+ </label>
+ <span className="flex shrink-0 items-center gap-1.5 text-muted-foreground text-xs tabular-nums">
+ {counting ? (
+ <Spinner className="size-3" />
+ ) : preview.error && preview.canRetry ? (
+ <Button
+ variant="link-muted"
+ size="xs"
+ loading={preview.isFetching}
+ disabled={preview.isFetching}
+ onClick={preview.refetch}
+ >
+ Try again
+ </Button>
+ ) : preview.error ? null : (
+ trimmedQuery !== "" &&
+ previewQuery !== "" &&
+ (preview.isComplete
+ ? preview.tasks.length === 1
+ ? "1 task matches"
+ : `${preview.tasks.length} tasks match`
+ : "Some matches may not be shown")
+ )}
+ </span>
+ </div>
+ <FeedQueryInput
+ id="task-feed-query"
+ autoFocus
+ openOnFocus={false}
+ value={query}
+ onChange={setQueryAndSuggestName}
+ onSubmit={submit}
+ placeholder="Example: billing created-by:@me -status:failed"
+ />
+ <div
+ className={cn(
+ "min-h-5 min-w-0 truncate text-xs",
+ preview.error || issue
+ ? issue?.kind === "unsupported" && !preview.error
+ ? "text-(--amber-11)"
+ : "text-destructive"
+ : unfinished
+ ? "text-(--amber-11)"
+ : "text-muted-foreground",
+ )}
+ title={issue?.message}
+ >
+ {preview.error
+ ? preview.errorMessage
+ : (issue?.message ??
+ (unfinished
+ ? `"${unfinished.word}" is searched as text. Did you mean ${unfinished.keys.slice(0, 2).join(" or ")}?`
+ : "Free text searches task titles. Repeat a filter to match either value. Use - to exclude a filter."))}
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ <label htmlFor="task-feed-name" className="font-medium text-sm">
+ Name
+ </label>
+ <Input
+ id="task-feed-name"
+ value={name}
+ placeholder="Name based on the query"
+ maxLength={MAX_FEED_NAME_LENGTH}
+ onChange={(event) => {
+ setName(event.target.value);
+ nameEdited.current = event.target.value.trim() !== "";
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ submit();
+ }
+ }}
+ />
+ </div>
+ </DialogBody>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button variant="primary" disabled={!canSubmit} onClick={submit}>
+ {feed ? "Save" : "Save search"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts b/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts
new file mode 100644
index 000000000000..310432565ef8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts
@@ -0,0 +1,58 @@
+import type { Task } from "@posthog/shared/domain-types";
+import type { ChannelFeedSystemMessage } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
+
+// Injected context wrappers a prompt may carry (Slack thread history, a
+// channel's CONTEXT.md, canvas instructions, saved personalization). The feed
+// shows what the user actually asked, so these are stripped and the timeline
+// renders them as their own collapsible surfaces.
+const CONTEXT_BLOCK_REGEX =
+ /<(slack_thread_context|channel_context|canvas_generation_instructions|user_custom_instructions)\b[^>]*>[\s\S]*?<\/\1>/g;
+
+export function stripContextBlocks(text: string): string {
+ return text
+ .replace(CONTEXT_BLOCK_REGEX, "")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+// A single feed entry, either a real task card or a synthetic system row, tagged
+// with the timestamp used to interleave the two.
+export type FeedEntry =
+ | { kind: "task"; id: string; createdAt: string; task: Task }
+ | {
+ kind: "system";
+ id: string;
+ createdAt: string;
+ message: ChannelFeedSystemMessage;
+ };
+
+// Merge tasks + system rows into one newest-first list. ISO timestamps sort
+// lexically, so a plain string compare is chronological. Announcements are
+// posted 1ms before the task they describe; if the backend truncates that
+// sub-second offset the timestamps tie, so break ties task-first to keep the
+// announcement directly under its card.
+export function mergeFeedEntries(
+ tasks: Task[],
+ systemMessages: ChannelFeedSystemMessage[],
+): FeedEntry[] {
+ const merged: FeedEntry[] = [
+ ...tasks.map((task) => ({
+ kind: "task" as const,
+ id: task.id,
+ createdAt: task.created_at,
+ task,
+ })),
+ ...systemMessages.map((message) => ({
+ kind: "system" as const,
+ id: message.id,
+ createdAt: message.createdAt,
+ message,
+ })),
+ ];
+ merged.sort(
+ (a, b) =>
+ b.createdAt.localeCompare(a.createdAt) ||
+ (a.kind === b.kind ? 0 : a.kind === "task" ? -1 : 1),
+ );
+ return merged;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestionUtils.ts b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestionUtils.ts
new file mode 100644
index 000000000000..feddc6c08722
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestionUtils.ts
@@ -0,0 +1,77 @@
+import type { ReactNode } from "react";
+
+export interface FeedQuerySuggestion {
+ insert: string;
+ label: string;
+ hint?: string;
+ icon?: ReactNode;
+}
+
+export interface FeedQueryEditContext {
+ chunk: { start: number; end: number; text: string };
+ activeKey: string | null;
+ typed: string;
+ // Completion matches without `not:`, so replacements restore it to avoid inverting the filter.
+ valueNegated: boolean;
+}
+
+export const FEED_QUERY_KEY_LABELS = [
+ "created-by:",
+ "commented-by:",
+ "mentions:",
+ "involves:",
+ "space:",
+ "repo:",
+ "status:",
+ "is:",
+ "origin:",
+ "pr:",
+ "ci:",
+ "type:",
+ "saved:",
+] as const;
+
+export function unfinishedFilterKeys(
+ text: string,
+): { word: string; keys: string[] }[] {
+ const candidates: { word: string; keys: string[] }[] = [];
+
+ for (const word of text.split(/\s+/)) {
+ if (word === "") continue;
+
+ const normalizedWord = word.toLowerCase();
+ const keys: string[] = [];
+ for (const key of FEED_QUERY_KEY_LABELS) {
+ if (key.startsWith(normalizedWord)) keys.push(key);
+ }
+ if (keys.length > 0) candidates.push({ word, keys });
+ }
+
+ return candidates;
+}
+
+function quoteIfNeeded(value: string): string {
+ return /\s/.test(value) ? `"${value}"` : value;
+}
+
+export function applyFeedQuerySuggestion(
+ value: string,
+ context: FeedQueryEditContext,
+ suggestion: FeedQuerySuggestion,
+): { next: string; caret: number; completedKey: boolean } {
+ const negation = context.chunk.text.startsWith("-") ? "-" : "";
+ const isKey = context.activeKey === null;
+ const valuePrefix = context.valueNegated ? "not:" : "";
+ const replacement = isKey
+ ? `${negation}${suggestion.insert}`
+ : `${negation}${context.activeKey}:${valuePrefix}${quoteIfNeeded(suggestion.insert)} `;
+ const next =
+ value.slice(0, context.chunk.start) +
+ replacement +
+ value.slice(context.chunk.end);
+ return {
+ next,
+ caret: context.chunk.start + replacement.length,
+ completedKey: isKey,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx
new file mode 100644
index 000000000000..789d0d7ea9ef
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx
@@ -0,0 +1,467 @@
+import {
+ AppWindowIcon,
+ ArchiveIcon,
+ AtIcon,
+ ChatCircleIcon,
+ CheckCircleIcon,
+ CircleHalfIcon,
+ GitMergeIcon,
+ GitPullRequestIcon,
+ HashIcon,
+ MagnifyingGlassIcon,
+ PackageIcon,
+ PencilSimpleIcon,
+ PushPinIcon,
+ SquaresFourIcon,
+ UserCircleIcon,
+ UsersIcon,
+ XIcon,
+} from "@phosphor-icons/react";
+import { TASK_RUN_STATUSES } from "@posthog/core/tasks/feedQuery";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import type {
+ FeedQueryEditContext,
+ FeedQuerySuggestion,
+} from "@posthog/ui/features/canvas/components/feedQuerySuggestionUtils";
+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { getOriginProductMeta } from "@posthog/ui/features/sidebar/components/items/TaskIcon";
+import { DOT_TONE_VAR } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+import { type ReactNode, useMemo } from "react";
+
+interface FeedQuerySuggestionGroup {
+ heading: string;
+ items: FeedQuerySuggestion[];
+}
+
+function keyIcon(icon: ReactNode): ReactNode {
+ return (
+ <span className="flex size-4 items-center justify-center text-(--gray-9)">
+ {icon}
+ </span>
+ );
+}
+
+const KEY_SUGGESTIONS: FeedQuerySuggestion[] = [
+ {
+ insert: "created-by:",
+ label: "created-by:",
+ hint: "who started the task",
+ icon: keyIcon(<UserCircleIcon size={14} />),
+ },
+ {
+ insert: "commented-by:",
+ label: "commented-by:",
+ hint: "who commented on the thread",
+ icon: keyIcon(<ChatCircleIcon size={14} />),
+ },
+ {
+ insert: "mentions:",
+ label: "mentions:",
+ hint: "who the thread mentions",
+ icon: keyIcon(<AtIcon size={14} />),
+ },
+ {
+ insert: "involves:",
+ label: "involves:",
+ hint: "task creator or commenter",
+ icon: keyIcon(<UsersIcon size={14} />),
+ },
+ {
+ insert: "space:",
+ label: "space:",
+ hint: "tasks in a space",
+ icon: keyIcon(<HashIcon size={14} />),
+ },
+ {
+ insert: "repo:",
+ label: "repo:",
+ hint: "task repository",
+ icon: keyIcon(<PackageIcon size={14} />),
+ },
+ {
+ insert: "status:",
+ label: "status:",
+ hint: "task's latest run",
+ icon: keyIcon(<CircleHalfIcon size={14} />),
+ },
+ {
+ insert: "is:",
+ label: "is:",
+ hint: "archived, pinned, running, done, failed",
+ icon: keyIcon(<ArchiveIcon size={14} />),
+ },
+ {
+ insert: "origin:",
+ label: "origin:",
+ hint: "where the task came from",
+ icon: keyIcon(<AppWindowIcon size={14} />),
+ },
+ {
+ insert: "pr:",
+ label: "pr:",
+ hint: "any, none, open, draft, merged, closed",
+ icon: keyIcon(<GitPullRequestIcon size={14} />),
+ },
+ {
+ insert: "ci:",
+ label: "ci:",
+ hint: "failing, passing, pending",
+ icon: keyIcon(<CheckCircleIcon size={14} />),
+ },
+];
+
+const PALETTE_KEY_SUGGESTIONS: FeedQuerySuggestion[] = [
+ {
+ insert: "type:",
+ label: "type:",
+ hint: "task, space, command, saved",
+ icon: keyIcon(<SquaresFourIcon size={14} />),
+ },
+ {
+ insert: "saved:",
+ label: "saved:",
+ hint: "open saved searches",
+ icon: keyIcon(<MagnifyingGlassIcon size={14} />),
+ },
+];
+
+const TYPE_VALUES: FeedQuerySuggestion[] = [
+ { insert: "task", label: "task", hint: "only tasks" },
+ { insert: "space", label: "space", hint: "only spaces" },
+ { insert: "command", label: "command", hint: "only commands" },
+ { insert: "saved", label: "saved", hint: "only saved searches" },
+].map((s) => ({ ...s, icon: keyIcon(<SquaresFourIcon size={14} />) }));
+
+const IS_VALUES = ["archived", "pinned", "running", "done", "failed"];
+
+const ORIGIN_VALUES: { value: string; fallbackHint: string }[] = [
+ { value: "user_created", fallbackHint: "you, from desktop or the app" },
+ { value: "slack", fallbackHint: "Slack" },
+ { value: "signals_scout", fallbackHint: "Signals scout" },
+ { value: "posthog_ai", fallbackHint: "PostHog AI" },
+ { value: "signal_report", fallbackHint: "Signals" },
+ { value: "error_tracking", fallbackHint: "Error tracking" },
+ { value: "session_summaries", fallbackHint: "Session summary" },
+ { value: "loop", fallbackHint: "Loops" },
+ { value: "automation", fallbackHint: "Automation" },
+ { value: "review_hog", fallbackHint: "ReviewHog" },
+ { value: "support_queue", fallbackHint: "Support" },
+ { value: "support_reply", fallbackHint: "Support reply" },
+ { value: "eval_clusters", fallbackHint: "Evals" },
+ { value: "experiments", fallbackHint: "Experiments" },
+ { value: "onboarding", fallbackHint: "Onboarding" },
+ { value: "hogdesk", fallbackHint: "HogDesk" },
+ { value: "mcp_analytics", fallbackHint: "MCP analytics" },
+ { value: "signals_chat", fallbackHint: "Signals chat" },
+ { value: "image_builder", fallbackHint: "Image builder" },
+];
+
+const PR_SUGGESTIONS: FeedQuerySuggestion[] = [
+ {
+ insert: "any",
+ label: "any",
+ hint: "has a pull request",
+ icon: keyIcon(<GitPullRequestIcon size={14} />),
+ },
+ {
+ insert: "none",
+ label: "none",
+ hint: "no pull request",
+ icon: keyIcon(<XIcon size={14} />),
+ },
+ {
+ insert: "open",
+ label: "open",
+ hint: "PR open for review",
+ icon: keyIcon(<GitPullRequestIcon size={14} />),
+ },
+ {
+ insert: "draft",
+ label: "draft",
+ hint: "PR still a draft",
+ icon: keyIcon(<PencilSimpleIcon size={14} />),
+ },
+ {
+ insert: "merged",
+ label: "merged",
+ hint: "PR merged",
+ icon: keyIcon(<GitMergeIcon size={14} />),
+ },
+ {
+ insert: "closed",
+ label: "closed",
+ hint: "PR closed without merging",
+ icon: keyIcon(<XIcon size={14} />),
+ },
+];
+
+const CI_SUGGESTED_VALUES = ["failing", "passing", "pending"];
+
+const CI_DOT_TONE: Record<string, string> = {
+ failing: DOT_TONE_VAR.red,
+ passing: DOT_TONE_VAR.green,
+ pending: DOT_TONE_VAR.yellow,
+};
+
+const STATUS_DOT_TONE: Record<string, string> = {
+ failed: DOT_TONE_VAR.red,
+ in_progress: DOT_TONE_VAR.blue,
+ completed: DOT_TONE_VAR.green,
+ queued: DOT_TONE_VAR.yellow,
+ cancelled: DOT_TONE_VAR.gray,
+ not_started: DOT_TONE_VAR.gray,
+};
+
+function statusDot(status: string): ReactNode {
+ return (
+ <span className="flex size-4 items-center justify-center">
+ <span
+ className="size-2 rounded-full"
+ style={{
+ backgroundColor: STATUS_DOT_TONE[status] ?? DOT_TONE_VAR.gray,
+ }}
+ />
+ </span>
+ );
+}
+
+function chunkAt(
+ value: string,
+ caret: number,
+): { start: number; end: number; text: string } {
+ let start = caret;
+ while (start > 0 && !/\s/.test(value[start - 1])) start--;
+ let end = caret;
+ while (end < value.length && !/\s/.test(value[end])) end++;
+ return { start, end, text: value.slice(start, end) };
+}
+
+export function FeedQueryMatchedLabel({
+ label,
+ typed,
+}: {
+ label: string;
+ typed: string;
+}) {
+ const matches =
+ typed !== "" && label.toLowerCase().startsWith(typed.toLowerCase());
+ if (!matches) return <span className="font-medium">{label}</span>;
+ return (
+ <span>
+ <span className="font-semibold text-foreground">
+ {label.slice(0, typed.length)}
+ </span>
+ <span className="font-medium">{label.slice(typed.length)}</span>
+ </span>
+ );
+}
+
+export function useFeedQuerySuggestions(
+ value: string,
+ caret: number,
+ options?: { includeType?: boolean },
+): { group: FeedQuerySuggestionGroup; context: FeedQueryEditContext } {
+ const includeType = options?.includeType ?? false;
+
+ const { members } = useOrgMembers();
+ const { channels } = useChannels();
+ const repositories = useMemo(
+ () => [...new Set(channels.flatMap((c) => c.repositories ?? []))].sort(),
+ [channels],
+ );
+
+ const chunk = useMemo(() => chunkAt(value, caret), [value, caret]);
+ const bare = chunk.text.replace(/^-/, "");
+ const colon = bare.indexOf(":");
+ const activeKey = colon === -1 ? null : bare.slice(0, colon).toLowerCase();
+ const rawValue = colon === -1 ? "" : bare.slice(colon + 1);
+ const valueNegated = /^not:/i.test(rawValue);
+ const activeValue = rawValue.replace(/^not:/i, "");
+ const typed = activeKey === null ? bare : activeValue;
+
+ const group = useMemo<FeedQuerySuggestionGroup>(() => {
+ const startsWith = (candidate: string) =>
+ candidate.toLowerCase().startsWith(activeValue.toLowerCase());
+ switch (activeKey) {
+ case null: {
+ const prefix = bare.toLowerCase();
+ const keys = includeType
+ ? [...KEY_SUGGESTIONS, ...PALETTE_KEY_SUGGESTIONS]
+ : KEY_SUGGESTIONS;
+ return {
+ heading: "Filters",
+ items: keys.filter((s) => s.label.startsWith(prefix)),
+ };
+ }
+ case "created-by":
+ case "author":
+ case "by":
+ case "commented-by":
+ case "commenter":
+ case "mentions":
+ case "mentioned":
+ case "involves": {
+ const me: FeedQuerySuggestion[] = startsWith("@me")
+ ? [
+ {
+ insert: "@me",
+ label: "@me",
+ hint: "you",
+ icon: keyIcon(<UserCircleIcon size={14} />),
+ },
+ ]
+ : [];
+ const matches = members
+ .filter(
+ (member) =>
+ startsWith(userDisplayName(member)) || startsWith(member.email),
+ )
+ .slice(0, 8);
+ return {
+ heading: "Teammates",
+ items: [
+ ...me,
+ ...matches.map((member) => {
+ const first = (member.first_name ?? "").toLowerCase();
+ const unique =
+ first !== "" &&
+ members.filter(
+ (m) => (m.first_name ?? "").toLowerCase() === first,
+ ).length === 1;
+ return {
+ insert: unique ? first : member.email,
+ label: userDisplayName(member),
+ hint: member.email,
+ icon: <UserAvatar user={member} size="xs" />,
+ };
+ }),
+ ],
+ };
+ }
+ case "space":
+ case "channel":
+ return {
+ heading: "Spaces",
+ items: channels
+ .filter((c) => startsWith(c.name))
+ .slice(0, 8)
+ .map((c) => ({
+ insert: c.name,
+ label: c.name,
+ icon: keyIcon(<HashIcon size={14} />),
+ })),
+ };
+ case "repo":
+ case "repository":
+ return {
+ heading: "Repositories",
+ items: repositories
+ .filter(startsWith)
+ .slice(0, 8)
+ .map((repo) => ({
+ insert: repo,
+ label: repo,
+ icon: keyIcon(<PackageIcon size={14} />),
+ })),
+ };
+ case "origin": {
+ const needle = activeValue.toLowerCase();
+ return {
+ heading: "Origin",
+ items: ORIGIN_VALUES.filter(({ value: v, fallbackHint }) => {
+ const hint = getOriginProductMeta(v)?.label ?? fallbackHint;
+ return (
+ v.startsWith(needle) || hint.toLowerCase().startsWith(needle)
+ );
+ })
+ .slice(0, 8)
+ .map(({ value: v, fallbackHint }) => {
+ const meta = getOriginProductMeta(v);
+ return {
+ insert: v,
+ label: v,
+ hint: meta?.label ?? fallbackHint,
+ icon: meta
+ ? keyIcon(<meta.Icon size={14} />)
+ : keyIcon(<AppWindowIcon size={14} />),
+ };
+ }),
+ };
+ }
+ case "status": {
+ const items: FeedQuerySuggestion[] = [];
+ for (const status of TASK_RUN_STATUSES) {
+ if (!startsWith(status)) continue;
+ items.push({
+ insert: status,
+ label: status,
+ icon: statusDot(status),
+ });
+ }
+ return { heading: "Run status", items };
+ }
+ case "is":
+ return {
+ heading: "Task state",
+ items: IS_VALUES.filter(startsWith).map((v) => ({
+ insert: v,
+ label: v,
+ icon:
+ v === "archived"
+ ? keyIcon(<ArchiveIcon size={14} />)
+ : v === "pinned"
+ ? keyIcon(<PushPinIcon size={14} />)
+ : statusDot(
+ v === "running"
+ ? "in_progress"
+ : v === "done"
+ ? "completed"
+ : "failed",
+ ),
+ })),
+ };
+ case "pr":
+ return {
+ heading: "Pull request",
+ items: PR_SUGGESTIONS.filter((s) => startsWith(s.label)),
+ };
+ case "ci":
+ return {
+ heading: "CI checks",
+ items: CI_SUGGESTED_VALUES.filter(startsWith).map((v) => ({
+ insert: v,
+ label: v,
+ icon: (
+ <span className="flex size-4 items-center justify-center">
+ <span
+ className="size-2 rounded-full"
+ style={{ backgroundColor: CI_DOT_TONE[v] }}
+ />
+ </span>
+ ),
+ })),
+ };
+ case "type": {
+ if (!includeType) return { heading: "", items: [] };
+ return {
+ heading: "Result type",
+ items: TYPE_VALUES.filter((s) => startsWith(s.label)),
+ };
+ }
+ default:
+ return { heading: "", items: [] };
+ }
+ }, [
+ activeKey,
+ activeValue,
+ bare,
+ members,
+ channels,
+ repositories,
+ includeType,
+ ]);
+
+ return { group, context: { chunk, activeKey, typed, valueNegated } };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useOrgMembers.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useOrgMembers.ts
index 360a06b62a84..79a2f02e0840 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useOrgMembers.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useOrgMembers.ts
@@ -13,9 +13,11 @@ export const orgMembersQueryKey = (orgId: string | null) =>
/** Members of the current organization, sorted by display name. */
export function useOrgMembers(options?: { enabled?: boolean }): {
members: UserBasic[];
+ error: Error | null;
isLoading: boolean;
isError: boolean;
isComplete: boolean;
+ refetch: () => void;
} {
const currentOrgId = useAuthStateValue((state) => state.currentOrgId);
const query = useAuthenticatedQuery(
@@ -36,8 +38,12 @@ export function useOrgMembers(options?: { enabled?: boolean }): {
);
return {
members,
+ error: query.error ?? null,
isLoading: query.isLoading,
isError: query.isError,
isComplete: query.data?.isComplete ?? false,
+ refetch: () => {
+ void query.refetch();
+ },
};
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.test.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.test.ts
new file mode 100644
index 000000000000..f5f586d96ff5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.test.ts
@@ -0,0 +1,81 @@
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import {
+ type TaskFeed,
+ useTaskFeedsStore,
+} from "@posthog/ui/features/canvas/stores/taskFeedsStore";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+let currentUserId = "user-1";
+
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => null,
+}));
+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
+ useCurrentUser: () => ({ data: { uuid: currentUserId } }),
+}));
+
+import { useProjectTaskFeed, useProjectTaskFeeds } from "./useProjectTaskFeeds";
+
+function feed(id: string, projectId: number, ownerId = "user-1"): TaskFeed {
+ return {
+ id,
+ projectId,
+ ownerId,
+ name: id,
+ query: "billing",
+ createdAt: "2026-08-01T00:00:00Z",
+ };
+}
+
+function selectProject(projectId: number | null): void {
+ useAuthStore.setState({
+ authState: { ...ANONYMOUS_AUTH_STATE, currentProjectId: projectId },
+ });
+}
+
+describe("useProjectTaskFeeds", () => {
+ beforeEach(() => {
+ currentUserId = "user-1";
+ useTaskFeedsStore.setState({
+ feeds: [
+ feed("in-project", 1),
+ feed("other-project", 2),
+ feed("other-user", 1, "user-2"),
+ ],
+ });
+ selectProject(1);
+ });
+
+ it("lists only the searches saved in the project you are in", () => {
+ const { result } = renderHook(() => useProjectTaskFeeds());
+
+ expect(result.current.map((f) => f.id)).toEqual(["in-project"]);
+ });
+
+ it("hides searches saved by another user in the same project", () => {
+ const { result, rerender } = renderHook(() => useProjectTaskFeeds());
+
+ currentUserId = "user-2";
+ rerender();
+
+ expect(result.current.map((f) => f.id)).toEqual(["other-user"]);
+ });
+
+ it("swaps the searches when the project changes", () => {
+ const { result } = renderHook(() => useProjectTaskFeeds());
+
+ act(() => selectProject(2));
+
+ expect(result.current.map((f) => f.id)).toEqual(["other-project"]);
+ });
+
+ it("hides a search saved in another project when opened by id", () => {
+ const { result } = renderHook(() => useProjectTaskFeed("other-project"));
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.ts
new file mode 100644
index 000000000000..dbc34d300e21
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useProjectTaskFeeds.ts
@@ -0,0 +1,30 @@
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
+import {
+ type TaskFeed,
+ useTaskFeedsStore,
+} from "@posthog/ui/features/canvas/stores/taskFeedsStore";
+import { useMemo } from "react";
+
+export function useProjectTaskFeeds(): TaskFeed[] {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const client = useOptionalAuthenticatedClient();
+ const { data: currentUser } = useCurrentUser({ client });
+ const ownerId = currentUser?.uuid;
+ const feeds = useTaskFeedsStore((state) => state.feeds);
+ return useMemo(
+ () =>
+ projectId === null || ownerId === undefined
+ ? []
+ : feeds.filter(
+ (feed) => feed.projectId === projectId && feed.ownerId === ownerId,
+ ),
+ [feeds, ownerId, projectId],
+ );
+}
+
+export function useProjectTaskFeed(feedId: string): TaskFeed | undefined {
+ const feeds = useProjectTaskFeeds();
+ return feeds.find((feed) => feed.id === feedId);
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.test.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.test.ts
new file mode 100644
index 000000000000..7309d251a199
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.test.ts
@@ -0,0 +1,89 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+let currentUserLoading = false;
+let membersComplete = true;
+let membersError: Error | null = null;
+let taskQueryError: Error | null = null;
+const refetch = vi.fn();
+const refetchMembers = vi.fn();
+
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => null,
+}));
+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
+ useCurrentUser: () => ({ data: null, isLoading: currentUserLoading }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
+ useOrgMembers: () => ({
+ members: [],
+ error: membersError,
+ isLoading: false,
+ isError: membersError !== null,
+ isComplete: membersComplete,
+ refetch: refetchMembers,
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
+ useChannels: () => ({ channels: [], isLoading: false }),
+}));
+vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ data: undefined,
+ error: taskQueryError,
+ isFetching: false,
+ isLoading: false,
+ refetch,
+ }),
+}));
+
+import { useFeedQueryPlan, useTaskFeedResults } from "./useTaskFeedResults";
+
+describe("task feed queries", () => {
+ beforeEach(() => {
+ currentUserLoading = false;
+ membersComplete = true;
+ membersError = null;
+ taskQueryError = null;
+ refetch.mockClear();
+ refetchMembers.mockClear();
+ });
+
+ it("waits for the current user before resolving an @me filter", () => {
+ currentUserLoading = true;
+
+ const { result } = renderHook(() => useFeedQueryPlan("created-by:@me"));
+
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.plan).toBeUndefined();
+ });
+
+ it("stops planning when member lookup fails", () => {
+ membersError = new Error("Network error");
+
+ const { result } = renderHook(() => useFeedQueryPlan("created-by:alex"));
+
+ expect(result.current.error).toBe(membersError);
+ expect(result.current.plan).toBeUndefined();
+ });
+
+ it("reports incomplete member lookup without rejecting the person filter", () => {
+ membersComplete = false;
+
+ const { result } = renderHook(() => useFeedQueryPlan("created-by:alex"));
+
+ expect(result.current.plan).toBeUndefined();
+ expect(result.current.errorMessage).toBe(
+ "Organization member lookup is incomplete. This search cannot verify every teammate.",
+ );
+ });
+
+ it("exposes task request failures instead of empty results", () => {
+ taskQueryError = new Error("Network error");
+
+ const { result } = renderHook(() => useTaskFeedResults("billing"));
+
+ expect(result.current.error).toBe(taskQueryError);
+ expect(result.current.tasks).toEqual([]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
new file mode 100644
index 000000000000..290e60056a21
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
@@ -0,0 +1,200 @@
+import {
+ type FeedQueryIssue,
+ type FeedQueryPlan,
+ type FeedQueryToken,
+ parseFeedQuery,
+ planFeedQuery,
+} from "@posthog/core/tasks/feedQuery";
+import type { Task } from "@posthog/shared/domain-types";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { useMemo } from "react";
+import {
+ SPACE_QUERY_GC_TIME_MS,
+ SPACE_QUERY_STALE_TIME_MS,
+} from "./spaceQueryPolicy";
+
+const TASK_FEED_POLL_INTERVAL_MS = 15_000;
+const TASK_FEED_MAX_PAGES = 5;
+
+function isPersonToken(token: FeedQueryToken): boolean {
+ return (
+ token.key === "created-by" ||
+ token.key === "commented-by" ||
+ token.key === "mentions" ||
+ token.key === "involves"
+ );
+}
+
+function isCurrentUserToken(token: FeedQueryToken): boolean {
+ const value = token.value.toLowerCase();
+ return value === "@me" || value === "me";
+}
+
+export function taskFeedResultsQueryKey(query: string) {
+ return ["task-feed-results", query] as const;
+}
+
+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 needsMembers = parsed.tokens.some(
+ (token) => isPersonToken(token) && !isCurrentUserToken(token),
+ );
+ const needsSpaces = parsed.tokens.some((t) => t.key === "space");
+ const needsCurrentUser = parsed.tokens.some(
+ (token) => isPersonToken(token) && isCurrentUserToken(token),
+ );
+
+ const client = useOptionalAuthenticatedClient();
+ const { data: me, isLoading: currentUserLoading } = useCurrentUser({
+ client,
+ });
+ const {
+ members,
+ error: membersError,
+ isComplete: membersComplete,
+ isLoading: membersLoading,
+ refetch: refetchMembers,
+ } = useOrgMembers({ enabled: needsMembers });
+ const { channels, isLoading: channelsLoading } = useChannels();
+
+ const memberLookupFailed = needsMembers && membersError !== null;
+ const memberLookupIncomplete = needsMembers && !membersComplete;
+ const waiting =
+ (needsMembers && membersLoading) ||
+ (needsCurrentUser && currentUserLoading) ||
+ (needsSpaces && channelsLoading);
+
+ const plan = useMemo(() => {
+ if (
+ normalized === "" ||
+ waiting ||
+ memberLookupFailed ||
+ memberLookupIncomplete
+ ) {
+ return undefined;
+ }
+ return planFeedQuery(parsed, {
+ members,
+ spaces: channels.map((c) => ({ id: c.id, name: c.name })),
+ me: me ?? null,
+ });
+ }, [
+ normalized,
+ waiting,
+ memberLookupFailed,
+ memberLookupIncomplete,
+ parsed,
+ members,
+ channels,
+ me,
+ ]);
+
+ return {
+ canRetry: memberLookupFailed,
+ error: memberLookupFailed
+ ? membersError
+ : memberLookupIncomplete
+ ? new Error("Organization member lookup is incomplete")
+ : null,
+ errorMessage: memberLookupFailed
+ ? "Couldn't load organization members. Try again."
+ : memberLookupIncomplete
+ ? "Organization member lookup is incomplete. This search cannot verify every teammate."
+ : null,
+ isLoading: normalized !== "" && waiting,
+ plan,
+ refetch: refetchMembers,
+ };
+}
+
+export function useTaskFeedResults(query: string | undefined): {
+ canRetry: boolean;
+ error: Error | null;
+ errorMessage: string | null;
+ isComplete: boolean;
+ isFetching: boolean;
+ isLoading: boolean;
+ issues: FeedQueryIssue[];
+ refetch: () => void;
+ tasks: Task[];
+} {
+ const normalized = query?.trim() ?? "";
+ const {
+ canRetry: planCanRetry,
+ error: planError,
+ errorMessage: planErrorMessage,
+ plan,
+ isLoading: planLoading,
+ refetch: refetchPlan,
+ } = useFeedQueryPlan(normalized);
+
+ const requests = plan?.requests ?? [];
+ const result = useAuthenticatedQuery<{ tasks: Task[]; isComplete: boolean }>(
+ taskFeedResultsQueryKey(normalized),
+ async (client) => {
+ const pages = await Promise.all(
+ requests.map((request) =>
+ client.getTasksWithStatus(request, {
+ maxPages: TASK_FEED_MAX_PAGES,
+ }),
+ ),
+ );
+ const byId = new Map<string, Task>();
+ for (const page of pages) {
+ for (const task of page.tasks) {
+ byId.set(task.id, task);
+ }
+ }
+ return {
+ tasks: [...byId.values()].sort((a, b) =>
+ b.created_at.localeCompare(a.created_at),
+ ),
+ isComplete: pages.every((page) => page.isComplete),
+ };
+ },
+ {
+ enabled: normalized !== "" && !!plan,
+ gcTime: SPACE_QUERY_GC_TIME_MS,
+ refetchInterval: TASK_FEED_POLL_INTERVAL_MS,
+ staleTime: SPACE_QUERY_STALE_TIME_MS,
+ },
+ );
+
+ const tasks = useMemo(() => {
+ const fetched = result.data?.tasks ?? [];
+ if (!plan) return [];
+ return fetched.filter((task) => plan.matches(task));
+ }, [result.data, plan]);
+
+ return {
+ canRetry: planError ? planCanRetry : result.error !== null,
+ error: planError ?? result.error ?? null,
+ errorMessage:
+ planErrorMessage ??
+ (result.error ? "Couldn't load matching tasks. Try again." : null),
+ isComplete: result.data?.isComplete ?? false,
+ isFetching: result.isFetching,
+ isLoading: planLoading || result.isLoading,
+ issues: plan?.issues ?? [],
+ refetch: () => {
+ if (planError) {
+ refetchPlan();
+ return;
+ }
+ void result.refetch();
+ },
+ tasks,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.test.ts b/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.test.ts
new file mode 100644
index 000000000000..164685a8dbf5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { useTaskFeedsStore } from "./taskFeedsStore";
+
+describe("taskFeedsStore", () => {
+ beforeEach(() => {
+ useTaskFeedsStore.setState({ feeds: [] });
+ });
+
+ it("stores a new feed with trimmed name and query", () => {
+ const feed = useTaskFeedsStore.getState().addFeed({
+ name: " Billing work ",
+ query: " billing ",
+ projectId: 1,
+ ownerId: "user-1",
+ });
+
+ expect(feed.name).toBe("Billing work");
+ expect(feed.query).toBe("billing");
+ expect(useTaskFeedsStore.getState().feeds).toEqual([feed]);
+ });
+
+ it("updates only the fields the patch names", () => {
+ const feed = useTaskFeedsStore.getState().addFeed({
+ name: "Billing work",
+ query: "billing",
+ projectId: 1,
+ ownerId: "user-1",
+ });
+
+ useTaskFeedsStore.getState().updateFeed(feed.id, { query: " invoices " });
+
+ const updated = useTaskFeedsStore.getState().feeds[0];
+ expect(updated.name).toBe("Billing work");
+ expect(updated.query).toBe("invoices");
+ expect(updated.id).toBe(feed.id);
+ });
+
+ it("removes only the named feed", () => {
+ const keep = useTaskFeedsStore.getState().addFeed({
+ name: "Keep",
+ query: "keep",
+ projectId: 1,
+ ownerId: "user-1",
+ });
+ const drop = useTaskFeedsStore.getState().addFeed({
+ name: "Drop",
+ query: "drop",
+ projectId: 1,
+ ownerId: "user-1",
+ });
+
+ useTaskFeedsStore.getState().removeFeed(drop.id);
+
+ expect(useTaskFeedsStore.getState().feeds).toEqual([keep]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.ts
new file mode 100644
index 000000000000..a2eadaa36b7e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/stores/taskFeedsStore.ts
@@ -0,0 +1,69 @@
+import { electronStorage } from "@posthog/ui/shell/rendererStorage";
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+export interface TaskFeed {
+ id: string;
+ projectId: number;
+ ownerId: string;
+ name: string;
+ query: string;
+ createdAt: string;
+}
+
+interface TaskFeedsState {
+ feeds: TaskFeed[];
+ addFeed: (input: {
+ name: string;
+ query: string;
+ projectId: number;
+ ownerId: string;
+ }) => TaskFeed;
+ updateFeed: (id: string, patch: { name?: string; query?: string }) => void;
+ removeFeed: (id: string) => void;
+}
+
+// Feeds are personal and project-scoped, so callers must use `useProjectTaskFeeds`.
+export const useTaskFeedsStore = create<TaskFeedsState>()(
+ persist(
+ (set) => ({
+ feeds: [],
+ addFeed: ({ name, query, projectId, ownerId }) => {
+ const feed: TaskFeed = {
+ id: crypto.randomUUID(),
+ projectId,
+ ownerId,
+ name: name.trim(),
+ query: query.trim(),
+ createdAt: new Date().toISOString(),
+ };
+ set((state) => ({ feeds: [...state.feeds, feed] }));
+ return feed;
+ },
+ updateFeed: (id, patch) =>
+ set((state) => ({
+ feeds: state.feeds.map((feed) =>
+ feed.id === id
+ ? {
+ ...feed,
+ ...(patch.name !== undefined
+ ? { name: patch.name.trim() }
+ : {}),
+ ...(patch.query !== undefined
+ ? { query: patch.query.trim() }
+ : {}),
+ }
+ : feed,
+ ),
+ })),
+ removeFeed: (id) =>
+ set((state) => ({
+ feeds: state.feeds.filter((feed) => feed.id !== id),
+ })),
+ }),
+ {
+ name: "task-feeds-storage",
+ storage: electronStorage,
+ },
+ ),
+);
diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.ts
index 824f1018c00e..299392834fc3 100644
--- a/products/desktop/packages/ui/src/router/navigationBridge.ts
+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts
@@ -48,6 +48,13 @@ export function navigateToHome(): void {
void getRouterOrNull()?.navigate({ to: "/website/home" });
}
+export function navigateToFeed(feedId: string): void {
+ void getRouterOrNull()?.navigate({
+ to: "/website/feeds/$feedId",
+ params: { feedId },
+ });
+}
+
export function navigateToChannel(channelId: string): void {
void getRouterOrNull()?.navigate({
to: "/website/$channelId",
diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.ts
index c98153ebe31d..b707c82ec852 100644
--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts
+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts
@@ -34,6 +34,7 @@ import { Route as WebsiteChannelIdIndexRouteImport } from './routes/website/$cha
import { Route as CodeLoopsIndexRouteImport } from './routes/code/loops/index'
import { Route as CodeInboxIndexRouteImport } from './routes/code/inbox/index'
import { Route as CodeAgentsIndexRouteImport } from './routes/code/agents/index'
+import { Route as WebsiteFeedsFeedIdRouteImport } from './routes/website/feeds/$feedId'
import { Route as WebsiteChannelIdNewRouteImport } from './routes/website/$channelId/new'
import { Route as WebsiteChannelIdLoopsRouteImport } from './routes/website/$channelId/loops'
import { Route as WebsiteChannelIdHistoryRouteImport } from './routes/website/$channelId/history'
@@ -206,6 +207,11 @@ const CodeAgentsIndexRoute = CodeAgentsIndexRouteImport.update({
path: '/',
getParentRoute: () => CodeAgentsRoute,
} as any)
+const WebsiteFeedsFeedIdRoute = WebsiteFeedsFeedIdRouteImport.update({
+ id: '/feeds/$feedId',
+ path: '/feeds/$feedId',
+ getParentRoute: () => WebsiteRoute,
+} as any)
const WebsiteChannelIdNewRoute = WebsiteChannelIdNewRouteImport.update({
id: '/$channelId/new',
path: '/$channelId/new',
@@ -497,6 +503,7 @@ export interface FileRoutesByFullPath {
'/website/$channelId/history': typeof WebsiteChannelIdHistoryRoute
'/website/$channelId/loops': typeof WebsiteChannelIdLoopsRoute
'/website/$channelId/new': typeof WebsiteChannelIdNewRoute
+ '/website/feeds/$feedId': typeof WebsiteFeedsFeedIdRoute
'/code/agents/': typeof CodeAgentsIndexRoute
'/code/inbox/': typeof CodeInboxIndexRoute
'/code/loops/': typeof CodeLoopsIndexRoute
@@ -560,6 +567,7 @@ export interface FileRoutesByTo {
'/website/$channelId/history': typeof WebsiteChannelIdHistoryRoute
'/website/$channelId/loops': typeof WebsiteChannelIdLoopsRoute
'/website/$channelId/new': typeof WebsiteChannelIdNewRoute
+ '/website/feeds/$feedId': typeof WebsiteFeedsFeedIdRoute
'/code/agents': typeof CodeAgentsIndexRoute
'/code/inbox': typeof CodeInboxIndexRoute
'/code/loops': typeof CodeLoopsIndexRoute
@@ -632,6 +640,7 @@ export interface FileRoutesById {
'/website/$channelId/history': typeof WebsiteChannelIdHistoryRoute
'/website/$channelId/loops': typeof WebsiteChannelIdLoopsRoute
'/website/$channelId/new': typeof WebsiteChannelIdNewRoute
+ '/website/feeds/$feedId': typeof WebsiteFeedsFeedIdRoute
'/code/agents/': typeof CodeAgentsIndexRoute
'/code/inbox/': typeof CodeInboxIndexRoute
'/code/loops/': typeof CodeLoopsIndexRoute
@@ -707,6 +716,7 @@ export interface FileRouteTypes {
| '/website/$channelId/history'
| '/website/$channelId/loops'
| '/website/$channelId/new'
+ | '/website/feeds/$feedId'
| '/code/agents/'
| '/code/inbox/'
| '/code/loops/'
@@ -770,6 +780,7 @@ export interface FileRouteTypes {
| '/website/$channelId/history'
| '/website/$channelId/loops'
| '/website/$channelId/new'
+ | '/website/feeds/$feedId'
| '/code/agents'
| '/code/inbox'
| '/code/loops'
@@ -841,6 +852,7 @@ export interface FileRouteTypes {
| '/website/$channelId/history'
| '/website/$channelId/loops'
| '/website/$channelId/new'
+ | '/website/feeds/$feedId'
| '/code/agents/'
| '/code/inbox/'
| '/code/loops/'
@@ -1076,6 +1088,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof CodeAgentsIndexRouteImport
parentRoute: typeof CodeAgentsRoute
}
+ '/website/feeds/$feedId': {
+ id: '/website/feeds/$feedId'
+ path: '/feeds/$feedId'
+ fullPath: '/website/feeds/$feedId'
+ preLoaderRoute: typeof WebsiteFeedsFeedIdRouteImport
+ parentRoute: typeof WebsiteRoute
+ }
'/website/$channelId/new': {
id: '/website/$channelId/new'
path: '/$channelId/new'
@@ -1415,6 +1434,7 @@ interface WebsiteRouteChildren {
WebsiteChannelIdHistoryRoute: typeof WebsiteChannelIdHistoryRoute
WebsiteChannelIdLoopsRoute: typeof WebsiteChannelIdLoopsRoute
WebsiteChannelIdNewRoute: typeof WebsiteChannelIdNewRoute
+ WebsiteFeedsFeedIdRoute: typeof WebsiteFeedsFeedIdRoute
WebsiteChannelIdIndexRoute: typeof WebsiteChannelIdIndexRoute
WebsiteChannelIdDashboardsDashboardIdRoute: typeof WebsiteChannelIdDashboardsDashboardIdRoute
WebsiteChannelIdTasksTaskIdRoute: typeof WebsiteChannelIdTasksTaskIdRoute
@@ -1434,6 +1454,7 @@ const WebsiteRouteChildren: WebsiteRouteChildren = {
WebsiteChannelIdHistoryRoute: WebsiteChannelIdHistoryRoute,
WebsiteChannelIdLoopsRoute: WebsiteChannelIdLoopsRoute,
WebsiteChannelIdNewRoute: WebsiteChannelIdNewRoute,
+ WebsiteFeedsFeedIdRoute: WebsiteFeedsFeedIdRoute,
WebsiteChannelIdIndexRoute: WebsiteChannelIdIndexRoute,
WebsiteChannelIdDashboardsDashboardIdRoute:
WebsiteChannelIdDashboardsDashboardIdRoute,
diff --git a/products/desktop/packages/ui/src/router/routes/website/feeds/$feedId.tsx b/products/desktop/packages/ui/src/router/routes/website/feeds/$feedId.tsx
new file mode 100644
index 000000000000..b724f9e67ed1
--- /dev/null
+++ b/products/desktop/packages/ui/src/router/routes/website/feeds/$feedId.tsx
@@ -0,0 +1,16 @@
+import { TaskFeedHome } from "@posthog/ui/features/canvas/components/TaskFeedHome";
+import {
+ ChannelSkeleton,
+ withRouteSkeleton,
+} from "@posthog/ui/router/routeSkeletons";
+import { createFileRoute } from "@tanstack/react-router";
+
+export const Route = createFileRoute("/website/feeds/$feedId")({
+ component: TaskFeedRoute,
+ ...withRouteSkeleton(ChannelSkeleton),
+});
+
+function TaskFeedRoute() {
+ const { feedId } = Route.useParams();
+ return <TaskFeedHome feedId={feedId} />;
+}