🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ test: prune redundant cases and restore boundary contract coverage (#19945)
AmAzing-2b4cc0f184ed
diff --git a/packages/builtin-tool-calculator/src/calculate.test.ts b/packages/builtin-tool-calculator/src/calculate.test.tsindex 190cef25a3a..67072dfca42 100644--- a/packages/builtin-tool-calculator/src/calculate.test.ts+++ b/packages/builtin-tool-calculator/src/calculate.test.ts@@ -4,12 +4,6 @@ import { describe, expect, it, vi } from 'vitest';import { calculatorExecutor } from '../src/executor';describe('Unit Conversion', () => {- it('should handle temperature conversion with mathjs syntax', async () => {- const result = await calculatorExecutor.calculate({ expression: '25 degC to degF' });- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(77, 0);- });-it('should handle various temperature formats', async () => {const fahrenheit = await calculatorExecutor.calculate({ expression: '100 degC to degF' });expect(fahrenheit.success).toBe(true);@@ -43,48 +37,6 @@ describe('Unit Conversion', () => {expect(result.success).toBe(true);expect(result.content).toContain('3*x');});-- it('should differentiate quadratic expressions', async () => {- const result = await calculatorExecutor.differentiate({- expression: 'x^2',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('2*x');- });-- it('should differentiate trigonometric functions', async () => {- const result = await calculatorExecutor.differentiate({- expression: 'sin(x)',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('cos(x)');- });-- it('should differentiate exponential functions', async () => {- const result = await calculatorExecutor.differentiate({- expression: 'exp(x)',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('e^x');- });-- it('should handle chain rule', async () => {- const result = await calculatorExecutor.differentiate({- expression: 'sin(x^2)',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('cos');- expect(result.content).toContain('x');- });-it('should differentiate with respect to custom variable', async () => {const result = await calculatorExecutor.differentiate({expression: 'y^2 + 2*y',@@ -129,49 +81,6 @@ describe('Unit Conversion', () => {expect(result.content).toContain('(1/3)');expect(result.content).toContain('x^3');});-- it('should integrate cubic expressions', async () => {- const result = await calculatorExecutor.integrate({- expression: 'x^3',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('(1/4)');- expect(result.content).toContain('x^4');- });-- it('should integrate trigonometric functions', async () => {- const result = await calculatorExecutor.integrate({- expression: 'sin(x)',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('-cos');- });-- it('should integrate exponential functions', async () => {- const result = await calculatorExecutor.integrate({- expression: 'exp(x)',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('e^x');- });-- it('should integrate linear expressions', async () => {- const result = await calculatorExecutor.integrate({- expression: '3*x',- variable: 'x',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('(3/2)');- expect(result.content).toContain('x^2');- });-it('should integrate with respect to custom variable', async () => {const result = await calculatorExecutor.integrate({expression: 'y^2',@@ -240,29 +149,6 @@ describe('Unit Conversion', () => {expect(result.error?.type).toBe('LimitError');expect(result.content).toContain('Limit computation error');});-- it('should compute limit approaching from left', async () => {- const result = await calculatorExecutor.limit({- expression: '(1+1/x)^x',- variable: 'x',- point: 'infinity',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('infinity');- });-- it('should compute limit with trigonometric function', async () => {- const result = await calculatorExecutor.limit({- expression: '(1-cos(x))/x',- variable: 'x',- point: 0,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('0');- });-it('should handle invalid expressions gracefully', async () => {const result = await calculatorExecutor.limit({expression: 'invalid',@@ -295,19 +181,6 @@ describe('Unit Conversion', () => {expect(PI.success).toBe(true);expect(parseFloat(PI.content || '0')).toBeCloseTo(3.14159, 5);});-- it('should handle PI in expressions', async () => {- const result = await calculatorExecutor.calculate({ expression: '2 * pi' });- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(6.28318, 4);- });-- it('should handle PI in trigonometric functions', async () => {- const result = await calculatorExecutor.calculate({ expression: 'sin(pi/2)' });- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(1, 5);- });-it('should handle PI in evaluate', async () => {const result = await calculatorExecutor.evaluate({expression: 'x * pi',@@ -316,18 +189,6 @@ describe('Unit Conversion', () => {expect(result.success).toBe(true);expect(parseFloat(result.content || '0')).toBeCloseTo(9.42477, 4);});-- it('should handle other constants like E', async () => {- const e = await calculatorExecutor.calculate({ expression: 'e' });- expect(e.success).toBe(true);- expect(parseFloat(e.content || '0')).toBeCloseTo(2.71828, 5);- });-- it('should handle constants in scientific notation', async () => {- const result = await calculatorExecutor.calculate({ expression: 'pi * 1e3' });- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(3141.59, 2);- });});describe('Calculator Definite Integration', () => {@@ -347,43 +208,6 @@ describe('Calculator Definite Integration', () => {expect(result.state?.lowerBound).toBe(0);expect(result.state?.upperBound).toBe(1);});-- it('should compute definite integral of trigonometric function', async () => {- const result = await calculatorExecutor.defintegrate({- expression: 'sin(x)',- variable: 'x',- lowerBound: 0,- upperBound: 'pi',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('2');- });-- it('should compute definite integral of exponential function', async () => {- const result = await calculatorExecutor.defintegrate({- expression: 'exp(x)',- variable: 'x',- lowerBound: 0,- upperBound: 1,- });-- expect(result.success).toBe(true);- expect(result.content).toMatch(/e|205671881\/119696244/); // Either 'e' or fraction form- });-- it('should compute definite integral with negative bounds', async () => {- const result = await calculatorExecutor.defintegrate({- expression: 'x^3',- variable: 'x',- lowerBound: -1,- upperBound: 1,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('0');- });-it('should compute definite integral to infinity', async () => {const result = await calculatorExecutor.defintegrate({expression: '1/x^2',@@ -395,18 +219,6 @@ describe('Calculator Definite Integration', () => {expect(result.success).toBe(true);expect(result.content).toMatch(/1|infinity/); // Either '1' or symbolic infinity form});-- it('should handle definite integral with fractional bounds', async () => {- const result = await calculatorExecutor.defintegrate({- expression: 'x',- variable: 'x',- lowerBound: 0.5,- upperBound: 1.5,- });-- expect(result.success).toBe(true);- });-it('should handle definite integral with string bounds', async () => {const result = await calculatorExecutor.defintegrate({expression: 'cos(x)',@@ -446,19 +258,6 @@ describe('Calculator Definite Integration', () => {expect(result.success).toBe(true);expect(result.content).toContain('invalid');});-- it('should handle complex expressions', async () => {- const result = await calculatorExecutor.defintegrate({- expression: 'x^2 + 2*x + 1',- variable: 'x',- lowerBound: 0,- upperBound: 2,- });-- expect(result.success).toBe(true);- expect(result.content).toBeDefined();- });-it('should handle zero-width interval', async () => {const result = await calculatorExecutor.defintegrate({expression: 'x^2',@@ -485,61 +284,6 @@ describe('Calculator Nerdamer Execute', () => {expect(result.state?.expression).toBe('expand((x+1)^2)');expect(result.state?.result).toBeDefined();});-- it('should execute factor expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'factor(x^2-1)',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('(-1+x)*(1+x)');- });-- it('should execute partfrac expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'partfrac(1/(x^2-1))',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('1/2');- });-- it('should execute simplify expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'simplify(x^2+2*x-x)',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('(1+x)*x');- });-- it('should execute toTeX expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'toTeX(x^2+2*x+1)',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('(1+2*x+x^2)*toTeX');- });-- it('should execute coefficients expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'coeffs(x^3+2*x^2+3*x+4)',- });-- expect(result.success).toBe(true);- expect(result.content).toContain('[4,3,2,1]');- });-- it('should execute roots expression', async () => {- const result = await calculatorExecutor.execute({- expression: 'roots(x^2-4)',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('[2,-2]');- });-it('should handle invalid expressions gracefully', async () => {const result = await calculatorExecutor.execute({expression: 'invalid_function(x)',@@ -573,43 +317,6 @@ describe('Calculator Base Conversion', () => {expect(result.content).toBe('10');expect(result.state?.decimalValue).toBe(10);});-- it('should base hexadecimal to octal', async () => {- const result = await calculatorExecutor.base({- number: 'FF',- fromBase: 16,- toBase: 8,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('377');- expect(result.state?.decimalValue).toBe(255);- });-- it('should base octal to hexadecimal', async () => {- const result = await calculatorExecutor.base({- number: '77',- fromBase: 8,- toBase: 16,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('3F');- expect(result.state?.decimalValue).toBe(63);- });-- it('should handle hexadecimal input', async () => {- const result = await calculatorExecutor.base({- number: 'FF',- fromBase: 16,- toBase: 10,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('255');- expect(result.state?.decimalValue).toBe(255);- });-it('should handle invalid numbers', async () => {const result = await calculatorExecutor.base({number: '2AB',@@ -632,19 +339,6 @@ describe('Calculator Base Conversion', () => {expect(result.content).toBe('35');expect(result.state?.decimalValue).toBe(35);});-- it('should base decimal to base 32', async () => {- const result = await calculatorExecutor.base({- number: '1000',- fromBase: 10,- toBase: 32,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('V8');- expect(result.state?.decimalValue).toBe(1000);- });-it('should handle invalid base 37', async () => {const result = await calculatorExecutor.base({number: '123',@@ -677,16 +371,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(true);expect(result.content).toBe('1.968503937 inch');});-- it('should handle unit conversions (kg to lb)', async () => {- const result = await calculatorExecutor.calculate({- expression: '1 kg to lb',- });-- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(2.20462, 5);- });-it('should handle scientific functions', async () => {const result = await calculatorExecutor.calculate({expression: 'sin(30 deg)',@@ -695,25 +379,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(true);expect(parseFloat(result.content || '0')).toBeCloseTo(0.5, 5);});-- it('should handle matrix operations', async () => {- const result = await calculatorExecutor.calculate({- expression: 'det([[1,2],[3,4]])',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('-2');- });-- it('should handle complex numbers', async () => {- const result = await calculatorExecutor.calculate({- expression: 'sqrt(-1)',- });-- expect(result.success).toBe(true);- expect(result.content).toBe('i');- });-it('should handle precision formatting', async () => {const result = await calculatorExecutor.calculate({expression: '10 / 3',@@ -756,17 +421,6 @@ describe('Calculator Core Functions', () => {expect(result.state?.result).toBe('36');expect(result.state?.variables).toEqual({ x: 5 });});-- it('should handle multiple variables', async () => {- const result = await calculatorExecutor.evaluate({- expression: 'a*x + b',- variables: { a: 2, x: 3, b: 1 },- });-- expect(result.success).toBe(true);- expect(result.content).toBe('7');- });-it('should handle no variables', async () => {const result = await calculatorExecutor.evaluate({expression: '2 + 2',@@ -785,16 +439,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(false);expect(result.error?.type).toBe('CalculationError');});-- it('should handle complex expressions with variables', async () => {- const result = await calculatorExecutor.evaluate({- expression: 'sin(x) * cos(y)',- variables: { x: 1.5708, y: 0 }, // Approximate pi/2- });-- expect(result.success).toBe(true);- expect(parseFloat(result.content || '0')).toBeCloseTo(1, 5);- });});describe('base', () => {@@ -808,18 +452,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(true);expect(result.content).toBe('11111111');});-- it('should handle string input in base conversion', async () => {- const result = await calculatorExecutor.base({- number: '255',- fromBase: 10,- toBase: 2,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('11111111');- });-it('should handle zero in base conversion', async () => {const result = await calculatorExecutor.base({number: '0',@@ -830,29 +462,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(true);expect(result.content).toBe('0');});-- it('should handle large numbers', async () => {- const result = await calculatorExecutor.base({- number: '4294967295',- fromBase: 10,- toBase: 16,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('FFFFFFFF');- });-- it('should handle base 36 conversion', async () => {- const result = await calculatorExecutor.base({- number: '123456789',- fromBase: 10,- toBase: 36,- });-- expect(result.success).toBe(true);- expect(result.content).toBe('21I3V9');- });-it('should handle invalid base error', async () => {const result = await calculatorExecutor.base({number: '123',@@ -900,17 +509,6 @@ describe('Calculator Core Functions', () => {expect(result.success).toBe(true);expect(result.content).toBe('Infinity');});-- it('should handle expression evaluation errors gracefully', async () => {- const result = await calculatorExecutor.evaluate({- expression: 'x ^^^^^ y',- variables: { x: 1, y: 2 },- });-- expect(result.success).toBe(false);- expect(result.error?.type).toBe('CalculationError');- });-it('should preserve state information on errors', async () => {const result = await calculatorExecutor.calculate({expression: 'invalid',@@ -957,18 +555,6 @@ describe('Calculator Sorting', () => {expect(Array.isArray(parsed)).toBe(true);expect(parsed).toEqual(['1.618', '2.718', '3.14']);});-- it('should compare mixed string and number inputs', async () => {- const result = await calculatorExecutor.sort({- numbers: ['3.14', 2.718, '1.618'],- mode: 'largest',- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('3.14');- });-it('should handle precision formatting', async () => {const result = await calculatorExecutor.sort({numbers: [3.1415926535, 2.7182818284, 1.6180339887],@@ -980,30 +566,6 @@ describe('Calculator Sorting', () => {expect(Array.isArray(parsed)).toBe(true);expect(parsed).toEqual(['1.618', '2.718', '3.142']);});-- it('should handle zero precision', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718, 1.618],- mode: 'largest',- precision: 0,- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('3');- });-- it('should handle duplicate values', async () => {- const result = await calculatorExecutor.sort({- numbers: [5, 3, 5, 2],- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(Array.isArray(parsed)).toBe(true);- expect(parsed).toEqual(['2', '3', '5', '5']);- });-it('should require at least 2 numbers', async () => {const result = await calculatorExecutor.sort({numbers: [3.14],@@ -1023,40 +585,6 @@ describe('Calculator Sorting', () => {expect(result.error?.type).toBe('ComparisonError');expect(result.content).toContain('Invalid number: invalid');});-- it('should handle negative numbers', async () => {- const result = await calculatorExecutor.sort({- numbers: [-3.14, -2.718, -1.618],- mode: 'smallest',- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('-3.14');- });-- it('should handle zero values', async () => {- const result = await calculatorExecutor.sort({- numbers: [0, -1, 1],- mode: 'largest',- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('1');- });-- it('should handle very large numbers', async () => {- const result = await calculatorExecutor.sort({- numbers: [1e10, 1e9, 1e11],- mode: 'smallest',- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('1000000000');- });-it('should preserve state information', async () => {const result = await calculatorExecutor.sort({numbers: [3.14, 2.718],@@ -1084,65 +612,6 @@ describe('Calculator Sorting', () => {expect(Array.isArray(parsed)).toBe(true);expect(parsed).toEqual(['4.669', '3.14', '2.718', '1.618']);});-- it('should sort in ascending order when reverse is false', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718, 1.618, 4.669],- reverse: false,- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(Array.isArray(parsed)).toBe(true);- expect(parsed).toEqual(['1.618', '2.718', '3.14', '4.669']);- });-- it('should default to ascending order when reverse is not specified', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718, 1.618, 4.669],- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(Array.isArray(parsed)).toBe(true);- expect(parsed).toEqual(['1.618', '2.718', '3.14', '4.669']);- });-- it('should work with reverse parameter in largest mode', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718, 1.618, 4.669],- mode: 'largest',- reverse: true,- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('4.669');- });-- it('should work with reverse parameter in smallest mode', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718, 1.618, 4.669],- mode: 'smallest',- reverse: true,- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parsed).toBe('1.618');- });-- it('should preserve reverse parameter in state', async () => {- const result = await calculatorExecutor.sort({- numbers: [3.14, 2.718],- reverse: true,- precision: 2,- });-- expect(result.success).toBe(true);- expect(result.state?.reverse).toBe(true);- expect(result.state?.sorted).toEqual(['3.14', '2.72']);- });});});@@ -1157,28 +626,6 @@ describe('Calculator Equation Solver', () => {expect(result.content).toContain('5');expect(result.state?.equation).toEqual(['3*x + 5 = 20']);});-- it('should solve quadratic equations', async () => {- const result = await calculatorExecutor.solve({- equation: ['x^2 - 5*x + 6 = 0'],- });-- expect(result.success).toBe(true);- expect(result.content).toContain('2');- expect(result.content).toContain('3');- expect(result.state?.equation).toEqual(['x^2 - 5*x + 6 = 0']);- });-- it('should solve perfect square equations', async () => {- const result = await calculatorExecutor.solve({- equation: ['x^2 + 2*x + 1 = 0'],- });-- expect(result.success).toBe(true);- expect(result.content).toContain('-1');- expect(result.state?.equation).toEqual(['x^2 + 2*x + 1 = 0']);- });-it('should solve equations with custom variable', async () => {const result = await calculatorExecutor.solve({equation: ['y^2 - 9 = 0'],@@ -1190,34 +637,6 @@ describe('Calculator Equation Solver', () => {expect(result.content).toContain('-3');expect(result.state?.variable).toEqual(['y']);});-- it('should solve simple equations', async () => {- const result = await calculatorExecutor.solve({- equation: ['x - 5 = 0'],- });-- expect(result.success).toBe(true);- expect(result.content).toContain('5');- });-- it('should handle equations with fractions', async () => {- const result = await calculatorExecutor.solve({- equation: ['2*x = 10'],- });-- expect(result.success).toBe(true);- expect(result.content).toContain('5');- });-- it('should handle cubic equations', async () => {- const result = await calculatorExecutor.solve({- equation: ['x^3 - 8 = 0'],- });-- expect(result.success).toBe(true);- expect(result.content).toContain('2');- });-it('should handle invalid equations gracefully', async () => {const result = await calculatorExecutor.solve({equation: ['invalid equation'],@@ -1251,6 +670,17 @@ describe('Calculator Equation Solver', () => {expect(parsed.y).toBe('1');});+ it('should solve system of two equations with default variables', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['3*x+2*y=7', 'x-y=1'],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parseFloat(parsed.x)).toBeCloseTo(1.8, 1);+ expect(parseFloat(parsed.y)).toBeCloseTo(0.8, 1);+ });+it('should report an unsolvable system instead of dereferencing an empty result', async () => {// Newer nerdamer returns nothing for an unsolvable system rather than// throwing. Assert the guard's own message: the surrounding catch turns@@ -1272,18 +702,6 @@ describe('Calculator Equation Solver', () => {spy.mockRestore();}});-- it('should solve system of two equations with default variables', async () => {- const result = await calculatorExecutor.solve({- equation: ['3*x+2*y=7', 'x-y=1'],- });-- expect(result.success).toBe(true);- const parsed = JSON.parse(result.content || '{}');- expect(parseFloat(parsed.x)).toBeCloseTo(1.8, 1);- expect(parseFloat(parsed.y)).toBeCloseTo(0.8, 1);- });-it('should solve system of three equations', async () => {const result = await calculatorExecutor.solve({equation: ['x+y+z=6', '2*x-y+z=3', 'x+2*y-z=2'],diff --git a/packages/const/src/utils/merge.test.ts b/packages/const/src/utils/merge.test.tsindex f3af1a49fc6..61488f656ff 100644--- a/packages/const/src/utils/merge.test.ts+++ b/packages/const/src/utils/merge.test.ts@@ -12,20 +12,6 @@ describe('merge', () => {expect(result).toEqual({ a: 1, b: 3, c: 4 });});-- it('should merge nested objects', () => {- const target = { a: { x: 1, y: 2 }, b: 3 };- const source = { a: { y: 4, z: 5 }, c: 6 };-- const result = merge(target, source);-- expect(result).toEqual({- a: { x: 1, y: 4, z: 5 },- b: 3,- c: 6,- });- });-it('should not mutate the original objects', () => {const target = { a: 1, b: 2 };const source = { b: 3, c: 4 };@@ -49,77 +35,9 @@ describe('merge', () => {expect(result).toEqual({ items: [4, 5] });});-- it('should replace arrays in nested objects', () => {- const target = {- config: {- values: [1, 2, 3],- name: 'original',- },- };- const source = {- config: {- values: [7, 8, 9],- },- };-- const result = merge(target, source);-- expect(result).toEqual({- config: {- values: [7, 8, 9],- name: 'original',- },- });- });-- it('should handle empty arrays', () => {- const target = { items: [1, 2, 3] };- const source = { items: [] };-- const result = merge(target, source);-- expect(result).toEqual({ items: [] });- });-- it('should handle arrays with objects', () => {- const target = { items: [{ id: 1, name: 'a' }] };- const source = { items: [{ id: 2, name: 'b' }] };-- const result = merge(target, source);-- expect(result).toEqual({ items: [{ id: 2, name: 'b' }] });- });});describe('edge cases', () => {- it('should handle empty target', () => {- const target = {};- const source = { a: 1, b: 2 };-- const result = merge(target, source);-- expect(result).toEqual({ a: 1, b: 2 });- });-- it('should handle empty source', () => {- const target = { a: 1, b: 2 };- const source = {};-- const result = merge(target, source);-- expect(result).toEqual({ a: 1, b: 2 });- });-- it('should handle null values', () => {- const target = { a: 1, b: 2 };- const source = { b: null };-- const result = merge(target, source);-- expect(result).toEqual({ a: 1, b: null });- });-it('should handle undefined values by not overwriting', () => {const target = { a: 1, b: 2 };const source = { b: undefined, c: 3 };@@ -129,99 +47,6 @@ describe('merge', () => {// lodash merge doesn't overwrite with undefinedexpect(result).toEqual({ a: 1, b: 2, c: 3 });});-- it('should handle deeply nested objects', () => {- const target = {- level1: {- level2: {- level3: {- value: 'original',- },- },- },- };- const source = {- level1: {- level2: {- level3: {- value: 'updated',- newProp: 'added',- },- },- },- };-- const result = merge(target, source);-- expect(result).toEqual({- level1: {- level2: {- level3: {- value: 'updated',- newProp: 'added',- },- },- },- });- });- });-- describe('mixed data types', () => {- it('should handle boolean values', () => {- const target = { enabled: true, active: false };- const source = { enabled: false };-- const result = merge(target, source);-- expect(result).toEqual({ enabled: false, active: false });- });-- it('should handle number values', () => {- const target = { count: 10, limit: 100 };- const source = { count: 20 };-- const result = merge(target, source);-- expect(result).toEqual({ count: 20, limit: 100 });- });-- it('should handle string values', () => {- const target = { name: 'original', description: 'test' };- const source = { name: 'updated' };-- const result = merge(target, source);-- expect(result).toEqual({ name: 'updated', description: 'test' });- });-- it('should handle mixed types in nested objects', () => {- const target = {- config: {- enabled: true,- count: 10,- items: [1, 2],- metadata: { key: 'value' },- },- };- const source = {- config: {- enabled: false,- items: [3, 4, 5],- metadata: { key: 'updated', newKey: 'newValue' },- },- };-- const result = merge(target, source);-- expect(result).toEqual({- config: {- enabled: false,- count: 10,- items: [3, 4, 5],- metadata: { key: 'updated', newKey: 'newValue' },- },- });- });});});@@ -301,16 +126,6 @@ describe('mergeArrayById', () => {const result = mergeArrayById(defaultItems, []);expect(result).toEqual(defaultItems);});-- it('should return all user items when default items is empty', () => {- const userItems = [- { id: '1', name: 'User 1', value: 300 },- { id: '2', name: 'User 2', value: 400 },- ];-- const result = mergeArrayById([], userItems);- expect(result).toEqual(userItems);- });});describe('ID matching scenarios', () => {@@ -327,49 +142,6 @@ describe('mergeArrayById', () => {expect(result).toContainEqual({ id: '1', name: 'User 1', value: 200 });expect(result).toContainEqual({ id: '2', name: 'User 2', value: 300 });});-- it('should preserve default items not in user items', () => {- const defaultItems = [- { id: '1', name: 'Default 1', value: 100 },- { id: '2', name: 'Default 2', value: 200 },- { id: '3', name: 'Default 3', value: 300 },- ];- const userItems = [{ id: '2', name: 'User 2', value: 250 }];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toHaveLength(3);- expect(result).toContainEqual({ id: '1', name: 'Default 1', value: 100 });- expect(result).toContainEqual({ id: '2', name: 'User 2', value: 250 });- expect(result).toContainEqual({ id: '3', name: 'Default 3', value: 300 });- });-- it('should merge multiple items correctly', () => {- const defaultItems = [- { id: '1', name: 'Default 1', value: 100, meta: { key: 'value1' } },- { id: '2', name: 'Default 2', value: 200, meta: { key: 'value2' } },- ];- const userItems = [- { id: '2', name: 'User 2', value: 300 },- { id: '1', name: 'User 1', value: 400 },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toHaveLength(2);- expect(result).toContainEqual({- id: '1',- name: 'User 1',- value: 400,- meta: { key: 'value1' },- });- expect(result).toContainEqual({- id: '2',- name: 'User 2',- value: 300,- meta: { key: 'value2' },- });- });});describe('special value handling', () => {@@ -447,47 +219,6 @@ describe('mergeArrayById', () => {surface: 'changed',});});-- it('should handle deeply nested object merging', () => {- const defaultItems = [- {- id: '1',- abilities: {- reasoning: true,- functionCalling: true,- },- config: {- deploymentName: 'default',- },- },- ];- const userItems = [- {- id: '1',- abilities: {- reasoning: false,- },- config: {- deploymentName: 'custom',- },- },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toEqual([- {- id: '1',- abilities: {- functionCalling: true,- reasoning: false,- },- config: {- deploymentName: 'custom',- },- },- ]);- });});describe('edge cases', () => {@@ -539,141 +270,5 @@ describe('mergeArrayById', () => {meta: 'second',});});-- it('should handle complex real-world scenario', () => {- const defaultItems = [- {- contextWindowTokens: 200_000,- description: 'Advanced reasoning model',- displayName: 'Model O1',- enabled: true,- id: 'o1',- abilities: {- reasoning: true,- functionCalling: true,- },- config: {- deploymentName: 'o1',- },- maxOutput: 100_000,- pricing: {- input: 15,- output: 60,- },- source: 'builtin',- },- ];- const userItems = [- {- id: 'o1',- abilities: {- reasoning: false,- },- config: {- deploymentName: 'custom-o1',- },- displayName: 'Custom O1',- enabled: false,- },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toEqual([- {- contextWindowTokens: 200_000,- description: 'Advanced reasoning model',- displayName: 'Custom O1',- enabled: false,- id: 'o1',- abilities: {- functionCalling: true,- reasoning: false,- },- config: {- deploymentName: 'custom-o1',- },- maxOutput: 100_000,- pricing: {- input: 15,- output: 60,- },- source: 'builtin',- },- ]);- });-- it('should handle items with only id property', () => {- const defaultItems = [{ id: '1', name: 'Default', value: 100 }];- const userItems = [{ id: '1' }];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toEqual([{ id: '1', name: 'Default', value: 100 }]);- });-- it('should handle mixed scenario with new, updated, and unchanged items', () => {- const defaultItems = [- { id: '1', name: 'Default 1', value: 100 },- { id: '2', name: 'Default 2', value: 200 },- { id: '3', name: 'Default 3', value: 300 },- ];- const userItems = [- { id: '2', name: 'Updated 2', value: 250 },- { id: '4', name: 'New 4', value: 400 },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result).toHaveLength(4);- expect(result).toContainEqual({ id: '1', name: 'Default 1', value: 100 });- expect(result).toContainEqual({ id: '2', name: 'Updated 2', value: 250 });- expect(result).toContainEqual({ id: '3', name: 'Default 3', value: 300 });- expect(result).toContainEqual({ id: '4', name: 'New 4', value: 400 });- });- });-- describe('primitive value handling in arrays', () => {- it('should handle simple property replacement', () => {- const defaultItems = [- {- id: '1',- name: 'Default',- count: 10,- },- ];- const userItems = [- {- id: '1',- count: 20,- },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result[0].count).toBe(20);- expect((result[0] as any).name).toBe('Default');- });-- it('should handle string values correctly', () => {- const defaultItems = [- {- id: '1',- title: 'Default Title',- description: 'Default Description',- },- ];- const userItems = [- {- id: '1',- title: 'Custom Title',- },- ];-- const result = mergeArrayById(defaultItems, userItems);-- expect(result[0].title).toBe('Custom Title');- expect((result[0] as any).description).toBe('Default Description');- });});});diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.tsindex 26fa1374690..3195e797758 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts@@ -96,12 +96,6 @@ describe('ToolNameResolver', () => {const result = resolver.generate('plugin', '', 'builtin');expect(result).toBe('plugin____');});-- it('should handle numeric identifiers and action names', () => {- const result = resolver.generate('plugin123', 'action456', 'type789');- expect(result).toBe('plugin123____action456____type789');- });-it('should hash invalid api names so provider tool names stay valid', () => {const result = resolver.generate('mcp-server', 'get.current/weather', 'mcp');@@ -109,15 +103,6 @@ describe('ToolNameResolver', () => {expect(result).toMatch(/^[\w-]+$/);expect(result).not.toContain('get.current/weather');});-- it('should hash non-ASCII api names so provider tool names stay valid', () => {- const result = resolver.generate('custom_mcp_plugin', '中文API', 'mcp');-- expect(result).toMatch(/^custom_mcp_plugin____MD5HASH_[\da-f]+____mcp$/);- expect(result).toMatch(/^[\w-]+$/);- expect(result).not.toContain('中文API');- });-it('should hash invalid identifiers so provider tool names stay valid', () => {const result = resolver.generate('@browser/use', 'open_page', 'mcp');@@ -454,41 +439,6 @@ describe('ToolNameResolver', () => {type: 'mcp',});});-- it('should resolve non-ASCII apiName hashed for provider-safe tool names', () => {- const identifier = 'custom_mcp_plugin';- const apiName = '中文API';- const toolName = resolver.generate(identifier, apiName, 'mcp');-- const result = resolver.resolve(- [- {- function: {- arguments: '{"query":"最近工作压力好大"}',- name: toolName,- },- id: 'call_1',- type: 'function',- },- ],- {- [identifier]: {- api: [{ description: 'Chat with companion', name: apiName, parameters: {} }],- identifier,- meta: {},- type: 'mcp' as const,- },- },- );-- expect(result[0]).toEqual({- apiName,- arguments: '{"query":"最近工作压力好大"}',- id: 'call_1',- identifier,- type: 'mcp',- });- });});describe('resolve - hashed identifier', () => {diff --git a/packages/fetch-sse/src/__tests__/request.test.ts b/packages/fetch-sse/src/__tests__/request.test.tsindex fa563058c26..88af50bdd93 100644--- a/packages/fetch-sse/src/__tests__/request.test.ts+++ b/packages/fetch-sse/src/__tests__/request.test.ts@@ -11,22 +11,6 @@ describe('getRequestBody', () => {// Assertexpect(result).toBeUndefined();});-- it('should return undefined when body is null', async () => {- // Arrange & Act- const result = await getRequestBody(null);-- // Assert- expect(result).toBeUndefined();- });-- it('should return undefined when body is not provided', async () => {- // Arrange & Act- const result = await getRequestBody();-- // Assert- expect(result).toBeUndefined();- });});describe('string input', () => {@@ -53,41 +37,6 @@ describe('getRequestBody', () => {// Empty string is falsy, so the function returns undefinedexpect(result).toBeUndefined();});-- it('should handle JSON string', async () => {- // Arrange- const body = JSON.stringify({ key: 'value', number: 123 });-- // Act- const result = await getRequestBody(body);-- // Assert- expect(result).toBe('{"key":"value","number":123}');- expect(typeof result).toBe('string');- });-- it('should handle string with special characters', async () => {- // Arrange- const body = 'test\nstring\twith\rspecial\u0000chars';-- // Act- const result = await getRequestBody(body);-- // Assert- expect(result).toBe('test\nstring\twith\rspecial\u0000chars');- });-- it('should handle very long string', async () => {- // Arrange- const body = 'a'.repeat(10000);-- // Act- const result = await getRequestBody(body);-- // Assert- expect(result).toBe(body);- expect(typeof result).toBe('string');- });});describe('ArrayBuffer input', () => {@@ -106,31 +55,6 @@ describe('getRequestBody', () => {expect(result).toBeInstanceOf(ArrayBuffer);expect((result as ArrayBuffer).byteLength).toBe(8);});-- it('should handle empty ArrayBuffer', async () => {- // Arrange- const buffer = new ArrayBuffer(0);-- // Act- const result = await getRequestBody(buffer);-- // Assert- expect(result).toBe(buffer);- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(0);- });-- it('should handle large ArrayBuffer', async () => {- // Arrange- const buffer = new ArrayBuffer(1024 * 1024); // 1MB-- // Act- const result = await getRequestBody(buffer);-- // Assert- expect(result).toBe(buffer);- expect((result as ArrayBuffer).byteLength).toBe(1024 * 1024);- });});describe('ArrayBufferView input (TypedArrays)', () => {@@ -154,68 +78,6 @@ describe('getRequestBody', () => {expect(resultView[0]).toBe(65);expect(resultView[1]).toBe(66);});-- it('should convert Uint16Array to sliced ArrayBuffer', async () => {- // Arrange- const buffer = new ArrayBuffer(32);- const uint16View = new Uint16Array(buffer, 8, 4); // offset: 8 bytes, length: 4 elements- uint16View[0] = 256;- uint16View[1] = 512;-- // Act- const result = await getRequestBody(uint16View);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(8); // 4 elements * 2 bytes- expect(result).not.toBe(buffer);-- // Verify data- const resultView = new Uint16Array(result as ArrayBuffer);- expect(resultView[0]).toBe(256);- expect(resultView[1]).toBe(512);- });-- it('should convert Int32Array to sliced ArrayBuffer', async () => {- // Arrange- const buffer = new ArrayBuffer(64);- const int32View = new Int32Array(buffer, 16, 8); // offset: 16 bytes, length: 8 elements- int32View[0] = -12345;- int32View[7] = 67890;-- // Act- const result = await getRequestBody(int32View);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(32); // 8 elements * 4 bytes- expect(result).not.toBe(buffer);-- // Verify data- const resultView = new Int32Array(result as ArrayBuffer);- expect(resultView[0]).toBe(-12345);- expect(resultView[7]).toBe(67890);- });-- it('should convert Float32Array to sliced ArrayBuffer', async () => {- // Arrange- const buffer = new ArrayBuffer(40);- const float32View = new Float32Array(buffer, 4, 5);- float32View[0] = 3.14159;- float32View[4] = 2.71828;-- // Act- const result = await getRequestBody(float32View);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(20); // 5 elements * 4 bytes-- const resultView = new Float32Array(result as ArrayBuffer);- expect(resultView[0]).toBeCloseTo(3.14159);- expect(resultView[4]).toBeCloseTo(2.71828);- });-it('should convert DataView to sliced ArrayBuffer', async () => {// Arrangeconst buffer = new ArrayBuffer(24);@@ -234,36 +96,6 @@ describe('getRequestBody', () => {expect(resultView[0]).toBe(65);expect(resultView[1]).toBe(66);});-- it('should handle TypedArray with zero offset', async () => {- // Arrange- const buffer = new ArrayBuffer(16);- const uint8View = new Uint8Array(buffer, 0, 16);- uint8View[0] = 100;-- // Act- const result = await getRequestBody(uint8View);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(16);-- const resultView = new Uint8Array(result as ArrayBuffer);- expect(resultView[0]).toBe(100);- });-- it('should handle empty TypedArray', async () => {- // Arrange- const buffer = new ArrayBuffer(16);- const uint8View = new Uint8Array(buffer, 8, 0); // zero length-- // Act- const result = await getRequestBody(uint8View);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(0);- });});describe('Blob input', () => {@@ -283,35 +115,6 @@ describe('getRequestBody', () => {const text = decoder.decode(result as ArrayBuffer);expect(text).toBe('test blob content');});-- it('should convert Blob with binary data', async () => {- // Arrange- const uint8Array = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"- const blob = new Blob([uint8Array], { type: 'application/octet-stream' });-- // Act- const result = await getRequestBody(blob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);-- const decoder = new TextDecoder();- const text = decoder.decode(result as ArrayBuffer);- expect(text).toBe('Hello');- });-- it('should handle empty Blob', async () => {- // Arrange- const blob = new Blob([], { type: 'text/plain' });-- // Act- const result = await getRequestBody(blob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(0);- });-it('should convert File (subclass of Blob)', async () => {// Arrangeconst fileContent = 'file content';@@ -327,34 +130,6 @@ describe('getRequestBody', () => {const text = decoder.decode(result as ArrayBuffer);expect(text).toBe('file content');});-- it('should handle Blob with multiple chunks', async () => {- // Arrange- const blob = new Blob(['chunk1', 'chunk2', 'chunk3'], { type: 'text/plain' });-- // Act- const result = await getRequestBody(blob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);-- const decoder = new TextDecoder();- const text = decoder.decode(result as ArrayBuffer);- expect(text).toBe('chunk1chunk2chunk3');- });-- it('should handle large Blob', async () => {- // Arrange- const largeData = 'x'.repeat(100000);- const blob = new Blob([largeData], { type: 'text/plain' });-- // Act- const result = await getRequestBody(blob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- expect((result as ArrayBuffer).byteLength).toBe(100000);- });});describe('Unsupported types', () => {@@ -376,48 +151,6 @@ describe('getRequestBody', () => {// CleanupwarnSpy.mockRestore();});-- it('should throw error for URLSearchParams', async () => {- // Arrange- const params = new URLSearchParams({ key: 'value' });-- // Spy on console.warn- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Act & Assert- await expect(getRequestBody(params as any)).rejects.toThrow(- 'Unsupported IPC proxy request body type',- );-- expect(warnSpy).toHaveBeenCalledWith('Unsupported IPC proxy request body type:', 'object');-- // Cleanup- warnSpy.mockRestore();- });-- it('should throw error for ReadableStream', async () => {- // Arrange- const stream = new ReadableStream({- start(controller) {- controller.enqueue('test');- controller.close();- },- });-- // Spy on console.warn- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Act & Assert- await expect(getRequestBody(stream as any)).rejects.toThrow(- 'Unsupported IPC proxy request body type',- );-- expect(warnSpy).toHaveBeenCalledWith('Unsupported IPC proxy request body type:', 'object');-- // Cleanup- warnSpy.mockRestore();- });-it('should throw error for plain object', async () => {// Arrangeconst obj = { key: 'value' };@@ -435,42 +168,6 @@ describe('getRequestBody', () => {// CleanupwarnSpy.mockRestore();});-- it('should throw error for number', async () => {- // Arrange- const num = 123;-- // Spy on console.warn- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Act & Assert- await expect(getRequestBody(num as any)).rejects.toThrow(- 'Unsupported IPC proxy request body type',- );-- expect(warnSpy).toHaveBeenCalledWith('Unsupported IPC proxy request body type:', 'number');-- // Cleanup- warnSpy.mockRestore();- });-- it('should throw error for boolean', async () => {- // Arrange- const bool = true;-- // Spy on console.warn- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Act & Assert- await expect(getRequestBody(bool as any)).rejects.toThrow(- 'Unsupported IPC proxy request body type',- );-- expect(warnSpy).toHaveBeenCalledWith('Unsupported IPC proxy request body type:', 'boolean');-- // Cleanup- warnSpy.mockRestore();- });});describe('Edge cases', () => {@@ -492,51 +189,6 @@ describe('getRequestBody', () => {const resultView = new Uint8Array(result as ArrayBuffer);expect(resultView.every((byte) => byte === 42)).toBe(true);});-- it('should preserve binary data integrity through TypedArray conversion', async () => {- // Arrange- const buffer = new ArrayBuffer(8);- const view = new Uint8Array(buffer);- // Set specific binary pattern- view[0] = 0xFF;- view[1] = 0x00;- view[2] = 0xAA;- view[3] = 0x55;- view[4] = 0x12;- view[5] = 0x34;- view[6] = 0x56;- view[7] = 0x78;-- // Act- const result = await getRequestBody(view);-- // Assert- const resultView = new Uint8Array(result as ArrayBuffer);- expect(resultView[0]).toBe(0xFF);- expect(resultView[1]).toBe(0x00);- expect(resultView[2]).toBe(0xAA);- expect(resultView[3]).toBe(0x55);- expect(resultView[4]).toBe(0x12);- expect(resultView[5]).toBe(0x34);- expect(resultView[6]).toBe(0x56);- expect(resultView[7]).toBe(0x78);- });-- it('should handle Blob with non-ASCII characters', async () => {- // Arrange- const unicodeText = 'Hello 世界 🌍 مرحبا';- const blob = new Blob([unicodeText], { type: 'text/plain;charset=utf-8' });-- // Act- const result = await getRequestBody(blob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);-- const decoder = new TextDecoder('utf-8');- const text = decoder.decode(result as ArrayBuffer);- expect(text).toBe('Hello 世界 🌍 مرحبا');- });});describe('Real-world scenarios', () => {@@ -555,48 +207,6 @@ describe('getRequestBody', () => {expect(typeof result).toBe('string');expect(result).toBe(apiPayload);});-- it('should handle file upload as Blob', async () => {- // Arrange- const imageData = new Uint8Array([- 0x89,- 0x50,- 0x4E,- 0x47,- 0x0D,- 0x0A,- 0x1A,- 0x0A, // PNG header- ]);- const imageBlob = new Blob([imageData], { type: 'image/png' });-- // Act- const result = await getRequestBody(imageBlob);-- // Assert- expect(result).toBeInstanceOf(ArrayBuffer);- const resultView = new Uint8Array(result as ArrayBuffer);- expect(resultView[0]).toBe(0x89);- expect(resultView[1]).toBe(0x50);- expect(resultView[2]).toBe(0x4E);- expect(resultView[3]).toBe(0x47);- });-- it('should handle binary protocol buffer data', async () => {- // Arrange- const protobufData = new Uint8Array([- 0x08, 0x96, 0x01, 0x12, 0x05, 0x48, 0x65, 0x6C, 0x6C, 0x6F,- ]);- const buffer = protobufData.buffer;-- // Act- const result = await getRequestBody(buffer);-- // Assert- expect(result).toBe(buffer);- expect(result).toBeInstanceOf(ArrayBuffer);- });-it('should handle empty request (no body)', async () => {// Arrange & Actconst result = await getRequestBody();diff --git a/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/base.test.tsindex ca211018415..9e94ba0a998 100644--- a/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts+++ b/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts@@ -90,37 +90,6 @@ describe('BaseFileSearch', () => {expect(fileSearch.testDetermineContentType('tar')).toBe('archive');expect(fileSearch.testDetermineContentType('gz')).toBe('archive');});-- it('should return audio for audio extensions', () => {- expect(fileSearch.testDetermineContentType('mp3')).toBe('audio');- expect(fileSearch.testDetermineContentType('wav')).toBe('audio');- expect(fileSearch.testDetermineContentType('ogg')).toBe('audio');- });-- it('should return video for video extensions', () => {- expect(fileSearch.testDetermineContentType('mp4')).toBe('video');- expect(fileSearch.testDetermineContentType('avi')).toBe('video');- expect(fileSearch.testDetermineContentType('mkv')).toBe('video');- });-- it('should return image for image extensions', () => {- expect(fileSearch.testDetermineContentType('png')).toBe('image');- expect(fileSearch.testDetermineContentType('jpg')).toBe('image');- expect(fileSearch.testDetermineContentType('gif')).toBe('image');- });-- it('should return document for document extensions', () => {- expect(fileSearch.testDetermineContentType('pdf')).toBe('document');- expect(fileSearch.testDetermineContentType('doc')).toBe('document');- expect(fileSearch.testDetermineContentType('docx')).toBe('document');- });-- it('should return code for code extensions', () => {- expect(fileSearch.testDetermineContentType('ts')).toBe('code');- expect(fileSearch.testDetermineContentType('js')).toBe('code');- expect(fileSearch.testDetermineContentType('py')).toBe('code');- });-it('should return unknown for unrecognized extensions', () => {expect(fileSearch.testDetermineContentType('xyz')).toBe('unknown');expect(fileSearch.testDetermineContentType('foo')).toBe('unknown');@@ -152,10 +121,6 @@ describe('BaseFileSearch', () => {expect(fileSearch.testEscapeGlobPattern('path\\file.ts')).toBe('path\\\\file\\.ts');});- it('should escape dots', () => {- expect(fileSearch.testEscapeGlobPattern('normal-file.ts')).toBe('normal-file\\.ts');- });-it('should return unchanged string if no special characters', () => {expect(fileSearch.testEscapeGlobPattern('normal-file-ts')).toBe('normal-file-ts');});diff --git a/packages/local-file-shell/src/shell/__tests__/utils.test.ts b/packages/local-file-shell/src/shell/__tests__/utils.test.tsindex ba32274625b..92f838e263b 100644--- a/packages/local-file-shell/src/shell/__tests__/utils.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/utils.test.ts@@ -83,14 +83,6 @@ describe('getShellConfig', () => {expect(config.cmd).toBe('/bin/sh');expect(config.args).toEqual(['-c', 'echo hello']);});-- it('should keep /bin/sh -c behavior on linux', async () => {- setPlatform('linux');- const config = await getShellConfig('ls -la');- expect(config.cmd).toBe('/bin/sh');- expect(config.args).toEqual(['-c', 'ls -la']);- });-it('should use pwsh with -EncodedCommand when pwsh.exe is on PATH', async () => {setPlatform('win32');// NB: use a delimiter-safe fake dir. On the CI/dev host the default `path`diff --git a/packages/model-runtime/src/providers/ai360/index.test.ts b/packages/model-runtime/src/providers/ai360/index.test.tsindex d283657ca05..54a6a53ec99 100644--- a/packages/model-runtime/src/providers/ai360/index.test.ts+++ b/packages/model-runtime/src/providers/ai360/index.test.ts@@ -1,5 +1,4 @@// @vitest-environment node-import { ModelProvider } from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LobeAi360AI, params } from './index';@@ -280,49 +279,6 @@ describe('LobeAi360AI - custom features', () => {expect(model.functionCall).toBe(true);});-- it('should detect reasoning models with 360gpt2-o1 keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [- {- id: '360gpt2-o1',- max_tokens: 8192,- total_tokens: 16384,- },- ],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- const model = models[0];-- expect(model.reasoning).toBe(true);- });-- it('should detect reasoning models with 360zhinao2-o1 keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [- {- id: '360zhinao2-o1-preview',- max_tokens: 8192,- total_tokens: 16384,- },- ],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- const model = models[0];-- expect(model.reasoning).toBe(true);- });-it('should handle case-insensitive reasoning keyword matching', async () => {const mockClient = {models: {@@ -413,28 +369,6 @@ describe('LobeAi360AI - custom features', () => {expect(typeof model.vision).toBe('boolean');expect(typeof model.reasoning).toBe('boolean');});-- it('should handle models with non-number max_tokens', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [- {- id: 'test-model',- max_tokens: 'unlimited' as any,- total_tokens: 8192,- },- ],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- const model = models[0];-- expect(model.maxOutput).toBeUndefined();- });-it('should handle models with null max_tokens', async () => {const mockClient = {models: {@@ -676,29 +610,6 @@ describe('LobeAi360AI - custom features', () => {expect(model.contextWindowTokens).toBe(0);expect(model.maxOutput).toBe(0);});-- it('should handle very large context window values', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [- {- id: 'large-context-model',- max_tokens: 128000,- total_tokens: 1000000,- },- ],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- const model = models[0];-- expect(model.contextWindowTokens).toBe(1000000);- expect(model.maxOutput).toBe(128000);- });-it('should handle models with special characters in ID', async () => {const mockClient = {models: {@@ -719,29 +630,6 @@ describe('LobeAi360AI - custom features', () => {expect(model.id).toBe('360gpt-pro-v2.0-beta');});-- it('should detect 360gpt-pro as functionCall capable', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [- {- id: '360gpt-pro',- max_tokens: 4096,- total_tokens: 8192,- },- ],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- const model = models[0];-- expect(model.id).toBe('360gpt-pro');- expect(model.functionCall).toBe(true);- });-it('should prioritize reasoning from keyword over knownModel', async () => {const mockClient = {models: {@@ -867,45 +755,6 @@ describe('LobeAi360AI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.temperature).toBe(0.7);});-- it('should preserve top_p without modification', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- top_p: 0.9,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.top_p).toBe(0.9);- });-- it('should preserve max_tokens without modification', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- max_tokens: 1024,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.max_tokens).toBe(1024);- });-- it('should preserve messages as-is', async () => {- const messages = [- { content: 'Hello', role: 'user' as const },- { content: 'Hi there!', role: 'assistant' as const },- { content: 'How are you?', role: 'user' as const },- ];-- await instance.chat({- messages,- model: '360gpt-pro',- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.messages).toEqual(messages);- });-it('should preserve model name', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -946,12 +795,6 @@ describe('LobeAi360AI - custom features', () => {});describe('exports', () => {- it('should export params object', () => {- expect(params).toBeDefined();- expect(params.provider).toBe(ModelProvider.Ai360);- expect(params.baseURL).toBe('https://api.360.cn/v1');- });-it('should export LobeAi360AI class', () => {expect(LobeAi360AI).toBeDefined();expect(typeof LobeAi360AI).toBe('function');@@ -964,23 +807,6 @@ describe('LobeAi360AI - custom features', () => {expect(params).toHaveProperty('debug');expect(params).toHaveProperty('models');});-- it('should have chatCompletion.handlePayload function', () => {- expect(params.chatCompletion).toBeDefined();- expect(params.chatCompletion.handlePayload).toBeDefined();- expect(typeof params.chatCompletion.handlePayload).toBe('function');- });-- it('should have debug.chatCompletion function', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('edge cases and comprehensive coverage', () => {@@ -994,18 +820,6 @@ describe('LobeAi360AI - custom features', () => {const result = params.chatCompletion.handlePayload!(payload);expect(result.tools).toBeUndefined();});-- it('should handle payload with null tools', () => {- const payload = {- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- tools: null as any,- } as any;-- const result = params.chatCompletion.handlePayload!(payload);- expect(result.tools).toBeNull();- });-it('should handle empty messages array', async () => {await instance.chat({messages: [],@@ -1015,196 +829,5 @@ describe('LobeAi360AI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.messages).toEqual([]);});-- it('should handle very small temperature values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 0.01,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(0.01);- });-- it('should handle temperature of 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 0,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(0);- });-- it('should handle temperature of 1', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 1,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(1);- });-- it('should handle high temperature values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 2,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(2);- });-- it('should handle top_p of 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- top_p: 0,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.top_p).toBe(0);- });-- it('should handle top_p of 1', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- top_p: 1,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.top_p).toBe(1);- });-- it('should handle very small top_p values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- top_p: 0.01,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.top_p).toBe(0.01);- });-- it('should handle large max_tokens values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- max_tokens: 100000,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.max_tokens).toBe(100000);- });-- it('should handle complex message history with multiple roles', async () => {- const messages = [- { content: 'You are a helpful assistant', role: 'system' as const },- { content: 'Hello', role: 'user' as const },- { content: 'Hi! How can I help?', role: 'assistant' as const },- { content: 'What is 2+2?', role: 'user' as const },- { content: '2+2 equals 4', role: 'assistant' as const },- { content: 'Thanks', role: 'user' as const },- ];-- await instance.chat({- messages,- model: '360gpt-pro',- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.messages).toEqual(messages);- });-- it('should handle combined parameters with web search', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 0.8,- top_p: 0.85,- max_tokens: 2048,- enabledSearch: true,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(0.8);- expect(calledPayload.top_p).toBe(0.85);- expect(calledPayload.max_tokens).toBe(2048);- expect(calledPayload.stream).toBe(false);- expect(calledPayload.tools?.some((tool: any) => tool.type === 'web_search')).toBe(true);- });-- it('should handle combined parameters with tools and no web search', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- temperature: 0.9,- top_p: 0.95,- max_tokens: 4096,- tools: [{ type: 'function', function: { name: 'test_tool' } }],- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.temperature).toBe(0.9);- expect(calledPayload.top_p).toBe(0.95);- expect(calledPayload.max_tokens).toBe(4096);- expect(calledPayload.stream).toBe(false);- expect(calledPayload.tools).toHaveLength(1);- });-- it('should preserve all model parameters', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360zhinao2-o1-preview',- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.model).toBe('360zhinao2-o1-preview');- });-- it('should handle multiple function tools', async () => {- const tools = [- { type: 'function' as const, function: { name: 'tool1', description: 'First tool' } },- { type: 'function' as const, function: { name: 'tool2', description: 'Second tool' } },- { type: 'function' as const, function: { name: 'tool3', description: 'Third tool' } },- ];-- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- tools,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.tools).toHaveLength(3);- expect(calledPayload.stream).toBe(false);- });-- it('should handle enabledSearch with multiple function tools', async () => {- const tools = [- { type: 'function' as const, function: { name: 'tool1', description: 'First tool' } },- { type: 'function' as const, function: { name: 'tool2', description: 'Second tool' } },- ];-- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: '360gpt-pro',- enabledSearch: true,- tools,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.tools).toHaveLength(3);- expect(calledPayload.tools?.filter((t: any) => t.type === 'function')).toHaveLength(2);- expect(calledPayload.tools?.filter((t: any) => t.type === 'web_search')).toHaveLength(1);- expect(calledPayload.stream).toBe(false);- });});});diff --git a/packages/model-runtime/src/providers/akashchat/index.test.ts b/packages/model-runtime/src/providers/akashchat/index.test.tsindex 3ed0cff8ada..fc30eb0a1ec 100644--- a/packages/model-runtime/src/providers/akashchat/index.test.ts+++ b/packages/model-runtime/src/providers/akashchat/index.test.ts@@ -219,17 +219,6 @@ describe('LobeAkashChatAI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.chat_template_kwargs).toBeUndefined();});-- it('should handle multiple thinking model keywords', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'DeepSeek-V3-1',- thinking: { type: 'enabled', budget_tokens: 1024 },- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.chat_template_kwargs).toEqual({ thinking: true });- });});});@@ -300,19 +289,6 @@ describe('LobeAkashChatAI - custom features', () => {expect(models).toEqual([]);});-- it('should throw when model API fails', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://chatapi.akash.network/api/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('API Error')),- },- };-- await expect(params.models({ client: mockClient as any })).rejects.toThrow('API Error');- });-it('should handle network timeout errors', async () => {const mockClient = {apiKey: 'test',@@ -324,19 +300,6 @@ describe('LobeAkashChatAI - custom features', () => {await expect(params.models({ client: mockClient as any })).rejects.toThrow('Network timeout');});-- it('should handle invalid API key errors', async () => {- const mockClient = {- apiKey: 'invalid',- baseURL: 'https://chatapi.akash.network/api/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Unauthorized')),- },- };-- await expect(params.models({ client: mockClient as any })).rejects.toThrow('Unauthorized');- });-it('should throw on malformed response data', async () => {const mockClient = {apiKey: 'test',diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.tsindex 4b18a61c61a..ca1fbdaa264 100644--- a/packages/model-runtime/src/providers/bedrock/index.test.ts+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts@@ -91,7 +91,6 @@ describe('LobeBedrockAI', () => {token: 'test-bedrock-api-key',});});-it('should throw InvalidBedrockCredentials if accessKeyId is missing', () => {expect(() => {new LobeBedrockAI({diff --git a/packages/model-runtime/src/providers/cerebras/index.test.ts b/packages/model-runtime/src/providers/cerebras/index.test.tsindex 3524ff3eeea..8c3e9f9a016 100644--- a/packages/model-runtime/src/providers/cerebras/index.test.ts+++ b/packages/model-runtime/src/providers/cerebras/index.test.ts@@ -28,22 +28,6 @@ describe('LobeCerebrasAI - custom features', () => {it('should export params with correct provider', () => {expect(params.provider).toBe(ModelProvider.Cerebras);});-- it('should have chatCompletion handlePayload function', () => {- expect(params.chatCompletion?.handlePayload).toBeDefined();- expect(typeof params.chatCompletion?.handlePayload).toBe('function');- });-- it('should have debug configuration', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('debug configuration', () => {@@ -64,12 +48,6 @@ describe('LobeCerebrasAI - custom features', () => {const result = params.debug.chatCompletion();expect(result).toBe(false);});-- it('should disable debug when env is empty string', () => {- process.env.DEBUG_CEREBRAS_CHAT_COMPLETION = '';- const result = params.debug.chatCompletion();- expect(result).toBe(false);- });});describe('handlePayload', () => {@@ -133,63 +111,6 @@ describe('LobeCerebrasAI - custom features', () => {expect(calledPayload.frequency_penalty).toBeUndefined();expect(calledPayload.presence_penalty).toBeUndefined();});-- it('should handle payload with only frequency_penalty', async () => {- await instance.chat({- frequency_penalty: 0.5,- messages: [{ content: 'Test', role: 'user' }],- model: 'llama3.1-8b',- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.frequency_penalty).toBeUndefined();- expect(calledPayload.presence_penalty).toBeUndefined();- });-- it('should handle payload with only presence_penalty', async () => {- await instance.chat({- messages: [{ content: 'Test', role: 'user' }],- model: 'llama3.1-8b',- presence_penalty: 0.5,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.frequency_penalty).toBeUndefined();- expect(calledPayload.presence_penalty).toBeUndefined();- });-- it('should handle payload with zero values for penalties', async () => {- await instance.chat({- frequency_penalty: 0,- messages: [{ content: 'Test', role: 'user' }],- model: 'llama3.1-8b',- presence_penalty: 0,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.frequency_penalty).toBeUndefined();- expect(calledPayload.presence_penalty).toBeUndefined();- });-- it('should call handlePayload directly and verify transformation', () => {- const payload = {- frequency_penalty: 0.5,- max_tokens: 100,- messages: [{ content: 'Test', role: 'user' }],- model: 'llama3.1-8b',- presence_penalty: 0.5,- temperature: 0.7,- };-- const transformedPayload = params.chatCompletion!.handlePayload!(payload as any);-- expect(transformedPayload.model).toBe('llama3.1-8b');- expect(transformedPayload.temperature).toBe(0.7);- expect(transformedPayload.max_tokens).toBe(100);- expect(transformedPayload.frequency_penalty).toBeUndefined();- expect(transformedPayload.presence_penalty).toBeUndefined();- });-describe('reasoning configuration', () => {it('should handle Z.ai GLM 4.7 default reasoning settings (reasoning_format: parsed)', async () => {await instance.chat({@@ -367,24 +288,6 @@ describe('LobeCerebrasAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle empty models list without data property', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.cerebras.ai/v1',- models: {- list: vi.fn().mockResolvedValue([]),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle null response', async () => {const mockClient = {apiKey: 'test_api_key',@@ -401,24 +304,6 @@ describe('LobeCerebrasAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle undefined response', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.cerebras.ai/v1',- models: {- list: vi.fn().mockResolvedValue(undefined),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle response with non-array data', async () => {const mockClient = {apiKey: 'test_api_key',@@ -451,49 +336,6 @@ describe('LobeCerebrasAI - custom features', () => {expect(mockClient.models.list).toHaveBeenCalledTimes(1);});-- it('should throw when API authentication fails', async () => {- const mockClient = {- apiKey: 'invalid_key',- baseURL: 'https://api.cerebras.ai/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('401 Unauthorized')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('401 Unauthorized');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when API rate limit fails', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.cerebras.ai/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('429 Too Many Requests')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('429 Too Many Requests');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when request times out', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.cerebras.ai/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Request timeout')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('Request timeout');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-it('should handle malformed JSON response', async () => {const mockClient = {apiKey: 'test_api_key',diff --git a/packages/model-runtime/src/providers/cohere/index.test.ts b/packages/model-runtime/src/providers/cohere/index.test.tsindex 29c4c2bc99e..af88319fdbf 100644--- a/packages/model-runtime/src/providers/cohere/index.test.ts+++ b/packages/model-runtime/src/providers/cohere/index.test.ts@@ -53,20 +53,6 @@ describe('LobeCohereAI - custom features', () => {expect.anything(),);});-- it('should clamp frequency_penalty negative values to 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- frequency_penalty: -0.5,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ frequency_penalty: 0 }),- expect.anything(),- );- });-it('should clamp presence_penalty to [0, 1] range', async () => {// Test upper boundawait instance.chat({@@ -80,20 +66,6 @@ describe('LobeCohereAI - custom features', () => {expect.anything(),);});-- it('should clamp presence_penalty negative values to 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- presence_penalty: -0.3,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ presence_penalty: 0 }),- expect.anything(),- );- });-it('should clamp top_p to [0, 1] range', async () => {// Test upper boundawait instance.chat({@@ -107,59 +79,6 @@ describe('LobeCohereAI - custom features', () => {expect.anything(),);});-- it('should clamp top_p negative values to 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- top_p: -0.1,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ top_p: 0 }),- expect.anything(),- );- });-- it('should accept valid frequency_penalty values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- frequency_penalty: 0.5,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ frequency_penalty: 0.5 }),- expect.anything(),- );- });-- it('should accept valid presence_penalty values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- presence_penalty: 0.7,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ presence_penalty: 0.7 }),- expect.anything(),- );- });-- it('should accept valid top_p values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- top_p: 0.9,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({ top_p: 0.9 }),- expect.anything(),- );- });-it('should handle all penalty parameters together', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -244,44 +163,6 @@ describe('LobeCohereAI - custom features', () => {expect(callArgs).not.toHaveProperty('presence_penalty');expect(callArgs).not.toHaveProperty('top_p');});-- it('should handle edge case: all penalties at maximum', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- frequency_penalty: 2,- presence_penalty: 2,- top_p: 2,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- frequency_penalty: 1,- presence_penalty: 1,- top_p: 1,- }),- expect.anything(),- );- });-- it('should handle edge case: all penalties at minimum', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'command-r7b',- frequency_penalty: -1,- presence_penalty: -1,- top_p: -1,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- frequency_penalty: 0,- presence_penalty: 0,- top_p: 0,- }),- expect.anything(),- );- });});describe('handlePayload - excludeUsage and noUserId', () => {@@ -640,13 +521,6 @@ describe('LobeCohereAI - custom features', () => {await expect(params.models({ client: mockClient as any })).rejects.toThrow('API Error');});-- it('should handle network timeout errors', async () => {- mockClient.models.list.mockRejectedValue(new Error('Network timeout'));-- await expect(params.models({ client: mockClient as any })).rejects.toThrow('Network timeout');- });-it('should handle invalid API response structure', async () => {mockClient.models.list.mockResolvedValue({body: {diff --git a/packages/model-runtime/src/providers/giteeai/index.test.ts b/packages/model-runtime/src/providers/giteeai/index.test.tsindex 25cc5b35767..1eaa471305b 100644--- a/packages/model-runtime/src/providers/giteeai/index.test.ts+++ b/packages/model-runtime/src/providers/giteeai/index.test.ts@@ -28,17 +28,6 @@ describe('LobeGiteeAI - custom features', () => {it('should export params with correct provider', () => {expect(params.provider).toBe(ModelProvider.GiteeAI);});-- it('should have debug configuration', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('debug configuration', () => {@@ -59,12 +48,6 @@ describe('LobeGiteeAI - custom features', () => {const result = params.debug.chatCompletion();expect(result).toBe(false);});-- it('should disable debug when env is empty string', () => {- process.env.DEBUG_GITEE_AI_CHAT_COMPLETION = '';- const result = params.debug.chatCompletion();- expect(result).toBe(false);- });});describe('models function', () => {@@ -126,24 +109,6 @@ describe('LobeGiteeAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle empty models list without data property', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://ai.gitee.com/v1',- models: {- list: vi.fn().mockResolvedValue([]),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle null response', async () => {const mockClient = {apiKey: 'test_api_key',@@ -160,24 +125,6 @@ describe('LobeGiteeAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle undefined response', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://ai.gitee.com/v1',- models: {- list: vi.fn().mockResolvedValue(undefined),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle response with non-array data', async () => {const mockClient = {apiKey: 'test_api_key',@@ -210,49 +157,6 @@ describe('LobeGiteeAI - custom features', () => {expect(mockClient.models.list).toHaveBeenCalledTimes(1);});-- it('should throw when API authentication fails', async () => {- const mockClient = {- apiKey: 'invalid_key',- baseURL: 'https://ai.gitee.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('401 Unauthorized')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('401 Unauthorized');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when API rate limit fails', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://ai.gitee.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('429 Too Many Requests')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('429 Too Many Requests');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when request times out', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://ai.gitee.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Request timeout')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('Request timeout');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-it('should handle malformed JSON response', async () => {const mockClient = {apiKey: 'test_api_key',diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.tsindex 58a8b74b340..a1fc60c6d92 100644--- a/packages/model-runtime/src/providers/moonshot/index.test.ts+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts@@ -314,29 +314,6 @@ describe('LobeMoonshotOpenAI', () => {const payload = getLastRequestPayload();expect(payload.temperature).toBe(0.4);});-- it('should normalize temperature to 0.5 when temperature is 1', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'moonshot-v1-8k',- temperature: 1,- });-- const payload = getLastRequestPayload();- expect(payload.temperature).toBe(0.5);- });-- it('should normalize temperature to 0 when temperature is 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'moonshot-v1-8k',- temperature: 0,- });-- const payload = getLastRequestPayload();- expect(payload.temperature).toBe(0);- });-it('should handle kimi-k2.5 model with thinking enabled by default', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -364,35 +341,6 @@ describe('LobeMoonshotOpenAI', () => {expect(payload.temperature).toBe(0.6);expect(payload.thinking).toEqual({ type: 'disabled' });});-- it('should handle kimi-k2.6 model with thinking enabled by default', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'kimi-k2.6',- temperature: 0.5,- top_p: 0.8,- });-- const payload = getLastRequestPayload();- expect(payload.temperature).toBe(1);- expect(payload.top_p).toBe(0.95);- expect(payload.frequency_penalty).toBe(0);- expect(payload.presence_penalty).toBe(0);- expect(payload.thinking).toEqual({ type: 'enabled' });- });-- it('should handle kimi-k2.6 model with thinking disabled', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'kimi-k2.6',- thinking: { budget_tokens: 0, type: 'disabled' },- });-- const payload = getLastRequestPayload();- expect(payload.temperature).toBe(0.6);- expect(payload.thinking).toEqual({ type: 'disabled' });- });-it('should handle kimi-k2.6 model with preserveThinking enabled', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -508,22 +456,6 @@ describe('LobeMoonshotOpenAI', () => {expect(payload.thinking).toEqual({ type: 'enabled' });expect(payload.temperature).toBe(1);});-- it('should always enable thinking for kimi-k2.7-code', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'kimi-k2.7-code',- temperature: 0.5,- });-- const payload = getLastRequestPayload();- expect(payload.thinking).toEqual({ type: 'enabled' });- expect(payload.temperature).toBe(1);- expect(payload.top_p).toBe(0.95);- expect(payload.frequency_penalty).toBe(0);- expect(payload.presence_penalty).toBe(0);- });-it('should ignore thinking disabled for native thinking models', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],diff --git a/packages/model-runtime/src/providers/nebius/index.test.ts b/packages/model-runtime/src/providers/nebius/index.test.tsindex 0e858cd73e1..59362cb6fae 100644--- a/packages/model-runtime/src/providers/nebius/index.test.ts+++ b/packages/model-runtime/src/providers/nebius/index.test.ts@@ -23,11 +23,6 @@ describe('LobeNebiusAI - custom features', () => {expect(params.chatCompletion).toBeDefined();expect(params.models).toBeDefined();});-- it('should have debug.chatCompletion function', () => {- expect(typeof params.debug?.chatCompletion).toBe('function');- });-it('should return false when DEBUG_NEBIUS_CHAT_COMPLETION is not set', () => {delete process.env.DEBUG_NEBIUS_CHAT_COMPLETION;expect(params.debug?.chatCompletion()).toBe(false);@@ -76,60 +71,6 @@ describe('LobeNebiusAI - custom features', () => {});});- describe('modality inference logic', () => {- it('should infer image type from modality', () => {- const modality = 'text -> image';- const parts = modality.split('->');- const right = parts[1]?.trim().toLowerCase();- expect(right).toBe('image');- });-- it('should infer embedding type from modality', () => {- const modality = 'text -> embedding';- const parts = modality.split('->');- const right = parts[1]?.trim().toLowerCase();- expect(right).toBe('embedding');- });-- it('should handle modality without ->', () => {- const modality = 'text';- const hasArrow = modality.includes('->');- expect(hasArrow).toBe(false);- });- });-- describe('pricing calculation', () => {- it('should convert pricing to per million tokens', () => {- const pricing = {- completion: 0.002,- prompt: 0.001,- };- const result = {- input: pricing.prompt * 1_000_000,- output: pricing.completion * 1_000_000,- };- expect(result.input).toBe(1000);- expect(result.output).toBe(2000);- });- });-- describe('features detection', () => {- it('should detect function-calling feature', () => {- const features = ['function-calling', 'vision'];- expect(features.includes('function-calling')).toBe(true);- });-- it('should detect reasoning feature', () => {- const features = ['reasoning', 'vision'];- expect(features.includes('reasoning')).toBe(true);- });-- it('should detect vision feature', () => {- const features = ['function-calling', 'vision'];- expect(features.includes('vision')).toBe(true);- });- });-describe('models function', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/model-runtime/src/providers/newapi/index.test.ts b/packages/model-runtime/src/providers/newapi/index.test.tsindex 25a40b2d3c0..7be4b53c663 100644--- a/packages/model-runtime/src/providers/newapi/index.test.ts+++ b/packages/model-runtime/src/providers/newapi/index.test.ts@@ -3,9 +3,7 @@ import { ModelProvider } from 'model-bank';import type { Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ChatStreamPayload } from '../../types/chat';import * as modelParseModule from '../../utils/modelParse';-import type { NewAPIModelCard, NewAPIPricing } from './index';import { LobeNewAPIAI, params } from './index';// Mock external dependencies@@ -14,12 +12,6 @@ vi.mock('../../utils/modelParse');// Mock console methodsvi.spyOn(console, 'error').mockImplementation(() => {});-// Type definitions for test data-interface MockPricingResponse {- data?: NewAPIPricing[];- success?: boolean;-}-describe('NewAPI Runtime - 100% Branch Coverage', () => {let mockFetch: Mock;let mockProcessMultiProviderModelList: Mock;@@ -43,610 +35,6 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {delete process.env.DEBUG_NEWAPI_CHAT_COMPLETION;});- describe('Debug Configuration Branch Coverage', () => {- it('should return false when DEBUG_NEWAPI_CHAT_COMPLETION is not set (Branch: debug = false)', () => {- delete process.env.DEBUG_NEWAPI_CHAT_COMPLETION;- const debugResult = process.env.DEBUG_NEWAPI_CHAT_COMPLETION === '1';- expect(debugResult).toBe(false);- });-- it('should return true when DEBUG_NEWAPI_CHAT_COMPLETION is set to 1 (Branch: debug = true)', () => {- process.env.DEBUG_NEWAPI_CHAT_COMPLETION = '1';- const debugResult = process.env.DEBUG_NEWAPI_CHAT_COMPLETION === '1';- expect(debugResult).toBe(true);- });- });-- describe('HandlePayload Function Branch Coverage - Direct Testing', () => {- // Create a mock Set for testing- let testResponsesAPIModels: Set<string>;-- const testHandlePayload = (payload: ChatStreamPayload) => {- // This replicates the exact handlePayload logic from the source- if (- testResponsesAPIModels.has(payload.model) ||- payload.model.includes('gpt-') ||- /^o\d/.test(payload.model)- ) {- return { ...payload, apiMode: 'responses' } as any;- }- return payload as any;- };-- it('should add apiMode for models in responsesAPIModels set (Branch A: responsesAPIModels.has = true)', () => {- testResponsesAPIModels = new Set(['o1-pro']);-- const payload: ChatStreamPayload = {- messages: [{ content: 'test', role: 'user' }],- model: 'o1-pro',- temperature: 0.5,- };-- const result = testHandlePayload(payload);-- expect(result).toEqual({ ...payload, apiMode: 'responses' });- });-- it('should add apiMode for gpt- models (Branch B: includes gpt- = true)', () => {- testResponsesAPIModels = new Set(); // Empty set to test gpt- logic-- const payload: ChatStreamPayload = {- messages: [{ content: 'test', role: 'user' }],- model: 'gpt-4o',- temperature: 0.5,- };-- const result = testHandlePayload(payload);-- expect(result).toEqual({ ...payload, apiMode: 'responses' });- });-- it('should add apiMode for o-series models (Branch C: /^o\\d/.test = true)', () => {- testResponsesAPIModels = new Set(); // Empty set to test o-series logic-- const payload: ChatStreamPayload = {- messages: [{ content: 'test', role: 'user' }],- model: 'o1-mini',- temperature: 0.5,- };-- const result = testHandlePayload(payload);-- expect(result).toEqual({ ...payload, apiMode: 'responses' });- });-- it('should add apiMode for o3 models (Branch C: /^o\\d/.test = true)', () => {- testResponsesAPIModels = new Set(); // Empty set to test o3 logic-- const payload: ChatStreamPayload = {- messages: [{ content: 'test', role: 'user' }],- model: 'o3-turbo',- temperature: 0.5,- };-- const result = testHandlePayload(payload);-- expect(result).toEqual({ ...payload, apiMode: 'responses' });- });-- it('should not modify payload for regular models (Branch D: all conditions false)', () => {- testResponsesAPIModels = new Set(); // Empty set to test fallback logic-- const payload: ChatStreamPayload = {- messages: [{ content: 'test', role: 'user' }],- model: 'claude-3-sonnet',- temperature: 0.5,- };-- const result = testHandlePayload(payload);-- expect(result).toEqual(payload);- });- });-- describe('GetProviderFromOwnedBy Function Branch Coverage - Direct Testing', () => {- // Test the getProviderFromOwnedBy function directly by extracting its logic- const testGetProviderFromOwnedBy = (ownedBy: string): string => {- const normalizedOwnedBy = ownedBy.toLowerCase();-- if (normalizedOwnedBy.includes('anthropic') || normalizedOwnedBy.includes('claude')) {- return 'anthropic';- }- if (normalizedOwnedBy.includes('google') || normalizedOwnedBy.includes('gemini')) {- return 'google';- }- if (normalizedOwnedBy.includes('xai') || normalizedOwnedBy.includes('grok')) {- return 'xai';- }-- return 'openai';- };-- it('should detect anthropic from anthropic string (Branch 1: includes anthropic = true)', () => {- const result = testGetProviderFromOwnedBy('Anthropic Inc.');- expect(result).toBe('anthropic');- });-- it('should detect anthropic from claude string (Branch 2: includes claude = true)', () => {- const result = testGetProviderFromOwnedBy('claude-team');- expect(result).toBe('anthropic');- });-- it('should detect google from google string (Branch 3: includes google = true)', () => {- const result = testGetProviderFromOwnedBy('Google LLC');- expect(result).toBe('google');- });-- it('should detect google from gemini string (Branch 4: includes gemini = true)', () => {- const result = testGetProviderFromOwnedBy('gemini-pro-team');- expect(result).toBe('google');- });-- it('should detect xai from xai string (Branch 5: includes xai = true)', () => {- const result = testGetProviderFromOwnedBy('xAI Corporation');- expect(result).toBe('xai');- });-- it('should detect xai from grok string (Branch 6: includes grok = true)', () => {- const result = testGetProviderFromOwnedBy('grok-beta');- expect(result).toBe('xai');- });-- it('should default to openai for unknown provider (Branch 7: default case)', () => {- const result = testGetProviderFromOwnedBy('unknown-company');- expect(result).toBe('openai');- });-- it('should default to openai for empty owned_by (Branch 7: default case)', () => {- const result = testGetProviderFromOwnedBy('');- expect(result).toBe('openai');- });- });-- describe('Models Function Branch Coverage - Logical Testing', () => {- // Test the complex models function logic by replicating its branching behavior-- describe('Data Handling Branches', () => {- it('should handle undefined data from models.list (Branch 3.1: data = undefined)', () => {- const data = undefined;- const modelList = data || [];- expect(modelList).toEqual([]);- });-- it('should handle null data from models.list (Branch 3.1: data = null)', () => {- const data = null;- const modelList = data || [];- expect(modelList).toEqual([]);- });-- it('should handle valid data from models.list (Branch 3.1: data exists)', () => {- const data = [{ created: 123, id: 'test-model', object: 'model', owned_by: 'openai' }];- const modelList = data || [];- expect(modelList).toEqual(data);- });- });-- describe('Pricing API Response Branches', () => {- it('should handle fetch failure (Branch 3.2: pricingResponse.ok = false)', () => {- const pricingResponse = { ok: false };- expect(pricingResponse.ok).toBe(false);- });-- it('should handle successful fetch (Branch 3.2: pricingResponse.ok = true)', () => {- const pricingResponse = { ok: true };- expect(pricingResponse.ok).toBe(true);- });-- it('should handle network error (Branch 3.18: error handling)', () => {- expect(() => {- throw new Error('Network error');- }).toThrow(Error);- });- });-- describe('Pricing Data Validation Branches', () => {- it('should handle pricingData.success = false (Branch 3.3)', () => {- const pricingData = { data: [], success: false };- const shouldProcess = pricingData.success && pricingData.data;- expect(shouldProcess).toBeFalsy();- });-- it('should handle missing pricingData.data (Branch 3.4)', () => {- const pricingData: MockPricingResponse = { success: true };- const shouldProcess = pricingData.success && pricingData.data;- expect(shouldProcess).toBeFalsy();- });-- it('should process valid pricing data (Branch 3.5: success && data = true)', () => {- const pricingData = { data: [{ model_name: 'test' }], success: true };- const shouldProcess = pricingData.success && pricingData.data;- expect(shouldProcess).toBeTruthy();- });- });-- describe('Pricing Calculation Branches', () => {- it('should handle no pricing match for model (Branch 3.6: pricing = undefined)', () => {- const pricingMap = new Map([['other-model', { model_name: 'other-model', quota_type: 0 }]]);- const pricing = pricingMap.get('test-model');- expect(pricing).toBeUndefined();- });-- it('should skip quota_type = 1 (Branch 3.7: quota_type !== 0)', () => {- const pricing = { model_price: 10, quota_type: 1 };- const shouldProcess = pricing.quota_type === 0;- expect(shouldProcess).toBe(false);- });-- it('should process quota_type = 0 (Branch 3.7: quota_type === 0)', () => {- const pricing = { model_price: 10, quota_type: 0 };- const shouldProcess = pricing.quota_type === 0;- expect(shouldProcess).toBe(true);- });-- it('should use model_price when > 0 (Branch 3.8: model_price && model_price > 0 = true)', () => {- const pricing = { model_price: 15, model_ratio: 10 };- let inputPrice;-- if (pricing.model_price && pricing.model_price > 0) {- inputPrice = pricing.model_price * 2;- } else if (pricing.model_ratio) {- inputPrice = pricing.model_ratio * 2;- }-- expect(inputPrice).toBe(30); // model_price * 2- });-- it('should fallback to model_ratio when model_price = 0 (Branch 3.8: model_price > 0 = false, Branch 3.9: model_ratio = true)', () => {- const pricing = { model_price: 0, model_ratio: 12 };- let inputPrice;-- if (pricing.model_price && pricing.model_price > 0) {- inputPrice = pricing.model_price * 2;- } else if (pricing.model_ratio) {- inputPrice = pricing.model_ratio * 2;- }-- expect(inputPrice).toBe(24); // model_ratio * 2- });-- it('should handle missing model_ratio (Branch 3.9: model_ratio = undefined)', () => {- const pricing: Partial<NewAPIPricing> = { quota_type: 0 }; // No model_price and no model_ratio- let inputPrice: number | undefined;-- if (pricing.model_price && pricing.model_price > 0) {- inputPrice = pricing.model_price * 2;- } else if (pricing.model_ratio) {- inputPrice = pricing.model_ratio * 2;- }-- expect(inputPrice).toBeUndefined();- });-- it('should calculate output price when inputPrice is defined (Branch 3.10: inputPrice !== undefined = true)', () => {- const inputPrice = 20;- const completionRatio = 1.5;-- let outputPrice;- if (inputPrice !== undefined) {- outputPrice = inputPrice * (completionRatio || 1);- }-- expect(outputPrice).toBe(30);- });-- it('should use default completion_ratio when not provided', () => {- const inputPrice = 16;- const completionRatio = undefined;-- let outputPrice;- if (inputPrice !== undefined) {- outputPrice = inputPrice * (completionRatio || 1);- }-- expect(outputPrice).toBe(16); // input * 1 (default)- });- });-- describe('Provider Detection Branches', () => {- it('should use supported_endpoint_types with anthropic (Branch 3.11: length > 0 = true, Branch 3.12: includes anthropic = true)', () => {- const model = { supported_endpoint_types: ['anthropic'] };- let detectedProvider = 'openai';-- if (- model.supported_endpoint_types &&- model.supported_endpoint_types.length > 0 &&- model.supported_endpoint_types.includes('anthropic')- ) {- detectedProvider = 'anthropic';- }-- expect(detectedProvider).toBe('anthropic');- });-- it('should use supported_endpoint_types with gemini (Branch 3.13: includes gemini = true)', () => {- const model = { supported_endpoint_types: ['gemini'] };- let detectedProvider = 'openai';-- if (- model.supported_endpoint_types &&- model.supported_endpoint_types.length > 0 &&- model.supported_endpoint_types.includes('gemini')- ) {- detectedProvider = 'google';- }-- expect(detectedProvider).toBe('google');- });-- it('should use supported_endpoint_types with xai (Branch 3.14: includes xai = true)', () => {- const model = { supported_endpoint_types: ['xai'] };- let detectedProvider = 'openai';-- if (- model.supported_endpoint_types &&- model.supported_endpoint_types.length > 0 &&- model.supported_endpoint_types.includes('xai')- ) {- detectedProvider = 'xai';- }-- expect(detectedProvider).toBe('xai');- });-- it('should fallback to owned_by when supported_endpoint_types is empty (Branch 3.11: length > 0 = false, Branch 3.15: owned_by = true)', () => {- const model: Partial<NewAPIModelCard> = {- owned_by: 'anthropic',- supported_endpoint_types: [],- };- let detectedProvider = 'openai';-- if (model.supported_endpoint_types && model.supported_endpoint_types.length > 0) {- // Skip - empty array- } else if (model.owned_by) {- detectedProvider = 'anthropic'; // Simplified for test- }-- expect(detectedProvider).toBe('anthropic');- });-- it('should fallback to owned_by when no supported_endpoint_types (Branch 3.15: owned_by = true)', () => {- const model: Partial<NewAPIModelCard> = { owned_by: 'google' };- let detectedProvider = 'openai';-- if (model.supported_endpoint_types && model.supported_endpoint_types.length > 0) {- // Skip - no supported_endpoint_types- } else if (model.owned_by) {- detectedProvider = 'google'; // Simplified for test- }-- expect(detectedProvider).toBe('google');- });-- it.skip('should use detectModelProvider fallback when no owned_by (Branch 3.15: owned_by = false, Branch 3.17)', () => {- const model: Partial<NewAPIModelCard> = { id: 'claude-3-sonnet', owned_by: '' };- mockDetectModelProvider.mockReturnValue('anthropic');-- let detectedProvider = 'openai';-- if (model.supported_endpoint_types && model.supported_endpoint_types.length > 0) {- // Skip - no supported_endpoint_types- } else if (model.owned_by) {- // Skip - empty owned_by- } else {- detectedProvider = mockDetectModelProvider(model.id || '');- }-- expect(detectedProvider).toBe('anthropic');- expect(mockDetectModelProvider).toHaveBeenCalledWith('claude-3-sonnet');- });-- it('should cleanup _detectedProvider field (Branch 3.16: _detectedProvider exists = true)', () => {- const model: any = {- _detectedProvider: 'openai',- displayName: 'Test Model',- id: 'test-model',- };-- if (model._detectedProvider) {- delete model._detectedProvider;- }-- expect(model).not.toHaveProperty('_detectedProvider');- });-- it('should skip cleanup when no _detectedProvider field (Branch 3.16: _detectedProvider exists = false)', () => {- const model: any = {- displayName: 'Test Model',- id: 'test-model',- };-- const hadDetectedProvider = '_detectedProvider' in model;-- if (model._detectedProvider) {- delete model._detectedProvider;- }-- expect(hadDetectedProvider).toBe(false);- });- });-- describe('URL Processing Branch Coverage', () => {- it('should remove trailing API version paths from baseURL', () => {- const testURLs = [- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v1' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v1/' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v1beta' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v1beta/' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v2' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com/v1alpha' },- { expected: 'https://api.newapi.com', input: 'https://api.newapi.com' },- ];-- testURLs.forEach(({ input, expected }) => {- const result = input.replace(/\/v\d+[a-z]*\/?$/, '');- expect(result).toBe(expected);- });- });- });- });-- describe('Integration and Runtime Tests', () => {- it('should validate runtime instantiation', () => {- expect(LobeNewAPIAI).toBeDefined();- expect(typeof LobeNewAPIAI).toBe('function');- });-- it('should validate NewAPI type definitions', () => {- const mockModel: NewAPIModelCard = {- created: 1_234_567_890,- id: 'test-model',- object: 'model',- owned_by: 'openai',- supported_endpoint_types: ['openai'],- };-- const mockPricing: NewAPIPricing = {- completion_ratio: 1.5,- enable_groups: ['default'],- model_name: 'test-model',- model_price: 10,- model_ratio: 5,- quota_type: 0,- supported_endpoint_types: ['openai'],- };-- expect(mockModel.id).toBe('test-model');- expect(mockPricing.quota_type).toBe(0);- });-- it('should test complex pricing and provider detection workflow', () => {- // Simulate the complex workflow of the models function- const models = [- {- id: 'anthropic-claude',- owned_by: 'anthropic',- supported_endpoint_types: ['anthropic'],- },- {- id: 'google-gemini',- owned_by: 'google',- supported_endpoint_types: ['gemini'],- },- {- id: 'openai-gpt4',- owned_by: 'openai',- },- ];-- const pricingData = [- { completion_ratio: 3, model_name: 'anthropic-claude', model_price: 20, quota_type: 0 },- { model_name: 'google-gemini', model_ratio: 5, quota_type: 0 },- { model_name: 'openai-gpt4', model_price: 30, quota_type: 1 }, // Should be skipped- ];-- const pricingMap = new Map(pricingData.map((p) => [p.model_name, p]));-- const enrichedModels = models.map((model) => {- const enhancedModel: any = { ...model };-- // Test pricing logic- const pricing = pricingMap.get(model.id);- if (pricing && pricing.quota_type === 0) {- let inputPrice: number | undefined;-- if (pricing.model_price && pricing.model_price > 0) {- inputPrice = pricing.model_price * 2;- } else if (pricing.model_ratio) {- inputPrice = pricing.model_ratio * 2;- }-- if (inputPrice !== undefined) {- const outputPrice = inputPrice * (pricing.completion_ratio || 1);- enhancedModel.pricing = {- units: [- {- name: 'textInput',- rate: inputPrice,- strategy: 'fixed',- unit: 'millionTokens',- },- {- name: 'textOutput',- rate: outputPrice,- strategy: 'fixed',- unit: 'millionTokens',- },- ],- };- }- }-- // Test provider detection logic- let detectedProvider = 'openai';- if (model.supported_endpoint_types && model.supported_endpoint_types.length > 0) {- if (model.supported_endpoint_types.includes('anthropic')) {- detectedProvider = 'anthropic';- } else if (model.supported_endpoint_types.includes('gemini')) {- detectedProvider = 'google';- }- }- enhancedModel._detectedProvider = detectedProvider;-- return enhancedModel;- });-- // Verify pricing results- expect(enrichedModels[0].pricing).toEqual({- units: [- { name: 'textInput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 120, strategy: 'fixed', unit: 'millionTokens' },- ],- }); // model_price * 2, input * completion_ratio- expect(enrichedModels[1].pricing).toEqual({- units: [- { name: 'textInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },- ],- }); // model_ratio * 2, input * 1 (default)- expect(enrichedModels[2].pricing).toBeUndefined(); // quota_type = 1, skipped-- // Verify provider detection- expect(enrichedModels[0]._detectedProvider).toBe('anthropic');- expect(enrichedModels[1]._detectedProvider).toBe('google');- expect(enrichedModels[2]._detectedProvider).toBe('openai');-- // Test cleanup logic- const finalModels = enrichedModels.map((model: any) => {- if (model._detectedProvider) {- delete model._detectedProvider;- }- return model;- });-- finalModels.forEach((model: any) => {- expect(model).not.toHaveProperty('_detectedProvider');- });- });-- it('should configure dynamic routers with correct baseURL from user options', () => {- // Test the dynamic routers configuration- const testOptions = {- apiKey: 'test-key',- baseURL: 'https://yourapi.cn/v1',- };-- // Create instance to test dynamic routers- const instance = new LobeNewAPIAI(testOptions);- expect(instance).toBeDefined();-- // The dynamic routers should be configured with user's baseURL- // This is tested indirectly through successful instantiation- // since the routers function processes the options.baseURL- const expectedBaseURL = testOptions.baseURL.replace(/\/v\d+[a-z]*\/?$/, '');- expect(expectedBaseURL).toBe('https://yourapi.cn');- });- });-// ============================================================================// COMPREHENSIVE INTEGRATION TESTS FOR 90%+ COVERAGE// ============================================================================@@ -661,21 +49,6 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {'X-Client': 'LobeHub',});});-- it('should export params with debug configuration', () => {- expect(params.debug).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should export params with models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });-- it('should export params with routers function', () => {- expect(params.routers).toBeDefined();- expect(typeof params.routers).toBe('function');- });});describe('Debug Configuration - Direct Testing', () => {@@ -1520,21 +893,5 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {expect(instance).toBeDefined();expect(instance).toBeInstanceOf(LobeNewAPIAI);});-- it('should create instance with custom baseURL', () => {- const instance = new LobeNewAPIAI({- apiKey: 'test-key',- baseURL: 'https://custom.com/v1',- });- expect(instance).toBeDefined();- });-- it('should create instance with additional options', () => {- const instance = new LobeNewAPIAI({- apiKey: 'test-key',- baseURL: 'https://custom.com',- });- expect(instance).toBeDefined();- });});});diff --git a/packages/model-runtime/src/providers/ollamacloud/index.test.ts b/packages/model-runtime/src/providers/ollamacloud/index.test.tsindex e3115cb047f..d6a8eb10b8b 100644--- a/packages/model-runtime/src/providers/ollamacloud/index.test.ts+++ b/packages/model-runtime/src/providers/ollamacloud/index.test.ts@@ -1,5 +1,4 @@// @vitest-environment node-import { ModelProvider } from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LobeOllamaCloudAI, params } from './index';@@ -17,12 +16,6 @@ describe('LobeOllamaCloudAI - custom features', () => {});describe('params export', () => {- it('should export params object', () => {- expect(params).toBeDefined();- expect(params.provider).toBe(ModelProvider.OllamaCloud);- expect(params.baseURL).toBe('https://ollama.com/v1');- });-it('should have correct structure', () => {expect(params).toHaveProperty('chatCompletion');expect(params).toHaveProperty('debug');@@ -49,12 +42,6 @@ describe('LobeOllamaCloudAI - custom features', () => {const result = params.debug.chatCompletion();expect(result).toBe(false);});-- it('should disable debug when env is empty string', () => {- process.env.DEBUG_OLLAMA_CLOUD_CHAT_COMPLETION = '';- const result = params.debug.chatCompletion();- expect(result).toBe(false);- });});describe('handlePayload', () => {@@ -87,44 +74,6 @@ describe('LobeOllamaCloudAI - custom features', () => {expect(result.model).toBe('llama3.2');expect(result.messages).toEqual(payload.messages);});-- it('should handle payload with additional parameters', () => {- const payload = {- frequency_penalty: 0.5,- messages: [{ content: 'Hello', role: 'user' }],- model: 'llama3.2',- presence_penalty: 0.3,- stop: ['END'],- top_p: 0.9,- };-- const result = params.chatCompletion.handlePayload(payload as any);-- expect(result.model).toBe('llama3.2');- expect(result.messages).toEqual(payload.messages);- expect(result.top_p).toBe(0.9);- expect(result.frequency_penalty).toBe(0.5);- expect(result.presence_penalty).toBe(0.3);- expect(result.stop).toEqual(['END']);- });-- it('should handle different model names', () => {- const payload1 = {- messages: [{ content: 'Hello', role: 'user' }],- model: 'llama3.2',- };-- const payload2 = {- messages: [{ content: 'Hello', role: 'user' }],- model: 'codellama',- };-- const result1 = params.chatCompletion.handlePayload(payload1 as any);- const result2 = params.chatCompletion.handlePayload(payload2 as any);-- expect(result1.model).toBe('llama3.2');- expect(result2.model).toBe('codellama');- });});describe('models function', () => {@@ -186,24 +135,6 @@ describe('LobeOllamaCloudAI - custom features', () => {expect(Array.isArray(result)).toBe(true);expect(result).toHaveLength(0);});-- it('should handle empty direct array', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockResolvedValue([]),- },- };-- const result = await params.models({ client: mockClient as any });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(result).toBeDefined();- expect(Array.isArray(result)).toBe(true);- expect(result).toHaveLength(0);- });-it('should handle API error gracefully', async () => {const mockClient = {apiKey: 'test',@@ -217,19 +148,6 @@ describe('LobeOllamaCloudAI - custom features', () => {expect(mockClient.models.list).toHaveBeenCalledTimes(1);});-- it('should handle network error', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Network Error')),- },- };-- await expect(params.models({ client: mockClient as any })).rejects.toThrow('Network Error');- });-it('should handle invalid API key error', async () => {const mockClient = {apiKey: 'invalid',@@ -257,23 +175,6 @@ describe('LobeOllamaCloudAI - custom features', () => {expect(Array.isArray(result)).toBe(true);expect(result).toHaveLength(0);});-- it('should handle undefined response', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockResolvedValue(undefined),- },- };-- const result = await params.models({ client: mockClient as any });-- expect(result).toBeDefined();- expect(Array.isArray(result)).toBe(true);- expect(result).toHaveLength(0);- });-it('should handle response with non-array data', async () => {const mockClient = {apiKey: 'test',@@ -291,54 +192,6 @@ describe('LobeOllamaCloudAI - custom features', () => {expect(Array.isArray(result)).toBe(true);expect(result).toHaveLength(0);});-- it('should handle response as non-array object without data property', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockResolvedValue({- models: [{ id: 'llama3.2' }],- }),- },- };-- const result = await params.models({ client: mockClient as any });-- expect(result).toBeDefined();- expect(Array.isArray(result)).toBe(true);- expect(result).toHaveLength(0);- });-- it('should handle response with data property but null value', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockResolvedValue({- data: null,- }),- },- };-- const result = await params.models({ client: mockClient as any });-- expect(result).toBeDefined();- expect(Array.isArray(result)).toBe(true);- expect(result).toHaveLength(0);- });-- it('should handle timeout error', async () => {- const mockClient = {- apiKey: 'test',- baseURL: 'https://ollama.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Request timeout')),- },- };-- await expect(params.models({ client: mockClient as any })).rejects.toThrow('Request timeout');- });});describe('runtime instantiation', () => {diff --git a/packages/model-runtime/src/providers/openrouter/index.test.ts b/packages/model-runtime/src/providers/openrouter/index.test.tsindex 14a761b99c0..886b2591581 100644--- a/packages/model-runtime/src/providers/openrouter/index.test.ts+++ b/packages/model-runtime/src/providers/openrouter/index.test.ts@@ -31,33 +31,12 @@ afterEach(() => {describe('LobeOpenRouterAI - custom features', () => {describe('Params Export', () => {- it('should export params object', () => {- expect(params).toBeDefined();- expect(params.provider).toBe('openrouter');- expect(params.baseURL).toBe('https://openrouter.ai/api/v1');- });-- it('should have chatCompletion configuration', () => {- expect(params.chatCompletion).toBeDefined();- expect(params.chatCompletion.handlePayload).toBeDefined();- });-it('should have constructorOptions with headers', () => {expect(params.constructorOptions).toBeDefined();expect(params.constructorOptions.defaultHeaders).toBeDefined();expect(params.constructorOptions.defaultHeaders['HTTP-Referer']).toBe('https://lobehub.com');expect(params.constructorOptions.defaultHeaders['X-Title']).toBe('LobeHub');});-- it('should have debug configuration', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('Debug Configuration', () => {diff --git a/packages/model-runtime/src/providers/qiniu/index.test.ts b/packages/model-runtime/src/providers/qiniu/index.test.tsindex 8bec8f696c0..c258c259735 100644--- a/packages/model-runtime/src/providers/qiniu/index.test.ts+++ b/packages/model-runtime/src/providers/qiniu/index.test.ts@@ -1,5 +1,4 @@// @vitest-environment node-import { ModelProvider } from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LobeQiniuAI, params } from './index';@@ -138,58 +137,6 @@ describe('LobeQiniuAI - custom features', () => {// Verify that the models are processed (non-empty if valid models exist)expect(Array.isArray(models)).toBe(true);});-- it('should handle models with OpenAI provider', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'gpt-4' }, { id: 'gpt-3.5-turbo' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });-- expect(models.length).toBeGreaterThan(0);- // Should detect OpenAI models and include them- const gpt4 = models.find((m) => m.id === 'gpt-4');- expect(gpt4).toBeDefined();- });-- it('should handle models with Anthropic provider', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'claude-3-opus' }, { id: 'claude-3-sonnet' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });-- expect(models.length).toBeGreaterThan(0);- // Should detect Anthropic models and include them- const claude = models.find((m) => m.id === 'claude-3-opus');- expect(claude).toBeDefined();- });-- it('should handle models with Google provider', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'gemini-pro' }, { id: 'gemini-1.5-pro' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });-- expect(models.length).toBeGreaterThan(0);- // Should detect Google models and include them- const gemini = models.find((m) => m.id === 'gemini-pro');- expect(gemini).toBeDefined();- });-it('should handle mixed provider models', async () => {const mockClient = {models: {@@ -226,19 +173,6 @@ describe('LobeQiniuAI - custom features', () => {expect(Array.isArray(models)).toBe(true);});-- it('should handle network timeout errors', async () => {- const mockClient = {- models: {- list: vi.fn().mockRejectedValue(new Error('Network timeout')),- },- };-- await expect(params.models!({ client: mockClient as any })).rejects.toThrow(- 'Network timeout',- );- });-it('should handle invalid API response format', async () => {const mockClient = {models: {@@ -283,17 +217,6 @@ describe('LobeQiniuAI - custom features', () => {});describe('exports', () => {- it('should export params object', () => {- expect(params).toBeDefined();- expect(params.provider).toBe(ModelProvider.Qiniu);- expect(params.baseURL).toBe('https://openai.qiniu.com/v1');- });-- it('should export LobeQiniuAI class', () => {- expect(LobeQiniuAI).toBeDefined();- expect(typeof LobeQiniuAI).toBe('function');- });-it('should export params with all required properties', () => {expect(params).toHaveProperty('provider');expect(params).toHaveProperty('baseURL');@@ -301,18 +224,6 @@ describe('LobeQiniuAI - custom features', () => {expect(params).toHaveProperty('debug');expect(params).toHaveProperty('models');});-- it('should have debug.chatCompletion function', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });-it('should have correct apiKey placeholder', () => {expect(params.apiKey).toBe('placeholder-to-avoid-error');});diff --git a/packages/model-runtime/src/providers/search1api/index.test.ts b/packages/model-runtime/src/providers/search1api/index.test.tsindex 2d63259d660..cf778cc5686 100644--- a/packages/model-runtime/src/providers/search1api/index.test.ts+++ b/packages/model-runtime/src/providers/search1api/index.test.ts@@ -54,37 +54,6 @@ describe('LobeSearch1API - custom features', () => {expect.anything(),);});-- it('should use presence_penalty when it is negative', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- presence_penalty: -0.5,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- presence_penalty: -0.5,- }),- expect.anything(),- );- });-- it('should use presence_penalty when it is 1', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- presence_penalty: 1,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- presence_penalty: 1,- }),- expect.anything(),- );- });-it('should not include frequency_penalty when presence_penalty is non-zero', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -173,51 +142,6 @@ describe('LobeSearch1API - custom features', () => {});describe('temperature handling', () => {- it('should preserve temperature when it is less than 2', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- temperature: 0.7,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 0.7,- }),- expect.anything(),- );- });-- it('should preserve temperature when it is 0', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- temperature: 0,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 0,- }),- expect.anything(),- );- });-- it('should preserve temperature when it is 1', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- temperature: 1,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 1,- }),- expect.anything(),- );- });-it('should preserve temperature when it is 1.99', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -247,22 +171,6 @@ describe('LobeSearch1API - custom features', () => {expect.anything(),);});-- it('should set temperature to undefined when it is greater than 2', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- temperature: 2.5,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: undefined,- }),- expect.anything(),- );- });-it('should set temperature to undefined when it is not provided', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -303,21 +211,6 @@ describe('LobeSearch1API - custom features', () => {expect.anything(),);});-- it('should preserve stream value when explicitly set to true', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- stream: true,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- stream: true,- }),- expect.anything(),- );- });});describe('other properties preservation', () => {@@ -387,58 +280,6 @@ describe('LobeSearch1API - custom features', () => {});describe('combined parameter scenarios', () => {- it('should handle presence_penalty with temperature < 2', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- presence_penalty: 0.5,- temperature: 0.8,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- presence_penalty: 0.5,- temperature: 0.8,- }),- expect.anything(),- );- });-- it('should handle presence_penalty with temperature >= 2', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- presence_penalty: 0.5,- temperature: 2.5,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- presence_penalty: 0.5,- temperature: undefined,- }),- expect.anything(),- );- });-- it('should handle frequency_penalty with temperature < 2', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- presence_penalty: 0,- frequency_penalty: 0.8,- temperature: 0.7,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- frequency_penalty: 0.8,- temperature: 0.7,- }),- expect.anything(),- );- });-it('should handle all parameters together', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -477,22 +318,6 @@ describe('LobeSearch1API - custom features', () => {expect.anything(),);});-- it('should handle very large temperature values', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-4o-mini',- temperature: 100,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: undefined,- }),- expect.anything(),- );- });-it('should handle edge case temperature exactly at 2', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],diff --git a/packages/model-runtime/src/providers/stepfun/index.test.ts b/packages/model-runtime/src/providers/stepfun/index.test.tsindex 9504f42bf19..01274fb113a 100644--- a/packages/model-runtime/src/providers/stepfun/index.test.ts+++ b/packages/model-runtime/src/providers/stepfun/index.test.ts@@ -23,11 +23,6 @@ describe('LobeStepfunAI - custom features', () => {expect(params.chatCompletion).toBeDefined();expect(params.models).toBeDefined();});-- it('should have debug.chatCompletion function', () => {- expect(typeof params.debug?.chatCompletion).toBe('function');- });-it('should return false when DEBUG_STEPFUN_CHAT_COMPLETION is not set', () => {delete process.env.DEBUG_STEPFUN_CHAT_COMPLETION;expect(params.debug?.chatCompletion()).toBe(false);@@ -76,9 +71,8 @@ describe('LobeStepfunAI - custom features', () => {});});- it('should not add web_search tool when enabledSearch is false', async () => {+ it('should not add web_search tool when enabledSearch is undefined', async () => {await instance.chat({- enabledSearch: false,messages: [{ content: 'Hello', role: 'user' }],model: 'step-1-8k',});@@ -87,8 +81,9 @@ describe('LobeStepfunAI - custom features', () => {expect(calledPayload.tools).toBeUndefined();});- it('should not add web_search tool when enabledSearch is undefined', async () => {+ it('should not add web_search tool when enabledSearch is false', async () => {await instance.chat({+ enabledSearch: false,messages: [{ content: 'Hello', role: 'user' }],model: 'step-1-8k',});@@ -96,7 +91,6 @@ describe('LobeStepfunAI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.tools).toBeUndefined();});-it('should preserve existing tools when enabledSearch is false', async () => {await instance.chat({enabledSearch: false,@@ -120,18 +114,6 @@ describe('LobeStepfunAI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.stream).toBe(true);});-- it('should keep stream enabled when web_search is enabled', async () => {- await instance.chat({- enabledSearch: true,- messages: [{ content: 'Hello', role: 'user' }],- model: 'step-1-8k',- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.stream).toBe(true);- });-it('should honor caller-provided stream=false when tools are present', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -143,18 +125,6 @@ describe('LobeStepfunAI - custom features', () => {const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];expect(calledPayload.stream).toBe(false);});-- it('should honor caller-provided stream=false when no tools are present', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'step-1-8k',- stream: false,- });-- const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];- expect(calledPayload.stream).toBe(false);- });-it('should set stream to true when no tools are present', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -196,72 +166,6 @@ describe('LobeStepfunAI - custom features', () => {const models = await params.models!({ client: mockClient as any });expect(models).toBeDefined();});-- it('should detect function call from step-1o- keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'step-1o-8k' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- expect(models).toBeDefined();- });-- it('should detect function call from step-1v- keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'step-1v-8k' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- expect(models).toBeDefined();- });-- it('should detect function call from step-2- keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'step-2-16k' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- expect(models).toBeDefined();- });-- it('should detect vision from step-1o- keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'step-1o-8k' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- expect(models).toBeDefined();- });-- it('should detect vision from step-r1-v- keyword', async () => {- const mockClient = {- models: {- list: vi.fn().mockResolvedValue({- data: [{ id: 'step-r1-v-8k' }],- }),- },- };-- const models = await params.models!({ client: mockClient as any });- expect(models).toBeDefined();- });-it('should detect vision from step-1v- keyword', async () => {const mockClient = {models: {diff --git a/packages/model-runtime/src/providers/v0/index.test.ts b/packages/model-runtime/src/providers/v0/index.test.tsindex 11409c20a8f..a77f0e1a0f3 100644--- a/packages/model-runtime/src/providers/v0/index.test.ts+++ b/packages/model-runtime/src/providers/v0/index.test.ts@@ -28,17 +28,6 @@ describe('LobeV0AI - custom features', () => {it('should export params with correct provider', () => {expect(params.provider).toBe(ModelProvider.V0);});-- it('should have debug configuration', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('debug configuration', () => {@@ -59,12 +48,6 @@ describe('LobeV0AI - custom features', () => {const result = params.debug.chatCompletion();expect(result).toBe(false);});-- it('should disable debug when env is empty string', () => {- process.env.DEBUG_V0_CHAT_COMPLETION = '';- const result = params.debug.chatCompletion();- expect(result).toBe(false);- });});describe('models function', () => {@@ -126,24 +109,6 @@ describe('LobeV0AI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle empty models list without data property', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.v0.dev/v1',- models: {- list: vi.fn().mockResolvedValue([]),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle null response', async () => {const mockClient = {apiKey: 'test_api_key',@@ -160,24 +125,6 @@ describe('LobeV0AI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle undefined response', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.v0.dev/v1',- models: {- list: vi.fn().mockResolvedValue(undefined),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle response with non-array data', async () => {const mockClient = {apiKey: 'test_api_key',@@ -210,49 +157,6 @@ describe('LobeV0AI - custom features', () => {expect(mockClient.models.list).toHaveBeenCalledTimes(1);});-- it('should throw when API authentication fails', async () => {- const mockClient = {- apiKey: 'invalid_key',- baseURL: 'https://api.v0.dev/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('401 Unauthorized')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('401 Unauthorized');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when API rate limit fails', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.v0.dev/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('429 Too Many Requests')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('429 Too Many Requests');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when request times out', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.v0.dev/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Request timeout')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('Request timeout');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-it('should handle malformed JSON response', async () => {const mockClient = {apiKey: 'test_api_key',diff --git a/packages/model-runtime/src/providers/zenmux/index.test.ts b/packages/model-runtime/src/providers/zenmux/index.test.tsindex 1fb2438c582..558e476f98d 100644--- a/packages/model-runtime/src/providers/zenmux/index.test.ts+++ b/packages/model-runtime/src/providers/zenmux/index.test.ts@@ -16,7 +16,6 @@ vi.spyOn(console, 'debug').mockImplementation(() => {});describe('ZenMux Runtime', () => {let mockFetch: Mock;let mockProcessMultiProviderModelList: Mock;- let mockDetectModelProvider: Mock;beforeEach(() => {// Setup fetch mock@@ -25,7 +24,6 @@ describe('ZenMux Runtime', () => {// Setup utility function mocksmockProcessMultiProviderModelList = vi.mocked(modelParseModule.processMultiProviderModelList);- mockDetectModelProvider = vi.mocked(modelParseModule.detectModelProvider);// Clear environment variablesdelete process.env.DEBUG_ZENMUX_CHAT_COMPLETION;@@ -52,30 +50,9 @@ describe('ZenMux Runtime', () => {describe('LobeZenMuxAI - custom features', () => {describe('Params Export', () => {- it('should export params object', () => {- expect(params).toBeDefined();- expect(params.id).toBe('zenmux');- });-- it('should have routers configuration', () => {- expect(params.routers).toBeDefined();- expect(typeof params.routers).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });-it('should have correct provider ID', () => {expect(params.id).toBe(ModelProvider.ZenMux);});-- it('should have chatCompletion handlePayload function', () => {- expect(params.chatCompletion).toBeDefined();- expect(params.chatCompletion?.handlePayload).toBeDefined();- expect(typeof params.chatCompletion?.handlePayload).toBe('function');- });});describe('ChatCompletion HandlePayload', () => {diff --git a/packages/model-runtime/src/providers/zeroone/index.test.ts b/packages/model-runtime/src/providers/zeroone/index.test.tsindex 27dd694e4e4..0b8682ae428 100644--- a/packages/model-runtime/src/providers/zeroone/index.test.ts+++ b/packages/model-runtime/src/providers/zeroone/index.test.ts@@ -28,17 +28,6 @@ describe('LobeZeroOneAI - custom features', () => {it('should export params with correct provider', () => {expect(params.provider).toBe(ModelProvider.ZeroOne);});-- it('should have debug configuration', () => {- expect(params.debug).toBeDefined();- expect(params.debug.chatCompletion).toBeDefined();- expect(typeof params.debug.chatCompletion).toBe('function');- });-- it('should have models function', () => {- expect(params.models).toBeDefined();- expect(typeof params.models).toBe('function');- });});describe('debug configuration', () => {@@ -59,12 +48,6 @@ describe('LobeZeroOneAI - custom features', () => {const result = params.debug.chatCompletion();expect(result).toBe(false);});-- it('should disable debug when env is empty string', () => {- process.env.DEBUG_ZEROONE_CHAT_COMPLETION = '';- const result = params.debug.chatCompletion();- expect(result).toBe(false);- });});describe('models function', () => {@@ -126,24 +109,6 @@ describe('LobeZeroOneAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle empty models list without data property', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.lingyiwanwu.com/v1',- models: {- list: vi.fn().mockResolvedValue([]),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle null response', async () => {const mockClient = {apiKey: 'test_api_key',@@ -160,24 +125,6 @@ describe('LobeZeroOneAI - custom features', () => {expect(Array.isArray(models)).toBe(true);expect(models).toHaveLength(0);});-- it('should handle undefined response', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.lingyiwanwu.com/v1',- models: {- list: vi.fn().mockResolvedValue(undefined),- },- } as any;-- const models = await params.models!({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toBeDefined();- expect(Array.isArray(models)).toBe(true);- expect(models).toHaveLength(0);- });-it('should handle response with non-array data', async () => {const mockClient = {apiKey: 'test_api_key',@@ -210,49 +157,6 @@ describe('LobeZeroOneAI - custom features', () => {expect(mockClient.models.list).toHaveBeenCalledTimes(1);});-- it('should throw when API authentication fails', async () => {- const mockClient = {- apiKey: 'invalid_key',- baseURL: 'https://api.lingyiwanwu.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('401 Unauthorized')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('401 Unauthorized');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when API rate limit fails', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.lingyiwanwu.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('429 Too Many Requests')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('429 Too Many Requests');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-- it('should throw when request times out', async () => {- const mockClient = {- apiKey: 'test_api_key',- baseURL: 'https://api.lingyiwanwu.com/v1',- models: {- list: vi.fn().mockRejectedValue(new Error('Request timeout')),- },- } as any;-- await expect(params.models!({ client: mockClient })).rejects.toThrow('Request timeout');-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- });-it('should handle malformed JSON response', async () => {const mockClient = {apiKey: 'test_api_key',diff --git a/packages/model-runtime/src/providers/zhipu/index.test.ts b/packages/model-runtime/src/providers/zhipu/index.test.tsindex 6a581bf1136..7552dd35b87 100644--- a/packages/model-runtime/src/providers/zhipu/index.test.ts+++ b/packages/model-runtime/src/providers/zhipu/index.test.ts@@ -257,22 +257,6 @@ describe('LobeZhipuAI - custom features', () => {expect.anything(),);});-- it('should clamp high temperature to 0.99 for glm-4-alltools', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'glm-4-alltools',- temperature: 2, // Will be normalized to 1.0, then clamped to 0.99- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 0.99,- }),- expect.anything(),- );- });-it('should clamp top_p to [0.01, 0.99] for glm-4-alltools', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -288,23 +272,6 @@ describe('LobeZhipuAI - custom features', () => {expect.anything(),);});-- it('should clamp high top_p to 0.99 for glm-4-alltools', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'glm-4-alltools',- temperature: 0.5,- top_p: 1,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- top_p: 0.99,- }),- expect.anything(),- );- });-it('should normalize and preserve temperature in range for glm-4-alltools', async () => {await instance.chat({messages: [{ content: 'Hello', role: 'user' }],@@ -336,36 +303,6 @@ describe('LobeZhipuAI - custom features', () => {expect.anything(),);});-- it('should normalize high temperature', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'glm-4',- temperature: 1.6,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 0.8,- }),- expect.anything(),- );- });-- it('should handle temperature 0 correctly', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'glm-4',- temperature: 0,- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- temperature: 0,- }),- expect.anything(),- );- });});describe('Thinking mode for GLM-4.5 models', () => {@@ -384,22 +321,6 @@ describe('LobeZhipuAI - custom features', () => {expect.anything(),);});-- it('should include thinking for glm-4.5-turbo', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'glm-4.5-turbo',- temperature: 0.5,- thinking: { type: 'disabled', budget_tokens: 0 },- });-- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(- expect.objectContaining({- thinking: { type: 'disabled' },- }),- expect.anything(),- );- });});describe('tool_stream for streaming tool calls', () => {diff --git a/packages/model-runtime/src/utils/comfyuiErrorParser.test.ts b/packages/model-runtime/src/utils/comfyuiErrorParser.test.tsindex edf4be88b87..42e00c321b9 100644--- a/packages/model-runtime/src/utils/comfyuiErrorParser.test.ts+++ b/packages/model-runtime/src/utils/comfyuiErrorParser.test.ts@@ -13,21 +13,6 @@ describe('comfyuiErrorParser', () => {const multiAsterisk = '* * * Error message';expect(cleanComfyUIErrorMessage(multiAsterisk)).toBe('* * Error message');});-- it('should convert escaped newlines', () => {- const message = 'Line 1\\nLine 2';- expect(cleanComfyUIErrorMessage(message)).toBe('Line 1 Line 2');- });-- it('should replace multiple newlines with single space', () => {- const message = 'Line 1\n\n\nLine 2';- expect(cleanComfyUIErrorMessage(message)).toBe('Line 1 Line 2');- });-- it('should trim leading and trailing spaces', () => {- const message = ' Error message ';- expect(cleanComfyUIErrorMessage(message)).toBe('Error message');- });});describe('parseComfyUIErrorMessage', () => {@@ -77,24 +62,6 @@ describe('comfyuiErrorParser', () => {expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);expect(result.error.message).toBe('fetch failed');});-- it('should return ComfyUIBizError for ECONNREFUSED (processed by server)', () => {- const error = { message: 'Connection ECONNREFUSED', code: 'ECONNREFUSED' };- const result = parseComfyUIErrorMessage(error);-- // Network error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('Connection ECONNREFUSED');- });-- it('should return ComfyUIBizError for WebSocket errors (processed by server)', () => {- const error = { message: 'WebSocket connection failed', code: 'WS_CONNECTION_FAILED' };- const result = parseComfyUIErrorMessage(error);-- // Network error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('WebSocket connection failed');- });});describe('Model errors', () => {@@ -106,25 +73,6 @@ describe('comfyuiErrorParser', () => {expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);expect(result.error.message).toBe('Model not found: flux1-dev.safetensors');});-- it('should return ComfyUIBizError for checkpoint not found (processed by server)', () => {- const error = { message: 'Checkpoint not found' };- const result = parseComfyUIErrorMessage(error);-- // Model error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('Checkpoint not found');- });-- it('should return ComfyUIBizError for safetensors file errors (processed by server)', () => {- const error = { message: 'Missing file: model.safetensors' };- const result = parseComfyUIErrorMessage(error);-- // Model error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('Missing file: model.safetensors');- });-it('should preserve server-provided file info but return ComfyUIBizError', () => {const error = {message: 'Some error',@@ -141,15 +89,6 @@ describe('comfyuiErrorParser', () => {});describe('Workflow errors', () => {- it('should return ComfyUIBizError for workflow validation errors (processed by server)', () => {- const error = { message: 'Workflow validation failed' };- const result = parseComfyUIErrorMessage(error);-- // Workflow error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('Workflow validation failed');- });-it('should return ComfyUIBizError for node execution errors (processed by server)', () => {const error = {message: 'Node execution failed',@@ -166,15 +105,6 @@ describe('comfyuiErrorParser', () => {node_type: 'KSampler',});});-- it('should return ComfyUIBizError for queue errors (processed by server)', () => {- const error = { message: 'Queue processing error' };- const result = parseComfyUIErrorMessage(error);-- // Workflow error detection moved to server-side- expect(result.errorType).toBe(AgentRuntimeErrorType.ComfyUIBizError);- expect(result.error.message).toBe('Queue processing error');- });});describe('SDK custom errors', () => {diff --git a/packages/model-runtime/src/utils/getFallbackModelProperty.test.ts b/packages/model-runtime/src/utils/getFallbackModelProperty.test.tsindex 00744289367..e05bd7e4c5e 100644--- a/packages/model-runtime/src/utils/getFallbackModelProperty.test.ts+++ b/packages/model-runtime/src/utils/getFallbackModelProperty.test.ts@@ -203,11 +203,6 @@ describe('getModelPropertyWithFallback', () => {);expect(result).toBeUndefined();});-- it('should return undefined for enabled property when model not found', async () => {- const result = await getModelPropertyWithFallback('non-existent-model', 'enabled');- expect(result).toBeUndefined();- });});describe('provider precedence logic', () => {diff --git a/packages/model-runtime/src/utils/googleErrorParser.test.ts b/packages/model-runtime/src/utils/googleErrorParser.test.tsindex 079fe6df042..06a9e6a2ca3 100644--- a/packages/model-runtime/src/utils/googleErrorParser.test.ts+++ b/packages/model-runtime/src/utils/googleErrorParser.test.ts@@ -9,30 +9,6 @@ import {describe('googleErrorParser', () => {describe('cleanErrorMessage', () => {- it('should remove leading asterisk and spaces', () => {- const input = '* API key not valid. Please check your credentials.';- const expected = 'API key not valid. Please check your credentials.';- expect(cleanErrorMessage(input)).toBe(expected);- });-- it('should convert escaped newlines to actual newlines', () => {- const input = 'Error occurred\\nPlease try again';- const expected = 'Error occurred Please try again';- expect(cleanErrorMessage(input)).toBe(expected);- });-- it('should replace multiple newlines with single space', () => {- const input = 'Line 1\n\n\nLine 2\nLine 3';- const expected = 'Line 1 Line 2 Line 3';- expect(cleanErrorMessage(input)).toBe(expected);- });-- it('should trim whitespace', () => {- const input = ' \t Error message \t ';- const expected = 'Error message';- expect(cleanErrorMessage(input)).toBe(expected);- });-it('should handle combined formatting issues', () => {const input ='* API key not valid.\\nPlease check your credentials.\\n\\nContact support if needed. ';@@ -54,19 +30,6 @@ describe('googleErrorParser', () => {});expect(result.prefix).toBe('Connection failed');});-- it('should handle different status codes', () => {- const input = 'Request failed [401 Unauthorized] Invalid credentials';- const result = extractStatusCodeFromError(input);-- expect(result.errorDetails).toEqual({- message: 'Invalid credentials',- statusCode: 401,- statusCodeText: '[401 Unauthorized]',- });- expect(result.prefix).toBe('Request failed');- });-it('should return null for messages without status codes', () => {const input = 'Simple error message without status code';const result = extractStatusCodeFromError(input);@@ -86,43 +49,6 @@ describe('googleErrorParser', () => {});expect(result.prefix).toBe('Error');});-- it('should handle multiple spaces between status code and text', () => {- const input = 'Error [500 Internal Server Error] Something went wrong';- const result = extractStatusCodeFromError(input);-- expect(result.errorDetails).toEqual({- message: 'Something went wrong',- statusCode: 500,- statusCodeText: '[500 Internal Server Error]',- });- expect(result.prefix).toBe('Error');- });-- it('should handle status code at the beginning of message', () => {- const input = '[429 Too Many Requests] Rate limit exceeded';- const result = extractStatusCodeFromError(input);-- expect(result.errorDetails).toEqual({- message: 'Rate limit exceeded',- statusCode: 429,- statusCodeText: '[429 Too Many Requests]',- });- expect(result.prefix).toBe('');- });-- it('should handle status code at the end of message', () => {- const input = 'Request failed [503 Service Unavailable]';- const result = extractStatusCodeFromError(input);-- expect(result.errorDetails).toEqual({- message: '',- statusCode: 503,- statusCodeText: '[503 Service Unavailable]',- });- expect(result.prefix).toBe('Request failed');- });-it('should not be vulnerable to ReDoS attacks', () => {// Test with a potentially malicious input that could cause catastrophic backtrackingconst maliciousInput = 'Error ' + 'a'.repeat(10000) + ' [not matching]';diff --git a/packages/model-runtime/src/utils/modelExtendParams.test.ts b/packages/model-runtime/src/utils/modelExtendParams.test.tsindex 0425630240d..31a38e2c615 100644--- a/packages/model-runtime/src/utils/modelExtendParams.test.ts+++ b/packages/model-runtime/src/utils/modelExtendParams.test.ts@@ -63,27 +63,6 @@ describe('applyModelExtendParams', () => {expect(result.thinkingLevel).toBe('medium');});-- it('defaults Gemini 3.8 Flash thinkingLevel to medium (thinkingLevel3)', () => {- const result = applyModelExtendParams({- chatConfig: chatConfig({}),- extendParams: ['thinkingLevel3', 'urlContext'],- model: 'gemini-3.8-flash',- });-- expect(result.thinkingLevel).toBe('medium');- });-- it('honors an explicit Gemini 3.8 Flash thinkingLevel3 value', () => {- const result = applyModelExtendParams({- chatConfig: chatConfig({ thinkingLevel3: 'low' }),- extendParams: ['thinkingLevel3', 'urlContext'],- model: 'gemini-3.8-flash',- });-- expect(result.thinkingLevel).toBe('low');- });-it('honors an explicit Gemini 3.7 Flash thinkingLevel3 value', () => {const result = applyModelExtendParams({chatConfig: chatConfig({ thinkingLevel3: 'high' }),@@ -103,27 +82,6 @@ describe('applyModelExtendParams', () => {expect(result.thinkingLevel).toBe('medium');});-- it('defaults Gemini 3.7 Flash thinkingLevel to medium (thinkingLevel3, no minimal)', () => {- const result = applyModelExtendParams({- chatConfig: chatConfig({}),- extendParams: ['thinkingLevel3', 'urlContext'],- model: 'gemini-3.7-flash',- });-- expect(result.thinkingLevel).toBe('medium');- });-- it('honors an explicit Gemini 3.6 Flash thinkingLevel value', () => {- const result = applyModelExtendParams({- chatConfig: chatConfig({ thinkingLevel: 'low' }),- extendParams: ['thinkingLevel'],- model: 'gemini-3.6-flash',- });-- expect(result.thinkingLevel).toBe('low');- });-it('defaults Gemini 3.5 Flash-Lite thinkingLevel to minimal', () => {const result = applyModelExtendParams({chatConfig: chatConfig({}),diff --git a/packages/model-runtime/src/utils/modelParse.test.ts b/packages/model-runtime/src/utils/modelParse.test.tsindex 3a2f37ab893..14c83b76a52 100644--- a/packages/model-runtime/src/utils/modelParse.test.ts+++ b/packages/model-runtime/src/utils/modelParse.test.ts@@ -701,19 +701,6 @@ describe('modelParse', () => {});describe('Extended tests for detectModelProvider', () => {- it('should handle unusual casing patterns', () => {- expect(detectModelProvider('gPt-4')).toBe('openai');- expect(detectModelProvider('CLauDe-3-OPUS')).toBe('anthropic');- expect(detectModelProvider('gEmiNi-PrO')).toBe('google');- expect(detectModelProvider('qWeN-TuRbO')).toBe('qwen');- });-- it('should handle model IDs with keywords in unusual positions', () => {- expect(detectModelProvider('custom-gpt-model')).toBe('openai');- expect(detectModelProvider('prefix-claude-suffix')).toBe('anthropic');- expect(detectModelProvider('test-qwen-beta-v1')).toBe('qwen');- });-it('should handle empty and special character model IDs', () => {expect(detectModelProvider('')).toBe('openai'); // Defaultexpect(detectModelProvider(' ')).toBe('openai'); // Defaultdiff --git a/packages/utils/src/apiKey.test.ts b/packages/utils/src/apiKey.test.tsindex 2d1a2d92c9d..dd1df979859 100644--- a/packages/utils/src/apiKey.test.ts+++ b/packages/utils/src/apiKey.test.ts@@ -9,12 +9,6 @@ describe('apiKey', () => {expect(apiKey.startsWith(API_KEY_PREFIX)).toBe(true);expect(apiKey.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);});-- it('should generate API key with correct length', () => {- const apiKey = generateApiKey();- expect(apiKey).toHaveLength(API_KEY_PREFIX.length + 16);- });-it('should generate unique API keys', () => {const keys = new Set();for (let i = 0; i < 100; i++) {@@ -23,17 +17,6 @@ describe('apiKey', () => {// All 100 keys should be uniqueexpect(keys.size).toBe(100);});-- it('should start with lb- prefix', () => {- const apiKey = generateApiKey();- expect(apiKey.startsWith(API_KEY_PREFIX)).toBe(true);- });-- it('should only contain lowercase alphanumeric characters after prefix', () => {- const apiKey = generateApiKey();- const randomPart = apiKey.slice(API_KEY_PREFIX.length);- expect(randomPart).toMatch(/^[\da-z]+$/);- });});describe('isApiKeyExpired', () => {@@ -46,52 +29,18 @@ describe('apiKey', () => {futureDate.setFullYear(futureDate.getFullYear() + 1); // 1 year from nowexpect(isApiKeyExpired(futureDate)).toBe(false);});-- it('should return true when expiration date is in the past', () => {- const pastDate = new Date();- pastDate.setFullYear(pastDate.getFullYear() - 1); // 1 year ago- expect(isApiKeyExpired(pastDate)).toBe(true);- });-it('should return true when expiration date is exactly now or just passed', () => {const now = new Date();now.setSeconds(now.getSeconds() - 1); // 1 second agoexpect(isApiKeyExpired(now)).toBe(true);});-- it('should handle edge case of expiration date being very close to now', () => {- const almostNow = new Date();- almostNow.setMilliseconds(almostNow.getMilliseconds() - 1); // 1ms ago- expect(isApiKeyExpired(almostNow)).toBe(true);- });});describe('validateApiKeyFormat', () => {- it('should validate correct API key format', () => {- const validKey = `${API_KEY_PREFIX}1234567890abcdef`;- expect(validateApiKeyFormat(validKey)).toBe(true);- });-- it('should accept keys with only numbers', () => {- const validKey = `${API_KEY_PREFIX}1234567890123456`;- expect(validateApiKeyFormat(validKey)).toBe(true);- });-- it('should accept keys with only lowercase letters', () => {- const validKey = `${API_KEY_PREFIX}abcdefabcdefabcd`;- expect(validateApiKeyFormat(validKey)).toBe(true);- });-it('should accept keys with mixed alphanumeric characters', () => {const validKey = `${API_KEY_PREFIX}abc123def456789a`;expect(validateApiKeyFormat(validKey)).toBe(true);});-- it('should reject keys without the configured prefix', () => {- const invalidKey = '1234567890abcdef';- expect(validateApiKeyFormat(invalidKey)).toBe(false);- });-it('should reject keys with wrong prefix', () => {const invalidKey = 'lb-1234567890abcdef';expect(validateApiKeyFormat(invalidKey)).toBe(false);@@ -101,17 +50,14 @@ describe('apiKey', () => {const invalidKey = `${API_KEY_PREFIX}123456789abcde`;expect(validateApiKeyFormat(invalidKey)).toBe(false);});-it('should reject keys that are too long', () => {const invalidKey = `${API_KEY_PREFIX}1234567890abcdef0`;expect(validateApiKeyFormat(invalidKey)).toBe(false);});-it('should reject keys with uppercase letters', () => {const invalidKey = `${API_KEY_PREFIX}1234567890ABCDEF`;expect(validateApiKeyFormat(invalidKey)).toBe(false);});-it('should reject keys with special characters', () => {const invalidKey = `${API_KEY_PREFIX}1234567890abcd-f`;expect(validateApiKeyFormat(invalidKey)).toBe(false);@@ -120,12 +66,6 @@ describe('apiKey', () => {it('should reject empty string', () => {expect(validateApiKeyFormat('')).toBe(false);});-- it('should reject keys with spaces', () => {- const invalidKey = `${API_KEY_PREFIX}1234567890abcd f`;- expect(validateApiKeyFormat(invalidKey)).toBe(false);- });-it('should validate generated keys', () => {const generatedKey = generateApiKey();expect(validateApiKeyFormat(generatedKey)).toBe(true);diff --git a/packages/utils/src/mimeType.test.ts b/packages/utils/src/mimeType.test.tsindex 5fea8998692..b270f0f4837 100644--- a/packages/utils/src/mimeType.test.ts+++ b/packages/utils/src/mimeType.test.ts@@ -24,53 +24,6 @@ describe('getMimeType', () => {expect(getMimeType('script.py')).toBe('text/x-python');expect(getMimeType('/path/to/script.py')).toBe('text/x-python');});-- it('should return correct MIME type for Go files', () => {- expect(getMimeType('main.go')).toBe('text/x-go');- expect(getMimeType('/src/main.go')).toBe('text/x-go');- });-- it('should return correct MIME type for Rust files', () => {- expect(getMimeType('lib.rs')).toBe('text/x-rust');- expect(getMimeType('/src/lib.rs')).toBe('text/x-rust');- });-- it('should return correct MIME type for Ruby files', () => {- expect(getMimeType('app.rb')).toBe('text/x-ruby');- });-- it('should return correct MIME type for Kotlin files', () => {- expect(getMimeType('Main.kt')).toBe('text/x-kotlin');- });-- it('should return correct MIME type for Scala files', () => {- expect(getMimeType('App.scala')).toBe('text/x-scala');- });-- it('should return correct MIME type for Swift files', () => {- expect(getMimeType('ContentView.swift')).toBe('text/x-swift');- });-- it('should return correct MIME type for Haskell files', () => {- expect(getMimeType('Main.hs')).toBe('text/x-haskell');- });-- it('should return correct MIME type for Lua files', () => {- expect(getMimeType('script.lua')).toBe('text/x-lua');- });-- it('should return correct MIME type for Perl files', () => {- expect(getMimeType('script.pl')).toBe('text/x-perl');- });-- it('should return correct MIME type for R files', () => {- expect(getMimeType('analysis.r')).toBe('text/x-r');- });-- it('should return correct MIME type for Clojure files', () => {- expect(getMimeType('core.clj')).toBe('text/x-clojure');- });-it('should return correct MIME type for Elixir files (.ex)', () => {expect(getMimeType('app.ex')).toBe('text/x-elixir');});@@ -78,24 +31,6 @@ describe('getMimeType', () => {it('should return correct MIME type for Elixir script files (.exs)', () => {expect(getMimeType('mix.exs')).toBe('text/x-elixir');});-- it('should return correct MIME type for Svelte files', () => {- expect(getMimeType('App.svelte')).toBe('text/x-svelte');- });-- it('should return correct MIME type for Vue files', () => {- expect(getMimeType('App.vue')).toBe('text/x-vue');- });-- it('should return correct MIME type for Verilog files', () => {- expect(getMimeType('adder.v')).toBe('text/x-verilog');- expect(getMimeType('/rtl/top.v')).toBe('text/x-verilog');- });-- it('should return correct MIME type for SystemVerilog files', () => {- expect(getMimeType('alu_top.sv')).toBe('text/x-systemverilog');- expect(getMimeType('/rtl/tb.sv')).toBe('text/x-systemverilog');- });});describe('case insensitivity for extensions', () => {@@ -124,38 +59,9 @@ describe('getMimeType', () => {it('should return correct MIME type for JSON files', () => {expect(getMimeType('config.json')).toBe('application/json');});-- it('should return correct MIME type for HTML files', () => {- expect(getMimeType('index.html')).toBe('text/html');- });-- it('should return correct MIME type for CSS files', () => {- expect(getMimeType('styles.css')).toBe('text/css');- });-it('should return correct MIME type for PNG images', () => {expect(getMimeType('photo.png')).toBe('image/png');});-- it('should return correct MIME type for JPEG images', () => {- expect(getMimeType('photo.jpg')).toBe('image/jpeg');- });-- it('should return correct MIME type for PDF files', () => {- expect(getMimeType('document.pdf')).toBe('application/pdf');- });-- it('should return correct MIME type for XML files', () => {- expect(getMimeType('data.xml')).toBe('application/xml');- });-- it('should return correct MIME type for plain text files', () => {- expect(getMimeType('readme.txt')).toBe('text/plain');- });-- it('should return correct MIME type for Markdown files', () => {- expect(getMimeType('README.md')).toBe('text/markdown');- });});describe('fallback to application/octet-stream', () => {diff --git a/packages/utils/src/time.test.ts b/packages/utils/src/time.test.tsindex c5d8046fa2e..88c1a42004d 100644--- a/packages/utils/src/time.test.ts+++ b/packages/utils/src/time.test.ts@@ -67,20 +67,6 @@ describe('time utilities', () => {expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-01-01 00:00:00');});-- it('should work correctly for Q3 (September)', () => {- vi.setSystemTime(new Date('2024-09-15T14:30:45.123'));- const result = thisQuarter();-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-07-01 00:00:00');- });-- it('should work correctly for Q4 (December)', () => {- vi.setSystemTime(new Date('2024-12-15T14:30:45.123'));- const result = thisQuarter();-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-10-01 00:00:00');- });});describe('thisYear', () => {@@ -97,18 +83,6 @@ describe('time utilities', () => {expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-15 11:00:00');});-- it('should handle 0 hours ago', () => {- const result = hoursAgo(0);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-15 14:00:00');- });-- it('should handle large hour values (cross day boundary)', () => {- const result = hoursAgo(25);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-14 13:00:00');- });});describe('daysAgo', () => {@@ -117,18 +91,6 @@ describe('time utilities', () => {expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-08 00:00:00');});-- it('should handle 0 days ago (today)', () => {- const result = daysAgo(0);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-15 00:00:00');- });-- it('should handle large day values (cross month boundary)', () => {- const result = daysAgo(30);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-05-16 00:00:00');- });});describe('weeksAgo', () => {@@ -137,12 +99,6 @@ describe('time utilities', () => {expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-05-26 00:00:00');});-- it('should handle 0 weeks ago (this week)', () => {- const result = weeksAgo(0);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-09 00:00:00');- });});describe('monthsAgo', () => {@@ -151,13 +107,6 @@ describe('time utilities', () => {expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-03-01 00:00:00');});-- it('should handle 0 months ago (this month)', () => {- const result = monthsAgo(0);-- expect(result.format('YYYY-MM-DD HH:mm:ss')).toBe('2024-06-01 00:00:00');- });-it('should handle cross year boundary', () => {const result = monthsAgo(12);@@ -201,21 +150,6 @@ describe('time utilities', () => {expect(result).toBe('20240205_010203');});-- it('should handle end of year date', () => {- const date = new Date('2024-12-31T00:00:00.000');- const result = getYYYYmmddHHMMss(date);-- expect(result).toBe('20241231_000000');- });-- it('should handle leap year date', () => {- const date = new Date('2024-02-29T12:30:45.789');- const result = getYYYYmmddHHMMss(date);-- expect(result).toBe('20240229_123045');- });-it('should work with the current mocked time', () => {const date = new Date('2024-06-15T14:30:45.123');const result = getYYYYmmddHHMMss(date);@@ -264,12 +198,6 @@ describe('time utilities', () => {const date = '2024-06-15'; // 0 days before 2024-06-15expect(isNewReleaseDate(date)).toBe(true);});-- it('should return true if date is exactly 13 days ago', () => {- const date = '2024-06-02'; // 13 days before 2024-06-15- expect(isNewReleaseDate(date)).toBe(true);- });-it('should return false if date is 15 days ago', () => {const date = '2024-05-31'; // 15 days before 2024-06-15expect(isNewReleaseDate(date)).toBe(false);@@ -279,13 +207,10 @@ describe('time utilities', () => {const date = '2024-06-16'; // 1 day after 2024-06-15expect(isNewReleaseDate(date)).toBe(true);});-- it('should work with real model release date (gemini-3-pro-preview)', () => {- // Released at 2025-11-18, system time is 2024-06-15, so it's in future- const date = '2025-11-18';+ it('should return true if date is exactly 13 days ago', () => {+ const date = '2024-06-02'; // 13 days before 2024-06-15expect(isNewReleaseDate(date)).toBe(true);});-it('should work with custom days', () => {const date = '2024-06-09'; // 6 days ago from 2024-06-15expect(isNewReleaseDate(date, 7)).toBe(true);diff --git a/packages/utils/src/url.test.ts b/packages/utils/src/url.test.tsindex a46c9ee9313..3e25f10afaf 100644--- a/packages/utils/src/url.test.ts+++ b/packages/utils/src/url.test.ts@@ -37,16 +37,6 @@ describe('pathString', () => {expect(result).toBe('https://www.example.com/home');});- it('should handle path with hostname', () => {- const result = pathString('//www.example.com/home');- expect(result).toBe('https://www.example.com/home');- });-- it('should handle path with port number', () => {- const result = pathString('//www.example.com:8080/home');- expect(result).toBe('https://www.example.com:8080/home');- });-it('should handle path with special characters', () => {const result = pathString('/home/测试');expect(result).toBe('/home/%E6%B5%8B%E8%AF%95');@@ -64,122 +54,12 @@ describe('inferContentTypeFromImageUrl', () => {expect(result).toBe('image/png');});- it('should handle URLs with hash fragments', () => {- const result = inferContentTypeFromImageUrl('https://example.com/image.jpg#section');- expect(result).toBe('image/jpeg');- });-it('should throw error when no extension', () => {expect(() => {inferContentTypeFromImageUrl('https://example.com/image');}).toThrow('Invalid image url: https://example.com/image');});- it('should throw error when only dot without extension', () => {- expect(() => {- inferContentTypeFromImageUrl('https://example.com/image.');- }).toThrow('Invalid image url: https://example.com/image.');- });-- it('should handle multiple dots in path', () => {- const result = inferContentTypeFromImageUrl('https://example.com/my.folder/image.test.png');- expect(result).toBe('image/png');- });-- it('should handle complex query parameters and hash combination', () => {- const result = inferContentTypeFromImageUrl(- 'https://example.com/image.jpeg?width=800&height=600&format=jpeg#preview',- );- expect(result).toBe('image/jpeg');- });-- it('should handle mixed case extensions', () => {- const result = inferContentTypeFromImageUrl('https://example.com/image.JpEg');- expect(result).toBe('image/jpeg');- });-- it('should throw error for invalid URLs', () => {- expect(() => {- inferContentTypeFromImageUrl('invalid-url');- }).toThrow('Invalid image url: invalid-url');- });-- it('should throw error for empty string', () => {- expect(() => {- inferContentTypeFromImageUrl('');- }).toThrow('Invalid image url: ');- });-- it('should throw error for non-image extensions', () => {- expect(() => {- inferContentTypeFromImageUrl('https://example.com/document.txt');- }).toThrow('Invalid image url: https://example.com/document.txt');- });-- it('should throw error for unknown extensions', () => {- expect(() => {- inferContentTypeFromImageUrl('https://example.com/file.unknownext');- }).toThrow('Invalid image url: https://example.com/file.unknownext');- });-- it('should handle URLs with port numbers', () => {- const result = inferContentTypeFromImageUrl('https://example.com:8080/image.png');- expect(result).toBe('image/png');- });-- it('should handle deeply nested paths', () => {- const result = inferContentTypeFromImageUrl(- 'https://cdn.example.com/assets/images/gallery/2024/photo.jpg',- );- expect(result).toBe('image/jpeg');- });-- it('should handle encoded filenames', () => {- const result = inferContentTypeFromImageUrl(- 'https://example.com/images/%E5%9B%BE%E7%89%87.png',- );- expect(result).toBe('image/png');- });-- it('should handle protocol-relative URLs', () => {- const result = inferContentTypeFromImageUrl('//example.com/image.webp');- expect(result).toBe('image/webp');- });-- it('should handle relative paths', () => {- const result = inferContentTypeFromImageUrl('generations/images/photo.jpg');- expect(result).toBe('image/jpeg');- });-- it('should handle relative paths with complex filenames', () => {- const result = inferContentTypeFromImageUrl(- 'generations/images/2NPfAQAMNxXPi82mzOHog_1056x1136_20250702_110911_raw.png',- );- expect(result).toBe('image/png');- });-- it('should handle relative paths with query parameters', () => {- const result = inferContentTypeFromImageUrl('images/photo.webp?v=123');- expect(result).toBe('image/webp');- });-- it('should handle relative paths with hash fragments', () => {- const result = inferContentTypeFromImageUrl('assets/images/banner.gif#preview');- expect(result).toBe('image/gif');- });-- it('should throw error for single character extensions (if no valid MIME type)', () => {- expect(() => {- inferContentTypeFromImageUrl('https://example.com/file.x');- }).toThrow('Invalid image url: https://example.com/file.x');- });-- it('should throw error for dot at end of path', () => {- expect(() => {- inferContentTypeFromImageUrl('https://example.com/path/.');- }).toThrow('Invalid image url: https://example.com/path/.');- });-it('should handle malformed URLs that result in no valid extension', () => {// These URLs will be processed by inferFileExtensionFromImageUrl and return empty stringconst invalidUrls = [@@ -215,6 +95,16 @@ describe('inferContentTypeFromImageUrl', () => {expect(result).toBe(expected);});});++ it('should handle multiple dots in path', () => {+ const result = inferContentTypeFromImageUrl('https://example.com/my.folder/image.test.png');+ expect(result).toBe('image/png');+ });++ it('should handle relative paths', () => {+ const result = inferContentTypeFromImageUrl('generations/images/photo.jpg');+ expect(result).toBe('image/jpeg');+ });});describe('inferFileExtensionFromImageUrl', () => {@@ -223,11 +113,6 @@ describe('inferFileExtensionFromImageUrl', () => {expect(result).toBe('png');});- it('should handle mixed case extensions', () => {- const result = inferFileExtensionFromImageUrl('https://example.com/image.JpEg');- expect(result).toBe('jpeg');- });-it('should handle URLs with query parameters', () => {const result = inferFileExtensionFromImageUrl('https://example.com/image.jpg?v=123&size=large');expect(result).toBe('jpg');@@ -238,41 +123,16 @@ describe('inferFileExtensionFromImageUrl', () => {expect(result).toBe('png');});- it('should handle multiple dots in path', () => {- const result = inferFileExtensionFromImageUrl('https://example.com/my.folder/image.test.webp');- expect(result).toBe('webp');- });-it('should return empty string when no extension', () => {const result = inferFileExtensionFromImageUrl('https://example.com/image');expect(result).toBe('');});- it('should return empty string when only dot without extension', () => {- const result = inferFileExtensionFromImageUrl('https://example.com/image.');- expect(result).toBe('');- });-it('should return empty string for non-image extensions', () => {const result = inferFileExtensionFromImageUrl('https://example.com/document.txt');expect(result).toBe('');});- it('should return empty string for other format extensions', () => {- const result = inferFileExtensionFromImageUrl('https://example.com/video.mp4');- expect(result).toBe('');- });-- it('should handle invalid URLs and return empty string', () => {- const result = inferFileExtensionFromImageUrl('invalid-url');- expect(result).toBe('');- });-- it('should handle empty string URLs and return empty string', () => {- const result = inferFileExtensionFromImageUrl('');- expect(result).toBe('');- });-it('should handle all supported image extensions', () => {const supportedExtensions = ['webp', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'tiff', 'tif'];@@ -282,51 +142,15 @@ describe('inferFileExtensionFromImageUrl', () => {});});- it('should handle URLs with port numbers', () => {- const result = inferFileExtensionFromImageUrl('https://example.com:8080/image.jpg');- expect(result).toBe('jpg');- });-- it('should handle subdomain URLs', () => {- const result = inferFileExtensionFromImageUrl('https://cdn.example.com/images/photo.webp');+ it('should handle multiple dots in path', () => {+ const result = inferFileExtensionFromImageUrl('https://example.com/my.folder/image.test.webp');expect(result).toBe('webp');});- it('should handle deep path URLs', () => {- const result = inferFileExtensionFromImageUrl(- 'https://example.com/assets/images/gallery/photo.png',- );- expect(result).toBe('png');- });-- it('should handle encoded URLs', () => {- const result = inferFileExtensionFromImageUrl(- 'https://example.com/images/%E5%9B%BE%E7%89%87.jpg',- );- expect(result).toBe('jpg');- });-it('should handle relative paths', () => {const result = inferFileExtensionFromImageUrl('generations/images/photo.jpg');expect(result).toBe('jpg');});-- it('should handle relative paths with complex filenames', () => {- const result = inferFileExtensionFromImageUrl(- 'generations/images/2NPfAQAMNxXPi82mzOHog_1056x1136_20250702_110911_raw.png',- );- expect(result).toBe('png');- });-- it('should handle relative paths with query parameters', () => {- const result = inferFileExtensionFromImageUrl('images/photo.webp?v=123');- expect(result).toBe('webp');- });-- it('should handle relative paths with hash fragments', () => {- const result = inferFileExtensionFromImageUrl('assets/images/banner.gif#preview');- expect(result).toBe('gif');- });});describe('isDesktopLocalStaticServerUrl', () => {