Fix/permission dialog id bug (#71)

* Fix permission dialog using wrong ID and add typed permission labels

- Fix critical bug: pass permission.id instead of permission.permission when responding
- Replace hardcoded switch statement with PERMISSION_LABELS derived from OpenCode types
- Add all permission types from PermissionConfig schema
* Add per-repo reset permissions feature
- Add POST /api/repos/:id/reset-permissions endpoint that disposes OpenCode instance
- Add resetRepoPermissions API function in frontend
- Add Reset Permissions button in RepoDetail header and mobile dropdown
- Add confirmation dialog explaining the action clears Allow Always permissions

* Improve OpenCode config error handling and UI responsiveness
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-17 13:26:42 -05:00
1 parent 2bd2b024b8
commit d035e196bd
9 files changed
+206 -53

No files matched your search

+30
View File
@@ -9,6 +9,7 @@ import * as archiveService from '../services/archive'
import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { opencodeServerManager } from '../services/opencode-single-server'
import { proxyToOpenCodeWithDirectory } from '../services/proxy'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-manager/shared/config/env'
@@ -359,6 +360,35 @@ app.get('/', async (c) => {
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.post('/:id/reset-permissions', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const response = await proxyToOpenCodeWithDirectory(
'/instance/dispose',
'POST',
repo.fullPath
)
if (!response.ok) {
const errorText = await response.text()
logger.error(`Failed to reset permissions for repo ${id}:`, errorText)
return c.json({ error: 'Failed to reset permissions' }, 500)
}
logger.info(`Reset permissions for repo ${id} (${repo.fullPath})`)
return c.json({ success: true })
} catch (error: unknown) {
logger.error('Failed to reset permissions:', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
return app
}
+13 -4
View File
@@ -153,7 +153,10 @@ export function createSettingsRoutes(db: Database) {
await writeFileContent(configPath, config.rawContent)
logger.info(`Wrote default config to: ${configPath}`)
await patchOpenCodeConfig(config.content)
const patchResult = await patchOpenCodeConfig(config.content)
if (!patchResult.success) {
return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500)
}
}
return c.json(config)
@@ -186,7 +189,10 @@ export function createSettingsRoutes(db: Database) {
await writeFileContent(configPath, config.rawContent)
logger.info(`Wrote default config to: ${configPath}`)
await patchOpenCodeConfig(config.content)
const patchResult = await patchOpenCodeConfig(config.content)
if (!patchResult.success) {
return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500)
}
}
return c.json(config)
@@ -232,7 +238,10 @@ export function createSettingsRoutes(db: Database) {
await writeFileContent(configPath, config.rawContent)
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
await patchOpenCodeConfig(config.content)
const patchResult = await patchOpenCodeConfig(config.content)
if (!patchResult.success) {
return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500)
}
return c.json(config)
} catch (error) {
@@ -276,7 +285,7 @@ export function createSettingsRoutes(db: Database) {
app.post('/opencode-reload', async (c) => {
try {
logger.info('OpenCode configuration reload requested')
await fetch(`http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}/config/`, {
await fetch(`http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}/config`, {
method: 'GET'
})
await opencodeServerManager.reloadConfig()
@@ -210,7 +210,7 @@ class OpenCodeServerManager {
async reloadConfig(): Promise<void> {
logger.info('Reloading OpenCode configuration (via API)')
try {
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/config/`, {
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/config`, {
method: 'GET'
})
@@ -220,7 +220,7 @@ class OpenCodeServerManager {
const currentConfig = await response.json()
logger.info('Triggering OpenCode config reload via PATCH')
const patchResponse = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/config/`, {
const patchResponse = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/config`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(currentConfig)
+33 -5
View File
@@ -43,7 +43,12 @@ export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
}
}
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<boolean> {
export type PatchConfigResult = {
success: boolean
error?: string
}
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<PatchConfigResult> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
method: 'PATCH',
@@ -53,14 +58,37 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
if (response.ok) {
logger.info('Patched OpenCode config via API')
return true
return { success: true }
}
logger.error(`Failed to patch OpenCode config: ${response.status} ${response.statusText}`)
return false
let errorMessage = `${response.status} ${response.statusText}`
try {
const errorBody = await response.json() as Record<string, unknown>
if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) {
const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> }
if (data.issues) {
const issues = data.issues
.map((issue) =>
issue.path ? `${issue.path.join('.')}: ${issue.message}` : issue.message
)
.join('; ')
errorMessage = `Invalid config: ${issues}`
}
} else if (typeof errorBody?.error === 'string') {
errorMessage = errorBody.error
} else if (typeof errorBody?.message === 'string') {
errorMessage = errorBody.message
}
} catch {
// Use default error message if we can't parse response body
}
logger.error(`Failed to patch OpenCode config: ${errorMessage}`)
return { success: false, error: errorMessage }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
logger.error('Failed to patch OpenCode config:', error)
return false
return { success: false, error: errorMessage }
}
}
+11
View File
@@ -201,3 +201,14 @@ export async function updateRepoOrder(order: number[]): Promise<void> {
throw new Error(error.error || 'Failed to update repo order')
}
}
export async function resetRepoPermissions(id: number): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/repos/${id}/reset-permissions`, {
method: 'POST',
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to reset permissions')
}
}
@@ -9,9 +9,32 @@ import {
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import type { PermissionRequest, PermissionResponse } from '@/api/types'
import type { components } from '@/api/opencode-types'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
type PermissionConfig = components['schemas']['PermissionConfig']
type KnownPermissionType = keyof Exclude<PermissionConfig, string> & string
const PERMISSION_LABELS: Record<KnownPermissionType, string> = {
read: 'Read File',
edit: 'Edit File',
glob: 'Search Files',
grep: 'Search Content',
list: 'List Directory',
bash: 'Run Command',
task: 'Run Task',
external_directory: 'External Access',
todowrite: 'Write Todo',
todoread: 'Read Todo',
question: 'Ask Question',
webfetch: 'Fetch URL',
websearch: 'Web Search',
codesearch: 'Code Search',
lsp: 'LSP Action',
doom_loop: 'Repeated Action',
}
interface PermissionRequestDialogProps {
permission: PermissionRequest | null
pendingCount: number
@@ -24,22 +47,10 @@ interface PermissionRequestDialogProps {
}
function getPermissionTypeLabel(type: string): string {
switch (type) {
case 'bash':
return 'Run Command'
case 'edit':
return 'Edit File'
case 'write':
return 'Write File'
case 'webfetch':
return 'Fetch URL'
case 'external_directory':
return 'External Access'
case 'doom_loop':
return 'Repeated Action'
default:
return type.charAt(0).toUpperCase() + type.slice(1)
if (type in PERMISSION_LABELS) {
return PERMISSION_LABELS[type as KnownPermissionType]
}
return type.charAt(0).toUpperCase() + type.slice(1)
}
function getPermissionDetails(permission: PermissionRequest): { primary: string; secondary?: string } {
@@ -125,9 +136,8 @@ export function PermissionRequestDialog({
setIsLoading(true)
setLoadingAction(response)
try {
await onRespond(permission.permission, permission.sessionID, response)
} catch (error) {
console.error('Failed to respond to permission:', error)
await onRespond(permission.id, permission.sessionID, response)
} catch {
showToast.error('Failed to respond to permission. Please try again.')
} finally {
setIsLoading(false)
@@ -61,7 +61,7 @@ export function OpenCodeConfigEditor({
setEditErrorLine(line)
setEditError('Invalid JSON/JSONC format')
} else {
setEditError(error instanceof Error ? error.message : 'Failed to update config')
setEditError('Failed to save. Please check your changes and try again.')
}
}
}
@@ -70,14 +70,14 @@ export function OpenCodeConfigEditor({
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent mobileFullscreen className="h-[90vh] max-w-6xl gap-0 flex flex-col p-0 sm:p-6">
<DialogContent mobileFullscreen className="gap-0 flex flex-col p-0 md:p-6 w-full min-w-0 sm:max-w-4xl">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
<DialogTitle className="text-lg sm:text-xl font-semibold">
{`Edit Config: ${config.name}`}
</DialogTitle>
</DialogHeader>
<div className="flex-1 p-0 sm:p-4 overflow-hidden relative">
<div className="flex-1 p-0 sm:p-4 overflow-hidden relative w-full">
<Textarea
id="edit-config-content"
ref={editTextareaRef}
@@ -115,12 +115,16 @@ export function OpenCodeConfigManager() {
},
})
const getApiErrorMessage = (error: unknown, fallback: string): string => {
if (error && typeof error === 'object' && 'response' in error) {
const response = (error as { response?: { data?: { details?: string; error?: string } } }).response
return response?.data?.details || response?.data?.error || fallback
}
return fallback
}
const getRestartErrorMessage = (error: unknown): string => {
return error && typeof error === 'object' && 'response' in error
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|| 'Failed to restart OpenCode server')
: 'Failed to restart OpenCode server'
return getApiErrorMessage(error, 'Failed to restart OpenCode server')
}
const rollbackMutation = useMutation({
@@ -184,7 +188,7 @@ export function OpenCodeConfigManager() {
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to update config:', error)
showToast.error('Failed to update config', { id: 'update-restart' })
showToast.error(getApiErrorMessage(error, 'Failed to update config'), { id: 'update-restart' })
} finally {
setIsUpdating(false)
}
@@ -238,7 +242,7 @@ export function OpenCodeConfigManager() {
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to create config:', error)
showToast.error('Failed to create configuration', { id: 'create-config' })
showToast.error(getApiErrorMessage(error, 'Failed to create configuration'), { id: 'create-config' })
throw error
} finally {
setIsUpdating(false)
@@ -272,12 +276,7 @@ export function OpenCodeConfigManager() {
showToast.success('Default config updated and server reloaded', { id: 'set-default' })
} catch (error) {
console.error('Failed to set default config:', error)
const errorMessage = error && typeof error === 'object' && 'response' in error
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|| 'Failed to set default config')
: 'Failed to set default config'
showToast.error(errorMessage, { id: 'set-default' })
showToast.error(getApiErrorMessage(error, 'Failed to set default config'), { id: 'set-default' })
} finally {
setIsUpdating(false)
}
@@ -504,11 +503,8 @@ export function OpenCodeConfigManager() {
showToast.success(successMsg, { id: 'edit-config' })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
if (error instanceof Error && error.message.includes('restart')) {
showToast.error(getRestartErrorMessage(error), { id: 'edit-config' })
} else {
showToast.error('Failed to save configuration', { id: 'edit-config' })
}
showToast.error(getApiErrorMessage(error, 'Failed to save configuration'), { id: 'edit-config' })
throw error
}
}}
isUpdating={isUpdating}
+72 -3
View File
@@ -1,7 +1,7 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getRepo } from "@/api/repos";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { getRepo, resetRepoPermissions } from "@/api/repos";
import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Header } from "@/components/ui/header";
@@ -15,8 +15,17 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Plug, FolderOpen, Plus, GitBranch, Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Plug, FolderOpen, Plus, GitBranch, Loader2, ShieldOff } from "lucide-react";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { showToast } from "@/lib/toast";
export function RepoDetail() {
const { id } = useParams<{ id: string }>();
@@ -26,6 +35,7 @@ export function RepoDetail() {
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
const [switchConfigOpen, setSwitchConfigOpen] = useState(false);
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false);
const pageRef = useRef<HTMLDivElement>(null);
const handleSwipeBack = useCallback(() => {
@@ -63,6 +73,18 @@ export function RepoDetail() {
const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory);
const resetPermissionsMutation = useMutation({
mutationFn: () => resetRepoPermissions(repoId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, repoDirectory] });
showToast.success("Permissions reset successfully");
setResetPermissionsOpen(false);
},
onError: () => {
showToast.error("Failed to reset permissions");
},
});
const handleCreateSession = async (options?: {
agentSlug?: string;
promptSlug?: string;
@@ -163,6 +185,15 @@ export function RepoDetail() {
<FolderOpen className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Files</span>
</Button>
<Button
variant="outline"
onClick={() => setResetPermissionsOpen(true)}
size="sm"
className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<ShieldOff className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Reset Permissions</span>
</Button>
<Header.MobileDropdown>
{!isWorktree && currentBranch && (
<>
@@ -185,6 +216,9 @@ export function RepoDetail() {
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
</DropdownMenuItem>
</Header.MobileDropdown>
<Button
onClick={() => handleCreateSession()}
@@ -236,6 +270,41 @@ export function RepoDetail() {
}}
/>
)}
<Dialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Permissions</DialogTitle>
<DialogDescription>
This will clear all "Allow Always" permissions for this repository.
You will be prompted again for permission when opencode needs to perform actions like running commands or editing files.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setResetPermissionsOpen(false)}
disabled={resetPermissionsMutation.isPending}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={() => resetPermissionsMutation.mutate()}
disabled={resetPermissionsMutation.isPending}
>
{resetPermissionsMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Resetting...
</>
) : (
"Reset Permissions"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}