skillhub/plugins/dsh/test/integration/skill-availability-fixture.mjs
dongmucat 6d436d664e
feat(dsh): connect accounts and manage namespace skills and members (#1114)
* feat(dsh): connect registry accounts and manage namespace skills and members

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): use the patched ZIP reader for skill packages

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): bind owned skill actions to the published version ID

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(auth): handle context-prefixed registry requests consistently

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): address account isolation and upload review findings

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): recover changed upload targets and clear private detail caches

Signed-off-by: dongmucat <1127093059@qq.com>

* refactor(dsh): keep registry authentication inside the plugin

Signed-off-by: dongmucat <1127093059@qq.com>

* test(dsh): canonicalize temporary profile roots across platforms

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): clear expired accounts during detail reads

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(auth): include DSH permissions in default personal tokens

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(web): refresh token form analytics manifest

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): organize account dialogs and preserve modal focus

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(ci): pin DSH browser checks to supported Ubuntu

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): unify workbench appearance and source navigation

Signed-off-by: dongmucat <1127093059@qq.com>

* test(dsh): wait for runtime readiness before availability install

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): align namespace pages with the account prototype

Signed-off-by: dongmucat <1127093059@qq.com>

* test(dsh): use monotonic clocks for fixture deadlines

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): expose namespace member management actions

Add a direct member-management entry, explain disabled role and state restrictions, and preserve keyboard focus after membership changes. Exercise add, role change and removal through the real account components.

Signed-off-by: dongmucat <1127093059@qq.com>

* feat(dsh): support drag and drop skill uploads

Use one validated file selection flow for dropping and browsing ZIPs. Show selected file details, protect in-flight uploads and confirmation revisions, and cover keyboard, busy and invalid-file behavior in Chromium.

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): right-align the catalog upload action

Signed-off-by: dongmucat <1127093059@qq.com>

* feat(dsh): persist Windows account credentials securely

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): remove saved accounts reliably on Windows Unicode paths

Signed-off-by: dongmucat <1127093059@qq.com>

* test(organizations): isolate committed portal fixtures

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(auth): preserve token lifecycle state during usage updates

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(skills): enforce caller-aware deletion across CLI endpoints

Signed-off-by: dongmucat <1127093059@qq.com>

* fix(dsh): submit account writes once and refresh registry views

Signed-off-by: dongmucat <1127093059@qq.com>

* chore(db): reserve unpublished token migration after upstream V128

Signed-off-by: dongmucat <1127093059@qq.com>

---------

Signed-off-by: dongmucat <1127093059@qq.com>
2026-11-25 16:07:19 +08:00

286 lines
15 KiB
JavaScript

