Skip to content

Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management and step Collapse #2088

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

lengyueyang
Copy link

Separate toggleable buttons from commands
This commit implements a complete separation between toggleable buttons and standard commands, allowing developers to independently define and configure these two distinct types of interactive UI elements.

Key features:

  • Created dedicated IToggleCommand interface distinct from ICommand
  • Added new backend method set_toggle_commands for setting toggleable buttons
  • Implemented toggleCommandsState for frontend state management
  • Updated frontend components to use the new toggle command state
  • Added persistent toggle functionality that preserves state between message submissions

Technical implementation:

  • Added ToggleCommandDict type in backend and removed toggleable property from CommandDict
  • Created toggleCommandsState for frontend state management
  • Modified ToggleableButtons component to use the new toggleCommand state
  • Added socket event handling for set_toggle_commands events
  • Implemented automatic reset of non-persistent toggles after message submission
  • Created demo example showing how to use separated toggle commands

Usage example:

commands = [
    {"id": "Search", "icon": "globe", "description": "Web search", "button": True}
]

toggle_commands = [
    {"id": "Debug", "icon": "bug", "description": "Show debug info", "persistent": True},
    {"id": "Thinking", "icon": "brain", "description": "Show thinking process"}
]

@cl.on_chat_start
async def start():
    await cl.context.emitter.set_commands(commands)
    await cl.context.emitter.set_toggle_commands(toggle_commands)

This implementation enhances UI interaction flexibility and provides developers with more granular control options.

feat(InfoPanel): Enhance information panel persistence and state management

  • Implement localStorage for saving panel data and title
  • Add visibility change listeners to restore state when returning from other tabs
  • Optimize state update logic to reduce unnecessary re-renders
  • Maintain global state in backend to ensure panel visibility after message interactions
  • Add data validation logic to prevent rendering with empty data

These improvements ensure users can continuously view the information panel throughout their chat session, including after sending messages, refreshing the page, and navigating back from other pages.

import chainlit as cl

@cl.header_auth_callback
def header_auth_callback(username: str):
  # Verify the signature of a token in the header (ex: jwt token)
  # or check that the value is matching a row from your database
  if username == "test-value":
    return cl.User(identifier="admin", metadata={"role": "admin", "provider": "header"})
  else:
    return cl.User(identifier="guest", metadata={})

from chainlit.sidebar import InfoPanelSidebar
import logging
import inspect

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@cl.on_chat_start
async def on_chat_start():
    """
    在聊天开始时,设置信息面板并发送到前端
    """
    logger.info(f"Chat started - preparing to send info panel data (function: {inspect.currentframe().f_code.co_name})")

    # 信息面板数据,以键值对形式定义
    info_data = {
        "性别": "男",
        "年龄": "58岁",
        "MRN": "002737777",
        "Episode": "2238787",
    }

    # 发送信息面板数据到前端显示
    logger.info(f"Sending info panel data to frontend: {info_data}")
    try:
        await InfoPanelSidebar.set_info_panel(info_data, title="患者信息")
        logger.info("Info panel data sent successfully")
    except Exception as e:
        logger.error(f"Error sending info panel data: {e}", exc_info=True)

    await cl.Message(
        content="您好,我是医疗助手。信息已经显示在左侧,请问有什么需要帮助的?"
    ).send()

@cl.on_message
async def on_message(message: cl.Message):
    pass

xiaowei.mao and others added 3 commits April 1, 2025 22:18
This commit implements a complete separation between toggleable buttons and standard commands, allowing developers to independently define and configure these two distinct types of interactive UI elements.

Key features:
- Created dedicated IToggleCommand interface distinct from ICommand
- Added new backend method set_toggle_commands for setting toggleable buttons
- Implemented toggleCommandsState for frontend state management
- Updated frontend components to use the new toggle command state
- Added persistent toggle functionality that preserves state between message submissions

