Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(tasks): AI filter — describe task filters in plain English (#7061)

Wolf Mermelstein064f9733fc86
diff --git a/apps/web/src/components/view-shell/AiFilterInput.tsx b/apps/web/src/components/view-shell/AiFilterInput.tsx
new file mode 100644
index 0000000000..3d5d30f332
--- /dev/null
+++ b/apps/web/src/components/view-shell/AiFilterInput.tsx
@@ -0,0 +1,178 @@
+import SparkleIcon from '@phosphor/sparkle.svg';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { cn } from '@ui';
+import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+
+/** `applied` may carry a `note` explaining any part of the request left unmapped. */
+export type AiFilterOutcome =
+ | { status: 'applied'; note?: string }
+ | { status: 'error'; message: string };
+
+export type AiFilterInputProps = {
+ placeholder?: string;
+ /** Turns the description into filters and applies them. */
+ onSubmit: (query: string) => Promise<AiFilterOutcome>;
+ /** Fires after a fully mapped apply, e.g. so the host menu can close. */
+ onApplied?: () => void;
+ inputRef?: (element: HTMLInputElement) => void;
+};
+
+type Feedback = { tone: 'note' | 'error'; text: string };
+
+/**
+ * Plain-English filter box for list filter menus: type a description, press
+ * Enter, and the host resolves it into concrete filters. Lives inside a
+ * Kobalte menu, so key events the input owns stop here rather than reaching
+ * the menu's typeahead and arrow-key handling.
+ */
+export function AiFilterInput(props: AiFilterInputProps) {
+ const [value, setValue] = createSignal('');
+ const [pending, setPending] = createSignal(false);
+ const [feedback, setFeedback] = createSignal<Feedback>();
+ let requestId = 0;
+ onCleanup(() => {
+ requestId += 1;
+ });
+
+ const submit = async () => {
+ const query = value().trim();
+ if (!query || pending()) return;
+
+ requestId += 1;
+ const id = requestId;
+ setPending(true);
+ setFeedback(undefined);
+ const outcome = await props.onSubmit(query);
+ if (id !== requestId) return;
+
+ setPending(false);
+ if (outcome.status === 'error') {
+ setFeedback({ tone: 'error', text: outcome.message });
+ return;
+ }
+ setValue('');
+ if (outcome.note) {
+ setFeedback({ tone: 'note', text: outcome.note });
+ return;
+ }
+ props.onApplied?.();
+ };
+
+ let input: HTMLInputElement | undefined;
+ // Kobalte focuses whichever row the mouse passes over, which would drop
+ // focus mid-word when the pointer drifts below the box. Once the user has
+ // engaged with the box, a hover-caused blur hands focus straight back.
+ // Keyboard navigation, a click anywhere else, or focus moving into a
+ // submenu releases it so the rest of the menu behaves as usual.
+ let engaged = false;
+ const release = () => {
+ engaged = false;
+ };
+ const menuOf = (element: Element) => element.closest('[role="menu"]');
+
+ const handleBlur = (event: FocusEvent) => {
+ if (!engaged || !input) return;
+ const next = event.relatedTarget;
+ if (!(next instanceof Element) || menuOf(next) !== menuOf(input)) {
+ release();
+ return;
+ }
+ queueMicrotask(() => {
+ if (engaged && input?.isConnected && document.activeElement !== input) {
+ input.focus({ preventScroll: true });
+ }
+ });
+ };
+
+ onMount(() => {
+ const onDocumentPointerDown = (event: PointerEvent) => {
+ if (!(event.target instanceof Node) || !input?.contains(event.target)) {
+ release();
+ }
+ };
+ document.addEventListener('pointerdown', onDocumentPointerDown, true);
+ onCleanup(() =>
+ document.removeEventListener('pointerdown', onDocumentPointerDown, true)
+ );
+ });
+
+ const setInput = (element: HTMLInputElement) => {
+ input = element;
+ props.inputRef?.(element);
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ switch (event.key) {
+ case 'Enter':
+ event.preventDefault();
+ event.stopPropagation();
+ void submit();
+ return;
+ case 'Escape':
+ case 'ArrowDown':
+ case 'ArrowUp':
+ case 'Tab':
+ // The menu owns these: dismiss, or move focus into the option rows.
+ release();
+ return;
+ default:
+ // Caret movement and typing belong to the input, not menu typeahead.
+ event.stopPropagation();
+ }
+ };
+
+ return (
+ <div class="flex w-60 flex-col gap-1">
+ <div
+ class={cn(
+ 'flex h-8 items-center gap-2 rounded-lg border border-edge-muted bg-input px-2',
+ 'focus-within:border-accent'
+ )}
+ >
+ <Show
+ when={pending()}
+ fallback={<SparkleIcon class="size-3.5 shrink-0 text-ink-muted" />}
+ >
+ <SpinnerIcon class="size-3.5 shrink-0 animate-spin text-ink-muted" />
+ </Show>
+ <input
+ ref={setInput}
+ type="text"
+ aria-label="Filter with AI"
+ aria-busy={pending()}
+ value={value()}
+ readOnly={pending()}
+ placeholder={props.placeholder ?? 'Describe a filter…'}
+ autocomplete="off"
+ spellcheck={false}
+ class={cn(
+ 'min-w-0 flex-1 bg-transparent text-sm text-ink caret-accent outline-none placeholder:text-ink-placeholder',
+ pending() && 'opacity-60'
+ )}
+ onInput={(event) => {
+ engaged = true;
+ setValue(event.currentTarget.value);
+ }}
+ onPointerDown={() => {
+ engaged = true;
+ }}
+ onBlur={handleBlur}
+ onKeyDown={handleKeyDown}
+ />
+ </div>
+ <Show when={feedback()}>
+ {(item) => (
+ <p
+ role={item().tone === 'error' ? 'alert' : 'status'}
+ class={cn(
+ 'px-1 text-xs leading-snug',
+ item().tone === 'error' ? 'text-failure-ink' : 'text-ink-muted'
+ )}
+ >
+ {item().text}
+ </p>
+ )}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/view-shell/ListDropdowns.test.tsx b/apps/web/src/components/view-shell/ListDropdowns.test.tsx
index f122ec738f..e9c71dbbe1 100644
--- a/apps/web/src/components/view-shell/ListDropdowns.test.tsx
+++ b/apps/web/src/components/view-shell/ListDropdowns.test.tsx
@@ -7,6 +7,7 @@ import {
} from '@solidjs/testing-library';
import { createSignal, type ParentProps } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { AiFilterOutcome } from './AiFilterInput';
import { ListFilterDropdown } from './ListDropdowns';
// Exercise the actual menus/comboboxes without initializing the app UI barrel.
@@ -148,3 +149,109 @@ it('focuses searchable submenus on opening and reopening and supports keyboard s
await waitFor(() => expect(open()).toBe(false));
}
});
+
+function setupAiFilter(onSubmit: (query: string) => Promise<AiFilterOutcome>) {
+ const [open, setOpen] = createSignal(true);
+ render(() => (
+ <ListFilterDropdown
+ label="Filter tasks"
+ open={open()}
+ onOpenChange={setOpen}
+ groups={[
+ {
+ id: 'people',
+ label: 'Assignee',
+ options: [{ id: 'alice', label: 'Alice' }],
+ },
+ ]}
+ isSelected={() => false}
+ onSelectionChange={() => {}}
+ aiFilter={{ placeholder: 'Filter with AI…', onSubmit }}
+ />
+ ));
+ return { open };
+}
+
+it('focuses the AI input when the menu opens, with ArrowDown reaching the first row', async () => {
+ setupAiFilter(async () => ({ status: 'applied' }) as const);
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ await waitFor(() => expect(document.activeElement).toBe(input));
+ // Kobalte's deferred menu focus must not win afterwards.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(document.activeElement).toBe(input);
+
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByRole('menuitem', { name: 'Assignee' })
+ )
+ );
+});
+
+it('submits the AI filter description on Enter and closes once it applies', async () => {
+ const onSubmit = vi.fn(async () => ({ status: 'applied' }) as const);
+ const { open } = setupAiFilter(onSubmit);
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ fireEvent.input(input, { target: { value: 'high priority only' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onSubmit).toHaveBeenCalledWith('high priority only');
+ await waitFor(() => expect(open()).toBe(false));
+});
+
+it('keeps the menu open with feedback when the request only partly maps', async () => {
+ const { open } = setupAiFilter(async () => ({
+ status: 'applied',
+ note: 'Tags cannot be excluded.',
+ }));
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ fireEvent.input(input, { target: { value: 'no dev tasks' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect((await screen.findByRole('status')).textContent).toBe(
+ 'Tags cannot be excluded.'
+ );
+ expect(open()).toBe(true);
+ expect((input as HTMLInputElement).value).toBe('');
+});
+
+it('shows an error and keeps the description when the request fails', async () => {
+ const { open } = setupAiFilter(async () => ({
+ status: 'error',
+ message: 'AI filtering is unavailable right now.',
+ }));
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ fireEvent.input(input, { target: { value: 'urgent tasks' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'AI filtering is unavailable right now.'
+ );
+ expect(open()).toBe(true);
+ expect((input as HTMLInputElement).value).toBe('urgent tasks');
+});
+
+it('hands focus back to the AI input when a hovered row steals it mid-description', async () => {
+ setupAiFilter(async () => ({ status: 'applied' }) as const);
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ const row = screen.getByRole('menuitem', { name: 'Assignee' });
+ await waitFor(() => expect(document.activeElement).toBe(input));
+ fireEvent.input(input, { target: { value: 'urgent' } });
+ expect(document.activeElement).toBe(input);
+
+ // Kobalte focuses whichever row the mouse moves over.
+ row.focus();
+ await waitFor(() => expect(document.activeElement).toBe(input));
+
+ // Keyboard navigation is a deliberate hand-off and must stick.
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ row.focus();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(document.activeElement).toBe(row);
+});
+
+it('ignores Enter on an empty description and leaves the option rows reachable', async () => {
+ const onSubmit = vi.fn(async () => ({ status: 'applied' }) as const);
+ setupAiFilter(onSubmit);
+ const input = await screen.findByPlaceholderText('Filter with AI…');
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(screen.getByRole('menuitem', { name: 'Assignee' })).toBeTruthy();
+});
diff --git a/apps/web/src/components/view-shell/ListDropdowns.tsx b/apps/web/src/components/view-shell/ListDropdowns.tsx
index 03bda840b8..44d53939b5 100644
--- a/apps/web/src/components/view-shell/ListDropdowns.tsx
+++ b/apps/web/src/components/view-shell/ListDropdowns.tsx
@@ -7,7 +7,8 @@ import FilterIcon from '@phosphor/funnel-simple.svg';
import SortIcon from '@phosphor/sort-ascending.svg';
import GroupIcon from '@phosphor/stack.svg';
import { cn, Dropdown } from '@ui';
-import { batch, For, type JSX, Show } from 'solid-js';
+import { batch, createSignal, For, type JSX, Show } from 'solid-js';
+import { AiFilterInput, type AiFilterInputProps } from './AiFilterInput';
export type ListControlOption<TId extends string> = {
id: TId;
@@ -150,6 +151,11 @@ export type ListFilterDropdownProps<
selected: boolean
) => void;
onClear?: () => void;
+ /**
+ * Adds a plain-English box above the groups that resolves a description
+ * into a selection. The menu closes once a fully mapped request applies.
+ */
+ aiFilter?: Pick<AiFilterInputProps, 'placeholder' | 'onSubmit'>;
customTrigger?: JSX.Element;
triggerRef?: (element: HTMLButtonElement) => void;
label?: string;
@@ -162,6 +168,15 @@ export function ListFilterDropdown<
TGroupId extends string,
TOptionId extends string,
>(props: ListFilterDropdownProps<TGroupId, TOptionId>) {
+ let aiFilterInput: HTMLInputElement | undefined;
+ // Uncontrolled menus track their own state so the AI box can close them.
+ const [internalOpen, setInternalOpen] = createSignal(false);
+ const isOpen = () => props.open ?? internalOpen();
+ const setOpen = (open: boolean) => {
+ props.onOpenChange?.(open);
+ if (props.open === undefined) setInternalOpen(open);
+ };
+
const isGroupActive = (group: ListFilterGroup<TGroupId, TOptionId>) =>
props.isGroupActive?.(group.id) ??
group.options.some(
@@ -171,11 +186,7 @@ export function ListFilterDropdown<
);
return (
- <Dropdown
- open={props.open}
- onOpenChange={props.onOpenChange}
- placement="bottom-end"
- >
+ <Dropdown open={isOpen()} onOpenChange={setOpen} placement="bottom-end">
<Show
when={props.customTrigger}
fallback={
@@ -193,7 +204,35 @@ export function ListFilterDropdown<
>
{(trigger) => trigger()}
</Show>
- <Dropdown.Content class={cn('min-w-32', props.contentClass)}>
+ <Dropdown.Content
+ class={cn('min-w-32', props.contentClass)}
+ onOpenAutoFocus={(event) => {
+ if (!props.aiFilter) return;
+ event.preventDefault();
+ // Kobalte focuses the menu itself on a deferred tick; land after it.
+ setTimeout(() => {
+ requestAnimationFrame(() => {
+ if (aiFilterInput?.isConnected) {
+ aiFilterInput.focus({ preventScroll: true });
+ }
+ });
+ }, 0);
+ }}
+ >
+ <Show when={props.aiFilter}>
+ {(aiFilter) => (
+ <Dropdown.Group>
+ <AiFilterInput
+ placeholder={aiFilter().placeholder}
+ onSubmit={aiFilter().onSubmit}
+ onApplied={() => setOpen(false)}
+ inputRef={(element) => {
+ aiFilterInput = element;
+ }}
+ />
+ </Dropdown.Group>
+ )}
+ </Show>
<Dropdown.Group>
<For each={props.groups}>
{(group) => (
diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.ts
index 0519fc501d..06905503fb 100644
--- a/apps/web/src/components/view-shell/index.ts
+++ b/apps/web/src/components/view-shell/index.ts
@@ -1,3 +1,4 @@
+export type { AiFilterOutcome } from './AiFilterInput';
export {
CollapsibleSection,
type CollapsibleSectionRootProps,
diff --git a/apps/web/src/features/tasks-view/components/TasksControls.tsx b/apps/web/src/features/tasks-view/components/TasksControls.tsx
index d07109ebae..5df5452996 100644
--- a/apps/web/src/features/tasks-view/components/TasksControls.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksControls.tsx
@@ -78,6 +78,10 @@ export function TasksControls() {
isSelected={filters.isSelected}
onSelectionChange={filters.setSelected}
onClear={filters.clear}
+ aiFilter={{
+ placeholder: 'Filter with AI…',
+ onSubmit: filters.applyDescription,
+ }}
/>
<Show when={filters.activeCount() > 0}>
<span class="pointer-events-none absolute -top-0.5 right-0 z-10 flex size-4 translate-x-1/2 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">
diff --git a/apps/web/src/features/tasks-view/filters/ai-task-filter.test.ts b/apps/web/src/features/tasks-view/filters/ai-task-filter.test.ts
new file mode 100644
index 0000000000..449d1f3630
--- /dev/null
+++ b/apps/web/src/features/tasks-view/filters/ai-task-filter.test.ts
@@ -0,0 +1,269 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ type AiTaskFilterCatalog,
+ buildAiTaskFilterRequest,
+ buildAiTaskFilterResponseFormat,
+ buildAiTaskFilterSystemPrompt,
+ parseAiTaskFilterResponse,
+} from './ai-task-filter';
+
+vi.mock('@app/features/soup', async () => ({
+ ...(await import('@app/features/soup/filters')),
+}));
+vi.mock('@entity', async () => ({
+ ...(await import('@entity/types/entity')),
+ ...(await import('@entity/utils/notification')),
+ ...(await import('@entity/utils/task-properties')),
+ ...(await import('@entity/utils/company-properties')),
+}));
+vi.mock('@notifications', async () => await import('@notifications/types'));
+
+// The soup barrel these pull in transitively imports the websocket client
+// modules, which open real sockets at module scope and reject under jsdom.
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+const CATALOG: AiTaskFilterCatalog = {
+ people: [
+ { id: 'user-me', label: 'Wolf (me)' },
+ { id: 'user-teo', label: 'Teo' },
+ ],
+ tags: [
+ { id: 'tag-dev', label: 'Dev' },
+ { id: 'tag-design', label: 'Design' },
+ ],
+};
+
+const reply = (value: unknown) => JSON.stringify(value);
+
+describe('buildAiTaskFilterRequest', () => {
+ it('lists every selectable option with its id in the system prompt', () => {
+ const prompt = buildAiTaskFilterSystemPrompt(CATALOG);
+
+ for (const line of [
+ '- not-started: Not started',
+ '- completed: Completed',
+ '- urgent: Urgent',
+ '- low: Low',
+ '- user-me: Wolf (me)',
+ '- user-teo: Teo',
+ '- tag-dev: Dev',
+ ]) {
+ expect(prompt).toContain(line);
+ }
+ });
+
+ it('marks empty catalogs instead of omitting the group', () => {
+ const prompt = buildAiTaskFilterSystemPrompt({ people: [], tags: [] });
+ expect(prompt).toContain('assigned. Available:\n(none)');
+ expect(prompt).toContain('at least one of them. Available:\n(none)');
+ });
+
+ it('asks for strict JSON constrained to the known status and priority ids', () => {
+ const format = buildAiTaskFilterResponseFormat();
+ expect(format.type).toBe('json_schema');
+ expect(format.json_schema.strict).toBe(true);
+
+ const schema = format.json_schema.schema as {
+ required: string[];
+ additionalProperties: boolean;
+ properties: Record<string, { items?: { enum?: string[] } }>;
+ };
+ expect(schema.additionalProperties).toBe(false);
+ expect(schema.required).toEqual(
+ expect.arrayContaining([
+ 'status',
+ 'priority',
+ 'assignees',
+ 'createdBy',
+ 'tags',
+ 'search',
+ 'unresolved',
+ ])
+ );
+ expect(schema.properties.status?.items?.enum).toEqual([
+ 'not-started',
+ 'in-progress',
+ 'in-review',
+ 'completed',
+ 'canceled',
+ ]);
+ expect(schema.properties.priority?.items?.enum).toEqual([
+ 'urgent',
+ 'high',
+ 'medium',
+ 'low',
+ ]);
+ expect(schema.properties.assignees?.items?.enum).toBeUndefined();
+ });
+
+ it('sends the trimmed query as the user turn with a deterministic model call', () => {
+ const request = buildAiTaskFilterRequest(' high priority only ', CATALOG);
+ expect(request.temperature).toBe(0);
+ expect(request.messages.at(-1)).toEqual({
+ role: 'user',
+ content: 'high priority only',
+ });
+ expect(request.response_format?.type).toBe('json_schema');
+ });
+});
+
+describe('parseAiTaskFilterResponse', () => {
+ it('maps a well-formed reply onto the tasks facet selection', () => {
+ const result = parseAiTaskFilterResponse(
+ reply({
+ status: ['in-progress', 'in-review'],
+ priority: ['high', 'urgent'],
+ assignees: ['user-me'],
+ createdBy: ['user-teo'],
+ tags: ['tag-dev'],
+ search: '',
+ unresolved: '',
+ }),
+ CATALOG
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ plan: {
+ facets: {
+ status: ['in-progress', 'in-review'],
+ priority: ['high', 'urgent'],
+ assignees: ['user-me'],
+ 'created-by': ['user-teo'],
+ tags: ['tag-dev'],
+ },
+ search: undefined,
+ unresolved: undefined,
+ },
+ });
+ });
+
+ it('drops unknown ids and deduplicates while keeping the rest of the plan', () => {
+ const result = parseAiTaskFilterResponse(
+ reply({
+ status: ['completed', 'completed'],
+ priority: [],
+ assignees: ['user-nobody'],
+ createdBy: [],
+ tags: ['tag-dev', 'tag-missing'],
+ search: '',
+ unresolved: 'No one named Nobody was found.',
+ }),
+ CATALOG
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ plan: {
+ facets: { status: ['completed'], tags: ['tag-dev'] },
+ search: undefined,
+ unresolved: 'No one named Nobody was found.',
+ },
+ });
+ });
+
+ it('accepts person and tag labels in place of ids, ignoring case and whitespace', () => {
+ const result = parseAiTaskFilterResponse(
+ reply({
+ status: [],
+ priority: [],
+ assignees: [' teo '],
+ createdBy: [],
+ tags: ['design'],
+ search: '',
+ unresolved: '',
+ }),
+ CATALOG
+ );
+
+ expect(result.ok && result.plan.facets).toEqual({
+ assignees: ['user-teo'],
+ tags: ['tag-design'],
+ });
+ });
+
+ it('keeps a trimmed search term as part of the plan', () => {
+ const result = parseAiTaskFilterResponse(
+ reply({
+ status: [],
+ priority: [],
+ assignees: [],
+ createdBy: [],
+ tags: [],
+ search: ' billing ',
+ unresolved: '',
+ }),
+ CATALOG
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ plan: { facets: {}, search: 'billing', unresolved: undefined },
+ });
+ });
+
+ it('reports a reply that maps to nothing, carrying the model explanation', () => {
+ const result = parseAiTaskFilterResponse(
+ reply({
+ status: [],
+ priority: [],
+ assignees: [],
+ createdBy: [],
+ tags: [],
+ search: '',
+ unresolved: 'Tasks cannot be filtered by due date.',
+ }),
+ CATALOG
+ );
+
+ expect(result).toEqual({
+ ok: false,
+ error: 'NO_FILTERS',
+ unresolved: 'Tasks cannot be filtered by due date.',
+ });
+ });
+
+ it('rejects missing, malformed, or non-object replies', () => {
+ expect(parseAiTaskFilterResponse(undefined, CATALOG)).toEqual({
+ ok: false,
+ error: 'INVALID_JSON',
+ });
+ expect(parseAiTaskFilterResponse('not json', CATALOG)).toEqual({
+ ok: false,
+ error: 'INVALID_JSON',
+ });
+ expect(parseAiTaskFilterResponse('["high"]', CATALOG)).toEqual({
+ ok: false,
+ error: 'INVALID_JSON',
+ });
+ expect(
+ parseAiTaskFilterResponse('{"status":["completed"]}', CATALOG)
+ ).toEqual({ ok: false, error: 'INVALID_JSON' });
+ });
+
+ it('rejects status or priority values outside the schema enums', () => {
+ expect(
+ parseAiTaskFilterResponse(
+ reply({
+ status: ['archived'],
+ priority: [],
+ assignees: [],
+ createdBy: [],
+ tags: [],
+ search: '',
+ unresolved: '',
+ }),
+ CATALOG
+ )
+ ).toEqual({ ok: false, error: 'INVALID_JSON' });
+ });
+});
diff --git a/apps/web/src/features/tasks-view/filters/ai-task-filter.ts b/apps/web/src/features/tasks-view/filters/ai-task-filter.ts
new file mode 100644
index 0000000000..d211af6b07
--- /dev/null
+++ b/apps/web/src/features/tasks-view/filters/ai-task-filter.ts
@@ -0,0 +1,186 @@
+import { type FacetSelection, TAG_FACET_ID } from '@app/features/soup';
+import type OpenAI from 'openai';
+import { z } from 'zod';
+import { TASK_PRIORITY_OPTIONS, TASK_STATUS_OPTIONS } from './task-facets';
+
+type AiTaskFilterChoice = { id: string; label: string };
+
+/** Everything the model may pick from when turning a request into filters. */
+export type AiTaskFilterCatalog = {
+ people: AiTaskFilterChoice[];
+ tags: AiTaskFilterChoice[];
+};
+
+export type AiTaskFilterPlan = {
+ facets: FacetSelection;
+ /** Free-text search to apply when the request names task content. */
+ search?: string;
+ /** Short explanation of the parts of the request that have no matching filter. */
+ unresolved?: string;
+};
+
+const AI_TASK_FILTER_MODEL = 'gpt-4o-mini';
+
+/** Keep prompts bounded for workspaces with very large address books. */
+const MAX_CHOICES_PER_GROUP = 400;
+
+const RESPONSE_SCHEMA_NAME = 'task_filters';
+
+const optionIds = (options: { id: string }[]) => options.map(({ id }) => id);
+
+const formatChoices = (choices: AiTaskFilterChoice[]) =>
+ choices
+ .slice(0, MAX_CHOICES_PER_GROUP)
+ .map((choice) => `- ${choice.id}: ${choice.label}`)
+ .join('\n');
+
+const formatOptions = (options: { id: string; label: string }[]) =>
+ options.map((option) => `- ${option.id}: ${option.label}`).join('\n');
+
+export function buildAiTaskFilterSystemPrompt(
+ catalog: AiTaskFilterCatalog
+): string {
+ return [
+ 'You translate a plain-English description of which tasks to show into a set of task list filters.',
+ '',
+ 'Filter groups (each is a list of option ids; an empty list means "no filter on this group"):',
+ '- status: options selected are ORed together. Available:',
+ formatOptions(TASK_STATUS_OPTIONS),
+ '- priority: options selected are ORed together. Available:',
+ formatOptions(TASK_PRIORITY_OPTIONS),
+ '- assignees: person ids; the task must have at least one of them assigned. Available:',
+ catalog.people.length > 0 ? formatChoices(catalog.people) : '(none)',
+ '- createdBy: person ids; the task must have been created by one of them. Uses the same people as assignees.',
+ '- tags: tag ids; the task must carry at least one of them. Available:',
+ catalog.tags.length > 0 ? formatChoices(catalog.tags) : '(none)',
+ '- search: free text matched against task titles and content. Use it only for subject matter the user wants to SEE that no filter group covers (e.g. "tasks about billing" → "billing"). Otherwise return an empty string.',
+ '',
+ 'Rules:',
+ '- Groups are ANDed: a task must satisfy every non-empty group.',
+ '- Filters can only include options, never exclude them. To express an exclusion on status or priority, select every other option in that group (e.g. "not completed" → every status except completed; "no low priority" → urgent, high, medium).',
+ '- Exclusions on assignees, createdBy, or tags cannot be expressed. Leave that group empty and mention the request in "unresolved".',
+ '- Never put a negated or excluded term into "search" (e.g. "no dev tasks" must not search for "dev"); never use "search" to stand in for a person or tag that is not listed. Report those in "unresolved" instead.',
+ '- Terms like "open", "active", or "unfinished" mean not-started, in-progress, and in-review. "Done" or "finished" means completed. "Important" or "critical" means urgent and high.',
+ '- The person marked "(me)" is the user making the request; "my tasks" or "assigned to me" refers to them.',
+ '- Match people and tags by name, tolerating typos, partial names, and casing. When a name matches nobody, leave it out and mention it in "unresolved".',
+ '- Always answer with option ids exactly as listed, never with labels.',
+ '- "unresolved" is one short sentence addressed to the user naming the part of the request that was skipped and why. Only describe what was actually skipped; do not mention filters that were applied. Empty string when everything was mapped.',
+ '- If the request has nothing to do with filtering tasks, return empty lists, an empty search, and explain in "unresolved".',
+ ].join('\n');
+}
+
+/**
+ * The model's reply, shared by the strict JSON schema sent with the request
+ * and the parser. Status and priority are enums, so strict mode rejects any
+ * other value at decode time; people and tags stay free strings so one
+ * unknown id drops alone instead of failing the whole reply.
+ */
+const AiTaskFilterReply = z.strictObject({
+ status: z.array(z.enum(optionIds(TASK_STATUS_OPTIONS))),
+ priority: z.array(z.enum(optionIds(TASK_PRIORITY_OPTIONS))),
+ assignees: z.array(z.string()),
+ createdBy: z.array(z.string()),
+ tags: z.array(z.string()),
+ search: z.string(),
+ unresolved: z.string(),
+});
+
+export function buildAiTaskFilterResponseFormat(): OpenAI.ResponseFormatJSONSchema {
+ const { $schema: _, ...schema } = z.toJSONSchema(AiTaskFilterReply, {
+ target: 'draft-07',
+ unrepresentable: 'throw',
+ });
+ return {
+ type: 'json_schema',
+ json_schema: { name: RESPONSE_SCHEMA_NAME, strict: true, schema },
+ };
+}
+
+export function buildAiTaskFilterRequest(
+ query: string,
+ catalog: AiTaskFilterCatalog
+): Omit<OpenAI.ChatCompletionCreateParamsNonStreaming, 'stream'> {
+ return {
+ model: AI_TASK_FILTER_MODEL,
+ temperature: 0,
+ max_tokens: 400,
+ response_format: buildAiTaskFilterResponseFormat(),
+ messages: [
+ { role: 'system', content: buildAiTaskFilterSystemPrompt(catalog) },
+ { role: 'user', content: query.trim() },
+ ],
+ };
+}
+
+const trimmedString = (value: string): string | undefined =>
+ value.trim() || undefined;
+
+/**
+ * Resolves model output against the known choices. Ids are preferred, but a
+ * label match (case-insensitive) is accepted so a model that echoes a name
+ * instead of an id still produces the right filter.
+ */
+function resolveChoices(
+ values: string[],
+ choices: AiTaskFilterChoice[]
+): string[] {
+ const byId = new Map(choices.map((choice) => [choice.id, choice.id]));
+ const byLabel = new Map(
+ choices.map((choice) => [choice.label.trim().toLowerCase(), choice.id])
+ );
+ const resolved = new Set<string>();
+ for (const value of values) {
+ const id = byId.get(value) ?? byLabel.get(value.trim().toLowerCase());
+ if (id) resolved.add(id);
+ }
+ return [...resolved];
+}
+
+export type AiTaskFilterParseResult =
+ | { ok: true; plan: AiTaskFilterPlan }
+ | { ok: false; error: 'INVALID_JSON' }
+ /** The reply was well-formed but mapped to nothing; `unresolved` says why. */
+ | { ok: false; error: 'NO_FILTERS'; unresolved?: string };
+
+/**
+ * Turns the model's JSON reply into a facet selection. Unknown ids are
+ * dropped rather than failing the whole request so one hallucinated option
+ * does not discard the rest of an otherwise good answer.
+ */
+export function parseAiTaskFilterResponse(
+ content: string | null | undefined,
+ catalog: AiTaskFilterCatalog
+): AiTaskFilterParseResult {
+ if (!content) return { ok: false, error: 'INVALID_JSON' };
+
+ let json: unknown;
+ try {
+ json = JSON.parse(content);
+ } catch {
+ return { ok: false, error: 'INVALID_JSON' };
+ }
+ const reply = AiTaskFilterReply.safeParse(json);
+ if (!reply.success) return { ok: false, error: 'INVALID_JSON' };
+ const data = reply.data;
+
+ const facets: FacetSelection = {};
+ const status = [...new Set(data.status)];
+ if (status.length > 0) facets.status = status;
+ const priority = [...new Set(data.priority)];
+ if (priority.length > 0) facets.priority = priority;
+ const assignees = resolveChoices(data.assignees, catalog.people);
+ if (assignees.length > 0) facets.assignees = assignees;
+ const createdBy = resolveChoices(data.createdBy, catalog.people);
+ if (createdBy.length > 0) facets['created-by'] = createdBy;
+ const tags = resolveChoices(data.tags, catalog.tags);
+ if (tags.length > 0) facets[TAG_FACET_ID] = tags;
+
+ const search = trimmedString(data.search);
+ const unresolved = trimmedString(data.unresolved);
+
+ if (Object.keys(facets).length === 0 && !search) {
+ return { ok: false, error: 'NO_FILTERS', unresolved };
+ }
+
+ return { ok: true, plan: { facets, search, unresolved } };
+}
diff --git a/apps/web/src/features/tasks-view/filters/use-task-filters.tsx b/apps/web/src/features/tasks-view/filters/use-task-filters.tsx
index 33ccd13518..8329a11a0c 100644
--- a/apps/web/src/features/tasks-view/filters/use-task-filters.tsx
+++ b/apps/web/src/features/tasks-view/filters/use-task-filters.tsx
@@ -1,4 +1,7 @@
-import type { ListFilterGroup } from '@app/components/view-shell';
+import type {
+ AiFilterOutcome,
+ ListFilterGroup,
+} from '@app/components/view-shell';
import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';
import { UserIcon } from '@core/component/UserIcon';
import { useUserId } from '@core/context/user';
@@ -6,10 +9,20 @@ import { idToDisplayName } from '@core/user/util';
import { PropertyValueIcon } from '@property/component/propertyValue';
import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';
import { useContacts } from '@queries/contacts/contacts';
-import { createMemo } from 'solid-js';
+import { batch, createMemo } from 'solid-js';
+import { match } from 'ts-pattern';
+import { requestAiTaskFilterPlan } from '../queries/ai-task-filter-plan';
import { useTasksView } from '../tasks-view-context';
+import type { AiTaskFilterCatalog } from './ai-task-filter';
import { TASK_PRIORITY_OPTIONS, TASK_STATUS_OPTIONS } from './task-facets';
+const AI_FILTER_UNAVAILABLE_MESSAGE =
+ 'AI filtering is unavailable right now. Try again in a moment.';
+const AI_FILTER_UNREADABLE_MESSAGE =
+ 'The AI reply could not be read. Try rephrasing your request.';
+const AI_FILTER_NOTHING_MATCHED_MESSAGE =
+ 'Nothing in that request maps to a filter. Try naming a status, priority, person, or tag.';
+
export type TaskFilterGroupId =
| 'status'
| 'priority'
@@ -18,7 +31,7 @@ export type TaskFilterGroupId =
| 'tags';
export function useTaskFilters() {
- const { state, setFacets } = useTasksView();
+ const { state, setFacets, setState } = useTasksView();
const contacts = useContacts();
const currentUserId = useUserId();
const tagGroup = useTagFilterGroup();
@@ -117,8 +130,39 @@ export function useTaskFilters() {
0
);
+ const aiCatalog = (): AiTaskFilterCatalog => ({
+ people: peopleOptions().map(({ id, label }) => ({ id, label })),
+ tags: tagGroup().options.map(({ id, label }) => ({ id, label })),
+ });
+
+ /** Replaces the selection with filters resolved from a plain-English request. */
+ const applyDescription = async (query: string): Promise<AiFilterOutcome> => {
+ const result = await requestAiTaskFilterPlan(query, aiCatalog());
+ if (result.isErr()) {
+ return {
+ status: 'error',
+ message: match(result.error)
+ .with({ code: 'UNAVAILABLE' }, () => AI_FILTER_UNAVAILABLE_MESSAGE)
+ .with({ code: 'UNREADABLE' }, () => AI_FILTER_UNREADABLE_MESSAGE)
+ .with(
+ { code: 'NO_FILTERS' },
+ ({ unresolved }) => unresolved ?? AI_FILTER_NOTHING_MATCHED_MESSAGE
+ )
+ .exhaustive(),
+ };
+ }
+
+ const plan = result.value;
+ batch(() => {
+ setFacets(plan.facets);
+ if (plan.search) setState('search', plan.search);
+ });
+ return { status: 'applied', note: plan.unresolved };
+ };
+
return {
activeCount,
+ applyDescription,
clear: () => setFacets({}),
groups,
isSelected,
diff --git a/apps/web/src/features/tasks-view/queries/ai-task-filter-plan.ts b/apps/web/src/features/tasks-view/queries/ai-task-filter-plan.ts
new file mode 100644
index 0000000000..1080f3482a
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/ai-task-filter-plan.ts
@@ -0,0 +1,41 @@
+import { dcsCompletion } from '@service-cognition/client';
+import { err, ok, type Result } from 'neverthrow';
+import {
+ type AiTaskFilterCatalog,
+ type AiTaskFilterPlan,
+ buildAiTaskFilterRequest,
+ parseAiTaskFilterResponse,
+} from '../filters/ai-task-filter';
+
+export type AiTaskFilterPlanError =
+ /** The completion request itself failed. */
+ | { code: 'UNAVAILABLE' }
+ /** The model answered with something that is not the expected JSON. */
+ | { code: 'UNREADABLE' }
+ /** A valid answer that selects nothing; `unresolved` is the model's reason. */
+ | { code: 'NO_FILTERS'; unresolved?: string };
+
+/** Asks the model to turn a plain-English request into a task filter plan. */
+export async function requestAiTaskFilterPlan(
+ query: string,
+ catalog: AiTaskFilterCatalog
+): Promise<Result<AiTaskFilterPlan, AiTaskFilterPlanError>> {
+ const completion = await dcsCompletion(
+ buildAiTaskFilterRequest(query, catalog)
+ );
+ if (completion.isErr()) {
+ console.error('AI task filter request failed', completion.error);
+ return err({ code: 'UNAVAILABLE' });
+ }
+
+ const parsed = parseAiTaskFilterResponse(
+ completion.value.choices[0]?.message?.content,
+ catalog
+ );
+ if (parsed.ok) return ok(parsed.plan);
+ return err(
+ parsed.error === 'NO_FILTERS'
+ ? { code: 'NO_FILTERS', unresolved: parsed.unresolved }
+ : { code: 'UNREADABLE' }
+ );
+}
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index 99e7b994c2..28091b828d 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -6,6 +6,17 @@
The desktop toolbar contains search (`Ctrl+F`), `Sort`, `Group`, and `Filter`;
the filter uses the legacy compact option rows and searchable Assignee, Created by,
and Tags submenus. Multi-select choices keep the menu open; Escape dismisses it.
+The top of the `Filter` menu is a `Filter with AI…` textbox, focused when the menu opens: type a plain-English
+description such as `urgent and high priority tasks that are not completed` and press
+Enter. It replaces the current selection with the matching Status, Priority, Assignee,
+Created by, and Tags options (exclusions on Status/Priority become the complementary
+options; subject matter such as `about billing` lands in the search box), then closes
+the menu. Requests that only partly map keep the menu open and show a muted note
+under the box; requests that map to nothing (excluding a tag, an unknown person,
+off-topic text) keep the typed text and show a red error there instead. The box keeps
+focus while you type even if the pointer drifts over the rows; ArrowDown moves into
+the rows and hovering a submenu hands focus to it as usual. The mobile drawer has no
+AI box.
Task creation is available from the `New` button in the Tasks sidebar. Below the tabs the
sidebar has a collapsible `Tags` section listing every personal and team tag, with a
`New tag` button beside the heading. Clicking a tag narrows the current tab to tasks