feat(privacy): split workspace anonymization into editable steps

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-25 21:33:40 +08:00
co-authored by Codex
parent f8a7a45b34
commit 23a4fa42c4
14 changed files with 243 additions and 58 deletions
@@ -48,6 +48,8 @@ pub enum PrivacyAction {
SetValue,
RenameKey,
RemoveField,
AnonymizeProject,
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
AnonymizeWorkspace,
}
@@ -16,10 +16,12 @@ pub(super) struct CompiledStep {
impl CompiledStep {
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
if rule.action == PrivacyAction::AnonymizeWorkspace
&& (rule.scope != PrivacyScope::TurnMetadata
|| rule.selector != "$.workspaces"
|| rule.pattern.is_some())
if matches!(
rule.action,
PrivacyAction::AnonymizeProject | PrivacyAction::AnonymizeWorkspace
) && (rule.scope != PrivacyScope::TurnMetadata
|| rule.selector != "$.workspaces"
|| rule.pattern.is_some())
{
return Err("工作区匿名化仅支持 turn_metadata 的 $.workspaces,且不使用匹配表达式");
}
@@ -99,6 +101,9 @@ impl CompiledStep {
) -> Result<bool, &'static str> {
budget.step()?;
match self.rule.action {
PrivacyAction::AnonymizeProject => {
*count += super::workspace::anonymize_project(value, budget)?;
}
PrivacyAction::AnonymizeWorkspace => {
*count += super::workspace::anonymize(value, budget)?;
}
@@ -20,6 +20,42 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
}
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
let count = anonymize_project(value, budget)?;
let workspaces = value.as_object_mut().ok_or("工作区映射必须是对象")?;
let mut renamed = Map::new();
// 保留已保存组合动作的用户名替换与 Git 裁剪,独立项目动作不包含这些副作用
for (path, mut metadata) in std::mem::take(workspaces) {
let object = metadata.as_object_mut().ok_or("工作区信息必须是对象")?;
object.remove("associated_remote_urls");
object.remove("latest_git_commit_hash");
let split = path.rfind(['/', '\\']).ok_or("工作区路径缺少工程目录")?;
let mut alias = String::new();
let mut username = false;
for part in path[..=split].split_inclusive(['/', '\\']) {
let component = part.trim_end_matches(['/', '\\']);
if username && !component.is_empty() {
alias.push_str("user");
alias.push_str(&part[component.len()..]);
username = false;
} else {
alias.push_str(part);
username = component.eq_ignore_ascii_case("users")
|| component.eq_ignore_ascii_case("home");
}
}
alias.push_str(&path[split + 1..]);
if renamed.insert(alias, metadata).is_some() {
return Err("工作区匿名化产生重名");
}
}
*workspaces = renamed;
Ok(count)
}
pub(super) fn anonymize_project(
value: &mut Value,
budget: &mut Budget<'_>,
) -> Result<usize, &'static str> {
let workspaces = value.as_object().ok_or("工作区映射必须是对象")?;
if workspaces.is_empty() {
return Ok(0);
@@ -32,9 +68,7 @@ pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<us
let mut renamed = Map::new();
for (path, metadata) in workspaces {
budget.text(path)?;
let mut metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
metadata.remove("associated_remote_urls");
metadata.remove("latest_git_commit_hash");
let metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
let alias = alias_path(path, session)?;
if renamed.insert(alias, Value::Object(metadata)).is_some() {
return Err("工作区匿名化产生重名");
@@ -63,21 +97,8 @@ fn alias_path(path: &str, session: &str) -> Result<String, &'static str> {
hash.update(session.as_bytes());
hash.update(path.as_bytes());
let digest = hash.finalize();
// 保留客户端的分隔符和父目录层级,用户名与工程名改用化名
let mut alias = String::new();
let mut username = false;
for part in path[..=split].split_inclusive(['/', '\\']) {
let component = part.trim_end_matches(['/', '\\']);
if username && !component.is_empty() {
alias.push_str("user");
alias.push_str(&part[component.len()..]);
username = false;
} else {
alias.push_str(part);
username =
component.eq_ignore_ascii_case("users") || component.eq_ignore_ascii_case("home");
}
}
// 只改工程名,父目录与用户名交给独立的字段名替换步骤
let mut alias = path[..=split].to_owned();
alias.push_str(&shuffled_project_name(&path[split + 1..], &digest));
alias.push_str(&format!(
"-{}-{}",
@@ -10,6 +10,119 @@ fn anonymous_rule() -> PrivacyRule {
)
}
fn composed_rule(username: &str) -> PrivacyRule {
let mut configured = rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
);
let mut rename = step(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::RenameKey,
);
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
rename.replacement = format!("${{1}}{username}${{2}}");
configured.steps.push(rename);
for selector in [
"$.workspaces.*.associated_remote_urls",
"$.workspaces.*.latest_git_commit_hash",
] {
configured.steps.push(step(
PrivacyScope::TurnMetadata,
selector,
PrivacyAction::RemoveField,
));
}
configured
}
#[test]
fn project_anonymization_preserves_usernames_and_git_information() {
for path in [
"/home/alex/projects/private",
"/Users/alex/private",
r"C:\Users\alex\private",
] {
let metadata = json!({"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true});
let mut request = sample(
vec![rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
)],
json!({"turn_metadata":{"workspaces":{path:metadata}}}),
);
request
.headers
.insert("session-id".into(), vec!["sample-session".into()]);
let output = preview(request).unwrap();
let (alias, value) = output.body["turn_metadata"]["workspaces"]
.as_object()
.unwrap()
.iter()
.next()
.unwrap();
assert!(alias.starts_with(path.rsplit_once(['/', '\\']).unwrap().0));
assert_ne!(alias, path);
assert_eq!(value, &metadata);
}
}
#[test]
fn independent_steps_preserve_combined_behavior_and_allow_customization() {
for path in [
"/home/alex/projects/private",
"/Users/alex/private",
r"C:\Users\alex\private",
] {
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}});
let mut request = sample(
vec![anonymous_rule()],
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
);
request.turn_metadata = Some(metadata.to_string());
request
.headers
.insert("session-id".into(), vec!["sample-session".into()]);
request
.headers
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
let combined = preview(request.clone()).unwrap();
request.policy.rules = vec![composed_rule("user")];
let composed = preview(request.clone()).unwrap();
assert_eq!(composed.body, combined.body);
assert_eq!(composed.headers, combined.headers);
assert_eq!(composed.turn_metadata, combined.turn_metadata);
let mut customized = composed_rule("blg");
customized.steps.remove(2);
request.policy.rules = vec![customized];
let output = preview(request).unwrap();
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
let (alias, workspace) = value["workspaces"]
.as_object()
.unwrap()
.iter()
.next()
.unwrap();
assert!(
alias.starts_with(
&path
.rsplit_once(['/', '\\'])
.unwrap()
.0
.replace("alex", "blg")
)
);
assert_eq!(
workspace["associated_remote_urls"],
metadata["workspaces"][path]["associated_remote_urls"]
);
assert!(workspace.get("latest_git_commit_hash").is_none());
}
}
#[test]
fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
for path in [
@@ -209,7 +322,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
compile(&policy(vec![rule(
scope,
selector,
PrivacyAction::AnonymizeWorkspace
PrivacyAction::AnonymizeProject
)]))
.is_err()
);
+12 -3
View File
@@ -2424,7 +2424,7 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
JSON 路径支持 `$`、`.成员`、`["带特殊字符的键"]`、`[索引]`、`.*` 和 `[*]`,不支持递归和过滤表达式。
缺少字段视为未命中;类型不符属于执行失败。`regex_replace` 替换字符串,`set_value` 保持原字段类型设置 JSON 值,
`rename_key` 替换所选对象的直接键名,重名时失败;`remove_field` 删除所选字段或数组项,不能删除作用范围根节点。
`anonymize_workspace` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按逻辑会话改写工程路径并删除 Git 远端与提交 metadata
`anonymize_project` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按账号与逻辑会话改写项目名,保留父目录、用户名及映射内的 metadata
删除动作的 `pattern: null` 表示无条件删除,字符串模式表示只删除字符串值匹配的字段或数组项。
请求头规则生成的值必须是 ASCII 文本,以保持 HTTP 与 WebSocket opening 的一致性;metadata 范围会自动转义 Unicode
@@ -2446,11 +2446,20 @@ WebSocket 请求头在握手时发送。隐私规则改变握手头时,普通
UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份](#openai-上游客户端身份)管理。
保存后的规则按其 `steps` 执行,不随预设定义变化
「按账号与会话匿名化工作区」预设使用 `anonymize_workspace`,保留路径分隔符与父目录层级,将用户目录中的用户名改为 `user`。
「按账号与会话匿名化工作区」预设按顺序生成四个可编辑步骤:
1. `anonymize_project` 根据原始路径生成项目化名,保留分隔符与父目录
2. `rename_key` 将 Linux、macOS 和 Windows 用户目录中的用户名改为 `user`,替换内容可自定义
3. `remove_field` 删除 `$.workspaces.*.associated_remote_urls`
4. `remove_field` 删除 `$.workspaces.*.latest_git_commit_hash`
各步骤可以修改、删除或调整顺序;用户名替换与 Git 信息处理不由项目匿名化动作隐式执行。
工程名取原名的前 48 个字母或数字打乱顺序,再加两组 1~1000 的数字和短后缀;没有字母或数字时使用 `project`。
例如 `codex-proxy-rs` 可变为 `xrpceodxroys-427-83-a1b2c3d4`。同一 Client Key、账号、逻辑会话和工作区的化名在重试与重启后保持一致;
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
映射内的 `associated_remote_urls`、`latest_git_commit_hash` 被移除,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
已保存的 `anonymize_workspace` 组合动作继续替换用户名、生成项目化名并删除 Git 信息。管理端编辑时将其展开为四个独立步骤,应用草稿并保存后生效;展开后的步骤仍计入总上限
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
+1 -1
View File
@@ -2,7 +2,7 @@ import type { RequestOptions } from '../../request'
import request from '../../request'
export type PrivacyScope = 'turn_metadata' | 'desktop_git_context' | 'environment_text' | 'request_body' | 'request_header'
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_workspace'
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project' | 'anonymize_workspace'
export type JsonValue = unknown
export interface PrivacyRule {
+2 -2
View File
@@ -592,8 +592,7 @@
"fieldPath": "Field path",
"fieldPathSyntax": "Field path syntax",
"jsonPathHelp": "Supports object members, quoted keys, array indexes, and * wildcards, for example $[\"workspaces\"][\"/home/alex/demo\"]",
"sessionAliasEffect": "Stable per account and session; Git metadata removed",
"anonymizeWorkspaceHelp": "Shuffle the project name and add numbers; rotate aliases for new accounts or sessions, remove Git metadata, and preserve execution paths",
"sessionAliasEffect": "Stable project alias per account and session",
"targetHelp": "Use $ for environment text and a header name for request headers",
"commonFields": "Common fields",
"deleteMatchHelp": "Remove only fields or array items whose values match the regular expression",
@@ -647,6 +646,7 @@
"gitCommitId": "Git commit ID",
"gitRemoteCollection": "Git remote collection",
"workspaceFingerprint": "Workspace fingerprint",
"anonymizeProject": "Anonymize project name by account and session",
"anonymizeWorkspace": "Anonymize workspace by account and session",
"unifyWorkspaceInformation": "Unify workspace information"
},
@@ -592,8 +592,7 @@
"fieldPath": "字段路径",
"fieldPathSyntax": "字段路径语法",
"jsonPathHelp": "支持对象成员、双引号键名、数组索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
"sessionAliasEffect": "同账号同会话化名固定,移除 Git 信息",
"anonymizeWorkspaceHelp": "打乱工程名并加数字,换账号或新会话时更换化名;移除 Git 信息,保留真实执行路径",
"sessionAliasEffect": "同账号同会话项目化名固定",
"targetHelp": "环境文本使用 $,请求头直接填写名称",
"commonFields": "常用字段",
"deleteMatchHelp": "仅删除值匹配正则的字段或数组项",
@@ -647,6 +646,7 @@
"gitCommitId": "Git 提交 ID",
"gitRemoteCollection": "Git 远端集合",
"workspaceFingerprint": "工作区指纹",
"anonymizeProject": "按账号与会话匿名化项目名",
"anonymizeWorkspace": "按账号与会话匿名化工作区",
"unifyWorkspaceInformation": "统一工作区信息"
},
@@ -592,8 +592,7 @@
"fieldPath": "字段路徑",
"fieldPathSyntax": "字段路徑語法",
"jsonPathHelp": "支持對象成員、雙引號鍵名、數組索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
"sessionAliasEffect": "同賬號同會話化名固定,移除 Git 資訊",
"anonymizeWorkspaceHelp": "打亂工程名並加數字,換賬號或新會話時更換化名;移除 Git 資訊,保留真實執行路徑",
"sessionAliasEffect": "同賬號同會話專案化名固定",
"targetHelp": "環境文本使用 $,請求頭直接填寫名稱",
"commonFields": "常用字段",
"deleteMatchHelp": "僅刪除值匹配正則的字段或數組項",
@@ -647,6 +646,7 @@
"gitCommitId": "Git 提交 ID",
"gitRemoteCollection": "Git 遠端集合",
"workspaceFingerprint": "工作區指紋",
"anonymizeProject": "按賬號與會話匿名化專案名稱",
"anonymizeWorkspace": "按賬號與會話匿名化工作區",
"unifyWorkspaceInformation": "統一工作區信息"
},
@@ -6,7 +6,7 @@ import { Play } from '@lucide/vue'
import { cloneDeep } from 'es-toolkit'
import { computed, ref, shallowRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { exampleRequest, newRule, newStep } from './presets'
import { exampleRequest, expandWorkspaceSteps, newRule, newStep } from './presets'
import StepFields from './StepFields.vue'
import StepList from './StepList.vue'
import { usePrivacyPreview } from './usePrivacyPreview'
@@ -46,6 +46,7 @@ watch(open, (value) => {
if (value) {
selectedIndex.value = 0
draft.value = cloneDeep(props.rule ?? newRule())
draft.value.steps = expandWorkspaceSteps(draft.value.steps)
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
sample.value = JSON.stringify(exampleRequest(), null, 2)
}
@@ -145,7 +145,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
{{ [...new Set(row.steps.map(step => scopes.find(item => item.value === step.scope)?.label))].join('、') }}
</template>
<template #action="{ row }">
{{ [...new Set(row.steps.map(step => actions.find(item => item.value === step.action)?.label))].join('、') }}
{{ [...new Set(row.steps.map(step => step.action === 'anonymize_workspace' ? t('settings.privacy.presets.anonymizeWorkspace') : actions.find(item => item.value === step.action)?.label))].join('、') }}
</template>
<template #actions="{ row }">
<div class="flex items-center justify-end gap-1">
@@ -12,7 +12,7 @@ const { t } = useI18n({ useScope: 'global' })
const step = defineModel<PrivacyStep>({ required: true })
const fixedValue = defineModel<string>('fixedValue', { required: true })
const fieldPresetId = useId()
const anonymizesWorkspace = computed(() => step.value.action === 'anonymize_workspace')
const anonymizesProject = computed(() => step.value.action === 'anonymize_project')
const usesPattern = computed(() => ['regex_replace', 'rename_key'].includes(step.value.action) || (step.value.action === 'remove_field' && step.value.pattern !== null))
const pattern = computed({
get: () => step.value.pattern ?? '',
@@ -44,7 +44,7 @@ const selectorPlaceholder = computed(() => ({
})[step.value.scope])
watch(() => step.value.action, (action) => {
if (action === 'anonymize_workspace') {
if (action === 'anonymize_project') {
step.value.scope = 'turn_metadata'
step.value.selector = '$.workspaces'
step.value.pattern = null
@@ -61,7 +61,7 @@ watch(() => step.value.action, (action) => {
<template>
<ZForm class="sm:grid-cols-2">
<ZFormItem class="md:[&>div:first-child]:min-h-8" :label="t('settings.privacy.rules.scope')">
<ZSelect v-model="step.scope" class="w-full" :options="scopes" :disabled="anonymizesWorkspace" :aria-label="t('settings.privacy.rules.scope')" />
<ZSelect v-model="step.scope" class="w-full" :options="scopes" :disabled="anonymizesProject" :aria-label="t('settings.privacy.rules.scope')" />
</ZFormItem>
<ZFormItem class="md:[&>div:first-child]:min-h-8" :label="t('settings.privacy.rules.processingMethod')">
<ZSelect v-model="step.action" class="w-full" :options="actions" :aria-label="t('settings.privacy.rules.processingMethod')" />
@@ -80,13 +80,10 @@ watch(() => step.value.action, (action) => {
</ZPopover>
</template>
<div class="flex flex-wrap items-center gap-2 sm:flex-nowrap">
<ZInput v-model="step.selector" :disabled="anonymizesWorkspace" :placeholder="selectorPlaceholder" :aria-label="t('settings.privacy.steps.fieldPath')" maxlength="1024" class="min-w-0 flex-1 font-mono" :class="fields.length ? 'basis-full sm:basis-auto' : undefined" spellcheck="false" />
<ZSelect v-if="fields.length" :id="fieldPresetId" v-model="fieldChoice" :disabled="anonymizesWorkspace" class="min-w-0 flex-1 sm:w-40 sm:flex-none" :options="fields" :aria-label="t('settings.privacy.steps.commonFields')" />
<ZInput v-model="step.selector" :disabled="anonymizesProject" :placeholder="selectorPlaceholder" :aria-label="t('settings.privacy.steps.fieldPath')" maxlength="1024" class="min-w-0 flex-1 font-mono" :class="fields.length ? 'basis-full sm:basis-auto' : undefined" spellcheck="false" />
<ZSelect v-if="fields.length" :id="fieldPresetId" v-model="fieldChoice" :disabled="anonymizesProject" class="min-w-0 flex-1 sm:w-40 sm:flex-none" :options="fields" :aria-label="t('settings.privacy.steps.commonFields')" />
</div>
</ZFormItem>
<p v-if="anonymizesWorkspace" class="m-0 text-z-sm text-z-text-secondary sm:col-span-2">
{{ t('settings.privacy.steps.anonymizeWorkspaceHelp') }}
</p>
<ZCheckbox v-if="step.action === 'remove_field'" v-model="conditional" class="sm:col-span-2" :label="t('settings.privacy.steps.deleteMatchHelp')" />
<ZFormItem v-if="usesPattern" :class="step.action === 'remove_field' ? 'sm:col-span-2' : undefined" :label="t('settings.privacy.steps.matchExpression')">
<ZInput v-model="pattern" :placeholder="step.action === 'rename_key' ? t('settings.privacy.steps.forExampleHome') : t('settings.privacy.steps.forExamplePrivateOrg')" :aria-label="t('settings.privacy.steps.matchExpression')" maxlength="4096" spellcheck="false" class="font-mono" />
@@ -27,7 +27,7 @@ const items = computed(() => props.steps.map((step, index) => {
: step.selector.trim() || t('settings.privacy.steps.noFieldsSelected'))
const scope = scopes.value.find(scope => scope.value === step.scope)?.label
const action = actions.value.find(action => action.value === step.action)?.label
const effect = step.action === 'anonymize_workspace'
const effect = step.action === 'anonymize_project'
? t('settings.privacy.steps.sessionAliasEffect')
: step.action === 'set_value'
? `→ ${props.fixedValues[index] ?? '""'}`
@@ -27,8 +27,8 @@ export const scopes = computed<{ value: PrivacyScope, label: string }[]>(() => (
]))
export const actions = computed<{ value: PrivacyAction, label: string }[]>(() => ([
{
value: 'anonymize_workspace',
label: t('settings.privacy.presets.anonymizeWorkspace'),
value: 'anonymize_project',
label: t('settings.privacy.presets.anonymizeProject'),
},
{
value: 'regex_replace',
@@ -53,6 +53,10 @@ export const fieldsByScope = computed<Partial<Record<PrivacyScope, { value: stri
value: '',
label: t('settings.privacy.presets.customFieldPath'),
},
{
value: '$.workspaces.*.associated_remote_urls',
label: t('settings.privacy.presets.gitRemoteCollection'),
},
{
value: '$.workspaces.*.associated_remote_urls.*',
label: t('settings.privacy.presets.gitRemoteAddress'),
@@ -115,18 +119,40 @@ export function newRule(): PrivacyRule {
}
}
// 化名从原始路径派生,用户名替换不能改变其身份输入
const workspaceSteps: Partial<PrivacyStep>[] = [
{
scope: 'turn_metadata',
selector: '$.workspaces',
action: 'anonymize_project',
pattern: null,
},
{
scope: 'turn_metadata',
selector: '$.workspaces',
action: 'rename_key',
pattern: String.raw`(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])`,
replacement: `\${1}user\${2}`,
},
{
scope: 'turn_metadata',
selector: '$.workspaces.*.associated_remote_urls',
action: 'remove_field',
pattern: null,
},
{
scope: 'turn_metadata',
selector: '$.workspaces.*.latest_git_commit_hash',
action: 'remove_field',
pattern: null,
},
]
export const presets = computed<{ key: string, name: string, steps: Partial<PrivacyStep>[] }[]>(() => ([
{
key: 'session-workspace',
name: t('settings.privacy.presets.anonymizeWorkspace'),
steps: [
{
scope: 'turn_metadata',
selector: '$.workspaces',
action: 'anonymize_workspace',
pattern: null,
},
],
steps: workspaceSteps,
},
{
key: 'workspace',
@@ -156,13 +182,24 @@ export function createPreset(key: string): PrivacyRule {
return {
...newRule(),
name: preset.name,
steps: preset.steps.map(step => ({
...newStep(),
...cloneDeep(step),
})),
steps: createSteps(preset.steps),
}
}
function createSteps(steps: Partial<PrivacyStep>[]): PrivacyStep[] {
return steps.map(step => ({
...newStep(),
...cloneDeep(step),
}))
}
export function expandWorkspaceSteps(steps: PrivacyStep[]): PrivacyStep[] {
// 只展开编辑草稿,已保存的组合动作由后端保持原行为
return steps.flatMap(step => step.action === 'anonymize_workspace'
? createSteps(workspaceSteps)
: [step])
}
// 样本使用虚构仓库、路径与标识,字段形状对应官方 Core 和 Desktop Git 上下文
const metadata = {
workspaces: {