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(opencode): share the "allow tool calls" affordance across wizard + settings (#462)
Call White0481353a76dd
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 4dd727fc7..30344c796 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -1672,6 +1672,116 @@ def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, t}+def test_opencode_permission_status_reports_allow_when_set(monkeypatch, tmp_path):+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(+ json.dumps({"model": "openai/gpt-5", "permission": "allow"}), encoding="utf-8"+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result == {"ok": True, "permission_allowed": True, "config_path": str(config_path)}+++def test_opencode_permission_status_reports_not_allowed_when_unset(monkeypatch, tmp_path):+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(json.dumps({"permission": "prompt"}), encoding="utf-8")++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is True+ assert result["permission_allowed"] is False+ assert result["config_path"] == str(config_path)+++def test_opencode_permission_status_is_read_only_when_no_config(monkeypatch, tmp_path):+ # The setup wizard polls this before any opencode.json exists: it must report+ # "not allowed" without creating the file (a read, unlike the write-side+ # setup_opencode_permission).+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is True+ assert result["permission_allowed"] is False+ assert not (tmp_path / ".config" / "opencode" / "opencode.json").exists()+++def test_opencode_permission_status_reports_allow_for_global_object(monkeypatch, tmp_path):+ # OpenCode's object form ``{"permission": {"*": "allow"}}`` is an allow-all+ # config and must register as allowed — otherwise the wizard gate blocks and+ # the callout nags users who already have a working config to overwrite it.+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(json.dumps({"permission": {"*": "allow"}}), encoding="utf-8")++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is True+ assert result["permission_allowed"] is True+++def test_opencode_permission_status_object_with_tool_override_is_not_allowed(monkeypatch, tmp_path):+ # An object permission that narrows a tool to ask/deny still prompts on that+ # tool (OpenCode resolves the last matching rule), which Vibe Remote can't+ # answer — so it must NOT count as granted, keeping the write-allow button.+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(+ json.dumps({"permission": {"*": "allow", "bash": "ask"}}), encoding="utf-8"+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is True+ assert result["permission_allowed"] is False+++def test_opencode_permission_status_nested_allow_object_is_granted(monkeypatch, tmp_path):+ # A granular all-allow tree (nested rule objects) avoids every approval+ # prompt, so it must register as granted — don't nag users to overwrite a+ # config that already works.+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(+ json.dumps({"permission": {"*": "allow", "bash": {"*": "allow"}}}), encoding="utf-8"+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is True+ assert result["permission_allowed"] is True+++def test_opencode_permission_status_returns_unknown_for_invalid_config(monkeypatch, tmp_path):+ # A malformed existing config can't be auto-fixed (setup refuses to overwrite+ # invalid files), so status reports unknown (ok: False) and the wizard gate+ # fails open rather than trapping the user behind an unsatisfiable Continue.+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text("{ not valid json", encoding="utf-8")++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.opencode_permission_status()++ assert result["ok"] is False+ assert result["permission_allowed"] is False+ assert result["config_path"] == str(config_path)++def test_setup_opencode_permission_accepts_jsonc_config(monkeypatch, tmp_path):config_path = tmp_path / ".config" / "opencode" / "opencode.json"config_path.parent.mkdir(parents=True, exist_ok=True)diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxindex 0766784db..ad595a90f 100644--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -15,7 +15,6 @@ import {Save,Search,Server,- Settings,Star,Terminal,Trash2,@@ -33,12 +32,13 @@ import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';import { BackendOAuthPanel } from '../BackendOAuthPanel';import { OpencodeProviderTestPanel } from '../OpencodeProviderTestPanel';import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';+import { OpencodePermissionSetup } from '../shared/OpencodePermissionSetup';import { useBackendRuntime } from '../shared/useBackendRuntime';+import { useOpencodePermission } from '../shared/useOpencodePermission';import { useApi } from '@/context/ApiContext';import type { OpencodeProvider } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';-type PermissionState = 'idle' | 'loading' | 'success' | 'error';type FilterMode = 'all' | 'configured' | 'oauth' | 'local';type CustomProviderAdapter = 'openai-compatible' | 'anthropic-compatible';@@ -163,8 +163,8 @@ export const OpencodeProviderConfig: React.FC<{fallbackDefaultBackend: BACKEND_ID,deferRestart,});- const [permissionState, setPermissionState] = useState<PermissionState>('idle');- const [permissionMessage, setPermissionMessage] = useState('');+ const permission = useOpencodePermission();+ const { setPermissionAllowed } = permission;// Provider catalog state.const [providers, setProviders] = useState<OpencodeProvider[] | null>(null);@@ -172,11 +172,6 @@ export const OpencodeProviderConfig: React.FC<{const [providersLoading, setProvidersLoading] = useState(false);const [providersError, setProvidersError] = useState<string | null>(null);const [serverStartAttempts, setServerStartAttempts] = useState(0);- // ``true`` when opencode.json carries ``permission: "allow"`` — the- // Settings page suppresses the "Allow tool calls" affordance once- // this is the case (page feedback: a permanent "Setup permission"- // button is misleading once permission is already set).- const [permissionAllowed, setPermissionAllowed] = useState(false);// Toolbar state.const [searchQuery, setSearchQuery] = useState('');@@ -223,7 +218,7 @@ export const OpencodeProviderConfig: React.FC<{} finally {setProvidersLoading(false);}- }, [api, t]);+ }, [api, t, setPermissionAllowed]);useEffect(() => {loadProvidersRef.current = loadProviders;@@ -280,28 +275,6 @@ export const OpencodeProviderConfig: React.FC<{};}, [runtime.enabled, providersError, providersLoading, serverStartAttempts]);- const setupPermission = async () => {- setPermissionState('loading');- setPermissionMessage('');- try {- const result = await api.opencodeSetupPermission();- setPermissionState(result.ok ? 'success' : 'error');- setPermissionMessage(result.message);- showToast(result.message, result.ok ? 'success' : 'error');- if (result.ok) {- // Flip locally so the affordance vanishes immediately rather- // than waiting for the next provider refresh tick — the next- // ``loadProviders`` will recompute the value from disk anyway.- setPermissionAllowed(true);- }- } catch (e: any) {- setPermissionState('error');- const msg = e?.message || String(e);- setPermissionMessage(msg);- showToast(msg, 'error');- }- };-// ``onSaveRuntime`` and ``toggleEnabled`` are owned by// ``useBackendRuntime``; the providers reload/clear side-effect// that used to live inside the page's toggle handler is now driven@@ -753,37 +726,16 @@ export const OpencodeProviderConfig: React.FC<{runtime={runtime}hideEnableToggle={hideEnableToggle}extraSlot={- // ``permission: "allow"`` setup is OpenCode-specific: without- // it the daemon prompts on every tool call and Vibe Remote- // can't reply. Hidden once opencode.json carries the value.- runtime.cliStatus === 'ok' && !permissionAllowed ? (- <div className="rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5">- <p className="mb-2 text-[12px] text-gold">- {t('agentDetection.permissionHintStrong')}- </p>- <div className="flex flex-wrap items-center gap-3">- <Button- variant="brand-gold"- size="xs"- onClick={() => void setupPermission()}- disabled={permissionState === 'loading'}- >- {permissionState === 'loading' ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Settings className="size-3.5" />- )}- {t('agentDetection.setupPermission')}- </Button>- {permissionState === 'success' && (- <span className="text-[12px] text-mint">{permissionMessage}</span>- )}- {permissionState === 'error' && (- <span className="text-[12px] text-destructive">{permissionMessage}</span>- )}- </div>- </div>- ) : null+ // ``permission: "allow"`` setup is OpenCode-specific: without it the+ // daemon prompts on every tool call and Vibe Remote can't reply.+ // Shared with the setup wizard; hidden once opencode.json carries it.+ <OpencodePermissionSetup+ cliReady={runtime.cliStatus === 'ok'}+ permissionAllowed={permission.permissionAllowed}+ state={permission.state}+ message={permission.message}+ onSetup={() => void permission.setupPermission()}+ />}/>diff --git a/ui/src/components/settings/shared/OpencodePermissionSetup.tsx b/ui/src/components/settings/shared/OpencodePermissionSetup.tsxnew file mode 100644index 000000000..83f19b971--- /dev/null+++ b/ui/src/components/settings/shared/OpencodePermissionSetup.tsx@@ -0,0 +1,62 @@+import { RefreshCw, Settings } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import type { OpencodePermissionState } from './useOpencodePermission';++export interface OpencodePermissionSetupProps {+ /** Whether the OpenCode CLI is detected/ready — the affordance only makes+ * sense once the binary exists. */+ cliReady: boolean;+ /** True once opencode.json already grants ``permission: "allow"``. */+ permissionAllowed: boolean;+ state: OpencodePermissionState;+ message: string;+ onSetup: () => void;+ className?: string;+}++/**+ * The shared "Allow tool calls" callout for OpenCode, rendered identically by+ * the Settings provider page and the setup wizard. Without+ * ``permission: "allow"`` the OpenCode daemon prompts on every tool call and+ * Vibe Remote can't answer — so this surfaces a prominent write-allow button.+ *+ * Renders nothing once the CLI isn't ready or permission is already granted: a+ * permanent "Setup permission" button is misleading once opencode.json already+ * carries the value.+ */+export function OpencodePermissionSetup({+ cliReady,+ permissionAllowed,+ state,+ message,+ onSetup,+ className,+}: OpencodePermissionSetupProps) {+ const { t } = useTranslation();+ if (!cliReady || permissionAllowed) return null;+ return (+ <div className={cn('rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5', className)}>+ <p className="mb-2 text-[12px] text-gold">{t('agentDetection.permissionHintStrong')}</p>+ <div className="flex flex-wrap items-center gap-3">+ <Button+ type="button"+ variant="brand-gold"+ size="xs"+ onClick={onSetup}+ disabled={state === 'loading'}+ >+ {state === 'loading' ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Settings className="size-3.5" />+ )}+ {t('agentDetection.setupPermission')}+ </Button>+ {state === 'success' && <span className="text-[12px] text-mint">{message}</span>}+ {state === 'error' && <span className="text-[12px] text-destructive">{message}</span>}+ </div>+ </div>+ );+}diff --git a/ui/src/components/settings/shared/useOpencodePermission.ts b/ui/src/components/settings/shared/useOpencodePermission.tsnew file mode 100644index 000000000..cad295c15--- /dev/null+++ b/ui/src/components/settings/shared/useOpencodePermission.ts@@ -0,0 +1,109 @@+import { useCallback, useEffect, useState } from 'react';+import { useApi } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++export type OpencodePermissionState = 'idle' | 'loading' | 'success' | 'error';++export interface UseOpencodePermissionOptions {+ // When true, fetch the cheap permission status on mount (and expose+ // ``refreshStatus`` for re-checks). The setup wizard sets this — it has no+ // provider probe and learns the state from GET /api/opencode/permission-status.+ // The Settings provider page leaves it false and feeds ``permissionAllowed``+ // from the value its provider load already returns.+ autoFetchStatus?: boolean;+}++export interface OpencodePermission {+ /** True once opencode.json carries ``permission: "allow"``. */+ permissionAllowed: boolean;+ /** Feed the value from an external source (e.g. the provider catalog load). */+ setPermissionAllowed: (value: boolean) => void;+ /** Write-action lifecycle state. */+ state: OpencodePermissionState;+ /** Latest success/error message from the write action. */+ message: string;+ /** True once an initial status fetch (or a successful write) has resolved. */+ statusLoaded: boolean;+ /** Cheap, read-only status re-check (no OpenCode server start). */+ refreshStatus: () => Promise<void>;+ /** Write ``permission: "allow"`` to opencode.json; flips state + the flag. */+ setupPermission: () => Promise<void>;+}++/**+ * Single source of truth for the OpenCode ``permission: "allow"`` affordance,+ * shared by the Settings provider page and the setup wizard so both behave+ * identically:+ * - owns the write action (POST /api/opencode/setup-permission) plus its+ * loading/success/error state and toast,+ * - tracks ``permissionAllowed`` and flips it locally on a successful write so+ * the affordance disappears immediately,+ * - can cheaply fetch the current status (GET /api/opencode/permission-status,+ * which reads opencode.json without starting the server) for callers that+ * don't already have a provider probe to derive it from.+ */+export function useOpencodePermission(options: UseOpencodePermissionOptions = {}): OpencodePermission {+ const { autoFetchStatus = false } = options;+ const api = useApi();+ const { showToast } = useToast();+ const [permissionAllowed, setPermissionAllowed] = useState(false);+ const [state, setState] = useState<OpencodePermissionState>('idle');+ const [message, setMessage] = useState('');+ const [statusLoaded, setStatusLoaded] = useState(false);++ const refreshStatus = useCallback(async () => {+ try {+ const result = await api.opencodePermissionStatus();+ if (result.ok) {+ setPermissionAllowed(result.permission_allowed === true);+ // Mark loaded only on a definitive answer so callers can fail open: a+ // failed/unknown status must never satisfy a "permission resolved" gate+ // and trap the user — see the wizard's Continue gate.+ setStatusLoaded(true);+ }+ } catch {+ // Best-effort: keep the current value and leave statusLoaded false.+ }+ }, [api]);++ const setupPermission = useCallback(async () => {+ setState('loading');+ setMessage('');+ try {+ const result = await api.opencodeSetupPermission();+ setState(result.ok ? 'success' : 'error');+ setMessage(result.message);+ showToast(result.message, result.ok ? 'success' : 'error');+ if (result.ok) {+ // Flip locally so the affordance vanishes immediately rather than+ // waiting for the next status / provider refresh tick.+ setPermissionAllowed(true);+ setStatusLoaded(true);+ }+ } catch (e) {+ setState('error');+ const msg = e instanceof Error ? e.message : String(e);+ setMessage(msg);+ showToast(msg, 'error');+ }+ }, [api, showToast]);++ useEffect(() => {+ // Opt-in mount fetch (the setup wizard): read the current permission status+ // from opencode.json once so the affordance and the Continue gate reflect+ // reality. The setState lands after the network read inside refreshStatus —+ // a one-shot external-system sync, not a render loop.+ // eslint-disable-next-line react-hooks/set-state-in-effect+ if (autoFetchStatus) void refreshStatus();+ }, [autoFetchStatus, refreshStatus]);++ return {+ permissionAllowed,+ setPermissionAllowed,+ state,+ message,+ statusLoaded,+ refreshStatus,+ setupPermission,+ };+}diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 6da49744b..2a8cd85d9 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -7,7 +7,6 @@ import {Download,ExternalLink,RefreshCw,- Settings,Sliders,} from 'lucide-react';import { Link } from 'react-router-dom';@@ -19,7 +18,9 @@ import type { BackendId } from '../visual';import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { BackendProviderConfig } from '../settings/providers/BackendProviderConfig';+import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';+import { useOpencodePermission } from '../settings/shared/useOpencodePermission';import { Button } from '../ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';import { DEFAULT_AGENT_STATE, DEFAULT_BACKEND_ID, getBackendUiMeta } from '@/lib/agentBackends';@@ -38,8 +39,6 @@ type AgentState = {status?: 'unknown' | 'ok' | 'missing';};-type PermissionState = 'idle' | 'loading' | 'success' | 'error';-const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;// Backends with a dedicated provider config body (rendered in the wizard@@ -79,8 +78,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, ondata.default_backend || data.agents?.default_backend || DEFAULT_BACKEND_ID);const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));- const [permissionState, setPermissionState] = useState<PermissionState>('idle');- const [permissionMessage, setPermissionMessage] = useState<string>('');+ const permission = useOpencodePermission({ autoFetchStatus: true });const [installingAgents, setInstallingAgents] = useState<Record<string, boolean>>({});const [installResults, setInstallResults] = useState<Record<string, { ok: boolean; message: string; output?: string | null }>@@ -167,23 +165,6 @@ 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 installAgent = async (name: string) => {if (isAnyInstalling) return;@@ -221,7 +202,21 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onsetExpandedOutputs((prev) => ({ ...prev, [name]: !prev[name] }));};- const canContinue = Object.values(agents).some((agent) => agent.enabled);+ // Gate the wizard's Continue when OpenCode is enabled and ready but hasn't+ // been granted ``permission: "allow"`` yet — without it every tool call+ // silently waits for an approval prompt Vibe Remote can't answer, so the+ // user must write it before proceeding. Fails open while the status is still+ // unknown (statusLoaded false) so a transient probe error can't trap the+ // user, and never gates the Settings page (isPage).+ const opencodeAgent = agents['opencode'];+ const opencodeNeedsPermission =+ !isPage &&+ !!opencodeAgent?.enabled &&+ opencodeAgent?.status === 'ok' &&+ permission.statusLoaded &&+ !permission.permissionAllowed;+ const canContinue =+ Object.values(agents).some((agent) => agent.enabled) && !opencodeNeedsPermission;const handlePrimaryAction = async () => {// Wait for an in-flight provider-modal sync and fold its result into the@@ -358,29 +353,15 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on</Button>))}- {name === 'opencode' && ready && (- <>- <Button- type="button"- variant="brand-gold"- size="sm"- onClick={setupPermission}- disabled={permissionState === 'loading'}- >- {permissionState === 'loading' ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Settings className="size-3.5" />- )}- {t('agentDetection.setupPermission')}- </Button>- {permissionState === 'success' && (- <span className="text-[11px] text-mint">{permissionMessage}</span>- )}- {permissionState === 'error' && (- <span className="text-[11px] text-danger">{permissionMessage}</span>- )}- </>+ {name === 'opencode' && (+ <OpencodePermissionSetup+ cliReady={ready}+ permissionAllowed={permission.permissionAllowed}+ state={permission.state}+ message={permission.message}+ onSetup={() => void permission.setupPermission()}+ className="w-full"+ />)}{isMissing(agent) && (@@ -448,6 +429,11 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// provider defaults) and the status pill reflect whatever changed// inside the modal. Keep the promise so Continue can await it.if (name) syncRef.current = syncBackendFromConfig(name);+ // The Configure-provider modal embeds its OWN useOpencodePermission+ // instance, so a permission write inside it doesn't touch this+ // wizard's gate/callout state. Re-read opencode.json so the gate+ // clears and the callout hides once allow was granted in the modal.+ if (name === 'opencode') void permission.refreshStatus();}}}>@@ -522,16 +508,23 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on) : (<span />)}- <Button- type="button"- variant="brand"- size="default"- onClick={() => void handlePrimaryAction()}- disabled={!canContinue || syncing}- >- {t('common.continue')}- <ArrowRight size={14} strokeWidth={2.25} />- </Button>+ <div className="flex flex-col items-end gap-1.5">+ {opencodeNeedsPermission && (+ <p className="text-right text-[12px] text-gold">+ {t('agentDetection.permissionGateHint')}+ </p>+ )}+ <Button+ type="button"+ variant="brand"+ size="default"+ onClick={() => void handlePrimaryAction()}+ disabled={!canContinue || syncing}+ >+ {t('common.continue')}+ <ArrowRight size={14} strokeWidth={2.25} />+ </Button>+ </div></div></WizardCard></div>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex c06395a51..7e7832f6c 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -123,6 +123,7 @@ export type ApiContextType = {doctor: () => Promise<any>;opencodeOptions: (cwd: string) => Promise<any>;opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;+ opencodePermissionStatus: () => Promise<{ ok: boolean; permission_allowed: boolean; config_path: string }>;claudeAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string }[]; error?: string }>;claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; error?: string }>;codexAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string; description?: string }[]; error?: string }>;@@ -1357,6 +1358,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrendoctor: () => postJson('/api/doctor', {}),opencodeOptions: (cwd) => postJson('/api/opencode/options', { cwd }),opencodeSetupPermission: () => postJson('/api/opencode/setup-permission', {}),+ opencodePermissionStatus: () => getJson('/api/opencode/permission-status'),claudeAgents: (cwd) => cwd ? getJson(`/api/claude/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/api/claude/agents'),claudeModels: () => getJson('/api/claude/models'),codexAgents: (cwd) => cwd ? getJson(`/api/codex/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/api/codex/agents'),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f47d198c2..5fd1b7d4f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1036,6 +1036,7 @@"permissionHint": "OpenCode requires permission config to skip approval prompts.","permissionHintStrong": "Without this, OpenCode prompts for approval on every tool call. Vibe Remote can't auto-reply, so the agent stalls.","setupPermission": "Allow tool calls in opencode.json",+ "permissionGateHint": "Allow OpenCode tool calls above before you continue.","installHint": "Agent not found. Click to install automatically.","installAgent": "Install","installing": "Installing...",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex f3a64a193..775cec7ba 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1036,6 +1036,7 @@"permissionHint": "OpenCode 需要配置权限以跳过审批提示。","permissionHintStrong": "不设置时 OpenCode 每次工具调用都会等审批,Vibe Remote 无法代答,Agent 会卡住。","setupPermission": "在 opencode.json 写入 allow",+ "permissionGateHint": "请先在上方为 OpenCode 写入工具调用权限,才能继续。","installHint": "未找到 Agent,点击自动安装。","installAgent": "一键安装","installing": "安装中...",diff --git a/vibe/api.py b/vibe/api.pyindex ae055a563..47eee2f45 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1894,6 +1894,85 @@ def _prepare_show_runtime_after_upgrade(vibe_path: str | None, cwd: str) -> strreturn "Show Runtime preparation failed; Vibe Remote upgrade is still installed." + (f"\n{output}" if output else "")+def _opencode_permission_grants_all(node) -> bool:+ """Recursively decide whether an OpenCode permission node allows every call.++ OpenCode resolves the last matching rule, with ``"*"`` as the wildcard at+ each level and tool entries that are themselves either a string or a nested+ rule object (https://opencode.ai/docs/permissions). A node grants all tool+ calls iff it is the string ``"allow"``, or a dict whose ``"*"`` wildcard+ grants all AND every nested rule grants all — so a single ``"bash": "ask"``+ (or a nested ``ask``/``deny``) keeps it ungranted, while a fully-``allow``+ tree (e.g. ``{"*": "allow", "bash": {"*": "allow"}}``) passes. Conservative:+ a dict without a ``"*"`` can't guarantee otherwise-unmatched keys, so it is+ treated as not-granted — erring toward keeping the write-allow button rather+ than letting a tool call silently stall on a prompt Vibe Remote can't answer.+ """+ if node == "allow":+ return True+ if isinstance(node, dict):+ return _opencode_permission_grants_all(node.get("*")) and all(+ _opencode_permission_grants_all(value) for value in node.values()+ )+ return False+++def opencode_permission_allowed(probe) -> bool:+ """Whether an OpenCode config probe already grants full tool-call permission.++ Single source of truth for the "Allow tool calls" state. Without a config+ that allows every call the OpenCode daemon prompts on tool calls and Vibe+ Remote can't answer the prompt, so both the Settings provider page and the+ setup wizard hide the write-allow affordance once this returns True.++ Accepts both forms OpenCode documents: the ``"permission": "allow"`` string+ shorthand and the granular object form — evaluated recursively via+ :func:`_opencode_permission_grants_all` so any config that already avoids all+ approval prompts (including nested ``allow`` rules) isn't gated or nagged to+ overwrite, while a partial config that can still prompt keeps the button.+ """+ config = getattr(probe, "config", None)+ if not isinstance(config, dict):+ return False+ return _opencode_permission_grants_all(config.get("permission"))+++def opencode_permission_status() -> dict:+ """Cheaply report whether ``opencode.json`` already grants ``permission: "allow"``.++ Reads (and JSONC-parses) the user's OpenCode config only — it never starts+ the OpenCode server — so the setup wizard can decide whether to surface the+ write-allow affordance without paying for a full provider probe (which the+ Settings page already does via ``get_opencode_providers``).++ Returns ``{"ok": bool, "permission_allowed": bool, "config_path": str}``.+ """+ config_paths = get_opencode_config_paths(Path.home())+ probe = load_first_opencode_user_config(home=Path.home(), logger_instance=logger)+ # A malformed existing config can't be auto-fixed — ``setup_opencode_permission``+ # refuses to overwrite invalid files — so report unknown (``ok: False``) here.+ # The wizard gate keys off a successful status read, so this makes it FAIL+ # OPEN instead of trapping the user behind a Continue the only available+ # action can't satisfy. (A missing config — no existing paths — is the normal+ # first-run case and stays ``ok: True`` so setup can create it.)+ if probe.config is None and probe.existing_paths:+ error_path, error_message = (+ probe.errors[0] if probe.errors else (probe.existing_paths[0], "unknown parse error")+ )+ return {+ "ok": False,+ "permission_allowed": False,+ "config_path": str(error_path),+ "message": f"Existing OpenCode config could not be parsed: {error_message}",+ }+ config_path = probe.path if probe.path is not None else (config_paths[0] if config_paths else None)+ return {+ "ok": True,+ "permission_allowed": opencode_permission_allowed(probe),+ "config_path": str(config_path) if config_path is not None else "",+ }++def setup_opencode_permission() -> dict:"""Set OpenCode permission to 'allow' in config file.@@ -1913,7 +1992,7 @@ def setup_opencode_permission() -> dict:probe = load_first_opencode_user_config(home=Path.home(), logger_instance=logger)if probe.config is not None and probe.path is not None:- if probe.config.get("permission") == "allow":+ if opencode_permission_allowed(probe):return {"ok": True,"message": "Permission already set",@@ -4726,9 +4805,7 @@ async def _get_opencode_providers_async() -> dict:# already ``allow`` — and strengthen the copy when it isn't, since a# missing/blocking setting silently makes every tool call wait for an# approval prompt that Vibe Remote can't reply to.- permission_allowed = False- if opencode_probe is not None and isinstance(opencode_probe.config, dict):- permission_allowed = opencode_probe.config.get("permission") == "allow"+ permission_allowed = opencode_permission_allowed(opencode_probe)return {"ok": True,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 1455fd2e3..d64b2d349 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2523,6 +2523,17 @@ def opencode_setup_permission():return jsonify(api.setup_opencode_permission())[email protected]("/api/opencode/permission-status", methods=["GET"])+def opencode_permission_status():+ # Cheap, read-only check (no OpenCode server start) so the setup wizard can+ # hide the write-allow affordance once opencode.json already grants it —+ # mirroring the Settings provider page, which derives the same flag from the+ # heavier provider probe.+ from vibe import api++ return jsonify(api.opencode_permission_status())++@app.route("/api/claude/agents", methods=["GET"])def claude_agents():from vibe import api