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(auth): restore public document access with preview session discovery (#8349)
Sean Aye682c26541e6d
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 53f7a56137..666aacff3e 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -78,6 +78,13 @@ without changing the active route. Backend registration still verifies accountownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.### General+- Keep signed-out Drive document routes on the shared detail viewer without+ mounting private list/sidebar sources; let document access checks decide visibility.+- Gate account-only queries, comment readers, and account WebSockets on confirmed+ authentication; keep public document loading independent of those services+ and distinguish unresolved identity from confirmed sign-out in UI prompts.+- Probe identity on deploy-preview origins even without a local login hint;+ shared HttpOnly dev cookies are not visible to JavaScript or localStorage.- Disable GraphQL cache sessions and clear login hints on confirmed auth 401s,even with retained user data; preserve session state on transient failures.- Mobile dock search owns transient category/mode state in `features/command/mobile`; reuse the shared entity source and explicit full-text adapter rather than overlaying the dock query on view tabs or saved facets. See `docs/agent-guide/search.md` at the repository root.diff --git a/apps/web/src/components/app/AppProviders.tsx b/apps/web/src/components/app/AppProviders.tsxindex 6876431e20..bb2a904f73 100644--- a/apps/web/src/components/app/AppProviders.tsx+++ b/apps/web/src/components/app/AppProviders.tsx@@ -12,7 +12,7 @@ import { useReactiveFavicon } from '@components/app/useReactiveFavicon';import { useGlobalAttachableHistory } from '@core/component/AI/signal/globalAttachments';import { toast } from '@core/component/Toast/Toast';import { TeamContextProvider } from '@core/context/team';-import { useUserId } from '@core/context/user';+import { useIsAuthenticated, useUserId } from '@core/context/user';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { createBlockOrchestrator } from '@core/orchestrator';import { fireAndForget } from '@core/util/fireAndForget';@@ -35,6 +35,7 @@ import { ImperativeDialogHost } from '@ui';import type { ParentProps } from 'solid-js';function ConfiguredGlobalAppStateProvider(props: ParentProps) {+ const authenticated = useIsAuthenticated();// Initialize global notification helpersconst notifInterface = usePlatformNotificationState();useChatRenameWebsocketSync();@@ -70,7 +71,8 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {const notificationSource = createNotificationSource(connectionGatewayWebsocket,(notification) =>- fireAndForget(deliverNotification(notification), 'notifications')+ fireAndForget(deliverNotification(notification), 'notifications'),+ () => authenticated() === true);useNotificationUpdates(notificationSource);useAccessRequestInvalidations();diff --git a/apps/web/src/features/activity/use-entity-activity-flag.ts b/apps/web/src/features/activity/use-entity-activity-flag.tsindex 99d0d21655..acef9a9794 100644--- a/apps/web/src/features/activity/use-entity-activity-flag.ts+++ b/apps/web/src/features/activity/use-entity-activity-flag.ts@@ -1,13 +1,15 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableEntityActivitySection } from '@core/constant/featureFlags';+import { useIsAuthenticated } from '@core/context/user';import type { Accessor } from 'solid-js';/*** Whether the entity side panel shows the Activity section. Gates the* section component itself, so the entity-activity GraphQL query is never- * issued while off.+ * issued while off or before sign-in.*/export function useEntityActivityFlag(): Accessor<boolean> {const flag = useFeatureFlag(enableEntityActivitySection);- return () => flag().enabled;+ const authenticated = useIsAuthenticated();+ return () => authenticated() === true && flag().enabled;}diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsxindex 974d3482dd..dfb8993ad3 100644--- a/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx@@ -23,6 +23,15 @@ const mocks = vi.hoisted(() => ({anchor: null as MessageListItem['state']['anchor'],}));+const [authenticated, setAuthenticated] = createSignal<boolean | undefined>(+ true+);+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => authenticated,+}));++beforeEach(() => setAuthenticated(true));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => true }));vi.mock('@components/app/split-layout/layoutUtils', () => ({useSplitPanel: () => undefined,@@ -109,6 +118,24 @@ function setup() {return { input, setEditorHasFocus };}+it('does not mount comment readers or the composer before sign-in', () => {+ setAuthenticated(undefined);+ render(() => <DocumentDiscussion editorHasFocus={false} />);+ expect(screen.queryByText('Sign in to view comments.')).toBeNull();+ expect(mocks.conversation).not.toHaveBeenCalled();+ expect(mocks.mount).not.toHaveBeenCalled();++ setAuthenticated(false);+ expect(screen.getByText('Sign in to view comments.')).toBeTruthy();+ expect(mocks.conversation).not.toHaveBeenCalled();+ setAuthenticated(true);+ expect(screen.queryByText('Sign in to view comments.')).toBeNull();+ expect(mocks.conversation).toHaveBeenCalledOnce();+ setAuthenticated(false);+ expect(screen.getByText('Sign in to view comments.')).toBeTruthy();+ expect(screen.queryByRole('textbox')).toBeNull();+});+describe('mobile document discussion accessory', () => {it('moves the composer to the accessory and hides an empty conversation', () => {setup();diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.tsxindex 25940061ca..b9ac149726 100644--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx@@ -1,10 +1,12 @@import { useUrlParams } from '@core/component/ParamsProvider';+import { useIsAuthenticated } from '@core/context/user';import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import { EntityDiscussion } from '@core/messages/EntityDiscussion';import {useMessageLink,useMessageRootsQuery,} from '@queries/messages/document-messages';+import { Match, Switch } from 'solid-js';import { useMarkdownDocument } from '../context/markdown-document-context';/**@@ -12,10 +14,26 @@ import { useMarkdownDocument } from '../context/markdown-document-context';* touch devices the composer moves to the floating accessory region and the* conversation shows only once it has roots, as the editor page does.*/-export function DocumentDiscussion(props: {+type DocumentDiscussionProps = {editorHasFocus: boolean;label?: string;-}) {+};++export function DocumentDiscussion(props: DocumentDiscussionProps) {+ const authenticated = useIsAuthenticated();+ return (+ <Switch>+ <Match when={authenticated() === true}>+ <AuthenticatedDocumentDiscussion {...props} />+ </Match>+ <Match when={authenticated() === false}>+ <p class="mt-3 text-xs text-ink-muted">Sign in to view comments.</p>+ </Match>+ </Switch>+ );+}++function AuthenticatedDocumentDiscussion(props: DocumentDiscussionProps) {const { documentId, kind, permissions } = useMarkdownDocument();const id = documentId();const documentKind = kind();diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex 6c5c9584ed..44f0c74065 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -79,6 +79,7 @@ import {enableGitBlame,isFeatureEnabled,} from '@core/constant/featureFlags';+import { useIsAuthenticated } from '@core/context/user';import { fileFolderDrop } from '@core/directive/fileFolderDrop';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { fireAndForget } from '@core/util/fireAndForget';@@ -148,6 +149,7 @@ export function MarkdownEditor(props: {permissions,state: documentState,} = useMarkdownDocument();+ const authenticated = useIsAuthenticated();const { canEdit } = permissions;const blockId = documentId();const documentKind = kind();@@ -804,7 +806,7 @@ export function MarkdownEditor(props: {/></Show>- <Show when={ENABLE_MARKDOWN_COMMENTS}>+ <Show when={ENABLE_MARKDOWN_COMMENTS && authenticated() === true}><Suspense><MessageCommentsProvideractiveComment={activeCommentIdParam}diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsxindex 8198f6662c..b62697a114 100644--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx@@ -359,6 +359,7 @@ vi.mock('@queries/channel/channel-participants', () => ({vi.mock('@core/context/user', async (importOriginal) => ({...(await importOriginal<typeof import('@core/context/user')>()),useUserId: () => () => 'macro|[email protected]',+ useIsAuthenticated: () => () => true,}));vi.mock('@queries/messages/mutations', () => ({useSendMessageMutation: () => ({ mutate: vi.fn() }),diff --git a/apps/web/src/features/drive-view/components/DriveDetailView.tsx b/apps/web/src/features/drive-view/components/DriveDetailView.tsxindex 334fc10147..4116e29aaa 100644--- a/apps/web/src/features/drive-view/components/DriveDetailView.tsx+++ b/apps/web/src/features/drive-view/components/DriveDetailView.tsx@@ -18,7 +18,7 @@ import { ShareTrigger } from '@core/component/TopBar/ShareButton';import { useDocumentShareModal } from '@core/component/TopBar/shareModal';import { useCopyLink } from '@core/util/useCopyLink';import { ErrorBoundary, For, Match, Show, Switch } from 'solid-js';-import { useDriveView } from '../context/drive-context';+import { useOptionalDriveView } from '../context/drive-context';import { driveLocationBreadcrumbs } from '../core/breadcrumbs';import { useDriveDetailNavigation } from '../drive-detail-navigation';import { FileDetailBreadcrumbItem } from '../views/FileDetailBreadcrumbItem';@@ -216,9 +216,14 @@ function StackEntityDetail(props: {}export function DriveDetailView() {- const { state, sidebar } = useDriveView();+ const drive = useOptionalDriveView();const breadcrumbOrderOffset = () =>- driveLocationBreadcrumbs(state.value().location, sidebar.folders()).length;+ drive+ ? driveLocationBreadcrumbs(+ drive.state.value().location,+ drive.sidebar.folders()+ ).length+ : 0;const navigationStack = useDriveDetailNavigation();const activeHasBlockHeader = () => {const target = navigationStack.active()?.data;diff --git a/apps/web/src/features/drive-view/context/drive-context.tsx b/apps/web/src/features/drive-view/context/drive-context.tsxindex 8c5cffdb1a..977fe42bf3 100644--- a/apps/web/src/features/drive-view/context/drive-context.tsx+++ b/apps/web/src/features/drive-view/context/drive-context.tsx@@ -39,8 +39,12 @@ const Context = createContext<DriveContext>();export const DriveProvider = Context.Provider;+export function useOptionalDriveView(): DriveContext | undefined {+ return useContext(Context);+}+export function useDriveView(): DriveContext {- const context = useContext(Context);+ const context = useOptionalDriveView();if (!context) throw new Error('DriveProvider is required');diff --git a/apps/web/src/features/drive-view/drive-view.tsx b/apps/web/src/features/drive-view/drive-view.tsxindex e2b9fae3bd..9c411f9274 100644--- a/apps/web/src/features/drive-view/drive-view.tsx+++ b/apps/web/src/features/drive-view/drive-view.tsx@@ -49,6 +49,7 @@ import { createDriveDataSource } from './queries/drive-data-source';import { createDriveSidebarSource } from './queries/drive-sidebar-source';import { documentsTour } from './tour';import { DriveLoading, DriveWorkspace } from './views/drive-workspace';+import { SignedOutDriveWorkspace } from './views/signed-out-drive-workspace';export type DriveViewProps = { initialFacets?: FacetSelection };@@ -191,6 +192,16 @@ function DriveComposition(props: { route: DriveRouteState }) {);}+/** Public details use the same viewer without constructing private Drive sources. */+export function SignedOutDriveView() {+ const route = createDriveRouteState(() => undefined);+ return (+ <DriveDetailNavigationProvider location={route.location}>+ <SignedOutDriveWorkspace />+ </DriveDetailNavigationProvider>+ );+}+export function DriveView(props: DriveViewProps) {const route = createDriveRouteState(() => props.initialFacets);return (diff --git a/apps/web/src/features/drive-view/route-views.test.tsx b/apps/web/src/features/drive-view/route-views.test.tsxnew file mode 100644index 0000000000..bc4e3b1622--- /dev/null+++ b/apps/web/src/features/drive-view/route-views.test.tsx@@ -0,0 +1,99 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal, type ParentProps } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const [authenticated, setAuthenticated] = createSignal<boolean | undefined>();+const mountPrivateDrive = vi.fn();++vi.mock('@core/auth', () => ({+ useIsAuthenticated: () => authenticated,+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({+ handle: { content: () => ({ type: 'component', params: {} }) },+ }),+}));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => ({ pageView: vi.fn(), track: vi.fn() }),+}));+vi.mock('./drive-view', () => ({+ DriveView: () => {+ mountPrivateDrive();+ return <div>My Files</div>;+ },+ SignedOutDriveView: () => <div>Shared document viewer</div>,+}));+vi.mock('./drive-view-skeleton', () => ({+ DriveViewSkeleton: () => <div>Confirming session</div>,+}));+vi.mock('@core/component/LoadingBlock', () => ({+ LoadingBlock: () => <div>Loading</div>,+}));+vi.mock('@app/lib/split-router', () => ({+ useSplitRouter: () => ({}),+ useRouteParams: () => ({}),+}));+vi.mock('@app/routes/routes', () => ({ driveCallRoute: {} }));+vi.mock('@block-call/call-route', () => ({ callDetailSearch: {} }));++// Keep the real withAuth gate; only the unrelated app analytics wrapper is stubbed.+vi.mock(+ '@components/app/split-layout/split-router/app-route-shell',+ async (importOriginal) => {+ const original =+ await importOriginal<+ typeof import('@components/app/split-layout/split-router/app-route-shell')+ >();+ return {+ ...original,+ AppView: (props: ParentProps) => <>{props.children}</>,+ };+ }+);++import { DriveRouteView } from './route-views';++beforeEach(() => {+ setAuthenticated(undefined);+ mountPrivateDrive.mockClear();+});+afterEach(cleanup);++it('mounts shared details without mounting private Drive sources when signed out', () => {+ setAuthenticated(false);+ render(() => <DriveRouteView />);++ expect(screen.getByText('Shared document viewer')).toBeTruthy();+ expect(screen.queryByText('My Files')).toBeNull();+ expect(mountPrivateDrive).not.toHaveBeenCalled();+});++it('waits for the session before choosing a workspace', () => {+ render(() => <DriveRouteView />);++ expect(screen.getByText('Confirming session')).toBeTruthy();+ expect(screen.queryByText('Shared document viewer')).toBeNull();+ expect(mountPrivateDrive).not.toHaveBeenCalled();+ setAuthenticated(false);+ expect(screen.getByText('Shared document viewer')).toBeTruthy();+});++it('switches between shared details and private Drive as the session changes', () => {+ setAuthenticated(false);+ render(() => (+ <>+ <button onClick={() => setAuthenticated(true)}>Sign in</button>+ <button onClick={() => setAuthenticated(false)}>Sign out</button>+ <DriveRouteView />+ </>+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));+ expect(screen.getByText('My Files')).toBeTruthy();+ expect(screen.queryByText('Shared document viewer')).toBeNull();+ expect(mountPrivateDrive).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByRole('button', { name: 'Sign out' }));+ expect(screen.getByText('Shared document viewer')).toBeTruthy();+ expect(screen.queryByText('My Files')).toBeNull();+});diff --git a/apps/web/src/features/drive-view/route-views.tsx b/apps/web/src/features/drive-view/route-views.tsxindex 5e3b700b7c..4c801f95f7 100644--- a/apps/web/src/features/drive-view/route-views.tsx+++ b/apps/web/src/features/drive-view/route-views.tsx@@ -6,15 +6,20 @@ import {AppView,withAuth,} from '@components/app/split-layout/split-router/app-route-shell';-import { lazy } from 'solid-js';-import { DriveView, type DriveViewProps } from './drive-view';+import { useIsAuthenticated } from '@core/auth';+import { lazy, Show } from 'solid-js';+import {+ DriveView,+ type DriveViewProps,+ SignedOutDriveView,+} from './drive-view';import { DriveViewSkeleton } from './drive-view-skeleton';const DriveCallDetail = lazy(async () => ({default: (await import('./views/DriveCallDetail')).DriveCallDetail,}));-export const DriveRouteView = withAuth(() => {+const AuthenticatedDriveRouteView = withAuth(() => {const panel = useSplitPanelOrThrow();const props = (): DriveViewProps => {const content = panel.handle.content();@@ -29,6 +34,18 @@ export const DriveRouteView = withAuth(() => {);}, DriveViewSkeleton);+export function DriveRouteView() {+ const authenticated = useIsAuthenticated();+ return (+ <Show+ when={authenticated() === false}+ fallback={<AuthenticatedDriveRouteView />}+ >+ <SignedOutDriveView />+ </Show>+ );+}+export function DriveCallRouteView() {const params = useRouteParams(driveCallRoute);const [search] = createSearchParams(callDetailSearch);diff --git a/apps/web/src/features/drive-view/views/signed-out-drive-workspace.test.tsx b/apps/web/src/features/drive-view/views/signed-out-drive-workspace.test.tsxnew file mode 100644index 0000000000..04722653cb--- /dev/null+++ b/apps/web/src/features/drive-view/views/signed-out-drive-workspace.test.tsx@@ -0,0 +1,71 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal, type ParentProps } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';++const [active, setActive] = createSignal<{ value: string }>();+const navigate = vi.fn();+const openDocument = vi.fn();++vi.mock('@app/components/view-shell', () => {+ const Slot = (props: ParentProps) => props.children;+ return {+ ViewBreadcrumbs: { Root: Slot },+ ViewShell: { Root: Slot, Main: Slot },+ };+});+vi.mock('@components/app/split-panel', () => {+ const Slot = (props: ParentProps) => props.children;+ return { SplitPanel: { Root: Slot, Body: Slot } };+});+vi.mock('@app/lib/split-router', () => ({+ SplitRouter: {+ Outlet: () => {+ openDocument();+ return <div>Shared document</div>;+ },+ },+}));+vi.mock('../drive-detail-navigation', () => ({+ useDriveDetailNavigation: () => ({ active, popTo: vi.fn() }),+}));+vi.mock('./drive-workspace', () => ({+ DriveLoading: () => <div>Loading files</div>,+}));+vi.mock('@core/component/LoadingBlock', () => ({+ LoadingBlock: () => <div>Loading files</div>,+}));+vi.mock('@solidjs/router', () => ({ useNavigate: () => navigate }));+vi.mock('@core/auth', () => ({ useIsAuthenticated: () => () => false }));++import { SignedOutDriveWorkspace } from './signed-out-drive-workspace';++afterEach(() => {+ cleanup();+ setActive(undefined);+ vi.clearAllMocks();+});++it('offers sign-in instead of loading a list without an active document', () => {+ render(() => <SignedOutDriveWorkspace />);+ expect(screen.getByText('Sign in to view your files')).toBeTruthy();+ expect(screen.queryByText('Loading files')).toBeNull();+ expect(openDocument).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Login' }));+ expect(navigate).toHaveBeenCalledWith('/login');+});++it('keeps public details available and shows sign-in when the detail is closed', () => {+ setActive({ value: 'document' });+ render(() => (+ <>+ <button onClick={() => setActive(undefined)}>Close document</button>+ <SignedOutDriveWorkspace />+ </>+ ));+ expect(screen.getByText('Shared document')).toBeTruthy();+ expect(screen.queryByText('Sign in to view your files')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Close document' }));+ expect(screen.getByText('Sign in to view your files')).toBeTruthy();+ expect(screen.queryByText('Shared document')).toBeNull();+ expect(openDocument).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/drive-view/views/signed-out-drive-workspace.tsx b/apps/web/src/features/drive-view/views/signed-out-drive-workspace.tsxnew file mode 100644index 0000000000..267b3e00a8--- /dev/null+++ b/apps/web/src/features/drive-view/views/signed-out-drive-workspace.tsx@@ -0,0 +1,43 @@+import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';+import { SplitRouter } from '@app/lib/split-router';+import { SplitPanel } from '@components/app/split-panel';+import { LoginButton } from '@core/component/TopBar/LoginButton';+import { EmptyStatePanel } from '@ui';+import { Show, Suspense } from 'solid-js';+import { useDriveDetailNavigation } from '../drive-detail-navigation';+import { DriveLoading } from './drive-workspace';++export function SignedOutDriveWorkspace() {+ const navigation = useDriveDetailNavigation();+ return (+ <ViewBreadcrumbs.Root+ value={navigation.active()?.value ?? ''}+ onChange={navigation.popTo}+ >+ <SplitPanel.Root>+ <SplitPanel.Body>+ <ViewShell.Root>+ <ViewShell.Main>+ <Show+ when={navigation.active()}+ fallback={+ <EmptyStatePanel+ centered+ title="Sign in to view your files"+ description="Your files and folders are available after you sign in."+ >+ <LoginButton />+ </EmptyStatePanel>+ }+ >+ <Suspense fallback={<DriveLoading />}>+ <SplitRouter.Outlet />+ </Suspense>+ </Show>+ </ViewShell.Main>+ </ViewShell.Root>+ </SplitPanel.Body>+ </SplitPanel.Root>+ </ViewBreadcrumbs.Root>+ );+}diff --git a/apps/web/src/features/meetings/queries/meeting-teammates.test.ts b/apps/web/src/features/meetings/queries/meeting-teammates.test.tsindex cd77125376..5b70d648af 100644--- a/apps/web/src/features/meetings/queries/meeting-teammates.test.ts+++ b/apps/web/src/features/meetings/queries/meeting-teammates.test.ts@@ -10,6 +10,7 @@ vi.mock('@service-auth/client', () => ({authServiceClient: { getTeam: vi.fn() },}));vi.mock('@core/component/Toast/Toast', () => ({ toast: {} }));+vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));vi.mock('@queries/client', () => ({queryClient: { invalidateQueries: vi.fn() },}));diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.tsindex c12c561362..367ce46b57 100644--- a/apps/web/src/features/notifications/notification-source.ts+++ b/apps/web/src/features/notifications/notification-source.ts@@ -35,7 +35,7 @@ import {onCleanup,untrack,} from 'solid-js';-import { createStore, reconcile } from 'solid-js/store';+import { createStore } from 'solid-js/store';import { fromZodError } from 'zod-validation-error';import { nextNotificationState } from './notification-state';import { createMutedEntitiesQuery } from './queries/muted-entities-query';@@ -237,20 +237,25 @@ function withNotificationOverrides(export function createNotificationSource(ws: ConnectionGatewayWebsocket,- onNotification?: (notification: UnifiedNotification) => void+ onNotification?: (notification: UnifiedNotification) => void,+ enabled: Accessor<boolean> = () => true): NotificationSource {const subscriptions: Set<SubscribeFn> = new Set();- const [mutedEntitiesStore, setMutedEntities] = createStore<UserUnsubscribe[]>(- []+ const notificationsQuery = useUserNotificationsQuery(+ () => ({ limit: QUERY_LIMIT }),+ () => ({ enabled: enabled() }));- const mutedEntities = createMemo(() => [...mutedEntitiesStore]);-- const notificationsQuery = useUserNotificationsQuery(() => ({- limit: QUERY_LIMIT,- }));const usesGraphql = () => notificationsQuery.transport === 'graphql';- const mutedEntitiesQuery = createMutedEntitiesQuery({ limit: QUERY_LIMIT });+ const mutedEntitiesQuery = createMutedEntitiesQuery(+ { limit: QUERY_LIMIT },+ enabled+ );+ // Read the current query rather than retaining a second copy across sessions.+ const mutedEntities = createMemo(() => {+ if (!enabled() || mutedEntitiesQuery.isPending) return [];+ return mutedEntitiesQuery.data ?? [];+ });const muteItem = useMuteItemMutation();const unmuteItem = useUnmuteItemMutation();@@ -264,7 +269,7 @@ export function createNotificationSource(// A shell that only needs mute state, local overrides, or realtime callbacks// must not instantiate the full GraphQL notification feed at startup.const notifications = createLazyMemo(() => {- if (notificationsQuery.isLoading) return [];+ if (!enabled() || notificationsQuery.isLoading) return [];const raw = notificationsQuery.data;if (!raw) return [];return raw.map(withNotificationOverrides);@@ -275,7 +280,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 (usesGraphql()) return;+ if (!enabled() || usesGraphql()) return;const raw = notificationsQuery.data;if (!raw) return;const presentIds = new Set(raw.map((n) => n.id));@@ -294,7 +299,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 (usesGraphql()) return;+ if (!enabled() || usesGraphql()) return;const raw = notificationsQuery.data;if (!raw) return;const seenIds = Object.keys(seenOverrides);@@ -328,7 +333,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 (usesGraphql()) return;+ if (!enabled() || usesGraphql()) return;if (!notificationsQuery.data) return;if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {fireAndForget(notificationsQuery.fetchNextPage(), 'notifications');@@ -336,15 +341,12 @@ export function createNotificationSource(});const isLoading = () => {- return notificationsQuery.isLoading || mutedEntitiesQuery.isLoading;+ return (+ enabled() &&+ (notificationsQuery.isLoading || mutedEntitiesQuery.isLoading)+ );};- createEffect(() => {- const mutedEntities = mutedEntitiesQuery.data;- if (!mutedEntities) return;- setMutedEntities(reconcile(mutedEntities));- });-// TODO(dev-rb/notifications): Verify whether document-mention suppression is// still required, and remove this source-based cleanup when it is not.if (!ENABLE_DOCUMENT_MENTION_NOTIFICATIONS) {@@ -361,7 +363,7 @@ export function createNotificationSource(createEffect(() => {// This flag defaults off in production. Cleanup may observe an activated// feed, but must not become the reader that wakes it during startup.- if (!notificationsQuery.isStarted) return;+ if (!enabled() || !notificationsQuery.isStarted) return;const toDiscard = notifications().filter((n) =>n.notification_event_type === 'document_mention' && n.state !== 'done'@@ -387,7 +389,8 @@ export function createNotificationSource(let graphqlSubscriptionDisposed = false;const runGraphqlNotificationRefetch = async (): Promise<void> => {- if (graphqlSubscriptionDisposed || graphqlRefetchInFlight) return;+ if (!enabled() || graphqlSubscriptionDisposed || graphqlRefetchInFlight)+ return;graphqlRefetchInFlight = true;try {do {@@ -409,7 +412,7 @@ export function createNotificationSource(const scheduleGraphqlNotificationRefetch = (): void => {// Still dispatch new-notification callbacks below. The first actual feed// reader will fetch current data; a patch must not wake an unused feed.- if (!notificationsQuery.isStarted) return;+ if (!enabled() || !notificationsQuery.isStarted) return;graphqlRefetchPending = true;if (graphqlRefetchScheduled || graphqlRefetchInFlight) return;graphqlRefetchScheduled = true;@@ -421,7 +424,7 @@ export function createNotificationSource(const unsubscribeFromGraphql = subscribeToGraphqlNotificationPatches((patch) => {- if (!usesGraphql()) return;+ if (!enabled() || !usesGraphql()) return;scheduleGraphqlNotificationRefetch();if (patch.__typename !== 'GraphqlNewNotification') return;const notification = mapGraphqlNotification(patch.notification);@@ -445,7 +448,11 @@ export function createNotificationSource(};createSocketEffect(ws, (wsData) => {- if (wsData.type !== NOTIFICATION_EVENT_TYPE || usesGraphql()) {+ if (+ !enabled() ||+ wsData.type !== NOTIFICATION_EVENT_TYPE ||+ usesGraphql()+ ) {return;}let parsedNotification: UnifiedNotification;@@ -483,7 +490,7 @@ export function createNotificationSource(// of whether the entity has notifications, and an empty batch would still// POST a no-op mutation.const bulkMarkAsDone = async (notifications: UnifiedNotification[]) => {- if (notifications.length === 0) return;+ if (!enabled() || notifications.length === 0) return;const ids = notifications.map((n) => n.id);const rollback = setDoneOverride(ids, true);try {@@ -497,7 +504,7 @@ export function createNotificationSource(};const bulkMarkAsRead = async (notifications: UnifiedNotification[]) => {- if (notifications.length === 0) return;+ if (!enabled() || notifications.length === 0) return;const ids = notifications.map((n) => n.id);const rollback = setSeenOverride(ids, new Date().toISOString());try {@@ -524,10 +531,12 @@ export function createNotificationSource(muteItemForRef(entity) ?? { item_id: entity.id, item_type: entity.type };const muteEntity = async (entity: Entity) => {+ if (!enabled()) return;await muteItem.mutateAsync(toMuteItem(entity));};const unmuteEntity = async (entity: Entity) => {+ if (!enabled()) return;await unmuteItem.mutateAsync(toMuteItem(entity));};diff --git a/apps/web/src/features/notifications/tests/notification-source-auth.test.ts b/apps/web/src/features/notifications/tests/notification-source-auth.test.tsnew file mode 100644index 0000000000..14a48ea0e1--- /dev/null+++ b/apps/web/src/features/notifications/tests/notification-source-auth.test.ts@@ -0,0 +1,141 @@+import {+ JsonSerializer,+ WebsocketBuilder,+} from '@macro-inc/collaboration/websocket';+import type { ToWebsocketMessage } from '@service-connection/generated/schemas/toWebsocketMessage';+import type { FromWebsocketMessage } from '@service-connection/websocket';+import type { UserUnsubscribe } from '@service-notification/generated/schemas';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ notifications: vi.fn(),+ muted: vi.fn(),+ mark: vi.fn(),+ readData: vi.fn(() => []),+}));+vi.mock('@core/constant/featureFlags', () => ({+ ENABLE_DOCUMENT_MENTION_NOTIFICATIONS: true,+}));+vi.mock('@queries/notification/user-notifications', () => ({+ useUserNotificationsQuery: mocks.notifications,+ useMarkNotificationsAsDoneMutation: () => ({ mutateAsync: mocks.mark }),+ useMarkNotificationsAsSeenMutation: () => ({ mutateAsync: mocks.mark }),+ optimisticInsertNotification: vi.fn(),+}));+vi.mock('@queries/notification/unsubscribes', () => ({+ createMutedEntitiesQuery: mocks.muted,+ useMuteItemMutation: () => ({ mutateAsync: mocks.mark }),+ useUnmuteItemMutation: () => ({ mutateAsync: mocks.mark }),+}));+vi.mock('@queries/notification/notification-soup', () => ({+ updateSoupForNotification: vi.fn(),+}));+vi.mock('@service-storage/graphql-soup', () => ({+ mapGraphqlNotification: vi.fn(),+}));+vi.mock('@service-storage/graphql-soup-websocket', () => ({+ subscribeToGraphqlNotificationPatches: () => () => {},+}));++import { createNotificationSource } from '../notification-source';++afterEach(() => vi.clearAllMocks());++it('disables both feeds without reading pending data or mutating before sign-in', async () => {+ const [enabled, setEnabled] = createSignal(false);+ mocks.notifications.mockReturnValue({+ transport: 'rest',+ get data() {+ return mocks.readData();+ },+ });+ mocks.muted.mockReturnValue({+ get data() {+ return mocks.readData();+ },+ });+ const ws = new WebsocketBuilder('ws://unused')+ .withAutoConnect(false)+ .withSerializer(+ new JsonSerializer<ToWebsocketMessage, FromWebsocketMessage>()+ )+ .build();+ const { source, dispose } = createRoot((dispose) => ({+ source: createNotificationSource(ws, undefined, enabled),+ dispose,+ }));+ try {+ expect(mocks.notifications.mock.calls[0][1]()).toEqual({ enabled: false });+ expect(mocks.muted.mock.calls[0][1]()).toBe(false);+ expect(source.notifications()).toEqual([]);+ expect(source.mutedEntities()).toEqual([]);+ expect(mocks.readData).not.toHaveBeenCalled();+ await source.muteEntity({ type: 'document', id: 'document' });+ expect(mocks.mark).not.toHaveBeenCalled();++ setEnabled(true);+ expect(mocks.notifications.mock.calls[0][1]()).toEqual({ enabled: true });+ expect(mocks.muted.mock.calls[0][1]()).toBe(true);+ source.notifications();+ expect(mocks.readData).toHaveBeenCalled();++ setEnabled(false);+ mocks.readData.mockClear();+ expect(source.notifications()).toEqual([]);+ expect(source.mutedEntities()).toEqual([]);+ await source.unmuteEntity({ type: 'document', id: 'document' });+ expect(mocks.mark).not.toHaveBeenCalled();+ expect(mocks.readData).not.toHaveBeenCalled();+ } finally {+ dispose();+ ws.close();+ }+});++it('does not expose the previous account’s muted items while the next account loads', () => {+ const [enabled, setEnabled] = createSignal(true);+ const [pending, setPending] = createSignal(false);+ const [muted, setMuted] = createSignal<UserUnsubscribe[] | undefined>([+ { item_id: 'alice-document', item_type: 'document' },+ ]);+ mocks.notifications.mockReturnValue({ transport: 'graphql' });+ mocks.muted.mockReturnValue({+ get isPending() {+ return pending();+ },+ get data() {+ return muted();+ },+ });+ const ws = new WebsocketBuilder('ws://unused')+ .withAutoConnect(false)+ .withSerializer(+ new JsonSerializer<ToWebsocketMessage, FromWebsocketMessage>()+ )+ .build();+ const { source, dispose } = createRoot((dispose) => ({+ source: createNotificationSource(ws, undefined, enabled),+ dispose,+ }));+ try {+ expect(source.mutedEntities()).toEqual([+ { item_id: 'alice-document', item_type: 'document' },+ ]);+ setEnabled(false);+ expect(source.mutedEntities()).toEqual([]);+ setPending(true);+ setMuted(undefined);+ setEnabled(true);+ expect(source.mutedEntities()).toEqual([]);++ setMuted([{ item_id: 'bob-channel', item_type: 'channel' }]);+ setPending(false);+ expect(source.mutedEntities()).toEqual([+ { item_id: 'bob-channel', item_type: 'channel' },+ ]);+ } finally {+ dispose();+ ws.close();+ }+});diff --git a/apps/web/src/lib/core/auth/session-websockets.test.ts b/apps/web/src/lib/core/auth/session-websockets.test.tsnew file mode 100644index 0000000000..751158c8c9--- /dev/null+++ b/apps/web/src/lib/core/auth/session-websockets.test.ts@@ -0,0 +1,127 @@+import { createRoot, createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const [authenticated, setAuthenticated] = createSignal<boolean | undefined>();+const [userId, setUserId] = createSignal<string | undefined>();+const sockets = vi.hoisted(() => ({+ gateway: { reconnect: vi.fn(), close: vi.fn(), buffer: { read: vi.fn() } },+ storage: { reconnect: vi.fn(), close: vi.fn() },+ stopGateway: vi.fn(),+ stopStorage: vi.fn(),+ activateGateway: vi.fn(),+ activateStorage: vi.fn(),+}));+const telemetry = vi.hoisted(() => ({+ hash: vi.fn(),+ roots: [] as {+ name: string;+ span: { setAttr: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> };+ completed: Promise<void>;+ }[],+}));+vi.mock('@core/util/hash', () => ({ contentHash: telemetry.hash }));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: {+ anonymousSpan: (name: string) => {+ const completed = Promise.withResolvers<void>();+ const span = { setAttr: vi.fn(), end: vi.fn(() => completed.resolve()) };+ telemetry.roots.push({ name, span, completed: completed.promise });+ return span;+ },+ },+}));+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => authenticated,+ useUserId: () => userId,+}));+vi.mock('@service-connection/websocket', () => ({+ ws: sockets.gateway,+ connectionGatewaySessionTelemetry: { activate: sockets.activateGateway },+}));+vi.mock('@service-storage/websocket', () => ({+ storageWS: sockets.storage,+ storageSessionTelemetry: { activate: sockets.activateStorage },+}));++import { useSessionWebsockets } from './session-websockets';++let dispose: (() => void) | undefined;+beforeEach(() => {+ telemetry.hash.mockResolvedValue('opaque-user-hash');+ sockets.activateGateway.mockReturnValue(sockets.stopGateway);+ sockets.activateStorage.mockReturnValue(sockets.stopStorage);+});+afterEach(() => {+ dispose?.();+ dispose = undefined;+ setAuthenticated(undefined);+ setUserId(undefined);+ telemetry.roots.length = 0;+ vi.clearAllMocks();+});++it('starts only for authenticated identities, drains on logout, and replaces account sessions', async () => {+ createRoot((cleanup) => {+ dispose = cleanup;+ useSessionWebsockets();+ });+ expect(sockets.gateway.reconnect).not.toHaveBeenCalled();+ setUserId('alice');+ setAuthenticated(false);+ expect(sockets.gateway.reconnect).not.toHaveBeenCalled();++ setAuthenticated(true);+ expect(sockets.gateway.reconnect).toHaveBeenCalledOnce();+ expect(sockets.storage.reconnect).toHaveBeenCalledOnce();+ setUserId('bob');+ expect(sockets.gateway.close).toHaveBeenCalledOnce();+ expect(sockets.storage.close).toHaveBeenCalledOnce();+ expect(sockets.gateway.reconnect).toHaveBeenCalledTimes(2);++ sockets.gateway.buffer.read.mockReturnValueOnce({ type: 'track_entity' });+ setAuthenticated(false);+ expect(sockets.gateway.close).toHaveBeenCalledTimes(2);+ expect(sockets.storage.close).toHaveBeenCalledTimes(2);+ expect(sockets.gateway.buffer.read).toHaveBeenCalledTimes(3);++ setAuthenticated(true);+ expect(sockets.gateway.reconnect).toHaveBeenCalledTimes(3);+ dispose?.();+ dispose = undefined;+ expect(sockets.gateway.close).toHaveBeenCalledTimes(3);+ expect(sockets.storage.close).toHaveBeenCalledTimes(3);+ expect(sockets.stopGateway).toHaveBeenCalledTimes(3);+ expect(sockets.stopStorage).toHaveBeenCalledTimes(3);+ await Promise.all(telemetry.roots.map((root) => root.completed));+ expect(telemetry.roots).toHaveLength(3);+ for (const root of telemetry.roots) {+ expect(root.name).toBe('auth.session_websockets.activate');+ expect(root.span.setAttr).toHaveBeenCalledWith(+ 'user.id_hash',+ 'opaque-user-hash'+ );+ expect(root.span.end).toHaveBeenCalledOnce();+ expect(sockets.activateGateway).toHaveBeenCalledWith(root.span);+ expect(sockets.activateStorage).toHaveBeenCalledWith(root.span);+ }+ expect(+ JSON.stringify(telemetry.roots.map((root) => root.span.setAttr.mock.calls))+ ).not.toMatch(/alice|bob/);+});++it('ends activation spans and connects even when identity hashing fails', async () => {+ telemetry.hash.mockRejectedValue(new Error('unavailable'));+ setUserId('macro|[email protected]');+ setAuthenticated(true);+ createRoot((cleanup) => {+ dispose = cleanup;+ useSessionWebsockets();+ });+ expect(sockets.gateway.reconnect).toHaveBeenCalledOnce();+ await telemetry.roots[0].completed;+ expect(telemetry.roots[0].span.setAttr).toHaveBeenCalledWith(+ 'user.id_hash_unavailable',+ true+ );+ expect(telemetry.roots[0].span.end).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/lib/core/auth/session-websockets.ts b/apps/web/src/lib/core/auth/session-websockets.tsnew file mode 100644index 0000000000..81f7bdde3a--- /dev/null+++ b/apps/web/src/lib/core/auth/session-websockets.ts@@ -0,0 +1,60 @@+import { useIsAuthenticated, useUserId } from '@core/context/user';+import { fireAndForget } from '@core/util/fireAndForget';+import { contentHash } from '@core/util/hash';+import { type Span, Telemetry } from '@macro-inc/observability';+import {+ connectionGatewaySessionTelemetry,+ ws,+} from '@service-connection/websocket';+import { storageSessionTelemetry, storageWS } from '@service-storage/websocket';+import { createEffect, on, onCleanup } from 'solid-js';++async function finishActivationSpan(span: Span, userId: string) {+ try {+ // Macro IDs can contain email addresses. Keep only an opaque identifier,+ // and suppress the runtime's raw user-ID enrichment for this entire trace.+ span.setAttr(+ 'user.id_hash',+ await contentHash(new TextEncoder().encode(userId))+ );+ } catch {+ span.setAttr('user.id_hash_unavailable', true);+ } finally {+ span.end();+ }+}++/** Account sockets stay closed on public pages and belong to one signed-in session. */+export function useSessionWebsockets() {+ const authenticated = useIsAuthenticated();+ const userId = useUserId();+ createEffect(+ on(+ () => (authenticated() === true ? userId() : undefined),+ (id) => {+ if (!id) return;+ const activation = Telemetry.anonymousSpan(+ 'auth.session_websockets.activate'+ );+ activation.setAttr('outcome', 'activated');+ const stopGatewayTrace =+ connectionGatewaySessionTelemetry.activate(activation);+ const stopStorageTrace = storageSessionTelemetry.activate(activation);+ fireAndForget(+ finishActivationSpan(activation, id),+ 'session-websockets'+ );+ ws.reconnect();+ storageWS.reconnect();+ onCleanup(() => {+ stopGatewayTrace();+ stopStorageTrace();+ ws.close();+ storageWS.close();+ // Never send a previous account's queued presence after another login.+ while (ws.buffer?.read() !== undefined) {}+ });+ }+ )+ );+}diff --git a/apps/web/src/lib/core/component/AI/signal/globalAttachments.test.ts b/apps/web/src/lib/core/component/AI/signal/globalAttachments.test.tsnew file mode 100644index 0000000000..79c8b67197--- /dev/null+++ b/apps/web/src/lib/core/component/AI/signal/globalAttachments.test.ts@@ -0,0 +1,40 @@+import { createRoot, createSignal } from 'solid-js';+import { expect, it, vi } from 'vitest';++const [authenticated, setAuthenticated] = createSignal(true);+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => authenticated,+}));+vi.mock('@core/component/AI/constant/fileType', () => ({+ SUPPORTED_CHAT_ATTACHMENT_BLOCKS: ['md'],+}));+vi.mock('@core/util/getItemBlockName', () => ({+ getItemBlockName: () => 'md',+}));+vi.mock('@queries/history/history', () => ({+ useHistoryQuery: () => ({+ isSuccess: true,+ data: [{ id: 'private-document', name: 'Private document' }],+ }),+}));++import {+ globalAttachableHistory,+ useGlobalAttachableHistory,+} from './globalAttachments';++it('clears attachment suggestions on logout even while the history cache retains data', () => {+ const dispose = createRoot((dispose) => {+ useGlobalAttachableHistory();+ return dispose;+ });+ try {+ expect(globalAttachableHistory().map((item) => item.id)).toEqual([+ 'private-document',+ ]);+ setAuthenticated(false);+ expect(globalAttachableHistory()).toEqual([]);+ } finally {+ dispose();+ }+});diff --git a/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsx b/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsxindex 8726671e5b..d05a0bb29a 100644--- a/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsx+++ b/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsx@@ -1,4 +1,5 @@import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';+import { useIsAuthenticated } from '@core/context/user';import { getItemBlockName } from '@core/util/getItemBlockName';import type { HistoryItem } from '@queries/history/history';import { useHistoryQuery } from '@queries/history/history';@@ -14,10 +15,14 @@ export { globalAttachableHistory };/** Keeps `globalAttachableHistory` current; call once where the app's state lives. */export function useGlobalAttachableHistory(): void {+ const authenticated = useIsAuthenticated();const historyQuery = useHistoryQuery();const attachableHistory = createMemo(() => {- const history = historyQuery.isSuccess ? historyQuery.data : [];+ const history =+ authenticated() === true && historyQuery.isSuccess+ ? historyQuery.data+ : [];return history.filter((item) => {const blockName = getItemBlockName(item, true);return SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(blockName);diff --git a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsxindex 0e3a616efa..46441ac7b2 100644--- a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx@@ -49,7 +49,10 @@ vi.mock('@core/component/AI/signal/globalAttachments', () => ({vi.mock('@core/context/team', () => ({TeamContextProvider: (props: { children: unknown }) => props.children,}));-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'test-user' }));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'test-user',+ useIsAuthenticated: () => () => true,+}));vi.mock('@core/orchestrator', () => ({createBlockOrchestrator: vi.fn(() => ({})),}));diff --git a/apps/web/src/lib/core/context/channels.test.tsx b/apps/web/src/lib/core/context/channels.test.tsxindex a9f6811b67..3a6e19e978 100644--- a/apps/web/src/lib/core/context/channels.test.tsx+++ b/apps/web/src/lib/core/context/channels.test.tsx@@ -17,7 +17,10 @@ vi.mock('@queries/channel/activity', () => ({data: [],}),}));-vi.mock('./user', () => ({ useUserId: () => () => undefined }));+vi.mock('./user', () => ({+ useUserId: () => () => undefined,+ useIsAuthenticated: () => () => true,+}));import { ChannelsContextProvider, useChannelCanCall } from './channels';diff --git a/apps/web/src/lib/core/context/channels.ts b/apps/web/src/lib/core/context/channels.tsindex d76396a533..b6da5a6e19 100644--- a/apps/web/src/lib/core/context/channels.ts+++ b/apps/web/src/lib/core/context/channels.ts@@ -7,7 +7,7 @@ import { ChannelTypeEnum } from '@service-storage/client';import type { ApiActivity as ChannelsActivity } from '@service-storage/generated/schemas/apiActivity';import { type Accessor, createMemo } from 'solid-js';import { createAssertedContextProvider } from './createContext';-import { useUserId } from './user';+import { useIsAuthenticated, useUserId } from './user';type ChannelsContextValue = {channels: Accessor<ApiChannelWithLatest[]>;@@ -20,16 +20,18 @@ type ChannelsContextValue = {export const [ChannelsContextProvider, useChannelsContext] =createAssertedContextProvider('ChannelsContext', (): ChannelsContextValue => {- const channelsQuery = useListChannelsQuery();- const activityQuery = useChannelsActivityQuery();+ const authenticated = useIsAuthenticated();+ const enabled = () => authenticated() === true;+ const channelsQuery = useListChannelsQuery(enabled);+ const activityQuery = useChannelsActivityQuery(enabled);const channels = () =>- queryReadyGate(channelsQuery) ? channelsQuery.data : [];+ enabled() && queryReadyGate(channelsQuery) ? channelsQuery.data : [];const activity = () =>- queryReadyGate(activityQuery) ? activityQuery.data : [];+ enabled() && queryReadyGate(activityQuery) ? activityQuery.data : [];const channelsById = createMemo(() => {- if (!queryReadyGate(channelsQuery)) return {};+ if (!enabled() || !queryReadyGate(channelsQuery)) return {};return channelsQuery.data.reduce<Record<string, ApiChannelWithLatest>>((acc, ch) => {acc[ch.id] = ch;@@ -40,7 +42,7 @@ export const [ChannelsContextProvider, useChannelsContext] =});const activityByChannelId = createMemo(() => {- if (!queryReadyGate(activityQuery)) return {};+ if (!enabled() || !queryReadyGate(activityQuery)) return {};return activityQuery.data.reduce<Record<string, ChannelsActivity>>((acc, a) => {acc[a.channel_id] = a;diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsxindex ff826cd815..040c370b88 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx@@ -1,63 +1,108 @@import { cleanup, render, screen } from '@solidjs/testing-library';-import { createSignal, type ParentProps } from 'solid-js';+import { createSignal, onCleanup, type ParentProps } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import { useQuickAccess } from './context';import { QuickAccessProvider } from './QuickAccessProvider';-const [sourceError, setSourceError] = createSignal<Error>();+const [authenticated, setAuthenticated] = createSignal<boolean | undefined>();+const [userId, setUserId] = createSignal<string>();+const mountSource = vi.fn();+const disposeSource = vi.fn();+const refresh = vi.fn();+const loadMore = vi.fn();+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => authenticated,+ useUserId: () => userId,+}));vi.mock('@channel/DebugSuspense', () => ({DebugSuspense: (props: ParentProps) => props.children,}));vi.mock('./QuickAccessSource', () => ({- createQuickAccessValue: () => ({- useList: () => ({- error: sourceError,- items: () => [],- totalCount: () => 0,- hasMore: () => false,+ createQuickAccessValue: () => {+ const id = userId();+ const error = new Error(`Unavailable for ${id}`);+ mountSource(id);+ onCleanup(() => disposeSource(id));+ return {+ useList: () => ({+ error: () => error,+ items: () => [{ kind: 'user', id }],+ totalCount: () => 1,+ hasMore: () => true,+ isLoading: () => false,+ isLoadingMore: () => false,+ loadMore,+ }),+ usesRecordSelection: () => true,+ usesSearchProjection: () => true,isLoading: () => false,- isLoadingMore: () => false,- loadMore: async () => {},- }),- usesRecordSelection: () => true,- usesSearchProjection: () => true,- isLoading: () => false,- refresh: () => {},- getById: () => undefined,- }),+ refresh,+ getById: () => undefined,+ };+ },}));afterEach(() => {cleanup();- setSourceError(undefined);+ setAuthenticated(undefined);+ setUserId(undefined);+ vi.clearAllMocks();});-it.each(['buckets', 'options'])(- 'forwards reactive list errors and recovery with %s',- (mode) => {- function Consumer() {- const access = useQuickAccess();- const list =- mode === 'buckets'- ? access.useList('person')- : access.useList({- buckets: ['email'],- searchTerm: () => 'proposal',- });- return <div>{list.error() ? 'Unavailable' : 'Ready'}</div>;- }- render(() => (- <QuickAccessProvider>- <Consumer />- </QuickAccessProvider>- ));- expect(screen.getByText('Ready')).toBeTruthy();+it('keeps consumers mounted while creating and disposing account sources across login and logout', async () => {+ let mounted = 0;+ let refreshCurrent: () => void = () => {};+ let loadCurrent: () => Promise<void> = async () => {};+ let currentError: () => unknown = () => undefined;+ function Consumer() {+ mounted++;+ const access = useQuickAccess();+ const list = access.useList('person');+ refreshCurrent = access.refresh;+ loadCurrent = list.loadMore;+ currentError = list.error;+ return (+ <div>+ {list+ .items()+ .map((item) => item.id)+ .join(',') || 'No account data'}+ </div>+ );+ }+ render(() => (+ <QuickAccessProvider>+ <Consumer />+ </QuickAccessProvider>+ ));+ expect(screen.getByText('No account data')).toBeTruthy();+ expect(mountSource).not.toHaveBeenCalled();+ expect(currentError()).toBeUndefined();+ refreshCurrent();+ await loadCurrent();+ expect(refresh).not.toHaveBeenCalled();+ expect(loadMore).not.toHaveBeenCalled();- setSourceError(new Error('Cache unavailable'));- expect(screen.getByText('Unavailable')).toBeTruthy();+ setUserId('alice');+ setAuthenticated(false);+ expect(mountSource).not.toHaveBeenCalled();+ setAuthenticated(true);+ expect(screen.getByText('alice')).toBeTruthy();+ expect(currentError()).toMatchObject({ message: 'Unavailable for alice' });+ refreshCurrent();+ await loadCurrent();+ expect(refresh).toHaveBeenCalledOnce();+ expect(loadMore).toHaveBeenCalledOnce();- setSourceError(undefined);- expect(screen.getByText('Ready')).toBeTruthy();- }-);+ setUserId('bob');+ expect(disposeSource).toHaveBeenCalledWith('alice');+ expect(screen.getByText('bob')).toBeTruthy();+ expect(currentError()).toMatchObject({ message: 'Unavailable for bob' });+ setAuthenticated(false);+ expect(disposeSource).toHaveBeenCalledWith('bob');+ expect(screen.getByText('No account data')).toBeTruthy();+ expect(currentError()).toBeUndefined();+ expect(mountSource).toHaveBeenCalledTimes(2);+ expect(mounted).toBe(1);+});diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsxindex 26ee403e8e..b80df93802 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx@@ -1,5 +1,6 @@import { DebugSuspense } from '@channel/DebugSuspense';-import { createMemo, type FlowComponent } from 'solid-js';+import { useIsAuthenticated, useUserId } from '@core/context/user';+import { createMemo, type FlowComponent, on } from 'solid-js';import { QuickAccessContextProvider } from './context';import { createQuickAccessValue } from './QuickAccessSource';import type {@@ -10,37 +11,46 @@ import type {} from './types';const QuickAccessProviderValue: FlowComponent = (props) => {- const source = createQuickAccessValue();+ const authenticated = useIsAuthenticated();+ const userId = useUserId();+ const source = createMemo(+ on(+ () => (authenticated() === true ? userId() : undefined),+ (id) => (id ? createQuickAccessValue() : undefined)+ )+ );const useList = ((...args: Bucket[] | [QuickAccessListOptions]): QuickAccessList => {const sourceList = createMemo(() => {+ const current = source();+ if (!current) return;const first = args[0];return typeof first === 'object'- ? source.useList(first)- : source.useList(...(args as Bucket[]));+ ? current.useList(first)+ : current.useList(...(args as Bucket[]));});return {- error: () => sourceList().error(),- items: () => sourceList().items(),- totalCount: () => sourceList().totalCount(),- hasMore: () => sourceList().hasMore(),- isLoading: () => sourceList().isLoading(),- isLoadingMore: () => sourceList().isLoadingMore(),+ error: () => sourceList()?.error(),+ items: () => sourceList()?.items() ?? [],+ totalCount: () => sourceList()?.totalCount() ?? 0,+ hasMore: () => sourceList()?.hasMore() ?? false,+ isLoading: () => sourceList()?.isLoading() ?? false,+ isLoadingMore: () => sourceList()?.isLoadingMore() ?? false,loadMore: async () => {- await sourceList().loadMore();+ await sourceList()?.loadMore();},};}) as QuickAccessContextValue['useList'];const quickAccess: QuickAccessContextValue = {useList,- usesRecordSelection: source.usesRecordSelection,- usesSearchProjection: source.usesSearchProjection,- isLoading: source.isLoading,- refresh: source.refresh,- getById: source.getById,+ usesRecordSelection: () => source()?.usesRecordSelection() ?? false,+ usesSearchProjection: () => source()?.usesSearchProjection() ?? false,+ isLoading: () => source()?.isLoading() ?? false,+ refresh: () => source()?.refresh(),+ getById: (id) => source()?.getById(id),};return (diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.tsindex 778b38ba57..94dfc15275 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts@@ -71,6 +71,11 @@ const mocks = vi.hoisted(() => ({>>,}));+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => () => true,+ useUserId: () => () => 'viewer',+}));+vi.mock('@core/constant/featureFlags', () => ({enableCrm: {},enableDatabases: {},diff --git a/apps/web/src/lib/core/context/user-info-gate.test.ts b/apps/web/src/lib/core/context/user-info-gate.test.tsnew file mode 100644index 0000000000..c055b1a9db--- /dev/null+++ b/apps/web/src/lib/core/context/user-info-gate.test.ts@@ -0,0 +1,56 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const hasLoginCookie = vi.hoisted(() => vi.fn(() => false));+vi.mock('@core/util/cookies', () => ({ hasLoginCookie }));++beforeEach(() => {+ vi.resetModules();+ hasLoginCookie.mockReturnValue(false);+ vi.stubGlobal(+ 'window',+ Object.assign(new EventTarget(), {+ location: new URL('https://macro.com/app'),+ })+ );+});+afterEach(() => vi.unstubAllGlobals());++it('checks shared dev credentials on a fresh preview origin without a local login marker', async () => {+ window.location.hostname = 'branch-abc123.preview.macro.com';+ const { shouldQueryUserInfo } = await import('./user-info-gate');+ expect(shouldQueryUserInfo()).toBe(true);+});++it.each([+ 'macro.com',+ 'dev.macro.com',+ 'localhost',+ 'notpreview.macro.com',+ 'branch.preview.macro.com.example.com',+])('keeps anonymous identity checks disabled on %s', async (hostname) => {+ window.location.hostname = hostname;+ const { shouldQueryUserInfo } = await import('./user-info-gate');+ expect(shouldQueryUserInfo()).toBe(false);+});++it('checks identity with an existing login marker', async () => {+ hasLoginCookie.mockReturnValue(true);+ const { shouldQueryUserInfo } = await import('./user-info-gate');+ expect(shouldQueryUserInfo()).toBe(true);+});++it('wakes an anonymous identity observer when another tab publishes a login marker', async () => {+ const { shouldQueryUserInfo } = await import('./user-info-gate');+ expect(shouldQueryUserInfo()).toBe(false);+ window.dispatchEvent(new StorageEvent('storage', { key: 'unrelated' }));+ expect(shouldQueryUserInfo()).toBe(false);++ hasLoginCookie.mockReturnValue(true);+ window.dispatchEvent(+ new StorageEvent('storage', {+ key: 'macro:login',+ newValue: 'true',+ })+ );+ expect(shouldQueryUserInfo()).toBe(true);+});diff --git a/apps/web/src/lib/core/context/user-info-gate.ts b/apps/web/src/lib/core/context/user-info-gate.tsindex 9e08fc9ba4..1205d781dc 100644--- a/apps/web/src/lib/core/context/user-info-gate.ts+++ b/apps/web/src/lib/core/context/user-info-gate.ts@@ -1,8 +1,13 @@import { hasLoginCookie } from '@core/util/cookies';import { createSignal } from 'solid-js';+// Preview hosts share HttpOnly dev auth cookies on .macro.com, but not the+// host-only login hint or localStorage from dev.macro.com. Probe identity there+// even without a hint; account services still require confirmed authentication.const [shouldQueryUserInfo, setShouldQueryUserInfo] = createSignal(- hasLoginCookie()+ hasLoginCookie() ||+ (typeof window !== 'undefined' &&+ window.location.hostname.endsWith('.preview.macro.com')));export { shouldQueryUserInfo };@@ -10,3 +15,11 @@ export { shouldQueryUserInfo };export function enableUserInfoQuery() {setShouldQueryUserInfo(true);}++// A login popup or sibling tab updates the shared login marker. It is only a+// hint to check identity, never proof that account services may start.+if (typeof window !== 'undefined') {+ window.addEventListener('storage', () => {+ if (hasLoginCookie()) enableUserInfoQuery();+ });+}diff --git a/apps/web/src/lib/core/internal/BlockLoader.test.tsx b/apps/web/src/lib/core/internal/BlockLoader.test.tsxindex 7541da438e..ad30822365 100644--- a/apps/web/src/lib/core/internal/BlockLoader.test.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.test.tsx@@ -4,6 +4,8 @@ import { err, ok } from 'neverthrow';import { createEffect, createSignal, on, Show } from 'solid-js';import { afterEach, beforeEach, expect, it, vi } from 'vitest';+vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/block', () => ({createBlockSignal<T>() {const signal = createSignal<T>();diff --git a/apps/web/src/lib/core/internal/BlockLoader.tsx b/apps/web/src/lib/core/internal/BlockLoader.tsxindex 4aa79c56db..9a26d21f2c 100644--- a/apps/web/src/lib/core/internal/BlockLoader.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.tsx@@ -1,6 +1,7 @@import { useSharedAccessUpdates } from '@app/features/access-requests/access-requests';import { shareEntity } from '@app/features/access-requests/core/types';import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { useIsAuthenticated } from '@core/context/user';import type { OwnedBlockHandle } from '@core/orchestrator';import { Telemetry } from '@macro-inc/observability';import { useQueryClient } from '@queries/client';@@ -55,6 +56,7 @@ export function BlockLoader<L extends LoadFunction<D, P>,T extends BlockDefinition<D, BlockName, P, L>,>(props: BlockLoaderProps<D, P, L, T>): JSX.Element {+ const authenticated = useIsAuthenticated();const setData = blockDataSignal.set;const setError = blockErrorSignal.set;const setLiveTrackingEnabled = blockLiveTrackingEnabledSignal.set;@@ -201,6 +203,7 @@ Check that the load function does not return a preload source when the intent is// we need to pass in a client accessor since the mutation is dynamically imported outside a query context providerimport('./trackBlockOpened').then(({ track }) => {+ if (authenticated() !== true) return;track({itemId: props.id,blockName: data.__block,diff --git a/apps/web/src/lib/queries/auth/preview-user-info.test.tsx b/apps/web/src/lib/queries/auth/preview-user-info.test.tsxnew file mode 100644index 0000000000..f1d138106f--- /dev/null+++ b/apps/web/src/lib/queries/auth/preview-user-info.test.tsx@@ -0,0 +1,95 @@+import { UserContextProvider, useIsAuthenticated } from '@core/context/user';+import { hasLoginCookie } from '@core/util/cookies';+import { cleanup, render, screen } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { Show } from 'solid-js';+import { afterAll, afterEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => {+ vi.stubGlobal('location', new URL('https://branch.preview.macro.com/app'));+ return {+ fetch: vi.fn(),+ startAccountServices: vi.fn(),+ client: undefined as QueryClient | undefined,+ };+});+vi.mock('@service-auth/client', () => ({+ authServiceClient: { getLegacyUserPermissions: mocks.fetch },+}));+vi.mock('@core/auth/push-registration-lifecycle', () => ({+ syncPushRegistrations: vi.fn(),+}));+vi.mock('../client', () => ({+ get queryClient() {+ return mocks.client;+ },+ queryPersistence: { restoreQuery: vi.fn() },+}));++// Exercise the real bootstrap gate, query and auth context together. Mocking+// the gate concealed the fresh-preview regression in the original change.+import { useUserInfoQuery } from './user-info';++function AccountServices() {+ mocks.startAccountServices();+ return <span>Account services active</span>;+}++function Identity() {+ const authenticated = useIsAuthenticated();+ const query = useUserInfoQuery();+ return (+ <>+ <span>{query.isError ? 'Signed out' : 'Checking identity'}</span>+ <Show when={authenticated() === true}>+ <AccountServices />+ </Show>+ </>+ );+}++function mountIdentity() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ mocks.client = client;+ render(() => (+ <QueryClientProvider client={client}>+ <UserContextProvider>+ <Identity />+ </UserContextProvider>+ </QueryClientProvider>+ ));+}++afterEach(() => {+ cleanup();+ mocks.client?.clear();+ vi.clearAllMocks();+});+afterAll(() => vi.unstubAllGlobals());++it('discovers shared dev credentials without a preview marker and waits for confirmed identity', async () => {+ expect(hasLoginCookie()).toBe(false);+ const response = ok({ id: 'viewer', authenticated: true });+ const identity = Promise.withResolvers<typeof response>();+ mocks.fetch.mockReturnValue(identity.promise);+ mountIdentity();++ expect(mocks.fetch).toHaveBeenCalledOnce();+ expect(mocks.startAccountServices).not.toHaveBeenCalled();+ identity.resolve(response);+ expect(await screen.findByText('Account services active')).toBeTruthy();+ expect(mocks.startAccountServices).toHaveBeenCalledOnce();+ expect(mocks.fetch).toHaveBeenCalledOnce();+});++it('keeps account services stopped when the preview has no valid dev credentials', async () => {+ mocks.fetch.mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]));+ mountIdentity();++ expect(await screen.findByText('Signed out')).toBeTruthy();+ expect(mocks.fetch).toHaveBeenCalledOnce();+ expect(mocks.startAccountServices).not.toHaveBeenCalled();+});diff --git a/apps/web/src/lib/queries/auth/user-info-gate.test.tsx b/apps/web/src/lib/queries/auth/user-info-gate.test.tsxnew file mode 100644index 0000000000..34b423943b--- /dev/null+++ b/apps/web/src/lib/queries/auth/user-info-gate.test.tsx@@ -0,0 +1,65 @@+import { cleanup, render, screen } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import { createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';++const [enabled, setEnabled] = createSignal(false);+const mocks = vi.hoisted(() => ({+ fetch: vi.fn(),+ client: undefined as QueryClient | undefined,+}));+vi.mock('@core/context/user-info-gate', () => ({+ shouldQueryUserInfo: () => enabled(),+ enableUserInfoQuery: () => setEnabled(true),+}));+vi.mock('@service-auth/client', () => ({+ authServiceClient: { getLegacyUserPermissions: mocks.fetch },+}));+vi.mock('@core/auth/push-registration-lifecycle', () => ({+ syncPushRegistrations: vi.fn(),+}));+vi.mock('../client', () => ({+ get queryClient() {+ return mocks.client;+ },+ queryPersistence: { restoreQuery: vi.fn() },+}));++import { invalidateUserInfo, useUserInfoQuery } from './user-info';++afterEach(() => {+ cleanup();+ mocks.client?.clear();+ setEnabled(false);+ vi.clearAllMocks();+});++it('observes the anonymous session without fetching until login enables identity checks', async () => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ mocks.client = client;+ mocks.fetch.mockResolvedValue(ok({ id: 'viewer', authenticated: true }));+ function Identity() {+ const query = useUserInfoQuery();+ return (+ <span>+ {query.isSuccess && query.data.authenticated+ ? 'Signed in'+ : 'Anonymous'}+ </span>+ );+ }+ render(() => (+ <QueryClientProvider client={client}>+ <Identity />+ </QueryClientProvider>+ ));+ expect(screen.getByText('Anonymous')).toBeTruthy();+ expect(mocks.fetch).not.toHaveBeenCalled();++ await invalidateUserInfo();+ expect(await screen.findByText('Signed in')).toBeTruthy();+ expect(mocks.fetch).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.tsindex ad5a8041bd..6cf49b916b 100644--- a/apps/web/src/lib/queries/auth/user-info.ts+++ b/apps/web/src/lib/queries/auth/user-info.ts@@ -1,5 +1,8 @@import { syncPushRegistrations } from '@core/auth/push-registration-lifecycle';-import { enableUserInfoQuery } from '@core/context/user-info-gate';+import {+ enableUserInfoQuery,+ shouldQueryUserInfo,+} from '@core/context/user-info-gate';import { hasLoginCookie } from '@core/util/cookies';import { fireAndForget } from '@core/util/fireAndForget';import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';@@ -53,7 +56,7 @@ export function useUserInfoQuery(options?: UseUserInfoQueryOptions) {userInfoQueryOptions(typeof options?.enabled === 'function'? options.enabled()- : (options?.enabled ?? true)+ : (options?.enabled ?? shouldQueryUserInfo())));}diff --git a/apps/web/src/lib/queries/channel/activity.ts b/apps/web/src/lib/queries/channel/activity.tsindex ce276f5748..738a6e2d9e 100644--- a/apps/web/src/lib/queries/channel/activity.ts+++ b/apps/web/src/lib/queries/channel/activity.ts@@ -6,16 +6,20 @@ import type { ActivityType } from '@service-storage/generated/schemas/activityTyimport type { ApiActivity as ChannelsActivity } from '@service-storage/generated/schemas/apiActivity';import { recordChannelActivity } from '@service-storage/graphql-channel-activity';import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';import { channelKeys } from './keys';function fetchChannelsActivity() {return throwOnErr(storageServiceClient.getActivity);}-export function useChannelsActivityQuery() {+export function useChannelsActivityQuery(+ enabled: Accessor<boolean> = () => true+) {return useQuery(() => ({queryKey: channelKeys.activity.queryKey,queryFn: fetchChannelsActivity,+ enabled: enabled(),}));}diff --git a/apps/web/src/lib/queries/channel/channels.ts b/apps/web/src/lib/queries/channel/channels.tsindex c025bae477..73b22011f1 100644--- a/apps/web/src/lib/queries/channel/channels.ts+++ b/apps/web/src/lib/queries/channel/channels.ts@@ -51,8 +51,8 @@ const listChannelsQueryOptions = queryOptions({queryFn: ({ signal }) => fetchAllChannels(signal),});-export function useListChannelsQuery() {- return useQuery(() => listChannelsQueryOptions);+export function useListChannelsQuery(enabled: Accessor<boolean> = () => true) {+ return useQuery(() => ({ ...listChannelsQueryOptions, enabled: enabled() }));}// The host is an app-level cache service, not component state; the keydiff --git a/apps/web/src/lib/queries/contacts/contacts.ts b/apps/web/src/lib/queries/contacts/contacts.tsindex be0e81839e..09a7292892 100644--- a/apps/web/src/lib/queries/contacts/contacts.ts+++ b/apps/web/src/lib/queries/contacts/contacts.ts@@ -1,3 +1,4 @@+import { useIsAuthenticated } from '@core/context/user';import type { IUser } from '@core/user/types';import { idToDisplayName, idToEmail } from '@core/user/util';import { throwOnErr } from '@core/util/result';@@ -16,7 +17,11 @@ export function contactsQueryOptions() {/** The raw contacts query — for callers that need its loading state. */export function useContactsQuery(enabled: Accessor<boolean> = () => true) {- return useQuery(() => ({ ...contactsQueryOptions(), enabled: enabled() }));+ const authenticated = useIsAuthenticated();+ return useQuery(() => ({+ ...contactsQueryOptions(),+ enabled: authenticated() === true && enabled(),+ }));}/**@@ -26,9 +31,10 @@ export function useContactsQuery(enabled: Accessor<boolean> = () => true) {export function useContacts(enabled: Accessor<boolean> = () => true): Accessor<IUser[]> {+ const authenticated = useIsAuthenticated();const query = useContactsQuery(enabled);return createMemo(() => {- if (!query.isSuccess) return [];+ if (authenticated() !== true || !query.isSuccess) return [];const contacts = query.data.contacts;return contacts.map((c) => ({id: c,diff --git a/apps/web/src/lib/queries/email/link-selection.test.tsx b/apps/web/src/lib/queries/email/link-selection.test.tsxindex f3695adaa0..dd4767469c 100644--- a/apps/web/src/lib/queries/email/link-selection.test.tsx+++ b/apps/web/src/lib/queries/email/link-selection.test.tsx@@ -19,7 +19,10 @@ vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));vi.mock('@queries/soup/normalized-cache', () => ({invalidateAllSoup: vi.fn(),}));-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|self',+ useIsAuthenticated: () => () => true,+}));vi.mock('@queries/client', () => ({ queryClient: {} }));const link = (id: string, owner: string, primary: boolean): Link => ({diff --git a/apps/web/src/lib/queries/email/link.test.tsx b/apps/web/src/lib/queries/email/link.test.tsxindex 395eaab2c8..26d731a5cf 100644--- a/apps/web/src/lib/queries/email/link.test.tsx+++ b/apps/web/src/lib/queries/email/link.test.tsx@@ -1,22 +1,30 @@import type { Link as EmailLink } from '@service-email/generated/schemas';-import { cleanup, render, screen } from '@solidjs/testing-library';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import { onlineManager } from '@tanstack/query-core';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { err, type Ok, ok } from 'neverthrow';-import { Suspense } from 'solid-js';+import { createSignal, Suspense } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { emailKeys } from './keys';-import { useDisableCalendarMutation, usePrimaryEmailLinkId } from './link';+import {+ useDisableCalendarMutation,+ useEmailLinksQuery,+ useInboxHealthProbeQuery,+ usePrimaryEmailLinkId,+} from './link';import { mountEmailMutation } from './tests/mutation';const disableLinkCalendarMock = vi.hoisted(() => vi.fn());const getLinksMock = vi.hoisted(() => vi.fn());+const healthCheckMock = vi.hoisted(() => vi.fn());+const [authenticated, setAuthenticated] = createSignal(true);const invalidateCalendarViewsMock = vi.hoisted(() => vi.fn());vi.mock('@service-email/client', () => ({emailClient: {disableLinkCalendar: disableLinkCalendarMock,getLinks: getLinksMock,+ healthCheckLinks: healthCheckMock,},}));@@ -28,7 +36,10 @@ vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));vi.mock('@queries/soup/normalized-cache', () => ({invalidateAllSoup: vi.fn(),}));-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|self',+ useIsAuthenticated: () => authenticated,+}));let testQueryClient: QueryClient;@@ -88,6 +99,7 @@ it('does not suspend an offline composer when its primary-inbox lookup resumes',});beforeEach(() => {+ setAuthenticated(true);vi.clearAllMocks();testQueryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -97,6 +109,45 @@ beforeEach(() => {});});+it('starts account lookups and health probes only after sign-in and stops on logout', async () => {+ testQueryClient.clear();+ setAuthenticated(false);+ getLinksMock.mockResolvedValue(ok({ links: [] }));+ healthCheckMock.mockResolvedValue(ok({}));+ function Account() {+ const links = useEmailLinksQuery();+ const health = useInboxHealthProbeQuery();+ return (+ <>+ <button onClick={() => setAuthenticated(true)}>Sign in</button>+ <button onClick={() => setAuthenticated(false)}>Sign out</button>+ <span>+ {authenticated() && links.isSuccess && health.isSuccess+ ? 'Connected'+ : 'Anonymous'}+ </span>+ </>+ );+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Account />+ </QueryClientProvider>+ ));+ expect(screen.getByText('Anonymous')).toBeTruthy();+ expect(getLinksMock).not.toHaveBeenCalled();+ expect(healthCheckMock).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));+ expect(await screen.findByText('Connected')).toBeTruthy();+ expect(getLinksMock).toHaveBeenCalledOnce();+ expect(healthCheckMock).toHaveBeenCalledOnce();+ fireEvent.click(screen.getByRole('button', { name: 'Sign out' }));+ await testQueryClient.invalidateQueries();+ expect(screen.getByText('Anonymous')).toBeTruthy();+ expect(getLinksMock).toHaveBeenCalledOnce();+ expect(healthCheckMock).toHaveBeenCalledOnce();+});+describe('useDisableCalendarMutation', () => {it('does not offer re-enable while the server is still deleting calendar data', async () => {let finish!: (value: Ok<Record<string, never>, never>) => void;diff --git a/apps/web/src/lib/queries/email/link.ts b/apps/web/src/lib/queries/email/link.tsindex c3828aeb18..087c84af3a 100644--- a/apps/web/src/lib/queries/email/link.ts+++ b/apps/web/src/lib/queries/email/link.ts@@ -1,4 +1,4 @@-import { useUserId } from '@core/context/user';+import { useIsAuthenticated, useUserId } from '@core/context/user';import { fireAndForget } from '@core/util/fireAndForget';import { throwOnErr } from '@core/util/result';import { Telemetry } from '@macro-inc/observability';@@ -30,9 +30,11 @@ const queryEnabled = () => true;* prompt — nothing renders from this query.*/export function useInboxHealthProbeQuery() {+ const authenticated = useIsAuthenticated();return useQuery(() => ({queryKey: emailKeys.linksHealthProbe.queryKey,queryFn: probeInboxHealth,+ enabled: authenticated() === true,staleTime: HEALTH_PROBE_STALE_TIME,refetchOnWindowFocus: true,retry: false,@@ -49,10 +51,11 @@ function fetchEmailLinks() {}export function useEmailLinksQuery(enabled: Accessor<boolean> = queryEnabled) {+ const authenticated = useIsAuthenticated();return useQuery(() => ({queryKey: emailKeys.links.queryKey,queryFn: fetchEmailLinks,- enabled: enabled(),+ enabled: authenticated() === true && enabled(),staleTime: LINK_STALE_TIME,refetchOnWindowFocus: 'always',}));diff --git a/apps/web/src/lib/queries/favorites/favorites.test.tsx b/apps/web/src/lib/queries/favorites/favorites.test.tsxindex 0a36565f55..2f0dac3894 100644--- a/apps/web/src/lib/queries/favorites/favorites.test.tsx+++ b/apps/web/src/lib/queries/favorites/favorites.test.tsx@@ -30,6 +30,8 @@ const mocks = vi.hoisted(() => ({reorderFavoritesRest: vi.fn(),}));+vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/constant/featureFlags', () => ({enableGraphqlSoup: { key: 'enable-graphql-soup' },isFeatureEnabled: mocks.graphqlSoupEnabled,@@ -190,7 +192,10 @@ describe('favorites transport', () => {const filter: FavoritesFilter = { entityType: ['channel'] };renderHook(() => useFavoritesData(filter));- expect(mocks.createGraphqlFavoritesQuery).toHaveBeenCalledWith(filter);+ expect(mocks.createGraphqlFavoritesQuery).toHaveBeenCalledWith(+ filter,+ expect.any(Function)+ );expect(mocks.getFavoritesRest).not.toHaveBeenCalled();});diff --git a/apps/web/src/lib/queries/favorites/favorites.ts b/apps/web/src/lib/queries/favorites/favorites.tsindex c126c90b8e..5211902e20 100644--- a/apps/web/src/lib/queries/favorites/favorites.ts+++ b/apps/web/src/lib/queries/favorites/favorites.ts@@ -2,6 +2,7 @@ import {enableGraphqlSoup,isFeatureEnabled,} from '@core/constant/featureFlags';+import { useIsAuthenticated } from '@core/context/user';import { throwOnErr } from '@core/util/result';import type { EntityData } from '@entity';import { storageServiceClient } from '@service-storage/client';@@ -78,11 +79,13 @@ function favoriteEntityKey(/** The user's favorites from the transport selected at hook creation. */export function useFavoritesQuery(filter?: FavoritesFilter) {+ const authenticated = useIsAuthenticated();+ const enabled = () => authenticated() === true;if (isFeatureEnabled(enableGraphqlSoup)) {- return createGraphqlFavoritesQuery(filter);+ return createGraphqlFavoritesQuery(filter, enabled);}- return createRestFavoritesQuery(filter);+ return createRestFavoritesQuery(filter, enabled);}// Cached callbacks outlive the hook; only the plain filter enters this closure.@@ -97,8 +100,14 @@ function restFavoritesQueryOptions(filter?: FavoritesFilter) {});}-function createRestFavoritesQuery(filter?: FavoritesFilter) {- return useQuery(() => restFavoritesQueryOptions(filter));+function createRestFavoritesQuery(+ filter: FavoritesFilter | undefined,+ enabled: Accessor<boolean>+) {+ return useQuery(() => ({+ ...restFavoritesQueryOptions(filter),+ enabled: enabled(),+ }));}/**@@ -114,12 +123,14 @@ function createRestFavoritesQuery(filter?: FavoritesFilter) {export function useFavoritesData(filter?: FavoritesFilter): Accessor<FavoritesList | undefined> {+ const authenticated = useIsAuthenticated();+ const enabled = () => authenticated() === true;if (isFeatureEnabled(enableGraphqlSoup)) {- const query = createGraphqlFavoritesQuery(filter);- return () => query.data;+ const query = createGraphqlFavoritesQuery(filter, enabled);+ return () => (enabled() ? query.data : undefined);}- const query = createRestFavoritesQuery(filter);- return () => (query.isSuccess ? query.data : undefined);+ const query = createRestFavoritesQuery(filter, enabled);+ return () => (enabled() && query.isSuccess ? query.data : undefined);}function readLists() {diff --git a/apps/web/src/lib/queries/favorites/graphql.test.tsx b/apps/web/src/lib/queries/favorites/graphql.test.tsxindex 00f75eebc9..6c0b7f4b61 100644--- a/apps/web/src/lib/queries/favorites/graphql.test.tsx+++ b/apps/web/src/lib/queries/favorites/graphql.test.tsx@@ -10,6 +10,8 @@ vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: getGraphqlSoupClientMock,}));+vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/constant/featureFlags', () => ({enableGraphqlSoup: {},isFeatureEnabled: () => true,diff --git a/apps/web/src/lib/queries/favorites/graphql.ts b/apps/web/src/lib/queries/favorites/graphql.tsindex f791dd84e2..d5c02161c2 100644--- a/apps/web/src/lib/queries/favorites/graphql.ts+++ b/apps/web/src/lib/queries/favorites/graphql.ts@@ -30,7 +30,7 @@ import {} from '@service-storage/graphql-favorites';import { getGraphqlSoupClient } from '@service-storage/graphql-soup';import type { AnyVariables, Client, OperationResult } from '@urql/core';-import { onCleanup } from 'solid-js';+import { type Accessor, onCleanup } from 'solid-js';import type { FavoriteMutationCallbacks } from './mutation';type GraphqlReorderFavoritesArgs = { favorites: SetFavoriteArgs[] };@@ -103,7 +103,8 @@ function activeFavoritesCacheTargets(/** Creates the live urql-solid favorites query. */export function createGraphqlFavoritesQuery(- filter?: ListFavoritesParams+ filter?: ListFavoritesParams,+ enabled: Accessor<boolean> = () => true): GraphqlFavoritesQuery {const variables = favoritesQueryVariables(filter);const query = createUrqlQuery<@@ -112,6 +113,7 @@ export function createGraphqlFavoritesQuery(FavoritesList>(() => ({query: FavoritesDocument,+ enabled: enabled(),client: getGraphqlSoupClient(),variables,requestPolicy: 'cache-and-network',diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.tsindex 11a5871bfc..7015be1b27 100644--- a/apps/web/src/lib/queries/history/history.ts+++ b/apps/web/src/lib/queries/history/history.ts@@ -1,5 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableGraphqlSoup } from '@core/constant/featureFlags';+import { useIsAuthenticated } from '@core/context/user';import { catchToResult, throwOnErr } from '@core/util/result';import { type MutationCallbacks, withCallbacks } from '@queries/utils';import {@@ -126,10 +127,12 @@ const restHistoryQueryOptions = {};export function useHistoryQuery() {+ const authenticated = useIsAuthenticated();const graphqlSoupFlag = useFeatureFlag(enableGraphqlSoup);const activeQueryClient = useQueryClient();const graphqlCacheHost = () => {- if (!graphqlSoupFlag().enabled) return undefined;+ if (authenticated() !== true || !graphqlSoupFlag().enabled)+ return undefined;const cacheHost = getGraphqlSoupCacheHost();return cacheHost?.disabled ? undefined : cacheHost;};@@ -157,9 +160,12 @@ export function useHistoryQuery() {HistoryQueryKey>(() => {const cacheHost = graphqlCacheHost();- return cacheHost- ? cachedGraphqlHistoryQueryOptions(cacheHost)- : restHistoryQueryOptions;+ return {+ ...(cacheHost+ ? cachedGraphqlHistoryQueryOptions(cacheHost)+ : restHistoryQueryOptions),+ enabled: authenticated() === true,+ };});}diff --git a/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx b/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsxindex 16e5e022d4..eaf7c3df60 100644--- a/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx+++ b/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({vi.mock('@app/lib/analytics/posthog', () => ({useFeatureFlag: () => () => ({ enabled: true }),}));+vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/constant/featureFlags', () => ({ enableGraphqlSoup: {} }));vi.mock('@core/constant/allBlocks', () => ({itemToSafeName: (item: { name: string }) => item.name,diff --git a/apps/web/src/lib/queries/notification/unsubscribes.ts b/apps/web/src/lib/queries/notification/unsubscribes.tsindex da2e34bda5..512eeb3d51 100644--- a/apps/web/src/lib/queries/notification/unsubscribes.ts+++ b/apps/web/src/lib/queries/notification/unsubscribes.ts@@ -3,6 +3,7 @@ import { throwOnErr } from '@core/util/result';import { notificationServiceClient } from '@service-notification/client';import type { UserUnsubscribe } from '@service-notification/generated/schemas/userUnsubscribe';import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';import { queryClient } from '../client';import { notificationKeys } from './keys';@@ -26,13 +27,17 @@ async function fetchUnsubscribes() {return response.value.data;}-export function useMutedEntitiesQuery(args?: { limit?: number }) {+export function useMutedEntitiesQuery(+ args?: { limit?: number },+ enabled: Accessor<boolean> = () => true+) {const limit =args?.limit && args.limit > 0 && args.limit <= 500 ? args.limit : 20;return useQuery(() => ({queryKey: notificationKeys.unsubscribes.queryKey,queryFn: fetchUnsubscribes,+ enabled: enabled(),initialPageParam: { limit },staleTime: 1000 * 60 * 5,gcTime: 1000 * 60 * 10,diff --git a/apps/web/src/lib/queries/properties/definitions.ts b/apps/web/src/lib/queries/properties/definitions.tsindex a411d0cba5..ba40e919fa 100644--- a/apps/web/src/lib/queries/properties/definitions.ts+++ b/apps/web/src/lib/queries/properties/definitions.ts@@ -1,4 +1,5 @@import { toast } from '@core/component/Toast/Toast';+import { useIsAuthenticated } from '@core/context/user';import { throwOnErr } from '@core/util/result';import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';@@ -46,7 +47,10 @@ export function useListPropertiesQuery(params: Accessor<ListPropertiesQueryParams>,enabled: Accessor<boolean> = () => true) {- return useQuery(() => listPropertiesQueryOptions(params(), enabled()));+ const authenticated = useIsAuthenticated();+ return useQuery(() =>+ listPropertiesQueryOptions(params(), authenticated() === true && enabled())+ );}export async function fetchPropertyDefinitionWithOptions(diff --git a/apps/web/src/lib/queries/storage/attachment-references.ts b/apps/web/src/lib/queries/storage/attachment-references.tsindex 9e63df65e9..658762491c 100644--- a/apps/web/src/lib/queries/storage/attachment-references.ts+++ b/apps/web/src/lib/queries/storage/attachment-references.ts@@ -1,3 +1,4 @@+import { useIsAuthenticated } from '@core/context/user';import { throwOnErr } from '@core/util/result';import {type ItemType,@@ -49,7 +50,11 @@ export function useAttachmentReferencesQuery(entityId: Accessor<string | null | undefined>,entityType: Accessor<ItemType>) {+ const authenticated = useIsAuthenticated();return useQuery(() =>- attachmentReferencesQueryOptions(entityType(), entityId())+ attachmentReferencesQueryOptions(+ entityType(),+ authenticated() === true ? entityId() : undefined+ ));}diff --git a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.tsindex d424e08153..6eade87efc 100644--- a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts+++ b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts@@ -37,6 +37,7 @@ vi.mock('@core/auth/push-registration-lifecycle', () => ({}));vi.mock('@core/context/user-info-gate', () => ({enableUserInfoQuery: vi.fn(),+ shouldQueryUserInfo: () => true,}));vi.mock('@service-auth/client', () => ({authServiceClient: { getLegacyUserPermissions: mocks.userInfo },diff --git a/apps/web/src/lib/queries/storage/instructions-md.ts b/apps/web/src/lib/queries/storage/instructions-md.tsindex 747606fe15..899f9324fd 100644--- a/apps/web/src/lib/queries/storage/instructions-md.ts+++ b/apps/web/src/lib/queries/storage/instructions-md.ts@@ -4,6 +4,7 @@ import {initializeEditorWithState,} from '@core/component/LexicalMarkdown/utils';+import { useIsAuthenticated } from '@core/context/user';import { storageServiceClient } from '@service-storage/client';import { syncServiceClient } from '@service-sync/client';import { useQuery } from '@tanstack/solid-query';@@ -50,7 +51,11 @@ function instructionsMdIdQueryOptions() {* Returns null if not yet created, throws otherwise.*/export function useInstructionsMdIdQuery() {- return useQuery(() => instructionsMdIdQueryOptions());+ const authenticated = useIsAuthenticated();+ return useQuery(() => ({+ ...instructionsMdIdQueryOptions(),+ enabled: authenticated() === true,+ }));}const getInstructionsMdText = async (id: string | null | undefined) => {@@ -96,10 +101,14 @@ function instructionsMdTextQueryOptions(/** useQuery hook for retrieving the instructions md document text content */export function useInstructionsMdTextQuery() {+ const authenticated = useIsAuthenticated();const idQuery = useInstructionsMdIdQuery();return useQuery(() =>- instructionsMdTextQueryOptions(idQuery.data, idQuery.isSuccess)+ instructionsMdTextQueryOptions(+ authenticated() === true && idQuery.isSuccess ? idQuery.data : undefined,+ authenticated() === true && idQuery.isSuccess+ ));}diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.tsindex 835d5d3006..663366bcc5 100644--- a/apps/web/src/lib/queries/team/teams.ts+++ b/apps/web/src/lib/queries/team/teams.ts@@ -1,5 +1,5 @@import { toast } from '@core/component/Toast/Toast';-import { useUserId } from '@core/context/user';+import { useIsAuthenticated, useUserId } from '@core/context/user';import { fireAndForget } from '@core/util/fireAndForget';import { ThrownResultError, throwOnErr } from '@core/util/result';import {@@ -46,10 +46,11 @@ export function useTeamQuery(teamId: Accessor<string>) {/** The current user's team, or `null` if they don't belong to one. */export function useCurrentTeamQuery(enabled?: Accessor<boolean>) {+ const authenticated = useIsAuthenticated();return useQuery(() => ({queryKey: teamKeys.currentTeam.queryKey,queryFn: fetchTeam,- enabled: enabled?.() ?? true,+ enabled: authenticated() === true && (enabled?.() ?? true),}));}diff --git a/apps/web/src/lib/service-clients/service-connection/README.md b/apps/web/src/lib/service-clients/service-connection/README.mdindex e649a8c4a2..63b7486ee8 100644--- a/apps/web/src/lib/service-clients/service-connection/README.md+++ b/apps/web/src/lib/service-clients/service-connection/README.md@@ -2,3 +2,11 @@App-local client and generated bindings for the connection service. Install,test, and regenerate it through `apps/web`.++`subscribeToStreamState` runs under the consuming row's Solid owner. It retains+stream-state subscriptions for mounted consumers, sends each entity once per+connection, and replays them on the gateway's first open and every reconnect.+Pending subscriptions are not socket-buffered. Multiple mounted rows share a+subscription; disposing the last consumer removes it from future replays.+The protocol has no unsubscribe frame, so remounting on the same connection+reuses its existing server subscription.diff --git a/apps/web/src/lib/service-clients/service-connection/stream-events.test.ts b/apps/web/src/lib/service-clients/service-connection/stream-events.test.tsnew file mode 100644index 0000000000..9bb6d85c3b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-connection/stream-events.test.ts@@ -0,0 +1,164 @@+import {+ ArrayQueue,+ JsonSerializer,+ WebsocketBuilder,+} from '@macro-inc/collaboration/websocket';+import { createRoot } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ToWebsocketMessage } from './generated/schemas/toWebsocketMessage';+import type {+ ConnectionGatewayWebsocket,+ FromWebsocketMessage,+} from './websocket';++const mocks = vi.hoisted(() => ({+ ws: undefined as ConnectionGatewayWebsocket | undefined,+}));+vi.mock('./websocket', () => ({+ get ws() {+ if (!mocks.ws) throw new Error('Missing test gateway');+ return mocks.ws;+ },+ createConnectionWebsocketEffect: vi.fn(),+}));++class TestSocket extends EventTarget {+ readonly CONNECTING = 0;+ readonly OPEN = 1;+ readonly CLOSING = 2;+ readonly CLOSED = 3;+ binaryType: BinaryType = 'blob';+ bufferedAmount = 0;+ extensions = '';+ protocol = '';+ url = 'ws://unused';+ readyState: number = this.CONNECTING;+ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;+ send = vi.fn();++ open() {+ this.readyState = this.OPEN;+ this.dispatchEvent(new Event('open'));+ }++ close() {+ this.readyState = this.CLOSED;+ this.dispatchEvent(new CloseEvent('close'));+ }+}++let nextSocket = Promise.withResolvers<TestSocket>();+const disposers: (() => void)[] = [];++beforeEach(() => {+ vi.resetModules();+ nextSocket = Promise.withResolvers<TestSocket>();+ mocks.ws = new WebsocketBuilder('ws://unused')+ .withAutoConnect(false)+ .withSerializer(+ new JsonSerializer<ToWebsocketMessage, FromWebsocketMessage>()+ )+ .withBuffer(new ArrayQueue())+ .withFactory(() => {+ const socket = new TestSocket();+ nextSocket.resolve(socket);+ return socket;+ })+ .build();+});+afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+ mocks.ws?.close();+});++it('sends pre-activation and connecting subscriptions once on open, then replays on reconnect', async () => {+ const { subscribeToStreamState } = await import('./stream-events');+ createRoot((dispose) => {+ disposers.push(dispose);+ subscribeToStreamState('before-activation', 'chat');+ subscribeToStreamState('not-streamable', 'document');+ });+ const disposeBeforeActivation = createRoot((dispose) => {+ subscribeToStreamState('already-unmounted', 'chat');+ return dispose;+ });+ disposeBeforeActivation();+ mocks.ws?.reconnect();+ const first = await nextSocket.promise;+ createRoot((dispose) => {+ disposers.push(dispose);+ subscribeToStreamState('while-connecting', 'chat');+ subscribeToStreamState('before-activation', 'chat');+ });+ expect(first.send).not.toHaveBeenCalled();+ first.open();+ expect(first.send.mock.calls).toEqual([+ [+ JSON.stringify({+ type: 'stream_events',+ entity_id: 'before-activation',+ entity_type: 'chat',+ }),+ ],+ [+ JSON.stringify({+ type: 'stream_events',+ entity_id: 'while-connecting',+ entity_type: 'chat',+ }),+ ],+ ]);++ nextSocket = Promise.withResolvers<TestSocket>();+ first.close();+ mocks.ws?.reconnect();+ const second = await nextSocket.promise;+ second.open();+ expect(second.send.mock.calls).toEqual(first.send.mock.calls);+});++it('keeps shared subscriptions while mounted and drops them from replay after the last consumer leaves', async () => {+ const { subscribeToStreamState } = await import('./stream-events');+ mocks.ws?.reconnect();+ const first = await nextSocket.promise;+ first.open();+ const disposeFirst = createRoot((dispose) => {+ disposers.push(dispose);+ subscribeToStreamState('shared-chat', 'chat');+ return dispose;+ });+ const disposeSecond = createRoot((dispose) => {+ disposers.push(dispose);+ subscribeToStreamState('shared-chat', 'chat');+ return dispose;+ });+ expect(first.send).toHaveBeenCalledOnce();+ disposeFirst();++ nextSocket = Promise.withResolvers<TestSocket>();+ first.close();+ mocks.ws?.reconnect();+ const second = await nextSocket.promise;+ second.open();+ expect(second.send.mock.calls).toEqual(first.send.mock.calls);+ disposeSecond();+ const disposeRemount = createRoot((dispose) => {+ disposers.push(dispose);+ subscribeToStreamState('shared-chat', 'chat');+ return dispose;+ });+ // The server has no unsubscribe frame: remounting must not create a second+ // subscription on the same connection, even after every consumer unmounted.+ expect(second.send).toHaveBeenCalledOnce();+ disposeRemount();++ nextSocket = Promise.withResolvers<TestSocket>();+ second.close();+ mocks.ws?.reconnect();+ const third = await nextSocket.promise;+ third.open();+ expect(third.send).not.toHaveBeenCalled();+});diff --git a/apps/web/src/lib/service-clients/service-connection/stream-events.ts b/apps/web/src/lib/service-clients/service-connection/stream-events.tsindex 5af85121f7..c786f1e4d2 100644--- a/apps/web/src/lib/service-clients/service-connection/stream-events.ts+++ b/apps/web/src/lib/service-clients/service-connection/stream-events.ts@@ -1,14 +1,39 @@import type { EntityData } from '@entity';-import type { Accessor } from 'solid-js';+import {+ WebsocketConnectionState,+ WebsocketEvent,+} from '@macro-inc/collaboration/websocket';+import { type Accessor, onCleanup } from 'solid-js';import { createStore } from 'solid-js/store';import type { StreamEvent } from './generated/schemas';-import { isStreamEntity } from './stream';+import { isStreamEntity, type StreamType } from './stream';import { createConnectionWebsocketEffect, ws } from './websocket';const [streamState, setStreamState] = createStore<Record<string, StreamEvent>>({});-const subscribed = new Set<string>();+const subscribed = new Map<+ string,+ { type: keyof StreamType; consumers: number }+>();+const sent = new Set<string>();++function sendStreamSubscription(+ entity_id: string,+ entity_type: keyof StreamType+) {+ // Replay owns pending subscriptions; buffering would send them twice on open.+ if (ws.readyState !== WebsocketConnectionState.Open || sent.has(entity_id))+ return;+ if (ws.send({ type: 'stream_events', entity_id, entity_type }))+ sent.add(entity_id);+}++ws.addEventListener(WebsocketEvent.Open, () => {+ sent.clear();+ for (const [id, subscription] of subscribed)+ sendStreamSubscription(id, subscription.type);+});createConnectionWebsocketEffect((data) => {if (data.type !== 'stream_event') return;@@ -30,11 +55,15 @@ export function subscribeToStreamState(entity_id: string,entity_type: EntityData['type']) {- if (!isStreamEntity(entity_type) || subscribed.has(entity_id)) return;- subscribed.add(entity_id);- ws.send({- type: 'stream_events',- entity_id,- entity_type: entity_type,+ if (!isStreamEntity(entity_type)) return;+ const subscription = subscribed.get(entity_id) ?? {+ type: entity_type,+ consumers: 0,+ };+ subscription.consumers++;+ subscribed.set(entity_id, subscription);+ sendStreamSubscription(entity_id, entity_type);+ onCleanup(() => {+ if (--subscription.consumers === 0) subscribed.delete(entity_id);});}diff --git a/apps/web/src/lib/service-clients/service-connection/websocket.ts b/apps/web/src/lib/service-clients/service-connection/websocket.tsindex 6092aa958e..cea45c78bb 100644--- a/apps/web/src/lib/service-clients/service-connection/websocket.ts+++ b/apps/web/src/lib/service-clients/service-connection/websocket.ts@@ -13,6 +13,7 @@ import {import { createWebsocketStateSignal } from '@macro-inc/collaboration/websocket/solid/state-signal';import { getMacroApiToken } from '@service-auth/fetch';import { createCallback } from '@solid-primitives/rootless';+import { createSessionWebsocketTelemetry } from '../session-websocket-telemetry';import type { ToWebsocketMessage } from './generated/schemas/toWebsocketMessage';import { instrumentGatewaySocket } from './presence-telemetry';@@ -41,13 +42,23 @@ async function resolveWsUrl() {return wsHost;}-export const ws = new WebsocketBuilder(resolveWsUrl)+export const connectionGatewaySessionTelemetry =+ createSessionWebsocketTelemetry('connection-gateway', resolveWsUrl);++export const ws = new WebsocketBuilder(+ connectionGatewaySessionTelemetry.resolveUrl+)+ .withAutoConnect(false).withSerializer(new JsonSerializer<ToWebsocketMessage, FromWebsocketMessage>()).withBuffer(new ArrayQueue()).withBackoff(new LinearBackoff(500, 500)).withMaxRetries(20)+ .onOpen(connectionGatewaySessionTelemetry.opened)+ .onError(connectionGatewaySessionTelemetry.failed)+ .onClose((_, event) => connectionGatewaySessionTelemetry.closed(event))+ .onRetry((_, event) => connectionGatewaySessionTelemetry.retry(event.detail)).withHeartbeat({interval: 1_000,timeout: 1_000,diff --git a/apps/web/src/lib/service-clients/service-storage/websocket.ts b/apps/web/src/lib/service-clients/service-storage/websocket.tsindex 34dfede1d8..918882fa5f 100644--- a/apps/web/src/lib/service-clients/service-storage/websocket.ts+++ b/apps/web/src/lib/service-clients/service-storage/websocket.ts@@ -8,6 +8,7 @@ import {import { createWebsocketStateSignal } from '@macro-inc/collaboration/websocket/solid/state-signal';import { createEffect, createSignal, onCleanup } from 'solid-js';import { v7 as uuidv7 } from 'uuid';+import { createSessionWebsocketTelemetry } from '../session-websocket-telemetry';/*** The interval in milliseconds to send a heartbeat message to the server.@@ -20,9 +21,19 @@ const HEARTBEAT_INTERVAL = 300000;*/const HEARTBEAT_TIMEOUT = 5000;-const ws = new WebsocketBuilder(SERVER_HOSTS['websocket-service'])+export const storageSessionTelemetry = createSessionWebsocketTelemetry(+ 'storage',+ () => SERVER_HOSTS['websocket-service']+);++const ws = new WebsocketBuilder(storageSessionTelemetry.resolveUrl)+ .withAutoConnect(false).withBackoff(new ConstantBackoff(2_000)).withMaxRetries(20)+ .onOpen(storageSessionTelemetry.opened)+ .onError(storageSessionTelemetry.failed)+ .onClose((_, event) => storageSessionTelemetry.closed(event))+ .onRetry((_, event) => storageSessionTelemetry.retry(event.detail)).withHeartbeat({pingMessage: JSON.stringify({ action: 'wsping' }),pongMessage: 'pong',diff --git a/apps/web/src/lib/service-clients/session-websocket-telemetry.test.ts b/apps/web/src/lib/service-clients/session-websocket-telemetry.test.tsnew file mode 100644index 0000000000..f65d55b219--- /dev/null+++ b/apps/web/src/lib/service-clients/session-websocket-telemetry.test.ts@@ -0,0 +1,157 @@+import type { Span } from '@macro-inc/observability';+import { expect, it, vi } from 'vitest';+import { createSessionWebsocketTelemetry } from './session-websocket-telemetry';++class RecordedSpan implements Span {+ static active: RecordedSpan | undefined;+ children: RecordedSpan[] = [];+ attributes: Record<string, unknown> = {};+ errors: unknown[] = [];+ ends = 0;+ constructor(readonly name: string) {}+ span(name: string): Span;+ span<T>(name: string, operation: (span: Span) => Promise<T>): Promise<T>;+ span<T>(+ name: string,+ operation?: (span: Span) => Promise<T>+ ): Span | Promise<T> {+ const child = new RecordedSpan(name);+ this.children.push(child);+ if (!operation) return child;+ return child.run(async () => {+ try {+ return await operation(child);+ } finally {+ child.end();+ }+ });+ }+ run<T>(operation: () => T): T {+ const previous = RecordedSpan.active;+ RecordedSpan.active = this;+ try {+ return operation();+ } finally {+ RecordedSpan.active = previous;+ }+ }+ setAttr(name: string, value: unknown) {+ this.attributes[name] = value;+ }+ event() {}+ error(error: unknown) {+ this.errors.push(error);+ }+ traceparent() {+ return undefined;+ }+ injectTraceHeaders() {}+ end() {+ this.ends++;+ }+}++it('links timed URL and handshake phases, retries, and closure without recording credentials', async () => {+ const resolve = vi.fn(() => {+ expect(RecordedSpan.active?.name).toBe('auth.session_socket.resolve_url');+ return 'wss://example.test/socket?macro-api-token=secret';+ });+ const telemetry = createSessionWebsocketTelemetry(+ 'connection-gateway',+ resolve+ );+ const root = new RecordedSpan('activation');+ const stop = telemetry.activate(root);+ expect(await telemetry.resolveUrl()).toContain('macro-api-token=secret');+ const attempt = root.children[1];+ expect(attempt.name).toBe('auth.session_socket.connect');+ expect(attempt.children.map((phase) => [phase.name, phase.ends])).toEqual([+ ['auth.session_socket.resolve_url', 1],+ ['auth.session_socket.handshake', 0],+ ]);+ telemetry.opened();+ expect(attempt.ends).toBe(1);+ expect(attempt.attributes.outcome).toBe('connected');+ expect(attempt.children[1].ends).toBe(1);++ telemetry.closed({ code: 1006, wasClean: false });+ telemetry.retry({ retries: 1, backoff: 500 });+ expect(root.children[2].attributes).toMatchObject({+ 'ws.close_code': 1006,+ outcome: 'disconnected',+ });+ expect(root.children[3].attributes).toMatchObject({+ 'ws.retries': 1,+ 'ws.backoff_ms': 500,+ });+ await telemetry.resolveUrl();+ const retryAttempt = root.children[4];+ telemetry.failed();+ expect(retryAttempt.attributes).toMatchObject({+ 'ws.retries': 1,+ outcome: 'connection-failed',+ });+ expect(retryAttempt.errors).toEqual(['Session WebSocket connection-failed']);+ expect(retryAttempt.children.every((span) => span.ends === 1)).toBe(true);+ stop();+ expect(root.children.every((span) => span.ends === 1)).toBe(true);+ expect(JSON.stringify(root)).not.toContain('secret');+ const count = root.children.length;+ telemetry.closed({ code: 1000, wasClean: true });+ telemetry.retry({ retries: 2, backoff: 500 });+ telemetry.failed();+ stop();+ expect(root.children).toHaveLength(count);+});++it.each(['resolve', 'reject'] as const)(+ 'finishes cancelled spans and isolates a late %s from the next session',+ async (settle) => {+ const oldUrl = Promise.withResolvers<string>();+ const resolve = vi+ .fn<() => Promise<string>>()+ .mockReturnValueOnce(oldUrl.promise)+ .mockResolvedValue('wss://example.test/new');+ const telemetry = createSessionWebsocketTelemetry('storage', resolve);+ const first = new RecordedSpan('first-session');+ const stopFirst = telemetry.activate(first);+ const pending = telemetry.resolveUrl();+ stopFirst();+ expect(first.children[1].attributes.outcome).toBe('cancelled');+ expect(first.children[1].children[0].ends).toBe(1);++ const second = new RecordedSpan('second-session');+ const stopSecond = telemetry.activate(second);+ await telemetry.resolveUrl();+ if (settle === 'resolve') {+ oldUrl.resolve('wss://example.test/old');+ await pending;+ } else {+ oldUrl.reject(new Error('sensitive token'));+ await expect(pending).rejects.toThrow('sensitive token');+ }+ expect(second.children[1].ends).toBe(0);+ telemetry.opened();+ expect(second.children[1].attributes.outcome).toBe('connected');+ stopSecond();+ expect(first.children.every((span) => span.ends === 1)).toBe(true);+ expect(second.children.every((span) => span.ends === 1)).toBe(true);+ expect(JSON.stringify(first)).not.toContain('sensitive token');+ }+);++it('ends failed URL resolution spans without logging the raw error', async () => {+ const telemetry = createSessionWebsocketTelemetry('storage', () => {+ throw new Error('credential-bearing error');+ });+ const root = new RecordedSpan('activation');+ const stop = telemetry.activate(root);+ await expect(telemetry.resolveUrl()).rejects.toThrow(+ 'credential-bearing error'+ );+ expect(root.children[1].attributes.outcome).toBe('url-resolution-failed');+ expect(root.children[1].ends).toBe(1);+ expect(root.children[1].children[0].ends).toBe(1);+ expect(JSON.stringify(root)).not.toContain('credential-bearing error');+ stop();+});diff --git a/apps/web/src/lib/service-clients/session-websocket-telemetry.ts b/apps/web/src/lib/service-clients/session-websocket-telemetry.tsnew file mode 100644index 0000000000..4653a4f817--- /dev/null+++ b/apps/web/src/lib/service-clients/session-websocket-telemetry.ts@@ -0,0 +1,102 @@+import type { Span } from '@macro-inc/observability';++type Attempt = { span: Span; phase: Span };+type Session = { root: Span; attempt?: Attempt; retries: number };++/** Bounded connection phases share one session trace; credentials and URLs are never recorded. */+export function createSessionWebsocketTelemetry(+ name: 'connection-gateway' | 'storage',+ resolve: () => string | Promise<string>+) {+ let session: Session | undefined;++ function finishAttempt(current: Session, outcome: string, failed = false) {+ const attempt = current.attempt;+ if (!attempt) return;+ current.attempt = undefined;+ for (const span of [attempt.phase, attempt.span]) {+ span.setAttr('outcome', outcome);+ if (failed) span.error(`Session WebSocket ${outcome}`);+ span.end();+ }+ }++ return {+ activate(root: Span) {+ const current: Session = { root, retries: 0 };+ session = current;+ const activation = root.span('auth.session_socket.activate');+ activation.setAttr('ws.service', name);+ activation.setAttr('outcome', 'activated');+ activation.end();+ return () => {+ if (session !== current) return;+ session = undefined;+ finishAttempt(current, 'cancelled');+ const closing = root.span('auth.session_socket.close');+ closing.setAttr('ws.service', name);+ closing.setAttr('outcome', 'session-ended');+ closing.end();+ };+ },++ async resolveUrl(): Promise<string> {+ const current = session;+ if (!current) return resolve();+ finishAttempt(current, 'superseded');+ const span = current.root.span('auth.session_socket.connect');+ span.setAttr('ws.service', name);+ span.setAttr('ws.retries', current.retries);+ const phase = span.span('auth.session_socket.resolve_url');+ current.attempt = { span, phase };+ try {+ // Auth refresh HTTP calls inherit this context; the upgrade itself has+ // no trace headers (the account WS backends do not accept trace queries).+ const url = await phase.run(resolve);+ if (session !== current) return url;+ phase.setAttr('outcome', 'resolved');+ phase.end();+ current.attempt = {+ span,+ phase: span.span('auth.session_socket.handshake'),+ };+ return url;+ } catch (error) {+ finishAttempt(current, 'url-resolution-failed', true);+ throw error;+ }+ },++ opened() {+ if (!session) return;+ finishAttempt(session, 'connected');+ session.retries = 0;+ },++ failed() {+ if (session) finishAttempt(session, 'connection-failed', true);+ },++ closed(event: { code: number; wasClean: boolean }) {+ if (!session) return;+ finishAttempt(session, 'closed-before-open', true);+ const closing = session.root.span('auth.session_socket.close');+ closing.setAttr('ws.service', name);+ closing.setAttr('ws.close_code', event.code);+ closing.setAttr('ws.was_clean', event.wasClean);+ closing.setAttr('outcome', 'disconnected');+ closing.end();+ },++ retry(event: { retries: number; backoff: number }) {+ if (!session) return;+ session.retries = event.retries;+ const retry = session.root.span('auth.session_socket.retry');+ retry.setAttr('ws.service', name);+ retry.setAttr('ws.retries', event.retries);+ retry.setAttr('ws.backoff_ms', event.backoff);+ retry.setAttr('outcome', 'retrying');+ retry.end();+ },+ };+}diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex e4b85ba577..993296c60e 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -15,6 +15,7 @@ import { CallStartedNotifier } from '@channel/Call/CallStartedNotifier';import { CallKitSync } from '@channel/Call/use-callkit';import { dismissBootShell } from '@components/app/boot-shell';import { RootFrame } from '@components/app/Layout';+import { useSessionWebsockets } from '@core/auth/session-websockets';import { ToastRegion } from '@core/component/Toast/ToastRegion';import { ChannelsContextProvider } from '@core/context/channels';import { EmailLinksContextProvider } from '@core/context/emailLinks';@@ -176,6 +177,7 @@ const BOOT_SHELL_MAX_WAIT_MS = 8000;*/function AppRouteFrame(props: RouteSectionProps) {useUserInfoSideEffects();+ useSessionWebsockets();onMount(() => {const cap = setTimeout(dismissBootShell, BOOT_SHELL_MAX_WAIT_MS);onCleanup(() => clearTimeout(cap));diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex ab451b915c..a024d78d7f 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -4,6 +4,21 @@ The document header has separate Share, Copy Share Link, and Side Panel buttons.They are borderless with a soft rounded background on hover. Share opens thesharing dialog; copying a link is a separate action.+Verify **Public → View** links in a fresh signed-out browser context. The+`/app/drive/md/<id>` route (including folder/tab document links and legacy+`/app/md/<id>` redirects) must show the document without private Drive lists or+folder navigation, on desktop and touch devices. The login banner may remain;+it must not replace the public document. Signed-out readers see **Sign in to view+comments**, not a comment-fetch error or composer. While identity is unresolved,+the discussion shows neither comments nor a sign-in prompt; throttle the preview+auth response to check this on desktop and touch devices. Account-only lists, contacts,+notifications, activity, and gateway/storage WebSockets must stay idle until+sign-in; public document metadata, properties, and sync still load normally.+Check that signing in restores account services and signing out stops them.+Private files still prompt for sign-in. Signed-out Drive list URLs (My Files,+Recent, Shared with me, or folders without a document target) show **Sign in to+view your files** with Login and Sign Up actions, never an indefinite loader.+Opening a private file link while signed in shows **You don't have access tothis file**, the signed-in email, and **Request access**. View is selected bydefault; choose View, Comment, or Edit where supported, submit, then verifydiff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.mdindex 0f9aa6f12c..0663853c24 100644--- a/docs/agent-guide/login.md+++ b/docs/agent-guide/login.md@@ -59,6 +59,24 @@ their clients. Mounted query observers must receive the next account's dataafter the wipe. Previous account data must not return through initial data,placeholder data, or a later query reset.+## CI deploy-preview authentication++PR previews at `https://<id>.preview.macro.com/app` use the dev backend and+its shared `.macro.com` HttpOnly cookies (`dev-macro-access-token` and+`dev-macro-refresh-token`). The `login` hint is host-only and `macro:login`+localStorage is origin-scoped, so a fresh preview has neither. Preview startup+must check identity anyway; the hostname is not proof of authentication.+Account queries and WebSockets still wait for a confirmed authenticated user.++Verify in a browser signed into `https://dev.macro.com`: open a fresh preview+hostname (or clear only that preview's localStorage and `login` hint, keeping+the shared dev cookies). It should request+`https://dev-gateway.macro.com/auth/user/legacy_user_permissions` and enter the+signed-in app without another login. Repeat in a clean browser context: the+identity check should fail without starting account services, and a public+document should remain readable. Ordinary signed-out public links without a+login hint should not start identity checks or account services.+## Hosted-dev proxy SSOOn an allowed OAuth origin such as `https://localhost:<port>`, Google/SSOdiff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.mdindex 580a5b1bce..fd1d8e32c9 100644--- a/docs/agent-guide/notifications.md+++ b/docs/agent-guide/notifications.md@@ -43,6 +43,11 @@ Also verify logout and notification opt-out while registration is pending: latebackend or native completions must leave the receiver disabled. If a new accountsigns in before cleanup finishes, its registration must remain active afterward.+Mute indicators must use the current account's query data, not a retained copy+from the previous session. Verify a same-tab sign-out/sign-in with the second+account's muted-items request delayed: show no previous-account mute indicators+while that query is pending, then apply only the second account's response.+Toast regions are labeled `Notifications (alt+T)`; seven empty live regions always exist inthe a11y tree (ignore them when parsing snapshots).diff --git a/docs/agent-guide/observability.md b/docs/agent-guide/observability.mdindex aaa05df4bf..ec164c7de8 100644--- a/docs/agent-guide/observability.md+++ b/docs/agent-guide/observability.md@@ -69,6 +69,28 @@ trace context — timestamps + service are the only join for those.applying and message fan-out remain untraced. Call joining now has a user-actiontrace; see below.+## Account WebSocket sessions++Search for `{ name="auth.session_websockets.activate" }` after signing in.+`user.id_hash` is SHA-256 of the Macro user ID; this trace suppresses automatic+raw user-ID enrichment because Macro IDs can contain email addresses. No socket+URLs, tokens, close reasons, or raw credential errors are recorded.++Gateway and storage child spans share that activation trace. `ws.service`+identifies the socket. `auth.session_socket.resolve_url` measures authorization+and URL resolution; `auth.session_socket.handshake` measures the upgrade. Their+`auth.session_socket.connect` parent ends on connection, failure, or cancellation.+`auth.session_socket.retry` records retry count and backoff milliseconds;+`auth.session_socket.close` distinguishes disconnects from session teardown.+Activation ends promptly rather than staying open for the whole login; later+retries and closure remain children of its trace.++Auth-refresh HTTP requests started during URL resolution inherit its trace+context. Browser WebSocket upgrades cannot send custom trace headers, and these+account backends do not currently consume trace-context query parameters, so+upgrade server spans are not yet joined to this browser trace. Verify browser+phases separately rather than assuming end-to-end upgrade correlation.+## Call joiningClick **Start call** on `/app/meet/new` or **Join call** on a shared meeting'sdiff --git a/packages/collaboration/README.md b/packages/collaboration/README.mdindex 42e5589bc5..1738bc4c86 100644--- a/packages/collaboration/README.md+++ b/packages/collaboration/README.md@@ -7,7 +7,13 @@ Shared collaboration runtime used by the web app and non-browser workers.- `@macro-inc/collaboration/sync-service/*` contains the sync-service wireprotocol and transport. Callers provide the environment-specific URL/token.- `@macro-inc/collaboration/websocket` contains the typed WebSocket runtime;- deeper utilities are available through `websocket/*` subpaths.+ deeper utilities are available through `websocket/*` subpaths. Use+ `withAutoConnect(false)` for session-owned sockets: construction and wake+ signals stay idle until `reconnect()`. `close()` stops retries; a subsequent+ reconnect resolves fresh credentials, discarding URLs from before the close,+ including closes during `UrlResolved` callbacks. Before a native socket exists,+ `readyState` reports CLOSED or CONNECTING, `bufferedAmount` is 0, and+ `extensions` is empty.Browser authentication, sync HTTP endpoints, and document history UI remain in`apps/web` because they depend on app state and browser policy.diff --git a/packages/collaboration/src/websocket/core/websocket-builder.ts b/packages/collaboration/src/websocket/core/websocket-builder.tsindex 18c15d71f2..dc36f0e3f0 100644--- a/packages/collaboration/src/websocket/core/websocket-builder.ts+++ b/packages/collaboration/src/websocket/core/websocket-builder.ts@@ -69,6 +69,14 @@ export class WebsocketBuilder<Send = WebsocketData, Receive = WebsocketData> {return this;}+ /** Start closed until reconnect() is called, without resolving a URL. */+ public withAutoConnect(+ autoConnect: boolean+ ): WebsocketBuilder<Send, Receive> {+ this._options = { ...this._options, autoConnect };+ return this;+ }+/*** Getter for the protocols.*@@ -187,6 +195,7 @@ export class WebsocketBuilder<Send = WebsocketData, Receive = WebsocketData> {);newBuilder._protocols = this._protocols;newBuilder._options = {+ autoConnect: this._options?.autoConnect,retry: this._options?.retry,heartbeat: this._options?.heartbeat,listeners: this._options?.listeners,diff --git a/packages/collaboration/src/websocket/core/websocket-options.ts b/packages/collaboration/src/websocket/core/websocket-options.tsindex a3d7c20d72..c40f7f8693 100644--- a/packages/collaboration/src/websocket/core/websocket-options.ts+++ b/packages/collaboration/src/websocket/core/websocket-options.ts@@ -17,6 +17,9 @@ export interface WebsocketOptions<> {readonly binaryType?: BinaryType;+ /** Connect immediately by default; false waits for an explicit reconnect(). */+ readonly autoConnect?: boolean;+/*** The Buffer to use.*/diff --git a/packages/collaboration/src/websocket/core/websocket.ts b/packages/collaboration/src/websocket/core/websocket.tsindex 7f7283d064..f055cd9578 100644--- a/packages/collaboration/src/websocket/core/websocket.ts+++ b/packages/collaboration/src/websocket/core/websocket.ts@@ -61,6 +61,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {private _binaryType?: BinaryType = 'blob'; // the binaryType to useprivate _closedByUser: boolean = false; // whether the websocket was closed by the user+ private connectionGeneration = 0;private _lastConnection?: Date; // timestamp of the last connectionprivate _underlyingWebsocket!: MinimalWebSocket; // assigned by tryConnectprivate connectPending: boolean = false; // whether tryConnect is resolving its url / creating a socket@@ -132,7 +133,12 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {this._url = resolver;}- this.tryConnect();+ this._closedByUser = options?.autoConnect === false;+ if (this._closedByUser) {+ this.connectionState = WebsocketConnectionState.Closed;+ } else {+ this.tryConnect();+ }}/**@@ -224,7 +230,12 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {* @return the readyState of the underlying websocket.*/get readyState(): number {- return this._underlyingWebsocket.readyState;+ return (+ this._underlyingWebsocket?.readyState ??+ (this.closedByUser+ ? WebsocketConnectionState.Closed+ : WebsocketConnectionState.Connecting)+ );}/**@@ -234,7 +245,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {* @return the bufferedAmount of the underlying websocket.*/get bufferedAmount(): number {- return this._underlyingWebsocket.bufferedAmount;+ return this._underlyingWebsocket?.bufferedAmount ?? 0;}/**@@ -244,7 +255,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {* @return the extensions of the underlying websocket.*/get extensions(): string {- return this._underlyingWebsocket.extensions;+ return this._underlyingWebsocket?.extensions ?? '';}/**@@ -306,6 +317,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {public close(code?: number, reason?: string): void {this.cancelScheduledConnectionRetry(); // cancel any scheduled retriesthis._closedByUser = true; // mark websocket as closed by user+ this.connectionGeneration++;// The underlying websocket is unassigned while the first connect attempt// is still resolving its url; tryConnect observes _closedByUser and// won't open a socket after this point.@@ -361,12 +373,13 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {*/private async tryConnect(): Promise<void> {this.connectPending = true;+ const generation = this.connectionGeneration;try {const url = await resolveUrl(this._urlResolver);// The websocket may have been closed by the user while the url was// resolving (e.g. a token fetch); don't open a connection nobody owns.- if (this._closedByUser) {+ if (this._closedByUser || generation !== this.connectionGeneration) {return;}@@ -380,6 +393,10 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {});this.dispatchEvent(WebsocketEvent.UrlResolved, event);+ // Listeners may close or replace the session synchronously.+ if (this._closedByUser || generation !== this.connectionGeneration) {+ return;+ }const factory = this._options.factory ?? platformWebSocketFactory;const newSocket = factory(this.url, this.protocols); // create new browser-native websocket and add all event listenersthis._underlyingWebsocket = newSocket;@@ -406,13 +423,18 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {} catch {// URL resolution can require online authorization. No native socket// exists to emit a close event when that fails, so retry it here too.- if (!this._closedByUser) {+ if (!this._closedByUser && generation === this.connectionGeneration) {this.connectionState = WebsocketConnectionState.Closed;this.dispatchEvent(WebsocketEvent.Error, new Event('error'));this.scheduleConnectionRetryIfNeeded();}} finally {this.connectPending = false;+ // A close followed by reconnect may be a different signed-in session.+ // Resolve fresh credentials instead of adopting the previous URL.+ if (!this._closedByUser && generation !== this.connectionGeneration) {+ this.tryConnect();+ }}}@@ -869,14 +891,14 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {reconnect() {// An explicit reconnect always overrides a prior user close — clear the// flag before the pending check so a close() that landed while a connect- // attempt was resolving its url doesn't strand the instance (tryConnect- // bails on _closedByUser after the url resolves).+ // attempt was resolving its url doesn't strand the instance. tryConnect+ // discards an old generation's URL and resolves a fresh one when it settles.this._closedByUser = false;if (this.connectPending) {// A fresh connection is already being established (e.g. 'online' and// 'visibilitychange' firing together on wake) — starting a second- // tryConnect would orphan the first socket. With _closedByUser cleared- // above, the in-flight attempt is adopted as this reconnect.+ // tryConnect would orphan the first socket. An unchanged generation+ // adopts this attempt; a closed generation retries with fresh credentials.return;}this.cancelScheduledConnectionRetry();diff --git a/packages/collaboration/src/websocket/tests/websocket-auto-connect.test.ts b/packages/collaboration/src/websocket/tests/websocket-auto-connect.test.tsnew file mode 100644index 0000000000..b3d1a53bcd--- /dev/null+++ b/packages/collaboration/src/websocket/tests/websocket-auto-connect.test.ts@@ -0,0 +1,146 @@+import { afterEach, expect, test, vi } from 'vitest';+import type { WebSocketServer } from 'ws';+import type { Websocket, WebsocketData } from '../';+import { JsonSerializer, WebsocketBuilder, WebsocketEvent } from '../';+import { startServer, stopClient, stopServer } from './websocket-test-utils';++let server: WebSocketServer | undefined;+let client: Websocket | undefined;++afterEach(async () => {+ await stopClient(client, 5000);+ await stopServer(server, 5000);+ client = undefined;+ server = undefined;+});++test('waits for explicit session activation, then closes without reconnecting on wake', async () => {+ server = await startServer(0, 5000);+ const address = server.address();+ if (!address || typeof address === 'string')+ throw new Error('Expected TCP server');+ const resolveUrl = vi.fn(() => `ws://localhost:${address.port}`);+ client = new WebsocketBuilder(resolveUrl)+ .withAutoConnect(false)+ .withSerializer(new JsonSerializer<WebsocketData, WebsocketData>())+ .build();++ expect(resolveUrl).not.toHaveBeenCalled();+ expect(client.closedByUser).toBe(true);+ expect(client.readyState).toBe(WebSocket.CLOSED);+ expect(client.bufferedAmount).toBe(0);+ expect(client.extensions).toBe('');+ expect(client.send('signed out')).toBe(false);+ client.reconnectIfDisconnected();+ expect(resolveUrl).not.toHaveBeenCalled();++ const opened = Promise.withResolvers<void>();+ client.addEventListener(WebsocketEvent.Open, () => opened.resolve(), {+ once: true,+ });+ client.reconnect();+ expect(client.readyState).toBe(WebSocket.CONNECTING);+ expect(client.bufferedAmount).toBe(0);+ expect(client.extensions).toBe('');+ await opened.promise;+ expect(client.readyState).toBe(WebSocket.OPEN);+ expect(resolveUrl).toHaveBeenCalledOnce();+ expect(client.send('signed in')).toBe(true);++ const closed = Promise.withResolvers<void>();+ client.addEventListener(WebsocketEvent.Close, () => closed.resolve(), {+ once: true,+ });+ client.close();+ await closed.promise;+ client.reconnectIfDisconnected();+ expect(resolveUrl).toHaveBeenCalledOnce();+ expect(client.send('signed out again')).toBe(false);++ const reopened = Promise.withResolvers<void>();+ client.addEventListener(WebsocketEvent.Open, () => reopened.resolve(), {+ once: true,+ });+ client.reconnect();+ await reopened.promise;+ expect(resolveUrl).toHaveBeenCalledTimes(2);+ expect(client.send('new session')).toBe(true);+});++test('discards credentials still resolving when a session is replaced', async () => {+ server = await startServer(0, 5000);+ const address = server.address();+ if (!address || typeof address === 'string')+ throw new Error('Expected TCP server');+ const oldUrl = Promise.withResolvers<string>();+ const newUrl = `ws://localhost:${address.port}/?session=new`;+ const resolveUrl = vi+ .fn<() => Promise<string>>()+ .mockReturnValueOnce(oldUrl.promise)+ .mockResolvedValue(newUrl);+ client = new WebsocketBuilder(resolveUrl).withAutoConnect(false).build();+ const opened = Promise.withResolvers<void>();+ const resolved = vi.fn();+ client.addEventListener(WebsocketEvent.UrlResolved, resolved);+ client.addEventListener(WebsocketEvent.Open, () => opened.resolve(), {+ once: true,+ });++ client.reconnect();+ client.close();+ client.reconnect();+ oldUrl.resolve(`ws://localhost:${address.port}/?session=old`);+ await opened.promise;+ expect(resolveUrl).toHaveBeenCalledTimes(2);+ expect(resolved).toHaveBeenCalledOnce();+ expect(client.url).toBe(newUrl);+});++test('does not create a native socket when a URL listener closes it', async () => {+ const resolved = Promise.withResolvers<void>();+ const factory = vi.fn(() => {+ throw new Error('Unexpected socket creation');+ });+ client = new WebsocketBuilder('ws://unused')+ .withAutoConnect(false)+ .withFactory(factory)+ .build();+ client.addEventListener(WebsocketEvent.UrlResolved, (socket) => {+ socket.close();+ resolved.resolve();+ });+ client.reconnect();+ await resolved.promise;+ expect(factory).not.toHaveBeenCalled();+ expect(client.closedByUser).toBe(true);+});++test('resolves fresh credentials when a URL listener replaces the session', async () => {+ server = await startServer(0, 5000);+ const address = server.address();+ if (!address || typeof address === 'string')+ throw new Error('Expected TCP server');+ const urls: (string | undefined)[] = [];+ server.on('connection', (_, request) => urls.push(request.url));+ const resolveUrl = vi+ .fn()+ .mockReturnValueOnce(`ws://localhost:${address.port}/?session=old`)+ .mockReturnValue(`ws://localhost:${address.port}/?session=new`);+ const opened = Promise.withResolvers<void>();+ client = new WebsocketBuilder(resolveUrl)+ .withAutoConnect(false)+ .onOpen(() => opened.resolve())+ .build();+ client.addEventListener(+ WebsocketEvent.UrlResolved,+ (socket) => {+ socket.close();+ socket.reconnect();+ },+ { once: true }+ );+ client.reconnect();+ await opened.promise;+ expect(resolveUrl).toHaveBeenCalledTimes(2);+ expect(urls).toEqual(['/?session=new']);+});diff --git a/packages/collaboration/src/websocket/tests/websocket-test-utils.ts b/packages/collaboration/src/websocket/tests/websocket-test-utils.tsindex 3da62d61ba..9ef952be9e 100644--- a/packages/collaboration/src/websocket/tests/websocket-test-utils.ts+++ b/packages/collaboration/src/websocket/tests/websocket-test-utils.ts@@ -26,8 +26,7 @@ export const stopClient = (): Promise<void> =>new Promise<void>((resolve, reject) => {if (client === undefined) return resolve();- if (client.underlyingWebsocket?.readyState === WebSocket.CLOSED)- return resolve();+ if (client.readyState === WebSocket.CLOSED) return resolve();rejectAfter(timeout, 'failed to stop client').catch((err) => reject(err));client.addEventListener(WebsocketEvent.Close, () => resolve(), {once: true,