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(channels): stabilize access after membership changes (#9238)

gbirman0b8618d1d22b
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index e7bf2f1ffb..511bbbf1f9 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -499,6 +499,7 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
feature-specific query orchestration with its owning feature.
- Refresh the channel list's bounded unread edge when opening a conversation,
including an empty unread result after a read on another device.
+- Decide channel detail access from completed server results; bound confirmations of contradictory cache membership, preserve known unavailable state during retries, and keep unavailable routes registered for notification/reconnect refresh.
- Read folders for picking or moving through `createFolderList`
(`queries/storage/folder-list`): it matches the Drive sidebar's source, so a
folder open in Drive, including a team folder, is always in the list. Keep
diff --git a/apps/web/src/features/channel/Channel/channel-entity.test.ts b/apps/web/src/features/channel/Channel/channel-entity.test.ts
index 9d0c7707ad..0332ba9258 100644
--- a/apps/web/src/features/channel/Channel/channel-entity.test.ts
+++ b/apps/web/src/features/channel/Channel/channel-entity.test.ts
@@ -20,8 +20,10 @@ vi.mock('@queries/soup/items', () => ({
}));
vi.mock('@service-storage/graphql-soup', () => ({
getGraphqlSoupClient: () => mocks.client,
- mapGraphqlSoupPage: (data: { entities: ChannelEntity[] }) => ({
- items: data.entities,
+ mapGraphqlSoupPage: (data: {
+ user: { soup: { items: ChannelEntity[] } };
+ }) => ({
+ items: data.user.soup.items,
}),
}));
vi.mock('@queries/soup/transform-utils', () => ({
@@ -74,7 +76,7 @@ beforeEach(() => {
requests(operation);
return {
operation,
- data: { entities: [CHANNEL] },
+ data: { user: { soup: { items: [CHANNEL] } } },
stale: false,
hasNext: false,
};
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index b12efb4cf5..58e3524df8 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -593,7 +593,8 @@ describe('channel selection loading and recovery', () => {
expect(mocks.markRead).not.toHaveBeenCalled();
setQuery('isFetching', true);
- expect(screen.getByTestId('channel-detail').textContent).toBe('one');
+ expect(screen.queryByTestId('channel-detail')).toBeNull();
+ expect(screen.getByText('Conversation unavailable')).toBeTruthy();
batch(() => {
setQuery('data', { entities: [full('one', ['new'])] });
setQuery('isFetching', false);
diff --git a/apps/web/src/features/channels-view/primitives/create-channel-detail.test.ts b/apps/web/src/features/channels-view/primitives/create-channel-detail.test.ts
index 87a386527b..8764b2c950 100644
--- a/apps/web/src/features/channels-view/primitives/create-channel-detail.test.ts
+++ b/apps/web/src/features/channels-view/primitives/create-channel-detail.test.ts
@@ -157,7 +157,9 @@ describe('channel opening', () => {
setLoad({ status: 'ready', channel: undefined });
expect(detail.view().status).toBe('unavailable');
setLoad({ status: 'pending' });
- expect(detail.view().status).toBe('loading');
+ expect(detail.view().status).toBe('unavailable');
+ setCached(channel('one'));
+ expect(detail.view().status).toBe('unavailable');
setLoad({ status: 'error', error: new Error('Offline') });
expect(detail.view().status).toBe('unavailable');
expect(markRead).not.toHaveBeenCalled();
diff --git a/apps/web/src/features/channels-view/primitives/create-channel-detail.ts b/apps/web/src/features/channels-view/primitives/create-channel-detail.ts
index 15fc696487..99f23641c9 100644
--- a/apps/web/src/features/channels-view/primitives/create-channel-detail.ts
+++ b/apps/web/src/features/channels-view/primitives/create-channel-detail.ts
@@ -42,12 +42,8 @@ export function createChannelDetail(options: {
? { status: 'ready', channel }
: { status: 'unavailable', channelId: id, denied: false };
}
- // Retrying an access failure cannot make previously denied data visible.
- if (
- previous?.status === 'unavailable' &&
- previous.channelId === id &&
- previous.denied
- )
+ // Pending revalidation cannot undo a confirmed absence or access failure.
+ if (previous?.status === 'unavailable' && previous.channelId === id)
return previous;
const cached = options.cached();
const channel =
diff --git a/apps/web/src/lib/queries/channel/browser-test/access.browser.e2e.ts b/apps/web/src/lib/queries/channel/browser-test/access.browser.e2e.ts
new file mode 100644
index 0000000000..039e1f5fea
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/access.browser.e2e.ts
@@ -0,0 +1,37 @@
+import { expect, test } from '@playwright/test';
+
+test('stale cache changes retain the conversation while fresh membership changes take effect', async ({
+ page,
+}) => {
+ await page.goto('/');
+ let completed = 0;
+ const act = async (name: string) => {
+ await page.getByRole('button', { name, exact: true }).click();
+ await expect(
+ page.getByRole('status', { name: 'Completed actions' })
+ ).toHaveText(String(++completed));
+ };
+ await act('Server allows opening');
+ const draft = page.getByRole('textbox', { name: 'Message draft' });
+ await draft.fill('Draft survives cache lag');
+ await act('Cache empty');
+ await expect(draft).toHaveValue('Draft survives cache lag');
+ await expect(
+ page.getByRole('status', { name: 'State history' })
+ ).not.toContainText('unavailable');
+ await act('Confirm access');
+ await act('Cache empty');
+ await expect(draft).toHaveValue('Draft survives cache lag');
+ await page.screenshot({
+ path: `/tmp/channel-flicker-${test.info().project.name}.png`,
+ });
+ await act('Server removes access');
+ await expect(
+ page.getByRole('heading', { name: 'Conversation unavailable' })
+ ).toBeVisible();
+ await act('Cache has channel');
+ await expect(draft).toHaveCount(0);
+ await act('Membership restored');
+ await expect(draft).toBeVisible();
+ await expect(page.getByRole('status', { name: 'Fixture error' })).toBeEmpty();
+});
diff --git a/apps/web/src/lib/queries/channel/browser-test/adapters.ts b/apps/web/src/lib/queries/channel/browser-test/adapters.ts
new file mode 100644
index 0000000000..2503fffe80
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/adapters.ts
@@ -0,0 +1,21 @@
+import type { Client } from '@urql/core';
+import type { channelPage } from '../tests/detail-cache-fixture';
+
+let client: Client;
+export function setClient(value: Client) {
+ client = value;
+}
+export function getGraphqlSoupClient() {
+ return client;
+}
+export function mapGraphqlSoupPage(data: ReturnType<typeof channelPage>) {
+ return { items: data.user.soup.items };
+}
+export function mapApiSoupItemToEntity(item: { id: string; name: string }) {
+ return {
+ ...item,
+ type: 'channel',
+ ownerId: 'viewer',
+ channelType: 'private',
+ };
+}
diff --git a/apps/web/src/lib/queries/channel/browser-test/harness.tsx b/apps/web/src/lib/queries/channel/browser-test/harness.tsx
new file mode 100644
index 0000000000..76ace824b2
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/harness.tsx
@@ -0,0 +1,98 @@
+import { createChannelDetail } from '@app/features/channels-view/primitives/create-channel-detail';
+import { createChannelDetailSource } from '@app/features/channels-view/queries/channel-detail-source';
+import { createEffect, createSignal, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { refreshActiveGraphqlSoupQueries } from '../../soup/graphql/active-queries';
+import { createChannelDetailQuery } from '../detail';
+import {
+ channelPage,
+ createDetailCacheFixture,
+} from '../tests/detail-cache-fixture';
+import { setClient } from './adapters';
+
+const transport = createDetailCacheFixture();
+setClient(transport.client);
+function Harness() {
+ const source = createChannelDetailSource({
+ channelId: () => 'one',
+ cached: () => undefined,
+ createQuery: createChannelDetailQuery,
+ });
+ const detail = createChannelDetail({
+ selection: () => ({ id: 'one' }),
+ cached: () => undefined,
+ source,
+ markRead: () => {},
+ });
+ const [history, setHistory] = createSignal<string[]>([]);
+ const [error, setError] = createSignal('');
+ const [completed, setCompleted] = createSignal(0);
+ createEffect(() => {
+ const status = detail.view().status;
+ setHistory((previous) => [...previous, status]);
+ });
+ const reply = async (allowed: boolean) => {
+ const request = await transport.requests.next();
+ request.respond(channelPage(allowed ? 'one' : undefined));
+ await transport.results.next();
+ };
+ const revalidate = async (allowed: boolean) => {
+ transport.results.clear();
+ const pending = refreshActiveGraphqlSoupQueries();
+ await reply(allowed);
+ await pending;
+ };
+ const run = (action: () => Promise<unknown>) => async () => {
+ try {
+ await action();
+ setCompleted((count) => count + 1);
+ } catch (error) {
+ setError(String(error));
+ }
+ };
+ return (
+ <main>
+ <h1>Channel access regression fixture</h1>
+ <p>
+ Synthetic transport over the real normalized cache, query, and channel
+ detail state.
+ </p>
+ <nav>
+ <button onClick={run(() => reply(true))}>Server allows opening</button>
+ <button onClick={run(() => transport.cache(channelPage()))}>
+ Cache empty
+ </button>
+ <button onClick={run(() => reply(true))}>Confirm access</button>
+ <button onClick={run(() => revalidate(false))}>
+ Server removes access
+ </button>
+ <button onClick={run(() => transport.cache(channelPage('one')))}>
+ Cache has channel
+ </button>
+ <button onClick={run(() => reply(true))}>Membership restored</button>
+ </nav>
+ <section aria-label="Channel detail">
+ <Show
+ when={detail.view().status === 'ready'}
+ fallback={
+ <h2>
+ {detail.view().status === 'loading'
+ ? 'Loading conversation'
+ : 'Conversation unavailable'}
+ </h2>
+ }
+ >
+ <h2>Conversation</h2>
+ <p>Channel content remains mounted during stale cache updates.</p>
+ <textarea aria-label="Message draft" placeholder="Write a message" />
+ </Show>
+ </section>
+ <output aria-label="State history">{history().join(' → ')}</output>
+ <output aria-label="Fixture error">{error()}</output>
+ <output aria-label="Completed actions">{completed()}</output>
+ </main>
+ );
+}
+const root = document.getElementById('app');
+if (!root) throw new Error('Missing fixture root');
+render(() => <Harness />, root);
diff --git a/apps/web/src/lib/queries/channel/browser-test/index.html b/apps/web/src/lib/queries/channel/browser-test/index.html
new file mode 100644
index 0000000000..d3c88c498f
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/index.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Channel access regression</title><style>body{margin:0;background:#fafafa;color:#252525;font:14px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{max-width:850px;padding:24px;margin:auto}h1{font-size:22px}nav{display:flex;flex-wrap:wrap;gap:8px}button{padding:8px;border:1px solid #ccc;border-radius:6px;background:white;color:inherit;font:inherit;cursor:pointer}section{margin:24px 0;padding:24px;border:1px solid #ddd;min-height:220px;background:white}textarea{box-sizing:border-box;width:100%;min-height:90px;font:inherit;padding:12px}output{display:block;overflow-wrap:anywhere;font-size:12px;color:#555}</style></head><body><div id="app"></div><script type="module" src="./harness.tsx"></script></body></html>
diff --git a/apps/web/src/lib/queries/channel/browser-test/playwright.config.ts b/apps/web/src/lib/queries/channel/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..d84c2b9930
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/playwright.config.ts
@@ -0,0 +1,30 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const web = fileURLToPath(new URL('../../../../../', import.meta.url));
+const port = 3198;
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ webServer: {
+ command: `bunx vite --config src/lib/queries/channel/browser-test/vite.config.ts --port ${port}`,
+ cwd: web,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: false,
+ },
+ projects: [
+ { name: 'desktop', use: { browserName: 'chromium' } },
+ {
+ name: 'phone',
+ use: { ...devices['iPhone 13'], browserName: 'chromium' },
+ },
+ ],
+});
diff --git a/apps/web/src/lib/queries/channel/browser-test/vite.config.ts b/apps/web/src/lib/queries/channel/browser-test/vite.config.ts
new file mode 100644
index 0000000000..dc96b3b374
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/browser-test/vite.config.ts
@@ -0,0 +1,21 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vite';
+import solid from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const web = fileURLToPath(new URL('../../../../../', import.meta.url));
+const adapters = fileURLToPath(new URL('./adapters.ts', import.meta.url));
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [solid(), tsconfigPaths({ projects: [`${web}/tsconfig.json`] })],
+ resolve: {
+ dedupe: ['solid-js'],
+ alias: [
+ { find: /^@service-storage\/graphql-soup$/, replacement: adapters },
+ { find: /^\.\.\/soup\/transform-utils$/, replacement: adapters },
+ ],
+ },
+ server: { host: '127.0.0.1', strictPort: true },
+});
diff --git a/apps/web/src/lib/queries/channel/detail-cache.test.ts b/apps/web/src/lib/queries/channel/detail-cache.test.ts
new file mode 100644
index 0000000000..1137b46f4d
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/detail-cache.test.ts
@@ -0,0 +1,267 @@
+import { createChannelDetail } from '@app/features/channels-view/primitives/create-channel-detail';
+import { createChannelDetailSource } from '@app/features/channels-view/queries/channel-detail-source';
+import { createChannelListUpdatesHandler } from '@service-storage/graphql-channel-list-updates';
+import { type Client, CombinedError, type RequestPolicy } from '@urql/core';
+import { createEffect, createRoot, createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { createChannelDetailQuery } from './detail';
+import { disposeChannelNotificationRefresh } from './notification-refresh';
+import {
+ channelPage,
+ createDetailCacheFixture,
+} from './tests/detail-cache-fixture';
+
+let client: () => Client;
+let transport: ReturnType<typeof createDetailCacheFixture>;
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: () => client(),
+ mapGraphqlSoupPage: (data: ReturnType<typeof channelPage>) => ({
+ items: data.user.soup.items,
+ }),
+}));
+// Mapping is a transport boundary; all cache, query, source, and view-state
+// transitions below run their production implementations.
+vi.mock('../soup/transform-utils', () => ({
+ mapApiSoupItemToEntity: (item: { id: string; name: string }) => ({
+ ...item,
+ type: 'channel',
+ ownerId: 'viewer',
+ channelType: 'private',
+ }),
+}));
+const disposers: (() => void)[] = [];
+afterEach(() => {
+ disposers.splice(0).forEach((dispose) => dispose());
+ vi.restoreAllMocks();
+});
+function setup(
+ options: {
+ requestPolicy?: RequestPolicy;
+ cached?: ReturnType<typeof channelPage>;
+ } = {}
+) {
+ transport = createDetailCacheFixture();
+ if (options.cached) transport.seed(options.cached);
+ disposers.push(() => disposeChannelNotificationRefresh(transport.client));
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ const [id, setId] = createSignal('one');
+ const [currentClient, setClient] = createSignal(transport.client);
+ client = currentClient;
+ const [enabled, setEnabled] = createSignal(true);
+ const source = createChannelDetailSource({
+ channelId: id,
+ cached: () => undefined,
+ createQuery: (id, active) =>
+ createChannelDetailQuery(
+ id,
+ () => enabled() && active(),
+ options.requestPolicy
+ ),
+ });
+ const detail = createChannelDetail({
+ selection: () => ({ id: id() }),
+ cached: () => undefined,
+ source,
+ markRead: () => {},
+ });
+ const states: string[] = [];
+ createEffect(() => states.push(detail.view().status));
+ return { detail, states, setId, setClient, setEnabled };
+ });
+}
+
+it('does not replace an admitted conversation with a lagging empty cache projection', async () => {
+ const { detail, states } = setup();
+ const first = await transport.requests.next();
+ first.respond(channelPage('one'));
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+ states.length = 0;
+ await transport.cache(channelPage());
+ expect(detail.view().status).toBe('ready');
+ expect(states).not.toContain('unavailable');
+ const confirmation = await transport.requests.next();
+ confirmation.respond(channelPage('one'));
+ await transport.results.next();
+ const count = transport.networkCount();
+ await transport.cache(channelPage());
+ expect(detail.view().status).toBe('ready');
+ expect(transport.networkCount()).toBe(count);
+});
+
+it('keeps a server-confirmed absence hidden through positive cache updates until a fresh grant', async () => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ expect(detail.view().status).toBe('unavailable');
+ await transport.cache(channelPage('one'));
+ expect(detail.view().status).toBe('unavailable');
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+});
+
+it('honors fresh access denial and does not let cached records restore access', async () => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ const refresh = expect(detail.refresh()).rejects.toThrow();
+ (await transport.requests.next()).respond(
+ undefined,
+ new CombinedError({ graphQLErrors: ['Forbidden'] })
+ );
+ await refresh;
+ expect(detail.view().status).toBe('unavailable');
+ await transport.cache(channelPage('one'));
+ expect(detail.view().status).toBe('unavailable');
+});
+
+it('does not reuse one channel’s membership decision for another', async () => {
+ const { detail, setId } = setup();
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ setId('two');
+ expect(detail.view().status).toBe('loading');
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ expect(detail.view().status).toBe('unavailable');
+});
+
+it('confirms a cache disappearance and hides a fresh server deletion', async () => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ await transport.cache(channelPage());
+ expect(detail.view().status).toBe('ready');
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ expect(detail.view().status).toBe('unavailable');
+});
+
+it.each(['reconnect', 'invite'] as const)(
+ 'recovers a denied route on %s before its message view mounts',
+ async (event) => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ expect(detail.view().status).toBe('unavailable');
+ const updates = createChannelListUpdatesHandler(transport.client);
+ disposers.push(updates.dispose);
+ if (event === 'reconnect') updates.reconnect();
+ else
+ await updates.onPatch({
+ __typename: 'GraphqlNewNotification',
+ notification: {
+ __typename: 'GraphqlNotification',
+ id: 'invite',
+ entityId: 'one',
+ entityType: 'CHANNEL',
+ targetEntityType: 'CHANNEL',
+ eventType: 'channel_invite',
+ state: 'UNSEEN',
+ sent: true,
+ senderId: 'sender',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ viewedAt: null,
+ metadata: {
+ __typename: 'GraphqlChannelInviteMetadata',
+ channelInviteChannelName: 'Conversation',
+ channelInviteMessageContent: null,
+ channelInviteSenderProfilePictureUrl: null,
+ channelInviteInvitedBy: 'sender',
+ },
+ },
+ });
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+ }
+);
+
+it('keeps an admitted conversation through a transport failure and later cache updates', async () => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ const refreshed = expect(detail.refresh()).rejects.toThrow();
+ (await transport.requests.next()).respond(
+ undefined,
+ new CombinedError({ networkError: new Error('Offline') })
+ );
+ await refreshed;
+ expect(detail.view().status).toBe('ready');
+ await transport.cache(channelPage());
+ expect(detail.view().status).toBe('ready');
+});
+
+it('confirms a cold cache-only absence before declaring the channel unavailable', async () => {
+ const { detail } = setup({
+ requestPolicy: 'cache-first',
+ cached: channelPage(),
+ });
+ const request = await transport.requests.next();
+ expect(detail.view().status).toBe('loading');
+ request.respond(channelPage('one'));
+ // The first result is the empty cache hit, followed by network confirmation.
+ await transport.results.next();
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+});
+
+it('keeps cache-first display readers local when a channel is cached', async () => {
+ const { detail } = setup({
+ requestPolicy: 'cache-first',
+ cached: channelPage('one'),
+ });
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+ expect(transport.networkCount()).toBe(0);
+});
+
+it('rechecks the same positive cache hint after disabling and reopening a denied reader', async () => {
+ const { detail, setEnabled } = setup({ requestPolicy: 'cache-first' });
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ await transport.cache(channelPage('one'));
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ const count = transport.networkCount();
+ await transport.cache(channelPage('one'));
+ expect(transport.networkCount()).toBe(count);
+ expect(detail.view().status).toBe('unavailable');
+ setEnabled(false);
+ setEnabled(true);
+ const request = await transport.requests.next();
+ transport.results.clear();
+ request.respond(channelPage('one'));
+ await transport.results.next();
+ expect(detail.view().status).toBe('ready');
+});
+
+it('does not retain a previous client’s denial after account replacement', async () => {
+ const { detail, setClient } = setup();
+ (await transport.requests.next()).respond(channelPage());
+ await transport.results.next();
+ const replacement = createDetailCacheFixture();
+ disposers.push(() => disposeChannelNotificationRefresh(replacement.client));
+ setClient(() => replacement.client);
+ (await replacement.requests.next()).respond(channelPage('one'));
+ await replacement.results.next();
+ expect(detail.view().status).toBe('ready');
+});
+
+it('keeps admitted channel fields live without refetching unchanged membership', async () => {
+ const { detail } = setup();
+ (await transport.requests.next()).respond(channelPage('one'));
+ await transport.results.next();
+ const count = transport.networkCount();
+ await transport.cache(channelPage('one', 'Renamed conversation'));
+ const view = detail.view();
+ expect(view.status).toBe('ready');
+ expect(view.status === 'ready' && view.channel.name).toBe(
+ 'Renamed conversation'
+ );
+ expect(transport.networkCount()).toBe(count);
+});
diff --git a/apps/web/src/lib/queries/channel/detail.ts b/apps/web/src/lib/queries/channel/detail.ts
index aab5adc636..554bce2858 100644
--- a/apps/web/src/lib/queries/channel/detail.ts
+++ b/apps/web/src/lib/queries/channel/detail.ts
@@ -1,13 +1,33 @@
-import { ChannelDetailSoupDocument } from '@service-storage/graphql/generated/graphql';
+import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';
+import {
+ ChannelDetailSoupDocument,
+ type ChannelDetailSoupQuery,
+} from '@service-storage/graphql/generated/graphql';
import {
getGraphqlSoupClient,
mapGraphqlSoupPage,
} from '@service-storage/graphql-soup';
-import type { RequestPolicy } from '@urql/core';
-import type { Accessor } from 'solid-js';
+import {
+ type Client,
+ makeOperation,
+ type OperationResult,
+ type RequestPolicy,
+} from '@urql/core';
+import {
+ type Accessor,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
import { createLiveQuery } from '../../graphql-cache/solid/create-live-query';
+import {
+ registerActiveGraphqlSoupQuery,
+ registerGraphqlSoupRevalidations,
+} from '../soup/graphql/active-queries';
import { buildGraphqlEntitySoupInput } from '../soup/graphql/entity-input';
import { mapApiSoupItemToEntity } from '../soup/transform-utils';
+import { registerChannelNotificationRefresh } from './register-notification-refresh';
/**
* A conversation and its complete unread edge. Activation readers revalidate
@@ -19,28 +39,132 @@ export function createChannelDetailQuery(
enabled: Accessor<boolean>,
requestPolicy: RequestPolicy = 'cache-and-network'
) {
- const query = createLiveQuery(
- ChannelDetailSoupDocument,
- () => {
- const id = channelId();
- const input = id && buildGraphqlEntitySoupInput('CHANNEL', id);
- return input ? { input } : undefined;
- },
- () => ({
- client: getGraphqlSoupClient(),
+ // Only a server result can decide that a channel is inaccessible. Cache
+ // projections can temporarily omit a newly joined channel, including after
+ // its network response has arrived but before persistence catches up.
+ const [server, setServer] = createSignal<{
+ id: string | undefined;
+ client: Client;
+ result: OperationResult<ChannelDetailSoupQuery>;
+ }>();
+ const membershipCheck = createMemo<{ checked?: boolean }>(
+ on([channelId, getGraphqlSoupClient, enabled], () => ({}))
+ );
+ const currentServer = () => {
+ const value = server();
+ return value?.id === channelId() && value?.client === getGraphqlSoupClient()
+ ? value.result
+ : undefined;
+ };
+ const includesChannel = (data: ChannelDetailSoupQuery | undefined) =>
+ data?.user?.soup?.items.some((item) => item.id === channelId()) ?? false;
+ const variables = createMemo(() => {
+ const id = channelId();
+ const input = id && buildGraphqlEntitySoupInput('CHANNEL', id);
+ return input ? { input } : undefined;
+ });
+ const query = createLiveQuery(ChannelDetailSoupDocument, variables, () => {
+ const id = channelId();
+ const client = getGraphqlSoupClient();
+ const membership = membershipCheck();
+ return {
+ client,
enabled: enabled(),
requestPolicy,
- select: (data) => ({
- entities: mapGraphqlSoupPage(data).items.map(mapApiSoupItemToEntity),
- }),
+ keepPreviousData: false,
+ onResult: (result) => {
+ const source = normalizedCacheResultMetadata(result)?.source;
+ if (!source || source === 'live-network') {
+ if (!result.stale && !result.hasNext)
+ setServer({ id, client, result });
+ return;
+ }
+ if (result.stale || result.hasNext) return;
+ const cachedMembership = includesChannel(result.data);
+ const confirmed = currentServer();
+ const confirmedMembership =
+ !!confirmed && !confirmed.error && includesChannel(confirmed.data);
+ if (
+ (!confirmed && cachedMembership) ||
+ (confirmed && cachedMembership === confirmedMembership)
+ ) {
+ membership.checked = undefined;
+ return;
+ }
+ // A cache-only membership change is a hint to check the server, in
+ // either direction. Confirm it once even if the same stale projection
+ // keeps arriving after a successful response.
+ if (membership.checked !== cachedMembership) {
+ membership.checked = cachedMembership;
+ client.reexecuteOperation(
+ makeOperation('query', result.operation, {
+ ...result.operation.context,
+ requestPolicy: 'network-only',
+ })
+ );
+ }
+ },
+ };
+ });
+ const data = createMemo(() => {
+ if (query.isPending) return undefined;
+ const confirmed = currentServer();
+ if (confirmed?.error) return undefined;
+ // A confirmed absence must also win over later stale positive cache rows.
+ let value = confirmed?.data;
+ if (
+ (!confirmed || includesChannel(confirmed.data)) &&
+ includesChannel(query.data)
+ ) {
+ value = query.data;
+ }
+ return value
+ ? {
+ entities: mapGraphqlSoupPage(value).items.map(mapApiSoupItemToEntity),
+ }
+ : undefined;
+ });
+ const refresh = registerChannelNotificationRefresh(() => ({
+ client: getGraphqlSoupClient(),
+ queries: variables()
+ ? [{ document: ChannelDetailSoupDocument, variables: variables()! }]
+ : [],
+ reader: {
+ enabled: query.isEnabled,
+ fetching: query.isFetching,
+ channelId: channelId(),
+ filtered: true,
+ notificationIds: query.isSuccess
+ ? (
+ query.data?.user.soup.items.find((item) => item.id === channelId())
+ ?.notifications ?? []
+ ).map((notification) => notification.id)
+ : [],
+ },
+ }));
+ // Keep unavailable routes subscribed to invite/reconnect revalidation too;
+ // their message view (and its notification reader) is not mounted yet.
+ onCleanup(
+ registerActiveGraphqlSoupQuery({
+ isEnabled: () => query.isEnabled,
+ refresh,
})
);
+ onCleanup(
+ registerGraphqlSoupRevalidations(
+ () =>
+ query.isEnabled && variables()
+ ? [{ document: ChannelDetailSoupDocument, variables: variables()! }]
+ : [],
+ getGraphqlSoupClient
+ )
+ );
return {
get isEnabled() {
return query.isEnabled;
},
get isPending() {
- return query.isPending;
+ return query.isPending || (!currentServer() && !data());
},
get isLoading() {
return query.isLoading;
@@ -49,13 +173,11 @@ export function createChannelDetailQuery(
return query.isFetching;
},
get error() {
- return query.error;
+ return currentServer()?.error ?? null;
},
get data() {
- return query.data;
- },
- refresh: async () => {
- await query.refetch({ requestPolicy: 'network-only' });
+ return data();
},
+ refresh,
};
}
diff --git a/apps/web/src/lib/queries/channel/tests/detail-cache-fixture.ts b/apps/web/src/lib/queries/channel/tests/detail-cache-fixture.ts
new file mode 100644
index 0000000000..a7f11dc96a
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/tests/detail-cache-fixture.ts
@@ -0,0 +1,111 @@
+import { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';
+import { createNoopCacheHost } from '@graphql-cache/host/noop-host';
+import {
+ type CombinedError,
+ createClient,
+ type Operation,
+ type OperationResult,
+} from '@urql/core';
+import { filter, makeSubject, mergeMap, pipe, tap } from 'wonka';
+
+// A controlled network and cache; query observers and the normalized exchange
+// are real. Each mailbox waits for an actual result, without timers or polling.
+function mailbox<T>() {
+ const values: T[] = [];
+ const waiters: ((value: T) => void)[] = [];
+ return {
+ push(value: T) {
+ const waiter = waiters.shift();
+ if (waiter) waiter(value);
+ else values.push(value);
+ },
+ next(): Promise<T> {
+ if (values.length) return Promise.resolve(values.shift()!);
+ return new Promise((resolve) => waiters.push(resolve));
+ },
+ clear() {
+ values.length = 0;
+ },
+ };
+}
+
+export function channelPage(id?: string, name = 'Conversation') {
+ return {
+ user: {
+ id: 'viewer',
+ soup: {
+ items: id ? [{ __typename: 'GraphqlSoupChannel', id, name }] : [],
+ nextCursor: null,
+ },
+ },
+ };
+}
+
+export function createDetailCacheFixture() {
+ let cached: ReturnType<typeof channelPage> | undefined;
+ let affected: (keys: number[]) => void = () => {};
+ const keys = new Set<number>();
+ const results = mailbox<OperationResult>();
+ const requests = mailbox<{
+ operation: Operation;
+ respond(data?: ReturnType<typeof channelPage>, error?: CombinedError): void;
+ }>();
+ let networkCount = 0;
+ const client = createClient({
+ url: 'https://example.test/graphql',
+ exchanges: [
+ ({ forward }) =>
+ (operations) =>
+ pipe(forward(operations), tap(results.push)),
+ normalizedCacheExchange({
+ ...createNoopCacheHost(),
+ disabled: false,
+ readQuery: async (args) => {
+ if (args.opKey !== undefined) keys.add(args.opKey);
+ return cached ? { kind: 'hit', data: cached } : { kind: 'miss' };
+ },
+ onOpsAffected: (callback) => {
+ affected = callback;
+ return () => {};
+ },
+ }),
+ () => (operations) =>
+ pipe(
+ operations,
+ filter((op) => op.kind === 'query'),
+ mergeMap((operation) => {
+ networkCount++;
+ const response = makeSubject<OperationResult>();
+ requests.push({
+ operation,
+ respond: (data, error) => {
+ response.next({
+ operation,
+ data,
+ error,
+ stale: false,
+ hasNext: false,
+ });
+ },
+ });
+ return response.source;
+ })
+ ),
+ ],
+ });
+ return {
+ client,
+ requests,
+ results,
+ networkCount: () => networkCount,
+ seed(data: ReturnType<typeof channelPage>) {
+ cached = data;
+ },
+ async cache(data: ReturnType<typeof channelPage>) {
+ results.clear();
+ cached = data;
+ affected([...keys]);
+ return results.next();
+ },
+ };
+}
diff --git a/docs/agent-guide/assets/channel-access-cache-desktop.png b/docs/agent-guide/assets/channel-access-cache-desktop.png
new file mode 100644
index 0000000000..e0d7d2e19f
Binary files /dev/null and b/docs/agent-guide/assets/channel-access-cache-desktop.png differ
diff --git a/docs/agent-guide/assets/channel-access-cache-phone.png b/docs/agent-guide/assets/channel-access-cache-phone.png
new file mode 100644
index 0000000000..469bf4c849
Binary files /dev/null and b/docs/agent-guide/assets/channel-access-cache-phone.png differ
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index f59843fbdd..d9ad5a8a55 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -881,9 +881,14 @@ response must not switch back or mark that earlier channel read.
A transient notification-fetch failure keeps the conversation and composer mounted
while notifications are unavailable. Recovery marks top-level message notifications
seen without moving the conversation. No notification read marking runs
-from an abbreviated list result, even if that result is empty. Access failures
+from an abbreviated list result, even if that result is empty. Access failures and server-confirmed missing channels
show **Conversation unavailable** and stay hidden during retry until access is
-confirmed. A route without cached channel metadata shows **Loading conversation**
+confirmed. With GraphQL caching enabled, an empty local projection cannot hide a
+server-confirmed conversation; a stale positive row cannot undo a fresh denial or
+deletion. Contradictory cache membership triggers a bounded server confirmation.
+An initially empty cache result waits for that confirmation before declaring the
+channel unavailable. Unavailable routes still recover from invite notifications
+and reconnect without mounting a message view first. A route without cached channel metadata shows **Loading conversation**
until its channel arrives. On mobile, opening from the Recent conversation list
also navigates immediately: a slow or failed notification lookup must not prevent
messages and the composer from loading. Full-edge notification hydration runs
@@ -1204,11 +1209,21 @@ an opened unread conversation, so mark-read and message targeting retain their
complete top-level inputs in Chat and thread-scoped inputs in Inbox. Reopening
a conversation must refresh that full
edge even within 30 seconds; mark-read waits for the refresh rather than using
-older cached notifications. Failed lookups and successful lookups with no matching
+older cached notifications. Failed server lookups and successful server lookups with no matching
channel show **Conversation unavailable** with **Retry**, never permanent loading.
Retry rather than marking just the one unread witness. Repeated mobile taps must
open the last selected conversation, not a slower earlier request.
+A backend-free cache regression runs on desktop and phone viewports:
+`bunx playwright test --config src/lib/queries/channel/browser-test/playwright.config.ts`.
+It uses the production normalized exchange, query adapter, and detail state with a
+controlled transport. Confirm a channel, type a draft, then deliver repeated empty
+cache projections: the composer must remain mounted. A fresh server absence must
+hide it, a cached positive row must leave it hidden, and a fresh grant must recover
+it. See the [desktop fixture](assets/channel-access-cache-desktop.png) and
+[phone fixture](assets/channel-access-cache-phone.png); these show synthetic data,
+not a full app session.
+
Opening also refreshes that channel's bounded unread edge in the same request.
Read a DM on another device while its web sidebar retains an unread dot (for
example, with the read-status websocket update withheld), then open it on web.