Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
import AppSelect from '../../components/forms/Select.js';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
import type {
CodexProfileConfig,
CodexProfileDeleteResponse,
CodexProfileDetailResponse,
CodexProfileListResponse,
CodexProfileMutationResponse,
CodexProfileResponse,
CreateCodexProfileRequest,
UpdateCodexProfileRequest
} from '@opencreator/protocol';
import {
FileSliders,
LoaderCircle,
Pencil,
Plus,
Save,
Trash2,
X
} from 'lucide-react';
import { useEffect, useState, type FormEvent } from 'react';
import { useConfirmDialog } from '../../components/dialogs/ConfirmDialogProvider.js';
import { IssueList } from '../issues/IssuePresenter.js';
import { usePageIssueState } from '../issues/page-issue-state.js';
export type ProfileSettingsService = {
listProfiles(): Promise<CodexProfileListResponse>;
getProfile(name: string): Promise<CodexProfileDetailResponse>;
createProfile(input: CreateCodexProfileRequest): Promise<CodexProfileMutationResponse>;
updateProfile(name: string, input: UpdateCodexProfileRequest): Promise<CodexProfileMutationResponse>;
deleteProfile(name: string): Promise<CodexProfileDeleteResponse>;
};
type ProfileEditorState =
| { mode: 'create' }
| { mode: 'edit'; name: string; profile?: CodexProfileResponse; loading: boolean };
const knownKeys = new Set(['model', 'model_reasoning_effort', 'sandbox_mode']);
export function ProfileSettingsView(props: {
connected: boolean;
service: ProfileSettingsService | null;
data?: CodexProfileListResponse;
onDataChange?(data: CodexProfileListResponse): void;
confirmDelete?(profile: CodexProfileResponse): boolean;
}) {
const l = useLocalizedCopy();
const confirm = useConfirmDialog();
const [data, setData] = useState(props.data);
const [loading, setLoading] = useState(
props.data === undefined && props.connected && props.service !== null
);
const [validationError, setValidationError] = useState<string>();
const [editor, setEditor] = useState<ProfileEditorState>();
const [saving, setSaving] = useState(false);
const [busyName, setBusyName] = useState<string>();
const [reloadToken, setReloadToken] = useState(0);
const pageIssues = usePageIssueState('settings-profiles');
useEffect(() => {
setData(props.data);
}, [props.data]);
useEffect(() => {
if (props.data !== undefined || !props.connected || props.service === null) return;
let canceled = false;
setLoading(true);
props.service.listProfiles()
.then(response => {
if (!canceled) {
updateData(response);
pageIssues.resolveOperation('settings.profiles.load');
}
})
.catch(reason => {
if (!canceled) pageIssues.captureOperationFailure(
'settings.profiles.load',
reason,
l("无法加载 Profiles,请重试。", "Unable to load Profiles, please try again."),
{ retryable: true }
);
})
.finally(() => {
if (!canceled) setLoading(false);
});
return () => {
canceled = true;
};
}, [
pageIssues.captureOperationFailure,
pageIssues.resolveOperation,
props.connected,
props.data,
props.service,
reloadToken
]);
function updateData(next: CodexProfileListResponse) {
setData(next);
props.onDataChange?.(next);
}
function upsertProfile(profile: CodexProfileResponse) {
if (data === undefined) return;
updateData({
...data,
profiles: [...data.profiles.filter(item => item.name !== profile.name), profile]
.sort((left, right) => left.name.localeCompare(right.name))
});
}
async function openEdit(profile: CodexProfileResponse) {
if (props.service === null) return;
setEditor({ mode: 'edit', name: profile.name, loading: true });
setValidationError(undefined);
const operationId = `settings.profiles.detail:${profile.name}`;
try {
const detail = await props.service.getProfile(profile.name);
if (containsSensitiveConfig(detail.profile.config)) {
setEditor(undefined);
setValidationError(l("该 Profile 含敏感配置,请直接编辑本机配置文件", "This Profile contains sensitive configuration, please edit the local configuration file directly."));
return;
}
setEditor({ mode: 'edit', name: profile.name, profile: detail.profile, loading: false });
pageIssues.resolveOperation(operationId);
} catch (reason) {
setEditor(undefined);
pageIssues.captureOperationFailure(operationId, reason, l("无法加载 Profile 详情,请重试。", "Unable to load profile details, please try again."));
}
}
async function deleteProfile(profile: CodexProfileResponse) {
if (props.service === null) return;
const confirmed = props.confirmDelete?.(profile) ?? await confirm({
title: '删除 Profile',
description: `确认删除“${profile.name}”?删除后无法恢复。`,
confirmLabel: '删除',
destructive: true
});
if (!confirmed) return;
setBusyName(profile.name);
const operationId = `settings.profiles.delete:${profile.name}`;
try {
await props.service.deleteProfile(profile.name);
if (data !== undefined) {
updateData({ ...data, profiles: data.profiles.filter(item => item.name !== profile.name) });
}
pageIssues.resolveOperation(operationId);
} catch (reason) {
pageIssues.captureOperationFailure(operationId, reason, l("无法删除 Profile,请检查占用情况后重试。", "Unable to delete Profile, please check the occupancy and try again."));
} finally {
setBusyName(undefined);
}
}
const writable = props.connected
&& props.service !== null
&& data?.writable === true
&& data.baseConfigValid;
return (
<section className="settings-section settings-management" aria-labelledby="settings-profiles-title">
<header className="settings-management__header">
<div>
<h1 id="settings-profiles-title">Profiles</h1>
<p>{l("维护会话和计划任务可复用的 Codex 配置。", "Maintain reusable Codex configuration for sessions and scheduled tasks.")}</p>
</div>
<button
className="settings-primary-button"
type="button"
disabled={!writable}
onClick={() => setEditor({ mode: 'create' })}
>
<Plus size={16} />
{l("新建 Profile", "New Profile")}</button>
</header>
{!props.connected || props.service === null ? (
<p className="settings-notice">{l("本地服务连接后可以管理 Profile。", "Profiles can be managed after the local service is connected.")}</p>
) : null}
{data !== undefined && !data.writable ? (
<p className="settings-notice">{l("当前 CODEX_HOME 为只读,无法修改 Profile", "Currently CODEX_HOME is read-only and Profile cannot be modified.")}</p>
) : null}
{data !== undefined && !data.baseConfigValid ? (
<p className="settings-notice">{l("基础 config.toml 无效,请先修复配置", "The basic config.toml is invalid, please repair the configuration first")}</p>
) : null}
{data?.diagnostics.map(diagnostic => (
<p className="settings-inline-warning" key={diagnostic}>{diagnostic}</p>
))}
{validationError ? <p className="settings-error" role="alert">{validationError}</p> : null}
<IssueList
issues={pageIssues.issues}
actions={{ retryOperations: {
'settings.profiles.load': () => setReloadToken(value => value + 1)
} }}
onDismiss={pageIssues.dismissIssue}
/>
{editor ? (
<ProfileEditor
state={editor}
saving={saving}
onCancel={() => setEditor(undefined)}
onSubmit={async (name, config) => {
if (props.service === null) return;
setSaving(true);
setValidationError(undefined);
const operationId = editor.mode === 'create'
? 'settings.profiles.create'
: `settings.profiles.update:${editor.name}`;
try {
const response = editor.mode === 'create'
? await props.service.createProfile({ name, config })
: await props.service.updateProfile(editor.name, { config });
upsertProfile(response.profile);
setEditor(undefined);
pageIssues.resolveOperation(operationId);
} catch (reason) {
pageIssues.captureOperationFailure(operationId, reason, l("无法保存 Profile,请检查配置后重试。", "Unable to save profile, please check the configuration and try again."));
} finally {
setSaving(false);
}
}}
/>
) : null}
{loading ? (
<div className="settings-state" role="status">
<LoaderCircle size={20} className="settings-spin" />
{l("正在加载 Profiles", "Loading Profiles")}</div>
) : data !== undefined && data.profiles.length === 0 ? (
<div className="settings-state">
<FileSliders size={22} />
{l("暂无 Profile", "No profile yet")}</div>
) : (
<ul className="settings-item-list" aria-label={l("Profile 列表", "Profile list")}>
{data?.profiles.map(profile => {
const busy = busyName === profile.name;
return (
<li className="settings-item" key={profile.name}>
<div className="settings-item__main">
<div className="settings-item__title">
<FileSliders size={16} />
<h2>{profile.name}</h2>
<span data-status={profile.status}>{profile.status === 'valid' ? l("有效", "Valid") : l("无效", "Invalid")}</span>
</div>
<p>{profileSummary(profile)}</p>
{profile.diagnostics.map(diagnostic => (
<p className="settings-inline-warning" key={diagnostic}>{diagnostic}</p>
))}
</div>
<div className="settings-item__actions">
<button
type="button"
aria-label={l(`编辑 ${profile.name}`, `Edit ${profile.name}`)}
title={l("编辑", "Edit")}
disabled={!writable || busy}
onClick={() => void openEdit(profile)}
>
<Pencil size={16} />
</button>
<button
type="button"
aria-label={l(`删除 ${profile.name}`, `Delete ${profile.name}`)}
title={l("删除", "Delete")}
disabled={!writable || busy}
onClick={() => void deleteProfile(profile)}
>
{busy ? <LoaderCircle size={16} className="settings-spin" /> : <Trash2 size={16} />}
</button>
</div>
</li>
);
})}
</ul>
)}
</section>
);
}
function ProfileEditor(props: {
state: ProfileEditorState;
saving: boolean;
onCancel(): void;
onSubmit(name: string, config: CodexProfileConfig): Promise<void>;
}) {
const l = useLocalizedCopy();
const profile = props.state.mode === 'edit' ? props.state.profile : undefined;
const [name, setName] = useState(profile?.name ?? '');
const [model, setModel] = useState(readString(profile?.config.model));
const [reasoning, setReasoning] = useState(readString(profile?.config.model_reasoning_effort));
const [sandbox, setSandbox] = useState(readString(profile?.config.sandbox_mode));
const [advanced, setAdvanced] = useState(() => JSON.stringify(advancedConfig(profile?.config), null, 2));
const [formError, setFormError] = useState<string>();
useEffect(() => {
setName(profile?.name ?? '');
setModel(readString(profile?.config.model));
setReasoning(readString(profile?.config.model_reasoning_effort));
setSandbox(readString(profile?.config.sandbox_mode));
setAdvanced(JSON.stringify(advancedConfig(profile?.config), null, 2));
}, [profile]);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (name.trim().length === 0) return setFormError('请输入 Profile 名称');
if (!/^[A-Za-z0-9_.-]+$/.test(name.trim())) {
return setFormError('Profile 名称只能包含字母、数字、下划线、点和短横线');
}
const parsed = parseAdvancedConfig(advanced);
if (!parsed.ok) return setFormError(parsed.message);
const config: CodexProfileConfig = { ...parsed.config };
if (model.trim()) config.model = model.trim();
if (reasoning) config.model_reasoning_effort = reasoning;
if (sandbox) config.sandbox_mode = sandbox;
setFormError(undefined);
await props.onSubmit(name.trim(), config);
}
if (props.state.mode === 'edit' && props.state.loading) {
return (
<div className="settings-editor settings-state" role="status">
<LoaderCircle size={20} className="settings-spin" />
{l("正在加载 Profile 详情", "Loading Profile details")}</div>
);
}
return (
<form className="settings-editor" aria-label={props.state.mode === 'create' ? l("新建 Profile", "New Profile") : l(`编辑 ${name}`, `Edit ${name}`)} onSubmit={submit}>
<header>
<div>
<p>{props.state.mode === 'create' ? l("新建配置", "New configuration") : l("编辑配置", "Edit configuration")}</p>
<h2>{props.state.mode === 'create' ? l("配置 Codex Profile", "Configure Codex Profile") : name}</h2>
</div>
<button type="button" aria-label={l("关闭 Profile 编辑器", "Close the Profile editor")} title={l("关闭", "Close")} onClick={props.onCancel}>
<X size={17} />
</button>
</header>
{formError ? <p className="settings-error" role="alert">{formError}</p> : null}
<div className="settings-form-grid">
<label>
<span>{l("Profile 名称", "Profile name")}</span>
<input
aria-label={l("Profile 名称", "Profile name")}
disabled={props.state.mode === 'edit'}
value={name}
onChange={event => setName(event.target.value)}
/>
</label>
<label>
<span>{l("模型", "Model")}</span>
<input
aria-label={l("模型", "Model")}
placeholder={l("使用 Codex 默认模型", "Use Codex default model")}
value={model}
onChange={event => setModel(event.target.value)}
/>
</label>
<label>
<span>{l("推理级别", "reasoning level")}</span>
<AppSelect aria-label={l("推理级别", "reasoning level")} value={reasoning} onChange={event => setReasoning(event.target.value)}>
<option value="">{l("使用默认值", "Use default value")}</option>
<option value="default">{l("默认", "Default")}</option>
<option value="low">{l("低", "Low")}</option>
<option value="medium">{l("中", "Medium")}</option>
<option value="high">{l("高", "High")}</option>
<option value="xhigh">{l("超高", "Extra high")}</option>
</AppSelect>
</label>
<label>
<span>Sandbox</span>
<AppSelect aria-label="Sandbox" value={sandbox} onChange={event => setSandbox(event.target.value)}>
<option value="">{l("使用默认值", "Use default value")}</option>
<option value="read-only">{l("只读", "Read only")}</option>
<option value="workspace-write">{l("工作区可写", "Workspace write access")}</option>
<option value="danger-full-access">{l("完全访问", "Full access")}</option>
</AppSelect>
</label>
<label className="settings-form-wide">
<span>{l("高级配置 JSON", "Advanced configuration JSON")}</span>
<textarea
aria-label={l("高级配置 JSON", "Advanced configuration JSON")}
rows={7}
spellCheck={false}
value={advanced}
onChange={event => setAdvanced(event.target.value)}
/>
<small>{l("仅支持字符串、有限数字、布尔值和同类型数组。", "Only strings, finite numbers, Boolean values, and arrays of the same type are supported.")}</small>
</label>
</div>
<footer>
<button className="settings-secondary-button" type="button" onClick={props.onCancel}>{l("取消", "Cancel")}</button>
<button className="settings-primary-button" type="submit" disabled={props.saving}>
{props.saving ? <LoaderCircle size={16} className="settings-spin" /> : <Save size={16} />}
{l('保存 Profile', 'Save Profile')}
</button>
</footer>
</form>
);
}
function advancedConfig(config: CodexProfileConfig | undefined): CodexProfileConfig {
if (config === undefined) return {};
return Object.fromEntries(
Object.entries(config).filter(([key]) => !knownKeys.has(key) && !isSensitiveKey(key))
);
}
function parseAdvancedConfig(value: string):
| { ok: true; config: CodexProfileConfig }
| { ok: false; message: string } {
let parsed: unknown;
try {
parsed = JSON.parse(value || '{}');
} catch {
return { ok: false, message: '高级配置必须是有效 JSON' };
}
if (!isPlainObject(parsed)) return { ok: false, message: '高级配置必须是 JSON 对象' };
for (const [key, entry] of Object.entries(parsed)) {
if (knownKeys.has(key)) return { ok: false, message: `${key} 请使用上方专用字段配置` };
if (isSensitiveKey(key)) return { ok: false, message: `${key} 属于敏感配置,不能在 Web 页面中编辑` };
if (!isProfileValue(entry)) return { ok: false, message: `${key} 不是支持的 Profile 配置值` };
}
return { ok: true, config: parsed as CodexProfileConfig };
}
function isProfileValue(value: unknown): boolean {
if (typeof value === 'string' || typeof value === 'boolean') return true;
if (typeof value === 'number') return Number.isFinite(value);
if (!Array.isArray(value)) return false;
if (value.length === 0) return true;
const type = typeof value[0];
if (type !== 'string' && type !== 'boolean' && type !== 'number') return false;
if (type === 'number' && value.some(item => typeof item !== 'number' || !Number.isFinite(item))) return false;
return value.every(item => typeof item === type);
}
function isSensitiveKey(key: string): boolean {
return /(?:secret|token|password|api[_-]?key|bearer|credential)/i.test(key);
}
function containsSensitiveConfig(config: CodexProfileConfig): boolean {
return Object.keys(config).some(isSensitiveKey);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function readString(value: unknown): string {
return typeof value === 'string' ? value : '';
}
function profileSummary(profile: CodexProfileResponse): string {
const model = readString(profile.config.model) || '默认模型';
const reasoning = readString(profile.config.model_reasoning_effort) || '默认推理';
const sandbox = readString(profile.config.sandbox_mode) || '默认 Sandbox';
const advancedCount = Object.keys(profile.config).filter(key => !knownKeys.has(key)).length;
return [model, reasoning, sandbox, advancedCount > 0 ? `${advancedCount} 项高级配置` : '']
.filter(Boolean)
.join(' · ');
}