Merge branch 'main' into github-import

This commit is contained in:
Anirban Kar
2024-12-03 02:48:37 +05:30
55 changed files with 31567 additions and 3783 deletions

View File

@@ -35,6 +35,8 @@ export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Re
return env.MISTRAL_API_KEY || cloudflareEnv.MISTRAL_API_KEY;
case 'OpenAILike':
return env.OPENAI_LIKE_API_KEY || cloudflareEnv.OPENAI_LIKE_API_KEY;
case 'Together':
return env.TOGETHER_API_KEY || cloudflareEnv.TOGETHER_API_KEY;
case 'xAI':
return env.XAI_API_KEY || cloudflareEnv.XAI_API_KEY;
case 'Cohere':
@@ -48,6 +50,8 @@ export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Re
export function getBaseURL(cloudflareEnv: Env, provider: string) {
switch (provider) {
case 'Together':
return env.TOGETHER_API_BASE_URL || cloudflareEnv.TOGETHER_API_BASE_URL;
case 'OpenAILike':
return env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL;
case 'LMStudio':

View File

@@ -146,6 +146,8 @@ export function getModel(provider: string, model: string, env: Env, apiKeys?: Re
return getGoogleModel(apiKey, model);
case 'OpenAILike':
return getOpenAILikeModel(baseURL, apiKey, model);
case 'Together':
return getOpenAILikeModel(baseURL, apiKey, model);
case 'Deepseek':
return getDeepseekModel(apiKey, model);
case 'Mistral':

View File

@@ -1,11 +1,11 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck TODO: Provider proper types
import { streamText as _streamText, convertToCoreMessages } from 'ai';
import { convertToCoreMessages, streamText as _streamText } from 'ai';
import { getModel } from '~/lib/.server/llm/model';
import { MAX_TOKENS } from './constants';
import { getSystemPrompt } from './prompts';
import { MODEL_LIST, DEFAULT_MODEL, DEFAULT_PROVIDER, MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
import { DEFAULT_MODEL, DEFAULT_PROVIDER, MODEL_LIST, MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
interface ToolResult<Name extends string, Args, Result> {
toolCallId: string;

View File

@@ -0,0 +1,52 @@
import { useState, useMemo, useCallback } from 'react';
import { debounce } from '~/utils/debounce';
import type { ChatHistoryItem } from '~/lib/persistence';
interface UseSearchFilterOptions {
items: ChatHistoryItem[];
searchFields?: (keyof ChatHistoryItem)[];
debounceMs?: number;
}
export function useSearchFilter({
items = [],
searchFields = ['description'],
debounceMs = 300,
}: UseSearchFilterOptions) {
const [searchQuery, setSearchQuery] = useState('');
const debouncedSetSearch = useCallback(debounce(setSearchQuery, debounceMs), []);
const handleSearchChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
debouncedSetSearch(event.target.value);
},
[debouncedSetSearch],
);
const filteredItems = useMemo(() => {
if (!searchQuery.trim()) {
return items;
}
const query = searchQuery.toLowerCase();
return items.filter((item) =>
searchFields.some((field) => {
const value = item[field];
if (typeof value === 'string') {
return value.toLowerCase().includes(query);
}
return false;
}),
);
}, [items, searchQuery, searchFields]);
return {
searchQuery,
filteredItems,
handleSearchChange,
};
}

View File

@@ -6,6 +6,11 @@ const logger = createScopedLogger('ChatHistory');
// this is used at the top level and never rejects
export async function openDatabase(): Promise<IDBDatabase | undefined> {
if (typeof indexedDB === 'undefined') {
console.error('indexedDB is not available in this environment.');
return undefined;
}
return new Promise((resolve) => {
const request = indexedDB.open('boltHistory', 1);
@@ -176,14 +181,7 @@ export async function forkChat(db: IDBDatabase, chatId: string, messageId: strin
// Get messages up to and including the selected message
const messages = chat.messages.slice(0, messageIndex + 1);
// Generate new IDs
const newId = await getNextId(db);
const urlId = await getUrlId(db, newId);
// Create the forked chat
await setMessages(db, newId, messages, urlId, chat.description ? `${chat.description} (fork)` : 'Forked chat');
return urlId;
return createChatFromMessages(db, chat.description ? `${chat.description} (fork)` : 'Forked chat', messages);
}
export async function duplicateChat(db: IDBDatabase, id: string): Promise<string> {
@@ -193,15 +191,23 @@ export async function duplicateChat(db: IDBDatabase, id: string): Promise<string
throw new Error('Chat not found');
}
return createChatFromMessages(db, `${chat.description || 'Chat'} (copy)`, chat.messages);
}
export async function createChatFromMessages(
db: IDBDatabase,
description: string,
messages: Message[],
): Promise<string> {
const newId = await getNextId(db);
const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat
await setMessages(
db,
newId,
chat.messages,
messages,
newUrlId, // Use the new urlId
`${chat.description || 'Chat'} (copy)`,
description,
);
return newUrlId; // Return the urlId instead of id for navigation

View File

@@ -4,7 +4,15 @@ import { atom } from 'nanostores';
import type { Message } from 'ai';
import { toast } from 'react-toastify';
import { workbenchStore } from '~/lib/stores/workbench';
import { getMessages, getNextId, getUrlId, openDatabase, setMessages, duplicateChat } from './db';
import {
getMessages,
getNextId,
getUrlId,
openDatabase,
setMessages,
duplicateChat,
createChatFromMessages,
} from './db';
export interface ChatHistoryItem {
id: string;
@@ -35,7 +43,7 @@ export function useChatHistory() {
setReady(true);
if (persistenceEnabled) {
toast.error(`Chat persistence is unavailable`);
toast.error('Chat persistence is unavailable');
}
return;
@@ -55,7 +63,7 @@ export function useChatHistory() {
description.set(storedMessages.description);
chatId.set(storedMessages.id);
} else {
navigate(`/`, { replace: true });
navigate('/', { replace: true });
}
setReady(true);
@@ -113,6 +121,45 @@ export function useChatHistory() {
console.log(error);
}
},
importChat: async (description: string, messages: Message[]) => {
if (!db) {
return;
}
try {
const newId = await createChatFromMessages(db, description, messages);
window.location.href = `/chat/${newId}`;
toast.success('Chat imported successfully');
} catch (error) {
if (error instanceof Error) {
toast.error('Failed to import chat: ' + error.message);
} else {
toast.error('Failed to import chat');
}
}
},
exportChat: async (id = urlId) => {
if (!db || !id) {
return;
}
const chat = await getMessages(db, id);
const chatData = {
messages: chat.messages,
description: chat.description,
exportDate: new Date().toISOString(),
};
const blob = new Blob([JSON.stringify(chatData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `chat-${new Date().toISOString()}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
},
};
}

View File

@@ -84,23 +84,22 @@ export class ActionRunner {
}
if (action.executed) {
return;
return; // No return value here
}
if (isStreaming && action.type !== 'file') {
return;
return; // No return value here
}
this.#updateAction(actionId, { ...action, ...data.action, executed: !isStreaming });
// eslint-disable-next-line consistent-return
return (this.#currentExecutionPromise = this.#currentExecutionPromise
this.#currentExecutionPromise = this.#currentExecutionPromise
.then(() => {
this.#executeAction(actionId, isStreaming);
return this.#executeAction(actionId, isStreaming);
})
.catch((error) => {
console.error('Action failed:', error);
}));
});
}
async #executeAction(actionId: string, isStreaming: boolean = false) {

View File

@@ -14,6 +14,7 @@ import { saveAs } from 'file-saver';
import { Octokit, type RestEndpointMethodTypes } from '@octokit/rest';
import * as nodePath from 'node:path';
import { extractRelativePath } from '~/utils/diff';
import { description } from '~/lib/persistence';
export interface ArtifactState {
id: string;
@@ -328,6 +329,13 @@ export class WorkbenchStore {
const zip = new JSZip();
const files = this.files.get();
// Get the project name from the description input, or use a default name
const projectName = (description.value ?? 'project').toLocaleLowerCase().split(' ').join('_');
// Generate a simple 6-character hash based on the current timestamp
const timestampHash = Date.now().toString(36).slice(-6);
const uniqueProjectName = `${projectName}_${timestampHash}`;
for (const [filePath, dirent] of Object.entries(files)) {
if (dirent?.type === 'file' && !dirent.isBinary) {
const relativePath = extractRelativePath(filePath);
@@ -350,8 +358,9 @@ export class WorkbenchStore {
}
}
// Generate the zip file and save it
const content = await zip.generateAsync({ type: 'blob' });
saveAs(content, 'project.zip');
saveAs(content, `${uniqueProjectName}.zip`);
}
async syncFiles(targetHandle: FileSystemDirectoryHandle) {
@@ -369,7 +378,9 @@ export class WorkbenchStore {
}
// create or get the file
const fileHandle = await currentHandle.getFileHandle(pathSegments[pathSegments.length - 1], { create: true });
const fileHandle = await currentHandle.getFileHandle(pathSegments[pathSegments.length - 1], {
create: true,
});
// write the file content
const writable = await fileHandle.createWritable();