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(access-requests): decide denied views from a fresh request state (#9193)
gbirman3d9813a7054b
diff --git a/apps/web/src/features/access-requests/access-requests.test.tsx b/apps/web/src/features/access-requests/access-requests.test.tsxindex da0327e61e..6a4c0aba20 100644--- a/apps/web/src/features/access-requests/access-requests.test.tsx+++ b/apps/web/src/features/access-requests/access-requests.test.tsx@@ -1,5 +1,5 @@import { cleanup, fireEvent, render } from '@solidjs/testing-library';-import type { JSX, ParentProps } from 'solid-js';+import { createSignal, type JSX, type ParentProps } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import { DocumentAccessDenied } from './access-requests';import type { SharingSource } from './context/contracts';@@ -11,6 +11,9 @@ vi.mock('@core/auth', () => ({ useIsAuthenticated: () => () => true }));vi.mock('@core/component/AccessErrorViews/Unauthorized', () => ({default: (props: ParentProps) => <div>{props.children}</div>,}));+vi.mock('@core/component/AccessErrorViews/NotFound', () => ({+ default: () => <div>Not found</div>,+}));vi.mock('@entity/owner/owner-display', () => ({OwnerLabel: (props: { ownerId: string }) => <span>{props.ownerId}</span>,}));@@ -141,3 +144,72 @@ it('preserves a reviewer’s selected grant level through a background request rfireEvent.click(view.getByRole('button', { name: 'Grant access' }));expect(review.resolve).toHaveBeenCalledWith(request, 'comment');});++it('decides the denied document screen from its own request state, not a cached one', () => {+ const [loading, setLoading] = createSignal(true);+ const fake = fakeSharingSource({+ accessLevel: 'view',+ mine: {+ id: 'request',+ requesterId: 'requester',+ requestedLevel: 'edit',+ status: 'pending',+ revision: 1,+ createdAt: '2026-10-15T00:00:00Z',+ updatedAt: '2026-10-15T00:00:00Z',+ },+ });+ source = { ...fake.source, loading };+ const onAccessGranted = vi.fn();+ const view = render(() => (+ <DocumentAccessDenied+ documentId="01a140ad-06d5-7791-8b68-bc128654bbba"+ onAccessGranted={onAccessGranted}+ />+ ));+ expect(view.getByText('Loading access requests…')).toBeTruthy();+ expect(view.queryByText('Access requested')).toBeNull();+ expect(onAccessGranted).not.toHaveBeenCalled();+ fake.setState((current) => ({ ...current, accessLevel: null, mine: null }));+ setLoading(false);+ expect(view.getByRole('button', { name: 'Request access' })).toBeTruthy();+ expect(onAccessGranted).not.toHaveBeenCalled();+ fake.setState((current) => ({ ...current, accessLevel: 'view' }));+ expect(onAccessGranted).toHaveBeenCalledOnce();+});++it('does not report a cached grant once the document turns out to be deleted', () => {+ const [loading, setLoading] = createSignal(true);+ const [notFound, setNotFound] = createSignal(false);+ source = {+ ...fakeSharingSource({ accessLevel: 'view' }).source,+ loading,+ notFound,+ };+ const onAccessGranted = vi.fn();+ const view = render(() => (+ <DocumentAccessDenied+ documentId="01a140ad-06d5-7791-8b68-bc128654bbba"+ onAccessGranted={onAccessGranted}+ />+ ));+ setNotFound(true);+ setLoading(false);+ expect(view.getByText('Not found')).toBeTruthy();+ expect(onAccessGranted).not.toHaveBeenCalled();+});++it('shows a deleted document as not found instead of offering a request', () => {+ const [notFound, setNotFound] = createSignal(false);+ source = { ...fakeSharingSource({ accessLevel: null }).source, notFound };+ const view = render(() => (+ <DocumentAccessDenied+ documentId="01a140ad-06d5-7791-8b68-bc128654bbba"+ onAccessGranted={vi.fn()}+ />+ ));+ expect(view.getByRole('button', { name: 'Request access' })).toBeTruthy();+ setNotFound(true);+ expect(view.getByText('Not found')).toBeTruthy();+ expect(view.queryByRole('button', { name: 'Request access' })).toBeNull();+});diff --git a/apps/web/src/features/access-requests/access-requests.tsx b/apps/web/src/features/access-requests/access-requests.tsxindex 74d38cdef3..1466e54672 100644--- a/apps/web/src/features/access-requests/access-requests.tsx+++ b/apps/web/src/features/access-requests/access-requests.tsx@@ -1,4 +1,5 @@import { useIsAuthenticated } from '@core/auth';+import NotFound from '@core/component/AccessErrorViews/NotFound';import Unauthorized from '@core/component/AccessErrorViews/Unauthorized';import { fireAndForget } from '@core/util/fireAndForget';import { Button } from '@ui';@@ -52,28 +53,37 @@ export function AccessDenied(props: {const authenticated = useIsAuthenticated();createEffect(on(- () => props.source.state()?.accessLevel,+ () =>+ props.source.loading() || props.source.notFound()+ ? undefined+ : props.source.state()?.accessLevel,(level) => {if (level) props.onAccessGranted();}));return (- <Unauthorized noun={props.noun}>- <Show when={authenticated()}>- <div class="mt-6 flex w-full flex-col gap-3 text-sm">- <Show when={props.source.loading()}>- <span class="text-ink-muted">Loading access requests…</span>- </Show>- <RequestAccessView- source={props.source}- allowedLevels={['view', 'comment', 'edit']}- />- <PermissionRequestsView source={props.source} />- <AccessRequestError source={props.source} />- </div>- </Show>- </Unauthorized>+ <Show when={!props.source.notFound()} fallback={<NotFound />}>+ <Unauthorized noun={props.noun}>+ <Show when={authenticated()}>+ <div class="mt-6 flex w-full flex-col gap-3 text-sm">+ <Show+ when={!props.source.loading()}+ fallback={+ <span class="text-ink-muted">Loading access requests…</span>+ }+ >+ <RequestAccessView+ source={props.source}+ allowedLevels={['view', 'comment', 'edit']}+ />+ <PermissionRequestsView source={props.source} />+ <AccessRequestError source={props.source} />+ </Show>+ </div>+ </Show>+ </Unauthorized>+ </Show>);}diff --git a/apps/web/src/features/access-requests/context/contracts.ts b/apps/web/src/features/access-requests/context/contracts.tsindex 495e18a562..1db801af36 100644--- a/apps/web/src/features/access-requests/context/contracts.ts+++ b/apps/web/src/features/access-requests/context/contracts.ts@@ -11,6 +11,8 @@ export type SharingSource = {state: Accessor<RequestState | undefined>;grants: Accessor<DirectAccess[]>;loading: Accessor<boolean>;+ /** The entity is gone, so its last cached state no longer applies. */+ notFound: Accessor<boolean>;busy: Accessor<boolean>;error: Accessor<string | undefined>;refresh(): Promise<void>;diff --git a/apps/web/src/features/access-requests/primitives/direct-access-invite.test.ts b/apps/web/src/features/access-requests/primitives/direct-access-invite.test.tsindex 3a140b9c72..dd4d656bdf 100644--- a/apps/web/src/features/access-requests/primitives/direct-access-invite.test.ts+++ b/apps/web/src/features/access-requests/primitives/direct-access-invite.test.ts@@ -15,6 +15,7 @@ it('grants view access by Macro email and preserves the address when the write f}),grants: () => [],loading: () => false,+ notFound: () => false,busy: () => false,error: () => undefined,refresh: async () => undefined,diff --git a/apps/web/src/features/access-requests/queries/source.test.tsx b/apps/web/src/features/access-requests/queries/source.test.tsxindex b461519dd3..3260c55f9e 100644--- a/apps/web/src/features/access-requests/queries/source.test.tsx+++ b/apps/web/src/features/access-requests/queries/source.test.tsx@@ -1,3 +1,4 @@+import { ThrownResultError } from '@core/util/result';import { cleanup, render } from '@solidjs/testing-library';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { errAsync, okAsync, ResultAsync } from 'neverthrow';@@ -17,10 +18,13 @@ const mocks = vi.hoisted(() => ({let snapshot: {isSuccess: boolean;isPending: boolean;- isLoading: boolean;+ isFetching: boolean;+ isPaused: boolean;+ isFetchedAfterMount: boolean;isError: boolean;+ error: Error | null;data: RequestState;- refetch: () => Promise<void>;+ refetch: () => Promise<{ data: RequestState; error?: Error | null }>;};let offset: Accessor<number>;vi.mock('@queries/access-requests/requests', () => ({@@ -70,10 +74,13 @@ function mount(initial: Partial<RequestState> = {}) {snapshot = {isSuccess: true,isPending: false,- isLoading: false,+ isFetching: false,+ isPaused: false,+ isFetchedAfterMount: true,isError: false,+ error: null,data,- refetch: async () => {},+ refetch: async () => ({ data }),};const client = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -173,3 +180,96 @@ it('does not show the previous document grant rows while the new document is penexpect(source.grants()).toEqual([]);pending.resolve([]);});++it('drops a grants failure from before the viewer lost access', async () => {+ const failed = Promise.withResolvers<void>();+ mocks.grants.mockImplementation(() => {+ failed.resolve();+ return errAsync([{ code: 'FORBIDDEN', message: 'no access' }]);+ });+ const { source, update } = mount({ accessLevel: 'comment' });+ await failed.promise;+ await vi.waitFor(() =>+ expect(source.error()).toBe('Could not load access requests.')+ );+ update('accessLevel', null);+ expect(source.error()).toBeUndefined();+ await source.refresh();+ expect(mocks.grants).toHaveBeenCalledOnce();+ expect(source.error()).toBeUndefined();+});++it('refreshes grants from the refetched state, not the cached one', async () => {+ const { source } = mount({ accessLevel: null });+ expect(mocks.grants).not.toHaveBeenCalled();+ snapshot.refetch = async () => ({+ data: { ...snapshot.data, accessLevel: 'comment' },+ });+ await source.refresh();+ expect(mocks.grants).toHaveBeenCalledOnce();+});++it('hides grant rows once the viewer can no longer read them', async () => {+ const grants = [{ userId: 'macro|[email protected]', accessLevel: 'view' }];+ mocks.grants.mockImplementation(() => okAsync(grants));+ const { source, update } = mount({ accessLevel: 'view' });+ await source.refresh();+ expect(source.grants()).toEqual(grants);+ update('accessLevel', null);+ expect(source.grants()).toEqual([]);+});++it('keeps grant rows while another page of requests loads', async () => {+ const grants = [{ userId: 'macro|[email protected]', accessLevel: 'view' }];+ mocks.grants.mockImplementation(() => okAsync(grants));+ const { source } = mount({ accessLevel: 'view' });+ await source.refresh();+ snapshot.isPending = true;+ expect(source.grants()).toEqual(grants);+});++it('does not refresh grants for an entity the refresh found deleted', async () => {+ const { source } = mount({ accessLevel: 'view' });+ await source.refresh();+ mocks.grants.mockClear();+ snapshot.refetch = async () => ({+ data: snapshot.data,+ error: new ThrownResultError([{ code: 'NOT_FOUND', message: 'gone' }]),+ });+ await source.refresh();+ expect(mocks.grants).not.toHaveBeenCalled();+});++it('keeps loading while a new mount refetches a cached state', () => {+ const { source } = mount({ accessLevel: 'view' });+ Object.assign(snapshot, { isFetching: true, isFetchedAfterMount: false });+ expect(source.loading()).toBe(true);+ Object.assign(snapshot, { isFetching: false, isFetchedAfterMount: true });+ expect(source.loading()).toBe(false);+ Object.assign(snapshot, { isFetching: true });+ expect(source.loading()).toBe(false);+});++it('keeps loading while an offline mount waits to refetch a cached state', () => {+ const { source } = mount({ accessLevel: 'view' });+ Object.assign(snapshot, { isPaused: true, isFetchedAfterMount: false });+ expect(source.loading()).toBe(true);+});++it('tells a deleted entity from a failed state read', () => {+ const { source } = mount({ accessLevel: null });+ expect(source.notFound()).toBe(false);+ Object.assign(snapshot, {+ isSuccess: false,+ isError: true,+ error: new ThrownResultError([+ { code: 'NETWORK_ERROR', message: 'offline' },+ ]),+ });+ expect(source.notFound()).toBe(false);+ Object.assign(snapshot, {+ error: new ThrownResultError([{ code: 'NOT_FOUND', message: 'gone' }]),+ });+ expect(source.notFound()).toBe(true);+ expect(source.state()?.accessLevel).toBeNull();+});diff --git a/apps/web/src/features/access-requests/queries/source.ts b/apps/web/src/features/access-requests/queries/source.tsindex 34c8c17fa6..697adc739b 100644--- a/apps/web/src/features/access-requests/queries/source.ts+++ b/apps/web/src/features/access-requests/queries/source.ts@@ -1,5 +1,5 @@import { fireAndForget } from '@core/util/fireAndForget';-import { throwOnErr } from '@core/util/result';+import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { accessRequestKeys } from '@queries/access-requests/keys';import {accessRequestsClient,@@ -11,7 +11,12 @@ import { useMutation, useQuery } from '@tanstack/solid-query';import { type Accessor, createSignal } from 'solid-js';import { match } from 'ts-pattern';import type { SharingSource } from '../context/contracts';-import type { AccessLevel, AccessRequest, ShareEntity } from '../core/types';+import type {+ AccessLevel,+ AccessRequest,+ RequestState,+ ShareEntity,+} from '../core/types';type Action =| { kind: 'submit'; level: AccessLevel; revision?: number }@@ -21,6 +26,11 @@ type Action =type Change = Action & { target: ShareEntity };+// Direct grants are readable only with access or review authority.+function canReadGrants(state: RequestState | undefined) {+ return !!state && (state.accessLevel != null || state.canReview);+}+function directAccessOptions(target: ShareEntity | undefined,enabled: boolean@@ -45,15 +55,11 @@ export function createSharingSource(): SharingSource {const [offset, setOffset] = createSignal(0);const state = useAccessRequestState(entity, enabled, offset);- const grants = useQuery(() => {- const current = !state.isPending ? state.data : undefined;- return directAccessOptions(- entity(),- enabled() &&- !!current &&- (current.accessLevel != null || current.canReview)- );- });+ const grantsReadable = () =>+ canReadGrants(!state.isPending ? state.data : undefined);+ const grants = useQuery(() =>+ directAccessOptions(entity(), enabled() && grantsReadable())+ );const mutation = useMutation(() => ({mutationFn: async (change: Change) => {const target = change.target;@@ -105,23 +111,28 @@ export function createSharingSource(};return {state: () => (state.isPending ? undefined : state.data),- grants: () => (grants.isPending ? [] : (grants.data ?? [])),- loading: () => state.isLoading,+ grants: () =>+ grants.isPending || (!state.isPending && !canReadGrants(state.data))+ ? []+ : (grants.data ?? []),+ // A cached state can predate an access change, so each mount waits for+ // its own refetch.+ loading: () =>+ (state.isFetching || state.isPaused) && !state.isFetchedAfterMount,+ notFound: () =>+ state.isError && thrownResultErrorHasCode(state.error, 'NOT_FOUND'),busy: () => mutation.isPending,+ // A grants error from before losing access no longer applies.error: () =>mutation.isError? 'Could not update access. Refresh and try again.'- : state.isError || grants.isError+ : state.isError || (grantsReadable() && grants.isError)? 'Could not load access requests.': undefined,async refresh() {mutation.reset();- await state.refetch();- if (- !state.isPending &&- state.data &&- (state.data.accessLevel != null || state.data.canReview)- )+ const { data, error } = await state.refetch();+ if (canReadGrants(data) && !thrownResultErrorHasCode(error, 'NOT_FOUND'))await grants.refetch();},submit: (level, revision) => mutate({ kind: 'submit', level, revision }),diff --git a/apps/web/src/features/access-requests/tests/source.ts b/apps/web/src/features/access-requests/tests/source.tsindex 74315f6799..24cf4792cf 100644--- a/apps/web/src/features/access-requests/tests/source.ts+++ b/apps/web/src/features/access-requests/tests/source.ts@@ -17,6 +17,7 @@ export function fakeSharingSource(initial: Partial<RequestState> = {}) {state,grants: () => [],loading: () => false,+ notFound: () => false,busy: () => false,error: () => undefined,refresh: vi.fn(async () => {}),diff --git a/apps/web/src/features/projects/project-unavailable.test.tsx b/apps/web/src/features/projects/project-unavailable.test.tsxindex 3905b26b0f..ebda4b131a 100644--- a/apps/web/src/features/projects/project-unavailable.test.tsx+++ b/apps/web/src/features/projects/project-unavailable.test.tsx@@ -71,19 +71,26 @@ it('keeps the unavailable notice when the viewer already has access', () => {expect(view.queryByRole('button', { name: 'Request access' })).toBeNull();});-it('shows the project skeleton until the request state decides the view', () => {+it('waits for its own request state instead of a cached one from before losing access', () => {const [loading, setLoading] = createSignal(true);- const [loaded, setLoaded] = createSignal(false);- const fake = fakeSharingSource({ accessLevel: null });- source = {- ...fake.source,- state: () => (loaded() ? fake.source.state() : undefined),- loading,- };+ const fake = fakeSharingSource({ accessLevel: 'view' });+ source = { ...fake.source, loading };const view = renderUnavailable();expect(view.getByText('Loading project')).toBeTruthy();expect(view.queryByRole('alert')).toBeNull();- setLoaded(true);+ fake.setState((current) => ({ ...current, accessLevel: null }));+ expect(view.queryByRole('button', { name: 'Request access' })).toBeNull();setLoading(false);expect(view.getByRole('button', { name: 'Request access' })).toBeTruthy();+ expect(view.queryByText('Loading project')).toBeNull();+});++it('keeps the unavailable notice for a deleted project with a cached denied state', () => {+ const [notFound, setNotFound] = createSignal(false);+ source = { ...fakeSharingSource({ accessLevel: null }).source, notFound };+ const view = renderUnavailable();+ expect(view.getByRole('button', { name: 'Request access' })).toBeTruthy();+ setNotFound(true);+ expect(view.getByRole('alert').textContent).toContain('Project unavailable');+ expect(view.queryByRole('button', { name: 'Request access' })).toBeNull();});diff --git a/apps/web/src/features/projects/project-unavailable.tsx b/apps/web/src/features/projects/project-unavailable.tsxindex 0a4b4a76f2..86e4267b74 100644--- a/apps/web/src/features/projects/project-unavailable.tsx+++ b/apps/web/src/features/projects/project-unavailable.tsx@@ -27,7 +27,8 @@ export function ProjectUnavailable(props: {// Stays denied after a grant, so the request view holds while the project// reloads; a reload that settles without the project falls back to Try again.const deniedId = createMemo<string | undefined>((denied) => {- const state = requests.state();+ if (requests.notFound()) return;+ const state = requests.loading() ? undefined : requests.state();if (state && state.accessLevel == null) return props.projectId;return denied === props.projectId && reloadedId() !== props.projectId? denieddiff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex ebfbda13a8..2968c1d766 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -50,6 +50,7 @@ vi.mock('@app/features/access-requests/access-requests', async (original) => ({state: () => undefined,grants: () => [],loading: () => false,+ notFound: () => false,busy: () => false,error: () => undefined,}),diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex c7ee33f21f..b227e95ebc 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -82,7 +82,10 @@ reloads when it receives the grant update. Signed-out visitors are prompted tosign in first; ordinary load failures retain **Try again**.An already-open document reloads after a permission upgrade on desktop and touchdevices. Removing its last grant closes the editor and returns to Request access;-a failed background refresh must not restore the revoked document.+a failed background refresh must not restore the revoked document. The denied+view shows **Loading access requests…** until its own request-state read lands,+never a request row or **Could not load access requests** left over from before+the change, and a document deleted while it is open shows the not-found view.In **People with access**, a non-owner can use **Request access** beneath theowner to request a supported upgrade (**Comment** or **Edit**). PDFs offerdiff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.mdindex 91a3d2f998..e299dd9472 100644--- a/docs/agent-guide/tasks.md+++ b/docs/agent-guide/tasks.md@@ -806,7 +806,9 @@ Opening a project without access shows `You don't have access to this project`with the same Request access row and access level as documents. The ownerreviews it under Share's `Permission requests`, and once granted the openproject loads in place. Losing access while the project is open switches to-that view. A deleted project shows `Project unavailable` with Try again.+that view through the project skeleton, without a `Project unavailable` or+stale `Access requested` flash. A deleted project shows `Project unavailable`+with Try again, also when it is deleted while its request view is open.Project information panels start closed and float over the content at everywidth, both in the Tasks project view and standalone initiative blocks. Opening