Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6790 feat(issues): support operator matching in scalar property filters (#7765)

Deo4fe6586b320e
diff --git a/packages/core/issue-views/baseline.test.ts b/packages/core/issue-views/baseline.test.ts
new file mode 100644
index 0000000000..c2a0cfeb14
--- /dev/null
+++ b/packages/core/issue-views/baseline.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { baselineFromQuery } from "./baseline";
+import { propertyFilterValueKey } from "../types";
+
+// The property-filter branch of baselineFromQuery: saved-view members must
+// survive a round-trip as-is when the client can represent them, and drop
+// silently when it cannot (hand-edited blob, operator a future client added).
+describe("baselineFromQuery property filters", () => {
+ const textId = "prop-note";
+ const numId = "prop-estimate";
+
+ it("passes strings and known operator objects through untouched", () => {
+ const members = [
+ "hello",
+ "__none__",
+ { op: "contains", value: "foo" },
+ { op: "gte", value: "3.5" },
+ ];
+ const baseline = baselineFromQuery({
+ propertyFilters: { [textId]: members },
+ });
+
+ expect(baseline.raw.propertyFilters[textId]).toEqual(members);
+ // Membership keys: strings are their own key; operators get their
+ // canonical key so Set lookups agree with the store.
+ expect([...baseline.property.get(textId)!]).toEqual(
+ members.map((m) => propertyFilterValueKey(m as never)),
+ );
+ });
+
+ it("drops members the store cannot represent", () => {
+ const baseline = baselineFromQuery({
+ propertyFilters: {
+ [textId]: [
+ "keep",
+ { op: "regex", value: "x" }, // unknown op
+ { op: 42, value: "x" }, // non-string op
+ { op: "contains", value: 7 }, // non-string value
+ { nope: true }, // not an operator shape
+ 7, // not a string
+ null,
+ ],
+ [numId]: [{ op: "regex", value: "x" }], // everything dropped
+ },
+ });
+
+ expect(baseline.raw.propertyFilters[textId]).toEqual(["keep"]);
+ // A definition with no representable members is not a filter at all.
+ expect(baseline.raw.propertyFilters[numId]).toBeUndefined();
+ expect(baseline.property.has(numId)).toBe(false);
+ });
+
+ it("treats a non-array member list as no filter", () => {
+ const baseline = baselineFromQuery({
+ propertyFilters: { [textId]: "hello" },
+ });
+ expect(baseline.raw.propertyFilters).toEqual({});
+ expect(baseline.property.size).toBe(0);
+ });
+});
diff --git a/packages/core/issue-views/baseline.ts b/packages/core/issue-views/baseline.ts
index 5aa7a48351..5f6759c161 100644
--- a/packages/core/issue-views/baseline.ts
+++ b/packages/core/issue-views/baseline.ts
@@ -1,5 +1,6 @@
import type { ActorFilterValue, FilterSnapshot } from "../issues/stores/view-store";
-import type { IssuePriority, IssueStatus } from "../types";
+import type { IssuePriority, IssueStatus, PropertyFilterValue } from "../types";
+import { isKnownPropertyFilterOp, isPropertyOperatorFilter, propertyFilterValueKey } from "../types";
import { PRIORITY_DISPLAY_ORDER } from "../issues/config";
/**
@@ -21,7 +22,7 @@ export interface IssueViewBaseline {
project: Set<string>;
includeNoProject: boolean;
label: Set<string>;
- /** Property definition id → fixed option ids. */
+ /** Property definition id → fixed member keys (`propertyFilterValueKey`). */
property: Map<string, Set<string>>;
/** Enum-sanitized snapshot, safe to hand straight to `resetFiltersTo`. */
raw: FilterSnapshot;
@@ -35,6 +36,22 @@ function stringArray(v: unknown): string[] {
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
}
+/**
+ * Sanitize one property filter's member list. Strings pass through (equality,
+ * "true"/"false", "__none__"); operator objects must carry a known op and a
+ * string value. Anything else — a hand-edited blob or an operator a future
+ * client added — is dropped: a member the store cannot represent must not
+ * enter the snapshot (same rule as the enum filters above).
+ */
+function propertyFilterValueArray(v: unknown): PropertyFilterValue[] {
+ if (!Array.isArray(v)) return [];
+ return v.filter(
+ (x): x is PropertyFilterValue =>
+ typeof x === "string" ||
+ (isPropertyOperatorFilter(x) && isKnownPropertyFilterOp(x.op)),
+ );
+}
+
function actorArray(v: unknown): ActorFilterValue[] {
if (!Array.isArray(v)) return [];
return v.filter(
@@ -65,16 +82,16 @@ export function baselineFromQuery(query: Record<string, unknown>): IssueViewBase
const includeNoAssignee = query.includeNoAssignee === true;
const includeNoProject = query.includeNoProject === true;
- const propertyFilters: Record<string, string[]> = {};
+ const propertyFilters: Record<string, PropertyFilterValue[]> = {};
const property = new Map<string, Set<string>>();
if (query.propertyFilters && typeof query.propertyFilters === "object") {
for (const [id, selected] of Object.entries(
query.propertyFilters as Record<string, unknown>,
)) {
- const values = stringArray(selected);
+ const values = propertyFilterValueArray(selected);
if (values.length > 0) {
propertyFilters[id] = values;
- property.set(id, new Set(values));
+ property.set(id, new Set(values.map(propertyFilterValueKey)));
}
}
}
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index 0fdeb50c79..0bd493d788 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -4,7 +4,7 @@ import { useEffect, useRef } from "react";
import { create } from "zustand";
import { createStore, type StoreApi } from "zustand/vanilla";
import { createJSONStorage, persist } from "zustand/middleware";
-import type { IssueStatus, IssueStatusCategory, IssuePriority } from "../../types";
+import type { IssueStatus, IssueStatusCategory, IssuePriority, PropertyFilterValue } from "../../types";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
@@ -127,7 +127,7 @@ export interface FilterSnapshot {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
- propertyFilters: Record<string, string[]>;
+ propertyFilters: Record<string, PropertyFilterValue[]>;
}
/** Filter-bar chip dimensions. Date is excluded: `dateFilter` lives outside
@@ -190,12 +190,14 @@ export interface IssueViewState {
includeNoProject: boolean;
labelFilters: string[];
/**
- * Custom-property filters: definition id → selected option ids (checkbox
- * definitions use the pseudo-options "true"/"false"). Empty array = no
+ * Custom-property filters: definition id → selected values (checkbox
+ * definitions use the pseudo-options "true"/"false"; scalars hold the
+ * committed value as a bare string, or an operator object per
+ * `PropertyFilterValue`, plus the "__none__" sentinel). Empty array = no
* filter for that definition; matching is OR within a definition and AND
* across definitions, mirroring the other filter groups.
*/
- propertyFilters: Record<string, string[]>;
+ propertyFilters: Record<string, PropertyFilterValue[]>;
dateFilter: IssueDateFilter | null;
// When true, the list only shows issues that currently have at least one
// agent task in `running` status. Drives the workspace "agents working"
@@ -257,7 +259,7 @@ export interface IssueViewState {
togglePropertyFilter: (propertyId: string, optionId: string) => void;
/** Replace a property's full filter value set (used by scalar value inputs
* for text/number/date/url, which build the array including "__none__"). */
- setPropertyFilterValues: (propertyId: string, optionIds: string[]) => void;
+ setPropertyFilterValues: (propertyId: string, optionIds: PropertyFilterValue[]) => void;
setDateFilter: (filter: IssueDateFilter | null) => void;
toggleAgentRunningFilter: () => void;
hideStatus: (category: IssueStatusCategory) => void;
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 147ce5c9b5..d45a47a70e 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -1,4 +1,5 @@
import type { Issue, IssueMetadata, IssueStatus, IssueStatusCategory, IssuePriority, IssueAssigneeType } from "./issue";
+import type { PropertyFilterValue } from "./property";
import type { MemberRole } from "./workspace";
import type { Project } from "./project";
@@ -185,8 +186,9 @@ export interface ListIssuesParams {
/** JSONB containment filter on `issue.metadata`. AND across keys. */
metadata?: IssueMetadata;
/** Custom-property filter: definition id → accepted values (option ids or
- * "true"/"false" for checkbox). OR within a definition, AND across. */
- properties?: Record<string, string[]>;
+ * "true"/"false" for checkbox; a plain string is exact equality, an
+ * operator object narrows it). OR within a definition, AND across. */
+ properties?: Record<string, PropertyFilterValue[]>;
open_only?: boolean;
/**
* Restrict the result to issues with at least one of `start_date` /
@@ -234,8 +236,9 @@ export interface ListGroupedIssuesParams {
/** JSONB containment filter on `issue.metadata`. AND across keys. */
metadata?: IssueMetadata;
/** Custom-property filter: definition id → accepted values (option ids or
- * "true"/"false" for checkbox). OR within a definition, AND across. */
- properties?: Record<string, string[]>;
+ * "true"/"false" for checkbox; a plain string is exact equality, an
+ * operator object narrows it). OR within a definition, AND across. */
+ properties?: Record<string, PropertyFilterValue[]>;
assignee_filters?: IssueActorRef[];
include_no_assignee?: boolean;
creator_filters?: IssueActorRef[];
@@ -299,7 +302,9 @@ export interface IssueTableFilters {
project_ids?: string[];
include_no_project?: boolean;
label_ids?: string[];
- properties?: Record<string, string[]>;
+ /** Same shape as `ListIssuesParams.properties`: bare strings are exact
+ * equality / "No value", operator objects narrow scalar matches. */
+ properties?: Record<string, PropertyFilterValue[]>;
date?: {
field: "created_at" | "updated_at";
start: string;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index b50126b4cb..97e68f5720 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -114,8 +114,8 @@ export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } fr
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
-export type { IssueProperty, IssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef } from "./property";
-export { ISSUE_PROPERTY_TYPES, isKnownPropertyType, ISSUE_PROPERTY_ACTOR_KINDS, MAX_ISSUE_PROPERTY_ACTOR_VALUES, isActorPropertyType, isFilterablePropertyType, isScalarPropertyType, formatActorRef, parseActorRef, actorRefsFromValue, actorRefValuesFromValue, hasUnknownActorRef } from "./property";
+export type { IssueProperty, IssuePropertyType, ScalarIssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef, PropertyFilterOp, PropertyOperatorFilter, PropertyFilterValue } from "./property";
+export { ISSUE_PROPERTY_TYPES, isKnownPropertyType, ISSUE_PROPERTY_ACTOR_KINDS, MAX_ISSUE_PROPERTY_ACTOR_VALUES, isActorPropertyType, isFilterablePropertyType, isScalarPropertyType, formatActorRef, parseActorRef, actorRefsFromValue, actorRefValuesFromValue, hasUnknownActorRef, isPropertyOperatorFilter, isKnownPropertyFilterOp, propertyFilterValueKey, PROPERTY_FILTER_OP_SYMBOLS, PROPERTY_FILTER_OPS_BY_TYPE } from "./property";
export type {
QuickAction,
QuickActionVisibility,
diff --git a/packages/core/types/property.ts b/packages/core/types/property.ts
index f78b4b48e0..7931706b09 100644
--- a/packages/core/types/property.ts
+++ b/packages/core/types/property.ts
@@ -79,7 +79,9 @@ export function isFilterablePropertyType(type: string): boolean {
}
/** Single-valued scalar properties: text / number / date / url. */
-export function isScalarPropertyType(type: string): boolean {
+export type ScalarIssuePropertyType = Extract<IssuePropertyType, "text" | "number" | "date" | "url">;
+
+export function isScalarPropertyType(type: string): type is ScalarIssuePropertyType {
return type === "text" || type === "url" || type === "number" || type === "date";
}
@@ -177,6 +179,96 @@ export interface IssueProperty {
export type IssuePropertyValue = string | number | boolean | string[];
export type IssuePropertyValues = Record<string, IssuePropertyValue>;
+/**
+ * Structured operators for scalar property filters (#7692). A plain string
+ * member still means exact equality — every pre-operator saved view, URL, and
+ * API call keeps its meaning. Operators ride alongside as objects:
+ *
+ * - `contains` — case-insensitive substring match (text / url)
+ * - `gt` / `gte` / `lt` / `lte` — numeric comparison (number)
+ * - `before` / `after` — lexicographic date comparison (date, "YYYY-MM-DD")
+ *
+ * Within one definition all members still OR, so an operator member composes
+ * with observed values and "No value" like any other alternative.
+ */
+export type PropertyFilterOp =
+ | "contains"
+ | "gt"
+ | "gte"
+ | "lt"
+ | "lte"
+ | "before"
+ | "after";
+
+export const PROPERTY_FILTER_OPS: readonly PropertyFilterOp[] = [
+ "contains",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "before",
+ "after",
+];
+
+/** Mathematical symbols shared by the scalar filter picker and active chips. */
+export const PROPERTY_FILTER_OP_SYMBOLS: Partial<Record<PropertyFilterOp, string>> = {
+ gt: ">",
+ gte: "≥",
+ lt: "<",
+ lte: "≤",
+};
+
+export function isKnownPropertyFilterOp(op: string): op is PropertyFilterOp {
+ return (PROPERTY_FILTER_OPS as readonly string[]).includes(op);
+}
+
+export interface PropertyOperatorFilter {
+ op: PropertyFilterOp;
+ /** Raw user input; the server interprets it per op. */
+ value: string;
+}
+
+/** One OR-alternative of a property filter: equality (bare string), the
+ * "No value" sentinel, or a structured operator. */
+export type PropertyFilterValue = string | PropertyOperatorFilter;
+
+/**
+ * Canonical membership key for one filter member, so equality strings and
+ * operator objects can live in `Set<string>`-shaped lookups (saved-view
+ * baselines, chip deltas) without stringifying objects ad hoc.
+ */
+export function propertyFilterValueKey(value: PropertyFilterValue): string {
+ return typeof value === "string" ? value : `${value.op}\u0000${value.value}`;
+}
+
+export function isPropertyOperatorFilter(value: unknown): value is PropertyOperatorFilter {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ typeof (value as PropertyOperatorFilter).op === "string" &&
+ typeof (value as PropertyOperatorFilter).value === "string"
+ );
+}
+
+/**
+ * Ops the filter menu offers per scalar property type, in display order.
+ * "is" (equality) is not in the list — it is the default and commits a bare
+ * string, so every pre-operator flow stays untouched. Non-scalar entries are
+ * intentionally empty: keeping the record exhaustive forces each future
+ * property type to make an explicit operator decision.
+ */
+export const PROPERTY_FILTER_OPS_BY_TYPE: Record<IssuePropertyType, readonly PropertyFilterOp[]> = {
+ text: ["contains"],
+ number: ["gt", "gte", "lt", "lte"],
+ select: [],
+ multi_select: [],
+ date: ["before", "after"],
+ checkbox: [],
+ url: ["contains"],
+ actor: [],
+ multi_actor: [],
+};
+
export interface CreatePropertyRequest {
name: string;
type: IssuePropertyType;
diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsx
index b2c6320baa..fc8e50db91 100644
--- a/packages/views/issues/components/filter-chips-bar.tsx
+++ b/packages/views/issues/components/filter-chips-bar.tsx
@@ -21,7 +21,7 @@ import { memberListOptions, agentListOptions, squadListOptions } from "@multica/
import { projectListOptions } from "@multica/core/projects/queries";
import { labelListOptions } from "@multica/core/labels/queries";
import { propertyListOptions } from "@multica/core/properties";
-import { isActorPropertyType, isScalarPropertyType, parseActorRef } from "@multica/core/types";
+import { isActorPropertyType, isScalarPropertyType, parseActorRef, propertyFilterValueKey, PROPERTY_FILTER_OP_SYMBOLS, type PropertyFilterValue } from "@multica/core/types";
import {
type ActorFilterValue,
type FilterDimension,
@@ -104,7 +104,7 @@ export function buildChipActorNames(
* stack. Unparseable entries drop out — the chip degrades to fewer avatars
* rather than rendering a broken one.
*/
-export function actorFilterValues(selected: string[]): ActorFilterValue[] {
+export function actorFilterValues(selected: PropertyFilterValue[]): ActorFilterValue[] {
return selected
.map((value) => parseActorRef(value))
.filter((ref): ref is NonNullable<ReturnType<typeof parseActorRef>> => ref !== null)
@@ -120,7 +120,7 @@ export function actorFilterValues(selected: string[]): ActorFilterValue[] {
* can only render a bare count (MUL-6286 review).
*/
export function hasActorPropertyFilterSelection(
- propertyFilters: Record<string, string[]>,
+ propertyFilters: Record<string, PropertyFilterValue[]>,
properties: { id: string; type: string }[],
): boolean {
return Object.entries(propertyFilters).some(
@@ -330,10 +330,12 @@ function useFilterChips(
const deltaLabels = baseline
? labelFilters.filter((id) => !baseline.label.has(id))
: labelFilters;
- const deltaProperties: Record<string, string[]> = {};
+ const deltaProperties: Record<string, PropertyFilterValue[]> = {};
for (const [id, selected] of Object.entries(propertyFilters)) {
const fixed = baseline?.property.get(id);
- const delta = fixed ? selected.filter((v) => !fixed.has(v)) : selected;
+ const delta = fixed
+ ? selected.filter((v) => !fixed.has(propertyFilterValueKey(v)))
+ : selected;
if (delta.length > 0) deltaProperties[id] = delta;
}
@@ -457,24 +459,39 @@ function useFilterChips(
// references, so names come from the directory and the icons are avatars.
const actorProperty = isActorPropertyType(definition.type);
const actorValues = actorProperty ? actorFilterValues(selected) : [];
- const optionName = (optionId: string): string | undefined => {
- if (optionId === NO_PROPERTY_VALUE) {
+ const optionName = (member: PropertyFilterValue): string | undefined => {
+ if (member === NO_PROPERTY_VALUE) {
return t(($) => $.pickers.custom_property.none);
}
+ // Scalar operator members summarize with their operator; the comparison
+ // symbols are locale-independent, the word ops get chip phrases.
+ if (typeof member === "object") {
+ if (member.op === "contains") {
+ return t(($) => $.filters.chip_op_contains, { value: member.value });
+ }
+ if (member.op === "before") {
+ return t(($) => $.filters.chip_op_before, { value: member.value });
+ }
+ if (member.op === "after") {
+ return t(($) => $.filters.chip_op_after, { value: member.value });
+ }
+ const symbol = PROPERTY_FILTER_OP_SYMBOLS[member.op] ?? member.op;
+ return `${symbol} ${member.value}`;
+ }
if (actorProperty) {
- const ref = parseActorRef(optionId);
+ const ref = parseActorRef(member);
return ref ? actorName({ type: ref.kind, id: ref.id }) : undefined;
}
if (definition.type === "checkbox") {
- return optionId === "true"
+ return member === "true"
? t(($) => $.pickers.custom_property.true_label)
: t(($) => $.pickers.custom_property.false_label);
}
// Scalar properties have no option list — the filter value IS the label.
if (isScalarPropertyType(definition.type)) {
- return optionId;
+ return member;
}
- return definition.config.options?.find((o) => o.id === optionId)?.name;
+ return definition.config.options?.find((o) => o.id === member)?.name;
};
const optionColors =
definition.type === "checkbox" || actorProperty
diff --git a/packages/views/issues/components/issues-header.property-filter.test.tsx b/packages/views/issues/components/issues-header.property-filter.test.tsx
index 65be96d953..31c407e81d 100644
--- a/packages/views/issues/components/issues-header.property-filter.test.tsx
+++ b/packages/views/issues/components/issues-header.property-filter.test.tsx
@@ -179,4 +179,48 @@ describe("IssueFilterMenu scalar property filter", () => {
await userEvent.type(screen.getByRole("textbox"), "{Enter}");
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["abc", "__none__"] });
});
+
+ it("picking contains with an empty draft, then typing commits an operator object", async () => {
+ // Regression: killing the pending operator on click downgraded the next
+ // commit back to equality — the pick silently did nothing.
+ const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
+ await openPropertySubmenu("Note");
+
+ expect(screen.getByRole("radiogroup", { name: "Filter operator" })).toBeInTheDocument();
+ expect(screen.getByRole("radio", { name: "is" })).toBeChecked();
+ const contains = screen.getByRole("radio", { name: "contains" });
+ await userEvent.click(contains);
+ expect(contains).toBeChecked();
+ await userEvent.type(screen.getByRole("textbox"), "hello{Enter}");
+
+ expect(store.getState().propertyFilters).toEqual({
+ [PROP]: [{ op: "contains", value: "hello" }],
+ });
+ });
+
+ it("clicking an operator commits the current draft with it immediately", async () => {
+ const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
+ await openPropertySubmenu("Note");
+
+ await userEvent.type(screen.getByRole("textbox"), "hello");
+ await userEvent.click(screen.getByRole("radio", { name: "contains" }));
+
+ expect(store.getState().propertyFilters).toEqual({
+ [PROP]: [{ op: "contains", value: "hello" }],
+ });
+ });
+
+ it("switching back to is commits a bare string again", async () => {
+ const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
+ await openPropertySubmenu("Note");
+
+ await userEvent.type(screen.getByRole("textbox"), "hello");
+ await userEvent.click(screen.getByRole("radio", { name: "contains" }));
+ expect(store.getState().propertyFilters).toEqual({
+ [PROP]: [{ op: "contains", value: "hello" }],
+ });
+
+ await userEvent.click(screen.getByRole("radio", { name: "is" }));
+ expect(store.getState().propertyFilters).toEqual({ [PROP]: ["hello"] });
+ });
});
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index f84a492424..c78c825622 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -75,7 +75,7 @@ import type {
IssueTableFacetsResponse,
WorkingAgentSummary,
} from "@multica/core/types";
-import { formatActorRef, isActorPropertyType, isFilterablePropertyType, isScalarPropertyType } from "@multica/core/types";
+import { formatActorRef, isActorPropertyType, isFilterablePropertyType, isScalarPropertyType, propertyFilterValueKey, PROPERTY_FILTER_OP_SYMBOLS, PROPERTY_FILTER_OPS_BY_TYPE, type PropertyFilterOp, type PropertyFilterValue } from "@multica/core/types";
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import { PropertyIcon } from "../../common/property-icon";
@@ -142,7 +142,7 @@ function getActiveFilterCount(
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
- propertyFilters?: Record<string, string[]>;
+ propertyFilters?: Record<string, PropertyFilterValue[]>;
dateFilter?: IssueDateFilter | null;
},
// Inside a saved view only the user's additions on top of the view's own
@@ -165,7 +165,13 @@ function getActiveFilterCount(
if (projectDelta) count++;
if (delta(state.labelFilters, baseline?.label) > 0) count++;
for (const [id, selected] of Object.entries(state.propertyFilters ?? {})) {
- if (delta(selected, baseline?.property.get(id)) > 0) count++;
+ // Property members can be operator objects — compare through their
+ // canonical keys so a view-fixed operator still cancels out.
+ const fixed = baseline?.property.get(id);
+ const deltaCount = fixed
+ ? selected.filter((v) => !fixed.has(propertyFilterValueKey(v))).length
+ : selected.length;
+ if (deltaCount > 0) count++;
}
if (state.dateFilter) count++;
return count;
@@ -665,6 +671,15 @@ function LabelSubContent({
* from the member directory instead, with the signed-in member first so
* "this property is me" stays one click away.
*/
+
+// Keyboard guard for the inline operator radios — same contract as the
+// scalar input below: Escape/Tab belong to the menu (close / move focus);
+// every other navigation or selection key must not bubble into the popup's
+// typeahead / list-navigation handlers.
+function stopScalarMenuKeys(event: React.KeyboardEvent) {
+ if (event.key === "Escape" || event.key === "Tab") return;
+ event.stopPropagation();
+}
function PropertyFilterOptions({
property,
counts,
@@ -676,10 +691,10 @@ function PropertyFilterOptions({
}: {
property: IssueProperty;
counts: Map<string, number> | undefined;
- selected: string[];
+ selected: PropertyFilterValue[];
onToggle: (optionId: string) => void;
/** Replace the property's full filter value set (scalar types only). */
- onSetValues: (optionIds: string[]) => void;
+ onSetValues: (optionIds: PropertyFilterValue[]) => void;
fixedIds?: Set<string>;
fixedTitle?: string;
}) {
@@ -689,7 +704,6 @@ function PropertyFilterOptions({
const actorProperty = isActorPropertyType(property.type);
// Scalar properties (text / number / date / url) have no option list — the
// filter menu shows a value input plus "No value".
- const scalarProperty = isScalarPropertyType(property.type);
const { data: actorMembers = [] } = useQuery({
...memberListOptions(wsId),
enabled: actorProperty,
@@ -724,12 +738,28 @@ function PropertyFilterOptions({
// Scalar value state lives at the top level so the hooks stay unconditional
// (Rules of Hooks): it is only rendered for text / number / date / url, but
// must be declared regardless of which branch runs. The draft syncs to the
- // committed `scalarValue` whenever that changes, so a filter cleared or
+ // committed scalar member whenever that changes, so a filter cleared or
// rewritten elsewhere cannot be written back from a stale input.
- const scalarValue = selected.find((id) => id !== NO_PROPERTY_VALUE) ?? "";
+ const committedMember = selected.find((member) => member !== NO_PROPERTY_VALUE);
+ const committedScalar =
+ typeof committedMember === "object" ? committedMember.value : (committedMember ?? "");
+ const committedOp: PropertyFilterOp | "is" =
+ typeof committedMember === "object" ? committedMember.op : "is";
const hasNoValue = selected.includes(NO_PROPERTY_VALUE);
- const [draft, setDraft] = useState(scalarValue);
- useEffect(() => setDraft(scalarValue), [scalarValue]);
+ const [draft, setDraft] = useState(committedScalar);
+ useEffect(() => setDraft(committedScalar), [committedScalar]);
+ // Operator picked in the open menu but not yet committed; null defers to the
+ // committed member (equality when there is none). Resets whenever the
+ // committed member changes — including right after this menu commits — so a
+ // value rewritten elsewhere can't inherit a stale operator.
+ const [pendingOp, setPendingOp] = useState<PropertyFilterOp | "is" | null>(null);
+ const committedKey =
+ committedMember === undefined
+ ? ""
+ : typeof committedMember === "object"
+ ? `op:${committedMember.op}:${committedMember.value}`
+ : `eq:${committedMember}`;
+ useEffect(() => setPendingOp(null), [committedKey]);
const options = [
...(actorProperty
? actorOptions.map((option) => ({
@@ -754,7 +784,7 @@ function PropertyFilterOptions({
noValueOption,
];
- if (scalarProperty) {
+ if (isScalarPropertyType(property.type)) {
const placeholder =
property.type === "url"
? t(($) => $.pickers.custom_property.url_placeholder)
@@ -762,20 +792,98 @@ function PropertyFilterOptions({
? t(($) => $.pickers.custom_property.number_placeholder)
: t(($) => $.pickers.custom_property.value_placeholder);
const noneCount = counts?.get(NO_PROPERTY_VALUE) ?? 0;
- // A saved view locks this dimension: the scalar value AND "No value" are
- // both part of the view's identity, so neither can be edited in place.
+ // A saved view locks this dimension: the value (with its operator) AND
+ // "No value" are both part of the view's identity, so neither can be
+ // edited in place.
const locked = fixedIds !== undefined && fixedIds.size > 0;
- const commitValue = (raw: string) => {
+ // "is" is equality and commits a bare string — the pre-operator shape.
+ // Every other op commits an operator object; the server and matcher both
+ // treat unknown shapes conservatively.
+ const effectiveOp: PropertyFilterOp | "is" = pendingOp ?? committedOp;
+ const scalarOperatorLabel = (op: PropertyFilterOp): string => {
+ if (op === "contains") return t(($) => $.pickers.custom_property.op_contains);
+ if (op === "before") return t(($) => $.pickers.custom_property.op_before);
+ if (op === "after") return t(($) => $.pickers.custom_property.op_after);
+ return PROPERTY_FILTER_OP_SYMBOLS[op] ?? op;
+ };
+ const opButtons: { op: PropertyFilterOp | "is"; label: string }[] = [
+ {
+ op: "is",
+ label:
+ property.type === "number"
+ ? "="
+ : t(($) => $.pickers.custom_property.op_is),
+ },
+ ...(PROPERTY_FILTER_OPS_BY_TYPE[property.type] ?? []).map((op) => ({
+ op,
+ label: scalarOperatorLabel(op),
+ })),
+ ];
+ const commitValue = (raw: string, op: PropertyFilterOp | "is" = effectiveOp) => {
const value = raw.trim();
// NO_PROPERTY_VALUE is the reserved "no value" sentinel — it cannot be
// filtered as a literal value. The value and "No value" compose like
// every other property type: committing a value replaces only the value
// member and preserves "No value" membership.
if (value === NO_PROPERTY_VALUE) return;
- onSetValues(value ? [value, ...(hasNoValue ? [NO_PROPERTY_VALUE] : [])] : hasNoValue ? [NO_PROPERTY_VALUE] : []);
+ const member: PropertyFilterValue | undefined = value
+ ? op === "is"
+ ? value
+ : { op, value }
+ : undefined;
+ onSetValues([
+ ...(member ? [member] : []),
+ ...(hasNoValue ? [NO_PROPERTY_VALUE] : []),
+ ]);
+ };
+ const applyOp = (op: PropertyFilterOp | "is") => {
+ // An explicit click commits the current draft with the chosen op, unlike
+ // the input which waits for Enter/blur. With an empty draft nothing
+ // commits, so the choice rides on pendingOp and the next Enter/blur
+ // commit carries it — killing pendingOp here would silently downgrade
+ // that later commit back to equality.
+ setPendingOp(op);
+ commitValue(draft, op);
};
return (
<>
+ {opButtons.length > 1 && (
+ <div
+ role="radiogroup"
+ aria-label={t(($) => $.pickers.custom_property.operator_label)}
+ className="flex flex-wrap gap-1 px-2 pt-1.5"
+ >
+ {opButtons.map(({ op, label }) => {
+ const active = effectiveOp === op;
+ return (
+ <label
+ key={op}
+ className={locked ? "cursor-not-allowed" : "cursor-pointer"}
+ >
+ <input
+ type="radio"
+ name={`property-filter-op-${property.id}`}
+ value={op}
+ checked={active}
+ disabled={locked}
+ onChange={() => applyOp(op)}
+ onKeyDown={stopScalarMenuKeys}
+ className="peer sr-only"
+ />
+ <span
+ className={`inline-flex h-6 items-center rounded-md px-1.5 text-caption transition-colors peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-ring ${
+ active
+ ? "bg-accent font-medium text-foreground"
+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
+ }`}
+ >
+ {label}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ )}
<div className="px-2 py-1.5">
<Input
type={property.type === "number" ? "number" : property.type === "date" ? "date" : "text"}
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 19af3b1dac..016d325122 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -8,7 +8,7 @@ import { projectListOptions } from "@multica/core/projects/queries";
import { childIssueProgressOptions } from "@multica/core/issues/queries";
import { issueSurfaceGanttOptions } from "@multica/core/issues/surface/repository";
import type { IssueSurfaceQueryPlan } from "@multica/core/issues/surface/query-plan";
-import type { IssueStatus, IssueStatusCategory } from "@multica/core/types";
+import type { IssueStatus, IssueStatusCategory, PropertyFilterValue } from "@multica/core/types";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { issueBehavesAsAny, statusFilterColumns } from "@multica/core/issues";
import {
@@ -140,7 +140,7 @@ export function useIssueSurfaceData({
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
- propertyFilters: Record<string, string[]>;
+ propertyFilters: Record<string, PropertyFilterValue[]>;
/** Distinct running-task issue ids projected by `/api/working-agents`. */
workingIssueIDs: ReadonlySet<string>;
showSubIssues: boolean;
diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.ts
index 5e5e419430..a6383d82ad 100644
--- a/packages/views/issues/utils/filter.test.ts
+++ b/packages/views/issues/utils/filter.test.ts
@@ -1,10 +1,11 @@
// @vitest-environment node
import { describe, it, expect } from "vitest";
-import type { Issue, IssueAssigneeGroup } from "@multica/core/types";
+import type { Issue, IssueAssigneeGroup, PropertyFilterValue } from "@multica/core/types";
import {
applyIssueFilters,
filterAssigneeGroups,
filterIssues,
+ issueMatchesPropertyFilters,
NO_PROPERTY_VALUE,
type IssueFilters,
} from "./filter";
@@ -546,3 +547,93 @@ describe("property filters", () => {
expect(result?.[0]?.total).toBe(1);
});
});
+
+// Scalar operator members (#7692): the matrix mirrors the server predicates in
+// server/internal/handler/property.go — contains is a case-insensitive
+// substring over stored strings only, gt/gte/lt/lte match stored numbers, and
+// before/after compare "YYYY-MM-DD" strings lexicographically. A missing key
+// never matches an operator, matching the server's NULL ->> semantics.
+describe("scalar operator filters", () => {
+ const textId = "prop-note";
+ const urlId = "prop-link";
+ const numId = "prop-estimate";
+ const dateId = "prop-due";
+
+ const withText = makeIssue({ id: "T", properties: { [textId]: "Hello World" } });
+ const withUrl = makeIssue({ id: "U", properties: { [urlId]: "https://example.com/Repo" } });
+ const withNum = makeIssue({ id: "N", properties: { [numId]: 3.5 } });
+ const withBool = makeIssue({ id: "B", properties: { [textId]: true } });
+ const withArray = makeIssue({ id: "A", properties: { [textId]: ["opt-alpha", "opt-beta"] } });
+ const withDate = makeIssue({ id: "D", properties: { [dateId]: "2026-03-01" } });
+ const unset = makeIssue({ id: "X" });
+
+ const matches = (issue: Issue, defId: string, member: PropertyFilterValue) =>
+ issueMatchesPropertyFilters(issue, { [defId]: [member] });
+
+ it("contains is a case-insensitive substring over text", () => {
+ expect(matches(withText, textId, { op: "contains", value: "world" })).toBe(true);
+ expect(matches(withText, textId, { op: "contains", value: "WORLD" })).toBe(true);
+ expect(matches(withText, textId, { op: "contains", value: "lo Wo" })).toBe(true);
+ expect(matches(withText, textId, { op: "contains", value: "hello!" })).toBe(false);
+ });
+
+ it("contains matches url values and never matches an unset key or an empty needle", () => {
+ expect(matches(withUrl, urlId, { op: "contains", value: "example.com" })).toBe(true);
+ expect(matches(unset, urlId, { op: "contains", value: "example.com" })).toBe(false);
+ // Asserted against a SET value on purpose: the unset case short-circuits
+ // before the operator runs, so it cannot catch an empty-needle match-all.
+ // The server rejects empty operator values; the matcher agrees.
+ expect(matches(withText, textId, { op: "contains", value: "" })).toBe(false);
+ });
+
+ it("contains never stringifies non-string stored values", () => {
+ expect(matches(withNum, numId, { op: "contains", value: "3.5" })).toBe(false);
+ expect(matches(withBool, textId, { op: "contains", value: "true" })).toBe(false);
+ expect(matches(withArray, textId, { op: "contains", value: "alpha" })).toBe(false);
+ });
+
+ it("number comparisons match stored numbers with the bound as a string", () => {
+ expect(matches(withNum, numId, { op: "gt", value: "3.5" })).toBe(false);
+ expect(matches(withNum, numId, { op: "gte", value: "3.5" })).toBe(true);
+ expect(matches(withNum, numId, { op: "lt", value: "3.50" })).toBe(false);
+ expect(matches(withNum, numId, { op: "lte", value: "3.50" })).toBe(true);
+ });
+
+ it("number comparisons reject non-numeric bounds and non-number values", () => {
+ expect(matches(withNum, numId, { op: "gt", value: "abc" })).toBe(false);
+ expect(matches(withText, textId, { op: "gt", value: "1" })).toBe(false);
+ expect(matches(unset, numId, { op: "gte", value: "1" })).toBe(false);
+ });
+
+ it("before/after compare date strings lexicographically", () => {
+ expect(matches(withDate, dateId, { op: "before", value: "2026-03-02" })).toBe(true);
+ expect(matches(withDate, dateId, { op: "before", value: "2026-03-01" })).toBe(false);
+ expect(matches(withDate, dateId, { op: "after", value: "2026-02-28" })).toBe(true);
+ expect(matches(withDate, dateId, { op: "after", value: "2026-03-01" })).toBe(false);
+ expect(matches(unset, dateId, { op: "before", value: "2030-01-01" })).toBe(false);
+ expect(matches(withNum, dateId, { op: "before", value: "2030-01-01" })).toBe(false);
+ });
+
+ it("an operator ORs with equality and No value within the definition", () => {
+ const lateDate = makeIssue({ id: "D2", properties: { [dateId]: "2027-01-01" } });
+ const result = filterIssues([withDate, lateDate, unset], {
+ ...NO_FILTER,
+ propertyFilters: {
+ [dateId]: [{ op: "before", value: "2026-06-01" }, "2027-01-01", NO_PROPERTY_VALUE],
+ },
+ });
+ expect(result.map((i) => i.id)).toEqual(["D", "D2", "X"]);
+ });
+
+ it("operators AND across definitions like every other filter group", () => {
+ const both = makeIssue({ id: "B", properties: { [textId]: "release notes", [numId]: 10 } });
+ const result = filterIssues([withText, withNum, both], {
+ ...NO_FILTER,
+ propertyFilters: {
+ [textId]: [{ op: "contains", value: "release" }],
+ [numId]: [{ op: "gte", value: "10" }],
+ },
+ });
+ expect(result.map((i) => i.id)).toEqual(["B"]);
+ });
+});
diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.ts
index 7965a1b97d..e5b973a820 100644
--- a/packages/views/issues/utils/filter.ts
+++ b/packages/views/issues/utils/filter.ts
@@ -1,4 +1,4 @@
-import type { Issue, IssueStatus, IssuePriority, IssueAssigneeGroup } from "@multica/core/types";
+import type { Issue, IssueStatus, IssuePriority, IssueAssigneeGroup, PropertyFilterValue, PropertyOperatorFilter } from "@multica/core/types";
import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";
import type { IssueActivityState } from "../surface/activity";
@@ -15,9 +15,9 @@ export interface IssueFilters {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
- /** Custom-property filters: definition id → selected option ids (OR within
+ /** Custom-property filters: definition id → selected values (OR within
* a definition, AND across definitions; checkbox uses "true"/"false"). */
- propertyFilters?: Record<string, string[]>;
+ propertyFilters?: Record<string, PropertyFilterValue[]>;
// When `agentRunningFilter` is true, only keep issues whose id is in
// `runningIssueIds`. The surface derives this set from the independent
// `/api/working-agents` projection so filter.ts stays free of fetching.
@@ -41,7 +41,7 @@ export interface IssueFilterState {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
- propertyFilters?: Record<string, string[]>;
+ propertyFilters?: Record<string, PropertyFilterValue[]>;
workingOnly: boolean;
/** See IssueFilters.showSubIssues — only an explicit `false` hides. */
showSubIssues?: boolean;
@@ -60,16 +60,77 @@ export interface IssueFilterContext {
*/
export const NO_PROPERTY_VALUE = "__none__";
+/**
+ * Match one stored value against one operator filter member. Mirrors the
+ * server-side operator predicates in `parsePropertiesFilterParam`
+ * (`server/internal/handler/property.go`):
+ *
+ * - `contains` is a case-insensitive substring test over stored strings only
+ * (the server's guarded `ILIKE '%…%'`), so "Foo" and "foo" agree.
+ * - `gt`/`gte`/`lt`/`lte` only match numeric stored values — the server
+ * guards with `jsonb_typeof(...) = 'number'`, so a text value is a miss
+ * here too.
+ * - `before`/`after` only match string values and compare lexicographically,
+ * which is chronological for the "YYYY-MM-DD" date-only strings the server
+ * stores and filters on.
+ *
+ * A missing key never matches an operator (the server's `->>` yields NULL,
+ * which no operator predicate satisfies) — handled by the caller before this
+ * runs.
+ */
+export function issueValueMatchesOperator(
+ value: NonNullable<Issue["properties"]>[string],
+ filter: PropertyOperatorFilter,
+): boolean {
+ switch (filter.op) {
+ case "contains": {
+ const needle = filter.value.toLowerCase();
+ // An empty needle would substring-match every value ("".includes("") is
+ // true); the server rejects an empty operator value outright, so the
+ // matcher must refuse it too rather than match-all on hand-edited
+ // saved-view blobs.
+ if (needle === "") return false;
+ if (typeof value === "string") return value.toLowerCase().includes(needle);
+ // Numbers, booleans, and arrays never match. Although jsonb ->> can
+ // serialize them, contains is deliberately a text/url operator on both
+ // the server and the client.
+ return false;
+ }
+ case "gt":
+ case "gte":
+ case "lt":
+ case "lte": {
+ if (typeof value !== "number") return false;
+ const bound = Number(filter.value);
+ if (!Number.isFinite(bound)) return false;
+ if (filter.op === "gt") return value > bound;
+ if (filter.op === "gte") return value >= bound;
+ if (filter.op === "lt") return value < bound;
+ return value <= bound;
+ }
+ case "before":
+ case "after": {
+ if (typeof value !== "string") return false;
+ return filter.op === "before" ? value < filter.value : value > filter.value;
+ }
+ default:
+ return false;
+ }
+}
+
/**
* Match one issue against the property filters. Select values are single
* option-id strings, multi_select values are option-id arrays, checkbox
- * values are booleans compared against the "true"/"false" pseudo-options.
- * An issue with no value for a filtered definition matches only when the
- * "No value" (NO_PROPERTY_VALUE) pseudo-option is selected for it.
+ * values are booleans compared against the "true"/"false" pseudo-options,
+ * and scalar definitions accept operator members (`PropertyOperatorFilter`)
+ * alongside plain equality strings. Within one definition any member
+ * matching is enough (OR); every definition must match (AND). An issue with
+ * no value for a filtered definition matches only when the "No value"
+ * (NO_PROPERTY_VALUE) pseudo-option is selected for it.
*/
export function issueMatchesPropertyFilters(
issue: Issue,
- propertyFilters: Record<string, string[]> | undefined,
+ propertyFilters: Record<string, PropertyFilterValue[]> | undefined,
): boolean {
if (!propertyFilters) return true;
for (const [propertyId, selected] of Object.entries(propertyFilters)) {
@@ -79,23 +140,26 @@ export function issueMatchesPropertyFilters(
if (selected.includes(NO_PROPERTY_VALUE)) continue;
return false;
}
- if (typeof value === "string") {
- // Skip the "No value" sentinel when comparing stored values: a literal
- // "__none__" text value is a real value (the server's key-absence
- // predicate excludes it from a No-value filter), and this path must
- // agree with the server.
- if (!selected.some((id) => id !== NO_PROPERTY_VALUE && id === value)) return false;
- } else if (typeof value === "number") {
- // Compare numerically so "3.50" and 3.5 agree with the server's jsonb
- // number containment; NO_PROPERTY_VALUE never matches a set value.
- if (!selected.some((id) => id !== NO_PROPERTY_VALUE && Number(id) === value)) return false;
- } else if (Array.isArray(value)) {
- if (!value.some((id) => selected.includes(id))) return false;
- } else if (typeof value === "boolean") {
- if (!selected.includes(String(value))) return false;
- } else {
- return false;
- }
+ const matched = selected.some((member) => {
+ if (member === NO_PROPERTY_VALUE) {
+ // The sentinel never matches a SET value: a literal "__none__" text
+ // value is a real value (the server's key-absence predicate excludes
+ // it from a No-value filter), and this path must agree with the
+ // server.
+ return false;
+ }
+ if (typeof member === "string") {
+ if (typeof value === "string") return member === value;
+ // Compare numerically so "3.50" and 3.5 agree with the server's
+ // jsonb number containment.
+ if (typeof value === "number") return Number(member) === value;
+ if (Array.isArray(value)) return value.includes(member);
+ if (typeof value === "boolean") return member === String(value);
+ return false;
+ }
+ return issueValueMatchesOperator(value, member);
+ });
+ if (!matched) return false;
}
return true;
}
@@ -229,7 +293,7 @@ export function filterAssigneeGroups(
showSubIssues?: boolean;
agentRunningFilter?: boolean;
runningIssueIds?: ReadonlySet<string>;
- propertyFilters?: Record<string, string[]>;
+ propertyFilters?: Record<string, PropertyFilterValue[]>;
},
): IssueAssigneeGroup[] | undefined {
const applyRunning = filters.agentRunningFilter === true;
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 9452d81c08..d3d6958814 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -123,6 +123,9 @@
"section_priority": "Priority",
"section_assignee": "Assignee",
"section_creator": "Creator",
+ "chip_op_contains": "contains {{value}}",
+ "chip_op_before": "before {{value}}",
+ "chip_op_after": "after {{value}}",
"section_project": "Project",
"section_label": "Label",
"section_date": "Date",
@@ -726,6 +729,11 @@
"custom_property": {
"empty": "Empty",
"none": "No value",
+ "op_is": "is",
+ "op_contains": "contains",
+ "op_before": "before",
+ "op_after": "after",
+ "operator_label": "Filter operator",
"true_label": "Yes",
"false_label": "No",
"value_placeholder": "Enter value…",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 3d27de367e..13e50f2b35 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -122,6 +122,9 @@
"section_priority": "優先度",
"section_assignee": "担当者",
"section_creator": "作成者",
+ "chip_op_contains": "{{value}} を含む",
+ "chip_op_before": "{{value}} より前",
+ "chip_op_after": "{{value}} より後",
"section_project": "プロジェクト",
"section_label": "ラベル",
"section_date": "日付",
@@ -695,6 +698,11 @@
"custom_property": {
"empty": "空",
"none": "値なし",
+ "op_is": "等しい",
+ "op_contains": "含む",
+ "op_before": "より前",
+ "op_after": "より後",
+ "operator_label": "フィルター演算子",
"true_label": "はい",
"false_label": "いいえ",
"value_placeholder": "値を入力…",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index c2969dccf8..3bd5e17bf7 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -122,6 +122,9 @@
"section_priority": "우선순위",
"section_assignee": "담당자",
"section_creator": "생성자",
+ "chip_op_contains": "{{value}} 포함",
+ "chip_op_before": "{{value}} 이전",
+ "chip_op_after": "{{value}} 이후",
"section_project": "프로젝트",
"section_label": "라벨",
"section_date": "날짜",
@@ -695,6 +698,11 @@
"custom_property": {
"empty": "비어 있음",
"none": "값 없음",
+ "op_is": "같음",
+ "op_contains": "포함",
+ "op_before": "이전",
+ "op_after": "이후",
+ "operator_label": "필터 연산자",
"true_label": "예",
"false_label": "아니요",
"value_placeholder": "값 입력…",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 4b5018ba29..c31c008657 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -122,6 +122,9 @@
"section_priority": "优先级",
"section_assignee": "负责人",
"section_creator": "创建者",
+ "chip_op_contains": "包含 {{value}}",
+ "chip_op_before": "早于 {{value}}",
+ "chip_op_after": "晚于 {{value}}",
"section_project": "项目",
"section_label": "标签",
"section_date": "日期",
@@ -704,7 +707,12 @@
"archived_hint": "已归档属性——值为只读",
"unknown_value": "无法显示",
"unknown_value_hint": "该值由更新版本的 Multica 设置,当前版本无法编辑——请更新应用,或清除该值",
- "none": "未设置"
+ "none": "未设置",
+ "op_is": "等于",
+ "op_contains": "包含",
+ "op_before": "早于",
+ "op_after": "晚于",
+ "operator_label": "筛选运算符"
},
"filter_options_aria": "筛选选项",
"no_results": "无结果",
diff --git a/server/internal/handler/issue_table_facets.go b/server/internal/handler/issue_table_facets.go
index d01ee1aa9a..ce798e5865 100644
--- a/server/internal/handler/issue_table_facets.go
+++ b/server/internal/handler/issue_table_facets.go
@@ -2,6 +2,7 @@ package handler
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"log/slog"
@@ -43,9 +44,9 @@ func issueTableQueryWithoutFacet(input issueTableQuerySpec, facet issueTableFace
output := input
output.Filters = input.Filters
if input.Filters.Properties != nil {
- output.Filters.Properties = make(map[string][]string, len(input.Filters.Properties))
+ output.Filters.Properties = make(map[string][]json.RawMessage, len(input.Filters.Properties))
for propertyID, values := range input.Filters.Properties {
- output.Filters.Properties[propertyID] = append([]string(nil), values...)
+ output.Filters.Properties[propertyID] = append([]json.RawMessage(nil), values...)
}
}
diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.go
index 8e5259892d..8820a8a2f8 100644
--- a/server/internal/handler/issue_table_query.go
+++ b/server/internal/handler/issue_table_query.go
@@ -89,7 +89,9 @@ type issueTableFiltersRequest struct {
ProjectIDs []string `json:"project_ids,omitempty"`
IncludeNoProject bool `json:"include_no_project,omitempty"`
LabelIDs []string `json:"label_ids,omitempty"`
- Properties map[string][]string `json:"properties,omitempty"`
+ // Members are raw JSON so operator objects ({op, value}) and plain
+ // strings both survive the round-trip into parsePropertiesFilterParam.
+ Properties map[string][]json.RawMessage `json:"properties,omitempty"`
Date *issueTableDateFilterRequest `json:"date,omitempty"`
WorkingOnly bool `json:"working_only,omitempty"`
WorkingIssueIDs []string `json:"working_issue_ids,omitempty"`
@@ -259,7 +261,7 @@ func canonicalIssueTableFingerprint(workspaceID string, spec issueTableQuerySpec
normalized.Filters.WorkingIssueIDs = sortedUniqueStrings(normalized.Filters.WorkingIssueIDs)
normalized.Filters.Creators = sortedUniqueActors(normalized.Filters.Creators)
for key, values := range normalized.Filters.Properties {
- normalized.Filters.Properties[key] = sortedUniqueStrings(values)
+ normalized.Filters.Properties[key] = sortedUniqueRawJSON(values)
}
encoded, err := json.Marshal(struct {
WorkspaceID string `json:"workspace_id"`
@@ -303,6 +305,32 @@ func sortedUniqueStrings(values []string) []string {
return result
}
+// sortedUniqueRawJSON canonicalizes property filter members for the query
+// fingerprint: byte-exact dedup + ordering. Members are raw JSON (strings and
+// operator objects), and marshaling the map back into the fingerprint input
+// must reproduce the same bytes for the same query regardless of member order.
+func sortedUniqueRawJSON(values []json.RawMessage) []json.RawMessage {
+ if len(values) == 0 {
+ return nil
+ }
+ seen := make(map[string]struct{}, len(values))
+ unique := make([]string, 0, len(values))
+ for _, value := range values {
+ key := string(value)
+ if _, exists := seen[key]; exists {
+ continue
+ }
+ seen[key] = struct{}{}
+ unique = append(unique, key)
+ }
+ sort.Strings(unique)
+ result := make([]json.RawMessage, len(unique))
+ for i, value := range unique {
+ result[i] = json.RawMessage(value)
+ }
+ return result
+}
+
func sortedUniqueActors(values []issueTableActorRef) []issueTableActorRef {
seen := make(map[string]issueTableActorRef, len(values))
for _, value := range values {
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index 69c0cc7c27..07c5370cb4 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -1079,16 +1079,105 @@ const (
// cannot collide with a real option id (select option ids are UUIDs and
// checkbox uses "true"/"false").
noPropertyValue = "__none__"
+ // operatorPatternKey marks a compiled operator alternative (see
+ // parsePropertiesFilterParam). Neither this nor the sibling keys spell a
+ // UUID, so the marker can never collide with a containment pattern, whose
+ // single key is the definition id.
+ operatorPatternKey = "__op__"
)
+// propertyFilterOperator is a structured member of a properties filter —
+// {"op": "contains", "value": "foo"} — alongside plain string members, which
+// keep meaning exact equality. Op semantics:
+//
+// - contains: case-insensitive substring over the value's text form
+// (text / url).
+// - gt / gte / lt / lte: numeric comparison, matched only against stored
+// jsonb numbers (number).
+// - before / after: lexicographic comparison against stored strings, which
+// is chronological for the "YYYY-MM-DD" date-only strings date
+// properties store (date).
+type propertyFilterOperator struct {
+ Op string `json:"op"`
+ Value string `json:"value"`
+}
+
+// propertyOperatorPattern is the compiled operator alternative: the JSON
+// object {"__op__": "<op>", "def": "<definitionId>", "value": "<value>"} that
+// both propertiesFilterPredicate and the static ListOpenIssues unroll
+// recognize. For `contains` the value is stored already ILIKE-escaped so both
+// consumers can concatenate it into the pattern directly.
+type propertyOperatorPattern struct {
+ Op string `json:"__op__"`
+ Def string `json:"def"`
+ Value string `json:"value"`
+}
+
+var propertyFilterOps = map[string]string{
+ "contains": "",
+ "gt": ">",
+ "gte": ">=",
+ "lt": "<",
+ "lte": "<=",
+ "before": "<",
+ "after": ">",
+}
+
+// escapeLikePattern escapes SQL LIKE wildcards for a literal substring match
+// under the default backslash escape character.
+func escapeLikePattern(s string) string {
+ replacer := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)
+ return replacer.Replace(s)
+}
+
+// validatePropertyFilterOperator checks one operator member and returns the
+// compiled pattern. The value rules mirror the legacy string rules: non-empty,
+// bounded, and only comparable shapes (a float for numeric ops, a real
+// date-only string for before/after).
+func validatePropertyFilterOperator(definitionID string, op propertyFilterOperator) (propertyOperatorPattern, error) {
+ if _, known := propertyFilterOps[op.Op]; !known {
+ return propertyOperatorPattern{}, fmt.Errorf("properties filter op %q is not supported", op.Op)
+ }
+ if op.Value == "" {
+ return propertyOperatorPattern{}, errors.New("properties filter operator values cannot be empty")
+ }
+ pattern := propertyOperatorPattern{Op: op.Op, Def: definitionID, Value: op.Value}
+ switch op.Op {
+ case "contains":
+ if utf8.RuneCountInString(op.Value) > maxPropertyTextValueLen {
+ return propertyOperatorPattern{}, fmt.Errorf("properties filter value must be %d characters or fewer", maxPropertyTextValueLen)
+ }
+ pattern.Value = escapeLikePattern(op.Value)
+ case "gt", "gte", "lt", "lte":
+ num, err := strconv.ParseFloat(op.Value, 64)
+ if err != nil || math.IsNaN(num) || math.IsInf(num, 0) {
+ return propertyOperatorPattern{}, fmt.Errorf("properties filter op %q requires a finite number", op.Op)
+ }
+ // Canonicalize to plain decimal before storing: ParseFloat accepts forms
+ // Postgres ::numeric rejects ("0x1p4" hex-float, "1_000" underscores on
+ // older PG), and the static open_only unroll casts this exact string
+ // inside SQL — an uncanonicalized value would 500 that path while the
+ // dynamic path (which binds the parsed float) succeeds.
+ pattern.Value = strconv.FormatFloat(num, 'f', -1, 64)
+ case "before", "after":
+ if _, err := time.Parse("2006-01-02", op.Value); err != nil {
+ return propertyOperatorPattern{}, fmt.Errorf("properties filter op %q requires a YYYY-MM-DD date", op.Op)
+ }
+ }
+ return pattern, nil
+}
+
// parsePropertiesFilterParam reads the `properties` query parameter — a JSON
// object of {<definitionId>: [<value>, ...]} — and compiles it into OR-groups
-// of containment objects: OR within a definition, AND across definitions.
+// of alternatives: OR within a definition, AND across definitions.
+//
+// A plain string member means equality; it expands to every containment form
+// it could match (option id string, array element, boolean, jsonb number),
+// and the forms that can't match are simply never satisfied. Values are
+// option ids for select/multi_select and "true"/"false" for checkbox.
//
-// Values are option ids for select/multi_select and "true"/"false" for
-// checkbox. The stored value shape differs per type (string, array element,
-// boolean), so each value expands to every containment form it could match;
-// forms that can't match are simply never satisfied.
+// An object member {"op", "value"} is a scalar operator (see
+// propertyFilterOperator) and compiles to one operator pattern.
//
// The special value noPropertyValue ("__none__") means "unset": it emits the
// marker object {"__none__": "<definitionId>"} that parseNoPropertyValuePattern
@@ -1099,7 +1188,7 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
if raw == "" {
return nil, true
}
- var parsed map[string][]string
+ var parsed map[string][]json.RawMessage
if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
writeError(w, http.StatusBadRequest, "properties filter must be a JSON object of {definitionId: [values]}")
return nil, false
@@ -1133,42 +1222,65 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
return true
}
hasNoValue := false
- for _, value := range values {
- if value == "" {
- writeError(w, http.StatusBadRequest, "properties filter values cannot be empty")
- return nil, false
- }
- if value == noPropertyValue {
- if hasNoValue {
+ for _, rawValue := range values {
+ // A plain string member keeps the legacy equality semantics.
+ var stringValue string
+ if err := json.Unmarshal(rawValue, &stringValue); err == nil {
+ value := stringValue
+ if value == "" {
+ writeError(w, http.StatusBadRequest, "properties filter values cannot be empty")
+ return nil, false
+ }
+ if value == noPropertyValue {
+ if hasNoValue {
+ continue
+ }
+ marker, err := json.Marshal(map[string]string{noPropertyValue: definitionID})
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "properties filter is invalid")
+ return nil, false
+ }
+ alternatives = append(alternatives, marker)
+ hasNoValue = true
continue
}
- marker, err := json.Marshal(map[string]string{noPropertyValue: definitionID})
- if err != nil {
- writeError(w, http.StatusBadRequest, "properties filter is invalid")
+ if !appendAlt(value) || !appendAlt([]string{value}) { // select string / multi_select element
return nil, false
}
- alternatives = append(alternatives, marker)
- hasNoValue = true
+ if value == "true" || value == "false" {
+ if !appendAlt(value == "true") { // checkbox boolean
+ return nil, false
+ }
+ }
+ if num, err := strconv.ParseFloat(value, 64); err == nil &&
+ !math.IsNaN(num) && !math.IsInf(num, 0) {
+ // number property scalar: a numeric filter value must match the
+ // stored jsonb number, not the string form appended above. NaN /
+ // Infinity are skipped: they are not representable as JSON, so
+ // marshaling them would 400 the whole filter.
+ if !appendAlt(num) {
+ return nil, false
+ }
+ }
continue
}
- if !appendAlt(value) || !appendAlt([]string{value}) { // select string / multi_select element
+ // An object member is a scalar operator.
+ var op propertyFilterOperator
+ if err := json.Unmarshal(rawValue, &op); err != nil || op.Op == "" {
+ writeError(w, http.StatusBadRequest, "properties filter values must be strings or {op, value} objects")
return nil, false
}
- if value == "true" || value == "false" {
- if !appendAlt(value == "true") { // checkbox boolean
- return nil, false
- }
+ pattern, err := validatePropertyFilterOperator(definitionID, op)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return nil, false
}
- if num, err := strconv.ParseFloat(value, 64); err == nil &&
- !math.IsNaN(num) && !math.IsInf(num, 0) {
- // number property scalar: a numeric filter value must match the
- // stored jsonb number, not the string form appended above. NaN /
- // Infinity are skipped: they are not representable as JSON, so
- // marshaling them would 400 the whole filter.
- if !appendAlt(num) {
- return nil, false
- }
+ buf, marshalErr := json.Marshal(pattern)
+ if marshalErr != nil {
+ writeError(w, http.StatusBadRequest, "properties filter is invalid")
+ return nil, false
}
+ alternatives = append(alternatives, buf)
}
totalAlternatives += len(alternatives)
groups = append(groups, alternatives)
@@ -1197,15 +1309,64 @@ func parseNoPropertyValuePattern(alt json.RawMessage) (string, bool) {
return defID, ok
}
-// propertiesFilterPredicate renders the AND-of-ORs containment check for a
-// compiled filter as plain `i.properties @> $n` disjunctions with one bind
-// parameter per alternative. Constant containment operands are what lets the
-// planner drive the jsonb_path_ops GIN index (a correlated
+// parseOperatorPattern reports whether an alternative is a compiled scalar
+// operator (see parsePropertiesFilterParam) and returns its parts. Containment
+// patterns never carry the "__op__" key, so the two shapes cannot be confused.
+func parseOperatorPattern(alt json.RawMessage) (propertyOperatorPattern, bool) {
+ var marker map[string]string
+ if err := json.Unmarshal(alt, &marker); err != nil {
+ return propertyOperatorPattern{}, false
+ }
+ op, hasOp := marker[operatorPatternKey]
+ def, hasDef := marker["def"]
+ if !hasOp || !hasDef {
+ return propertyOperatorPattern{}, false
+ }
+ return propertyOperatorPattern{Op: op, Def: def, Value: marker["value"]}, true
+}
+
+// operatorPatternPredicate renders one operator alternative as SQL. Ops were
+// validated at parse time, so the re-parses below cannot fail for compiled
+// input; a malformed pattern degrades to FALSE rather than matching.
+func operatorPatternPredicate(pattern propertyOperatorPattern, addArg func(any) string) string {
+ defArg := addArg(pattern.Def)
+ switch pattern.Op {
+ case "contains":
+ // Value is ILIKE-escaped at parse time. Restrict substring matching to
+ // stored strings: ->> also serializes numbers, booleans, and arrays, while
+ // the client matcher intentionally treats contains as a text/url operator.
+ return fmt.Sprintf("(jsonb_typeof(i.properties -> %s) = 'string' AND (i.properties ->> %s) ILIKE '%%' || %s || '%%')",
+ defArg, defArg, addArg(pattern.Value))
+ case "gt", "gte", "lt", "lte":
+ // Bind the canonical decimal as numeric on every serving path. CASE makes
+ // the jsonb type guard structural instead of relying on SQL qualifier
+ // evaluation order before the cast.
+ num, err := strconv.ParseFloat(pattern.Value, 64)
+ if err != nil || math.IsNaN(num) || math.IsInf(num, 0) {
+ return "FALSE"
+ }
+ canonical := strconv.FormatFloat(num, 'f', -1, 64)
+ return fmt.Sprintf("(CASE WHEN jsonb_typeof(i.properties -> %s) = 'number' THEN (i.properties ->> %s)::numeric END %s %s::numeric)",
+ defArg, defArg, propertyFilterOps[pattern.Op], addArg(canonical))
+ case "before", "after":
+ return fmt.Sprintf("(jsonb_typeof(i.properties -> %s) = 'string' AND i.properties ->> %s %s %s)",
+ defArg, defArg, propertyFilterOps[pattern.Op], addArg(pattern.Value))
+ default:
+ return "FALSE"
+ }
+}
+
+// propertiesFilterPredicate renders the AND-of-ORs filter check with one bind
+// parameter per alternative. Equality alternatives are plain
+// `i.properties @> $n` containment disjunctions — constant operands are what
+// lets the planner drive the jsonb_path_ops GIN index (a correlated
// jsonb_array_elements form defeats it — verified via EXPLAIN in review).
//
// A "no value" marker alternative renders as a key-absence disjunction —
// `NOT (i.properties ? $m)` — which cannot use the GIN index but is exact for
-// the unset state (property values are never null; DELETE unsets).
+// the unset state (property values are never null; DELETE unsets). An operator
+// alternative renders as its typed comparison (ILIKE / numeric / date string),
+// also unindexed: scalar ranges fundamentally cannot use a containment index.
func propertiesFilterPredicate(groups [][]json.RawMessage, addArg func(any) string) string {
groupSQL := make([]string, 0, len(groups))
for _, alternatives := range groups {
@@ -1215,6 +1376,10 @@ func propertiesFilterPredicate(groups [][]json.RawMessage, addArg func(any) stri
ors = append(ors, fmt.Sprintf("NOT (i.properties ? %s)", addArg(defID)))
continue
}
+ if pattern, ok := parseOperatorPattern(alt); ok {
+ ors = append(ors, operatorPatternPredicate(pattern, addArg))
+ continue
+ }
ors = append(ors, fmt.Sprintf("i.properties @> %s::jsonb", addArg(string(alt))))
}
groupSQL = append(groupSQL, "("+strings.Join(ors, " OR ")+")")
diff --git a/server/internal/handler/property_test.go b/server/internal/handler/property_test.go
index e439e499c9..40c151bb42 100644
--- a/server/internal/handler/property_test.go
+++ b/server/internal/handler/property_test.go
@@ -1303,3 +1303,309 @@ func createPropertyTestMember(t *testing.T) string {
}
return userID
}
+
+func TestParsePropertiesFilterOperatorUnit(t *testing.T) {
+ defID := uuid.NewString()
+ w := httptest.NewRecorder()
+ var args []any
+ addArg := func(v any) string {
+ args = append(args, v)
+ return fmt.Sprintf("$%d", len(args))
+ }
+
+ // A contains member compiles to the operator pattern (with the LIKE
+ // wildcards escaped) and renders as an ILIKE predicate, never as a
+ // containment pattern or the no-value marker.
+ groups, ok := parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":[{"op":"contains","value":"50%% off"}]}`, defID))
+ if !ok {
+ t.Fatalf("contains parse failed: %s", w.Body.String())
+ }
+ if len(groups) != 1 || len(groups[0]) != 1 {
+ t.Fatalf("expected one group with one alternative, got %d / %d", len(groups), len(groups[0]))
+ }
+ if _, isMarker := parseNoPropertyValuePattern(groups[0][0]); isMarker {
+ t.Fatalf("operator alternative misdetected as the no-value marker")
+ }
+ pattern, isOp := parseOperatorPattern(groups[0][0])
+ if !isOp || pattern.Op != "contains" || pattern.Def != defID {
+ t.Fatalf("expected contains operator pattern, got %+v isOp=%v", pattern, isOp)
+ }
+ if pattern.Value != `50\% off` {
+ t.Fatalf("contains value not LIKE-escaped: %q", pattern.Value)
+ }
+ args = nil
+ sql := propertiesFilterPredicate(groups, addArg)
+ if !strings.Contains(sql, "jsonb_typeof") || !strings.Contains(sql, "= 'string'") ||
+ !strings.Contains(sql, "ILIKE") || strings.Contains(sql, "@>") {
+ t.Fatalf("contains predicate wrong: %s", sql)
+ }
+
+ // Numeric ops validate their value and render the typed comparison.
+ groups, ok = parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":[{"op":"gte","value":"3.5"}]}`, defID))
+ if !ok {
+ t.Fatalf("gte parse failed: %s", w.Body.String())
+ }
+ args = nil
+ sql = propertiesFilterPredicate(groups, addArg)
+ if !strings.Contains(sql, "CASE WHEN") || !strings.Contains(sql, "::numeric END >= $") ||
+ !strings.Contains(sql, "::numeric)") {
+ t.Fatalf("gte predicate wrong: %s", sql)
+ }
+ // The canonical decimal stays a string bind and is explicitly cast to
+ // numeric, matching the static open_only path without float8 demotion.
+ last := args[len(args)-1]
+ if value, isString := last.(string); !isString || value != "3.5" {
+ t.Fatalf("gte bind arg must be canonical string 3.5, got %T %v", last, last)
+ }
+
+ // ParseFloat accepts forms Postgres ::numeric rejects (hex-float,
+ // underscores); the compiled pattern must store the canonical plain
+ // decimal or the static open_only unroll would 500 on the cast.
+ groups, ok = parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":[{"op":"gt","value":"0x1p4"}]}`, defID))
+ if !ok {
+ t.Fatalf("hex-float parse failed: %s", w.Body.String())
+ }
+ pattern, isOp = parseOperatorPattern(groups[0][0])
+ if !isOp || pattern.Value != "16" {
+ t.Fatalf("hex-float bound not canonicalized to 16: %+v isOp=%v", pattern, isOp)
+ }
+
+ // Date ops render the lexicographic string comparison.
+ groups, ok = parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":[{"op":"before","value":"2026-02-01"}]}`, defID))
+ if !ok {
+ t.Fatalf("before parse failed: %s", w.Body.String())
+ }
+ args = nil
+ sql = propertiesFilterPredicate(groups, addArg)
+ if !strings.Contains(sql, "= 'string' AND") || !strings.Contains(sql, "< $") {
+ t.Fatalf("before predicate wrong: %s", sql)
+ }
+
+ // An operator composes OR-style with legacy equality members and the
+ // no-value sentinel in one group.
+ groups, ok = parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":["3.5",{"op":"lt","value":"10"},"__none__"]}`, defID))
+ if !ok {
+ t.Fatalf("mixed parse failed: %s", w.Body.String())
+ }
+ // "3.5" expands to 3 containment forms, the operator is 1, the marker 1.
+ if len(groups[0]) != 5 {
+ t.Fatalf("expected 5 alternatives, got %d", len(groups[0]))
+ }
+
+ // Invalid members are rejected with a 400.
+ for name, raw := range map[string]string{
+ "unknown op": `{"op":"regex","value":"x"}`,
+ "empty value": `{"op":"contains","value":""}`,
+ "non-numeric": `{"op":"gt","value":"abc"}`,
+ "NaN": `{"op":"lt","value":"NaN"}`,
+ "bad date": `{"op":"before","value":"02/01/2026"}`,
+ "missing value": `{"op":"contains"}`,
+ } {
+ w = httptest.NewRecorder()
+ _, ok := parsePropertiesFilterParam(w, fmt.Sprintf(`{"%s":[%s]}`, defID, raw))
+ if ok {
+ t.Fatalf("%s: expected rejection", name)
+ }
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("%s: expected 400, got %d", name, w.Code)
+ }
+ }
+}
+
+func TestListIssuesPropertyFilterOperators(t *testing.T) {
+ text := createTestProperty(t, map[string]any{"name": "OT" + uuid.NewString()[:8], "type": "text"})
+ num := createTestProperty(t, map[string]any{"name": "ON" + uuid.NewString()[:8], "type": "number"})
+ date := createTestProperty(t, map[string]any{"name": "OD" + uuid.NewString()[:8], "type": "date"})
+ box := createTestProperty(t, map[string]any{"name": "OB" + uuid.NewString()[:8], "type": "checkbox"})
+ multi := createTestProperty(t, map[string]any{
+ "name": "OM" + uuid.NewString()[:8], "type": "multi_select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "Alpha", "color": "#3b82f6"},
+ {"name": "Beta", "color": "#22c55e"},
+ }},
+ })
+
+ marker := uuid.NewString()[:8]
+ helloWorld := "Alpha " + marker + " World"
+ percentDone := "100% done " + marker
+ hasText := createPropertyTestIssue(t, "op text")
+ hasAll := createPropertyTestIssue(t, "op all")
+ empty := createPropertyTestIssue(t, "op empty")
+ if w := setIssuePropertyRaw(t, hasText, text.ID, percentDone); w.Code != http.StatusOK {
+ t.Fatalf("seed text: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasText, date.ID, "2026-01-10"); w.Code != http.StatusOK {
+ t.Fatalf("seed text date: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasAll, text.ID, helloWorld); w.Code != http.StatusOK {
+ t.Fatalf("seed text2: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasAll, num.ID, 15); w.Code != http.StatusOK {
+ t.Fatalf("seed num: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasAll, date.ID, "2026-03-01"); w.Code != http.StatusOK {
+ t.Fatalf("seed date: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasAll, box.ID, true); w.Code != http.StatusOK {
+ t.Fatalf("seed checkbox: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, hasAll, multi.ID, []string{multi.Config.Options[0].ID}); w.Code != http.StatusOK {
+ t.Fatalf("seed multi-select: %d %s", w.Code, w.Body.String())
+ }
+
+ listIssues := func(query string) (int, []IssueResponse) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.ListIssues(w, newRequest("GET", "/api/issues"+query, nil))
+ if w.Code != http.StatusOK {
+ return w.Code, nil
+ }
+ var resp struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ json.NewDecoder(w.Body).Decode(&resp)
+ return w.Code, resp.Issues
+ }
+ opQuery := func(defID string, members ...any) string {
+ buf, _ := json.Marshal(map[string]any{defID: members})
+ return "?limit=50&properties=" + url.QueryEscape(string(buf))
+ }
+ expect := func(query string, want ...string) {
+ t.Helper()
+ code, got := listIssues(query)
+ if code != http.StatusOK {
+ t.Fatalf("ListIssues%s: expected 200, got %d", query, code)
+ }
+ present := map[string]bool{}
+ for _, issue := range got {
+ present[issue.ID] = true
+ }
+ for _, id := range want {
+ if !present[id] {
+ t.Fatalf("query %s missed issue %s", query, id)
+ }
+ }
+ // Every returned issue must carry a matching value for the filtered
+ // definition (or none, when "__none__" is a member) — checked by the
+ // negative assertions at each call site.
+ return
+ }
+ notPresent := func(query, id string) {
+ t.Helper()
+ _, got := listIssues(query)
+ for _, issue := range got {
+ if issue.ID == id {
+ t.Fatalf("query %s unexpectedly matched issue %s", query, id)
+ }
+ }
+ }
+
+ // contains is case-insensitive and matches fragments.
+ expect(opQuery(text.ID, map[string]any{"op": "contains", "value": "world"}), hasAll)
+ notPresent(opQuery(text.ID, map[string]any{"op": "contains", "value": "world"}), hasText)
+ // The % in the needle is a literal percent, not a wildcard.
+ expect(opQuery(text.ID, map[string]any{"op": "contains", "value": "% done"}), hasText)
+ notPresent(opQuery(text.ID, map[string]any{"op": "contains", "value": "% done"}), hasAll)
+ // contains is string-only even when a hand-edited URL applies it to another
+ // property type. jsonb ->> would otherwise stringify both values and match.
+ containsNumber := opQuery(num.ID, map[string]any{"op": "contains", "value": "15"})
+ notPresent(containsNumber, hasAll)
+ notPresent(containsNumber+"&open_only=true", hasAll)
+ containsBoolean := opQuery(box.ID, map[string]any{"op": "contains", "value": "true"})
+ notPresent(containsBoolean, hasAll)
+ notPresent(containsBoolean+"&open_only=true", hasAll)
+ containsArray := opQuery(multi.ID, map[string]any{"op": "contains", "value": multi.Config.Options[0].ID[:8]})
+ notPresent(containsArray, hasAll)
+ notPresent(containsArray+"&open_only=true", hasAll)
+
+ // Numeric comparison matches stored jsonb numbers only.
+ expect(opQuery(num.ID, map[string]any{"op": "gt", "value": "10"}), hasAll)
+ notPresent(opQuery(num.ID, map[string]any{"op": "gt", "value": "10"}), hasText)
+ expect(opQuery(num.ID, map[string]any{"op": "gte", "value": "15"}), hasAll)
+ notPresent(opQuery(num.ID, map[string]any{"op": "lte", "value": "5"}), hasAll)
+
+ // Date comparison is chronological.
+ expect(opQuery(date.ID, map[string]any{"op": "before", "value": "2026-02-01"}), hasText)
+ notPresent(opQuery(date.ID, map[string]any{"op": "before", "value": "2026-02-01"}), hasAll)
+ expect(opQuery(date.ID, map[string]any{"op": "after", "value": "2026-02-01"}), hasAll)
+ notPresent(opQuery(date.ID, map[string]any{"op": "after", "value": "2026-02-01"}), hasText)
+
+ // An operator composes OR-style with the no-value sentinel.
+ noneOrAfter := opQuery(date.ID, map[string]any{"op": "after", "value": "2026-02-01"}, "__none__")
+ expect(noneOrAfter, hasAll, empty)
+ notPresent(noneOrAfter, hasText)
+
+ // AND across definitions still applies: text contains "world" AND
+ // number <= 5 matches nothing.
+ both, _ := json.Marshal(map[string]any{
+ text.ID: []any{map[string]any{"op": "contains", "value": "world"}},
+ num.ID: []any{map[string]any{"op": "lte", "value": "5"}},
+ })
+ notPresent("?limit=50&properties="+url.QueryEscape(string(both)), hasAll)
+
+ // Malformed operators are rejected outright.
+ for name, member := range map[string]map[string]any{
+ "unknown op": {"op": "regex", "value": "x"},
+ "empty value": {"op": "contains", "value": ""},
+ "bad number": {"op": "gt", "value": "15x"},
+ "bad date": {"op": "before", "value": "March 1"},
+ } {
+ if code, _ := listIssues(opQuery(num.ID, member)); code != http.StatusBadRequest {
+ t.Fatalf("%s: expected 400, got %d", name, code)
+ }
+ }
+
+ // The static ListOpenIssues unroll agrees with the dynamic predicates.
+ expect(opQuery(text.ID, map[string]any{"op": "contains", "value": "world"})+"&open_only=true", hasAll)
+ notPresent(opQuery(text.ID, map[string]any{"op": "contains", "value": "world"})+"&open_only=true", hasText)
+ expect(opQuery(num.ID, map[string]any{"op": "gte", "value": "15"})+"&open_only=true", hasAll)
+ expect(noneOrAfter+"&open_only=true", hasAll, empty)
+ notPresent(noneOrAfter+"&open_only=true", hasText)
+
+ // A ParseFloat-only bound form (hex-float) must behave identically on the
+ // dynamic and the static open_only path — an uncanonicalized raw string
+ // would 500 the static ::numeric cast.
+ expect(opQuery(num.ID, map[string]any{"op": "lt", "value": "0x1p4"}), hasAll)
+ expect(opQuery(num.ID, map[string]any{"op": "lt", "value": "0x1p4"})+"&open_only=true", hasAll)
+ notPresent(opQuery(num.ID, map[string]any{"op": "lt", "value": "0x1p4"})+"&open_only=true", hasText)
+
+ // Issues without the filtered key never match an operator on either path —
+ // the guards (ILIKE-NULL / jsonb_typeof / IS NOT NULL) exclude the seeded
+ // "empty" issue, which is open and matches the same queries pre-guard.
+ notPresent(opQuery(text.ID, map[string]any{"op": "contains", "value": "world"}), empty)
+ notPresent(opQuery(date.ID, map[string]any{"op": "before", "value": "2026-02-01"}), empty)
+ notPresent(opQuery(date.ID, map[string]any{"op": "after", "value": "2026-02-01"}), empty)
+ notPresent(opQuery(num.ID, map[string]any{"op": "gte", "value": "15"})+"&open_only=true", empty)
+
+ // The table-rows endpoint is the third serving path for the properties
+ // filter: members arrive as raw JSON in issueTableFiltersRequest, go
+ // through the byte-exact fingerprint canonicalization, and compile via the
+ // same parsePropertiesFilterParam the list endpoints use. Pin the path
+ // with operator members ANDed across two definitions.
+ rowsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(rowsRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", map[string]any{
+ "query": map[string]any{
+ "scope": map[string]any{"kind": "workspace"},
+ "filters": map[string]any{
+ "properties": map[string]any{
+ num.ID: []any{map[string]any{"op": "gte", "value": "15"}},
+ text.ID: []any{map[string]any{"op": "contains", "value": "world"}},
+ },
+ },
+ "sort": map[string]any{"field": "position", "direction": "asc"},
+ },
+ "group": map[string]any{"kind": "none"},
+ "hierarchy": map[string]any{"enabled": false},
+ "page": map[string]any{"limit": 10},
+ }))
+ if rowsRecorder.Code != http.StatusOK {
+ t.Fatalf("table rows with operator members: %d %s", rowsRecorder.Code, rowsRecorder.Body.String())
+ }
+ var rowsResponse issueTableRowsResponse
+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&rowsResponse); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+ if rowsResponse.Total != 1 || len(rowsResponse.Rows) != 1 || rowsResponse.Rows[0].Issue.ID != hasAll {
+ t.Fatalf("table rows operator filter wrong: total=%d rows=%d", rowsResponse.Total, len(rowsResponse.Rows))
+ }
+}
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index ff539416e7..4e7743f863 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -1226,11 +1226,15 @@ WHERE i.workspace_id = $1
AND ($7::uuid IS NULL OR i.project_id = $7)
AND ($8::jsonb IS NULL OR i.metadata @> $8::jsonb)
-- properties_filter is a jsonb array of groups, each group an array of
- -- containment patterns (built by parsePropertiesFilterParam): the issue
- -- must match at least one pattern from EVERY group (AND of ORs). A pattern
- -- of the shape {"__none__": "<definitionId>"} is the "no value" marker and
- -- matches when the issue's properties are missing that key. The correlated
- -- form skips the GIN index, which is fine here: open_only is already an
+ -- patterns (built by parsePropertiesFilterParam): the issue must match at
+ -- least one pattern from EVERY group (AND of ORs). Three pattern shapes:
+ -- {"__none__": "<definitionId>"} — "no value" marker;
+ -- {"<definitionId>": <value>, ...} — containment;
+ -- {"__op__": "<op>", "def": "<id>", "value": "<v>"} — scalar operator
+ -- (contains / gt / gte / lt / lte / before / after), where the contains
+ -- value arrives already ILIKE-escaped and the op was validated in Go, so
+ -- the per-op branches below only ever see legal values. The correlated
+ -- form skips the GIN index, which is fine here: open_only is an
-- unpaginated workspace scan. The terminal-status predicate intentionally
-- remains a filter rather than a positive index narrowing so unknown legacy
-- status keys stay visible.
@@ -1243,7 +1247,33 @@ WHERE i.workspace_id = $1
SELECT 1
FROM jsonb_array_elements(pf.alternatives) AS alt(pattern)
WHERE (alt.pattern ? '__none__' AND NOT (i.properties ? (alt.pattern ->> '__none__')))
- OR (NOT (alt.pattern ? '__none__') AND i.properties @> alt.pattern)
+ OR (NOT (alt.pattern ? '__none__') AND NOT (alt.pattern ? '__op__')
+ AND i.properties @> alt.pattern)
+ OR (alt.pattern ? '__op__'
+ AND i.properties ->> (alt.pattern ->> 'def') IS NOT NULL
+ AND (
+ (alt.pattern ->> '__op__' = 'contains'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND (i.properties ->> (alt.pattern ->> 'def')) ILIKE '%' || (alt.pattern ->> 'value') || '%')
+ OR (alt.pattern ->> '__op__' = 'gt'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END > (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'gte'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END >= (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'lt'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END < (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'lte'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END <= (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'before'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND i.properties ->> (alt.pattern ->> 'def') < (alt.pattern ->> 'value'))
+ OR (alt.pattern ->> '__op__' = 'after'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND i.properties ->> (alt.pattern ->> 'def') > (alt.pattern ->> 'value'))
+ ))
)
)
)
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 8975519bef..d9f6f43821 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -362,11 +362,15 @@ WHERE i.workspace_id = $1
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)
-- properties_filter is a jsonb array of groups, each group an array of
- -- containment patterns (built by parsePropertiesFilterParam): the issue
- -- must match at least one pattern from EVERY group (AND of ORs). A pattern
- -- of the shape {"__none__": "<definitionId>"} is the "no value" marker and
- -- matches when the issue's properties are missing that key. The correlated
- -- form skips the GIN index, which is fine here: open_only is already an
+ -- patterns (built by parsePropertiesFilterParam): the issue must match at
+ -- least one pattern from EVERY group (AND of ORs). Three pattern shapes:
+ -- {"__none__": "<definitionId>"} — "no value" marker;
+ -- {"<definitionId>": <value>, ...} — containment;
+ -- {"__op__": "<op>", "def": "<id>", "value": "<v>"} — scalar operator
+ -- (contains / gt / gte / lt / lte / before / after), where the contains
+ -- value arrives already ILIKE-escaped and the op was validated in Go, so
+ -- the per-op branches below only ever see legal values. The correlated
+ -- form skips the GIN index, which is fine here: open_only is an
-- unpaginated workspace scan. The terminal-status predicate intentionally
-- remains a filter rather than a positive index narrowing so unknown legacy
-- status keys stay visible.
@@ -379,7 +383,33 @@ WHERE i.workspace_id = $1
SELECT 1
FROM jsonb_array_elements(pf.alternatives) AS alt(pattern)
WHERE (alt.pattern ? '__none__' AND NOT (i.properties ? (alt.pattern ->> '__none__')))
- OR (NOT (alt.pattern ? '__none__') AND i.properties @> alt.pattern)
+ OR (NOT (alt.pattern ? '__none__') AND NOT (alt.pattern ? '__op__')
+ AND i.properties @> alt.pattern)
+ OR (alt.pattern ? '__op__'
+ AND i.properties ->> (alt.pattern ->> 'def') IS NOT NULL
+ AND (
+ (alt.pattern ->> '__op__' = 'contains'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND (i.properties ->> (alt.pattern ->> 'def')) ILIKE '%' || (alt.pattern ->> 'value') || '%')
+ OR (alt.pattern ->> '__op__' = 'gt'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END > (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'gte'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END >= (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'lt'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END < (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'lte'
+ AND CASE WHEN jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'number'
+ THEN (i.properties ->> (alt.pattern ->> 'def'))::numeric END <= (alt.pattern ->> 'value')::numeric)
+ OR (alt.pattern ->> '__op__' = 'before'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND i.properties ->> (alt.pattern ->> 'def') < (alt.pattern ->> 'value'))
+ OR (alt.pattern ->> '__op__' = 'after'
+ AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'
+ AND i.properties ->> (alt.pattern ->> 'def') > (alt.pattern ->> 'value'))
+ ))
)
)
)