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.

fix(tasks): group tasks by their project property (#8983)

Wolf Mermelsteina7e1921b740c
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 35f0c97685..03cf76cfc3 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -212,6 +212,9 @@ Shared diff and Changes views expand files with at most 40 additions + deletions
by default; keep saved per-capture choices and explicit toggles authoritative.
Use `/app/debug/diff-view-ui` to exercise the 40/41-line boundary.
+Project grouping in Soup and its live cache projection uses the system Project
+property (initiative membership), with an empty key labeled No Project.
+
Keep persistent list hotkeys free of mounted-view closures, and clear
virtualizer accessors when their view unmounts.
Keep editor newline handling local; result-opening handlers must yield
diff --git a/apps/web/src/features/tasks-view/AGENTS.md b/apps/web/src/features/tasks-view/AGENTS.md
index 8b9c757a79..93878773a2 100644
--- a/apps/web/src/features/tasks-view/AGENTS.md
+++ b/apps/web/src/features/tasks-view/AGENTS.md
@@ -14,6 +14,8 @@ Main Tasks and reusable task-list hosts. Projects and CRM embed `TasksViewProvid
## Gotchas
+- Group task lists by the Project property, matching the Project column and Board; resolve project headers through the authorized project identity query.
+
- Save filters, selected layout, grouping, and ordered sort directions; keep text search and scroll state local, and capture implicit person conditions as normal OR-valued facets.
- Preserve stable tag/property bindings when labels disappear; skip unsupported or malformed conditions without discarding supported filters.
- Label the semantic viewer token Me, explain it with “Matches whoever opens this saved view,” and resolve it only when executing a filter; a selected fixed user stays fixed.
@@ -46,6 +48,7 @@ Run from `apps/web`:
- `bun run test src/features/tasks-view`
- `bun run type-check`
+- Project grouping browser regression: `bunx playwright test --config src/features/tasks-view/browser-test/playwright.config.ts project-grouping.browser.e2e.ts`.
## Related
diff --git a/apps/web/src/features/tasks-view/browser-test/project-grouping.browser.e2e.ts b/apps/web/src/features/tasks-view/browser-test/project-grouping.browser.e2e.ts
new file mode 100644
index 0000000000..fd5ba9b237
--- /dev/null
+++ b/apps/web/src/features/tasks-view/browser-test/project-grouping.browser.e2e.ts
@@ -0,0 +1,55 @@
+import { expect, test } from '@playwright/test';
+
+for (const mobile of [false, true]) {
+ test.describe(mobile ? 'phone' : 'desktop', () => {
+ test.use({
+ viewport: mobile
+ ? { width: 390, height: 844 }
+ : { width: 1280, height: 800 },
+ hasTouch: mobile,
+ isMobile: mobile,
+ });
+ test('project grouping follows assignment and clearing', async ({
+ page,
+ }) => {
+ await page.routeWebSocket('**', (socket) => socket.close());
+ await page.goto(
+ '/src/features/tasks-view/browser-test/project-grouping.html'
+ );
+ const first = page.getByRole('region', {
+ name: 'Project One',
+ exact: true,
+ });
+ const second = page.getByRole('region', {
+ name: 'Project Two',
+ exact: true,
+ });
+ const unassigned = page.getByRole('region', {
+ name: 'No Project',
+ exact: true,
+ });
+ await expect(first.getByRole('button')).toContainText('Project One', {
+ timeout: 30000,
+ });
+ if (mobile)
+ expect(await page.evaluate(() => window.innerWidth)).toBe(390);
+ await expect(second.getByRole('button')).toContainText('Project Two');
+ await expect(unassigned).toContainText('Task Without Project');
+ await expect(first).toContainText('Task One');
+ await expect(second).toContainText('Task Two');
+ await first.getByRole('button').click();
+ await expect(
+ first.getByRole('gridcell', { name: 'Task One', exact: true })
+ ).toHaveCount(0);
+ await first.getByRole('button').click();
+ await page
+ .getByRole('button', { name: 'Clear Task One project' })
+ .click();
+ await expect(first).toHaveCount(0);
+ await expect(unassigned).toContainText('Task One');
+ await page.getByRole('button', { name: 'Restore Project One' }).click();
+ await expect(first).toContainText('Task One');
+ await expect(unassigned).not.toContainText('Task One');
+ });
+ });
+}
diff --git a/apps/web/src/features/tasks-view/browser-test/project-grouping.html b/apps/web/src/features/tasks-view/browser-test/project-grouping.html
new file mode 100644
index 0000000000..4e43e6ed10
--- /dev/null
+++ b/apps/web/src/features/tasks-view/browser-test/project-grouping.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Task project grouping regression</title></head>
+ <body><div id="root"></div><script type="module" src="./project-grouping.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/tasks-view/browser-test/project-grouping.tsx b/apps/web/src/features/tasks-view/browser-test/project-grouping.tsx
new file mode 100644
index 0000000000..e0fcce448e
--- /dev/null
+++ b/apps/web/src/features/tasks-view/browser-test/project-grouping.tsx
@@ -0,0 +1,177 @@
+// Production grouping and headers over synthetic tasks; only HTTP is replaced.
+import '@app/index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { enableGraphqlSoup, enableProjects } from '@core/constant/featureFlags';
+import { UserContextProvider } from '@core/context/user';
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
+import { authKeys } from '@queries/auth/keys';
+import { queryClient } from '@queries/client';
+import { localSoupGroupKeys } from '@queries/soup/graphql/grouped-local-projection';
+import { groupedDocument } from '@queries/soup/graphql/grouped-test-fixtures';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { TaskGroupHeader } from '../components/task-list/TaskGroupHeader';
+
+enableProjects.override = true;
+enableGraphqlSoup.override = false;
+const VIEWER_ID = 'macro|[email protected]';
+const PROJECTS = new Map([
+ ['ad000000-0000-0000-0000-000000000001', 'Project One'],
+ ['ad000000-0000-0000-0000-000000000002', 'Project Two'],
+]);
+queryClient.setQueryData(authKeys.userInfo.queryKey, {
+ id: VIEWER_ID,
+ email: '[email protected]',
+ authenticated: true,
+});
+window.fetch = async (_input, init) => {
+ const body = JSON.parse(String(init?.body ?? '{}'));
+ const id = body.variables?.initiativeId;
+ if (id && PROJECTS.has(id)) {
+ return Response.json({
+ data: {
+ user: {
+ id: VIEWER_ID,
+ initiative: {
+ __typename: 'GraphqlSoupInitiative',
+ id,
+ displayName: PROJECTS.get(id),
+ viewerPermission: {
+ __typename: 'GraphqlAccessLevelPermission',
+ accessLevel: 'OWNER',
+ },
+ },
+ },
+ },
+ });
+ }
+ return Response.json({});
+};
+
+function Fixture() {
+ const [cleared, setCleared] = createSignal(false);
+ const [collapsed, setCollapsed] = createSignal(new Set<string>());
+ const tasks = createMemo(() =>
+ ['Task One', 'Task Two', 'Task Without Project'].map((name, index) => {
+ const item = groupedDocument(name);
+ const projectId = [...PROJECTS.keys()][index];
+ item.properties =
+ projectId && !(index === 0 && cleared())
+ ? [
+ {
+ ...item.properties[0],
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ value: {
+ __typename: 'GraphqlEntityReferencePropertyValue',
+ references: [
+ {
+ entityId: projectId,
+ entityType: 'INITIATIVE',
+ specificMessageId: null,
+ },
+ ],
+ },
+ },
+ ]
+ : [];
+ return item;
+ })
+ );
+ const groups = createMemo(() => {
+ const bins = new Map<string, ReturnType<typeof tasks>>();
+ for (const item of tasks()) {
+ for (const key of localSoupGroupKeys(
+ item,
+ { groupBy: { field: 'PROJECT' } },
+ new Date()
+ ) ?? []) {
+ bins.set(key, [...(bins.get(key) ?? []), item]);
+ }
+ }
+ return [...bins].sort(([a], [b]) =>
+ a ? (b ? a.localeCompare(b) : -1) : 1
+ );
+ });
+ return (
+ <main class="mx-auto max-w-5xl p-4 text-ink">
+ <h1 class="mb-4 text-xl font-semibold">Tasks</h1>
+ <div class="mb-4 flex items-center justify-between text-sm">
+ <span>Group by Project</span>
+ <button
+ type="button"
+ class="rounded border border-edge-muted px-3 py-2"
+ onClick={() => setCleared((value) => !value)}
+ >
+ {cleared() ? 'Restore Project One' : 'Clear Task One project'}
+ </button>
+ </div>
+ <div role="grid" aria-label="Tasks grouped by Project">
+ <For each={groups()}>
+ {([key, items]) => (
+ <section aria-label={PROJECTS.get(key) ?? 'No Project'}>
+ <TaskGroupHeader
+ row={{
+ kind: 'group-header',
+ id: `group-${key}`,
+ groupId: key,
+ label: key || 'No Project',
+ count: items.length,
+ }}
+ groupBy="project"
+ expanded={!collapsed().has(key)}
+ focused={false}
+ columnCount={2}
+ onFocus={() => {}}
+ onToggle={() =>
+ setCollapsed((previous) => {
+ const next = new Set(previous);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ })
+ }
+ />
+ <Show when={!collapsed().has(key)}>
+ <For each={items}>
+ {(item) => (
+ <div
+ role="row"
+ class="flex items-center justify-between gap-3 border-b border-edge-muted px-5 py-4 text-sm"
+ >
+ <span role="gridcell">{item.displayName}</span>
+ <span role="gridcell" class="truncate text-ink-muted">
+ {PROJECTS.get(
+ item.properties[0]?.value?.__typename ===
+ 'GraphqlEntityReferencePropertyValue'
+ ? (item.properties[0].value.references[0]
+ ?.entityId ?? '')
+ : ''
+ ) ?? 'No Project'}
+ </span>
+ </div>
+ )}
+ </For>
+ </Show>
+ </section>
+ )}
+ </For>
+ </div>
+ </main>
+ );
+}
+render(
+ () => (
+ <QueryClientProvider client={queryClient}>
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <UserContextProvider>
+ <Fixture />
+ </UserContextProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ </QueryClientProvider>
+ ),
+ document.getElementById('root')!
+);
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
index a9bafa28f9..7b31034b49 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
@@ -6,9 +6,10 @@ import { getDisplayName, tryMacroId } from '@core/user';
import { getPropertyOptionLabel } from '@entity';
import CaretRightIcon from '@icon/system/regular/caret-right.svg';
import CircleDashedIcon from '@icon/system/regular/circle-dashed.svg';
-import FolderIcon from '@icon/system/regular/folder-simple.svg';
+import ProjectIcon from '@icon/system/regular/stack.svg';
import { PROPERTY_OPTION_IDS } from '@property';
import { PropertyValueIcon } from '@property/component/propertyValue';
+import { usePropertyEntityDisplay } from '@property/hooks/usePropertyEntityDisplay';
import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';
import { ComposerSurface, cn, Layer } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
@@ -42,6 +43,13 @@ export function TaskGroupHeader(props: {
? props.row.groupId
: ''
);
+ const project = usePropertyEntityDisplay(
+ () => (props.groupBy === 'project' ? props.row.groupId : ''),
+ () =>
+ props.groupBy === 'project' && props.row.groupId
+ ? 'INITIATIVE'
+ : undefined
+ );
const label = createMemo(() => {
if (!props.row.groupId) return props.row.label || 'Not set';
@@ -49,6 +57,8 @@ export function TaskGroupHeader(props: {
return getPropertyOptionLabel(props.row.groupId) ?? props.row.label;
}
+ if (props.groupBy === 'project') return project.name();
+
if (props.groupBy === 'assignee') {
if (isBotPrincipalId(props.row.groupId)) return agent.name();
const assigneeId = tryMacroId(props.row.groupId);
@@ -125,7 +135,7 @@ export function TaskGroupHeader(props: {
/>
</Match>
<Match when={props.groupBy === 'project'}>
- <FolderIcon class="size-3.5 shrink-0" />
+ <ProjectIcon class="size-3.5 shrink-0" />
</Match>
</Switch>
<span class="truncate">{label()}</span>
diff --git a/apps/web/src/features/tasks-view/queries/task-query.test.ts b/apps/web/src/features/tasks-view/queries/task-query.test.ts
index 56a8197a13..b3a51ca016 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.test.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.test.ts
@@ -132,7 +132,7 @@ describe('task CRM scope', () => {
});
});
-it('uses the initiative Project property for board columns without changing legacy list grouping', () => {
+it('uses explicit Project property grouping for board editing and Project grouping for lists', () => {
const boardQuery = buildTaskQuery({
...options,
groupBy: 'project',
diff --git a/apps/web/src/features/tasks-view/queries/task-query.ts b/apps/web/src/features/tasks-view/queries/task-query.ts
index bd85266910..200692ad2f 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.ts
@@ -119,7 +119,7 @@ export type BuildTaskQueryOptions = {
crm?: TaskCrmScope;
/** Only tasks whose name contains this text, case-insensitively. */
nameContains?: string;
- /** Board Project columns use the initiative property, not legacy folders. */
+ /** Board Project columns use explicit property grouping for column editing. */
board?: boolean;
};
diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
index 28fa9ae5b5..4c80d85bac 100644
--- a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
@@ -1,3 +1,4 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { describe, expect, it } from 'vitest';
import { parseCacheRevision } from '../../../graphql-cache/protocol';
import type {
@@ -5,6 +6,11 @@ import type {
GroupSoupQuery,
SoupItemFieldsFragment,
} from '../../../service-clients/service-storage/graphql/generated/graphql';
+import { mapGraphqlSoupItem } from '../../../service-clients/service-storage/graphql-soup';
+import {
+ computeGroupKeysForItem,
+ resolveGroupMetaForKey,
+} from '../grouped/api';
import {
localSoupGroupKeys,
mergeGroupedSoupBins,
@@ -288,6 +294,55 @@ describe('local grouped Soup projection', () => {
).toBeUndefined();
});
+ it('moves project groups with the initiative property despite a different folder', () => {
+ const task = groupedDocument('a');
+ task.projectId = 'legacy-folder';
+ task.properties[0] = {
+ ...task.properties[0],
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ value: {
+ __typename: 'GraphqlEntityReferencePropertyValue',
+ references: [
+ {
+ entityId: 'initiative-1',
+ entityType: 'INITIATIVE',
+ specificMessageId: null,
+ },
+ ],
+ },
+ };
+ const projectInput: GroupedSoupInitialInput = {
+ groupBy: { field: 'PROJECT' },
+ };
+ expect(localSoupGroupKeys(task, projectInput, now)).toEqual([
+ 'initiative-1',
+ ]);
+ const apiTask = mapGraphqlSoupItem(task);
+ expect(apiTask).toBeDefined();
+ if (!apiTask) throw new Error('Task must map to the REST item shape');
+ expect(computeGroupKeysForItem(apiTask, { type: 'project' })).toEqual([
+ 'initiative-1',
+ ]);
+ expect(resolveGroupMetaForKey({ type: 'project' }, '')?.label).toBe(
+ 'No Project'
+ );
+
+ const unassigned = { ...task, properties: [] };
+ const result = projectLocalGroupedSoup(
+ [{ key: 'initiative-1', items: [task], totalCount: 1, nextCursor: null }],
+ new Map(),
+ snapshot([unassigned]),
+ projectInput,
+ now
+ );
+ expect(
+ result.find((bin) => bin.key === '')?.items.map((item) => item.id)
+ ).toEqual(['a']);
+ expect(result.find((bin) => bin.key === 'initiative-1')?.totalCount).toBe(
+ 0
+ );
+ });
+
it('distinguishes known empty property values from unknown grouping evidence', () => {
expect(localSoupGroupKeys(groupedDocument('a', []), input, now)).toEqual([
'',
@@ -298,7 +353,7 @@ describe('local grouped Soup projection', () => {
{ ...input, groupBy: { field: 'PROJECT' } },
now
)
- ).toEqual(['project-2']);
+ ).toEqual(['']);
const linked = groupedDocument('a');
linked.properties[0].value = {
__typename: 'GraphqlLinkPropertyValue',
diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.ts b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.ts
index 86932eb855..0ae8beba79 100644
--- a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.ts
+++ b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.ts
@@ -1,3 +1,4 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { match } from 'ts-pattern';
import type {
GroupedSoupInitialInput,
@@ -21,12 +22,19 @@ export function localSoupGroupKeys(
match(input.groupBy.field)
// Entity type cannot change for a normalized identity. Retain its server key.
.with('ENTITY_TYPE', () => undefined)
- .with('PROJECT', () => {
- if ('projectId' in item) return [item.projectId ?? ''];
- if (item.__typename === 'GraphqlSoupProject')
- return [item.parentId ?? ''];
- return undefined;
- })
+ .with('PROJECT', () =>
+ localSoupGroupKeys(
+ item,
+ {
+ ...input,
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ },
+ },
+ now
+ )
+ )
.with('PROPERTY', () => {
if (!('properties' in item)) return undefined;
const entityType = match(item)
diff --git a/apps/web/src/lib/queries/soup/grouped/api.ts b/apps/web/src/lib/queries/soup/grouped/api.ts
index b3e01b8e7e..8d278a717e 100644
--- a/apps/web/src/lib/queries/soup/grouped/api.ts
+++ b/apps/web/src/lib/queries/soup/grouped/api.ts
@@ -47,25 +47,6 @@ function hasProperties<T extends SoupApiItem>(
return true;
}
-function hasProjectId<T extends SoupApiItem>(
- item: T
-): item is T & {
- data: T['data'] & {
- projectId?: string;
- };
-} {
- if (
- item.tag === 'channel' ||
- item.tag === 'call' ||
- item.tag === 'crmCompany' ||
- item.tag === 'foreignEntity' ||
- item.tag === 'project'
- )
- return false;
-
- return true;
-}
-
export function serializeGroupByField(
field: GroupByField
): ApiGroupedSoupField {
@@ -255,18 +236,17 @@ export function makeGroupComparator(
export function computeGroupKeysForItem(
item: SoupApiItem,
groupBy: GroupByField | undefined
-) {
+): string[] | undefined {
if (!groupBy) return;
return match(groupBy)
.with({ type: 'entity_type' }, () => [item.tag])
- .with({ type: 'project' }, () => {
- if (!hasProjectId(item)) return;
-
- const projectId = item.data.projectId;
-
- return [projectId ?? NOT_SET_GROUP_KEY];
- })
+ .with({ type: 'project' }, () =>
+ computeGroupKeysForItem(item, {
+ type: 'property',
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ })
+ )
.with({ type: 'property' }, (propertyGroupBy) => {
if (!hasProperties(item)) return;
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 71ecd25045..26728e94a6 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -1463,7 +1463,7 @@ export type GraphqlGroupByField =
| 'DATE'
/** Group by Soup entity type. */
| 'ENTITY_TYPE'
- /** Group by containing project. */
+ /** Group by the Project property (initiative membership). */
| 'PROJECT'
/** Group by a property value. */
| 'PROPERTY';
diff --git a/crates/graphql_soup/AGENTS.md b/crates/graphql_soup/AGENTS.md
index 670af0ca41..8355347d7f 100644
--- a/crates/graphql_soup/AGENTS.md
+++ b/crates/graphql_soup/AGENTS.md
@@ -10,6 +10,8 @@ viewer pattern), which apply to every type defined here.
## Gotchas
+- `PROJECT` grouping forwards the Project property (initiative membership) to Soup; legacy folder IDs are not grouping keys.
+
- `SoupItemLoader` (single-entity lookups, `soupUpdates` hydration) resolves
email threads through entity-access view receipts, the rule the REST thread
route applies, not through the viewer's inbox scope; Soup's email leg only
diff --git a/crates/graphql_soup/src/inputs.rs b/crates/graphql_soup/src/inputs.rs
index 4b5257bc24..6e0507a15e 100644
--- a/crates/graphql_soup/src/inputs.rs
+++ b/crates/graphql_soup/src/inputs.rs
@@ -243,7 +243,7 @@ enum GraphqlGroupByField {
Date,
/// Group by Soup entity type.
EntityType,
- /// Group by containing project.
+ /// Group by the Project property (initiative membership).
Project,
/// Group by a property value.
Property,
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index dfe17fae74..6d37e87f52 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -66,6 +66,9 @@ rows, initiatives, ...) and get back a single unified, paginated result.
## Gotchas
+- Project grouping uses the system Project property (initiative membership),
+ including canonical TASK assignments, rather than legacy folder `project_id`.
+
- `crm_association.rs` resolves CRM scope before filtering, sorting, and paging.
Activity uses property edges rather than references and matches email within
the caller's mailbox. Keep browser requests bounded; never expand every CRM
diff --git a/crates/soup/src/domain/models/grouping.rs b/crates/soup/src/domain/models/grouping.rs
index aaca7339f7..87ea7ab8b3 100644
--- a/crates/soup/src/domain/models/grouping.rs
+++ b/crates/soup/src/domain/models/grouping.rs
@@ -26,6 +26,7 @@ fn resolve_group_label_and_order(key: &str, group_by: &GroupByField) -> (String,
entity_type_labels::label(key).to_string(),
Some(entity_type_labels::display_order(key)),
),
+ // Project keys are initiative IDs; keep the dedicated unassigned label.
GroupByField::Project if key.is_empty() => ("No Project".to_string(), Some(i32::MAX)),
GroupByField::Property { .. } if key.is_empty() => ("Not Set".to_string(), Some(i32::MAX)),
_ => (key.to_string(), None),
diff --git a/crates/soup/src/outbound/pg_soup_repo/grouping.rs b/crates/soup/src/outbound/pg_soup_repo/grouping.rs
index 64d4a3e375..29e21c90eb 100644
--- a/crates/soup/src/outbound/pg_soup_repo/grouping.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/grouping.rs
@@ -2,13 +2,19 @@
use models_grouping::{GroupByField, date_bucket_sql_key, date_bucket_sql_order};
use std::borrow::Cow;
+use system_properties::SystemPropertyKey;
+
+const PROJECT_GROUPING: GroupByField = GroupByField::Property {
+ property_definition_id: SystemPropertyKey::PROJECT_UUID,
+ entity_type: None,
+};
/// Build the group select expression for a field.
pub fn group_select_expr(field: &GroupByField) -> Cow<'static, str> {
match field {
GroupByField::Date => Cow::Owned(date_bucket_sql_key("sort_ts")),
GroupByField::EntityType => Cow::Borrowed("item_type"),
- GroupByField::Project => Cow::Borrowed("COALESCE(project_id::text, '')"),
+ GroupByField::Project => group_select_expr(&PROJECT_GROUPING),
GroupByField::Property { .. } => Cow::Borrowed(
"COALESCE(
CASE ep_group.values->>'type'
@@ -28,7 +34,7 @@ pub fn group_order_expr(field: &GroupByField) -> Cow<'static, str> {
match field {
GroupByField::Date => Cow::Owned(date_bucket_sql_order("sort_ts")),
GroupByField::EntityType => Cow::Borrowed("item_type"),
- GroupByField::Project => Cow::Borrowed("project_id NULLS LAST"),
+ GroupByField::Project => group_order_expr(&PROJECT_GROUPING),
GroupByField::Property { .. } => Cow::Borrowed(
"COALESCE(
(SELECT po.display_order FROM property_options po
@@ -64,6 +70,8 @@ pub struct GroupJoinClause {
/// type, so a task ignores legacy `DOCUMENT` assignments for the same id.
pub fn group_join_clause(field: &GroupByField) -> Option<GroupJoinClause> {
match field {
+ // Project is the initiative property displayed by the task column.
+ GroupByField::Project => group_join_clause(&PROJECT_GROUPING),
GroupByField::Property {
property_definition_id,
entity_type,
diff --git a/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs b/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
index f6a03281c3..66c8245fdc 100644
--- a/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
@@ -1,5 +1,6 @@
mod access;
mod pagination;
+mod project;
mod sorting;
use super::*;
@@ -46,13 +47,6 @@ fn entity_type_expr() {
assert_eq!(&*expr, "item_type");
}
-#[test]
-fn project_expr() {
- let expr = group_select_expr(&GroupByField::Project);
- assert!(expr.contains("project_id"));
- assert!(expr.contains("COALESCE"));
-}
-
#[test]
fn property_join_includes_definition_id() {
let field = GroupByField::Property {
diff --git a/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.rs b/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.rs
new file mode 100644
index 0000000000..0fa0783e35
--- /dev/null
+++ b/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.rs
@@ -0,0 +1,100 @@
+use super::*;
+use crate::domain::models::SoupPropertiesField;
+use crate::domain::models::grouping::{ItemGroupingInfo, build_grouped_response};
+use document_sub_type::DocumentSubType;
+use item_filters::ast::project::ProjectLiteral;
+use uuid::{Uuid, uuid};
+
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ fixtures(path = ".", scripts("project")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn tasks_group_by_their_project_property(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let owner = sqlx::query_scalar!(
+ r#"SELECT owner FROM "Document" WHERE id = '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa'"#
+ )
+ .fetch_one(&pool)
+ .await?;
+ let user_id = MacroUserIdStr::parse_from_str(&owner)?;
+ let filter = EntityFilterAst {
+ document_filter: Some(Arc::new(Expr::val(DocumentLiteral::SubType(
+ DocumentSubType::Task,
+ )))),
+ chat_filter: Some(Arc::new(Expr::val(ChatLiteral::Importance(false)))),
+ project_filter: Some(Arc::new(Expr::val(ProjectLiteral::Importance(false)))),
+ ..EntityFilterAst::mock_empty()
+ };
+ // Exercise both the initial bins and the group-specific load-more query.
+ for group_key in [
+ None,
+ Some("ad000000-0000-0000-0000-000000000001"),
+ Some("ad000000-0000-0000-0000-000000000002"),
+ Some(""),
+ ] {
+ let items = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(SimpleSortMethod::ViewedUpdated, filter.clone()),
+ exclude_frecency: false,
+ grouping: GroupingConfig {
+ field: GroupByField::Project,
+ group_key: group_key.map(str::to_owned),
+ per_group_limit: None,
+ },
+ },
+ )
+ .await?
+ .collect::<Vec<_>>();
+ let expected: Vec<(&str, Uuid)> = vec![
+ (
+ "ad000000-0000-0000-0000-000000000001",
+ uuid!("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ ),
+ (
+ "ad000000-0000-0000-0000-000000000002",
+ uuid!("11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ ),
+ ("", uuid!("11111111-cccc-cccc-cccc-cccccccccccc")),
+ ]
+ .into_iter()
+ .filter(|(key, _)| group_key.is_none_or(|requested| requested == *key))
+ .collect();
+ assert_eq!(items.len(), expected.len());
+ for (key, id) in expected {
+ let item = items
+ .iter()
+ .find(|item| item.item.id() == id)
+ .expect("task returned");
+ assert_eq!(item.key, key);
+ assert_eq!(item.total_group_count, 1);
+ }
+ let response = build_grouped_response(
+ items.into_iter().map(|group| ItemGroupingInfo {
+ key: group.key,
+ total_group_count: group.total_group_count,
+ index_in_group: group.index_in_group,
+ item: group.item.map_extra(|()| SoupPropertiesField::default()),
+ }),
+ &GroupByField::Project,
+ SimpleSortMethod::ViewedUpdated,
+ group_key.map(str::to_owned),
+ filter.clone(),
+ );
+ if group_key.is_none() || group_key == Some("") {
+ let unassigned = response
+ .groups
+ .iter()
+ .find(|group| group.key.is_empty())
+ .expect("unassigned group");
+ assert_eq!(unassigned.label, "No Project");
+ assert_eq!(unassigned.total_count, 1);
+ }
+ }
+ Ok(())
+}
diff --git a/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.sql b/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.sql
new file mode 100644
index 0000000000..bf0c779769
--- /dev/null
+++ b/crates/soup/src/outbound/pg_soup_repo/grouping/test/project.sql
@@ -0,0 +1,27 @@
+-- All three tasks have legacy folder IDs that must not determine their groups.
+INSERT INTO document_sub_type (document_id, sub_type) VALUES
+('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'task'),
+('11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'task'),
+('11111111-cccc-cccc-cccc-cccccccccccc', 'task');
+
+INSERT INTO "SharePermission" (id) VALUES ('group-project-one'), ('group-project-two');
+INSERT INTO initiative (id, name, owner_user_id, share_permission_id)
+SELECT projects.id::uuid, projects.name, document.owner, projects.share_permission_id
+FROM (VALUES
+ ('ad000000-0000-0000-0000-000000000001', 'Project One', 'group-project-one'),
+ ('ad000000-0000-0000-0000-000000000002', 'Project Two', 'group-project-two')
+) AS projects(id, name, share_permission_id)
+CROSS JOIN "Document" document
+WHERE document.id = '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values) VALUES
+('e0000000-0000-0000-0000-000000000101', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TASK',
+ '00000001-0000-0000-0000-000000000014',
+ '{"type":"EntityReference","value":[{"entity_type":"INITIATIVE","entity_id":"ad000000-0000-0000-0000-000000000001"}]}'),
+('e0000000-0000-0000-0000-000000000102', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'TASK',
+ '00000001-0000-0000-0000-000000000014',
+ '{"type":"EntityReference","value":[{"entity_type":"INITIATIVE","entity_id":"ad000000-0000-0000-0000-000000000002"}]}'),
+-- A stale DOCUMENT assignment for a task must not create another group.
+('e0000000-0000-0000-0000-000000000103', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'DOCUMENT',
+ '00000001-0000-0000-0000-000000000014',
+ '{"type":"EntityReference","value":[{"entity_type":"INITIATIVE","entity_id":"ad000000-0000-0000-0000-000000000002"}]}');
diff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.md
index 51df83eec5..db07ab8096 100644
--- a/docs/agent-guide/tasks.md
+++ b/docs/agent-guide/tasks.md
@@ -397,6 +397,17 @@ The shared board primitives remain independent of Tasks queries and mutations.
## Cached grouped lists
+Project grouping in the task list matches the Project column: tasks group by
+their initiative Project property, with unassigned tasks under **No Project**.
+Legacy folder membership does not affect these groups. Project headers resolve
+through the same authorized identity query as the Project column. Verify two
+projects and an unassigned task on desktop and mobile; changing or clearing a
+task’s Project must move it to the matching group without reloading.
+
+The synthetic project-grouping browser regression uses the production grouping
+logic and group headers, with HTTP replaced. Run from `apps/web`:
+`bunx playwright test --config src/features/tasks-view/browser-test/playwright.config.ts project-grouping.browser.e2e.ts`.
+
With GraphQL caching enabled, previously loaded grouped task lists remain usable
when their background refresh fails without an HTTP response. Load a Priority-grouped
view online, navigate away, then reopen it offline. Repeat by holding its GroupSoup
diff --git a/docs/design/initiatives-projects.md b/docs/design/initiatives-projects.md
index f246833f1c..008a69edcf 100644
--- a/docs/design/initiatives-projects.md
+++ b/docs/design/initiatives-projects.md
@@ -116,7 +116,7 @@ The user request takes precedence over Linear differences: Macro Projects live u
- New feature: `apps/web/src/features/projects/`; decode `Initiative*` transport DTOs to a feature-owned Project model.
- Preserve existing folder `project`, `projectId`, `/projects` APIs, block routes and tools. New task relationship fields use `initiativeId`/`initiative` internally.
- Register component splits through [componentRegistry](../../apps/web/src/components/app/split-layout/componentRegistry.tsx), using a project-specific component identity such as `initiative-view~<id>~<tab>`. Follow existing ID serialization patterns; component params alone are lost on URL restore. Host adapters translate all project links, command results and notification targets into this identity.
-- Existing task grouping named `project` currently means folder grouping in [task-query](../../apps/web/src/features/tasks-view/queries/task-query.ts). Add a distinct initiative grouping key if grouping is exposed, and label the existing folder operation clearly. Never silently reinterpret persisted folder filters.
+- Task grouping named `project` uses the Project property (initiative membership), matching the Project column. Legacy folder filters retain their existing meaning.
### Properties, permissions and membership
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index f40c664ca2..9f1d9d7168 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -5421,7 +5421,7 @@ enum GraphqlGroupByField {
"""
ENTITY_TYPE
"""
- Group by containing project.
+ Group by the Project property (initiative membership).
"""
PROJECT
"""