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
57 changes: 57 additions & 0 deletions app/components/VersionNotificationBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { toast } from 'sonner';
import { Button } from '@ui/Button';
import { SymbolIcon } from '@radix-ui/react-icons';
import { captureMessage } from '@sentry/remix';
import useSWR from 'swr';

export default function useVersionNotificationBanner() {
// eslint-disable-next-line local/no-direct-process-env
const currentSha = process.env.VERCEL_GIT_COMMIT_SHA;
const { data, error } = useSWR<{ sha?: string | null }>('/api/version', {
// Refresh every hour.
refreshInterval: 1000 * 60 * 60,
// Refresh on focus at most every 10 minutes.
focusThrottleInterval: 1000 * 60 * 10,
shouldRetryOnError: false,
fetcher: versionFetcher,
});

if (!error && data?.sha && currentSha && data.sha !== currentSha) {
toast.info(
<div className="flex flex-col">
A new version of Chef is available! Refresh this page to update.
<Button
className="ml-auto w-fit items-center"
inline
size="xs"
icon={<SymbolIcon />}
// Make the href the current page so that the page refreshes.
onClick={() => window.location.reload()}
>
Refresh
</Button>
</div>,
{
id: 'chefVersion',
duration: Number.POSITIVE_INFINITY,
},
);
}
}

const versionFetcher = async (url: string) => {
const res = await fetch(url, {
method: 'POST',
});

if (!res.ok) {
try {
const { error } = await res.json();
captureMessage(error);
} catch (_e) {
captureMessage('Failed to fetch dashboard version information.');
}
throw new Error('Failed to fetch dashboard version information.');
}
return res.json();
};
1 change: 1 addition & 0 deletions app/entry.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { RemixBrowser, useLocation, useMatches } from '@remix-run/react';
import { startTransition, useEffect } from 'react';
import { hydrateRoot } from 'react-dom/client';

// eslint-disable-next-line local/no-direct-process-env
const environment = process.env.VERCEL_ENV === 'production' ? 'production' : 'development';

