mirror of
https://github.com/stackblitz-labs/bolt.diy
synced 2025-05-11 23:40:55 +00:00
fix: improve push to github option (#1111)
* feat: better push to githubbutton * added url update on push to github
This commit is contained in:
parent
df766c98d4
commit
6d4196a2b4
@ -6,6 +6,7 @@ import { generateId } from '~/utils/fileUtils';
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { LoadingOverlay } from '~/components/ui/LoadingOverlay';
|
import { LoadingOverlay } from '~/components/ui/LoadingOverlay';
|
||||||
|
import type { IChatMetadata } from '~/lib/persistence';
|
||||||
|
|
||||||
const IGNORE_PATTERNS = [
|
const IGNORE_PATTERNS = [
|
||||||
'node_modules/**',
|
'node_modules/**',
|
||||||
@ -35,7 +36,7 @@ const ig = ignore().add(IGNORE_PATTERNS);
|
|||||||
|
|
||||||
interface GitCloneButtonProps {
|
interface GitCloneButtonProps {
|
||||||
className?: string;
|
className?: string;
|
||||||
importChat?: (description: string, messages: Message[]) => Promise<void>;
|
importChat?: (description: string, messages: Message[], metadata?: IChatMetadata) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function GitCloneButton({ importChat }: GitCloneButtonProps) {
|
export default function GitCloneButton({ importChat }: GitCloneButtonProps) {
|
||||||
@ -98,7 +99,7 @@ ${file.content}
|
|||||||
messages.push(commandsMessage);
|
messages.push(commandsMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
|
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages, { gitUrl: repoUrl });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during import:', error);
|
console.error('Error during import:', error);
|
||||||
|
@ -94,7 +94,7 @@ ${file.content}
|
|||||||
messages.push(commandsMessage);
|
messages.push(commandsMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
|
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages, { gitUrl: repoUrl });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during import:', error);
|
console.error('Error during import:', error);
|
||||||
|
@ -18,6 +18,7 @@ import { EditorPanel } from './EditorPanel';
|
|||||||
import { Preview } from './Preview';
|
import { Preview } from './Preview';
|
||||||
import useViewport from '~/lib/hooks';
|
import useViewport from '~/lib/hooks';
|
||||||
import Cookies from 'js-cookie';
|
import Cookies from 'js-cookie';
|
||||||
|
import { chatMetadata, useChatHistory } from '~/lib/persistence';
|
||||||
|
|
||||||
interface WorkspaceProps {
|
interface WorkspaceProps {
|
||||||
chatStarted?: boolean;
|
chatStarted?: boolean;
|
||||||
@ -66,6 +67,8 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
|
|||||||
const unsavedFiles = useStore(workbenchStore.unsavedFiles);
|
const unsavedFiles = useStore(workbenchStore.unsavedFiles);
|
||||||
const files = useStore(workbenchStore.files);
|
const files = useStore(workbenchStore.files);
|
||||||
const selectedView = useStore(workbenchStore.currentView);
|
const selectedView = useStore(workbenchStore.currentView);
|
||||||
|
const metadata = useStore(chatMetadata);
|
||||||
|
const { updateChatMestaData } = useChatHistory();
|
||||||
|
|
||||||
const isSmallViewport = useViewport(1024);
|
const isSmallViewport = useViewport(1024);
|
||||||
|
|
||||||
@ -171,18 +174,28 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
|
|||||||
<PanelHeaderButton
|
<PanelHeaderButton
|
||||||
className="mr-1 text-sm"
|
className="mr-1 text-sm"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const repoName = prompt(
|
let repoName = metadata?.gitUrl?.split('/').slice(-1)[0]?.replace('.git', '') || null;
|
||||||
'Please enter a name for your new GitHub repository:',
|
let repoConfirmed: boolean = true;
|
||||||
'bolt-generated-project',
|
|
||||||
);
|
if (repoName) {
|
||||||
|
repoConfirmed = confirm(`Do you want to push to the repository ${repoName}?`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!repoName || !repoConfirmed) {
|
||||||
|
repoName = prompt(
|
||||||
|
'Please enter a name for your new GitHub repository:',
|
||||||
|
'bolt-generated-project',
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
}
|
||||||
|
|
||||||
if (!repoName) {
|
if (!repoName) {
|
||||||
alert('Repository name is required. Push to GitHub cancelled.');
|
alert('Repository name is required. Push to GitHub cancelled.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const githubUsername = Cookies.get('githubUsername');
|
let githubUsername = Cookies.get('githubUsername');
|
||||||
const githubToken = Cookies.get('githubToken');
|
let githubToken = Cookies.get('githubToken');
|
||||||
|
|
||||||
if (!githubUsername || !githubToken) {
|
if (!githubUsername || !githubToken) {
|
||||||
const usernameInput = prompt('Please enter your GitHub username:');
|
const usernameInput = prompt('Please enter your GitHub username:');
|
||||||
@ -193,9 +206,26 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
workbenchStore.pushToGitHub(repoName, usernameInput, tokenInput);
|
githubUsername = usernameInput;
|
||||||
} else {
|
githubToken = tokenInput;
|
||||||
workbenchStore.pushToGitHub(repoName, githubUsername, githubToken);
|
|
||||||
|
Cookies.set('githubUsername', usernameInput);
|
||||||
|
Cookies.set('githubToken', tokenInput);
|
||||||
|
Cookies.set(
|
||||||
|
'git:github.com',
|
||||||
|
JSON.stringify({ username: tokenInput, password: 'x-oauth-basic' }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const commitMessage =
|
||||||
|
prompt('Please enter a commit message:', 'Initial commit') || 'Initial commit';
|
||||||
|
workbenchStore.pushToGitHub(repoName, commitMessage, githubUsername, githubToken);
|
||||||
|
|
||||||
|
if (!metadata?.gitUrl) {
|
||||||
|
updateChatMestaData({
|
||||||
|
...(metadata || {}),
|
||||||
|
gitUrl: `https://github.com/${githubUsername}/${repoName}.git`,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
@ -92,6 +92,7 @@ export function useGit() {
|
|||||||
},
|
},
|
||||||
onAuthFailure: (url, _auth) => {
|
onAuthFailure: (url, _auth) => {
|
||||||
toast.error(`Error Authenticating with ${url.split('/')[2]}`);
|
toast.error(`Error Authenticating with ${url.split('/')[2]}`);
|
||||||
|
throw `Error Authenticating with ${url.split('/')[2]}`;
|
||||||
},
|
},
|
||||||
onAuthSuccess: (url, auth) => {
|
onAuthSuccess: (url, auth) => {
|
||||||
saveGitAuth(url, auth);
|
saveGitAuth(url, auth);
|
||||||
@ -107,6 +108,8 @@ export function useGit() {
|
|||||||
return { workdir: webcontainer.workdir, data };
|
return { workdir: webcontainer.workdir, data };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Git clone error:', error);
|
console.error('Git clone error:', error);
|
||||||
|
|
||||||
|
// toast.error(`Git clone error ${(error as any).message||""}`);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -2,6 +2,11 @@ import type { Message } from 'ai';
|
|||||||
import { createScopedLogger } from '~/utils/logger';
|
import { createScopedLogger } from '~/utils/logger';
|
||||||
import type { ChatHistoryItem } from './useChatHistory';
|
import type { ChatHistoryItem } from './useChatHistory';
|
||||||
|
|
||||||
|
export interface IChatMetadata {
|
||||||
|
gitUrl: string;
|
||||||
|
gitBranch?: string;
|
||||||
|
}
|
||||||
|
|
||||||
const logger = createScopedLogger('ChatHistory');
|
const logger = createScopedLogger('ChatHistory');
|
||||||
|
|
||||||
// this is used at the top level and never rejects
|
// this is used at the top level and never rejects
|
||||||
@ -53,6 +58,7 @@ export async function setMessages(
|
|||||||
urlId?: string,
|
urlId?: string,
|
||||||
description?: string,
|
description?: string,
|
||||||
timestamp?: string,
|
timestamp?: string,
|
||||||
|
metadata?: IChatMetadata,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const transaction = db.transaction('chats', 'readwrite');
|
const transaction = db.transaction('chats', 'readwrite');
|
||||||
@ -69,6 +75,7 @@ export async function setMessages(
|
|||||||
urlId,
|
urlId,
|
||||||
description,
|
description,
|
||||||
timestamp: timestamp ?? new Date().toISOString(),
|
timestamp: timestamp ?? new Date().toISOString(),
|
||||||
|
metadata,
|
||||||
});
|
});
|
||||||
|
|
||||||
request.onsuccess = () => resolve();
|
request.onsuccess = () => resolve();
|
||||||
@ -204,6 +211,7 @@ export async function createChatFromMessages(
|
|||||||
db: IDBDatabase,
|
db: IDBDatabase,
|
||||||
description: string,
|
description: string,
|
||||||
messages: Message[],
|
messages: Message[],
|
||||||
|
metadata?: IChatMetadata,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const newId = await getNextId(db);
|
const newId = await getNextId(db);
|
||||||
const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat
|
const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat
|
||||||
@ -214,6 +222,8 @@ export async function createChatFromMessages(
|
|||||||
messages,
|
messages,
|
||||||
newUrlId, // Use the new urlId
|
newUrlId, // Use the new urlId
|
||||||
description,
|
description,
|
||||||
|
undefined, // Use the current timestamp
|
||||||
|
metadata,
|
||||||
);
|
);
|
||||||
|
|
||||||
return newUrlId; // Return the urlId instead of id for navigation
|
return newUrlId; // Return the urlId instead of id for navigation
|
||||||
@ -230,5 +240,19 @@ export async function updateChatDescription(db: IDBDatabase, id: string, descrip
|
|||||||
throw new Error('Description cannot be empty');
|
throw new Error('Description cannot be empty');
|
||||||
}
|
}
|
||||||
|
|
||||||
await setMessages(db, id, chat.messages, chat.urlId, description, chat.timestamp);
|
await setMessages(db, id, chat.messages, chat.urlId, description, chat.timestamp, chat.metadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateChatMetadata(
|
||||||
|
db: IDBDatabase,
|
||||||
|
id: string,
|
||||||
|
metadata: IChatMetadata | undefined,
|
||||||
|
): Promise<void> {
|
||||||
|
const chat = await getMessages(db, id);
|
||||||
|
|
||||||
|
if (!chat) {
|
||||||
|
throw new Error('Chat not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
await setMessages(db, id, chat.messages, chat.urlId, chat.description, chat.timestamp, metadata);
|
||||||
}
|
}
|
||||||
|
@ -13,6 +13,7 @@ import {
|
|||||||
setMessages,
|
setMessages,
|
||||||
duplicateChat,
|
duplicateChat,
|
||||||
createChatFromMessages,
|
createChatFromMessages,
|
||||||
|
type IChatMetadata,
|
||||||
} from './db';
|
} from './db';
|
||||||
|
|
||||||
export interface ChatHistoryItem {
|
export interface ChatHistoryItem {
|
||||||
@ -21,6 +22,7 @@ export interface ChatHistoryItem {
|
|||||||
description?: string;
|
description?: string;
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
|
metadata?: IChatMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;
|
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;
|
||||||
@ -29,7 +31,7 @@ export const db = persistenceEnabled ? await openDatabase() : undefined;
|
|||||||
|
|
||||||
export const chatId = atom<string | undefined>(undefined);
|
export const chatId = atom<string | undefined>(undefined);
|
||||||
export const description = atom<string | undefined>(undefined);
|
export const description = atom<string | undefined>(undefined);
|
||||||
|
export const chatMetadata = atom<IChatMetadata | undefined>(undefined);
|
||||||
export function useChatHistory() {
|
export function useChatHistory() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { id: mixedId } = useLoaderData<{ id?: string }>();
|
const { id: mixedId } = useLoaderData<{ id?: string }>();
|
||||||
@ -65,6 +67,7 @@ export function useChatHistory() {
|
|||||||
setUrlId(storedMessages.urlId);
|
setUrlId(storedMessages.urlId);
|
||||||
description.set(storedMessages.description);
|
description.set(storedMessages.description);
|
||||||
chatId.set(storedMessages.id);
|
chatId.set(storedMessages.id);
|
||||||
|
chatMetadata.set(storedMessages.metadata);
|
||||||
} else {
|
} else {
|
||||||
navigate('/', { replace: true });
|
navigate('/', { replace: true });
|
||||||
}
|
}
|
||||||
@ -81,6 +84,21 @@ export function useChatHistory() {
|
|||||||
return {
|
return {
|
||||||
ready: !mixedId || ready,
|
ready: !mixedId || ready,
|
||||||
initialMessages,
|
initialMessages,
|
||||||
|
updateChatMestaData: async (metadata: IChatMetadata) => {
|
||||||
|
const id = chatId.get();
|
||||||
|
|
||||||
|
if (!db || !id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await setMessages(db, id, initialMessages, urlId, description.get(), undefined, metadata);
|
||||||
|
chatMetadata.set(metadata);
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('Failed to update chat metadata');
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
},
|
||||||
storeMessageHistory: async (messages: Message[]) => {
|
storeMessageHistory: async (messages: Message[]) => {
|
||||||
if (!db || messages.length === 0) {
|
if (!db || messages.length === 0) {
|
||||||
return;
|
return;
|
||||||
@ -109,7 +127,7 @@ export function useChatHistory() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await setMessages(db, chatId.get() as string, messages, urlId, description.get());
|
await setMessages(db, chatId.get() as string, messages, urlId, description.get(), undefined, chatMetadata.get());
|
||||||
},
|
},
|
||||||
duplicateCurrentChat: async (listItemId: string) => {
|
duplicateCurrentChat: async (listItemId: string) => {
|
||||||
if (!db || (!mixedId && !listItemId)) {
|
if (!db || (!mixedId && !listItemId)) {
|
||||||
@ -125,13 +143,13 @@ export function useChatHistory() {
|
|||||||
console.log(error);
|
console.log(error);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
importChat: async (description: string, messages: Message[]) => {
|
importChat: async (description: string, messages: Message[], metadata?: IChatMetadata) => {
|
||||||
if (!db) {
|
if (!db) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newId = await createChatFromMessages(db, description, messages);
|
const newId = await createChatFromMessages(db, description, messages, metadata);
|
||||||
window.location.href = `/chat/${newId}`;
|
window.location.href = `/chat/${newId}`;
|
||||||
toast.success('Chat imported successfully');
|
toast.success('Chat imported successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -434,7 +434,7 @@ export class WorkbenchStore {
|
|||||||
return syncedFiles;
|
return syncedFiles;
|
||||||
}
|
}
|
||||||
|
|
||||||
async pushToGitHub(repoName: string, githubUsername?: string, ghToken?: string) {
|
async pushToGitHub(repoName: string, commitMessage?: string, githubUsername?: string, ghToken?: string) {
|
||||||
try {
|
try {
|
||||||
// Use cookies if username and token are not provided
|
// Use cookies if username and token are not provided
|
||||||
const githubToken = ghToken || Cookies.get('githubToken');
|
const githubToken = ghToken || Cookies.get('githubToken');
|
||||||
@ -523,7 +523,7 @@ export class WorkbenchStore {
|
|||||||
const { data: newCommit } = await octokit.git.createCommit({
|
const { data: newCommit } = await octokit.git.createCommit({
|
||||||
owner: repo.owner.login,
|
owner: repo.owner.login,
|
||||||
repo: repo.name,
|
repo: repo.name,
|
||||||
message: 'Initial commit from your app',
|
message: commitMessage || 'Initial commit from your app',
|
||||||
tree: newTree.sha,
|
tree: newTree.sha,
|
||||||
parents: [latestCommitSha],
|
parents: [latestCommitSha],
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user