Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: tags in soupbar (#6309)
Peter Chinmanad2d56051d7d
diff --git a/apps/web/src/components/view-shell/CollapsibleSection.tsx b/apps/web/src/components/view-shell/CollapsibleSection.tsxindex cd5b0810f7..c7b73eb5e6 100644--- a/apps/web/src/components/view-shell/CollapsibleSection.tsx+++ b/apps/web/src/components/view-shell/CollapsibleSection.tsx@@ -21,7 +21,7 @@ function Trigger(props: ComponentProps<typeof Collapsible.Trigger>) {<Collapsible.Trigger{...rest}class={cn(- 'group flex h-9 w-full min-w-0 items-center gap-2.5 rounded-xl px-3 py-2 text-left text-sm font-medium text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/30',+ 'group flex h-9 w-full min-w-0 items-center gap-2.5 rounded-xl px-3 py-2 text-left text-sm font-medium text-ink-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/30',local.class)}>diff --git a/apps/web/src/components/view-shell/collapsed-sections.ts b/apps/web/src/components/view-shell/collapsed-sections.tsnew file mode 100644index 0000000000..821fa1adc1--- /dev/null+++ b/apps/web/src/components/view-shell/collapsed-sections.ts@@ -0,0 +1,91 @@+import type { PersistenceStorage } from '@app/lib/persistence';+import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';+import { createUserScopedStorage } from '@core/util/userScopedStorage';+import type { Accessor } from 'solid-js';+import { z } from 'zod';++/** View state that remembers which sidebar sections the user folded away. */+export type CollapsedSidebarSectionsState = {+ collapsedSidebarSectionIds: string[];+};++const collapsedSectionsSchema = z.object({+ version: z.literal(1).default(1),+ collapsedSidebarSectionIds: z.array(z.string()).default([]),+});++type CollapsedSectionsPreferences = z.infer<typeof collapsedSectionsSchema>;++const DEFAULT_PREFERENCES: CollapsedSectionsPreferences = {+ version: 1,+ collapsedSidebarSectionIds: [],+};++/** Store updater that folds or unfolds one section by id. */+export const setSidebarSectionCollapsed = (id: string, open: boolean) =>+ open ? removeValue(id) : addUnique(id);++export type CreateCollapsedSidebarSectionsStorageOptions = {+ /** localStorage key prefix; the user id is appended. */+ key: string;+ userId: Accessor<string | undefined>;+ restore: boolean;+};++/**+ * Persists a view's folded sidebar sections per user, separately from the+ * split entry state so the choice survives reloads and every visit.+ */+export function createCollapsedSidebarSectionsStorage<+ TState extends CollapsedSidebarSectionsState,+>(+ options: CreateCollapsedSidebarSectionsStorageOptions+): PersistenceStorage<TState> {+ const storage = createUserScopedStorage(options.key);+ let previous: string | undefined;++ const serialize = (state: TState): string =>+ JSON.stringify({+ version: 1,+ collapsedSidebarSectionIds: [...state.collapsedSidebarSectionIds],+ } satisfies CollapsedSectionsPreferences);++ const parse = (raw: string): CollapsedSectionsPreferences => {+ try {+ const result = collapsedSectionsSchema.safeParse(JSON.parse(raw));+ return result.success ? result.data : DEFAULT_PREFERENCES;+ } catch {+ return DEFAULT_PREFERENCES;+ }+ };++ return {+ restore: (current) => {+ if (!options.restore) return undefined;++ const userId = options.userId();+ if (!userId) return undefined;++ const raw = storage.read(userId);+ if (raw === null) return undefined;++ return {+ ...current,+ collapsedSidebarSectionIds: [...parse(raw).collapsedSidebarSectionIds],+ };+ },+ initialize: (current) => {+ previous = serialize(current);+ },+ write: (current) => {+ const userId = options.userId();+ if (!userId) return;++ const serialized = serialize(current);+ if (serialized === previous) return;++ previous = serialized;+ storage.write(userId, serialized);+ },+ };+}diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.tsindex b32a59099b..5aa353e0f9 100644--- a/apps/web/src/components/view-shell/index.ts+++ b/apps/web/src/components/view-shell/index.ts@@ -2,6 +2,10 @@ export {CollapsibleSection,type CollapsibleSectionRootProps,} from './CollapsibleSection';+export {+ createCollapsedSidebarSectionsStorage,+ setSidebarSectionCollapsed,+} from './collapsed-sections';export {type ListControlOption,ListFilterDropdown,diff --git a/apps/web/src/features/email-view/components/EmailControls.tsx b/apps/web/src/features/email-view/components/EmailControls.tsxindex f88de80b91..f80f7ca786 100644--- a/apps/web/src/features/email-view/components/EmailControls.tsx+++ b/apps/web/src/features/email-view/components/EmailControls.tsx@@ -22,7 +22,7 @@ export function EmailControls(props: EmailControlsProps) {label="Filter email"open={props.filterOpen}onOpenChange={props.onFilterOpenChange}- groups={filters.groups}+ groups={filters.groups()}isSelected={filters.isSelected}onSelectionChange={filters.setSelected}onClear={filters.clear}diff --git a/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsxindex bb01ec96c5..684cd62b30 100644--- a/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx+++ b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx@@ -30,11 +30,11 @@ export function EmailFilterDrawer() {<Accordionmultiplecollapsible- defaultValue={[INBOX_SECTION_ID, filters.groups[0].id]}+ defaultValue={[INBOX_SECTION_ID, filters.groups()[0].id]}><div class="flex flex-col gap-3"><EmailInboxDrawerSection value={INBOX_SECTION_ID} />- <For each={filters.groups}>+ <For each={filters.groups()}>{(group) => (<MobileFilterDrawer.Sectionvalue={group.id}diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex 5b19783b26..14129c4014 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -36,6 +36,7 @@ import {import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import SpinnerIcon from '@phosphor/spinner.svg';+import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';import { createElementSize } from '@solid-primitives/resize-observer';import { debounce } from '@solid-primitives/scheduled';import { Button, cn } from '@ui';@@ -89,8 +90,10 @@ export function EmailList(props: EmailListProps) {const { state, setOpenThreadId } = useEmailView();const panel = useSplitPanelOrThrow();+ const tagSets = useTagSets();+ const tagSetsReady = useTagSetsReady();const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>- useEmailDataSource(state)+ useEmailDataSource(state, { tagSets, tagSetsReady }));function openEntity(diff --git a/apps/web/src/features/email-view/components/EmailSidebar.tsx b/apps/web/src/features/email-view/components/EmailSidebar.tsxindex 69f368b305..4927d94549 100644--- a/apps/web/src/features/email-view/components/EmailSidebar.tsx+++ b/apps/web/src/features/email-view/components/EmailSidebar.tsx@@ -9,6 +9,7 @@ import FileIcon from '@phosphor/file.svg';import ComposeIcon from '@phosphor/note-pencil.svg';import PaperPlaneTiltIcon from '@phosphor/paper-plane-tilt.svg';import UsersThreeIcon from '@phosphor/users-three.svg';+import { SidebarTagsSection } from '@property/tags/SidebarTagsSection';import { Button, pressHandlers } from '@ui';import { type Component, For } from 'solid-js';import { Dynamic } from 'solid-js/web';@@ -48,12 +49,25 @@ function Tab(props: { item: EmailTabItem; onNavigate?: () => void }) {}export function EmailNavigation(props: { onNavigate?: () => void }) {+ const { state, showTags, isSidebarSectionOpen, setSidebarSectionOpen } =+ useEmailView();+return (- <ViewSidebar.Nav aria-label="Email tabs">- <For each={EMAIL_TABS}>- {(item) => <Tab item={item} onNavigate={props.onNavigate} />}- </For>- </ViewSidebar.Nav>+ <div class="flex flex-col gap-6">+ <ViewSidebar.Nav aria-label="Email tabs">+ <For each={EMAIL_TABS}>+ {(item) => <Tab item={item} onNavigate={props.onNavigate} />}+ </For>+ </ViewSidebar.Nav>++ <SidebarTagsSection+ activeIds={state.facets.tags ?? []}+ onActiveIdsChange={showTags}+ open={isSidebarSectionOpen('tags')}+ onOpenChange={(open) => setSidebarSectionOpen('tags', open)}+ onNavigate={props.onNavigate}+ />+ </div>);}diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxindex 5442f321d0..c580e72db9 100644--- a/apps/web/src/features/email-view/email-view-context.tsx+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -1,3 +1,4 @@+import { setSidebarSectionCollapsed } from '@app/components/view-shell';import { registerInboxFilterSplit } from '@app/features/next-soup/soup-view/inbox-filter-controllers';import { normalizeFacetSelection } from '@app/features/soup';import { makePersistedState } from '@app/lib/persistence';@@ -28,7 +29,14 @@ export type EmailViewContext = {setTab: (tab: EmailTab) => void;setInboxIds: (ids: string[] | undefined) => void;setFacets: (facets: EmailViewState['facets']) => void;+ /**+ * Shows the given tags across the whole mailbox: a non-empty selection+ * lands on the All tab. Clearing keeps the current tab.+ */+ showTags: (tagIds: string[]) => void;setOpenThreadId: (threadId: string | undefined) => void;+ isSidebarSectionOpen: (id: string) => boolean;+ setSidebarSectionOpen: (id: string, open: boolean) => void;/*** Whether the view may open its preview pane on its own. Written by the* Preview toggle so an explicit close stays closed across visits; shares@@ -58,12 +66,16 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<initial.inboxIds === undefined ? undefined : [...initial.inboxIds],facets: normalizeFacetSelection(initial.facets),openThreadId: initial.openThreadId,+ collapsedSidebarSectionIds: [+ ...(initial.collapsedSidebarSectionIds ?? []),+ ],}),createEmailViewPersistence({handle: panel.handle,userId,restoreEntryState: props.initialState === undefined,restoreLocalState: props.initialState === undefined,+ restorePreferences: initial.collapsedSidebarSectionIds === undefined,}));@@ -87,9 +99,33 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<setState('facets', reconcile(normalizeFacetSelection(facets)));};+ // A tag reaches across every mailbox slice, so choosing one from a narrower+ // tab moves to All; as with `setTab`, that move drops the tab's other filters.+ const showTags = (tagIds: string[]) => {+ setState(+ produce((draft) => {+ const movesToAll = tagIds.length > 0 && draft.tab !== 'all';+ if (movesToAll) draft.tab = 'all';+ draft.facets = normalizeFacetSelection({+ ...(movesToAll ? {} : draft.facets),+ tags: tagIds,+ });+ })+ );+ };+const setOpenThreadId = (threadId: string | undefined) =>setState('openThreadId', threadId);+ const isSidebarSectionOpen = (id: string) =>+ !state.collapsedSidebarSectionIds.includes(id);++ const setSidebarSectionOpen = (id: string, open: boolean) =>+ setState(+ 'collapsedSidebarSectionIds',+ setSidebarSectionCollapsed(id, open)+ );+// The classic sidebar's nested account rows scope the mail list by split id// (see `SidebarMailLink`); registering keeps them driving this view too, and// flushes a selection queued while navigating here.@@ -106,7 +142,10 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<setTab,setInboxIds,setFacets,+ showTags,setOpenThreadId,+ isSidebarSectionOpen,+ setSidebarSectionOpen,previewOpen,setPreviewOpen,};diff --git a/apps/web/src/features/email-view/filters/email-facets.ts b/apps/web/src/features/email-view/filters/email-facets.tsindex 395fc34412..27b8ea9f11 100644--- a/apps/web/src/features/email-view/filters/email-facets.ts+++ b/apps/web/src/features/email-view/filters/email-facets.ts@@ -4,7 +4,14 @@ import {hasImageAttachmentFilter,hasPdfAttachmentFilter,} from '@app/features/next-soup/filters/predicates';-import { clause, type Facet, type FacetOption } from '@app/features/soup';+import {+ clause,+ type Facet,+ type FacetOption,+ TAG_FACET_ID,+ type TagFacetContext,+ tagFacetOption,+} from '@app/features/soup';import type { EntityIconSelector } from '@core/component/EntityIcon';import type { EmailEntity, EntityData } from '@entity';import type { EmailFilterGroupId, EmailFilterOptionId } from '../types';@@ -15,7 +22,11 @@ type EmailFilterOption = {iconType?: EntityIconSelector;};-type EmailFacetOption = FacetOption<EmailEntity, undefined> & EmailFilterOption;+/** Tags are the one facet whose options come from data rather than a list. */+export type EmailFacetContext = TagFacetContext;++type EmailFacetOption = FacetOption<EmailEntity, EmailFacetContext> &+ EmailFilterOption;function readOption(id: EmailFilterOptionId,@@ -90,11 +101,17 @@ const EMAIL_CALENDAR_OPTIONS: EmailFacetOption[] = [},];-export const EMAIL_FACETS: Facet<EmailEntity, undefined, EmailFacetOption>[] = [+export const EMAIL_FACETS: Facet<EmailEntity, EmailFacetContext>[] = [{ id: 'read', mode: 'or', options: EMAIL_READ_OPTIONS },{ id: 'done', mode: 'or', options: EMAIL_DONE_OPTIONS },{ id: 'attachments', mode: 'or', options: EMAIL_ATTACHMENT_OPTIONS },{ id: 'calendar', mode: 'or', options: EMAIL_CALENDAR_OPTIONS },+ {+ id: TAG_FACET_ID,+ mode: 'or',+ options: (optionId, context) =>+ tagFacetOption<EmailEntity>(optionId, context),+ },];type EmailFilterGroup = {diff --git a/apps/web/src/features/email-view/filters/use-email-filters.tsx b/apps/web/src/features/email-view/filters/use-email-filters.tsxindex 112558d621..4dddf92b67 100644--- a/apps/web/src/features/email-view/filters/use-email-filters.tsx+++ b/apps/web/src/features/email-view/filters/use-email-filters.tsx@@ -1,30 +1,37 @@import type { ListFilterGroup } from '@app/components/view-shell';import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';import { EntityIcon } from '@core/component/EntityIcon';+import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';import { createMemo } from 'solid-js';import { useEmailView } from '../email-view-context';-import type { EmailFilterGroupId, EmailFilterOptionId } from '../types';+import type { EmailFilterGroupId } from '../types';import { EMAIL_FILTER_GROUPS } from './email-facets';-const FILTER_GROUPS: ListFilterGroup<- EmailFilterGroupId,- EmailFilterOptionId->[] = EMAIL_FILTER_GROUPS.map((group) => ({- ...group,- options: group.options.map((option) => ({- ...option,- icon: option.iconType- ? () => <EntityIcon targetType={option.iconType} size="xs" />- : undefined,- })),-}));+type EmailFilterGroup = ListFilterGroup<EmailFilterGroupId, string>;-const groupFor = (groupId: EmailFilterGroupId) =>- FILTER_GROUPS.find((group) => group.id === groupId);+const STATIC_FILTER_GROUPS: EmailFilterGroup[] = EMAIL_FILTER_GROUPS.map(+ (group) => ({+ ...group,+ options: group.options.map((option) => ({+ ...option,+ icon: option.iconType+ ? () => <EntityIcon targetType={option.iconType} size="xs" />+ : undefined,+ })),+ })+);/** Shared selection semantics for the desktop menu and mobile drawer. */export function useEmailFilters() {const { state, setFacets } = useEmailView();+ const tagGroup = useTagFilterGroup();+ // Tags come last: the static groups are short, the tag list grows with use.+ const groups = createMemo((): EmailFilterGroup[] => [+ ...STATIC_FILTER_GROUPS,+ tagGroup(),+ ]);+ const groupFor = (groupId: EmailFilterGroupId) =>+ groups().find((group) => group.id === groupId);const activeFilterCount = createMemo(() =>Object.values(state.facets).reduce((count, optionIds) => count + optionIds.length,@@ -33,10 +40,7 @@ export function useEmailFilters() {);// Single-select groups carry an "All" option that stands for no selection.- const isSelected = (- groupId: EmailFilterGroupId,- optionId: EmailFilterOptionId- ) => {+ const isSelected = (groupId: EmailFilterGroupId, optionId: string) => {const selected = state.facets[groupId] ?? [];const group = groupFor(groupId);if (@@ -51,7 +55,7 @@ export function useEmailFilters() {const setSelected = (groupId: EmailFilterGroupId,- optionId: EmailFilterOptionId,+ optionId: string,selected: boolean) => {const group = groupFor(groupId);@@ -76,7 +80,7 @@ export function useEmailFilters() {};return {- groups: FILTER_GROUPS,+ groups,activeCount: activeFilterCount,isSelected,setSelected,diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.tsindex 808a17655f..9219627649 100644--- a/apps/web/src/features/email-view/persistence.ts+++ b/apps/web/src/features/email-view/persistence.ts@@ -1,3 +1,4 @@+import { createCollapsedSidebarSectionsStorage } from '@app/components/view-shell';import { INBOX_FILTER_ENTRY_KEY } from '@app/features/next-soup/soup-view/inbox-filter-controllers';import { normalizeFacetSelection } from '@app/features/soup';import type {@@ -230,6 +231,7 @@ export type CreateEmailViewPersistenceOptions = {userId: Accessor<string | undefined>;restoreEntryState?: boolean;restoreLocalState?: boolean;+ restorePreferences?: boolean;};/**@@ -244,6 +246,11 @@ export function createEmailViewPersistence(return {storages: [+ createCollapsedSidebarSectionsStorage({+ key: 'macro:email:preferences:v1',+ userId: options.userId,+ restore: options.restorePreferences ?? true,+ }),createEmailLocalStateStorage({userId: options.userId,restore: options.restoreLocalState ?? true,diff --git a/apps/web/src/features/email-view/queries/email-query.test.ts b/apps/web/src/features/email-view/queries/email-query.test.tsindex ab8cc9af56..b0342d42f7 100644--- a/apps/web/src/features/email-view/queries/email-query.test.ts+++ b/apps/web/src/features/email-view/queries/email-query.test.ts@@ -1,4 +1,9 @@+import {+ createTagFacetContext,+ EMPTY_TAG_FACET_CONTEXT,+} from '@app/features/soup';import type { EntityData, WithNotification } from '@entity';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';import { describe, expect, it, vi } from 'vitest';import type { EmailTab } from '../types';import {@@ -41,9 +46,25 @@ const contextFor = (tab: 'all',inboxIds: undefined,facets: {},+ facetContext: EMPTY_TAG_FACET_CONTEXT,...overrides,});+const TAG_SETS = [+ {+ scope: 'user',+ definition: { id: 'tag-definition' },+ options: [+ {+ id: 'invoices',+ propertyDefinitionId: 'tag-definition',+ displayOrder: 0,+ value: { type: 'string', value: 'Invoices' },+ },+ ],+ },+] as TagSetResponse[];+describe('buildEmailQuery', () => {it('lists the server view each tab reads from', () => {expect(TABS.map((tab) => [tab, emailViewForTab(tab)])).toEqual([@@ -154,6 +175,26 @@ describe('buildEmailQuery', () => {expect(withAttachments).toEqual(plain);});+ it('refines by selected tags as a property filter', () => {+ const facetContext = createTagFacetContext(TAG_SETS);+ const { propf } = buildEmailQuery(+ contextFor({ facets: { tags: ['invoices'] }, facetContext })+ ).body;++ expect(propf).toEqual({+ l: { pd: 'tag-definition', v: { so: 'invoices' } },+ });+ });++ it('keeps an unresolved tag selection from filtering', () => {+ const plain = buildEmailQuery(contextFor()).body;+ const withUnknownTag = buildEmailQuery(+ contextFor({ facets: { tags: ['deleted-tag'] } })+ ).body;++ expect(withUnknownTag).toEqual(plain);+ });+it('pages by latest thread activity, newest first', () => {expect(buildEmailQuery(contextFor()).params).toEqual({expand: true,@@ -253,6 +294,30 @@ describe('buildEmailSearchRequest', () => {expect(filters).toEqual({ calendar_only: true });});++ it('sends selected tags as an entity-wide filter', () => {+ const { filters } = requestFor({+ facets: { tags: ['invoices', 'invoices'] },+ facetContext: createTagFacetContext(TAG_SETS),+ });++ expect(filters.tag_option_ids).toEqual(['invoices']);+ expect(filters.tag_filter_mode).toBe('any');+ expect(filters.email_filters).toEqual({});+ });++ it('drops a selected tag that no longer exists, like the list query', () => {+ const { filters } = requestFor({+ facets: { tags: ['invoices', 'deleted-tag'] },+ facetContext: createTagFacetContext(TAG_SETS),+ });++ expect(filters.tag_option_ids).toEqual(['invoices']);++ const unresolved = requestFor({ facets: { tags: ['deleted-tag'] } });+ expect(unresolved.filters.tag_option_ids).toBeUndefined();+ expect(unresolved.filters.tag_filter_mode).toBeUndefined();+ });});describe('groupEmailEntitiesByDate', () => {diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.tsindex 71dc3d7bbc..6eb16423af 100644--- a/apps/web/src/features/email-view/queries/email-query.ts+++ b/apps/web/src/features/email-view/queries/email-query.ts@@ -10,7 +10,7 @@ import {} from '@app/features/soup';import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';import { match } from 'ts-pattern';-import { EMAIL_FACETS } from '../filters/email-facets';+import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';import type { EmailTab } from '../types';export type EmailQueryContext = {@@ -18,6 +18,7 @@ export type EmailQueryContext = {/** `undefined` = every linked inbox; `[]` = none; otherwise email link ids. */inboxIds: string[] | undefined;facets: FacetSelection;+ facetContext: EmailFacetContext;};/**@@ -86,7 +87,11 @@ export function buildEmailQuery(if (inbox) expressions.push(inbox);const base = compileClause(confine({ ef: clause.and(...expressions) }));- const refinements = compileFacets(context.facets, EMAIL_FACETS, undefined);+ const refinements = compileFacets(+ context.facets,+ EMAIL_FACETS,+ context.facetContext+ );const body: SoupAstBody = {...mergeAst(base, refinements),emailView: emailViewForTab(context.tab),diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.tsindex b503e9af85..41cf44dcba 100644--- a/apps/web/src/features/email-view/queries/email-search.ts+++ b/apps/web/src/features/email-view/queries/email-search.ts@@ -86,13 +86,26 @@ export function buildEmailSearchRequest(context.inboxIds.length > 0 ? [...context.inboxIds] : [NIL_UUID];}+ // Tags are entity-wide in the search service, so they sit beside the+ // per-type filters rather than inside `email_filters`. Like the list+ // query, a selected tag that no longer exists stops filtering.+ const tagOptionIds = [...new Set(context.facets.tags ?? [])].filter((id) =>+ context.facetContext.tagPropertyDefinitionByOptionId.has(id)+ );+return {params: { cursor: null, page_size: 100 },body: {query: search.query,match_type: search.matchType,search_on: 'name_content',- filters: { ...nonEmailFilters, email_filters: emailFilters },+ filters: {+ ...nonEmailFilters,+ email_filters: emailFilters,+ ...(tagOptionIds.length > 0+ ? { tag_option_ids: tagOptionIds, tag_filter_mode: 'any' }+ : {}),+ },},};}diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.tsindex fa6318e68e..7b540ff46a 100644--- a/apps/web/src/features/email-view/queries/use-email-query.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.ts@@ -4,7 +4,9 @@ import {buildGroupedSoupRows,createSearchState,createSoupLoadMoreRow,+ createTagFacetContext,type SoupRow,+ tagFacetReady,testFacets,} from '@app/features/soup';import { withEntityNotifications } from '@app/features/soup/entity-notifications';@@ -17,9 +19,10 @@ import {type WithNotification,} from '@entity';import { useSoupAstItemsQuery } from '@queries/soup/items';-import { createMemo } from 'solid-js';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { type Accessor, createMemo } from 'solid-js';import { match } from 'ts-pattern';-import { EMAIL_FACETS } from '../filters/email-facets';+import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';import type { EmailTab, EmailViewState } from '../types';import { buildEmailQuery, type EmailQueryContext } from './email-query';import { groupEmailEntitiesByDate } from './email-results';@@ -34,6 +37,15 @@ export type EmailDataSourceInput = Pick<'tab' | 'search' | 'inboxIds' | 'facets'>;+export type UseEmailDataSourceOptions = {+ /**+ * Read by the caller, not here: the source runs under the split panel's+ * owner, above the view's tag-sets provider.+ */+ tagSets: Accessor<readonly TagSetResponse[]>;+ tagSetsReady: Accessor<boolean>;+};+/*** The server owns importance, calendar, sent and inbox scoping, so — as with* the legacy presets' client filters — only the shapes a cached entity can@@ -59,21 +71,32 @@ type AdmittedEmails = {/** Query, service search, and row assembly owned by the Email view. */export function useEmailDataSource(- state: EmailDataSourceInput+ state: EmailDataSourceInput,+ options: UseEmailDataSourceOptions): EmailDataSource {const notificationSource = useGlobalNotificationSource();const userId = useUserId();+ const facetContext = createMemo(+ (): EmailFacetContext => createTagFacetContext(options.tagSets())+ );+const queryContext = createMemo((): EmailQueryContext => ({tab: state.tab,inboxIds: state.inboxIds === undefined ? undefined : [...state.inboxIds],facets: state.facets,+ facetContext: facetContext(),}));const queryArgs = createMemo(() => buildEmailQuery(queryContext()));- const query = useSoupAstItemsQuery(queryArgs);+ // A restored tag selection waits for the tag sets rather than listing the+ // whole mailbox and then narrowing.+ const facetsReady = () => tagFacetReady(state.facets, options.tagSetsReady());+ const query = useSoupAstItemsQuery(queryArgs, () => ({+ enabled: facetsReady(),+ }));const selectEmails = (entities: EntityData[]): EmailEntity[] => {const context = queryContext();@@ -91,6 +114,9 @@ export function useEmailDataSource(// every search result comes from the search service.const search = createSearchState({text: () => state.search,+ // Held back with the list query so a tag selection is not stripped from+ // the request before the sets that resolve it have loaded.+ enabled: facetsReady,disableLocalSearch: () => true,buildRequest: (request) => buildEmailSearchRequest(queryContext(), request),});@@ -129,7 +155,7 @@ export function useEmailDataSource(].join('|');const selection = { ...context.facets, read: [] };const matchesOtherFacets = (email: EmailEntity) =>- testFacets(selection, EMAIL_FACETS, email, undefined);+ testFacets(selection, EMAIL_FACETS, email, context.facetContext);// Without a read filter there is nothing to admit, so no ids are kept.if (activeRead.length === 0) {@@ -146,7 +172,9 @@ export function useEmailDataSource(: new Set<string>();const readSelection = { read: activeRead };for (const email of emails) {- if (testFacets(readSelection, EMAIL_FACETS, email, undefined)) {+ if (+ testFacets(readSelection, EMAIL_FACETS, email, context.facetContext)+ ) {admittedIds.add(email.id);}}@@ -201,7 +229,8 @@ export function useEmailDataSource(const isLoading = () => {if (!search.isSearching()) {- return query.isLoading && rawEntities().length === 0;+ // A query held back for the tag sets is loading, not empty.+ return (query.isLoading || !facetsReady()) && rawEntities().length === 0;}if (entities().items.length > 0) return false;if (usesServiceSearch()) return search.isLoading();diff --git a/apps/web/src/features/email-view/types.ts b/apps/web/src/features/email-view/types.tsindex e2ea4efc7c..a6981a69f2 100644--- a/apps/web/src/features/email-view/types.ts+++ b/apps/web/src/features/email-view/types.ts@@ -14,7 +14,12 @@ export type EmailTab =| 'shared'| 'all';-export type EmailFilterGroupId = 'read' | 'done' | 'attachments' | 'calendar';+export type EmailFilterGroupId =+ | 'read'+ | 'done'+ | 'attachments'+ | 'calendar'+ | 'tags';export type EmailFilterOptionId =| 'all'@@ -42,6 +47,8 @@ export type EmailViewState = {* next visit, the way the Channels view reopens its selected channel.*/openThreadId?: string;+ /** Sidebar sections the user folded away; kept per user, not per visit. */+ collapsedSidebarSectionIds: string[];};export type EmailViewStateOptions = Partial<EmailViewState>;diff --git a/apps/web/src/features/property/tags/SidebarTagsSection.test.tsx b/apps/web/src/features/property/tags/SidebarTagsSection.test.tsxnew file mode 100644index 0000000000..b58923e659--- /dev/null+++ b/apps/web/src/features/property/tags/SidebarTagsSection.test.tsx@@ -0,0 +1,135 @@+/**+ * @vitest-environment jsdom+ */++import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import {+ SidebarTagsSection,+ type SidebarTagsSectionProps,+ selectSidebarTag,+} from './SidebarTagsSection';+import { TagSetsProvider } from './tag-sets-context';++const mocks = vi.hoisted(() => ({+ tagEditorDialog: vi.fn(),+}));++vi.mock('./TagEditorDialog', () => ({+ TagEditorDialog: (props: { open: boolean }) => {+ mocks.tagEditorDialog(props);+ return <div data-testid="tag-editor" data-open={String(props.open)} />;+ },+}));++vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({ isSuccess: false, data: undefined }),+}));++const TAG_SETS = [+ {+ scope: 'user',+ definition: { id: 'personal-definition' },+ options: [+ {+ id: 'urgent',+ propertyDefinitionId: 'personal-definition',+ displayOrder: 0,+ value: { type: 'string', value: 'Urgent' },+ },+ {+ id: 'later',+ propertyDefinitionId: 'personal-definition',+ displayOrder: 1,+ value: { type: 'string', value: 'Later' },+ },+ ],+ },+] as TagSetResponse[];++function renderSection(+ overrides: Partial<SidebarTagsSectionProps> = {},+ tagSets: TagSetResponse[] = TAG_SETS+) {+ const [activeIds, setActiveIds] = createSignal<string[]>([]);+ const onActiveIdsChange = vi.fn((ids: string[]) => setActiveIds(ids));++ render(() => (+ <TagSetsProvider tagSets={() => tagSets}>+ <SidebarTagsSection+ activeIds={activeIds()}+ onActiveIdsChange={onActiveIdsChange}+ open+ onOpenChange={() => {}}+ {...overrides}+ />+ </TagSetsProvider>+ ));++ return { onActiveIdsChange };+}++describe('selectSidebarTag', () => {+ it('shows a chosen tag alone and drops a chosen active tag', () => {+ expect(selectSidebarTag([], 'urgent')).toEqual(['urgent']);+ expect(selectSidebarTag(['later'], 'urgent')).toEqual(['urgent']);+ expect(selectSidebarTag(['urgent'], 'urgent')).toEqual([]);+ expect(selectSidebarTag(['urgent', 'later'], 'urgent')).toEqual(['later']);+ });+});++describe('SidebarTagsSection', () => {+ it('lists every tag and marks the active ones', () => {+ renderSection({ activeIds: ['later'] });++ const rows = screen.getAllByRole('button', { name: /Urgent|Later/ });+ expect(rows.map((row) => row.textContent)).toEqual(['Urgent', 'Later']);+ expect(+ screen.getByRole('button', { name: 'Later' }).getAttribute('aria-current')+ ).toBe('page');+ expect(+ screen+ .getByRole('button', { name: 'Urgent' })+ .getAttribute('aria-current')+ ).toBeNull();+ });++ it('hands the host the selection a click asks for', async () => {+ const onNavigate = vi.fn();+ const { onActiveIdsChange } = renderSection({ onNavigate });++ await fireEvent.click(screen.getByRole('button', { name: 'Urgent' }));+ expect(onActiveIdsChange).toHaveBeenLastCalledWith(['urgent']);+ expect(onNavigate).toHaveBeenCalledOnce();++ await fireEvent.click(screen.getByRole('button', { name: 'Urgent' }));+ expect(onActiveIdsChange).toHaveBeenLastCalledWith([]);+ });++ it('opens the tag editor from the New tag action', async () => {+ renderSection();++ const editorOpen = () =>+ screen.getByTestId('tag-editor').getAttribute('data-open');+ expect(editorOpen()).toBe('false');++ await fireEvent.click(screen.getByRole('button', { name: 'New tag' }));++ expect(editorOpen()).toBe('true');+ expect(mocks.tagEditorDialog).toHaveBeenLastCalledWith(+ expect.objectContaining({+ mode: { type: 'create', initialScope: 'user' },+ teamAvailable: false,+ })+ );+ });++ it('explains an empty list instead of rendering no rows', () => {+ renderSection({}, []);++ expect(screen.getByText('No tags yet')).toBeTruthy();+ expect(screen.queryByRole('navigation', { name: 'Tags' })).toBeNull();+ });+});diff --git a/apps/web/src/features/property/tags/SidebarTagsSection.tsx b/apps/web/src/features/property/tags/SidebarTagsSection.tsxnew file mode 100644index 0000000000..8c0c7c8a7f--- /dev/null+++ b/apps/web/src/features/property/tags/SidebarTagsSection.tsx@@ -0,0 +1,110 @@+import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';+import PlusIcon from '@phosphor/plus.svg';+import { useCurrentTeamQuery } from '@queries/team/teams';+import { Button } from '@ui';+import { createSignal, For, Show } from 'solid-js';+import { TagDot } from './TagDot';+import { TagEditorDialog } from './TagEditorDialog';+import { useTagOptions } from './tag-options';++export type SidebarTagsSectionProps = {+ /** Tag option ids the view is currently showing. */+ activeIds: readonly string[];+ /** Receives the selection a row click asks for; the host stores it. */+ onActiveIdsChange: (ids: string[]) => void;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Runs after a row is chosen, for hosts that show the section in a menu. */+ onNavigate?: () => void;+};++/**+ * A sidebar row is a destination, not a checkbox: choosing a tag shows that+ * tag alone, and choosing an active tag drops it from the selection.+ */+export function selectSidebarTag(+ activeIds: readonly string[],+ id: string+): string[] {+ if (activeIds.includes(id)) {+ return activeIds.filter((activeId) => activeId !== id);+ }+ return [id];+}++/**+ * The Tags section of a list view's sidebar: every tag the user can apply,+ * with the active ones highlighted, plus a shortcut to create one. Reads tag+ * sets from the nearest `TagSetsProvider`.+ */+export function SidebarTagsSection(props: SidebarTagsSectionProps) {+ const tags = useTagOptions();+ const teamQuery = useCurrentTeamQuery();+ const [creating, setCreating] = createSignal(false);+ const teamAvailable = () =>+ teamQuery.isSuccess && Boolean(teamQuery.data?.team);+ const isActive = (id: string) => props.activeIds.includes(id);++ return (+ <CollapsibleSection.Root+ open={props.open}+ onOpenChange={props.onOpenChange}+ >+ <div class="flex items-center gap-1">+ <CollapsibleSection.Trigger class="min-w-0 flex-1 text-xs">+ <CollapsibleSection.Indicator class="ml-0" />+ <span class="truncate">Tags</span>+ </CollapsibleSection.Trigger>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ label="New tag"+ // Right edge inset so the plus centres on the trailing caret of other sections.+ class="mr-2 shrink-0 rounded-lg"+ onClick={() => setCreating(true)}+ >+ <PlusIcon class="size-3.5" />+ </Button>+ </div>+ <CollapsibleSection.Content>+ <Show+ when={tags().length > 0}+ fallback={+ <p class="px-3 py-2 text-sm text-ink-extra-muted">No tags yet</p>+ }+ >+ <ViewSidebar.Nav aria-label="Tags">+ <For each={tags()}>+ {(tag) => (+ <ViewSidebar.Item+ active={isActive(tag.id)}+ onClick={() => {+ props.onActiveIdsChange(+ selectSidebarTag(props.activeIds, tag.id)+ );+ props.onNavigate?.();+ }}+ >+ <span+ aria-hidden="true"+ class="flex size-4 shrink-0 items-center justify-center"+ >+ <TagDot color={tag.color} />+ </span>+ <span class="truncate">{tag.label}</span>+ </ViewSidebar.Item>+ )}+ </For>+ </ViewSidebar.Nav>+ </Show>+ </CollapsibleSection.Content>+ <TagEditorDialog+ open={creating()}+ mode={{ type: 'create', initialScope: 'user' }}+ teamAvailable={teamAvailable()}+ onClose={() => setCreating(false)}+ />+ </CollapsibleSection.Root>+ );+}diff --git a/apps/web/src/features/property/tags/tag-options.test.ts b/apps/web/src/features/property/tags/tag-options.test.tsnew file mode 100644index 0000000000..9e2117a791--- /dev/null+++ b/apps/web/src/features/property/tags/tag-options.test.ts@@ -0,0 +1,67 @@+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { describe, expect, it } from 'vitest';+import { listTagOptions } from './tag-options';++const option = (+ id: string,+ label: string,+ propertyDefinitionId: string,+ displayOrder: number,+ color?: string+) => ({+ id,+ propertyDefinitionId,+ displayOrder,+ color,+ value: { type: 'string' as const, value: label },+});++describe('listTagOptions', () => {+ it('lists personal tags before team tags, each in display order', () => {+ const tagSets = [+ {+ scope: 'team',+ definition: { id: 'team-definition' },+ options: [option('launch', 'Launch', 'team-definition', 0, '#123')],+ },+ {+ scope: 'user',+ definition: { id: 'personal-definition' },+ options: [+ option('later', 'Later', 'personal-definition', 1),+ option('urgent', 'Urgent', 'personal-definition', 0),+ ],+ },+ ] as TagSetResponse[];++ expect(listTagOptions(tagSets)).toEqual([+ {+ id: 'urgent',+ label: 'Urgent',+ color: undefined,+ scope: 'user',+ propertyDefinitionId: 'personal-definition',+ },+ {+ id: 'later',+ label: 'Later',+ color: undefined,+ scope: 'user',+ propertyDefinitionId: 'personal-definition',+ },+ {+ id: 'launch',+ label: 'Launch',+ color: '#123',+ scope: 'team',+ propertyDefinitionId: 'team-definition',+ },+ ]);+ });++ it('skips a set that has not been provisioned yet', () => {+ const tagSets = [{ scope: 'user', options: [] }] as TagSetResponse[];++ expect(listTagOptions(tagSets)).toEqual([]);+ });+});diff --git a/apps/web/src/features/property/tags/tag-options.ts b/apps/web/src/features/property/tags/tag-options.tsnew file mode 100644index 0000000000..963a7bed40--- /dev/null+++ b/apps/web/src/features/property/tags/tag-options.ts@@ -0,0 +1,46 @@+import type { TagScope } from '@service-properties/generated/schemas/tagScope';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { type Accessor, createMemo } from 'solid-js';+import { useTagSets } from './tag-sets-context';++/** A tag as list surfaces show it: the option plus the set it belongs to. */+export type TagOptionSummary = {+ id: string;+ label: string;+ color?: string;+ scope: TagScope;+ propertyDefinitionId: string;+};++const SCOPE_ORDER: Record<TagScope, number> = { user: 0, team: 1 };++/**+ * Flattens tag sets into display order: the personal set before the team+ * set, each in the order the user arranged it in Settings.+ */+export function listTagOptions(+ tagSets: readonly TagSetResponse[]+): TagOptionSummary[] {+ return [...tagSets]+ .sort((a, b) => SCOPE_ORDER[a.scope] - SCOPE_ORDER[b.scope])+ .flatMap((set) =>+ [...set.options]+ .sort((a, b) => a.displayOrder - b.displayOrder)+ .map(+ (option): TagOptionSummary => ({+ id: option.id,+ label:+ option.value.type === 'string' ? option.value.value : option.id,+ color: option.color ?? undefined,+ scope: set.scope,+ propertyDefinitionId: option.propertyDefinitionId,+ })+ )+ );+}++/** The provider's tag sets in display order. */+export function useTagOptions(): Accessor<TagOptionSummary[]> {+ const tagSets = useTagSets();+ return createMemo(() => listTagOptions(tagSets()));+}diff --git a/apps/web/src/features/property/tags/tag-sets-context.tsx b/apps/web/src/features/property/tags/tag-sets-context.tsxindex 68117315b6..2817742bec 100644--- a/apps/web/src/features/property/tags/tag-sets-context.tsx+++ b/apps/web/src/features/property/tags/tag-sets-context.tsx@@ -14,13 +14,21 @@ type TagSets = Accessor<TagSetResponse[]>;type TagOption = { option: PropertyOptionResponse; scope: TagScope };type TagSetsContextValue = {tagSets: TagSets;+ /** False only while the sets are still being fetched for the first time. */+ ready: Accessor<boolean>;optionById: Accessor<ReadonlyMap<string, TagOption>>;};+const ALWAYS_READY = () => true;+const TagSetsContext = createContext<TagSetsContextValue>();/** Shares loaded tag definitions with a feature subtree. */-export const TagSetsProvider: FlowComponent<{ tagSets: TagSets }> = (props) => {+export const TagSetsProvider: FlowComponent<{+ tagSets: TagSets;+ /** Omit when the sets are caller-owned and available from the start. */+ ready?: Accessor<boolean>;+}> = (props) => {const optionById = createMemo(() => {const options = new Map<string, TagOption>();for (const set of props.tagSets()) {@@ -32,7 +40,13 @@ export const TagSetsProvider: FlowComponent<{ tagSets: TagSets }> = (props) => {});return (- <TagSetsContext.Provider value={{ tagSets: props.tagSets, optionById }}>+ <TagSetsContext.Provider+ value={{+ tagSets: props.tagSets,+ ready: () => props.ready?.() ?? ALWAYS_READY(),+ optionById,+ }}+ >{props.children}</TagSetsContext.Provider>);@@ -44,8 +58,15 @@ export const TagSetsQueryProvider: FlowComponent = (props) => {// Avoid suspending on a cold query, but retain cached tags after refetch errors.const tagSets = (): TagSetResponse[] =>tagsQuery.isPending ? [] : (tagsQuery.data ?? []);+ // Fetched once, successfully or not: a failed load still lets tag-aware+ // lists run unfiltered rather than wait forever.+ const ready = () => tagsQuery.isFetched;- return <TagSetsProvider tagSets={tagSets}>{props.children}</TagSetsProvider>;+ return (+ <TagSetsProvider tagSets={tagSets} ready={ready}>+ {props.children}+ </TagSetsProvider>+ );};function useTagSetsContext(): TagSetsContextValue {@@ -62,6 +83,11 @@ export function useTagSets(): TagSets {return useTagSetsContext().tagSets;}+/** Whether the nearest provider's tag sets have finished their first load. */+export function useTagSetsReady(): Accessor<boolean> {+ return useTagSetsContext().ready;+}+/** Returns the provider-owned tag-option index shared by every list row. */export function useTagOptionById() {return useTagSetsContext().optionById;diff --git a/apps/web/src/features/property/tags/use-tag-filter-group.tsx b/apps/web/src/features/property/tags/use-tag-filter-group.tsxnew file mode 100644index 0000000000..4875991f86--- /dev/null+++ b/apps/web/src/features/property/tags/use-tag-filter-group.tsx@@ -0,0 +1,27 @@+import type { ListFilterGroup } from '@app/components/view-shell';+import { TAG_FACET_ID } from '@app/features/soup';+import { type Accessor, createMemo } from 'solid-js';+import { TagDot } from './TagDot';+import { useTagOptions } from './tag-options';++export type TagFilterGroup = ListFilterGroup<typeof TAG_FACET_ID, string>;++/**+ * The Tags group of a list view's filter menu. Option ids are tag option ids,+ * so the selection can be stored directly under the shared tags facet.+ */+export function useTagFilterGroup(): Accessor<TagFilterGroup> {+ const tagOptions = useTagOptions();++ return createMemo(+ (): TagFilterGroup => ({+ id: TAG_FACET_ID,+ label: 'Tags',+ options: tagOptions().map((tag) => ({+ id: tag.id,+ label: tag.label,+ icon: () => <TagDot color={tag.color} />,+ })),+ })+ );+}diff --git a/apps/web/src/features/soup/filters/facets/index.ts b/apps/web/src/features/soup/filters/facets/index.tsindex d05504c3f5..6cf18c3793 100644--- a/apps/web/src/features/soup/filters/facets/index.ts+++ b/apps/web/src/features/soup/filters/facets/index.ts@@ -26,6 +26,14 @@ export {normalizeFacetSelection,serializeFacetSelection,} from './selection';+export {+ createTagFacetContext,+ EMPTY_TAG_FACET_CONTEXT,+ TAG_FACET_ID,+ type TagFacetContext,+ tagFacetOption,+ tagFacetReady,+} from './tag-facet';export type {Facet,FacetClause,diff --git a/apps/web/src/features/soup/filters/facets/tag-facet.test.ts b/apps/web/src/features/soup/filters/facets/tag-facet.test.tsnew file mode 100644index 0000000000..c12394a33a--- /dev/null+++ b/apps/web/src/features/soup/filters/facets/tag-facet.test.ts@@ -0,0 +1,125 @@+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';+import { describe, expect, it } from 'vitest';+import { compileFacets } from './compile';+import { testFacets } from './evaluate';+import {+ createTagFacetContext,+ EMPTY_TAG_FACET_CONTEXT,+ TAG_FACET_ID,+ tagFacetOption,+ tagFacetReady,+} from './tag-facet';+import type { Facet } from './types';++const TAG_SETS = [+ {+ scope: 'user',+ definition: { id: 'personal-definition' },+ options: [+ {+ id: 'urgent',+ propertyDefinitionId: 'personal-definition',+ displayOrder: 0,+ value: { type: 'string', value: 'Urgent' },+ },+ ],+ },+ {+ scope: 'team',+ definition: { id: 'team-definition' },+ options: [+ {+ id: 'launch',+ propertyDefinitionId: 'team-definition',+ displayOrder: 0,+ value: { type: 'string', value: 'Launch' },+ },+ ],+ },+] as TagSetResponse[];++type Item = { properties?: SoupProperty[] };++const tagged = (...optionIds: string[]): Item => ({+ properties: [+ {+ id: 'assignment',+ definition: { id: 'personal-definition' },+ value: { type: 'SelectOption', value: optionIds },+ } as SoupProperty,+ ],+});++const TAG_FACET: Facet<Item, ReturnType<typeof createTagFacetContext>> = {+ id: TAG_FACET_ID,+ mode: 'or',+ options: (optionId, context) => tagFacetOption<Item>(optionId, context),+};++describe('createTagFacetContext', () => {+ it('maps every option across sets to the definition that owns it', () => {+ const context = createTagFacetContext(TAG_SETS);++ expect([...context.tagPropertyDefinitionByOptionId]).toEqual([+ ['urgent', 'personal-definition'],+ ['launch', 'team-definition'],+ ]);+ });+});++describe('tagFacetOption', () => {+ const context = createTagFacetContext(TAG_SETS);++ it('resolves a known tag to its definition and option', () => {+ const option = tagFacetOption<Item>('launch', context);++ expect(option?.propertyDefinitionId).toBe('team-definition');+ expect(option?.propertyOptionId).toBe('launch');+ });++ it('resolves nothing for a tag outside the loaded sets', () => {+ expect(tagFacetOption<Item>('missing', context)).toBeUndefined();+ expect(tagFacetOption<Item>('urgent', EMPTY_TAG_FACET_CONTEXT)).toBe(+ undefined+ );+ });++ it('compiles the selection to one property filter per tag', () => {+ const ast = compileFacets(+ { tags: ['urgent', 'launch'] },+ [TAG_FACET],+ context+ );++ expect(ast.propf).toEqual({+ '|': [+ { l: { pd: 'team-definition', v: { so: 'launch' } } },+ { l: { pd: 'personal-definition', v: { so: 'urgent' } } },+ ],+ });+ });++ it('admits items carrying any selected tag', () => {+ const matches = (item: Item) =>+ testFacets({ tags: ['urgent'] }, [TAG_FACET], item, context);++ expect(matches(tagged('urgent'))).toBe(true);+ expect(matches(tagged('launch', 'urgent'))).toBe(true);+ expect(matches(tagged('launch'))).toBe(false);+ expect(matches({})).toBe(false);+ });+});++describe('tagFacetReady', () => {+ it('waits for the tag sets only while a tag is selected', () => {+ expect(tagFacetReady({}, false)).toBe(true);+ expect(tagFacetReady({ read: ['unread'] }, false)).toBe(true);+ expect(tagFacetReady({ tags: ['urgent'] }, false)).toBe(false);+ expect(tagFacetReady({ tags: ['urgent'] }, true)).toBe(true);+ });++ it('does not hold the query for a tag that no longer exists', () => {+ expect(tagFacetReady({ tags: ['gone'] }, true)).toBe(true);+ });+});diff --git a/apps/web/src/features/soup/filters/facets/tag-facet.ts b/apps/web/src/features/soup/filters/facets/tag-facet.tsnew file mode 100644index 0000000000..fc4dacda64--- /dev/null+++ b/apps/web/src/features/soup/filters/facets/tag-facet.ts@@ -0,0 +1,92 @@+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';+import { clause } from './clause';+import type { FacetOption, FacetSelection } from './types';++/** The facet id every tag-aware view stores its selected tag option ids under. */+export const TAG_FACET_ID = 'tags';++/**+ * A tag is a select option on the property definition that owns its set, so+ * resolving a selected option id needs the definition behind it.+ */+export type TagFacetContext = {+ tagPropertyDefinitionByOptionId: ReadonlyMap<string, string>;+};++export const EMPTY_TAG_FACET_CONTEXT: TagFacetContext = {+ tagPropertyDefinitionByOptionId: new Map(),+};++export function createTagFacetContext(+ tagSets: readonly TagSetResponse[]+): TagFacetContext {+ const tagPropertyDefinitionByOptionId = new Map<string, string>();+ for (const set of tagSets) {+ for (const option of set.options) {+ tagPropertyDefinitionByOptionId.set(+ option.id,+ option.propertyDefinitionId+ );+ }+ }+ return { tagPropertyDefinitionByOptionId };+}++type TaggedItem = { properties?: SoupProperty[] };++type TagFacetOption<TItem extends TaggedItem> = FacetOption<+ TItem,+ TagFacetContext+> & {+ propertyDefinitionId: string;+ propertyOptionId: string;+};++const itemHasTag = (item: TaggedItem, optionId: string): boolean =>+ item.properties?.some(+ (property) =>+ property.value?.type === 'SelectOption' &&+ property.value.value.includes(optionId)+ ) ?? false;++/**+ * Resolves a selected tag into a server clause and a client predicate. Unknown+ * ids (a deleted tag, or a set that has not loaded yet) resolve to nothing so+ * the selection is preserved but does not filter.+ */+export function tagFacetOption<TItem extends TaggedItem>(+ optionId: string,+ context: TagFacetContext+): TagFacetOption<TItem> | undefined {+ const propertyDefinitionId =+ context.tagPropertyDefinitionByOptionId.get(optionId);+ if (!propertyDefinitionId) return undefined;++ return {+ id: optionId,+ propertyDefinitionId,+ propertyOptionId: optionId,+ clause: {+ propf: clause.eq('properties', {+ propertyId: propertyDefinitionId,+ type: 'select',+ value: optionId,+ }),+ },+ predicate: (item) => itemHasTag(item, optionId),+ };+}++/**+ * Whether a view may run its query given the tag sets' load state. A restored+ * tag selection waits for the sets so the list does not show the whole+ * collection and then narrow; once they have loaded, a selected tag that no+ * longer exists simply stops filtering rather than blocking the query.+ */+export function tagFacetReady(+ selection: FacetSelection,+ tagSetsReady: boolean+): boolean {+ return tagSetsReady || (selection[TAG_FACET_ID] ?? []).length === 0;+}diff --git a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx b/apps/web/src/features/tasks-view/components/TasksSidebar.tsxindex 284d941ad6..0ebb600d41 100644--- a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx+++ b/apps/web/src/features/tasks-view/components/TasksSidebar.tsx@@ -4,7 +4,6 @@ import {ViewSidebar,} from '@app/components/view-shell';import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';-import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';import {favoriteSplitContent,useFavoriteDisplayName,@@ -16,12 +15,12 @@ import CheckSquareIcon from '@phosphor/check-square.svg';import ListChecksIcon from '@phosphor/list-checks.svg';import NoteIcon from '@phosphor/note-pencil.svg';import PlusIcon from '@phosphor/plus.svg';+import { SidebarTagsSection } from '@property/tags/SidebarTagsSection';import { useFavoritesData } from '@queries/favorites/favorites';import type { Favorite } from '@service-storage/generated/schemas/favorite';import { Button } from '@ui';import { createMemo, For, Show } from 'solid-js';import { Dynamic } from 'solid-js/web';-import { useTaskFilters } from '../filters/use-task-filters';import { useTasksView } from '../tasks-view-context';import type { TaskTab } from '../types';@@ -128,56 +127,16 @@ function TaskFavorites(props: {);}-function TaskTags(props: {- open: boolean;- onOpenChange: (open: boolean) => void;-}) {- const filters = useTaskFilters();- const tags = () =>- filters.groups().find((group) => group.id === 'tags')?.options ?? [];-- return (- <CollapsibleSection.Root- open={props.open}- onOpenChange={props.onOpenChange}- >- <CollapsibleSection.Trigger class="text-xs">- <CollapsibleSection.Indicator class="order-first ml-0" />- <span class="truncate">Tags</span>- </CollapsibleSection.Trigger>- <CollapsibleSection.Content>- <ViewSidebar.Nav aria-label="Task tags">- <For each={tags()}>- {(tag) => {- const selected = () => filters.isSelected('tags', tag.id);-- return (- <ViewSidebar.Item- active={selected()}- aria-pressed={selected()}- class="font-normal"- onClick={() =>- filters.setSelected('tags', tag.id, !selected())- }- >- <span class="flex size-4 shrink-0 items-center justify-center">- {tag.icon?.()}- </span>- <span class="truncate">{tag.label}</span>- </ViewSidebar.Item>- );- }}- </For>- </ViewSidebar.Nav>- </CollapsibleSection.Content>- </CollapsibleSection.Root>- );-}-export function TasksSidebar() {const layout = useSplitLayout();const panel = useSplitPanelOrThrow();- const { state, setState, setTab } = useTasksView();+ const {+ state,+ setTab,+ setFacets,+ isSidebarSectionOpen,+ setSidebarSectionOpen,+ } = useTasksView();useViewTabHotkeys({scopeId: panel.splitHotkeyScope,@@ -187,15 +146,6 @@ export function TasksSidebar() {setActiveId: setTab,});- const sectionOpen = (id: string) =>- !state.collapsedSidebarSectionIds.includes(id);-- const setSectionOpen = (id: string, open: boolean) =>- setState(- 'collapsedSidebarSectionIds',- open ? removeValue(id) : addUnique(id)- );-return (<ViewSidebar.Root aria-label="Tasks navigation" class="gap-4 bg-panel"><ViewSidebar.Header>@@ -228,13 +178,16 @@ export function TasksSidebar() {</div><TaskFavorites- open={sectionOpen('favorites')}- onOpenChange={(open) => setSectionOpen('favorites', open)}+ open={isSidebarSectionOpen('favorites')}+ onOpenChange={(open) => setSidebarSectionOpen('favorites', open)}/>- <TaskTags- open={sectionOpen('tags')}- onOpenChange={(open) => setSectionOpen('tags', open)}+ {/* Tags narrow the current tab; switching tabs clears them like any facet. */}+ <SidebarTagsSection+ activeIds={state.facets.tags ?? []}+ onActiveIdsChange={(ids) => setFacets({ ...state.facets, tags: ids })}+ open={isSidebarSectionOpen('tags')}+ onOpenChange={(open) => setSidebarSectionOpen('tags', open)}/></ViewSidebar.Content></ViewSidebar.Root>diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsxindex e3bdfeae0e..351d4fc4d9 100644--- a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx+++ b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx@@ -42,7 +42,7 @@ import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import SpinnerIcon from '@phosphor/spinner.svg';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property';-import { useTagSets } from '@property/tags/tag-sets-context';+import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { EntityType } from '@service-properties/generated/schemas/entityType';import { debounce } from '@solid-primitives/scheduled';@@ -124,10 +124,12 @@ export function TaskList(props: TaskListProps) {setState('collapsedGroupIds', toggleValue(groupId));const tagSets = useTagSets();+ const tagSetsReady = useTagSetsReady();const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>useTasksDataSource(state, {userId,tagSets,+ tagSetsReady,isGroupExpanded,}));diff --git a/apps/web/src/features/tasks-view/filters/task-facets.ts b/apps/web/src/features/tasks-view/filters/task-facets.tsindex b8bbfe404d..e5f4a92bf1 100644--- a/apps/web/src/features/tasks-view/filters/task-facets.ts+++ b/apps/web/src/features/tasks-view/filters/task-facets.ts@@ -1,10 +1,14 @@import {clause,+ EMPTY_TAG_FACET_CONTEXT,type Facet,type FacetClause,type FacetOption,type FacetSelection,resolveFacetOption,+ TAG_FACET_ID,+ type TagFacetContext,+ tagFacetOption,} from '@app/features/soup';import type { TaskEntityWithProperties } from '@entity/types/entity';import {@@ -14,13 +18,10 @@ import {} from '@entity/utils/task-properties';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';-export type TaskFacetContext = {- tagPropertyDefinitionByOptionId: ReadonlyMap<string, string>;-};+export type TaskFacetContext = TagFacetContext;-export const EMPTY_TASK_FACET_CONTEXT: TaskFacetContext = {- tagPropertyDefinitionByOptionId: new Map(),-};+export const EMPTY_TASK_FACET_CONTEXT: TaskFacetContext =+ EMPTY_TAG_FACET_CONTEXT;export type TaskFacetOption = FacetOption<TaskEntityWithProperties,@@ -98,31 +99,11 @@ const creatorOption = (id: string): TaskFacetOption => ({predicate: (task) => task.ownerId === id,});-const taskHasSelectOption = (- task: TaskEntityWithProperties,- optionId: string-) =>- task.properties?.some(- (property) =>- property.value?.type === 'SelectOption' &&- property.value.value.includes(optionId)- ) ?? false;-const tagOption = (id: string,context: TaskFacetContext-): TaskFacetOption | undefined => {- const propertyDefinitionId = context.tagPropertyDefinitionByOptionId.get(id);- if (!propertyDefinitionId) return undefined;-- return {- id,- propertyDefinitionId,- propertyOptionId: id,- clause: propertyClause(propertyDefinitionId, 'select', id),- predicate: (task) => taskHasSelectOption(task, id),- };-};+): TaskFacetOption | undefined =>+ tagFacetOption<TaskEntityWithProperties>(id, context);export const TASK_STATUS_OPTIONS = [statusOption(@@ -156,7 +137,7 @@ export const TASK_FACETS: Facet<{ id: 'priority', mode: 'or', options: TASK_PRIORITY_OPTIONS },{ id: 'assignees', mode: 'or', options: assigneeOption },{ id: 'created-by', mode: 'or', options: creatorOption },- { id: 'tags', mode: 'or', options: tagOption },+ { id: TAG_FACET_ID, mode: 'or', options: tagOption },];export const DEFAULT_TASK_FACET_SELECTION: FacetSelection = {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.tsxindex 09e046c194..419b212c98 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@@ -4,8 +4,7 @@ import { UserIcon } from '@core/component/UserIcon';import { useUserId } from '@core/context/user';import { idToDisplayName } from '@core/user/util';import { PropertyValueIcon } from '@property/component/propertyValue';-import { TagDot } from '@property/tags/TagDot';-import { useTagSets } from '@property/tags/tag-sets-context';+import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';import { useContacts } from '@queries/contacts/contacts';import { createMemo } from 'solid-js';import { useTasksView } from '../tasks-view-context';@@ -22,7 +21,7 @@ export function useTaskFilters() {const { state, setFacets } = useTasksView();const contacts = useContacts();const currentUserId = useUserId();- const tagSets = useTagSets();+ const tagGroup = useTagFilterGroup();const peopleOptions = createMemo(() => {const people = [...contacts()];@@ -89,18 +88,7 @@ export function useTaskFilters() {label: 'Created by',options: peopleOptions(),},- {- id: 'tags',- label: 'Tags',- options: tagSets().flatMap((set) =>- set.options.map((option) => ({- id: option.id,- label:- option.value.type === 'string' ? option.value.value : option.id,- icon: () => <TagDot color={option.color ?? undefined} />,- }))- ),- },+ tagGroup(),]);diff --git a/apps/web/src/features/tasks-view/persistence.ts b/apps/web/src/features/tasks-view/persistence.tsindex 0f0b21f7e5..76df1a4e09 100644--- a/apps/web/src/features/tasks-view/persistence.ts+++ b/apps/web/src/features/tasks-view/persistence.ts@@ -1,3 +1,4 @@+import { createCollapsedSidebarSectionsStorage } from '@app/components/view-shell';import { normalizeFacetSelection } from '@app/features/soup';import type {MakePersistedStateOptions,@@ -7,7 +8,6 @@ import {createEntryPersistenceStorage,type EntryPersistenceHandle,} from '@components/app/split-layout/entry-persistence';-import { createUserScopedStorage } from '@core/util/userScopedStorage';import type { Accessor } from 'solid-js';import { z } from 'zod';import { DEFAULT_TASK_FACET_SELECTION } from './filters/task-facets';@@ -62,18 +62,6 @@ const DEFAULT_TASKS_ENTRY_STATE = {collapsedGroupIds: [],} satisfies TasksEntryState;-const tasksPreferencesSchemaWithDefaults = z.object({- version: z.literal(1).default(1),- collapsedSidebarSectionIds: z.array(z.string()).default([]),-});--type TasksPreferences = z.infer<typeof tasksPreferencesSchemaWithDefaults>;--const DEFAULT_TASKS_PREFERENCES = {- version: 1,- collapsedSidebarSectionIds: [],-} satisfies TasksPreferences;-const tasksListStateSchemaWithDefaults = z.object({version: z.literal(1).default(1),focusKey: z.string().optional(),@@ -162,69 +150,6 @@ export function createTasksListEntryStorage(});}-const preferencesStorage = createUserScopedStorage(- 'macro:tasks:preferences:v1'-);--function createTasksPreferencesStorage(options: {- userId: Accessor<string | undefined>;- restore: boolean;-}): PersistenceStorage<TasksViewState> {- let previous: string | undefined;-- const serialize = (state: TasksViewState): string =>- JSON.stringify({- version: 1,- collapsedSidebarSectionIds: [...state.collapsedSidebarSectionIds],- } satisfies TasksPreferences);-- return {- restore: (current) => {- if (!options.restore) return undefined;-- const userId = options.userId();- if (!userId) return undefined;-- const raw = preferencesStorage.read(userId);- if (raw === null) return undefined;-- try {- const result = tasksPreferencesSchemaWithDefaults.safeParse(- JSON.parse(raw)- );- const restored = result.success- ? result.data- : DEFAULT_TASKS_PREFERENCES;-- return {- ...current,- collapsedSidebarSectionIds: [...restored.collapsedSidebarSectionIds],- };- } catch {- return {- ...current,- collapsedSidebarSectionIds: [- ...DEFAULT_TASKS_PREFERENCES.collapsedSidebarSectionIds,- ],- };- }- },- initialize: (current) => {- previous = serialize(current);- },- write: (current) => {- const userId = options.userId();- if (!userId) return;-- const serialized = serialize(current);- if (serialized === previous) return;-- previous = serialized;- preferencesStorage.write(userId, serialized);- },- };-}-export type CreateTasksViewPersistenceOptions = {handle: EntryPersistenceHandle;userId: Accessor<string | undefined>;@@ -238,7 +163,8 @@ export function createTasksViewPersistence(): MakePersistedStateOptions<TasksViewState> {return {storages: [- createTasksPreferencesStorage({+ createCollapsedSidebarSectionsStorage({+ key: 'macro:tasks:preferences:v1',userId: options.userId,restore: options.restorePreferences ?? true,}),diff --git a/apps/web/src/features/tasks-view/queries/task-search.test.ts b/apps/web/src/features/tasks-view/queries/task-search.test.tsnew file mode 100644index 0000000000..99a0816bb7--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/task-search.test.ts@@ -0,0 +1,65 @@+import { createTagFacetContext } from '@app/features/soup';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { describe, expect, it, vi } from 'vitest';+import { buildTaskSearchRequest } from './task-search';++// 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 TAG_SETS = [+ {+ scope: 'user',+ definition: { id: 'tag-definition' },+ options: [+ {+ id: 'urgent',+ propertyDefinitionId: 'tag-definition',+ displayOrder: 0,+ value: { type: 'string', value: 'Urgent' },+ },+ ],+ },+] as TagSetResponse[];++const requestFor = (facets: Record<string, string[]>, withTagSets = true) => {+ const { body } = buildTaskSearchRequest({+ query: 'launch',+ matchType: 'partial',+ tab: 'team-tasks',+ userId: 'user-1',+ facets,+ facetContext: withTagSets ? createTagFacetContext(TAG_SETS) : undefined,+ });+ if (!body.filters) throw new Error('search request has no filters');++ return body.filters;+};++describe('buildTaskSearchRequest', () => {+ it('sends selected tags as an entity-wide filter', () => {+ const filters = requestFor({ tags: ['urgent', 'urgent'] });++ expect(filters.tag_option_ids).toEqual(['urgent']);+ expect(filters.tag_filter_mode).toBe('any');+ });++ it('drops a selected tag that no longer exists, like the list query', () => {+ expect(+ requestFor({ tags: ['urgent', 'deleted-tag'] }).tag_option_ids+ ).toEqual(['urgent']);++ const unresolved = requestFor({ tags: ['deleted-tag'] }, false);+ expect(unresolved.tag_option_ids).toBeUndefined();+ expect(unresolved.tag_filter_mode).toBeUndefined();+ });+});diff --git a/apps/web/src/features/tasks-view/queries/task-search.ts b/apps/web/src/features/tasks-view/queries/task-search.tsindex 4fc1acba48..51353bdc59 100644--- a/apps/web/src/features/tasks-view/queries/task-search.ts+++ b/apps/web/src/features/tasks-view/queries/task-search.ts@@ -86,10 +86,8 @@ export function buildTaskSearchRequest(options: {facets: FacetSelection;facetContext?: TaskFacetContext;}): SearchSoupQueryArgs {- const propertyFilters = selectedPropertyFilters(- options.facets,- options.facetContext ?? EMPTY_TASK_FACET_CONTEXT- );+ const facetContext = options.facetContext ?? EMPTY_TASK_FACET_CONTEXT;+ const propertyFilters = selectedPropertyFilters(options.facets, facetContext);if (options.tab === 'my-tasks') {propertyFilters.push({@@ -100,7 +98,10 @@ export function buildTaskSearchRequest(options: {}const owners = selectedCreators(options.facets, options.tab, options.userId);- const tagOptionIds = [...new Set(options.facets.tags ?? [])];+ // Like the list query, a selected tag that no longer exists stops filtering.+ const tagOptionIds = [...new Set(options.facets.tags ?? [])].filter((id) =>+ facetContext.tagPropertyDefinitionByOptionId.has(id)+ );return {params: { cursor: null, page_size: 100 },diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.tsindex 9cfe35e2de..d31dbee7a8 100644--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts@@ -3,11 +3,13 @@ import {buildFlatSoupRows,buildGroupedSoupRows,createSearchState,+ createTagFacetContext,deduplicateSoupEntities,isSoupRowVisible,type SoupGroup,type SoupRow,sortItems,+ tagFacetReady,useSearchContext,} from '@app/features/soup';import { withEntityNotifications } from '@app/features/soup/entity-notifications';@@ -39,6 +41,7 @@ export type TasksDataSourceInput = Pick<export type UseTasksDataSourceOptions = {userId: Accessor<string | undefined>;tagSets: Accessor<readonly TagSetResponse[]>;+ tagSetsReady: Accessor<boolean>;isGroupExpanded: (groupId: string) => boolean;};@@ -64,23 +67,12 @@ export function useTasksDataSource(const attachNotifications = (entity: TaskEntityWithProperties) =>withEntityNotifications(entity, notificationSource);- const facetContext = createMemo((): TaskFacetContext => {- const tagPropertyDefinitionByOptionId = new Map<string, string>();- for (const set of options.tagSets()) {- for (const option of set.options) {- tagPropertyDefinitionByOptionId.set(- option.id,- option.propertyDefinitionId- );- }- }- return { tagPropertyDefinitionByOptionId };- });+ const facetContext = createMemo(+ (): TaskFacetContext => createTagFacetContext(options.tagSets())+ );const facetOptionsReady = () =>- (state.facets.tags ?? []).every((id) =>- facetContext().tagPropertyDefinitionByOptionId.has(id)- );+ tagFacetReady(state.facets, options.tagSetsReady());const queryArgs = () =>buildTaskQuery({@@ -261,7 +253,8 @@ export function useTasksDataSource(const isLoading = () => {if (!search.isSearching()) {- return query.isLoading && rows().length === 0;+ // A query held back for the tag sets is loading, not empty.+ return (query.isLoading || !facetOptionsReady()) && rows().length === 0;}if (tasks().length > 0) return false;if (usesServiceSearch()) return search.isLoading();diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsxindex c1001c8d9a..430f0bd543 100644--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx@@ -1,3 +1,4 @@+import { setSidebarSectionCollapsed } from '@app/components/view-shell';import { normalizeFacetSelection } from '@app/features/soup';import { makePersistedState } from '@app/lib/persistence';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';@@ -31,6 +32,8 @@ export type TasksViewContext = {setTab: (tab: TaskTab) => void;setFacets: (facets: TasksViewState['facets']) => void;setPrimarySort: (id: TaskSortId) => void;+ isSidebarSectionOpen: (id: string) => boolean;+ setSidebarSectionOpen: (id: string, open: boolean) => void;};export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<@@ -91,11 +94,22 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<setState('sort', [{ id, reversed }]);};+ const isSidebarSectionOpen = (id: string) =>+ !state.collapsedSidebarSectionIds.includes(id);++ const setSidebarSectionOpen = (id: string, open: boolean) =>+ setState(+ 'collapsedSidebarSectionIds',+ setSidebarSectionCollapsed(id, open)+ );+return {state,setState,setTab,setFacets,setPrimarySort,+ isSidebarSectionOpen,+ setSidebarSectionOpen,};});diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex d875393970..b37d4488c4 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -101,7 +101,7 @@ With the new app views enabled, mobile and tablet Email use a floating, horizontscrolling row of those tabs, with `Open email filters` at the left. The rest of theview is the email list, which scrolls beneath the header and supports pull to refreshand swiping left to mark emails done in Signal and Noise. The filter button opens a-bottom drawer for status, done, attachment and calendar filters, plus an `Inbox`+bottom drawer for status, done, attachment, calendar and tag filters, plus an `Inbox`section when the user can pick one: `All inboxes` or a single address, never several.`Clear all` resets those filters and the inbox selection. Desktop keeps its sidebar,search field, filter menu and preview control. The sidebar lists the inboxes above the@@ -109,7 +109,10 @@ tabs as plain rows; clicking one shows only that inbox, and the `+` beside`All inboxes` (`Connect another account`) starts the add-inbox flow. Sidebar rows,`New`, and the panel's back, forward and close controls act on primary-buttonmousedown, so the selection changes before the click completes; a normal click-still works.+still works. The sidebar ends with a collapsible `Tags` section (every personal and+team tag, plus a `New tag` button): clicking a tag opens the `All` tab filtered to+threads carrying it, clicking it again clears it, and choosing any tab clears it like+the other filters.## Searchdiff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.mdindex 87072e855a..deb128cc7a 100644--- a/docs/AGENT_GUIDE/tasks.md+++ b/docs/AGENT_GUIDE/tasks.md@@ -4,9 +4,13 @@`Go to Tasks` → `/app/component/tasks`. Tabs: `My tasks`, `Created by me`, and `Team tasks`.The desktop toolbar contains search (`Ctrl+F`), `Sort`, `Group`, `Filter`, and `Preview`;-task creation is available from the `New` button in the Tasks sidebar. On mobile, the tabs+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+carrying it (the same selection as the `Tags` group of the `Filter` menu); clicking it again+clears it, and switching tabs clears it like any other filter. On mobile, the tabsare pills and the leading sliders button opens one drawer containing Sort, Group, and-Filters. Mobile intentionally omits the search and create controls.+Filters (including Tags). Mobile intentionally omits the search and create controls.New accounts are seeded with three sample tasks (`Intro to tasks`, `Advanced task features`,`How we use tasks at Macro`).