Staging/ui regressions #2134
No files matched your search
@@ -48,6 +48,13 @@ The first run needs `pnpm install --dir e2e` and `pnpm --dir e2e exec playwright
|
||||
install chromium`. The cloud environment ships Chromium and Playwright
|
||||
preinstalled; run with `NODE_PATH=$(pnpm root -g)`.
|
||||
|
||||
## Mocked settings review
|
||||
|
||||
With the dashboard running on local Vite and the browser dependencies installed,
|
||||
run `node e2e/settings-save.cjs http://127.0.0.1:5173`. Playwright intercepts the
|
||||
API in the browser; this check needs neither sign-in nor a running backend.
|
||||
Set `CHROME_BIN` to use an installed Chromium instead of Playwright's browser.
|
||||
|
||||
## Single-binary smoke check
|
||||
|
||||
Point this check at an already running, disposable `archie` instance with its
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
// An isolated catalogue entry keeps the check independent of the live source.
|
||||
await page.route('**/api/extensions/catalogue', route => route.fulfill({ json: [{
|
||||
name: 'preview-extension', display_name: 'Preview extension', description: 'An extension to preview.',
|
||||
contract: 'workflow', group: 'platform', latest: '1.0.0', default_version: '1.0.0',
|
||||
versions: [{ version: '1.0.0', digest: 'preview-digest', registered: true, settings: [] }],
|
||||
}] }));
|
||||
await page.setViewportSize({ width: 390, height: 600 });
|
||||
await go('/settings/extensions?tab=marketplace');
|
||||
const opener = page.getByRole('button', { name: 'Details for Preview extension' });
|
||||
const preview = page.getByRole('dialog', { name: 'Preview extension' });
|
||||
const version = preview.getByRole('combobox', { name: 'Version' });
|
||||
const close = preview.getByRole('button', { name: 'Close' });
|
||||
|
||||
await opener.click();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
assert.ok(await version.evaluate(el => el === document.activeElement));
|
||||
await shot('version-focus');
|
||||
const { clearance, ring } = await version.evaluate(el => {
|
||||
let scroll = el.parentElement;
|
||||
while (getComputedStyle(scroll).overflowY !== 'auto') scroll = scroll.parentElement;
|
||||
const bounds = scroll.getBoundingClientRect();
|
||||
const field = el.getBoundingClientRect();
|
||||
const css = getComputedStyle(el);
|
||||
return {
|
||||
clearance: Math.min(field.left - bounds.left, bounds.left + scroll.clientWidth - field.right),
|
||||
ring: Math.max(3, parseFloat(css.outlineWidth) + parseFloat(css.outlineOffset)),
|
||||
};
|
||||
});
|
||||
assert.ok(clearance + 0.1 >= ring, `Version focus ring: ${clearance}px clearance for ${ring}px ring`);
|
||||
|
||||
await page.keyboard.press('Space');
|
||||
const options = page.getByRole('listbox');
|
||||
await options.waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await options.waitFor({ state: 'hidden' });
|
||||
await preview.waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await preview.waitFor({ state: 'detached' });
|
||||
assert.ok(await opener.evaluate(el => el === document.activeElement));
|
||||
|
||||
await opener.click();
|
||||
await close.click();
|
||||
await preview.waitFor({ state: 'detached' });
|
||||
assert.ok(await opener.evaluate(el => el === document.activeElement));
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const org = { id: 'example-org', name: 'Example', version: 1 };
|
||||
const user = { id: '11111111-1111-4111-8111-111111111111', name: 'Alex Rivera', kind: 'user' };
|
||||
const other = { id: '22222222-2222-4222-8222-222222222222', name: user.name, kind: 'user' };
|
||||
const bot = { id: '33333333-3333-4333-8333-333333333333', name: 'Nightly bot', kind: 'bot' };
|
||||
const missing = { id: '44444444-4444-4444-8444-444444444444' };
|
||||
const target = { id: '55555555-5555-4555-8555-555555555555', name: 'Riley Singh', kind: 'user' };
|
||||
|
||||
const member = (actor) => ({
|
||||
identity_id: actor.id, display_name: actor.name, kind: actor.kind, role: 'viewer', status: 'active',
|
||||
});
|
||||
|
||||
// An audit actor link must resolve the exact user, not another member with the same name.
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
const at = new Date().toISOString();
|
||||
const records = [user, bot, missing].map((actor, i) => ({
|
||||
id: `audit-${i}`, at, category: 'runtime', kind: 'task', action: 'task.retry', severity: 'info', outcome: 'success',
|
||||
actor, summary: `Task audit ${i}`,
|
||||
target: i === 1 ? { kind: 'identity', id: target.id, label: target.name } : { kind: 'task', id: String(i + 1) },
|
||||
}));
|
||||
await page.route('**/api/**', async (route) => {
|
||||
const { pathname: path, searchParams } = new URL(route.request().url());
|
||||
const version = Number(searchParams.get('version')) || 2;
|
||||
const fixtures = {
|
||||
'/api/auth/status': { user: { id: 'operator', display_name: 'Operator' }, setup_required: false },
|
||||
'/api/capabilities': { sections: { settings: false } },
|
||||
'/api/orgs': { current: org.id, orgs: [org] },
|
||||
[`/api/orgs/${org.id}/members`]: { members: [member(user), { ...member(other), status: 'suspended' }, member(target)] },
|
||||
[`/api/orgs/${org.id}/member-candidates`]: { identities: [] },
|
||||
[`/api/orgs/${org.id}/history`]: { events: [{ id: 'history', kind: 'org', old_name: 'Previous', new_name: org.name, at, actor_id: user.id, actor_name: user.name }] },
|
||||
'/api/audit': { records },
|
||||
'/api/access/decisions': { decisions: [{ at, principal: user.id, outcome: 'allowed', action: 'read', kind: 'task', resource: '1', level: 'org', policies: [], count: 1 }] },
|
||||
'/api/alerts': { alerts: [] },
|
||||
'/api/proposals/example': { id: 'example', title: 'Example proposal', kind: 'policy', state: 'rejected', proposed_by_id: bot.id, answered_by_id: user.id, actions: [], created_at: at },
|
||||
'/api/runs/example': {
|
||||
run: { id: 'example', workflow: 'Example run', state: 'succeeded', created_at: at, finished_at: at }, stages: [],
|
||||
actions: [{ decision: { id: 'decision', level: 'ask', action: { connector: 'example', name: 'act' }, at, refused_by: 'policy-rule' }, approval: { state: 'approved', answered_by: user.name, answered_by_id: user.id, answered_via: 'web' } }],
|
||||
},
|
||||
'/api/approvals': [],
|
||||
'/api/policies/hard-rules': { version, body: '// example', created_at: at, created_by: user.id, versions: [{ version: 2 }, { version: 1 }] },
|
||||
'/api/policies/change-request': { version: 1, body: '', created_at: at },
|
||||
'/api/workflows': [{ id: 'workflow', name: 'Example workflow', version: 1, body: 'steps: []', created_by: user.id, created_at: at, enabled: true }],
|
||||
'/api/workflow-drafts': [],
|
||||
'/api/workflow-stats': [],
|
||||
'/api/triggers': [],
|
||||
};
|
||||
if (path === '/api/stream') return route.fulfill({ status: 200, contentType: 'text/event-stream', body: ': ready\n\n' });
|
||||
await route.fulfill({ json: fixtures[path] ?? {} });
|
||||
});
|
||||
await go('/org/audit');
|
||||
await page.getByText(user.name, { exact: true }).filter({ visible: true }).waitFor();
|
||||
const link = page.getByRole('link', { name: user.name, exact: true });
|
||||
assert.equal(await link.count(), 1, 'the visible audit user name should be a link');
|
||||
assert.equal(await page.getByRole('link', { name: bot.name, exact: true }).count(), 0);
|
||||
assert.equal(await page.getByRole('link', { name: missing.id, exact: true }).count(), 0);
|
||||
const targetLink = page.getByRole('link', { name: target.name, exact: true });
|
||||
const targetHref = await targetLink.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
assert.equal(targetHref && new URL(targetHref, page.url()).searchParams.get('member'), target.id, 'an audit identity target should link to its user');
|
||||
await shot('audit-actor');
|
||||
await link.click();
|
||||
await page.waitForURL((url) => url.pathname === '/org/members' && url.searchParams.get('member') === user.id);
|
||||
await page.getByRole('heading', { name: 'Members' }).waitFor();
|
||||
const row = page.getByRole('row').filter({ hasText: user.name });
|
||||
await row.first().waitFor();
|
||||
assert.equal(await row.count(), 1);
|
||||
assert.match(await row.innerText(), /\bactive\b/);
|
||||
await shot('target-member');
|
||||
await page.getByRole('link', { name: 'All members' }).click();
|
||||
await page.getByRole('button', { name: `Suspend ${user.name}` }).waitFor();
|
||||
assert.equal(await row.count(), 2);
|
||||
await go(`/org/members?org=${org.id}&member=${missing.id}`);
|
||||
await page.getByText('Member not found in this organisation', { exact: true }).waitFor();
|
||||
|
||||
const unresolved = [];
|
||||
for (const [path, ready] of [
|
||||
['/proposals/example', () => page.getByText('Rejected by', { exact: true }).waitFor()],
|
||||
['/runs/example', () => page.getByText('Refused by policy-rule', { exact: true }).waitFor()],
|
||||
['/controls', () => page.getByRole('textbox', { name: 'Hard rules', exact: true }).waitFor()],
|
||||
['/org', () => page.getByRole('heading', { name: 'Name changes' }).waitFor()],
|
||||
['/org/decisions', () => page.getByRole('cell', { name: 'Allowed' }).waitFor()],
|
||||
['/workflows', () => page.getByRole('link', { name: 'Example workflow', exact: true }).waitFor()],
|
||||
]) {
|
||||
await go(path);
|
||||
await ready();
|
||||
const credit = page.getByRole('link', { name: user.name, exact: true });
|
||||
const href = await credit.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
if (!href || new URL(href, page.url()).searchParams.get('member') !== user.id) unresolved.push(path);
|
||||
assert.equal(await page.getByRole('link', { name: bot.id, exact: true }).count(), 0);
|
||||
assert.equal(await page.getByRole('link', { name: 'policy-rule', exact: true }).count(), 0);
|
||||
if (path === '/controls') {
|
||||
await page.getByRole('combobox', { name: 'Hard rules version' }).click();
|
||||
await page.getByRole('option', { name: 'Version 1' }).click();
|
||||
await page.getByRole('textbox', { name: 'Hard rules, version 1' }).waitFor();
|
||||
const oldHref = await credit.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
if (!oldHref || new URL(oldHref, page.url()).searchParams.get('member') !== user.id) unresolved.push('/controls (previous version)');
|
||||
}
|
||||
}
|
||||
assert.deepEqual(unresolved, [], 'attribution should display the user name linked by ID');
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, fail, shot }) => {
|
||||
const opener = page.getByRole('button', { name: 'New policy', exact: true });
|
||||
const editor = page.getByRole('dialog', { name: /New policy|draft-policy/ });
|
||||
const confirm = page.getByRole('alertdialog', { name: 'Discard unsaved changes?' });
|
||||
const id = editor.getByRole('textbox', { name: 'Policy id' });
|
||||
const cedar = editor.getByRole('textbox', { name: 'Cedar policy' });
|
||||
const dismissals = {
|
||||
Close: () => editor.getByRole('button', { name: 'Close', exact: true }).click({ timeout: 2000 }),
|
||||
Cancel: () => editor.getByRole('button', { name: 'Cancel', exact: true }).click({ timeout: 2000 }),
|
||||
Escape: () => page.keyboard.press('Escape'),
|
||||
Backdrop: () => page.mouse.click(8, 8),
|
||||
};
|
||||
const focused = (field) => field.evaluate(el => el === document.activeElement);
|
||||
const closed = async () => {
|
||||
await page.locator('[role="alertdialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
await page.locator('[role="dialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
assert.ok(await focused(opener), 'focus did not return to New policy');
|
||||
};
|
||||
const cases = async (scenario, rows, run) => {
|
||||
for (const row of rows) {
|
||||
// A failed modal must not block the next independently tested path.
|
||||
await go('/org/policies');
|
||||
try { await run(row); } catch (error) { fail(`${scenario} ${row}: ${error.message}`); }
|
||||
}
|
||||
};
|
||||
|
||||
await cases('Mobile', ['focus clearance'], async () => {
|
||||
await page.setViewportSize({ width: 390, height: 600 });
|
||||
await opener.click();
|
||||
for (const field of [id, cedar]) {
|
||||
// Opening focuses the ID; Tab past the level selector to reach Cedar.
|
||||
if (field === cedar) {
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Tab');
|
||||
}
|
||||
assert.ok(await focused(field), 'keyboard focus did not reach the policy field');
|
||||
const { name, clearance, ring } = await field.evaluate(el => {
|
||||
const form = el.closest('form');
|
||||
const bounds = form.getBoundingClientRect();
|
||||
const field = el.getBoundingClientRect();
|
||||
const css = getComputedStyle(el);
|
||||
return {
|
||||
name: el.getAttribute('aria-label'),
|
||||
clearance: Math.min(field.left - bounds.left, field.top - bounds.top,
|
||||
bounds.left + form.clientWidth - field.right, bounds.top + form.clientHeight - field.bottom),
|
||||
ring: Math.max(3, parseFloat(css.outlineWidth) + parseFloat(css.outlineOffset)),
|
||||
};
|
||||
});
|
||||
if (clearance + 0.1 < ring) fail(`${name} focus ring: ${clearance}px clearance for ${ring}px ring`);
|
||||
await shot(name);
|
||||
}
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
|
||||
await cases('Clean', Object.keys(dismissals), async (action) => {
|
||||
await opener.click();
|
||||
await dismissals[action]();
|
||||
await closed();
|
||||
});
|
||||
|
||||
await cases('Dirty', Object.keys(dismissals), async (action) => {
|
||||
await opener.click();
|
||||
await id.pressSequentially('draft-policy');
|
||||
await dismissals[action]();
|
||||
const keep = confirm.getByRole('button', { name: 'Keep editing' });
|
||||
await keep.waitFor({ timeout: 2000 });
|
||||
if (action === 'Escape') await page.keyboard.press('Escape');
|
||||
else await keep.click({ timeout: 2000 });
|
||||
await page.locator('[role="alertdialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
assert.equal(await id.inputValue(), 'draft-policy');
|
||||
assert.ok(await editor.evaluate(el => el.contains(document.activeElement)), 'focus did not return to the editor');
|
||||
await dismissals[action]();
|
||||
await confirm.getByRole('button', { name: 'Discard changes' }).click({ timeout: 2000 });
|
||||
await closed();
|
||||
await opener.click();
|
||||
assert.equal(await id.inputValue(), '', 'discarded policy reappeared on reopen');
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const waiting = {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
title: 'Correct the workflow',
|
||||
kind: 'workflow_change',
|
||||
state: 'pending',
|
||||
needs: 'owner',
|
||||
actions: [],
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
// Keep the last successful result and protect its tab from competing reads.
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
const now = new Date();
|
||||
await page.clock.install({ time: now });
|
||||
await page.clock.pauseAt(new Date(now.getTime() + 60_000));
|
||||
tolerate(/503.*\/api\/proposals/);
|
||||
|
||||
const pendingURL = '**/api/proposals?state=pending';
|
||||
let current = waiting;
|
||||
let failNext;
|
||||
await page.route(pendingURL, async route => {
|
||||
if (failNext) {
|
||||
const failing = failNext;
|
||||
failNext = undefined;
|
||||
await failing;
|
||||
await route.fulfill({ status: 503, contentType: 'application/problem+json', json: { detail: 'Could not refresh proposals' } });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ json: [current] });
|
||||
});
|
||||
|
||||
await go('/proposals');
|
||||
const proposal = page.getByRole('link', { name: waiting.title, exact: true });
|
||||
const sort = page.getByRole('columnheader', { name: 'Proposal', exact: true });
|
||||
await proposal.waitFor();
|
||||
await sort.getByRole('button').press('Enter');
|
||||
await proposal.focus();
|
||||
|
||||
const failure = Promise.withResolvers();
|
||||
failNext = failure.promise;
|
||||
const refresh = page.waitForRequest(pendingURL);
|
||||
await page.clock.runFor(5000);
|
||||
await refresh;
|
||||
assert.equal(await proposal.isVisible(), true, 'the row should stay visible during a refresh');
|
||||
failure.resolve();
|
||||
|
||||
const error = page.getByRole('alert').filter({ hasText: 'Could not refresh proposals' });
|
||||
await error.waitFor();
|
||||
assert.equal(await proposal.isVisible(), true, 'a failed refresh must not replace the table');
|
||||
assert.equal(await sort.getAttribute('aria-sort'), 'ascending', 'the table should keep the operator’s sort');
|
||||
assert.equal(await proposal.evaluate(link => link === document.activeElement), true, 'the row should keep keyboard focus');
|
||||
await shot('failed-refresh-retains-table');
|
||||
|
||||
current = { ...waiting, title: 'Workflow correction updated' };
|
||||
await error.getByRole('button', { name: 'Retry' }).click();
|
||||
await page.getByRole('link', { name: current.title, exact: true }).waitFor();
|
||||
await error.waitFor({ state: 'hidden' });
|
||||
assert.equal(await sort.getAttribute('aria-sort'), 'ascending');
|
||||
|
||||
// A failed read belongs to its filter, not to the newly selected tab.
|
||||
failNext = Promise.resolve();
|
||||
await page.clock.runFor(5000);
|
||||
await error.waitFor();
|
||||
const published = Promise.withResolvers();
|
||||
await page.route('**/api/proposals?state=published', async route => {
|
||||
await published.promise;
|
||||
await route.fulfill({ json: [] });
|
||||
});
|
||||
const publishedTab = page.getByRole('tab', { name: 'Published' });
|
||||
await publishedTab.click();
|
||||
const loading = page.getByRole('status', { name: 'Loading proposals' });
|
||||
assert.equal(await loading.isVisible(), true, 'a new tab must not inherit the previous tab’s error');
|
||||
assert.equal(await error.isVisible(), false);
|
||||
assert.equal(await page.getByRole('table').count(), 0, 'rows from the previous tab must not appear');
|
||||
published.resolve();
|
||||
const empty = page.getByText('No proposals', { exact: true });
|
||||
await empty.waitFor();
|
||||
|
||||
// A slow read must still take effect after a background poll ticks.
|
||||
const slow = Promise.withResolvers();
|
||||
const stale = Promise.withResolvers();
|
||||
let first = true;
|
||||
await page.route(pendingURL, async route => {
|
||||
const read = first ? slow : stale;
|
||||
first = false;
|
||||
await read.promise;
|
||||
await route.fulfill({ json: [waiting] });
|
||||
});
|
||||
const switched = page.waitForRequest(pendingURL);
|
||||
await page.getByRole('tab', { name: 'Waiting' }).click();
|
||||
await switched;
|
||||
await page.clock.runFor(5000);
|
||||
slow.resolve();
|
||||
await proposal.waitFor({ timeout: 3000 }).catch(() => {
|
||||
assert.fail('a slow read must render its result even after a background poll ticks');
|
||||
});
|
||||
|
||||
// A late response for Waiting cannot replace the Published result.
|
||||
const nextPoll = page.waitForRequest(pendingURL);
|
||||
await page.clock.runFor(5000);
|
||||
await nextPoll;
|
||||
await publishedTab.click();
|
||||
await empty.waitFor();
|
||||
const response = page.waitForResponse(pendingURL);
|
||||
stale.resolve();
|
||||
await (await response).finished();
|
||||
await page.clock.runFor(50);
|
||||
assert.equal(await proposal.isVisible(), false, 'a response for the previous tab must not replace the current one');
|
||||
assert.equal(await empty.isVisible(), true);
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
// Run against local Vite only: node e2e/settings-save.cjs [http://127.0.0.1:5173]
|
||||
// Every API request is intercepted; no real settings can be changed.
|
||||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
const { chromium } = require('playwright');
|
||||
|
||||
const base = new URL(process.argv[2] ?? 'http://127.0.0.1:5173');
|
||||
assert.equal(base.hostname, '127.0.0.1', 'use a local Vite server');
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
|
||||
async function scenario(t, path) {
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_BIN });
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const provider = { id, name: 'Example', class: 'openai', base_url: 'https://provider.example' };
|
||||
const saved = {
|
||||
'/api/settings/agent-models': { default: { provider_id: id, model: 'original' } },
|
||||
'/api/settings/model-providers': [provider],
|
||||
'/api/settings/model-classes': [{ class: 'openai' }],
|
||||
'/api/settings/model-policy': { workflow_aliases: null, chat_aliases: null },
|
||||
'/api/settings/instructions': { text: 'Original instructions' },
|
||||
};
|
||||
const moduleWrites = {
|
||||
'/api/settings/agent-model': (body) => (saved['/api/settings/agent-models'].default = body),
|
||||
[`/api/settings/model-providers/${id}`]: (body) => Object.assign(provider, body),
|
||||
'/api/settings/model-policy': (body) => (saved['/api/settings/model-policy'] = body),
|
||||
'/api/settings/instructions': (body) => (saved['/api/settings/instructions'] = { text: body.text.trim() }),
|
||||
'/api/settings/agent-model/test': (body) => ({ model: body.model, answer: 'Ready' }),
|
||||
};
|
||||
const writes = [];
|
||||
const failed = new Set();
|
||||
const legacy = [];
|
||||
await page.route('**/*', async (r) => {
|
||||
const request = r.request();
|
||||
const url = new URL(request.url());
|
||||
if (url.origin !== base.origin) return r.abort();
|
||||
const path = url.pathname;
|
||||
if (!path.startsWith('/api/')) return r.continue();
|
||||
if (path.startsWith('/api/control-plane/')) legacy.push(path);
|
||||
if (request.method() !== 'GET') {
|
||||
const body = request.postDataJSON();
|
||||
writes.push([request.method(), path, body]);
|
||||
if (failed.delete(path)) {
|
||||
return r.fulfill({ status: 503, contentType: 'application/problem+json', body: '{"detail":"Save temporarily unavailable"}' });
|
||||
}
|
||||
if (moduleWrites[path]) return r.fulfill({ json: moduleWrites[path](body) });
|
||||
return r.fulfill({ status: 404 });
|
||||
}
|
||||
const context = {
|
||||
'/api/auth/status': { setup_required: false, user: { id: 'u', display_name: 'Operator', kind: 'operator' }, instance: 'archie' },
|
||||
'/api/authentication': { public_url: base.origin, oidc_issuer: '', oidc_client_id: '', oidc_audience: '', trusted_proxies: [] },
|
||||
'/api/capabilities': { sections: { chat: false } },
|
||||
'/api/orgs': { orgs: [{ id: 'test', name: 'Test', role: 'owner', version: 1 }], current: 'test', instance_admin: true },
|
||||
'/api/alerts': { alerts: [] },
|
||||
'/api/credentials': [],
|
||||
};
|
||||
return r.fulfill({ json: saved[path] ?? context[path] ?? {} });
|
||||
});
|
||||
await page.goto(new URL(path, base).href);
|
||||
return { page, writes, failed, saved, legacy };
|
||||
}
|
||||
|
||||
async function review(page) {
|
||||
await page.getByRole('button', { name: 'Review and save', exact: true }).click({ timeout: 3500 });
|
||||
return page.getByRole('dialog');
|
||||
}
|
||||
|
||||
test('Models reviews only staged edits and retries only the unfinished writes', async (t) => {
|
||||
const { page, writes, failed, legacy } = await scenario(t, '/settings/models');
|
||||
const alias = page.locator('#model-default');
|
||||
await alias.fill('new-model');
|
||||
await page.getByRole('button', { name: /Example/ }).click();
|
||||
await page.getByLabel('Name for Example').fill('Renamed');
|
||||
await page.getByLabel('Aliases workflows may use').fill('default');
|
||||
await page.getByLabel('Aliases chat may use').fill('default');
|
||||
const nav = page.getByRole('navigation', { name: 'Instance', exact: true });
|
||||
await nav.getByRole('link', { name: 'Authentication', exact: true }).click();
|
||||
await nav.getByRole('link', { name: 'Models', exact: true }).click();
|
||||
assert.equal(await alias.inputValue(), 'new-model');
|
||||
const dialog = await review(page);
|
||||
await dialog.getByText('new-model', { exact: false }).waitFor();
|
||||
await dialog.getByText('Renamed', { exact: false }).waitFor();
|
||||
await dialog.getByRole('button', { name: 'Revert chat', exact: true }).click();
|
||||
assert.deepEqual(writes, [], 'editing and opening the review must not write');
|
||||
|
||||
const providerPath = `/api/settings/model-providers/${id}`;
|
||||
failed.add(providerPath);
|
||||
const confirm = dialog.getByRole('button', { name: 'Save', exact: true });
|
||||
await confirm.click();
|
||||
await dialog.getByText('Save temporarily unavailable').waitFor();
|
||||
const aliasWrite = ['PUT', '/api/settings/agent-model', { provider_id: id, model: 'new-model' }];
|
||||
const providerWrite = ['PUT', providerPath, { name: 'Renamed', class: 'openai', base_url: 'https://provider.example' }];
|
||||
const policyWrite = ['PUT', '/api/settings/model-policy', { workflow_aliases: ['default'], chat_aliases: null }];
|
||||
assert.deepEqual(writes, [aliasWrite, providerWrite], 'stop after the rejected write');
|
||||
assert.equal(await dialog.getByText('new-model', { exact: false }).count(), 0, 'successful alias is no longer staged');
|
||||
await confirm.click();
|
||||
await dialog.waitFor({ state: 'hidden' });
|
||||
assert.deepEqual(writes, [aliasWrite, providerWrite, providerWrite, policyWrite]);
|
||||
assert.deepEqual(legacy, []);
|
||||
});
|
||||
|
||||
test('Testing a model runs immediately without saving its draft', async (t) => {
|
||||
const { page, writes } = await scenario(t, '/settings/models');
|
||||
await page.locator('#model-default').fill('try-this');
|
||||
await page.getByRole('button', { name: 'Test', exact: true }).click();
|
||||
await page.getByText('try-this answered “Ready”').waitFor();
|
||||
const dialog = await review(page);
|
||||
await dialog.getByText('After: try-this').waitFor();
|
||||
assert.deepEqual(writes, [['POST', '/api/settings/agent-model/test', { provider_id: id, model: 'try-this' }]]);
|
||||
});
|
||||
|
||||
test('Instructions can be discarded or retried from the review', async (t) => {
|
||||
const { page, writes, saved, failed, legacy } = await scenario(t, '/org/instructions');
|
||||
const text = page.getByRole('textbox', { name: 'Instructions' });
|
||||
await text.fill('Discard me');
|
||||
let dialog = await review(page);
|
||||
await dialog.getByText('Discard me', { exact: false }).waitFor();
|
||||
await dialog.getByRole('button', { name: 'Discard all' }).click();
|
||||
assert.equal(await text.inputValue(), 'Original instructions');
|
||||
await text.fill('New instructions');
|
||||
dialog = await review(page);
|
||||
const path = '/api/settings/instructions';
|
||||
assert.deepEqual(writes, [], 'discard and review do not write');
|
||||
const confirm = dialog.getByRole('button', { name: 'Save', exact: true });
|
||||
saved[path].text = 'Changed in another tab';
|
||||
await confirm.click();
|
||||
await dialog.getByText('Changed elsewhere. Latest values loaded.').waitFor();
|
||||
await dialog.getByText('Changed in another tab').waitFor();
|
||||
assert.deepEqual(writes, [], 'a newer value needs another review before it is overwritten');
|
||||
failed.add(path);
|
||||
await confirm.click();
|
||||
await dialog.getByText('Save temporarily unavailable').waitFor();
|
||||
const command = ['PUT', path, { text: 'New instructions' }];
|
||||
assert.deepEqual(writes, [command]);
|
||||
await confirm.click();
|
||||
await dialog.waitFor({ state: 'hidden' });
|
||||
assert.deepEqual(writes, [command, command]);
|
||||
assert.equal(saved[path].text, 'New instructions');
|
||||
assert.deepEqual(legacy, []);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { Undo2 } from "@lucide/vue";
|
||||
import ChangeList from "@/components/ChangeList.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import {
|
||||
changesFromFields,
|
||||
metadataRows,
|
||||
@@ -25,8 +26,9 @@ const href = computed(() => targetHref(props.record.target));
|
||||
<ChangeList v-if="changes.length" :changes="changes" :revertable="false" />
|
||||
<MetadataList v-if="rows.length" :rows="rows">
|
||||
<template #value="{ row }">
|
||||
<UserReference v-if="row.key === 'target' && record.target?.kind === 'identity'" :id="record.target.id" :name="record.target.label" />
|
||||
<RouterLink
|
||||
v-if="row.key === 'target' && href"
|
||||
v-else-if="row.key === 'target' && href"
|
||||
:to="href"
|
||||
class="hover:underline"
|
||||
>{{ row.value }}</RouterLink>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
@@ -474,23 +475,27 @@ async function saveRetention(): Promise<void> {
|
||||
</div>
|
||||
<p class="mt-0.5 text-caption text-fg-subtle sm:hidden">
|
||||
<template v-if="hasTarget(row.target)">
|
||||
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
|
||||
<UserReference v-if="row.target.kind === 'identity'" :id="row.target.id" :name="row.target.label" />
|
||||
<RouterLink v-else-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
|
||||
<span v-else>{{ row.target.label || row.target.id }}</span>
|
||||
·
|
||||
</template>
|
||||
<span>{{ row.actor.name || row.actor.id }}</span>
|
||||
<UserReference :id="row.actor.id" :name="row.actor.name" :kind="row.actor.kind" />
|
||||
·
|
||||
<Timestamp :at="row.at" />
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
<template #cell-target="{ row }">
|
||||
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
|
||||
<span v-else>{{ row.target?.label || row.target?.id }}</span>
|
||||
<span class="block text-caption text-fg-subtle">{{ targetDetail(row.target) }}</span>
|
||||
<UserReference v-if="row.target?.kind === 'identity'" :id="row.target.id" :name="row.target.label" />
|
||||
<template v-else>
|
||||
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
|
||||
<span v-else>{{ row.target?.label || row.target?.id }}</span>
|
||||
<span class="block text-caption text-fg-subtle">{{ targetDetail(row.target) }}</span>
|
||||
</template>
|
||||
</template>
|
||||
<template #cell-actor="{ row }">
|
||||
<span>{{ row.actor.name || row.actor.id }}</span>
|
||||
<UserReference :id="row.actor.id" :name="row.actor.name" :kind="row.actor.kind" />
|
||||
<span class="block text-caption text-fg-subtle">{{ row.actor.kind }}</span>
|
||||
</template>
|
||||
<template #cell-when="{ row }"><Timestamp :at="row.at" /></template>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { useDecisionsStore } from "@/stores/decisions";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { decisionResource, type AccessDecision } from "./decisions";
|
||||
|
||||
const store = useDecisionsStore();
|
||||
@@ -81,7 +82,7 @@ onMounted(() => void store.load());
|
||||
<Badge :variant="row.outcome === 'allowed' ? 'ok' : 'danger'">{{ row.outcome === "allowed" ? "Allowed" : "Denied" }}</Badge>
|
||||
</template>
|
||||
<template #cell-action="{ row }"><span class="font-mono text-caption">{{ row.action }}</span></template>
|
||||
<template #cell-principal="{ row }"><span class="font-mono text-caption">{{ row.principal }}</span></template>
|
||||
<template #cell-principal="{ row }"><UserReference :id="row.principal" class="text-caption" /></template>
|
||||
<template #cell-resource="{ row }"><span class="font-mono text-caption">{{ decisionResource(row) }}</span></template>
|
||||
<template #cell-level="{ row }"><Badge variant="idle">{{ row.level }}</Badge></template>
|
||||
<template #cell-policies="{ row }">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { onMounted } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
@@ -21,15 +22,15 @@ onMounted(reload);
|
||||
<p v-if="data.tightened_because">Tightened <Timestamp :at="data.tightened_at" />: {{ data.tightened_because }}</p>
|
||||
<ul v-if="data.autonomy_proposals?.length" class="space-y-0.5">
|
||||
<li v-for="p in data.autonomy_proposals" :key="p.id">
|
||||
Autonomy proposal {{ p.from }} → {{ p.to }}, {{ p.state }}<template v-if="p.answered_by"> by {{ p.answered_by }}</template>, proposed <Timestamp :at="p.proposed_at" />
|
||||
Autonomy proposal {{ p.from }} → {{ p.to }}, {{ p.state }}<template v-if="p.answered_by || p.answered_by_id"> by <UserReference :id="p.answered_by_id" :name="p.answered_by" /></template>, proposed <Timestamp :at="p.proposed_at" />
|
||||
</li>
|
||||
</ul>
|
||||
<ul v-if="data.resets?.length" class="space-y-0.5">
|
||||
<li v-for="r in data.resets" :key="r.at">Reset {{ r.from }} → {{ r.to }} by {{ r.by }} <Timestamp :at="r.at" /></li>
|
||||
<li v-for="r in data.resets" :key="r.at">Reset {{ r.from }} → {{ r.to }} by <UserReference :id="r.by" /> <Timestamp :at="r.at" /></li>
|
||||
</ul>
|
||||
<ul v-if="data.history?.length" class="space-y-0.5">
|
||||
<li v-for="h in data.history" :key="h.at + (h.run_id ?? '')">
|
||||
<Timestamp :at="h.at" /> · {{ h.level }}<template v-if="h.target"> · {{ h.target }}</template><template v-if="h.answered_by"> · answered by {{ h.answered_by }}</template><template v-if="h.refused_by"> · refused by {{ h.refused_by }}</template>
|
||||
<Timestamp :at="h.at" /> · {{ h.level }}<template v-if="h.target"> · {{ h.target }}</template><template v-if="h.answered_by || h.answered_by_id"> · answered by <UserReference :id="h.answered_by_id" :name="h.answered_by" /></template><template v-if="h.refused_by"> · refused by {{ h.refused_by }}</template>
|
||||
<template v-if="h.run_id"> · <RouterLink class="underline" :to="`/runs/${h.run_id}`">run</RouterLink></template>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type PolicyKind } from "@/lib/api";
|
||||
import { useRead } from "@/lib/use-read";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
|
||||
/** One Cedar rule set: the current text, edited in place and published as a
|
||||
* new version, and the versions before it, read-only. */
|
||||
@@ -78,13 +79,13 @@ function discard(): void {
|
||||
<template v-else-if="viewingOld">
|
||||
<ReadError v-if="old.error.value" :message="old.error.value" retry-label="Retry" @retry="old.reload" />
|
||||
<p v-if="old.data.value" class="mb-2 text-caption text-fg-muted">
|
||||
<Timestamp :at="old.data.value.created_at" /><template v-if="old.data.value.created_by"> by {{ old.data.value.created_by }}</template>
|
||||
<Timestamp :at="old.data.value.created_at" /><template v-if="old.data.value.created_by"> by <UserReference :id="old.data.value.created_by" /></template>
|
||||
</p>
|
||||
<Textarea :model-value="old.data.value?.body ?? ''" readonly class="min-h-60 font-mono" :aria-label="`${title}, version ${picked}`" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="mb-2 text-caption text-fg-muted">
|
||||
<Timestamp :at="latest.data.value.created_at" /><template v-if="latest.data.value.created_by"> by {{ latest.data.value.created_by }}</template>
|
||||
<Timestamp :at="latest.data.value.created_at" /><template v-if="latest.data.value.created_by"> by <UserReference :id="latest.data.value.created_by" /></template>
|
||||
</p>
|
||||
<Textarea v-model="text" class="min-h-60 font-mono" spellcheck="false" :aria-label="title" />
|
||||
<div class="mt-2 flex flex-wrap items-center justify-end gap-2">
|
||||
|
||||
@@ -209,7 +209,7 @@ onMounted(load);
|
||||
<DialogTitle>{{ draft.id || "New policy" }}</DialogTitle>
|
||||
<DialogDescription>Set the policy scope and Cedar expression.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form id="policy-editor" class="min-h-0 flex-1 space-y-3 overflow-y-auto pr-1" @submit.prevent="save">
|
||||
<form id="policy-editor" class="min-h-0 flex-1 space-y-3 overflow-y-auto p-1" @submit.prevent="save">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Input v-model="draft.id" :readonly="editingExisting" placeholder="policy id" aria-label="Policy id" class="w-56" />
|
||||
<Select v-model="draft.level">
|
||||
@@ -256,7 +256,8 @@ onMounted(load);
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Keep editing</AlertDialogCancel>
|
||||
<AlertDialogAction @click="confirmDiscard">Discard changes</AlertDialogAction>
|
||||
<!-- The controlled discard action must consume the callback before closing the alert. -->
|
||||
<Button type="button" @click="confirmDiscard">Discard changes</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
@@ -5,8 +5,8 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import CreateAccount from "@/accounts/CreateAccount.vue";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { Pause, Play, Plus, Trash2 } from "@lucide/vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -34,6 +34,7 @@ import { api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
import { ROLE_LABELS, ROLES, type Candidate, type Member, type Role } from "./org";
|
||||
import UserReference from "./UserReference.vue";
|
||||
|
||||
/**
|
||||
* The org's members and the role each holds. A membership is org-wide, or
|
||||
@@ -46,7 +47,15 @@ const error = ref("");
|
||||
const loading = ref(true);
|
||||
const busy = ref("");
|
||||
const identities = useOrgStore();
|
||||
const { org } = storeToRefs(identities);
|
||||
const route = useRoute();
|
||||
const selected = computed(() => typeof route.query.member === "string" ? route.query.member : "");
|
||||
const focused = computed(() => !!selected.value);
|
||||
const org = computed(() => selected.value && typeof route.query.org === "string"
|
||||
? identities.orgs.find((entry) => entry.id === route.query.org)
|
||||
: identities.org);
|
||||
const visibleMembers = computed(() => selected.value
|
||||
? members.value.filter((member) => member.identity_id === selected.value && member.kind === "user")
|
||||
: members.value);
|
||||
|
||||
const picked = ref("");
|
||||
const pickedRole = ref<Role>("viewer");
|
||||
@@ -54,34 +63,37 @@ const pickedRole = ref<Role>("viewer");
|
||||
// subject. They sign in as this role once the provider vouches for them.
|
||||
const person = ref("");
|
||||
const personRole = ref<Role>("viewer");
|
||||
const pending = ref<Member | null>(null);
|
||||
|
||||
let loadRevision = 0;
|
||||
async function load(): Promise<void> {
|
||||
if (!org.value) return;
|
||||
const id = org.value.id;
|
||||
const revision = ++loadRevision;
|
||||
try {
|
||||
const id = org.value.id;
|
||||
const [list, offered] = await Promise.all([
|
||||
api.orgMembers<{ members: Member[] }>(id),
|
||||
api.orgMemberCandidates<{ identities: Candidate[] }>(id),
|
||||
identities.readMembers(id, true),
|
||||
focused.value ? null : api.orgMemberCandidates<{ identities: Candidate[] }>(id),
|
||||
]);
|
||||
if (org.value?.id !== id) return;
|
||||
members.value = list.members;
|
||||
candidates.value = offered.identities;
|
||||
if (revision !== loadRevision) return;
|
||||
members.value = list;
|
||||
candidates.value = offered?.identities ?? [];
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
if (revision === loadRevision) error.value = describeError(cause, errors.common.unknown);
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await identities.loadOrg();
|
||||
await load();
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
watch([() => org.value?.id, focused], async ([id, isFocused]) => {
|
||||
if (!id) loadRevision++;
|
||||
members.value = [];
|
||||
candidates.value = [];
|
||||
pending.value = null;
|
||||
error.value = "";
|
||||
loading.value = !!id;
|
||||
await load();
|
||||
if (org.value?.id === id && focused.value === isFocused) loading.value = false;
|
||||
}, { immediate: true });
|
||||
|
||||
async function run(key: string, action: () => Promise<void>): Promise<void> {
|
||||
busy.value = key;
|
||||
@@ -135,7 +147,6 @@ const toggleStatus = (member: Member) =>
|
||||
await load();
|
||||
});
|
||||
|
||||
const pending = ref<Member | null>(null);
|
||||
const remove = (member: Member) =>
|
||||
run(member.identity_id + (member.workspace_id ?? ""), async () => {
|
||||
if (!org.value) return;
|
||||
@@ -146,7 +157,10 @@ const remove = (member: Member) =>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Members" />
|
||||
<PageHeader title="Members">
|
||||
<span v-if="org && org.id !== identities.org?.id" class="text-label text-fg-muted">{{ org.name }}</span>
|
||||
<Button v-if="selected" as-child variant="outline" size="sm"><RouterLink :to="{ name: 'org-members' }">All members</RouterLink></Button>
|
||||
</PageHeader>
|
||||
|
||||
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
|
||||
@@ -160,16 +174,20 @@ const remove = (member: Member) =>
|
||||
<TableHead class="w-44">Role</TableHead>
|
||||
<TableHead class="w-28">Status</TableHead>
|
||||
<TableHead class="w-40">Last sign-in</TableHead>
|
||||
<TableHead class="w-28 text-right">Actions</TableHead>
|
||||
<TableHead v-if="!focused" class="w-28 text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="member in members" :key="member.identity_id + (member.workspace_id ?? '')">
|
||||
<TableCell class="font-medium">{{ member.display_name }}</TableCell>
|
||||
<TableRow v-for="member in visibleMembers" :key="member.identity_id + (member.workspace_id ?? '')">
|
||||
<TableCell class="font-medium">
|
||||
<UserReference v-if="!focused" :id="member.identity_id" :name="member.display_name" :kind="member.kind" :org-id="org?.id" />
|
||||
<template v-else>{{ member.display_name || member.identity_id }}</template>
|
||||
</TableCell>
|
||||
<TableCell class="text-fg-subtle capitalize">{{ member.kind.replace("_", " ") }}</TableCell>
|
||||
<TableCell class="font-mono text-caption text-fg-subtle">{{ member.workspace_id ?? "–" }}</TableCell>
|
||||
<TableCell>
|
||||
<Select :model-value="member.role" @update:model-value="setRole(member, $event)">
|
||||
<span v-if="focused">{{ ROLE_LABELS[member.role] }}</span>
|
||||
<Select v-else :model-value="member.role" @update:model-value="setRole(member, $event)">
|
||||
<SelectTrigger class="w-36" :aria-label="`Role for ${member.display_name}`">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -180,7 +198,7 @@ const remove = (member: Member) =>
|
||||
</TableCell>
|
||||
<TableCell><Badge :variant="member.status === 'active' ? 'ok' : 'idle'">{{ member.status }}</Badge></TableCell>
|
||||
<TableCell class="text-label text-fg-subtle"><Timestamp v-if="member.last_sign_in" :at="member.last_sign_in" /><template v-else>–</template></TableCell>
|
||||
<TableCell class="text-right">
|
||||
<TableCell v-if="!focused" class="text-right">
|
||||
<Tooltip v-if="!member.workspace_id && member.kind !== 'system'">
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
@@ -210,13 +228,13 @@ const remove = (member: Member) =>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow v-if="loading">
|
||||
<TableCell colspan="7" class="text-label text-fg-muted" role="status">Loading members…</TableCell>
|
||||
<TableCell :colspan="focused ? 6 : 7" class="text-label text-fg-muted" role="status">Loading members…</TableCell>
|
||||
</TableRow>
|
||||
<TableRow v-else-if="!members.length && !error">
|
||||
<TableCell colspan="7">
|
||||
<TableRow v-else-if="!visibleMembers.length && !error">
|
||||
<TableCell :colspan="focused ? 6 : 7">
|
||||
<Empty class="py-6">
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>No members yet</EmptyTitle>
|
||||
<EmptyTitle>{{ selected ? 'Member not found in this organisation' : 'No members yet' }}</EmptyTitle>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</TableCell>
|
||||
@@ -225,8 +243,8 @@ const remove = (member: Member) =>
|
||||
</Table>
|
||||
</Section>
|
||||
|
||||
<CreateAccount v-if="org?.id===identities.homeOrg" @created="load" />
|
||||
<div class="grid gap-4" :class="candidates.length ? 'lg:grid-cols-2' : ''">
|
||||
<CreateAccount v-if="!focused && org?.id===identities.homeOrg" @created="load" />
|
||||
<div v-if="!focused && org" class="grid gap-4" :class="candidates.length ? 'lg:grid-cols-2' : ''">
|
||||
<Section v-if="candidates.length" title="Add an identity" class="mb-0">
|
||||
<form class="flex flex-wrap items-center gap-2" @submit.prevent="add">
|
||||
<Select v-model="picked">
|
||||
|
||||
@@ -25,6 +25,7 @@ import { ApiError, api, describeError } from "@/lib/api";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import type { OrgEvent } from "./org";
|
||||
import UserReference from "./UserReference.vue";
|
||||
|
||||
/**
|
||||
* The organisation home: where each kind of organisation configuration lives,
|
||||
@@ -154,7 +155,7 @@ function describeChange(event: OrgEvent): string {
|
||||
<ul v-else class="divide-y">
|
||||
<li v-for="event in history" :key="event.id" class="flex flex-wrap items-baseline gap-x-2 gap-y-1 py-2 first:pt-0 last:pb-0">
|
||||
<span class="text-label">{{ describeChange(event) }}</span>
|
||||
<span class="text-caption text-fg-muted">by {{ event.actor_name }}</span>
|
||||
<span class="text-caption text-fg-muted">by <UserReference :id="event.actor_id" :name="event.actor_name" :org-id="org?.id" /></span>
|
||||
<Timestamp class="ml-auto text-caption text-fg-subtle" :at="event.at" />
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import UserReference from "./UserReference.vue";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
@@ -316,7 +317,7 @@ const identityColumns: DataTableColumn<IdentityRow>[] = [
|
||||
<Empty><EmptyHeader><EmptyTitle>No model calls in this range.</EmptyTitle></EmptyHeader></Empty>
|
||||
</template>
|
||||
<template #cell-identity="{ row }">
|
||||
<span :title="row.identity_id || undefined">{{ row.identity_name || "Unknown" }}</span>
|
||||
<UserReference :id="row.identity_id" :name="row.identity_name" :title="row.identity_id || undefined" fallback="Unknown" />
|
||||
</template>
|
||||
<template #cell-calls="{ row }">
|
||||
<span class="tabular-nums">{{ row.calls.toLocaleString() }}</span>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from "vue";
|
||||
import { useAccountsStore } from "@/accounts/accounts";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
|
||||
const props = defineProps<{ id?: string | null; name?: string; kind?: string; orgId?: string; fallback?: string }>();
|
||||
const org = useOrgStore();
|
||||
const accounts = useAccountsStore();
|
||||
const scope = computed(() => props.orgId || org.homeOrg);
|
||||
const recordName = computed(() => props.name === props.id ? undefined : props.name);
|
||||
|
||||
watch(() => [props.id, recordName.value, props.kind, props.orgId] as const, ([id, name, kind, orgId]) => {
|
||||
if (!id || (kind && kind !== "user")) return;
|
||||
if (!name || !kind) org.watchIdentities();
|
||||
void org.loadOrg().then(() => {
|
||||
if (!name || !kind) return org.readMembers(orgId || org.homeOrg);
|
||||
}).catch(() => { /* Without a directory, keep the attribution supplied by the record. */ });
|
||||
}, { immediate: true });
|
||||
|
||||
const identity = computed(() => org.identities.find((entry) => entry.id === props.id));
|
||||
const member = computed(() => org.membersByOrg.get(scope.value)?.find((entry) => entry.identity_id === props.id));
|
||||
const account = computed(() => accounts.status?.user?.id === props.id ? accounts.status?.user : undefined);
|
||||
const kind = computed(() => props.kind || member.value?.kind || identity.value?.kind || account.value?.kind);
|
||||
const label = computed(() => recordName.value || member.value?.display_name || identity.value?.display_name || account.value?.display_name || props.id || props.fallback);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterLink
|
||||
v-if="id && kind === 'user' && scope"
|
||||
:to="{ name: 'org-members', query: { org: scope, member: id } }"
|
||||
class="text-link underline underline-offset-2 focus-visible:outline-2 focus-visible:outline-ring"
|
||||
@click.stop
|
||||
>{{ label }}</RouterLink>
|
||||
<span v-else>{{ label }}</span>
|
||||
</template>
|
||||
@@ -21,6 +21,7 @@ import { emptyValue } from "@/lib/format";
|
||||
import { usePoll, useRead } from "@/lib/use-read";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
import { stateLabel, stateTone } from "@/runs/state";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { actionTone, approveProposal, kindLabel, proposalTone } from "./state";
|
||||
|
||||
/** A proposal with its evidence, the actions it will take and how each was
|
||||
@@ -43,8 +44,8 @@ const details = computed(() => {
|
||||
{ label: "Kind", value: kindLabel(p.kind) },
|
||||
{ label: "Approval", value: p.needs === "authority" ? "A person with authority over policies" : "The owner" },
|
||||
...(p.target_id ? [{ label: "Target", value: `${p.target_kind} ${p.target_id}` }] : []),
|
||||
{ label: "Proposed by", value: p.proposed_by_id, mono: true },
|
||||
...(p.answered_by_id ? [{ label: p.state === "rejected" ? "Rejected by" : "Approved by", value: p.answered_by_id, mono: true }] : []),
|
||||
{ label: "Proposed by", value: p.proposed_by_id, userReference: true },
|
||||
...(p.answered_by_id ? [{ label: p.state === "rejected" ? "Rejected by" : "Approved by", value: p.answered_by_id, userReference: true }] : []),
|
||||
...(p.answer_reason ? [{ label: "Reason", value: p.answer_reason }] : []),
|
||||
{ label: "Proposal", value: p.id, mono: true },
|
||||
];
|
||||
@@ -96,6 +97,7 @@ async function reject(): Promise<void> {
|
||||
<MetadataList :rows="details">
|
||||
<template #value="{ row }">
|
||||
<span v-if="row.label === 'Proposal'" class="inline-flex items-center gap-1">{{ row.value }}<CodeBlockCopyButton :value="row.value ?? ''" /></span>
|
||||
<UserReference v-else-if="'userReference' in row" :id="row.value" />
|
||||
<template v-else>{{ row.value }}</template>
|
||||
</template>
|
||||
</MetadataList>
|
||||
|
||||
@@ -15,14 +15,19 @@ import { useLiveResource } from "@/stores/session";
|
||||
import { kindLabel, proposalTone, STATES } from "./state";
|
||||
|
||||
const state = ref<ProposalState>("pending");
|
||||
const { data, error, reload } = useRead(() => api.proposals(state.value));
|
||||
const { data, error, loading, reload } = useRead(() => api.proposals(state.value));
|
||||
onMounted(reload);
|
||||
watch(state, () => {
|
||||
data.value = undefined;
|
||||
error.value = "";
|
||||
void reload();
|
||||
});
|
||||
useLiveResource(null, () => void reload());
|
||||
usePoll(reload);
|
||||
// A background refresh must not supersede a slow read for the same tab.
|
||||
function refresh(): void {
|
||||
if (!loading.value) void reload();
|
||||
}
|
||||
useLiveResource(null, refresh);
|
||||
usePoll(refresh);
|
||||
|
||||
const columns: DataTableColumn<Proposal>[] = [
|
||||
{ id: "title", label: "Proposal", fixed: true, width: "auto", sort: (p) => p.title },
|
||||
@@ -42,11 +47,11 @@ const columns: DataTableColumn<Proposal>[] = [
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</PageHeader>
|
||||
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
|
||||
<div v-else-if="!data" role="status" aria-label="Loading proposals" class="space-y-2"><Skeleton class="h-10 w-full" /><Skeleton class="h-10 w-full" /></div>
|
||||
<Empty v-else-if="!data.length"><EmptyHeader><EmptyTitle>No proposals</EmptyTitle></EmptyHeader></Empty>
|
||||
<ReadError v-if="error" :class="data && 'mb-2'" :message="error" retry-label="Retry" @retry="reload" />
|
||||
<div v-if="!data && !error" role="status" aria-label="Loading proposals" class="space-y-2"><Skeleton class="h-10 w-full" /><Skeleton class="h-10 w-full" /></div>
|
||||
<Empty v-else-if="data && !data.length"><EmptyHeader><EmptyTitle>No proposals</EmptyTitle></EmptyHeader></Empty>
|
||||
<DataTable
|
||||
v-else
|
||||
v-else-if="data"
|
||||
:columns="columns"
|
||||
:rows="data"
|
||||
:row-key="(p) => p.id"
|
||||
|
||||
@@ -18,6 +18,7 @@ import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type RunAction, type RunEntry, type RunStage } from "@/lib/api";
|
||||
import { duration, emptyValue } from "@/lib/format";
|
||||
import AgentTranscript from "@/workflows/AgentTranscript.vue";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { usePoll, useRead } from "@/lib/use-read";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
import ApprovalsSection from "./ApprovalsSection.vue";
|
||||
@@ -193,8 +194,8 @@ const result = computed(() => {
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<p v-if="action.approval?.answered_by" class="text-caption text-fg-muted">
|
||||
Answered by {{ action.approval.answered_by }}<template v-if="action.approval.answered_via"> via {{ action.approval.answered_via }}</template>
|
||||
<p v-if="action.approval?.answered_by || action.approval?.answered_by_id" class="text-caption text-fg-muted">
|
||||
Answered by <UserReference :id="action.approval.answered_by_id" :name="action.approval.answered_by" /><template v-if="action.approval.answered_via"> via {{ action.approval.answered_via }}</template>
|
||||
</p>
|
||||
<p v-if="action.rejudged" class="text-caption text-fg-muted">Judged again before it ran: {{ action.rejudged.level }}<template v-if="action.rejudged.refused_by">, refused by {{ action.rejudged.refused_by }}</template></p>
|
||||
<p v-if="action.effect?.error" class="text-caption text-danger">{{ action.effect.error }}</p>
|
||||
|
||||
@@ -63,7 +63,7 @@ const authority = computed(() => grants(selected.value?.grants));
|
||||
<DialogDescription>{{ entry?.description || "Manifest metadata and authority." }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto pr-1">
|
||||
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto p-1">
|
||||
<MetadataList :rows="entryDetails" />
|
||||
|
||||
<SettingRow v-if="entry?.versions.length" label="Version" for="catalogue-preview-version">
|
||||
|
||||
@@ -1,76 +1,57 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { Check } from "@lucide/vue";
|
||||
import { computed, onMounted, watch } from "vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { api } from "@/lib/api";
|
||||
import { useRead } from "@/lib/use-read";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
|
||||
// The server refuses more than this; it joins every agent's system prompt.
|
||||
const KIND = "org-instructions";
|
||||
const MAX_BYTES = 8192;
|
||||
const store = useSettingsStore();
|
||||
const { data, error, reload } = useRead(api.instructions);
|
||||
watch(data, (saved) => {
|
||||
if (saved === undefined) return;
|
||||
store.trackModuleSetting(KIND, {
|
||||
title: "Instructions",
|
||||
saved,
|
||||
read: api.instructions,
|
||||
write: ({ text }) => api.saveInstructions(text),
|
||||
validate: ({ text }) => new TextEncoder().encode(text).length <= MAX_BYTES ? [] : [
|
||||
{ path: "text", label: "Instructions", message: "Must be at most 8 KiB." },
|
||||
],
|
||||
});
|
||||
});
|
||||
onMounted(reload);
|
||||
|
||||
const saved = ref<string | null>(null);
|
||||
const text = ref("");
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
const justSaved = ref(false);
|
||||
|
||||
const dirty = computed(() => saved.value !== null && text.value !== saved.value);
|
||||
const draft = computed(() => store.draftValue(KIND) as { text: string } | undefined);
|
||||
const text = computed({
|
||||
get: () => draft.value?.text ?? "",
|
||||
set: (value: string) => store.setDraftValue(KIND, { text: value }),
|
||||
});
|
||||
const chars = computed(() => text.value.length);
|
||||
const tooLong = computed(() => new TextEncoder().encode(text.value).length > MAX_BYTES);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const body = await api.instructions();
|
||||
saved.value = text.value = body.text;
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, "Could not load the instructions.");
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
justSaved.value = false;
|
||||
try {
|
||||
const body = await api.saveInstructions(text.value);
|
||||
saved.value = text.value = body.text;
|
||||
justSaved.value = true;
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, "Could not save the instructions.");
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
const saveError = computed(() => store.pageErrorFor(KIND));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Instructions" />
|
||||
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<form v-if="saved !== null" @submit.prevent="save">
|
||||
<Section>
|
||||
<Textarea
|
||||
id="instructions-text"
|
||||
v-model="text"
|
||||
:rows="18"
|
||||
class="mt-1 font-mono text-label"
|
||||
aria-label="Instructions"
|
||||
:aria-invalid="tooLong"
|
||||
@input="justSaved = false"
|
||||
/>
|
||||
<p class="mt-1.5 text-caption text-fg-subtle">
|
||||
{{ chars.toLocaleString() }} chars · ~{{ Math.round(chars / 4).toLocaleString() }} tokens
|
||||
</p>
|
||||
</Section>
|
||||
<div class="mt-3 flex items-center justify-end gap-2">
|
||||
<Check v-if="justSaved" role="status" aria-label="Saved" class="size-4 text-fg-muted" />
|
||||
<Button type="submit" :disabled="busy || !dirty || tooLong">Save</Button>
|
||||
</div>
|
||||
</form>
|
||||
<Alert v-if="error || saveError" variant="destructive" class="mb-4"><AlertDescription>{{ error || saveError }}</AlertDescription></Alert>
|
||||
<Section v-if="draft">
|
||||
<Textarea
|
||||
id="instructions-text"
|
||||
v-model="text"
|
||||
:rows="18"
|
||||
class="mt-1 font-mono text-label"
|
||||
aria-label="Instructions"
|
||||
:aria-invalid="store.issuesFor(KIND).length > 0"
|
||||
:disabled="store.savingDrafts"
|
||||
/>
|
||||
<p class="mt-1.5 text-caption text-fg-subtle">
|
||||
{{ chars.toLocaleString() }} chars · ~{{ Math.round(chars / 4).toLocaleString() }} tokens
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { computed, onUnmounted, ref } from "vue";
|
||||
import { computed, onUnmounted } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -22,12 +22,11 @@ import { diffValues } from "@/lib/changes";
|
||||
import type { SettingsSchema } from "@/workflows/workflow-yaml";
|
||||
|
||||
const store = useSettingsStore();
|
||||
const { reviewing } = storeToRefs(store);
|
||||
const { reviewing, savingDrafts: saving } = storeToRefs(store);
|
||||
onUnmounted(() => { reviewing.value = false; });
|
||||
const saving = ref(false);
|
||||
|
||||
const titleOf = (kind: string) =>
|
||||
store.catalog.find((item) => item.kind === kind)?.title ?? kind;
|
||||
store.moduleTitle(kind) ?? store.catalog.find((item) => item.kind === kind)?.title ?? kind;
|
||||
function fieldLabel(kind: string, path: string): string {
|
||||
let schema: SettingsSchema;
|
||||
try { schema = JSON.parse(store.catalog.find((item) => item.kind === kind)?.schema_json || "{}"); }
|
||||
@@ -68,14 +67,9 @@ function discardAll() {
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (invalid.value.length) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const outcome = await store.saveDrafts();
|
||||
if (!outcome.failed) reviewing.value = false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
if (saving.value || invalid.value.length) return;
|
||||
const outcome = await store.saveDrafts();
|
||||
if (!outcome.failed) reviewing.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -92,7 +86,7 @@ async function save() {
|
||||
<span class="font-medium">{{ count }} unsaved settings {{ count === 1 ? "change" : "changes" }}</span>
|
||||
<span class="text-fg-subtle"> · {{ sections.map((s) => s.title).join(", ") }}</span>
|
||||
</p>
|
||||
<Button variant="ghost" size="sm" @click="discardAll">Discard</Button>
|
||||
<Button variant="ghost" size="sm" :disabled="saving" @click="discardAll">Discard</Button>
|
||||
<Button size="sm" @click="reviewing = true">Review and save</Button>
|
||||
</div>
|
||||
<ul
|
||||
@@ -113,6 +107,7 @@ async function save() {
|
||||
<SheetTitle>Review {{ count }} {{ count === 1 ? "change" : "changes" }}</SheetTitle>
|
||||
<SheetDescription>
|
||||
{{ sections.length }} {{ sections.length === 1 ? "section" : "sections" }}
|
||||
<template v-if="sections.length > 1"> · Saved separately; stops at the first failure.</template>
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div class="flex-1 space-y-3 overflow-y-auto px-4 pb-4">
|
||||
@@ -123,12 +118,13 @@ async function save() {
|
||||
<template #action>
|
||||
<div class="flex items-center gap-2">
|
||||
<Badge v-if="section.restart" variant="warn">After restart</Badge>
|
||||
<Button variant="ghost" size="sm" @click="store.resetDraft(section.kind)">Revert</Button>
|
||||
<Button variant="ghost" size="sm" :disabled="saving" @click="store.resetDraft(section.kind)">Revert</Button>
|
||||
</div>
|
||||
</template>
|
||||
<ChangeList
|
||||
:changes="section.changes"
|
||||
:label="(path) => fieldLabel(section.kind, path)"
|
||||
:revertable="!saving"
|
||||
@revert="(change) => store.revertDraftChange(section.kind, change)"
|
||||
/>
|
||||
<ul v-if="section.issues.length" class="mt-2 space-y-0.5 text-caption text-danger" role="alert">
|
||||
@@ -140,7 +136,7 @@ async function save() {
|
||||
</Section>
|
||||
</div>
|
||||
<SheetFooter class="flex-row justify-end gap-2 border-t border-border">
|
||||
<Button variant="ghost" @click="discardAll">Discard all</Button>
|
||||
<Button variant="ghost" :disabled="saving" @click="discardAll">Discard all</Button>
|
||||
<Button :disabled="saving || invalid.length > 0" @click="save">
|
||||
<Spinner v-if="saving" data-icon="inline-start" />Save</Button>
|
||||
</SheetFooter>
|
||||
|
||||
@@ -11,11 +11,13 @@ import { Label } from "@/components/ui/label";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { api, describeError, type AgentModel, type ModelProvider } from "@/lib/api";
|
||||
import { api, describeError, type AgentModel, type ModelPolicy, type ModelProvider } from "@/lib/api";
|
||||
import { useRead } from "@/lib/use-read";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import { canCreateProvider, providerInput } from "./provider-input.ts";
|
||||
|
||||
const store = useSettingsStore();
|
||||
const providers = useRead(() => api.modelProviders());
|
||||
const models = useRead(() => api.agentModels());
|
||||
const classes = useRead(() => api.modelClasses());
|
||||
@@ -37,11 +39,14 @@ const classNames = computed(() => classList.value.map((entry) => entry.class));
|
||||
const bearerCredentials = computed(() =>
|
||||
(credentials.data.value ?? []).filter((entry) => entry.kind === "bearer" && entry.scope !== "person"),
|
||||
);
|
||||
const modelMap = computed(() => models.data.value ?? {});
|
||||
|
||||
const hasModels = computed(() => models.data.value !== undefined);
|
||||
const hasProviders = computed(() => providers.data.value !== undefined);
|
||||
const policyData = computed(() => policy.data.value);
|
||||
const errorOf = (...reads: { error: { value: string } }[]) => reads.map((read) => read.error.value).find(Boolean) ?? "";
|
||||
const saveError = computed(() => store.moduleKinds
|
||||
.filter((kind) => kind.startsWith("model"))
|
||||
.map(store.pageErrorFor)
|
||||
.find(Boolean));
|
||||
|
||||
const error = ref("");
|
||||
async function run(act: () => Promise<void>): Promise<boolean> {
|
||||
@@ -60,17 +65,37 @@ interface AliasForm {
|
||||
provider_id: string;
|
||||
model: string;
|
||||
}
|
||||
const aliasEdits = ref<Record<string, AliasForm>>({});
|
||||
const addedAliases = ref<string[]>([]);
|
||||
const formOf = (model?: AgentModel): AliasForm => ({ provider_id: model?.provider_id ?? "", model: model?.model ?? "" });
|
||||
const aliasPrefix = "model-alias/";
|
||||
const aliasKind = (alias: string) => `${aliasPrefix}${alias}`;
|
||||
const storedAlias = (alias: string) => store.moduleSaved(aliasKind(alias)) as AliasForm | undefined;
|
||||
function trackAlias(alias: string, model?: AgentModel): void {
|
||||
store.trackModuleSetting(aliasKind(alias), {
|
||||
title: `Model alias: ${alias}`,
|
||||
saved: formOf(model),
|
||||
read: async () => formOf((await api.agentModels())[alias]),
|
||||
write: async (value) => formOf(await api.putAgentModel(alias === "default" ? "" : alias, value)),
|
||||
validate: (value) => [
|
||||
...(!value.provider_id ? [{ path: "provider_id", label: "Provider", message: "Select a provider." }] : []),
|
||||
...(!value.model.trim() ? [{ path: "model", label: "Model", message: "Enter a model." }] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
const trackedAliases = computed(() => store.moduleKinds
|
||||
.filter((kind) => kind.startsWith(aliasPrefix)).map((kind) => kind.slice(aliasPrefix.length)));
|
||||
watch(models.data, (rows) => {
|
||||
const next: Record<string, AliasForm> = {};
|
||||
for (const [alias, model] of Object.entries(rows ?? {})) next[alias] = aliasEdits.value[alias] ?? formOf(model);
|
||||
for (const alias of ["default", ...addedAliases.value]) next[alias] ??= aliasEdits.value[alias] ?? formOf();
|
||||
aliasEdits.value = next;
|
||||
if (!rows) return;
|
||||
for (const alias of new Set(["default", ...Object.keys(rows), ...trackedAliases.value])) trackAlias(alias, rows[alias]);
|
||||
});
|
||||
const aliases = computed(() => [...new Set(["default", ...Object.keys(models.data.value ?? {}), ...addedAliases.value])]);
|
||||
const aliasField = (alias: string): AliasForm => (aliasEdits.value[alias] ??= formOf());
|
||||
const aliases = computed(() => [...new Set(["default", ...addedAliases.value,
|
||||
...trackedAliases.value.filter((alias) => storedAlias(alias)?.model || store.changesFor(aliasKind(alias)).length),
|
||||
])]);
|
||||
const aliasField = (alias: string) => (store.draftValue(aliasKind(alias)) as AliasForm | undefined) ?? formOf();
|
||||
function editAlias(alias: string, field: keyof AliasForm, value: string): void {
|
||||
if (!hasModels.value || aliasBusy.value) return;
|
||||
store.setDraftValue(aliasKind(alias), { ...aliasField(alias), [field]: value });
|
||||
}
|
||||
const aliasBusy = ref("");
|
||||
const aliasError = ref<Record<string, string>>({});
|
||||
const tested = ref<Record<string, string>>({});
|
||||
@@ -85,13 +110,6 @@ async function aliasRun(alias: string, act: () => Promise<void>): Promise<void>
|
||||
aliasBusy.value = "";
|
||||
}
|
||||
}
|
||||
const saveAlias = (alias: string) =>
|
||||
aliasRun(alias, async () => {
|
||||
const field = aliasField(alias);
|
||||
await api.putAgentModel(alias === "default" ? "" : alias, { provider_id: field.provider_id, model: field.model });
|
||||
addedAliases.value = addedAliases.value.filter((name) => name !== alias);
|
||||
await models.reload();
|
||||
});
|
||||
const testAlias = (alias: string) =>
|
||||
aliasRun(alias, async () => {
|
||||
const field = aliasField(alias);
|
||||
@@ -100,17 +118,17 @@ const testAlias = (alias: string) =>
|
||||
});
|
||||
const removeAlias = (alias: string) =>
|
||||
aliasRun(alias, async () => {
|
||||
if (models.data.value?.[alias]) await api.deleteAgentModel(alias === "default" ? "" : alias);
|
||||
if (storedAlias(alias)?.model) await api.deleteAgentModel(alias === "default" ? "" : alias);
|
||||
addedAliases.value = addedAliases.value.filter((name) => name !== alias);
|
||||
delete aliasEdits.value[alias];
|
||||
store.forgetModuleSetting(aliasKind(alias));
|
||||
await models.reload();
|
||||
});
|
||||
const newAlias = ref("");
|
||||
function addAlias(): void {
|
||||
const name = newAlias.value.trim();
|
||||
if (!name || aliases.value.includes(name)) return;
|
||||
if (!hasModels.value || !name || aliases.value.includes(name)) return;
|
||||
trackAlias(name);
|
||||
addedAliases.value = [...addedAliases.value, name];
|
||||
aliasEdits.value = { ...aliasEdits.value, [name]: formOf() };
|
||||
newAlias.value = "";
|
||||
}
|
||||
|
||||
@@ -119,22 +137,46 @@ interface ProviderForm {
|
||||
name: string;
|
||||
class: string;
|
||||
base_url: string;
|
||||
key: string;
|
||||
api_key_credential: string;
|
||||
}
|
||||
const providerEdits = ref<Record<string, ProviderForm>>({});
|
||||
const providerForm = (provider?: ModelProvider): ProviderForm => ({
|
||||
name: provider?.name ?? "",
|
||||
class: provider?.class ?? classNames.value[0] ?? "",
|
||||
base_url: provider?.base_url ?? "",
|
||||
key: provider?.api_key_credential_id || NONE,
|
||||
const providerKind = (id: string) => `model-provider/${id}`;
|
||||
const providerForm = (provider: ModelProvider): ProviderForm => ({
|
||||
name: provider.name,
|
||||
class: provider.class,
|
||||
base_url: provider.base_url ?? "",
|
||||
api_key_credential: provider.api_key_credential_id ?? "",
|
||||
});
|
||||
function trackProvider(provider: ModelProvider): void {
|
||||
const { id } = provider;
|
||||
store.trackModuleSetting(providerKind(id), {
|
||||
title: (saved) => `Model provider: ${saved.name}`,
|
||||
saved: providerForm(provider),
|
||||
read: async () => {
|
||||
const current = (await api.modelProviders()).find((row) => row.id === id);
|
||||
if (!current) throw new Error("This provider was removed. Discard its draft.");
|
||||
return providerForm(current);
|
||||
},
|
||||
write: async (field) => providerForm(await api.putModelProvider(id, providerInput({
|
||||
name: field.name,
|
||||
class: field.class,
|
||||
base_url: field.base_url,
|
||||
api_key_credential_id: field.api_key_credential || undefined,
|
||||
}))),
|
||||
validate: (field) => !field.name.trim() ? [{ path: "name", label: "Name", message: "Enter a name." }] : [],
|
||||
});
|
||||
}
|
||||
watch(providers.data, (rows) => {
|
||||
for (const provider of rows ?? []) providerEdits.value[provider.id] ??= providerForm(provider);
|
||||
for (const provider of rows ?? []) trackProvider(provider);
|
||||
});
|
||||
const providerField = (id: string): ProviderForm => (providerEdits.value[id] ??= providerForm());
|
||||
const providerField = (id: string) => (store.draftValue(providerKind(id)) as ProviderForm | undefined) ?? providerForm(providerById.value.get(id)!);
|
||||
const storedProviderName = (provider: ModelProvider) => (store.moduleSaved(providerKind(provider.id)) as ProviderForm | undefined)?.name ?? provider.name;
|
||||
function editProvider(id: string, field: keyof ProviderForm, value: string): void {
|
||||
if (providerBusy.value) return;
|
||||
store.setDraftValue(providerKind(id), { ...providerField(id), [field]: value });
|
||||
}
|
||||
function credentialLabel(id: string): string {
|
||||
const key = providerField(id).key;
|
||||
if (key === NONE) return "no key";
|
||||
const key = providerField(id).api_key_credential;
|
||||
if (!key) return "no key";
|
||||
const found = bearerCredentials.value.find((entry) => entry.id === key);
|
||||
if (found) return found.name;
|
||||
const saved = providerById.value.get(id);
|
||||
@@ -142,35 +184,17 @@ function credentialLabel(id: string): string {
|
||||
return "missing credential";
|
||||
}
|
||||
function hasUnknownCredential(id: string): boolean {
|
||||
const key = providerField(id).key;
|
||||
return key !== NONE && !bearerCredentials.value.some((entry) => entry.id === key);
|
||||
const key = providerField(id).api_key_credential;
|
||||
return !!key && !bearerCredentials.value.some((entry) => entry.id === key);
|
||||
}
|
||||
const providerBusy = ref("");
|
||||
const saveProvider = async (id: string): Promise<void> => {
|
||||
providerBusy.value = id;
|
||||
try {
|
||||
const field = providerField(id);
|
||||
await run(async () => {
|
||||
const saved = await api.putModelProvider(id, providerInput({
|
||||
name: field.name,
|
||||
class: field.class,
|
||||
base_url: field.base_url,
|
||||
api_key_credential_id: field.key === NONE ? undefined : field.key,
|
||||
}));
|
||||
providerEdits.value[id] = providerForm(saved);
|
||||
await Promise.all([providers.reload(), models.reload()]);
|
||||
});
|
||||
} finally {
|
||||
providerBusy.value = "";
|
||||
}
|
||||
};
|
||||
const removeProvider = async (id: string): Promise<void> => {
|
||||
providerBusy.value = id;
|
||||
try {
|
||||
await run(async () => {
|
||||
await api.deleteModelProvider(id);
|
||||
delete providerEdits.value[id];
|
||||
await providers.reload();
|
||||
store.forgetModuleSetting(providerKind(id));
|
||||
});
|
||||
} finally {
|
||||
providerBusy.value = "";
|
||||
@@ -193,8 +217,7 @@ function addProvider(): void {
|
||||
const classId = newClass.value || classNames.value[0];
|
||||
if (!classId || !canCreateProvider(name, classId, newProviderBaseURL.value, newProviderDefaultBaseURL.value)) return;
|
||||
void run(async () => {
|
||||
const created = await api.createModelProvider(providerInput({ name, class: classId, base_url: newProviderBaseURL.value }));
|
||||
providerEdits.value[created.id] = providerForm(created);
|
||||
await api.createModelProvider(providerInput({ name, class: classId, base_url: newProviderBaseURL.value }));
|
||||
newProvider.value = "";
|
||||
newProviderBaseURL.value = "";
|
||||
await providers.reload();
|
||||
@@ -202,27 +225,27 @@ function addProvider(): void {
|
||||
}
|
||||
|
||||
// Policy: which aliases workflows and chat may name. Empty means any.
|
||||
const workflowText = ref("");
|
||||
const chatText = ref("");
|
||||
watch(policy.data, (current) => {
|
||||
workflowText.value = current?.workflow_aliases?.join(", ") ?? "";
|
||||
chatText.value = current?.chat_aliases?.join(", ") ?? "";
|
||||
const POLICY = "models-policy";
|
||||
const policyForm = (current: ModelPolicy) => ({
|
||||
workflows: current.workflow_aliases?.join(", ") ?? "",
|
||||
chat: current.chat_aliases?.join(", ") ?? "",
|
||||
});
|
||||
function aliasList(text: string): string[] | null {
|
||||
const list = text.split(",").map((alias) => alias.trim()).filter(Boolean);
|
||||
return list.length ? list : null;
|
||||
}
|
||||
const policyBusy = ref(false);
|
||||
async function savePolicy(): Promise<void> {
|
||||
policyBusy.value = true;
|
||||
try {
|
||||
await run(async () => {
|
||||
await api.putModelPolicy({ workflow_aliases: aliasList(workflowText.value), chat_aliases: aliasList(chatText.value) });
|
||||
await policy.reload();
|
||||
});
|
||||
} finally {
|
||||
policyBusy.value = false;
|
||||
}
|
||||
watch(policy.data, (current) => {
|
||||
if (!current) return;
|
||||
store.trackModuleSetting(POLICY, {
|
||||
title: "Model policy",
|
||||
saved: policyForm(current),
|
||||
read: async () => policyForm(await api.modelPolicy()),
|
||||
write: async ({ workflows, chat }) => policyForm(await api.putModelPolicy({ workflow_aliases: aliasList(workflows), chat_aliases: aliasList(chat) })),
|
||||
});
|
||||
});
|
||||
const policyFields = computed(() => (store.draftValue(POLICY) as ReturnType<typeof policyForm> | undefined));
|
||||
function editPolicy(field: keyof ReturnType<typeof policyForm>, value: string): void {
|
||||
if (policyFields.value) store.setDraftValue(POLICY, { ...policyFields.value, [field]: value });
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -230,28 +253,27 @@ async function savePolicy(): Promise<void> {
|
||||
<div>
|
||||
<PageHeader title="Models" />
|
||||
|
||||
<Alert v-if="error || errorOf(models, providers, classes, credentials, policy)" variant="destructive" class="mb-4">
|
||||
<AlertDescription>{{ error || errorOf(models, providers, classes, credentials, policy) }}</AlertDescription>
|
||||
<Alert v-if="error || saveError || errorOf(models, providers, classes, credentials, policy)" variant="destructive" class="mb-4">
|
||||
<AlertDescription>{{ error || saveError || errorOf(models, providers, classes, credentials, policy) }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<p v-if="!hasModels && !models.error.value" class="flex items-center gap-2 text-label text-fg-muted" role="status"><Spinner />Loading models…</p>
|
||||
|
||||
<Section v-else title="Aliases">
|
||||
<p v-if="hasModels && !modelMap.default" class="mb-3 text-label text-warn" role="alert">Set the default alias.</p>
|
||||
<Section v-else-if="hasModels" title="Aliases">
|
||||
<p v-if="!storedAlias('default')?.model" class="mb-3 text-label text-warn" role="alert">Set the default alias.</p>
|
||||
<div v-for="alias in aliases" :key="alias" class="border-b border-border py-2.5 last-of-type:border-b-0">
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<Label :for="`model-${alias}`" class="w-28 text-label font-medium @max-xl:w-full">{{ alias }}</Label>
|
||||
<Select v-model="aliasField(alias).provider_id">
|
||||
<Select :model-value="aliasField(alias).provider_id" :disabled="store.savingDrafts || !!aliasBusy" @update:model-value="(value) => editAlias(alias, 'provider_id', String(value ?? ''))">
|
||||
<SelectTrigger class="w-44 font-mono" :aria-label="`${alias} provider`"><SelectValue placeholder="provider" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="provider in providerList" :key="provider.id" :value="provider.id">{{ provider.name }}</SelectItem>
|
||||
<SelectItem v-for="provider in providerList" :key="provider.id" :value="provider.id">{{ storedProviderName(provider) }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input :id="`model-${alias}`" v-model="aliasField(alias).model" class="min-w-40 flex-1 basis-40 font-mono" placeholder="model" />
|
||||
<Input :id="`model-${alias}`" :model-value="aliasField(alias).model" :disabled="store.savingDrafts || !!aliasBusy" class="min-w-40 flex-1 basis-40 font-mono" placeholder="model" @update:model-value="(value) => editAlias(alias, 'model', String(value))" />
|
||||
<span class="ml-auto flex items-center gap-1">
|
||||
<Button variant="outline" size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider_id || !aliasField(alias).model" @click="testAlias(alias)">Test</Button>
|
||||
<Button size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider_id || !aliasField(alias).model" @click="saveAlias(alias)">Save</Button>
|
||||
<Button v-if="alias !== 'default' || modelMap[alias]" variant="ghost" size="icon" :aria-label="`Remove alias ${alias}`" :disabled="!!aliasBusy" @click="removeAlias(alias)"><Trash2 /></Button>
|
||||
<Button variant="outline" size="sm" :disabled="store.savingDrafts || !!aliasBusy || !aliasField(alias).provider_id || !aliasField(alias).model" @click="testAlias(alias)">Test</Button>
|
||||
<Button v-if="alias !== 'default' || storedAlias(alias)?.model" variant="ghost" size="icon" :aria-label="`Remove alias ${alias}`" :disabled="store.savingDrafts || !!aliasBusy || (!!storedAlias(alias)?.model && store.changesFor(aliasKind(alias)).length > 0)" @click="removeAlias(alias)"><Trash2 /></Button>
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="tested[alias]" role="status" class="pt-1.5 text-caption text-ok">{{ tested[alias] }}</p>
|
||||
@@ -259,7 +281,7 @@ async function savePolicy(): Promise<void> {
|
||||
</div>
|
||||
<form class="flex flex-wrap gap-2 border-t border-border pt-3" @submit.prevent="addAlias">
|
||||
<Input v-model="newAlias" class="max-w-56 font-mono" placeholder="alias" aria-label="New alias" />
|
||||
<Button type="submit" variant="outline" size="sm" :disabled="!newAlias.trim()"><Plus data-icon="inline-start" />Add alias</Button>
|
||||
<Button type="submit" variant="outline" size="sm" :disabled="store.savingDrafts || !newAlias.trim()"><Plus data-icon="inline-start" />Add alias</Button>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
@@ -268,7 +290,7 @@ async function savePolicy(): Promise<void> {
|
||||
<AccordionItem v-for="provider in providerList" :key="provider.id" :value="provider.id">
|
||||
<AccordionTrigger class="hover:no-underline">
|
||||
<span class="flex min-w-0 flex-1 flex-wrap items-center gap-x-3">
|
||||
<span class="w-28 text-left font-mono text-label font-medium">{{ provider.name }}</span>
|
||||
<span class="w-28 text-left font-mono text-label font-medium">{{ storedProviderName(provider) }}</span>
|
||||
<span class="font-mono text-caption text-fg-muted">{{ providerField(provider.id).class }}</span>
|
||||
<span class="min-w-0 truncate font-mono text-caption text-fg-subtle">{{ credentialLabel(provider.id) }}</span>
|
||||
</span>
|
||||
@@ -276,33 +298,32 @@ async function savePolicy(): Promise<void> {
|
||||
<AccordionContent>
|
||||
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
|
||||
<Label :for="`prov-${provider.id}-name`" class="w-28 text-label font-medium @max-xl:w-full">Name</Label>
|
||||
<Input :id="`prov-${provider.id}-name`" v-model="providerField(provider.id).name" class="max-w-md font-mono" :aria-label="`Name for ${provider.name}`" />
|
||||
<Input :id="`prov-${provider.id}-name`" :model-value="providerField(provider.id).name" class="max-w-md font-mono" :aria-label="`Name for ${storedProviderName(provider)}`" :disabled="store.savingDrafts || !!providerBusy" @update:model-value="(value) => editProvider(provider.id, 'name', String(value))" />
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
|
||||
<Label :for="`prov-${provider.id}-class`" class="w-28 text-label font-medium @max-xl:w-full">Class</Label>
|
||||
<Select v-model="providerField(provider.id).class">
|
||||
<SelectTrigger :id="`prov-${provider.id}-class`" class="w-48 font-mono" :aria-label="`Class for ${provider.name}`"><SelectValue /></SelectTrigger>
|
||||
<Select :model-value="providerField(provider.id).class" :disabled="store.savingDrafts || !!providerBusy" @update:model-value="(value) => editProvider(provider.id, 'class', String(value ?? ''))">
|
||||
<SelectTrigger :id="`prov-${provider.id}-class`" class="w-48 font-mono" :aria-label="`Class for ${storedProviderName(provider)}`"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem v-for="classId in classNames" :key="classId" :value="classId">{{ classId }}</SelectItem></SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
|
||||
<Label :for="`prov-${provider.id}-url`" class="w-28 text-label font-medium @max-xl:w-full">Base URL</Label>
|
||||
<Input :id="`prov-${provider.id}-url`" v-model="providerField(provider.id).base_url" class="max-w-md font-mono" :placeholder="classList.find((entry) => entry.class === providerField(provider.id).class)?.default_base_url || 'class default'" />
|
||||
<Input :id="`prov-${provider.id}-url`" :model-value="providerField(provider.id).base_url" class="max-w-md font-mono" :placeholder="classList.find((entry) => entry.class === providerField(provider.id).class)?.default_base_url || 'class default'" :disabled="store.savingDrafts || !!providerBusy" @update:model-value="(value) => editProvider(provider.id, 'base_url', String(value))" />
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
|
||||
<Label :for="`prov-${provider.id}-key`" class="w-28 text-label font-medium @max-xl:w-full">API key</Label>
|
||||
<Select v-model="providerField(provider.id).key">
|
||||
<SelectTrigger :id="`prov-${provider.id}-key`" class="w-56" :aria-label="`API key for ${provider.name}`"><SelectValue /></SelectTrigger>
|
||||
<Select :model-value="providerField(provider.id).api_key_credential || NONE" :disabled="store.savingDrafts || !!providerBusy" @update:model-value="(value) => editProvider(provider.id, 'api_key_credential', value === NONE ? '' : String(value ?? ''))">
|
||||
<SelectTrigger :id="`prov-${provider.id}-key`" class="w-56" :aria-label="`API key for ${storedProviderName(provider)}`"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem :value="NONE">No key</SelectItem>
|
||||
<SelectItem v-if="hasUnknownCredential(provider.id)" :value="providerField(provider.id).key" disabled>{{ credentialLabel(provider.id) }}</SelectItem>
|
||||
<SelectItem v-if="hasUnknownCredential(provider.id)" :value="providerField(provider.id).api_key_credential" disabled>{{ credentialLabel(provider.id) }}</SelectItem>
|
||||
<SelectItem v-for="credential in bearerCredentials" :key="credential.id" :value="credential.id">{{ credential.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex justify-end gap-1 pb-1">
|
||||
<Button variant="ghost" size="sm" class="text-danger" :disabled="!!providerBusy" @click="removeProvider(provider.id)"><Trash2 data-icon="inline-start" />Remove</Button>
|
||||
<Button size="sm" :disabled="!!providerBusy || !providerField(provider.id).name.trim() || !providerField(provider.id).class" @click="saveProvider(provider.id)">Save</Button>
|
||||
<Button variant="ghost" size="sm" class="text-danger" :disabled="store.savingDrafts || !!providerBusy || store.changesFor(providerKind(provider.id)).length > 0" @click="removeProvider(provider.id)"><Trash2 data-icon="inline-start" />Remove</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
@@ -314,20 +335,20 @@ async function savePolicy(): Promise<void> {
|
||||
<SelectContent><SelectItem v-for="classId in classNames" :key="classId" :value="classId">{{ classId }}</SelectItem></SelectContent>
|
||||
</Select>
|
||||
<Input v-model="newProviderBaseURL" class="min-w-56 flex-1 basis-56 font-mono" :placeholder="newProviderDefaultBaseURL || 'Base URL'" aria-label="Base URL for new provider" />
|
||||
<Button type="submit" variant="outline" size="sm" :disabled="!canAddProvider"><Plus data-icon="inline-start" />Add provider</Button>
|
||||
<Button type="submit" variant="outline" size="sm" :disabled="store.savingDrafts || !canAddProvider"><Plus data-icon="inline-start" />Add provider</Button>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Section v-if="policyData" title="Policy">
|
||||
<Section v-if="policyFields" title="Policy">
|
||||
<div class="flex flex-wrap items-center gap-3 py-2">
|
||||
<Label for="policy-workflows" class="w-28 text-label font-medium @max-xl:w-full">Workflows</Label>
|
||||
<Input id="policy-workflows" v-model="workflowText" class="min-w-40 flex-1 basis-40 font-mono" placeholder="any alias" aria-label="Aliases workflows may use" />
|
||||
<Input id="policy-workflows" :model-value="policyFields.workflows" class="min-w-40 flex-1 basis-40 font-mono" placeholder="any alias" aria-label="Aliases workflows may use" :disabled="store.savingDrafts" @update:model-value="(value) => editPolicy('workflows', String(value))" />
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 py-2">
|
||||
<Label for="policy-chat" class="w-28 text-label font-medium @max-xl:w-full">Chat</Label>
|
||||
<Input id="policy-chat" v-model="chatText" class="min-w-40 flex-1 basis-40 font-mono" placeholder="any alias" aria-label="Aliases chat may use" />
|
||||
<Input id="policy-chat" :model-value="policyFields.chat" class="min-w-40 flex-1 basis-40 font-mono" placeholder="any alias" aria-label="Aliases chat may use" :disabled="store.savingDrafts" @update:model-value="(value) => editPolicy('chat', String(value))" />
|
||||
</div>
|
||||
<div class="flex justify-end pt-2"><Button size="sm" :disabled="policyBusy" @click="savePolicy">Save</Button></div>
|
||||
|
||||
</Section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -32,24 +32,6 @@ export interface BlockingField extends FieldIssue {
|
||||
kind: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* collectIssues runs each dirty section's validator against its draft. It is
|
||||
* driven by the dirty list on purpose: a section with no changes is not
|
||||
* blocked, so a value the server already accepted can never stop an unrelated
|
||||
* save.
|
||||
*/
|
||||
export function collectIssues(
|
||||
dirtyKinds: readonly string[],
|
||||
draftValue: (kind: string) => unknown,
|
||||
validators: Record<string, DraftValidator | undefined>,
|
||||
): BlockingField[] {
|
||||
return dirtyKinds.flatMap((kind) => {
|
||||
const validate = validators[kind];
|
||||
if (!validate) return [];
|
||||
return validate(draftValue(kind)).map((issue) => ({ ...issue, kind }));
|
||||
});
|
||||
}
|
||||
|
||||
interface SchedulingDraft {
|
||||
poll_interval?: string;
|
||||
label?: string | null;
|
||||
|
||||
+17
-1
@@ -3,7 +3,7 @@ import { computed, onScopeDispose, ref } from "vue";
|
||||
|
||||
import { errors } from "../copy/errors/index.ts";
|
||||
import { api, describeError } from "../lib/api.ts";
|
||||
import type { Org } from "../org/org.ts";
|
||||
import type { Member, Org } from "../org/org.ts";
|
||||
import { useSessionStore } from "./session.ts";
|
||||
|
||||
export interface Identity {
|
||||
@@ -34,6 +34,20 @@ export const useOrgStore = defineStore("org", () => {
|
||||
/** The org the Org area shows; an instance admin can point it elsewhere. */
|
||||
const org = ref<Org | null>(null);
|
||||
let pending: Promise<void> | null = null;
|
||||
const membersByOrg = ref(new Map<string, Member[]>());
|
||||
const memberReads = new Map<string, Promise<Member[]>>();
|
||||
|
||||
function readMembers(id: string, refresh = false): Promise<Member[]> {
|
||||
if (!id) return Promise.resolve([]);
|
||||
const current = memberReads.get(id);
|
||||
if (current && !refresh) return current;
|
||||
const read = api.orgMembers<{ members: Member[] }>(id).then(({ members }) => {
|
||||
if (memberReads.get(id) === read) membersByOrg.value.set(id, members);
|
||||
return members;
|
||||
});
|
||||
memberReads.set(id, read);
|
||||
return read;
|
||||
}
|
||||
|
||||
/** loadOrg reads the org list; reload refetches it after an org is created. */
|
||||
function loadOrg(reload = false): Promise<void> {
|
||||
@@ -160,6 +174,8 @@ export const useOrgStore = defineStore("org", () => {
|
||||
actInOrg,
|
||||
org,
|
||||
loadOrg,
|
||||
membersByOrg,
|
||||
readMembers,
|
||||
viewOrg,
|
||||
renameOrg,
|
||||
identities,
|
||||
|
||||
+111
-12
@@ -7,7 +7,6 @@ import type { ConfigView } from "../settings/types.ts";
|
||||
|
||||
import { diffValues, revertChange, saveInOrder, type Change } from "../lib/changes.ts";
|
||||
import {
|
||||
collectIssues,
|
||||
draftValidators,
|
||||
type BlockingField,
|
||||
type FieldIssue,
|
||||
@@ -144,6 +143,18 @@ class ControlPlaneError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
interface ModuleSetting<T> {
|
||||
title: string | ((saved: T) => string);
|
||||
saved: T;
|
||||
read: () => Promise<T>;
|
||||
write: (value: T) => Promise<T>;
|
||||
validate?: (value: T) => FieldIssue[];
|
||||
}
|
||||
|
||||
interface ModuleDraft extends ModuleSetting<unknown> {
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set("Accept", "application/json");
|
||||
@@ -227,6 +238,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
const catalog = ref<ResourceDescriptor[]>([]);
|
||||
const catalogError = ref("");
|
||||
const reviewing = ref(false);
|
||||
const savingDrafts = ref(false);
|
||||
const states = reactive<Record<string, ResourceState>>({});
|
||||
const live = useSessionStore();
|
||||
const applyStatus = ref<ApplyStatusResponse>({ records: [], processes: [] });
|
||||
@@ -271,6 +283,32 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
// rather than silently overwritten.
|
||||
const forms = shallowReactive<Record<string, SettingsForm>>({});
|
||||
const bases = shallowReactive<Record<string, ControlPlaneResource>>({});
|
||||
const moduleDrafts = shallowReactive(new Map<string, ModuleDraft>());
|
||||
|
||||
function trackModuleSetting<T>(kind: string, setting: ModuleSetting<T>): void {
|
||||
const held = moduleDrafts.get(kind);
|
||||
if (held && (savingDrafts.value || changesFor(kind).length)) return;
|
||||
const { title, write, validate } = setting;
|
||||
moduleDrafts.set(kind, {
|
||||
...setting,
|
||||
title: typeof title === "string" ? title : (saved) => title(saved as T),
|
||||
value: setting.saved,
|
||||
write: (value) => write(value as T),
|
||||
validate: validate && ((value) => validate(value as T)),
|
||||
});
|
||||
}
|
||||
|
||||
function forgetModuleSetting(kind: string): void {
|
||||
moduleDrafts.delete(kind);
|
||||
stateFor(kind).error = undefined;
|
||||
}
|
||||
|
||||
const moduleKinds = computed(() => [...moduleDrafts.keys()].sort());
|
||||
const moduleTitle = (kind: string) => {
|
||||
const draft = moduleDrafts.get(kind);
|
||||
return typeof draft?.title === "function" ? draft.title(draft.saved) : draft?.title;
|
||||
};
|
||||
const moduleSaved = (kind: string) => moduleDrafts.get(kind)?.saved;
|
||||
|
||||
function createForm(resource: ControlPlaneResource): void {
|
||||
const kind = resource.kind;
|
||||
@@ -289,11 +327,20 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
|
||||
/** The edited value of a kind, read-only: edits go through its form. */
|
||||
function draftValue(kind: string): unknown {
|
||||
const module = moduleDrafts.get(kind);
|
||||
if (module) return module.value;
|
||||
return forms[kind]?.values.value;
|
||||
}
|
||||
|
||||
/** Replaces a form's values, keeping the version the edit started from. */
|
||||
function setDraftValue(kind: string, value: unknown): void {
|
||||
const module = moduleDrafts.get(kind);
|
||||
if (module) {
|
||||
if (savingDrafts.value) return;
|
||||
moduleDrafts.set(kind, { ...module, value });
|
||||
stateFor(kind).error = undefined;
|
||||
return;
|
||||
}
|
||||
forms[kind]?.reset(cloneControlPlaneValue(value), { keepDefaultValues: true });
|
||||
}
|
||||
|
||||
@@ -308,6 +355,11 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
}
|
||||
|
||||
function resetDraft(kind: string): void {
|
||||
const module = moduleDrafts.get(kind);
|
||||
if (module) {
|
||||
setDraftValue(kind, module.saved);
|
||||
return;
|
||||
}
|
||||
const resource = stateFor(kind).resource;
|
||||
const form = forms[kind];
|
||||
if (!resource || !form) return;
|
||||
@@ -317,7 +369,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
|
||||
/** Undoes one change in a draft and keeps the rest. */
|
||||
function revertDraftChange(kind: string, change: Change): void {
|
||||
if (forms[kind]) setDraftValue(kind, revertChange(draftValue(kind), change));
|
||||
if (forms[kind] || moduleDrafts.has(kind)) setDraftValue(kind, revertChange(draftValue(kind), change));
|
||||
}
|
||||
|
||||
/** Loads an earlier version into the draft and opens the review, so a restore
|
||||
@@ -337,6 +389,8 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
const byKind: Record<string, Change[]> = {};
|
||||
for (const [kind, form] of Object.entries(forms))
|
||||
byKind[kind] = diffValues(bases[kind]!.value, form.values.value);
|
||||
for (const [kind, draft] of moduleDrafts)
|
||||
byKind[kind] = diffValues(draft.saved, draft.value);
|
||||
return byKind;
|
||||
});
|
||||
|
||||
@@ -351,8 +405,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
}
|
||||
|
||||
const dirtyKinds = computed(() =>
|
||||
genericResources.value
|
||||
.map(({ kind }) => kind)
|
||||
[...genericResources.value.map(({ kind }) => kind), ...moduleKinds.value]
|
||||
.filter((kind) => changesFor(kind).length > 0),
|
||||
);
|
||||
|
||||
@@ -369,14 +422,14 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
/** Invalid fields across every dirty section. Derived from dirtyKinds, so a
|
||||
* save can only be blocked by a section that has something to save. */
|
||||
const invalidFields = computed<BlockingField[]>(() =>
|
||||
collectIssues(dirtyKinds.value, draftValue, draftValidators),
|
||||
dirtyKinds.value.flatMap((kind) => issuesFor(kind).map((issue) => ({ ...issue, kind }))),
|
||||
);
|
||||
|
||||
/** The issues for one section, empty unless it has unsaved changes. The
|
||||
* pages read this, so an inline error and the save bar can never disagree. */
|
||||
function issuesFor(kind: string): FieldIssue[] {
|
||||
if (changesFor(kind).length === 0) return [];
|
||||
const validate = draftValidators[kind];
|
||||
const validate = moduleDrafts.get(kind)?.validate ?? draftValidators[kind];
|
||||
return validate ? validate(draftValue(kind)) : [];
|
||||
}
|
||||
|
||||
@@ -392,16 +445,51 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
return saved;
|
||||
}
|
||||
|
||||
async function saveModuleDraft(kind: string, draft: ModuleDraft): Promise<boolean> {
|
||||
const state = stateFor(kind);
|
||||
state.error = undefined;
|
||||
try {
|
||||
// A preflight read can catch a change since review, but these module
|
||||
// APIs do not make the following PUT conditional on what we read.
|
||||
const latest = await draft.read();
|
||||
if (!diffValues(latest, draft.value).length) {
|
||||
moduleDrafts.set(kind, { ...draft, saved: latest, value: latest });
|
||||
return true;
|
||||
}
|
||||
if (diffValues(draft.saved, latest).length) {
|
||||
moduleDrafts.set(kind, { ...draft, saved: latest });
|
||||
state.error = errors.stores.settings.conflict;
|
||||
return false;
|
||||
}
|
||||
const saved = await draft.write(draft.value);
|
||||
moduleDrafts.set(kind, { ...draft, saved, value: saved });
|
||||
return true;
|
||||
} catch (error) {
|
||||
state.error = describeError(error, errors.common.unknown);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function saveDraft(kind: string): Promise<boolean> {
|
||||
const module = moduleDrafts.get(kind);
|
||||
if (module) return saveModuleDraft(kind, module);
|
||||
const form = forms[kind];
|
||||
return form ? form.submit() : Promise.resolve(true);
|
||||
}
|
||||
|
||||
function saveDrafts() {
|
||||
return saveInOrder(dirtyKinds.value, saveDraft);
|
||||
async function saveDrafts() {
|
||||
const kinds = dirtyKinds.value;
|
||||
if (savingDrafts.value || invalidFields.value.length)
|
||||
return { saved: [], failed: kinds[0], untouched: kinds };
|
||||
savingDrafts.value = true;
|
||||
try {
|
||||
return await saveInOrder(kinds, saveDraft);
|
||||
} finally {
|
||||
savingDrafts.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadResource(kind: string): Promise<void> {
|
||||
async function loadResource(kind: string): Promise<boolean> {
|
||||
const state = stateFor(kind);
|
||||
state.loading = true;
|
||||
try {
|
||||
@@ -412,8 +500,10 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
)
|
||||
).resource,
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
state.error = describeError(error, errors.common.unknown);
|
||||
return false;
|
||||
} finally {
|
||||
state.loading = false;
|
||||
}
|
||||
@@ -493,9 +583,12 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof ControlPlaneError && error.status === 409) {
|
||||
state.conflict = true;
|
||||
state.error = errors.stores.settings.conflict;
|
||||
await loadResource(kind);
|
||||
// Loading the resource clears its last error. Mark the conflict after
|
||||
// that read so the review can show the latest version before retrying.
|
||||
if (await loadResource(kind)) {
|
||||
state.conflict = true;
|
||||
state.error = errors.stores.settings.conflict;
|
||||
}
|
||||
} else {
|
||||
state.error = describeError(error, errors.common.unknown);
|
||||
}
|
||||
@@ -522,6 +615,12 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
config,
|
||||
loadConfig,
|
||||
reviewing,
|
||||
savingDrafts,
|
||||
moduleKinds,
|
||||
moduleTitle,
|
||||
moduleSaved,
|
||||
trackModuleSetting,
|
||||
forgetModuleSetting,
|
||||
pageErrorFor,
|
||||
applyStatusFor,
|
||||
changesFor,
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { api } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { runQuery, type LogState } from "./task-run";
|
||||
import { firstLine } from "./first-line";
|
||||
import { approvalLabels, statusKind, statusLabel } from "@/lib/task-meta";
|
||||
@@ -47,19 +48,17 @@ const failure = computed(() => {
|
||||
if (attempt.value?.status === "failed" || (current && status.value === "dead")) return { title: errors.tasks.header.attemptFailed(run.attemptNumber, stage?.name), detail: stage?.error || run.task?.park_reason || "", parked: false };
|
||||
return null;
|
||||
});
|
||||
// The daemon names a workflow's identity by its id in the parked reason; this
|
||||
// page knows which ids are identities and shows each by name, linked to the
|
||||
// page that manages it. An id this install does not know keeps its raw text.
|
||||
// Only IDs known to be identities are recognized in a free-form failure.
|
||||
const identities = useOrgStore();
|
||||
identities.watchIdentities();
|
||||
const detailParts = computed(() => {
|
||||
const text = failure.value?.detail ?? "";
|
||||
const known = identities.identities.map((actor) => actor.id).filter((id) => text.includes(id));
|
||||
if (!known.length) return [{ text, to: "" }];
|
||||
if (!known.length) return [{ text, id: "" }];
|
||||
const pattern = new RegExp(`(${known.map((id) => id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "g");
|
||||
return text
|
||||
.split(pattern)
|
||||
.map((part) => (known.includes(part) ? { text: identities.identityName(part), to: "/org/agents" } : { text: part, to: "" }));
|
||||
.map((part) => ({ text: part, id: known.includes(part) ? part : "" }));
|
||||
});
|
||||
const jumping = ref(false);
|
||||
const jumpError = ref("");
|
||||
@@ -192,7 +191,7 @@ const headerActions = computed(() => headerActionIds(run.task));
|
||||
<AlertDescription>
|
||||
<p v-if="failure.detail" class="mt-0.5 font-mono text-caption text-fg-muted [overflow-wrap:anywhere]">
|
||||
<template v-for="(part, index) in detailParts" :key="index">
|
||||
<RouterLink v-if="part.to" :to="part.to" class="underline decoration-dotted hover:text-foreground">{{ part.text }}</RouterLink>
|
||||
<UserReference v-if="part.id" :id="part.id" />
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</p>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { ago } from "@/lib/format";
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { cn } from "@/lib/utils";
|
||||
import WorkflowCanvas from "./WorkflowCanvas.vue";
|
||||
@@ -45,7 +46,7 @@ const CHANGE_VARIANTS = { added: "default", edited: "secondary", removed: "destr
|
||||
<li v-for="item in revisions" :key="item.version">
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left hover:bg-secondary"
|
||||
class="block w-full px-3 pt-2 text-left hover:bg-secondary"
|
||||
:class="item.version === selected && 'bg-secondary'"
|
||||
:aria-current="item.version === selected"
|
||||
@click="selected = item.version"
|
||||
@@ -54,8 +55,8 @@ const CHANGE_VARIANTS = { added: "default", edited: "secondary", removed: "destr
|
||||
<span class="font-mono text-caption text-fg-subtle">v{{ item.version }}</span>
|
||||
<Badge :variant="CHANGE_VARIANTS[item.change]">{{ item.change }}</Badge>
|
||||
</span>
|
||||
<span class="mt-0.5 block truncate text-caption text-fg-muted" :title="item.at">{{ item.actor || "unknown" }} · <template v-if="item.source">{{ item.source }} · </template><Timestamp :at="item.at" /></span>
|
||||
</button>
|
||||
<div class="mt-0.5 truncate px-3 pb-2 text-caption text-fg-muted" :title="item.at"><UserReference :id="item.actor" fallback="unknown" /> · <template v-if="item.source">{{ item.source }} · </template><Timestamp :at="item.at" /></div>
|
||||
</li>
|
||||
<!-- A failed reload says so even over an older list, which may be stale. -->
|
||||
<li v-if="error" class="px-3 py-2 text-label text-danger" role="alert">
|
||||
@@ -68,9 +69,10 @@ const CHANGE_VARIANTS = { added: "default", edited: "secondary", removed: "destr
|
||||
<Select v-if="revisions.length" :model-value="String(selected)" @update:model-value="selected = Number($event)">
|
||||
<SelectTrigger class="w-full md:hidden" aria-label="Revision"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="item in revisions" :key="item.version" :value="String(item.version)">v{{ item.version }} · {{ item.change }} · {{ item.actor || "unknown" }} · {{ ago(item.at) }}</SelectItem>
|
||||
<SelectItem v-for="item in revisions" :key="item.version" :value="String(item.version)">v{{ item.version }} · {{ item.change }} · {{ ago(item.at) }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div v-if="revision" class="text-caption text-fg-muted md:hidden"><UserReference :id="revision.actor" fallback="unknown" /></div>
|
||||
<div class="flex min-h-0 flex-col gap-2">
|
||||
<div v-if="revision" class="flex items-center gap-2 max-md:flex-wrap">
|
||||
<Tabs v-model="mode"><TabsList><TabsTrigger value="yaml">YAML</TabsTrigger><TabsTrigger value="canvas">Canvas</TabsTrigger></TabsList></Tabs>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import UserReference from "@/org/UserReference.vue";
|
||||
import { computed, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useMediaQuery } from "@vueuse/core";
|
||||
@@ -166,7 +167,7 @@ async function create(): Promise<void> {
|
||||
<TableCell><WorkflowLastRun :to="lastTo(row)" :state="row.last?.state" :tone="row.last && stateTone(row.last.state)" :at="row.last?.created_at" :running="row.running" :known="runsKnown" /></TableCell>
|
||||
<TableCell><WorkflowDelivery :counts="{ completed: row.succeeded }" :runs="row.runs" /><span v-if="!row.runs && runsKnown" class="text-caption text-fg-subtle">No runs</span></TableCell>
|
||||
<TableCell class="whitespace-normal">
|
||||
<span class="flex flex-col gap-0.5"><Timestamp :at="row.published" /><span v-if="row.by" class="truncate text-caption text-fg-muted">{{ row.by }}</span></span>
|
||||
<span class="flex flex-col gap-0.5"><Timestamp :at="row.published" /><UserReference v-if="row.by" :id="row.by" class="truncate text-caption" /></span>
|
||||
</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<WorkflowRowActions :id="row.id" :name="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
|
||||
@@ -199,6 +200,7 @@ async function create(): Promise<void> {
|
||||
<Badge v-if="startsMore(row).length" variant="secondary" :title="startsMore(row).join('\n')">+{{ startsMore(row).length }}</Badge>
|
||||
<span class="ml-auto shrink-0">{{ stepsLabel(row) }}</span>
|
||||
</p>
|
||||
<UserReference v-if="row.by" :id="row.by" class="truncate text-caption" />
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<WorkflowLastRun :to="lastTo(row)" :state="row.last?.state" :tone="row.last && stateTone(row.last.state)" :at="row.last?.created_at" :running="row.running" :known="runsKnown" />
|
||||
<div class="flex flex-col items-end gap-1 text-caption text-fg-muted">
|
||||
|
||||
@@ -128,6 +128,62 @@ test("save errors appear on the page only when not presented in the review drawe
|
||||
}
|
||||
});
|
||||
|
||||
// A rejected save must not silently retry against the same stale version.
|
||||
test("a conflicting settings save keeps the draft for review and retries with the latest version", async (t) => {
|
||||
for (const [kind, value] of [
|
||||
["workflow-execution-settings", { max_model_tool_steps: 5 }],
|
||||
["scheduling-policy", { poll_interval: "1m" }],
|
||||
] as const) {
|
||||
await t.test(kind, async (t) => {
|
||||
setActivePinia(createPinia());
|
||||
const store = useSettingsStore();
|
||||
const resourcePath = `/api/control-plane/resources/${kind}`;
|
||||
const initial = { kind, version: 7, value: {} };
|
||||
let resource = initial;
|
||||
let failRead = false;
|
||||
const sent: unknown[] = [];
|
||||
t.mock.method(globalThis, "fetch", async (path: string, init: RequestInit) => {
|
||||
if (path === "/api/capabilities") return Response.json({ sections: { settings: false } });
|
||||
if (path === "/api/control-plane/catalog") {
|
||||
return Response.json({ resources: [{ kind, commands: ["replace"] }] });
|
||||
}
|
||||
if (path === resourcePath) {
|
||||
return failRead ? new Response("Could not read the latest version", { status: 503 }) : Response.json({ resource });
|
||||
}
|
||||
assert.equal(path, `${resourcePath}/commands/replace`);
|
||||
assert.equal(init.method, "POST");
|
||||
const command = JSON.parse(String(init.body));
|
||||
sent.push(command);
|
||||
if (command.expected_version !== resource.version) {
|
||||
return new Response("Changed elsewhere", { status: 409 });
|
||||
}
|
||||
resource = { ...resource, version: resource.version + 1, value: command.value };
|
||||
return Response.json({ resource });
|
||||
});
|
||||
|
||||
await store.load();
|
||||
store.setDraftValue(kind, value);
|
||||
resource = { ...resource, version: 8 };
|
||||
|
||||
failRead = true;
|
||||
assert.equal((await store.saveDrafts()).failed, kind);
|
||||
assert.match(store.pageErrorFor(kind) ?? "", /Could not read the latest version/);
|
||||
assert.deepEqual(store.draftValue(kind), value);
|
||||
|
||||
failRead = false;
|
||||
assert.equal((await store.saveDrafts()).failed, kind);
|
||||
assert.match(store.pageErrorFor(kind) ?? "", /Changed elsewhere/);
|
||||
assert.deepEqual(store.draftValue(kind), value);
|
||||
assert.deepEqual(sent, [{ value, expected_version: 7 }, { value, expected_version: 7 }], "no automatic overwrite");
|
||||
|
||||
assert.ok(!(await store.saveDrafts()).failed);
|
||||
assert.deepEqual(sent.at(-1), { value, expected_version: 8 });
|
||||
assert.deepEqual(store.dirtyKinds, []);
|
||||
assert.equal(store.pageErrorFor(kind), undefined);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("an unset resource opens without changes and an untouched save keeps it unset", async () => {
|
||||
setActivePinia(createPinia());
|
||||
const store = useSettingsStore();
|
||||
|
||||
Reference in new issue
Block a user