:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): search pull requests and artifacts in Cmd+K (#79676)
Alessandro Pogliaghiade470427136
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 24bfcb7b8f3c..fa84258a0f8b 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -318,6 +318,7 @@ rules:|TaskAutomation|TaskPresence|TaskRun+ |TaskSearchDocument|TaskSession|TaskThreadMessage|TaskThreadMessageMentiondiff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex 5baac068442e..ffe7624d00f6 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -17,3 +17,4 @@posthog.1264_delete_revenue_analytics_user_product_listproduct_analytics.0004_delete_revenue_analytics_insightstasks.0079_backfill_task_repositories+tasks.0088_backfill_task_search_documentsdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 8fc7a03f0e0e..5faa69e16670 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -99,6 +99,7 @@ post_delete:products.signals.backend.receivers.tombstone_report_embedding_on_harpost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changepost_delete:products.surveys.backend.models.survey_changedpost_delete:products.tasks.backend.models.delete_task_session_object+post_delete:products.tasks.backend.search_index.channel_deletedpost_delete:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_deletedpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_oauthpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_secret_key@@ -204,6 +205,10 @@ post_save:products.slack_app.backend.signals.onboard_slack_inbox_on_installpost_save:products.surveys.backend.models.survey_changedpost_save:products.tasks.backend.models.project_task_created_activitypost_save:products.tasks.backend.models.track_task_run_completion+post_save:products.tasks.backend.search_index.channel_saved+post_save:products.tasks.backend.search_index.task_artifact_saved+post_save:products.tasks.backend.search_index.task_run_saved+post_save:products.tasks.backend.search_index.task_savedpost_save:products.workflows.backend.models.hog_flow.hog_flow.action_saved_for_hog_flowspost_save:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_savedpost_save:products.workflows.backend.models.hog_flow.hog_flow.team_saved_for_hog_flowsdiff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex f683e6b87fc9..80c093ca5eb8 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -208,6 +208,17 @@ export interface TaskListOptions {limit?: number;}+export interface TaskSearchResult {+ id: string;+ kind: "task" | "pull_request" | "artifact" | "channel";+ title: string;+ subtitle: string;+ task_id: string | null;+ task_run_id: string | null;+ channel_id: string | null;+ metadata: Record<string, unknown>;+}+export interface TaskSessionStorageAccess {id: string;download_url: string | null;@@ -2186,6 +2197,19 @@ export class PostHogAPIClient {return (await this.getTasksPage(options)).tasks;}+ async searchTasks(query: string, limit = 20): Promise<TaskSearchResult[]> {+ const teamId = await this.getTeamId();+ const path = `/api/projects/${teamId}/tasks/search/`;+ const url = new URL(`${this.api.baseUrl}${path}`);+ url.searchParams.set("q", query);+ url.searchParams.set("limit", String(limit));+ const response = await this.api.fetcher.fetch({ method: "get", url, path });+ if (!response.ok) {+ throw new Error(`Failed to search tasks: ${response.statusText}`);+ }+ return (await response.json()) as TaskSearchResult[];+ }+/*** The same list with the total behind it, for surfaces that ask for a short* page and still have to say how much they are not showing.diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex c5a720c032eb..387705063cd8 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -53,6 +53,8 @@ export type CommandMenuAction =| "go-back"| "go-forward"| "open-task"+ | "open-task-from-pull-request"+ | "open-artifact"| "open-channel"| "open-command-center"| "open-inbox"diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex be81fcd70ad8..f95b197ddc7a 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -93,6 +93,17 @@ export interface Task {latest_run?: TaskRun;}+export interface TaskSearchResult {+ id: string;+ kind: "task" | "pull_request" | "artifact" | "channel";+ title: string;+ subtitle: string;+ task_id: string | null;+ task_run_id: string | null;+ channel_id: string | null;+ metadata: Record<string, unknown>;+}+/*** A backend task channel — the single channel identity: it owns the task feed,* threads, instructions (CONTEXT.md) and filed canvases. `personal` is thediff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.tsxindex 1e90bd9593b0..3b72e0f7ef86 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx@@ -45,7 +45,14 @@ import {formatHotkeyParts,SHORTCUTS,} from "@posthog/ui/features/command/keyboard-shortcuts";+import { taskSearchDelay } from "@posthog/ui/features/command/taskSearchQuery";import { useFileSearchContext } from "@posthog/ui/features/command/useFileSearchContext";+import {+ type Command,+ type CommandSection,+ useSearchSections,+} from "@posthog/ui/features/command/useSearchSections";+import { useTaskSearch } from "@posthog/ui/features/command/useTaskSearch";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useFolders } from "@posthog/ui/features/folders/useFolders";import { useProvisioningStore } from "@posthog/ui/features/provisioning/store";@@ -93,23 +100,6 @@ interface CommandMenuProps {onOpenChange: (open: boolean) => void;}-type Command = {- id: string;- label: string;- /** Muted trailing detail shown after a middot, e.g. a task's channel. */- detail?: string;- keywords?: string;- icon: React.ReactNode;- action: CommandMenuAction;- /** Channel in scope for the bluebird open-channel / open-task actions. */- channelId?: string;- /** Hotkey string (e.g. "mod+b") shown right-aligned when present. */- shortcut?: string;- onRun: () => void;-};--type CommandSection = { label: string; items: Command[] };-/*** Task icon for the command palette. Renders the same shared `TaskIcon` as* the sidebar — cloud run status, PR/branch status, etc. — deriving its@@ -170,6 +160,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {(state) => state.activeTasks,);const [query, setQuery] = useState("");+ const [remoteQuery, setRemoteQuery] = useState("");const { repoPath } = useFileSearchContext();const canSearchFiles = !!repoPath;const openFilePicker = useFileSearchStore((state) => state.openPicker);@@ -177,6 +168,19 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {() => window.matchMedia("(prefers-color-scheme: dark)").matches,);+ useEffect(() => {+ const trimmed = query.trim();+ const delay = taskSearchDelay(trimmed);+ if (!open || delay === null) {+ setRemoteQuery("");+ return;+ }+ const timer = window.setTimeout(() => setRemoteQuery(trimmed), delay);+ return () => window.clearTimeout(timer);+ }, [open, query]);++ const { data: searchResults = [] } = useTaskSearch(remoteQuery, open);+useEffect(() => {const mq = window.matchMedia("(prefers-color-scheme: dark)");const onChange = (e: MediaQueryListEvent) =>@@ -560,10 +564,25 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {];}, [channels, closeSettingsDialog, spacesLayout]);+ const searchSections = useSearchSections({+ remoteQuery,+ searchResults,+ tasks,+ taskSections,+ channels,+ bluebirdEnabled,+ spacesLayout,+ });+// Commands, channels, and tasks share a single filterable list.const sections = useMemo(- () => [...commandSections, ...channelSections, ...taskSections],- [commandSections, channelSections, taskSections],+ () => [+ ...searchSections,+ ...commandSections,+ ...channelSections,+ ...taskSections,+ ],+ [searchSections, commandSections, channelSections, taskSections],);const allCommands = useMemo(@@ -649,7 +668,8 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {</span>{cmd.detail && (<span className="shrink-0 text-gray-9">- · #{cmd.detail}+ · {cmd.detailPrefix ?? "#"}+ {cmd.detail}</span>)}{cmd.shortcut && (diff --git a/products/desktop/packages/ui/src/features/command/taskSearchQuery.test.ts b/products/desktop/packages/ui/src/features/command/taskSearchQuery.test.tsnew file mode 100644index 000000000000..f2a443d66ace--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/taskSearchQuery.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";+import { taskSearchDelay } from "./taskSearchQuery";++describe("taskSearchDelay", () => {+ it.each(["https://github.com/posthog/posthog/pull/123"])(+ "searches structured query %s immediately",+ (query) => expect(taskSearchDelay(query)).toBe(0),+ );++ it.each(["7", "#123"])("debounces numeric query %s", (query) =>+ expect(taskSearchDelay(query)).toBe(120),+ );++ it("debounces names", () => {+ expect(taskSearchDelay("release report")).toBe(120);+ });++ it.each(["", " ", "a", "#"])("does not remotely search %j", (query) => {+ expect(taskSearchDelay(query)).toBeNull();+ });+});diff --git a/products/desktop/packages/ui/src/features/command/taskSearchQuery.ts b/products/desktop/packages/ui/src/features/command/taskSearchQuery.tsnew file mode 100644index 000000000000..391e530d6fe1--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/taskSearchQuery.ts@@ -0,0 +1,5 @@+export function taskSearchDelay(query: string): number | null {+ const trimmed = query.trim();+ if (!/^#?\d+$/.test(trimmed) && trimmed.length < 2) return null;+ return /^https?:\/\//i.test(trimmed) ? 0 : 120;+}diff --git a/products/desktop/packages/ui/src/features/command/useSearchSections.tsx b/products/desktop/packages/ui/src/features/command/useSearchSections.tsxnew file mode 100644index 000000000000..5219e6be2894--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/useSearchSections.tsx@@ -0,0 +1,151 @@+import { GitDiffIcon } from "@phosphor-icons/react";+import type { CommandMenuAction } from "@posthog/shared/analytics-events";+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";+import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";+import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import {+ navigateToChannel,+ navigateToChannelArtifacts,+ navigateToChannelTask,+ navigateToTaskDetail,+} from "@posthog/ui/router/navigationBridge";+import { openTask } from "@posthog/ui/router/useOpenTask";+import { FileTextIcon } from "@radix-ui/react-icons";+import { type ReactNode, useMemo } from "react";++export type Command = {+ id: string;+ label: string;+ /** Muted trailing detail shown after a middot, e.g. a task's channel. */+ detail?: string;+ detailPrefix?: string;+ keywords?: string;+ icon: ReactNode;+ action: CommandMenuAction;+ /** Channel in scope for the bluebird open-channel / open-task actions. */+ channelId?: string;+ /** Hotkey string (e.g. "mod+b") shown right-aligned when present. */+ shortcut?: string;+ onRun: () => void;+};++export type CommandSection = { label: string; items: Command[] };++type SearchChannel = { id: string; name: string };++type UseSearchSectionsOptions = {+ remoteQuery: string;+ searchResults: TaskSearchResult[];+ tasks: Task[];+ taskSections: CommandSection[];+ channels: SearchChannel[];+ bluebirdEnabled: boolean;+ spacesLayout: boolean;+};++/** Convert remote matches into commands that open the match's owning task or space. */+export function useSearchSections({+ remoteQuery,+ searchResults,+ tasks,+ taskSections,+ channels,+ bluebirdEnabled,+ spacesLayout,+}: UseSearchSectionsOptions): CommandSection[] {+ return useMemo(() => {+ if (!remoteQuery || searchResults.length === 0) return [];++ const tasksById = new Map(tasks.map((task) => [task.id, task]));+ const visibleTaskIds = new Set(+ taskSections.flatMap((section) =>+ section.items.map((item) => item.id.replace(/^task-/, "")),+ ),+ );+ const channelIds = new Set(channels.map((channel) => channel.id));+ const items: Command[] = [];++ for (const result of searchResults) {+ if (result.kind === "channel" && !bluebirdEnabled) continue;+ if (+ (result.kind === "task" &&+ result.task_id &&+ visibleTaskIds.has(result.task_id)) ||+ (result.kind === "channel" &&+ result.channel_id &&+ channelIds.has(result.channel_id))+ ) {+ continue;+ }++ const task = result.task_id ? tasksById.get(result.task_id) : undefined;+ items.push({+ id: `search-${result.id}`,+ label: result.title,+ detail: result.subtitle || undefined,+ detailPrefix: "",+ keywords: `${remoteQuery} ${result.subtitle} ${Object.values(result.metadata).join(" ")}`,+ icon:+ result.kind === "pull_request" ? (+ <GitDiffIcon size={12} className="text-gray-11" />+ ) : result.kind === "channel" ? (+ channelGlyph(result.title, {+ size: 12,+ space: spacesLayout,+ className: "text-muted-foreground",+ })+ ) : (+ <FileTextIcon className="h-3 w-3 text-gray-11" />+ ),+ action: (result.kind === "channel"+ ? "open-channel"+ : result.kind === "pull_request"+ ? "open-task-from-pull-request"+ : result.kind === "artifact"+ ? "open-artifact"+ : "open-task") as CommandMenuAction,+ channelId: bluebirdEnabled+ ? (result.channel_id ?? undefined)+ : undefined,+ onRun: () => {+ closeSettings();+ if (+ bluebirdEnabled &&+ result.kind === "channel" &&+ result.channel_id+ ) {+ navigateToChannel(result.channel_id);+ } else if (+ bluebirdEnabled &&+ result.kind === "artifact" &&+ result.channel_id &&+ result.metadata.living === true+ ) {+ navigateToChannelArtifacts(result.channel_id);+ } else if (task) {+ // PR matches intentionally open their containing task. Cmd+K is a+ // navigator for Desktop context, not an external-link launcher.+ void openTask(+ task,+ result.channel_id ? { channelId: result.channel_id } : undefined,+ );+ } else if (bluebirdEnabled && result.task_id && result.channel_id) {+ navigateToChannelTask(result.channel_id, result.task_id);+ } else if (result.task_id) {+ navigateToTaskDetail(result.task_id);+ }+ },+ });+ }++ return items.length > 0 ? [{ label: "Search results", items }] : [];+ }, [+ remoteQuery,+ searchResults,+ tasks,+ taskSections,+ channels,+ bluebirdEnabled,+ spacesLayout,+ ]);+}diff --git a/products/desktop/packages/ui/src/features/command/useTaskSearch.ts b/products/desktop/packages/ui/src/features/command/useTaskSearch.tsnew file mode 100644index 000000000000..fbef81efc4a6--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/useTaskSearch.ts@@ -0,0 +1,14 @@+import type { TaskSearchResult } from "@posthog/shared/domain-types";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";++export function useTaskSearch(query: string, enabled: boolean) {+ return useAuthenticatedQuery<TaskSearchResult[]>(+ ["task-global-search", query],+ (client) => client.searchTasks(query),+ {+ enabled: enabled && query.length > 0,+ staleTime: 30_000,+ retry: false,+ },+ );+}diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex 1992d0fd8a03..4c8bb1be7e2e 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -51,6 +51,13 @@ export function navigateToChannel(channelId: string): void {});}+export function navigateToChannelArtifacts(channelId: string): void {+ void getRouterOrNull()?.navigate({+ to: "/website/$channelId/artifacts",+ params: { channelId },+ });+}+export function navigateToChannelTask(channelId: string, taskId: string): void {void getRouterOrNull()?.navigate({to: "/website/$channelId/tasks/$taskId",diff --git a/products/tasks/backend/apps.py b/products/tasks/backend/apps.pyindex a57e25eab2fd..29dfcfd68fd8 100644--- a/products/tasks/backend/apps.py+++ b/products/tasks/backend/apps.py@@ -10,4 +10,4 @@ class TasksConfig(AppConfig):# Signal receivers live in their own import-light modules so every# process type (celery, temporal, migrate) wires them without pulling# the viewset import graph into django.setup().- from products.tasks.backend import activity_logging, team_deletion # noqa: F401, PLC0415+ from products.tasks.backend import activity_logging, search_index, team_deletion # noqa: F401, PLC0415diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 40ec1cb68558..5c9b17d433bf 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -29,7 +29,22 @@ from uuid import UUID, uuid4from django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import IntegrityError, transaction-from django.db.models import CharField, Count, Exists, F, Func, Min, OuterRef, Q, QuerySet, Subquery+from django.db.models import (+ Case,+ CharField,+ Count,+ Exists,+ F,+ Func,+ IntegerField,+ Min,+ OuterRef,+ Q,+ QuerySet,+ Subquery,+ Value,+ When,+)from django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone as django_timezonefrom django.utils.http import content_disposition_header@@ -82,6 +97,7 @@ from products.tasks.backend.models import (TaskCommentActivity,TaskPin,TaskRun,+ TaskSearchDocument,TaskSession,TaskThreadMessage,TaskThreadMessageMention,@@ -4377,6 +4393,65 @@ def list_tasks(team_id: int, user_id: int | None, *, filters: dict) -> list[contreturn _tasks_to_dtos(_list_tasks_queryset(team_id, user_id, filters=filters), team_id)+def search_tasks(+ team_id: int,+ user_id: int | None,+ query: str,+ *,+ limit: int = 20,+ bypass_visibility: bool = False,+) -> list[dict]:+ normalized = query.strip().lower()+ if not normalized:+ return []+ visible_task_ids = (+ _visible_task_qs(team_id, user_id, bypass_visibility=bypass_visibility).filter(internal=False).values("id")+ )+ visibility = Q(task_id__in=Subquery(visible_task_ids)) | (+ Q(task__isnull=True, channel__deleted=False) & Channel.visible_to_q(user_id, relation="channel")+ )+ identifiers = [normalized]+ pr_match = re.match(r"^https?://github\.com/([^/]+/[^/]+)/pull/(\d+)(?:[/?#].*)?$", normalized)+ if pr_match:+ repository, number = pr_match.groups()+ identifiers.extend(+ [f"https://github.com/{repository}/pull/{number}", f"{repository}#{number}", f"#{number}", number]+ )+ exact_match = Q()+ for identifier in identifiers:+ exact_match |= Q(exact_identifiers__contains=[identifier])+ matches = exact_match+ if len(normalized) >= 3:+ matches |= Q(search_text__icontains=normalized)+ documents = (+ TaskSearchDocument.objects.for_team(team_id)+ .filter(visibility)+ .filter(matches)+ .annotate(+ _rank=Case(+ When(exact_match, then=Value(0)),+ When(search_text__startswith=normalized, then=Value(1)),+ default=Value(2),+ output_field=IntegerField(),+ )+ )+ .order_by("_rank", "-updated_at")[: min(limit, 50)]+ )+ return [+ {+ "id": str(document.id),+ "kind": document.kind,+ "title": document.title,+ "subtitle": document.subtitle,+ "task_id": str(document.task_id) if document.task_id else None,+ "task_run_id": str(document.task_run_id) if document.task_run_id else None,+ "channel_id": str(document.channel_id) if document.channel_id else None,+ "metadata": document.metadata,+ }+ for document in documents+ ]++def inaccessible_repositories_via_integration(team_id: int, integration_id: int, repositories: list[str]) -> list[str]:return _inaccessible_repositories_via_integration(team_id, integration_id, repositories)@@ -4684,7 +4759,12 @@ def set_task_title(task_id: str | UUID, team_id: int, title: str) -> bool:``title_manually_set`` untouched (this isn't a user edit) and clamps to the column length. Returnswhether a row was updated."""- return bool(Task.objects.filter(id=task_id, team_id=team_id).update(title=title[:255]))+ task = Task.objects.filter(id=task_id, team_id=team_id).first()+ if task is None:+ return False+ task.title = title[:255]+ task.save(update_fields=["title"])+ return Truedef update_task(diff --git a/products/tasks/backend/management/commands/rebuild_task_search_index.py b/products/tasks/backend/management/commands/rebuild_task_search_index.pynew file mode 100644index 000000000000..3c769884dc2a--- /dev/null+++ b/products/tasks/backend/management/commands/rebuild_task_search_index.py@@ -0,0 +1,29 @@+from django.core.management.base import BaseCommand, CommandError++from posthog.models.scoping.manager import resolve_effective_team_id++from products.tasks.backend.models import Channel, Task+from products.tasks.backend.search_index import rebuild_team_search_index+++class Command(BaseCommand):+ help = "Rebuild the Desktop task/PR/artifact/space search projection for one project"++ def add_arguments(self, parser):+ parser.add_argument("team_id", type=int, nargs="?")+ parser.add_argument("--all", action="store_true", dest="all_teams")++ def handle(self, *args, **options):+ team_id = options["team_id"]+ if options["all_teams"] == (team_id is not None):+ raise CommandError("Pass exactly one of team_id or --all")+ if options["all_teams"]:+ source_team_ids = set(Task.objects.values_list("team_id", flat=True).distinct())+ source_team_ids.update(Channel.objects.values_list("team_id", flat=True).distinct())+ team_ids = sorted({resolve_effective_team_id(source_team_id) for source_team_id in source_team_ids})+ else:+ team_ids = [team_id]+ for current_team_id in team_ids:+ rebuild_team_search_index(current_team_id)+ self.stdout.write(f"Rebuilt task search index for team {current_team_id}")+ self.stdout.write(self.style.SUCCESS("Task search index rebuild complete"))diff --git a/products/tasks/backend/migrations/0087_tasksearchdocument.py b/products/tasks/backend/migrations/0087_tasksearchdocument.pynew file mode 100644index 000000000000..bffd3a76db94--- /dev/null+++ b/products/tasks/backend/migrations/0087_tasksearchdocument.py@@ -0,0 +1,107 @@+# Generated by Django 5.2++import django.utils.timezone+import django.db.models.deletion+import django.contrib.postgres.fields+import django.contrib.postgres.indexes+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1279_drop_duckgresserverteam_table"),+ ("tasks", "0086_clear_disconnected_channel_repositories"),+ ]++ operations = [+ migrations.CreateModel(+ name="TaskSearchDocument",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ (+ "kind",+ models.CharField(+ choices=[+ ("task", "Task"),+ ("pull_request", "Pull request"),+ ("artifact", "Artifact"),+ ("channel", "Channel"),+ ],+ max_length=32,+ ),+ ),+ ("source_key", models.CharField(max_length=512)),+ ("title", models.CharField(max_length=512)),+ ("subtitle", models.CharField(blank=True, default="", max_length=512)),+ ("search_text", models.TextField()),+ (+ "exact_identifiers",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=512), blank=True, default=list, size=None+ ),+ ),+ ("metadata", models.JSONField(blank=True, default=dict)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "channel",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="tasks.channel",+ ),+ ),+ (+ "task",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="tasks.task",+ ),+ ),+ (+ "task_run",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="tasks.taskrun",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_task_search_document",+ "indexes": [+ models.Index(fields=["team", "kind"], name="task_search_doc_team_kind_idx"),+ django.contrib.postgres.indexes.GinIndex(+ fields=["exact_identifiers"], name="task_search_doc_exact_gin"+ ),+ django.contrib.postgres.indexes.GinIndex(+ fields=["search_text"], name="task_search_doc_text_trgm", opclasses=["gin_trgm_ops"]+ ),+ ],+ "constraints": [+ models.UniqueConstraint(fields=("team", "kind", "source_key"), name="task_search_doc_source_unique")+ ],+ },+ )+ ]diff --git a/products/tasks/backend/migrations/0088_backfill_task_search_documents.py b/products/tasks/backend/migrations/0088_backfill_task_search_documents.pynew file mode 100644index 000000000000..88aa382337dd--- /dev/null+++ b/products/tasks/backend/migrations/0088_backfill_task_search_documents.py@@ -0,0 +1,244 @@+import re+import hashlib+from typing import Any++from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++PR_URL_RE = re.compile(r"^https?://github\.com/(?P<repo>[^/]+/[^/]+)/pull/(?P<number>\d+)(?:/.*)?$", re.IGNORECASE)+MAX_INDEXED_PR_URLS = 50+MAX_INDEXED_ARTIFACTS = 100+MAX_IDENTIFIER_LENGTH = 512+BATCH_SIZE = 1_000+LOG_EVERY_BATCHES = 25+++def _normalized(values):+ return list(+ dict.fromkeys(value.strip().lower()[:MAX_IDENTIFIER_LENGTH] for value in values if value and value.strip())+ )+++def _source_key(value):+ if len(value) <= MAX_IDENTIFIER_LENGTH:+ return value+ digest = hashlib.sha256(value.encode()).hexdigest()+ return f"{value[: MAX_IDENTIFIER_LENGTH - len(digest) - 1]}:{digest}"+++def _task_slug(task):+ if task.task_number is None:+ return ""+ clean_name = "".join(character for character in task.team.name if character.isalnum())+ uppercase_letters = [character for character in clean_name if character.isupper()]+ prefix = "".join(uppercase_letters[:3]) if len(uppercase_letters) >= 3 else clean_name[:3].upper() or "TSK"+ return f"{prefix}-{task.task_number}"+++def _document(SearchDocument, *, team_id, kind, source_key, title, subtitle="", identifiers=(), **relations):+ exact_identifiers = _normalized(identifiers)+ return SearchDocument(+ team_id=team_id,+ kind=kind,+ source_key=_source_key(source_key),+ title=title[:512],+ subtitle=subtitle[:512],+ search_text=" ".join(_normalized([title, subtitle, *exact_identifiers])),+ exact_identifiers=exact_identifiers,+ metadata=relations.pop("metadata", {}),+ **relations,+ )+++def backfill_task_search_documents(apps, schema_editor):+ Channel = apps.get_model("tasks", "Channel")+ Task = apps.get_model("tasks", "Task")+ TaskArtifact = apps.get_model("tasks", "TaskArtifact")+ TaskRun = apps.get_model("tasks", "TaskRun")+ SearchDocument = apps.get_model("tasks", "TaskSearchDocument")+ Team = apps.get_model("posthog", "Team")+ parent_team_ids = dict(Team.objects.exclude(parent_team_id=None).values_list("id", "parent_team_id"))+ documents: list[Any] = []+ documents_processed = 0+ batches_committed = 0++ logger.info("task_search_backfill_started", batch_size=BATCH_SIZE)++ def canonical_team_id(team_id):+ return parent_team_ids.get(team_id) or team_id++ def flush():+ nonlocal documents_processed, batches_committed+ if not documents:+ return+ batch_count = len(documents)+ SearchDocument.objects.bulk_create(documents, batch_size=BATCH_SIZE, ignore_conflicts=True)+ documents.clear()+ documents_processed += batch_count+ batches_committed += 1+ if batches_committed % LOG_EVERY_BATCHES == 0:+ logger.info(+ "task_search_backfill_progress",+ batches_committed=batches_committed,+ documents_processed=documents_processed,+ )++ def add(document):+ documents.append(document)+ if len(documents) >= BATCH_SIZE:+ flush()++ for channel in (+ Channel.objects.filter(deleted=False).only("id", "team_id", "name", "channel_type").iterator(chunk_size=1_000)+ ):+ add(+ _document(+ SearchDocument,+ team_id=canonical_team_id(channel.team_id),+ kind="channel",+ source_key=str(channel.id),+ title=channel.name,+ identifiers=[channel.name],+ channel_id=channel.id,+ metadata={"channel_type": channel.channel_type},+ )+ )++ for task in (+ Task.objects.filter(deleted=False)+ .select_related("team")+ .only(+ "id",+ "team_id",+ "team__name",+ "task_number",+ "title",+ "repository",+ "channel_id",+ "archived",+ )+ .iterator(chunk_size=1_000)+ ):+ identifiers = [str(task.task_number)] if task.task_number is not None else []+ slug = _task_slug(task)+ if slug:+ identifiers.append(slug)+ add(+ _document(+ SearchDocument,+ team_id=canonical_team_id(task.team_id),+ kind="task",+ source_key=str(task.id),+ title=task.title,+ subtitle=task.repository or "",+ identifiers=identifiers,+ task_id=task.id,+ channel_id=task.channel_id,+ metadata={"archived": task.archived},+ )+ )++ for run in (+ TaskRun.objects.filter(task__deleted=False)+ .select_related("task")+ .only("id", "team_id", "task_id", "output", "artifacts", "task__title", "task__channel_id")+ .iterator(chunk_size=1_000)+ ):+ output = run.output or {}+ listed = output.get("pr_urls")+ urls = [value for value in listed if isinstance(value, str)] if isinstance(listed, list) else []+ if isinstance(output.get("pr_url"), str):+ urls.append(output["pr_url"])+ for url in list(dict.fromkeys(url for url in urls if url.strip()))[:MAX_INDEXED_PR_URLS]:+ match = PR_URL_RE.match(url.strip())+ if not match:+ continue+ repo, number = match.group("repo", "number")+ add(+ _document(+ SearchDocument,+ team_id=canonical_team_id(run.team_id),+ kind="pull_request",+ source_key=f"run:{run.id}:{url.lower()}",+ title=f"PR #{number}",+ subtitle=repo,+ identifiers=[url, f"#{number}", number, f"{repo}#{number}"],+ task_id=run.task_id,+ task_run_id=run.id,+ channel_id=run.task.channel_id,+ metadata={"url": url, "number": int(number), "repository": repo},+ )+ )+ for position, artifact in enumerate((run.artifacts or [])[:MAX_INDEXED_ARTIFACTS]):+ if not isinstance(artifact, dict) or artifact.get("dismissed_at"):+ continue+ name = artifact.get("name")+ if not isinstance(name, str) or not name.strip():+ continue+ source_id = artifact.get("id") or artifact.get("storage_path") or f"{position}:{name}"+ add(+ _document(+ SearchDocument,+ team_id=canonical_team_id(run.team_id),+ kind="artifact",+ source_key=f"run:{run.id}:{source_id}",+ title=name,+ subtitle=run.task.title,+ identifiers=[name],+ task_id=run.task_id,+ task_run_id=run.id,+ channel_id=run.task.channel_id,+ metadata={"artifact_id": artifact.get("id"), "artifact_type": artifact.get("type")},+ )+ )++ for artifact in (+ TaskArtifact.objects.filter(status="active", task__deleted=False)+ .select_related("task")+ .only(+ "id",+ "team_id",+ "task_id",+ "task_run_id",+ "name",+ "artifact_type",+ "task__title",+ "task__channel_id",+ )+ .iterator(chunk_size=1_000)+ ):+ add(+ _document(+ SearchDocument,+ team_id=canonical_team_id(artifact.team_id),+ kind="artifact",+ source_key=f"living:{artifact.id}",+ title=artifact.name,+ subtitle=artifact.task.title,+ identifiers=[artifact.name],+ task_id=artifact.task_id,+ task_run_id=artifact.task_run_id,+ channel_id=artifact.task.channel_id,+ metadata={"artifact_id": str(artifact.id), "artifact_type": artifact.artifact_type, "living": True},+ )+ )++ flush()+ logger.info(+ "task_search_backfill_completed",+ batches_committed=batches_committed,+ documents_processed=documents_processed,+ )+++class Migration(migrations.Migration):+ # Each 1,000-document bulk insert commits independently. Avoid wrapping the+ # complete historical scan in a deployment-long transaction.+ atomic = False++ dependencies = [("tasks", "0087_tasksearchdocument")]++ operations = [migrations.RunPython(backfill_task_search_documents, migrations.RunPython.noop, elidable=True)]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 619fb492710d..cf6892a4e9b6 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0086_clear_disconnected_channel_repositories+0088_backfill_task_search_documentsdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 29756baf7492..59713d34a07d 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -18,6 +18,7 @@ if TYPE_CHECKING:from django.conf import settingsfrom django.contrib.postgres.fields import ArrayField+from django.contrib.postgres.indexes import GinIndexfrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, connection, models, transactionfrom django.db.models.fields.json import KeyTransform@@ -2542,6 +2543,41 @@ class TaskArtifact(TeamScopedRootMixin, UUIDModel):return f"{self.name} ({self.artifact_type})"+class TaskSearchDocument(TeamScopedRootMixin, UUIDModel):+ """Small, rebuildable search projection for Desktop's global command menu."""++ class Kind(models.TextChoices):+ TASK = "task", "Task"+ PULL_REQUEST = "pull_request", "Pull request"+ ARTIFACT = "artifact", "Artifact"+ CHANNEL = "channel", "Channel"++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+", null=True, blank=True)+ task_run = models.ForeignKey(TaskRun, on_delete=models.CASCADE, related_name="+", null=True, blank=True)+ channel = models.ForeignKey(Channel, on_delete=models.SET_NULL, related_name="+", null=True, blank=True)+ kind = models.CharField(max_length=32, choices=Kind)+ source_key = models.CharField(max_length=512)+ title = models.CharField(max_length=512)+ subtitle = models.CharField(max_length=512, blank=True, default="")+ search_text = models.TextField()+ exact_identifiers = ArrayField(models.CharField(max_length=512), default=list, blank=True)+ metadata = models.JSONField(default=dict, blank=True)+ created_at = models.DateTimeField(default=django_timezone.now)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_task_search_document"+ constraints = [+ models.UniqueConstraint(fields=["team", "kind", "source_key"], name="task_search_doc_source_unique")+ ]+ indexes = [+ models.Index(fields=["team", "kind"], name="task_search_doc_team_kind_idx"),+ GinIndex(fields=["exact_identifiers"], name="task_search_doc_exact_gin"),+ GinIndex(fields=["search_text"], name="task_search_doc_text_trgm", opclasses=["gin_trgm_ops"]),+ ]++class SandboxSession(TeamScopedRootMixin, UUIDModel):"""Usage ledger for one cloud sandbox: when it ran, its resource shape, and whichslice of its lifetime is attributable to a user.diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 58ff6204b325..1da1c78bf3a8 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1527,6 +1527,26 @@ class TaskListQuerySerializer(serializers.Serializer):)+class TaskSearchQuerySerializer(serializers.Serializer):+ q = serializers.CharField(min_length=1, max_length=512, help_text="Text or exact identifier to search for.")+ limit = serializers.IntegerField(+ required=False, default=20, min_value=1, max_value=50, help_text="Maximum number of results to return."+ )+++class TaskSearchResultSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Search document identifier.")+ kind = serializers.ChoiceField(+ choices=["task", "pull_request", "artifact", "channel"], help_text="Type of matched resource."+ )+ title = serializers.CharField(help_text="Primary result label.")+ subtitle = serializers.CharField(allow_blank=True, help_text="Secondary result context.")+ task_id = serializers.UUIDField(allow_null=True, help_text="Containing task identifier, when applicable.")+ task_run_id = serializers.UUIDField(allow_null=True, help_text="Containing task run identifier, when applicable.")+ channel_id = serializers.UUIDField(allow_null=True, help_text="Containing space identifier, when applicable.")+ metadata = serializers.JSONField(help_text="Resource-specific navigation metadata.")++class ChannelSerializer(DataclassSerializer):"""Response shape for a task channel, read from a frozen ``ChannelDTO``."""diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 5a5a54a31107..9ed419913bd2 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -140,6 +140,8 @@ from products.tasks.backend.presentation.serializers import (TaskRunSetOutputRequestSerializer,TaskRunStartRequestSerializer,TaskRunUpdateSerializer,+ TaskSearchQuerySerializer,+ TaskSearchResultSerializer,TaskSerializer,TaskSessionResponseSerializer,TaskSessionSyncResponseSerializer,@@ -353,6 +355,30 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):TaskSerializer(tasks_facade._tasks_to_dtos(page, self.team_id), many=True).data)+ @validated_request(+ query_serializer=TaskSearchQuerySerializer,+ responses={200: OpenApiResponse(response=TaskSearchResultSerializer(many=True))},+ summary="Search tasks, pull requests, artifacts, and spaces",+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="search",+ pagination_class=None,+ required_scopes=["task:read"],+ )+ def search(self, request, *args, **kwargs):+ query = request.validated_query_data["q"]+ limit = request.validated_query_data["limit"]+ results = tasks_facade.search_tasks(+ self.team_id,+ self._user_id(),+ query,+ limit=limit,+ bypass_visibility=_can_bypass_visibility(request, self.team_id),+ )+ return Response(TaskSearchResultSerializer(results, many=True).data)+@extend_schema(responses={200: OpenApiResponse(response=TaskSerializer, description="Task")},summary="Get task",diff --git a/products/tasks/backend/search_index.py b/products/tasks/backend/search_index.pynew file mode 100644index 000000000000..07a873132a8d--- /dev/null+++ b/products/tasks/backend/search_index.py@@ -0,0 +1,287 @@+import re+import hashlib+import logging+from collections.abc import Iterable+from typing import Any++from django.db import transaction+from django.db.models import Q, Value+from django.db.models.functions import Concat, Lower, Trim+from django.db.models.signals import post_delete, post_save+from django.dispatch import receiver++from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.team import Team++from products.tasks.backend.models import Channel, Task, TaskArtifact, TaskRun, TaskSearchDocument++logger = logging.getLogger(__name__)++_PR_URL_RE = re.compile(r"^https?://github\.com/(?P<repo>[^/]+/[^/]+)/pull/(?P<number>\d+)(?:/.*)?$", re.IGNORECASE)+MAX_INDEXED_PR_URLS = 50+MAX_INDEXED_ARTIFACTS = 100+MAX_IDENTIFIER_LENGTH = 512+++def _normalized(values: Iterable[str]) -> list[str]:+ return list(+ dict.fromkeys(value.strip().lower()[:MAX_IDENTIFIER_LENGTH] for value in values if value and value.strip())+ )+++def _source_key(value: str) -> str:+ if len(value) <= MAX_IDENTIFIER_LENGTH:+ return value+ digest = hashlib.sha256(value.encode()).hexdigest()+ return f"{value[: MAX_IDENTIFIER_LENGTH - len(digest) - 1]}:{digest}"+++def _upsert(+ *,+ team_id: int,+ kind: str,+ source_key: str,+ title: str,+ subtitle: str = "",+ identifiers: Iterable[str] = (),+ task_id: Any = None,+ task_run_id: Any = None,+ channel_id: Any = None,+ metadata: dict[str, Any] | None = None,+) -> None:+ exact_identifiers = _normalized(identifiers)+ TaskSearchDocument.objects.for_team(team_id, canonical=True).update_or_create(+ team_id=team_id,+ kind=kind,+ source_key=_source_key(source_key),+ defaults={+ "task_id": task_id,+ "task_run_id": task_run_id,+ "channel_id": channel_id,+ "title": title[:512],+ "subtitle": subtitle[:512],+ "search_text": " ".join(_normalized([title, subtitle, *exact_identifiers])),+ "exact_identifiers": exact_identifiers,+ "metadata": metadata or {},+ },+ )+++def index_task(task_id: Any, *, include_related: bool = True, canonical_team_id: int | None = None) -> None:+ task = Task.objects.filter(id=task_id).first()+ if task is None or task.deleted:+ TaskSearchDocument.objects.unscoped().filter(task_id=task_id).delete()+ return+ identifiers = [str(task.task_number)] if task.task_number is not None else []+ if task.slug:+ identifiers.append(task.slug)+ canonical_team_id = canonical_team_id or resolve_effective_team_id(task.team_id)+ _upsert(+ team_id=canonical_team_id,+ kind=TaskSearchDocument.Kind.TASK,+ source_key=str(task.id),+ title=task.title,+ subtitle=task.repository or "",+ identifiers=identifiers,+ task_id=task.id,+ channel_id=task.channel_id,+ metadata={"archived": task.archived},+ )+ if not include_related:+ return+ # Task title/channel changes affect descendant navigation context, but+ # rereading every historical run manifest would make a task save unbounded.+ # Update the projected fields in a fixed number of queries instead.+ descendants = TaskSearchDocument.objects.for_team(canonical_team_id, canonical=True).filter(task_id=task.id)+ descendants.update(channel_id=task.channel_id)+ descendants.filter(kind=TaskSearchDocument.Kind.ARTIFACT).update(+ subtitle=task.title[:MAX_IDENTIFIER_LENGTH],+ search_text=Trim(+ Concat(+ Lower("title"),+ Value(" "),+ Lower(Value(task.title[:MAX_IDENTIFIER_LENGTH])),+ )+ ),+ )+++def _pr_urls(output: dict[str, Any] | None) -> list[str]:+ if not output:+ return []+ listed = output.get("pr_urls")+ values = [value for value in listed if isinstance(value, str)] if isinstance(listed, list) else []+ single = output.get("pr_url")+ if isinstance(single, str):+ values.append(single)+ return list(dict.fromkeys(value for value in values if value.strip()))[:MAX_INDEXED_PR_URLS]+++def index_task_run(run_id: Any, *, canonical_team_id: int | None = None) -> None:+ run = TaskRun.objects.select_related("task").filter(id=run_id).first()+ if run is None or run.task.deleted:+ TaskSearchDocument.objects.unscoped().filter(task_run_id=run_id).delete()+ return+ canonical_team_id = canonical_team_id or resolve_effective_team_id(run.team_id)+ TaskSearchDocument.objects.for_team(canonical_team_id, canonical=True).filter(+ source_key__startswith=f"run:{run.id}:"+ ).delete()+ for url in _pr_urls(run.output):+ match = _PR_URL_RE.match(url.strip())+ if not match:+ continue+ repo, number = match.group("repo", "number")+ _upsert(+ team_id=canonical_team_id,+ kind=TaskSearchDocument.Kind.PULL_REQUEST,+ source_key=f"run:{run.id}:{url.lower()}",+ title=f"PR #{number}",+ subtitle=repo,+ identifiers=[url, f"#{number}", number, f"{repo}#{number}"],+ task_id=run.task_id,+ task_run_id=run.id,+ channel_id=run.task.channel_id,+ metadata={"url": url, "number": int(number), "repository": repo},+ )+ for position, artifact in enumerate((run.artifacts or [])[:MAX_INDEXED_ARTIFACTS]):+ if not isinstance(artifact, dict) or artifact.get("dismissed_at"):+ continue+ name = artifact.get("name")+ if not isinstance(name, str) or not name.strip():+ continue+ source_id = artifact.get("id") or artifact.get("storage_path") or f"{position}:{name}"+ _upsert(+ team_id=canonical_team_id,+ kind=TaskSearchDocument.Kind.ARTIFACT,+ source_key=f"run:{run.id}:{source_id}",+ title=name,+ subtitle=run.task.title,+ identifiers=[name],+ task_id=run.task_id,+ task_run_id=run.id,+ channel_id=run.task.channel_id,+ metadata={"artifact_id": artifact.get("id"), "artifact_type": artifact.get("type")},+ )+++def index_task_artifact(artifact_id: Any, *, canonical_team_id: int | None = None) -> None:+ artifact = TaskArtifact.objects.unscoped().select_related("task").filter(id=artifact_id).first()+ source_key = f"living:{artifact_id}"+ if artifact is None or artifact.status != TaskArtifact.Status.ACTIVE or artifact.task.deleted:+ TaskSearchDocument.objects.unscoped().filter(+ kind=TaskSearchDocument.Kind.ARTIFACT, source_key=source_key+ ).delete()+ return+ canonical_team_id = canonical_team_id or resolve_effective_team_id(artifact.team_id)+ _upsert(+ team_id=canonical_team_id,+ kind=TaskSearchDocument.Kind.ARTIFACT,+ source_key=source_key,+ title=artifact.name,+ subtitle=artifact.task.title,+ identifiers=[artifact.name],+ task_id=artifact.task_id,+ task_run_id=artifact.task_run_id,+ channel_id=artifact.task.channel_id,+ metadata={"artifact_id": str(artifact.id), "artifact_type": artifact.artifact_type, "living": True},+ )+++def index_channel(channel_id: Any, *, canonical_team_id: int | None = None) -> None:+ channel = Channel.objects.unscoped().filter(id=channel_id).first()+ if channel is None or channel.deleted:+ TaskSearchDocument.objects.unscoped().filter(+ kind=TaskSearchDocument.Kind.CHANNEL, source_key=str(channel_id)+ ).delete()+ return+ canonical_team_id = canonical_team_id or resolve_effective_team_id(channel.team_id)+ _upsert(+ team_id=canonical_team_id,+ kind=TaskSearchDocument.Kind.CHANNEL,+ source_key=str(channel.id),+ title=channel.name,+ identifiers=[channel.name],+ channel_id=channel.id,+ metadata={"channel_type": channel.channel_type},+ )+++def rebuild_team_search_index(team_id: int) -> None:+ canonical_team_id = resolve_effective_team_id(team_id)+ environment_ids = Team.objects.filter(Q(id=canonical_team_id) | Q(parent_team_id=canonical_team_id)).values_list(+ "id", flat=True+ )+ TaskSearchDocument.objects.for_team(canonical_team_id, canonical=True).delete()+ for task_id in Task.objects.filter(team_id__in=environment_ids).values_list("id", flat=True).iterator():+ index_task(task_id, include_related=False, canonical_team_id=canonical_team_id)+ for run_id in TaskRun.objects.filter(team_id__in=environment_ids).values_list("id", flat=True).iterator():+ index_task_run(run_id, canonical_team_id=canonical_team_id)+ for artifact_id in (+ TaskArtifact.objects.for_team(canonical_team_id, canonical=True).values_list("id", flat=True).iterator()+ ):+ index_task_artifact(artifact_id, canonical_team_id=canonical_team_id)+ for channel_id in (+ Channel.objects.for_team(canonical_team_id, canonical=True).values_list("id", flat=True).iterator()+ ):+ index_channel(channel_id, canonical_team_id=canonical_team_id)+++def _after_commit(callback) -> None:+ def safely_index() -> None:+ try:+ callback()+ except Exception:+ # This projection is rebuildable and must never turn a successful+ # task/run write into an apparent request failure.+ logger.exception("task_search_index_update_failed")++ transaction.on_commit(safely_index)+++@receiver(post_save, sender=Task)+def task_saved(sender, instance: Task, update_fields=None, **kwargs) -> None:+ if update_fields is not None and not set(update_fields) & {+ "title",+ "task_number",+ "slug",+ "repository",+ "channel",+ "archived",+ "deleted",+ }:+ return+ include_related = update_fields is None or bool(set(update_fields) & {"title", "channel"})+ _after_commit(lambda: index_task(instance.id, include_related=include_related))+++@receiver(post_save, sender=TaskRun)+def task_run_saved(sender, instance: TaskRun, update_fields=None, **kwargs) -> None:+ if update_fields is not None and not set(update_fields) & {"output", "artifacts"}:+ return+ _after_commit(lambda: index_task_run(instance.id))+++@receiver(post_save, sender=TaskArtifact)+def task_artifact_saved(sender, instance: TaskArtifact, update_fields=None, **kwargs) -> None:+ if update_fields is not None and not set(update_fields) & {"name", "status", "task", "task_run", "artifact_type"}:+ return+ _after_commit(lambda: index_task_artifact(instance.id))+++@receiver(post_save, sender=Channel)+def channel_saved(sender, instance: Channel, update_fields=None, **kwargs) -> None:+ if update_fields is not None and not set(update_fields) & {"name", "deleted", "channel_type", "created_by"}:+ return+ _after_commit(lambda: index_channel(instance.id))+++@receiver(post_delete, sender=Channel)+def channel_deleted(sender, instance: Channel, **kwargs) -> None:+ _after_commit(+ lambda: (+ TaskSearchDocument.objects.unscoped()+ .filter(kind=TaskSearchDocument.Kind.CHANNEL, source_key=str(instance.id))+ .delete()+ )+ )diff --git a/products/tasks/backend/tests/test_search_index.py b/products/tasks/backend/tests/test_search_index.pynew file mode 100644index 000000000000..39e70affa7b6--- /dev/null+++ b/products/tasks/backend/tests/test_search_index.py@@ -0,0 +1,218 @@+from django.test import TransactionTestCase++from posthog.models import Organization, Team, User+from posthog.models.scoping import team_scope++from products.tasks.backend.facade.api import search_tasks, set_task_title+from products.tasks.backend.models import Channel, Task, TaskArtifact, TaskRun, TaskSearchDocument+from products.tasks.backend.search_index import (+ MAX_INDEXED_ARTIFACTS,+ MAX_INDEXED_PR_URLS,+ index_task_artifact,+ index_task_run,+)+++class TestTaskSearchIndex(TransactionTestCase):+ def setUp(self):+ self.organization = Organization.objects.create(name="Search Org")+ self.team = Team.objects.create(organization=self.organization, name="Search Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="search-user")+ self.enterContext(team_scope(self.team.id))++ def make_task(self, title="Index command menu", **kwargs):+ channel = kwargs.pop("channel", None) or Channel.objects.create(+ team=self.team, name=f"space-{Task.objects.count()}", created_by=self.user+ )+ return Task.objects.create(+ team=self.team,+ title=title,+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ created_by=self.user,+ repository="posthog/posthog",+ channel=channel,+ **kwargs,+ )++ def test_indexes_pr_url_number_and_artifact_name(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ output={"pr_urls": ["https://github.com/PostHog/posthog/pull/123"]},+ artifacts=[{"id": "report", "name": "search-report.csv", "type": "output"}],+ )+ index_task_run(run.id)++ pr_result = search_tasks(self.team.id, self.user.id, "123")[0]+ self.assertEqual(pr_result["kind"], TaskSearchDocument.Kind.PULL_REQUEST)+ self.assertEqual(pr_result["metadata"]["url"], "https://github.com/PostHog/posthog/pull/123")++ artifact_result = search_tasks(self.team.id, self.user.id, "search-report")[0]+ self.assertEqual(artifact_result["kind"], TaskSearchDocument.Kind.ARTIFACT)+ self.assertEqual(artifact_result["task_id"], str(task.id))++ def test_short_queries_only_match_exact_identifiers(self):+ task = self.make_task(title="A common title")+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ artifacts=[{"id": "short", "name": "x"}],+ )+ index_task_run(run.id)++ self.assertEqual(search_tasks(self.team.id, self.user.id, "a"), [])+ self.assertEqual(search_tasks(self.team.id, self.user.id, "x")[0]["kind"], TaskSearchDocument.Kind.ARTIFACT)++ def test_searches_pr_url_with_noncanonical_suffix(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ output={"pr_url": "https://github.com/PostHog/posthog/pull/123"},+ )+ index_task_run(run.id)++ result = search_tasks(self.team.id, self.user.id, "https://github.com/posthog/posthog/pull/123/files")[0]++ self.assertEqual(result["kind"], TaskSearchDocument.Kind.PULL_REQUEST)++ def test_replaces_documents_when_run_output_changes(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ output={"pr_url": "https://github.com/posthog/posthog/pull/10"},+ )+ index_task_run(run.id)+ run.output = {"pr_url": "https://github.com/posthog/posthog/pull/11"}+ run.save(update_fields=["output"])+ index_task_run(run.id)++ self.assertEqual(search_tasks(self.team.id, self.user.id, "10"), [])+ self.assertEqual(search_tasks(self.team.id, self.user.id, "11")[0]["title"], "PR #11")++ def test_indexes_automated_task_title_updates(self):+ task = self.make_task(title="Researching report")++ self.assertTrue(set_task_title(task.id, self.team.id, "Research: Search indexing"))++ self.assertEqual(search_tasks(self.team.id, self.user.id, "search indexing")[0]["task_id"], str(task.id))++ def test_updates_descendant_context_without_reindexing_runs(self):+ task = self.make_task(title="Old title")+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ artifacts=[{"id": "report", "name": "report.csv"}],+ )+ index_task_run(run.id)+ new_channel = Channel.objects.create(team=self.team, name="new-space", created_by=self.user)++ task.title = "New title"+ task.channel = new_channel+ task.save(update_fields=["title", "channel"])++ document = TaskSearchDocument.objects.for_team(self.team.id).get(+ kind=TaskSearchDocument.Kind.ARTIFACT,+ task_run_id=run.id,+ )+ self.assertEqual(document.subtitle, "New title")+ self.assertEqual(document.channel_id, new_channel.id)+ self.assertIn("new title", document.search_text)++ def test_limits_pr_documents_from_run_output(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ output={+ "pr_urls": [+ f"https://github.com/PostHog/posthog/pull/{number}" for number in range(MAX_INDEXED_PR_URLS + 10)+ ]+ },+ )++ index_task_run(run.id)++ self.assertEqual(+ TaskSearchDocument.objects.for_team(self.team.id)+ .filter(kind=TaskSearchDocument.Kind.PULL_REQUEST, task_run_id=run.id)+ .count(),+ MAX_INDEXED_PR_URLS,+ )++ def test_limits_artifact_documents_from_run_output(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ artifacts=[+ {"id": str(number), "name": f"artifact-{number}"} for number in range(MAX_INDEXED_ARTIFACTS + 10)+ ],+ )++ index_task_run(run.id)++ self.assertEqual(+ TaskSearchDocument.objects.for_team(self.team.id)+ .filter(kind=TaskSearchDocument.Kind.ARTIFACT, task_run_id=run.id)+ .count(),+ MAX_INDEXED_ARTIFACTS,+ )++ def test_indexes_active_living_artifact(self):+ task = self.make_task()+ run = TaskRun.objects.create(team=self.team, task=task)+ artifact = TaskArtifact.objects.for_team(self.team.id).create(+ team=self.team,+ task=task,+ task_run=run,+ created_by=self.user,+ name="Release checklist",+ artifact_type=TaskArtifact.ArtifactType.DOCUMENT,+ adapter=TaskArtifact.Adapter.DOCUMENT_CONNECTOR,+ )+ index_task_artifact(artifact.id)++ result = search_tasks(self.team.id, self.user.id, "release checklist")[0]+ self.assertTrue(result["metadata"]["living"])+ self.assertEqual(result["channel_id"], str(task.channel_id))++ def test_search_respects_personal_channel_visibility(self):+ personal = Channel.objects.create(+ team=self.team,+ name="me",+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=self.user,+ )+ self.make_task(title="Private search target", channel=personal)+ other_user = User.objects.create(email="[email protected]", distinct_id="other-search-user")++ self.assertEqual(search_tasks(self.team.id, other_user.id, "private search target"), [])+ self.assertEqual(search_tasks(self.team.id, self.user.id, "private search target")[0]["kind"], "task")+ self.assertEqual(+ search_tasks(+ self.team.id,+ other_user.id,+ "private search target",+ bypass_visibility=True,+ )[0]["kind"],+ "task",+ )++ def test_deleted_task_descendants_are_removed(self):+ task = self.make_task()+ run = TaskRun.objects.create(+ team=self.team,+ task=task,+ output={"pr_url": "https://github.com/PostHog/posthog/pull/456"},+ )+ index_task_run(run.id)+ task.deleted = True+ task.save(update_fields=["deleted"])++ index_task_run(run.id)++ self.assertEqual(search_tasks(self.team.id, self.user.id, "456"), [])diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex e3ed2edb6796..f0b45478ee86 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3787,6 +3787,54 @@ export interface RepositoryReadinessResponseApi {scan?: ScanEvidenceApi}+/**+ * * `task` - task+ * * `pull_request` - pull_request+ * * `artifact` - artifact+ * * `channel` - channel+ */+export type TaskSearchResultKindEnumApi = (typeof TaskSearchResultKindEnumApi)[keyof typeof TaskSearchResultKindEnumApi]++export const TaskSearchResultKindEnumApi = {+ Task: 'task',+ PullRequest: 'pull_request',+ Artifact: 'artifact',+ Channel: 'channel',+} as const++export interface TaskSearchResultApi {+ /** Search document identifier. */+ id: string+ /** Type of matched resource.+ *+ * * `task` - task+ * * `pull_request` - pull_request+ * * `artifact` - artifact+ * * `channel` - channel */+ kind: TaskSearchResultKindEnumApi+ /** Primary result label. */+ title: string+ /** Secondary result context. */+ subtitle: string+ /**+ * Containing task identifier, when applicable.+ * @nullable+ */+ task_id: string | null+ /**+ * Containing task run identifier, when applicable.+ * @nullable+ */+ task_run_id: string | null+ /**+ * Containing space identifier, when applicable.+ * @nullable+ */+ channel_id: string | null+ /** Resource-specific navigation metadata. */+ metadata: unknown+}+/*** Slack-side identifiers and the mapping metadata for a thread → task lookup.*/@@ -4429,6 +4477,21 @@ export type TasksRepositoryReadinessRetrieveParams = {window_days?: number}+export type TasksSearchRetrieveParams = {+ /**+ * Maximum number of results to return.+ * @minimum 1+ * @maximum 50+ */+ limit?: number+ /**+ * Text or exact identifier to search for.+ * @minLength 1+ * @maxLength 512+ */+ q: string+}+export type TasksSlackThreadContextRetrieveParams = {/*** Full Slack permalink to any message in the thread (e.g. https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the thread are accepted too — the `thread_ts` query param (when present) takes precedence over the in-path message ts.diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 9ce892d7f216..d27694487b49 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -110,6 +110,7 @@ import type {TaskRunRelayMessageRequestApi,TaskRunRelayMessageResponseApi,TaskRunStartRequestApi,+ TaskSearchResultApi,TaskSessionResponseApi,TaskSessionSyncResponseApi,TaskStagedArtifactsFinalizeUploadRequestApi,@@ -127,6 +128,7 @@ import type {TasksRunsListParams,TasksRunsSessionLogsRetrieveParams,TasksRunsStreamRetrieveParams,+ TasksSearchRetrieveParams,TasksSlackThreadContextRetrieveParams,TasksSummariesCreateParams,TasksThreadMessagesListParams,@@ -2471,6 +2473,37 @@ export const tasksRepositoryReadinessRetrieve = async (})}+export const getTasksSearchRetrieveUrl = (projectId: string, params: TasksSearchRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/tasks/search/?${stringifiedParams}`+ : `/api/projects/${projectId}/tasks/search/`+}++/**+ * API for managing tasks within a project. Tasks represent units of work to be performed by an agent.+ * @summary Search tasks, pull requests, artifacts, and spaces+ */+export const tasksSearchRetrieve = async (+ projectId: string,+ params: TasksSearchRetrieveParams,+ options?: RequestInit+): Promise<TaskSearchResultApi[]> => {+ return apiMutator<TaskSearchResultApi[]>(getTasksSearchRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getTasksSlackThreadContextRetrieveUrl = (projectId: string,params: TasksSlackThreadContextRetrieveParamsdiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 3b00b9908f8a..358403727950 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -611,6 +611,9 @@ tools:tasks-runs-task-session-sync-create:operation: tasks_runs_task_session_sync_createenabled: false+ tasks-search-retrieve:+ operation: tasks_search_retrieve+ enabled: falsetasks-slack-thread-context-retrieve:operation: tasks_slack_thread_context_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7e973381b5b4..46b5f8db0e8d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -76085,6 +76085,55 @@ export namespace Schemas {pending_user_artifact_ids?: string[];}+ /**+ * * `task` - task+ * * `pull_request` - pull_request+ * * `artifact` - artifact+ * * `channel` - channel+ */+ export type TaskSearchResultKindEnum = typeof TaskSearchResultKindEnum[keyof typeof TaskSearchResultKindEnum];+++ export const TaskSearchResultKindEnum = {+ Task: 'task',+ PullRequest: 'pull_request',+ Artifact: 'artifact',+ Channel: 'channel',+ } as const;++ export interface TaskSearchResult {+ /** Search document identifier. */+ id: string;+ /** Type of matched resource.+ *+ * * `task` - task+ * * `pull_request` - pull_request+ * * `artifact` - artifact+ * * `channel` - channel */+ kind: TaskSearchResultKindEnum;+ /** Primary result label. */+ title: string;+ /** Secondary result context. */+ subtitle: string;+ /**+ * Containing task identifier, when applicable.+ * @nullable+ */+ task_id: string | null;+ /**+ * Containing task run identifier, when applicable.+ * @nullable+ */+ task_run_id: string | null;+ /**+ * Containing space identifier, when applicable.+ * @nullable+ */+ channel_id: string | null;+ /** Resource-specific navigation metadata. */+ metadata: unknown;+ }+export interface TaskSessionResponse {/** Task session identifier */id: string;@@ -88771,6 +88820,21 @@ export namespace Schemas {window_days?: number;};+ export type TasksSearchRetrieveParams = {+ /**+ * Maximum number of results to return.+ * @minimum 1+ * @maximum 50+ */+ limit?: number;+ /**+ * Text or exact identifier to search for.+ * @minLength 1+ * @maxLength 512+ */+ q: string;+ };+export type TasksSlackThreadContextRetrieveParams = {/*** Full Slack permalink to any message in the thread (e.g. https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the thread are accepted too — the `thread_ts` query param (when present) takes precedence over the in-path message ts.