Technical implementation:
- Added ToggleCommandDict type in backend and removed toggleable property from CommandDict
- Created toggleCommandsState for frontend state management
- Modified ToggleableButtons component to use the new toggleCommand state
- Added socket event handling for set_toggle_commands events
- Implemented automatic reset of non-persistent toggles after message submission
- Created demo example showing how to use separated toggle commands

Usage example:
```python
commands = [
    {"id": "Search", "icon": "globe", "description": "Web search", "button": True}
]

toggle_commands = [
    {"id": "Debug", "icon": "bug", "description": "Show debug info", "persistent": True},
    {"id": "Thinking", "icon": "brain", "description": "Show thinking process"}
]

@cl.on_chat_start
async def start():
    await cl.context.emitter.set_commands(commands)
    await cl.context.emitter.set_toggle_commands(toggle_commands)
```

This implementation enhances UI interaction flexibility and provides developers with more granular control options.
```
…gement

- Implement localStorage for saving panel data and title
- Add visibility change listeners to restore state when returning from other tabs
- Optimize state update logic to reduce unnecessary re-renders
- Maintain global state in backend to ensure panel visibility after message interactions
- Add data validation logic to prevent rendering with empty data

These improvements ensure users can continuously view the information panel throughout their chat session, including after sending messages, refreshing the page, and navigating back from other pages.
@dosubot dosubot bot added size:L This PR changes 100-499 lines, ignoring generated files. backend Pertains to the Python backend. frontend Pertains to the frontend. labels Apr 3, 2025
@lengyueyang lengyueyang changed the title Add Toggle-able Buttons on Chat and Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management #1938 #2002 Apr 3, 2025
@lengyueyang lengyueyang changed the title Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management #1938 #2002 Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management Apr 3, 2025
xiaowei.mao added 2 commits April 3, 2025 16:14
This commit includes several UX enhancements to the Chainlit components:
1. Step Component:
  - Add 'collapse' property to automatically collapse completed steps
  - Steps with 'collapse=True' will fold up once they're finished
  - Maintain backward compatibility with existing 'default_open' behavior

2. InfoPanel Component:
  - Improve InfoPanel behavior to hide by default when no data is sent
  - Add session-based tracking to prevent showing stale data across sessions
  - Clear localStorage when new sessions begin without panel data

3. Action Component:
  - Add customization options including background color and text color
  - Support 'fullWidth' layout for actions that should appear one per line
  - Implement custom styling through 'variant', 'size', and 'className' props
  - Fix icon display issues in fullWidth buttons by adding proper spacing
  - Optimize responsive layout for better mobile experience

Each feature includes accompanying example files demonstrating usage patterns.
@dosubot dosubot bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Apr 3, 2025
@lengyueyang lengyueyang changed the title Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management Add Toggle-able Buttons on Chat and Enhance information panel persistence and state management and step Collapse Apr 3, 2025
Fixed the following issues:
1. When starter.toggle_commands is an empty array, all toggleables (including persistent ones)
   are now set to inactive, making behavior consistent with commands handling
2. Fixed UI state and backend message synchronization issues, ensuring toggleables sent to
   backend match UI display
3. Improved state update logic, distinguishing between empty array and undefined toggle_commands
4. Added detailed logging for debugging and tracking state changes

Changes:
- Optimized toggle_commands handling logic in Starter.tsx
- Enhanced state monitoring in ToggleableButtons component
- Added debug logs to track toggleables state changes
- Fixed synchronization issues between state updates and message sending
```
This commit improves the history refresh mechanism by:
- Simplifying the `trigger_history_refresh` function to focus on the primary refresh method
- Moving history refresh from chat start to chat end to ensure updates are visible after session completion
- Removing redundant refresh attempts to improve performance
- Adding clearer logging messages for better debugging and monitoring
- Restructuring the code for better maintainability

These changes ensure that thread history is properly refreshed when needed, providing a better user experience while improving application efficiency.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Pertains to the Python backend. frontend Pertains to the frontend. size:XL This PR changes 500-999 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant