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.

Seanaye/feat/cold start feature flag (#6746)

Sean Aye156ac34e949f
diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.ts
index 59a6a5dd26..55dd7d96b9 100644
--- a/apps/web/src/features/notifications/notification-source.ts
+++ b/apps/web/src/features/notifications/notification-source.ts
@@ -1,8 +1,4 @@
-import {
- ENABLE_DOCUMENT_MENTION_NOTIFICATIONS,
- enableGraphqlSoup,
- isFeatureEnabled,
-} from '@core/constant/featureFlags';
+import { ENABLE_DOCUMENT_MENTION_NOTIFICATIONS } from '@core/constant/featureFlags';
import type { Entity } from '@core/types';
import { muteItemForRef } from '@entity/utils/notification';
import { createSocketEffect } from '@macro-inc/collaboration/websocket';
@@ -238,6 +234,7 @@ export function createNotificationSource(
const notificationsQuery = useUserNotificationsQuery(() => ({
limit: QUERY_LIMIT,
}));
+ const usesGraphql = () => notificationsQuery.transport === 'graphql';
const mutedEntitiesQuery = createMutedEntitiesQuery({ limit: QUERY_LIMIT });
const muteItem = useMuteItemMutation();
const unmuteItem = useUnmuteItemMutation();
@@ -260,7 +257,7 @@ export function createNotificationSource(
// Soup edges. Keep their intent until explicitly cleared, replaced, or rolled
// back rather than letting pagination resurrect stale edge state.
createEffect(() => {
- if (isFeatureEnabled(enableGraphqlSoup)) return;
+ if (usesGraphql()) return;
const raw = notificationsQuery.data;
if (!raw) return;
const presentIds = new Set(raw.map((n) => n.id));
@@ -279,7 +276,7 @@ export function createNotificationSource(
// a fetch that is still running may hold a pre-write snapshot that will
// land later; in both cases the override must survive.
createEffect(() => {
- if (isFeatureEnabled(enableGraphqlSoup)) return;
+ if (usesGraphql()) return;
const raw = notificationsQuery.data;
if (!raw) return;
const seenIds = Object.keys(seenOverrides);
@@ -313,7 +310,7 @@ export function createNotificationSource(
// TODO(dev-rb/notifications): Remove this legacy eager pagination when the
// REST notification source is retired. GraphQL consumers should use Soup
// notification edges or dedicated notification queries instead.
- if (isFeatureEnabled(enableGraphqlSoup)) return;
+ if (usesGraphql()) return;
if (!notificationsQuery.data) return;
if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {
notificationsQuery.fetchNextPage();
@@ -389,7 +386,7 @@ export function createNotificationSource(
const unsubscribeFromGraphql = subscribeToGraphqlNotificationPatches(
(patch) => {
- if (!isFeatureEnabled(enableGraphqlSoup)) return;
+ if (!usesGraphql()) return;
scheduleGraphqlNotificationRefetch();
if (patch.__typename !== 'GraphqlNewNotification') return;
dispatchIncomingNotification(mapGraphqlNotification(patch.notification));
@@ -411,10 +408,7 @@ export function createNotificationSource(
};
createSocketEffect(ws, (wsData) => {
- if (
- wsData.type !== NOTIFICATION_EVENT_TYPE ||
- isFeatureEnabled(enableGraphqlSoup)
- ) {
+ if (wsData.type !== NOTIFICATION_EVENT_TYPE || usesGraphql()) {
return;
}
let parsedNotification: UnifiedNotification;
@@ -521,9 +515,7 @@ export function createNotificationSource(
unmuteEntity,
subscribe,
get withLocalOverrides() {
- return isFeatureEnabled(enableGraphqlSoup)
- ? withNotificationOverrides
- : undefined;
+ return usesGraphql() ? withNotificationOverrides : undefined;
},
};
}
diff --git a/apps/web/src/features/notifications/tests/notification-source.test.ts b/apps/web/src/features/notifications/tests/notification-source.test.ts
index 05fccae4c8..40db991c9a 100644
--- a/apps/web/src/features/notifications/tests/notification-source.test.ts
+++ b/apps/web/src/features/notifications/tests/notification-source.test.ts
@@ -526,6 +526,81 @@ describe('createNotificationSource', () => {
}
});
+ it('follows the query transport for pagination, realtime delivery and edge overrides', async () => {
+ // An imperative flag snapshot can disagree with the mounted query during
+ // startup. Only the facade's reactive transport owns source behavior.
+ mocks.graphqlEnabled = true;
+ const [transport, setTransport] = createSignal<'rest' | 'graphql'>('rest');
+ const fetchNextPage = vi.fn(async () => undefined);
+ const refetch = vi.fn(async () => undefined);
+ mocks.notificationsQuery = {
+ data: [],
+ get transport() {
+ return transport();
+ },
+ hasNextPage: true,
+ isFetching: false,
+ fetchNextPage,
+ refetch,
+ };
+ const incoming: UnifiedNotification = {
+ ...notification(
+ '00000000-0000-4000-8000-000000000011',
+ 'reminder',
+ 'reminder-transport'
+ ),
+ notification_event_type: 'reminder',
+ notification_metadata: {
+ tag: 'reminder',
+ content: {
+ description: 'Transport transition',
+ reminderId: '00000000-0000-4000-8000-000000000012',
+ },
+ },
+ };
+ const restEvent = {
+ type: 'notification',
+ data: JSON.stringify({ ...incoming, notification_id: incoming.id }),
+ };
+ const graphqlEvent = {
+ __typename: 'GraphqlNewNotification',
+ notification: incoming,
+ };
+ const receive = vi.fn();
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource(
+ {} as ConnectionGatewayWebsocket,
+ receive
+ ),
+ dispose,
+ }));
+ try {
+ expect(fetchNextPage).toHaveBeenCalledOnce();
+ expect(source.withLocalOverrides).toBeUndefined();
+ mocks.graphqlPatchCallback?.(graphqlEvent);
+ expect(receive).not.toHaveBeenCalled();
+ mocks.socketCallback?.(restEvent);
+ expect(receive).toHaveBeenCalledOnce();
+ expect(mocks.optimisticInsertNotification).toHaveBeenCalledOnce();
+
+ setTransport('graphql');
+ expect(source.withLocalOverrides).toBeTypeOf('function');
+ expect(fetchNextPage).toHaveBeenCalledOnce();
+ mocks.socketCallback?.(restEvent);
+ expect(receive).toHaveBeenCalledOnce();
+ mocks.graphqlPatchCallback?.(graphqlEvent);
+ expect(receive).toHaveBeenCalledTimes(2);
+ await Promise.resolve();
+ expect(refetch).toHaveBeenCalledOnce();
+
+ setTransport('rest');
+ expect(source.withLocalOverrides).toBeUndefined();
+ expect(fetchNextPage).toHaveBeenCalledTimes(2);
+ } finally {
+ dispose();
+ }
+ });
+
it('coalesces uncached GraphQL patches and ignores connection gateway notifications when enabled', async () => {
const incoming = notification('new-notification', 'channel', 'channel-1');
const refetch = vi.fn().mockResolvedValue(undefined);
diff --git a/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx b/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
index 545c1b286f..9f83b0a349 100644
--- a/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
+++ b/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
@@ -2,14 +2,21 @@
* @vitest-environment jsdom
*/
+import { createUrqlInfiniteQuery } from '@app/lib/urql-solid';
import type { UnifiedNotification } from '@notifications/types';
import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';
import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createClient, type Operation } from '@urql/core';
import { ok } from 'neverthrow';
-import type { JSX } from 'solid-js';
+import { type Accessor, createMemo, createSignal, type JSX } from 'solid-js';
import { render } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { filter, map, pipe } from 'wonka';
+import type {
+ GraphqlNotificationsQueryArgs,
+ GraphqlNotificationsQueryOptions,
+} from '../graphql/user-notifications';
import { notificationKeys } from '../keys';
import {
applyNotificationStatusUpdate,
@@ -32,6 +39,7 @@ const {
restMarkSeenMock,
restUserNotificationsMock,
restMarkUndoneMock,
+ useFeatureFlagMock,
} = vi.hoisted(() => ({
createGraphqlMutationMock: vi.fn(),
createGraphqlQueryMock: vi.fn(),
@@ -43,6 +51,11 @@ const {
restMarkSeenMock: vi.fn(),
restUserNotificationsMock: vi.fn(),
restMarkUndoneMock: vi.fn(),
+ useFeatureFlagMock: vi.fn(),
+}));
+
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: useFeatureFlagMock,
}));
vi.mock('@core/constant/featureFlags', () => ({
@@ -128,6 +141,9 @@ type GraphqlMutationOptions = {
beforeEach(() => {
graphqlCacheEnabledMock.mockReturnValue(true);
graphqlSoupEnabledMock.mockReturnValue(true);
+ useFeatureFlagMock.mockReturnValue(() => ({
+ enabled: graphqlSoupEnabledMock(),
+ }));
restUserNotificationsMock.mockResolvedValue(
ok({ items: [], next_cursor: null })
);
@@ -370,6 +386,111 @@ describe('useUserNotificationsQuery transport facade', () => {
dispose();
});
+ it.each([false, true])(
+ 'reacts to GraphQL flags arriving during a cold REST fetch (done=%s)',
+ async (done) => {
+ const [enabled, setEnabled] = createSignal(false);
+ useFeatureFlagMock.mockReturnValue(() => ({ enabled: enabled() }));
+ graphqlSoupEnabledMock.mockReturnValue(false);
+ const restNotification = createMockNotification({ id: 'rest-document' });
+ const graphqlNotification = createMockNotification({
+ id: 'graphql-document',
+ });
+ let resolveRest!: (page: GetAllUserNotificationsResponse) => void;
+ restUserNotificationsMock.mockImplementationOnce(async () => {
+ const page = await new Promise<GetAllUserNotificationsResponse>(
+ (resolve) => {
+ resolveRest = resolve;
+ }
+ );
+ return ok(page);
+ });
+
+ const operations: Operation[] = [];
+ const client = createClient({
+ url: 'http://localhost/graphql',
+ exchanges: [
+ () => (operations$) =>
+ pipe(
+ operations$,
+ filter((operation) => operation.kind === 'query'),
+ map((operation) => {
+ operations.push(operation);
+ return {
+ operation,
+ data: { items: [graphqlNotification], nextCursor: null },
+ stale: false,
+ hasNext: false,
+ };
+ })
+ ),
+ ],
+ });
+ createGraphqlQueryMock.mockImplementationOnce(
+ (
+ _args: Accessor<GraphqlNotificationsQueryArgs>,
+ options: Accessor<GraphqlNotificationsQueryOptions>
+ ) =>
+ createUrqlInfiniteQuery<
+ { items: UnifiedNotification[]; nextCursor: string | null },
+ { cursor: string | null },
+ string | null,
+ UnifiedNotification[]
+ >(() => ({
+ client,
+ query: 'query Notifications { items { id } nextCursor }',
+ variables: (cursor) => ({ cursor }),
+ enabled: options().enabled,
+ initialPageParam: null,
+ getNextPageParam: (page) => page.nextCursor,
+ select: ({ pages }) => pages.flatMap((page) => page.items),
+ }))
+ );
+ let query!: UserNotificationsQuery;
+ let notifications!: Accessor<UnifiedNotification[]>;
+ const dispose = renderWithClient(() => {
+ query = useUserNotificationsQuery(() => ({ limit: 500, done }));
+ notifications = createMemo(() => query.data ?? []);
+ return <div />;
+ });
+ try {
+ await vi.waitFor(() => expect(resolveRest).toBeDefined());
+ expect(query.transport).toBe('rest');
+ expect(operations).toHaveLength(0);
+
+ graphqlSoupEnabledMock.mockReturnValue(true);
+ setEnabled(true);
+ resolveRest(createMockNotificationPage([restNotification]));
+ await vi.waitFor(() =>
+ expect(notifications()).toEqual([
+ done ? restNotification : graphqlNotification,
+ ])
+ );
+ expect(query.transport).toBe(done ? 'rest' : 'graphql');
+ expect(operations).toHaveLength(done ? 0 : 1);
+
+ if (done) return;
+ await query.refetch();
+ expect(operations).toHaveLength(2);
+ expect(operations[1].context.requestPolicy).toBe('network-only');
+
+ // A later rollback must also re-enable REST, not just change getters.
+ restUserNotificationsMock.mockClear();
+ graphqlSoupEnabledMock.mockReturnValue(false);
+ setEnabled(false);
+ expect(query.transport).toBe('rest');
+ await vi.waitFor(() =>
+ expect(notifications()).toEqual([restNotification])
+ );
+ await query.refetch();
+ expect(restUserNotificationsMock).toHaveBeenCalledOnce();
+ expect(operations).toHaveLength(2);
+ } finally {
+ dispose();
+ }
+ }
+ );
+
it('keeps done-history pagination on REST', () => {
let query: UserNotificationsQuery | undefined;
diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.ts
index 46288efcb5..6f66fa93c2 100644
--- a/apps/web/src/lib/queries/notification/user-notifications.ts
+++ b/apps/web/src/lib/queries/notification/user-notifications.ts
@@ -1,3 +1,4 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import {
enableGraphqlSoup,
isFeatureEnabled,
@@ -230,10 +231,12 @@ export function useUserNotificationsQuery(
args: Accessor<UserNotificationsQueryArgs>,
options?: Accessor<UserNotificationsQueryOptions>
): UserNotificationsQuery {
+ const graphqlSoupFlag = useFeatureFlag(enableGraphqlSoup);
const queryEnabled = () => options?.().enabled !== false;
- const usesGraphql = () =>
- isFeatureEnabled(enableGraphqlSoup) && args().done !== true;
+ // Cold-start flags can arrive after the observers mount. Enabling and
+ // reading a transport must react to the same flag, not an imperative snapshot.
+ const usesGraphql = () => graphqlSoupFlag().enabled && args().done !== true;
const graphqlQuery = createGraphqlNotificationsQuery(args, () => ({
enabled: queryEnabled() && usesGraphql(),
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 73bbdbd27a..50f9e54544 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -73,6 +73,13 @@ Touch devices render the legacy Notifications view without waiting for the new a
views feature flag. Desktop waits for flag readiness before choosing the new Home
view or its legacy fallback.
+On a cold launch, notification transport follows the GraphQL Soup flag reactively:
+if the flag arrives after REST starts, the GraphQL notification query must actually
+start too. Verify a reload with delayed flags retains non-email notifications once
+loading settles, including when the list itself uses REST (notified-at sorting).
+Email alone is not sufficient verification: its inbox membership does not require
+the global notification feed.
+
GraphQL-attached notification rows share the global feed's local seen/done
overrides: Mark Done and Undo reflect local intent without waiting for an older
cached notification snapshot to be replaced. These display overrides do not turn