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
165 changes: 63 additions & 102 deletions backend/knowledge.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,26 @@ This document provides an overview of the Manicode backend architecture, key com
9. [Build and Deployment](#build-and-deployment)
10. [Security Considerations](#security-considerations)
11. [TODO List](#todo-list)
12. [User Quota and Billing](#user-quota-and-billing)
12. [Automatic URL Detection and Scraping](#automatic-url-detection-and-scraping)

## Development Workflow

### Hot Reloading

The project uses hot reloading to improve development efficiency. This is implemented for both the backend and npm-app:

1. Backend:
- Uses Bun's built-in watch functionality to monitor both `backend/src` and `common/src` directories.
- Run with `bun run dev` in the backend directory.

2. npm-app:
- Similar setup to the backend, watching both `npm-app/src` and `common/src`.
- Run with `bun run dev` in the npm-app directory.

This setup ensures consistent development practices across different parts of the project, allowing for immediate feedback on code changes.


## Architecture Overview

The Manicode backend is built on Node.js using TypeScript. It uses an Express server for HTTP requests and a WebSocket server for real-time communication with clients. The backend integrates with the Claude AI model to process user inputs and generate code changes.
Expand Down Expand Up @@ -70,48 +88,35 @@ The backend handles file operations for the Manicode project:
- **Reading Files**: The `read_files` tool allows the AI to access project file contents.
- **Applying Changes**: The `applyChanges` function in `prompts.ts` processes and applies file modifications suggested by the AI.

## Code Organization and Best Practices

1. **Centralize Shared Logic**: When implementing functionality that's used in multiple places (e.g., web API and backend), create shared functions to promote code reuse and consistency. This is particularly important for business logic like referral handling and usage calculations.

2. **Shared Function Location**: Place shared functions in a common directory accessible to both the web API and backend. Consider creating a `common/src/utils` directory for such shared functionality.

3. **DRY Principle**: Always look for opportunities to refactor repeated code into shared, reusable functions. This not only reduces code duplication but also makes maintenance and updates easier.

4. **Consistent API**: When creating shared functions, ensure they have a consistent API that can be easily used by different parts of the application.

5. **Testing Shared Functions**: Implement unit tests for shared functions to ensure they work correctly in all contexts where they are used.

6. **Documentation**: Document shared functions clearly, including their purpose, inputs, outputs, and any side effects, so that other developers can use them effectively.

7. **Version Control**: When making changes to shared functions, consider the impact on all parts of the application that use them, and test thoroughly.
## Web Scraping

8. **Dependency Injection**: Prefer pulling common dependencies (like database connections or environment variables) from centralized locations rather than passing them as parameters. This reduces function complexity and improves maintainability.
The backend now includes a web scraping tool that allows the AI assistant to retrieve content from external web pages. This functionality is useful for gathering information from documentation, APIs, or other web-based resources.

9. **Single Responsibility Principle**: Design functions to have a single, well-defined purpose. For example, separate the logic of determining eligibility for a referral code from the generation of the full referral link.
- **Tool Name**: `scrape_web_page`
- **Input**: A URL of the web page to scrape
- **Output**: The content of the scraped web page

10. **Abstraction Refinement**: Be prepared to refine initial implementations as the system's needs become clearer. This might involve changing function signatures, splitting functions, or adjusting their purposes to better fit the overall architecture.
## Debugging and Logging

- Avoid adding logging statements directly to utility functions in the `common/` directory.
- Prefer to add logging in the calling functions within the `backend/` directory.
- When investigating issues, focus on adding temporary logging to the relevant backend functions rather than modifying shared utility functions.


## Error Handling and Quota Management

## Development Guidelines
### Quota Exceeded Errors

1. **Type Safety**: Utilize TypeScript's type system to ensure code reliability and catch errors early.
2. **Error Handling**: Implement proper error handling and logging throughout the application.
3. **Code Organization**: Keep related functionality grouped in appropriate modules and files.
4. **Documentation**: Maintain clear and up-to-date documentation, including this knowledge file.
5. **Testing**: Implement unit tests for critical components and functions.
6. **Environment Variables**: Use environment variables for configuration and sensitive information.
7. **Code Style**: Follow consistent coding style and use tools like Prettier for formatting.
When a user exceeds their quota, the error message returned now includes the current usage information. This helps users understand their current status without requiring an additional API call.

## Web Scraping
Implementation details:

The backend now includes a web scraping tool that allows the AI assistant to retrieve content from external web pages. This functionality is useful for gathering information from documentation, APIs, or other web-based resources.
- The `protec` middleware in `websockets/middleware.ts` handles quota checks.
- For both authenticated and anonymous users, when quota is exceeded:
1. Retrieve current usage: `const { usage, limit } = await quotaManager.checkQuota(id)`
2. Include usage in error message: `return getUsageInfo(true, fingerprintId, userId)`

- **Tool Name**: `scrape_web_page`
- **Input**: A URL of the web page to scrape
- **Output**: The content of the scraped web page
This approach ensures that clients receive immediate feedback about their quota status, improving user experience and reducing unnecessary API calls.

## Tool Handling

Expand All @@ -127,29 +132,6 @@ The backend implements a tool handling system that allows the AI assistant to pe
2. **Error Catching**: WebSocket errors are caught and logged in both server and client code.
3. **Graceful Degradation**: The system attempts to handle errors gracefully, providing meaningful error messages when possible.

## Logging

- The project uses the pino logging library for structured logging.
- In production, use structured JSON logs for better parsing and analysis.
- In development, use pretty-printed logs for improved readability.
- Configure logging levels using the `LOG_LEVEL` environment variable.
- Example configuration:

```typescript
import pino from 'pino'
import { env } from '../env.mjs'

export const logger = pino({
level: env.LOG_LEVEL || 'info',
transport: env.NODE_ENV === 'production'
? undefined // Use default JSON logger in production
: {
target: 'pino-pretty',
options: {
colorize: true
}
}
})
## Build and Deployment

1. **Build Process**: The backend uses TypeScript compilation to build the project.
Expand All @@ -170,6 +152,20 @@ export const logger = pino({
4. Create a robust testing suite for backend components.
5. Optimize the file diff generation process for better reliability and performance.

## User Quota and Billing

### Usage Limit Handling

- The system tracks user usage and compares it against their quota limit.
- Warning messages are shown at 25%, 50%, and 75% of the usage limit.
- When a user reaches or exceeds 100% of their usage limit:
- An error message MUST ALWAYS be displayed to the user.
- This error message should inform the user that they've reached their monthly limit.
- For logged-in users, provide a link to the pricing page for upgrades.
- For anonymous users, prompt them to log in for more credits.
- If available, include a referral link for additional credits.


## Referral System

The referral system is an important feature of our application. Here are key points to remember:
Expand All @@ -186,61 +182,26 @@ The referral system is an important feature of our application. Here are key poi

Remember to keep the referral system logic consistent between the backend API and the websocket server to ensure uniform behavior across different parts of the application.

## Recent Updates

1. **Error Handling Improvements**:

- Updated error messages in the `protec` middleware to include more helpful information and the support email address.
- Changed the return type of some middleware functions from `Error` to `ServerAction` for more consistent error handling.

2. **Usage Information Refactoring**:

- Renamed `sendUsageInfo` to `getUsageInfo` in `websocket-action.ts`.
- Modified `getUsageInfo` to return a usage response object instead of directly sending an action.
- Updated the `usage-response` action schema to include a `showUser` boolean field.

3. **Environment Configuration**:

- Added `NEXT_PUBLIC_SUPPORT_EMAIL` to the environment variables in `env.mjs`.

## Debugging Docker Issues

- When encountering "Cannot find module" errors in a Docker container, it's important to verify the contents of the container itself, not just the local build.
- SSH access to the machine running the Docker container provides valuable debugging capabilities.
- The `dist` directory being correct locally doesn't guarantee it's correct inside the container.
- If a container is continuously restarting, it often indicates that the application is crashing immediately after starting. This prevents executing commands inside the container directly.
- The absence of the `dist` directory in the Docker container can cause "Cannot find module" errors, even if the directory exists locally.

## Git and Docker Best Practices

- The `dist` directory should be ignored by Git to avoid checking in build files.
- However, the `dist` directory needs to be included in the Docker image for the application to run correctly.
- The build process should occur before creating the Docker image to ensure the latest compiled files are included.

## Prompts

The backend uses several prompts to guide the AI assistant's behavior:

1. **System Prompt**: Initializes the AI assistant with project-specific context and instructions.
2. **Request Files Prompt**: Determines which files are relevant to a user's request.
3. **Main Prompt**: Processes the user's input and generates responses, including code changes.

### Request Files Prompt

- Located in `src/request-files-prompt.ts`
- Purpose: Identify all potentially relevant files for a user's request
- Key features:
- Uses chain-of-thought reasoning to consider all possible relevant files
- Aims to be comprehensive, requesting up to 100 files or more if necessary
- Considers indirect dependencies and files that provide context
- Outputs a thought process and a list of file paths

The Request Files Prompt is executed before the Main Prompt to ensure that all necessary files are loaded into the system context before processing the user's request.

## File Diff Generation

The backend uses two main strategies for generating file diffs:

1. **Diff Blocks Generation**: Implemented in `generate-diffs-prompt.ts`.
2. **Diff via Expansion**: Implemented in `generate-diffs-via-expansion.ts`.

### Using Bun for Testing

This project uses Bun for testing instead of Jest. When writing tests, keep the following in mind:
4. **CLI Enhancements**:
- Improved the formatting of the welcome message in the CLI.

- Use `import { mock } from 'bun:test'` instead of Jest's mocking functions.
- Bun's test API is similar to Jest's, but there are some differences in implementation.
- When mocking methods, use `mock(object.method)` instead of Jest's `jest.spyOn(object, 'method')`.
- Bun's `mock` function expects 0-1 arguments, not 2 like Jest's `spyOn`.
These changes aim to provide a better user experience by offering more informative error messages, streamlining usage information handling, and improving the overall system consistency.

Remember to keep this knowledge file updated as the application evolves or new features are added.
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
"license": "UNLICENSED",
"scripts": {
"start": "bun run -r tsconfig-paths/register src/index.ts",
"dev": "bun --hot run -r tsconfig-paths/register src/index.ts",
"prebuild": "bun clean && cd ../common && bun run ../scripts/build-version-info.js",
"build": "tsc --build && tsc-alias",
"postbuild": "mkdir -p dist/common && cp -R ../common/dist/* dist/common && tsc-alias",
"clean": "rm -rf dist && rm -f tsconfig.tsbuildinfo",
"dev": "nodemon --exec bun run -r tsconfig-paths/register src/index.ts",
"test": "bun test",
"test:manifold": "bun test src/__tests__/manifold-project.test.ts",
"test:watch": "bun test --watch"
Expand Down
1 change: 1 addition & 0 deletions backend/src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const env = createEnv({
ENVIRONMENT: z.string().min(1),
NEXT_PUBLIC_APP_URL: z.string().min(1),
NEXTAUTH_SECRET: z.string().min(1),
NEXT_PUBLIC_SUPPORT_EMAIL: z.string().min(1),
},
runtimeEnv: process.env,
})
2 changes: 1 addition & 1 deletion backend/src/openai-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export async function promptOpenAI(
temperature: 0,
// store: true,
}),
timeoutPromise(200000) as Promise<OpenAI.Chat.ChatCompletion>,
timeoutPromise(120_000) as Promise<OpenAI.Chat.ChatCompletion>,
])

if (
Expand Down
57 changes: 29 additions & 28 deletions backend/src/websockets/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { WebSocket } from 'ws'
import { ClientAction } from 'common/actions'
import { ClientAction, ServerAction } from 'common/actions'
import { match, P } from 'ts-pattern'
import db from 'common/db'
import * as schema from 'common/db/schema'
Expand All @@ -8,31 +8,32 @@ import {
AuthenticatedQuotaManager,
} from '../billing/quota-manager'
import { sql, eq } from 'drizzle-orm'
import { sendAction } from './websocket-action'
import { genUsageResponse, sendAction } from './websocket-action'
import { logger } from '@/util/logger'
import { env } from '@/env.mjs'

export class WebSocketMiddleware {
private middlewares: Array<
(
action: ClientAction,
clientSessionId: string,
ws: WebSocket
) => Promise<void | Error>
) => Promise<void | ServerAction>
> = []

use<T extends ClientAction['type']>(
callback: (
action: Extract<ClientAction, { type: T }>,
clientSessionId: string,
ws: WebSocket
) => Promise<void | Error>
) => Promise<void | ServerAction>
) {
this.middlewares.push(
callback as (
action: ClientAction,
clientSessionId: string,
ws: WebSocket
) => Promise<void | Error>
) => Promise<void | ServerAction>
)
}

Expand All @@ -42,13 +43,10 @@ export class WebSocketMiddleware {
ws: WebSocket
): Promise<boolean> {
for (const middleware of this.middlewares) {
const res = await middleware(action, clientSessionId, ws)
if (res) {
console.error('Middleware execution halted:', res)
sendAction(ws, {
type: 'action-error',
message: res.message,
})
const actionOrContinue = await middleware(action, clientSessionId, ws)
if (actionOrContinue) {
logger.error('Middleware execution halted:', actionOrContinue)
sendAction(ws, actionOrContinue)
return false
}
}
Expand Down Expand Up @@ -85,7 +83,7 @@ protec.use(async (action, _clientSessionId, ws) => {
{
authToken: P.string,
},
async ({ authToken }) => {
async ({ authToken, fingerprintId }) => {
const quotas = await db
.select({
userId: schema.user.id,
Expand All @@ -98,17 +96,20 @@ protec.use(async (action, _clientSessionId, ws) => {

const quota = quotas[0]
if (!quota) {
return new Error(`Unable to find user for given token ${authToken}!`)
return {
type: 'action-error' as const,
message: `Unable to find user for given token ${authToken}! Please reach out to ${env.NEXT_PUBLIC_SUPPORT_EMAIL} for help.`,
}
}

const quotaManager = new AuthenticatedQuotaManager()
if (quota.quotaExceeded) {
if (quota.nextQuotaReset < new Date()) {
// End date is in the past, so we should reset the quota
const quotaManager = new AuthenticatedQuotaManager()
await quotaManager.resetQuota(quota.userId)
} else {
console.error(`Quota exceeded for user ${quota.userId}`)
return new Error(`Quota exceeded! Enter 'usage' to learn more.`)
logger.error(`Quota exceeded for user ${quota.userId}`)
return genUsageResponse(fingerprintId, quota.userId)
}
}
return
Expand Down Expand Up @@ -138,29 +139,29 @@ protec.use(async (action, _clientSessionId, ws) => {

const quota = quotas[0]
if (!quota) {
return new Error(
`Unable to find fingerprint for given id ${fingerprintId}!`
)
return {
type: 'action-error' as const,
message: `Unable to find fingerprint for given id ${fingerprintId}! Please reach out to ${env.NEXT_PUBLIC_SUPPORT_EMAIL} for help.`,
}
}

const quotaManager = new AnonymousQuotaManager()
if (quota.quotaExceeded) {
if (quota.nextQuotaReset < new Date()) {
// End date is in the past, so we should reset the quota
const quotaManager = new AnonymousQuotaManager()
quotaManager.resetQuota(quota.fingerprintId)
} else {
console.error(
`Quota exceeded for fingerprint ${quota.fingerprintId}`
)
return new Error(`Quota exceeded! Enter 'usage' to learn more.`)
logger.error(`Quota exceeded for fingerprint ${fingerprintId}`)
return genUsageResponse(fingerprintId)
}
}
return
}
)
.otherwise(() => {
return new Error(
'No authToken or fingerprintId found, cannot check quota'
)
return {
type: 'action-error' as const,
message: `No authToken or fingerprintId found, cannot check quota. Please reach out to ${env.NEXT_PUBLIC_SUPPORT_EMAIL} for help.`,
}
})
})
Loading