-
Notifications
You must be signed in to change notification settings - Fork 109
feat(settings): upload and replace the OpenCode config directory #340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
chriswritescode-dev
wants to merge
1
commit into
main
Choose a base branch
from
feat/config-directory-upload
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| import path from 'path' | ||
| import { promises as fs } from 'fs' | ||
| import { randomUUID } from 'crypto' | ||
| import type { Database } from 'bun:sqlite' | ||
| import { FILE_LIMITS, getConfigPath } from '@opencode-manager/shared/config/env' | ||
| import { | ||
| OPENCODE_CANONICAL_CONFIG_FILENAME, | ||
| getCommonUploadRootDirectory, | ||
| isExcludedOpenCodeConfigUploadPath, | ||
| isOpenCodeConfigUploadPath, | ||
| } from '@opencode-manager/shared/utils' | ||
| import { fileExists, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations' | ||
| import { mkdirSafe } from '../utils/fs-safe' | ||
| import { SettingsService } from './settings' | ||
| import { logger } from '../utils/logger' | ||
|
|
||
| export interface UploadedConfigDirectoryFile { | ||
| relativePath: string | ||
| content: Buffer | ||
| } | ||
|
|
||
| export interface ReplaceOpenCodeConfigDirectoryResult { | ||
| configDirectory: string | ||
| configSourceFilename: string | ||
| filesInstalled: string[] | ||
| skippedPaths: string[] | ||
| preservedEntries: string[] | ||
| executablesRestored: string[] | ||
| } | ||
|
|
||
| const MAX_CONFIG_DIRECTORY_FILES = 5000 | ||
| const PRESERVED_ENTRIES = ['node_modules'] | ||
| const STAGING_PREFIX = '.opencode-config-staging-' | ||
| const BACKUP_PREFIX = '.opencode-config-backup-' | ||
| const SHEBANG_PREFIX = '#!' | ||
|
|
||
| export async function replaceOpenCodeConfigDirectory( | ||
| db: Database, | ||
| files: UploadedConfigDirectoryFile[], | ||
| userId = 'default', | ||
| ): Promise<ReplaceOpenCodeConfigDirectoryResult> { | ||
| const normalizedFiles = files.map((file) => ({ | ||
| relativePath: normalizeUploadRelativePath(file.relativePath, { collapseEmptySegments: true }), | ||
| content: file.content, | ||
| })) | ||
|
|
||
| const commonRoot = getCommonUploadRootDirectory(normalizedFiles.map((file) => file.relativePath)) | ||
| const strippedFiles = normalizedFiles | ||
| .map((file) => ({ | ||
| relativePath: commonRoot ? file.relativePath.slice(commonRoot.length + 1) : file.relativePath, | ||
| content: file.content, | ||
| })) | ||
| .filter((file) => file.relativePath !== '') | ||
|
|
||
| const kept: UploadedConfigDirectoryFile[] = [] | ||
| const skippedPaths: string[] = [] | ||
| for (const file of strippedFiles) { | ||
| if (isExcludedOpenCodeConfigUploadPath(file.relativePath)) { | ||
| skippedPaths.push(file.relativePath) | ||
| } else { | ||
| kept.push(file) | ||
| } | ||
| } | ||
|
|
||
| if (kept.length === 0) { | ||
| throw new Error('No files were provided for the OpenCode config directory replace') | ||
| } | ||
| if (kept.length > MAX_CONFIG_DIRECTORY_FILES) { | ||
| throw new Error('Uploaded config directory contains too many files (max 5000)') | ||
| } | ||
| const totalBytes = kept.reduce((sum, file) => sum + file.content.length, 0) | ||
| if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) { | ||
| throw new Error('Uploaded config directory files exceed maximum upload size') | ||
| } | ||
|
|
||
| const configCandidates = kept | ||
| .map((file, index) => ({ file, index })) | ||
| .filter(({ file }) => isOpenCodeConfigUploadPath(file.relativePath)) | ||
| const jsonCandidate = configCandidates.find(({ file }) => file.relativePath === 'opencode.json') | ||
| const jsoncCandidate = configCandidates.find(({ file }) => file.relativePath === 'opencode.jsonc') | ||
| const chosenConfig = jsonCandidate ?? jsoncCandidate | ||
| if (!chosenConfig) { | ||
| throw new Error('Uploaded directory must contain opencode.json or opencode.jsonc at its root') | ||
| } | ||
|
|
||
| const configSourceFilename = chosenConfig.file.relativePath | ||
| const droppedJsoncFile = jsonCandidate && jsoncCandidate ? jsoncCandidate.file : undefined | ||
| if (droppedJsoncFile) { | ||
| skippedPaths.push(droppedJsoncFile.relativePath) | ||
| } | ||
|
|
||
| new SettingsService(db).upsertDefaultOpenCodeConfig(chosenConfig.file.content.toString('utf8'), userId) | ||
|
|
||
| const filesToWrite = kept | ||
| .filter((file) => file !== droppedJsoncFile) | ||
| .map((file) => file.relativePath === configSourceFilename | ||
| ? { relativePath: OPENCODE_CANONICAL_CONFIG_FILENAME, content: file.content } | ||
| : file) | ||
|
|
||
| const configDirectory = getConfigPath() | ||
| const parent = path.dirname(configDirectory) | ||
|
|
||
| const executablesRestored: string[] = [] | ||
| const preservedEntries: string[] = [] | ||
| let staged: string | null = null | ||
| let backupPath: string | null = null | ||
|
|
||
| try { | ||
| await mkdirSafe(parent) | ||
| staged = await fs.mkdtemp(path.join(parent, STAGING_PREFIX)) | ||
|
|
||
| for (const file of filesToWrite) { | ||
| const target = resolveWithinDirectory(staged, file.relativePath, 'config directory') | ||
| await mkdirSafe(path.dirname(target)) | ||
| await fs.writeFile(target, file.content) | ||
| if (file.content.subarray(0, SHEBANG_PREFIX.length).toString() === SHEBANG_PREFIX) { | ||
| await fs.chmod(target, 0o755) | ||
| executablesRestored.push(file.relativePath) | ||
| } | ||
| } | ||
|
|
||
| if (await fileExists(configDirectory)) { | ||
| backupPath = path.join(parent, BACKUP_PREFIX + randomUUID()) | ||
| await fs.rename(configDirectory, backupPath) | ||
| await fs.rename(staged, configDirectory) | ||
| staged = null | ||
|
|
||
| for (const name of PRESERVED_ENTRIES) { | ||
| const backupEntryPath = path.join(backupPath, name) | ||
| const targetEntryPath = path.join(configDirectory, name) | ||
| if (await fileExists(backupEntryPath) && !(await fileExists(targetEntryPath))) { | ||
| await fs.rename(backupEntryPath, targetEntryPath) | ||
| preservedEntries.push(name) | ||
| } | ||
| } | ||
| } else { | ||
| await fs.rename(staged, configDirectory) | ||
| staged = null | ||
| } | ||
|
|
||
| if (backupPath) { | ||
| await fs.rm(backupPath, { recursive: true, force: true }) | ||
| } | ||
|
|
||
| logger.info(`Replaced OpenCode config directory at ${configDirectory}`) | ||
|
|
||
| return { | ||
| configDirectory, | ||
| configSourceFilename, | ||
| filesInstalled: filesToWrite.map((file) => file.relativePath), | ||
| skippedPaths, | ||
| preservedEntries, | ||
| executablesRestored, | ||
| } | ||
| } catch (error) { | ||
| if (staged) { | ||
| await fs.rm(staged, { recursive: true, force: true }) | ||
| } | ||
| if (backupPath) { | ||
| if (await fileExists(configDirectory)) { | ||
| await fs.rm(backupPath, { recursive: true, force: true }) | ||
| } else { | ||
| await fs.rename(backupPath, configDirectory) | ||
| } | ||
| } | ||
| throw error | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Persist the default config after the directory swap succeeds, or restore it on failure.
Line 92 writes the uploaded config into the database before any filesystem work starts. If staging,
fs.rename, orchmodfails at lines 108-139, the catch block at lines 155-167 restores the previous directory from the backup but leaves the database default config pointing at the uploaded content. The route then returns 500, so the caller assumes nothing changed, while the persisted default config and the on-diskopencode.jsondisagree. A later restart or config read then uses the wrong content.Move the upsert after the swap, or capture the previous default config and restore it in the catch block.
🛠️ Proposed ordering fix
if (backupPath) { await fs.rm(backupPath, { recursive: true, force: true }) } + new SettingsService(db).upsertDefaultOpenCodeConfig(chosenConfig.file.content.toString('utf8'), userId) + logger.info(`Replaced OpenCode config directory at ${configDirectory}`)Note: validation errors raised by
upsertDefaultOpenCodeConfigwould then surface after the swap. If pre-swap validation must stay, keep a validation-only call first and persist only after the swap.🤖 Prompt for AI Agents