Sentry.init({
Expand Down
4 changes: 4 additions & 0 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import posthog from 'posthog-js';
import 'allotment/dist/style.css';

import { ErrorDisplay } from './components/ErrorComponent';
import useVersionNotificationBanner from './components/VersionNotificationBanner';

export async function loader() {
// These environment variables are available in the client (they aren't secret).
// eslint-disable-next-line local/no-direct-process-env
const CONVEX_URL = process.env.VITE_CONVEX_URL || globalThis.process.env.CONVEX_URL!;
const CONVEX_OAUTH_CLIENT_ID = globalThis.process.env.CONVEX_OAUTH_CLIENT_ID!;
return json({
Expand Down Expand Up @@ -130,6 +132,8 @@ export function Layout({ children }: { children: React.ReactNode }) {
});
}, []);

useVersionNotificationBanner();

return (
<>
<ClientOnly>
Expand Down
2 changes: 1 addition & 1 deletion app/routes/api.enhance-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export async function action({ request }: ActionFunctionArgs) {
}

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
apiKey: globalThis.process.env.OPENAI_API_KEY,
});

const completion = await openai.chat.completions.create({
Expand Down
80 changes: 80 additions & 0 deletions app/routes/api.version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { json } from '@vercel/remix';
import type { ActionFunctionArgs } from '@vercel/remix';

export async function action({ request }: ActionFunctionArgs) {
const globalEnv = globalThis.process.env;
const projectId = globalEnv.VERCEL_PROJECT_ID;
const teamId = globalEnv.VERCEL_TEAM_ID;
const productionBranchUrl = globalEnv.VERCEL_PRODUCTION_BRANCH_URL || 'chef.convex.dev';

if (request.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: { 'Content-Type': 'application/json' },
});
}

if (!globalEnv.VERCEL_TOKEN) {
return json({ error: 'Failed to fetch version information' }, { status: 500 });
}

const requestOptions = {
headers: {
Authorization: `Bearer ${globalThis.process.env.VERCEL_TOKEN}`,
},
method: 'get',
};

if (globalThis.process.env.VERCEL_ENV !== 'preview') {
// If we're not in a preview deployment, fetch the production deployment from Vercel's undocumented
// production-deployment API.
// This response includes a boolean indicating if the production deployment is stale (i.e. rolled back)
// We accept the risk that this API might change because it is not documented, meaning the version
// notification feature might silently fail.
const prodResponse = await fetch(
`https://vercel.com/api/v1/projects/${projectId}/production-deployment?teamId=${teamId}`,
requestOptions,
);
if (!prodResponse.ok) {
return json({ error: 'Failed to fetch production version information' }, { status: 500 });
}

const prodData = await prodResponse.json();

// Since we retrieved data from an undocumented API
// let's defensively check that the data we need is present
// and return an opaque error if it isn't.
if (!prodData || typeof prodData.deploymentIsStale !== 'boolean') {
return json({ error: 'Failed to fetch production deployment' }, { status: 500 });
}

// If the production deployment is rolled back,
// we should not show a version notification.
if (prodData.deploymentIsStale) {
return json({ sha: null }, { status: 200 });
}
}

// Even though we retrieved the production data, we might be on a preview branch deployment.
// So, fetch the data specific to the latest branch deployment.
const branchUrl = globalThis.process.env.VERCEL_BRANCH_URL || productionBranchUrl;
if (!branchUrl) {
throw new Error('VERCEL_BRANCH_URL or VERCEL_PRODUCTION_BRANCH_URL not set');
}
const branchResponse = await fetch(
`https://api.vercel.com/v13/deployments/${branchUrl}?teamId=${teamId}`,
requestOptions,
);
if (!branchResponse.ok) {
throw new Error('Failed to fetch branch version information');
}

const branchData = await branchResponse.json();

return json(
{
sha: branchData.gitSource.sha,
},
{ status: 200 },
);
}
35 changes: 35 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,34 @@ import reactPlugin from 'eslint-plugin-react';
import reactHooksPlugin from 'eslint-plugin-react-hooks';
import noGlobalFetchRule from './eslint-rules/no-global-fetch.js';

const noDirectProcessEnv = {
meta: {
type: 'problem',
docs: {
description: 'Disallow direct process.env usage',
category: 'Best Practices',
},
fixable: null,
schema: [],
messages: {
noDirectProcessEnv:
'Direct process.env usage is not allowed. Use globalThis.process.env instead because process.env is shimmed in for both the browser and the server.',
},
},
create(context) {
return {
MemberExpression(node) {
if (node.object.name === 'process' && node.property.name === 'env') {
context.report({
node,
messageId: 'noDirectProcessEnv',
});
}
},
};
},
};

export default [
{
ignores: [
Expand All @@ -24,6 +52,11 @@ export default [
plugins: {
react: reactPlugin,
'react-hooks': reactHooksPlugin,
local: {
rules: {
'no-direct-process-env': noDirectProcessEnv,
},
},
},
rules: {
...reactPlugin.configs.flat.recommended.rules,
Expand Down Expand Up @@ -84,6 +117,8 @@ export default [
selector: 'Literal[value=/bottom-4(?:\\D|$)/i]',
},
],
// Don't allow direct process.env usage
'local/no-direct-process-env': 'error',
},
settings: {
react: {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"dependencies": {
"@ai-sdk/amazon-bedrock": "^2.2.9",
"@ai-sdk/anthropic": "^1.2.12",
"@convex-dev/ai-sdk-google": "1.2.17",
"@ai-sdk/google": "^1.2.11",
"@ai-sdk/openai": "^1.3.6",
"@ai-sdk/react": "^1.2.5",
Expand All @@ -57,6 +56,7 @@
"@codemirror/search": "^6.5.8",
"@codemirror/state": "^6.4.1",
"@codemirror/view": "^6.35.0",
"@convex-dev/ai-sdk-google": "1.2.17",
"@convex-dev/design-system": "0.1.11",
"@convex-dev/eslint-plugin": "0.0.1-alpha.4",
"@convex-dev/migrations": "^0.2.8",
Expand Down Expand Up @@ -135,6 +135,7 @@
"remix-utils": "^7.7.0",
"shiki": "^1.24.0",
"sonner": "^2.0.3",
"swr": "^2.3.4",
"ua-parser-js": "^1.0.40",
"undici": "^7.7.0",
"unist-util-visit": "^5.0.0",
Expand Down
16 changes: 15 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

77 changes: 0 additions & 77 deletions template/eslint.config.js

This file was deleted.

1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default defineConfig((config) => {
return {
define: {
'process.env.VERCEL_ENV': JSON.stringify(process.env.VERCEL_ENV),
'process.env.VERCEL_GIT_COMMIT_SHA': JSON.stringify(process.env.VERCEL_GIT_COMMIT_SHA),
},

/*
Expand Down