Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
startupsEnterpriseUrl,
} from '../../lib/plans';
import { useSquadPlanPrices } from '../../hooks/useSquadPlanPrices';
import { useStartupsSetupRefresh } from '../../hooks/useStartupsSetupRefresh';
import { useLogStartups } from '../../hooks/useLogStartups';
import {
StartupsSetup,
Expand Down Expand Up @@ -806,6 +807,8 @@ const SetupStep = ({
squad,
plan,
);
// Shows what the founder's agent changes over MCP as it happens
useStartupsSetupRefresh({ squad, enabled: !editing });
const preview = (
<StartupsPagePreview
squad={squad}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import type { ReactNode } from 'react';
import React from 'react';
import { act, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import defaultUser from '../../../../__tests__/fixture/loggedUser';
import { AuthContextProvider } from '../../../contexts/AuthContext';
import { generateQueryKey, RequestKey } from '../../../lib/query';
import {
STARTUPS_SETUP_REFRESH_MS,
useStartupsSetupRefresh,
} from './useStartupsSetupRefresh';

const squad = { id: 'squad1', handle: 'acme' };

const setup = (enabled = true) => {
const client = new QueryClient();
const invalidate = jest.spyOn(client, 'invalidateQueries');
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={client}>
<AuthContextProvider
user={defaultUser}
updateUser={jest.fn()}
tokenRefreshed
getRedirectUri={jest.fn()}
loadingUser={false}
loadedUserFromCache
>
{children}
</AuthContextProvider>
</QueryClientProvider>
);
const { unmount } = renderHook(
() => useStartupsSetupRefresh({ squad, enabled }),
{
wrapper,
},
);
const refetchedKeys = () =>
invalidate.mock.calls.map(([filters]) => filters?.queryKey);

return { unmount, invalidate, refetchedKeys };
};

describe('useStartupsSetupRefresh', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('refetches the page, plan, seats and intel settings every 30 seconds', () => {
const { refetchedKeys } = setup();
expect(refetchedKeys()).toHaveLength(0);

act(() => {
jest.advanceTimersByTime(STARTUPS_SETUP_REFRESH_MS);
});

expect(refetchedKeys()).toEqual([
generateQueryKey(RequestKey.Squad, defaultUser, 'acme'),
generateQueryKey(RequestKey.SquadSubscription, defaultUser, 'squad1'),
generateQueryKey(RequestKey.SquadSeats, defaultUser, 'squad1'),
generateQueryKey(
RequestKey.SquadIntel,
defaultUser,
'squad1',
'settings',
),
]);
});

it('refetches when the window gets focus back', () => {
const { invalidate } = setup();

act(() => {
window.dispatchEvent(new Event('focus'));
});

expect(invalidate).toHaveBeenCalledTimes(4);
});

it('stops when disabled or unmounted', () => {
const disabled = setup(false);
act(() => {
window.dispatchEvent(new Event('focus'));
jest.advanceTimersByTime(STARTUPS_SETUP_REFRESH_MS);
});
expect(disabled.invalidate).not.toHaveBeenCalled();

const mounted = setup();
mounted.unmount();
act(() => {
jest.advanceTimersByTime(STARTUPS_SETUP_REFRESH_MS);
});
expect(mounted.invalidate).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useAuthContext } from '../../../contexts/AuthContext';
import type { Squad } from '../../../graphql/sources';
import { generateQueryKey, RequestKey } from '../../../lib/query';
import { getSquadId } from '../lib/features';

/** How often the onboarding checks for what the founder's agent changed. */
export const STARTUPS_SETUP_REFRESH_MS = 30 * 1000;

/**
* Keeps the onboarding's checklist and page preview close to live while the
* founder's agent edits the page over MCP in another window: refetches when the
* window gets focus back and every 30 seconds while the tab is visible.
*/
export const useStartupsSetupRefresh = ({
squad,
enabled = true,
}: {
squad: Pick<Squad, 'id' | 'handle'>;
/** Off while a row is open, so a refetch doesn't reset what's being typed. */
enabled?: boolean;
}): void => {
const client = useQueryClient();
const { user } = useAuthContext();
const sourceId = getSquadId(squad);
const { handle } = squad;

useEffect(() => {
if (!enabled || !user) {
return undefined;
}

let lastRefresh = 0;
const refresh = () => {
// Switching tabs fires both focus and visibilitychange
if (Date.now() - lastRefresh < 1000) {
return;
}

lastRefresh = Date.now();
[
// The page itself, its products and its branding
generateQueryKey(RequestKey.Squad, user, handle),
generateQueryKey(RequestKey.SquadSubscription, user, sourceId),
generateQueryKey(RequestKey.SquadSeats, user, sourceId),
generateQueryKey(RequestKey.SquadIntel, user, sourceId, 'settings'),
].forEach((queryKey) => client.invalidateQueries({ queryKey }));
};
const isVisible = () => document.visibilityState !== 'hidden';
const onVisibilityChange = () => {
if (isVisible()) {
refresh();
}
};

// The agent usually runs in another app, so coming back to the browser
// window doesn't change the tab's visibility, only the window's focus.
window.addEventListener('focus', refresh);
document.addEventListener('visibilitychange', onVisibilityChange);
const interval = setInterval(() => {
if (isVisible()) {
refresh();
}
}, STARTUPS_SETUP_REFRESH_MS);

return () => {
window.removeEventListener('focus', refresh);
document.removeEventListener('visibilitychange', onVisibilityChange);
clearInterval(interval);
};
}, [client, enabled, handle, sourceId, user]);
};
Loading