Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Revert "fix(drive): open public links without account services (#8296)" (#8333)

Sean Ayecec4fad6bf3a
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 36e2e9ec91..528e8b27a2 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -78,10 +78,6 @@ without changing the active route. Backend registration still verifies account
ownership. 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.
- 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.tsx
index bb2a904f73..6876431e20 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 { useIsAuthenticated, useUserId } from '@core/context/user';
+import { useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { createBlockOrchestrator } from '@core/orchestrator';
import { fireAndForget } from '@core/util/fireAndForget';
@@ -35,7 +35,6 @@ import { ImperativeDialogHost } from '@ui';
import type { ParentProps } from 'solid-js';
function ConfiguredGlobalAppStateProvider(props: ParentProps) {
- const authenticated = useIsAuthenticated();
// Initialize global notification helpers
const notifInterface = usePlatformNotificationState();
useChatRenameWebsocketSync();
@@ -71,8 +70,7 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
const notificationSource = createNotificationSource(
connectionGatewayWebsocket,
(notification) =>
- fireAndForget(deliverNotification(notification), 'notifications'),
- () => authenticated() === true
+ fireAndForget(deliverNotification(notification), 'notifications')
);
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.ts
index acef9a9794..99d0d21655 100644
--- a/apps/web/src/features/activity/use-entity-activity-flag.ts
+++ b/apps/web/src/features/activity/use-entity-activity-flag.ts
@@ -1,15 +1,13 @@
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 or before sign-in.
+ * issued while off.
*/
export function useEntityActivityFlag(): Accessor<boolean> {
const flag = useFeatureFlag(enableEntityActivitySection);
- const authenticated = useIsAuthenticated();
- return () => authenticated() === true && flag().enabled;
+ return () => 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.tsx
index 681ee1292c..974d3482dd 100644
--- a/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx
+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx
@@ -23,15 +23,6 @@ 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,
@@ -118,22 +109,6 @@ 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.getByText('Sign in to view comments.')).toBeTruthy();
- expect(mocks.conversation).not.toHaveBeenCalled();
- expect(mocks.mount).not.toHaveBeenCalled();
-
- setAuthenticated(false);
- expect(mocks.conversation).not.toHaveBeenCalled();
- setAuthenticated(true);
- 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.tsx
index 9fbce97390..25940061ca 100644
--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
@@ -1,12 +1,10 @@
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 { Show } from 'solid-js';
import { useMarkdownDocument } from '../context/markdown-document-context';
/**
@@ -14,26 +12,10 @@ 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.
*/
-type DocumentDiscussionProps = {
+export function DocumentDiscussion(props: {
editorHasFocus: boolean;
label?: string;
-};
-
-export function DocumentDiscussion(props: DocumentDiscussionProps) {
- const authenticated = useIsAuthenticated();
- return (
- <Show
- when={authenticated() === true}
- fallback={
- <p class="mt-3 text-xs text-ink-muted">Sign in to view comments.</p>
- }
- >
- <AuthenticatedDocumentDiscussion {...props} />
- </Show>
- );
-}
-
-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.tsx
index 44f0c74065..6c5c9584ed 100644
--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
@@ -79,7 +79,6 @@ 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';
@@ -149,7 +148,6 @@ export function MarkdownEditor(props: {
permissions,
state: documentState,
} = useMarkdownDocument();
- const authenticated = useIsAuthenticated();
const { canEdit } = permissions;
const blockId = documentId();
const documentKind = kind();
@@ -806,7 +804,7 @@ export function MarkdownEditor(props: {
/>
</Show>
- <Show when={ENABLE_MARKDOWN_COMMENTS && authenticated() === true}>
+ <Show when={ENABLE_MARKDOWN_COMMENTS}>
<Suspense>
<MessageCommentsProvider
activeComment={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.tsx
index b62697a114..8198f6662c 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,7 +359,6 @@ 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.tsx
index 4116e29aaa..334fc10147 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 { useOptionalDriveView } from '../context/drive-context';
+import { useDriveView } from '../context/drive-context';
import { driveLocationBreadcrumbs } from '../core/breadcrumbs';
import { useDriveDetailNavigation } from '../drive-detail-navigation';
import { FileDetailBreadcrumbItem } from '../views/FileDetailBreadcrumbItem';
@@ -216,14 +216,9 @@ function StackEntityDetail(props: {
}
export function DriveDetailView() {
- const drive = useOptionalDriveView();
+ const { state, sidebar } = useDriveView();
const breadcrumbOrderOffset = () =>
- drive
- ? driveLocationBreadcrumbs(
- drive.state.value().location,
- drive.sidebar.folders()
- ).length
- : 0;
+ driveLocationBreadcrumbs(state.value().location, sidebar.folders()).length;
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.tsx
index 977fe42bf3..8c5cffdb1a 100644
--- a/apps/web/src/features/drive-view/context/drive-context.tsx
+++ b/apps/web/src/features/drive-view/context/drive-context.tsx
@@ -39,12 +39,8 @@ const Context = createContext<DriveContext>();
export const DriveProvider = Context.Provider;
-export function useOptionalDriveView(): DriveContext | undefined {
- return useContext(Context);
-}
-
export function useDriveView(): DriveContext {
- const context = useOptionalDriveView();
+ const context = useContext(Context);
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.tsx
index 9c411f9274..e2b9fae3bd 100644
--- a/apps/web/src/features/drive-view/drive-view.tsx
+++ b/apps/web/src/features/drive-view/drive-view.tsx
@@ -49,7 +49,6 @@ 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 };
@@ -192,16 +191,6 @@ 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.tsx
deleted file mode 100644
index bc4e3b1622..0000000000
--- a/apps/web/src/features/drive-view/route-views.test.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-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.tsx
index 4c801f95f7..5e3b700b7c 100644
--- a/apps/web/src/features/drive-view/route-views.tsx
+++ b/apps/web/src/features/drive-view/route-views.tsx
@@ -6,20 +6,15 @@ import {
AppView,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
-import { useIsAuthenticated } from '@core/auth';
-import { lazy, Show } from 'solid-js';
-import {
- DriveView,
- type DriveViewProps,
- SignedOutDriveView,
-} from './drive-view';
+import { lazy } from 'solid-js';
+import { DriveView, type DriveViewProps } from './drive-view';
import { DriveViewSkeleton } from './drive-view-skeleton';
const DriveCallDetail = lazy(async () => ({
default: (await import('./views/DriveCallDetail')).DriveCallDetail,
}));
-const AuthenticatedDriveRouteView = withAuth(() => {
+export const DriveRouteView = withAuth(() => {
const panel = useSplitPanelOrThrow();
const props = (): DriveViewProps => {
const content = panel.handle.content();
@@ -34,18 +29,6 @@ const AuthenticatedDriveRouteView = 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.tsx
deleted file mode 100644
index 04722653cb..0000000000
--- a/apps/web/src/features/drive-view/views/signed-out-drive-workspace.test.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-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.tsx
deleted file mode 100644
index 267b3e00a8..0000000000
--- a/apps/web/src/features/drive-view/views/signed-out-drive-workspace.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-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.ts
index 5b70d648af..cd77125376 100644
--- a/apps/web/src/features/meetings/queries/meeting-teammates.test.ts
+++ b/apps/web/src/features/meetings/queries/meeting-teammates.test.ts
@@ -10,7 +10,6 @@ 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.ts
index 581658c11e..c12c561362 100644
--- a/apps/web/src/features/notifications/notification-source.ts
+++ b/apps/web/src/features/notifications/notification-source.ts
@@ -237,27 +237,20 @@ function withNotificationOverrides(
export function createNotificationSource(
ws: ConnectionGatewayWebsocket,
- onNotification?: (notification: UnifiedNotification) => void,
- enabled: Accessor<boolean> = () => true
+ onNotification?: (notification: UnifiedNotification) => void
): NotificationSource {
const subscriptions: Set<SubscribeFn> = new Set();
const [mutedEntitiesStore, setMutedEntities] = createStore<UserUnsubscribe[]>(
[]
);
- const mutedEntities = createMemo(() =>
- enabled() ? [...mutedEntitiesStore] : []
- );
+ const mutedEntities = createMemo(() => [...mutedEntitiesStore]);
- const notificationsQuery = useUserNotificationsQuery(
- () => ({ limit: QUERY_LIMIT }),
- () => ({ enabled: enabled() })
- );
+ const notificationsQuery = useUserNotificationsQuery(() => ({
+ limit: QUERY_LIMIT,
+ }));
const usesGraphql = () => notificationsQuery.transport === 'graphql';
- const mutedEntitiesQuery = createMutedEntitiesQuery(
- { limit: QUERY_LIMIT },
- enabled
- );
+ const mutedEntitiesQuery = createMutedEntitiesQuery({ limit: QUERY_LIMIT });
const muteItem = useMuteItemMutation();
const unmuteItem = useUnmuteItemMutation();
@@ -271,7 +264,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 (!enabled() || notificationsQuery.isLoading) return [];
+ if (notificationsQuery.isLoading) return [];
const raw = notificationsQuery.data;
if (!raw) return [];
return raw.map(withNotificationOverrides);
@@ -282,7 +275,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 (!enabled() || usesGraphql()) return;
+ if (usesGraphql()) return;
const raw = notificationsQuery.data;
if (!raw) return;
const presentIds = new Set(raw.map((n) => n.id));
@@ -301,7 +294,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 (!enabled() || usesGraphql()) return;
+ if (usesGraphql()) return;
const raw = notificationsQuery.data;
if (!raw) return;
const seenIds = Object.keys(seenOverrides);
@@ -335,7 +328,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 (!enabled() || usesGraphql()) return;
+ if (usesGraphql()) return;
if (!notificationsQuery.data) return;
if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {
fireAndForget(notificationsQuery.fetchNextPage(), 'notifications');
@@ -343,14 +336,10 @@ export function createNotificationSource(
});
const isLoading = () => {
- return (
- enabled() &&
- (notificationsQuery.isLoading || mutedEntitiesQuery.isLoading)
- );
+ return notificationsQuery.isLoading || mutedEntitiesQuery.isLoading;
};
createEffect(() => {
- if (!enabled() || mutedEntitiesQuery.isPending) return;
const mutedEntities = mutedEntitiesQuery.data;
if (!mutedEntities) return;
setMutedEntities(reconcile(mutedEntities));
@@ -372,7 +361,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 (!enabled() || !notificationsQuery.isStarted) return;
+ if (!notificationsQuery.isStarted) return;
const toDiscard = notifications().filter(
(n) =>
n.notification_event_type === 'document_mention' && n.state !== 'done'
@@ -398,8 +387,7 @@ export function createNotificationSource(
let graphqlSubscriptionDisposed = false;
const runGraphqlNotificationRefetch = async (): Promise<void> => {
- if (!enabled() || graphqlSubscriptionDisposed || graphqlRefetchInFlight)
- return;
+ if (graphqlSubscriptionDisposed || graphqlRefetchInFlight) return;
graphqlRefetchInFlight = true;
try {
do {
@@ -421,7 +409,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 (!enabled() || !notificationsQuery.isStarted) return;
+ if (!notificationsQuery.isStarted) return;
graphqlRefetchPending = true;
if (graphqlRefetchScheduled || graphqlRefetchInFlight) return;
graphqlRefetchScheduled = true;
@@ -433,7 +421,7 @@ export function createNotificationSource(
const unsubscribeFromGraphql = subscribeToGraphqlNotificationPatches(
(patch) => {
- if (!enabled() || !usesGraphql()) return;
+ if (!usesGraphql()) return;
scheduleGraphqlNotificationRefetch();
if (patch.__typename !== 'GraphqlNewNotification') return;
const notification = mapGraphqlNotification(patch.notification);
@@ -457,11 +445,7 @@ export function createNotificationSource(
};
createSocketEffect(ws, (wsData) => {
- if (
- !enabled() ||
- wsData.type !== NOTIFICATION_EVENT_TYPE ||
- usesGraphql()
- ) {
+ if (wsData.type !== NOTIFICATION_EVENT_TYPE || usesGraphql()) {
return;
}
let parsedNotification: UnifiedNotification;
@@ -499,7 +483,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 (!enabled() || notifications.length === 0) return;
+ if (notifications.length === 0) return;
const ids = notifications.map((n) => n.id);
const rollback = setDoneOverride(ids, true);
try {
@@ -513,7 +497,7 @@ export function createNotificationSource(
};
const bulkMarkAsRead = async (notifications: UnifiedNotification[]) => {
- if (!enabled() || notifications.length === 0) return;
+ if (notifications.length === 0) return;
const ids = notifications.map((n) => n.id);
const rollback = setSeenOverride(ids, new Date().toISOString());
try {
@@ -540,12 +524,10 @@ 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.ts
deleted file mode 100644
index 0a7d3e9b3a..0000000000
--- a/apps/web/src/features/notifications/tests/notification-source-auth.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-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 { createRoot, createSignal } from 'solid-js';
-import { 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';
-
-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();
- }
-});
diff --git a/apps/web/src/lib/core/auth/session-websockets.test.ts b/apps/web/src/lib/core/auth/session-websockets.test.ts
deleted file mode 100644
index 751158c8c9..0000000000
--- a/apps/web/src/lib/core/auth/session-websockets.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-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.ts
deleted file mode 100644
index 81f7bdde3a..0000000000
--- a/apps/web/src/lib/core/auth/session-websockets.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-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.ts
deleted file mode 100644
index 79c8b67197..0000000000
--- a/apps/web/src/lib/core/component/AI/signal/globalAttachments.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-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.tsx
index d05a0bb29a..8726671e5b 100644
--- a/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsx
+++ b/apps/web/src/lib/core/component/AI/signal/globalAttachments.tsx
@@ -1,5 +1,4 @@
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';
@@ -15,14 +14,10 @@ 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 =
- authenticated() === true && historyQuery.isSuccess
- ? historyQuery.data
- : [];
+ const history = 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.tsx
index 46441ac7b2..0e3a616efa 100644
--- a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
@@ -49,10 +49,7 @@ 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',
- useIsAuthenticated: () => () => true,
-}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'test-user' }));
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.tsx
index 3a6e19e978..a9f6811b67 100644
--- a/apps/web/src/lib/core/context/channels.test.tsx
+++ b/apps/web/src/lib/core/context/channels.test.tsx
@@ -17,10 +17,7 @@ vi.mock('@queries/channel/activity', () => ({
data: [],
}),
}));
-vi.mock('./user', () => ({
- useUserId: () => () => undefined,
- useIsAuthenticated: () => () => true,
-}));
+vi.mock('./user', () => ({ useUserId: () => () => undefined }));
import { ChannelsContextProvider, useChannelCanCall } from './channels';
diff --git a/apps/web/src/lib/core/context/channels.ts b/apps/web/src/lib/core/context/channels.ts
index b6da5a6e19..d76396a533 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 { useIsAuthenticated, useUserId } from './user';
+import { useUserId } from './user';
type ChannelsContextValue = {
channels: Accessor<ApiChannelWithLatest[]>;
@@ -20,18 +20,16 @@ type ChannelsContextValue = {
export const [ChannelsContextProvider, useChannelsContext] =
createAssertedContextProvider('ChannelsContext', (): ChannelsContextValue => {
- const authenticated = useIsAuthenticated();
- const enabled = () => authenticated() === true;
- const channelsQuery = useListChannelsQuery(enabled);
- const activityQuery = useChannelsActivityQuery(enabled);
+ const channelsQuery = useListChannelsQuery();
+ const activityQuery = useChannelsActivityQuery();
const channels = () =>
- enabled() && queryReadyGate(channelsQuery) ? channelsQuery.data : [];
+ queryReadyGate(channelsQuery) ? channelsQuery.data : [];
const activity = () =>
- enabled() && queryReadyGate(activityQuery) ? activityQuery.data : [];
+ queryReadyGate(activityQuery) ? activityQuery.data : [];
const channelsById = createMemo(() => {
- if (!enabled() || !queryReadyGate(channelsQuery)) return {};
+ if (!queryReadyGate(channelsQuery)) return {};
return channelsQuery.data.reduce<Record<string, ApiChannelWithLatest>>(
(acc, ch) => {
acc[ch.id] = ch;
@@ -42,7 +40,7 @@ export const [ChannelsContextProvider, useChannelsContext] =
});
const activityByChannelId = createMemo(() => {
- if (!enabled() || !queryReadyGate(activityQuery)) return {};
+ if (!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.tsx
index 040c370b88..ff826cd815 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx
@@ -1,108 +1,63 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
-import { createSignal, onCleanup, type ParentProps } from 'solid-js';
+import { createSignal, type ParentProps } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
import { useQuickAccess } from './context';
import { QuickAccessProvider } from './QuickAccessProvider';
-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();
+const [sourceError, setSourceError] = createSignal<Error>();
-vi.mock('@core/context/user', () => ({
- useIsAuthenticated: () => authenticated,
- useUserId: () => userId,
-}));
vi.mock('@channel/DebugSuspense', () => ({
DebugSuspense: (props: ParentProps) => props.children,
}));
vi.mock('./QuickAccessSource', () => ({
- 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,
+ createQuickAccessValue: () => ({
+ useList: () => ({
+ error: sourceError,
+ items: () => [],
+ totalCount: () => 0,
+ hasMore: () => false,
isLoading: () => false,
- refresh,
- getById: () => undefined,
- };
- },
+ isLoadingMore: () => false,
+ loadMore: async () => {},
+ }),
+ usesRecordSelection: () => true,
+ usesSearchProjection: () => true,
+ isLoading: () => false,
+ refresh: () => {},
+ getById: () => undefined,
+ }),
}));
afterEach(() => {
cleanup();
- setAuthenticated(undefined);
- setUserId(undefined);
- vi.clearAllMocks();
+ setSourceError(undefined);
});
-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();
+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();
- 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(new Error('Cache unavailable'));
+ expect(screen.getByText('Unavailable')).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);
-});
+ setSourceError(undefined);
+ expect(screen.getByText('Ready')).toBeTruthy();
+ }
+);
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx
index b80df93802..26ee403e8e 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx
@@ -1,6 +1,5 @@
import { DebugSuspense } from '@channel/DebugSuspense';
-import { useIsAuthenticated, useUserId } from '@core/context/user';
-import { createMemo, type FlowComponent, on } from 'solid-js';
+import { createMemo, type FlowComponent } from 'solid-js';
import { QuickAccessContextProvider } from './context';
import { createQuickAccessValue } from './QuickAccessSource';
import type {
@@ -11,46 +10,37 @@ import type {
} from './types';
const QuickAccessProviderValue: FlowComponent = (props) => {
- const authenticated = useIsAuthenticated();
- const userId = useUserId();
- const source = createMemo(
- on(
- () => (authenticated() === true ? userId() : undefined),
- (id) => (id ? createQuickAccessValue() : undefined)
- )
- );
+ const source = createQuickAccessValue();
const useList = ((
...args: Bucket[] | [QuickAccessListOptions]
): QuickAccessList => {
const sourceList = createMemo(() => {
- const current = source();
- if (!current) return;
const first = args[0];
return typeof first === 'object'
- ? current.useList(first)
- : current.useList(...(args as Bucket[]));
+ ? source.useList(first)
+ : source.useList(...(args as Bucket[]));
});
return {
- error: () => sourceList()?.error(),
- items: () => sourceList()?.items() ?? [],
- totalCount: () => sourceList()?.totalCount() ?? 0,
- hasMore: () => sourceList()?.hasMore() ?? false,
- isLoading: () => sourceList()?.isLoading() ?? false,
- isLoadingMore: () => sourceList()?.isLoadingMore() ?? false,
+ error: () => sourceList().error(),
+ items: () => sourceList().items(),
+ totalCount: () => sourceList().totalCount(),
+ hasMore: () => sourceList().hasMore(),
+ isLoading: () => sourceList().isLoading(),
+ isLoadingMore: () => sourceList().isLoadingMore(),
loadMore: async () => {
- await sourceList()?.loadMore();
+ await sourceList().loadMore();
},
};
}) as QuickAccessContextValue['useList'];
const quickAccess: QuickAccessContextValue = {
useList,
- usesRecordSelection: () => source()?.usesRecordSelection() ?? false,
- usesSearchProjection: () => source()?.usesSearchProjection() ?? false,
- isLoading: () => source()?.isLoading() ?? false,
- refresh: () => source()?.refresh(),
- getById: (id) => source()?.getById(id),
+ usesRecordSelection: source.usesRecordSelection,
+ usesSearchProjection: source.usesSearchProjection,
+ isLoading: source.isLoading,
+ refresh: source.refresh,
+ getById: source.getById,
};
return (
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index 94dfc15275..778b38ba57 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -71,11 +71,6 @@ 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.ts
deleted file mode 100644
index 8031c6dc42..0000000000
--- a/apps/web/src/lib/core/context/user-info-gate.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { expect, it, vi } from 'vitest';
-
-const hasLoginCookie = vi.hoisted(() => vi.fn(() => false));
-vi.mock('@core/util/cookies', () => ({ hasLoginCookie }));
-
-import { shouldQueryUserInfo } from './user-info-gate';
-
-it('wakes an anonymous identity observer when another tab publishes a login marker', () => {
- 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.ts
index 8af34ecc99..9e08fc9ba4 100644
--- a/apps/web/src/lib/core/context/user-info-gate.ts
+++ b/apps/web/src/lib/core/context/user-info-gate.ts
@@ -10,11 +10,3 @@ 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.tsx
index ad30822365..7541da438e 100644
--- a/apps/web/src/lib/core/internal/BlockLoader.test.tsx
+++ b/apps/web/src/lib/core/internal/BlockLoader.test.tsx
@@ -4,8 +4,6 @@ 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.tsx
index 9a26d21f2c..4aa79c56db 100644
--- a/apps/web/src/lib/core/internal/BlockLoader.tsx
+++ b/apps/web/src/lib/core/internal/BlockLoader.tsx
@@ -1,7 +1,6 @@
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';
@@ -56,7 +55,6 @@ 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;
@@ -203,7 +201,6 @@ 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 provider
import('./trackBlockOpened')
.then(({ track }) => {
- if (authenticated() !== true) return;
track({
itemId: props.id,
blockName: data.__block,
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.tsx
deleted file mode 100644
index 34b423943b..0000000000
--- a/apps/web/src/lib/queries/auth/user-info-gate.test.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-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.ts
index 6cf49b916b..ad5a8041bd 100644
--- a/apps/web/src/lib/queries/auth/user-info.ts
+++ b/apps/web/src/lib/queries/auth/user-info.ts
@@ -1,8 +1,5 @@
import { syncPushRegistrations } from '@core/auth/push-registration-lifecycle';
-import {
- enableUserInfoQuery,
- shouldQueryUserInfo,
-} from '@core/context/user-info-gate';
+import { enableUserInfoQuery } 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';
@@ -56,7 +53,7 @@ export function useUserInfoQuery(options?: UseUserInfoQueryOptions) {
userInfoQueryOptions(
typeof options?.enabled === 'function'
? options.enabled()
- : (options?.enabled ?? shouldQueryUserInfo())
+ : (options?.enabled ?? true)
)
);
}
diff --git a/apps/web/src/lib/queries/channel/activity.ts b/apps/web/src/lib/queries/channel/activity.ts
index 738a6e2d9e..ce276f5748 100644
--- a/apps/web/src/lib/queries/channel/activity.ts
+++ b/apps/web/src/lib/queries/channel/activity.ts
@@ -6,20 +6,16 @@ import type { ActivityType } from '@service-storage/generated/schemas/activityTy
import 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(
- enabled: Accessor<boolean> = () => true
-) {
+export function useChannelsActivityQuery() {
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.ts
index 73b22011f1..c025bae477 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(enabled: Accessor<boolean> = () => true) {
- return useQuery(() => ({ ...listChannelsQueryOptions, enabled: enabled() }));
+export function useListChannelsQuery() {
+ return useQuery(() => listChannelsQueryOptions);
}
// The host is an app-level cache service, not component state; the key
diff --git a/apps/web/src/lib/queries/contacts/contacts.ts b/apps/web/src/lib/queries/contacts/contacts.ts
index 09a7292892..be0e81839e 100644
--- a/apps/web/src/lib/queries/contacts/contacts.ts
+++ b/apps/web/src/lib/queries/contacts/contacts.ts
@@ -1,4 +1,3 @@
-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';
@@ -17,11 +16,7 @@ export function contactsQueryOptions() {
/** The raw contacts query — for callers that need its loading state. */
export function useContactsQuery(enabled: Accessor<boolean> = () => true) {
- const authenticated = useIsAuthenticated();
- return useQuery(() => ({
- ...contactsQueryOptions(),
- enabled: authenticated() === true && enabled(),
- }));
+ return useQuery(() => ({ ...contactsQueryOptions(), enabled: enabled() }));
}
/**
@@ -31,10 +26,9 @@ 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 (authenticated() !== true || !query.isSuccess) return [];
+ if (!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.tsx
index dd4767469c..f3695adaa0 100644
--- a/apps/web/src/lib/queries/email/link-selection.test.tsx
+++ b/apps/web/src/lib/queries/email/link-selection.test.tsx
@@ -19,10 +19,7 @@ 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',
- useIsAuthenticated: () => () => true,
-}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));
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.tsx
index 26d731a5cf..395eaab2c8 100644
--- a/apps/web/src/lib/queries/email/link.test.tsx
+++ b/apps/web/src/lib/queries/email/link.test.tsx
@@ -1,30 +1,22 @@
import type { Link as EmailLink } from '@service-email/generated/schemas';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { cleanup, 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 { createSignal, Suspense } from 'solid-js';
+import { Suspense } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { emailKeys } from './keys';
-import {
- useDisableCalendarMutation,
- useEmailLinksQuery,
- useInboxHealthProbeQuery,
- usePrimaryEmailLinkId,
-} from './link';
+import { useDisableCalendarMutation, 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,
},
}));
@@ -36,10 +28,7 @@ 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',
- useIsAuthenticated: () => authenticated,
-}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));
let testQueryClient: QueryClient;
@@ -99,7 +88,6 @@ 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 } },
@@ -109,45 +97,6 @@ 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.ts
index 087c84af3a..c3828aeb18 100644
--- a/apps/web/src/lib/queries/email/link.ts
+++ b/apps/web/src/lib/queries/email/link.ts
@@ -1,4 +1,4 @@
-import { useIsAuthenticated, useUserId } from '@core/context/user';
+import { useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { Telemetry } from '@macro-inc/observability';
@@ -30,11 +30,9 @@ 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,
@@ -51,11 +49,10 @@ function fetchEmailLinks() {
}
export function useEmailLinksQuery(enabled: Accessor<boolean> = queryEnabled) {
- const authenticated = useIsAuthenticated();
return useQuery(() => ({
queryKey: emailKeys.links.queryKey,
queryFn: fetchEmailLinks,
- enabled: authenticated() === true && enabled(),
+ enabled: 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.tsx
index 2f0dac3894..0a36565f55 100644
--- a/apps/web/src/lib/queries/favorites/favorites.test.tsx
+++ b/apps/web/src/lib/queries/favorites/favorites.test.tsx
@@ -30,8 +30,6 @@ 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,
@@ -192,10 +190,7 @@ describe('favorites transport', () => {
const filter: FavoritesFilter = { entityType: ['channel'] };
renderHook(() => useFavoritesData(filter));
- expect(mocks.createGraphqlFavoritesQuery).toHaveBeenCalledWith(
- filter,
- expect.any(Function)
- );
+ expect(mocks.createGraphqlFavoritesQuery).toHaveBeenCalledWith(filter);
expect(mocks.getFavoritesRest).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/lib/queries/favorites/favorites.ts b/apps/web/src/lib/queries/favorites/favorites.ts
index 5211902e20..c126c90b8e 100644
--- a/apps/web/src/lib/queries/favorites/favorites.ts
+++ b/apps/web/src/lib/queries/favorites/favorites.ts
@@ -2,7 +2,6 @@ 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';
@@ -79,13 +78,11 @@ 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, enabled);
+ return createGraphqlFavoritesQuery(filter);
}
- return createRestFavoritesQuery(filter, enabled);
+ return createRestFavoritesQuery(filter);
}
// Cached callbacks outlive the hook; only the plain filter enters this closure.
@@ -100,14 +97,8 @@ function restFavoritesQueryOptions(filter?: FavoritesFilter) {
});
}
-function createRestFavoritesQuery(
- filter: FavoritesFilter | undefined,
- enabled: Accessor<boolean>
-) {
- return useQuery(() => ({
- ...restFavoritesQueryOptions(filter),
- enabled: enabled(),
- }));
+function createRestFavoritesQuery(filter?: FavoritesFilter) {
+ return useQuery(() => restFavoritesQueryOptions(filter));
}
/**
@@ -123,14 +114,12 @@ function createRestFavoritesQuery(
export function useFavoritesData(
filter?: FavoritesFilter
): Accessor<FavoritesList | undefined> {
- const authenticated = useIsAuthenticated();
- const enabled = () => authenticated() === true;
if (isFeatureEnabled(enableGraphqlSoup)) {
- const query = createGraphqlFavoritesQuery(filter, enabled);
- return () => (enabled() ? query.data : undefined);
+ const query = createGraphqlFavoritesQuery(filter);
+ return () => query.data;
}
- const query = createRestFavoritesQuery(filter, enabled);
- return () => (enabled() && query.isSuccess ? query.data : undefined);
+ const query = createRestFavoritesQuery(filter);
+ return () => (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.tsx
index 6c0b7f4b61..00f75eebc9 100644
--- a/apps/web/src/lib/queries/favorites/graphql.test.tsx
+++ b/apps/web/src/lib/queries/favorites/graphql.test.tsx
@@ -10,8 +10,6 @@ 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.ts
index d5c02161c2..f791dd84e2 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 { type Accessor, onCleanup } from 'solid-js';
+import { onCleanup } from 'solid-js';
import type { FavoriteMutationCallbacks } from './mutation';
type GraphqlReorderFavoritesArgs = { favorites: SetFavoriteArgs[] };
@@ -103,8 +103,7 @@ function activeFavoritesCacheTargets(
/** Creates the live urql-solid favorites query. */
export function createGraphqlFavoritesQuery(
- filter?: ListFavoritesParams,
- enabled: Accessor<boolean> = () => true
+ filter?: ListFavoritesParams
): GraphqlFavoritesQuery {
const variables = favoritesQueryVariables(filter);
const query = createUrqlQuery<
@@ -113,7 +112,6 @@ 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.ts
index 7015be1b27..11a5871bfc 100644
--- a/apps/web/src/lib/queries/history/history.ts
+++ b/apps/web/src/lib/queries/history/history.ts
@@ -1,6 +1,5 @@
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 {
@@ -127,12 +126,10 @@ const restHistoryQueryOptions = {
};
export function useHistoryQuery() {
- const authenticated = useIsAuthenticated();
const graphqlSoupFlag = useFeatureFlag(enableGraphqlSoup);
const activeQueryClient = useQueryClient();
const graphqlCacheHost = () => {
- if (authenticated() !== true || !graphqlSoupFlag().enabled)
- return undefined;
+ if (!graphqlSoupFlag().enabled) return undefined;
const cacheHost = getGraphqlSoupCacheHost();
return cacheHost?.disabled ? undefined : cacheHost;
};
@@ -160,12 +157,9 @@ export function useHistoryQuery() {
HistoryQueryKey
>(() => {
const cacheHost = graphqlCacheHost();
- return {
- ...(cacheHost
- ? cachedGraphqlHistoryQueryOptions(cacheHost)
- : restHistoryQueryOptions),
- enabled: authenticated() === true,
- };
+ return cacheHost
+ ? cachedGraphqlHistoryQueryOptions(cacheHost)
+ : restHistoryQueryOptions;
});
}
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.tsx
index eaf7c3df60..16e5e022d4 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,8 +17,6 @@ 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.ts
index 512eeb3d51..da2e34bda5 100644
--- a/apps/web/src/lib/queries/notification/unsubscribes.ts
+++ b/apps/web/src/lib/queries/notification/unsubscribes.ts
@@ -3,7 +3,6 @@ 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';
@@ -27,17 +26,13 @@ async function fetchUnsubscribes() {
return response.value.data;
}
-export function useMutedEntitiesQuery(
- args?: { limit?: number },
- enabled: Accessor<boolean> = () => true
-) {
+export function useMutedEntitiesQuery(args?: { limit?: number }) {
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.ts
index ba40e919fa..a411d0cba5 100644
--- a/apps/web/src/lib/queries/properties/definitions.ts
+++ b/apps/web/src/lib/queries/properties/definitions.ts
@@ -1,5 +1,4 @@
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';
@@ -47,10 +46,7 @@ export function useListPropertiesQuery(
params: Accessor<ListPropertiesQueryParams>,
enabled: Accessor<boolean> = () => true
) {
- const authenticated = useIsAuthenticated();
- return useQuery(() =>
- listPropertiesQueryOptions(params(), authenticated() === true && enabled())
- );
+ return useQuery(() => listPropertiesQueryOptions(params(), 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.ts
index 658762491c..9e63df65e9 100644
--- a/apps/web/src/lib/queries/storage/attachment-references.ts
+++ b/apps/web/src/lib/queries/storage/attachment-references.ts
@@ -1,4 +1,3 @@
-import { useIsAuthenticated } from '@core/context/user';
import { throwOnErr } from '@core/util/result';
import {
type ItemType,
@@ -50,11 +49,7 @@ export function useAttachmentReferencesQuery(
entityId: Accessor<string | null | undefined>,
entityType: Accessor<ItemType>
) {
- const authenticated = useIsAuthenticated();
return useQuery(() =>
- attachmentReferencesQueryOptions(
- entityType(),
- authenticated() === true ? entityId() : undefined
- )
+ attachmentReferencesQueryOptions(entityType(), entityId())
);
}
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.ts
index 6eade87efc..d424e08153 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,7 +37,6 @@ 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.ts
index 899f9324fd..747606fe15 100644
--- a/apps/web/src/lib/queries/storage/instructions-md.ts
+++ b/apps/web/src/lib/queries/storage/instructions-md.ts
@@ -4,7 +4,6 @@ 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';
@@ -51,11 +50,7 @@ function instructionsMdIdQueryOptions() {
* Returns null if not yet created, throws otherwise.
*/
export function useInstructionsMdIdQuery() {
- const authenticated = useIsAuthenticated();
- return useQuery(() => ({
- ...instructionsMdIdQueryOptions(),
- enabled: authenticated() === true,
- }));
+ return useQuery(() => instructionsMdIdQueryOptions());
}
const getInstructionsMdText = async (id: string | null | undefined) => {
@@ -101,14 +96,10 @@ function instructionsMdTextQueryOptions(
/** useQuery hook for retrieving the instructions md document text content */
export function useInstructionsMdTextQuery() {
- const authenticated = useIsAuthenticated();
const idQuery = useInstructionsMdIdQuery();
return useQuery(() =>
- instructionsMdTextQueryOptions(
- authenticated() === true && idQuery.isSuccess ? idQuery.data : undefined,
- authenticated() === true && idQuery.isSuccess
- )
+ instructionsMdTextQueryOptions(idQuery.data, idQuery.isSuccess)
);
}
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index 663366bcc5..835d5d3006 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 { useIsAuthenticated, useUserId } from '@core/context/user';
+import { useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
import { ThrownResultError, throwOnErr } from '@core/util/result';
import {
@@ -46,11 +46,10 @@ 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: authenticated() === true && (enabled?.() ?? true),
+ enabled: enabled?.() ?? true,
}));
}
diff --git a/apps/web/src/lib/service-clients/service-connection/websocket.ts b/apps/web/src/lib/service-clients/service-connection/websocket.ts
index cea45c78bb..6092aa958e 100644
--- a/apps/web/src/lib/service-clients/service-connection/websocket.ts
+++ b/apps/web/src/lib/service-clients/service-connection/websocket.ts
@@ -13,7 +13,6 @@ 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';
@@ -42,23 +41,13 @@ async function resolveWsUrl() {
return wsHost;
}
-export const connectionGatewaySessionTelemetry =
- createSessionWebsocketTelemetry('connection-gateway', resolveWsUrl);
-
-export const ws = new WebsocketBuilder(
- connectionGatewaySessionTelemetry.resolveUrl
-)
- .withAutoConnect(false)
+export const ws = new WebsocketBuilder(resolveWsUrl)
.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.ts
index 918882fa5f..34dfede1d8 100644
--- a/apps/web/src/lib/service-clients/service-storage/websocket.ts
+++ b/apps/web/src/lib/service-clients/service-storage/websocket.ts
@@ -8,7 +8,6 @@ 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.
@@ -21,19 +20,9 @@ const HEARTBEAT_INTERVAL = 300000;
*/
const HEARTBEAT_TIMEOUT = 5000;
-export const storageSessionTelemetry = createSessionWebsocketTelemetry(
- 'storage',
- () => SERVER_HOSTS['websocket-service']
-);
-
-const ws = new WebsocketBuilder(storageSessionTelemetry.resolveUrl)
- .withAutoConnect(false)
+const ws = new WebsocketBuilder(SERVER_HOSTS['websocket-service'])
.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.ts
deleted file mode 100644
index f65d55b219..0000000000
--- a/apps/web/src/lib/service-clients/session-websocket-telemetry.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-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.ts
deleted file mode 100644
index 4653a4f817..0000000000
--- a/apps/web/src/lib/service-clients/session-websocket-telemetry.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-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.tsx
index 993296c60e..e4b85ba577 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -15,7 +15,6 @@ 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';
@@ -177,7 +176,6 @@ 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.md
index 58d5b98e69..f5964129b0 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -4,19 +4,6 @@ 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 the
sharing 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. 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 to
this file**, the signed-in email, and **Request access**. View is selected by
default; choose View, Comment, or Edit where supported, submit, then verify
diff --git a/docs/agent-guide/observability.md b/docs/agent-guide/observability.md
index ec164c7de8..aaa05df4bf 100644
--- a/docs/agent-guide/observability.md
+++ b/docs/agent-guide/observability.md
@@ -69,28 +69,6 @@ trace context — timestamps + service are the only join for those.
applying and message fan-out remain untraced. Call joining now has a user-action
trace; 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 joining
Click **Start call** on `/app/meet/new` or **Join call** on a shared meeting's
diff --git a/packages/collaboration/README.md b/packages/collaboration/README.md
index 1738bc4c86..42e5589bc5 100644
--- a/packages/collaboration/README.md
+++ b/packages/collaboration/README.md
@@ -7,13 +7,7 @@ Shared collaboration runtime used by the web app and non-browser workers.
- `@macro-inc/collaboration/sync-service/*` contains the sync-service wire
protocol 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. 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.
+ deeper utilities are available through `websocket/*` subpaths.
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.ts
index dc36f0e3f0..18c15d71f2 100644
--- a/packages/collaboration/src/websocket/core/websocket-builder.ts
+++ b/packages/collaboration/src/websocket/core/websocket-builder.ts
@@ -69,14 +69,6 @@ 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.
*
@@ -195,7 +187,6 @@ 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.ts
index c40f7f8693..a3d7c20d72 100644
--- a/packages/collaboration/src/websocket/core/websocket-options.ts
+++ b/packages/collaboration/src/websocket/core/websocket-options.ts
@@ -17,9 +17,6 @@ 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.ts
index f055cd9578..7f7283d064 100644
--- a/packages/collaboration/src/websocket/core/websocket.ts
+++ b/packages/collaboration/src/websocket/core/websocket.ts
@@ -61,7 +61,6 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
private _binaryType?: BinaryType = 'blob'; // the binaryType to use
private _closedByUser: boolean = false; // whether the websocket was closed by the user
- private connectionGeneration = 0;
private _lastConnection?: Date; // timestamp of the last connection
private _underlyingWebsocket!: MinimalWebSocket; // assigned by tryConnect
private connectPending: boolean = false; // whether tryConnect is resolving its url / creating a socket
@@ -133,12 +132,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
this._url = resolver;
}
- this._closedByUser = options?.autoConnect === false;
- if (this._closedByUser) {
- this.connectionState = WebsocketConnectionState.Closed;
- } else {
- this.tryConnect();
- }
+ this.tryConnect();
}
/**
@@ -230,12 +224,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
* @return the readyState of the underlying websocket.
*/
get readyState(): number {
- return (
- this._underlyingWebsocket?.readyState ??
- (this.closedByUser
- ? WebsocketConnectionState.Closed
- : WebsocketConnectionState.Connecting)
- );
+ return this._underlyingWebsocket.readyState;
}
/**
@@ -245,7 +234,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
* @return the bufferedAmount of the underlying websocket.
*/
get bufferedAmount(): number {
- return this._underlyingWebsocket?.bufferedAmount ?? 0;
+ return this._underlyingWebsocket.bufferedAmount;
}
/**
@@ -255,7 +244,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;
}
/**
@@ -317,7 +306,6 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
public close(code?: number, reason?: string): void {
this.cancelScheduledConnectionRetry(); // cancel any scheduled retries
this._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.
@@ -373,13 +361,12 @@ 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 || generation !== this.connectionGeneration) {
+ if (this._closedByUser) {
return;
}
@@ -393,10 +380,6 @@ 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 listeners
this._underlyingWebsocket = newSocket;
@@ -423,18 +406,13 @@ 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 && generation === this.connectionGeneration) {
+ if (!this._closedByUser) {
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();
- }
}
}
@@ -891,14 +869,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
- // discards an old generation's URL and resolves a fresh one when it settles.
+ // attempt was resolving its url doesn't strand the instance (tryConnect
+ // bails on _closedByUser after the url resolves).
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. An unchanged generation
- // adopts this attempt; a closed generation retries with fresh credentials.
+ // tryConnect would orphan the first socket. With _closedByUser cleared
+ // above, the in-flight attempt is adopted as this reconnect.
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.ts
deleted file mode 100644
index b3d1a53bcd..0000000000
--- a/packages/collaboration/src/websocket/tests/websocket-auto-connect.test.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-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.ts
index 9ef952be9e..3da62d61ba 100644
--- a/packages/collaboration/src/websocket/tests/websocket-test-utils.ts
+++ b/packages/collaboration/src/websocket/tests/websocket-test-utils.ts
@@ -26,7 +26,8 @@ export const stopClient = (
): Promise<void> =>
new Promise<void>((resolve, reject) => {
if (client === undefined) return resolve();
- if (client.readyState === WebSocket.CLOSED) return resolve();
+ if (client.underlyingWebsocket?.readyState === WebSocket.CLOSED)
+ return resolve();
rejectAfter(timeout, 'failed to stop client').catch((err) => reject(err));
client.addEventListener(WebsocketEvent.Close, () => resolve(), {
once: true,