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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(admin): add DM bind system, admin permission control, and user management
cyhf44af4d6f849
diff --git a/config/v2_settings.py b/config/v2_settings.pyindex 6ca969f11..1fd33290f 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -1,6 +1,9 @@import jsonimport logging+import secrets+import stringfrom dataclasses import dataclass, field+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Dict, List, Optional@@ -11,6 +14,11 @@ logger = logging.getLogger(__name__)DEFAULT_SHOW_MESSAGE_TYPES: List[str] = []ALLOWED_MESSAGE_TYPES = {"system", "assistant", "toolcall"}+# Bind code prefix and length+_BIND_CODE_PREFIX = "vr-"+_BIND_CODE_RANDOM_LENGTH = 6+_BIND_CODE_ALPHABET = string.ascii_lowercase + string.digits+def normalize_show_message_types(show_message_types: Optional[List[str]]) -> List[str]:if show_message_types is None:@@ -18,6 +26,17 @@ def normalize_show_message_types(show_message_types: Optional[List[str]]) -> Lisreturn [msg for msg in show_message_types if msg in ALLOWED_MESSAGE_TYPES]+def _generate_bind_code() -> str:+ """Generate a random bind code like 'vr-a3x9k2'."""+ random_part = "".join(secrets.choice(_BIND_CODE_ALPHABET) for _ in range(_BIND_CODE_RANDOM_LENGTH))+ return f"{_BIND_CODE_PREFIX}{random_part}"+++def _now_iso() -> str:+ """Return current UTC time as ISO 8601 string."""+ return datetime.now(timezone.utc).isoformat()++@dataclassclass RoutingSettings:agent_backend: Optional[str] = None@@ -45,9 +64,64 @@ class ChannelSettings:require_mention: Optional[bool] = None+@dataclass+class UserSettings:+ """Settings for a bound DM user."""++ display_name: str = ""+ is_admin: bool = False+ bound_at: str = "" # ISO 8601 timestamp+ enabled: bool = True+ show_message_types: List[str] = field(default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy())+ custom_cwd: Optional[str] = None+ routing: RoutingSettings = field(default_factory=RoutingSettings)+++@dataclass+class BindCode:+ """A bind code for authorizing DM access."""++ code: str+ type: str # "one_time" or "expiring"+ created_at: str # ISO 8601+ expires_at: Optional[str] = None # ISO 8601, only for "expiring" type+ is_active: bool = True+ used_by: List[str] = field(default_factory=list) # user_ids that used this code++@dataclassclass SettingsState:channels: Dict[str, ChannelSettings] = field(default_factory=dict)+ users: Dict[str, UserSettings] = field(default_factory=dict)+ bind_codes: List[BindCode] = field(default_factory=list)+++def _parse_routing(payload: dict) -> RoutingSettings:+ """Parse a routing settings dict into a RoutingSettings dataclass."""+ return RoutingSettings(+ agent_backend=payload.get("agent_backend"),+ opencode_agent=payload.get("opencode_agent"),+ opencode_model=payload.get("opencode_model"),+ opencode_reasoning_effort=payload.get("opencode_reasoning_effort"),+ claude_agent=payload.get("claude_agent"),+ claude_model=payload.get("claude_model"),+ codex_model=payload.get("codex_model"),+ codex_reasoning_effort=payload.get("codex_reasoning_effort"),+ )+++def _routing_to_dict(routing: RoutingSettings) -> dict:+ """Serialize a RoutingSettings to dict."""+ return {+ "agent_backend": routing.agent_backend,+ "opencode_agent": routing.opencode_agent,+ "opencode_model": routing.opencode_model,+ "opencode_reasoning_effort": routing.opencode_reasoning_effort,+ "claude_agent": routing.claude_agent,+ "claude_model": routing.claude_model,+ "codex_model": routing.codex_model,+ "codex_reasoning_effort": routing.codex_reasoning_effort,+ }class SettingsStore:@@ -64,59 +138,110 @@ class SettingsStore:except Exception as exc:logger.error("Failed to load settings: %s", exc)return- raw_channels = payload.get("channels") if isinstance(payload, dict) else None- if raw_channels is None:+ if not isinstance(payload, dict):logger.error("Failed to load settings: invalid format")return++ # --- Channels ---+ raw_channels = payload.get("channels")+ if raw_channels is None:+ # Legacy format or empty — tolerate missing channels key+ raw_channels = {}if not isinstance(raw_channels, dict):logger.error("Failed to load settings: channels must be an object")- return- channels = {}- for channel_id, channel_payload in raw_channels.items():- if not isinstance(channel_payload, dict):+ raw_channels = {}+ channels: Dict[str, ChannelSettings] = {}+ for channel_id, cp in raw_channels.items():+ if not isinstance(cp, dict):continue- routing_payload = channel_payload.get("routing") or {}- routing = RoutingSettings(- agent_backend=routing_payload.get("agent_backend"),- opencode_agent=routing_payload.get("opencode_agent"),- opencode_model=routing_payload.get("opencode_model"),- opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),- claude_agent=routing_payload.get("claude_agent"),- claude_model=routing_payload.get("claude_model"),- codex_model=routing_payload.get("codex_model"),- codex_reasoning_effort=routing_payload.get("codex_reasoning_effort"),- )channels[channel_id] = ChannelSettings(- enabled=channel_payload.get("enabled", False),- show_message_types=normalize_show_message_types(channel_payload.get("show_message_types")),- custom_cwd=channel_payload.get("custom_cwd"),- routing=routing,- require_mention=channel_payload.get("require_mention"),+ enabled=cp.get("enabled", False),+ show_message_types=normalize_show_message_types(cp.get("show_message_types")),+ custom_cwd=cp.get("custom_cwd"),+ routing=_parse_routing(cp.get("routing") or {}),+ require_mention=cp.get("require_mention"),)- self.settings = SettingsState(channels=channels)++ # --- Users ---+ raw_users = payload.get("users") or {}+ users: Dict[str, UserSettings] = {}+ if isinstance(raw_users, dict):+ for user_id, up in raw_users.items():+ if not isinstance(up, dict):+ continue+ users[user_id] = UserSettings(+ display_name=up.get("display_name", ""),+ is_admin=up.get("is_admin", False),+ bound_at=up.get("bound_at", ""),+ enabled=up.get("enabled", True),+ show_message_types=normalize_show_message_types(up.get("show_message_types")),+ custom_cwd=up.get("custom_cwd"),+ routing=_parse_routing(up.get("routing") or {}),+ )++ # --- Bind Codes ---+ raw_codes = payload.get("bind_codes") or []+ bind_codes: List[BindCode] = []+ if isinstance(raw_codes, list):+ for bc in raw_codes:+ if not isinstance(bc, dict):+ continue+ bind_codes.append(+ BindCode(+ code=bc.get("code", ""),+ type=bc.get("type", "one_time"),+ created_at=bc.get("created_at", ""),+ expires_at=bc.get("expires_at"),+ is_active=bc.get("is_active", True),+ used_by=bc.get("used_by") or [],+ )+ )++ self.settings = SettingsState(channels=channels, users=users, bind_codes=bind_codes)def save(self) -> None:paths.ensure_data_dirs()- payload = {"channels": {}}- for channel_id, settings in self.settings.channels.items():+ payload: dict = {"channels": {}, "users": {}, "bind_codes": []}++ # Channels+ for channel_id, s in self.settings.channels.items():payload["channels"][channel_id] = {- "enabled": settings.enabled,- "show_message_types": settings.show_message_types,- "custom_cwd": settings.custom_cwd,- "routing": {- "agent_backend": settings.routing.agent_backend,- "opencode_agent": settings.routing.opencode_agent,- "opencode_model": settings.routing.opencode_model,- "opencode_reasoning_effort": settings.routing.opencode_reasoning_effort,- "claude_agent": settings.routing.claude_agent,- "claude_model": settings.routing.claude_model,- "codex_model": settings.routing.codex_model,- "codex_reasoning_effort": settings.routing.codex_reasoning_effort,- },- "require_mention": settings.require_mention,+ "enabled": s.enabled,+ "show_message_types": s.show_message_types,+ "custom_cwd": s.custom_cwd,+ "routing": _routing_to_dict(s.routing),+ "require_mention": s.require_mention,}++ # Users+ for user_id, u in self.settings.users.items():+ payload["users"][user_id] = {+ "display_name": u.display_name,+ "is_admin": u.is_admin,+ "bound_at": u.bound_at,+ "enabled": u.enabled,+ "show_message_types": u.show_message_types,+ "custom_cwd": u.custom_cwd,+ "routing": _routing_to_dict(u.routing),+ }++ # Bind codes+ for bc in self.settings.bind_codes:+ payload["bind_codes"].append(+ {+ "code": bc.code,+ "type": bc.type,+ "created_at": bc.created_at,+ "expires_at": bc.expires_at,+ "is_active": bc.is_active,+ "used_by": bc.used_by,+ }+ )+self.settings_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ # --- Channel helpers ---+def get_channel(self, channel_id: str) -> ChannelSettings:if channel_id not in self.settings.channels:self.settings.channels[channel_id] = ChannelSettings()@@ -125,3 +250,118 @@ class SettingsStore:def update_channel(self, channel_id: str, settings: ChannelSettings) -> None:self.settings.channels[channel_id] = settingsself.save()++ # --- User helpers ---++ def get_user(self, user_id: str) -> Optional[UserSettings]:+ """Get user settings, or None if user is not bound."""+ return self.settings.users.get(user_id)++ def is_bound_user(self, user_id: str) -> bool:+ return user_id in self.settings.users++ def is_admin(self, user_id: str) -> bool:+ user = self.settings.users.get(user_id)+ return user is not None and user.is_admin++ def has_any_admin(self) -> bool:+ """Return True if at least one admin exists."""+ return any(u.is_admin for u in self.settings.users.values())++ def get_admins(self) -> Dict[str, UserSettings]:+ """Return all admin users."""+ return {uid: u for uid, u in self.settings.users.items() if u.is_admin}++ def add_user(self, user_id: str, display_name: str, is_admin: bool = False) -> UserSettings:+ """Add a new bound user. Returns the created UserSettings."""+ user = UserSettings(+ display_name=display_name,+ is_admin=is_admin,+ bound_at=_now_iso(),+ enabled=True,+ )+ self.settings.users[user_id] = user+ self.save()+ return user++ def update_user(self, user_id: str, settings: UserSettings) -> None:+ self.settings.users[user_id] = settings+ self.save()++ def remove_user(self, user_id: str) -> bool:+ if user_id in self.settings.users:+ del self.settings.users[user_id]+ self.save()+ return True+ return False++ def set_admin(self, user_id: str, is_admin: bool) -> bool:+ """Set admin flag for a user. Returns False if user not found or trying to remove last admin."""+ user = self.settings.users.get(user_id)+ if user is None:+ return False+ if not is_admin:+ # Prevent removing the last admin+ admin_count = sum(1 for u in self.settings.users.values() if u.is_admin)+ if admin_count <= 1 and user.is_admin:+ return False+ user.is_admin = is_admin+ self.save()+ return True++ # --- Bind code helpers ---++ def create_bind_code(self, code_type: str = "one_time", expires_at: Optional[str] = None) -> BindCode:+ """Create a new bind code."""+ code = _generate_bind_code()+ bc = BindCode(+ code=code,+ type=code_type,+ created_at=_now_iso(),+ expires_at=expires_at if code_type == "expiring" else None,+ is_active=True,+ )+ self.settings.bind_codes.append(bc)+ self.save()+ return bc++ def validate_bind_code(self, code: str) -> Optional[BindCode]:+ """Validate a bind code. Returns the BindCode if valid, None otherwise."""+ for bc in self.settings.bind_codes:+ if bc.code != code:+ continue+ if not bc.is_active:+ return None+ if bc.type == "expiring" and bc.expires_at:+ try:+ expires = datetime.fromisoformat(bc.expires_at)+ if datetime.now(timezone.utc) > expires:+ return None+ except (ValueError, TypeError):+ pass+ return bc+ return None++ def use_bind_code(self, code: str, user_id: str) -> bool:+ """Mark a bind code as used by a user. Returns True on success."""+ bc = self.validate_bind_code(code)+ if bc is None:+ return False+ bc.used_by.append(user_id)+ if bc.type == "one_time":+ bc.is_active = False+ self.save()+ return True++ def deactivate_bind_code(self, code: str) -> bool:+ """Deactivate a bind code. Returns True if found and deactivated."""+ for bc in self.settings.bind_codes:+ if bc.code == code:+ bc.is_active = False+ self.save()+ return True+ return False++ def get_bind_codes(self) -> List[BindCode]:+ """Return all bind codes."""+ return list(self.settings.bind_codes)diff --git a/core/controller.py b/core/controller.pyindex 5a1d6075b..5595533d0 100644--- a/core/controller.py+++ b/core/controller.py@@ -282,6 +282,7 @@ class Controller:"set_cwd": self.command_handler.handle_set_cwd,"settings": self.settings_handler.handle_settings,"stop": self.command_handler.handle_stop,+ "bind": self.command_handler.handle_bind,}# Register callbacks with the IM clientdiff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 2ef2a02de..bc22460b5 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -413,6 +413,65 @@ class CommandHandlers:channel_context = self._get_channel_context(context)await self.im_client.send_message(channel_context, f"❌ {self._t('error.resumeFailed')}")+ async def handle_bind(self, context: MessageContext, args: str = ""):+ """Handle /bind command - bind a user to this Vibe Remote instance via bind code"""+ try:+ code = args.strip()+ if not code:+ channel_context = self._get_channel_context(context)+ await self.im_client.send_message(channel_context, self._t("bind.usage"))+ return++ store = self.settings_manager.store++ # Check if user is already bound+ if store.is_bound_user(context.user_id):+ channel_context = self._get_channel_context(context)+ await self.im_client.send_message(channel_context, self._t("bind.alreadyBound"))+ return++ # Validate the bind code+ bind_code = store.validate_bind_code(code)+ if bind_code is None:+ channel_context = self._get_channel_context(context)+ await self.im_client.send_message(channel_context, self._t("bind.invalidCode"))+ return++ # Fetch user info for display name+ try:+ user_info = await self.im_client.get_user_info(context.user_id)+ except Exception as e:+ logger.warning(f"Failed to get user info during bind: {e}")+ user_info = {"id": context.user_id}++ display_name = (+ user_info.get("display_name") or user_info.get("real_name") or user_info.get("name") or context.user_id+ )++ # Auto-admin: if no admins exist, first user becomes admin+ is_admin = not store.has_any_admin()++ # Add user and consume the bind code+ store.add_user(context.user_id, display_name, is_admin=is_admin)+ store.use_bind_code(code, context.user_id)++ if is_admin:+ msg = self._t("bind.successAdmin", name=display_name)+ else:+ msg = self._t("bind.success", name=display_name)++ channel_context = self._get_channel_context(context)+ await self.im_client.send_message(channel_context, msg)+ logger.info(f"User {context.user_id} ({display_name}) bound successfully (admin={is_admin})")++ except Exception as e:+ logger.error(f"Error handling bind command: {e}", exc_info=True)+ try:+ channel_context = self._get_channel_context(context)+ await self.im_client.send_message(channel_context, self._t("bind.error", error=str(e)))+ except Exception as send_error:+ logger.error(f"Failed to send bind error message: {send_error}", exc_info=True)+async def handle_stop(self, context: MessageContext, args: str = ""):"""Handle /stop command - send interrupt message to the active agent"""try:diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 02ea43d48..18aa670f3 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -301,6 +301,19 @@ class MessageHandler:settings_handler = SettingsHandler(self.controller)command_handlers = CommandHandlers(self.controller)+ # --- Admin permission check for protected operations ---+ admin_protected = ("cmd_settings", "cmd_routing", "cmd_change_cwd", "vibe_update_now")+ if any(callback_data.startswith(p) for p in admin_protected):+ store = self.settings_manager.store+ # Only enforce if at least one admin exists (backward compat)+ if store.has_any_admin() and not store.is_admin(context.user_id):+ logger.info(f"Permission denied: {context.user_id} attempted {callback_data}")+ try:+ await self.im_client.send_message(context, self._t("permission.adminOnly"))+ except Exception:+ pass+ return+# Route based on callback dataif callback_data.startswith("toggle_msg_"):# Toggle message type visibilitydiff --git a/core/update_checker.py b/core/update_checker.pyindex 5c43eace5..8db34f139 100644--- a/core/update_checker.py+++ b/core/update_checker.py@@ -134,7 +134,7 @@ class UpdateChecker:self._check_task: Optional[asyncio.Task] = Noneself._running = Falseself._upgrade_lock = asyncio.Lock() # Prevent concurrent upgrades- self._cached_owner_dm_channel: Optional[str] = None # Cache DM channel ID+ self._cached_owner_dm_channel: Optional[str] = None # Cache DM channel ID (legacy fallback)def start(self) -> None:"""Start the periodic update checker."""@@ -289,8 +289,26 @@ class UpdateChecker:return False+ def _get_admin_user_ids(self) -> list:+ """Get admin user IDs from the settings store.++ Returns a list of admin user IDs, or empty list if none configured.+ """+ try:+ if hasattr(self.controller, "settings_manager"):+ store = getattr(self.controller.settings_manager, "store", None)+ if store and hasattr(store, "get_admins"):+ admins = store.get_admins()+ return list(admins.keys())+ except Exception as e:+ logger.warning(f"Failed to get admin user IDs: {e}")+ return []+async def _get_workspace_owner_id(self) -> Optional[str]:- """Get the Slack workspace primary owner's user ID."""+ """Get the Slack workspace primary owner's user ID.++ Legacy fallback: used only when no admins are configured.+ """try:im_client = self.controller.im_clientif not im_client or not hasattr(im_client, "web_client"):@@ -362,20 +380,81 @@ class UpdateChecker:return Noneasync def _send_update_notification(self, current: str, latest: str) -> None:+ """Send update notification to admin users, with platform-specific fallbacks."""platform = getattr(self.controller.config, "platform", "slack")- if platform == "slack":- await self._send_slack_notification(current, latest)- return- if platform == "discord":- await self._send_discord_notification(current, latest)+ admin_ids = self._get_admin_user_ids()++ if admin_ids:+ # Send DM to each admin via the platform-agnostic send_dm method+ await self._send_notification_to_admins(admin_ids, current, latest, platform)+ else:+ # Legacy fallback: no admins configured+ if platform == "slack":+ await self._send_slack_notification_legacy(current, latest)+ elif platform == "discord":+ await self._send_discord_notification_fallback(current, latest)+ else:+ logger.warning("Update notification skipped: no admins and unsupported platform %s", platform)++ async def _send_notification_to_admins(self, admin_ids: list, current: str, latest: str, platform: str) -> None:+ """Send update notification DM to each admin user."""+ im_client = self.controller.im_client+ if not im_client:return- logger.warning("Update notification skipped for unsupported platform: %s", platform)- async def _send_slack_notification(self, current: str, latest: str) -> None:- """Send a Slack notification about the available update."""+ if platform == "slack":+ text = f"Vibe Remote update available: {current} → {latest}"+ blocks = [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": f":rocket: *Vibe Remote Update Available*\n\n"+ f"A new version is available: `{current}` → `{latest}`",+ },+ },+ {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "Update Now", "emoji": True},+ "style": "primary",+ "action_id": UPDATE_BUTTON_ACTION_ID,+ "value": latest,+ }+ ],+ },+ ]+ for uid in admin_ids:+ try:+ await im_client.send_dm(uid, text, blocks=blocks)+ logger.info(f"Sent update notification to admin {uid}")+ except Exception as e:+ logger.error(f"Failed to send update notification to admin {uid}: {e}")+ elif platform == "discord":+ text = f"🚀 **Vibe Remote Update Available**\n\nUpdate from `{current}` → `{latest}`"+ for uid in admin_ids:+ try:+ await im_client.send_dm(uid, text)+ logger.info(f"Sent update notification to admin {uid}")+ except Exception as e:+ logger.error(f"Failed to send update notification to admin {uid}: {e}")+ else:+ # Lark/Feishu+ text = f"🚀 Vibe Remote Update Available\n\nUpdate from {current} → {latest}"+ for uid in admin_ids:+ try:+ await im_client.send_dm(uid, text)+ logger.info(f"Sent update notification to admin {uid}")+ except Exception as e:+ logger.error(f"Failed to send update notification to admin {uid}: {e}")++ async def _send_slack_notification_legacy(self, current: str, latest: str) -> None:+ """Legacy Slack notification: send to workspace owner when no admins configured."""owner_id = await self._get_workspace_owner_id()if not owner_id:- logger.warning("Cannot send update notification: no workspace owner found")+ logger.warning("Cannot send update notification: no admins and no workspace owner found")return# Open DM channel first (required for sending messages to users)@@ -416,11 +495,11 @@ class UpdateChecker:except Exception as e:logger.error(f"Failed to send update notification: {e}")- async def _send_discord_notification(self, current: str, latest: str) -> None:- """Send a Discord notification about the available update."""+ async def _send_discord_notification_fallback(self, current: str, latest: str) -> None:+ """Fallback Discord notification: send to first enabled channel when no admins configured."""channel_id = self._get_default_notification_channel_id()if not channel_id:- logger.warning("Cannot send update notification: no enabled channel found")+ logger.warning("Cannot send update notification: no admins and no enabled channel found")returntry:from modules.im import InlineButton, InlineKeyboard, MessageContext@@ -608,8 +687,17 @@ class UpdateChecker:except Exception as e:logger.error("Failed to edit Discord update message: %s", e)else:- # Fallback: send a new message to owner- if platform == "slack":+ # Fallback: send a new message to admins, or workspace owner+ admin_ids = self._get_admin_user_ids()+ if admin_ids:+ for uid in admin_ids:+ try:+ await im_client.send_dm(uid, success_text)+ logger.info(f"Sent post-update notification to admin {uid}")+ except Exception as e:+ logger.error(f"Failed to send post-update notification to admin {uid}: {e}")+ elif platform == "slack":+ # Legacy fallback: try workspace ownerowner_id = await self._get_workspace_owner_id()if owner_id:dm_channel = await self._open_dm_channel(owner_id)diff --git a/docs/plans/dm-bind-admin-permission.md b/docs/plans/dm-bind-admin-permission.mdnew file mode 100644index 000000000..9f3a5bdc8--- /dev/null+++ b/docs/plans/dm-bind-admin-permission.md@@ -0,0 +1,365 @@+# DM Bind & Admin Permission Plan++## Background++Vibe Remote currently allows any user in an enabled channel to access all bot management functions (settings, routing, CWD changes, etc.) via the `/start` menu buttons. There is no permission control — any user can modify bot configuration. Additionally, DM (private chat) with the bot is technically possible on all three platforms but has no authorization mechanism.++This plan introduces:+1. **DM bind mechanism** — users must authenticate via a bind code before using the bot in private chat.+2. **User management UI** — a User List tab parallel to the Channel List, with per-user settings.+3. **Admin permission control** — only designated admins can use management buttons in channels and DMs.++## Goals++- Add a User List tab in the web UI, structurally identical to Channel List, for managing bound users.+- Implement a bind code system so that DM access is explicitly authorized.+- Allow per-user settings (CWD, routing, message types) just like per-channel settings.+- Add an `is_admin` flag per user; only admins can operate management buttons in `/start` menu.+- Route update notifications to Vibe Remote admins instead of platform workspace owners.+- Support all three platforms: Slack, Discord, Lark/Feishu.++## Non-Goals++- Platform-native admin role detection (Slack `is_admin`, Discord `guild_permissions.administrator`, Lark `is_tenant_manager`) — we use a self-managed admin list instead.+- User list fetching from platform APIs (no `users.list`, `guild.fetch_members()`, etc.) — users appear in the list only after binding.+- Multi-platform simultaneous operation (Vibe Remote runs one platform at a time).++## Key Concepts++### Bind Code++A short alphanumeric code (e.g., `vr-a3x9k2`) that authorizes a user to DM the bot. Two types:++| Type | Behavior |+|------|----------|+| **One-time** | Single use, invalidated after one successful bind |+| **Expiring** | Reusable until expiration date, supports multiple binds |++Bind codes are created in the web UI by whoever has access to the admin panel (localhost). The first bind code is auto-generated during setup wizard completion.++### User Lifecycle++```+Admin creates bind code in Web UI+ → User sends `/bind <code>` to bot in DM+ → Bot validates code, creates user entry in settings+ → User appears in User List with default settings+ → Admin can toggle is_admin for that user in Web UI+```++### Permission Model++| Action | Requires Admin? |+|--------|----------------|+| Send messages to bot (in enabled channel) | No |+| Send messages to bot (in DM, after bind) | No |+| `/start` — view menu | No |+| `/clear` — clear conversation | No |+| `/resume` — resume session | No |+| `/cwd` — view current CWD | No |+| Click Settings button | Yes |+| Click Routing button | Yes |+| Click Change CWD button | Yes |+| Click Update Now button | Yes |+| `/bind <code>` — bind in DM | No (requires valid code) |++Unauthorized button clicks receive an ephemeral/private message: "Only admins can change bot settings."++## Data Model++### New: UserSettings (config/v2_settings.py)++```python+@dataclass+class UserSettings:+ display_name: str = ""+ is_admin: bool = False+ bound_at: str = "" # ISO 8601 timestamp+ enabled: bool = True+ show_message_types: List[str] = field(default_factory=list)+ custom_cwd: Optional[str] = None+ routing: RoutingSettings = field(default_factory=RoutingSettings)+ require_mention: Optional[bool] = None # Not applicable for DM, but kept for consistency+```++### New: BindCode (config/v2_settings.py)++```python+@dataclass+class BindCode:+ code: str # e.g. "vr-a3x9k2"+ type: str # "one_time" or "expiring"+ created_at: str # ISO 8601+ expires_at: Optional[str] = None # ISO 8601, only for "expiring" type+ is_active: bool = True # False after one-time code is used+ used_by: List[str] = field(default_factory=list) # user_ids that used this code+```++### Extended: SettingsState++```python+@dataclass+class SettingsState:+ channels: Dict[str, ChannelSettings] = field(default_factory=dict)+ users: Dict[str, UserSettings] = field(default_factory=dict) # NEW+ bind_codes: List[BindCode] = field(default_factory=list) # NEW+```++### settings.json Example++```json+{+ "channels": {+ "C0123456789": {+ "enabled": true,+ "custom_cwd": "/home/user/project",+ "routing": { "agent_backend": "opencode" },+ "show_message_types": [],+ "require_mention": null+ }+ },+ "users": {+ "U0E0FM3QT": {+ "display_name": "cyh",+ "is_admin": true,+ "bound_at": "2026-03-13T10:05:00Z",+ "enabled": true,+ "custom_cwd": null,+ "routing": { "agent_backend": "opencode" },+ "show_message_types": [],+ "require_mention": null+ }+ },+ "bind_codes": [+ {+ "code": "vr-a3x9k2",+ "type": "one_time",+ "created_at": "2026-03-13T10:00:00Z",+ "expires_at": null,+ "is_active": false,+ "used_by": ["U0E0FM3QT"]+ },+ {+ "code": "vr-open2026",+ "type": "expiring",+ "created_at": "2026-03-13T10:00:00Z",+ "expires_at": "2026-03-20T10:00:00Z",+ "is_active": true,+ "used_by": ["U12345678"]+ }+ ]+}+```++## API Endpoints (New)++### User Management++| Method | Path | Description |+|--------|------|-------------|+| `GET /users` | — | List all bound users with settings |+| `POST /users` | — | Save all user settings (bulk, same pattern as `/settings`) |+| `POST /users/<user_id>/admin` | `{"is_admin": true}` | Toggle admin flag for a user |+| `DELETE /users/<user_id>` | — | Remove a bound user |++### Bind Code Management++| Method | Path | Description |+|--------|------|-------------|+| `GET /bind-codes` | — | List all bind codes (with usage info) |+| `POST /bind-codes` | `{"type": "one_time"}` or `{"type": "expiring", "expires_at": "..."}` | Create a new bind code |+| `DELETE /bind-codes/<code>` | — | Deactivate/delete a bind code |++### Setup Wizard Extension++| Method | Path | Description |+|--------|------|-------------|+| `GET /setup/first-bind-code` | — | Get or generate the initial bind code (shown on wizard Summary page) |++## IM Command: /bind++### Flow++```+User DMs bot: /bind vr-a3x9k2+ → Bot checks: is this a DM? (Slack: D-prefix, Discord: DMChannel, Lark: p2p)+ → Bot looks up code in settings.bind_codes+ → Validates: is_active? not expired? correct type?+ → If valid:+ - Fetch user info (display_name) via platform API+ - Create UserSettings entry in settings.users+ - If one_time: mark code is_active=false+ - Add user_id to code's used_by list+ - Reply: "Bind successful! You can now use the bot in DM."+ - If this is the first user AND no admins exist: auto-set is_admin=true+ → If invalid:+ - Reply: "Invalid or expired bind code."+```++### DM Message Filtering++In each IM client's message handler, before processing a DM message:++```python+# Pseudocode for all three platforms+if is_dm_message(context):+ user_id = context.user_id+ if not settings_store.is_bound_user(user_id):+ # Check if message is /bind command+ if message.startswith("/bind "):+ await handle_bind_command(context, message)+ return+ # Otherwise reject+ await send_ephemeral(context, "Please use /bind <code> to activate DM access.")+ return+ # Bound user — continue normal processing with user-specific settings+```++## Frontend Changes++### Navigation++AppShell sidebar adds a new nav item:+- **Users** (`Users` icon from lucide-react) → route `/users`++### New Route++| Route | Component | Description |+|-------|-----------|-------------|+| `/users` | `UserList isPage` | User management page |++### UserList Component++Reuse the ChannelList component pattern. The UserList and ChannelList should share as much structure as possible.++**Option A (Recommended): Extract a shared `EntityList` component**++```+EntityList+ ├── props: entities[], entityType ("channel" | "user"), onSave(), ...+ ├── Per-entity: enable toggle, settings (CWD, routing, message types)+ ├── User-specific: is_admin toggle, bound_at display+ └── Channel-specific: require_mention setting+```++Both `/channels` and `/users` pages use `EntityList` with different `entityType` and data sources.++**Option B: Copy ChannelList and modify**++Simpler but duplicates code. Less maintainable.++### Bind Code Management Section++On the `/users` page, above or below the user list, add a "Bind Codes" section:++```+┌─────────────────────────────────────────────────┐+│ Bind Codes [+ New Code] │+├─────────────────────────────────────────────────┤+│ vr-a3x9k2 One-time Used by cyh [Copy] │+│ vr-open2026 Expires 3/20 1 user used [Copy] │+│ vr-tmp123 One-time Active [Copy] │+└─────────────────────────────────────────────────┘+```++"+ New Code" opens an inline form:+- Type: One-time / Expiring (radio)+- If Expiring: date picker for expiration+- Generate → shows code with copy button++### Wizard Summary Page Extension++On the Summary page (final wizard step), after "Launch Service":+- Show the auto-generated first bind code+- Instructions: "Send `/bind <code>` to the bot in a DM to become the first admin."++## Implementation Plan++### Phase 1: Data Model & API (Backend)++- [ ] Extend `config/v2_settings.py`:+ - Add `UserSettings` dataclass+ - Add `BindCode` dataclass+ - Extend `SettingsState` with `users` and `bind_codes`+ - Update `SettingsStore._load()` and `.save()` to handle new fields+ - Add helper methods: `get_user()`, `update_user()`, `remove_user()`, `is_bound_user()`, `is_admin()`, `get_admins()`+ - Add bind code methods: `create_bind_code()`, `validate_bind_code()`, `use_bind_code()`, `deactivate_bind_code()`, `get_bind_codes()`+- [ ] Extend `vibe/api.py`:+ - Add `get_users()`, `save_users()`, `toggle_admin()`, `remove_user()` functions+ - Add `get_bind_codes()`, `create_bind_code()`, `delete_bind_code()` functions+ - Add `get_first_bind_code()` for wizard+- [ ] Extend `vibe/ui_server.py`:+ - Register new endpoints: `/users`, `/users/<id>/admin`, `/bind-codes`, `/setup/first-bind-code`++### Phase 2: IM Command & DM Filtering++- [ ] Add `/bind` command handler in `core/handlers/command_handlers.py`:+ - Parse bind code from message+ - Validate code via `SettingsStore`+ - Create user entry with platform user info+ - Auto-admin logic for first user+- [ ] Add DM authorization check in each IM client:+ - `modules/im/slack.py`: In message handler, check `channel_id.startswith("D")` → verify bound+ - `modules/im/discord.py`: In `on_message`, check `is_dm` → verify bound+ - `modules/im/feishu.py`: In message handler, check `is_p2p` → verify bound+- [ ] For unbound DM users: reply with bind instruction, then return (don't process)+- [ ] For `/bind` command: process even if unbound (it's the binding action itself)++### Phase 3: Admin Permission Check++- [ ] Add permission check in `core/handlers/message_handler.py` `handle_callback_query()`:+ - Define protected callback_data prefixes: `cmd_settings`, `cmd_routing`, `cmd_change_cwd`, `vibe_update_now`+ - Before routing to handler, check `settings_store.is_admin(context.user_id)`+ - If not admin: send ephemeral/private rejection message, return+- [ ] Update Discord's existing update button permission check to use the new unified mechanism+- [ ] Add i18n keys for permission error messages++### Phase 4: Frontend — User List & Bind Codes++- [ ] Refactor `ChannelList.tsx` into a shared `EntityList` component (or add `entityType` prop)+- [ ] Create `/users` route and `UserList` page component+- [ ] Add bind code management UI section+- [ ] Add "Users" nav item to `AppShell.tsx`+- [ ] Add `ApiContext` methods: `getUsers()`, `saveUsers()`, `toggleAdmin()`, `removeUser()`, `getBindCodes()`, `createBindCode()`, `deleteBindCode()`+- [ ] Add i18n keys (en.json + zh.json) for all new UI strings+- [ ] Extend wizard Summary step to show first bind code++### Phase 5: Update Notification Reroute++- [ ] Modify `core/update_checker.py`:+ - Replace Slack workspace owner lookup with `settings_store.get_admins()`+ - Send update DM to each admin user via `im_client.send_dm(user_id, message)`+- [ ] Add `send_dm(user_id, message)` to `BaseIMClient` interface if not present+- [ ] Implement `send_dm()` in all three IM clients:+ - Slack: `conversations_open(users=user_id)` → `chat_postMessage(channel=dm_channel_id)`+ - Discord: `user.create_dm()` → `dm_channel.send()`+ - Lark: `POST /im/v1/messages?receive_id_type=open_id` with `receive_id=user_open_id`++## Testing++- Manual: Start bot → generate bind code in UI → DM bot with `/bind <code>` → verify DM works+- Manual: Set user as admin in UI → verify only admin can click Settings/Routing buttons+- Manual: Non-admin clicks Settings → verify rejection message appears+- Manual: Verify one-time code becomes inactive after use+- Manual: Verify expiring code rejects after expiration+- Manual: Verify first bound user auto-becomes admin+- Manual: Verify update notification goes to admins, not workspace owners++## Risks & Mitigations++| Risk | Mitigation |+|------|-----------|+| User loses the first bind code | Web UI can always generate new codes; the setup person has localhost access |+| All admins are removed | Prevent removing the last admin in both UI and API |+| Bot restart clears bind state | All state is persisted to `settings.json` on disk |+| Platform user_id format differences | IDs are opaque strings, no format assumptions; one platform active at a time |+| Existing deployments have no admins | Migration: if `users` key is missing in settings.json, all management buttons remain open (backward compatible). First `/bind` creates the admin. Or: show a migration prompt in web UI. |++## Migration Strategy++For existing Vibe Remote deployments upgrading to this version:++1. `settings.json` without `users`/`bind_codes` keys → treated as empty (no users, no bind codes).+2. **DM behavior**: If no users are configured, DM messages are rejected with bind instructions (same as new installs).+3. **Channel behavior**: If no admins exist, management buttons remain unrestricted (backward compatible). Once the first admin is created, permission enforcement activates.+4. Web UI shows a banner: "No admins configured. Create a bind code and bind a user to enable permission control."diff --git a/modules/im/base.py b/modules/im/base.pyindex 004206673..2a97732e1 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -322,6 +322,24 @@ class BaseIMClient(ABC):"""return False+ async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:+ """Send a direct message to a user by their platform user ID.++ This is a convenience method for sending DMs without requiring a+ pre-existing MessageContext. Subclasses should override with+ platform-specific DM-open + send logic.++ Args:+ user_id: Platform-specific user ID+ text: Message text+ **kwargs: Additional platform-specific arguments (e.g. blocks for Slack)++ Returns:+ Message ID of the sent message, or None on failure+ """+ logger.warning("send_dm not implemented for this platform")+ return None+@abstractmethoddef format_markdown(self, text: str) -> str:"""Format markdown text for the specific platformdiff --git a/modules/im/discord.py b/modules/im/discord.pyindex 66991134f..443e385c7 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -146,6 +146,24 @@ class DiscordBot(BaseIMClient):return Falsereturn True+ async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:+ """Send a direct message to a Discord user."""+ try:+ uid = self._to_int_id(user_id)+ if uid is None:+ return None+ user = self.client.get_user(uid)+ if user is None:+ user = await self.client.fetch_user(uid)+ if user is None:+ return None+ dm_channel = user.dm_channel or await user.create_dm()+ message = await dm_channel.send(content=text)+ return str(message.id)+ except Exception as e:+ logger.error("Failed to send DM to Discord user %s: %s", user_id, e)+ return None+async def send_message(self,context: MessageContext,@@ -462,6 +480,21 @@ class DiscordBot(BaseIMClient):bot_id = str(self.client.user.id)content = content.replace(f"<@{bot_id}>", "").replace(f"<@!{bot_id}>", "").strip()+ # DM authorization gate: require user to be bound for DM access+ if is_dm and self.settings_manager:+ store = self.settings_manager.store+ if not store.is_bound_user(str(message.author.id)):+ # Allow /bind command through for unbound users+ if content.startswith("/bind ") or content == "/bind":+ pass # Will be handled by command routing below+ else:+ try:+ hint = self._t("bind.dmNotBound", channel_id)+ await channel.send(content=hint)+ except Exception as e:+ logger.error(f"Failed to send DM bind hint: {e}")+ return+# Handle slash-like commands in plain messagesif content.startswith("/"):command_context = MessageContext(diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 5038b88b1..07eed404c 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -253,6 +253,38 @@ class FeishuBot(BaseIMClient):# ------------------------------------------------------------------# Sending messages# ------------------------------------------------------------------+ async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:+ """Send a direct message to a Feishu/Lark user by open_id.++ Uses receive_id_type=open_id to send directly to the user without+ needing to open a DM chat first.+ """+ self._ensure_client()+ try:+ from lark_oapi.api.im.v1 import (+ CreateMessageRequest,+ CreateMessageRequestBody,+ )++ content = self._build_card_json(text)+ body = (+ CreateMessageRequestBody.builder().receive_id(user_id).msg_type("interactive").content(content).build()+ )+ request = CreateMessageRequest.builder().receive_id_type("open_id").request_body(body).build()+ response = await self._lark_client.im.v1.message.acreate(request)+ if not response.success():+ logger.error(+ "Failed to send Feishu DM to %s: code=%s msg=%s",+ user_id,+ response.code,+ response.msg,+ )+ return None+ return response.data.message_id+ except Exception as e:+ logger.error("Failed to send DM to Feishu user %s: %s", user_id, e)+ return None+async def send_message(self,context: MessageContext,@@ -1065,6 +1097,22 @@ class FeishuBot(BaseIMClient):else:return+ # DM (p2p) authorization gate: require user to be bound for DM access+ if is_p2p and self.settings_manager:+ store = self.settings_manager.store+ if not store.is_bound_user(user_id):+ # Allow /bind command through for unbound users+ if text.startswith("/bind ") or text == "/bind":+ pass # Will be handled by command routing below+ else:+ try:+ hint_ctx = MessageContext(user_id="system", channel_id=chat_id)+ hint = self._t("bind.dmNotBound", chat_id)+ await self.send_message(hint_ctx, hint)+ except Exception as exc:+ logger.error("Failed to send DM bind hint: %s", exc)+ return+# Channel authorisationif not await self._is_authorized_channel(chat_id):logger.info("Unauthorized message from channel: %s", chat_id)diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 49e0ef2f8..4fb3a5052 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -136,6 +136,25 @@ class SlackBot(BaseIMClient):# Fallback to original text if conversion failsreturn text+ async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:+ """Send a direct message to a Slack user by opening a DM channel first."""+ self._ensure_clients()+ try:+ resp = await self.web_client.conversations_open(users=[user_id])+ if not resp.get("ok"):+ logger.warning("Failed to open DM channel with user %s", user_id)+ return None+ dm_channel = resp.get("channel", {}).get("id")+ if not dm_channel:+ return None+ msg_kwargs = {"channel": dm_channel, "text": text}+ msg_kwargs.update(kwargs)+ result = await self.web_client.chat_postMessage(**msg_kwargs)+ return result.get("ts")+ except Exception as e:+ logger.error("Failed to send DM to Slack user %s: %s", user_id, e)+ return None+async def send_message(self,context: MessageContext,@@ -875,6 +894,22 @@ class SlackBot(BaseIMClient):logger.debug(f"No settings_manager, ignoring thread message: '{text}'")return+ # DM authorization gate: require user to be bound for DM access+ if channel_id.startswith("D") and self.settings_manager:+ store = self.settings_manager.store+ if not store.is_bound_user(user_id):+ # Allow /bind command through for unbound users+ if text.startswith("/bind ") or text == "/bind":+ pass # Will be handled by command routing below+ else:+ try:+ self._ensure_clients()+ hint = self._t("bind.dmNotBound", channel_id)+ await self.web_client.chat_postMessage(channel=channel_id, text=hint)+ except Exception as e:+ logger.error(f"Failed to send DM bind hint: {e}")+ return+# Only check channel authorization for messages we're actually going to processif not await self._is_authorized_channel(channel_id):logger.info(f"Unauthorized message from channel: {channel_id}")diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex b7d0dedb7..c71f33447 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -3,6 +3,7 @@ import { Wizard } from './components/Wizard';import { AppShell } from './components/AppShell';import { Dashboard } from './components/Dashboard';import { ChannelList } from './components/steps/ChannelList';+import { UserList } from './components/steps/UserList';import { DoctorPanel } from './components/steps/DoctorPanel';import { LogsPanel } from './components/steps/LogsPanel';import { StatusProvider } from './context/StatusContext';@@ -47,6 +48,7 @@ function AppRoutes() {<Route element={<AuthGuard><AppShell /></AuthGuard>}><Route path="/dashboard" element={<Dashboard />} /><Route path="/channels" element={<ChannelList isPage />} />+ <Route path="/users" element={<UserList />} /><Route path="/doctor" element={<DoctorPanel isPage />} /><Route path="/doctor/logs" element={<LogsPanel />} /><Route path="/" element={<Navigate to="/dashboard" replace />} />diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 439633a94..38121c80a 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,6 +1,6 @@import React from 'react';import { NavLink, Outlet, useLocation } from 'react-router-dom';-import { LayoutDashboard, MessageSquare, Activity } from 'lucide-react';+import { LayoutDashboard, MessageSquare, Activity, Users } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useStatus } from '../context/StatusContext';import { LanguageSwitcher } from './LanguageSwitcher';@@ -53,6 +53,7 @@ export const AppShell: React.FC = () => {<nav className="flex-1 p-4 space-y-1"><NavItem to="/dashboard" icon={LayoutDashboard}>{t('nav.dashboard')}</NavItem><NavItem to="/channels" icon={MessageSquare}>{t('nav.channels')}</NavItem>+ <NavItem to="/users" icon={Users}>{t('nav.users')}</NavItem><NavItem to="/doctor" icon={Activity}>{t('nav.doctor')}</NavItem></nav>@@ -76,6 +77,7 @@ export const AppShell: React.FC = () => {<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-panel border-t border-border flex justify-around p-3 z-50 pb-safe"><NavLink to="/dashboard" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><LayoutDashboard /></NavLink><NavLink to="/channels" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><MessageSquare /></NavLink>+ <NavLink to="/users" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Users /></NavLink><NavLink to="/doctor" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Activity /></NavLink></nav></div>diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex 11c47a417..a006bbb37 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import { CheckCircle2, MessageSquare, Zap, Terminal } from 'lucide-react';+import { CheckCircle2, MessageSquare, Zap, Terminal, Copy, Check, Key } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';import { useStatus } from '../../context/StatusContext';@@ -19,6 +19,8 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {const { control } = useStatus();const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ const [bindCode, setBindCode] = useState<string | null>(null);+ const [codeCopied, setCodeCopied] = useState(false);const platform = data.platform || 'slack';const [requireMention, setRequireMention] = useState(platform === 'discord' ? (data.discord?.require_mention || false)@@ -28,6 +30,17 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {const [autoUpdate, setAutoUpdate] = useState(data.update?.auto_update ?? true);const navigate = useNavigate();+ const copyBindCode = async () => {+ if (!bindCode) return;+ try {+ await navigator.clipboard.writeText(`/bind ${bindCode}`);+ setCodeCopied(true);+ setTimeout(() => setCodeCopied(false), 2000);+ } catch {+ // Fallback: select text+ }+ };+const saveAll = async () => {setSaving(true);setError(null);@@ -56,8 +69,21 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {await api.saveSettings(buildSettingsPayload(updatedData));// Start service- await control('start'); // Use start, fallback to restart if running? Or just start.- // Wait a bit then redirect+ await control('start');++ // Fetch first bind code (auto-generated on first access)+ try {+ const resp = await api.getFirstBindCode();+ if (resp?.code) {+ setBindCode(resp.code);+ setSaving(false);+ return; // Don't navigate yet — show bind code first+ }+ } catch {+ // Non-critical: skip bind code display+ }++ // No bind code — redirect immediatelysetTimeout(() => {navigate('/dashboard');}, 1000);@@ -70,6 +96,51 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {}};+ // If bind code is available, show the bind code screen+ if (bindCode) {+ return (+ <div className="flex flex-col h-full max-w-2xl mx-auto items-center justify-center">+ <div className="w-16 h-16 bg-success/10 text-success rounded-full flex items-center justify-center border border-success/20 mb-6">+ <CheckCircle2 size={40} />+ </div>+ <h2 className="text-2xl font-display font-bold text-text mb-2">{t('summary.title')}</h2>+ <p className="text-muted mb-8">Vibe Remote is running!</p>++ <div className="bg-panel border border-border rounded-lg p-6 shadow-sm w-full max-w-md">+ <div className="flex items-center gap-3 mb-4">+ <div className="w-10 h-10 bg-warning/10 text-warning rounded-lg flex items-center justify-center flex-shrink-0">+ <Key size={20} />+ </div>+ <div>+ <h3 className="text-base font-semibold text-text">{t('summary.bindCodeTitle')}</h3>+ <p className="text-xs text-muted">{t('summary.bindCodeDesc')}</p>+ </div>+ </div>+ <div className="flex items-center gap-2 bg-bg border border-border rounded-md p-3">+ <code className="flex-1 text-sm font-mono text-text select-all">/bind {bindCode}</code>+ <button+ onClick={copyBindCode}+ className="p-2 text-muted hover:text-text transition-colors rounded-md hover:bg-panel"+ title="Copy"+ >+ {codeCopied ? <Check size={16} className="text-success" /> : <Copy size={16} />}+ </button>+ </div>+ {codeCopied && (+ <p className="text-xs text-success mt-2">{t('summary.bindCodeCopied')}</p>+ )}+ </div>++ <button+ onClick={() => navigate('/dashboard')}+ className="mt-8 px-8 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg font-bold transition-colors shadow-sm"+ >+ Go to Dashboard+ </button>+ </div>+ );+ }+return (<div className="flex flex-col h-full max-w-2xl mx-auto"><div className="flex items-center gap-4 mb-8">diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxnew file mode 100644index 000000000..cbe00c13e--- /dev/null+++ b/ui/src/components/steps/UserList.tsx@@ -0,0 +1,653 @@+import React, { useEffect, useState } from 'react';+import { User, Shield, ShieldOff, Copy, Check, Plus, Trash2, FolderOpen, HelpCircle } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { useApi } from '../../context/ApiContext';+import { useToast } from '../../context/ToastContext';+import { Combobox } from '../ui/combobox';+import { DirectoryBrowser } from '../ui/directory-browser';+import clsx from 'clsx';++/** Input that only commits value on blur */+function BlurInput({+ value,+ onCommit,+ ...props+}: { value: string; onCommit: (v: string) => void } & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange' | 'onBlur'>) {+ const [local, setLocal] = useState(value);+ useEffect(() => setLocal(value), [value]);+ return (+ <input+ {...props}+ value={local}+ onChange={(e) => setLocal(e.target.value)}+ onBlur={() => { if (local !== value) onCommit(local); }}+ />+ );+}++interface UserConfig {+ display_name: string;+ is_admin: boolean;+ bound_at: string;+ enabled: boolean;+ show_message_types: string[];+ custom_cwd: string;+ routing: {+ agent_backend: string | null;+ opencode_agent?: string | null;+ opencode_model?: string | null;+ opencode_reasoning_effort?: string | null;+ claude_agent?: string | null;+ claude_model?: string | null;+ codex_model?: string | null;+ codex_reasoning_effort?: string | null;+ };+}++interface BindCodeItem {+ code: string;+ type: string;+ created_at: string;+ expires_at: string | null;+ is_active: boolean;+ used_by: string[];+}++// ─── Bind Code Section ───────────────────────────────────────────────────++const BindCodeSection: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const [codes, setCodes] = useState<BindCodeItem[]>([]);+ const [showForm, setShowForm] = useState(false);+ const [newType, setNewType] = useState<'one_time' | 'expiring'>('one_time');+ const [newExpiry, setNewExpiry] = useState('');+ const [copiedCode, setCopiedCode] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);++ const loadCodes = async () => {+ try {+ const result = await api.getBindCodes();+ if (result.ok) setCodes(result.bind_codes || []);+ } catch (e) {+ console.error('Failed to load bind codes:', e);+ }+ };++ useEffect(() => { loadCodes(); }, []);++ const handleCreate = async () => {+ setLoading(true);+ try {+ const result = await api.createBindCode(newType, newType === 'expiring' ? newExpiry : undefined);+ if (result.ok) {+ showToast(t('bindCode.created'));+ setShowForm(false);+ setNewType('one_time');+ setNewExpiry('');+ loadCodes();+ }+ } catch (e) {+ console.error('Failed to create bind code:', e);+ } finally {+ setLoading(false);+ }+ };++ const handleDelete = async (code: string) => {+ try {+ const result = await api.deleteBindCode(code);+ if (result.ok) {+ showToast(t('bindCode.deleted'));+ loadCodes();+ }+ } catch (e) {+ console.error('Failed to delete bind code:', e);+ }+ };++ const handleCopy = (code: string) => {+ navigator.clipboard.writeText(code);+ setCopiedCode(code);+ setTimeout(() => setCopiedCode(null), 2000);+ };++ const getCodeStatus = (bc: BindCodeItem) => {+ if (!bc.is_active) {+ return bc.type === 'one_time' && bc.used_by.length > 0 ? 'used' : 'inactive';+ }+ if (bc.type === 'expiring' && bc.expires_at) {+ if (new Date(bc.expires_at) < new Date()) return 'expired';+ }+ return 'active';+ };++ const statusColors: Record<string, string> = {+ active: 'bg-success/10 text-success border-success/20',+ used: 'bg-neutral-100 text-muted border-border',+ expired: 'bg-warning/10 text-warning border-warning/20',+ inactive: 'bg-neutral-100 text-muted border-border',+ };++ return (+ <div className="mb-6 bg-panel border border-border rounded-xl p-4 shadow-sm">+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold font-display">{t('bindCode.title')}</h3>+ <button+ onClick={() => setShowForm(!showForm)}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium transition-colors"+ >+ <Plus size={14} /> {t('bindCode.newCode')}+ </button>+ </div>++ {showForm && (+ <div className="mb-4 p-3 bg-bg border border-border rounded-lg space-y-3">+ <div className="flex items-center gap-4">+ <label className="text-sm text-muted">{t('bindCode.codeType')}</label>+ <label className="flex items-center gap-1.5 text-sm">+ <input type="radio" checked={newType === 'one_time'} onChange={() => setNewType('one_time')} className="text-accent" />+ {t('bindCode.oneTime')}+ </label>+ <label className="flex items-center gap-1.5 text-sm">+ <input type="radio" checked={newType === 'expiring'} onChange={() => setNewType('expiring')} className="text-accent" />+ {t('bindCode.expiring')}+ </label>+ </div>+ {newType === 'expiring' && (+ <div className="flex items-center gap-3">+ <label className="text-sm text-muted">{t('bindCode.expirationDate')}</label>+ <input+ type="date"+ value={newExpiry}+ onChange={(e) => setNewExpiry(e.target.value)}+ min={new Date().toISOString().split('T')[0]}+ className="bg-bg border border-border rounded px-3 py-1.5 text-sm focus:outline-none focus:border-accent text-text"+ />+ </div>+ )}+ <button+ onClick={handleCreate}+ disabled={loading || (newType === 'expiring' && !newExpiry)}+ className="px-4 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium disabled:opacity-50 transition-colors"+ >+ {t('bindCode.generate')}+ </button>+ </div>+ )}++ {codes.length === 0 ? (+ <p className="text-sm text-muted">{t('userList.noUsers')}</p>+ ) : (+ <div className="divide-y divide-border">+ {codes.map((bc) => {+ const status = getCodeStatus(bc);+ return (+ <div key={bc.code} className="flex items-center justify-between py-2.5">+ <div className="flex items-center gap-3">+ <code className="font-mono text-sm bg-bg px-2 py-0.5 rounded border border-border">{bc.code}</code>+ <span className={clsx('text-xs px-2 py-0.5 rounded-full border', statusColors[status])}>+ {t(`bindCode.${status}`)}+ </span>+ <span className="text-xs text-muted">+ {bc.type === 'one_time' ? t('bindCode.oneTime') : t('bindCode.expiring')}+ </span>+ {bc.used_by.length > 0 && (+ <span className="text-xs text-muted">{t('bindCode.usedBy', { count: bc.used_by.length })}</span>+ )}+ {bc.type === 'expiring' && bc.expires_at && (+ <span className="text-xs text-muted">+ {t('bindCode.expiresAt', { date: new Date(bc.expires_at).toLocaleDateString() })}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleCopy(bc.code)}+ className="p-1.5 text-muted hover:text-text transition-colors"+ title={t('bindCode.copy')}+ >+ {copiedCode === bc.code ? <Check size={14} className="text-success" /> : <Copy size={14} />}+ </button>+ {bc.is_active && (+ <button+ onClick={() => handleDelete(bc.code)}+ className="p-1.5 text-muted hover:text-danger transition-colors"+ title={t('bindCode.delete')}+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+};++// ─── User List Page ──────────────────────────────────────────────────────++export const UserList: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const [, setLoading] = useState(false);+ const [users, setUsers] = useState<Record<string, UserConfig>>({});+ const [config, setConfig] = useState<any>({});+ const [opencodeOptionsByCwd, setOpencodeOptionsByCwd] = useState<Record<string, any>>({});+ const [claudeAgentsByCwd, setClaudeAgentsByCwd] = useState<Record<string, any[]>>({});+ const [claudeModels, setClaudeModels] = useState<string[]>([]);+ const [codexModels, setCodexModels] = useState<string[]>([]);+ const [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);++ useEffect(() => {+ api.getConfig().then(setConfig);+ loadUsers();+ }, []);++ const loadUsers = async () => {+ try {+ const result = await api.getUsers();+ if (result.ok) setUsers(result.users || {});+ } catch (e) {+ console.error('Failed to load users:', e);+ }+ };++ const loadOpenCodeOptions = async (cwd: string) => {+ try {+ const result = await api.opencodeOptions(cwd);+ if (result.ok) setOpencodeOptionsByCwd((prev) => ({ ...prev, [cwd]: result.data }));+ } catch (e) { console.error('Failed to load OpenCode options:', e); }+ };++ const loadClaudeAgents = async (cwd: string) => {+ try {+ const result = await api.claudeAgents(cwd);+ if (result.ok) setClaudeAgentsByCwd((prev) => ({ ...prev, [cwd]: result.agents || [] }));+ } catch (e) { console.error('Failed to load Claude agents:', e); }+ };++ useEffect(() => {+ if (config.agents?.claude?.enabled) api.claudeModels().then(r => r.ok && setClaudeModels(r.models || []));+ }, [config.agents?.claude?.enabled]);++ useEffect(() => {+ if (config.agents?.codex?.enabled) api.codexModels().then(r => r.ok && setCodexModels(r.models || []));+ }, [config.agents?.codex?.enabled]);++ // Load agent options for enabled users+ useEffect(() => {+ const defaultCwd = config.runtime?.default_cwd || '~/work';+ const defaultBackend = config.agents?.default_backend || 'opencode';+ Object.values(users).forEach((u) => {+ if (!u.enabled) return;+ const cwd = u.custom_cwd || defaultCwd;+ const backend = u.routing?.agent_backend || defaultBackend;+ if (backend === 'opencode' && config.agents?.opencode?.enabled && !opencodeOptionsByCwd[cwd]) loadOpenCodeOptions(cwd);+ if (backend === 'claude' && config.agents?.claude?.enabled && !claudeAgentsByCwd[cwd]) loadClaudeAgents(cwd);+ });+ }, [users, config]);++ const persistUsers = async (next: Record<string, UserConfig>) => {+ setLoading(true);+ try {+ await api.saveUsers({ users: next });+ showToast(t('userList.settingsSaved'));+ } catch {+ showToast(t('userList.settingsSaveFailed'), 'error');+ } finally {+ setLoading(false);+ }+ };++ const updateUser = (userId: string, patch: Partial<UserConfig>) => {+ const base = users[userId] || defaultUserConfig();+ const next = { ...base, ...patch };+ if (!next.routing || typeof next.routing !== 'object') {+ next.routing = { agent_backend: config.agents?.default_backend || 'opencode' };+ }+ const nextUsers = { ...users, [userId]: next };+ setUsers(nextUsers);+ void persistUsers(nextUsers);+ };++ const handleToggleAdmin = async (userId: string, isAdmin: boolean) => {+ try {+ const result = await api.toggleAdmin(userId, isAdmin);+ if (result.ok) {+ showToast(t('userList.adminToggled'));+ loadUsers();+ } else {+ showToast(result.error || t('userList.cannotRemoveLastAdmin'), 'error');+ }+ } catch (e) {+ console.error('Failed to toggle admin:', e);+ }+ };++ const handleRemoveUser = async (userId: string) => {+ if (!confirm(t('userList.removeConfirm'))) return;+ try {+ const result = await api.removeUser(userId);+ if (result.ok) {+ showToast(t('userList.userRemoved'));+ loadUsers();+ } else {+ showToast(result.error || '', 'error');+ }+ } catch (e) {+ console.error('Failed to remove user:', e);+ }+ };++ const defaultUserConfig = (): UserConfig => ({+ display_name: '',+ is_admin: false,+ bound_at: '',+ enabled: true,+ show_message_types: [],+ custom_cwd: '',+ routing: { agent_backend: 'opencode' },+ });++ const getReasoningOptions = (cwd: string, modelKey: string) => {+ const lookup = opencodeOptionsByCwd[cwd]?.reasoning_options || {};+ return (lookup as Record<string, { value: string; label: string }[]>)[modelKey] || [];+ };++ const userEntries = Object.entries(users).sort(+ (a, b) => Number(b[1].is_admin) - Number(a[1].is_admin) || a[1].display_name.localeCompare(b[1].display_name)+ );++ return (+ <>+ <div className="max-w-5xl mx-auto flex flex-col h-full">+ <div className="flex justify-between items-center mb-6">+ <div>+ <h2 className="text-3xl font-display font-bold">{t('userList.title')}</h2>+ <p className="text-muted">{t('userList.subtitle')}</p>+ </div>+ </div>++ <BindCodeSection />++ <div className="flex-1 overflow-y-auto border border-border rounded-xl divide-y divide-border bg-panel shadow-sm">+ {userEntries.length === 0 ? (+ <div className="p-8 text-center text-muted">{t('userList.noUsers')}</div>+ ) : (+ userEntries.map(([userId, userConfig]) => {+ const effectiveCwd = userConfig.custom_cwd || config.runtime?.default_cwd || '~/work';+ const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];+ const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];+ return (+ <div key={userId} className="p-4 hover:bg-neutral-50/50 transition-colors">+ {/* User header row */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <User size={20} className="text-muted" />+ <div>+ <div className="font-medium flex items-center gap-2 text-text">+ {userConfig.display_name || userId}+ {userConfig.is_admin && (+ <span className="text-xs px-1.5 py-0.5 rounded bg-accent/10 text-accent border border-accent/20 font-medium">{t('userList.admin')}</span>+ )}+ </div>+ <div className="text-xs text-muted font-mono">ID: {userId}</div>+ {userConfig.bound_at && (+ <div className="text-xs text-muted">+ {t('userList.boundAt')}: {new Date(userConfig.bound_at).toLocaleDateString()}+ </div>+ )}+ </div>+ </div>+ <div className="flex items-center gap-2">+ {/* Admin toggle */}+ <button+ onClick={() => handleToggleAdmin(userId, !userConfig.is_admin)}+ className={clsx(+ 'flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium transition-colors border',+ userConfig.is_admin+ ? 'bg-accent/10 text-accent border-accent/20 hover:bg-accent/20'+ : 'bg-neutral-100 text-muted border-border hover:bg-neutral-200'+ )}+ title={userConfig.is_admin ? 'Remove admin' : 'Make admin'}+ >+ {userConfig.is_admin ? <Shield size={12} /> : <ShieldOff size={12} />}+ {userConfig.is_admin ? t('userList.admin') : t('userList.user')}+ </button>+ {/* Remove */}+ <button+ onClick={() => handleRemoveUser(userId)}+ className="p-1.5 text-muted hover:text-danger transition-colors"+ title={t('userList.removeUser')}+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>++ {/* User settings (always shown for enabled users) */}+ {userConfig.enabled && (+ <div className="mt-4 pl-8 space-y-4">+ {/* Basic Settings */}+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <div className="space-y-1">+ <label className="text-xs font-medium text-muted uppercase">{t('channelList.workingDirectory')}</label>+ <div className="flex gap-1.5">+ <BlurInput+ type="text"+ placeholder={config.runtime?.default_cwd || t('channelList.useGlobalDefault')}+ value={userConfig.custom_cwd}+ onCommit={(v) => updateUser(userId, { custom_cwd: v })}+ className="flex-1 bg-bg border border-border rounded px-3 py-2 text-sm focus:outline-none focus:border-accent text-text placeholder:text-muted/50 font-mono"+ />+ <button+ type="button"+ onClick={() => setBrowsingCwdFor(userId)}+ title={t('directoryBrowser.title')}+ className="px-2 py-2 bg-neutral-100 hover:bg-neutral-200 border border-border rounded text-muted hover:text-text transition-colors shrink-0"+ >+ <FolderOpen size={14} />+ </button>+ </div>+ </div>+ <div className="space-y-1">+ <label className="text-xs font-medium text-muted uppercase">{t('channelList.backend')}</label>+ <select+ value={userConfig.routing.agent_backend || 'opencode'}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, agent_backend: e.target.value } })}+ className="w-full bg-bg border border-border rounded px-3 py-2 text-sm focus:outline-none focus:border-accent text-text"+ >+ <option value="opencode">OpenCode</option>+ <option value="claude">ClaudeCode</option>+ <option value="codex">Codex</option>+ </select>+ </div>+ </div>++ {/* Show Message Types */}+ <div className="space-y-2">+ <div className="text-xs font-medium text-muted uppercase flex items-center gap-1">+ {t('channelList.showMessageTypes')}+ <span className="relative group">+ <HelpCircle size={12} className="text-muted/50 cursor-help" />+ <span className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-text text-bg text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 w-64 whitespace-normal font-normal normal-case">+ {t('channelList.showMessageTypesHint')}+ </span>+ </span>+ </div>+ <div className="flex flex-wrap gap-3 text-sm">+ {['system', 'assistant', 'toolcall'].map((msgType) => {+ const checked = (userConfig.show_message_types || []).includes(msgType);+ return (+ <label key={msgType} className="flex items-center gap-2 text-text">+ <input+ type="checkbox"+ checked={checked}+ onChange={() => {+ const next = checked+ ? userConfig.show_message_types.filter((v) => v !== msgType)+ : [...(userConfig.show_message_types || []), msgType];+ updateUser(userId, { show_message_types: next });+ }}+ className="h-4 w-4 rounded border-border text-accent focus:ring-accent"+ />+ <span className="capitalize">{msgType === 'toolcall' ? 'Toolcall' : msgType}</span>+ </label>+ );+ })}+ </div>+ </div>++ {/* OpenCode Settings */}+ {(!userConfig.routing.agent_backend || userConfig.routing.agent_backend === 'opencode') && (+ <div className="space-y-3">+ <div className="text-xs font-medium text-muted uppercase">{t('channelList.opencodeSettings')}</div>+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3 bg-bg/50 p-3 rounded border border-border">+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.agent')}</label>+ <select+ value={userConfig.routing.opencode_agent || ''}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, opencode_agent: e.target.value || null } })}+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"+ >+ <option value="">{t('common.default')}</option>+ {(opencodeOptions?.agents || []).map((a: any) => (+ <option key={a.name} value={a.name}>{a.name}</option>+ ))}+ </select>+ </div>+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.model')}</label>+ <select+ value={userConfig.routing.opencode_model || ''}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, opencode_model: e.target.value || null, opencode_reasoning_effort: null } })}+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"+ >+ <option value="">{t('common.default')}</option>+ {(opencodeOptions?.models?.providers || []).flatMap((provider: any) => {+ const pid = provider.id || provider.provider_id || provider.name;+ const pLabel = provider.name || pid;+ const models = provider.models || {};+ if (Array.isArray(models)) {+ return models.map((m: any) => {+ const mid = typeof m === 'string' ? m : m.id;+ return <option key={`${pid}:${mid}`} value={`${pid}/${mid}`}>{pLabel}/{mid}</option>;+ });+ }+ return Object.keys(models).map((mid) => (+ <option key={`${pid}:${mid}`} value={`${pid}/${mid}`}>{pLabel}/{mid}</option>+ ));+ })}+ </select>+ </div>+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.reasoningEffort')}</label>+ <select+ value={userConfig.routing.opencode_reasoning_effort || ''}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, opencode_reasoning_effort: e.target.value || null } })}+ disabled={!getReasoningOptions(effectiveCwd, userConfig.routing.opencode_model || '').length}+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm disabled:opacity-50"+ >+ <option value="">{t('common.default')}</option>+ {getReasoningOptions(effectiveCwd, userConfig.routing.opencode_model || '').map((opt) => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ </div>+ </div>+ </div>+ )}++ {/* Claude Settings */}+ {userConfig.routing.agent_backend === 'claude' && (+ <div className="space-y-3">+ <div className="text-xs font-medium text-muted uppercase">{t('channelList.claudeSettings')}</div>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.agent')}</label>+ <select+ value={userConfig.routing.claude_agent || ''}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, claude_agent: e.target.value || null } })}+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"+ >+ <option value="">{t('common.default')}</option>+ {claudeAgents.map((a: any) => <option key={a.id} value={a.id}>{a.name}</option>)}+ </select>+ </div>+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.model')}</label>+ <Combobox+ options={[{ value: '', label: t('common.default') }, ...claudeModels.map(m => ({ value: m, label: m }))]}+ value={userConfig.routing.claude_model || ''}+ onValueChange={(v) => updateUser(userId, { routing: { ...userConfig.routing, claude_model: v || null } })}+ placeholder={t('channelList.claudeModelPlaceholder')}+ searchPlaceholder={t('channelList.searchModel')}+ allowCustomValue={true}+ />+ </div>+ </div>+ </div>+ )}++ {/* Codex Settings */}+ {userConfig.routing.agent_backend === 'codex' && (+ <div className="space-y-3">+ <div className="text-xs font-medium text-muted uppercase">{t('channelList.codexSettings')}</div>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.model')}</label>+ <Combobox+ options={[{ value: '', label: t('common.default') }, ...codexModels.map(m => ({ value: m, label: m }))]}+ value={userConfig.routing.codex_model || ''}+ onValueChange={(v) => updateUser(userId, { routing: { ...userConfig.routing, codex_model: v || null } })}+ placeholder={t('channelList.codexModelPlaceholder')}+ searchPlaceholder={t('channelList.searchModel')}+ allowCustomValue={true}+ />+ </div>+ <div className="space-y-1">+ <label className="text-xs text-muted">{t('channelList.reasoningEffort')}</label>+ <select+ value={userConfig.routing.codex_reasoning_effort || ''}+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, codex_reasoning_effort: e.target.value || null } })}+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"+ >+ <option value="">{t('common.default')}</option>+ <option value="low">{t('channelList.reasoningLow')}</option>+ <option value="medium">{t('channelList.reasoningMedium')}</option>+ <option value="high">{t('channelList.reasoningHigh')}</option>+ <option value="xhigh">{t('channelList.reasoningXHigh')}</option>+ </select>+ </div>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+ })+ )}+ </div>+ </div>++ {/* Directory browser modal */}+ {browsingCwdFor && (+ <DirectoryBrowser+ initialPath={users[browsingCwdFor]?.custom_cwd || config.runtime?.default_cwd || '~/work'}+ onSelect={(path) => {+ updateUser(browsingCwdFor, { custom_cwd: path });+ setBrowsingCwdFor(null);+ }}+ onClose={() => setBrowsingCwdFor(null)}+ />+ )}+ </>+ );+};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 5a6af9ae7..08fc34b1b 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -6,6 +6,14 @@ export type ApiContextType = {saveConfig: (payload: any) => Promise<any>;getSettings: () => Promise<any>;saveSettings: (payload: any) => Promise<any>;+ getUsers: () => Promise<any>;+ saveUsers: (payload: any) => Promise<any>;+ toggleAdmin: (userId: string, isAdmin: boolean) => Promise<any>;+ removeUser: (userId: string) => Promise<any>;+ getBindCodes: () => Promise<any>;+ createBindCode: (type: string, expiresAt?: string) => Promise<any>;+ deleteBindCode: (code: string) => Promise<any>;+ getFirstBindCode: () => Promise<any>;detectCli: (binary: string) => Promise<any>;installAgent: (name: string) => Promise<InstallResult>;slackAuthTest: (botToken: string) => Promise<any>;@@ -121,6 +129,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrensaveConfig: (payload) => postJson('/config', payload),getSettings: () => getJson('/settings'),saveSettings: (payload) => postJson('/settings', payload),+ getUsers: () => getJson('/users'),+ saveUsers: (payload) => postJson('/users', payload),+ toggleAdmin: (userId, isAdmin) => postJson(`/users/${encodeURIComponent(userId)}/admin`, { is_admin: isAdmin }),+ removeUser: (userId) => fetch(`/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),+ getBindCodes: () => getJson('/bind-codes'),+ createBindCode: (type, expiresAt) => postJson('/bind-codes', { type, expires_at: expiresAt }),+ deleteBindCode: (code) => fetch(`/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),+ getFirstBindCode: () => getJson('/setup/first-bind-code'),detectCli: (binary) => getJson(`/cli/detect?binary=${encodeURIComponent(binary)}`),installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),slackAuthTest: (botToken) => postJson('/slack/auth_test', { bot_token: botToken }),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex edfb87b50..7ddc8685c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -40,6 +40,7 @@"nav": {"dashboard": "Dashboard","channels": "Channels",+ "users": "Users","doctor": "Doctor"},"appShell": {@@ -325,7 +326,11 @@"tipAgentSwitchDesc": "Prefix your message with AgentName: to route to a specific agent. E.g., \"Plan: Design the API\"","tipThread": "Thread = Session","tipThreadDesc": "Each thread is an isolated session. Start multiple threads for parallel tasks.",- "finishAndStart": "Finish & Start"+ "finishAndStart": "Finish & Start",+ "bindCodeTitle": "Your First Bind Code",+ "bindCodeDesc": "Send this command to the bot in a DM to become the first admin:",+ "bindCodeCommand": "/bind",+ "bindCodeCopied": "Copied!"},"dashboard": {"title": "Dashboard",@@ -418,5 +423,40 @@"empty": "No subdirectories","showHidden": "Show hidden directories","hideHidden": "Hide hidden directories"+ },+ "userList": {+ "title": "Users",+ "subtitle": "Manage bound users and their settings",+ "noUsers": "No bound users yet. Create a bind code and share it with users.",+ "settingsSaved": "User settings saved",+ "settingsSaveFailed": "Failed to save user settings",+ "admin": "Admin",+ "user": "User",+ "boundAt": "Bound",+ "removeUser": "Remove",+ "removeConfirm": "Remove this user? This cannot be undone.",+ "cannotRemoveLastAdmin": "Cannot remove the last admin",+ "adminToggled": "Admin status updated",+ "userRemoved": "User removed"+ },+ "bindCode": {+ "title": "Bind Codes",+ "newCode": "New Code",+ "oneTime": "One-time",+ "expiring": "Expiring",+ "active": "Active",+ "used": "Used",+ "expired": "Expired",+ "inactive": "Inactive",+ "usedBy": "{{count}} used",+ "expiresAt": "Expires {{date}}",+ "copy": "Copy",+ "copied": "Copied!",+ "delete": "Delete",+ "generate": "Generate",+ "codeType": "Type",+ "expirationDate": "Expiration date",+ "created": "Bind code created",+ "deleted": "Bind code deleted"}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 919e583d5..4bb38d9db 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -40,6 +40,7 @@"nav": {"dashboard": "仪表盘","channels": "频道",+ "users": "用户","doctor": "诊断"},"appShell": {@@ -325,7 +326,11 @@"tipAgentSwitchDesc": "在消息前加 AgentName: 前缀即可路由到指定 Agent,如 \"Plan: 设计 API\"","tipThread": "Thread = 会话","tipThreadDesc": "每个 Thread 是独立会话,可开多个 Thread 并行执行任务。",- "finishAndStart": "完成并启动"+ "finishAndStart": "完成并启动",+ "bindCodeTitle": "您的首个绑定码",+ "bindCodeDesc": "在私聊中向机器人发送以下命令,成为第一个管理员:",+ "bindCodeCommand": "/bind",+ "bindCodeCopied": "已复制!"},"dashboard": {"title": "仪表盘",@@ -418,5 +423,40 @@"empty": "没有子目录","showHidden": "显示隐藏目录","hideHidden": "隐藏隐藏目录"+ },+ "userList": {+ "title": "用户",+ "subtitle": "管理已绑定的用户及其设置",+ "noUsers": "暂无绑定用户。创建绑定码并分享给用户。",+ "settingsSaved": "用户设置已保存",+ "settingsSaveFailed": "保存用户设置失败",+ "admin": "管理员",+ "user": "用户",+ "boundAt": "绑定于",+ "removeUser": "移除",+ "removeConfirm": "确定要移除此用户吗?此操作不可撤销。",+ "cannotRemoveLastAdmin": "无法移除最后一个管理员",+ "adminToggled": "管理员状态已更新",+ "userRemoved": "用户已移除"+ },+ "bindCode": {+ "title": "绑定码",+ "newCode": "新建绑定码",+ "oneTime": "一次性",+ "expiring": "有效期",+ "active": "可用",+ "used": "已使用",+ "expired": "已过期",+ "inactive": "已失效",+ "usedBy": "已使用 {{count}} 次",+ "expiresAt": "{{date}} 到期",+ "copy": "复制",+ "copied": "已复制!",+ "delete": "删除",+ "generate": "生成",+ "codeType": "类型",+ "expirationDate": "到期日期",+ "created": "绑定码已创建",+ "deleted": "绑定码已删除"}}diff --git a/vibe/api.py b/vibe/api.pyindex 27f2e738d..cb3f8beb6 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -13,8 +13,11 @@ from config.v2_config import V2Configfrom config.v2_settings import (SettingsStore,ChannelSettings,+ UserSettings,RoutingSettings,normalize_show_message_types,+ _parse_routing,+ _routing_to_dict,)from config.v2_sessions import SessionsStore@@ -109,22 +112,11 @@ def save_settings(payload: dict) -> dict:store = SettingsStore()channels = {}for channel_id, channel_payload in (payload.get("channels") or {}).items():- routing_payload = channel_payload.get("routing") or {}- routing = RoutingSettings(- agent_backend=routing_payload.get("agent_backend"),- opencode_agent=routing_payload.get("opencode_agent"),- opencode_model=routing_payload.get("opencode_model"),- opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),- claude_agent=routing_payload.get("claude_agent"),- claude_model=routing_payload.get("claude_model"),- codex_model=routing_payload.get("codex_model"),- codex_reasoning_effort=routing_payload.get("codex_reasoning_effort"),- )channels[channel_id] = ChannelSettings(enabled=channel_payload.get("enabled", True),show_message_types=normalize_show_message_types(channel_payload.get("show_message_types")),custom_cwd=channel_payload.get("custom_cwd"),- routing=routing,+ routing=_parse_routing(channel_payload.get("routing") or {}),require_mention=channel_payload.get("require_mention"),)store.settings.channels = channels@@ -374,24 +366,36 @@ async def opencode_options_async(cwd: str) -> dict:def _settings_to_payload(store: SettingsStore) -> dict:- payload = {"channels": {}}+ payload: dict = {"channels": {}, "users": {}, "bind_codes": []}for channel_id, settings in store.settings.channels.items():payload["channels"][channel_id] = {"enabled": settings.enabled,"show_message_types": normalize_show_message_types(settings.show_message_types),"custom_cwd": settings.custom_cwd,"require_mention": settings.require_mention,- "routing": {- "agent_backend": settings.routing.agent_backend,- "opencode_agent": settings.routing.opencode_agent,- "opencode_model": settings.routing.opencode_model,- "opencode_reasoning_effort": settings.routing.opencode_reasoning_effort,- "claude_agent": settings.routing.claude_agent,- "claude_model": settings.routing.claude_model,- "codex_model": settings.routing.codex_model,- "codex_reasoning_effort": settings.routing.codex_reasoning_effort,- },+ "routing": _routing_to_dict(settings.routing),+ }+ for user_id, u in store.settings.users.items():+ payload["users"][user_id] = {+ "display_name": u.display_name,+ "is_admin": u.is_admin,+ "bound_at": u.bound_at,+ "enabled": u.enabled,+ "show_message_types": u.show_message_types,+ "custom_cwd": u.custom_cwd,+ "routing": _routing_to_dict(u.routing),}+ for bc in store.settings.bind_codes:+ payload["bind_codes"].append(+ {+ "code": bc.code,+ "type": bc.type,+ "created_at": bc.created_at,+ "expires_at": bc.expires_at,+ "is_active": bc.is_active,+ "used_by": bc.used_by,+ }+ )return payload@@ -1087,6 +1091,130 @@ def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu") -> dicreturn {"ok": False, "error": str(exc)}+# ---------------------------------------------------------------------------+# User and Bind Code management (for admin permission feature)+# ---------------------------------------------------------------------------+++def get_users() -> dict:+ """Get all bound users."""+ store = SettingsStore()+ users = {}+ for user_id, u in store.settings.users.items():+ users[user_id] = {+ "display_name": u.display_name,+ "is_admin": u.is_admin,+ "bound_at": u.bound_at,+ "enabled": u.enabled,+ "show_message_types": u.show_message_types,+ "custom_cwd": u.custom_cwd,+ "routing": _routing_to_dict(u.routing),+ }+ return {"ok": True, "users": users}+++def save_users(payload: dict) -> dict:+ """Save user settings (bulk update from UI)."""+ store = SettingsStore()+ users = {}+ for user_id, up in (payload.get("users") or {}).items():+ if not isinstance(up, dict):+ continue+ users[user_id] = UserSettings(+ display_name=up.get("display_name", ""),+ is_admin=up.get("is_admin", False),+ bound_at=up.get("bound_at", ""),+ enabled=up.get("enabled", True),+ show_message_types=normalize_show_message_types(up.get("show_message_types")),+ custom_cwd=up.get("custom_cwd"),+ routing=_parse_routing(up.get("routing") or {}),+ )+ store.settings.users = users+ store.save()+ return get_users()+++def toggle_admin(user_id: str, is_admin: bool) -> dict:+ """Toggle admin status for a user."""+ store = SettingsStore()+ if not store.set_admin(user_id, is_admin):+ if not store.is_bound_user(user_id):+ return {"ok": False, "error": "User not found"}+ return {"ok": False, "error": "Cannot remove the last admin"}+ return {"ok": True}+++def remove_user(user_id: str) -> dict:+ """Remove a bound user."""+ store = SettingsStore()+ user = store.get_user(user_id)+ if user is None:+ return {"ok": False, "error": "User not found"}+ # Prevent removing the last admin+ if user.is_admin:+ admin_count = sum(1 for u in store.settings.users.values() if u.is_admin)+ if admin_count <= 1:+ return {"ok": False, "error": "Cannot remove the last admin"}+ store.remove_user(user_id)+ return {"ok": True}+++def get_bind_codes() -> dict:+ """Get all bind codes."""+ store = SettingsStore()+ codes = []+ for bc in store.get_bind_codes():+ codes.append(+ {+ "code": bc.code,+ "type": bc.type,+ "created_at": bc.created_at,+ "expires_at": bc.expires_at,+ "is_active": bc.is_active,+ "used_by": bc.used_by,+ }+ )+ return {"ok": True, "bind_codes": codes}+++def create_bind_code(code_type: str = "one_time", expires_at: Optional[str] = None) -> dict:+ """Create a new bind code."""+ if code_type not in ("one_time", "expiring"):+ return {"ok": False, "error": "type must be 'one_time' or 'expiring'"}+ store = SettingsStore()+ bc = store.create_bind_code(code_type, expires_at)+ return {+ "ok": True,+ "bind_code": {+ "code": bc.code,+ "type": bc.type,+ "created_at": bc.created_at,+ "expires_at": bc.expires_at,+ "is_active": bc.is_active,+ },+ }+++def delete_bind_code(code: str) -> dict:+ """Deactivate a bind code."""+ store = SettingsStore()+ if store.deactivate_bind_code(code):+ return {"ok": True}+ return {"ok": False, "error": "Bind code not found"}+++def get_first_bind_code() -> dict:+ """Get or create the initial bind code for setup wizard."""+ store = SettingsStore()+ # If any active code exists, return it+ for bc in store.get_bind_codes():+ if bc.is_active:+ return {"ok": True, "code": bc.code, "is_new": False}+ # Otherwise create a new one-time code+ bc = store.create_bind_code("one_time")+ return {"ok": True, "code": bc.code, "is_new": True}++# ---------------------------------------------------------------------------# Lark temporary WebSocket connection (for setup wizard)# ---------------------------------------------------------------------------diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 1a3eddd87..ac16da8c1 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -243,6 +243,18 @@"xhigh": "Extra High","max": "Max"},+ "bind": {+ "success": "✅ Bind successful! Welcome, {name}. You can now use Vibe Remote via DM.",+ "successAdmin": "✅ Bind successful! Welcome, {name}. You are the first user and have been granted admin privileges.",+ "alreadyBound": "You are already bound. No action needed.",+ "invalidCode": "❌ Invalid or expired bind code. Please check and try again.",+ "usage": "Usage: `/bind <code>`\n\nPlease enter the bind code provided by an admin.",+ "dmNotBound": "🔒 You haven't bound your account yet.\nUse `/bind <code>` to get started.",+ "error": "❌ Bind failed: {error}"+ },+ "permission": {+ "adminOnly": "🔒 Only admins can change bot settings. Contact an admin if you need access."+ },"language": {"systemDefault": "(System Default)","en": "English",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex bdbec6750..76dbd81e6 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -243,6 +243,18 @@"xhigh": "超高","max": "最大"},+ "bind": {+ "success": "✅ 绑定成功!欢迎,{name}。你现在可以通过私信使用 Vibe Remote。",+ "successAdmin": "✅ 绑定成功!欢迎,{name}。你是第一个用户,已被自动授予管理员权限。",+ "alreadyBound": "你已经绑定过了,无需再次操作。",+ "invalidCode": "❌ 无效或已过期的绑定码,请检查后重试。",+ "usage": "用法:`/bind <绑定码>`\n\n请输入管理员提供的绑定码。",+ "dmNotBound": "🔒 你还未绑定账号。\n使用 `/bind <绑定码>` 开始使用。",+ "error": "❌ 绑定失败:{error}"+ },+ "permission": {+ "adminOnly": "🔒 仅管理员可以修改 Bot 设置。如需权限请联系管理员。"+ },"language": {"systemDefault": "(系统默认)","en": "English",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 755650402..e75ece4d7 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -486,6 +486,82 @@ def browse_directory():)+# =============================================================================+# User & Bind Code Endpoints+# =============================================================================++[email protected]("/users", methods=["GET"])+def users_get():+ from vibe import api++ return jsonify(api.get_users())++[email protected]("/users", methods=["POST"])+def users_post():+ from vibe import api++ payload = request.json or {}+ return jsonify(api.save_users(payload))++[email protected]("/users/<user_id>/admin", methods=["POST"])+def users_toggle_admin(user_id):+ from vibe import api++ payload = request.json or {}+ return jsonify(api.toggle_admin(user_id, payload.get("is_admin", False)))++[email protected]("/users/<user_id>", methods=["DELETE"])+def users_delete(user_id):+ from vibe import api++ result = api.remove_user(user_id)+ if not result.get("ok"):+ return jsonify(result), 400+ return jsonify(result)++[email protected]("/bind-codes", methods=["GET"])+def bind_codes_get():+ from vibe import api++ return jsonify(api.get_bind_codes())++[email protected]("/bind-codes", methods=["POST"])+def bind_codes_post():+ from vibe import api++ payload = request.json or {}+ result = api.create_bind_code(+ code_type=payload.get("type", "one_time"),+ expires_at=payload.get("expires_at"),+ )+ if not result.get("ok"):+ return jsonify(result), 400+ return jsonify(result)++[email protected]("/bind-codes/<code>", methods=["DELETE"])+def bind_codes_delete(code):+ from vibe import api++ result = api.delete_bind_code(code)+ if not result.get("ok"):+ return jsonify(result), 404+ return jsonify(result)++[email protected]("/setup/first-bind-code", methods=["GET"])+def setup_first_bind_code():+ from vibe import api++ return jsonify(api.get_first_bind_code())++# =============================================================================# Static Files (SPA)# =============================================================================