Files
ccs/tests/unit/cliproxy/thinking-validator.test.ts
T
Kai (Tam Nhu) TranGitHubgithub-actions[bot] <github-actions[bot]@users.noreply.github.com>
051805074e feat: account safety, quota monitoring, and stability fixes (#530)
* fix(cliproxy): migrate deprecated gemini-claude-* model names to upstream claude-* names (#515)

* fix(cliproxy): migrate deprecated gemini-claude-* model names to upstream claude-* names

CLIProxyAPI registry no longer recognizes the gemini-claude-* prefix convention.
Model names in catalog, base config, and user settings are migrated to upstream
claude-* names. Auto-migration in env-builder rewrites existing user settings on
load and persists the change.

Closes #513

* fix: address code review feedback — sync UI layer and add migration tests

- Sync UI isNativeGeminiModel() with backend (remove gemini-claude- exclusion)
- Update UI model catalog agy entries from gemini-claude-* to claude-*
- Update CI/CD workflow and code-reviewer default model names
- Add unit tests for migrateDeprecatedModelNames() logic

* fix(hooks): isolate image type check before error-prone processing (#514)

* fix(hooks): isolate image type check before error-prone processing

Restructure processHook() into two phases so non-image Read calls
never see hook error messages. Phase 1 defensively checks tool name
and file extension, exiting 0 silently on any failure. Phase 2 only
runs for confirmed image/PDF files where errors are relevant.

Closes #511

* fix(hooks): sync image analyzer hook file on every profile launch

Add installImageAnalyzerHook() call to cliproxy executor, matching
the existing installWebSearchHook() pattern. This ensures the .cjs
file in ~/.ccs/hooks/ gets refreshed from the npm package on every
launch, so users receive hook updates after npm update.

* chore(release): 7.41.0-dev.1 [skip ci]

* fix(cliproxy): add fork:true for Claude model aliases in config generator (#523)

Config generator now outputs fork:true for Claude model alias entries,
ensuring both upstream (claude-*) and aliased (gemini-claude-*) model
names appear in /v1/models listings. Also preserves fork flag when
parsing user-added aliases during config regeneration.

Bumps config version to v7 to trigger regeneration on next ccs doctor.

Closes #522

* chore(release): 7.41.0-dev.2 [skip ci]

* feat(cliproxy): add account safety guards to prevent Google account bans (#516)

* feat(cliproxy): add account safety guards to prevent Google account bans

Implements cross-provider isolation to prevent Google from flagging
concurrent OAuth usage across different client IDs (ref: #509, #512).

Three pillars:
1. Auto-pause enforcement at session launch — conflicting accounts in
   other Google OAuth providers are paused so CLIProxyAPI can't use them,
   restored on session exit with crash recovery via auto-paused.json
2. Ban/disable detection — error responses matching Google ban patterns
   auto-pause the affected account to prevent further damage
3. Cross-provider conflict warnings during OAuth registration

Key design decisions:
- PID-based session tracking for crash recovery (dead PID = restore)
- Timestamp comparison prevents restoring ban-paused accounts on exit
- Schema validation on auto-paused.json prevents corrupted state
- Falls back to warn-only when another session is managing isolation

* fix(cliproxy): address code review feedback (attempt 1/5)

- Re-read auto-paused.json before write in enforceProviderIsolation to
  reduce concurrent write race window
- Use actual email from registry for display instead of raw accountId
- Export maskEmail for testability
- Add 27 unit tests covering ban detection, email masking,
  cross-provider duplicate detection, enforcement lifecycle,
  crash recovery, and timestamp-guarded restore

* fix(cliproxy): address remaining review feedback (attempt 2/5)

- Add handleBanDetection test verifying account pause on ban error
- Add warnCrossProviderDuplicates tests (true/false/non-Google)
- Document PID reuse limitation in isPidAlive JSDoc comment

* chore(release): 7.41.0-dev.3 [skip ci]

* feat(cliproxy): runtime quota monitoring during active sessions (#529)

* feat(cliproxy): add runtime quota monitoring during active sessions

Adds adaptive background quota polling to detect and respond to quota
exhaustion during active CLIProxy sessions. Prevents rate-limit-driven
account bans by auto-cooling exhausted accounts and switching defaults.

- Adaptive polling: 300s normal, 60s at 20% threshold, stops at 0%
- Stderr warnings at 20%, boxed exhaustion alerts at 0%
- Cooldown + default switch on exhaustion (existing patterns)
- Configurable via quota_management.runtime_monitor in config.yaml
- Timer.unref() prevents blocking process exit
- monitorStopped guard for in-flight poll safety

Closes #524

* fix: address code review feedback (attempt 1/5)

- M1: Round quotaPercent display with Math.round() to avoid ugly floats
- M2: Rename exhaust_threshold -> exhaustion_threshold for consistency
  with existing auto.exhaustion_threshold config field
- M3: Replace async not.toThrow() with direct await assertion pattern

* fix: address code review feedback (attempt 2/5)

- Remove .claude/agent-memory/ from tracking and add to .gitignore
- Unify cooldown_minutes default to 5 (was 10 in runtime_monitor, 5 in auto)
- Add threshold validation in startQuotaMonitor (warn > exhaustion)
- Document intentional post-switch monitoring gap in code comment

* chore(release): 7.41.0-dev.4 [skip ci]

* fix(cliproxy): mask email in ban detection and fix JSDoc default

- Use maskEmail() in handleBanDetection output for consistency
- Fix cooldown_minutes JSDoc: default is 5, not 10

* chore(release): 7.41.0-dev.5 [skip ci]

* fix(cliproxy): address all review feedback (Low + informational)

- Add sync constraint comment on process.exit handler (executor)
- Add TOCTOU race acceptability comment (account-safety)
- Mask email in handleQuotaExhaustion reason string
- Use realistic exhaustion_threshold (5) in test configs

* chore(release): 7.41.0-dev.6 [skip ci]

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-02-12 00:48:29 +07:00

172 lines
6.1 KiB
TypeScript

/**
* Thinking Validator Unit Tests
*
* Tests for thinking budget validation logic
*/
import { describe, it, expect } from 'bun:test';
import {
validateThinking,
THINKING_LEVEL_BUDGETS,
VALID_THINKING_LEVELS,
THINKING_OFF_VALUES,
THINKING_BUDGET_MIN,
THINKING_BUDGET_MAX,
THINKING_BUDGET_DEFAULT_MIN,
} from '../../../src/cliproxy/thinking-validator';
describe('Thinking Validator', () => {
describe('Constants', () => {
it('should export valid budget bounds', () => {
expect(THINKING_BUDGET_MIN).toBe(0);
expect(THINKING_BUDGET_MAX).toBe(100000);
expect(THINKING_BUDGET_DEFAULT_MIN).toBe(512);
});
it('should export valid thinking levels', () => {
expect(VALID_THINKING_LEVELS).toContain('minimal');
expect(VALID_THINKING_LEVELS).toContain('low');
expect(VALID_THINKING_LEVELS).toContain('medium');
expect(VALID_THINKING_LEVELS).toContain('high');
expect(VALID_THINKING_LEVELS).toContain('xhigh');
expect(VALID_THINKING_LEVELS).toContain('auto');
});
it('should export level budget mappings', () => {
expect(THINKING_LEVEL_BUDGETS.minimal).toBe(512);
expect(THINKING_LEVEL_BUDGETS.low).toBe(1024);
expect(THINKING_LEVEL_BUDGETS.medium).toBe(8192);
expect(THINKING_LEVEL_BUDGETS.high).toBe(24576);
expect(THINKING_LEVEL_BUDGETS.xhigh).toBe(32768);
});
it('should export off values', () => {
expect(THINKING_OFF_VALUES).toContain('off');
expect(THINKING_OFF_VALUES).toContain('none');
expect(THINKING_OFF_VALUES).toContain('disabled');
expect(THINKING_OFF_VALUES).toContain('0');
});
});
describe('Off values', () => {
it('should handle "off" value', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', 'off');
expect(result.valid).toBe(true);
expect(result.value).toBe('off');
expect(result.warning).toBeUndefined();
});
it('should handle "none" value', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', 'none');
expect(result.valid).toBe(true);
expect(result.value).toBe('off');
});
it('should handle "disabled" value', () => {
const result = validateThinking('agy', 'claude-sonnet-4-20250514', 'disabled');
expect(result.valid).toBe(true);
expect(result.value).toBe('off');
});
it('should handle "0" string as off', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', '0');
expect(result.valid).toBe(true);
expect(result.value).toBe('off');
});
it('should be case-insensitive for off values', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', 'OFF');
expect(result.valid).toBe(true);
expect(result.value).toBe('off');
});
});
describe('Named levels (levels-type models like Gemini)', () => {
it('should accept valid level names', () => {
const levels = ['low', 'medium', 'high'];
for (const level of levels) {
const result = validateThinking('gemini', 'gemini-3-pro-preview', level);
expect(result.valid).toBe(true);
}
});
it('should be case-insensitive for level names', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', 'HIGH');
expect(result.valid).toBe(true);
});
it('should map numeric budgets to closest level for level-type models', () => {
// Level-type models convert budget to closest named level
const result = validateThinking('gemini', 'gemini-3-pro-preview', 8192);
expect(result.valid).toBe(true);
expect(typeof result.value).toBe('string'); // Should be a level name
expect(result.warning).toContain('Mapped');
});
});
describe('Budget-type models (like Claude via agy)', () => {
// Claude models via agy use budget-type thinking
const budgetModel = 'claude-sonnet-4-5-thinking';
it('should accept valid numeric budget', () => {
const result = validateThinking('agy', budgetModel, 8192);
expect(result.valid).toBe(true);
expect(result.value).toBe(8192);
});
it('should accept numeric string budget', () => {
const result = validateThinking('agy', budgetModel, '8192');
expect(result.valid).toBe(true);
expect(result.value).toBe(8192);
});
it('should reject negative budgets', () => {
const result = validateThinking('agy', budgetModel, -100);
expect(result.valid).toBe(false);
expect(result.warning).toContain('Negative');
});
it('should clamp excessively high budgets', () => {
const result = validateThinking('agy', budgetModel, 999999999);
expect(result.valid).toBe(true);
expect(result.warning).toContain('Clamped');
});
it('should reject partial numeric parses like "123abc"', () => {
const result = validateThinking('agy', budgetModel, '123abc');
// Should either fail or find closest level match, not parse as 123
expect(result.value).not.toBe(123);
});
});
describe('Auto value', () => {
it('should accept auto value', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', 'auto');
expect(result.valid).toBe(true);
expect(result.value).toBe('auto');
});
});
describe('Unknown models', () => {
it('should pass through value for unknown models with warning', () => {
const result = validateThinking('gemini', 'unknown-model-xyz', 'high');
expect(result.valid).toBe(true);
expect(result.warning).toContain('unknown');
});
});
describe('Edge cases', () => {
it('should handle whitespace in input', () => {
const result = validateThinking('gemini', 'gemini-3-pro-preview', ' high ');
expect(result.valid).toBe(true);
});
it('should handle empty string by passing through for unknown', () => {
// Empty string on known model goes to level/budget validation
const result = validateThinking('gemini', 'gemini-3-pro-preview', '');
// For level-type models, empty string will try to match levels
expect(result.valid).toBeDefined(); // Just check it doesn't crash
});
});
});