Skip to content

fix playground - #2153

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/playground
Nov 6, 2025
Merged

fix playground #2153
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/playground

Conversation

@seefs001

@seefs001 seefs001 commented Nov 3, 2025

Copy link
Copy Markdown
Collaborator

fix #2150

Summary by CodeRabbit

  • Refactor
    • Improved internal Base64 encoding implementation for consistent handling across the application.

@coderabbitai

coderabbitai Bot commented Nov 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Introduces a cross-environment Base64 encoding utility module that properly handles non-ASCII characters. Replaces direct btoa() calls in token and playground components with the new encodeToBase64() function. The helper provides environment-specific paths for Node.js (Buffer), browsers (window.btoa), and globalThis, with binary string conversion for proper encoding support.

Changes

Cohort / File(s) Summary
New Base64 helper module
web/src/helpers/base64.js
Adds encodeToBase64(value) function supporting Node.js (Buffer), browser (window.btoa), and globalThis environments. Includes toBinaryString(text) helper for reliable UTF-8 to binary conversion, enabling proper encoding of non-ASCII characters. Throws error if no encoding method available.
Helper exports
web/src/helpers/index.js
Re-exports all exports from ./base64 module to expose encodeToBase64 through central helpers index.
Token and Playground components
web/src/hooks/tokens/useTokensData.jsx, web/src/pages/Playground/index.jsx
Replaces direct btoa() calls with encodeToBase64() for cherryConfig and avatar SVG encoding, respectively.

Sequence Diagram

