Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: full permissions mode with a composer toggle

Samrat Talukdar54bc54ecfc3b
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index c793e86e..f4eeb94f 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -390,6 +390,15 @@ export type OmniRushRuntimeConfigStatus = {
};
};
+export type OmniRushApprovalMode = "guarded" | "full";
+export type OmniRushRuntimeApprovals = {
+ /** Effective mode: the environment override, else the setting, else guarded. */
+ mode: OmniRushApprovalMode;
+ source: "environment" | "settings" | "default";
+ /** The persisted user setting, even while the environment overrides it. */
+ setting: OmniRushApprovalMode | null;
+};
+
export type OmniRushDesktopCloudSyncChange = {
id: string;
kind: "new" | "modified" | "removed";
@@ -1824,6 +1833,16 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
`/workspace/${encodeURIComponent(workspaceId)}/runtime-config`,
{ token, hostToken, timeoutMs: timeouts.config },
),
+ getRuntimeApprovals: () =>
+ requestJson<OmniRushRuntimeApprovals>(baseUrl, "/runtime-config/approvals", { token, hostToken, timeoutMs: timeouts.config }),
+ setRuntimeApprovals: (mode: OmniRushApprovalMode) =>
+ requestJson<OmniRushRuntimeApprovals & { ok: boolean; changed: boolean }>(baseUrl, "/runtime-config/approvals", {
+ token,
+ hostToken,
+ method: "PUT",
+ body: { mode },
+ timeoutMs: timeouts.config,
+ }),
patchConfig: (workspaceId: string, payload: { opencode?: Record<string, unknown>; omnirush?: Record<string, unknown> }) =>
requestJson<{ updatedAt?: number | null }>(baseUrl, `/workspace/${workspaceId}/config`, {
token,
diff --git a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
index bddf7558..47b1a08a 100644
--- a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
+++ b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
@@ -11,6 +11,7 @@ import type { ComposerSettingsSection } from "@/react-app/domains/settings/libra
import { DEFAULT_MODEL } from "@/app/constants";
import { ReactSessionComposer } from "@/react-app/domains/session/surface/composer/composer";
import { WorkspaceRunModeMenu } from "@/react-app/domains/session/surface/composer/workspace-run-mode-menu";
+import { FullPermissionsToggle } from "@/react-app/domains/session/surface/composer/full-permissions-toggle";
import {
snapshotComposerSessionState,
type ComposerSessionState,
@@ -423,6 +424,7 @@ export function NewTaskComposer(props: NewTaskComposerProps) {
}}>Clear the current draft to restore the unsent message</button> : null}
<ReactSessionComposer
runModeControl={<WorkspaceRunModeMenu client={workspaceClient} workspaceId={workspaceId} busy={props.busy} />}
+ fullPermissionsControl={<FullPermissionsToggle client={workspaceClient} workspaceId={workspaceId} />}
draft={props.draft}
mentions={mentions}
onDraftChange={handleDraftChange}
diff --git a/apps/app/src/react-app/domains/session/surface/composer/composer.tsx b/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
index 30eff11c..71b69663 100644
--- a/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
+++ b/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
@@ -118,6 +118,8 @@ type ComposerProps = {
flush?: boolean;
topAccessory?: ReactNode;
runModeControl?: ReactNode;
+ /** The "Full permissions" switch, rendered right after the model selector. */
+ fullPermissionsControl?: ReactNode;
};
const FLUSH_PROMPT_EVENT = "omnirush:flushPromptDraft";
@@ -1761,6 +1763,7 @@ export const ReactSessionComposer = memo(function ReactSessionComposer(props: Co
if (!props.steering) props.onModelVariantChange(value);
}}
/>
+ {props.fullPermissionsControl}
{props.modelUnavailable ? props.onRefreshOrganizationModels ? (
<button
type="button"
diff --git a/apps/app/src/react-app/domains/session/surface/composer/full-permissions-toggle.tsx b/apps/app/src/react-app/domains/session/surface/composer/full-permissions-toggle.tsx
new file mode 100644
index 00000000..6859b35c
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/surface/composer/full-permissions-toggle.tsx
@@ -0,0 +1,93 @@
+/** @jsxImportSource react */
+import { LoaderCircle, ShieldCheck } from "lucide-react";
+
+import { toast } from "@/components/ui/sonner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useDesktopRestriction } from "@/react-app/domains/cloud/desktop-config-provider";
+import {
+ approvalsEnvironmentHint,
+ useApprovalMode,
+ type ApprovalsClient,
+} from "@/react-app/domains/settings/approval-mode";
+
+export const FULL_PERMISSIONS_ON_HINT =
+ "Full permissions on: nothing asks for approval. Switch off to return to guarded mode.";
+export const FULL_PERMISSIONS_OFF_HINT =
+ "Guarded mode: the engine asks before risky commands. Switch on to run every command and edit files without asking. Organisation policies still apply.";
+export const FULL_PERMISSIONS_POLICY_LOCK =
+ "Locked by your organisation: its policy does not allow changing app settings.";
+export const FULL_PERMISSIONS_LOADING_HINT = "Loading the approval mode…";
+
+type Props = {
+ client: ApprovalsClient | null;
+ /** Engine reloaded after a change; without one the setting is saved and a reload is asked for. */
+ workspaceId: string | null;
+};
+
+/**
+ * The composer's "Full permissions" switch, beside the model selector. It
+ * shares state with Settings > General > Approvals through useApprovalMode,
+ * so the two never disagree. Hidden until a server client exists.
+ */
+export function FullPermissionsToggle(props: Props) {
+ const policyLocked = useDesktopRestriction("allowControlSettings");
+ if (!props.client) return null;
+ return <FullPermissionsSwitch client={props.client} workspaceId={props.workspaceId} policyLocked={policyLocked} />;
+}
+
+function FullPermissionsSwitch(props: { client: ApprovalsClient; workspaceId: string | null; policyLocked: boolean }) {
+ const { approvals, busy, status, setFullPermissions } = useApprovalMode(props.client, props.workspaceId);
+ const full = approvals?.mode === "full";
+ const lockReason = props.policyLocked
+ ? FULL_PERMISSIONS_POLICY_LOCK
+ : approvals
+ ? approvalsEnvironmentHint(approvals)
+ : null;
+ // Disabled while the mode loads, while a change is in flight and while the
+ // environment or the organisation forces the mode.
+ const disabled = busy || !approvals || lockReason !== null;
+ const hint = lockReason
+ ?? (!approvals ? (status || FULL_PERMISSIONS_LOADING_HINT) : full ? FULL_PERMISSIONS_ON_HINT : FULL_PERMISSIONS_OFF_HINT);
+
+ const toggle = async () => {
+ if (disabled) return;
+ const change = await setFullPermissions(!full);
+ if (!change) return;
+ if (change.tone === "success") toast.success(change.status);
+ else if (change.tone === "warning") toast.warning(change.status);
+ else toast.error(change.status);
+ };
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ role="switch"
+ aria-checked={full}
+ aria-label="Full permissions"
+ aria-disabled={disabled || undefined}
+ aria-busy={busy || undefined}
+ data-testid="full-permissions-toggle"
+ data-state={full ? "on" : "off"}
+ data-lock-reason={lockReason ?? undefined}
+ onClick={() => void toggle()}
+ // Same height, radius, padding and text size as the model selector
+ // trigger. Kept focusable while disabled (aria-disabled, not
+ // disabled) so the tooltip can explain why.
+ className={`flex h-9 max-h-9 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-sm transition-colors aria-disabled:cursor-not-allowed aria-disabled:opacity-60 ${
+ full
+ ? "bg-[var(--dls-accent)] text-[var(--dls-accent-fg)] hover:bg-[var(--dls-accent-hover)] aria-disabled:hover:bg-[var(--dls-accent)]"
+ : "text-gray-10 hover:bg-gray-3 hover:text-gray-12 aria-disabled:hover:bg-transparent aria-disabled:hover:text-gray-10"
+ }`}
+ />
+ }
+ >
+ {busy ? <LoaderCircle className="size-4 animate-spin" /> : <ShieldCheck className="size-4" />}
+ <span className="whitespace-nowrap">Full permissions</span>
+ </TooltipTrigger>
+ <TooltipContent>{hint}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index 3df04aca..e71df66f 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -50,6 +50,7 @@ import type {
} from "@/react-app/domains/connections/cloud-mcp-submit-readiness";
import { ReactSessionComposer } from "./composer/composer";
import { WorkspaceRunModeMenu } from "./composer/workspace-run-mode-menu";
+import { FullPermissionsToggle } from "./composer/full-permissions-toggle";
import { useSessionModelSelection } from "./session-model-store";
import type { ProviderCatalog } from "./use-model-behavior";
import type { ModelAvailability } from "./model-availability";
@@ -3222,6 +3223,7 @@ export function SessionSurface(props: SessionSurfaceProps) {
)))}
<ReactSessionComposer
runModeControl={<WorkspaceRunModeMenu client={props.client} workspaceId={props.workspaceId} busy={chatStreaming || preparingCloudTools || Boolean(props.activePermission || props.activeQuestion)} />}
+ fullPermissionsControl={<FullPermissionsToggle client={props.client} workspaceId={props.workspaceId} />}
draft={autoSendPayload ? draft : autoSending ? "" : draft}
mentions={mentions}
onDraftChange={handleComposerDraftChange}
diff --git a/apps/app/src/react-app/domains/settings/approval-mode.ts b/apps/app/src/react-app/domains/settings/approval-mode.ts
new file mode 100644
index 00000000..593adef8
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/approval-mode.ts
@@ -0,0 +1,155 @@
+// Shared approval-mode state. The Settings > General "Approvals" card and the
+// composer's "Full permissions" switch both read it through useApprovalMode,
+// so they show the same mode and a change in either updates the other at once.
+// State is keyed by server (client.baseUrl): the mode is a server-wide setting,
+// not a workspace one, and a remote workspace talks to a different server.
+import { useCallback, useEffect } from "react";
+import { create } from "zustand";
+
+import type { OmniRushRuntimeApprovals, OmniRushServerClient } from "@/app/lib/omnirush-server";
+import { reloadEngineWithDesktopFallback } from "@/react-app/shell/engine-reload-escalation";
+
+export type ApprovalsClient = Pick<OmniRushServerClient, "getRuntimeApprovals" | "setRuntimeApprovals" | "reloadEngine"> & {
+ /** Keys the shared state; clients without one share a single entry. */
+ baseUrl?: string;
+};
+
+export const FULL_PERMISSIONS_HELP = "Runs every command and edits files without asking. Organisation policies still apply.";
+
+/** Shown while OMNIRUSH_APPROVALS in the launch environment forces the mode. */
+export function approvalsEnvironmentHint(approvals: OmniRushRuntimeApprovals): string | null {
+ if (approvals.source !== "environment") return null;
+ return `Set by environment (OMNIRUSH_APPROVALS=${approvals.mode}); change it where the app is launched.`;
+}
+
+export type FullPermissionsOutcome = {
+ approvals: OmniRushRuntimeApprovals;
+ status: string;
+ /** "success" once the engine reloaded; "warning" when the setting is saved but the engine still needs a reload. */
+ tone: "success" | "warning";
+};
+
+/**
+ * Persist the approval mode, then reload the engine the way Settings "Reload"
+ * does (a manual reload bypasses the fingerprint guard) so the new permission
+ * rules apply within seconds. A failed reload keeps the saved setting and says
+ * what to do next.
+ */
+export async function applyFullPermissions(
+ client: ApprovalsClient,
+ workspaceId: string | null,
+ enabled: boolean,
+): Promise<FullPermissionsOutcome> {
+ const { mode, source, setting } = await client.setRuntimeApprovals(enabled ? "full" : "guarded");
+ const approvals: OmniRushRuntimeApprovals = { mode, source, setting };
+ const label = mode === "full" ? "Full permissions on." : "Guarded mode.";
+ if (!workspaceId) return { approvals, status: `${label} Reload the engine to apply it.`, tone: "warning" };
+ try {
+ await reloadEngineWithDesktopFallback(client, workspaceId);
+ return { approvals, status: `${label} Engine reloaded.`, tone: "success" };
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ return { approvals, status: `${label} Engine reload failed: ${reason} Use Reload in Settings to apply it.`, tone: "warning" };
+ }
+}
+
+export type ApprovalModeEntry = {
+ /** Null until the server has answered (or while the load keeps failing). */
+ approvals: OmniRushRuntimeApprovals | null;
+ /** True while a change persists and the engine reloads. */
+ busy: boolean;
+ /** The last load or change result, or the error to act on. */
+ status: string;
+};
+
+const EMPTY_ENTRY: ApprovalModeEntry = { approvals: null, busy: false, status: "" };
+
+type ApprovalModeStore = {
+ byServer: Record<string, ApprovalModeEntry>;
+ patch: (key: string, patch: Partial<ApprovalModeEntry>) => void;
+};
+
+export const useApprovalModeStore = create<ApprovalModeStore>((set) => ({
+ byServer: {},
+ patch: (key, patch) =>
+ set((state) => ({
+ byServer: { ...state.byServer, [key]: { ...(state.byServer[key] ?? EMPTY_ENTRY), ...patch } },
+ })),
+}));
+
+export function approvalModeKey(client: ApprovalsClient): string {
+ return client.baseUrl?.trim() || "default";
+}
+
+function messageOf(error: unknown, fallback: string): string {
+ return error instanceof Error && error.message ? error.message : fallback;
+}
+
+const inflightLoads = new Map<string, Promise<void>>();
+// Bumped whenever a change starts so a load that began before the change
+// cannot overwrite the new mode with the value it fetched earlier.
+const changeSequence = new Map<string, number>();
+
+/** Record that a change is starting so earlier in-flight loads are ignored. */
+export function markApprovalChange(key: string): void {
+ changeSequence.set(key, (changeSequence.get(key) ?? 0) + 1);
+}
+
+/** Fetch the mode; components mounting at the same time share one request. */
+export function loadApprovalMode(client: ApprovalsClient): Promise<void> {
+ const key = approvalModeKey(client);
+ const pending = inflightLoads.get(key);
+ if (pending) return pending;
+ const { patch } = useApprovalModeStore.getState();
+ const startedAt = changeSequence.get(key) ?? 0;
+ const task = client.getRuntimeApprovals()
+ .then((approvals) => {
+ const stale = (changeSequence.get(key) ?? 0) !== startedAt || useApprovalModeStore.getState().byServer[key]?.busy;
+ if (!stale) patch(key, { approvals });
+ })
+ .catch((error: unknown) => patch(key, { status: messageOf(error, "The approval mode could not be loaded.") }))
+ .finally(() => {
+ inflightLoads.delete(key);
+ });
+ inflightLoads.set(key, task);
+ return task;
+}
+
+export type ApprovalModeChange = {
+ approvals: OmniRushRuntimeApprovals | null;
+ status: string;
+ tone: "success" | "warning" | "error";
+};
+
+/**
+ * The approval mode of the server behind `client`, loaded on mount, and the
+ * action that changes it. `workspaceId` names the engine to reload afterwards;
+ * without one the setting is saved and the status asks for a reload.
+ */
+export function useApprovalMode(client: ApprovalsClient | null, workspaceId: string | null) {
+ const key = client ? approvalModeKey(client) : null;
+ const entry = useApprovalModeStore((state) => (key ? state.byServer[key] : undefined)) ?? EMPTY_ENTRY;
+
+ useEffect(() => {
+ if (!client) return;
+ void loadApprovalMode(client);
+ }, [client]);
+
+ const setFullPermissions = useCallback(async (enabled: boolean): Promise<ApprovalModeChange | null> => {
+ if (!client || !key) return null;
+ const { patch } = useApprovalModeStore.getState();
+ markApprovalChange(key);
+ patch(key, { busy: true, status: enabled ? "Turning full permissions on…" : "Switching to guarded mode…" });
+ try {
+ const outcome = await applyFullPermissions(client, workspaceId, enabled);
+ patch(key, { approvals: outcome.approvals, busy: false, status: outcome.status });
+ return outcome;
+ } catch (error) {
+ const status = messageOf(error, "The approval mode could not be saved.");
+ patch(key, { busy: false, status });
+ return { approvals: useApprovalModeStore.getState().byServer[key]?.approvals ?? null, status, tone: "error" };
+ }
+ }, [client, key, workspaceId]);
+
+ return { approvals: entry.approvals, busy: entry.busy, status: entry.status, setFullPermissions };
+}
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index 89f588ca..f782147b 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -6,6 +6,7 @@ import {
FolderLock,
Paintbrush,
RefreshCcw,
+ ShieldCheck,
Sparkles,
Terminal,
Wrench,
@@ -14,6 +15,7 @@ import {
import type { OmniRushAccountSignOutReason } from "@omnirush/types/desktop-ipc";
+import { Switch } from "@/components/ui/switch";
import { t } from "../../../../i18n";
import type { SettingsTab } from "../../../../app/types";
import {
@@ -21,11 +23,22 @@ import {
omnirushAccountSignOut,
omnirushAccountStatus,
} from "../../../../app/lib/desktop";
+import type { OmniRushRuntimeApprovals } from "../../../../app/lib/omnirush-server";
import { isElectronRuntime } from "../../../../app/utils";
+import {
+ FULL_PERMISSIONS_HELP,
+ approvalsEnvironmentHint,
+ useApprovalMode,
+ type ApprovalsClient,
+} from "../approval-mode";
export type GeneralSettingsViewProps = {
onNavigateTab: (tab: SettingsTab) => void;
developerMode: boolean;
+ /** Server client for the Approvals card; the card is hidden without one. */
+ omnirushClient?: ApprovalsClient | null;
+ /** Workspace whose engine is reloaded after the approval mode changes. */
+ runtimeWorkspaceId?: string | null;
};
type NativeAccountStatus = Awaited<ReturnType<typeof omnirushAccountStatus>>;
@@ -122,10 +135,54 @@ export function accountServerLine(account: Pick<NativeAccountStatus, "connected"
return account.connected ? `Connected to ${host}` : `Account server: ${host}`;
}
+/**
+ * Settings > General > Approvals. The mode, busy flag and status come from
+ * useApprovalMode, which the composer's "Full permissions" switch shares.
+ */
+export function ApprovalsCard(props: {
+ approvals: OmniRushRuntimeApprovals | null;
+ busy: boolean;
+ status: string;
+ onToggle: (enabled: boolean) => void;
+}) {
+ const hint = props.approvals ? approvalsEnvironmentHint(props.approvals) : null;
+ const full = props.approvals?.mode === "full";
+ return (
+ <div className="space-y-3">
+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">
+ Approvals
+ </div>
+ <div className="flex items-center gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">
+ <ShieldCheck size={17} className={full ? "text-amber-400" : "text-dls-secondary"} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-medium text-dls-text">Full permissions</div>
+ <div className="text-[11px] text-dls-secondary">{FULL_PERMISSIONS_HELP}</div>
+ {hint ? (
+ <div className="mt-0.5 text-[11px] text-dls-secondary" data-testid="approvals-env-hint">{hint}</div>
+ ) : null}
+ {props.status ? (
+ <div className="mt-0.5 text-[11px] text-dls-secondary" data-testid="approvals-status">{props.status}</div>
+ ) : null}
+ </div>
+ <Switch
+ aria-label="Full permissions"
+ checked={full}
+ disabled={props.busy || !props.approvals || hint !== null}
+ onCheckedChange={props.onToggle}
+ />
+ </div>
+ </div>
+ );
+}
+
export function GeneralSettingsView(props: GeneralSettingsViewProps) {
const [account, setAccount] = useState<NativeAccountStatus | null>(null);
const [accountBusy, setAccountBusy] = useState(false);
const [accountMessage, setAccountMessage] = useState("");
+ const approvalsClient = props.omnirushClient ?? null;
+ const approvalMode = useApprovalMode(approvalsClient, props.runtimeWorkspaceId ?? null);
useEffect(() => {
if (!isElectronRuntime()) return;
@@ -256,6 +313,14 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
</div>
</div>
+ {approvalsClient ? (
+ <ApprovalsCard
+ approvals={approvalMode.approvals}
+ busy={approvalMode.busy}
+ status={approvalMode.status}
+ onToggle={(enabled) => void approvalMode.setFullPermissions(enabled)}
+ />
+ ) : null}
</div>
);
}
diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsx
index 7dea7f65..f8a87082 100644
--- a/apps/app/src/react-app/shell/settings-route.tsx
+++ b/apps/app/src/react-app/shell/settings-route.tsx
@@ -2245,6 +2245,8 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
<GeneralSettingsView
onNavigateTab={(tab) => navigateSettingsPath(tab)}
developerMode={developerMode}
+ omnirushClient={omnirushClient}
+ runtimeWorkspaceId={runtimeWorkspaceId}
/>
);
case "permissions":
diff --git a/apps/app/tests/approval-mode-store.test.ts b/apps/app/tests/approval-mode-store.test.ts
new file mode 100644
index 00000000..c04cac69
--- /dev/null
+++ b/apps/app/tests/approval-mode-store.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from "bun:test";
+
+import { approvalModeKey, loadApprovalMode, markApprovalChange, useApprovalModeStore } from "../src/react-app/domains/settings/approval-mode";
+
+type Approvals = { mode: "guarded" | "full"; source: "environment" | "settings" | "default"; setting: "guarded" | "full" | null };
+
+const full: Approvals = { mode: "full", source: "settings", setting: "full" };
+const guarded: Approvals = { mode: "guarded", source: "default", setting: null };
+
+describe("approval mode store", () => {
+ test("a load that started before a change cannot overwrite the new mode", async () => {
+ let release: (value: Approvals) => void = () => {};
+ const held = new Promise<Approvals>((resolve) => { release = resolve; });
+ const client = {
+ baseUrl: "http://127.0.0.1:65530",
+ getRuntimeApprovals: () => held,
+ setRuntimeApprovals: async () => full,
+ reloadEngine: async () => ({}),
+ } as never;
+ const key = approvalModeKey(client);
+ const pendingLoad = loadApprovalMode(client);
+
+ // The change starts and completes while the old load is still in flight.
+ markApprovalChange(key);
+ const { patch } = useApprovalModeStore.getState();
+ patch(key, { busy: true, status: "Turning full permissions on…" });
+ patch(key, { approvals: full, busy: false, status: "Full permissions on. Engine reloaded." });
+
+ release(guarded);
+ await pendingLoad;
+ expect(useApprovalModeStore.getState().byServer[key]?.approvals?.mode).toBe("full");
+ });
+
+ test("a fresh load after the change still applies", async () => {
+ const client = {
+ baseUrl: "http://127.0.0.1:65531",
+ getRuntimeApprovals: async () => guarded,
+ setRuntimeApprovals: async () => full,
+ reloadEngine: async () => ({}),
+ } as never;
+ const key = approvalModeKey(client);
+ markApprovalChange(key);
+ await loadApprovalMode(client);
+ expect(useApprovalModeStore.getState().byServer[key]?.approvals?.mode).toBe("guarded");
+ });
+});
diff --git a/apps/app/tests/approvals-settings-card.test.tsx b/apps/app/tests/approvals-settings-card.test.tsx
new file mode 100644
index 00000000..74ef2ca9
--- /dev/null
+++ b/apps/app/tests/approvals-settings-card.test.tsx
@@ -0,0 +1,98 @@
+import { describe, expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import type { OmniRushApprovalMode, OmniRushRuntimeApprovals } from "../src/app/lib/omnirush-server";
+import {
+ FULL_PERMISSIONS_HELP,
+ applyFullPermissions,
+ type ApprovalsClient,
+} from "../src/react-app/domains/settings/approval-mode";
+import { ApprovalsCard } from "../src/react-app/domains/settings/pages/general-view";
+
+function fakeClient(options: { reloadError?: Error } = {}) {
+ const calls: string[] = [];
+ let approvals: OmniRushRuntimeApprovals = { mode: "guarded", source: "default", setting: null };
+ const client: ApprovalsClient = {
+ getRuntimeApprovals: async () => approvals,
+ setRuntimeApprovals: async (mode: OmniRushApprovalMode) => {
+ calls.push(`set:${mode}`);
+ approvals = { mode, source: "settings", setting: mode };
+ return { ...approvals, ok: true, changed: true };
+ },
+ reloadEngine: async (workspaceId: string) => {
+ calls.push(`reload:${workspaceId}`);
+ if (options.reloadError) throw options.reloadError;
+ return { ok: true };
+ },
+ };
+ return { client, calls };
+}
+
+/** The Base UI switch root: `aria-checked` carries the mode, `aria-disabled` the locked state. */
+function switchMarkup(markup: string): string {
+ const match = markup.match(/<[a-z]+[^>]*role="switch"[^>]*>/);
+ if (!match) throw new Error(`no switch in ${markup}`);
+ return match[0];
+}
+
+describe("approvals settings card", () => {
+ test("shows the switch with its helper text and reflects the current mode", () => {
+ const markup = renderToStaticMarkup(
+ <ApprovalsCard approvals={{ mode: "full", source: "settings", setting: "full" }} busy={false} status="" onToggle={() => {}} />,
+ );
+ expect(markup).toContain("Approvals");
+ expect(markup).toContain("Full permissions");
+ expect(markup).toContain(FULL_PERMISSIONS_HELP);
+ expect(switchMarkup(markup)).toContain('aria-checked="true"');
+ expect(switchMarkup(markup)).not.toContain('aria-disabled="true"');
+ expect(markup).not.toContain("Set by environment");
+
+ const off = renderToStaticMarkup(
+ <ApprovalsCard approvals={{ mode: "guarded", source: "default", setting: null }} busy={false} status="Guarded mode. Engine reloaded." onToggle={() => {}} />,
+ );
+ expect(switchMarkup(off)).toContain('aria-checked="false"');
+ expect(off).toContain("Guarded mode. Engine reloaded.");
+ });
+
+ test("disables the switch and says so while the environment forces the mode", () => {
+ const markup = renderToStaticMarkup(
+ <ApprovalsCard approvals={{ mode: "full", source: "environment", setting: "guarded" }} busy={false} status="" onToggle={() => {}} />,
+ );
+ expect(switchMarkup(markup)).toContain('aria-checked="true"');
+ expect(switchMarkup(markup)).toContain('aria-disabled="true"');
+ expect(markup).toContain("Set by environment (OMNIRUSH_APPROVALS=full)");
+ // Nothing is claimed before the server has answered.
+ const loading = renderToStaticMarkup(<ApprovalsCard approvals={null} busy={false} status="" onToggle={() => {}} />);
+ expect(switchMarkup(loading)).toContain('aria-disabled="true"');
+ });
+
+ test("toggling persists the mode, then reloads the workspace engine", async () => {
+ const { client, calls } = fakeClient();
+ const on = await applyFullPermissions(client, "ws_1", true);
+ expect(calls).toEqual(["set:full", "reload:ws_1"]);
+ expect(on.approvals).toEqual({ mode: "full", source: "settings", setting: "full" });
+ expect(on.status).toBe("Full permissions on. Engine reloaded.");
+ expect(on.tone).toBe("success");
+
+ const off = await applyFullPermissions(client, "ws_1", false);
+ expect(calls.slice(2)).toEqual(["set:guarded", "reload:ws_1"]);
+ expect(off.status).toBe("Guarded mode. Engine reloaded.");
+ expect(off.tone).toBe("success");
+ expect(await client.getRuntimeApprovals()).toEqual({ mode: "guarded", source: "settings", setting: "guarded" });
+ });
+
+ test("keeps the saved setting and explains when the reload fails or no workspace is active", async () => {
+ const failing = fakeClient({ reloadError: new Error("engine busy") });
+ const result = await applyFullPermissions(failing.client, "ws_1", true);
+ expect(failing.calls).toEqual(["set:full", "reload:ws_1"]);
+ expect(result.approvals.mode).toBe("full");
+ expect(result.status).toBe("Full permissions on. Engine reload failed: engine busy Use Reload in Settings to apply it.");
+ expect(result.tone).toBe("warning");
+
+ const idle = fakeClient();
+ const saved = await applyFullPermissions(idle.client, null, true);
+ expect(idle.calls).toEqual(["set:full"]);
+ expect(saved.status).toBe("Full permissions on. Reload the engine to apply it.");
+ expect(saved.tone).toBe("warning");
+ });
+});
diff --git a/apps/app/tests/composer-editable-on-snapshot-error.test.tsx b/apps/app/tests/composer-editable-on-snapshot-error.test.tsx
index d01571e2..84abf4b2 100644
--- a/apps/app/tests/composer-editable-on-snapshot-error.test.tsx
+++ b/apps/app/tests/composer-editable-on-snapshot-error.test.tsx
@@ -107,6 +107,9 @@ test("the composer stays editable when snapshot refresh fails or the model is un
mock.module("@/react-app/domains/session/surface/composer/workspace-run-mode-menu", () => ({
WorkspaceRunModeMenu: () => null,
}));
+ mock.module("@/react-app/domains/session/surface/composer/full-permissions-toggle", () => ({
+ FullPermissionsToggle: () => null,
+ }));
mock.module("@/app/lib/opencode-session-native", () => ({
composeNativeSessionSnapshot: async () => {
if (rejectSnapshot) throw new Error("snapshot refresh failed");
diff --git a/apps/app/tests/composer-focus-continuity.test.tsx b/apps/app/tests/composer-focus-continuity.test.tsx
index 508d5155..0ea90f18 100644
--- a/apps/app/tests/composer-focus-continuity.test.tsx
+++ b/apps/app/tests/composer-focus-continuity.test.tsx
@@ -134,6 +134,7 @@ test("composer focus and optimistic sends preserve drafts through snapshots and
let fetchedSnapshot = createSnapshot({ type: "busy" }, 1);
mock.module("@/components/model-select", () => ({ ModelSelect: () => null }));
mock.module("@/react-app/domains/session/surface/composer/workspace-run-mode-menu", () => ({ WorkspaceRunModeMenu: () => null }));
+ mock.module("@/react-app/domains/session/surface/composer/full-permissions-toggle", () => ({ FullPermissionsToggle: () => null }));
mock.module("@/app/lib/opencode-session-native", () => ({
composeNativeSessionSnapshot: async () => fetchedSnapshot,
}));
diff --git a/apps/app/tests/full-permissions-toggle.test.tsx b/apps/app/tests/full-permissions-toggle.test.tsx
new file mode 100644
index 00000000..5fc5988e
--- /dev/null
+++ b/apps/app/tests/full-permissions-toggle.test.tsx
@@ -0,0 +1,260 @@
+/** @jsxImportSource react */
+import { afterEach, expect, mock, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+
+import type { OmniRushApprovalMode, OmniRushRuntimeApprovals } from "../src/app/lib/omnirush-server";
+import type { ApprovalsClient } from "../src/react-app/domains/settings/approval-mode";
+
+// The composer switch reads the organization policy through the desktop-config
+// provider and reports through the app toaster; neither is mounted here.
+let policyLocked = false;
+const toasts: string[] = [];
+mock.module("@/react-app/domains/cloud/desktop-config-provider", () => ({
+ useDesktopRestriction: () => policyLocked,
+}));
+mock.module("@/components/ui/sonner", () => ({
+ toast: {
+ success: (message: string) => toasts.push(`success:${message}`),
+ warning: (message: string) => toasts.push(`warning:${message}`),
+ error: (message: string) => toasts.push(`error:${message}`),
+ },
+}));
+
+if (typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined") {
+ GlobalRegistrator.register({ url: "http://localhost/" });
+}
+Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
+
+const [
+ { FullPermissionsToggle, FULL_PERMISSIONS_OFF_HINT, FULL_PERMISSIONS_POLICY_LOCK },
+ { useApprovalMode, useApprovalModeStore },
+ { ApprovalsCard },
+ { TooltipProvider },
+] = await Promise.all([
+ import("../src/react-app/domains/session/surface/composer/full-permissions-toggle"),
+ import("../src/react-app/domains/settings/approval-mode"),
+ import("../src/react-app/domains/settings/pages/general-view"),
+ import("../src/components/ui/tooltip"),
+]);
+
+function fakeClient(
+ baseUrl: string,
+ initial: OmniRushRuntimeApprovals,
+ options: { reloadError?: Error; setError?: Error; holdSet?: boolean } = {},
+) {
+ const calls: string[] = [];
+ let gets = 0;
+ let approvals = initial;
+ let release: (() => void) | null = null;
+ const client: ApprovalsClient = {
+ baseUrl,
+ getRuntimeApprovals: async () => {
+ gets += 1;
+ return approvals;
+ },
+ setRuntimeApprovals: async (mode: OmniRushApprovalMode) => {
+ calls.push(`set:${mode}`);
+ if (options.holdSet) await new Promise<void>((resolve) => { release = resolve; });
+ if (options.setError) throw options.setError;
+ approvals = { mode, source: "settings", setting: mode };
+ return { ...approvals, ok: true, changed: true };
+ },
+ reloadEngine: async (workspaceId: string) => {
+ calls.push(`reload:${workspaceId}`);
+ if (options.reloadError) throw options.reloadError;
+ return { ok: true };
+ },
+ };
+ return { client, calls, gets: () => gets, release: () => release?.() };
+}
+
+const mounted: { root: Root; container: HTMLElement }[] = [];
+
+async function mount(ui: ReactNode) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ mounted.push({ root, container });
+ await act(async () => root.render(<TooltipProvider delay={0}>{ui}</TooltipProvider>));
+ return container;
+}
+
+afterEach(async () => {
+ for (const { root, container } of mounted.splice(0)) {
+ await act(async () => root.unmount());
+ container.remove();
+ }
+ toasts.length = 0;
+ policyLocked = false;
+ useApprovalModeStore.setState({ byServer: {} });
+});
+
+async function waitFor(predicate: () => boolean, label: string) {
+ const deadline = Date.now() + 2_000;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
+ });
+ }
+ throw new Error(`Timed out waiting for ${label}`);
+}
+
+function toggleIn(container: HTMLElement): HTMLButtonElement {
+ const button = container.querySelector<HTMLButtonElement>('[data-testid="full-permissions-toggle"]');
+ if (!button) throw new Error("the Full permissions switch is not rendered");
+ return button;
+}
+
+async function click(button: HTMLElement) {
+ await act(async () => {
+ button.click();
+ });
+}
+
+const guardedByDefault: OmniRushRuntimeApprovals = { mode: "guarded", source: "default", setting: null };
+
+test("shows the current mode on load and reads as active while full permissions are on", async () => {
+ const guarded = fakeClient("http://guarded.test", guardedByDefault);
+ const container = await mount(<FullPermissionsToggle client={guarded.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(container).getAttribute("aria-disabled") === null, "the guarded mode to load");
+ const off = toggleIn(container);
+ expect(off.getAttribute("role")).toBe("switch");
+ expect(off.getAttribute("aria-checked")).toBe("false");
+ expect(off.textContent).toContain("Full permissions");
+ expect(off.dataset.state).toBe("off");
+ expect(off.dataset.lockReason).toBeUndefined();
+ expect(off.className).not.toContain("--dls-accent");
+
+ const full = fakeClient("http://full.test", { mode: "full", source: "settings", setting: "full" });
+ const active = await mount(<FullPermissionsToggle client={full.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(active).getAttribute("aria-checked") === "true", "the full mode to load");
+ expect(toggleIn(active).dataset.state).toBe("on");
+ expect(toggleIn(active).getAttribute("aria-disabled")).toBeNull();
+ expect(toggleIn(active).className).toContain("bg-[var(--dls-accent)]");
+
+ // Nothing renders without a server client.
+ const none = await mount(<FullPermissionsToggle client={null} workspaceId="ws_1" />);
+ expect(none.querySelector('[data-testid="full-permissions-toggle"]')).toBeNull();
+});
+
+test("is disabled with a tooltip while the environment or the organisation forces the mode", async () => {
+ const env = fakeClient("http://env.test", { mode: "full", source: "environment", setting: "guarded" });
+ const container = await mount(<FullPermissionsToggle client={env.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(container).getAttribute("aria-checked") === "true", "the environment mode to load");
+ const button = toggleIn(container);
+ expect(button.getAttribute("aria-disabled")).toBe("true");
+ expect(button.dataset.lockReason).toBe("Set by environment (OMNIRUSH_APPROVALS=full); change it where the app is launched.");
+ await click(button);
+ expect(env.calls).toEqual([]);
+ expect(toasts).toEqual([]);
+
+ await act(async () => {
+ button.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
+ button.dispatchEvent(new MouseEvent("mouseenter"));
+ });
+ await waitFor(
+ () => document.querySelector('[data-slot="tooltip-content"]')?.textContent?.includes("Set by environment (OMNIRUSH_APPROVALS=full)") === true,
+ "the environment tooltip",
+ );
+
+ policyLocked = true;
+ const guarded = fakeClient("http://policy.test", guardedByDefault);
+ const locked = await mount(<FullPermissionsToggle client={guarded.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(locked).dataset.lockReason === FULL_PERMISSIONS_POLICY_LOCK, "the policy lock");
+ expect(toggleIn(locked).getAttribute("aria-disabled")).toBe("true");
+ await click(toggleIn(locked));
+ expect(guarded.calls).toEqual([]);
+});
+
+test("clicking persists the mode, reloads the engine and stays disabled while the reload is in flight", async () => {
+ const held = fakeClient("http://toggle.test", guardedByDefault, { holdSet: true });
+ const container = await mount(<FullPermissionsToggle client={held.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(container).getAttribute("aria-disabled") === null, "the guarded mode to load");
+
+ await click(toggleIn(container));
+ await waitFor(() => toggleIn(container).getAttribute("aria-busy") === "true", "the in-flight state");
+ expect(toggleIn(container).getAttribute("aria-disabled")).toBe("true");
+ expect(held.calls).toEqual(["set:full"]);
+ // A second click while in flight is ignored.
+ await click(toggleIn(container));
+ expect(held.calls).toEqual(["set:full"]);
+
+ await act(async () => held.release());
+ await waitFor(() => toggleIn(container).getAttribute("aria-checked") === "true", "the full mode");
+ expect(held.calls).toEqual(["set:full", "reload:ws_1"]);
+ expect(toggleIn(container).getAttribute("aria-busy")).toBeNull();
+ expect(toggleIn(container).getAttribute("aria-disabled")).toBeNull();
+ expect(toasts).toEqual(["success:Full permissions on. Engine reloaded."]);
+
+ await click(toggleIn(container));
+ await act(async () => held.release());
+ await waitFor(() => toggleIn(container).getAttribute("aria-checked") === "false", "the guarded mode again");
+ expect(held.calls.slice(2)).toEqual(["set:guarded", "reload:ws_1"]);
+ expect(toasts[1]).toBe("success:Guarded mode. Engine reloaded.");
+});
+
+test("reports a failed reload or a refused change without losing the switch", async () => {
+ const reloadFails = fakeClient("http://reload-fails.test", guardedByDefault, { reloadError: new Error("engine busy") });
+ const container = await mount(<FullPermissionsToggle client={reloadFails.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(container).getAttribute("aria-disabled") === null, "the guarded mode to load");
+ await click(toggleIn(container));
+ await waitFor(() => toggleIn(container).getAttribute("aria-checked") === "true", "the saved full mode");
+ expect(toasts).toEqual(["warning:Full permissions on. Engine reload failed: engine busy Use Reload in Settings to apply it."]);
+
+ const refused = fakeClient("http://refused.test", guardedByDefault, { setError: new Error("settings are locked") });
+ const other = await mount(<FullPermissionsToggle client={refused.client} workspaceId="ws_1" />);
+ await waitFor(() => toggleIn(other).getAttribute("aria-disabled") === null, "the second guarded mode to load");
+ await click(toggleIn(other));
+ await waitFor(() => toasts.length === 2, "the error toast");
+ expect(toasts[1]).toBe("error:settings are locked");
+ expect(toggleIn(other).getAttribute("aria-checked")).toBe("false");
+ expect(toggleIn(other).getAttribute("aria-disabled")).toBeNull();
+ expect(refused.calls).toEqual(["set:full"]);
+});
+
+/** The Settings card exactly as GeneralSettingsView wires it. */
+function SettingsCard(props: { client: ApprovalsClient }) {
+ const mode = useApprovalMode(props.client, "ws_1");
+ return (
+ <ApprovalsCard
+ approvals={mode.approvals}
+ busy={mode.busy}
+ status={mode.status}
+ onToggle={(enabled) => void mode.setFullPermissions(enabled)}
+ />
+ );
+}
+
+test("shares its state with the Settings card, so a change in either shows in the other", async () => {
+ const shared = fakeClient("http://shared.test", guardedByDefault);
+ const container = await mount(
+ <>
+ <FullPermissionsToggle client={shared.client} workspaceId="ws_1" />
+ <SettingsCard client={shared.client} />
+ </>,
+ );
+ const cardSwitch = () => {
+ const element = container.querySelector<HTMLButtonElement>('[role="switch"][data-slot="switch"]');
+ if (!element) throw new Error("the Settings switch is not rendered");
+ return element;
+ };
+ await waitFor(() => toggleIn(container).getAttribute("aria-disabled") === null, "the shared load");
+ expect(shared.gets()).toBe(1);
+ expect(cardSwitch().getAttribute("aria-checked")).toBe("false");
+
+ await click(toggleIn(container));
+ await waitFor(() => cardSwitch().getAttribute("aria-checked") === "true", "the card to follow the composer");
+ expect(container.querySelector('[data-testid="approvals-status"]')?.textContent).toBe("Full permissions on. Engine reloaded.");
+ expect(toasts).toEqual(["success:Full permissions on. Engine reloaded."]);
+
+ await click(cardSwitch());
+ await waitFor(() => toggleIn(container).getAttribute("aria-checked") === "false", "the composer to follow the card");
+ expect(shared.calls).toEqual(["set:full", "reload:ws_1", "set:guarded", "reload:ws_1"]);
+ // Settings changes report inline, not through the composer toast.
+ expect(toasts).toHaveLength(1);
+ expect(toggleIn(container).dataset.lockReason).toBeUndefined();
+ expect(FULL_PERMISSIONS_OFF_HINT).toContain("Guarded mode");
+});
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index fa2c4e25..667822b5 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -1927,6 +1927,10 @@ export function createRuntimeManager({
const gatewayCredentials = await omnirushGatewayCredentials?.load?.() ?? null;
// Inject user env vars so the server and managed OpenCode inherit them.
+ // The embedded server runs in this process and reads process.env, so an
+ // OMNIRUSH_APPROVALS=full|guarded from the launching shell reaches it
+ // here (the user env file cannot set OMNIRUSH_* keys, see
+ // loadUserEnvFile) and forces the engine approval mode.
const serverEnv = await buildChildEnv({});
Object.assign(process.env, serverEnv);
if (omnirushGatewayCredentials) {
diff --git a/apps/server/src/approval-mode.ts b/apps/server/src/approval-mode.ts
new file mode 100644
index 00000000..441324ce
--- /dev/null
+++ b/apps/server/src/approval-mode.ts
@@ -0,0 +1,51 @@
+/**
+ * Approval mode of the desktop engine.
+ *
+ * guarded (default) the git workflow rules ask for write and destructive
+ * commands; everything else follows the engine defaults.
+ * full every engine permission is allowed without a prompt; the
+ * organization's deny rules from Den still apply.
+ *
+ * Precedence, highest first: OMNIRUSH_APPROVALS=full|guarded in the server
+ * (desktop) process environment, then the user setting persisted in the
+ * global runtime config row, then guarded. The server resolves the mode; the
+ * managed-policy engine plugin learns it from every /managed-policy/evaluate
+ * answer, so a toggle applies to the next tool call without an engine restart
+ * (the injected permission rules still need the reload Settings triggers).
+ *
+ * Shared by the server and the engine plugins (imported with "../"), so it
+ * must stay free of server-only dependencies.
+ */
+export type ApprovalMode = "guarded" | "full";
+export type ApprovalModeSource = "environment" | "settings" | "default";
+
+export const APPROVAL_MODE_ENV = "OMNIRUSH_APPROVALS";
+export const DEFAULT_APPROVAL_MODE: ApprovalMode = "guarded";
+
+export interface ResolvedApprovalMode {
+ mode: ApprovalMode;
+ source: ApprovalModeSource;
+ /** The persisted user setting, whether or not the environment overrides it. */
+ setting: ApprovalMode | null;
+}
+
+export function parseApprovalMode(value: unknown): ApprovalMode | null {
+ if (typeof value !== "string") return null;
+ const mode = value.trim().toLowerCase();
+ return mode === "full" || mode === "guarded" ? mode : null;
+}
+
+export function approvalModeFromEnv(env: NodeJS.ProcessEnv = process.env): ApprovalMode | null {
+ return parseApprovalMode(env[APPROVAL_MODE_ENV]);
+}
+
+export function resolveApprovalMode(
+ runtime: { approvals?: { mode: ApprovalMode } },
+ env: NodeJS.ProcessEnv = process.env,
+): ResolvedApprovalMode {
+ const setting = runtime.approvals?.mode ?? null;
+ const environment = approvalModeFromEnv(env);
+ if (environment) return { mode: environment, source: "environment", setting };
+ if (setting) return { mode: setting, source: "settings", setting };
+ return { mode: DEFAULT_APPROVAL_MODE, source: "default", setting };
+}
diff --git a/apps/server/src/git-command-policy.test.ts b/apps/server/src/git-command-policy.test.ts
index df015748..d5b0920e 100644
--- a/apps/server/src/git-command-policy.test.ts
+++ b/apps/server/src/git-command-policy.test.ts
@@ -24,13 +24,24 @@ function commandNodes(command: string): string[] {
});
}
-/** The engine's evaluation: its own allow-everything default followed by the injected bash rules; last match wins. */
-function engineAction(bash: Record<string, string>, command: string): string {
+/** The engine's evaluation: its own allow-everything default followed by the injected bash rules; last match wins. The plugin marks destructive commands in guarded mode only. */
+function engineAction(bash: Record<string, string>, command: string, mode: "guarded" | "full" = "guarded"): string {
const rules = [{ permission: "*", pattern: "*", action: "allow" as const }, ...rulesFromPermissionConfig({ bash })];
- const marked = markDestructiveCommands(command).command;
+ const marked = mode === "full" ? command : markDestructiveCommands(command).command;
return commandNodes(marked).map((node) => winningRule(rules, "bash", node)?.action ?? "ask").join(",");
}
+/** The pinned engine's own default ruleset for the omnirush agent, as effective-permissions.e2e.test.ts records it. */
+const ENGINE_DEFAULT_RULES = [
+ { permission: "*", pattern: "*", action: "allow" as const },
+ { permission: "doom_loop", pattern: "*", action: "ask" as const },
+ { permission: "external_directory", pattern: "*", action: "ask" as const },
+ { permission: "read", pattern: "*", action: "allow" as const },
+ { permission: "read", pattern: "*.env", action: "ask" as const },
+ { permission: "read", pattern: "*.env.*", action: "ask" as const },
+ { permission: "read", pattern: "*.env.example", action: "allow" as const },
+];
+
describe("git workflow command classification", () => {
test("read-only git and gh commands", () => {
for (const command of [
@@ -267,6 +278,45 @@ describe("git workflow permission rules", () => {
expect(engineAction(blocked, "gh pr list")).toBe("allow");
});
+ test("full approval mode: one catch-all allow, no ask rules, organization denies still come last", () => {
+ const full = legacyExecutionPermissions(undefined, "full");
+ expect(full).toEqual({ bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" });
+ for (const command of ["git status", "git commit -m x", "git push --force origin f", "rm -rf build", "sudo rm -rf /x",
+ "bash -c 'git reset --hard'", `${DESTRUCTIVE_MARKER} git push -f origin f`, "if git push -f origin f; then echo ok; fi"]) {
+ expect(engineAction(full.bash, command, "full").split(",").every((action) => action === "allow")).toBe(true);
+ }
+ const denied = legacyExecutionPermissions({ commands: "deny", blockedCommands: [], blockBrowserUploads: false }, "full");
+ expect(denied.bash).toEqual({ "*": "deny" });
+ expect(engineAction(denied.bash, "echo hi", "full")).toBe("deny");
+ const blocked = legacyExecutionPermissions(
+ { commands: "allow", blockedCommands: ["git push*"], browserOrigins: ["https://approved.example"], blockBrowserUploads: false },
+ "full",
+ );
+ expect(Object.entries(blocked.bash)).toEqual([["*", "allow"], ["git push*", "deny"]]);
+ expect(engineAction(blocked.bash, "git push --force origin f", "full")).toBe("deny");
+ expect(engineAction(blocked.bash, "rm -rf build", "full")).toBe("allow");
+ expect(blocked).toMatchObject({ read: { "*": "allow" }, edit: "allow", webfetch: "deny", websearch: "deny" });
+ });
+
+ test("full approval mode outranks the engine's default ask rules, including reading .env files", () => {
+ // The engine appends the injected block after its own defaults; last match wins.
+ const action = (mode: "guarded" | "full", permission: string, pattern: string) =>
+ winningRule([...ENGINE_DEFAULT_RULES, ...rulesFromPermissionConfig(legacyExecutionPermissions(undefined, mode))], permission, pattern)?.action ?? "ask";
+ // Guarded mode leaves every category but bash to the engine defaults.
+ expect(action("guarded", "read", "/workspace/.env")).toBe("ask");
+ expect(action("guarded", "read", "/workspace/.env.local")).toBe("ask");
+ expect(action("guarded", "read", "/workspace/.env.example")).toBe("allow");
+ expect(action("guarded", "external_directory", "/outside/repo")).toBe("ask");
+ expect(action("guarded", "doom_loop", "*")).toBe("ask");
+ for (const [permission, pattern] of [
+ ["read", "/workspace/.env"], ["read", "/workspace/.env.local"], ["read", "/workspace/src/index.ts"],
+ ["bash", "git push --force origin f"], ["edit", "/workspace/.env"], ["external_directory", "/outside/repo"],
+ ["doom_loop", "*"], ["webfetch", "https://example.com"], ["websearch", "*"],
+ ]) {
+ expect({ permission, pattern, action: action("full", permission, pattern) }).toEqual({ permission, pattern, action: "allow" });
+ }
+ });
+
test("rule table shape", () => {
const rules = gitWorkflowPermissionRules();
expect(Object.entries(rules).slice(0, 3)).toEqual([["git *", "ask"], ["gh *", "ask"], ["sudo *", "ask"]]);
diff --git a/apps/server/src/managed-policy-rules.ts b/apps/server/src/managed-policy-rules.ts
index 20d61bf7..32db0026 100644
--- a/apps/server/src/managed-policy-rules.ts
+++ b/apps/server/src/managed-policy-rules.ts
@@ -1,5 +1,6 @@
import type { DesktopConfig, DesktopExecutionPolicy, DesktopPolicyKey } from "@omnirush/types/den/desktop-policies";
import { z } from "zod";
+import type { ApprovalMode } from "./approval-mode.js";
import { gitWorkflowPermissionRules } from "./git-command-policy.js";
export const managedPolicyActionSchema = z.enum([
@@ -41,18 +42,30 @@ export function executionRules(policy: DesktopExecutionPolicy | undefined): Engi
}
type LegacyExecutionPermissions = {
bash: Record<string, "allow" | "ask" | "deny">;
+ /** Full mode only: a catch-all allow appended after the engine's default `read *.env: ask` / `read *.env.*: ask` rules. */
+ read?: Record<string, "allow">;
webfetch?: "allow" | "deny";
websearch?: "allow" | "deny";
+ edit?: "allow";
+ doom_loop?: "allow";
+ external_directory?: "allow";
};
/**
- * Engine permission block for every managed desktop: the built-in git and PR
- * workflow rules (read-only commands run, write commands ask once per
- * session per command family, destructive commands always ask) followed by
- * the organization's execution policy. The engine picks the last matching
- * rule, so an organization deny always wins over a workflow allow.
+ * Engine permission block for every managed desktop: in guarded mode the
+ * built-in git and PR workflow rules (read-only commands run, write commands
+ * ask once per session per command family, destructive commands always ask);
+ * in full mode a single catch-all allow for bash, a catch-all allow for read
+ * (the engine's own defaults ask before reading `*.env` and `*.env.*`; the
+ * later `read *` allow wins) and allow for every other permission category
+ * the pinned engine exposes, so nothing asks. Both are
+ * followed by the organization's execution policy. The engine picks the last
+ * matching rule, so an organization deny always wins over a workflow or
+ * full-mode allow.
*/
-export function legacyExecutionPermissions(policy: DesktopExecutionPolicy | undefined): LegacyExecutionPermissions {
- const permissions: LegacyExecutionPermissions = { bash: gitWorkflowPermissionRules() };
+export function legacyExecutionPermissions(policy: DesktopExecutionPolicy | undefined, mode: ApprovalMode = "guarded"): LegacyExecutionPermissions {
+ const permissions: LegacyExecutionPermissions = mode === "full"
+ ? { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" }
+ : { bash: gitWorkflowPermissionRules() };
for (const rule of executionRules(policy)) {
if (rule.action === "shell") {
// Re-insert so a pattern the workflow rules already use moves after them.
@@ -140,6 +153,7 @@ export function policyRequestActions(method: string, path: string): ManagedPolic
const actions: ManagedPolicyAction[] = [];
if (/^\/workspaces\/(local|remote)$/.test(path)) actions.push("workspace");
if (/^\/runtime-config\/providers$/.test(path)) actions.push("provider");
+ if (/^\/runtime-config\/approvals$/.test(path)) actions.push("settings");
if (/^\/workspace\/[^/]+\/(?:cloud-plugins|claude-plugins|plugins|skills|commands|mcp)(?:\/|$)/.test(path)
&& !/\/mcp\/[^/]+\/(?:auth|managed\/connect)$/.test(path)) actions.push("extensions");
if (/^\/workspace\/[^/]+\/(?:config|opencode-config|runtime-config|permissions|authorized-folders)(?:\/|$)/.test(path)) actions.push("settings");
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index 512f62c0..517b78b4 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -11,6 +11,7 @@ import {
writeOmniRushRuntimeConfigFile,
} from "./omnirush-runtime-config.js";
import { writeGlobalRuntimeOpencodeConfig, writeRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";
+import { rulesFromPermissionConfig, winningRule } from "./effective-permissions.js";
import { gitWorkflowPermissionRules } from "./git-command-policy.js";
import type { ServerConfig } from "./types.js";
@@ -76,6 +77,41 @@ describe("omnirush runtime config file", () => {
expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).permission).toEqual({ bash: gitWorkflowPermissionRules() });
});
+ test("full approval mode allows every permission category; the environment overrides the setting", () => {
+ const permission = { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" };
+ const full = buildOmniRushRuntimeConfigObjectFromSnapshot(
+ { approvals: { mode: "full" }, permission: { external_directory: { "/Users/sam/Docs": "allow" } } },
+ undefined,
+ {},
+ );
+ expect(full.permission).toEqual(permission);
+ expect(full.agent).toMatchObject({ omnirush: { permission: { ...permission, skill: { "get-started": "deny" } } } });
+ // The setting is server state, never engine config.
+ expect(full.approvals).toBeUndefined();
+
+ // The engine asks before reading .env files by default and appends the injected block after its
+ // own rules; the full-mode catch-all read allow wins, the guarded block leaves the default alone.
+ const engineEnvDefaults = [{ permission: "read", pattern: "*.env", action: "ask" as const }, { permission: "read", pattern: "*.env.*", action: "ask" as const }];
+ const guarded = buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {});
+ for (const file of ["/workspace/.env", "/workspace/.env.local"]) {
+ expect(winningRule([...engineEnvDefaults, ...rulesFromPermissionConfig(full.permission)], "read", file)?.action).toBe("allow");
+ expect(winningRule([...engineEnvDefaults, ...rulesFromPermissionConfig(guarded.permission)], "read", file)?.action).toBe("ask");
+ }
+
+ // Organization denies are appended last so the engine's last-match-wins keeps them.
+ const denied = buildOmniRushRuntimeConfigObjectFromSnapshot({
+ approvals: { mode: "full" },
+ managedPolicy: { execution: { commands: "allow", blockedCommands: ["curl *"], browserOrigins: ["https://approved.example"], blockBrowserUploads: false } },
+ }, undefined, {});
+ expect(denied.permission).toEqual({ ...permission, bash: { "*": "allow", "curl *": "deny" }, webfetch: "deny", websearch: "deny" });
+
+ // OMNIRUSH_APPROVALS on the server process wins in both directions; the default stays guarded.
+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({ approvals: { mode: "full" } }, undefined, { OMNIRUSH_APPROVALS: "guarded" }).permission)
+ .toEqual({ bash: gitWorkflowPermissionRules() });
+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, { OMNIRUSH_APPROVALS: "full" }).permission).toEqual(permission);
+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {}).permission).toEqual({ bash: gitWorkflowPermissionRules() });
+ });
+
test("writes global-row MCPs and omnirush defaults into the file", async () => {
const { config } = await setup();
await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 56df4b5c..6f532412 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -1,3 +1,4 @@
+import { resolveApprovalMode } from "./approval-mode.js";
import { legacyExecutionPermissions } from "./managed-policy-rules.js";
import { managedPolicyPluginPath } from "./managed-policy-plugin.js";
/**
@@ -160,10 +161,12 @@ export async function buildOmniRushRuntimeConfigObject(
export function buildOmniRushRuntimeConfigObjectFromSnapshot(
runtimeConfig: RuntimeOpencodeConfig,
internalGateway?: InternalGatewayRuntime,
+ env: NodeJS.ProcessEnv = process.env,
): Record<string, unknown> {
const disabledProviders = runtimeDisabledProviderList(runtimeConfig);
- const permissions = legacyExecutionPermissions(runtimeConfig.managedPolicy?.execution);
- const { managedPolicy: _managedPolicy, ...engineConfig } = runtimeConfig;
+ // OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.
+ const permissions = legacyExecutionPermissions(runtimeConfig.managedPolicy?.execution, resolveApprovalMode(runtimeConfig, env).mode);
+ const { managedPolicy: _managedPolicy, approvals: _approvals, ...engineConfig } = runtimeConfig;
const provider = {
...runtimeProviderMap(runtimeConfig),
...(internalGateway
diff --git a/apps/server/src/opencode-plugins/managed-policy-client.ts b/apps/server/src/opencode-plugins/managed-policy-client.ts
index 25846816..7fb1e6f7 100644
--- a/apps/server/src/opencode-plugins/managed-policy-client.ts
+++ b/apps/server/src/opencode-plugins/managed-policy-client.ts
@@ -4,6 +4,7 @@ import { execFile } from "node:child_process";
import { isAbsolute, resolve } from "node:path";
import { promisify } from "node:util";
+import { DEFAULT_APPROVAL_MODE, parseApprovalMode, type ApprovalMode } from "../approval-mode.js";
import type { ManagedPolicyAction } from "../managed-policy-rules.js";
import { classifyShellCommand, markDestructiveCommands, type ClassifiedCommand, type IdentityFields } from "../git-command-policy.js";
@@ -30,18 +31,26 @@ export async function checkManagedTool(tool: string, raw: unknown, context: Mana
else if (tool === "webfetch" || tool === "websearch") action = tool;
else if (tool === "browser_navigate" || tool === "browser_open") action = "browser";
else if (tool === "omnirush_execute") {
- if (input.id === "browser.open_url") return check("browser", record(input.args));
+ if (input.id === "browser.open_url") {
+ await check("browser", record(input.args));
+ return;
+ }
if (typeof input.id === "string" && /^(?:plugin|skill|mcp)\.(?:install|add|update|remove)/.test(input.id)) action = "extensions";
}
// Even read-only tools synchronize policy, so unknown identities cannot keep
// running with a previous member's loaded configuration.
- await check(action ?? "sync", input);
+ const verdict = await check(action ?? "sync", input);
// The organization policy saw the command as written; the git workflow
// rules then rewrite it in place (the engine reads the same args object).
- if (action === "shell") await prepareShellCommand(input, context);
+ if (action === "shell") await prepareShellCommand(input, context, { approvalMode: verdict.approvalMode });
+}
+
+export interface PolicyVerdict {
+ /** Approval mode the server resolved (environment, then setting, then guarded) at the time of this call. */
+ approvalMode: ApprovalMode;
}
-export async function check(action: ManagedPolicyAction, input: Record<string, unknown>): Promise<void> {
+export async function check(action: ManagedPolicyAction, input: Record<string, unknown>): Promise<PolicyVerdict> {
const base = process.env.OMNIRUSH_SERVER_URL;
const token = process.env.OMNIRUSH_POLICY_TOKEN;
if (!base || !token) throw new Error("OmniRush.ai policy service is unavailable.");
@@ -49,10 +58,12 @@ export async function check(action: ManagedPolicyAction, input: Record<string, u
method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({ action, input }), signal: AbortSignal.timeout(15_000),
});
+ const payload = record(await response.json().catch(() => undefined));
if (!response.ok) {
- const payload = record(await response.json());
throw new Error(typeof payload.message === "string" ? payload.message : "Your organization blocked this action.");
}
+ // A server that predates approval modes answers without one: guarded.
+ return { approvalMode: parseApprovalMode(payload.approvalMode) ?? DEFAULT_APPROVAL_MODE };
}
// ---------------------------------------------------------------------------
@@ -106,6 +117,8 @@ export interface PrepareShellOptions {
readIdentity?: GitIdentityReader;
ensureIdentity?: (directory: string) => Promise<void>;
env?: NodeJS.ProcessEnv;
+ /** Full mode leaves the command untouched and never refuses a commit; default guarded. */
+ approvalMode?: ApprovalMode;
}
/** Repositories the command records commits in, resolved against the tool's working directory. */
@@ -127,6 +140,11 @@ export function commitRepositories(classified: ClassifiedCommand[], cwd: string)
* an exported `GIT_AUTHOR_*` / `GIT_COMMITTER_*` pair or the process
* environment, so the recovery the refusal message asks for is never refused
* again.
+ *
+ * In full approval mode nothing asks, so the destructive marker is not
+ * written and a missing identity never refuses the command: the account
+ * identity is still applied to the repository when one is connected, and the
+ * commit runs with whatever git has otherwise.
*/
export async function prepareShellCommand(
input: Record<string, unknown>,
@@ -134,9 +152,10 @@ export async function prepareShellCommand(
options: PrepareShellOptions = {},
): Promise<void> {
if (typeof input.command !== "string") return;
- const marked = markDestructiveCommands(input.command);
- if (marked.command !== input.command) input.command = marked.command;
- const classified = classifyShellCommand(marked.command);
+ const full = options.approvalMode === "full";
+ const command = full ? input.command : markDestructiveCommands(input.command).command;
+ if (command !== input.command) input.command = command;
+ const classified = classifyShellCommand(command);
const base = context.directory && isAbsolute(context.directory) ? context.directory : process.cwd();
const workdir = typeof input.workdir === "string" && input.workdir.trim() ? input.workdir.trim() : ".";
const cwd = resolve(base, workdir);
@@ -164,11 +183,21 @@ export async function prepareShellCommand(
}
// The server applies the account identity to this repository or refuses
// with the message that explains what to ask the user.
- await ensureIdentity(directory);
+ try {
+ await ensureIdentity(directory);
+ } catch (error) {
+ if (!full) throw error;
+ settled.add(directory);
+ continue;
+ }
const after = await readIdentity(directory);
if (!after.name || !after.email) {
- throw new Error("Git identity is not configured for this repository (user.name and user.email are unset). "
- + 'Ask the user which name and email to commit with, then run: git config user.name "<name>" && git config user.email "<email>" (never --global).');
+ if (!full) {
+ throw new Error("Git identity is not configured for this repository (user.name and user.email are unset). "
+ + 'Ask the user which name and email to commit with, then run: git config user.name "<name>" && git config user.email "<email>" (never --global).');
+ }
+ settled.add(directory);
+ continue;
}
settled.add(directory);
notes.push(`omnirush.ai set the commit identity for ${directory} to ${after.name} <${after.email}> from the connected omnirush.ai account `
diff --git a/apps/server/src/opencode-plugins/managed-policy-next.ts b/apps/server/src/opencode-plugins/managed-policy-next.ts
index 4bd8444e..3c7fd058 100644
--- a/apps/server/src/opencode-plugins/managed-policy-next.ts
+++ b/apps/server/src/opencode-plugins/managed-policy-next.ts
@@ -15,7 +15,7 @@ export default {
applyEnginePath();
await ctx.tool.hook("execute.before", (event) =>
checkManagedTool(event.tool, event.input, { directory: ctx.directory, callID: event.callID, sessionID: event.sessionID }));
- await ctx.shell.hook("create.before", (event) => check("shell", { command: event.command }));
- await ctx.session.hook("http.request", (event) => check("model", event.model));
+ await ctx.shell.hook("create.before", async (event) => { await check("shell", { command: event.command }); });
+ await ctx.session.hook("http.request", async (event) => { await check("model", event.model); });
},
};
diff --git a/apps/server/src/opencode-plugins/managed-policy.test.ts b/apps/server/src/opencode-plugins/managed-policy.test.ts
index 856db4a8..5f2a2f07 100644
--- a/apps/server/src/opencode-plugins/managed-policy.test.ts
+++ b/apps/server/src/opencode-plugins/managed-policy.test.ts
@@ -45,7 +45,7 @@ async function temporaryRepository(): Promise<string> {
* Stand-in for the server's /managed-policy/evaluate route: records calls and,
* for git_identity, behaves like a desktop with (or without) an account.
*/
-function policyServer(options: { account: { name: string; email: string } | null }) {
+function policyServer(options: { account: { name: string; email: string } | null; approvalMode?: "guarded" | "full" }) {
const calls: EvaluateCall[] = [];
const server = Bun.serve({
port: 0,
@@ -62,7 +62,8 @@ function policyServer(options: { account: { name: string; email: string } | null
if (!gitGet(directory, "--get", "user.name")) git(directory, "config", "--local", "user.name", options.account.name);
if (!gitGet(directory, "--get", "user.email")) git(directory, "config", "--local", "user.email", options.account.email);
}
- return Response.json({ allowed: true });
+ // A server without approval modes answers without the field (guarded).
+ return Response.json({ allowed: true, ...(options.approvalMode ? { approvalMode: options.approvalMode } : {}) });
},
});
stops.push(() => server.stop(true));
@@ -219,6 +220,56 @@ describe("managed-policy engine plugin: git workflows", () => {
expect(gitGet(workspace, "--local", "--get", "user.email")).toBe("");
});
+ test("full approval mode: no destructive marker and no identity refusal, the organization policy still evaluated", async () => {
+ const { calls } = policyServer({ account: null, approvalMode: "full" });
+ const repo = await temporaryRepository();
+ const hooks = await managedPolicy({ directory: repo });
+ const push: Record<string, unknown> = { command: "git status && git push --force origin main" };
+ await hooks["tool.execute.before"]({ tool: "bash", callID: "call_20", sessionID: "ses_1" }, { args: push });
+ expect(push.command).toBe("git status && git push --force origin main");
+ // A commit in a repository without an identity and without an account runs instead of being refused.
+ const commit: Record<string, unknown> = { command: "git commit -m x && rm -rf build" };
+ await hooks["tool.execute.before"]({ tool: "bash", callID: "call_21", sessionID: "ses_1" }, { args: commit });
+ expect(commit.command).toBe("git commit -m x && rm -rf build");
+ expect(calls.map((call) => call.action)).toEqual(["shell", "shell", "git_identity"]);
+ expect(await readGitIdentity(repo)).toEqual({ repository: true, name: null, email: null });
+ expect(annotateShellOutput("call_21", "out")).toBe("out");
+ // A marker the model wrote itself is left alone: nothing asks anyway.
+ const marked: Record<string, unknown> = { command: `${DESTRUCTIVE_MARKER} rm -rf build` };
+ await hooks["tool.execute.before"]({ tool: "bash", callID: "call_22", sessionID: "ses_1" }, { args: marked });
+ expect(marked.command).toBe(`${DESTRUCTIVE_MARKER} rm -rf build`);
+ });
+
+ test("full approval mode still sets the connected account's identity for the repository and says so", async () => {
+ const { calls } = policyServer({ account: { name: "Sam Example", email: "[email protected]" }, approvalMode: "full" });
+ const repo = await temporaryRepository();
+ const hooks = await managedPolicy({ directory: repo });
+ const args: Record<string, unknown> = { command: "git commit -m x" };
+ await hooks["tool.execute.before"]({ tool: "bash", callID: "call_23", sessionID: "ses_1" }, { args });
+ expect(calls.map((call) => call.action)).toEqual(["shell", "git_identity"]);
+ expect(git(repo, "config", "--local", "--get", "user.name")).toBe("Sam Example");
+ expect(gitGet(repo, "--global", "--get", "user.name")).toBe("");
+ const output = { title: "git commit", output: "[main abc] x", metadata: {} };
+ await hooks["tool.execute.after"]({ tool: "bash", callID: "call_23", sessionID: "ses_1", args }, output);
+ expect(output.output).toContain("set the commit identity for");
+ });
+
+ test("the next-engine plugin skips the marker and the refusal in full mode as well", async () => {
+ const { calls } = policyServer({ account: null, approvalMode: "full" });
+ const repo = await temporaryRepository();
+ const hooks: Record<string, (event: never) => Promise<void>> = {};
+ await managedPolicyNext.setup({
+ directory: repo,
+ tool: { hook: async (name, callback) => { hooks[`tool.${name}`] = callback as never; } },
+ shell: { hook: async (name, callback) => { hooks[`shell.${name}`] = callback as never; } },
+ session: { hook: async (name, callback) => { hooks[`session.${name}`] = callback as never; } },
+ });
+ const input: Record<string, unknown> = { command: "git commit -m x && rm -rf build" };
+ await hooks["tool.execute.before"]({ tool: "bash", input, callID: "call_24" } as never);
+ expect(input.command).toBe("git commit -m x && rm -rf build");
+ expect(calls.map((call) => call.action)).toEqual(["shell", "git_identity"]);
+ });
+
test("hands the bash tool a PATH with the well-known tool directories", async () => {
policyServer({ account: null });
const hooks = await managedPolicy({ directory: await temporaryRepository() });
diff --git a/apps/server/src/opencode-plugins/managed-policy.ts b/apps/server/src/opencode-plugins/managed-policy.ts
index 18ef2cbe..8ca63546 100644
--- a/apps/server/src/opencode-plugins/managed-policy.ts
+++ b/apps/server/src/opencode-plugins/managed-policy.ts
@@ -19,6 +19,6 @@ export default async function managedPolicy(input?: { directory?: string }) {
"shell.env": async (_event: { cwd: string }, output: { env: Record<string, string> }) => {
if (enginePath) output.env.PATH = enginePath;
},
- "chat.params": async (input: { model: { providerID: string; id: string } }) => check("model", input.model),
+ "chat.params": async (input: { model: { providerID: string; id: string } }) => { await check("model", input.model); },
};
}
diff --git a/apps/server/src/runtime-opencode-config-store.test.ts b/apps/server/src/runtime-opencode-config-store.test.ts
index 2d43cd50..f4800139 100644
--- a/apps/server/src/runtime-opencode-config-store.test.ts
+++ b/apps/server/src/runtime-opencode-config-store.test.ts
@@ -2,6 +2,9 @@ import { describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { resolveApprovalMode } from "./approval-mode.js";
+import { managedDesktopPolicy } from "./managed-desktop-policy.js";
+import { policyRequestActions } from "./managed-policy-rules.js";
import { addMcp, listMcp, setMcpEnabled } from "./mcp.js";
import { buildOmniRushRuntimeConfig } from "./omnirush-runtime-config.js";
import { readOmniRushWorkspaceConfig } from "./omnirush-workspace-config-store.js";
@@ -327,4 +330,55 @@ describe("runtime OpenCode config store", () => {
}
});
});
+
+ test("approval mode persists in the global row, OMNIRUSH_APPROVALS overrides it, and the engine plugin is told", async () => {
+ await withWorkspace(async ({ config }) => {
+ const previousMode = process.env.OMNIRUSH_APPROVALS;
+ delete process.env.OMNIRUSH_APPROVALS;
+ const server = await startServer(config) as Served;
+ const base = `http://127.0.0.1:${server.port}`;
+ const headers = { authorization: `Bearer ${config.token}`, "content-type": "application/json" };
+ const readApprovals = async () => (await fetch(`${base}/runtime-config/approvals`, { headers })).json();
+ const policyHeaders = { authorization: `Bearer ${managedDesktopPolicy(config).evaluationToken}`, "content-type": "application/json" };
+ const evaluate = async () => (await fetch(`${base}/managed-policy/evaluate`, {
+ method: "POST", headers: policyHeaders, body: JSON.stringify({ action: "shell", input: { command: "git status" } }),
+ })).json();
+ try {
+ expect(await readApprovals()).toEqual({ mode: "guarded", source: "default", setting: null });
+ expect(await evaluate()).toEqual({ allowed: true, approvalMode: "guarded" });
+
+ const invalid = await fetch(`${base}/runtime-config/approvals`, { method: "PUT", headers, body: JSON.stringify({ mode: "yes" }) });
+ expect(invalid.status).toBe(400);
+
+ const enabled = await fetch(`${base}/runtime-config/approvals`, { method: "PUT", headers, body: JSON.stringify({ mode: "full" }) });
+ expect(enabled.status).toBe(200);
+ expect(await enabled.json()).toEqual({ ok: true, changed: true, mode: "full", source: "settings", setting: "full" });
+ expect((await readGlobalRuntimeOpencodeConfig(config)).approvals).toEqual({ mode: "full" });
+ // Workspace rows never carry the mode; the effective config inherits the global one.
+ expect((await readEffectiveRuntimeOpencodeConfig(config, WORKSPACE_ID)).approvals).toEqual({ mode: "full" });
+ // The injected engine config follows the row; the setting itself stays out of it.
+ const injected = JSON.parse(await buildOmniRushRuntimeConfig(config)) as { permission?: { bash?: Record<string, string> }; approvals?: unknown };
+ expect(injected.permission?.bash).toEqual({ "*": "allow" });
+ expect(injected.approvals).toBeUndefined();
+ // Every evaluate answer carries the mode, so the plugin needs no restart.
+ expect(await evaluate()).toEqual({ allowed: true, approvalMode: "full" });
+
+ // The environment wins over the setting; Settings shows the switch disabled.
+ process.env.OMNIRUSH_APPROVALS = "guarded";
+ expect(await readApprovals()).toEqual({ mode: "guarded", source: "environment", setting: "full" });
+ expect(await evaluate()).toEqual({ allowed: true, approvalMode: "guarded" });
+ const guarded = JSON.parse(await buildOmniRushRuntimeConfig(config)) as { permission?: { bash?: Record<string, string> } };
+ expect(guarded.permission?.bash?.["*"]).toBeUndefined();
+
+ expect(resolveApprovalMode({ approvals: { mode: "guarded" } }, { OMNIRUSH_APPROVALS: " FULL " })).toEqual({ mode: "full", source: "environment", setting: "guarded" });
+ expect(resolveApprovalMode({}, { OMNIRUSH_APPROVALS: "yes" })).toEqual({ mode: "guarded", source: "default", setting: null });
+ // Organizations that lock settings lock the switch as well.
+ expect(policyRequestActions("PUT", "/runtime-config/approvals")).toEqual(["settings"]);
+ } finally {
+ if (previousMode === undefined) delete process.env.OMNIRUSH_APPROVALS;
+ else process.env.OMNIRUSH_APPROVALS = previousMode;
+ await server.stop(true);
+ }
+ });
+ });
});
diff --git a/apps/server/src/runtime-opencode-config-store.ts b/apps/server/src/runtime-opencode-config-store.ts
index 90621d70..870f6afc 100644
--- a/apps/server/src/runtime-opencode-config-store.ts
+++ b/apps/server/src/runtime-opencode-config-store.ts
@@ -1,5 +1,6 @@
import { desktopConfigSchema, type DesktopConfig } from "@omnirush/types/den/desktop-policies-runtime";
import { existsSync } from "node:fs";
+import { parseApprovalMode, type ApprovalMode } from "./approval-mode.js";
import { importNodeSqlite, runtimeDbPath } from "./runtime-db.js";
import type { ServerConfig } from "./types.js";
import { createWorkspaceKvStore, isRecord } from "./workspace-kv-store.js";
@@ -8,6 +9,8 @@ export { runtimeDbPath, runtimeStorageDir } from "./runtime-db.js";
export type RuntimeOpencodeConfig = {
managedPolicy?: DesktopConfig;
+ /** User setting for the engine approval mode; global row only, OMNIRUSH_APPROVALS overrides it. */
+ approvals?: { mode: ApprovalMode };
default_agent?: string;
plugin?: string[];
disabled_providers?: string[];
@@ -38,9 +41,11 @@ function normalizeRuntimeOpencodeConfig(value: unknown): RuntimeOpencodeConfig {
const permission = isRecord(value.permission) ? value.permission : undefined;
const externalDirectory = permission && isRecord(permission.external_directory) ? permission.external_directory : undefined;
const provider = isRecord(value.provider) ? value.provider : undefined;
+ const approvalMode = isRecord(value.approvals) ? parseApprovalMode(value.approvals.mode) : null;
return {
...(defaultAgent ? { default_agent: defaultAgent } : {}),
...(value.managedPolicy !== undefined ? { managedPolicy: desktopConfigSchema.parse(value.managedPolicy) } : {}),
+ ...(approvalMode ? { approvals: { mode: approvalMode } } : {}),
...(plugin ? { plugin } : {}),
...(disabledProviders ? { disabled_providers: disabledProviders } : {}),
...(mcp ? { mcp } : {}),
@@ -259,6 +264,8 @@ export function mergeRuntimeOpencodeConfigLayers(
return normalizeRuntimeOpencodeConfig({
...(base.managedPolicy ? { managedPolicy: base.managedPolicy } : {}),
+ // The approval mode is engine-global like the managed policy.
+ ...(base.approvals ? { approvals: base.approvals } : {}),
...(base.default_agent || overlay.default_agent ? { default_agent: overlay.default_agent ?? base.default_agent } : {}),
...(plugin.length ? { plugin } : {}),
...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index dfe68ee9..90c56386 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,4 +1,5 @@
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
+import { parseApprovalMode, resolveApprovalMode } from "./approval-mode.js";
import { createTaskRecovery, setTaskRecovery } from "./task-recovery.js";
import { managedPolicyActionSchema } from "./managed-policy-rules.js";
import { readFile, realpath, writeFile, rm, stat } from "node:fs/promises";
@@ -3489,6 +3490,25 @@ function createRoutes(
return jsonResponse({ provider: runtimeProviderMap(runtime) });
});
+ // Engine approval mode: OMNIRUSH_APPROVALS in the server environment wins
+ // over the persisted setting (source "environment"), so Settings shows the
+ // switch disabled while the environment forces it.
+ addRoute(routes, "GET", "/runtime-config/approvals", "client", async () =>
+ jsonResponse(resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config))));
+
+ addRoute(routes, "PUT", "/runtime-config/approvals", "client", async (ctx) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
+ const body = await readJsonBody(ctx.request);
+ const mode = parseApprovalMode(body.mode);
+ if (!mode) throw new ApiError(400, "invalid_payload", 'mode must be "guarded" or "full"');
+ const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({ ...current, approvals: { mode } }));
+ // The injected engine config file must carry the new rules before the
+ // client's engine reload re-reads it.
+ await writeOmniRushRuntimeConfigFile(config);
+ return jsonResponse({ ok: true, changed: result.changed, ...resolveApprovalMode(result.config) });
+ });
+
addRoute(routes, "PUT", "/den-session", "host-token", async (ctx) => {
ensureWritable(config);
const session = parseCloudProviderDenSession(await readJsonBody(ctx.request));
@@ -3563,7 +3583,9 @@ function createRoutes(
const action = managedPolicyActionSchema.safeParse(body.action);
if (!action.success || !isRecord(body.input)) throw new ApiError(400, "invalid_payload", "A supported policy action and input are required");
await managedDesktopPolicy(config).assert(action.data, body.input);
- return jsonResponse({ allowed: true });
+ // The plugin applies the git workflow rules (destructive marker, commit
+ // identity refusal) only in guarded mode.
+ return jsonResponse({ allowed: true, approvalMode: resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config)).mode });
});
addRoute(routes, "GET", "/cloud-provider-sync/status", "client", async () => {
diff --git a/docs/approvals.md b/docs/approvals.md
new file mode 100644
index 00000000..a8a3569f
--- /dev/null
+++ b/docs/approvals.md
@@ -0,0 +1,88 @@
+# Approval modes
+
+The engine asks before some tool calls. The omnirush.ai desktop app has two
+approval modes:
+
+| Mode | What asks |
+| --- | --- |
+| `guarded` (default) | The git and pull-request rules from [git-workflows.md](git-workflows.md): write commands ask once per session per command family, destructive commands always ask. Everything else follows the engine's own defaults (for example editing files outside authorized folders). |
+| `full` | Nothing asks. The injected engine config sets `permission.bash` to a single `"*": "allow"` rule (no git ask rules, no `OMNIRUSH_DESTRUCTIVE` marker rule), `permission.read` to a single `"*": "allow"` rule (the engine asks before reading `.env` files by default; the later catch-all wins) and `edit`, `webfetch`, `websearch`, `doom_loop` and `external_directory` to `allow`. |
+
+Organization rules from Den (`commands: deny`, `blockedCommands`, approved
+browser origins) are still appended after those rules in both modes. The
+engine keeps the last matching rule, so an organization deny always wins;
+only the "ask" rules are dropped in full mode.
+
+## Switching in the app
+
+Two controls, one setting: the "Full permissions" switch beside the model
+selector in the chat composer (the new-task composer and the session
+composer) and Settings > General > Approvals > "Full permissions". They share
+the loaded mode, so a change in either shows in the other at once. Toggling
+either:
+
+1. persists the setting in the global runtime config row
+ (`approvals.mode`, `PUT /runtime-config/approvals`);
+2. rewrites the injected engine config file
+ (`~/.config/omnirush/runtime-opencode-config.json`);
+3. triggers a manual engine reload, the same call Settings "Reload" makes, so
+ the rules apply within seconds. The status reads "Full permissions on.
+ Engine reloaded.", "Guarded mode. Engine reloaded." or the error to act
+ on: Settings shows it under the switch, the composer shows it as a toast.
+ Both controls stay disabled until the reload finishes.
+
+Both controls reflect the current mode on load. While full mode is on the
+composer switch is filled in the accent colour, so it is obvious that nothing
+will ask for approval. While `OMNIRUSH_APPROVALS` forces the mode both are
+disabled: Settings shows "Set by environment", the composer says so in a
+tooltip. When the organization policy disables changing app settings the
+composer switch is disabled as well and its tooltip says why.
+
+## Forcing the mode from the environment
+
+`OMNIRUSH_APPROVALS=full` or `OMNIRUSH_APPROVALS=guarded` in the environment
+of the server process wins over the persisted setting. The value is
+case-insensitive; anything else is ignored and the setting (or the default)
+applies.
+
+- Desktop app: the embedded server runs inside the Electron process and reads
+ the app's environment, so launch the app from a shell with the variable
+ set. On macOS a Finder or Dock launch has no shell environment; start the
+ binary directly:
+
+ ```sh
+ OMNIRUSH_APPROVALS=full "/Applications/OmniRush.ai.app/Contents/MacOS/OmniRush.ai"
+ ```
+
+ On Linux run the AppImage or installed binary the same way; on Windows set
+ the variable in the shell that starts the executable.
+- Development: `OMNIRUSH_APPROVALS=full pnpm dev`, and
+ `OMNIRUSH_APPROVALS=full pnpm world up dev-headless --detach` for the
+ headless web world.
+- Standalone server: set the variable for the `omnirush-server` process.
+
+The Settings > Environment tab cannot set it: `OMNIRUSH_*` keys in the user
+environment file are reserved and dropped.
+
+## How the mode reaches the engine
+
+- `apps/server/src/approval-mode.ts` resolves the mode: environment, then
+ setting, then `guarded`.
+- `legacyExecutionPermissions` (`apps/server/src/managed-policy-rules.ts`)
+ renders the permission block for that mode into the injected engine config
+ (`apps/server/src/omnirush-runtime-config.ts`). The engine re-reads the file
+ on reload.
+- The managed-policy engine plugin does not read the environment. Every
+ `POST /managed-policy/evaluate` answer carries `approvalMode`, so the plugin
+ applies the mode the server resolved for that very tool call. In full mode
+ it skips the destructive-marker rewrite and the commit-identity refusal; it
+ still sets the repository-local identity from the connected omnirush.ai
+ account when the repository has none, and says so in the tool output.
+
+## API
+
+| Action | Request |
+| --- | --- |
+| Read the mode | `GET /runtime-config/approvals` -> `{ mode, source, setting }` (`source`: `environment`, `settings` or `default`) |
+| Set the mode | `PUT /runtime-config/approvals` `{ mode: "guarded" \| "full" }` (client token, collaborator scope; refused when the organization disables changing settings) |
+| Engine plugin evaluation | `POST /managed-policy/evaluate` -> `{ allowed: true, approvalMode }` |
diff --git a/docs/git-workflows.md b/docs/git-workflows.md
index 17c646d4..87a02fff 100644
--- a/docs/git-workflows.md
+++ b/docs/git-workflows.md
@@ -112,6 +112,27 @@ Server side this is the `git_identity` action of `/managed-policy/evaluate`
profile through the account store; a standalone server with
`OMNIRUSH_GATEWAY_URL` / `OMNIRUSH_ACCESS_TOKEN` reads `/device/me` directly.
+## Full permissions mode
+
+The rules above are the `guarded` approval mode, the default. Settings >
+General > Approvals > "Full permissions" switches the engine to `full` mode:
+nothing asks. The injected `permission.bash` block becomes a single
+`"*": "allow"` rule (no git ask rules, no `OMNIRUSH_DESTRUCTIVE` marker rule),
+`permission.read` becomes a single `"*": "allow"` rule (so `.env` files, which
+the engine asks about by default, are read without a prompt) and `edit`,
+`webfetch`, `websearch`, `doom_loop` and `external_directory` are set to
+`allow`. Organization denies from Den are still appended last and win.
+
+In full mode the managed-policy plugin does not write the destructive marker
+and never refuses a commit for a missing identity; it still sets the
+repository-local identity from the connected omnirush.ai account when the
+repository has none, and reports it in the tool output.
+
+`OMNIRUSH_APPROVALS=full|guarded` in the environment of the app or server
+process forces the mode and disables the switch. See
+[approvals.md](approvals.md) for how to launch with it and how the mode reaches
+the engine.
+
## Troubleshooting gh
- `gh: command not found` in the agent: install GitHub CLI (`brew install gh`