: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(error-tracking): add code owners assignment import (#65766)
Hugues Pouillot727728a39f55
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 22afb97a637c..30ccf2b7fb0c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6441,9 +6441,9 @@ snapshots:scenes-app-settings-environment--settings-environment-error-tracking--light:hash: v1.k794b7964.d2eb44367a4f4e948d2c45e4ad089bdfd0929ae4e1e6ae0e79c624a3a1d8d90f.IWh0_HTcd0w3UEmbt5VOFHToiunPwoEZDRHLYkGKc6cscenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:- hash: v1.k794b7964.386dc1a7039bbb1e4eac3be3979a70cc2057616b69690cd2113749f9cbe5e475.867W7aHCnIK9-MMCGOhAeoDpMbal3wJGRKi7FPgcVCc+ hash: v1.k794b7964.c030607be142741290a17194eb5a53592b076cbbdda3d70b81ccef75cc9b6c22.hF0RJI0j4NAOVdWGJwOGpip8ckZRCUqgT1rdlGW3YqYscenes-app-settings-environment--settings-environment-error-tracking-configuration--light:- hash: v1.k794b7964.1da10a4331fb41fd378fad352c416601d4eedf888bf9aae5e270b1074468b957.RU3clHXF0srO7U8dAFNMBVfuvSYvXcj2NAnY2uJvG9Y+ hash: v1.k794b7964.2f40238b917b2e66cf31cca3dbe5c92a33d5f1c5eb0d1645a4178f87cd789580.9Y8shA4VVl68EO_EkKUyYwRr3yBNPd-w1EgPr3VTQhYscenes-app-settings-environment--settings-environment-feature-flags--dark:hash: v1.k794b7964.4a627c125b4196ab9adfe9389e8fa20e9ba68c9110af68d1087ac9b6325da406.WVq_ojXXs-K3q725sJPCE3y4bmi1S_bf1T72JHY5vvEscenes-app-settings-environment--settings-environment-feature-flags--light:diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex ff9de074ecd7..02830eed8e24 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -13,6 +13,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner'import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'import { codeEditorLogicType } from 'lib/monaco/codeEditorLogicType'import { findNextFocusableElement, findPreviousFocusableElement } from 'lib/monaco/domUtils'+import { initCodeownersLanguage } from 'lib/monaco/languages/codeowners'import { initHogLanguage } from 'lib/monaco/languages/hog'import { initHogJsonLanguage } from 'lib/monaco/languages/hogJson'import { initHogQLLanguage } from 'lib/monaco/languages/hogQL'@@ -80,6 +81,9 @@ function initEditor(if (editorProps?.language === 'liquid') {initLiquidLanguage(monaco)}+ if (editorProps?.language === 'codeowners') {+ initCodeownersLanguage(monaco)+ }editor.onKeyDown((evt) => {if (evt.keyCode === monaco.KeyCode.Space) {diff --git a/frontend/src/lib/monaco/languages/codeowners.ts b/frontend/src/lib/monaco/languages/codeowners.tsnew file mode 100644index 000000000000..2886d51495ec--- /dev/null+++ b/frontend/src/lib/monaco/languages/codeowners.ts@@ -0,0 +1,31 @@+import { Monaco } from '@monaco-editor/react'+import { languages } from 'monaco-editor'++export const conf: () => languages.LanguageConfiguration = () => ({+ comments: {+ lineComment: '#',+ },+})++export const language: () => languages.IMonarchLanguage = () => ({+ defaultToken: '',+ tokenizer: {+ root: [+ [/#.*$/, 'comment'],+ // Email owners — matched before the path rule, which stops at '@'.+ [/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/, 'type'],+ // Team / user owners: @org/team, @user.+ [/@[A-Za-z0-9/_.-]+/, 'type'],+ // Path patterns, including glob wildcards.+ [/[^\s#@]+/, 'string'],+ ],+ },+})++export function initCodeownersLanguage(monaco: Monaco): void {+ if (!monaco.languages.getLanguages().some((lang: { id: string }) => lang.id === 'codeowners')) {+ monaco.languages.register({ id: 'codeowners' })+ monaco.languages.setLanguageConfiguration('codeowners', conf())+ monaco.languages.setMonarchTokensProvider('codeowners', language())+ }+}diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex 497e1a64aa62..115c351245cd 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -341,9 +341,15 @@ def get_assignment_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingAsreturn _to_assignment_rule(rule) if rule is not None else None-def create_assignment_rule(team_id: int, *, filters: dict, assignee: dict) -> contracts.ErrorTrackingAssignmentRule:+def create_assignment_rule(+ team_id: int, *, filters: dict, assignee: dict, order_key: int = 0+) -> contracts.ErrorTrackingAssignmentRule:rule = logic.create_assignment_rule(- team_id, filters=filters, assignee_type=assignee["type"], assignee_id=assignee["id"]+ team_id,+ filters=filters,+ assignee_type=assignee["type"],+ assignee_id=assignee["id"],+ order_key=order_key,)return _to_assignment_rule(rule)diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.pyindex 8ba8fe07024d..66249d13689b 100644--- a/products/error_tracking/backend/logic/__init__.py+++ b/products/error_tracking/backend/logic/__init__.py@@ -515,13 +515,13 @@ def get_assignment_rule(team_id: int, rule_id: str) -> ErrorTrackingAssignmentRudef create_assignment_rule(- team_id: int, *, filters: dict, assignee_type: str, assignee_id: int | UUID+ team_id: int, *, filters: dict, assignee_type: str, assignee_id: int | UUID, order_key: int = 0) -> ErrorTrackingAssignmentRule:return ErrorTrackingAssignmentRule.objects.create(team_id=team_id,filters=filters,bytecode=_rule_bytecode(team_id, filters),- order_key=0,+ order_key=order_key,user_id=cast(int, assignee_id) if assignee_type == "user" else None,role_id=cast(UUID, assignee_id) if assignee_type == "role" else None,)diff --git a/products/error_tracking/backend/presentation/views/assignment_rules.py b/products/error_tracking/backend/presentation/views/assignment_rules.pyindex 7ce244d29916..3c4e9758e905 100644--- a/products/error_tracking/backend/presentation/views/assignment_rules.py+++ b/products/error_tracking/backend/presentation/views/assignment_rules.py@@ -78,6 +78,15 @@ class ErrorTrackingAssignmentRuleCreateRequestSerializer(serializers.Serializer)assignee = ErrorTrackingAssignmentRuleAssigneeRequestSerializer(help_text="User or role to assign matching issues to.")+ order_key = serializers.IntegerField(+ required=False,+ default=0,+ help_text=(+ "Evaluation priority among rules; lower is evaluated first and the first matching rule wins. "+ "Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a "+ "deterministic order."+ ),+ )class ErrorTrackingAssignmentRuleUpdateRequestSerializer(serializers.Serializer):@@ -186,6 +195,7 @@ class ErrorTrackingAssignmentRuleViewSet(TeamAndOrgViewSetMixin, viewsets.Generiself.team.id,filters=request.validated_data["filters"],assignee=request.validated_data["assignee"],+ order_key=request.validated_data.get("order_key", 0),)except error_tracking_api.InvalidBytecodeError as err:raise ValidationError(str(err)) from errdiff --git a/products/error_tracking/backend/tests/api/test_assignment_rules.py b/products/error_tracking/backend/tests/api/test_assignment_rules.pyindex 4f5dc8504d0d..1f5a82b9aa3c 100644--- a/products/error_tracking/backend/tests/api/test_assignment_rules.py+++ b/products/error_tracking/backend/tests/api/test_assignment_rules.py@@ -52,7 +52,7 @@ class TestAssignmentRuleAPI(APIBaseTest):assert rule.bytecode is not Noneassert len(rule.bytecode) > 0- def test_create_accepts_frontend_payload_shape_with_extra_fields(self) -> None:+ def test_create_accepts_order_key_and_ignores_frontend_only_fields(self) -> None:response = self.client.post(self._url(),data={@@ -69,7 +69,7 @@ class TestAssignmentRuleAPI(APIBaseTest):rule = ErrorTrackingAssignmentRule.objects.get(id=response.json()["id"])assert rule.filters == VALID_FILTERSassert rule.user_id == self.user.id- assert rule.order_key == 0+ assert rule.order_key == 123assert rule.disabled_data is None@parameterized.expand(diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex 461adea28430..387eb68cb176 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -335,6 +335,8 @@ export interface ErrorTrackingAssignmentRuleCreateRequestApi {filters: PropertyGroupFilterValueApi/** User or role to assign matching issues to. */assignee: ErrorTrackingAssignmentRuleAssigneeRequestApi+ /** Evaluation priority among rules; lower is evaluated first and the first matching rule wins. Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a deterministic order. */+ order_key?: number}export interface ErrorTrackingAssignmentRuleUpdateRequestApi {diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex 2fa795bf767d..82db8ab223dc 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -9,6 +9,8 @@*/import * as zod from 'zod'+export const errorTrackingAssignmentRulesCreateBodyOrderKeyDefault = 0+export const ErrorTrackingAssignmentRulesCreateBody = /* @__PURE__ */ zod.object({filters: zod.record(zod.string(), zod.unknown())@@ -27,6 +29,12 @@ export const ErrorTrackingAssignmentRulesCreateBody = /* @__PURE__ */ zod.object.describe('User ID when `type` is `user`, or role UUID when `type` is `role`.'),}).describe('User or role to assign matching issues to.'),+ order_key: zod+ .number()+ .default(errorTrackingAssignmentRulesCreateBodyOrderKeyDefault)+ .describe(+ 'Evaluation priority among rules; lower is evaluated first and the first matching rule wins. Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a deterministic order.'+ ),})export const ErrorTrackingAssignmentRulesUpdateBody = /* @__PURE__ */ zod.object({diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/AssignmentRules.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/AssignmentRules.tsxindex 15eaf5085f83..35dd0f0b64cd 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/AssignmentRules.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/AssignmentRules.tsx@@ -1,6 +1,8 @@import { useActions } from 'kea'import { useCallback } from 'react'+import { LemonButton } from '@posthog/lemon-ui'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import {@@ -13,9 +15,12 @@ import { RuleList } from '../rules/RuleList'import { ErrorTrackingAssignmentRule, ErrorTrackingRuleType } from '../rules/types'import { AssignmentRuleModal } from './AssignmentRuleModal'import { assignmentRuleModalLogic } from './assignmentRuleModalLogic'+import { CodeOwnersModal } from './CodeOwnersModal'+import { codeOwnersModalLogic } from './codeOwnersModalLogic'export function AssignmentRules(): JSX.Element {const { ensureAssigneeTypesLoaded } = useActions(assigneeSelectLogic)+ const { openModal: openCodeOwnersModal } = useActions(codeOwnersModalLogic)const onMount = useCallback(() => {ensureAssigneeTypesLoaded()@@ -25,10 +30,20 @@ export function AssignmentRules(): JSX.Element {<RuleListruleType={ErrorTrackingRuleType.Assignment}modalLogic={assignmentRuleModalLogic}- modal={<AssignmentRuleModal />}+ modal={+ <>+ <AssignmentRuleModal />+ <CodeOwnersModal />+ </>+ }taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}pageKeyPrefix="assignment-rule"onMount={onMount}+ headerActions={+ <LemonButton type="secondary" size="small" onClick={() => openCodeOwnersModal()}>+ Code owners+ </LemonButton>+ }description={<p>Automatically assign newly created issues based on properties of the exception event the first timediff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersConfigureTable.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersConfigureTable.tsxnew file mode 100644index 000000000000..279bad32be30--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersConfigureTable.tsx@@ -0,0 +1,152 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { Tooltip } from '@posthog/lemon-ui'++import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { MenuOpenIndicator } from 'lib/ui/Menus/Menus'+import { Button, Spinner, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'lib/ui/quill'++import { AssigneeIconDisplay, AssigneeLabelDisplay } from '../../../components/Assignee/AssigneeDisplay'+import { AssigneeSelect } from '../../../components/Assignee/AssigneeSelect'+import { assigneeSelectLogic } from '../../../components/Assignee/assigneeSelectLogic'+import { buildImpactRows } from './codeownersImpact'+import { CodeOwnerOwnerMapping } from './codeownersImport'+import { codeOwnersModalLogic } from './codeOwnersModalLogic'+import { exceptionsUrl, issuesUrl } from './codeownersUrls'++function pathsTooltip(patterns: string[]): JSX.Element {+ return <span className="block whitespace-pre-line text-left">{patterns.join('\n')}</span>+}++export function CodeOwnersConfigureTable(): JSX.Element {+ const { mappingRows } = useValues(codeOwnersModalLogic)+ const { setOwnerAssignee } = useActions(codeOwnersModalLogic)++ return (+ <div className="flex flex-col gap-2">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="px-0">Owner</TableHead>+ <TableHead className="px-0 text-right">PostHog role / user</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {mappingRows.map((row: CodeOwnerOwnerMapping) => {+ return (+ <TableRow key={row.owner}>+ <TableCell className="px-0">+ <div className="flex flex-col gap-1">+ <span className="font-mono text-xs whitespace-nowrap">{row.owner}</span>+ {row.matchFragments.length === 0 ? (+ <Tooltip title={pathsTooltip(row.patterns)} placement="left">+ <span className="w-fit self-start text-xs text-warning">+ no usable path+ </span>+ </Tooltip>+ ) : (+ <Tooltip title={pathsTooltip(row.patterns)} placement="left">+ <span className="w-fit self-start text-xs text-secondary">+ {row.matchFragments.length}{' '}+ {row.matchFragments.length === 1 ? 'path' : 'paths'}+ </span>+ </Tooltip>+ )}+ </div>+ </TableCell>+ <TableCell className="px-0">+ <div className="flex justify-end">+ <AssigneeSelect+ assignee={row.assignee}+ onChange={(assignee) => setOwnerAssignee(row.owner, assignee)}+ >+ {(assignee, isOpen) => (+ <ButtonPrimitive+ className="w-64"+ data-state={isOpen ? 'open' : 'closed'}+ >+ <div className="flex min-w-0 items-center">+ <AssigneeIconDisplay assignee={assignee} size="small" />+ <AssigneeLabelDisplay+ assignee={assignee}+ className="ml-1 min-w-0 truncate"+ size="small"+ placeholder="Assign…"+ />+ </div>+ <MenuOpenIndicator className="ml-auto" />+ </ButtonPrimitive>+ )}+ </AssigneeSelect>+ </div>+ </TableCell>+ </TableRow>+ )+ })}+ </TableBody>+ </Table>+ </div>+ )+}++export function CodeOwnersImpactTable(): JSX.Element {+ const { savableRows, matchResults, matchResultsLoading, dateRange } = useValues(codeOwnersModalLogic)+ const { resolveAssignee } = useValues(assigneeSelectLogic)++ const impactRows = useMemo(+ () => buildImpactRows(savableRows, matchResults, resolveAssignee),+ [matchResults, resolveAssignee, savableRows]+ )++ return (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="px-0 text-left">PostHog role / user</TableHead>+ <TableHead className="px-0 text-left">Exceptions</TableHead>+ <TableHead className="px-0 text-left">Issues</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {impactRows.map((row) => (+ <TableRow key={row.label}>+ <TableCell className="px-0 text-left">{row.label}</TableCell>+ <TableCell className="px-0 text-left">+ {matchResultsLoading ? (+ <Spinner />+ ) : (+ <Button+ variant="link-muted"+ size="xs"+ className="justify-start text-left px-0"+ onClick={() =>+ window.open(exceptionsUrl(row.patterns, dateRange), '_blank', 'noopener')+ }+ >+ {row.exceptionCount}+ </Button>+ )}+ </TableCell>+ <TableCell className="px-0 text-left">+ {matchResultsLoading ? (+ <Spinner />+ ) : (+ <Button+ variant="link-muted"+ size="xs"+ className="justify-start text-left px-0"+ onClick={() =>+ window.open(issuesUrl(row.patterns, dateRange), '_blank', 'noopener')+ }+ >+ {row.issueCount}+ </Button>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersModal.tsxnew file mode 100644index 000000000000..c2b67bc0a5ab--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/CodeOwnersModal.tsx@@ -0,0 +1,221 @@+import { useActions, useValues } from 'kea'+import { ReactNode } from 'react'++import { CodeEditor } from 'lib/monaco/CodeEditor'+import {+ Button,+ Dialog,+ DialogContent,+ DialogTitle,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from 'lib/ui/quill'++import { CodeOwnersConfigureTable, CodeOwnersImpactTable } from './CodeOwnersConfigureTable'+import { codeOwnersModalLogic } from './codeOwnersModalLogic'++const CODE_OWNERS_PLACEHOLDER = 'products/error_tracking/** @team/error-tracking'+const BASE_MODAL_CLASS = 'max-h-[80vh] max-w-[56rem] bg-surface-primary flex flex-col overflow-hidden p-0 gap-0'+const DATE_RANGE_LABELS: Record<string, string> = {+ '-7d': 'Last 7 days',+ '-30d': 'Last 30 days',+ '-90d': 'Last 90 days',+}++function ModalHeader({ title, description }: { title: string; description: string }): JSX.Element {+ return (+ <div className="flex shrink-0 flex-col gap-2 border-b border-primary px-4 py-3 pr-2">+ <DialogTitle className="text-base font-semibold">{title}</DialogTitle>+ <p className="m-0 text-sm text-secondary">{description}</p>+ </div>+ )+}++function ModalFooter({ left, children }: { left?: ReactNode; children: ReactNode }): JSX.Element {+ return (+ <footer className="flex shrink-0 items-center justify-between gap-3 border-t border-primary p-4">+ <div className="min-w-0">{left}</div>+ <div className="flex gap-2 shrink-0">{children}</div>+ </footer>+ )+}++function PasteStep(): JSX.Element {+ const { rawText, hasParsedOwners, unmatchedCount, parseErrors } = useValues(codeOwnersModalLogic)+ const { closeModal, setRawText, goToConfigure } = useActions(codeOwnersModalLogic)+ const hasParseErrors = parseErrors.length > 0++ return (+ <>+ <ModalHeader+ title="Create assignment rules from code owners"+ description="Paste your code owners file. Each owner becomes one assignment rule for exceptions whose source files match its paths."+ />+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">+ <CodeEditor+ className="border rounded"+ language="codeowners"+ value={rawText}+ onChange={(value) => setRawText(value ?? '')}+ height={420}+ options={{+ placeholder: CODE_OWNERS_PLACEHOLDER,+ minimap: { enabled: false },+ scrollBeyondLastLine: false,+ wordWrap: 'on',+ lineNumbers: 'on',+ folding: false,+ lineDecorationsWidth: 8,+ lineNumbersMinChars: 2,+ fontSize: 12,+ renderLineHighlight: 'none',+ }}+ />+ </div>+ <ModalFooter+ left={+ <div className="flex flex-col gap-0.5 text-xs text-warning text-left max-h-16 overflow-auto">+ {parseErrors.slice(0, 4).map((error) => (+ <span key={error.line}>+ L{error.line}: {error.reason}+ </span>+ ))}+ {parseErrors.length > 4 && <span>+{parseErrors.length - 4} more</span>}+ </div>+ }+ >+ <Button variant="outline" onClick={closeModal}>+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={goToConfigure}+ disabled={!hasParsedOwners || hasParseErrors}+ title={+ hasParseErrors+ ? 'Fix code owners parsing errors before continuing'+ : hasParsedOwners+ ? undefined+ : 'Paste at least one code owner line'+ }+ >+ {unmatchedCount > 0+ ? `Map ${unmatchedCount} unresolved owner${unmatchedCount === 1 ? '' : 's'}`+ : 'Review mappings'}+ </Button>+ </ModalFooter>+ </>+ )+}++function ConfigureStep(): JSX.Element {+ const { mappingUnresolvedCount } = useValues(codeOwnersModalLogic)+ const { goToImpact, backToPaste } = useActions(codeOwnersModalLogic)++ return (+ <>+ <ModalHeader+ title="Map unresolved code owners"+ description="Match unresolved owners to a PostHog role or user."+ />+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">+ <CodeOwnersConfigureTable />+ </div>+ <ModalFooter+ left={+ mappingUnresolvedCount > 0 ? (+ <span className="text-xs text-warning">+ {mappingUnresolvedCount} owner{mappingUnresolvedCount === 1 ? '' : 's'} still need a PostHog+ mapping.+ </span>+ ) : (+ <span className="text-xs text-success">All owners are mapped.</span>+ )+ }+ >+ <Button variant="outline" onClick={backToPaste}>+ Back+ </Button>+ <Button+ variant="primary"+ onClick={goToImpact}+ disabled={mappingUnresolvedCount > 0}+ title={+ mappingUnresolvedCount > 0 ? 'Map every unresolved owner before reviewing impact' : undefined+ }+ >+ Review impact+ </Button>+ </ModalFooter>+ </>+ )+}++function ImpactWindowSelect(): JSX.Element {+ const { dateRange } = useValues(codeOwnersModalLogic)+ const { setDateRange } = useActions(codeOwnersModalLogic)++ return (+ <Select value={dateRange} onValueChange={(value) => value && setDateRange(value)}>+ <SelectTrigger id="codeowners-impact-window">+ <SelectValue>{(value: string) => DATE_RANGE_LABELS[value] ?? value}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {Object.entries(DATE_RANGE_LABELS).map(([value, label]) => (+ <SelectItem key={value} value={value}>+ {label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++function ImpactStep(): JSX.Element {+ const { savableRows, savingLoading } = useValues(codeOwnersModalLogic)+ const { backToMapping, saveAll } = useActions(codeOwnersModalLogic)++ return (+ <>+ <ModalHeader+ title="Review assignment rule impact"+ description="Impact is grouped by the PostHog role or user that will receive the generated assignment rules."+ />+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">+ <CodeOwnersImpactTable />+ </div>+ <ModalFooter left={<ImpactWindowSelect />}>+ <Button variant="outline" onClick={backToMapping}>+ Back+ </Button>+ <Button+ variant="primary"+ onClick={saveAll}+ loading={savingLoading}+ disabled={savableRows.length === 0}+ title={savableRows.length === 0 ? 'No rules with an assignee to save' : undefined}+ >+ Save {savableRows.length} {savableRows.length === 1 ? 'rule' : 'rules'}+ </Button>+ </ModalFooter>+ </>+ )+}++export function CodeOwnersModal(): JSX.Element {+ const { isOpen, step } = useValues(codeOwnersModalLogic)+ const { closeModal } = useActions(codeOwnersModalLogic)++ return (+ <Dialog open={isOpen} onOpenChange={(open) => !open && closeModal()}>+ <DialogContent size="wide" className={BASE_MODAL_CLASS}>+ {step === 'paste' && <PasteStep />}+ {step === 'configure' && <ConfigureStep />}+ {step === 'impact' && <ImpactStep />}+ </DialogContent>+ </Dialog>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.test.tsnew file mode 100644index 000000000000..e068c4c586ee--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.test.ts@@ -0,0 +1,176 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'+import { RoleType } from '~/types'++import { rulesLogic } from '../rules/rulesLogic'+import { ErrorTrackingRuleType } from '../rules/types'+import { codeOwnersModalLogic } from './codeOwnersModalLogic'++function role(id: string, name: string): RoleType {+ return { id, name } as RoleType+}++describe('codeOwnersModalLogic', () => {+ let logic: ReturnType<typeof codeOwnersModalLogic.build>+ let assignmentRulesLogic: ReturnType<typeof rulesLogic.build>+ let createRuleSpy: jest.SpyInstance+ let loadRulesSpy: jest.SpyInstance++ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api.roles, 'list').mockResolvedValue({ results: [role('error-tracking', 'Error tracking')] } as any)+ jest.spyOn(api.organizationMembers, 'listAll').mockResolvedValue([] as any)+ jest.spyOn(api, 'query').mockResolvedValue({ results: [[3, 2]] } as any)+ loadRulesSpy = jest.spyOn(api.errorTracking, 'rules').mockResolvedValue({ results: [] } as any)+ createRuleSpy = jest.spyOn(api.errorTracking, 'createRule').mockResolvedValue({ id: 'new-rule' } as any)+ jest.spyOn(lemonToast, 'warning').mockImplementation(jest.fn())+ jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())++ assignmentRulesLogic = rulesLogic({ ruleType: ErrorTrackingRuleType.Assignment })+ assignmentRulesLogic.mount()+ logic = codeOwnersModalLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ assignmentRulesLogic.unmount()+ resumeKeaLoadersErrors()+ jest.restoreAllMocks()+ })++ it('derives parsed owners and concise parse errors from raw text', async () => {+ await expectLogic(logic, () => {+ logic.actions.setRawText(['frontend/** @posthog/frontend', 'backend/**'].join('\n'))+ }).toMatchValues({+ parsedOwners: [{ owner: '@posthog/frontend', patterns: ['frontend/**'], index: 0 }],+ parseErrors: [{ line: 2, reason: 'Missing owner' }],+ hasParsedOwners: true,+ })+ })++ it('loads assignable roles and users when opened and resets modal state', async () => {+ await expectLogic(logic, () => {+ logic.actions.setRawText('frontend/** @posthog/frontend')+ logic.actions.setOwnerAssignee('@posthog/frontend', { type: 'role', id: 'frontend' })+ logic.actions.openModal()+ })+ .toFinishAllListeners()+ .toMatchValues({+ isOpen: true,+ step: 'paste',+ rawText: '',+ assigneeOverrides: {},+ matchResults: {},+ })++ expect(api.roles.list).toHaveBeenCalled()+ expect(api.organizationMembers.listAll).toHaveBeenCalled()+ })++ it('freezes owners to map when entering the mapping step', async () => {+ await expectLogic(logic, () => {+ logic.actions.setRawText('a/** @team/backend\nb/** @team/backend\nc/** @team/frontend')+ logic.actions.goToConfigure()+ })+ .toFinishAllListeners()+ .toMatchValues({+ step: 'configure',+ ownersToMap: ['@team/backend', '@team/backend', '@team/frontend'],+ mappingRows: expect.arrayContaining([+ expect.objectContaining({ owner: '@team/backend', patterns: ['a/**', 'b/**'] }),+ expect.objectContaining({ owner: '@team/frontend', patterns: ['c/**'] }),+ ]),+ })+ })++ it('keeps manual assignee picks over automatic matches', async () => {+ await expectLogic(logic, () => {+ logic.actions.setRawText('a/** @posthog/error-tracking')+ logic.actions.setOwnerAssignee('@posthog/error-tracking', { type: 'user', id: 123 })+ }).toMatchValues({+ ownerRows: [+ expect.objectContaining({+ owner: '@posthog/error-tracking',+ assignee: { type: 'user', id: 123 },+ }),+ ],+ })+ })++ it('retests impact when the date range changes on the impact step', async () => {+ await expectLogic(logic, () => {+ logic.actions.setRawText('a/** @team/backend')+ logic.actions.setOwnerAssignee('@team/backend', { type: 'role', id: 'backend' })+ logic.actions.goToImpact()+ }).toFinishAllListeners()++ jest.mocked(api.query).mockClear()++ await expectLogic(logic, () => {+ logic.actions.setDateRange('-30d')+ }).toFinishAllListeners()++ expect(api.query).toHaveBeenCalledWith(expect.objectContaining({ after: '-30d' }))+ })++ it('saves all generated assignment rules and reloads rules on success', async () => {+ await expectLogic(logic, () => {+ logic.actions.openModal()+ logic.actions.setRawText('a/** @team/backend')+ logic.actions.setOwnerAssignee('@team/backend', { type: 'role', id: 'backend' })+ logic.actions.saveAll()+ })+ .toFinishAllListeners()+ .toMatchValues({ isOpen: false, savingLoading: false })++ expect(createRuleSpy).toHaveBeenCalledWith(+ ErrorTrackingRuleType.Assignment,+ expect.objectContaining({ assignee: { type: 'role', id: 'backend' } })+ )+ expect(loadRulesSpy).toHaveBeenCalledWith(ErrorTrackingRuleType.Assignment)+ })++ it('reports partial save failures while keeping successful creates', async () => {+ createRuleSpy.mockReset()+ createRuleSpy.mockResolvedValueOnce({ id: 'created' } as any).mockRejectedValueOnce(new Error('nope'))++ await expectLogic(logic, () => {+ logic.actions.openModal()+ logic.actions.setRawText('a/** @team/backend\nb/** @team/frontend')+ logic.actions.setOwnerAssignee('@team/backend', { type: 'role', id: 'backend' })+ logic.actions.setOwnerAssignee('@team/frontend', { type: 'role', id: 'frontend' })+ logic.actions.saveAll()+ })+ .toFinishAllListeners()+ .toMatchValues({ isOpen: false, savingLoading: false })++ expect(createRuleSpy).toHaveBeenCalledTimes(2)+ expect(loadRulesSpy).toHaveBeenCalledWith(ErrorTrackingRuleType.Assignment)+ expect(lemonToast.warning).toHaveBeenCalledWith('Created 1 of 2 assignment rules. 1 failed.')+ expect(lemonToast.error).not.toHaveBeenCalled()+ })++ it('reloads rules and shows an error when every create fails', async () => {+ silenceKeaLoadersErrors()+ createRuleSpy.mockReset()+ createRuleSpy.mockRejectedValue(new Error('nope'))++ await expectLogic(logic, () => {+ logic.actions.setRawText('a/** @team/backend')+ logic.actions.setOwnerAssignee('@team/backend', { type: 'role', id: 'backend' })+ logic.actions.saveAll()+ })+ .toFinishAllListeners()+ .toMatchValues({ savingLoading: false })++ expect(loadRulesSpy).toHaveBeenCalledWith(ErrorTrackingRuleType.Assignment)+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to save assignment rules')+ })+})diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.tsnew file mode 100644index 000000000000..83c30ed90d16--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeOwnersModalLogic.ts@@ -0,0 +1,226 @@+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { organizationLogic } from 'scenes/organizationLogic'+import { rolesLogic } from 'scenes/settings/organization/Permissions/Roles/rolesLogic'++import { ErrorTrackingIssueAssignee, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { AnyPropertyFilter, OrganizationMemberType, RoleType } from '~/types'++import { assigneeSelectLogic } from '../../../components/Assignee/assigneeSelectLogic'+import { rulesLogic } from '../rules/rulesLogic'+import { ErrorTrackingAssignmentRule, ErrorTrackingRuleType } from '../rules/types'+import { CodeownersError, OwnerGroup, entriesByOwner, findCodeownersErrors, parseCodeowners } from './codeowners'+import {+ CodeOwnerOwnerMapping,+ CodeOwnerRuleCandidate,+ buildMappingRows,+ buildOwnerFilters,+ buildOwnerRows,+ buildSavableRows,+} from './codeownersImport'+import type { codeOwnersModalLogicType } from './codeOwnersModalLogicType'++export type MatchCount = { exceptionCount: number; issueCount: number }+export type SaveAllResult = { createdCount: number; failedCount: number; totalCount: number }+export type CodeOwnerEntryRow = CodeOwnerRuleCandidate+export type CodeOwnerMappingRow = CodeOwnerOwnerMapping++export const codeOwnersModalLogic = kea<codeOwnersModalLogicType>([+ path([+ 'products',+ 'error_tracking',+ 'scenes',+ 'ErrorTrackingConfigurationScene',+ 'assignment_rules',+ 'codeOwnersModalLogic',+ ]),++ connect(() => ({+ values: [+ rolesLogic,+ ['roles'],+ assigneeSelectLogic,+ ['meFirstMembers'],+ organizationLogic,+ ['currentOrganization'],+ ],+ actions: [rolesLogic, ['loadRoles'], assigneeSelectLogic, ['ensureAssigneeTypesLoaded']],+ })),++ actions({+ openModal: true,+ closeModal: true,+ setRawText: (rawText: string) => ({ rawText }),+ setOwnerAssignee: (owner: string, assignee: ErrorTrackingIssueAssignee | null) => ({ owner, assignee }),+ setOwnersToMap: (owners: string[]) => ({ owners }),+ goToConfigure: true,+ goToImpact: true,+ backToMapping: true,+ backToPaste: true,+ setDateRange: (dateRange: string) => ({ dateRange }),+ }),++ reducers({+ isOpen: [false, { openModal: () => true, closeModal: () => false }],+ step: [+ 'paste' as 'paste' | 'configure' | 'impact',+ {+ openModal: () => 'paste',+ goToConfigure: () => 'configure',+ goToImpact: () => 'impact',+ backToMapping: () => 'configure',+ backToPaste: () => 'paste',+ },+ ],+ rawText: ['', { setRawText: (_, { rawText }) => rawText, openModal: () => '' }],+ // Manual assignee picks keyed by owner; presence of the key overrides the auto-match (null = cleared).+ assigneeOverrides: [+ {} as Record<string, ErrorTrackingIssueAssignee | null>,+ {+ setOwnerAssignee: (state, { owner, assignee }) => ({ ...state, [owner]: assignee }),+ openModal: () => ({}),+ },+ ],+ ownersToMap: [+ [] as string[],+ {+ setOwnersToMap: (_, { owners }) => owners,+ openModal: () => [],+ backToPaste: () => [],+ },+ ],+ dateRange: ['-7d' as string, { setDateRange: (_, { dateRange }) => dateRange, openModal: () => '-7d' }],+ }),++ loaders(({ values }) => ({+ matchResults: [+ {} as Record<string, MatchCount | null>,+ {+ resetMatchResults: () => ({}),+ testMatches: async () => {+ const results: Record<string, MatchCount | null> = {}+ await Promise.all(+ values.savableRows.map(async (row) => {+ const filters = buildOwnerFilters(row.patterns)+ const properties = filters.values as AnyPropertyFilter[]+ if (properties.length === 0) {+ results[row.entryId] = null+ return+ }+ const response = (await api.query({+ kind: NodeKind.EventsQuery,+ event: '$exception',+ select: ['count()', 'count(distinct properties.$exception_issue_id)'],+ after: values.dateRange,+ fixedProperties: [{ type: filters.type, values: properties }],+ tags: { productKey: ProductKey.ERROR_TRACKING },+ } as Record<string, any>)) as Record<string, any>+ results[row.entryId] = {+ exceptionCount: response.results?.[0]?.[0] ?? 0,+ issueCount: response.results?.[0]?.[1] ?? 0,+ }+ })+ )+ return results+ },+ },+ ],+ saving: [+ { createdCount: 0, failedCount: 0, totalCount: 0 } as SaveAllResult,+ {+ saveAll: async (): Promise<SaveAllResult> => {+ const rows = values.savableRows+ const results = await Promise.allSettled(+ rows.map((row, index) => {+ const rule: ErrorTrackingAssignmentRule = {+ id: 'new',+ filters: buildOwnerFilters(row.patterns),+ assignee: row.assignee,+ disabled_data: null,+ // Later code owner entries win: rules are first-match by ascending order_key,+ // so the last owner gets the lowest key.+ order_key: rows.length - 1 - index,+ }+ return api.errorTracking.createRule(ErrorTrackingRuleType.Assignment, rule)+ })+ )+ const failedCount = results.filter((result) => result.status === 'rejected').length+ const createdCount = results.length - failedCount+ if (createdCount === 0 && failedCount > 0) {+ throw new Error('Failed to save assignment rules')+ }+ return { createdCount, failedCount, totalCount: rows.length }+ },+ },+ ],+ })),++ listeners(({ actions, values }) => ({+ openModal: () => {+ actions.loadRoles()+ actions.ensureAssigneeTypesLoaded()+ actions.resetMatchResults()+ },+ goToConfigure: () => {+ actions.setOwnersToMap(values.ownerRows.map((row) => row.owner))+ actions.testMatches()+ },+ setDateRange: () => {+ if (values.step === 'impact') {+ actions.testMatches()+ }+ },+ goToImpact: () => {+ actions.testMatches()+ },+ saveAllSuccess: ({ saving }) => {+ actions.closeModal()+ rulesLogic({ ruleType: ErrorTrackingRuleType.Assignment }).actions.loadRules()+ if (saving.failedCount > 0) {+ lemonToast.warning(+ `Created ${saving.createdCount} of ${saving.totalCount} assignment rules. ${saving.failedCount} failed.`+ )+ }+ },+ saveAllFailure: () => {+ rulesLogic({ ruleType: ErrorTrackingRuleType.Assignment }).actions.loadRules()+ lemonToast.error('Failed to save assignment rules')+ },+ })),++ selectors({+ parsedOwners: [(s) => [s.rawText], (rawText: string): OwnerGroup[] => entriesByOwner(parseCodeowners(rawText))],+ ownerRows: [+ (s) => [s.parsedOwners, s.roles, s.meFirstMembers, s.assigneeOverrides],+ (+ parsedOwners: OwnerGroup[],+ roles: RoleType[],+ meFirstMembers: OrganizationMemberType[],+ assigneeOverrides: Record<string, ErrorTrackingIssueAssignee | null>+ ): CodeOwnerRuleCandidate[] => buildOwnerRows(parsedOwners, roles, meFirstMembers, assigneeOverrides),+ ],+ savableRows: [+ (s) => [s.ownerRows],+ (rows: CodeOwnerRuleCandidate[]): CodeOwnerRuleCandidate[] => buildSavableRows(rows),+ ],+ mappingRows: [+ (s) => [s.ownerRows, s.ownersToMap],+ (rows: CodeOwnerRuleCandidate[], ownersToMap: string[]): CodeOwnerOwnerMapping[] =>+ buildMappingRows(rows, ownersToMap),+ ],+ hasParsedOwners: [(s) => [s.parsedOwners], (owners: OwnerGroup[]): boolean => owners.length > 0],+ parseErrors: [(s) => [s.rawText], (rawText: string): CodeownersError[] => findCodeownersErrors(rawText)],+ unmatchedCount: [+ (s) => [s.ownerRows],+ (rows: CodeOwnerRuleCandidate[]): number => rows.filter((r) => r.assignee === null).length,+ ],+ mappingUnresolvedCount: [+ (s) => [s.mappingRows],+ (rows: CodeOwnerOwnerMapping[]): number => rows.filter((r) => r.assignee === null).length,+ ],+ }),+])diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.test.tsnew file mode 100644index 000000000000..4942ef3ce84c--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.test.ts@@ -0,0 +1,279 @@+import { ErrorTrackingIssueAssignee } from '~/queries/schema/schema-general'+import {+ AnyPropertyFilter,+ FilterLogicalOperator,+ OrganizationMemberType,+ PropertyFilterType,+ PropertyOperator,+ RoleType,+} from '~/types'++import { matchingExceptionsUrl, matchingIssuesUrl } from '../rules/ruleMatchUrls'+import {+ bestAssigneeMatch,+ entriesByOwner,+ findCodeownersErrors,+ longestCommonSubstringLength,+ ownerMatchFragments,+ patternToSourceMatch,+ parseCodeowners,+ patternToSourceValue,+} from './codeowners'+import { buildImpactRows } from './codeownersImpact'+import { CodeOwnerRuleCandidate, buildMappingRows, buildOwnerFilters, buildSavableRows } from './codeownersImport'+import { exceptionsUrl as codeOwnersExceptionsUrl, issuesUrl as codeOwnersIssuesUrl } from './codeownersUrls'++function makeRole(name: string): RoleType {+ return { id: name.toLowerCase(), name } as RoleType+}++function makeMember(firstName: string, email: string, id: number = 1): OrganizationMemberType {+ return { user: { id, first_name: firstName, email } } as OrganizationMemberType+}++function candidate(+ owner: string,+ assignee: ErrorTrackingIssueAssignee | null,+ patterns: string[],+ orderIndex: number+): CodeOwnerRuleCandidate {+ return {+ entryId: `${orderIndex}:${owner}`,+ orderIndex,+ owner,+ patterns,+ matchFragments: ownerMatchFragments(patterns),+ assignee,+ }+}++describe('codeowners helpers', () => {+ describe('parseCodeowners', () => {+ it('parses patterns and owners, skipping comments and blank lines', () => {+ const text = [+ '# Comment line',+ '',+ 'products/error_tracking/** @posthog/error-tracking',+ 'frontend/ @posthog/frontend @alice',+ ' # indented comment',+ 'no-owners-here',+ ].join('\n')++ expect(parseCodeowners(text)).toEqual([+ { pattern: 'products/error_tracking/**', owners: ['@posthog/error-tracking'] },+ { pattern: 'frontend/', owners: ['@posthog/frontend', '@alice'] },+ ])+ })++ it('returns nothing for empty or comment-only input', () => {+ expect(parseCodeowners('')).toEqual([])+ expect(parseCodeowners('# just a comment\n\n')).toEqual([])+ })+ })++ describe('entriesByOwner', () => {+ it('preserves owner entries in source order', () => {+ const entries = parseCodeowners(['a/** @team-x', 'b/** @team-y @team-x', 'a/** @team-x'].join('\n'))++ expect(entriesByOwner(entries)).toEqual([+ { owner: '@team-x', patterns: ['a/**'], index: 0 },+ { owner: '@team-y', patterns: ['b/**'], index: 1 },+ { owner: '@team-x', patterns: ['b/**'], index: 2 },+ { owner: '@team-x', patterns: ['a/**'], index: 3 },+ ])+ })+ })++ describe('patternToSourceValue', () => {+ it.each([+ ['products/error_tracking/**', 'products/error_tracking'],+ ['/frontend/', 'frontend'],+ ['docs/*', 'docs'],+ ['*.py', '.py'],+ ['**/*.tsx', '.tsx'],+ ['src/components/Button.tsx', 'src/components/Button.tsx'],+ ['*', ''],+ ])('translates %s to %s', (pattern, expected) => {+ expect(patternToSourceValue(pattern)).toBe(expected)+ })+ })++ describe('patternToSourceMatch', () => {+ it.each([+ ['products/error_tracking/**', { operator: 'regex', value: '(^|/)products/error_tracking/.*' }],+ ['frontend/*.tsx', { operator: 'regex', value: '(^|/)frontend/[^/]*\\.tsx' }],+ ['nodejs/src/cdp/', { operator: 'icontains', value: 'nodejs/src/cdp' }],+ ])('translates %s to a source match', (pattern, expected) => {+ expect(patternToSourceMatch(pattern)).toEqual(expected)+ })+ })++ describe('longestCommonSubstringLength', () => {+ it.each([+ ['', '', 0],+ ['abc', '', 0],+ ['', 'abc', 0],+ ['error tracking', 'error tracking', 14],+ ['error tracking', 'product analytics', 2],+ ])('longest common substring length for %s and %s is %i', (a, b, expected) => {+ expect(longestCommonSubstringLength(a, b)).toBe(expected)+ })+ })++ describe('bestAssigneeMatch', () => {+ const roles = [makeRole('Frontend'), makeRole('Backend Team'), makeRole('Error Tracking')]+ const members = [+ makeMember('Alice Example', '[email protected]'),+ makeMember('Max Backend', '[email protected]', 2),+ ]++ it('matches roles by longest common substring', () => {+ expect(bestAssigneeMatch('@posthog/error-tracking', roles, members)).toMatchObject({+ type: 'role',+ role: { name: 'Error Tracking' },+ })+ })++ it('matches users by name or email local part', () => {+ expect(bestAssigneeMatch('@alice', roles, members)).toMatchObject({+ type: 'user',+ user: { email: '[email protected]' },+ })+ })++ it('does not fuzzy match short owner tokens', () => {+ expect(bestAssigneeMatch('@dev', [makeRole('Developer experience')], [])).toBeNull()+ })+ })++ describe('ownerMatchFragments', () => {+ it('de-dupes and drops empty fragments', () => {+ expect(ownerMatchFragments(['products/error_tracking/**', 'products/error_tracking/api', '*'])).toEqual([+ '(^|/)products/error_tracking/.*',+ 'products/error_tracking/api',+ ])+ })+ })++ describe('buildSavableRows', () => {+ it('merges candidates by assignee and keeps source order precedence', () => {+ const assignee = { type: 'role' as const, id: 'error-tracking' }+ const rows = [+ candidate('@team/error-tracking', assignee, ['a/**'], 0),+ candidate('@team/error-tracking-oncall', assignee, ['b/**'], 2),+ candidate('@unmapped', null, ['c/**'], 3),+ candidate('@empty', { type: 'user' as const, id: 1 }, ['*'], 4),+ ]++ expect(buildSavableRows(rows)).toMatchObject([+ {+ owner: '@team/error-tracking, @team/error-tracking-oncall',+ orderIndex: 2,+ patterns: ['a/**', 'b/**'],+ assignee,+ },+ ])+ })+ })++ describe('buildMappingRows', () => {+ it('dedupes owners while keeping all patterns', () => {+ const rows = [+ candidate('@team/error-tracking', null, ['a/**'], 0),+ candidate('@team/frontend', null, ['b/**'], 1),+ candidate('@team/error-tracking', null, ['c/**'], 2),+ ]++ expect(buildMappingRows(rows, ['@team/error-tracking'])).toMatchObject([+ { owner: '@team/error-tracking', patterns: ['a/**', 'c/**'] },+ ])+ })+ })++ describe('buildImpactRows', () => {+ it('groups counts by resolved assignee', () => {+ const assignee = { type: 'role' as const, id: 'error-tracking' }+ const rows = [+ candidate('@team/error-tracking', assignee, ['a/**'], 0),+ candidate('@oncall', assignee, ['b/**'], 1),+ ]+ const role = makeRole('Error tracking')++ expect(+ buildImpactRows(+ rows,+ {+ '0:@team/error-tracking': { exceptionCount: 2, issueCount: 1 },+ '1:@oncall': { exceptionCount: 3, issueCount: 2 },+ },+ () => ({ id: role.id, type: 'role', role })+ )+ ).toEqual([+ {+ key: 'role:error-tracking',+ label: 'Error tracking',+ exceptionCount: 5,+ issueCount: 3,+ patterns: ['a/**', 'b/**'],+ },+ ])+ })+ })++ describe('rule match URLs', () => {+ const browserFilter: AnyPropertyFilter = {+ key: '$browser',+ value: ['Firefox'],+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ }++ it('builds exception and issue links for normal rule filters', () => {+ const exceptionsUrl = decodeURIComponent(matchingExceptionsUrl([browserFilter], '-30d'))+ const issuesUrl = decodeURIComponent(matchingIssuesUrl([browserFilter], FilterLogicalOperator.And, '-30d'))++ expect(exceptionsUrl).toContain('$exception')+ expect(exceptionsUrl).toContain('timestamp DESC')+ expect(exceptionsUrl).toContain('-30d')+ expect(issuesUrl).toContain('filterGroup')+ expect(issuesUrl).toContain('"date_from":"-30d"')+ })++ it('uses the same rule match URL helpers for code owners impact links', () => {+ const patterns = ['products/error_tracking/**']+ const filters = buildOwnerFilters(patterns)++ expect(codeOwnersExceptionsUrl(patterns, '-90d')).toEqual(+ matchingExceptionsUrl(filters.values as AnyPropertyFilter[], '-90d')+ )+ expect(codeOwnersIssuesUrl(patterns, '-90d')).toEqual(+ matchingIssuesUrl(filters.values as AnyPropertyFilter[], filters.type, '-90d')+ )+ })+ })++ describe('findCodeownersErrors', () => {+ it('flags lines with no owner and invalid owner tokens, with 1-based line numbers', () => {+ const text = [+ '# comment',+ 'products/error_tracking/** @posthog/error-tracking',+ 'frontend/**',+ 'docs/* not-a-handle [email protected]',+ ].join('\n')++ expect(findCodeownersErrors(text)).toEqual([+ { line: 3, reason: 'Missing owner' },+ { line: 4, reason: 'Invalid owner' },+ ])+ })++ it('returns no errors for valid input', () => {+ expect(findCodeownersErrors('a/** @team\nb/** @user [email protected]')).toEqual([])+ })++ it('skips section headers', () => {+ expect(findCodeownersErrors('[Backend]\na/** @team')).toEqual([])+ expect(parseCodeowners('[Backend]\na/** @team')).toEqual([{ pattern: 'a/**', owners: ['@team'] }])+ })+ })+})diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.tsnew file mode 100644index 000000000000..d9ff81136e4f--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeowners.ts@@ -0,0 +1,3 @@+export * from './codeownersMatching'+export * from './codeownersParsing'+export * from './codeownersPaths'diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImpact.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImpact.tsnew file mode 100644index 000000000000..e0626ea8b5c1--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImpact.ts@@ -0,0 +1,57 @@+import { Assignee } from '../../../components/Assignee/assigneeSelectLogic'+import { CodeOwnerRuleCandidate } from './codeownersImport'+import { MatchCount } from './codeOwnersModalLogic'++export interface CodeOwnersImpactRow {+ key: string+ label: string+ exceptionCount: number+ issueCount: number+ patterns: string[]+}++function assigneeKey(assignee: NonNullable<CodeOwnerRuleCandidate['assignee']>): string {+ return assignee.type === 'role' ? `role:${assignee.id}` : `user:${assignee.id}`+}++function assigneeLabel(assignee: Assignee): string {+ if (!assignee) {+ return 'Assign…'+ }+ return assignee.type === 'role' ? assignee.role.name : assignee.user.first_name || assignee.user.email+}++export function buildImpactRows(+ savableRows: CodeOwnerRuleCandidate[],+ matchResults: Record<string, MatchCount | null>,+ resolveAssignee: (assignee: CodeOwnerRuleCandidate['assignee']) => Assignee+): CodeOwnersImpactRow[] {+ const groups = new Map<string, CodeOwnersImpactRow>()++ for (const row of savableRows) {+ if (!row.assignee) {+ continue+ }++ const resolved = resolveAssignee(row.assignee)+ if (!resolved) {+ continue+ }++ const key = assigneeKey(row.assignee)+ const existing = groups.get(key) ?? {+ key,+ label: assigneeLabel(resolved),+ exceptionCount: 0,+ issueCount: 0,+ patterns: [],+ }+ const count = matchResults[row.entryId]+ existing.exceptionCount += count?.exceptionCount ?? 0+ existing.issueCount += count?.issueCount ?? 0+ existing.patterns.push(...row.patterns)+ groups.set(key, existing)+ }++ return Array.from(groups.values())+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImport.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImport.tsnew file mode 100644index 000000000000..5d7b9471b3a2--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersImport.ts@@ -0,0 +1,125 @@+import { ErrorTrackingIssueAssignee } from '~/queries/schema/schema-general'+import {+ AnyPropertyFilter,+ FilterLogicalOperator,+ OrganizationMemberType,+ PropertyFilterType,+ PropertyOperator,+ RoleType,+ UniversalFiltersGroup,+} from '~/types'++import { bestAssigneeMatch, OwnerGroup, ownerMatchFragments, patternToSourceMatch } from './codeowners'++export interface CodeOwnerRuleCandidate {+ entryId: string+ orderIndex: number+ owner: string+ patterns: string[]+ matchFragments: string[]+ assignee: ErrorTrackingIssueAssignee | null+}++export interface CodeOwnerOwnerMapping {+ owner: string+ patterns: string[]+ matchFragments: string[]+ assignee: ErrorTrackingIssueAssignee | null+}++/** OR-group of `$exception_sources` filters, one per (de-duped, non-empty) owned path. */+export function buildOwnerFilters(patterns: string[]): UniversalFiltersGroup {+ const matches = patterns.map(patternToSourceMatch).filter((match) => match !== null)+ const values: AnyPropertyFilter[] = Array.from(+ new Map(matches.map((match) => [`${match.operator}:${match.value}`, match])).values()+ ).map((match) => ({+ key: '$exception_sources',+ type: PropertyFilterType.Event,+ operator: match.operator === 'regex' ? PropertyOperator.Regex : PropertyOperator.IContains,+ value: match.value,+ }))+ return { type: FilterLogicalOperator.Or, values }+}++export function buildOwnerRows(+ parsedOwners: OwnerGroup[],+ roles: RoleType[],+ meFirstMembers: OrganizationMemberType[],+ assigneeOverrides: Record<string, ErrorTrackingIssueAssignee | null>+): CodeOwnerRuleCandidate[] {+ return parsedOwners.map(({ owner, patterns, index }) => {+ const base = {+ entryId: `${index}:${owner}`,+ orderIndex: index,+ owner,+ patterns,+ matchFragments: ownerMatchFragments(patterns),+ }++ if (Object.prototype.hasOwnProperty.call(assigneeOverrides, owner)) {+ return { ...base, assignee: assigneeOverrides[owner] }+ }++ const match = bestAssigneeMatch(owner, roles, meFirstMembers)+ const assignee = match+ ? match.type === 'role'+ ? { type: 'role' as const, id: match.role.id }+ : { type: 'user' as const, id: match.user.id }+ : null+ return { ...base, assignee }+ })+}++export function buildSavableRows(rows: CodeOwnerRuleCandidate[]): CodeOwnerRuleCandidate[] {+ const rowsByAssignee = new Map<string, CodeOwnerRuleCandidate>()++ for (const row of rows) {+ if (row.assignee === null || buildOwnerFilters(row.patterns).values.length === 0) {+ continue+ }++ const key = `${row.assignee.type}:${row.assignee.id}`+ const existing = rowsByAssignee.get(key)+ if (!existing) {+ rowsByAssignee.set(key, { ...row, patterns: [...row.patterns], matchFragments: [...row.matchFragments] })+ continue+ }++ if (row.orderIndex > existing.orderIndex) {+ existing.orderIndex = row.orderIndex+ existing.entryId = row.entryId+ }+ existing.owner = existing.owner.includes(row.owner) ? existing.owner : `${existing.owner}, ${row.owner}`+ existing.patterns.push(...row.patterns)+ existing.matchFragments = ownerMatchFragments(existing.patterns)+ }++ return Array.from(rowsByAssignee.values()).sort((a, b) => a.orderIndex - b.orderIndex)+}++export function buildMappingRows(rows: CodeOwnerRuleCandidate[], mappingOwners: string[]): CodeOwnerOwnerMapping[] {+ const mappingOwnerSet = new Set(mappingOwners)+ const rowsByOwner = new Map<string, CodeOwnerOwnerMapping>()++ for (const row of rows) {+ if (!mappingOwnerSet.has(row.owner)) {+ continue+ }++ const existing = rowsByOwner.get(row.owner)+ if (existing) {+ existing.patterns.push(...row.patterns)+ existing.matchFragments = ownerMatchFragments(existing.patterns)+ continue+ }++ rowsByOwner.set(row.owner, {+ owner: row.owner,+ patterns: [...row.patterns],+ matchFragments: [...row.matchFragments],+ assignee: row.assignee,+ })+ }++ return Array.from(rowsByOwner.values())+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersMatching.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersMatching.tsnew file mode 100644index 000000000000..5fe91b99dd5a--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersMatching.ts@@ -0,0 +1,85 @@+import type { OrganizationMemberType, RoleType } from '~/types'++export type AssigneeMatch =+ | { type: 'role'; role: RoleType; score: number }+ | { type: 'user'; user: OrganizationMemberType['user']; score: number }++const MIN_FUZZY_OWNER_LENGTH = 5++function normalizeName(value: string): string {+ return value.toLowerCase().replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim()+}++function normalizeOwnerToken(owner: string): string {+ const withoutAt = owner.replace(/^@/, '')+ const lastSlash = withoutAt.lastIndexOf('/')+ return normalizeName(lastSlash >= 0 ? withoutAt.slice(lastSlash + 1) : withoutAt)+}++export function longestCommonSubstringLength(a: string, b: string): number {+ if (!a || !b) {+ return 0+ }++ let best = 0+ let previous = Array.from({ length: b.length + 1 }, () => 0)+ let current = Array.from({ length: b.length + 1 }, () => 0)++ for (let i = 1; i <= a.length; i++) {+ for (let j = 1; j <= b.length; j++) {+ current[j] = a[i - 1] === b[j - 1] ? previous[j - 1] + 1 : 0+ best = Math.max(best, current[j])+ }+ ;[previous, current] = [current, previous]+ current.fill(0)+ }++ return best+}++function commonSubstringScore(target: string, candidate: string): number {+ return longestCommonSubstringLength(target, candidate) / Math.max(Math.min(target.length, candidate.length), 1)+}++function scoreCandidate(target: string, candidate: string): number {+ const normalizedCandidate = normalizeName(candidate)+ if (target.length < MIN_FUZZY_OWNER_LENGTH && target !== normalizedCandidate) {+ return 0+ }+ return commonSubstringScore(target, normalizedCandidate)+}++function userNames(member: OrganizationMemberType): string[] {+ const { user } = member+ return [user.first_name, user.email.split('@')[0], user.email]+ .map((value) => normalizeName(value))+ .filter((value) => value.length > 0)+}++function roleMatch(target: string, role: RoleType): AssigneeMatch {+ return { type: 'role', role, score: scoreCandidate(target, role.name) }+}++function userMatch(target: string, member: OrganizationMemberType): AssigneeMatch {+ const score = Math.max(...userNames(member).map((name) => scoreCandidate(target, name)), 0)+ return { type: 'user', user: member.user, score }+}++export function bestAssigneeMatch(+ owner: string,+ roles: RoleType[],+ members: OrganizationMemberType[],+ threshold: number = 0.75+): AssigneeMatch | null {+ const target = normalizeOwnerToken(owner)+ const matches = [+ ...roles.map((role) => roleMatch(target, role)),+ ...members.map((member) => userMatch(target, member)),+ ]+ const best = matches.reduce<AssigneeMatch | null>(+ (best, match) => (!best || match.score > best.score ? match : best),+ null+ )+ const requiredScore = target.length < MIN_FUZZY_OWNER_LENGTH ? 1 : threshold+ return best && best.score >= requiredScore ? best : null+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersParsing.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersParsing.tsnew file mode 100644index 000000000000..7895064161f2--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersParsing.ts@@ -0,0 +1,75 @@+export interface CodeownersEntry {+ pattern: string+ owners: string[]+}++export interface OwnerGroup {+ owner: string+ patterns: string[]+ index: number+}++export interface CodeownersError {+ /** 1-based line number. */+ line: number+ reason: string+}++const OWNER_RE = /^@[A-Za-z0-9/_.-]+$/+const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/+const SECTION_HEADER_RE = /^\[[^\]]+\]$/++function isSkippableLine(line: string): boolean {+ return !line || line.startsWith('#') || SECTION_HEADER_RE.test(line)+}++/** Parse code owners-style text into (pattern, owners) entries. */+export function parseCodeowners(text: string): CodeownersEntry[] {+ const entries: CodeownersEntry[] = []+ for (const rawLine of text.split(/\r?\n/)) {+ const line = rawLine.trim()+ if (isSkippableLine(line)) {+ continue+ }++ const [pattern, ...owners] = line.split(/\s+/)+ if (pattern && owners.length > 0) {+ entries.push({ pattern, owners })+ }+ }+ return entries+}++/** Validate code owners-style text line by line. */+export function findCodeownersErrors(text: string): CodeownersError[] {+ const errors: CodeownersError[] = []+ text.split(/\r?\n/).forEach((rawLine, index) => {+ const line = rawLine.trim()+ if (isSkippableLine(line)) {+ return+ }++ const [, ...owners] = line.split(/\s+/)+ if (owners.length === 0) {+ errors.push({ line: index + 1, reason: 'Missing owner' })+ return+ }++ const invalid = owners.filter((owner) => !OWNER_RE.test(owner) && !EMAIL_RE.test(owner))+ if (invalid.length > 0) {+ errors.push({ line: index + 1, reason: 'Invalid owner' })+ }+ })+ return errors+}++/** Expand entries to one row per owner token, preserving source order. */+export function entriesByOwner(entries: CodeownersEntry[]): OwnerGroup[] {+ const groups: OwnerGroup[] = []+ for (const { pattern, owners } of entries) {+ for (const owner of owners) {+ groups.push({ owner, patterns: [pattern], index: groups.length })+ }+ }+ return groups+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersPaths.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersPaths.tsnew file mode 100644index 000000000000..7efaf498e153--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersPaths.ts@@ -0,0 +1,62 @@+export interface SourceMatch {+ operator: 'icontains' | 'regex'+ value: string+}++/**+ * Turn a code owners glob into a path fragment for an `icontains` match against `$exception_sources`.+ * Stack-frame source paths are often absolute or transformed, so we match a substring rather than+ * trying to honor full glob semantics. Extension-only patterns become their extension (`.py`, `.tsx`).+ */+export function patternToSourceValue(pattern: string): string {+ const trimmed = pattern.trim().replace(/^\/+/, '')+ const extMatch = trimmed.match(/(?:^|\/)\*+(\.[A-Za-z0-9.]+)$/)+ if (extMatch) {+ return extMatch[1]+ }+ return trimmed+ .replace(/\*+/g, '')+ .replace(/\/{2,}/g, '/')+ .replace(/^\/+|\/+$/g, '')+}++function escapeRegex(value: string): string {+ return value.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')+}++export function isGlobPattern(pattern: string): boolean {+ return /[*?[]/.test(pattern)+}++export function globPatternToRegex(pattern: string): string {+ const trimmed = pattern.trim().replace(/^\/+/, '')+ if (!trimmed || /^\*+$/.test(trimmed)) {+ return ''+ }++ let regex = '(^|/)'+ for (let i = 0; i < trimmed.length; i++) {+ const char = trimmed[i]+ const nextChar = trimmed[i + 1]+ if (char === '*' && nextChar === '*') {+ regex += '.*'+ i+++ } else if (char === '*') {+ regex += '[^/]*'+ } else if (char === '?') {+ regex += '[^/]'+ } else {+ regex += escapeRegex(char)+ }+ }+ return regex+}++export function patternToSourceMatch(pattern: string): SourceMatch | null {+ const value = isGlobPattern(pattern) ? globPatternToRegex(pattern) : patternToSourceValue(pattern)+ return value ? { operator: isGlobPattern(pattern) ? 'regex' : 'icontains', value } : null+}++export function ownerMatchFragments(patterns: string[]): string[] {+ return Array.from(new Set(patterns.map((pattern) => patternToSourceMatch(pattern)?.value ?? ''))).filter(Boolean)+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersUrls.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersUrls.tsnew file mode 100644index 000000000000..fe26cf3968fb--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/codeownersUrls.ts@@ -0,0 +1,14 @@+import { AnyPropertyFilter } from '~/types'++import { matchingExceptionsUrl, matchingIssuesUrl } from '../rules/ruleMatchUrls'+import { buildOwnerFilters } from './codeownersImport'++export function exceptionsUrl(patterns: string[], dateRange: string): string {+ const filters = buildOwnerFilters(patterns)+ return matchingExceptionsUrl(filters.values as AnyPropertyFilter[], dateRange)+}++export function issuesUrl(patterns: string[], dateRange: string): string {+ const filters = buildOwnerFilters(patterns)+ return matchingIssuesUrl(filters.values as AnyPropertyFilter[], filters.type, dateRange)+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/MatchResultBanner.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/MatchResultBanner.tsxindex 5c26fee1e8f8..a389cfe4dd36 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/MatchResultBanner.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/MatchResultBanner.tsx@@ -1,12 +1,8 @@-import { combineUrl } from 'kea-router'-import { LemonButton, Link } from '@posthog/lemon-ui'-import { urls } from 'scenes/urls'+import { AnyPropertyFilter, FilterLogicalOperator } from '~/types'-import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'-import { NodeKind, ProductKey } from '~/queries/schema/schema-general'-import { ActivityTab, AnyPropertyFilter, FilterLogicalOperator } from '~/types'+import { matchingExceptionsUrl, matchingIssuesUrl } from './ruleMatchUrls'const DATE_RANGE_LABELS: Record<string, string> = {'-7d': '7 days',@@ -52,32 +48,8 @@ export function MatchResultBanner({)}- const issuesUrl = urls.errorTracking({- filterGroup: { type: filterType, values: [{ type: filterType, values: properties }] },- dateRange: { date_from: dateRange, date_to: null },- })-- const exceptionsUrl = combineUrl(- urls.activity(ActivityTab.ExploreEvents),- {},- {- q: {- kind: NodeKind.DataTableNode,- full: true,- source: {- kind: NodeKind.EventsQuery,- select: defaultDataTableColumns(NodeKind.EventsQuery),- orderBy: ['timestamp DESC'],- after: dateRange,- event: '$exception',- properties,- tags: { productKey: ProductKey.ERROR_TRACKING },- },- propertiesViaUrl: true,- showPersistentColumnConfigurator: true,- },- }- ).url+ const issuesUrl = matchingIssuesUrl(properties, filterType, dateRange)+ const exceptionsUrl = matchingExceptionsUrl(properties, dateRange)const issuesLink = (<Link to={`${window.location.origin}${issuesUrl}`} target="_blank" targetBlankIcon={false}>diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleList.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleList.tsxindex dbd679eecb54..abc95af7b1e9 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleList.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleList.tsx@@ -4,8 +4,8 @@ import { SortableContext, arrayMove, verticalListSortingStrategy } from '@dnd-kiimport { useActions, useValues } from 'kea'import { ReactNode, useEffect } from 'react'-import { IconWarning } from '@posthog/icons'-import { LemonButton, LemonCard, LemonDivider, Spinner } from '@posthog/lemon-ui'+import { IconTrash, IconWarning } from '@posthog/icons'+import { LemonButton, LemonCard, LemonCheckbox, LemonDialog, LemonDivider, Spinner } from '@posthog/lemon-ui'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'@@ -27,6 +27,8 @@ interface RuleListProps {description?: ReactNoderenderCardHeaderExtra?: (rule: any) => ReactNodeonMount?: () => void+ /** Extra actions rendered to the left of the Reorder/Add rule buttons (e.g. bulk import). */+ headerActions?: ReactNode}export function RuleList({@@ -38,11 +40,23 @@ export function RuleList({description,renderCardHeaderExtra,onMount,+ headerActions,}: RuleListProps): JSX.Element {const logic = rulesLogic({ ruleType })- const { rules, allRules, isReorderingRules, rulesLoading, initialLoadComplete } = useValues(logic)- const { loadRules, startReorderingRules, finishReorderingRules, cancelReorderingRules, reorderLocalRules } =- useActions(logic)+ const { rules, allRules, isReorderingRules, isSelectingRules, selectedRuleIds, rulesLoading, initialLoadComplete } =+ useValues(logic)+ const {+ loadRules,+ startReorderingRules,+ finishReorderingRules,+ cancelReorderingRules,+ reorderLocalRules,+ startSelectingRules,+ cancelSelectingRules,+ toggleSelectedRule,+ setSelectedRuleIds,+ deleteSelectedRules,+ } = useActions(logic)const { openModal } = useActions(modalLogic)useEffect(() => {@@ -55,6 +69,8 @@ export function RuleList({}const displayRules = (isReorderingRules ? allRules : rules) as ErrorTrackingRule[]+ const selectedRuleCount = selectedRuleIds.length+ const allRulesSelected = rules.length > 0 && selectedRuleCount === rules.lengthreturn (<>@@ -80,12 +96,59 @@ export function RuleList({Finish reordering</LemonButton></>+ ) : isSelectingRules ? (+ <>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setSelectedRuleIds(allRulesSelected ? [] : rules.map((rule) => rule.id))}+ >+ {allRulesSelected ? 'Deselect all' : 'Select all'}+ </LemonButton>+ <LemonButton type="secondary" size="small" onClick={cancelSelectingRules}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ status="danger"+ size="small"+ icon={<IconTrash />}+ disabled={selectedRuleCount === 0}+ loading={rulesLoading}+ onClick={() =>+ LemonDialog.open({+ title: 'Delete rules',+ description: `Are you sure you want to delete ${selectedRuleCount} ${+ selectedRuleCount === 1 ? 'rule' : 'rules'+ }?`,+ secondaryButton: {+ type: 'secondary',+ children: 'Cancel',+ },+ primaryButton: {+ type: 'primary',+ status: 'danger',+ onClick: deleteSelectedRules,+ children: 'Delete',+ },+ })+ }+ >+ Delete{selectedRuleCount > 0 ? ` ${selectedRuleCount}` : ''}+ </LemonButton>+ </>) : (<>+ {headerActions}{rules.length > 1 && (- <LemonButton type="secondary" size="small" onClick={startReorderingRules}>- Reorder- </LemonButton>+ <>+ <LemonButton type="secondary" size="small" onClick={startSelectingRules}>+ Select+ </LemonButton>+ <LemonButton type="secondary" size="small" onClick={startReorderingRules}>+ Reorder+ </LemonButton>+ </>)}<LemonButton type="primary" size="small" onClick={() => openModal()}>Add rule@@ -110,11 +173,28 @@ export function RuleList({const disabled = !!rule.disabled_datareturn (- <SortableRuleItem key={rule.id} ruleId={rule.id} reorderable={isReorderingRules}>+ <SortableRuleItem+ key={rule.id}+ ruleId={rule.id}+ reorderable={isReorderingRules}+ leading={+ isSelectingRules ? (+ <LemonCheckbox+ checked={selectedRuleIds.includes(rule.id)}+ onChange={() => toggleSelectedRule(rule.id)}+ />+ ) : null+ }+ ><LemonCardhoverEffect={false}- className={cn('flex flex-col p-0', !isReorderingRules && 'cursor-pointer')}- onClick={isReorderingRules ? undefined : () => openModal(rule)}+ className={cn(+ 'flex flex-col p-0',+ !isReorderingRules && !isSelectingRules && 'cursor-pointer'+ )}+ onClick={+ isReorderingRules || isSelectingRules ? undefined : () => openModal(rule)+ }><div className="flex items-center justify-between px-3 py-2">{renderCardHeaderExtra ? (diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/SortableRuleItem.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/SortableRuleItem.tsxindex d9fce7f544f6..b0bbb1ba7500 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/SortableRuleItem.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/SortableRuleItem.tsx@@ -1,6 +1,6 @@import { useSortable } from '@dnd-kit/sortable'import { CSS } from '@dnd-kit/utilities'-import { PropsWithChildren } from 'react'+import { PropsWithChildren, ReactNode } from 'react'import { SortableDragIcon } from 'lib/lemon-ui/icons'import { cn } from 'lib/utils/css-classes'@@ -10,8 +10,9 @@ import { ErrorTrackingRule } from './types'export function SortableRuleItem({ruleId,reorderable,+ leading,children,-}: PropsWithChildren<{ ruleId: ErrorTrackingRule['id']; reorderable: boolean }>): JSX.Element {+}: PropsWithChildren<{ ruleId: ErrorTrackingRule['id']; reorderable: boolean; leading?: ReactNode }>): JSX.Element {const { setNodeRef, attributes, transform, transition, listeners, active, isDragging } = useSortable({ id: ruleId })return (@@ -30,6 +31,7 @@ export function SortableRuleItem({{...listeners}/>)}+ {leading && <div className="flex shrink-0 items-start pt-2">{leading}</div>}<div className="flex-1">{children}</div></div>)diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/ruleMatchUrls.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/ruleMatchUrls.tsnew file mode 100644index 000000000000..769f8584007e--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/ruleMatchUrls.ts@@ -0,0 +1,42 @@+import { combineUrl } from 'kea-router'++import { urls } from 'scenes/urls'++import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'+import { NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { ActivityTab, AnyPropertyFilter, FilterLogicalOperator } from '~/types'++export function matchingIssuesUrl(+ properties: AnyPropertyFilter[],+ filterType: FilterLogicalOperator,+ dateRange: string+): string {+ return urls.errorTracking({+ filterGroup: { type: filterType, values: [{ type: filterType, values: properties }] },+ dateRange: { date_from: dateRange, date_to: null },+ })+}++export function matchingExceptionsUrl(properties: AnyPropertyFilter[], dateRange: string): string {+ return combineUrl(+ urls.activity(ActivityTab.ExploreEvents),+ {},+ {+ q: {+ kind: NodeKind.DataTableNode,+ full: true,+ source: {+ kind: NodeKind.EventsQuery,+ select: defaultDataTableColumns(NodeKind.EventsQuery),+ orderBy: ['timestamp DESC'],+ after: dateRange,+ event: '$exception',+ properties,+ tags: { productKey: ProductKey.ERROR_TRACKING },+ },+ propertiesViaUrl: true,+ showPersistentColumnConfigurator: true,+ },+ }+ ).url+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsxindex 599d6e44bbb5..6956440da6c6 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx@@ -57,6 +57,10 @@ export const rulesLogic = kea<rulesLogicType>([addRule: true,startReorderingRules: true,cancelReorderingRules: true,+ startSelectingRules: true,+ cancelSelectingRules: true,+ toggleSelectedRule: (id: ErrorTrackingRule['id']) => ({ id }),+ setSelectedRuleIds: (ids: ErrorTrackingRule['id'][]) => ({ ids }),setRuleEditable: (id: ErrorTrackingRule['id']) => ({ id }),unsetRuleEditable: (id: ErrorTrackingRule['id']) => ({ id }),updateLocalRule: (rule: ErrorTrackingRule) => ({ rule }),@@ -74,6 +78,24 @@ export const rulesLogic = kea<rulesLogicType>([finishReorderingRulesSuccess: () => false,},],+ isSelectingRules: [+ false,+ {+ startSelectingRules: () => true,+ cancelSelectingRules: () => false,+ deleteSelectedRulesSuccess: () => false,+ },+ ],+ selectedRuleIds: [+ [] as ErrorTrackingRule['id'][],+ {+ setSelectedRuleIds: (_, { ids }) => ids,+ toggleSelectedRule: (state, { id }) =>+ state.includes(id) ? state.filter((selectedId) => selectedId !== id) : [...state, id],+ cancelSelectingRules: () => [],+ deleteSelectedRulesSuccess: () => [],+ },+ ],initialLoadComplete: [false,{@@ -112,6 +134,14 @@ export const rulesLogic = kea<rulesLogicType>([const newValues = [...values.rules]return newValues.filter((v) => v.id !== id)},+ deleteSelectedRules: async () => {+ await Promise.all(+ values.selectedRuleIds.map((id) =>+ id === 'new' ? Promise.resolve() : api.errorTracking.deleteRule(props.ruleType, id)+ )+ )+ return values.rules.filter((rule) => !values.selectedRuleIds.includes(rule.id))+ },finishReorderingRules: async () => {const rules = values.localRulesconst ruleOrders = Object.fromEntries(rules.map((r) => [r.id, r.order_key]))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3ca34ddf3070..619fcfe8b43a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18909,6 +18909,8 @@ export namespace Schemas {filters: PropertyGroupFilterValue;/** User or role to assign matching issues to. */assignee: ErrorTrackingAssignmentRuleAssigneeRequest;+ /** Evaluation priority among rules; lower is evaluated first and the first matching rule wins. Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a deterministic order. */+ order_key?: number;}export interface ErrorTrackingAssignmentRuleUpdateRequest {diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex b9ce0409e653..91d71acb602a 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -51,6 +51,7 @@ export const errorTrackingAssignmentRulesCreateBodyFiltersOneValuesItemOnesixTypexport const errorTrackingAssignmentRulesCreateBodyFiltersOneValuesItemOnesevenTypeDefault = `error_tracking_issue`export const errorTrackingAssignmentRulesCreateBodyFiltersOneValuesItemTwozeroTypeDefault = `revenue_analytics`export const errorTrackingAssignmentRulesCreateBodyFiltersOneValuesItemTwooneTypeDefault = `workflow_variable`+export const errorTrackingAssignmentRulesCreateBodyOrderKeyDefault = 0export const ErrorTrackingAssignmentRulesCreateBody = /* @__PURE__ */ zod.object({filters: zod@@ -1002,6 +1003,12 @@ export const ErrorTrackingAssignmentRulesCreateBody = /* @__PURE__ */ zod.object.describe('User ID when `type` is `user`, or role UUID when `type` is `role`.'),}).describe('User or role to assign matching issues to.'),+ order_key: zod+ .number()+ .default(errorTrackingAssignmentRulesCreateBodyOrderKeyDefault)+ .describe(+ 'Evaluation priority among rules; lower is evaluated first and the first matching rule wins. Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a deterministic order.'+ ),})export const ErrorTrackingGroupingRulesListParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.tsindex 8ff2bca9efa5..3024b56de10d 100644--- a/services/mcp/src/tools/generated/error_tracking.ts+++ b/services/mcp/src/tools/generated/error_tracking.ts@@ -48,6 +48,9 @@ const errorTrackingAssignmentRulesCreate = (): ToolBase<if (params.assignee !== undefined) {body['assignee'] = params.assignee}+ if (params.order_key !== undefined) {+ body['order_key'] = params.order_key+ }const result = await context.api.request<Schemas.ErrorTrackingAssignmentRule>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/error_tracking/assignment_rules/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-assignment-rules-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-assignment-rules-create.jsonindex 078a3edd19ca..c55589f7d0f3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-assignment-rules-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-assignment-rules-create.json@@ -1801,6 +1801,11 @@},"required": ["type", "values"],"type": "object"+ },+ "order_key": {+ "default": 0,+ "description": "Evaluation priority among rules; lower is evaluated first and the first matching rule wins. Defaults to 0. Pass distinct ascending values when creating several rules at once to give them a deterministic order.",+ "type": "number"}},"required": ["filters", "assignee"],