sequenceDiagram
    participant App as App Component
    participant Helper as encodeToBase64()
    participant Env as Runtime Environment
    
    App->>Helper: encodeToBase64(value)
    Helper->>Env: Detect environment
    
    alt Node.js with Buffer
        Env-->>Helper: Buffer available
        Helper->>Helper: Convert string → Buffer
        Helper->>Helper: Encode to Base64
    else Browser with btoa
        Env-->>Helper: window.btoa available
        Helper->>Helper: toBinaryString(value)
        Helper->>Helper: btoa(binary)
    else globalThis.btoa
        Env-->>Helper: globalThis.btoa available
        Helper->>Helper: toBinaryString(value)
        Helper->>Helper: globalThis.btoa(binary)
    else No encoding method
        Env-->>Helper: ✗ No method
        Helper-->>App: throw Error
    end
    
    Helper-->>App: Base64 encoded string
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Verify toBinaryString() correctly handles UTF-8 and non-ASCII characters (e.g., Chinese characters)
  • Confirm environment detection logic covers all target platforms and that fallback is appropriate
  • Validate that both component usage sites (token and playground) properly benefit from the fix, particularly addressing the Chinese username encoding issue (【bug】用户名为中文时,操练场打开空白,控制台报错 #2150)
  • Check error handling path when no Base64 encoding method is available

Poem

🐰 A bunny's wisdom in binary code,
When Chinese names graced the playground road,
UTF-8 troubles turned to bytes so clean,
Cross-browser magic—the best we've seen!
Base64 blessed, the encoding's bright,
No more blank screens—we got it right! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title Check ❓ Inconclusive The PR title "fix playground" is vague and generic, using non-descriptive language that does not clearly convey the specific nature of the fix. While the title does relate to the changeset (playground is involved), it fails to explain the core issue being addressed—specifically, the fix for Base64 encoding to support non-ASCII characters like Chinese usernames. The title provides insufficient meaningful information about what problem is being solved or how it is being solved, making it ambiguous to anyone scanning commit history. Consider revising the title to be more descriptive and specific, such as "Fix Base64 encoding for non-ASCII character usernames in playground" or "Handle Unicode characters in playground Base64 encoding." This would clearly communicate the specific issue being resolved and make the purpose of the changeset immediately apparent to future reviewers.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues Check ✅ Passed The PR directly addresses the core issue in #2150 by creating a cross-environment Base64 encoding helper that properly handles non-ASCII characters, including Chinese characters. The new encodeToBase64 function uses a toBinaryString helper to reliably convert Unicode strings to binary representation compatible with btoa, which is the root cause of the blank playground page and console errors. The changes replace direct btoa calls in useTokensData.jsx and Playground/index.jsx with this new helper, ensuring that usernames and other data containing Chinese characters are encoded correctly across all runtime environments. This implementation satisfies the objective to fix the playground blank page issue and prevent console errors for users with Chinese character usernames.
Out of Scope Changes Check ✅ Passed All code changes in this PR are directly related to resolving the Base64 encoding issue for non-ASCII characters in usernames. The new base64.js helper module provides the core fix, the re-export in helpers/index.js follows standard module pattern conventions, and both uses in useTokensData.jsx and Playground/index.jsx apply the fix to the relevant encoding locations. No changes appear to introduce unrelated functionality or modify unrelated areas of the codebase outside the scope of fixing the non-ASCII character encoding issue.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
web/src/helpers/base64.js (1)

37-56: Well-designed cross-environment Base64 encoding.

The implementation correctly handles Unicode characters across different environments:

  • Node.js: Uses Buffer.from(input, 'utf-8') for direct UTF-8 encoding
  • Browser: Uses window.btoa(toBinaryString(input)) to handle Unicode via binary string conversion
  • Fallback: Checks globalThis.btoa for other environments
  • Error handling: Throws descriptive error if no encoding method available

This properly fixes the root cause of issue #2150 where btoa() failed on Chinese characters.

Consider adding JSDoc documentation to clarify the Unicode handling behavior:

+/**
+ * Encodes a value to Base64 with full Unicode support.
+ * Handles non-ASCII characters (e.g., Chinese, emoji) by converting to UTF-8 bytes.
+ * @param {*} value - Value to encode (will be converted to string)
+ * @returns {string} Base64-encoded string
+ * @throws {Error} If Base64 encoding is unavailable in the current environment
+ */
 export const encodeToBase64 = (value) => {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00782aa and 025c725.

📒 Files selected for processing (4)
  • web/src/helpers/base64.js (1 hunks)
  • web/src/helpers/index.js (1 hunks)
  • web/src/hooks/tokens/useTokensData.jsx (2 hunks)
  • web/src/pages/Playground/index.jsx (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
web/src/pages/Playground/index.jsx (1)
web/src/helpers/base64.js (2)
  • encodeToBase64 (37-56)
  • encodeToBase64 (37-56)
web/src/hooks/tokens/useTokensData.jsx (1)
web/src/helpers/base64.js (2)
  • encodeToBase64 (37-56)
  • encodeToBase64 (37-56)
🔇 Additional comments (6)
web/src/helpers/index.js (1)

23-23: LGTM! Base64 utilities properly exposed.

The re-export correctly makes encodeToBase64 available through the central helpers index, maintaining consistency with the existing module structure.

web/src/pages/Playground/index.jsx (2)

50-50: Good addition of Unicode-safe encoding utility.

The import of encodeToBase64 enables proper handling of non-ASCII characters in the avatar generation.


64-77: Critical fix: This resolves the Chinese username bug.

Replacing btoa with encodeToBase64 correctly handles Unicode characters in usernames. The native btoa() throws errors with Chinese characters because it only accepts Latin1 (0-255) code points, while encodeToBase64 properly converts Unicode to UTF-8 bytes before Base64 encoding.

This directly fixes issue #2150 where Chinese usernames caused blank playground pages and console errors.

web/src/hooks/tokens/useTokensData.jsx (2)

23-29: Good addition of encoding utility to imports.

The encodeToBase64 import complements existing helper utilities and enables Unicode-safe encoding.


124-155: Consistent Unicode-safe encoding for config data.

Replacing btoa with encodeToBase64 ensures that cherryConfig JSON can be safely encoded even if it contains non-ASCII characters. While the current config fields (baseUrl, apiKey, id) are typically ASCII, this change provides robustness and consistency with the encoding approach used elsewhere in the PR.

web/src/helpers/base64.js (1)

20-35: Solid Unicode-to-binary-string conversion.

The toBinaryString helper correctly converts Unicode strings to binary strings suitable for btoa:

  • Primary path uses TextEncoder to produce UTF-8 bytes, then converts each byte to a character
  • Fallback uses encodeURIComponent with regex replacement to achieve the same result

Both paths correctly handle non-ASCII characters by representing UTF-8 bytes as a binary string (where each character has code point 0-255).

@Calcium-Ion
Calcium-Ion merged commit fb610e6 into QuantumNous:main Nov 6, 2025
1 check passed
Xiaoshuaiawd referenced this pull request in Xiaoshuaiawd/new-api Nov 12, 2025
* main: (77 commits)
  refactor(adaptor): Comment out enable_thinking logic for clarity and future adjustments
  fix GetChannelKey AdminAuth -> RootAuth
  fix GetChannelKey AdminAuth -> RootAuth
  feat: vidu reference2video only viduq2
  feat: vidu specify reference2video via metadata action
  同步多语言README文档
  chore: Update README.md for improved structure and clarity, including new sections for partners, acknowledgments, and deployment instructions
  feat: replicate channel flux model
  feat: ShouldPreserveThinkingSuffix (#2189)
  fix(channel): 当没有可用密钥时返回错误而不是第一个密钥
  fix: update tag normalization regex
  feat: restrict automatic channel testing to master node only
  feat: EditTagModal header && param (#2159)
  add custom tool (#2157)
  fix playground (#2153)
  feat: add TASK_PRICE_PATCH environment variable for per-task billing configuration
  feat:  EditTokenModal 中针对用户创建的 token 默认无限额度
  feat: add environment variable switch for critical rate limit
  feat: enhance Ali video request processing with resolution mapping and size validation
  fix: logger
  ...
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

【bug】用户名为中文时,操练场打开空白,控制台报错

2 participants