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: add one-click OpenCode permission setup in wizard
yh cb45fc5fceede
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 689f563ba..257424f41 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -1,5 +1,5 @@import React, { useEffect, useState } from 'react';-import { Check, X, RefreshCw, Search } from 'lucide-react';+import { Check, X, RefreshCw, Search, Settings } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';@@ -16,6 +16,8 @@ type AgentState = {status?: 'unknown' | 'ok' | 'missing';};+type PermissionState = 'idle' | 'loading' | 'success' | 'error';+export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack }) => {const { t } = useTranslation();const api = useApi();@@ -28,6 +30,8 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, oncodex: { enabled: false, cli_path: 'codex', status: 'unknown' },});+ const [permissionState, setPermissionState] = useState<PermissionState>('idle');+ const [permissionMessage, setPermissionMessage] = useState<string>('');const isMissing = (agent: AgentState) => agent.status === 'missing';@@ -67,6 +71,23 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}));};+ const setupPermission = async () => {+ setPermissionState('loading');+ try {+ const result = await api.opencodeSetupPermission();+ if (result.ok) {+ setPermissionState('success');+ setPermissionMessage(result.message);+ } else {+ setPermissionState('error');+ setPermissionMessage(result.message);+ }+ } catch (e) {+ setPermissionState('error');+ setPermissionMessage(String(e));+ }+ };+const canContinue = Object.values(agents).some((agent) => agent.enabled);return (@@ -150,6 +171,32 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on</button></div></div>++ {name === 'opencode' && agent.status === 'ok' && (+ <div className="mt-2 p-3 bg-amber-50 border border-amber-200 rounded-lg">+ <p className="text-sm text-amber-800 mb-2">{t('agentDetection.permissionHint')}</p>+ <div className="flex items-center gap-3">+ <button+ onClick={setupPermission}+ disabled={permissionState === 'loading'}+ className="flex items-center gap-2 px-3 py-1.5 bg-amber-500 hover:bg-amber-600 text-white rounded text-sm font-medium transition-colors disabled:opacity-50"+ >+ {permissionState === 'loading' ? (+ <RefreshCw size={14} className="animate-spin" />+ ) : (+ <Settings size={14} />+ )}+ {t('agentDetection.setupPermission')}+ </button>+ {permissionState === 'success' && (+ <span className="text-sm text-green-600">{permissionMessage}</span>+ )}+ {permissionState === 'error' && (+ <span className="text-sm text-red-600">{permissionMessage}</span>+ )}+ </div>+ </div>+ )}</div></div>))}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 706e48ea7..29759d115 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -12,6 +12,7 @@ export type ApiContextType = {slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;doctor: () => Promise<any>;opencodeOptions: (cwd: string) => Promise<any>;+ opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;getLogs: (lines?: number) => Promise<{ logs: LogEntry[]; total: number }>;getVersion: () => Promise<VersionInfo>;doUpgrade: () => Promise<UpgradeResult>;@@ -108,6 +109,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenslackManifest: () => getJson('/slack/manifest'),doctor: () => postJson('/doctor', {}),opencodeOptions: (cwd) => postJson('/opencode/options', { cwd }),+ opencodeSetupPermission: () => postJson('/opencode/setup-permission', {}),getLogs: (lines = 500) => postJson('/logs', { lines }),getVersion: () => getJson('/version'),doUpgrade: () => postJson('/upgrade', {}),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex d7d850ae0..d78ffa914 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -116,7 +116,9 @@"cliPath": "CLI Path","cliPathPlaceholder": "Path to {{name}} CLI...","cliPathDetection": "CLI path detection and enablement",- "recommended": "(recommended)"+ "recommended": "(recommended)",+ "permissionHint": "OpenCode requires permission config to skip approval prompts.",+ "setupPermission": "Setup Permission"},"channelList": {"title": "Channel Settings",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b790d08f4..a43534d54 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -116,7 +116,9 @@"cliPath": "CLI 路径","cliPathPlaceholder": "{{name}} CLI 路径...","cliPathDetection": "CLI 路径检测和启用设置",- "recommended": "(推荐)"+ "recommended": "(推荐)",+ "permissionHint": "OpenCode 需要配置权限以跳过审批提示。",+ "setupPermission": "一键设置权限"},"channelList": {"title": "频道设置",diff --git a/vibe/api.py b/vibe/api.pyindex ba99b3820..17d6b52a9 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -145,11 +145,13 @@ def list_channels(bot_token: str) -> dict:cursor=cursor,)for channel in response.get("channels", []):- channels.append({- "id": channel.get("id"),- "name": channel.get("name"),- "is_private": channel.get("is_private", False),- })+ channels.append(+ {+ "id": channel.get("id"),+ "name": channel.get("name"),+ "is_private": channel.get("is_private", False),+ }+ )cursor = response.get("response_metadata", {}).get("next_cursor")if not cursor:break@@ -185,7 +187,9 @@ async def opencode_options_async(cwd: str) -> dict:if not config.opencode:return {"ok": False, "error": "opencode disabled"}opencode_config = config.opencode- timeout_seconds = min(10.0, float(opencode_config.request_timeout_seconds or 10))+ timeout_seconds = min(+ 10.0, float(opencode_config.request_timeout_seconds or 10)+ )def _build_reasoning_options(models: dict,@@ -221,10 +225,18 @@ async def opencode_options_async(cwd: str) -> dict:request_timeout_seconds=opencode_config.request_timeout_seconds,)await asyncio.wait_for(server.ensure_running(), timeout=timeout_seconds)- agents = await asyncio.wait_for(server.get_available_agents(cwd), timeout=timeout_seconds)- models = await asyncio.wait_for(server.get_available_models(cwd), timeout=timeout_seconds)- defaults = await asyncio.wait_for(server.get_default_config(cwd), timeout=timeout_seconds)- reasoning_options = _build_reasoning_options(models, build_reasoning_effort_options)+ agents = await asyncio.wait_for(+ server.get_available_agents(cwd), timeout=timeout_seconds+ )+ models = await asyncio.wait_for(+ server.get_available_models(cwd), timeout=timeout_seconds+ )+ defaults = await asyncio.wait_for(+ server.get_default_config(cwd), timeout=timeout_seconds+ )+ reasoning_options = _build_reasoning_options(+ models, build_reasoning_effort_options+ )data = {"agents": agents,"models": models,@@ -263,43 +275,47 @@ def _settings_to_payload(store: SettingsStore) -> dict:def get_slack_manifest() -> dict:"""Get Slack App Manifest template for self-host mode.-+Loads manifest from vibe/templates/slack_manifest.json.-+Returns:{"ok": True, "manifest": str, "manifest_compact": str} on success{"ok": False, "error": str} on failure"""import jsonimport importlib.resources-+try:manifest = None-+# Try to load from package resources (installed via pip/uv)try:- if hasattr(importlib.resources, 'files'):- package_files = importlib.resources.files('vibe')- template_path = package_files / 'templates' / 'slack_manifest.json'- if hasattr(template_path, 'read_text'):- manifest = json.loads(template_path.read_text(encoding='utf-8'))+ if hasattr(importlib.resources, "files"):+ package_files = importlib.resources.files("vibe")+ template_path = package_files / "templates" / "slack_manifest.json"+ if hasattr(template_path, "read_text"):+ manifest = json.loads(template_path.read_text(encoding="utf-8"))except (TypeError, FileNotFoundError, AttributeError, json.JSONDecodeError):pass-+# Fallback: load from file system (development mode)if manifest is None:this_dir = Path(__file__).parent- template_file = this_dir / 'templates' / 'slack_manifest.json'+ template_file = this_dir / "templates" / "slack_manifest.json"if template_file.exists():- manifest = json.loads(template_file.read_text(encoding='utf-8'))-+ manifest = json.loads(template_file.read_text(encoding="utf-8"))+if manifest is None:return {"ok": False, "error": "Manifest template file not found"}-+# Pretty JSON for display, compact JSON for URLmanifest_pretty = json.dumps(manifest, indent=2)- manifest_compact = json.dumps(manifest, separators=(',', ':'))- return {"ok": True, "manifest": manifest_pretty, "manifest_compact": manifest_compact}+ manifest_compact = json.dumps(manifest, separators=(",", ":"))+ return {+ "ok": True,+ "manifest": manifest_pretty,+ "manifest_compact": manifest_compact,+ }except Exception as exc:logger.error("Failed to load Slack manifest: %s", exc)return {"ok": False, "error": str(exc)}@@ -307,7 +323,7 @@ def get_slack_manifest() -> dict:def get_version_info() -> dict:"""Get current version and check for updates.-+Returns:{"current": str,@@ -318,10 +334,10 @@ def get_version_info() -> dict:"""import urllib.requestfrom vibe import __version__-+current = __version__result = {"current": current, "latest": None, "has_update": False, "error": None}-+try:url = "https://pypi.org/pypi/vibe-remote/json"req = urllib.request.Request(url, headers={"User-Agent": "vibe-remote"})@@ -329,46 +345,50 @@ def get_version_info() -> dict:data = json.loads(resp.read().decode("utf-8"))latest = data.get("info", {}).get("version", "")result["latest"] = latest-+# Simple version comparison (works for semver)if latest and latest != current:try:- current_parts = [int(x) for x in current.split(".")[:3] if x.isdigit()]- latest_parts = [int(x) for x in latest.split(".")[:3] if x.isdigit()]+ current_parts = [+ int(x) for x in current.split(".")[:3] if x.isdigit()+ ]+ latest_parts = [+ int(x) for x in latest.split(".")[:3] if x.isdigit()+ ]result["has_update"] = latest_parts > current_partsexcept (ValueError, AttributeError):result["has_update"] = latest != currentexcept Exception as e:result["error"] = str(e)-+return resultdef do_upgrade(auto_restart: bool = True) -> dict:"""Perform upgrade to latest version.-+Args:auto_restart: If True, restart vibe after successful upgrade-+Returns:{"ok": bool, "message": str, "output": str | None, "restarting": bool}"""import sys-+# Determine upgrade method based on how vibe was installed# Check if running from uv tool environmentexe_path = sys.executableis_uv_tool = ".local/share/uv/tools/" in exe_path or "/uv/tools/" in exe_path-+uv_path = shutil.which("uv")-+if is_uv_tool and uv_path:# Installed via uv tool, upgrade with uvcmd = [uv_path, "tool", "install", "vibe-remote", "--upgrade"]else:# Installed via pip or other method, use current Python's pipcmd = [sys.executable, "-m", "pip", "install", "--upgrade", "vibe-remote"]-+try:result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)if result.returncode == 0:@@ -388,10 +408,11 @@ def do_upgrade(auto_restart: bool = True) -> dict:start_new_session=True,)restarting = True-+return {"ok": True,- "message": "Upgrade successful." + (" Restarting..." if restarting else " Please restart vibe."),+ "message": "Upgrade successful."+ + (" Restarting..." if restarting else " Please restart vibe."),"output": result.stdout,"restarting": restarting,}@@ -403,6 +424,64 @@ def do_upgrade(auto_restart: bool = True) -> dict:"restarting": False,}except subprocess.TimeoutExpired:- return {"ok": False, "message": "Upgrade timed out", "output": None, "restarting": False}+ return {+ "ok": False,+ "message": "Upgrade timed out",+ "output": None,+ "restarting": False,+ }except Exception as e:return {"ok": False, "message": str(e), "output": None, "restarting": False}+++def setup_opencode_permission() -> dict:+ """Set OpenCode permission to 'allow' in config file.++ Always uses ~/.opencode/opencode.json as per OpenCode documentation.++ Returns:+ {"ok": bool, "message": str, "config_path": str}+ """+ from pathlib import Path++ config_path = Path.home() / ".opencode" / "opencode.json"++ try:+ config_path.parent.mkdir(parents=True, exist_ok=True)++ config = {}+ if config_path.exists():+ content = config_path.read_text(encoding="utf-8").strip()+ if content:+ config = json.loads(content)+ if not isinstance(config, dict):+ return {+ "ok": False,+ "message": "Config is not a JSON object",+ "config_path": str(config_path),+ }++ if config.get("permission") == "allow":+ return {+ "ok": True,+ "message": "Permission already set",+ "config_path": str(config_path),+ }++ config["permission"] = "allow"+ config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")++ return {+ "ok": True,+ "message": "Permission set to 'allow'",+ "config_path": str(config_path),+ }+ except json.JSONDecodeError as e:+ return {+ "ok": False,+ "message": f"Invalid JSON: {e}",+ "config_path": str(config_path),+ }+ except Exception as e:+ logger.error(f"Failed to setup OpenCode permission: {e}")+ return {"ok": False, "message": str(e), "config_path": str(config_path)}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 2b978eaab..6369aa0f0 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -90,7 +90,9 @@ def status():if running:payload["service_pid"] = payload.get("service_pid") or payload["pid"]elif payload.get("state") == "running":- runtime.write_status("stopped", "process not running", None, payload.get("ui_pid"))+ runtime.write_status(+ "stopped", "process not running", None, payload.get("ui_pid")+ )payload = runtime.read_status()payload["running"] = Falsepayload["pid"] = None@@ -209,7 +211,9 @@ def ui_reload():from config import paths as config_pathsworking_dir = get_working_dir()- command = f"from vibe.ui_server import run_ui_server; run_ui_server('{host}', {port})"+ command = (+ f"from vibe.ui_server import run_ui_server; run_ui_server('{host}', {port})"+ )stdout_path = config_paths.get_runtime_dir() / "ui_stdout.log"stderr_path = config_paths.get_runtime_dir() / "ui_stderr.log"stdout = stdout_path.open("ab")@@ -224,7 +228,9 @@ def ui_reload():)stdout.close()stderr.close()- config_paths.get_runtime_ui_pid_path().write_text(str(process.pid), encoding="utf-8")+ config_paths.get_runtime_ui_pid_path().write_text(+ str(process.pid), encoding="utf-8"+ )runtime.write_status(status.get("state", "running"),status.get("detail"),@@ -293,12 +299,14 @@ def logs():line = line.rstrip("\n")match = log_pattern.match(line)if match:- logs_list.append({- "timestamp": match.group(1),- "logger": match.group(2),- "level": match.group(3),- "message": match.group(4),- })+ logs_list.append(+ {+ "timestamp": match.group(1),+ "logger": match.group(2),+ "level": match.group(3),+ "message": match.group(4),+ }+ )elif logs_list and line:logs_list[-1]["message"] += "\n" + linereturn jsonify({"logs": logs_list, "total": len(all_lines)})@@ -326,6 +334,13 @@ def upgrade():return jsonify(result)[email protected]("/opencode/setup-permission", methods=["POST"])+def opencode_setup_permission():+ from vibe import api++ return jsonify(api.setup_opencode_permission())++# =============================================================================# Static Files (SPA)# =============================================================================@@ -347,12 +362,17 @@ def serve_static(path):resolved_path = file_path.resolve()# Security check: ensure path is within ui_dist- if ui_dist.resolve() not in resolved_path.parents and resolved_path != ui_dist.resolve():+ if (+ ui_dist.resolve() not in resolved_path.parents+ and resolved_path != ui_dist.resolve()+ ):return jsonify({"error": "not_found"}), 404if resolved_path.exists() and resolved_path.is_file():mime_type, _ = mimetypes.guess_type(str(resolved_path))- return send_file(resolved_path, mimetype=mime_type or "application/octet-stream")+ return send_file(+ resolved_path, mimetype=mime_type or "application/octet-stream"+ )# SPA fallback: serve index.html for routes without file extensionif "." not in path: