Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
243 changes: 243 additions & 0 deletions src/components/agents/config/__tests__/SavePreviewPanel.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
import { describe, expect, it, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import type { ConfigPreview, InstancePreview } from '@/types/agent-config';
import {
detailFor,
error422,
instanceIds,
instancesMixed,
previewMixed,
previewStandalone,
} from '@/composables/agent-config/__tests__/fixtures';
import PrimeDialog from 'primevue/dialog';
import SavePreviewPanel from '../editor/SavePreviewPanel.vue';
import DiffRows from '../editor/DiffRows.vue';
import { safetyForRow } from '../editor/review';
import { globalWith, piniaWith, ADMIN } from './helpers';

// The async CodeMirror wrappers are replaced by synchronous stubs.
vi.mock('@/components/code-editor', () => import('./codeEditorMock'));

const details = new Map(
instancesMixed.items
.filter((i) => i.reportedAt)
.map((i) => [i.instanceId, detailFor(i, {})]),
);

function mountPanel(
preview: ConfigPreview,
extra: Record<string, unknown> = {},
) {
return mount(SavePreviewPanel, {
props: {
preview,
instanceDetails: details,
currentOverlay: {},
draftOverlay: { plugins: { 'local-ssh': { schedule: '@hourly' } } },
baseRevision: 7,
...extra,
},
global: globalWith(piniaWith(ADMIN)),
});
}

const inst = (over: Partial<InstancePreview>): InstancePreview => ({
instanceId: instanceIds.a,
hostname: 'ip-a',
mode: 'apply_safe',
stale: false,
validated: true,
effective: null,
errors: [],
warnings: [],
changes: [],
willApply: true,
...over,
});
const clean = (instances: InstancePreview[]): ConfigPreview => ({
desiredRevision: 7,
standalone: false,
overlayErrors: [],
instances,
});
const saveButton = (w: ReturnType<typeof mount>) =>
w.find('[data-test="save-config"]');

describe('SavePreviewPanel (U2.5)', () => {
it('summarises will-apply with willApplyReason labels and offending changes', () => {
const w = mountPanel(previewMixed);
expect(w.find('[data-test="apply-summary"]').text()).toContain(
'0 of 3 instances will apply',
);
const lines = w.findAll('[data-test="not-applying"]').map((l) => l.text());
expect(lines[0]).toContain('Needs apply_all for some changes');
expect(lines[0]).toContain('/plugins/local-ssh/source');
expect(lines[0]).toContain('Untrusted source');
expect(lines[2]).toContain('Report-only mode');
});

it('tags rows by the most specific change prefix', () => {
const changes = [
{ path: '/plugins/a', safety: 'unsafe' as const, reason: 'x' },
{
path: '/plugins/a/schedule',
safety: 'safe' as const,
reason: 'logging',
},
];
expect(safetyForRow('/plugins/a/schedule', changes)).toBe('safe');
expect(safetyForRow('/plugins/a/config/k', changes)).toBe('unsafe');
expect(safetyForRow('/verbosity', changes)).toBe('no-effect');
expect(
safetyForRow('/plugins', [
{ path: '/plugins/b/source', safety: 'forbidden', reason: 'y' },
]),
).toBe('forbidden');
});

it('blocks saving on overlay errors / error policy errors / validated instance errors only', () => {
// previewMixed: overlay error + validated ip-d error → blocked.
expect(
saveButton(mountPanel(previewMixed)).attributes('disabled'),
).toBeDefined();

// Errors only on a non-validated instance → warnings, not blocking.
const nonValidated = clean([
inst({
validated: false,
mode: 'report',
errors: [{ path: '/x', message: 'bad' }],
}),
]);
const w = mountPanel(nonValidated);
expect(saveButton(w).attributes('disabled')).toBeUndefined();
expect(w.find('[data-test="instance-error-nonblocking"]').text()).toContain(
'Not validated on save',
);

const validated = clean([
inst({ errors: [{ path: '/x', message: 'bad' }] }),
]);
expect(
saveButton(mountPanel(validated)).attributes('disabled'),
).toBeDefined();
});

it('R59 file warnings do not block', () => {
const p = clean([
inst({
warnings: [{ path: '/plugins/y/schedule', message: 'file cron' }],
}),
]);
const w = mountPanel(p);
expect(saveButton(w).attributes('disabled')).toBeUndefined();
expect(w.find('[data-test="instance-warnings"]').text()).toContain(
'does not block',
);
expect(saveButton(w).text()).toBe('Save as r8');
});

it('shows the standalone banner and an overlay diff', () => {
const w = mountPanel(previewStandalone);
expect(w.find('[data-test="standalone"]').exists()).toBe(true);
expect(w.find('[data-test="apply-summary"]').exists()).toBe(false);
expect(w.find('[data-test="diff-rows"]').text()).toContain('/plugins');
});

it('diffs merge(base, current) vs merge(base, draft) per instance with safety tags', () => {
const p = clean([
inst({
changes: [
{
path: '/plugins/local-ssh/schedule',
safety: 'safe',
reason: 'logging',
},
],
}),
]);
const w = mountPanel(p);
const row = w.find('[data-path="/plugins/local-ssh/schedule"]');
expect(row.text()).toContain('*/5 * * * *');
expect(row.text()).toContain('@hourly');
expect(row.find('[data-safety="safe"]').exists()).toBe(true);
});

it('falls back to the change list when the base is unavailable', () => {
const p = clean([
inst({
instanceId: 'unknown-id',
changes: [{ path: '/v', safety: 'safe', reason: 'logging' }],
}),
]);
expect(mountPanel(p).find('[data-test="changes-fallback"]').exists()).toBe(
true,
);
});

it('treats errors as blocking on non-stale instances when validated is absent (older API)', () => {
const p = clean([
inst({ validated: undefined, errors: [{ path: '/x', message: 'bad' }] }),
]);
const w = mountPanel(p);
expect(saveButton(w).attributes('disabled')).toBeDefined();
expect(w.find('[data-test="legacy-validation"]').exists()).toBe(true);
});

it('maps a 422 body onto the lists and instance panels', () => {
const w = mountPanel(clean([inst({})]), { saveErrors: error422.errors });
expect(w.find('[data-test="overlay-error"]').text()).toContain('/api');
expect(
w.find(`[data-test="instance-panel-${instanceIds.a}"]`).text(),
).toContain('invalid cron');
expect(saveButton(w).attributes('disabled')).toBeDefined();
});

it('emits save with the comment', async () => {
const w = mountPanel(clean([inst({})]));
await w.find('[data-test="save-comment"]').setValue('why');
await saveButton(w).trigger('click');
expect(w.emitted('save')?.[0]).toEqual(['why']);
});

it('disables Back while saving', () => {
const w = mountPanel(clean([inst({})]), { saving: true });
expect(
w.find('[data-test="review-back"]').attributes('disabled'),
).toBeDefined();
expect(saveButton(w).attributes('disabled')).toBeDefined();
});

it('reports its nested diff dialog opening and closing (Esc gate)', async () => {
const w = mountPanel(clean([inst({})]));
const row = { path: '/x', kind: 'changed', before: 'a', after: 'b' };
w.findComponent(DiffRows).vm.$emit('open-diff', row);
await w.vm.$nextTick();
expect(w.emitted('childOpen')).toEqual([[true]]);
const diff = w
.findAllComponents(PrimeDialog)
.find((d) => d.props('header') === '/x')!;
diff.vm.$emit('update:visible', false);
await w.vm.$nextTick();
expect(w.emitted('childOpen')).toEqual([[true], [false]]);
});
});

describe('review rows for policy_data arrays', () => {
it('shows a whole-array write as element-level rows', () => {
const w = mountPanel(clean([inst({})]), {
currentOverlay: {
plugins: { 'local-ssh': { policy_data: { users: ['a', 'b'] } } },
},
draftOverlay: {
plugins: { 'local-ssh': { policy_data: { users: ['a', 'B', 'c'] } } },
},
});
const paths = w
.findAll('[data-test="diff-rows"] tr[data-path]')
.map((r) => r.attributes('data-path'));
expect(paths).toContain('/plugins/local-ssh/policy_data/users/1');
expect(paths).toContain('/plugins/local-ssh/policy_data/users/2');
expect(paths).not.toContain('/plugins/local-ssh/policy_data/users');
});
});
80 changes: 80 additions & 0 deletions src/components/agents/config/editor/DiffRows.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<template>
<table class="w-full text-left text-xs" data-test="diff-rows">
<tbody>
<tr v-if="!rows.length">
<td class="py-1 text-gray-500">No differences.</td>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should-fix] UI-COMP-001 · Component convention not followed

Introduced in #334. text-gray-400/text-gray-500 with no dark: variant; 745 of 823 such class attributes in the repo pair them with dark:text-slate-*.

Why: Mixed patterns make components harder to maintain; there are no auto-imports.
Fix: Add the matching dark:text-slate-400/dark:text-slate-500 variant, as the neighbouring components do.

ccf-review · 4d276dd210ce · rules@6be9e11b8bc6

</tr>
<tr
v-for="row in rows"
:key="row.path"
class="border-t border-ccf-300 align-top dark:border-slate-700"
:data-path="row.path"
>
<td class="py-1 pr-2 font-mono break-all">{{ row.path }}</td>
<td class="py-1 pr-2">
<template v-if="row.multiline">
<button
type="button"
class="text-sky-700 hover:underline dark:text-sky-300"
data-test="view-diff"
@click="$emit('open-diff', row)"
>
View diff
</button>
</template>
<template v-else>
<ValueCell :value="row.before" :missing="row.kind === 'added'" />
<span class="mx-1 text-gray-400">→</span>
<ValueCell :value="row.after" :missing="row.kind === 'removed'" />
</template>
</td>
<td v-if="!hideTags" class="py-1 text-right">
<SafetyTag :kind="safetyForRow(row.path, changes)" />
</td>
</tr>
</tbody>
</table>
</template>

