Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modgpt/fix/clerk2 #662

Closed
wants to merge 6 commits into from
Closed
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 @@ -9,6 +9,7 @@ import {
type PanelsRefs,
} from "@studio/main/PageBottomPane";
import { SignInRequired } from "@studio/main/PaneLayout/SignInRequired";
import { useModStore } from "@studio/store/zustand/mod";
import { TabNames } from "@studio/store/zustand/view";
import type { ReactNode } from "react";
import { PanelGroup } from "react-resizable-panels";
Expand All @@ -33,7 +34,8 @@ export const useTabs = ({
beforePanel: PanelData;
afterPanel: PanelData;
}) => {
const aiAssistantData = useAiService();
const { setContent } = useModStore();
const aiAssistantData = useAiService({ setCodemod: setContent });
const tabs = [
{
value: TabNames.MODGPT,
Expand Down
2 changes: 2 additions & 0 deletions apps/frontend/app/(website)/studio/main/modGPT/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const ChatBase = ({
setToken,
canAddMessages,
startIterativeCodemodGeneration,
resetMessages,
},
className,
isSignedIn,
Expand All @@ -37,6 +38,7 @@ const ChatBase = ({
/>
<PromptPanel
id={id}
resetMessages={resetMessages}
isLoading={isLoading}
stop={handleStop}
append={append}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ interface Props {
}

export const ChatMessages = ({ messages }: Props) => {
const { setContent } = useModStore();

if (!messages.length) {
return null;
}
Expand All @@ -32,18 +30,6 @@ export const ChatMessages = ({ messages }: Props) => {
<div key={index}>
<ChatMessage message={message} />

{message.codemod && (
<Button
variant={"solid"}
disabled={false}
color={"primary"}
className={"w-full"}
onClick={() => message.codemod && setContent(message.codemod)}
>
Use codemod
</Button>
)}

{index < messages.length - 1 && (
<Separator className="my-4 md:my-8" />
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type PromptPanelProps = Pick<
typeof useAiService
>["startIterativeCodemodGeneration"];
canAddMessages: ReturnType<typeof useAiService>["canAddMessages"];
resetMessages: ReturnType<typeof useAiService>["resetMessages"];
};

export function PromptPanel(props: PromptPanelProps) {
Expand All @@ -46,6 +47,7 @@ export function PromptPanel(props: PromptPanelProps) {
setToken,
startIterativeCodemodGeneration,
canAddMessages,
resetMessages,
} = props;
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const [expandedHelper, setExpandedHelper] = useState(true);
Expand Down Expand Up @@ -104,7 +106,7 @@ export function PromptPanel(props: PromptPanelProps) {
input={input}
setInput={setInput}
isLoading={isLoading}
onReset={() => setMessages([])}
onReset={resetMessages}
/>
</div>
</div>
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/(website)/studio/main/modGPT/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { SEND_CHAT } from "@studio/constants";

export const shouldUseCodemodAi = isServer
? false
: new URLSearchParams(window.location.search)
: new URLSearchParams(window?.location.search)
.get(FEATURE_FLAG_QUERY_KEY)
?.split(",")
.includes(CODEMOD_AI_FEATURE_FLAG);
Expand All @@ -22,5 +22,5 @@ const prodGptServer = shouldUseCodemodAi
? "https://backend.codemod.com/modgpt"
: "https://backend.codemod.com";
export const modGptServer = `${
isDevelopment ? "http://0.0.0.0:9999" : prodGptServer
isDevelopment ? "http://0.0.0.0:8082" : prodGptServer
}/${SEND_CHAT}`;
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,26 @@ import {
useSaveMssgsToLocalStorage,
} from "@chatbot/useAiService/utils";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";

export const useAiService = () => {
// const initialMessages = useInitialMss();
const showCodemodCopiedToast = () =>
toast("Codemod copied to the right pane", {
position: "top-center",
duration: 12000,
});
export const useAiService = ({
setCodemod,
}: {
setCodemod: (content: string) => void;
}) => {
const initialMessages = useInitialMss();

const [messages, setMessages] = useState<LLMMessage[]>([]);
const [canAddMessages, setCanAddMessages] = useState(true);

// useEffect(() => {
// setMessages(initialMessages);
// }, [initialMessages]);
useEffect(() => {
setMessages(initialMessages);
}, [initialMessages]);

const {
isLoading,
Expand All @@ -32,33 +42,53 @@ export const useAiService = () => {
setCanAddMessages,
});

const lastMss = modGPTMessages?.at(-1);
const lastModGptMss = modGPTMessages?.at(-1);
const lastMss = messages?.at(-1);

useEffect(() => {
if (!codemodAIMessage) return;
setMessages((m) => [...m, codemodAIMessage]);

const updateMessages =
lastMss?.role === "assistant"
? () =>
messages.with(-1, {
...lastMss,
content: `${lastMss.content}\n\n${codemodAIMessage.content}`,
})
: (m: LLMMessage[]) => [...m, codemodAIMessage];
setMessages(updateMessages);

if (codemodAIMessage.codemod) {
showCodemodCopiedToast();
appendModGPTMessages({
name: "app",
role: "user",
content: `This is a codemod generated: ${codemodAIMessage.codemod}. Briefly explain. List item by item. Be very concise, I will add additional questions if needed. Start with "here\'s a breakdown of the codemod"`,
content: `This is a codemod generated: ${codemodAIMessage.codemod}. Remember it. Reply with just a single sentence - asking if a user wants to know more about generated codemod"`,
});
setCodemod(codemodAIMessage.codemod);
}
}, [codemodAIMessage]);

useEffect(() => {
if (!lastMss?.content) return;
const index = messages.findIndex(({ id }) => id === lastMss.id);
if (!lastModGptMss?.content) return;

const index = messages.findIndex(({ id }) => id === lastModGptMss.id);
const updateMessages =
index > -1
? () => messages.with(index, lastMss)
: (m: LLMMessage[]) => [...m, lastMss];
? () => messages.with(index, lastModGptMss)
: (m: LLMMessage[]) => [...m, lastModGptMss];
setMessages(updateMessages);
}, [lastMss?.content]);
}, [lastModGptMss?.content]);

const resetMessages = () => {
setMessages([]);
localStorage.removeItem("frozenMessages");
};

// useSaveMssgsToLocalStorage({ messages, isLoading });
useSaveMssgsToLocalStorage({ messages, isLoading });

return {
resetMessages,
isLoading,
messages,
setMessages,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const useSaveMssgsToLocalStorage = ({
messages,
}: { isLoading: boolean; messages: Message[] }) => {
useEffect(() => {
if (isLoading || messages.length === 0) {
if (isLoading) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/hooks/useFeatureFlags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useState } from "react";

const useFeatureFlags = () => {
const [features] = useState(() => {
const urlParams = new URLSearchParams(window.location.search);
const urlParams = new URLSearchParams(window?.location.search);

const featureFlags = urlParams.get(FEATURE_FLAG_QUERY_KEY) ?? "";
return featureFlags.split(",");
Expand Down
2 changes: 1 addition & 1 deletion apps/modgpt/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:20-alpine3.16 as builder
FROM node:20-alpine3.16 as builder

WORKDIR /app

Expand Down
2 changes: 2 additions & 0 deletions apps/modgpt/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ services:
CLAUDE_API_KEY: ${CLAUDE_API_KEY}
REPLICATE_API_KEY: ${REPLICATE_API_KEY}
OPEN_AI_API_KEY: ${OPEN_AI_API_KEY}
NODE_ENV: ${NODE_ENV}
CLERK_DISABLED: ${CLERK_DISABLED}
ports:
- '8082:8082'
networks:
Expand Down
2 changes: 1 addition & 1 deletion apps/modgpt/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@codemod-com/modgpt",
"version": "0.0.8",
"version": "0.0.9",
"type": "module",
"scripts": {
"build": "node esbuild.config.js",
Expand Down
3 changes: 2 additions & 1 deletion apps/modgpt/src/dev-utils/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ export const areClerkKeysSet = (
);
};

export const isDevelopment = NODE_ENV === "development";
export const clerkApplied = areClerkKeysSet(environment);
export const isDevelopment = false; //NODE_ENV === "development";
3 changes: 1 addition & 2 deletions apps/modgpt/src/dev-utils/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const ALLOWED_ORIGINS = [
/^https?:\/\/codemod\.com$/,
];

const corsDisableHeaders = {
export const corsDisableHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*",
Expand All @@ -18,7 +18,6 @@ export const getCorsDisabledHeaders = (fastify: FastifyInstance) => {
fastify.options("/sendChat", (request, reply) => {
reply.status(204).headers(corsDisableHeaders).send();
});
return corsDisableHeaders;
};

const X_CODEMOD_ACCESS_TOKEN = (
Expand Down
5 changes: 1 addition & 4 deletions apps/modgpt/src/fastifyInstance.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import Fastify, { type FastifyPluginCallback } from "fastify";
import type { FastifyPluginCallback } from "fastify";

export const fastify = Fastify({
logger: true,
});
export type Instance = Parameters<FastifyPluginCallback>[0];
31 changes: 21 additions & 10 deletions apps/modgpt/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ import { clerkPlugin } from "@clerk/fastify";
import cors from "@fastify/cors";
import fastifyMultipart from "@fastify/multipart";
import fastifyRateLimit from "@fastify/rate-limit";
import type { FastifyPluginCallback } from "fastify";
import { environment } from "./dev-utils/configs";
import { corsOptions } from "./dev-utils/cors";
import { fastify } from "./fastifyInstance";
import Fastify, { type FastifyPluginCallback } from "fastify";
import { clerkApplied, environment, isDevelopment } from "./dev-utils/configs";
import { corsOptions, getCorsDisabledHeaders } from "./dev-utils/cors";

export const initApp = async (toRegister: FastifyPluginCallback[]) => {
const { PORT: port } = environment;
if (Number.isNaN(port)) {
throw new Error(`Invalid port ${port}`);
}

const fastify = Fastify({
logger: true,
});

const handleProcessExit = (code: 0 | 1) => {
fastify.close();

Expand Down Expand Up @@ -46,6 +49,20 @@ export const initApp = async (toRegister: FastifyPluginCallback[]) => {
done();
});

if (!isDevelopment && clerkApplied) {
const clerkOptions = {
publishableKey: environment.CLERK_PUBLISH_KEY,
secretKey: environment.CLERK_SECRET_KEY,
jwtKey: environment.CLERK_JWT_KEY,
};

fastify.register(clerkPlugin, clerkOptions);
} else {
if (!clerkApplied)
console.warn("No Clerk keys set. Authentication is disabled.");
if (isDevelopment) console.info("ENV set to development");
}

await fastify.register(cors, corsOptions);

await fastify.register(fastifyRateLimit, {
Expand All @@ -55,12 +72,6 @@ export const initApp = async (toRegister: FastifyPluginCallback[]) => {

await fastify.register(fastifyMultipart);

await fastify.register(clerkPlugin, {
publishableKey: environment.CLERK_PUBLISH_KEY,
secretKey: environment.CLERK_SECRET_KEY,
jwtKey: environment.CLERK_JWT_KEY,
});

for (const plugin of toRegister) {
await fastify.register(plugin);
}
Expand Down
Loading