diff --git a/backend/knowledge.md b/backend/knowledge.md index a8df0ae500..fa23c75e68 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -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. @@ -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 @@ -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. @@ -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: @@ -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. diff --git a/backend/package.json b/backend/package.json index e335922ba2..3c2b161cea 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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" diff --git a/backend/src/env.mjs b/backend/src/env.mjs index e65add2659..2d9d328d3f 100644 --- a/backend/src/env.mjs +++ b/backend/src/env.mjs @@ -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, }) diff --git a/backend/src/openai-api.ts b/backend/src/openai-api.ts index 20d2b87799..b496432b91 100644 --- a/backend/src/openai-api.ts +++ b/backend/src/openai-api.ts @@ -49,7 +49,7 @@ export async function promptOpenAI( temperature: 0, // store: true, }), - timeoutPromise(200000) as Promise, + timeoutPromise(120_000) as Promise, ]) if ( diff --git a/backend/src/websockets/middleware.ts b/backend/src/websockets/middleware.ts index 25cc97c26b..c3781bc4d6 100644 --- a/backend/src/websockets/middleware.ts +++ b/backend/src/websockets/middleware.ts @@ -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' @@ -8,8 +8,9 @@ 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< @@ -17,7 +18,7 @@ export class WebSocketMiddleware { action: ClientAction, clientSessionId: string, ws: WebSocket - ) => Promise + ) => Promise > = [] use( @@ -25,14 +26,14 @@ export class WebSocketMiddleware { action: Extract, clientSessionId: string, ws: WebSocket - ) => Promise + ) => Promise ) { this.middlewares.push( callback as ( action: ClientAction, clientSessionId: string, ws: WebSocket - ) => Promise + ) => Promise ) } @@ -42,13 +43,10 @@ export class WebSocketMiddleware { ws: WebSocket ): Promise { 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 } } @@ -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, @@ -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 @@ -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.`, + } }) }) diff --git a/backend/src/websockets/websocket-action.ts b/backend/src/websockets/websocket-action.ts index c3b00edab8..728d3819d8 100644 --- a/backend/src/websockets/websocket-action.ts +++ b/backend/src/websockets/websocket-action.ts @@ -56,6 +56,47 @@ async function calculateUsage(fingerprintId: string, userId?: string) { return { usage: creditsUsed, limit: quota } } +export async function genUsageResponse( + fingerprintId: string, + userId?: string +): Promise> { + const params = await withLoggerContext( + { fingerprintId, userId }, + async () => { + const { usage, limit } = await calculateUsage(fingerprintId, userId) + logger.info('Sending usage info') + + let referralLink: string | undefined = undefined + if (userId) { + logger.info(`Checking referral status for user ${userId}`) + const referralStatus = await hasMaxedReferrals(userId) + if (referralStatus.reason === undefined) { + referralLink = referralStatus.referralLink + logger.info( + `Generated referral link for user ${userId}. Referral count: ${referralStatus.details.referralCount}` + ) + } else { + logger.info( + `Not generating referral link for user ${userId}: ${referralStatus.reason}. Details: ${JSON.stringify(referralStatus.details)}` + ) + } + } else { + logger.info('No userId provided, skipping referral link generation') + } + return { + usage, + limit, + referralLink, + } + } + ) + + return { + type: 'usage-response', + ...params, + } +} + const onUserInput = async ( { fingerprintId, @@ -105,7 +146,10 @@ const onUserInput = async ( changes, }) } else { - const { usage, limit } = await calculateUsage(fingerprintId, userId) + const { usage, limit, referralLink } = await genUsageResponse( + fingerprintId, + userId + ) sendAction(ws, { type: 'response-complete', userInputId, @@ -113,6 +157,7 @@ const onUserInput = async ( changes, usage, limit, + referralLink, }) } } catch (e) { @@ -315,31 +360,14 @@ const onInit = async ( }) } -const onUsageRequest = async ( +export const onUsageRequest = async ( { fingerprintId, authToken }: Extract, _clientSessionId: string, ws: WebSocket ) => { const userId = await getUserIdFromAuthToken(authToken) - const { usage, limit } = await calculateUsage(fingerprintId, userId) - await withLoggerContext({ fingerprintId, userId, usage, limit }, async () => { - logger.info('Sending usage info') - - let referralLink: string | undefined = undefined - if (userId) { - const shouldGenerateReferralLink = await hasMaxedReferrals(userId) - if (shouldGenerateReferralLink.reason === undefined) { - referralLink = shouldGenerateReferralLink.referralLink - } - } - - sendAction(ws, { - type: 'usage-response', - usage, - limit, - referralLink, - }) - }) + const action = await genUsageResponse(fingerprintId, userId) + sendAction(ws, action) } const onGenerateCommitMessage = async ( diff --git a/bun.lockb b/bun.lockb index 4cf1421eca..391ec0670e 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/common/src/actions.ts b/common/src/actions.ts index c6092524e3..4115364817 100644 --- a/common/src/actions.ts +++ b/common/src/actions.ts @@ -128,6 +128,7 @@ export const SERVER_ACTION_SCHEMA = z.discriminatedUnion('type', [ changes: CHANGES, usage: z.number().optional(), limit: z.number().optional(), + referralLink: z.string().optional(), }), z.object({ type: z.literal('read-files'), diff --git a/common/src/util/server/referral.ts b/common/src/util/server/referral.ts index 905767a6e2..08eb391ad7 100644 --- a/common/src/util/server/referral.ts +++ b/common/src/util/server/referral.ts @@ -7,38 +7,62 @@ import { MAX_REFERRALS } from '../../constants' export async function hasMaxedReferrals(userId: string): Promise< | { reason: - | 'You have reached your usage limit' + | 'You have maxxed out the number of referrals you can make. Thanks for your support!' | "Your user isn't in our system" + | 'An error occurred while checking referrals' + details?: { + referralCount?: number + error?: string + } } | { reason: undefined referralLink: string + details: { + referralCount: number + } } > { - const limitReached = await db - .select({ - limitReached: sql`count(*) >= ${MAX_REFERRALS}`, - }) - .from(schema.referral) - .where(eq(schema.referral.referrer_id, userId)) - .then((result) => (result.length > 0 ? result[0].limitReached : false)) - if (limitReached) { - return { reason: 'You have reached your usage limit' } - } + try { + const referralCount = await db + .select({ + count: sql`count(*)`, + }) + .from(schema.referral) + .where(eq(schema.referral.referrer_id, userId)) + .then((result) => (result.length > 0 ? result[0].count : 0)) - const user = await db.query.user.findFirst({ - where: eq(schema.user.id, userId), - columns: { - referral_code: true, - }, - }) + if (referralCount >= MAX_REFERRALS) { + return { + reason: + 'You have maxxed out the number of referrals you can make. Thanks for your support!', + details: { referralCount }, + } + } - if (!user || !user.referral_code) { - return { reason: "Your user isn't in our system" } - } + const user = await db.query.user.findFirst({ + where: eq(schema.user.id, userId), + columns: { + referral_code: true, + }, + }) - return { - reason: undefined, - referralLink: getReferralLink(user.referral_code), + if (!user || !user.referral_code) { + return { + reason: "Your user isn't in our system", + details: { referralCount }, + } + } + + return { + reason: undefined, + referralLink: getReferralLink(user.referral_code), + details: { referralCount }, + } + } catch (error) { + return { + reason: 'An error occurred while checking referrals', + details: { error: error instanceof Error ? error.message : String(error) }, + } } } diff --git a/knowledge.md b/knowledge.md index 587b54f236..1c546fb1eb 100644 --- a/knowledge.md +++ b/knowledge.md @@ -84,10 +84,21 @@ The `MAX_REFERRALS` constant is used to limit the number of referrals a user can 6. Remember that imports automatically remove 'src' from the path. When editing files, always include 'src' in the file path if it's part of the actual directory structure. ## Knowledge Management +## Knowledge File Management -- Knowledge is stored in `knowledge.md` files, which can be created in relevant directories throughout the project. -- Mani automatically updates knowledge files when learning new information or correcting mistakes. -- Developers are encouraged to review and commit knowledge file changes to share insights across the team. +- Knowledge is stored in `knowledge.md` files, which can be created in relevant directories throughout the project. +- Mani automatically updates knowledge files when learning new information or correcting mistakes. +- Developers are encouraged to review and commit knowledge file changes to share insights across the team. + +When updating knowledge files: + +1. Focus on high-level impacts and overall project direction, rather than specific implementation details. +2. Summarize changes in terms of their effect on the project's goals and user experience. +3. Avoid duplicating information that's already evident from the code itself. +4. Keep entries concise and relevant to the long-term understanding of the project. +5. When in doubt, prefer broader, more abstract descriptions over detailed, low-level explanations. + +These guidelines help maintain useful and accessible knowledge files that provide valuable context without becoming overly verbose or quickly outdated. ## Terminal Command Execution diff --git a/npm-app/loadEnv.js b/npm-app/loadEnv.js index d5b0cd577c..0f2deee99c 100644 --- a/npm-app/loadEnv.js +++ b/npm-app/loadEnv.js @@ -2,7 +2,11 @@ const fs = require('fs') const { match } = require('ts-pattern') const dotenv = require('dotenv') -const ENV_VARS_TO_PULL = ['NEXT_PUBLIC_APP_URL', 'NEXT_PUBLIC_BACKEND_URL'] +const ENV_VARS_TO_PULL = [ + 'NEXT_PUBLIC_APP_URL', + 'NEXT_PUBLIC_BACKEND_URL', + 'NEXT_PUBLIC_SUPPORT_EMAIL', +] dotenv.config({ path: '../stack.env' }) if (!process.env.ENVIRONMENT) { diff --git a/npm-app/src/cli.ts b/npm-app/src/cli.ts index 1494783f99..bdee346ff9 100644 --- a/npm-app/src/cli.ts +++ b/npm-app/src/cli.ts @@ -143,7 +143,7 @@ export class CLI { public printInitialPrompt(initialInput?: string) { if (this.client.user) { console.log( - `Welcome back ${this.client.user.name}! What would you like to do?\n` + `\nWelcome back ${this.client.user.name}! What would you like to do?` ) } else { console.log(`What would you like to do?\n`) @@ -335,10 +335,6 @@ export class CLI { } } - if (this.client.lastWarnedPct >= 100) { - this.client.getUsage() // refresh, in case user upgraded - return - } this.startLoadingAnimation() await this.readyPromise diff --git a/npm-app/src/client.ts b/npm-app/src/client.ts index c67c33b211..0ab79fdd74 100644 --- a/npm-app/src/client.ts +++ b/npm-app/src/client.ts @@ -255,14 +255,14 @@ export class Client { this.returnControlToUser() } else { console.warn( - `Authentication failed: ${action.message}. Please try again in a few minutes or contact support.` + `Authentication failed: ${action.message}. Please try again in a few minutes or contact support at ${process.env.NEXT_PUBLIC_SUPPORT_EMAIL}.` ) } }) this.webSocket.subscribe('usage-response', (action) => { const { usage, limit, referralLink } = action - console.log(`\nUsage: ${usage} / ${limit} credits`) + console.log(`Usage: ${usage} / ${limit} credits`) this.showUsageWarning(usage, limit, referralLink) this.returnControlToUser() }) @@ -273,6 +273,17 @@ export class Client { limit: number, referralLink?: string ) { + const errorCopy = [ + this.user + ? yellow(`Visit ${process.env.NEXT_PUBLIC_APP_URL}/pricing to upgrade.`) + : yellow('Type "login" to sign up and get more credits!'), + referralLink + ? yellow( + `You can also refer friends using this link and get more credits: ${referralLink}` + ) + : '', + ].join('\n') + const pct: number = match(Math.floor((usage / limit) * 100)) .with(P.number.gte(100), () => 100) .with(P.number.gte(75), () => 75) @@ -282,13 +293,12 @@ export class Client { if (pct >= 100) { console.error( - [ - red( - 'You have reached your monthly usage limit. You must upgrade your plan to continue using the service.' - ), - ].join('\n') + [red('You have reached your monthly usage limit.'), errorCopy].join( + '\n' + ) ) this.returnControlToUser() + this.lastWarnedPct = 100 return } @@ -297,16 +307,7 @@ export class Client { [ '', yellow(`You have used over ${pct}% of your monthly usage limit.`), - this.user - ? yellow( - `Visit ${process.env.NEXT_PUBLIC_APP_URL}/pricing to upgrade.` - ) - : yellow('Type "login" to sign up and get more credits!'), - referralLink - ? yellow( - `You can also refer friends using this link and get more credits: ${referralLink}` - ) - : '', + errorCopy, ].join('\n') ) this.lastWarnedPct = pct @@ -430,6 +431,8 @@ export class Client { this.lastWarnedPct = 0 this.limit = a.limit } + + this.showUsageWarning(a.usage, a.limit, a.referralLink) }) return { diff --git a/package.json b/package.json index 8de20f6d1f..4f6b683155 100644 --- a/package.json +++ b/package.json @@ -12,10 +12,10 @@ "packages/*" ], "scripts": { - "start-client": "bun --cwd npm-app start", "start-db": "bun --cwd common db:start", + "start-client": "bun --cwd npm-app start", "start-web": "bun run start-db && bun --cwd web dev", - "start-server": "bun run start-db && bun --cwd backend start", + "start-server": "bun run start-db && bun --cwd backend dev", "start-manifold": "bun --cwd npm-app start-manifold", "start-litestar": "bun --cwd npm-app start-litestar", "start-jpcsp": "bun --cwd npm-app start-jpcsp", diff --git a/web/knowledge.md b/web/knowledge.md index 6218554291..502560a6f5 100644 --- a/web/knowledge.md +++ b/web/knowledge.md @@ -124,3 +124,18 @@ Key points: Pricing information is displayed on the pricing page (`web/src/app/pricing/page.tsx`). Remember to keep this knowledge file updated as the application evolves or new features are added. + +## Responsive Design + +### Navigation + +- Desktop: Display "Pricing" and "Referrals" links in the main navigation bar. +- Mobile: Due to limited space, consider alternative ways to display these links: + - Use a hamburger icon to reveal the dropdown menu. + - Include icons with menu items for better visual cues. + - Incorporate all navigation items, including "Pricing", "Referrals", and other relevant buttons (e.g., login/logout). + - Follow the current menu format for consistency across desktop and mobile views. +- Ensure the mobile menu design is consistent with the overall application style. +- Ensure all navigation options are easily accessible regardless of device size. +- Test responsive design across various screen sizes and devices. + - Consider using Tailwind CSS classes for responsive design implementation. diff --git a/web/src/app/api/healthz/route.ts b/web/src/app/api/healthz/route.ts index da013ddaab..19acdccc04 100644 --- a/web/src/app/api/healthz/route.ts +++ b/web/src/app/api/healthz/route.ts @@ -1,5 +1,5 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from 'next/server' export const GET = async () => { - return NextResponse.json({ status: 'ok' }); -}; + return NextResponse.json({ status: 'ok' }) +} diff --git a/web/src/app/pricing/page.tsx b/web/src/app/pricing/page.tsx index d46bac6a9a..37d9e2b00c 100644 --- a/web/src/app/pricing/page.tsx +++ b/web/src/app/pricing/page.tsx @@ -44,7 +44,7 @@ const PricingPage = () => { const pricingPlans = [ { name: 'Free', - price: '$0', + price: '$0/month', credits: CREDITS_USAGE_LIMITS.FREE, features: [ {