<script setup lang="ts">
import { defineComponent, h, ref } from 'vue';
import type { ConfigChange } from '@/types/agent-config';
import type { DiffEntry } from '@/utils/agent-config/config-diff';
import SafetyTag from './SafetyTag.vue';
import { safetyForRow, truncate } from './review';

defineProps<{
rows: DiffEntry[];
changes: ConfigChange[];
hideTags?: boolean;
}>();
defineEmits<{ 'open-diff': [row: DiffEntry] }>();

// A value truncated to 120 characters with a "show" toggle.
const ValueCell = defineComponent({
props: { value: { type: null, default: undefined }, missing: Boolean },
setup(p) {
const open = ref(false);
return () => {
if (p.missing)
return h('span', { class: 'text-gray-400 italic' }, 'absent');
const t = truncate(p.value);
const full = truncate(p.value, Number.MAX_SAFE_INTEGER).text;
Comment on lines +61 to +62
return h('span', { class: 'font-mono break-all' }, [
open.value ? full : t.text,
t.truncated
? h(
'button',
{
type: 'button',
class: 'ml-1 text-sky-700 hover:underline dark:text-sky-300',
onClick: () => (open.value = !open.value),
},
open.value ? 'hide' : 'show',
)
: null,
]);
};
},
});
</script>
32 changes: 32 additions & 0 deletions src/components/agents/config/editor/SafetyTag.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<template>
<ConfigPill :severity="severity" :data-safety="kind">{{ label }}</ConfigPill>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import ConfigPill from '../ConfigPill.vue';
import type { SafetyTagKind } from './review';

const props = defineProps<{ kind: SafetyTagKind }>();

const severity = computed(
() =>
(
({
safe: 'success',
unsafe: 'warn',
forbidden: 'danger',
'no-effect': 'secondary',
}) as const
)[props.kind],
);
const label = computed(
() =>
({
safe: 'safe',
unsafe: 'needs apply_all',
forbidden: 'forbidden',
'no-effect': 'no effect vs file',
})[props.kind],
);
</script>
Loading
Loading