import { executeFixtureTool } from './fixture-tool-execution.mjs';
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, readFile, readdir, rename, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as delay } from 'node:timers/promises';
export const inject = ['sessionController', 'workspaceRegistry', 'tools', 'sessions', 'skills', 'skillhub', 'typertGateway'];
export function apply(ctx, config) {
const root = resolve(config.root);
assert(root.startsWith(resolve(tmpdir()) + sep));
assert(fileURLToPath(import.meta.url).startsWith(resolve(tmpdir()) + sep));
assert.equal(process.env.DSH_HOME, join(root, 'home'));
const checkpoint = { scenario: 'setup', checkpoint: 'setup', assertion: 'none' };
const abort = new AbortController();
const timer = setTimeout(() => run(ctx, root, AbortSignal.any([abort.signal, AbortSignal.timeout(70000)]), checkpoint)
.catch(error => writeFile(join(root, 'skill-availability-result.json'), JSON.stringify({ passed: false, error: error.message, checkpoint: { ...checkpoint, osCode: error.code }, operation: checkpoint.operation }))), 1000);
return () => { clearTimeout(timer); abort.abort(); };
}
/** Preserve the failing mutation/inspection when cleanup also fails. No retry hides a Host failure. */
export async function withRenamedAvailabilityPath(checkpoint, from, to, inspect, move = rename) {
Object.assign(checkpoint, { checkpoint: 'mutation-apply', assertion: 'none' });
// A failed rename leaves no backup owned by this fixture; do not try to restore it.
await move(from, to);
let inspectionFailed = false;
try { return await inspect(); }
catch (error) { inspectionFailed = true; throw error; }
finally {
if (inspectionFailed) {
try { await move(to, from); }
catch (error) { checkpoint.restoreOsCode = error.code; }
} else {
Object.assign(checkpoint, { checkpoint: 'mutation-restore', assertion: 'none' });
await move(to, from);
}
}
}
/** Each probe owns a fresh Host; a fixed startup delay cannot establish runtime readiness. */
export async function waitForAvailabilityRuntime(read, signal, { timeoutMs = 20000, pollMs = 100 } = {}) {
const deadline = performance.now() + timeoutMs;
for (;;) {
signal.throwIfAborted();
const status = read();
signal.throwIfAborted();
if (performance.now() >= deadline) {
throw Object.assign(new Error('Fixture local runtime did not become ready before the deadline.'), { code: 'RUNTIME_READY_TIMEOUT' });
}
if (status?.state === 'ready' && status.hostInstanceId) return;
if (status && !['starting', 'ready'].includes(status.state)) {
throw Object.assign(new Error('Fixture local runtime cannot become ready.'), { code: 'RUNTIME_NOT_READY' });
}
await delay(Math.min(pollMs, Math.max(1, deadline - performance.now())), undefined, { signal });
}
}
/** File commit and official watcher discovery are independent; wait only on read-only observations. */
export async function waitForAvailabilityWinner(read, directory, signal, { timeoutMs = 15000, pollMs = 100 } = {}) {
signal.throwIfAborted();
const timeout = Object.assign(new Error('Official Host discovery did not select the installed fixture before the deadline.'), { code: 'DISCOVERY_TIMEOUT' });
const deadline = performance.now() + timeoutMs;
const bounded = new AbortController();
const cancel = () => bounded.abort(signal.reason);
signal.addEventListener('abort', cancel, { once: true });
const timer = setTimeout(() => bounded.abort(timeout), timeoutMs);
const valid = () => {
if (performance.now() >= deadline) bounded.abort(timeout);
bounded.signal.throwIfAborted();
};
let rejectAbort;
const cancelled = new Promise((_resolve, reject) => {
rejectAbort = () => reject(bounded.signal.reason);
bounded.signal.addEventListener('abort', rejectAbort, { once: true });
});
try {
await Promise.race([cancelled, (async () => {
for (;;) {
valid();
const { snapshot, winner } = await read(bounded.signal);
valid();
if (snapshot.complete && snapshot.skills.some(skill => skill.name === 'document-helper')
&& winner?.name === 'document-helper' && winner.path === join(directory, 'SKILL.md')
&& winner.resourceBase?.kind === 'directory' && winner.resourceBase.path === directory) return;
await delay(pollMs, undefined, { signal: bounded.signal });
}
})()]);
} catch (error) {
if (bounded.signal.aborted) throw bounded.signal.reason;
throw error;
} finally {
clearTimeout(timer);
signal.removeEventListener('abort', cancel);
bounded.signal.removeEventListener('abort', rejectAbort);
}
}
async function digest(directory) {
const hash = createHash('sha256');
async function visit(path, relative = '') {
let entries;
try { entries = await readdir(path, { withFileTypes: true }); }
catch (error) { if (error.code === 'ENOENT') { hash.update('missing:' + relative); return; } throw error; }
const observed = await stat(path);
hash.update(JSON.stringify([relative, observed.mtimeMs, observed.ctimeMs, observed.mode]));
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
const name = relative + '/' + entry.name;
hash.update(name);
if (entry.isDirectory()) await visit(join(path, entry.name), name);
else if (entry.isFile()) {
const observed = await stat(join(path, entry.name));
hash.update(JSON.stringify([observed.mtimeMs, observed.ctimeMs, observed.mode]));
hash.update(await readFile(join(path, entry.name)));
}
else throw new Error('Unexpected fixture filesystem entry');
}
}
await visit(directory);
return hash.digest('hex');
}
async function run(ctx, root, signal, checkpoint) {
const mark = (phase, assertion = 'none') => Object.assign(checkpoint, { checkpoint: phase, assertion });
const project = join(root, 'availability-' + randomUUID());
await mkdir(project);
const workspace = await ctx.workspaceRegistry.create(project);
const created = await ctx.sessionController.create({ workspaceId: workspace.id, agentPreset: 'standard' });
const resolved = await ctx.sessionController.resolveAgent(created.sessionId);
if ('error' in resolved) throw resolved.error;
const agent = resolved.agent;
const execute = (name, args) => executeFixtureTool(ctx, root, { callId: randomUUID(), name, arguments: args, agent, signal });
const namespace = process.env.DSH_FIXTURE_NAMESPACE;
const paths = { project: join(project, '.dsh/skills/document-helper'), user: join(root, 'home/skills/document-helper') };
const records = [];
const protectedPaths = [project, join(root, 'home/skills'), join(root, 'home/skillhub'), join(root, 'native-install-home/.skillhub')];
async function check(args, expected) {
mark('before-digest');
const before = await Promise.all(protectedPaths.map(digest));
mark('execute');
const result = await execute('astron_skillhub_check_availability', args);
mark('assertion', 'isError');
assert.equal(result.isError, false);
mark('assertion', 'kind');
assert.equal(result.value.kind, 'skillhub-availability');
mark('assertion', 'schemaVersion');
assert.equal(result.value.schemaVersion, 1);
for (const [key, value] of Object.entries(expected)) { mark('assertion', key); assert.deepEqual(result.value.diagnosis[key], value, key); }
mark('assertion', 'installation');
if (args.name) assert.equal(result.value.diagnosis.installation, undefined);
else {
mark('assertion', 'namespace');
assert.equal(result.value.diagnosis.installation.namespace, namespace);
mark('assertion', 'slug');
assert.equal(result.value.diagnosis.installation.slug, 'document-helper');
mark('assertion', 'version');
assert.equal(result.value.diagnosis.installation.version, '1.2.0');
}
mark('assertion', 'version');
assert.equal(result.value.diagnosis.version, undefined);
mark('assertion', 'fingerprint');
assert.equal(result.value.diagnosis.fingerprint, undefined);
const rendered = JSON.stringify(result.content);
mark('assertion', 'render');
assert(rendered.includes('skillhub-availability'), 'Real tools.execute rendered the diagnosis');
mark('assertion', 'privacy');
for (const forbidden of [root, 'AVAILABILITY_PRIVATE_SENTINEL', 'resourceBase', 'metadata', 'provider']) assert(!rendered.includes(forbidden), 'Model render leaked ' + forbidden);
mark('after-digest', 'unchanged');
assert.deepEqual(await Promise.all(protectedPaths.map(digest)), before, 'Diagnosis changed installation/inventory/operation files');
records.push({ query: args.name ? 'name' : 'managed', ...expected });
return result.value.diagnosis;
}
async function install(scope) {
checkpoint.operation = { deadlineReached: false };
mark('install');
const result = await execute('astron_skillhub_install', { namespace, slug: 'document-helper', scope });
checkpoint.install = { status: result.value?.status, code: result.value?.code, reason: ctx.skillhub.getInstallationContextDiagnostic() };
mark('assertion', 'isError');
assert.equal(result.isError, false);
mark('assertion', 'accepted');
assert.equal(result.value.status, 'accepted');
const deadline = performance.now() + 15000;
let operation;
mark('install-poll');
while (performance.now() < deadline) {
operation = await ctx.skillhub.getInstallationOperation(created.sessionId, result.value.operationId);
checkpoint.operation = { phase: operation?.phase, files: operation?.files, recovery: operation?.recovery,
discovery: operation?.discovery, deadlineReached: performance.now() >= deadline };
if (['completed', 'failed', 'unknown', 'recovery-required'].includes(operation?.phase)) break;
await delay(100, undefined, { signal });
}
checkpoint.operation.deadlineReached = performance.now() >= deadline;
mark('assertion', 'completed');
assert.equal(operation?.phase, 'completed');
// Do not mistake a completed file transaction for the asynchronous watcher having refreshed its catalog.
mark('install-poll', 'discovery');
try {
await waitForAvailabilityWinner(async boundedSignal => {
const options = { scope: agent, cwd: project, signal: boundedSignal };
const snapshot = await ctx.skills.snapshot(options);
boundedSignal.throwIfAborted();
return { snapshot, winner: await ctx.skills.get('document-helper', options) };
}, paths[scope], signal);
} catch (error) {
if (error.code === 'DISCOVERY_TIMEOUT') checkpoint.operation.deadlineReached = true;
throw error;
}
}
async function reference(scope) {
mark('reference');
const sourceRevision = ctx.skillhub.getContext().sourceRevision;
const list = await ctx.typertGateway.invoke({ peer: ctx.get('connection')?.browserPeer ?? ctx.get('connection')?.operator,
namespace: 'skillhub', method: 'listInstalled', args: { agentId: created.sessionId, sourceRevision }, signal });
const item = list.items.find(value => value.namespace === namespace && value.scope === scope);
mark('assertion', 'reference');
assert(item);
return { sourceRevision, itemKey: item.itemKey };
}
checkpoint.scenario = 'user-install';
mark('runtime-ready');
await waitForAvailabilityRuntime(() => {
const status = ctx.skillhub.getLocalRuntimeStatus();
checkpoint.runtimeState = status?.state ?? 'absent';
return status;
}, signal);
delete checkpoint.runtimeState;
await install('user');
checkpoint.scenario = 'user-winner';
await check(await reference('user'), { association: 'managed-reference', scope: 'user', integrity: 'verified', discovery: 'winner', name: 'document-helper' });
checkpoint.scenario = 'project-install';
await install('project');
checkpoint.scenario = 'project-winner';
await check(await reference('project'), { scope: 'project', integrity: 'verified', discovery: 'winner' });
checkpoint.scenario = 'user-shadowed';
await check(await reference('user'), { integrity: 'verified', discovery: 'shadowed', reason: 'same-name-winner' });
checkpoint.scenario = 'remote';
const remote = await ctx.typertGateway.invoke({ peer: ctx.get('connection')?.browserPeer ?? ctx.get('connection')?.operator,
namespace: 'skillhub', method: 'checkAvailability', args: { agentId: created.sessionId, ...await reference('project') }, signal });
mark('assertion', 'discovery');
assert.equal(remote.discovery, 'winner');
checkpoint.scenario = 'by-name';
await check({ name: 'document-helper' }, { association: 'not-associated', integrity: 'unknown', discovery: 'winner' });
const target = paths.project;
const skillPath = join(target, 'SKILL.md');
const original = await readFile(skillPath, 'utf8');
for (const mode of ['content-modified', 'skill-missing', 'directory-missing']) {
checkpoint.scenario = mode;
mark('mutation');
const backup = join(root, 'availability-backup-' + randomUUID());
if (mode === 'content-modified') {
try {
await writeFile(skillPath, original + '\nAVAILABILITY_PRIVATE_SENTINEL');
await check(await reference('project'), { integrity: 'changed' });
} finally { await writeFile(skillPath, original); }
} else {
await withRenamedAvailabilityPath(checkpoint, mode === 'skill-missing' ? skillPath : target, backup,
async () => check(await reference('project'), { integrity: 'missing' }));
}
}
checkpoint.scenario = 'policy';
for (const userInvocable of [true, false]) for (const modelInvocable of [true, false]) {
const name = `availability-policy-${Number(userInvocable)}-${Number(modelInvocable)}`;
const dispose = ctx.skills.register({ name, description: 'Fixture', content: 'AVAILABILITY_PRIVATE_SENTINEL',
source: 'runtime', provider: 'AVAILABILITY_PRIVATE_SENTINEL', metadata: { private: 'AVAILABILITY_PRIVATE_SENTINEL' },
resourceBase: { kind: 'directory', path: join(root, 'AVAILABILITY_PRIVATE_SENTINEL') }, invocation: { userInvocable, modelInvocable } });
try { await check({ name }, { association: 'not-associated', integrity: 'unknown', discovery: 'winner', invocation: { userInvocable, modelInvocable } }); }
finally { dispose(); }
}
checkpoint.scenario = 'absent';
await check({ name: 'availability-absent' }, { discovery: 'not-discovered', integrity: 'unknown' });
checkpoint.scenario = 'incomplete-provider';
const dispose = ctx.skills.registerProvider(() => ({ name: 'availability-incomplete',
list: async () => ({ candidates: [], complete: false }), get: async () => undefined }));
try { await check({ name: 'document-helper' }, { discovery: 'unknown', reason: 'snapshot-incomplete' }); }
finally { dispose(); }
checkpoint.scenario = 'failed-provider';
const failedProvider = ctx.skills.registerProvider(() => ({ name: 'availability-failed',
list: async () => { throw new Error('AVAILABILITY_PRIVATE_SENTINEL'); }, get: async () => undefined }));
try { await check({ name: 'document-helper' }, { discovery: 'unknown', reason: 'snapshot-incomplete' }); }
finally { failedProvider(); }
await writeFile(join(root, 'skill-availability-result.json'), JSON.stringify({ passed: true, records,
realAgentScope: true, remoteAgentMethod: true, modelRenderChecked: true, protectedFilesUnchanged: true,
registry: 'isolated-fixture', modelInvoked: false }, null, 2));
}