📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
import mongoose from 'mongoose';
|
|
|
|
|
import { MongoMemoryServer } from 'mongodb-memory-server';
|
|
|
|
|
import { matchModelName, findMatchingPattern } from './test-helpers';
|
|
|
|
|
import { createModels } from '~/models';
|
|
|
|
|
import { createTxMethods, tokenValues, premiumTokenValues } from './tx';
|
|
|
|
|
import { createTransactionMethods } from './transaction';
|
|
|
|
|
import { createSpendTokensMethods } from './spendTokens';
|
|
|
|
|
import type { ITransaction } from '~/schema/transaction';
|
|
|
|
|
import type { IBalance } from '..';
|
|
|
|
|
|
|
|
|
|
jest.mock('~/config/winston', () => ({
|
|
|
|
|
error: jest.fn(),
|
|
|
|
|
warn: jest.fn(),
|
|
|
|
|
info: jest.fn(),
|
|
|
|
|
debug: jest.fn(),
|
2024-08-24 04:36:08 -04:00
|
|
|
}));
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
let mongoServer: InstanceType<typeof MongoMemoryServer>;
|
|
|
|
|
let spendTokens: ReturnType<typeof createSpendTokensMethods>['spendTokens'];
|
|
|
|
|
let spendStructuredTokens: ReturnType<typeof createSpendTokensMethods>['spendStructuredTokens'];
|
|
|
|
|
let createTransaction: ReturnType<typeof createTransactionMethods>['createTransaction'];
|
|
|
|
|
let createAutoRefillTransaction: ReturnType<
|
|
|
|
|
typeof createTransactionMethods
|
|
|
|
|
>['createAutoRefillTransaction'];
|
|
|
|
|
let getCacheMultiplier: ReturnType<typeof createTxMethods>['getCacheMultiplier'];
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
describe('spendTokens', () => {
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
let userId: mongoose.Types.ObjectId;
|
|
|
|
|
let Transaction: mongoose.Model<ITransaction>;
|
|
|
|
|
let Balance: mongoose.Model<IBalance>;
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
beforeAll(async () => {
|
|
|
|
|
mongoServer = await MongoMemoryServer.create();
|
2025-05-30 22:18:13 -04:00
|
|
|
await mongoose.connect(mongoServer.getUri());
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const models = createModels(mongoose);
|
|
|
|
|
Object.assign(mongoose.models, models);
|
|
|
|
|
|
|
|
|
|
Transaction = mongoose.models.Transaction;
|
|
|
|
|
Balance = mongoose.models.Balance;
|
|
|
|
|
|
|
|
|
|
const txMethods = createTxMethods(mongoose, { matchModelName, findMatchingPattern });
|
|
|
|
|
getCacheMultiplier = txMethods.getCacheMultiplier;
|
|
|
|
|
|
|
|
|
|
const transactionMethods = createTransactionMethods(mongoose, {
|
|
|
|
|
getMultiplier: txMethods.getMultiplier,
|
|
|
|
|
getCacheMultiplier: txMethods.getCacheMultiplier,
|
|
|
|
|
});
|
|
|
|
|
createTransaction = transactionMethods.createTransaction;
|
|
|
|
|
createAutoRefillTransaction = transactionMethods.createAutoRefillTransaction;
|
|
|
|
|
|
|
|
|
|
const spendMethods = createSpendTokensMethods(mongoose, {
|
|
|
|
|
createTransaction: transactionMethods.createTransaction,
|
|
|
|
|
createStructuredTransaction: transactionMethods.createStructuredTransaction,
|
|
|
|
|
});
|
|
|
|
|
spendTokens = spendMethods.spendTokens;
|
|
|
|
|
spendStructuredTokens = spendMethods.spendStructuredTokens;
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
afterAll(async () => {
|
|
|
|
|
await mongoose.disconnect();
|
|
|
|
|
await mongoServer.stop();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
beforeEach(async () => {
|
|
|
|
|
// Clear collections before each test
|
|
|
|
|
await Transaction.deleteMany({});
|
|
|
|
|
await Balance.deleteMany({});
|
|
|
|
|
|
|
|
|
|
// Create a new user ID for each test
|
|
|
|
|
userId = new mongoose.Types.ObjectId();
|
|
|
|
|
|
2025-08-26 12:10:18 -04:00
|
|
|
// Balance config is now passed directly in txData
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should create transactions for both prompt and completion tokens', async () => {
|
2025-03-22 17:54:25 -04:00
|
|
|
// Create a balance for the user
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 10000,
|
|
|
|
|
});
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
const txData = {
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
2024-08-24 04:36:08 -04:00
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'gpt-3.5-turbo',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2024-08-24 04:36:08 -04:00
|
|
|
};
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: 100,
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Check completion transaction
|
|
|
|
|
expect(transactions[0].tokenType).toBe('completion');
|
|
|
|
|
expect(transactions[0].rawAmount).toBe(-50);
|
|
|
|
|
|
|
|
|
|
// Check prompt transaction
|
|
|
|
|
expect(transactions[1].tokenType).toBe('prompt');
|
|
|
|
|
expect(transactions[1].rawAmount).toBe(-100);
|
|
|
|
|
|
|
|
|
|
// Verify balance was updated
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(balance).toBeDefined();
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBeLessThan(10000); // Balance should be reduced
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should handle zero completion tokens', async () => {
|
2025-03-22 17:54:25 -04:00
|
|
|
// Create a balance for the user
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 10000,
|
|
|
|
|
});
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
const txData = {
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
2024-08-24 04:36:08 -04:00
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'gpt-3.5-turbo',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2024-08-24 04:36:08 -04:00
|
|
|
};
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: 100,
|
|
|
|
|
completionTokens: 0,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Check completion transaction
|
|
|
|
|
expect(transactions[0].tokenType).toBe('completion');
|
|
|
|
|
// In JavaScript -0 and 0 are different but functionally equivalent
|
|
|
|
|
// Use Math.abs to handle both 0 and -0
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(Math.abs(transactions[0].rawAmount!)).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Check prompt transaction
|
|
|
|
|
expect(transactions[1].tokenType).toBe('prompt');
|
|
|
|
|
expect(transactions[1].rawAmount).toBe(-100);
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should handle undefined token counts', async () => {
|
|
|
|
|
const txData = {
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
2024-08-24 04:36:08 -04:00
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'gpt-3.5-turbo',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2024-08-24 04:36:08 -04:00
|
|
|
};
|
|
|
|
|
const tokenUsage = {};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
// Verify no transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId });
|
|
|
|
|
expect(transactions).toHaveLength(0);
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
2025-03-21 22:48:11 +01:00
|
|
|
it('should not update balance when the balance feature is disabled', async () => {
|
2025-08-26 12:10:18 -04:00
|
|
|
// Balance is now passed directly in txData
|
2025-03-22 17:54:25 -04:00
|
|
|
// Create a balance for the user
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 10000,
|
|
|
|
|
});
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
const txData = {
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
2024-08-24 04:36:08 -04:00
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'gpt-3.5-turbo',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: false },
|
2024-08-24 04:36:08 -04:00
|
|
|
};
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: 100,
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Verify balance was not updated (should still be 10000)
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(10000);
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
it('should not allow balance to go below zero when spending tokens', async () => {
|
|
|
|
|
// Create a balance with a low amount
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 5000,
|
|
|
|
|
});
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
const txData = {
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
2024-08-24 04:36:08 -04:00
|
|
|
conversationId: 'test-convo',
|
2025-03-22 17:54:25 -04:00
|
|
|
model: 'gpt-4', // Using a more expensive model
|
2024-08-24 04:36:08 -04:00
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2024-08-24 04:36:08 -04:00
|
|
|
};
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Spending more tokens than the user has balance for
|
2024-08-24 04:36:08 -04:00
|
|
|
const tokenUsage = {
|
2025-03-22 17:54:25 -04:00
|
|
|
promptTokens: 1000,
|
|
|
|
|
completionTokens: 500,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Verify balance was reduced to exactly 0, not negative
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(balance).toBeDefined();
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Check that the transaction records show the adjusted values
|
|
|
|
|
const transactionResults = await Promise.all(
|
|
|
|
|
transactions.map((t) =>
|
2025-05-30 22:18:13 -04:00
|
|
|
createTransaction({
|
2025-03-22 17:54:25 -04:00
|
|
|
...txData,
|
|
|
|
|
tokenType: t.tokenType,
|
|
|
|
|
rawAmount: t.rawAmount,
|
|
|
|
|
}),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// The second transaction should have an adjusted value since balance is already 0
|
|
|
|
|
expect(transactionResults[1]).toEqual(
|
|
|
|
|
expect.objectContaining({
|
|
|
|
|
balance: 0,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should handle multiple transactions in sequence with low balance and not increase balance', async () => {
|
|
|
|
|
// This test is specifically checking for the issue reported in production
|
|
|
|
|
// where the balance increases after a transaction when it should remain at 0
|
|
|
|
|
// Create a balance with a very low amount
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 100,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// First transaction - should reduce balance to 0
|
|
|
|
|
const txData1 = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo-1',
|
|
|
|
|
model: 'gpt-4',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage1 = {
|
|
|
|
|
promptTokens: 100,
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData1, tokenUsage1);
|
|
|
|
|
|
|
|
|
|
// Check balance after first transaction
|
|
|
|
|
let balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Second transaction - should keep balance at 0, not make it negative or increase it
|
|
|
|
|
const txData2 = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo-2',
|
|
|
|
|
model: 'gpt-4',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage2 = {
|
|
|
|
|
promptTokens: 200,
|
|
|
|
|
completionTokens: 100,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData2, tokenUsage2);
|
|
|
|
|
|
|
|
|
|
// Check balance after second transaction - should still be 0
|
|
|
|
|
balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Verify all transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId });
|
|
|
|
|
expect(transactions).toHaveLength(4); // 2 transactions (prompt+completion) for each call
|
|
|
|
|
|
|
|
|
|
// Let's examine the actual transaction records to see what's happening
|
|
|
|
|
const transactionDetails = await Transaction.find({ user: userId }).sort({ createdAt: 1 });
|
|
|
|
|
|
|
|
|
|
// Log the transaction details for debugging
|
|
|
|
|
console.log('Transaction details:');
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
transactionDetails.forEach((tx, i: number) => {
|
2025-03-22 17:54:25 -04:00
|
|
|
console.log(`Transaction ${i + 1}:`, {
|
|
|
|
|
tokenType: tx.tokenType,
|
|
|
|
|
rawAmount: tx.rawAmount,
|
|
|
|
|
tokenValue: tx.tokenValue,
|
|
|
|
|
model: tx.model,
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Check the return values from Transaction.create directly
|
|
|
|
|
// This is to verify that the incrementValue is not becoming positive
|
2025-05-30 22:18:13 -04:00
|
|
|
const directResult = await createTransaction({
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo-3',
|
|
|
|
|
model: 'gpt-4',
|
|
|
|
|
tokenType: 'completion',
|
|
|
|
|
rawAmount: -100,
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
console.log('Direct Transaction.create result:', directResult);
|
|
|
|
|
|
|
|
|
|
// The completion value should never be positive
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(directResult!.completion).not.toBeGreaterThan(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should ensure tokenValue is always negative for spending tokens', async () => {
|
|
|
|
|
// Create a balance for the user
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 10000,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Test with various models to check multiplier calculations
|
|
|
|
|
const models = ['gpt-3.5-turbo', 'gpt-4', 'claude-3-5-sonnet'];
|
|
|
|
|
|
|
|
|
|
for (const model of models) {
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: `test-convo-${model}`,
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: 100,
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
// Get the transactions for this model
|
|
|
|
|
const transactions = await Transaction.find({
|
|
|
|
|
user: userId,
|
|
|
|
|
model,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Verify tokenValue is negative for all transactions
|
|
|
|
|
transactions.forEach((tx) => {
|
|
|
|
|
console.log(`Model ${model}, Type ${tx.tokenType}: tokenValue = ${tx.tokenValue}`);
|
|
|
|
|
expect(tx.tokenValue).toBeLessThan(0);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should handle structured transactions in sequence with low balance', async () => {
|
|
|
|
|
// Create a balance with a very low amount
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 100,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// First transaction - should reduce balance to 0
|
|
|
|
|
const txData1 = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo-1',
|
|
|
|
|
model: 'claude-3-5-sonnet',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage1 = {
|
2024-08-24 04:36:08 -04:00
|
|
|
promptTokens: {
|
|
|
|
|
input: 10,
|
|
|
|
|
write: 100,
|
|
|
|
|
read: 5,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
await spendStructuredTokens(txData1, tokenUsage1);
|
|
|
|
|
|
|
|
|
|
// Check balance after first transaction
|
|
|
|
|
let balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Second transaction - should keep balance at 0, not make it negative or increase it
|
|
|
|
|
const txData2 = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo-2',
|
|
|
|
|
model: 'claude-3-5-sonnet',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage2 = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 20,
|
|
|
|
|
write: 200,
|
|
|
|
|
read: 10,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 100,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendStructuredTokens(txData2, tokenUsage2);
|
|
|
|
|
|
|
|
|
|
// Check balance after second transaction - should still be 0
|
|
|
|
|
balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Verify all transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId });
|
|
|
|
|
expect(transactions).toHaveLength(4); // 2 transactions (prompt+completion) for each call
|
|
|
|
|
|
|
|
|
|
// Let's examine the actual transaction records to see what's happening
|
|
|
|
|
const transactionDetails = await Transaction.find({ user: userId }).sort({ createdAt: 1 });
|
|
|
|
|
|
|
|
|
|
// Log the transaction details for debugging
|
|
|
|
|
console.log('Structured transaction details:');
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
transactionDetails.forEach((tx, i: number) => {
|
2025-03-22 17:54:25 -04:00
|
|
|
console.log(`Transaction ${i + 1}:`, {
|
|
|
|
|
tokenType: tx.tokenType,
|
|
|
|
|
rawAmount: tx.rawAmount,
|
|
|
|
|
tokenValue: tx.tokenValue,
|
|
|
|
|
inputTokens: tx.inputTokens,
|
|
|
|
|
writeTokens: tx.writeTokens,
|
|
|
|
|
readTokens: tx.readTokens,
|
|
|
|
|
model: tx.model,
|
|
|
|
|
});
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should not allow balance to go below zero when spending structured tokens', async () => {
|
|
|
|
|
// Create a balance with a low amount
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 5000,
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'claude-3-5-sonnet', // Using a model that supports structured tokens
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Spending more tokens than the user has balance for
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 100,
|
|
|
|
|
write: 1000,
|
|
|
|
|
read: 50,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 500,
|
|
|
|
|
};
|
|
|
|
|
|
2024-08-24 04:36:08 -04:00
|
|
|
const result = await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Verify balance was reduced to exactly 0, not negative
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(balance).toBeDefined();
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBe(0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// The result should show the adjusted values
|
|
|
|
|
expect(result).toEqual({
|
|
|
|
|
prompt: expect.objectContaining({
|
|
|
|
|
user: userId.toString(),
|
|
|
|
|
balance: expect.any(Number),
|
2024-08-24 04:36:08 -04:00
|
|
|
}),
|
2025-03-22 17:54:25 -04:00
|
|
|
completion: expect.objectContaining({
|
|
|
|
|
user: userId.toString(),
|
|
|
|
|
balance: 0, // Final balance should be 0
|
2024-08-24 04:36:08 -04:00
|
|
|
}),
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should handle multiple concurrent transactions correctly with a high balance', async () => {
|
|
|
|
|
// Create a balance with a high amount
|
2025-04-01 23:09:24 -04:00
|
|
|
const initialBalance = 10000000;
|
2025-03-22 17:54:25 -04:00
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Simulate the recordCollectedUsage function from the production code
|
|
|
|
|
const conversationId = 'test-concurrent-convo';
|
|
|
|
|
const context = 'message';
|
|
|
|
|
const model = 'gpt-4';
|
|
|
|
|
|
2025-04-01 23:09:24 -04:00
|
|
|
const amount = 50;
|
|
|
|
|
// Create `amount` of usage records to simulate multiple transactions
|
|
|
|
|
const collectedUsage = Array.from({ length: amount }, (_, i) => ({
|
2025-03-22 17:54:25 -04:00
|
|
|
model,
|
|
|
|
|
input_tokens: 100 + i * 10, // Increasing input tokens
|
|
|
|
|
output_tokens: 50 + i * 5, // Increasing output tokens
|
|
|
|
|
input_token_details: {
|
|
|
|
|
cache_creation: i % 2 === 0 ? 20 : 0, // Some have cache creation
|
|
|
|
|
cache_read: i % 3 === 0 ? 10 : 0, // Some have cache read
|
|
|
|
|
},
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
// Process all transactions concurrently to simulate race conditions
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const promises: Promise<unknown>[] = [];
|
2025-03-22 17:54:25 -04:00
|
|
|
let expectedTotalSpend = 0;
|
|
|
|
|
|
|
|
|
|
for (let i = 0; i < collectedUsage.length; i++) {
|
|
|
|
|
const usage = collectedUsage[i];
|
|
|
|
|
if (!usage) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const cache_creation = Number(usage.input_token_details?.cache_creation) || 0;
|
|
|
|
|
const cache_read = Number(usage.input_token_details?.cache_read) || 0;
|
|
|
|
|
|
|
|
|
|
const txMetadata = {
|
|
|
|
|
context,
|
|
|
|
|
conversationId,
|
|
|
|
|
user: userId,
|
|
|
|
|
model: usage.model,
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Calculate expected spend for this transaction
|
|
|
|
|
const promptTokens = usage.input_tokens;
|
|
|
|
|
const completionTokens = usage.output_tokens;
|
|
|
|
|
|
|
|
|
|
// For regular transactions
|
|
|
|
|
if (cache_creation === 0 && cache_read === 0) {
|
|
|
|
|
// Add to expected spend using the correct multipliers from tx.js
|
|
|
|
|
// For gpt-4, the multipliers are: prompt=30, completion=60
|
|
|
|
|
expectedTotalSpend += promptTokens * 30; // gpt-4 prompt rate is 30
|
|
|
|
|
expectedTotalSpend += completionTokens * 60; // gpt-4 completion rate is 60
|
|
|
|
|
|
|
|
|
|
promises.push(
|
|
|
|
|
spendTokens(txMetadata, {
|
|
|
|
|
promptTokens,
|
|
|
|
|
completionTokens,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
// For structured transactions with cache operations
|
|
|
|
|
// The multipliers for claude models with cache operations are different
|
|
|
|
|
// But since we're using gpt-4 in the test, we need to use appropriate values
|
|
|
|
|
expectedTotalSpend += promptTokens * 30; // Base prompt rate for gpt-4
|
|
|
|
|
// Since gpt-4 doesn't have cache multipliers defined, we'll use the prompt rate
|
|
|
|
|
expectedTotalSpend += cache_creation * 30; // Write rate (using prompt rate as fallback)
|
|
|
|
|
expectedTotalSpend += cache_read * 30; // Read rate (using prompt rate as fallback)
|
|
|
|
|
expectedTotalSpend += completionTokens * 60; // Completion rate for gpt-4
|
|
|
|
|
|
|
|
|
|
promises.push(
|
|
|
|
|
spendStructuredTokens(txMetadata, {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: promptTokens,
|
|
|
|
|
write: cache_creation,
|
|
|
|
|
read: cache_read,
|
|
|
|
|
},
|
|
|
|
|
completionTokens,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Wait for all transactions to complete
|
|
|
|
|
await Promise.all(promises);
|
|
|
|
|
|
|
|
|
|
// Verify final balance
|
|
|
|
|
const finalBalance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(finalBalance).toBeDefined();
|
|
|
|
|
|
|
|
|
|
// The final balance should be the initial balance minus the expected total spend
|
|
|
|
|
const expectedFinalBalance = initialBalance - expectedTotalSpend;
|
|
|
|
|
|
|
|
|
|
console.log('Initial balance:', initialBalance);
|
|
|
|
|
console.log('Expected total spend:', expectedTotalSpend);
|
|
|
|
|
console.log('Expected final balance:', expectedFinalBalance);
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
console.log('Actual final balance:', finalBalance!.tokenCredits);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Allow for small rounding differences
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(finalBalance!.tokenCredits).toBeCloseTo(expectedFinalBalance, 0);
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Verify all transactions were created
|
|
|
|
|
const transactions = await Transaction.find({
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// We should have 2 transactions (prompt + completion) for each usage record
|
|
|
|
|
// Some might be structured, some regular
|
|
|
|
|
expect(transactions.length).toBeGreaterThanOrEqual(collectedUsage.length);
|
|
|
|
|
|
|
|
|
|
// Log transaction details for debugging
|
|
|
|
|
console.log('Transaction summary:');
|
|
|
|
|
let totalTokenValue = 0;
|
|
|
|
|
transactions.forEach((tx) => {
|
|
|
|
|
console.log(`${tx.tokenType}: rawAmount=${tx.rawAmount}, tokenValue=${tx.tokenValue}`);
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
totalTokenValue += tx.tokenValue!;
|
2025-03-22 17:54:25 -04:00
|
|
|
});
|
|
|
|
|
console.log('Total token value from transactions:', totalTokenValue);
|
|
|
|
|
|
|
|
|
|
// The difference between expected and actual is significant
|
|
|
|
|
// This is likely due to the multipliers being different in the test environment
|
|
|
|
|
// Let's adjust our expectation based on the actual transactions
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const actualSpend = initialBalance - finalBalance!.tokenCredits;
|
2025-03-22 17:54:25 -04:00
|
|
|
console.log('Actual spend:', actualSpend);
|
|
|
|
|
|
|
|
|
|
// Instead of checking the exact balance, let's verify that:
|
|
|
|
|
// 1. The balance was reduced (tokens were spent)
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(finalBalance!.tokenCredits).toBeLessThan(initialBalance);
|
2025-03-22 17:54:25 -04:00
|
|
|
// 2. The total token value from transactions matches the actual spend
|
|
|
|
|
expect(Math.abs(totalTokenValue)).toBeCloseTo(actualSpend, -3); // Allow for larger differences
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-01 23:09:24 -04:00
|
|
|
// Add this new test case
|
|
|
|
|
it('should handle multiple concurrent balance increases correctly', async () => {
|
|
|
|
|
// Start with zero balance
|
|
|
|
|
const initialBalance = 0;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const numberOfRefills = 25;
|
|
|
|
|
const refillAmount = 1000;
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const promises: Promise<unknown>[] = [];
|
2025-04-01 23:09:24 -04:00
|
|
|
for (let i = 0; i < numberOfRefills; i++) {
|
|
|
|
|
promises.push(
|
2025-05-30 22:18:13 -04:00
|
|
|
createAutoRefillTransaction({
|
2025-04-01 23:09:24 -04:00
|
|
|
user: userId,
|
|
|
|
|
tokenType: 'credits',
|
|
|
|
|
context: 'concurrent-refill-test',
|
|
|
|
|
rawAmount: refillAmount,
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-04-01 23:09:24 -04:00
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Wait for all refill transactions to complete
|
|
|
|
|
const results = await Promise.all(promises);
|
|
|
|
|
|
|
|
|
|
// Verify final balance
|
|
|
|
|
const finalBalance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(finalBalance).toBeDefined();
|
|
|
|
|
|
|
|
|
|
// The final balance should be the initial balance plus the sum of all refills
|
|
|
|
|
const expectedFinalBalance = initialBalance + numberOfRefills * refillAmount;
|
|
|
|
|
|
|
|
|
|
console.log('Initial balance (Increase Test):', initialBalance);
|
|
|
|
|
console.log(`Performed ${numberOfRefills} refills of ${refillAmount} each.`);
|
|
|
|
|
console.log('Expected final balance (Increase Test):', expectedFinalBalance);
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
console.log('Actual final balance (Increase Test):', finalBalance!.tokenCredits);
|
2025-04-01 23:09:24 -04:00
|
|
|
|
|
|
|
|
// Use toBeCloseTo for safety, though toBe should work for integer math
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(finalBalance!.tokenCredits).toBeCloseTo(expectedFinalBalance, 0);
|
2025-04-01 23:09:24 -04:00
|
|
|
|
|
|
|
|
// Verify all transactions were created
|
|
|
|
|
const transactions = await Transaction.find({
|
|
|
|
|
user: userId,
|
|
|
|
|
context: 'concurrent-refill-test',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// We should have one transaction for each refill attempt
|
|
|
|
|
expect(transactions.length).toBe(numberOfRefills);
|
|
|
|
|
|
|
|
|
|
// Optional: Verify the sum of increments from the results matches the balance change
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const totalIncrementReported = results.reduce((sum: number, result) => {
|
2025-04-01 23:09:24 -04:00
|
|
|
// Assuming createAutoRefillTransaction returns an object with the increment amount
|
|
|
|
|
// Adjust this based on the actual return structure.
|
|
|
|
|
// Let's assume it returns { balance: newBalance, transaction: { rawAmount: ... } }
|
|
|
|
|
// Or perhaps we check the transaction.rawAmount directly
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
const r = result as Record<string, Record<string, unknown>>;
|
|
|
|
|
return sum + ((r?.transaction?.rawAmount as number) || 0);
|
2025-04-01 23:09:24 -04:00
|
|
|
}, 0);
|
|
|
|
|
console.log('Total increment reported by results:', totalIncrementReported);
|
|
|
|
|
expect(totalIncrementReported).toBe(expectedFinalBalance - initialBalance);
|
|
|
|
|
|
|
|
|
|
// Optional: Check the sum of tokenValue from saved transactions
|
|
|
|
|
let totalTokenValueFromDb = 0;
|
|
|
|
|
transactions.forEach((tx) => {
|
|
|
|
|
// For refills, rawAmount is positive, and tokenValue might be calculated based on it
|
|
|
|
|
// Let's assume tokenValue directly reflects the increment for simplicity here
|
|
|
|
|
// If calculation is involved, adjust accordingly
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
totalTokenValueFromDb += tx.rawAmount!; // Or tx.tokenValue if that holds the increment
|
2025-04-01 23:09:24 -04:00
|
|
|
});
|
|
|
|
|
console.log('Total rawAmount from DB transactions:', totalTokenValueFromDb);
|
|
|
|
|
expect(totalTokenValueFromDb).toBeCloseTo(expectedFinalBalance - initialBalance, 0);
|
|
|
|
|
});
|
|
|
|
|
|
2025-03-22 17:54:25 -04:00
|
|
|
it('should create structured transactions for both prompt and completion tokens', async () => {
|
|
|
|
|
// Create a balance for the user
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 10000,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-convo',
|
|
|
|
|
model: 'claude-3-5-sonnet',
|
|
|
|
|
context: 'test',
|
2025-08-26 12:10:18 -04:00
|
|
|
balance: { enabled: true },
|
2025-03-22 17:54:25 -04:00
|
|
|
};
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 10,
|
|
|
|
|
write: 100,
|
|
|
|
|
read: 5,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 50,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
// Verify transactions were created
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
expect(transactions).toHaveLength(2);
|
|
|
|
|
|
|
|
|
|
// Check completion transaction
|
|
|
|
|
expect(transactions[0].tokenType).toBe('completion');
|
|
|
|
|
expect(transactions[0].rawAmount).toBe(-50);
|
|
|
|
|
|
|
|
|
|
// Check prompt transaction
|
|
|
|
|
expect(transactions[1].tokenType).toBe('prompt');
|
|
|
|
|
expect(transactions[1].inputTokens).toBe(-10);
|
|
|
|
|
expect(transactions[1].writeTokens).toBe(-100);
|
|
|
|
|
expect(transactions[1].readTokens).toBe(-5);
|
|
|
|
|
|
|
|
|
|
// Verify result contains transaction info
|
2024-08-24 04:36:08 -04:00
|
|
|
expect(result).toEqual({
|
|
|
|
|
prompt: expect.objectContaining({
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId.toString(),
|
|
|
|
|
prompt: expect.any(Number),
|
2024-08-24 04:36:08 -04:00
|
|
|
}),
|
|
|
|
|
completion: expect.objectContaining({
|
2025-03-22 17:54:25 -04:00
|
|
|
user: userId.toString(),
|
|
|
|
|
completion: expect.any(Number),
|
2024-08-24 04:36:08 -04:00
|
|
|
}),
|
|
|
|
|
});
|
2025-03-22 17:54:25 -04:00
|
|
|
|
|
|
|
|
// Verify balance was updated
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
|
|
|
|
expect(balance).toBeDefined();
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance!.tokenCredits).toBeLessThan(10000); // Balance should be reduced
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|
2026-02-06 18:35:36 -05:00
|
|
|
|
|
|
|
|
describe('premium token pricing', () => {
|
|
|
|
|
it('should charge standard rates for claude-opus-4-6 when prompt tokens are below threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const promptTokens = 100000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-standard-pricing',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * tokenValues[model].prompt + completionTokens * tokenValues[model].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance?.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge premium rates for claude-opus-4-6 when prompt tokens exceed threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const promptTokens = 250000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-premium-pricing',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * premiumTokenValues[model].prompt +
|
|
|
|
|
completionTokens * premiumTokenValues[model].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance?.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge premium rates for both prompt and completion in structured tokens when above threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-structured-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 200000,
|
|
|
|
|
write: 10000,
|
|
|
|
|
read: 5000,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 1000,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
const premiumPromptRate = premiumTokenValues[model].prompt;
|
|
|
|
|
const premiumCompletionRate = premiumTokenValues[model].completion;
|
|
|
|
|
const writeRate = getCacheMultiplier({ model, cacheType: 'write' });
|
|
|
|
|
const readRate = getCacheMultiplier({ model, cacheType: 'read' });
|
|
|
|
|
|
|
|
|
|
const expectedPromptCost =
|
|
|
|
|
tokenUsage.promptTokens.input * premiumPromptRate +
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
tokenUsage.promptTokens.write * (writeRate ?? 0) +
|
|
|
|
|
tokenUsage.promptTokens.read * (readRate ?? 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
const expectedCompletionCost = tokenUsage.completionTokens * premiumCompletionRate;
|
|
|
|
|
|
🏢 feat: Multi-Tenant Data Isolation Infrastructure (#12091)
* chore: imports
* chore: optional chaining in `spendTokens.spec.ts`
* feat: Add tenantId field to all MongoDB schemas for multi-tenant isolation
- Add AsyncLocalStorage-based tenant context (`tenantContext.ts`) for
request-scoped tenantId propagation without modifying method signatures
- Add Mongoose `applyTenantIsolation` plugin that injects `{ tenantId }`
into all query filters when tenant context is present, with
`TENANT_ISOLATION_STRICT` env var for fail-closed production mode
- Add optional `tenantId` field to all 28 collection schemas
- Update all compound unique indexes to include tenantId (email, OAuth IDs,
role names, serverName, conversationId+user, messageId+user, etc.)
- Apply tenant isolation plugin in all 28 model factories
- Add `tenantId?: string` to all TypeScript document interfaces
Behaviorally inert — transitional mode (default) passes through all queries
unchanged. No migration required for existing deployments.
* refactor: Update tenant context and enhance tenant isolation plugin
- Changed `tenantId` in `TenantContext` to be optional, allowing for more flexible usage.
- Refactored `runAsSystem` function to accept synchronous functions, improving usability.
- Introduced comprehensive tests for the `applyTenantIsolation` plugin, ensuring correct tenant filtering in various query scenarios.
- Enhanced the plugin to handle aggregate queries and save operations with tenant context, improving data isolation capabilities.
* docs: tenant context documentation and improve tenant isolation tests
- Added detailed documentation for the `tenantStorage` AsyncLocalStorage instance in `tenantContext.ts`, clarifying its usage for async tenant context propagation.
- Updated tests in `tenantIsolation.spec.ts` to improve clarity and coverage, including new tests for strict mode behavior and tenant context propagation through await boundaries.
- Refactored existing test cases for better readability and consistency, ensuring robust validation of tenant isolation functionality.
* feat: Enhance tenant isolation by preventing tenantId mutations in update operations
- Added a new function to assert that tenantId cannot be modified through update operators in Mongoose queries.
- Implemented middleware to enforce this restriction during findOneAndUpdate, updateOne, and updateMany operations.
- Updated documentation to reflect the new behavior regarding tenantId modifications, ensuring clarity on tenant isolation rules.
* feat: Enhance tenant isolation tests and enforce tenantId restrictions
- Updated existing tests to clarify behavior regarding tenantId preservation during save and insertMany operations.
- Introduced new tests to validate that tenantId cannot be modified through update operations, ensuring strict adherence to tenant isolation rules.
- Added checks for mismatched tenantId scenarios, reinforcing the integrity of tenant context propagation.
- Enhanced test coverage for async context propagation and mutation guards, improving overall robustness of tenant isolation functionality.
* fix: Remove duplicate re-exports in utils/index.ts
Merge artifact caused `string` and `tempChatRetention` to be exported
twice, which produces TypeScript compile errors for duplicate bindings.
* fix: Resolve admin capability gap in multi-tenant mode (TODO #12091)
- hasCapabilityForPrincipals now queries both tenant-scoped AND
platform-level grants when tenantId is set, so seeded ADMIN grants
remain effective in tenant mode.
- Add applyTenantIsolation to SystemGrant model factory.
* fix: Harden tenant isolation plugin
- Add replaceGuard for replaceOne/findOneAndReplace to prevent
cross-tenant document reassignment via replacement documents.
- Cache isStrict() result to avoid process.env reads on every query.
Export _resetStrictCache() for test teardown.
- Replace console.warn with project logger (winston).
- Add 5 new tests for replace guard behavior (46 total).
* style: Fix import ordering in convo.ts and message.ts
Move type imports after value imports per project style guide.
* fix: Remove tenant isolation from SystemGrant, stamp tenantId in replaceGuard
- SystemGrant is a cross-tenant control plane whose methods handle
tenantId conditions explicitly. Applying the isolation plugin
injects a hard equality filter that overrides the $and/$or logic
in hasCapabilityForPrincipals, making platform-level ADMIN grants
invisible in tenant mode.
- replaceGuard now stamps tenantId into replacement documents when
absent, preventing replaceOne from silently stripping tenant
context. Replacements with a matching tenantId are allowed;
mismatched tenantId still throws.
* test: Add multi-tenant unique constraint and replace stamping tests
- Verify same name/email can exist in different tenants (compound
unique index allows it).
- Verify duplicate within same tenant is rejected (E11000).
- Verify tenant-scoped query returns only the correct document.
- Update replaceOne test to assert tenantId is stamped into
replacement document.
- Add test for replacement with matching tenantId.
* style: Reorder imports in message.ts to align with project style guide
* feat: Add migration to drop superseded unique indexes for multi-tenancy
Existing deployments have single-field unique indexes (e.g. { email: 1 })
that block multi-tenant operation — same email in different tenants
triggers E11000. Mongoose autoIndex creates the new compound indexes
but never drops the old ones.
dropSupersededTenantIndexes() drops all 19 superseded indexes across 11
collections. It is idempotent, skips missing indexes/collections, and
is a no-op on fresh databases.
Must be called before enabling multi-tenant middleware on an existing
deployment. Single-tenant deployments are unaffected (old indexes
coexist harmlessly until migration runs).
Includes 11 tests covering:
- Full upgrade simulation (create old indexes, drop them, verify gone)
- Multi-tenant writes work after migration (same email, different tenant)
- Intra-tenant uniqueness preserved (duplicate within tenant rejected)
- Fresh database (no-op, no errors)
- Partial migration (some collections exist, some don't)
- SUPERSEDED_INDEXES coverage validation
* fix: Update systemGrant test — platform grants now satisfy tenant queries
The TODO #12091 fix intentionally changed hasCapabilityForPrincipals to
match both tenant-scoped AND platform-level grants. The test expected
the old behavior (platform grant invisible to tenant query). Updated
test name and expectation to match the new semantics.
* fix: Align getCapabilitiesForPrincipal with hasCapabilityForPrincipals tenant query
getCapabilitiesForPrincipal used a hard tenantId equality filter while
hasCapabilityForPrincipals uses $and/$or to match both tenant-scoped
and platform-level grants. This caused the two functions to disagree
on what grants a principal holds in tenant mode.
Apply the same $or pattern: when tenantId is provided, match both
{ tenantId } and { tenantId: { $exists: false } }.
Adds test verifying platform-level ADMIN grants appear in
getCapabilitiesForPrincipal when called with a tenantId.
* fix: Remove categories from tenant index migration
categoriesSchema is exported but never used to create a Mongoose model.
No Category model factory exists, no code constructs a model from it,
and no categories collection exists in production databases. Including
it in the migration would attempt to drop indexes from a non-existent
collection (harmlessly skipped) but implies the collection is managed.
* fix: Restrict runAsSystem to async callbacks only
Sync callbacks returning Mongoose thenables silently lose ALS context —
the system bypass does nothing and strict mode throws with no indication
runAsSystem was involved. Narrowing to () => Promise<T> makes the wrong
pattern a compile error. All existing call sites already use async.
* fix: Use next(err) consistently in insertMany pre-hook
The hook accepted a next callback but used throw for errors. Standardize
on next(err) for all error paths so the hook speaks one language —
callback-style throughout.
* fix: Replace optional chaining with explicit null assertions in spendTokens tests
Optional chaining on test assertions masks failures with unintelligible
error messages. Add expect(result).not.toBeNull() before accessing
properties, so a null result produces a clear diagnosis instead of
"received value must be a number".
2026-03-07 16:37:10 -05:00
|
|
|
expect(result).not.toBeNull();
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(result!.prompt!.prompt).toBeCloseTo(-expectedPromptCost, 0);
|
|
|
|
|
expect(result!.completion!.completion).toBeCloseTo(-expectedCompletionCost, 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge standard rates for structured tokens when below threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-structured-standard',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 50000,
|
|
|
|
|
write: 10000,
|
|
|
|
|
read: 5000,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 1000,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
const standardPromptRate = tokenValues[model].prompt;
|
|
|
|
|
const standardCompletionRate = tokenValues[model].completion;
|
|
|
|
|
const writeRate = getCacheMultiplier({ model, cacheType: 'write' });
|
|
|
|
|
const readRate = getCacheMultiplier({ model, cacheType: 'read' });
|
|
|
|
|
|
|
|
|
|
const expectedPromptCost =
|
|
|
|
|
tokenUsage.promptTokens.input * standardPromptRate +
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
tokenUsage.promptTokens.write * (writeRate ?? 0) +
|
|
|
|
|
tokenUsage.promptTokens.read * (readRate ?? 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
const expectedCompletionCost = tokenUsage.completionTokens * standardCompletionRate;
|
|
|
|
|
|
🏢 feat: Multi-Tenant Data Isolation Infrastructure (#12091)
* chore: imports
* chore: optional chaining in `spendTokens.spec.ts`
* feat: Add tenantId field to all MongoDB schemas for multi-tenant isolation
- Add AsyncLocalStorage-based tenant context (`tenantContext.ts`) for
request-scoped tenantId propagation without modifying method signatures
- Add Mongoose `applyTenantIsolation` plugin that injects `{ tenantId }`
into all query filters when tenant context is present, with
`TENANT_ISOLATION_STRICT` env var for fail-closed production mode
- Add optional `tenantId` field to all 28 collection schemas
- Update all compound unique indexes to include tenantId (email, OAuth IDs,
role names, serverName, conversationId+user, messageId+user, etc.)
- Apply tenant isolation plugin in all 28 model factories
- Add `tenantId?: string` to all TypeScript document interfaces
Behaviorally inert — transitional mode (default) passes through all queries
unchanged. No migration required for existing deployments.
* refactor: Update tenant context and enhance tenant isolation plugin
- Changed `tenantId` in `TenantContext` to be optional, allowing for more flexible usage.
- Refactored `runAsSystem` function to accept synchronous functions, improving usability.
- Introduced comprehensive tests for the `applyTenantIsolation` plugin, ensuring correct tenant filtering in various query scenarios.
- Enhanced the plugin to handle aggregate queries and save operations with tenant context, improving data isolation capabilities.
* docs: tenant context documentation and improve tenant isolation tests
- Added detailed documentation for the `tenantStorage` AsyncLocalStorage instance in `tenantContext.ts`, clarifying its usage for async tenant context propagation.
- Updated tests in `tenantIsolation.spec.ts` to improve clarity and coverage, including new tests for strict mode behavior and tenant context propagation through await boundaries.
- Refactored existing test cases for better readability and consistency, ensuring robust validation of tenant isolation functionality.
* feat: Enhance tenant isolation by preventing tenantId mutations in update operations
- Added a new function to assert that tenantId cannot be modified through update operators in Mongoose queries.
- Implemented middleware to enforce this restriction during findOneAndUpdate, updateOne, and updateMany operations.
- Updated documentation to reflect the new behavior regarding tenantId modifications, ensuring clarity on tenant isolation rules.
* feat: Enhance tenant isolation tests and enforce tenantId restrictions
- Updated existing tests to clarify behavior regarding tenantId preservation during save and insertMany operations.
- Introduced new tests to validate that tenantId cannot be modified through update operations, ensuring strict adherence to tenant isolation rules.
- Added checks for mismatched tenantId scenarios, reinforcing the integrity of tenant context propagation.
- Enhanced test coverage for async context propagation and mutation guards, improving overall robustness of tenant isolation functionality.
* fix: Remove duplicate re-exports in utils/index.ts
Merge artifact caused `string` and `tempChatRetention` to be exported
twice, which produces TypeScript compile errors for duplicate bindings.
* fix: Resolve admin capability gap in multi-tenant mode (TODO #12091)
- hasCapabilityForPrincipals now queries both tenant-scoped AND
platform-level grants when tenantId is set, so seeded ADMIN grants
remain effective in tenant mode.
- Add applyTenantIsolation to SystemGrant model factory.
* fix: Harden tenant isolation plugin
- Add replaceGuard for replaceOne/findOneAndReplace to prevent
cross-tenant document reassignment via replacement documents.
- Cache isStrict() result to avoid process.env reads on every query.
Export _resetStrictCache() for test teardown.
- Replace console.warn with project logger (winston).
- Add 5 new tests for replace guard behavior (46 total).
* style: Fix import ordering in convo.ts and message.ts
Move type imports after value imports per project style guide.
* fix: Remove tenant isolation from SystemGrant, stamp tenantId in replaceGuard
- SystemGrant is a cross-tenant control plane whose methods handle
tenantId conditions explicitly. Applying the isolation plugin
injects a hard equality filter that overrides the $and/$or logic
in hasCapabilityForPrincipals, making platform-level ADMIN grants
invisible in tenant mode.
- replaceGuard now stamps tenantId into replacement documents when
absent, preventing replaceOne from silently stripping tenant
context. Replacements with a matching tenantId are allowed;
mismatched tenantId still throws.
* test: Add multi-tenant unique constraint and replace stamping tests
- Verify same name/email can exist in different tenants (compound
unique index allows it).
- Verify duplicate within same tenant is rejected (E11000).
- Verify tenant-scoped query returns only the correct document.
- Update replaceOne test to assert tenantId is stamped into
replacement document.
- Add test for replacement with matching tenantId.
* style: Reorder imports in message.ts to align with project style guide
* feat: Add migration to drop superseded unique indexes for multi-tenancy
Existing deployments have single-field unique indexes (e.g. { email: 1 })
that block multi-tenant operation — same email in different tenants
triggers E11000. Mongoose autoIndex creates the new compound indexes
but never drops the old ones.
dropSupersededTenantIndexes() drops all 19 superseded indexes across 11
collections. It is idempotent, skips missing indexes/collections, and
is a no-op on fresh databases.
Must be called before enabling multi-tenant middleware on an existing
deployment. Single-tenant deployments are unaffected (old indexes
coexist harmlessly until migration runs).
Includes 11 tests covering:
- Full upgrade simulation (create old indexes, drop them, verify gone)
- Multi-tenant writes work after migration (same email, different tenant)
- Intra-tenant uniqueness preserved (duplicate within tenant rejected)
- Fresh database (no-op, no errors)
- Partial migration (some collections exist, some don't)
- SUPERSEDED_INDEXES coverage validation
* fix: Update systemGrant test — platform grants now satisfy tenant queries
The TODO #12091 fix intentionally changed hasCapabilityForPrincipals to
match both tenant-scoped AND platform-level grants. The test expected
the old behavior (platform grant invisible to tenant query). Updated
test name and expectation to match the new semantics.
* fix: Align getCapabilitiesForPrincipal with hasCapabilityForPrincipals tenant query
getCapabilitiesForPrincipal used a hard tenantId equality filter while
hasCapabilityForPrincipals uses $and/$or to match both tenant-scoped
and platform-level grants. This caused the two functions to disagree
on what grants a principal holds in tenant mode.
Apply the same $or pattern: when tenantId is provided, match both
{ tenantId } and { tenantId: { $exists: false } }.
Adds test verifying platform-level ADMIN grants appear in
getCapabilitiesForPrincipal when called with a tenantId.
* fix: Remove categories from tenant index migration
categoriesSchema is exported but never used to create a Mongoose model.
No Category model factory exists, no code constructs a model from it,
and no categories collection exists in production databases. Including
it in the migration would attempt to drop indexes from a non-existent
collection (harmlessly skipped) but implies the collection is managed.
* fix: Restrict runAsSystem to async callbacks only
Sync callbacks returning Mongoose thenables silently lose ALS context —
the system bypass does nothing and strict mode throws with no indication
runAsSystem was involved. Narrowing to () => Promise<T> makes the wrong
pattern a compile error. All existing call sites already use async.
* fix: Use next(err) consistently in insertMany pre-hook
The hook accepted a next callback but used throw for errors. Standardize
on next(err) for all error paths so the hook speaks one language —
callback-style throughout.
* fix: Replace optional chaining with explicit null assertions in spendTokens tests
Optional chaining on test assertions masks failures with unintelligible
error messages. Add expect(result).not.toBeNull() before accessing
properties, so a null result produces a clear diagnosis instead of
"received value must be a number".
2026-03-07 16:37:10 -05:00
|
|
|
expect(result).not.toBeNull();
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(result!.prompt!.prompt).toBeCloseTo(-expectedPromptCost, 0);
|
|
|
|
|
expect(result!.completion!.completion).toBeCloseTo(-expectedCompletionCost, 0);
|
2026-02-20 16:21:32 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge standard rates for gemini-3.1-pro-preview when prompt tokens are below threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'gemini-3.1-pro-preview';
|
|
|
|
|
const promptTokens = 100000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-gemini31-standard-pricing',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * tokenValues['gemini-3.1'].prompt +
|
|
|
|
|
completionTokens * tokenValues['gemini-3.1'].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(balance!.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-20 16:21:32 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge premium rates for gemini-3.1-pro-preview when prompt tokens exceed threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'gemini-3.1-pro-preview';
|
|
|
|
|
const promptTokens = 250000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-gemini31-premium-pricing',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * premiumTokenValues['gemini-3.1'].prompt +
|
|
|
|
|
completionTokens * premiumTokenValues['gemini-3.1'].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(balance!.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-20 16:21:32 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge premium rates for gemini-3.1-pro-preview-customtools when prompt tokens exceed threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'gemini-3.1-pro-preview-customtools';
|
|
|
|
|
const promptTokens = 250000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-gemini31-customtools-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * premiumTokenValues['gemini-3.1'].prompt +
|
|
|
|
|
completionTokens * premiumTokenValues['gemini-3.1'].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(balance!.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-20 16:21:32 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should charge premium rates for structured gemini-3.1 tokens when total input exceeds threshold', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'gemini-3.1-pro-preview';
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-gemini31-structured-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: {
|
|
|
|
|
input: 200000,
|
|
|
|
|
write: 10000,
|
|
|
|
|
read: 5000,
|
|
|
|
|
},
|
|
|
|
|
completionTokens: 1000,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
const premiumPromptRate = premiumTokenValues['gemini-3.1'].prompt;
|
|
|
|
|
const premiumCompletionRate = premiumTokenValues['gemini-3.1'].completion;
|
|
|
|
|
const writeRate = getCacheMultiplier({ model, cacheType: 'write' });
|
|
|
|
|
const readRate = getCacheMultiplier({ model, cacheType: 'read' });
|
|
|
|
|
|
|
|
|
|
const expectedPromptCost =
|
|
|
|
|
tokenUsage.promptTokens.input * premiumPromptRate +
|
2026-03-28 21:06:39 -04:00
|
|
|
tokenUsage.promptTokens.write * writeRate! +
|
|
|
|
|
tokenUsage.promptTokens.read * readRate!;
|
2026-02-20 16:21:32 -05:00
|
|
|
const expectedCompletionCost = tokenUsage.completionTokens * premiumCompletionRate;
|
|
|
|
|
|
🏢 feat: Multi-Tenant Data Isolation Infrastructure (#12091)
* chore: imports
* chore: optional chaining in `spendTokens.spec.ts`
* feat: Add tenantId field to all MongoDB schemas for multi-tenant isolation
- Add AsyncLocalStorage-based tenant context (`tenantContext.ts`) for
request-scoped tenantId propagation without modifying method signatures
- Add Mongoose `applyTenantIsolation` plugin that injects `{ tenantId }`
into all query filters when tenant context is present, with
`TENANT_ISOLATION_STRICT` env var for fail-closed production mode
- Add optional `tenantId` field to all 28 collection schemas
- Update all compound unique indexes to include tenantId (email, OAuth IDs,
role names, serverName, conversationId+user, messageId+user, etc.)
- Apply tenant isolation plugin in all 28 model factories
- Add `tenantId?: string` to all TypeScript document interfaces
Behaviorally inert — transitional mode (default) passes through all queries
unchanged. No migration required for existing deployments.
* refactor: Update tenant context and enhance tenant isolation plugin
- Changed `tenantId` in `TenantContext` to be optional, allowing for more flexible usage.
- Refactored `runAsSystem` function to accept synchronous functions, improving usability.
- Introduced comprehensive tests for the `applyTenantIsolation` plugin, ensuring correct tenant filtering in various query scenarios.
- Enhanced the plugin to handle aggregate queries and save operations with tenant context, improving data isolation capabilities.
* docs: tenant context documentation and improve tenant isolation tests
- Added detailed documentation for the `tenantStorage` AsyncLocalStorage instance in `tenantContext.ts`, clarifying its usage for async tenant context propagation.
- Updated tests in `tenantIsolation.spec.ts` to improve clarity and coverage, including new tests for strict mode behavior and tenant context propagation through await boundaries.
- Refactored existing test cases for better readability and consistency, ensuring robust validation of tenant isolation functionality.
* feat: Enhance tenant isolation by preventing tenantId mutations in update operations
- Added a new function to assert that tenantId cannot be modified through update operators in Mongoose queries.
- Implemented middleware to enforce this restriction during findOneAndUpdate, updateOne, and updateMany operations.
- Updated documentation to reflect the new behavior regarding tenantId modifications, ensuring clarity on tenant isolation rules.
* feat: Enhance tenant isolation tests and enforce tenantId restrictions
- Updated existing tests to clarify behavior regarding tenantId preservation during save and insertMany operations.
- Introduced new tests to validate that tenantId cannot be modified through update operations, ensuring strict adherence to tenant isolation rules.
- Added checks for mismatched tenantId scenarios, reinforcing the integrity of tenant context propagation.
- Enhanced test coverage for async context propagation and mutation guards, improving overall robustness of tenant isolation functionality.
* fix: Remove duplicate re-exports in utils/index.ts
Merge artifact caused `string` and `tempChatRetention` to be exported
twice, which produces TypeScript compile errors for duplicate bindings.
* fix: Resolve admin capability gap in multi-tenant mode (TODO #12091)
- hasCapabilityForPrincipals now queries both tenant-scoped AND
platform-level grants when tenantId is set, so seeded ADMIN grants
remain effective in tenant mode.
- Add applyTenantIsolation to SystemGrant model factory.
* fix: Harden tenant isolation plugin
- Add replaceGuard for replaceOne/findOneAndReplace to prevent
cross-tenant document reassignment via replacement documents.
- Cache isStrict() result to avoid process.env reads on every query.
Export _resetStrictCache() for test teardown.
- Replace console.warn with project logger (winston).
- Add 5 new tests for replace guard behavior (46 total).
* style: Fix import ordering in convo.ts and message.ts
Move type imports after value imports per project style guide.
* fix: Remove tenant isolation from SystemGrant, stamp tenantId in replaceGuard
- SystemGrant is a cross-tenant control plane whose methods handle
tenantId conditions explicitly. Applying the isolation plugin
injects a hard equality filter that overrides the $and/$or logic
in hasCapabilityForPrincipals, making platform-level ADMIN grants
invisible in tenant mode.
- replaceGuard now stamps tenantId into replacement documents when
absent, preventing replaceOne from silently stripping tenant
context. Replacements with a matching tenantId are allowed;
mismatched tenantId still throws.
* test: Add multi-tenant unique constraint and replace stamping tests
- Verify same name/email can exist in different tenants (compound
unique index allows it).
- Verify duplicate within same tenant is rejected (E11000).
- Verify tenant-scoped query returns only the correct document.
- Update replaceOne test to assert tenantId is stamped into
replacement document.
- Add test for replacement with matching tenantId.
* style: Reorder imports in message.ts to align with project style guide
* feat: Add migration to drop superseded unique indexes for multi-tenancy
Existing deployments have single-field unique indexes (e.g. { email: 1 })
that block multi-tenant operation — same email in different tenants
triggers E11000. Mongoose autoIndex creates the new compound indexes
but never drops the old ones.
dropSupersededTenantIndexes() drops all 19 superseded indexes across 11
collections. It is idempotent, skips missing indexes/collections, and
is a no-op on fresh databases.
Must be called before enabling multi-tenant middleware on an existing
deployment. Single-tenant deployments are unaffected (old indexes
coexist harmlessly until migration runs).
Includes 11 tests covering:
- Full upgrade simulation (create old indexes, drop them, verify gone)
- Multi-tenant writes work after migration (same email, different tenant)
- Intra-tenant uniqueness preserved (duplicate within tenant rejected)
- Fresh database (no-op, no errors)
- Partial migration (some collections exist, some don't)
- SUPERSEDED_INDEXES coverage validation
* fix: Update systemGrant test — platform grants now satisfy tenant queries
The TODO #12091 fix intentionally changed hasCapabilityForPrincipals to
match both tenant-scoped AND platform-level grants. The test expected
the old behavior (platform grant invisible to tenant query). Updated
test name and expectation to match the new semantics.
* fix: Align getCapabilitiesForPrincipal with hasCapabilityForPrincipals tenant query
getCapabilitiesForPrincipal used a hard tenantId equality filter while
hasCapabilityForPrincipals uses $and/$or to match both tenant-scoped
and platform-level grants. This caused the two functions to disagree
on what grants a principal holds in tenant mode.
Apply the same $or pattern: when tenantId is provided, match both
{ tenantId } and { tenantId: { $exists: false } }.
Adds test verifying platform-level ADMIN grants appear in
getCapabilitiesForPrincipal when called with a tenantId.
* fix: Remove categories from tenant index migration
categoriesSchema is exported but never used to create a Mongoose model.
No Category model factory exists, no code constructs a model from it,
and no categories collection exists in production databases. Including
it in the migration would attempt to drop indexes from a non-existent
collection (harmlessly skipped) but implies the collection is managed.
* fix: Restrict runAsSystem to async callbacks only
Sync callbacks returning Mongoose thenables silently lose ALS context —
the system bypass does nothing and strict mode throws with no indication
runAsSystem was involved. Narrowing to () => Promise<T> makes the wrong
pattern a compile error. All existing call sites already use async.
* fix: Use next(err) consistently in insertMany pre-hook
The hook accepted a next callback but used throw for errors. Standardize
on next(err) for all error paths so the hook speaks one language —
callback-style throughout.
* fix: Replace optional chaining with explicit null assertions in spendTokens tests
Optional chaining on test assertions masks failures with unintelligible
error messages. Add expect(result).not.toBeNull() before accessing
properties, so a null result produces a clear diagnosis instead of
"received value must be a number".
2026-03-07 16:37:10 -05:00
|
|
|
expect(result).not.toBeNull();
|
2026-03-28 21:06:39 -04:00
|
|
|
expect(result!.prompt!.prompt).toBeCloseTo(-expectedPromptCost, 0);
|
|
|
|
|
expect(result!.completion!.completion).toBeCloseTo(-expectedCompletionCost, 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should not apply premium pricing to non-premium models regardless of prompt size', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-5';
|
|
|
|
|
const promptTokens = 300000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-no-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const expectedCost =
|
|
|
|
|
promptTokens * tokenValues[model].prompt + completionTokens * tokenValues[model].completion;
|
|
|
|
|
|
|
|
|
|
const balance = await Balance.findOne({ user: userId });
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(balance?.tokenCredits).toBeCloseTo(initialBalance - expectedCost, 0);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
describe('inputTokenCount Normalization', () => {
|
|
|
|
|
it('should normalize negative promptTokens to zero for inputTokenCount', async () => {
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 100000000,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-negative-prompt',
|
|
|
|
|
model: 'claude-opus-4-6',
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens: -500, completionTokens: 100 });
|
|
|
|
|
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
|
|
|
|
|
const completionTx = transactions.find((t) => t.tokenType === 'completion');
|
|
|
|
|
const promptTx = transactions.find((t) => t.tokenType === 'prompt');
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(Math.abs(promptTx?.rawAmount ?? 0)).toBe(0);
|
|
|
|
|
expect(completionTx?.rawAmount).toBe(-100);
|
2026-02-06 18:35:36 -05:00
|
|
|
|
|
|
|
|
const standardCompletionRate = tokenValues['claude-opus-4-6'].completion;
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(completionTx?.rate).toBe(standardCompletionRate);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should use normalized inputTokenCount for premium threshold check on completion', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const promptTokens = 250000;
|
|
|
|
|
const completionTokens = 500;
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-normalized-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens, completionTokens });
|
|
|
|
|
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
const completionTx = transactions.find((t) => t.tokenType === 'completion');
|
|
|
|
|
const promptTx = transactions.find((t) => t.tokenType === 'prompt');
|
|
|
|
|
|
|
|
|
|
const premiumPromptRate = premiumTokenValues[model].prompt;
|
|
|
|
|
const premiumCompletionRate = premiumTokenValues[model].completion;
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(promptTx?.rate).toBe(premiumPromptRate);
|
|
|
|
|
expect(completionTx?.rate).toBe(premiumCompletionRate);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should keep inputTokenCount as zero when promptTokens is zero', async () => {
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: 100000000,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-zero-prompt',
|
|
|
|
|
model: 'claude-opus-4-6',
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens: 0, completionTokens: 100 });
|
|
|
|
|
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
const completionTx = transactions.find((t) => t.tokenType === 'completion');
|
|
|
|
|
const promptTx = transactions.find((t) => t.tokenType === 'prompt');
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(Math.abs(promptTx?.rawAmount ?? 0)).toBe(0);
|
2026-02-06 18:35:36 -05:00
|
|
|
|
|
|
|
|
const standardCompletionRate = tokenValues['claude-opus-4-6'].completion;
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(completionTx?.rate).toBe(standardCompletionRate);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should not trigger premium pricing with negative promptTokens on premium model', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-negative-no-premium',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendTokens(txData, { promptTokens: -300000, completionTokens: 500 });
|
|
|
|
|
|
|
|
|
|
const transactions = await Transaction.find({ user: userId }).sort({ tokenType: 1 });
|
|
|
|
|
const completionTx = transactions.find((t) => t.tokenType === 'completion');
|
|
|
|
|
|
|
|
|
|
const standardCompletionRate = tokenValues[model].completion;
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(completionTx?.rate).toBe(standardCompletionRate);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should normalize negative structured token values to zero in spendStructuredTokens', async () => {
|
|
|
|
|
const initialBalance = 100000000;
|
|
|
|
|
await Balance.create({
|
|
|
|
|
user: userId,
|
|
|
|
|
tokenCredits: initialBalance,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const model = 'claude-opus-4-6';
|
|
|
|
|
const txData = {
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-negative-structured',
|
|
|
|
|
model,
|
|
|
|
|
context: 'test',
|
|
|
|
|
balance: { enabled: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const tokenUsage = {
|
|
|
|
|
promptTokens: { input: -100, write: 50, read: -30 },
|
|
|
|
|
completionTokens: -200,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await spendStructuredTokens(txData, tokenUsage);
|
|
|
|
|
|
|
|
|
|
const transactions = await Transaction.find({
|
|
|
|
|
user: userId,
|
|
|
|
|
conversationId: 'test-negative-structured',
|
|
|
|
|
}).sort({ tokenType: 1 });
|
|
|
|
|
|
|
|
|
|
const completionTx = transactions.find((t) => t.tokenType === 'completion');
|
|
|
|
|
const promptTx = transactions.find((t) => t.tokenType === 'prompt');
|
|
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(Math.abs(promptTx?.inputTokens ?? 0)).toBe(0);
|
|
|
|
|
expect(promptTx?.writeTokens).toBe(-50);
|
|
|
|
|
expect(Math.abs(promptTx?.readTokens ?? 0)).toBe(0);
|
2026-02-06 18:35:36 -05:00
|
|
|
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(Math.abs(completionTx?.rawAmount ?? 0)).toBe(0);
|
2026-02-06 18:35:36 -05:00
|
|
|
|
|
|
|
|
const standardRate = tokenValues[model].completion;
|
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830)
* chore: move database model methods to /packages/data-schemas
* chore: add TypeScript ESLint rule to warn on unused variables
* refactor: model imports to streamline access
- Consolidated model imports across various files to improve code organization and reduce redundancy.
- Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path.
- Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact.
- Enhanced test files to align with the new import paths, maintaining test coverage and integrity.
* chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas
* test: update agent model mocks in unit tests
- Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality.
- Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication.
- Ensured consistency in agent mock implementations across test files.
* fix: update types in data-schemas
* refactor: enhance type definitions in transaction and spending methods
- Updated type definitions in `checkBalance.ts` to use specific request and response types.
- Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety.
- Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods.
- Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness.
* refactor: streamline model imports and enhance code organization
- Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy.
- Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact.
- Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods.
* feat: implement loadAddedAgent and refactor agent loading logic
- Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution.
- Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`.
- Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`.
- Enhanced type definitions and improved error handling in the agent loading process.
- Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage.
* refactor: enhance balance handling with new update interface
- Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase.
- Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety.
- Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities.
- Enhanced overall code clarity and maintainability by refining type definitions related to balance operations.
* feat: add unit tests for loadAgent functionality and enhance agent loading logic
- Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks.
- Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality.
- Improved test coverage for agent loading, including handling of non-existent agents and user permissions.
* chore: reorder memory method exports for consistency
- Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
|
|
|
expect(completionTx?.rate).toBe(standardRate);
|
2026-02-06 18:35:36 -05:00
|
|
|
});
|
|
|
|
|
});
|
2024-08-24 04:36:08 -04:00
|
|
|
});
|