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
fix(projects): preserve authorization across cached identity reads (#9461)
dev-rb2b777aa3ae07
diff --git a/.agents/rules/web/solid.md b/.agents/rules/web/solid.mdindex d3799819fa..322431dde9 100644--- a/.agents/rules/web/solid.md+++ b/.agents/rules/web/solid.md@@ -64,6 +64,7 @@ State ownership, reactivity, and async error handling.expensive. Cheap derivations (() => a() + b()) don't need it regardless ofsubscriber count.- Before rolling your own reactive utility, check solid-primitives first.+- Use keyed reactive collections for mutable maps instead of cloning the whole map into a signal on each write.- Never read a solid-query `query.data` unguarded from a component body or aneager `createMemo`. `data` is a resource read: while the query is pending itsuspends the caller's nearest `<Suspense>`, which detaches and re-attachesdiff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex db503ee0f0..2d995d7e48 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -318,7 +318,9 @@ feature code to cover a remount.Project identity chips use cache-first reads and the shared `GraphqlUser.initiative`entity resolver to reuse complete authorized records from project lists or details.Keep cold row metadata reads non-suspending so virtual scrolling never detaches-its list; permission revalidation remains independent of row mounts.+its list; permission revalidation remains independent of row mounts. Project+reads retain client-scoped denial state across remounts and immediately reauthorize+previous-viewer cache hits; older requests never clear newer denial decisions.Resolve server date-group keys through the shared `DATE_GROUP_BUCKETS` metadatain `lib/queries/soup/grouped/api.ts` for labels and display order; cached Maildiff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex b68e1ce6ba..9739a51530 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -800,11 +800,14 @@ property in its ordinary create request. Project descriptions use the project'scollaborative surface, provisioned by an authoritative ensure mutation.Permissions and server-owned membership still revalidate on activity, focus, and-the existing project polling interval. A denied mounted read stays hidden across-cache hits until an authorized network response succeeds. Disabled detail reads-and results for another viewer are not exposed. Mentions also refresh on session-rename, deletion, metadata updates, and reconnect when the normalized cache is-unavailable.+the existing project polling interval. Project denials are scoped to the client,+viewer, project, and operation, surviving row remounts until a fresh authorized+network response succeeds. Recovery requests capture the current denial version;+older responses and cache updates cannot clear a newer denial. A rejected+previous-viewer cache hit triggers one immediate network recovery per activation.+Disabled reads and results for another viewer are not exposed. Other query+consumers retain mount-local denial state. Mentions also refresh on session rename,+deletion, metadata updates, and reconnect when the normalized cache is unavailable.Invalidations arriving during a refresh cause a trailing authorized read insteadof being discarded; simultaneous refresh requests share one read.diff --git a/apps/web/src/features/projects/projects.test.tsx b/apps/web/src/features/projects/projects.test.tsxindex 7fcd189d4b..e59684a381 100644--- a/apps/web/src/features/projects/projects.test.tsx+++ b/apps/web/src/features/projects/projects.test.tsx@@ -454,6 +454,10 @@ it('keeps permission denials latched across cache hits and hides disabled detailexpect(query.data).toBeUndefined();expect(query.error).toBe(denial);requests[0].next(data);+ expect(query.data).toBeUndefined();+ const recovery = query.refetch({ requestPolicy: 'network-only' });+ requests[1].next(data);+ await recovery;expect(query.data?.project.name).toBe('Launch');setViewer(undefined);expect(query.data).toBeUndefined();@@ -463,3 +467,89 @@ it('keeps permission denials latched across cache hits and hides disabled detailexpect(query.data).toBeUndefined();expect(query.isSuccess).toBe(false);});++it('reauthorizes a denied identity after remount without exposing cached data', async () => {+ setupGraphql();+ const data = (+ await mocks.soup({+ query: (+ await import('@service-storage/graphql/generated/graphql')+ ).InitiativeIdentityDocument,+ })+ ).data;+ const { client, requests } = controlledClient();+ const mount = () =>+ createRoot((dispose) => {+ onTestFinished(dispose);+ return {+ dispose,+ query: createProjectIdentityQuery(+ () => client,+ () => 'viewer',+ () => 'launch'+ ),+ };+ });+ const first = mount();+ requests[0].next(data);+ expect(first.query.data?.name).toBe('Launch');+ const denial = new CombinedError({+ graphQLErrors: [{ message: 'Denied', extensions: { code: 'FORBIDDEN' } }],+ });+ requests[0].next(undefined, denial);+ expect(first.query.data).toBeUndefined();+ first.dispose();++ const second = mount();+ expect(requests[1].operation.context.requestPolicy).toBe('network-only');+ requests[1].next(data, undefined, true);+ expect(second.query.data).toBeUndefined();+ expect(second.query.error).toBe(denial);+ requests[1].next(data);+ expect(second.query.data?.name).toBe('Launch');+});++it('immediately reauthorizes another viewer cache hit once per activation', async () => {+ setupGraphql();+ const data = (+ await mocks.soup({+ query: (+ await import('@service-storage/graphql/generated/graphql')+ ).InitiativeIdentityDocument,+ })+ ).data;+ const { client, requests } = controlledClient();+ const [viewer, setViewer] = createSignal('next-viewer');+ const [gate, setGate] = createSignal({ enabled: true });+ const query = createRoot((dispose) => {+ onTestFinished(dispose);+ return createProjectIdentityQuery(+ () => client,+ viewer,+ () => 'launch',+ () => gate().enabled+ );+ });+ requests[0].next(data, undefined, true);+ expect(query.data).toBeUndefined();+ await vi.waitFor(() => expect(requests).toHaveLength(2));+ expect(requests[1].operation.context.requestPolicy).toBe('network-only');+ requests[1].next(data, undefined, true);+ expect(query.data).toBeUndefined();+ expect(requests).toHaveLength(2);+ setGate({ enabled: true });+ expect(requests).toHaveLength(2);+ requests[1].next({ user: { ...data.user, id: 'next-viewer' } });+ expect(query.data?.name).toBe('Launch');++ setViewer('last-viewer');+ expect(query.data).toBeUndefined();+ const recovery = requests.at(-1)!;+ expect(recovery.operation.context.requestPolicy).toBe('network-only');+ recovery.next(+ undefined,+ new CombinedError({ networkError: new Error('Offline') })+ );+ expect(query.data).toBeUndefined();+ expect(requests.at(-1)).toBe(recovery);+});diff --git a/apps/web/src/features/projects/queries/project-identity.ts b/apps/web/src/features/projects/queries/project-identity.tsindex 6aceb9e995..a83124d212 100644--- a/apps/web/src/features/projects/queries/project-identity.ts+++ b/apps/web/src/features/projects/queries/project-identity.ts@@ -1,3 +1,4 @@+import { fireAndForget } from '@core/util/fireAndForget';import type { OptimisticResponse } from '@graphql-cache/exchange/optimistic';import type { CacheHost } from '@graphql-cache/host/types';import { createLiveQuery } from '@graphql-cache/solid/create-live-query';@@ -16,11 +17,13 @@ import {} from '@service-storage/initiative';import {type Client,+ createRequest,type DocumentInput,+ getOperationName,type RequestPolicy,stringifyDocument,} from '@urql/core';-import { type Accessor, createMemo } from 'solid-js';+import { type Accessor, createEffect, createMemo, untrack } from 'solid-js';import type { ProjectIdentity } from '../core/project';import { toProjectDetail } from './project-model';import { projectProperties } from './project-properties';@@ -86,29 +89,80 @@ function createAuthorizedProjectQuery<enabled: Accessor<boolean>,requestPolicy: RequestPolicy = 'cache-and-network') {- const active = () => enabled() && Boolean(userId() && projectId());- const authorization = createQueryAuthorization(() =>- JSON.stringify([userId(), projectId()])+ const operationName = getOperationName(+ createRequest(document, { initiativeId: '' }).query);+ const currentClient = createMemo(client);+ const currentViewer = createMemo(userId);+ const currentProject = createMemo(projectId);+ const readEnabled = createMemo(enabled);+ const scope = createMemo(() => ({+ client: currentClient(),+ viewerId: currentViewer(),+ projectId: currentProject(),+ active: readEnabled() && Boolean(currentViewer() && currentProject()),+ }));+ const active = () => scope().active;+ const authorization = createMemo(() => {+ const current = scope();+ const key = JSON.stringify([+ operationName,+ current.viewerId,+ current.projectId,+ ]);+ return createQueryAuthorization(() => key, current.client);+ });const query = createLiveQuery(document,- () => (active() ? { initiativeId: projectId() } : undefined),- () => ({- client: client(),- requestPolicy,- keepPreviousData: false,- onResult: authorization.onResult,- select: (data) => ({ viewerId: data.user.id, value: select(data) }),- })+ () => (active() ? { initiativeId: scope().projectId } : undefined),+ () => {+ const current = scope();+ const auth = authorization();+ return {+ client: current.client,+ requestPolicy: untrack(() =>+ auth.error() ? 'network-only' : requestPolicy+ ),+ context: auth.requestContext(),+ keepPreviousData: false,+ onResult: (result) => {+ if (result.data && result.data.user.id !== current.viewerId) return;+ auth.onResult(result);+ },+ select: (data) => ({ viewerId: data.user.id, value: select(data) }),+ };+ });+ const refetch: typeof query.refetch = (options = {}) =>+ query.refetch({+ ...options,+ context: { ...options.context, ...authorization().requestContext() },+ });registerProjectRevalidation(client, active, () =>- query.refetch({ requestPolicy: 'cache-and-network' })+ refetch({ requestPolicy: 'cache-and-network' }));+ let recoveredScope: ReturnType<typeof scope> | undefined;+ createEffect(() => {+ const current = scope();+ const result = query.data;+ if (+ !current.active ||+ !result ||+ result.viewerId === current.viewerId ||+ recoveredScope === current+ )+ return;+ recoveredScope = current;+ fireAndForget(+ refetch({ requestPolicy: 'network-only' }),+ 'project-identity.viewer-recovery'+ );+ });const data = createMemo(() => {const result = query.data;if (!active() ||- authorization.error() ||+ authorization().error() ||!result ||result.viewerId !== userId())@@ -120,23 +174,27 @@ function createAuthorizedProjectQuery<return data();},get error() {- return active() ? (authorization.error() ?? query.error) : null;+ return active() ? (authorization().error() ?? query.error) : null;},get isSuccess() {return (active() &&- !authorization.error() &&+ !authorization().error() &&query.isSuccess &&query.data?.viewerId === userId());},get isPending() {- return !active() || query.isPending;+ return (+ !active() ||+ query.isPending ||+ (query.isFetching && query.data?.viewerId !== scope().viewerId)+ );},get isError() {- return active() && Boolean(authorization.error() || query.isError);+ return active() && Boolean(authorization().error() || query.isError);},- refetch: query.refetch,+ refetch,};}diff --git a/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.test.tsindex 5a7d866dac..feb918fa06 100644--- a/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.test.ts+++ b/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.test.ts@@ -7,6 +7,7 @@ import {} from '@urql/core';import { afterEach, describe, expect, it, vi } from 'vitest';import { empty, makeSubject, mergeMap, pipe, type Subject } from 'wonka';+import { createQueryAuthorization } from '../../queries/authorization';import { networkRevalidationExchange } from './network-revalidation-exchange';const LIST = gql`query List { items { id tags } }`;@@ -88,6 +89,30 @@ describe('networkRevalidationExchange', () => {detail.unsubscribe();});+ it('captures fresh authorization for mutation-triggered revalidation', async () => {+ const { client, requests, respond, flush } = setup();+ const authorization = createQueryAuthorization(+ () => 'viewer:project',+ client+ );+ const list = client+ .query(LIST, {}, authorization.requestContext())+ .subscribe(authorization.onResult);+ respond(0);+ const denied = new CombinedError({ graphQLErrors: ['Forbidden'] });+ respond(0, { data: undefined, error: denied });+ expect(authorization.error()).toBe(denied);++ const saved = client.mutation(SAVE, {}).toPromise();+ respond(1);+ await flush();+ expect(requests).toHaveLength(3);+ respond(2);+ await saved;+ expect(authorization.error()).toBeUndefined();+ list.unsubscribe();+ });+it('does not refetch on the healthy normalized-cache path', async () => {const { client, requests, respond } = setup(() => false);const list = client.query(LIST, {}).subscribe(() => {});diff --git a/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.tsindex 16feaf8c6e..40d72f61f5 100644--- a/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.ts+++ b/apps/web/src/lib/graphql-cache/exchange/network-revalidation-exchange.ts@@ -38,10 +38,19 @@ export function networkRevalidationExchange(finish(operation.key);}if (operation.kind !== 'query') return operation;+ const authorization = operation.context.queryAuthorization;const id = ++requestId;const tagged = makeOperation('query', operation, {...operation.context,[REQUEST_CONTEXT_KEY]: id,+ ...(authorization+ ? {+ queryAuthorization: {+ ...authorization,+ version: authorization.currentVersion(),+ },+ }+ : {}),});queries.set(operation.key, { operation: tagged, requestId: id });return tagged;diff --git a/apps/web/src/lib/queries/authorization.test.ts b/apps/web/src/lib/queries/authorization.test.tsnew file mode 100644index 0000000000..f8fd31023a--- /dev/null+++ b/apps/web/src/lib/queries/authorization.test.ts@@ -0,0 +1,214 @@+import { CombinedError, createClient, createRequest, gql } from '@urql/core';+import { createComputed, createRoot } from 'solid-js';+import { describe, expect, it, onTestFinished } from 'vitest';+import { createQueryAuthorization } from './authorization';++const document = gql`query Viewer { viewer { id } }`;++describe('createQueryAuthorization', () => {+ it('shares denial across consumers and rejects success started before the denial', () => {+ const client = createClient({ url: 'http://test/graphql', exchanges: [] });+ const first = createQueryAuthorization(() => 'viewer:project', client);+ const second = createQueryAuthorization(() => 'viewer:project', client);+ const oldOperation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ const deniedOperation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ second.requestContext()+ );+ const denial = new CombinedError({ graphQLErrors: ['Forbidden'] });++ second.onResult({+ stale: false,+ hasNext: false,+ operation: deniedOperation,+ error: denial,+ extensions: { __macroNormalizedCache: { source: 'live-network' } },+ });+ expect(first.error()).toBe(denial);+ expect(second.error()).toBe(denial);++ first.onResult({+ stale: false,+ hasNext: false,+ operation: oldOperation,+ data: { viewer: { id: 'old' } },+ });+ expect(first.error()).toBe(denial);+ expect(second.error()).toBe(denial);++ const recoveryOperation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ first.onResult({+ stale: false,+ hasNext: false,+ operation: recoveryOperation,+ data: { viewer: { id: 'current' } },+ extensions: { __macroNormalizedCache: { source: 'live-network' } },+ });+ expect(first.error()).toBeUndefined();+ expect(second.error()).toBeUndefined();++ second.onResult({+ stale: false,+ hasNext: false,+ operation: deniedOperation,+ error: denial,+ });+ expect(first.error()).toBeUndefined();+ });++ it('notifies only observers of the changed authorization scope', () => {+ const client = createClient({ url: 'http://test/graphql', exchanges: [] });+ const first = createQueryAuthorization(() => 'viewer:first', client);+ const second = createQueryAuthorization(() => 'viewer:second', client);+ const firstErrors: (CombinedError | undefined)[] = [];+ const secondErrors: (CombinedError | undefined)[] = [];+ createRoot((dispose) => {+ onTestFinished(dispose);+ createComputed(() => firstErrors.push(first.error()));+ createComputed(() => secondErrors.push(second.error()));+ });+ const operation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ const denial = new CombinedError({ graphQLErrors: ['Forbidden'] });++ first.onResult({ stale: false, hasNext: false, operation, error: denial });+ expect(firstErrors).toEqual([undefined, denial]);+ expect(secondErrors).toEqual([undefined]);++ const recovery = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ first.onResult({+ stale: false,+ hasNext: false,+ operation: recovery,+ data: { viewer: { id: 'current' } },+ });+ expect(firstErrors).toEqual([undefined, denial, undefined]);+ expect(secondErrors).toEqual([undefined]);+ });++ it.each([+ 'normalized-cache-hit',+ 'affected-cache-reread',+ 'normalized-cache-patch',+ ])('ignores %s results for denial and recovery', (source) => {+ const client = createClient({ url: 'http://test/graphql', exchanges: [] });+ const first = createQueryAuthorization(() => 'viewer:project', client);+ const second = createQueryAuthorization(() => 'viewer:project', client);+ const operation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ const denial = new CombinedError({ graphQLErrors: ['Forbidden'] });++ first.onResult({+ stale: false,+ hasNext: false,+ operation,+ error: denial,+ extensions: { __macroNormalizedCache: { source } },+ });+ expect(second.error()).toBeUndefined();++ second.onResult({ stale: false, hasNext: false, operation, error: denial });+ expect(first.error()).toBe(denial);+ const cacheOperation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ first.onResult({+ stale: false,+ hasNext: false,+ operation: cacheOperation,+ data: { viewer: { id: 'cached' } },+ extensions: { __macroNormalizedCache: { source } },+ });+ expect(first.error()).toBe(denial);+ expect(second.error()).toBe(denial);+ });++ it('isolates different scopes and clients', () => {+ const client = createClient({ url: 'http://test/graphql', exchanges: [] });+ const otherClient = createClient({+ url: 'http://test/graphql',+ exchanges: [],+ });+ const first = createQueryAuthorization(() => 'viewer:first', client);+ const otherScope = createQueryAuthorization(() => 'viewer:second', client);+ const otherSession = createQueryAuthorization(+ () => 'viewer:first',+ otherClient+ );+ const operation = client.createRequestOperation(+ 'query',+ createRequest(document, {}),+ first.requestContext()+ );+ const denial = new CombinedError({ graphQLErrors: ['Forbidden'] });++ first.onResult({ stale: false, hasNext: false, operation, error: denial });+ expect(first.error()).toBe(denial);+ expect(otherScope.error()).toBeUndefined();+ expect(otherSession.error()).toBeUndefined();++ otherScope.onResult({+ stale: false,+ hasNext: false,+ operation,+ error: denial,+ });+ expect(otherScope.error()).toBeUndefined();+ const otherOperation = otherClient.createRequestOperation(+ 'query',+ createRequest(document, {}),+ otherSession.requestContext()+ );+ otherSession.onResult({+ stale: false,+ hasNext: false,+ operation: otherOperation,+ data: { viewer: { id: 'current' } },+ });+ expect(first.error()).toBe(denial);+ });++ it('preserves independent mount-local authorization without a request context', () => {+ const first = createQueryAuthorization(() => 'batch');+ const second = createQueryAuthorization(() => 'batch');+ const client = createClient({ url: 'http://test/graphql', exchanges: [] });+ const operation = client.createRequestOperation(+ 'query',+ createRequest(document, {})+ );+ const denial = new CombinedError({ graphQLErrors: ['Forbidden'] });++ first.onResult({ stale: false, hasNext: false, operation, error: denial });+ expect(first.error()).toBe(denial);+ expect(second.error()).toBeUndefined();++ first.onResult({+ stale: false,+ hasNext: false,+ operation,+ data: { viewer: { id: 'current' } },+ });+ expect(first.error()).toBeUndefined();+ });+});diff --git a/apps/web/src/lib/queries/authorization.ts b/apps/web/src/lib/queries/authorization.tsindex 29e3ed6596..395fbd6ccb 100644--- a/apps/web/src/lib/queries/authorization.ts+++ b/apps/web/src/lib/queries/authorization.ts@@ -1,23 +1,70 @@import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';-import type { CombinedError, OperationResult } from '@urql/core';-import { createSignal } from 'solid-js';+import { ReactiveMap } from '@solid-primitives/map';+import type { Client, CombinedError, OperationResult } from '@urql/core';+import { untrack } from 'solid-js';++declare module '@urql/core' {+ interface OperationContext {+ queryAuthorization?: {+ scope: string;+ version: number;+ currentVersion: () => number;+ };+ }+}++type AuthorizationState = { version: number; error?: CombinedError };+const CLIENT_AUTHORIZATION = new WeakMap<+ Client,+ ReactiveMap<string, AuthorizationState>+>();+const AUTHORIZATION_CONTEXT_KEY = 'queryAuthorization';/** A cache hit cannot restore access after the server has denied this read. */-export function createQueryAuthorization(key: () => string) {- const [denials, setDenials] = createSignal(new Map<string, CombinedError>());+export function createQueryAuthorization(key: () => string, client?: Client) {+ let store = client ? CLIENT_AUTHORIZATION.get(client) : undefined;+ if (!store) {+ store = new ReactiveMap<string, AuthorizationState>();+ if (client) CLIENT_AUTHORIZATION.set(client, store);+ }+ const state = store;+return {- error: () => denials().get(key()),+ error: () => state.get(key())?.error,+ /** Capture each request's scope and denial version before dispatch. */+ requestContext() {+ const scope = key();+ const currentVersion = () =>+ untrack(() => state.get(scope)?.version ?? 0);+ return {+ [AUTHORIZATION_CONTEXT_KEY]: {+ scope,+ version: currentVersion(),+ currentVersion,+ },+ };+ },onResult(result: OperationResult) {const source = normalizedCacheResultMetadata(result)?.source;if (source && source !== 'live-network') return;+ const scope = key();+ const previous = state.get(scope);+ if (client) {+ const request = result.operation.context[AUTHORIZATION_CONTEXT_KEY];+ if (+ !request ||+ request.scope !== scope ||+ request.version !== (previous?.version ?? 0)+ )+ return;+ }if (result.error?.graphQLErrors.length) {- setDenials((previous) => new Map(previous).set(key(), result.error!));- } else if (!result.error && result.data && denials().has(key())) {- setDenials((previous) => {- const next = new Map(previous);- next.delete(key());- return next;+ state.set(scope, {+ version: (previous?.version ?? 0) + 1,+ error: result.error,});+ } else if (!result.error && result.data && previous?.error) {+ state.set(scope, { version: previous.version + 1 });}},};diff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.mdindex 46cab63423..ae26f2295e 100644--- a/docs/agent-guide/tasks.md+++ b/docs/agent-guide/tasks.md@@ -615,6 +615,10 @@ row remounts must reuse complete cached identities without newpermission refreshes remain separate. Hold a cold folder-preview or identityrequest while scrolling on desktop and phone: only the row metadata may showloading, and the list must remain mounted at the same scroll position.+After a project read is denied, scroll its row out of view and back: the cached+label must remain hidden until a new authorized response succeeds. Switch viewers+while retaining cached rows: mismatched identities must reauthorize immediately,+without exposing the previous viewer's data or repeatedly retrying a failed read.## Reviews view