Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): improve wizard flow, credential UX, and channel settings

cyhhaoa1108c8490a1
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 23b99f81f..e33b5ed0d 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -449,21 +449,32 @@ class DiscordBot(BaseIMClient):
if context.thread_id:
target = await self._fetch_channel(context.thread_id)
if not isinstance(target, discord.Thread):
+ logger.info(
+ "Discord typing: thread_id %s resolved to %s (not Thread), falling back to channel_id",
+ context.thread_id,
+ type(target).__name__ if target else None,
+ )
target = None
if target is None:
target = await self._fetch_channel(context.channel_id)
if target is None:
+ logger.info(
+ "Discord typing: could not fetch channel (channel_id=%s, thread_id=%s)",
+ context.channel_id,
+ context.thread_id,
+ )
return False
trigger = getattr(target, "trigger_typing", None)
if not callable(trigger):
+ logger.info("Discord typing: %s has no trigger_typing method", type(target).__name__)
return False
try:
await trigger()
return True
except Exception as err:
- logger.debug("Failed to trigger Discord typing indicator: %s", err)
+ logger.info("Discord typing: trigger_typing failed: %s", err)
return False
async def clear_typing_indicator(self, context: MessageContext) -> bool:
diff --git a/modules/im/slack.py b/modules/im/slack.py
index b40b3eafe..e5cc5d366 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -75,6 +75,13 @@ class SlackBot(BaseIMClient):
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._on_ready: Optional[Callable] = None
+ # RTM typing indicator (best-effort, may not work with modern Slack apps)
+ self._rtm_ws: Optional[aiohttp.ClientWebSocketResponse] = None
+ self._rtm_session: Optional[aiohttp.ClientSession] = None
+ self._rtm_available: Optional[bool] = None # None = not yet attempted
+ self._rtm_msg_id: int = 0
+ self._rtm_drain_task: Optional[asyncio.Task] = None
+
def set_settings_manager(self, settings_manager):
"""Set the settings manager for thread tracking"""
self.settings_manager = settings_manager
@@ -735,6 +742,115 @@ class SlackBot(BaseIMClient):
logger.debug(f"Failed to remove Slack reaction: {err}")
return False
+ # ------------------------------------------------------------------
+ # RTM-based typing indicator (best-effort)
+ # ------------------------------------------------------------------
+
+ async def _ensure_rtm_connection(self) -> Optional[aiohttp.ClientWebSocketResponse]:
+ """Lazily establish an RTM WebSocket solely for typing indicator events.
+
+ Returns the WebSocket on success or ``None`` when RTM is unavailable
+ (e.g. modern Slack apps that lack the ``rtm:stream`` scope). A
+ negative result is cached so subsequent calls return immediately.
+ """
+ if self._rtm_available is False:
+ return None
+
+ # Reuse an existing live connection
+ if self._rtm_ws is not None and not self._rtm_ws.closed:
+ return self._rtm_ws
+
+ # Close stale resources before reconnecting
+ await self._close_rtm()
+
+ self._ensure_clients()
+ try:
+ resp = await self.web_client.rtm_connect()
+ if not resp.get("ok"):
+ err_msg = resp.get("error", "unknown")
+ logger.info("Slack RTM unavailable (%s) — typing indicator disabled", err_msg)
+ self._rtm_available = False
+ return None
+
+ wss_url = resp["url"]
+ self._rtm_session = aiohttp.ClientSession()
+ self._rtm_ws = await self._rtm_session.ws_connect(
+ wss_url,
+ heartbeat=30,
+ autoclose=True,
+ )
+ self._rtm_available = True
+ self._rtm_drain_task = asyncio.create_task(self._rtm_drain_loop())
+ logger.info("Slack RTM WebSocket connected for typing indicator")
+ return self._rtm_ws
+ except Exception as exc:
+ logger.info("Slack RTM connect failed: %s — typing indicator disabled", exc)
+ self._rtm_available = False
+ await self._close_rtm()
+ return None
+
+ async def _rtm_drain_loop(self) -> None:
+ """Read and discard incoming RTM messages to prevent buffer buildup."""
+ try:
+ ws = self._rtm_ws
+ if ws is None:
+ return
+ async for _ in ws:
+ pass # discard all incoming RTM events
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ pass # connection lost — handled on next send attempt
+
+ async def _close_rtm(self) -> None:
+ """Tear down RTM WebSocket and its aiohttp session."""
+ if self._rtm_drain_task is not None:
+ self._rtm_drain_task.cancel()
+ try:
+ await self._rtm_drain_task
+ except (asyncio.CancelledError, Exception):
+ pass
+ self._rtm_drain_task = None
+
+ if self._rtm_ws is not None:
+ try:
+ await self._rtm_ws.close()
+ except Exception:
+ pass
+ self._rtm_ws = None
+
+ if self._rtm_session is not None:
+ try:
+ await self._rtm_session.close()
+ except Exception:
+ pass
+ self._rtm_session = None
+
+ async def send_typing_indicator(self, context: MessageContext) -> bool:
+ """Send a typing indicator via RTM WebSocket (best-effort)."""
+ ws = await self._ensure_rtm_connection()
+ if ws is None:
+ return False
+ try:
+ self._rtm_msg_id += 1
+ await ws.send_json(
+ {
+ "id": self._rtm_msg_id,
+ "type": "typing",
+ "channel": context.channel_id,
+ }
+ )
+ return True
+ except Exception as exc:
+ logger.debug("Slack RTM typing send failed: %s", exc)
+ # Connection may be broken; reset so next call reconnects
+ self._rtm_ws = None
+ return False
+
+ async def clear_typing_indicator(self, context: MessageContext) -> bool:
+ """Slack typing indicators auto-expire (~3 s); no explicit clear needed."""
+ return True
+
async def send_message_with_buttons(
self,
context: MessageContext,
@@ -1775,6 +1891,8 @@ class SlackBot(BaseIMClient):
await self._async_close()
async def _async_close(self) -> None:
+ await self._close_rtm()
+
if self.socket_client is not None:
try:
disconnect = getattr(self.socket_client, "disconnect", None)
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index a96a1e074..536cc65cd 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -546,6 +546,9 @@ class MultiSettingsManager:
def get_message_type_display_names(self) -> Dict[str, str]:
return self.managers[self.primary_platform].get_message_type_display_names()
+ def _canonicalize_message_type(self, message_type: str) -> str:
+ return self.managers[self.primary_platform]._canonicalize_message_type(message_type)
+
def get_channel_routing(self, settings_key: Union[int, str]) -> Optional[ChannelRouting]:
manager, raw = self._resolve(settings_key)
return manager.get_channel_routing(raw)
diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsx
index c97bdd2ae..5c7493bba 100644
--- a/ui/src/components/Dashboard.tsx
+++ b/ui/src/components/Dashboard.tsx
@@ -280,77 +280,6 @@ export const Dashboard: React.FC = () => {
<h3 className="font-semibold flex items-center gap-2 text-text"><MessageSquare size={18} /> {t('dashboard.messageHandling')}</h3>
</div>
<div className="space-y-3 text-sm">
- <div className="space-y-2">
- <div className="text-muted flex items-center gap-1">
- {t('dashboard.requireMention')}
- <span className="relative group">
- <Info size={12} className="text-muted/50 cursor-help" />
- <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 bg-text text-bg text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
- {t('dashboard.requireMentionHint')}
- </span>
- </span>
- </div>
- {enabledPlatforms.map((platform) => (
- <div key={platform} className="flex justify-between items-center">
- <span className="text-text capitalize">{platform}</span>
- <button
- onClick={() => {
- setSettingsMessage(null);
- const currentValue = platform === 'discord'
- ? !!config.discord?.require_mention
- : platform === 'lark'
- ? !!config.lark?.require_mention
- : platform === 'wechat'
- ? !!config.wechat?.require_mention
- : !!config.slack?.require_mention;
- const toggleValue = !currentValue;
- const newConfig = {
- ...config,
- discord: {
- ...(config.discord || {}),
- require_mention: platform === 'discord' ? toggleValue : config.discord?.require_mention,
- },
- slack: {
- ...(config.slack || {}),
- require_mention: platform === 'slack' ? toggleValue : config.slack?.require_mention,
- },
- lark: {
- ...(config.lark || {}),
- require_mention: platform === 'lark' ? toggleValue : config.lark?.require_mention,
- },
- wechat: {
- ...(config.wechat || {}),
- require_mention: platform === 'wechat' ? toggleValue : config.wechat?.require_mention,
- },
- };
- setConfig(newConfig);
- autoSaveMessageConfig(newConfig);
- }}
- className={`px-2 py-1 rounded text-xs font-semibold border ${
- (platform === 'discord'
- ? config.discord?.require_mention
- : platform === 'lark'
- ? config.lark?.require_mention
- : platform === 'wechat'
- ? config.wechat?.require_mention
- : config.slack?.require_mention)
- ? 'bg-success/10 text-success border-success/20'
- : 'bg-neutral-100 text-muted border-border'
- }`}
- >
- {(platform === 'discord'
- ? config.discord?.require_mention
- : platform === 'lark'
- ? config.lark?.require_mention
- : platform === 'wechat'
- ? config.wechat?.require_mention
- : config.slack?.require_mention)
- ? t('channelList.mentionStatusOn')
- : t('channelList.mentionStatusOff')}
- </button>
- </div>
- ))}
- </div>
<div className="flex justify-between items-center">
<span className="text-muted flex items-center gap-1">
{t('dashboard.ackMode')}
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index 0ea65f41a..ad944c682 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { Welcome } from './steps/Welcome';
-import { ModeSelection } from './steps/ModeSelection';
+// import { ModeSelection } from './steps/ModeSelection'; // temporarily hidden — SaaS mode not yet available
import { PlatformSelection } from './steps/PlatformSelection';
import { AgentDetection } from './steps/AgentDetection';
import { SlackConfig } from './steps/SlackConfig';
@@ -130,21 +130,19 @@ export const Wizard: React.FC = () => {
};
});
- const channelSteps = enabledPlatforms
- .filter((platform) => platformSupportsChannels(platform))
- .map((platform) => ({
- id: `channels-${platform}`,
- title: `${platform}-channels`,
- component: (props: any) => <ChannelList {...props} forcedPlatform={platform} />,
- }));
+ // Channel steps: merge into a single step with platform tabs (instead of one step per platform)
+ const channelPlatforms = enabledPlatforms.filter(platformSupportsChannels);
+ const channelStep = channelPlatforms.length > 0
+ ? [{ id: 'channels', title: 'Channels', component: (props: any) => <ChannelList {...props} wizardPlatforms={channelPlatforms} /> }]
+ : [];
return [
{ id: 'welcome', title: 'Welcome', component: Welcome },
- { id: 'mode', title: 'Mode', component: ModeSelection },
+ // { id: 'mode', title: 'Mode', component: ModeSelection }, // temporarily hidden — SaaS mode not yet available
{ id: 'agents', title: 'Agents', component: AgentDetection },
{ id: 'platform', title: 'Platform', component: PlatformSelection },
...platformSteps,
- ...channelSteps,
+ ...channelStep,
{ id: 'summary', title: 'Finish', component: Summary },
];
}, [data]);
@@ -219,11 +217,14 @@ export const Wizard: React.FC = () => {
) {
await api.saveConfig(buildConfigPayload(mergedData));
}
- if (stepData?.settingsPlatform && stepData?.channelConfigsByPlatform) {
- await api.saveSettings(
- { channels: stepData.channelConfigsByPlatform[stepData.settingsPlatform] || {} },
- stepData.settingsPlatform,
- );
+ if (stepData?.channelConfigsByPlatform) {
+ const platforms = Object.keys(stepData.channelConfigsByPlatform);
+ for (const p of platforms) {
+ const channelConfigs = stepData.channelConfigsByPlatform[p];
+ if (channelConfigs && Object.keys(channelConfigs).length > 0) {
+ await api.saveSettings({ channels: channelConfigs }, p);
+ }
+ }
}
};
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 34cc0da7d..586a8cbcc 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
-import { Hash, CheckSquare, Square, RefreshCw, HelpCircle, Globe, FolderOpen, MessageSquare, Users } from 'lucide-react';
+import { Hash, CheckSquare, Square, RefreshCw, HelpCircle, Globe, FolderOpen, MessageSquare, Users, AtSign } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
@@ -33,6 +33,8 @@ interface ChannelListProps {
onBack?: () => void;
isPage?: boolean;
forcedPlatform?: string;
+ /** When set in wizard mode, show platform tabs to switch between platforms in a single step */
+ wizardPlatforms?: string[];
}
interface ChannelConfig {
@@ -53,7 +55,7 @@ interface ChannelConfig {
require_mention?: boolean | null; // null=use global default, true=require, false=don't require
}
-export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBack, isPage, forcedPlatform }) => {
+export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBack, isPage, forcedPlatform, wizardPlatforms }) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -61,7 +63,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [channels, setChannels] = useState<any[]>([]);
const [browseAll, setBrowseAll] = useState(false);
const [loadingAll, setLoadingAll] = useState(false);
- const scopedInitialPlatform = forcedPlatform || data.platform || 'slack';
+ // Wizard multi-platform mode: show tabs instead of separate steps
+ const isWizardMultiPlatform = !isPage && Array.isArray(wizardPlatforms) && wizardPlatforms.length > 1;
+ const [wizardActivePlatform, setWizardActivePlatform] = useState(forcedPlatform || wizardPlatforms?.[0] || 'slack');
+ const [wizardConfigsMap, setWizardConfigsMap] = useState<Record<string, Record<string, ChannelConfig>>>({});
+ const scopedInitialPlatform = forcedPlatform || wizardPlatforms?.[0] || data.platform || 'slack';
const [configs, setConfigs] = useState<Record<string, ChannelConfig>>(
data.channelConfigsByPlatform?.[scopedInitialPlatform] || data.channelConfigs || {}
);
@@ -82,16 +88,22 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (isPage) return;
let cancelled = false;
+ const targetPlatform = isWizardMultiPlatform ? wizardActivePlatform : (forcedPlatform || data.platform);
const loadWizardPlatformSettings = async () => {
+ // If we already have locally saved configs for this platform, use them
+ if (isWizardMultiPlatform && wizardConfigsMap[targetPlatform]) {
+ if (!cancelled) setConfigs(wizardConfigsMap[targetPlatform]);
+ return;
+ }
try {
- const settings = await api.getSettings(forcedPlatform || data.platform);
+ const settings = await api.getSettings(targetPlatform);
if (!cancelled) {
setConfigs(settings.channels || {});
}
} catch {
if (!cancelled) {
// Fallback to wizard-local state if API fetch fails.
- setConfigs(data.channelConfigsByPlatform?.[forcedPlatform || data.platform || 'slack'] || data.channelConfigs || {});
+ setConfigs(data.channelConfigsByPlatform?.[targetPlatform || 'slack'] || data.channelConfigs || {});
}
}
};
@@ -122,9 +134,24 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
}, [forcedPlatform, isPage]);
- const platform = forcedPlatform || pagePlatform || config.platform || data.platform || 'slack';
+ const platform = isWizardMultiPlatform
+ ? wizardActivePlatform
+ : (forcedPlatform || pagePlatform || config.platform || data.platform || 'slack');
const channelPlatforms = getEnabledPlatforms(config).filter(platformSupportsChannels);
+ // Switch platforms in wizard multi-platform mode
+ const switchWizardPlatform = (newPlatform: string) => {
+ if (newPlatform === wizardActivePlatform) return;
+ // Save current platform's configs to map
+ setWizardConfigsMap(prev => ({ ...prev, [wizardActivePlatform]: configs }));
+ // Load new platform's configs from map, then from data, then empty
+ const saved = wizardConfigsMap[newPlatform];
+ setConfigs(saved || data.channelConfigsByPlatform?.[newPlatform] || {});
+ setWizardActivePlatform(newPlatform);
+ setChannels([]);
+ setBrowseAll(false);
+ };
+
useEffect(() => {
if (!isPage) return;
if (!platform) return;
@@ -494,23 +521,60 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</div>
</div>
- {isPage && channelPlatforms.length > 1 && (
+ {((isPage && channelPlatforms.length > 1) || isWizardMultiPlatform) && (
<div className="mb-4 flex flex-wrap gap-2">
- {channelPlatforms.map((candidate) => (
+ {(isWizardMultiPlatform ? wizardPlatforms! : channelPlatforms).map((candidate) => (
<button
key={candidate}
- onClick={() => setPagePlatform(candidate)}
+ onClick={() => isWizardMultiPlatform ? switchWizardPlatform(candidate) : setPagePlatform(candidate)}
className={clsx(
'px-3 py-1.5 rounded-full text-sm border transition-colors',
platform === candidate ? 'bg-accent text-white border-accent' : 'bg-panel text-text border-border hover:border-accent/60'
)}
>
- {candidate}
+ {t(`platform.${candidate}.title`)}
</button>
))}
</div>
)}
+ {/* Platform-level require @mention toggle (page mode only) */}
+ {isPage && (
+ <div className="mb-4 bg-panel border border-border p-3 rounded-lg flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm">
+ <AtSign size={14} className="text-accent" />
+ <span className="font-medium text-text">{t('dashboard.requireMention')}</span>
+ <span className="text-xs text-muted">{t('dashboard.requireMentionHint')}</span>
+ </div>
+ <button
+ onClick={async () => {
+ const key = platform as 'slack' | 'discord' | 'lark' | 'wechat';
+ const current = !!(config as any)[key]?.require_mention;
+ const updated = {
+ ...config,
+ [key]: { ...(config as any)[key], require_mention: !current },
+ };
+ setConfig(updated);
+ try {
+ await api.saveConfig(updated);
+ showToast(t('common.saved'), 'success');
+ } catch { /* ignore */ }
+ }}
+ className={clsx(
+ 'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
+ (config as any)[platform]?.require_mention ? 'bg-accent' : 'bg-neutral-300'
+ )}
+ >
+ <span
+ className={clsx(
+ 'inline-block h-4 w-4 rounded-full bg-white transition-transform shadow-sm',
+ (config as any)[platform]?.require_mention ? 'translate-x-6' : 'translate-x-1'
+ )}
+ />
+ </button>
+ </div>
+ )}
+
<div className="mb-4 bg-panel border border-border p-4 rounded-lg space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
@@ -963,14 +1027,27 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('common.back')}
</button>
<button
- onClick={() => onNext && onNext({
- channelConfigsByPlatform: {
- ...(data.channelConfigsByPlatform || {}),
- [platform]: configs,
- },
- settingsPlatform: platform,
- ...(platform === 'discord' ? { discord: { ...config.discord, guild_allowlist: selectedGuild ? [selectedGuild] : [] } } : {}),
- })}
+ onClick={() => {
+ if (isWizardMultiPlatform) {
+ // Merge configs from all visited platforms
+ const allConfigs = { ...wizardConfigsMap, [wizardActivePlatform]: configs };
+ onNext && onNext({
+ channelConfigsByPlatform: {
+ ...(data.channelConfigsByPlatform || {}),
+ ...allConfigs,
+ },
+ });
+ } else {
+ onNext && onNext({
+ channelConfigsByPlatform: {
+ ...(data.channelConfigsByPlatform || {}),
+ [platform]: configs,
+ },
+ settingsPlatform: platform,
+ ...(platform === 'discord' ? { discord: { ...config.discord, guild_allowlist: selectedGuild ? [selectedGuild] : [] } } : {}),
+ });
+ }
+ }}
className="px-6 py-2 bg-accent hover:bg-accent/90 text-white rounded-lg font-medium shadow-sm"
>
{t('common.continue')}
diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsx
index ca1c452bb..9676ea402 100644
--- a/ui/src/components/steps/DiscordConfig.tsx
+++ b/ui/src/components/steps/DiscordConfig.tsx
@@ -42,7 +42,12 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa
}
}, [botToken, expandedSteps]);
- const isValid = useMemo(() => botToken.length > 0 && authResult?.ok, [botToken, authResult]);
+ const isValid = useMemo(() => {
+ if (!botToken) return false;
+ if (authResult?.ok) return true;
+ // Allow proceeding if token matches previously saved config (already validated before)
+ return Boolean(data.discord?.bot_token && botToken === data.discord?.bot_token);
+ }, [botToken, authResult, data.discord?.bot_token]);
const runAuthTest = async () => {
setChecking(true);
diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsx
index 660d59fd9..22a16a963 100644
--- a/ui/src/components/steps/LarkConfig.tsx
+++ b/ui/src/components/steps/LarkConfig.tsx
@@ -74,7 +74,12 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
};
}, []);
- const isValid = useMemo(() => appId.length > 0 && appSecret.length > 0 && authResult?.ok, [appId, appSecret, authResult]);
+ const isValid = useMemo(() => {
+ if (!appId || !appSecret) return false;
+ if (authResult?.ok) return true;
+ // Allow proceeding if credentials match previously saved config (already validated before)
+ return Boolean(data.lark?.app_id && data.lark?.app_secret && appId === data.lark?.app_id && appSecret === data.lark?.app_secret);
+ }, [appId, appSecret, authResult, data.lark?.app_id, data.lark?.app_secret]);
const runAuthTest = async () => {
setChecking(true);
diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsx
index 4936f60ad..f38b2cfdd 100644
--- a/ui/src/components/steps/PlatformSelection.tsx
+++ b/ui/src/components/steps/PlatformSelection.tsx
@@ -54,7 +54,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
<p className="text-muted mt-1">{t('platform.subtitle')}</p>
</div>
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 flex-1">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 flex-1">
{ALL_PLATFORMS.map((option) => {
const active = selected.includes(option);
return (
@@ -74,11 +74,11 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
</div>
<div
className={clsx(
- 'mt-1 h-5 w-5 rounded border flex items-center justify-center text-xs font-bold',
- active ? 'border-accent bg-accent text-white' : 'border-border text-transparent'
+ 'mt-1 h-5 w-5 rounded-full border flex items-center justify-center text-xs font-bold',
+ active ? 'border-accent bg-accent text-white' : 'border-border bg-bg'
)}
>
- ✓
+ {active ? selected.indexOf(option) + 1 : ''}
</div>
</div>
{active && primary === option && (
diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsx
index 245ec60b6..3eac81cc2 100644
--- a/ui/src/components/steps/WeChatConfig.tsx
+++ b/ui/src/components/steps/WeChatConfig.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
-import { Check, RefreshCw, Smartphone, Wifi, AlertTriangle, Loader2 } from 'lucide-react';
+import { Check, RefreshCw, Smartphone, Wifi, AlertTriangle, Loader2, KeyRound } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
@@ -97,10 +97,12 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
if (autoStartedRef.current) return;
if (starting) return;
if (loginState !== 'idle') return;
+ // Don't auto-start QR flow if we already have a token from previous config
+ if (data.wechat?.bot_token) return;
autoStartedRef.current = true;
void startLogin();
- }, [loginState, startLogin, starting]);
+ }, [loginState, startLogin, starting, data.wechat?.bot_token]);
const startPolling = (key: string) => {
stopPolling();
@@ -143,7 +145,10 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
void pollOnce();
};
- const isConnected = loginState === 'connected' && !!botToken;
+ // Allow proceeding if we have a token (either freshly scanned or from existing config)
+ const canProceed = !!botToken;
+ // Whether we're showing the "already bound" idle state (existing token, QR not started)
+ const isAlreadyBound = loginState === 'idle' && !!botToken;
const stepIndicator = (stepNum: number, label: string, active: boolean, completed: boolean) => (
<div className="flex items-center gap-2">
@@ -160,6 +165,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
);
const getStepState = () => {
+ if (isAlreadyBound) return { step: 3, scanning: false, connected: true };
if (loginState === 'idle') return { step: 1, scanning: false, connected: false };
if (loginState === 'qr_ready') return { step: 2, scanning: false, connected: false };
if (loginState === 'scanning' || loginState === 'confirming') return { step: 2, scanning: true, connected: false };
@@ -188,8 +194,38 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
</div>
<div className="flex-1 space-y-4 overflow-y-auto pr-1">
- {/* Start Login */}
- {loginState === 'idle' && (
+ {/* Already bound — existing token, no QR needed */}
+ {isAlreadyBound && (
+ <div className="bg-panel border border-border rounded-xl p-6 space-y-4">
+ <div className="flex flex-col items-center space-y-4">
+ <div className="w-20 h-20 bg-success/10 text-success rounded-full flex items-center justify-center">
+ <Check size={40} />
+ </div>
+ <div className="text-center">
+ <h3 className="text-lg font-semibold text-text">{t('wechatConfig.alreadyBound')}</h3>
+ <p className="text-sm text-muted mt-1">{t('wechatConfig.alreadyBoundDesc')}</p>
+ </div>
+ <div className="w-full bg-bg border border-border rounded-lg p-3">
+ <div className="text-xs text-muted mb-1 flex items-center gap-1"><KeyRound size={12} /> Token</div>
+ <div className="text-sm font-mono text-text truncate">{botToken.slice(0, 12)}{'•'.repeat(16)}</div>
+ </div>
+ <button
+ onClick={() => {
+ autoStartedRef.current = true;
+ void startLogin();
+ }}
+ disabled={starting}
+ className="px-4 py-2 bg-panel border border-border text-text rounded-lg flex items-center gap-2 text-sm font-medium hover:bg-neutral-50 transition-colors disabled:opacity-50"
+ >
+ <RefreshCw size={14} className={starting ? 'animate-spin' : ''} />
+ {t('wechatConfig.rebind')}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Start Login — only when no existing token */}
+ {loginState === 'idle' && !botToken && (
<div className="bg-panel border border-border rounded-xl p-6 text-center space-y-4">
<div className="w-16 h-16 bg-accent/10 text-accent rounded-full flex items-center justify-center mx-auto">
<Loader2 size={32} className="animate-spin" />
@@ -301,10 +337,10 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
},
});
}}
- disabled={!isConnected}
+ disabled={!canProceed}
className={clsx(
'px-8 py-3 rounded-lg font-medium transition-colors shadow-sm',
- isConnected ? 'bg-accent hover:bg-accent/90 text-white' : 'bg-neutral-200 text-muted cursor-not-allowed'
+ canProceed ? 'bg-accent hover:bg-accent/90 text-white' : 'bg-neutral-200 text-muted cursor-not-allowed'
)}
>
{t('common.continue')}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index cbe5eb263..cbdc2b8c2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -230,7 +230,10 @@
"pollError": "An error occurred while checking status.",
"errorTitle": "Connection Failed",
"retry": "Try Again",
- "refreshQr": "Refresh QR Code"
+ "refreshQr": "Refresh QR Code",
+ "alreadyBound": "WeChat Connected",
+ "alreadyBoundDesc": "Your WeChat account is already linked. You can proceed or rebind with a different account.",
+ "rebind": "Rebind Account"
},
"slackConfig": {
"title": "Slack Configuration",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ce6c50819..264bf4275 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -230,7 +230,10 @@
"pollError": "检查状态时发生错误。",
"errorTitle": "连接失败",
"retry": "重试",
- "refreshQr": "刷新二维码"
+ "refreshQr": "刷新二维码",
+ "alreadyBound": "微信已绑定",
+ "alreadyBoundDesc": "你的微信账号已绑定。可以直接继续,或点击下方按钮重新绑定其他账号。",
+ "rebind": "重新绑定"
},
"slackConfig": {
"title": "Slack 配置",