Merge pull request #494 from runkids/runkids/extras-mode-rules

refactor(extras): keep target mode rules in config and share them in the UI
This commit is contained in:
Willie
2026-10-08 16:18:15 +08:00
committed by GitHub
7 changed files with 88 additions and 35 deletions
+18
View File
@@ -44,6 +44,24 @@ func ManagedExtraMode(mode string) bool {
return mode == "import" || mode == "prepend" || mode == "append"
}
// EffectiveMode returns the target's mode after its extension: a transform
// extension only makes sense with copy mode.
func (t ExtraTargetConfig) EffectiveMode() string {
if t.Extension != "" {
return "copy"
}
return t.Mode
}
// Normalize applies EffectiveMode and drops include and exclude from a
// symlink target: one link to the whole folder cannot leave files out.
func (t *ExtraTargetConfig) Normalize() {
t.Mode = t.EffectiveMode()
if t.Mode == "symlink" {
t.Include, t.Exclude = nil, nil
}
}
// ValidateExtraMode checks that mode is a valid sync mode.
// Empty string is allowed (defaults to "merge" at runtime).
func ValidateExtraMode(mode string) error {
+16
View File
@@ -58,3 +58,19 @@ func TestValidateExtraName_CaseOnlyDifferenceIsDuplicate(t *testing.T) {
t.Error("ValidateExtraNameUnique(\"Rules\", [rules]) = nil, want error")
}
}
func TestExtraTargetNormalize_ExtensionForcesCopy(t *testing.T) {
target := ExtraTargetConfig{Mode: "symlink", Extension: "x", Include: []string{"*.md"}}
target.Normalize()
if target.Mode != "copy" || len(target.Include) != 1 {
t.Errorf("got mode %q include %v, want copy with include kept", target.Mode, target.Include)
}
}
func TestExtraTargetNormalize_SymlinkDropsFilters(t *testing.T) {
target := ExtraTargetConfig{Mode: "symlink", Include: []string{"*.md"}, Exclude: []string{"a"}}
target.Normalize()
if target.Include != nil || target.Exclude != nil {
t.Errorf("got include %v exclude %v, want both dropped", target.Include, target.Exclude)
}
}
+8 -16
View File
@@ -507,15 +507,8 @@ func (s *Server) handleExtrasCreate(w http.ResponseWriter, r *http.Request) {
// Build ExtraConfig
extra := config.ExtraConfig{Name: body.Name, Source: body.Source, File: body.File}
for _, t := range body.Targets {
et := config.ExtraTargetConfig{Path: t.Path, Flatten: t.Flatten, As: t.As}
if t.Mode != "" {
et.Mode = t.Mode
}
if t.Extension != "" {
// A transform extension only makes sense with copy mode.
et.Extension = t.Extension
et.Mode = "copy"
}
et := config.ExtraTargetConfig{Path: t.Path, Mode: t.Mode, Flatten: t.Flatten, Extension: t.Extension, As: t.As}
et.Normalize()
extra.Targets = append(extra.Targets, et)
}
if err := config.ValidateExtraConfig(extra); err != nil {
@@ -838,14 +831,13 @@ func (s *Server) handleExtrasMode(w http.ResponseWriter, r *http.Request) {
// An extension transform implies copy mode. Reject only a mode
// explicitly requested in this call that conflicts; otherwise
// force copy, overriding any prior mode on the target.
if newExtension != "" {
if body.Mode != "" && body.Mode != "copy" {
writeError(w, http.StatusBadRequest, "extension requires copy mode, but mode "+body.Mode+" was set on the target")
return
}
newMode = "copy"
// force copy, overriding any prior mode on the target. Filters
// are not dropped here: symlink with filters fails validation.
if newExtension != "" && body.Mode != "" && body.Mode != "copy" {
writeError(w, http.StatusBadRequest, "extension requires copy mode, but mode "+body.Mode+" was set on the target")
return
}
newMode = config.ExtraTargetConfig{Mode: newMode, Extension: newExtension}.EffectiveMode()
// Validate the combination
if err := config.ValidateExtraFlatten(newFlatten, newMode); err != nil {
+1 -8
View File
@@ -99,14 +99,7 @@ func (s *Server) handleExtrasEditTarget(w http.ResponseWriter, r *http.Request)
in := body.Target
next := config.ExtraTargetConfig{Path: in.Path, Mode: in.Mode, Flatten: in.Flatten, Extension: in.Extension, As: in.As, Include: in.Include, Exclude: in.Exclude}
if next.Extension != "" {
// A transform extension only makes sense with copy mode.
next.Mode = "copy"
}
if next.Mode == "symlink" {
// One link to the whole folder cannot leave files out.
next.Include, next.Exclude = nil, nil
}
next.Normalize()
newPath := filepath.Clean(resolveExtrasTargetPath(s.projectRoot, next.Path))
if !s.IsProjectMode() {
next.Path = newPath
+21 -6
View File
@@ -23,6 +23,21 @@ export const MODES = ['merge', 'copy', 'symlink'] as const;
// A single file can't be a directory symlink; import writes an @ line instead.
export const FILE_MODES = ['merge', 'copy', 'import', 'prepend', 'append'] as const;
/** The target fields whose rules Add target and Edit target share. */
export interface TargetFields {
mode: string;
flatten: boolean;
extension: string;
}
/** Applies a field change with the rules that follow from it: an extension converts each file, so it always writes copies; symlink links the whole folder, so flatten turns off. */
export function applyDraftChange<T extends TargetFields>(draft: T, patch: Partial<TargetFields>): T {
const next = { ...draft, ...patch };
if (patch.extension) next.mode = 'copy';
if (next.mode === 'symlink') next.flatten = false;
return next;
}
const Mono = ({ children }: { children: ReactNode }) => <span className="font-mono">{children}</span>;
/** Reports a save: the sync it ran when files moved, else a plain saved toast. */
@@ -84,9 +99,9 @@ export function EditTargetDialog({ extra, target, extensions, markFor, onClose,
const report = useSaveToast();
const single = Boolean(extra.file);
const [path, setPath] = useState(target.path);
const [mode, setMode] = useState(target.mode);
const [flatten, setFlatten] = useState(target.flatten);
const [extension, setExtension] = useState(target.extension ?? '');
const [fields, setFields] = useState<TargetFields>({ mode: target.mode, flatten: target.flatten, extension: target.extension ?? '' });
const { mode, flatten, extension } = fields;
const change = (patch: Partial<TargetFields>) => setFields(applyDraftChange(fields, patch));
const [as, setAs] = useState(target.as ?? '');
const [filters, setFilters] = useState({ include: target.include ?? [], exclude: target.exclude ?? [] });
const [saving, setSaving] = useState(false);
@@ -156,7 +171,7 @@ export function EditTargetDialog({ extra, target, extensions, markFor, onClose,
<span className="text-[13px] font-semibold">{t('extras.modal.colExtension')}</span>
<Select
value={extension}
onChange={(v) => { setExtension(v); if (v) setMode('copy'); }}
onChange={(v) => change({ extension: v })}
options={[{ value: '', label: t('extras.noExtension') }, ...extensions.map((e) => ({ value: e, label: e }))]}
disabled={saving || mode === 'symlink' || (extensions.length === 0 && !extension)}
/>
@@ -166,7 +181,7 @@ export function EditTargetDialog({ extra, target, extensions, markFor, onClose,
<span className="text-[13px] font-semibold">{t('extras.modal.colMode')}</span>
<Select
value={extension ? 'copy' : mode}
onChange={setMode}
onChange={(v) => change({ mode: v })}
options={(single ? FILE_MODES : MODES).map((m) => ({ value: m, label: m, description: t(single ? `extras.fileModeDescription.${m}` : `extras.modeDescription.${m}`) }))}
disabled={saving || Boolean(extension)}
/>
@@ -175,7 +190,7 @@ export function EditTargetDialog({ extra, target, extensions, markFor, onClose,
<div className="ss-fld w-[110px]">
<span className="text-[13px] font-semibold">{t('extras.flatten')}</span>
<span className="flex h-9 items-center gap-2">
<button type="button" role="switch" aria-checked={flat} aria-label={t('extras.flatten')} className={`ss-sw ${flat ? 'on' : ''} disabled:opacity-50`} onClick={() => setFlatten(!flatten)} disabled={saving || mode === 'symlink'}><i /></button>
<button type="button" role="switch" aria-checked={flat} aria-label={t('extras.flatten')} className={`ss-sw ${flat ? 'on' : ''} disabled:opacity-50`} onClick={() => change({ flatten: !flatten })} disabled={saving || mode === 'symlink'}><i /></button>
<span className="text-xs text-ink-2">{t(flat ? 'extras.flattenOn' : 'extras.flattenOff')}</span>
</span>
</div>
+20
View File
@@ -152,6 +152,26 @@ describe('Extras page in a project', () => {
});
});
// Issue #490: Edit target clears flatten on symlink, like Add target.
it('keeps flatten off after Edit target switches to symlink and back', async () => {
const user = userEvent.setup();
// jsdom has no scrollIntoView, which the dropdown calls on its focused option.
HTMLElement.prototype.scrollIntoView = vi.fn();
renderPage();
await user.click(await screen.findByRole('button', { name: 'More actions for .claude/rules' }));
await user.click(screen.getByRole('menuitem', { name: 'Edit target…' }));
const dialog = screen.getByRole('dialog');
await user.click(within(dialog).getByRole('switch', { name: 'Flatten' }));
const mode = within(dialog).getAllByRole('combobox')[1];
await user.click(mode);
await user.click(screen.getByRole('option', { name: /^symlink/ }));
await user.click(mode);
await user.click(screen.getByRole('option', { name: /^merge/ }));
await user.click(within(dialog).getByRole('button', { name: 'Save' }));
expect(api.editExtraTarget).toHaveBeenLastCalledWith('rules', '.claude/rules', expect.objectContaining({ mode: 'merge', flatten: false }));
});
it('renames an extra in Edit extra', async () => {
const user = userEvent.setup();
renderPage();
+4 -5
View File
@@ -24,7 +24,7 @@ import ProjectInstructions from '../components/instructions/ProjectInstructions'
import SharedInstructions from '../components/instructions/SharedInstructions';
import { isAgentsExtra } from '../components/instructions/instructionsView';
import { useAvailableTargetsQuery, useOverviewQuery } from '../hooks/useSharedQueries';
import { EditExtraDialog, EditTargetDialog, FILE_MODES, MODES, joinFile } from '../components/extras/ExtraEditDialogs';
import { EditExtraDialog, EditTargetDialog, FILE_MODES, MODES, applyDraftChange, joinFile } from '../components/extras/ExtraEditDialogs';
import { invalidate } from '../lib/queryEvents';
/** A file name typed where a path would be wrong. */
@@ -112,7 +112,7 @@ function FileDraftFields({ draft, onChange, fileName, known, disabled }: {
<Select
className="w-[104px] shrink-0"
value={draft.mode}
onChange={(v) => onChange({ ...draft, mode: v })}
onChange={(v) => onChange(applyDraftChange(draft, { mode: v }))}
options={FILE_MODES.map((m) => ({ value: m, label: m, description: t(`extras.fileModeDescription.${m}`) }))}
disabled={disabled}
/>
@@ -145,15 +145,14 @@ function DraftFields({ draft, onChange, extensions, known, disabled }: {
<Select
className="w-[170px] shrink-0"
value={draft.extension}
// An extension converts each file, so it always writes copies
onChange={(v) => onChange({ ...draft, extension: v, ...(v ? { mode: 'copy' } : {}) })}
onChange={(v) => onChange(applyDraftChange(draft, { extension: v }))}
options={[{ value: '', label: t('extras.noExtension') }, ...extensions.map((e) => ({ value: e, label: e }))]}
disabled={disabled || extensions.length === 0}
/>
<Select
className="w-[104px] shrink-0"
value={locked ? 'copy' : draft.mode}
onChange={(v) => onChange({ ...draft, mode: v, ...(v === 'symlink' ? { flatten: false } : {}) })}
onChange={(v) => onChange(applyDraftChange(draft, { mode: v }))}
options={MODES.map((m) => ({ value: m, label: m, description: t(`extras.modeDescription.${m}`) }))}
disabled={disabled || locked}
/>