mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
refactor(ui): isolate resource operations and cancellable reads (#957)
* refactor(ui): isolate resource operations and cancellable reads Keep resource toggle rollback and move reconciliation outside the view. Preserve the preview and revision protocols and distinguish cancelled resource reads from connection failures. * refactor(ui): standardize JSON requests across dashboard APIs Keep HTTP verbs, paths and payloads visible at each endpoint without repeating serialization. Preserve bodyless requests, raw JSON imports and streaming responses, and cover the extras request contracts. * refactor(ui): share sync eligibility and upgrade recovery Use scoped plans for sync counts and writes, share restart polling, and restore only the edited target field when a resource write fails. * fix(ui): show pending MCP source migrations in sync preview Render the migration counted by the global plan rather than an empty preview when no MCP target file changes. Cover the mismatch through the rendered sync page.
This commit is contained in:
+11
-31
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, BASE, createSSEStream, kindQuery } from './http';
|
||||
import { http, BASE, createSSEStream, kindQuery } from './http';
|
||||
import type {
|
||||
AuditAllResponse,
|
||||
AuditPolicy,
|
||||
@@ -8,9 +8,9 @@ import type {
|
||||
} from './types/audit';
|
||||
|
||||
export const auditApi = {
|
||||
auditAll: (kind?: 'skills' | 'agents') => apiFetch<AuditAllResponse>(`/audit${kindQuery(kind)}`),
|
||||
auditAll: (kind?: 'skills' | 'agents') => http.get<AuditAllResponse>(`/audit${kindQuery(kind)}`),
|
||||
auditSkill: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<AuditSkillResponse>(
|
||||
http.get<AuditSkillResponse>(
|
||||
`/audit/${encodeURIComponent(name)}${kindQuery(kind === 'agent' ? kind : undefined)}`,
|
||||
),
|
||||
auditAllStream: (
|
||||
@@ -30,36 +30,16 @@ export const auditApi = {
|
||||
onError,
|
||||
'Audit stream failed',
|
||||
),
|
||||
getAuditRules: () => apiFetch<AuditRulesResponse>('/audit/rules'),
|
||||
putAuditRules: (raw: string) =>
|
||||
apiFetch<{ success: boolean }>('/audit/rules', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ raw }),
|
||||
}),
|
||||
initAuditRules: () =>
|
||||
apiFetch<{ success: boolean; path: string }>('/audit/rules', {
|
||||
method: 'POST',
|
||||
}),
|
||||
getCompiledRules: () => apiFetch<CompiledRulesResponse>('/audit/rules/compiled'),
|
||||
getAuditRules: () => http.get<AuditRulesResponse>('/audit/rules'),
|
||||
putAuditRules: (raw: string) => http.put<{ success: boolean }>('/audit/rules', { raw }),
|
||||
initAuditRules: () => http.post<{ success: boolean; path: string }>('/audit/rules'),
|
||||
getCompiledRules: () => http.get<CompiledRulesResponse>('/audit/rules/compiled'),
|
||||
/** Severity at which install and sync refuse a resource. */
|
||||
setAuditThreshold: (blockThreshold: string) =>
|
||||
apiFetch<AuditPolicy>('/audit/policy', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ blockThreshold }),
|
||||
}),
|
||||
http.patch<AuditPolicy>('/audit/policy', { blockThreshold }),
|
||||
/** Preset for how strict a scan is: default, strict, or permissive. */
|
||||
setAuditProfile: (profile: string) =>
|
||||
apiFetch<AuditPolicy>('/audit/policy', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ profile }),
|
||||
}),
|
||||
setAuditProfile: (profile: string) => http.patch<AuditPolicy>('/audit/policy', { profile }),
|
||||
toggleRule: (req: { id?: string; pattern?: string; enabled: boolean; severity?: string }) =>
|
||||
apiFetch<{ success: boolean }>('/audit/rules/toggle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(req),
|
||||
}),
|
||||
resetRules: () =>
|
||||
apiFetch<{ success: boolean }>('/audit/rules/reset', {
|
||||
method: 'POST',
|
||||
}),
|
||||
http.post<{ success: boolean }>('/audit/rules/toggle', req),
|
||||
resetRules: () => http.post<{ success: boolean }>('/audit/rules/reset'),
|
||||
};
|
||||
|
||||
+16
-38
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, kindQuery } from './http';
|
||||
import { http, kindQuery } from './http';
|
||||
import type {
|
||||
BackupListResponse,
|
||||
FileBackup,
|
||||
@@ -8,54 +8,32 @@ import type {
|
||||
} from './types/backups';
|
||||
|
||||
export const backupsApi = {
|
||||
listBackups: () => apiFetch<BackupListResponse>('/backups'),
|
||||
listBackups: () => http.get<BackupListResponse>('/backups'),
|
||||
createBackup: (target?: string) =>
|
||||
apiFetch<{ success: boolean; backedUpTargets: string[] }>('/backup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target: target ?? '' }),
|
||||
}),
|
||||
cleanupBackups: () =>
|
||||
apiFetch<{ success: boolean; removed: number }>('/backup/cleanup', { method: 'POST' }),
|
||||
http.post<{ success: boolean; backedUpTargets: string[] }>('/backup', { target: target ?? '' }),
|
||||
cleanupBackups: () => http.post<{ success: boolean; removed: number }>('/backup/cleanup'),
|
||||
restore: (opts: { timestamp: string; target: string; force?: boolean }) =>
|
||||
apiFetch<{ success: boolean; target: string; timestamp: string }>('/restore', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
http.post<{ success: boolean; target: string; timestamp: string }>('/restore', opts),
|
||||
validateRestore: (opts: { timestamp: string; target: string }) =>
|
||||
apiFetch<RestoreValidateResponse>('/restore/validate', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
deleteAllBackups: () =>
|
||||
apiFetch<{ success: boolean; removed: number }>('/backups', { method: 'DELETE' }),
|
||||
http.post<RestoreValidateResponse>('/restore/validate', opts),
|
||||
deleteAllBackups: () => http.delete<{ success: boolean; removed: number }>('/backups'),
|
||||
deleteBackup: (timestamp: string) =>
|
||||
apiFetch<{ success: boolean }>(`/backups/${encodeURIComponent(timestamp)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean }>(`/backups/${encodeURIComponent(timestamp)}`),
|
||||
// File history: earlier versions of single files skillshare rewrote
|
||||
listFileBackups: () => apiFetch<{ files: FileBackup[] }>('/file-backups'),
|
||||
listFileBackups: () => http.get<{ files: FileBackup[] }>('/file-backups'),
|
||||
getFileBackupVersions: (path: string) =>
|
||||
apiFetch<FileBackupVersions>(`/file-backups/versions?path=${encodeURIComponent(path)}`),
|
||||
http.get<FileBackupVersions>(`/file-backups/versions?path=${encodeURIComponent(path)}`),
|
||||
getFileBackupVersion: (path: string, id: string) =>
|
||||
apiFetch<{ content: string; current: string }>(
|
||||
http.get<{ content: string; current: string }>(
|
||||
`/file-backups/version?path=${encodeURIComponent(path)}&id=${encodeURIComponent(id)}`,
|
||||
),
|
||||
restoreFileBackup: (body: { path: string; id: string; unlink?: boolean }) =>
|
||||
apiFetch<{ success: boolean; backup_id?: string }>('/file-backups/restore', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
listTrash: () => apiFetch<TrashListResponse>('/trash'),
|
||||
http.post<{ success: boolean; backup_id?: string }>('/file-backups/restore', body),
|
||||
listTrash: () => http.get<TrashListResponse>('/trash'),
|
||||
restoreTrash: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean }>(`/trash/${encodeURIComponent(name)}/restore${kindQuery(kind)}`, {
|
||||
method: 'POST',
|
||||
}),
|
||||
http.post<{ success: boolean }>(`/trash/${encodeURIComponent(name)}/restore${kindQuery(kind)}`),
|
||||
deleteTrash: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean }>(`/trash/${encodeURIComponent(name)}${kindQuery(kind)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean }>(`/trash/${encodeURIComponent(name)}${kindQuery(kind)}`),
|
||||
emptyTrash: (kind: 'skill' | 'agent' | 'all' = 'all') =>
|
||||
apiFetch<{ success: boolean; removed: number }>(`/trash/empty${kindQuery(kind)}`, {
|
||||
method: 'POST',
|
||||
}),
|
||||
http.post<{ success: boolean; removed: number }>(`/trash/empty${kindQuery(kind)}`),
|
||||
};
|
||||
|
||||
+9
-25
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
import type {
|
||||
AgentignoreResponse,
|
||||
AvailableTarget,
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
} from './types/config';
|
||||
|
||||
export const configApi = {
|
||||
getConfig: () => apiFetch<{ config: unknown; raw: string }>('/config'),
|
||||
getConfig: () => http.get<{ config: unknown; raw: string }>('/config'),
|
||||
/** Settings the Settings page owns; the rest of config.yaml stays untouched. */
|
||||
patchConfig: (body: {
|
||||
mode?: string;
|
||||
@@ -15,27 +15,11 @@ export const configApi = {
|
||||
backupMaxCount?: number;
|
||||
backupMaxSizeMB?: number;
|
||||
autoUpdateCheck?: boolean;
|
||||
}) =>
|
||||
apiFetch<{ mode: string; logMaxEntries: number | null }>('/config', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
putConfig: (raw: string) =>
|
||||
apiFetch<ConfigSaveResponse>('/config', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ raw }),
|
||||
}),
|
||||
availableTargets: () => apiFetch<{ targets: AvailableTarget[] }>('/config/available-targets'),
|
||||
getSkillignore: () => apiFetch<SkillignoreResponse>('/skillignore'),
|
||||
putSkillignore: (raw: string) =>
|
||||
apiFetch<{ success: boolean }>('/skillignore', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ raw }),
|
||||
}),
|
||||
getAgentignore: () => apiFetch<AgentignoreResponse>('/agentignore'),
|
||||
putAgentignore: (raw: string) =>
|
||||
apiFetch<{ success: boolean }>('/agentignore', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ raw }),
|
||||
}),
|
||||
}) => http.patch<{ mode: string; logMaxEntries: number | null }>('/config', body),
|
||||
putConfig: (raw: string) => http.put<ConfigSaveResponse>('/config', { raw }),
|
||||
availableTargets: () => http.get<{ targets: AvailableTarget[] }>('/config/available-targets'),
|
||||
getSkillignore: () => http.get<SkillignoreResponse>('/skillignore'),
|
||||
putSkillignore: (raw: string) => http.put<{ success: boolean }>('/skillignore', { raw }),
|
||||
getAgentignore: () => http.get<AgentignoreResponse>('/agentignore'),
|
||||
putAgentignore: (raw: string) => http.put<{ success: boolean }>('/agentignore', { raw }),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { extrasApi } from './extras';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
function recordRequests() {
|
||||
const requests: [string, string, unknown][] = [];
|
||||
vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {
|
||||
requests.push([
|
||||
init.method ?? 'GET',
|
||||
url,
|
||||
typeof init.body === 'string' ? JSON.parse(init.body) : init.body,
|
||||
]);
|
||||
return Response.json({ success: true });
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
it('distinguishes a bodyless POST from syncing with empty options', async () => {
|
||||
const requests = recordRequests();
|
||||
await extrasApi.openExtensionsDir();
|
||||
await extrasApi.syncExtras();
|
||||
expect(requests).toEqual([
|
||||
['POST', '/api/extensions/open', undefined],
|
||||
['POST', '/api/extras/sync', {}],
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves omitted and cleared settings and sends the target path on DELETE', async () => {
|
||||
const requests = recordRequests();
|
||||
await extrasApi.setExtraMode('my notes', 'out', 'copy');
|
||||
await extrasApi.setExtraMode('my notes', 'out', 'copy', false, '');
|
||||
await extrasApi.removeExtraTarget('my notes', 'out');
|
||||
expect(requests).toEqual([
|
||||
['PATCH', '/api/extras/my%20notes/mode', { target: 'out', mode: 'copy' }],
|
||||
[
|
||||
'PATCH',
|
||||
'/api/extras/my%20notes/mode',
|
||||
{ target: 'out', mode: 'copy', flatten: false, extension: '' },
|
||||
],
|
||||
['DELETE', '/api/extras/my%20notes/targets', { path: 'out' }],
|
||||
]);
|
||||
});
|
||||
+31
-87
@@ -1,5 +1,8 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http, type SuccessResponse } from './http';
|
||||
import type {
|
||||
CreateExtraRequest,
|
||||
EditExtraTarget,
|
||||
ExtensionActionResult,
|
||||
ExtensionInfo,
|
||||
Extra,
|
||||
ExtraDiffResult,
|
||||
@@ -8,109 +11,50 @@ import type {
|
||||
ExtrasSyncResult,
|
||||
} from './types/extras';
|
||||
|
||||
const extraPath = (name: string) => `/extras/${encodeURIComponent(name)}`;
|
||||
|
||||
export const extrasApi = {
|
||||
listExtras: () => apiFetch<{ extras: Extra[] }>('/extras'),
|
||||
listExtras: () => http.get<{ extras: Extra[] }>('/extras'),
|
||||
diffExtras: (name?: string) =>
|
||||
apiFetch<{ extras: ExtraDiffResult[] }>(
|
||||
http.get<{ extras: ExtraDiffResult[] }>(
|
||||
`/extras/diff${name ? '?name=' + encodeURIComponent(name) : ''}`,
|
||||
),
|
||||
createExtra: (data: {
|
||||
name: string;
|
||||
source?: string;
|
||||
folder?: string; // a folder in the shared extras folder; the server stores it as the source
|
||||
file?: string; // single-file extra: the file in the source folder
|
||||
targets: Array<{
|
||||
path: string;
|
||||
mode: string;
|
||||
flatten?: boolean;
|
||||
extension?: string;
|
||||
as?: string;
|
||||
}>;
|
||||
}) =>
|
||||
apiFetch<{ success: boolean }>('/extras', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
syncExtras: (opts?: { name?: string; dry_run?: boolean; force?: boolean }) =>
|
||||
apiFetch<{ extras: ExtrasSyncResult[] }>('/extras/sync', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts ?? {}),
|
||||
}),
|
||||
deleteExtra: (name: string) =>
|
||||
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}`, { method: 'DELETE' }),
|
||||
listExtraExtensions: () => apiFetch<{ extensions: string[] }>('/extras/extensions'),
|
||||
// Extensions management (Config page)
|
||||
listExtensions: () => apiFetch<{ extensions: ExtensionInfo[] }>('/extensions'),
|
||||
installExtension: (name: string) =>
|
||||
apiFetch<{ success: boolean; name: string }>('/extensions/install', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name }),
|
||||
}),
|
||||
openExtensionsDir: () => apiFetch<{ path: string }>('/extensions/open', { method: 'POST' }),
|
||||
removeExtension: (name: string) =>
|
||||
apiFetch<{ success: boolean; name: string }>(`/extensions/${encodeURIComponent(name)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
// extension: undefined = leave unchanged; '' = clear; name = set (forces copy mode)
|
||||
createExtra: (input: CreateExtraRequest) => http.post<SuccessResponse>('/extras', input),
|
||||
syncExtras: (options: { name?: string; dry_run?: boolean; force?: boolean } = {}) =>
|
||||
http.post<{ extras: ExtrasSyncResult[] }>('/extras/sync', options),
|
||||
deleteExtra: (name: string) => http.delete<SuccessResponse>(extraPath(name)),
|
||||
|
||||
// undefined leaves the extension unchanged; '' clears it; a name forces copy mode.
|
||||
setExtraMode: (
|
||||
name: string,
|
||||
target: string,
|
||||
mode: string,
|
||||
flatten?: boolean,
|
||||
extension?: string,
|
||||
) =>
|
||||
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/mode`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({
|
||||
target,
|
||||
mode,
|
||||
...(flatten !== undefined && { flatten }),
|
||||
...(extension !== undefined && { extension }),
|
||||
}),
|
||||
}),
|
||||
) => http.patch<SuccessResponse>(`${extraPath(name)}/mode`, { target, mode, flatten, extension }),
|
||||
addExtraTarget: (
|
||||
name: string,
|
||||
target: { path: string; mode?: string; flatten?: boolean; as?: string },
|
||||
) =>
|
||||
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(target),
|
||||
}),
|
||||
) => http.post<SuccessResponse>(`${extraPath(name)}/targets`, target),
|
||||
previewExtraFilter: (name: string, include: string[], exclude: string[]) =>
|
||||
apiFetch<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(
|
||||
`/extras/${encodeURIComponent(name)}/preview`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ include, exclude }),
|
||||
},
|
||||
http.post<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(
|
||||
`${extraPath(name)}/preview`,
|
||||
{ include, exclude },
|
||||
),
|
||||
// A new path or file name also clears the old place and syncs.
|
||||
editExtraTarget: (
|
||||
name: string,
|
||||
path: string,
|
||||
target: {
|
||||
path: string;
|
||||
mode: string;
|
||||
flatten: boolean;
|
||||
extension: string;
|
||||
as: string;
|
||||
include: string[];
|
||||
exclude: string[];
|
||||
},
|
||||
) =>
|
||||
apiFetch<ExtraEditResult>(`/extras/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ path, target }),
|
||||
}),
|
||||
editExtraTarget: (name: string, path: string, target: EditExtraTarget) =>
|
||||
http.put<ExtraEditResult>(`${extraPath(name)}/targets`, { path, target }),
|
||||
// source: omitted = unchanged, '' = the default folder; a new source relinks every target.
|
||||
editExtra: (name: string, data: { name?: string; source?: string }) =>
|
||||
apiFetch<ExtraEditResult>(`/extras/${encodeURIComponent(name)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
http.patch<ExtraEditResult>(extraPath(name), data),
|
||||
removeExtraTarget: (name: string, path: string) =>
|
||||
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'DELETE',
|
||||
body: JSON.stringify({ path }),
|
||||
}),
|
||||
http.delete<SuccessResponse>(`${extraPath(name)}/targets`, { path }),
|
||||
|
||||
listExtraExtensions: () => http.get<{ extensions: string[] }>('/extras/extensions'),
|
||||
listExtensions: () => http.get<{ extensions: ExtensionInfo[] }>('/extensions'),
|
||||
installExtension: (name: string) =>
|
||||
http.post<ExtensionActionResult>('/extensions/install', { name }),
|
||||
openExtensionsDir: () => http.post<{ path: string }>('/extensions/open'),
|
||||
removeExtension: (name: string) =>
|
||||
http.delete<ExtensionActionResult>(`/extensions/${encodeURIComponent(name)}`),
|
||||
};
|
||||
|
||||
+13
-35
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
import type {
|
||||
GitBranches,
|
||||
GitCheckoutResponse,
|
||||
@@ -9,48 +9,26 @@ import type {
|
||||
} from './types/git';
|
||||
|
||||
export const gitApi = {
|
||||
gitStatus: () => apiFetch<GitStatus>('/git/status'),
|
||||
gitStatus: () => http.get<GitStatus>('/git/status'),
|
||||
gitSetRoot: (scope: string, remoteURL?: string) =>
|
||||
apiFetch<{ success: boolean; scope: string; gitRoot: string }>('/git/root', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(remoteURL ? { scope, remoteURL } : { scope }),
|
||||
}),
|
||||
http.post<{ success: boolean; scope: string; gitRoot: string }>(
|
||||
'/git/root',
|
||||
remoteURL ? { scope, remoteURL } : { scope },
|
||||
),
|
||||
gitBranches: (opts?: { fetch?: boolean }) =>
|
||||
apiFetch<GitBranches>(`/git/branches${opts?.fetch ? '?fetch=true' : ''}`),
|
||||
gitCheckout: (branch: string) =>
|
||||
apiFetch<GitCheckoutResponse>('/git/checkout', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ branch }),
|
||||
}),
|
||||
http.get<GitBranches>(`/git/branches${opts?.fetch ? '?fetch=true' : ''}`),
|
||||
gitCheckout: (branch: string) => http.post<GitCheckoutResponse>('/git/checkout', { branch }),
|
||||
gitAbsorbNested: (subdirs: string[]) =>
|
||||
apiFetch<{ success: boolean; disabled: string[] }>('/git/absorb-nested', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ subdirs }),
|
||||
}),
|
||||
http.post<{ success: boolean; disabled: string[] }>('/git/absorb-nested', { subdirs }),
|
||||
gitCommit: (opts: { message?: string; dryRun?: boolean }) =>
|
||||
apiFetch<PushResponse>('/git/commit', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
gitDiscard: (opts: { dryRun?: boolean }) =>
|
||||
apiFetch<PushResponse>('/git/discard', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
push: (opts: { message?: string; dryRun?: boolean }) =>
|
||||
apiFetch<PushResponse>('/push', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
http.post<PushResponse>('/git/commit', opts),
|
||||
gitDiscard: (opts: { dryRun?: boolean }) => http.post<PushResponse>('/git/discard', opts),
|
||||
push: (opts: { message?: string; dryRun?: boolean }) => http.post<PushResponse>('/push', opts),
|
||||
/** force replaces local files with the remote when a first pull cannot merge (error code merge_failed). */
|
||||
pull: (opts?: {
|
||||
dryRun?: boolean;
|
||||
force?: boolean;
|
||||
resolution?: GitPullResolution;
|
||||
alwaysSync?: boolean;
|
||||
}) =>
|
||||
apiFetch<PullResponse>('/pull', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts ?? {}),
|
||||
}),
|
||||
}) => http.post<PullResponse>('/pull', opts ?? {}),
|
||||
};
|
||||
|
||||
+17
-19
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
|
||||
/** The Agents hooks can be managed for, in display order. */
|
||||
export const hookAgents = [
|
||||
@@ -216,48 +216,46 @@ export interface CodexTrustPlan {
|
||||
}[];
|
||||
}
|
||||
|
||||
const post = <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
|
||||
|
||||
export const hooksApi = {
|
||||
list: () => apiFetch<HookInventory>('/hooks'),
|
||||
catalog: () => apiFetch<Record<string, HookAgentCatalog>>('/hooks/catalog'),
|
||||
list: () => http.get<HookInventory>('/hooks'),
|
||||
catalog: () => http.get<Record<string, HookAgentCatalog>>('/hooks/catalog'),
|
||||
/** An empty mutation previews synchronizing the current source. */
|
||||
preview: (mutation: HookMutation = {}) => post<HookPreview>('/hooks/preview', { mutation }),
|
||||
preview: (mutation: HookMutation = {}) => http.post<HookPreview>('/hooks/preview', { mutation }),
|
||||
configure: (mutation: HookMutation, revision: string, sync: boolean) =>
|
||||
post<HookResult>('/hooks', { mutation, revision, sync }),
|
||||
http.post<HookResult>('/hooks', { mutation, revision, sync }),
|
||||
/** Save to the source only. The server refuses a write it has not previewed; the revision also catches concurrent edits. */
|
||||
save: async (mutation: HookMutation) =>
|
||||
post<HookResult>('/hooks', {
|
||||
http.post<HookResult>('/hooks', {
|
||||
mutation,
|
||||
revision: (await post<HookPlan>('/hooks/preview', { mutation })).revision,
|
||||
revision: (await http.post<HookPlan>('/hooks/preview', { mutation })).revision,
|
||||
sync: false,
|
||||
}),
|
||||
/** Each Agent's native contribution of one hook, as sync would write it: its own file(s) and scripts only, never the shared settings. Writes nothing. */
|
||||
render: (mutation: HookMutation) =>
|
||||
post<{ rendered: HookRendered[] }>('/hooks/render', { mutation }),
|
||||
http.post<{ rendered: HookRendered[] }>('/hooks/render', { mutation }),
|
||||
/** Apply only the changes of one hooks.projects root; the global scope and other projects stay pending. */
|
||||
syncProject: (root: string, revision: string) =>
|
||||
post<HookResult>('/hooks', { mutation: {}, revision, sync: true, root }),
|
||||
http.post<HookResult>('/hooks', { mutation: {}, revision, sync: true, root }),
|
||||
/** Reads native configuration or code, or the pasted `content`; nothing is executed. */
|
||||
import: async (body: HookImportRequest) => {
|
||||
const res = await post<{ candidates: HookCandidate[] } | HookCandidate[]>(
|
||||
const res = await http.post<{ candidates: HookCandidate[] } | HookCandidate[]>(
|
||||
'/hooks/import',
|
||||
body,
|
||||
);
|
||||
return Array.isArray(res) ? res : (res.candidates ?? []);
|
||||
},
|
||||
/** What editing or removing unmanaged hooks would write to their target files. Writes nothing. */
|
||||
previewNative: (edits: HookNativeEdit[]) => post<HookPreview>('/hooks/native/preview', { edits }),
|
||||
previewNative: (edits: HookNativeEdit[]) =>
|
||||
http.post<HookPreview>('/hooks/native/preview', { edits }),
|
||||
/** Writes previewed edits, with a backup per file. The hooks stay unmanaged. */
|
||||
applyNative: (edits: HookNativeEdit[], revision: string) =>
|
||||
post<HookResult>('/hooks/native', { edits, revision }),
|
||||
http.post<HookResult>('/hooks/native', { edits, revision }),
|
||||
/** Starts a Codex process to list the hooks, so call it only when the user asks. Global scope only. */
|
||||
previewCodexTrust: () => post<CodexTrustPlan>('/hooks/codex-trust/preview', {}),
|
||||
previewCodexTrust: () => http.post<CodexTrustPlan>('/hooks/codex-trust/preview', {}),
|
||||
/** Records trust for the previewed hooks. Refused (409) when they changed since the preview. */
|
||||
trustCodex: (revision: string) => post<CodexTrustPlan>('/hooks/codex-trust', { revision }),
|
||||
trustCodex: (revision: string) => http.post<CodexTrustPlan>('/hooks/codex-trust', { revision }),
|
||||
previewRestore: (backupId: string) =>
|
||||
post<HookPlan>('/hooks/restore', { backupId, preview: true }),
|
||||
http.post<HookPlan>('/hooks/restore', { backupId, preview: true }),
|
||||
restore: (backupId: string, revision: string) =>
|
||||
post<HookResult>('/hooks/restore', { backupId, revision }),
|
||||
http.post<HookResult>('/hooks/restore', { backupId, revision }),
|
||||
};
|
||||
|
||||
+19
-1
@@ -90,7 +90,8 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...init,
|
||||
});
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (init?.signal?.aborted) throw error;
|
||||
throw new ApiError(0, 'Server connection lost - try restarting with "skillshare ui".', {
|
||||
code: 'connection_lost',
|
||||
});
|
||||
@@ -125,6 +126,23 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export type SuccessResponse = { success: boolean };
|
||||
|
||||
function jsonRequest(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE') {
|
||||
return <T>(path: string, body?: unknown) =>
|
||||
apiFetch<T>(path, { method, body: JSON.stringify(body) });
|
||||
}
|
||||
|
||||
export const http = {
|
||||
get: <T>(path: string, signal?: AbortSignal) => apiFetch<T>(path, { signal }),
|
||||
// Import already-serialized JSON without quoting it a second time.
|
||||
postRaw: <T>(path: string, body: string) => apiFetch<T>(path, { method: 'POST', body }),
|
||||
post: jsonRequest('POST'),
|
||||
put: jsonRequest('PUT'),
|
||||
patch: jsonRequest('PATCH'),
|
||||
delete: jsonRequest('DELETE'),
|
||||
};
|
||||
|
||||
// createSSEStream creates an EventSource with the standard done/error lifecycle.
|
||||
// The `handlers` map registers named SSE event listeners; the special key "done"
|
||||
// is treated as the terminal event that closes the connection.
|
||||
|
||||
+14
-16
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
|
||||
export interface HubEntry {
|
||||
id: string;
|
||||
@@ -40,33 +40,31 @@ export interface HubRefs {
|
||||
source?: string;
|
||||
}
|
||||
const root = '/hub/drafts';
|
||||
const json = (method: string, data: unknown) => ({ method, body: JSON.stringify(data) });
|
||||
|
||||
export const hubDrafts = {
|
||||
list: () => apiFetch<HubDraft[]>(root),
|
||||
get: (id: string) => apiFetch<DraftResponse>(`${root}/${encodeURIComponent(id)}`),
|
||||
candidates: () => apiFetch<HubEntry[]>(`${root}/candidates`),
|
||||
create: (draft: Partial<HubDraft>) => apiFetch<DraftResponse>(root, json('POST', draft)),
|
||||
list: () => http.get<HubDraft[]>(root),
|
||||
get: (id: string) => http.get<DraftResponse>(`${root}/${encodeURIComponent(id)}`),
|
||||
candidates: () => http.get<HubEntry[]>(`${root}/candidates`),
|
||||
create: (draft: Partial<HubDraft>) => http.post<DraftResponse>(root, draft),
|
||||
save: (draft: HubDraft) =>
|
||||
apiFetch<DraftResponse>(`${root}/${encodeURIComponent(draft.id)}`, json('PUT', draft)),
|
||||
http.put<DraftResponse>(`${root}/${encodeURIComponent(draft.id)}`, draft),
|
||||
remove: (draft: HubDraft) =>
|
||||
apiFetch(
|
||||
http.delete(
|
||||
`${root}/${encodeURIComponent(draft.id)}?revision=${encodeURIComponent(draft.revision)}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
import: (raw: string) => apiFetch<DraftResponse>(`${root}/import`, { method: 'POST', body: raw }),
|
||||
import: (raw: string) => http.postRaw<DraftResponse>(`${root}/import`, raw),
|
||||
export: (draft: HubDraft) =>
|
||||
apiFetch<Record<string, unknown>>(
|
||||
`${root}/${encodeURIComponent(draft.id)}/export`,
|
||||
json('POST', { revision: draft.revision }),
|
||||
),
|
||||
http.post<Record<string, unknown>>(`${root}/${encodeURIComponent(draft.id)}/export`, {
|
||||
revision: draft.revision,
|
||||
}),
|
||||
};
|
||||
|
||||
/** Lists a source's branches and tags; with `ref` ("" = default branch), also returns the source rewritten to it. */
|
||||
export const hubRefs = (source: string, ref?: string) =>
|
||||
apiFetch<HubRefs>('/hub/refs', json('POST', ref === undefined ? { source } : { source, ref }));
|
||||
http.post<HubRefs>('/hub/refs', ref === undefined ? { source } : { source, ref });
|
||||
/** Lists a git source's branches and tags, also when its URL cannot pin a ref (SSH, other hosts). */
|
||||
export const gitRefs = (source: string) =>
|
||||
apiFetch<HubRefs>('/hub/refs', json('POST', { source, anyGit: true }));
|
||||
http.post<HubRefs>('/hub/refs', { source, anyGit: true });
|
||||
|
||||
export function hubAddCommand(location: string, label: string): string {
|
||||
const quote = (s: string) => `'${s.replace(/'/g, `'"'"'`)}'`;
|
||||
|
||||
+15
-35
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, BASE, createSSEStream } from './http';
|
||||
import { http, BASE, createSSEStream } from './http';
|
||||
import type {
|
||||
BatchInstallResult,
|
||||
CheckResult,
|
||||
@@ -15,31 +15,23 @@ import type {
|
||||
} from './types/install';
|
||||
|
||||
export const installApi = {
|
||||
hubIndex: () => apiFetch<HubIndex>('/hub/index'),
|
||||
getHubConfig: () => apiFetch<HubConfigResponse>('/hub/saved'),
|
||||
hubIndex: () => http.get<HubIndex>('/hub/index'),
|
||||
getHubConfig: () => http.get<HubConfigResponse>('/hub/saved'),
|
||||
putHubConfig: (data: { hubs: HubSavedEntry[]; default: string }) =>
|
||||
apiFetch<{ success: boolean }>('/hub/saved', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
http.put<{ success: boolean }>('/hub/saved', data),
|
||||
addHub: (hub: { label: string; url: string }) =>
|
||||
apiFetch<{ success: boolean }>('/hub/saved', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(hub),
|
||||
}),
|
||||
http.post<{ success: boolean }>('/hub/saved', hub),
|
||||
removeHub: (label: string) =>
|
||||
apiFetch<{ success: boolean }>(`/hub/saved/${encodeURIComponent(label)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean }>(`/hub/saved/${encodeURIComponent(label)}`),
|
||||
search: (q: string, limit = 20) =>
|
||||
apiFetch<{ results: SearchResult[] }>(`/search?q=${encodeURIComponent(q)}&limit=${limit}`),
|
||||
http.get<{ results: SearchResult[] }>(`/search?q=${encodeURIComponent(q)}&limit=${limit}`),
|
||||
searchHub: (q: string, hubURL: string) =>
|
||||
apiFetch<{ results: SearchResult[] }>(
|
||||
http.get<{ results: SearchResult[] }>(
|
||||
`/search?q=${encodeURIComponent(q)}&hub=${encodeURIComponent(hubURL)}`,
|
||||
),
|
||||
preview: (source: string) =>
|
||||
apiFetch<SkillPreview>(`/preview?source=${encodeURIComponent(source)}`),
|
||||
check: () => apiFetch<CheckResult>('/check'),
|
||||
http.get<SkillPreview>(`/preview?source=${encodeURIComponent(source)}`),
|
||||
check: () => http.get<CheckResult>('/check'),
|
||||
checkStream: (
|
||||
onDiscovering: () => void,
|
||||
onStart: (total: number) => void,
|
||||
@@ -59,10 +51,7 @@ export const installApi = {
|
||||
'Check stream failed',
|
||||
),
|
||||
discover: (source: string, branch?: string) =>
|
||||
apiFetch<DiscoverResult>('/discover', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source, branch }),
|
||||
}),
|
||||
http.post<DiscoverResult>('/discover', { source, branch }),
|
||||
install: (opts: {
|
||||
source: string;
|
||||
name?: string;
|
||||
@@ -72,16 +61,11 @@ export const installApi = {
|
||||
into?: string;
|
||||
branch?: string;
|
||||
kind?: 'skill' | 'agent';
|
||||
}) =>
|
||||
apiFetch<InstallResult>('/install', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
}) => http.post<InstallResult>('/install', opts),
|
||||
// Entries recorded in config but not on disk (bare `skillshare install`)
|
||||
missingConfigEntries: () =>
|
||||
apiFetch<{ entries: ConfigEntry[]; file: string }>('/install/missing'),
|
||||
installFromConfig: () =>
|
||||
apiFetch<InstallFromConfigResult>('/install/from-config', { method: 'POST' }),
|
||||
http.get<{ entries: ConfigEntry[]; file: string }>('/install/missing'),
|
||||
installFromConfig: () => http.post<InstallFromConfigResult>('/install/from-config'),
|
||||
installBatch: (opts: {
|
||||
source: string;
|
||||
skills: DiscoveredSkill[];
|
||||
@@ -91,9 +75,5 @@ export const installApi = {
|
||||
name?: string;
|
||||
branch?: string;
|
||||
kind?: 'skill' | 'agent';
|
||||
}) =>
|
||||
apiFetch<BatchInstallResult>('/install/batch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
}) => http.post<BatchInstallResult>('/install/batch', opts),
|
||||
};
|
||||
|
||||
+41
-82
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
import type {
|
||||
ConvertMethod,
|
||||
InstructionsChange,
|
||||
@@ -16,11 +16,10 @@ import type {
|
||||
|
||||
export const instructionsApi = {
|
||||
getTargetInstructions: (name: string) =>
|
||||
apiFetch<TargetInstructions>(`/targets/${encodeURIComponent(name)}/instructions`),
|
||||
http.get<TargetInstructions>(`/targets/${encodeURIComponent(name)}/instructions`),
|
||||
putTargetInstructions: (name: string, content: string) =>
|
||||
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ content }),
|
||||
http.put<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions`, {
|
||||
content,
|
||||
}),
|
||||
convertTargetInstructions: (
|
||||
name: string,
|
||||
@@ -32,123 +31,89 @@ export const instructionsApi = {
|
||||
apply: boolean;
|
||||
},
|
||||
) =>
|
||||
apiFetch<{ changes: InstructionsChange[] }>(
|
||||
http.post<{ changes: InstructionsChange[] }>(
|
||||
`/targets/${encodeURIComponent(name)}/instructions/convert`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
body,
|
||||
),
|
||||
setTargetInstructionsSetup: (name: string, setup: TargetInstructionsSetup) =>
|
||||
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(setup),
|
||||
}),
|
||||
http.put<{ success: boolean }>(
|
||||
`/targets/${encodeURIComponent(name)}/instructions/setup`,
|
||||
setup,
|
||||
),
|
||||
removeTargetInstructionsSetup: (name: string) =>
|
||||
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`),
|
||||
// A target's other files
|
||||
listTargetFiles: (name: string) =>
|
||||
apiFetch<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`),
|
||||
http.get<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`),
|
||||
getTargetFile: (name: string, path: string) =>
|
||||
apiFetch<TargetFile & { content: string }>(
|
||||
http.get<TargetFile & { content: string }>(
|
||||
`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`,
|
||||
),
|
||||
putTargetFile: (name: string, path: string, content: string) =>
|
||||
apiFetch<TargetFile & { content: string }>(
|
||||
http.put<TargetFile & { content: string }>(
|
||||
`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ content }),
|
||||
},
|
||||
{ content },
|
||||
),
|
||||
addTargetFile: (name: string, path: string) =>
|
||||
apiFetch<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path }),
|
||||
}),
|
||||
http.post<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`, { path }),
|
||||
removeTargetFile: (name: string, path: string) =>
|
||||
apiFetch<TargetFileList>(
|
||||
http.delete<TargetFileList>(
|
||||
`/targets/${encodeURIComponent(name)}/files?path=${encodeURIComponent(path)}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
listSharedInstructions: () =>
|
||||
apiFetch<{
|
||||
http.get<{
|
||||
files: SharedInstructionsFile[];
|
||||
targets: SharedInstructionsTarget[];
|
||||
file_links: boolean;
|
||||
}>('/instructions'),
|
||||
createSharedInstructions: (body: { name: string; content?: string; from_target?: string }) =>
|
||||
apiFetch<{ success: boolean; path: string }>('/instructions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
http.post<{ success: boolean; path: string }>('/instructions', body),
|
||||
getSharedInstructionsContent: (name: string) =>
|
||||
apiFetch<{ name: string; path: string; exists: boolean; content: string }>(
|
||||
http.get<{ name: string; path: string; exists: boolean; content: string }>(
|
||||
`/instructions/${encodeURIComponent(name)}/content`,
|
||||
),
|
||||
/** Saves the shared file; its copy targets are rewritten too (copies). */
|
||||
putSharedInstructionsContent: (name: string, content: string) =>
|
||||
apiFetch<{ success: boolean; copies?: SharedCopyResult[] }>(
|
||||
http.put<{ success: boolean; copies?: SharedCopyResult[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/content`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ content }),
|
||||
},
|
||||
{ content },
|
||||
),
|
||||
/** Sets exactly which shared files each target uses; [] restores their own files. */
|
||||
assignSharedInstructions: (targets: string[], extras: string[]) =>
|
||||
apiFetch<{ success: boolean; errors: string[]; warnings?: InstructionsWarning[] }>(
|
||||
http.post<{ success: boolean; errors: string[]; warnings?: InstructionsWarning[] }>(
|
||||
'/instructions/assign',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targets, extras }),
|
||||
},
|
||||
{ targets, extras },
|
||||
),
|
||||
restoreSharedInstructions: (name: string, target: string) =>
|
||||
apiFetch<{ success: boolean; errors: string[] }>(
|
||||
http.post<{ success: boolean; errors: string[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/restore`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target }),
|
||||
},
|
||||
{ target },
|
||||
),
|
||||
setSharedInstructionsMode: (name: string, target: string, mode: string) =>
|
||||
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
http.put<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/targets/${encodeURIComponent(target)}/mode`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ mode }),
|
||||
},
|
||||
{ mode },
|
||||
),
|
||||
getSharedRestorePreview: (name: string, target: string) =>
|
||||
apiFetch<SharedRestorePreview>(
|
||||
http.get<SharedRestorePreview>(
|
||||
`/instructions/${encodeURIComponent(name)}/restore-preview?target=${encodeURIComponent(target)}`,
|
||||
),
|
||||
addInstructionLocation: (name: string, body: { path: string; as?: string; mode?: string }) =>
|
||||
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
http.post<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/locations`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
body,
|
||||
),
|
||||
setInstructionLocationMode: (name: string, path: string, mode: string) =>
|
||||
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
http.put<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/locations/mode`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ path, mode }),
|
||||
},
|
||||
{ path, mode },
|
||||
),
|
||||
removeInstructionLocation: (name: string, path: string) =>
|
||||
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
http.delete<{ success: boolean; warnings?: InstructionsWarning[] }>(
|
||||
`/instructions/${encodeURIComponent(name)}/locations?path=${encodeURIComponent(path)}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
getLocationRestorePreview: (name: string, path: string) =>
|
||||
apiFetch<SharedRestorePreview>(
|
||||
http.get<SharedRestorePreview>(
|
||||
`/instructions/${encodeURIComponent(name)}/locations/restore-preview?path=${encodeURIComponent(path)}`,
|
||||
),
|
||||
/** Settles a modified target, or a location when `on` has its `path`. */
|
||||
@@ -157,19 +122,13 @@ export const instructionsApi = {
|
||||
on: { target: string } | { path: string },
|
||||
action: 'collect' | 'reapply',
|
||||
) =>
|
||||
apiFetch<{ success: boolean }>(`/instructions/${encodeURIComponent(name)}/resolve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...on, action }),
|
||||
http.post<{ success: boolean }>(`/instructions/${encodeURIComponent(name)}/resolve`, {
|
||||
...on,
|
||||
action,
|
||||
}),
|
||||
getProjectInstructions: () => apiFetch<ProjectInstructions>('/instructions/project'),
|
||||
getProjectInstructions: () => http.get<ProjectInstructions>('/instructions/project'),
|
||||
putProjectInstructions: (content: string) =>
|
||||
apiFetch<{ success: boolean }>('/instructions/project', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ content }),
|
||||
}),
|
||||
http.put<{ success: boolean }>('/instructions/project', { content }),
|
||||
addProjectInstructionsShim: (target: string) =>
|
||||
apiFetch<{ success: boolean }>('/instructions/project/shim', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target }),
|
||||
}),
|
||||
http.post<{ success: boolean }>('/instructions/project/shim', { target }),
|
||||
};
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { apiFetch } from './http';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { auditApi } from './audit';
|
||||
import { resourcesApi } from './resources';
|
||||
|
||||
vi.mock('./http', async (load) => ({
|
||||
...(await load<typeof import('./http')>()),
|
||||
apiFetch: vi.fn(),
|
||||
}));
|
||||
const fetch = vi.fn<typeof globalThis.fetch>();
|
||||
|
||||
// The kind unions are closed today; a cast stands in for a value that needs escaping.
|
||||
const odd = 'a&b' as 'skill';
|
||||
|
||||
describe('?kind= query', () => {
|
||||
beforeEach(() => vi.mocked(apiFetch).mockReset());
|
||||
beforeEach(() => {
|
||||
fetch.mockReset().mockImplementation(async () => Response.json({}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('is encoded on resource requests', async () => {
|
||||
await resourcesApi.getResource('demo', odd);
|
||||
|
||||
expect(vi.mocked(apiFetch).mock.calls[0][0]).toBe('/resources/demo?kind=a%26b');
|
||||
expect(fetch.mock.calls[0][0]).toBe('/api/resources/demo?kind=a%26b');
|
||||
});
|
||||
|
||||
it('is encoded on audit requests', async () => {
|
||||
await auditApi.auditAll(odd as unknown as 'skills');
|
||||
|
||||
expect(vi.mocked(apiFetch).mock.calls[0][0]).toBe('/audit?kind=a%26b');
|
||||
expect(fetch.mock.calls[0][0]).toBe('/api/audit?kind=a%26b');
|
||||
});
|
||||
|
||||
it('is left off without a kind', async () => {
|
||||
await resourcesApi.listSkills();
|
||||
await auditApi.auditAll();
|
||||
|
||||
expect(vi.mocked(apiFetch).mock.calls.map(([path]) => path)).toEqual(['/resources', '/audit']);
|
||||
expect(fetch.mock.calls.map(([path]) => path)).toEqual(['/api/resources', '/api/audit']);
|
||||
});
|
||||
});
|
||||
|
||||
+4
-5
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
import type { LogListResponse, LogStatsResponse } from './types/log';
|
||||
|
||||
export const logApi = {
|
||||
@@ -13,16 +13,15 @@ export const logApi = {
|
||||
if (filters?.cmd) params.set('cmd', filters.cmd);
|
||||
if (filters?.status) params.set('status', filters.status);
|
||||
if (filters?.since) params.set('since', filters.since);
|
||||
return apiFetch<LogListResponse>(`/log?${params.toString()}`);
|
||||
return http.get<LogListResponse>(`/log?${params.toString()}`);
|
||||
},
|
||||
clearLog: (type?: string) =>
|
||||
apiFetch<{ success: boolean }>(`/log?type=${type ?? 'ops'}`, { method: 'DELETE' }),
|
||||
clearLog: (type?: string) => http.delete<{ success: boolean }>(`/log?type=${type ?? 'ops'}`),
|
||||
getLogStats: (type?: string, filters?: { cmd?: string; status?: string; since?: string }) => {
|
||||
const params = new URLSearchParams();
|
||||
params.set('type', type ?? 'ops');
|
||||
if (filters?.cmd) params.set('cmd', filters.cmd);
|
||||
if (filters?.status) params.set('status', filters.status);
|
||||
if (filters?.since) params.set('since', filters.since);
|
||||
return apiFetch<LogStatsResponse>(`/log/stats?${params.toString()}`);
|
||||
return http.get<LogStatsResponse>(`/log/stats?${params.toString()}`);
|
||||
},
|
||||
};
|
||||
|
||||
+20
-22
@@ -1,26 +1,24 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { apiFetch } from './client';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { mcpApi } from './mcp';
|
||||
|
||||
vi.mock('./client', () => ({ apiFetch: vi.fn() }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('mcpApi.save', () => {
|
||||
it('previews the mutation and saves with its revision', async () => {
|
||||
vi.mocked(apiFetch)
|
||||
.mockResolvedValueOnce({ revision: 'rev-1' })
|
||||
.mockResolvedValueOnce({ applied: [] });
|
||||
const mutation = { name: 'docs', server: { url: 'https://docs.example/mcp' } };
|
||||
await mcpApi.save(mutation);
|
||||
expect(
|
||||
vi
|
||||
.mocked(apiFetch)
|
||||
.mock.calls.map(([path, init]) => [
|
||||
path,
|
||||
typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body,
|
||||
]),
|
||||
).toEqual([
|
||||
['/mcp/preview', { mutation }],
|
||||
['/mcp', { mutation, revision: 'rev-1', sync: false }],
|
||||
]);
|
||||
});
|
||||
it('previews the mutation and saves with its revision', async () => {
|
||||
const fetch = vi
|
||||
.fn<typeof globalThis.fetch>()
|
||||
.mockResolvedValueOnce(Response.json({ revision: 'rev-1' }))
|
||||
.mockResolvedValueOnce(Response.json({ applied: [] }));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const mutation = { name: 'docs', server: { url: 'https://docs.example/mcp' } };
|
||||
await mcpApi.save(mutation);
|
||||
expect(
|
||||
fetch.mock.calls.map(([url, init]) => [
|
||||
url,
|
||||
init?.method,
|
||||
typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body,
|
||||
]),
|
||||
).toEqual([
|
||||
['/api/mcp/preview', 'POST', { mutation }],
|
||||
['/api/mcp', 'POST', { mutation, revision: 'rev-1', sync: false }],
|
||||
]);
|
||||
});
|
||||
|
||||
+14
-14
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
|
||||
export const mcpTargets = [
|
||||
'claude',
|
||||
@@ -125,11 +125,10 @@ export interface MCPImportSource {
|
||||
path: string;
|
||||
piExtension?: string;
|
||||
}
|
||||
const post = <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
|
||||
|
||||
export const mcpApi = {
|
||||
list: () =>
|
||||
apiFetch<{
|
||||
http.get<{
|
||||
source: {
|
||||
path: string;
|
||||
configPath: string;
|
||||
@@ -161,23 +160,23 @@ export const mcpApi = {
|
||||
backups: MCPBackup[];
|
||||
unmanaged: MCPUnmanaged[];
|
||||
}>('/mcp'),
|
||||
preview: (mutation: MCPMutation = {}) => post<MCPPlan>('/mcp/preview', { mutation }),
|
||||
preview: (mutation: MCPMutation = {}) => http.post<MCPPlan>('/mcp/preview', { mutation }),
|
||||
configure: (mutation: MCPMutation, revision: string, sync: boolean) =>
|
||||
post<MCPResult>('/mcp', { mutation, revision, sync }),
|
||||
http.post<MCPResult>('/mcp', { mutation, revision, sync }),
|
||||
/** Apply only the changes of one mcp.projects root; the global scope and other projects stay pending. */
|
||||
syncProject: (root: string, revision: string) =>
|
||||
post<MCPResult>('/mcp', { mutation: {}, revision, sync: true, root }),
|
||||
http.post<MCPResult>('/mcp', { mutation: {}, revision, sync: true, root }),
|
||||
/** Save to the source only. The server refuses a write it has not previewed; the revision also catches concurrent edits. */
|
||||
save: async (mutation: MCPMutation) =>
|
||||
post<MCPResult>('/mcp', {
|
||||
http.post<MCPResult>('/mcp', {
|
||||
mutation,
|
||||
revision: (await post<MCPPlan>('/mcp/preview', { mutation })).revision,
|
||||
revision: (await http.post<MCPPlan>('/mcp/preview', { mutation })).revision,
|
||||
sync: false,
|
||||
}),
|
||||
/** One server as each of its targets' config files would hold it. Reads configuration only; no server is executed and no file is written. */
|
||||
/** `toolGaps`: the parts of the server's tool policy that Agent does not apply. */
|
||||
render: (mutation: MCPMutation) =>
|
||||
post<{
|
||||
http.post<{
|
||||
rendered: {
|
||||
target: string;
|
||||
path: string;
|
||||
@@ -193,11 +192,12 @@ export const mcpApi = {
|
||||
name?: string;
|
||||
root?: string;
|
||||
piExtension?: string;
|
||||
}) => post<{ candidates: MCPCandidate[] }>('/mcp/import', body),
|
||||
previewRestore: (backupId: string) => post<MCPPlan>('/mcp/restore', { backupId, preview: true }),
|
||||
}) => http.post<{ candidates: MCPCandidate[] }>('/mcp/import', body),
|
||||
previewRestore: (backupId: string) =>
|
||||
http.post<MCPPlan>('/mcp/restore', { backupId, preview: true }),
|
||||
restore: (backupId: string, revision: string) =>
|
||||
post<MCPResult>('/mcp/restore', { backupId, revision }),
|
||||
http.post<MCPResult>('/mcp/restore', { backupId, revision }),
|
||||
/** Open one Agent's config file, as listed in `paths` or `projectPaths`, the way the skill page opens a skill; `folder` opens its directory instead. */
|
||||
open: (target: string, opts: { project?: string; folder?: boolean } = {}) =>
|
||||
post<{ editor: string; path: string; pid: number }>('/mcp/open', { target, ...opts }),
|
||||
http.post<{ editor: string; path: string; pid: number }>('/mcp/open', { target, ...opts }),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
import type { MCPMutation } from './mcp';
|
||||
|
||||
/** One result of `skillshare mcp check`. `subject` names the variable, command, package, image, or host; never a value. */
|
||||
@@ -32,8 +32,7 @@ export interface MCPProbe {
|
||||
|
||||
export const mcpCheckApi = {
|
||||
/** Read-only. Findings that are errors still resolve; only a check that cannot run rejects. */
|
||||
run: () => apiFetch<MCPCheckReport>('/mcp/check'),
|
||||
run: () => http.get<MCPCheckReport>('/mcp/check'),
|
||||
/** Starts the server as the form describes it, saved or not, and asks for its tools. Saves nothing. */
|
||||
probe: (mutation: MCPMutation) =>
|
||||
apiFetch<MCPProbe>('/mcp/probe', { method: 'POST', body: JSON.stringify({ mutation }) }),
|
||||
probe: (mutation: MCPMutation) => http.post<MCPProbe>('/mcp/probe', { mutation }),
|
||||
};
|
||||
|
||||
+15
-31
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
|
||||
export interface MemoryNote {
|
||||
path: string;
|
||||
@@ -66,51 +66,35 @@ export interface MemoryOverviewResponse {
|
||||
}
|
||||
|
||||
export const memoryApi = {
|
||||
getMemoryOverview: () => apiFetch<MemoryOverviewResponse>('/extras/memory/recent'),
|
||||
getMemoryOverview: () => http.get<MemoryOverviewResponse>('/extras/memory/recent'),
|
||||
listMemoryNotes: (search = '') =>
|
||||
apiFetch<MemoryNotesResponse>(`/extras/memory/notes?search=${encodeURIComponent(search)}`),
|
||||
initMemory: () =>
|
||||
apiFetch<{ success: boolean; root: string }>('/extras/memory/init', { method: 'POST' }),
|
||||
getMemoryGuidance: () => apiFetch<MemoryGuidance>('/extras/memory/guidance'),
|
||||
http.get<MemoryNotesResponse>(`/extras/memory/notes?search=${encodeURIComponent(search)}`),
|
||||
initMemory: () => http.post<{ success: boolean; root: string }>('/extras/memory/init'),
|
||||
getMemoryGuidance: () => http.get<MemoryGuidance>('/extras/memory/guidance'),
|
||||
planMemoryGuidance: (targets: string[], modes: Record<string, MemoryUpdateMode>) =>
|
||||
apiFetch<MemoryGuidancePlan>('/extras/memory/guidance/plan', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targets, modes }),
|
||||
}),
|
||||
http.post<MemoryGuidancePlan>('/extras/memory/guidance/plan', { targets, modes }),
|
||||
applyMemoryGuidance: (
|
||||
targets: string[],
|
||||
modes: Record<string, MemoryUpdateMode>,
|
||||
token: string,
|
||||
) =>
|
||||
apiFetch<{
|
||||
http.post<{
|
||||
success: boolean;
|
||||
applied: string[];
|
||||
errors: { path: string; error: string }[];
|
||||
targets: MemoryGuidanceTarget[];
|
||||
}>('/extras/memory/guidance/apply', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targets, modes, token }),
|
||||
}),
|
||||
}>('/extras/memory/guidance/apply', { targets, modes, token }),
|
||||
linkMemoryIndex: (path: string, version: string) =>
|
||||
apiFetch<MemoryNote>('/extras/memory/index', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ path, version }),
|
||||
}),
|
||||
http.put<MemoryNote>('/extras/memory/index', { path, version }),
|
||||
readMemoryNote: (path: string) =>
|
||||
apiFetch<MemoryNote>(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`),
|
||||
http.get<MemoryNote>(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`),
|
||||
writeMemoryNote: (path: string, content: string, version: string) =>
|
||||
apiFetch<MemoryNote>('/extras/memory/notes/content', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ path, content, version }),
|
||||
}),
|
||||
http.put<MemoryNote>('/extras/memory/notes/content', { path, content, version }),
|
||||
moveMemoryNote: (path: string, newPath: string, version: string) =>
|
||||
apiFetch<MemoryNote>('/extras/memory/move', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path, new_path: newPath, version }),
|
||||
}),
|
||||
http.post<MemoryNote>('/extras/memory/move', { path, new_path: newPath, version }),
|
||||
deleteMemoryNote: (path: string, version: string) =>
|
||||
apiFetch<{ success: boolean; path: string }>('/extras/memory/notes/content', {
|
||||
method: 'DELETE',
|
||||
body: JSON.stringify({ path, version }),
|
||||
http.delete<{ success: boolean; path: string }>('/extras/memory/notes/content', {
|
||||
path,
|
||||
version,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
|
||||
/** Where an extension row comes from: a file in the extensions folder, a settings entry, a plugin, or a Skillshare hook. */
|
||||
export type OmpExtensionSource = 'native' | 'configured' | 'plugin' | 'hook';
|
||||
@@ -61,13 +61,10 @@ export interface OmpExtensionsPlan {
|
||||
|
||||
const base = (target: string) => `/targets/${encodeURIComponent(target)}/omp-extensions`;
|
||||
const post = (target: string, verb: string, changes: OmpExtensionChange[], revision: string) =>
|
||||
apiFetch<OmpExtensionsPlan>(`${base(target)}/${verb}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ changes, revision }),
|
||||
});
|
||||
http.post<OmpExtensionsPlan>(`${base(target)}/${verb}`, { changes, revision });
|
||||
|
||||
export const ompExtensionsApi = {
|
||||
get: (target: string) => apiFetch<OmpExtensionsView>(base(target)),
|
||||
get: (target: string) => http.get<OmpExtensionsView>(base(target)),
|
||||
/** Writes nothing; `revision` is the view's. */
|
||||
preview: (target: string, changes: OmpExtensionChange[], revision: string) =>
|
||||
post(target, 'preview', changes, revision),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
|
||||
/** What a Pi target's settings select for an extension; whether Pi loaded it is never known here. */
|
||||
export type PiSelection = 'loads' | 'skipped' | 'unknown' | 'none';
|
||||
@@ -118,18 +118,12 @@ export interface PiExtensionsPlan {
|
||||
const base = (target: string) => `/targets/${encodeURIComponent(target)}/pi-extensions`;
|
||||
|
||||
export const piExtensionsApi = {
|
||||
get: (target: string) => apiFetch<PiExtensionsView>(base(target)),
|
||||
get: (target: string) => http.get<PiExtensionsView>(base(target)),
|
||||
/** Writes nothing; the plan's revision is what apply checks the file against. */
|
||||
preview: (target: string, changes: PiExtensionChange[]) =>
|
||||
apiFetch<PiExtensionsPlan>(`${base(target)}/preview`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ changes }),
|
||||
}),
|
||||
http.post<PiExtensionsPlan>(`${base(target)}/preview`, { changes }),
|
||||
apply: (target: string, changes: PiExtensionChange[], revision: string) =>
|
||||
apiFetch<PiExtensionsPlan>(`${base(target)}/apply`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ changes, revision }),
|
||||
}),
|
||||
http.post<PiExtensionsPlan>(`${base(target)}/apply`, { changes, revision }),
|
||||
};
|
||||
|
||||
/** A target whose Agent is Pi: pi itself or a Pi account. A project's Pi has its tab on the project page. */
|
||||
|
||||
+19
-15
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { apiFetch } from './client';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
type PluginBinding,
|
||||
bindingStatus,
|
||||
@@ -9,22 +8,27 @@ import {
|
||||
syncAction,
|
||||
} from './plugins';
|
||||
|
||||
vi.mock('./client', () => ({ apiFetch: vi.fn() }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('pluginsApi.list', () => {
|
||||
it('reads a null installed list as empty', async () => {
|
||||
vi.mocked(apiFetch).mockResolvedValueOnce({
|
||||
packages: {},
|
||||
hosts: [
|
||||
{
|
||||
target: 'opencode',
|
||||
version: '1.18.32',
|
||||
status: 'blocked',
|
||||
error: 'both opencode.json and opencode.jsonc exist',
|
||||
installed: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValueOnce(
|
||||
Response.json({
|
||||
packages: {},
|
||||
hosts: [
|
||||
{
|
||||
target: 'opencode',
|
||||
version: '1.18.32',
|
||||
status: 'blocked',
|
||||
error: 'both opencode.json and opencode.jsonc exist',
|
||||
installed: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
const inv = await pluginsApi.list();
|
||||
expect(inv.hosts[0].installed).toEqual([]);
|
||||
});
|
||||
|
||||
+8
-10
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './client';
|
||||
import { http } from './http';
|
||||
import { BASE, createSSEStream, parseApiErrorPayload } from './http';
|
||||
|
||||
export type PluginTarget = string;
|
||||
@@ -336,12 +336,10 @@ async function updateStream(items: PluginUpdateItem[], on: (e: PluginUpdateEvent
|
||||
}
|
||||
}
|
||||
|
||||
const post = <T>(path: string, body: unknown) =>
|
||||
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
|
||||
export const pluginsApi = {
|
||||
/** `hosts: false` answers from config alone, without waiting on any Agent's CLI; `hosts` comes back empty. */
|
||||
list: (hosts = true) =>
|
||||
apiFetch<PluginInventory>(hosts ? '/plugins' : '/plugins?hosts=false').then((inv) => ({
|
||||
http.get<PluginInventory>(hosts ? '/plugins' : '/plugins?hosts=false').then((inv) => ({
|
||||
...inv,
|
||||
// A failed inventory could arrive as null; one Agent must not break the whole page.
|
||||
hosts: inv.hosts.map((h) => ({
|
||||
@@ -351,15 +349,15 @@ export const pluginsApi = {
|
||||
})),
|
||||
/** `name` is a plugin already managed here: its reviewed copy answers instead of downloading the source again. */
|
||||
discover: (source: string, sourceRef?: string, entry?: string, name?: string) =>
|
||||
post<PluginDiscovery>('/plugins/discover', { source, sourceRef, entry, name }),
|
||||
http.post<PluginDiscovery>('/plugins/discover', { source, sourceRef, entry, name }),
|
||||
/** The reviewed local copy of the plugin's source; empty for an imported plugin, which has none. */
|
||||
files: (name: string) =>
|
||||
apiFetch<{ files: string[] }>(`/plugins/${encodeURIComponent(name)}/files`),
|
||||
http.get<{ files: string[] }>(`/plugins/${encodeURIComponent(name)}/files`),
|
||||
file: (name: string, path: string) =>
|
||||
apiFetch<{ content: string }>(
|
||||
http.get<{ content: string }>(
|
||||
`/plugins/${encodeURIComponent(name)}/files/${path.split('/').map(encodeURIComponent).join('/')}`,
|
||||
),
|
||||
preview: (request: PluginRequest) => post<PluginPlan>('/plugins/preview', { request }),
|
||||
preview: (request: PluginRequest) => http.post<PluginPlan>('/plugins/preview', { request }),
|
||||
/** Checks every plugin at once on the server; each plugin's answer arrives through `on` as soon as it is ready. */
|
||||
check: (on: (e: PluginCheckEvent) => void) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
@@ -374,9 +372,9 @@ export const pluginsApi = {
|
||||
);
|
||||
}),
|
||||
apply: (request: PluginRequest, revision: string) =>
|
||||
post<PluginResult>('/plugins/apply', { request, revision }),
|
||||
http.post<PluginResult>('/plugins/apply', { request, revision }),
|
||||
/** Updates the plugins one after another on the server; each one's progress arrives through `on`. */
|
||||
update: updateStream,
|
||||
/** The plugin under way finishes; no other starts. */
|
||||
stopUpdate: () => post<{ stopping: boolean }>('/plugins/update/stop', {}),
|
||||
stopUpdate: () => http.post<{ stopping: boolean }>('/plugins/update/stop', {}),
|
||||
};
|
||||
|
||||
@@ -43,6 +43,28 @@ describe('source links API', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('resource list transport', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('preserves cancellation rather than reporting a lost connection', async () => {
|
||||
const controller = new AbortController();
|
||||
const fetch = vi.fn<typeof globalThis.fetch>(
|
||||
(_, init) =>
|
||||
new Promise((_, reject) =>
|
||||
init?.signal?.addEventListener('abort', () => reject(controller.signal.reason)),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const request = resourcesApi.listSkills('agent', controller.signal);
|
||||
controller.abort();
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/resources?kind=agent',
|
||||
expect.objectContaining({ signal: controller.signal }),
|
||||
);
|
||||
await expect(request).rejects.toBe(controller.signal.reason);
|
||||
});
|
||||
});
|
||||
|
||||
describe('repo removal intent', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
|
||||
+33
-68
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, kindQuery } from './http';
|
||||
import { http, kindQuery } from './http';
|
||||
import type {
|
||||
BatchToggleResult,
|
||||
MoveRequest,
|
||||
@@ -21,51 +21,38 @@ import type {
|
||||
} from './types/resources';
|
||||
|
||||
export const resourcesApi = {
|
||||
createSourceLink: (body: SourceLinkRequest) =>
|
||||
apiFetch<SourceLinkResult>('/source-links', { method: 'POST', body: JSON.stringify(body) }),
|
||||
createSourceLink: (body: SourceLinkRequest) => http.post<SourceLinkResult>('/source-links', body),
|
||||
removeSourceLink: (name: string) =>
|
||||
apiFetch<{ success: boolean; name: string; warning?: string }>(
|
||||
http.delete<{ success: boolean; name: string; warning?: string }>(
|
||||
`/source-links/${encodeURIComponent(name)}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
getOverview: () => apiFetch<Overview>('/overview'),
|
||||
listSkills: (kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{
|
||||
getOverview: () => http.get<Overview>('/overview'),
|
||||
listSkills: (kind?: 'skill' | 'agent', signal?: AbortSignal) =>
|
||||
http.get<{
|
||||
resources: Skill[];
|
||||
sourceLinks?: SourceLink[];
|
||||
sourceLinkWarnings?: string[];
|
||||
linked_repos?: LinkedRepo[];
|
||||
}>(`/resources${kindQuery(kind)}`),
|
||||
}>(`/resources${kindQuery(kind)}`, signal),
|
||||
getResource: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ resource: Skill; skillMdContent: string; files: string[] }>(
|
||||
http.get<{ resource: Skill; skillMdContent: string; files: string[] }>(
|
||||
`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`,
|
||||
),
|
||||
deleteResource: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean }>(`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean }>(`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`),
|
||||
disableResource: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean; name: string; disabled: boolean }>(
|
||||
http.post<{ success: boolean; name: string; disabled: boolean }>(
|
||||
`/resources/${encodeURIComponent(name)}/disable${kindQuery(kind)}`,
|
||||
{ method: 'POST' },
|
||||
),
|
||||
enableResource: (name: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean; name: string; disabled: boolean }>(
|
||||
http.post<{ success: boolean; name: string; disabled: boolean }>(
|
||||
`/resources/${encodeURIComponent(name)}/enable${kindQuery(kind)}`,
|
||||
{ method: 'POST' },
|
||||
),
|
||||
batchUninstall: (opts: BatchUninstallRequest) =>
|
||||
apiFetch<BatchUninstallResult>('/uninstall/batch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
moveResources: (opts: MoveRequest) =>
|
||||
apiFetch<MoveResult>('/resources/batch/move', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
http.post<BatchUninstallResult>('/uninstall/batch', opts),
|
||||
moveResources: (opts: MoveRequest) => http.post<MoveResult>('/resources/batch/move', opts),
|
||||
getTemplates: async () => {
|
||||
const res = await apiFetch<TemplatesResponse>('/resources/templates');
|
||||
const res = await http.get<TemplatesResponse>('/resources/templates');
|
||||
// Normalize: Go omits nil slices, so scaffoldDirs may be undefined
|
||||
for (const p of res.patterns) {
|
||||
if (!p.scaffoldDirs) p.scaffoldDirs = [];
|
||||
@@ -73,83 +60,61 @@ export const resourcesApi = {
|
||||
return res;
|
||||
},
|
||||
previewSkill: (data: Omit<CreateSkillRequest, 'scaffoldDirs'>) =>
|
||||
apiFetch<{ content: string; path: string }>(
|
||||
http.get<{ content: string; path: string }>(
|
||||
`/resources/templates/preview?${new URLSearchParams(Object.entries(data).filter(([, v]) => v) as [string, string][])}`,
|
||||
),
|
||||
createSkill: (data: CreateSkillRequest) =>
|
||||
apiFetch<CreateSkillResponse>('/resources', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
createSkill: (data: CreateSkillRequest) => http.post<CreateSkillResponse>('/resources', data),
|
||||
batchSetTargets: (folder: string, target: string | null) =>
|
||||
apiFetch<{ updated: number; skipped: number; errors: string[] }>('/resources/batch/targets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ folder, target: target ?? '' }),
|
||||
http.post<{ updated: number; skipped: number; errors: string[] }>('/resources/batch/targets', {
|
||||
folder,
|
||||
target: target ?? '',
|
||||
}),
|
||||
batchToggleResources: (names: string[], enable: boolean, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<BatchToggleResult>('/resources/batch/toggle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ names, enable, kind }),
|
||||
}),
|
||||
http.post<BatchToggleResult>('/resources/batch/toggle', { names, enable, kind }),
|
||||
setSkillTargets: (name: string, target: string | null) =>
|
||||
apiFetch<{ success: boolean }>(`/resources/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ target: target ?? '' }),
|
||||
http.patch<{ success: boolean }>(`/resources/${encodeURIComponent(name)}/targets`, {
|
||||
target: target ?? '',
|
||||
}),
|
||||
// Repo uninstall
|
||||
deleteRepo: (name: string, force = false, recordOnly = false) =>
|
||||
apiFetch<{ success: boolean; name: string; movedToTrash: boolean }>(
|
||||
http.delete<{ success: boolean; name: string; movedToTrash: boolean }>(
|
||||
`/repos/${encodeURIComponent(name)}${force ? '?force=true' : ''}${recordOnly ? `${force ? '&' : '?'}recordOnly=true` : ''}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
// Skill file content
|
||||
getSkillFile: (skillName: string, filepath: string) =>
|
||||
apiFetch<SkillFileContent>(`/resources/${encodeURIComponent(skillName)}/files/${filepath}`),
|
||||
http.get<SkillFileContent>(`/resources/${encodeURIComponent(skillName)}/files/${filepath}`),
|
||||
// Files changed since install, diffed against the installed version; name is the skill's relPath.
|
||||
getLocalChanges: (name: string) =>
|
||||
apiFetch<{ files: LocalFileChange[] }>(`/resources/${encodeURIComponent(name)}/local-changes`),
|
||||
http.get<{ files: LocalFileChange[] }>(`/resources/${encodeURIComponent(name)}/local-changes`),
|
||||
// Save SKILL.md / agent markdown.
|
||||
saveSkillContent: (name: string, content: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{
|
||||
http.put<{
|
||||
bytesWritten: number;
|
||||
path: string;
|
||||
contentType: string;
|
||||
savedAt: string;
|
||||
}>(`/resources/${encodeURIComponent(name)}/content${kindQuery(kind)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ content }),
|
||||
}),
|
||||
}>(`/resources/${encodeURIComponent(name)}/content${kindQuery(kind)}`, { content }),
|
||||
// Update source URL for a tracked skill or agent.
|
||||
updateSkillSource: (name: string, source: string, kind?: 'skill' | 'agent') =>
|
||||
apiFetch<{ success: boolean; source: string; repoUrl: string }>(
|
||||
http.patch<{ success: boolean; source: string; repoUrl: string }>(
|
||||
`/resources/${encodeURIComponent(name)}/source${kindQuery(kind)}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ source }),
|
||||
},
|
||||
{ source },
|
||||
),
|
||||
// Launch an external editor (VS Code / Cursor / $EDITOR) against the skill file.
|
||||
openSkillInEditor: (name: string, opts?: { editor?: string; kind?: 'skill' | 'agent' }) =>
|
||||
apiFetch<{ editor: string; path: string; pid: number }>(
|
||||
http.post<{ editor: string; path: string; pid: number }>(
|
||||
`/resources/${encodeURIComponent(name)}/open-in-editor${kindQuery(opts?.kind)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ editor: opts?.editor ?? 'auto' }),
|
||||
},
|
||||
{ editor: opts?.editor ?? 'auto' },
|
||||
),
|
||||
collectScan: (target?: string, kind?: 'skill' | 'agent') => {
|
||||
const params = new URLSearchParams();
|
||||
if (target) params.set('target', target);
|
||||
if (kind) params.set('kind', kind);
|
||||
const qs = params.toString();
|
||||
return apiFetch<CollectScanResult>(`/collect/scan${qs ? '?' + qs : ''}`);
|
||||
return http.get<CollectScanResult>(`/collect/scan${qs ? '?' + qs : ''}`);
|
||||
},
|
||||
collect: (opts: {
|
||||
skills: { name: string; targetName: string; kind?: string }[];
|
||||
force?: boolean;
|
||||
}) =>
|
||||
apiFetch<CollectResult>('/collect', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
}) => http.post<CollectResult>('/collect', opts),
|
||||
};
|
||||
|
||||
+10
-16
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, BASE, createSSEStream } from './http';
|
||||
import { http, BASE, createSSEStream } from './http';
|
||||
import type {
|
||||
DiffTarget,
|
||||
FolderConflict,
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
|
||||
export const syncApi = {
|
||||
getSyncMatrix: (target?: string) =>
|
||||
apiFetch<{ entries: SyncMatrixEntry[] }>(
|
||||
http.get<{ entries: SyncMatrixEntry[] }>(
|
||||
`/sync-matrix${target ? '?target=' + encodeURIComponent(target) : ''}`,
|
||||
),
|
||||
previewSyncMatrix: (
|
||||
@@ -19,24 +19,18 @@ export const syncApi = {
|
||||
agentInclude?: string[],
|
||||
agentExclude?: string[],
|
||||
) =>
|
||||
apiFetch<{ entries: SyncMatrixEntry[] }>('/sync-matrix/preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
target,
|
||||
include,
|
||||
exclude,
|
||||
...(agentInclude && { agent_include: agentInclude }),
|
||||
...(agentExclude && { agent_exclude: agentExclude }),
|
||||
}),
|
||||
http.post<{ entries: SyncMatrixEntry[] }>('/sync-matrix/preview', {
|
||||
target,
|
||||
include,
|
||||
exclude,
|
||||
...(agentInclude && { agent_include: agentInclude }),
|
||||
...(agentExclude && { agent_exclude: agentExclude }),
|
||||
}),
|
||||
/** `project` (a root under projects) limits the sync to that project's targets. */
|
||||
sync: (opts: { dryRun?: boolean; force?: boolean; kind?: 'skill' | 'agent'; project?: string }) =>
|
||||
apiFetch<SyncResponse>('/sync', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
http.post<SyncResponse>('/sync', opts),
|
||||
diff: (target?: string) =>
|
||||
apiFetch<{ diffs: DiffTarget[]; folder_conflicts?: FolderConflict[] } & IgnoreSources>(
|
||||
http.get<{ diffs: DiffTarget[]; folder_conflicts?: FolderConflict[] } & IgnoreSources>(
|
||||
`/diff${target ? '?target=' + encodeURIComponent(target) : ''}`,
|
||||
),
|
||||
diffStream: (
|
||||
|
||||
+9
-10
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, BASE, createSSEStream } from './http';
|
||||
import { http, BASE, createSSEStream } from './http';
|
||||
import type {
|
||||
AnalyzeResponse,
|
||||
DoctorCheck,
|
||||
@@ -8,23 +8,22 @@ import type {
|
||||
|
||||
export const systemApi = {
|
||||
getUpdatePolicy: () =>
|
||||
apiFetch<{ enabled: boolean; configured: boolean; envOverride: boolean }>('/update-settings'),
|
||||
http.get<{ enabled: boolean; configured: boolean; envOverride: boolean }>('/update-settings'),
|
||||
getVersionCheck: (manual = false) =>
|
||||
apiFetch<VersionCheck>(manual ? '/version?manual=true' : '/version'),
|
||||
http.get<VersionCheck>(manual ? '/version?manual=true' : '/version'),
|
||||
upgradeApp: () =>
|
||||
apiFetch<{
|
||||
http.post<{
|
||||
ok: boolean;
|
||||
updated: boolean;
|
||||
devMode?: boolean;
|
||||
latestVersion?: string;
|
||||
output?: string;
|
||||
}>('/upgrade', { method: 'POST' }),
|
||||
}>('/upgrade'),
|
||||
restartApp: (opts?: { clearCache?: boolean }) =>
|
||||
apiFetch<{ ok: boolean; restarting: boolean }>('/restart', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ clearCache: opts?.clearCache ?? true }),
|
||||
http.post<{ ok: boolean; restarting: boolean }>('/restart', {
|
||||
clearCache: opts?.clearCache ?? true,
|
||||
}),
|
||||
health: () => apiFetch<{ status: string; version: string; uptime_seconds: number }>('/health'),
|
||||
health: () => http.get<{ status: string; version: string; uptime_seconds: number }>('/health'),
|
||||
/** Runs doctor, passing each check to onCheck as it is found; resolves with the full result. */
|
||||
doctorStream: (onCheck: (check: DoctorCheck) => void, signal?: AbortSignal) =>
|
||||
new Promise<DoctorResponse>((resolve, reject) => {
|
||||
@@ -36,5 +35,5 @@ export const systemApi = {
|
||||
);
|
||||
signal?.addEventListener('abort', () => es.close());
|
||||
}),
|
||||
analyze: () => apiFetch<AnalyzeResponse>('/analyze'),
|
||||
analyze: () => http.get<AnalyzeResponse>('/analyze'),
|
||||
};
|
||||
|
||||
+19
-33
@@ -1,4 +1,4 @@
|
||||
import { apiFetch } from './http';
|
||||
import { http } from './http';
|
||||
import type { TargetInstructionsSetup } from './types/instructions';
|
||||
import type {
|
||||
ProjectInput,
|
||||
@@ -12,22 +12,16 @@ import type {
|
||||
export const targetsApi = {
|
||||
/** Own targets by default. 'projects' lists the targets of projects alone, 'all' what a sync writes. */
|
||||
listTargets: (scope?: 'projects' | 'all') =>
|
||||
apiFetch<{ targets: Target[]; sourceSkillCount: number }>(
|
||||
http.get<{ targets: Target[]; sourceSkillCount: number }>(
|
||||
`/targets${scope ? `?scope=${scope}` : ''}`,
|
||||
),
|
||||
listProjects: () => apiFetch<ProjectList>('/projects'),
|
||||
saveProject: (project: ProjectInput) =>
|
||||
apiFetch<ProjectMutation>('/projects', { method: 'PUT', body: JSON.stringify(project) }),
|
||||
listProjects: () => http.get<ProjectList>('/projects'),
|
||||
saveProject: (project: ProjectInput) => http.put<ProjectMutation>('/projects', project),
|
||||
removeProject: (root: string, shared = false) =>
|
||||
apiFetch<ProjectMutation>(
|
||||
http.delete<ProjectMutation>(
|
||||
`/projects?root=${encodeURIComponent(root)}${shared ? '&shared=true' : ''}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
convertProject: (root: string) =>
|
||||
apiFetch<ProjectMutation>('/projects/convert', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ root }),
|
||||
}),
|
||||
convertProject: (root: string) => http.post<ProjectMutation>('/projects/convert', { root }),
|
||||
/** skillsEnabled false adds a target that skillshare writes no skills to, and creates no skills folder. */
|
||||
addTarget: (
|
||||
name: string,
|
||||
@@ -36,26 +30,18 @@ export const targetsApi = {
|
||||
instructions?: TargetInstructionsSetup,
|
||||
skillsEnabled = true,
|
||||
) =>
|
||||
apiFetch<{ success: boolean }>('/targets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
path,
|
||||
...(agentPath && { agentPath }),
|
||||
...(instructions && { instructions }),
|
||||
...(!skillsEnabled && { skills_enabled: false }),
|
||||
}),
|
||||
http.post<{ success: boolean }>('/targets', {
|
||||
name,
|
||||
path,
|
||||
...(agentPath && { agentPath }),
|
||||
...(instructions && { instructions }),
|
||||
...(!skillsEnabled && { skills_enabled: false }),
|
||||
}),
|
||||
/** Adds another config folder of a built-in Agent, such as a second account. cli runs its plugin commands instead of the Agent's executable. */
|
||||
addAgentConfigDir: (name: string, agent: string, configDir: string, cli?: string) =>
|
||||
apiFetch<{ success: boolean }>('/targets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, agent, configDir, ...(cli && { cli }) }),
|
||||
}),
|
||||
http.post<{ success: boolean }>('/targets', { name, agent, configDir, ...(cli && { cli }) }),
|
||||
removeTarget: (name: string) =>
|
||||
apiFetch<{ success: boolean; warnings?: string[] }>(`/targets/${encodeURIComponent(name)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
http.delete<{ success: boolean; warnings?: string[] }>(`/targets/${encodeURIComponent(name)}`),
|
||||
/** skills_enabled false also removes the links skillshare made in the skills folder; detach says what went and what stayed. */
|
||||
updateTarget: (
|
||||
name: string,
|
||||
@@ -71,11 +57,11 @@ export const targetsApi = {
|
||||
skills_enabled?: boolean;
|
||||
},
|
||||
) =>
|
||||
apiFetch<{ success: boolean; detach?: SkillsDetach }>(`/targets/${encodeURIComponent(name)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
http.patch<{ success: boolean; detach?: SkillsDetach }>(
|
||||
`/targets/${encodeURIComponent(name)}`,
|
||||
opts,
|
||||
),
|
||||
/** What turning skills off would remove and keep, without writing anything. */
|
||||
skillsOffPreview: (name: string) =>
|
||||
apiFetch<SkillsOffPreview>(`/targets/${encodeURIComponent(name)}/skills-off-preview`),
|
||||
http.get<SkillsOffPreview>(`/targets/${encodeURIComponent(name)}/skills-off-preview`),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,32 @@
|
||||
// Extras types
|
||||
export interface CreateExtraRequest {
|
||||
name: string;
|
||||
source?: string;
|
||||
folder?: string; // a folder in the shared extras folder; the server stores it as the source
|
||||
file?: string; // single-file extra: the file in the source folder
|
||||
targets: Array<{
|
||||
path: string;
|
||||
mode: string;
|
||||
flatten?: boolean;
|
||||
extension?: string;
|
||||
as?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface EditExtraTarget {
|
||||
path: string;
|
||||
mode: string;
|
||||
flatten: boolean;
|
||||
extension: string;
|
||||
as: string;
|
||||
include: string[];
|
||||
exclude: string[];
|
||||
}
|
||||
|
||||
export interface ExtensionActionResult {
|
||||
success: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ExtraTarget {
|
||||
path: string;
|
||||
mode: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiFetch, BASE, createSSEStream } from './http';
|
||||
import { http, BASE, createSSEStream } from './http';
|
||||
import type { UpdateResultItem, UpdateStreamSummary } from './types/update';
|
||||
|
||||
export const updateApi = {
|
||||
@@ -9,11 +9,7 @@ export const updateApi = {
|
||||
all?: boolean;
|
||||
skipAudit?: boolean;
|
||||
branch?: string;
|
||||
}) =>
|
||||
apiFetch<{ results: UpdateResultItem[] }>('/update', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
}) => http.post<{ results: UpdateResultItem[] }>('/update', opts),
|
||||
updateAllStream: (
|
||||
onStart: (total: number) => void,
|
||||
onResult: (item: UpdateResultItem) => void,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upgradeAndReconnect } from '../lib/upgradeWorkflow';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { X, Copy, Check, CircleArrowUp } from 'lucide-react';
|
||||
@@ -86,33 +87,14 @@ export default function UpdateDialog({
|
||||
}
|
||||
};
|
||||
|
||||
const waitForRestartThenReload = async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
for (let i = 0; i < 40; i++) {
|
||||
try {
|
||||
await api.health();
|
||||
window.location.reload();
|
||||
return;
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
}
|
||||
setStatus(
|
||||
t(
|
||||
'updateDialog.restartManual',
|
||||
{},
|
||||
'Updated. Restart with skillshare ui start if this page does not reconnect.',
|
||||
),
|
||||
);
|
||||
setUpdating(false);
|
||||
};
|
||||
|
||||
const handleUpdateNow = async () => {
|
||||
setUpdating(true);
|
||||
setStatus(t('updateDialog.updating', {}, 'Updating Skillshare…'));
|
||||
try {
|
||||
const result = await api.upgradeApp();
|
||||
if (result.devMode) {
|
||||
const outcome = await upgradeAndReconnect(() =>
|
||||
setStatus(t('updateDialog.restarting', {}, 'Restarting local UI server…')),
|
||||
);
|
||||
if (outcome === 'dev') {
|
||||
setStatus(t('updateDialog.restartDev', {}, 'DEV mode restart simulated.'));
|
||||
await new Promise((resolve) => setTimeout(resolve, 900));
|
||||
setUpdating(false);
|
||||
@@ -120,10 +102,16 @@ export default function UpdateDialog({
|
||||
onDismiss?.();
|
||||
return;
|
||||
}
|
||||
setStatus(t('updateDialog.restarting', {}, 'Restarting local UI server…'));
|
||||
// The upgrade already cached the new version's UI; clearing it would force a re-download.
|
||||
await api.restartApp({ clearCache: false });
|
||||
void waitForRestartThenReload();
|
||||
if (outcome === 'manual') {
|
||||
setStatus(
|
||||
t(
|
||||
'updateDialog.restartManual',
|
||||
{},
|
||||
'Updated. Restart with skillshare ui start if this page does not reconnect.',
|
||||
),
|
||||
);
|
||||
setUpdating(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setStatus(upgradeErrorMessage(err, t));
|
||||
setUpdating(false);
|
||||
|
||||
@@ -12,14 +12,11 @@ import SyncResultList, { SyncUpToDate } from '../SyncResultList';
|
||||
import {
|
||||
countChanges,
|
||||
HOOKS_CHANGED,
|
||||
hooksGroups,
|
||||
reviewSyncConfig,
|
||||
MCP_CHANGED,
|
||||
mcpGroups,
|
||||
otherWarnings,
|
||||
projectChanges,
|
||||
resourceGroups,
|
||||
runSync,
|
||||
type ChangeGroup,
|
||||
type SyncFailure,
|
||||
} from '../sync/syncView';
|
||||
import SyncResult from '../sync/SyncResult';
|
||||
@@ -55,13 +52,9 @@ export default function ProjectSyncDialog({ open, onClose, project, targets }: P
|
||||
const diffs = (diff.data?.diffs ?? []).filter((d) => names.has(d.target));
|
||||
const ignored = { skill: diff.data?.ignored_skills, agent: diff.data?.agent_ignored_skills };
|
||||
const plan = mcp.data?.plan;
|
||||
const changes = projectChanges(plan, project.path);
|
||||
const conflicts = changes.filter((c) => c.action === 'conflict');
|
||||
const mcpBlocked = conflicts.length > 0;
|
||||
const hookPlan = hooks.data?.plan;
|
||||
const hookChanges = (hookPlan?.changes ?? []).filter((c) => c.root === project.path);
|
||||
const hooksBlocked = hookChanges.some((c) => c.action === 'conflict');
|
||||
const sections: { label: string; groups: ChangeGroup[] }[] = [
|
||||
const config = reviewSyncConfig(plan, hooks.data?.plan, project.path);
|
||||
const { conflicts, mcpBlocked, hookChanges, hooksBlocked } = config;
|
||||
const resourceSections = [
|
||||
{
|
||||
label: 'Skills',
|
||||
groups: resourceGroups(diffs, mine, new Set(['skill']), false, ignored).groups,
|
||||
@@ -70,17 +63,13 @@ export default function ProjectSyncDialog({ open, onClose, project, targets }: P
|
||||
label: 'Agents',
|
||||
groups: resourceGroups(diffs, mine, new Set(['agent']), false, ignored).groups,
|
||||
},
|
||||
{ label: 'MCP', groups: plan ? mcpGroups({ ...plan, changes }) : [] },
|
||||
{ label: 'Hooks', groups: hookPlan ? hooksGroups({ ...hookPlan, changes: hookChanges }) : [] },
|
||||
].filter((s) => s.groups.length > 0);
|
||||
const count = sections.reduce(
|
||||
(n, s) =>
|
||||
n +
|
||||
((s.label === 'MCP' && mcpBlocked) || (s.label === 'Hooks' && hooksBlocked)
|
||||
? 0
|
||||
: countChanges(s.groups)),
|
||||
0,
|
||||
);
|
||||
];
|
||||
const sections = [
|
||||
...resourceSections,
|
||||
{ label: 'MCP', groups: config.mcpRows },
|
||||
{ label: 'Hooks', groups: config.hookRows },
|
||||
].filter((s) => s.groups.length);
|
||||
const count = resourceSections.reduce((n, s) => n + countChanges(s.groups), 0) + config.count;
|
||||
const loading = diff.isPending || mcp.isPending || (hooks.isPending && !hooks.error) || !targets;
|
||||
|
||||
const close = () => {
|
||||
@@ -96,14 +85,7 @@ export default function ProjectSyncDialog({ open, onClose, project, targets }: P
|
||||
const { resources, failures: failed } = await runSync({
|
||||
resources: project.declared ? 'both' : null,
|
||||
extras: false,
|
||||
mcp:
|
||||
plan && !mcpBlocked && (plan.migrates || changes.some((c) => c.action !== 'unchanged'))
|
||||
? plan
|
||||
: null,
|
||||
hooks:
|
||||
hookPlan && !hooksBlocked && hookChanges.some((c) => c.action !== 'unchanged')
|
||||
? hookPlan
|
||||
: null,
|
||||
...config.run,
|
||||
force: false,
|
||||
project: { root: project.root, path: project.path },
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo, useState, type ReactNode } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useResourceMove } from '../../hooks/useResourceMove';
|
||||
import {
|
||||
ArrowLeft,
|
||||
CircleCheck,
|
||||
@@ -12,9 +12,8 @@ import {
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { api, ApiError } from '../../api/client';
|
||||
import { ApiError } from '../../api/client';
|
||||
import type { MoveItemResult, Skill } from '../../api/client';
|
||||
import { clearAuditCache } from '../../lib/auditCache';
|
||||
import {
|
||||
baseName,
|
||||
existingFolders,
|
||||
@@ -22,8 +21,6 @@ import {
|
||||
linkPrefix,
|
||||
planFolder,
|
||||
} from '../../lib/moveFolders';
|
||||
import { queryKeys } from '../../lib/queryKeys';
|
||||
import { invalidate } from '../../lib/queryEvents';
|
||||
import { countLabel } from '../../lib/resourceGrouping';
|
||||
import { plural, useT } from '../../i18n';
|
||||
import Button from '../Button';
|
||||
@@ -52,7 +49,6 @@ const known = (code?: string) => (code && KNOWN_CODES.has(code) ? code : undefin
|
||||
const codeOf = (err: unknown) => known(err instanceof ApiError ? err.code : undefined);
|
||||
|
||||
/** The API takes '.' for the source root. */
|
||||
const wire = (dest: string) => (dest === '' ? '.' : dest);
|
||||
|
||||
/** An item that stays where it is is not a move. */
|
||||
const unchanged = (r: MoveItemResult) =>
|
||||
@@ -241,10 +237,8 @@ export function MoveDialog({
|
||||
onClose,
|
||||
}: Props) {
|
||||
const t = useT();
|
||||
const queryClient = useQueryClient();
|
||||
const [dest, setDest] = useState<string | null>(null);
|
||||
const [naming, setNaming] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [results, setResults] = useState<MoveItemResult[] | null>(null);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
// What was asked for stays what is shown: a detail page changes its skill's name once the move is done.
|
||||
@@ -284,18 +278,8 @@ export function MoveDialog({
|
||||
onBack: () => setNaming(false),
|
||||
});
|
||||
|
||||
// What a move to `dest` would do: new paths, link names, refusals, filter warnings. Changes nothing, so
|
||||
// it is not worth repeating on focus, and it stops once the real move has run.
|
||||
const preview = useQuery({
|
||||
queryKey: queryKeys.movePreview(names, dest ?? ''),
|
||||
queryFn: () => api.moveResources({ names, dest: wire(dest ?? ''), dryRun: true }),
|
||||
enabled: dest !== null && !results,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
const { preview, move } = useResourceMove(names, dest, results !== null);
|
||||
const running = move.isPending;
|
||||
const planned = useMemo(
|
||||
() => new Map((preview.data?.results ?? []).map((r) => [r.name, r])),
|
||||
[preview.data],
|
||||
@@ -306,15 +290,8 @@ export function MoveDialog({
|
||||
|
||||
const run = async (targets: string[], force: boolean) => {
|
||||
if (dest === null) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const res = await api.moveResources({
|
||||
names: targets,
|
||||
dest: wire(dest),
|
||||
force: force || undefined,
|
||||
});
|
||||
clearAuditCache(queryClient);
|
||||
void invalidate(queryClient, 'skillsMoved');
|
||||
const res = await move.mutateAsync({ targets, destination: dest, force });
|
||||
// A retry replaces only the rows it retried.
|
||||
setResults((prev) =>
|
||||
prev ? prev.map((r) => res.results.find((n) => n.name === r.name) ?? r) : res.results,
|
||||
@@ -330,8 +307,6 @@ export function MoveDialog({
|
||||
)
|
||||
: names.map((name) => ({ name, success: false, error_code: code })),
|
||||
);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
mcpGroups,
|
||||
otherWarnings,
|
||||
pendingCount,
|
||||
reviewSyncConfig,
|
||||
receivesSkill,
|
||||
resourceGroups,
|
||||
runSync,
|
||||
@@ -627,6 +628,34 @@ describe('failureExplanation', () => {
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('shows a scoped conflict but only submits/counts the unblocked project', () => {
|
||||
const plan = {
|
||||
...hooks,
|
||||
blocked: true,
|
||||
changes: [
|
||||
{ ...hookChange, root: '/a', action: 'conflict' },
|
||||
{ ...hookChange, root: '/b' },
|
||||
],
|
||||
};
|
||||
const a = reviewSyncConfig(null, plan, '/a'),
|
||||
b = reviewSyncConfig(null, plan, '/b');
|
||||
expect(a.hookRows).toHaveLength(1);
|
||||
expect([a.count, a.run.hooks]).toEqual([0, null]);
|
||||
expect([b.count, b.run.hooks]).toEqual([1, plan]);
|
||||
});
|
||||
|
||||
it('counts a global migration even without file rows', () => {
|
||||
const plan: MCPPlan = {
|
||||
revision: 'r',
|
||||
sourcePath: '',
|
||||
blocked: false,
|
||||
changes: [],
|
||||
migrates: true,
|
||||
};
|
||||
const reviewed = reviewSyncConfig(plan, null);
|
||||
expect([reviewed.count, reviewed.run.mcp]).toEqual([1, plan]);
|
||||
});
|
||||
|
||||
it('applies the fresh revision of a reviewed hooks plan, after checking it is unchanged', async () => {
|
||||
vi.mocked(hooksApi.preview).mockResolvedValue({ ...hooks, revision: 'h2' });
|
||||
vi.mocked(hooksApi.configure).mockResolvedValue({ applied: [], backupIds: [] });
|
||||
|
||||
@@ -369,12 +369,12 @@ export function pendingCount(
|
||||
hooks?: HookPlan | null,
|
||||
): number {
|
||||
const parts = new Set<Part>(['skill', 'agent', 'extra', 'mcp', 'hooks']);
|
||||
return countChanges([
|
||||
...resourceGroups(diffs, targets, parts, false).groups,
|
||||
...extraGroups(extras, false),
|
||||
...(plan?.blocked ? [] : mcpGroups(plan)),
|
||||
...(hooks?.blocked ? [] : hooksGroups(hooks)),
|
||||
]);
|
||||
const config = reviewSyncConfig(plan, hooks);
|
||||
return (
|
||||
countChanges(resourceGroups(diffs, targets, parts, false).groups) +
|
||||
countChanges(extraGroups(extras, false)) +
|
||||
config.count
|
||||
);
|
||||
}
|
||||
export const countEdited = (groups: ChangeGroup[]) =>
|
||||
groups.reduce((n, g) => n + g.rows.filter((r) => r.edited).length, 0);
|
||||
@@ -388,6 +388,42 @@ export const HOOKS_CHANGED = 'hooks-changed';
|
||||
export const projectChanges = (plan: MCPPlan | null | undefined, root: string) =>
|
||||
(plan?.changes ?? []).filter((c) => projectOf([root], c) === root);
|
||||
|
||||
/** Use the same scoped eligibility for the preview, its count, and the submitted plans. */
|
||||
export function reviewSyncConfig(
|
||||
mcp: MCPPlan | null | undefined,
|
||||
hooks: HookPlan | null | undefined,
|
||||
root?: string,
|
||||
) {
|
||||
const changes = root ? projectChanges(mcp, root) : (mcp?.changes ?? []);
|
||||
const hookChanges = (hooks?.changes ?? []).filter((c) => !root || c.root === root);
|
||||
const conflicts = changes.filter((c) => c.action === 'conflict');
|
||||
const mcpBlocked = root ? conflicts.length > 0 : !!mcp?.blocked;
|
||||
const hooksBlocked = root ? hookChanges.some((c) => c.action === 'conflict') : !!hooks?.blocked;
|
||||
const mcpRows = mcpGroups(mcp && { ...mcp, changes });
|
||||
const hookRows = hooksGroups(hooks && { ...hooks, changes: hookChanges });
|
||||
const reviewedMcp =
|
||||
mcp && !mcpBlocked && (mcp.migrates || changes.some((c) => c.action !== 'unchanged'))
|
||||
? mcp
|
||||
: null;
|
||||
const reviewedHooks =
|
||||
hooks && !hooksBlocked && hookChanges.some((c) => c.action !== 'unchanged') ? hooks : null;
|
||||
const migrationOnly = !!reviewedMcp?.migrates && !root && !countChanges(mcpRows);
|
||||
return {
|
||||
migrationOnly,
|
||||
mcpRows,
|
||||
hookRows,
|
||||
conflicts,
|
||||
hookChanges,
|
||||
mcpBlocked,
|
||||
hooksBlocked,
|
||||
count:
|
||||
(reviewedMcp ? countChanges(mcpRows) : 0) +
|
||||
(reviewedHooks ? countChanges(hookRows) : 0) +
|
||||
Number(migrationOnly),
|
||||
run: { mcp: reviewedMcp, hooks: reviewedHooks },
|
||||
};
|
||||
}
|
||||
|
||||
// Revisions move on any config write, including the resource sync; only the reviewed changes must hold.
|
||||
const changeKey = (plan: MCPPlan, root?: string) =>
|
||||
(root ? projectChanges(plan, root) : plan.changes)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { api, type Skill } from '../../api/client';
|
||||
import { queryKeys } from '../../lib/queryKeys';
|
||||
import { useResourceToggle } from '../useResourceToggle';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
function resource(flatName: string, kind: Skill['kind']): Skill {
|
||||
return { flatName, kind, name: flatName, sourcePath: '', relPath: flatName, isInRepo: false };
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const client = new QueryClient();
|
||||
const skill = resource('same', 'skill');
|
||||
const agent = resource('same', 'agent');
|
||||
const key = queryKeys.skills.all;
|
||||
client.setQueryData(key, { resources: [skill, agent, resource('other', 'skill')] });
|
||||
const feedback = { onMany: vi.fn(), onOne: vi.fn(), onError: vi.fn() };
|
||||
const { result } = renderHook(() => useResourceToggle(feedback), {
|
||||
wrapper: ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
),
|
||||
});
|
||||
const flags = () =>
|
||||
client.getQueryData<{ resources: Skill[] }>(key)?.resources.map((s) => !!s.disabled);
|
||||
return { result, flags, skill, feedback };
|
||||
}
|
||||
|
||||
it('keeps successful batch changes and does not touch a same-named agent', async () => {
|
||||
const { result, flags, feedback } = setup();
|
||||
const response = {
|
||||
summary: { updated: 1, unchanged: 0, failed: 1 },
|
||||
results: [
|
||||
{ name: 'same', success: true, disabled: true },
|
||||
{ name: 'other', success: false, disabled: false, error: 'read-only' },
|
||||
],
|
||||
};
|
||||
vi.spyOn(api, 'batchToggleResources').mockResolvedValue(response);
|
||||
const input = { kind: 'skill' as const, names: ['same', 'other'], enable: false };
|
||||
await act(() => result.current.toggleMany.mutateAsync(input));
|
||||
expect(flags()).toEqual([true, false, false]);
|
||||
expect(feedback.onMany).toHaveBeenCalledWith(response, input);
|
||||
});
|
||||
|
||||
it('runs a queued single toggle after a failed overlapping batch rolls back', async () => {
|
||||
const { result, flags, skill } = setup();
|
||||
let reject!: (e: Error) => void;
|
||||
vi.spyOn(api, 'batchToggleResources').mockImplementation(
|
||||
() =>
|
||||
new Promise((_, no) => {
|
||||
reject = no;
|
||||
}),
|
||||
);
|
||||
const single = vi
|
||||
.spyOn(api, 'disableResource')
|
||||
.mockResolvedValue({ name: 'same', success: true, disabled: true });
|
||||
act(() =>
|
||||
result.current.toggleMany.mutate({ kind: 'skill', names: ['same', 'other'], enable: false }),
|
||||
);
|
||||
await waitFor(() => expect(flags()).toEqual([true, false, true]));
|
||||
act(() => result.current.toggleOne.mutate({ s: skill, disable: true }));
|
||||
expect(single).not.toHaveBeenCalled();
|
||||
reject(new Error('write failed'));
|
||||
await waitFor(() => expect(result.current.toggleOne.isSuccess).toBe(true));
|
||||
expect(flags()).toEqual([true, false, false]);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../api/client';
|
||||
import { clearAuditCache } from '../lib/auditCache';
|
||||
import { queryKeys } from '../lib/queryKeys';
|
||||
import { invalidate } from '../lib/queryEvents';
|
||||
|
||||
const wire = (dest: string) => (dest === '' ? '.' : dest);
|
||||
|
||||
export function useResourceMove(names: string[], dest: string | null, completed: boolean) {
|
||||
const queryClient = useQueryClient();
|
||||
// What a move to `dest` would do: new paths, link names, refusals, filter warnings. Changes nothing, so
|
||||
// it is not worth repeating on focus, and it stops once the real move has run.
|
||||
const preview = useQuery({
|
||||
queryKey: queryKeys.movePreview(names, dest ?? ''),
|
||||
queryFn: () => api.moveResources({ names, dest: wire(dest ?? ''), dryRun: true }),
|
||||
enabled: dest !== null && !completed,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
const move = useMutation({
|
||||
mutationFn: ({
|
||||
targets,
|
||||
destination,
|
||||
force,
|
||||
}: {
|
||||
targets: string[];
|
||||
destination: string;
|
||||
force: boolean;
|
||||
}) => api.moveResources({ names: targets, dest: wire(destination), force: force || undefined }),
|
||||
onSuccess: () => {
|
||||
clearAuditCache(queryClient);
|
||||
void invalidate(queryClient, 'skillsMoved');
|
||||
},
|
||||
});
|
||||
return { preview, move };
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api, type BatchToggleResult, type Skill } from '../api/client';
|
||||
import { invalidate } from '../lib/queryEvents';
|
||||
import { queryKeys } from '../lib/queryKeys';
|
||||
|
||||
type One = { s: Skill; disable: boolean };
|
||||
type Many = { names: string[]; enable: boolean; kind: Skill['kind'] };
|
||||
type Feedback = {
|
||||
onOne: (input: One) => void;
|
||||
onMany: (result: BatchToggleResult, input: Many) => void;
|
||||
onError: (error: Error) => void;
|
||||
};
|
||||
type List = Awaited<ReturnType<typeof api.listSkills>>;
|
||||
|
||||
// Both endpoints write the same flags. Queue writes (including reconciliation) across hook instances.
|
||||
const scope = { id: 'resource-toggle' };
|
||||
const queryKey = queryKeys.skills.all;
|
||||
|
||||
export function useResourceToggle(feedback: Feedback) {
|
||||
const client = useQueryClient();
|
||||
|
||||
async function optimistic<T>(
|
||||
kind: Skill['kind'],
|
||||
names: string[],
|
||||
disabled: boolean,
|
||||
request: () => Promise<T>,
|
||||
failedNames?: (result: T) => string[],
|
||||
) {
|
||||
await client.cancelQueries({ queryKey, exact: true });
|
||||
const selected = new Set(names);
|
||||
const previous = new Map<string, boolean | undefined>();
|
||||
client.setQueryData<List>(
|
||||
queryKey,
|
||||
(list) =>
|
||||
list && {
|
||||
...list,
|
||||
resources: list.resources.map((s) => {
|
||||
if (s.kind !== kind || !selected.has(s.flatName)) return s;
|
||||
previous.set(s.flatName, s.disabled);
|
||||
return { ...s, disabled };
|
||||
}),
|
||||
},
|
||||
);
|
||||
function restore(failed: Set<string>) {
|
||||
if (!failed.size) return;
|
||||
client.setQueryData<List>(
|
||||
queryKey,
|
||||
(list) =>
|
||||
list && {
|
||||
...list,
|
||||
resources: list.resources.map((s) =>
|
||||
s.kind === kind && failed.has(s.flatName) && previous.has(s.flatName)
|
||||
? { ...s, disabled: previous.get(s.flatName) }
|
||||
: s,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
try {
|
||||
const result = await request();
|
||||
if (failedNames) restore(new Set(failedNames(result)));
|
||||
return result;
|
||||
} catch (error) {
|
||||
restore(selected);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const toggleOne = useMutation({
|
||||
scope,
|
||||
mutationFn: ({ s, disable }: One) =>
|
||||
optimistic(s.kind, [s.flatName], disable, () =>
|
||||
disable ? api.disableResource(s.flatName, s.kind) : api.enableResource(s.flatName, s.kind),
|
||||
),
|
||||
onSuccess: (_, input) => feedback.onOne(input),
|
||||
onError: feedback.onError,
|
||||
onSettled: () => invalidate(client, 'skillSyncChanged'),
|
||||
});
|
||||
const toggleMany = useMutation({
|
||||
scope,
|
||||
mutationFn: ({ kind, names, enable }: Many) =>
|
||||
optimistic(
|
||||
kind,
|
||||
names,
|
||||
!enable,
|
||||
() => api.batchToggleResources(names, enable, kind),
|
||||
(result) => result.results.filter((r) => !r.success).map((r) => r.name),
|
||||
),
|
||||
onSuccess: (result, input) => feedback.onMany(result, input),
|
||||
onError: feedback.onError,
|
||||
onSettled: () => invalidate(client, 'skillsToggled'),
|
||||
});
|
||||
return { toggleOne, toggleMany };
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export const useHooksQuery = (options?: Options<Data<typeof hooksApi.list>>) =>
|
||||
export const useSkillsQuery = (options?: Options<Data<typeof api.listSkills>>) =>
|
||||
useQuery({
|
||||
queryKey: queryKeys.skills.all,
|
||||
queryFn: () => api.listSkills(),
|
||||
queryFn: ({ signal }) => api.listSkills(undefined, signal),
|
||||
staleTime: staleTimes.skills,
|
||||
...options,
|
||||
});
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} Änderung",
|
||||
"sync.changes.other": "{count} Änderungen",
|
||||
"sync.checking": "Prüfe, was sich ändert…",
|
||||
"sync.migrateMcpSource": "MCP-Quelleinstellungen migrieren",
|
||||
"sync.nothing": "Nichts zu synchronisieren. Alle Ziele entsprechen deiner Quelle.",
|
||||
"sync.noTargets": "Noch keine Ziele. Füge eines hinzu, um zu synchronisieren.",
|
||||
"sync.addTarget": "Ziel hinzufügen",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} change",
|
||||
"sync.changes.other": "{count} changes",
|
||||
"sync.checking": "Checking what will change…",
|
||||
"sync.migrateMcpSource": "Migrate MCP source settings",
|
||||
"sync.nothing": "Nothing to sync. Every target matches your source.",
|
||||
"sync.noTargets": "No targets yet. Add one to start syncing.",
|
||||
"sync.addTarget": "Add target",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} cambio",
|
||||
"sync.changes.other": "{count} cambios",
|
||||
"sync.checking": "Comprobando qué cambiará…",
|
||||
"sync.migrateMcpSource": "Migrar la configuración de origen de MCP",
|
||||
"sync.nothing": "Nada que sincronizar. Todos los destinos coinciden con tu origen.",
|
||||
"sync.noTargets": "Aún no hay destinos. Añade uno para empezar a sincronizar.",
|
||||
"sync.addTarget": "Añadir destino",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} تغییر",
|
||||
"sync.changes.other": "{count} تغییر",
|
||||
"sync.checking": "در حال بررسی تغییرات…",
|
||||
"sync.migrateMcpSource": "انتقال تنظیمات منبع MCP",
|
||||
"sync.nothing": "چیزی برای همگامسازی نیست. همه هدفها با منبع شما یکساناند.",
|
||||
"sync.noTargets": "هنوز هدفی ندارید. برای شروع همگامسازی یکی اضافه کنید.",
|
||||
"sync.addTarget": "افزودن هدف",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} changement",
|
||||
"sync.changes.other": "{count} changements",
|
||||
"sync.checking": "Vérification des changements…",
|
||||
"sync.migrateMcpSource": "Migrer les paramètres source MCP",
|
||||
"sync.nothing": "Rien à synchroniser. Toutes les cibles correspondent à votre source.",
|
||||
"sync.noTargets": "Aucune cible pour l'instant. Ajoutez-en une pour synchroniser.",
|
||||
"sync.addTarget": "Ajouter une cible",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} perubahan",
|
||||
"sync.changes.other": "{count} perubahan",
|
||||
"sync.checking": "Memeriksa apa yang akan berubah…",
|
||||
"sync.migrateMcpSource": "Migrasikan pengaturan sumber MCP",
|
||||
"sync.nothing": "Tidak ada yang perlu disinkronkan. Semua target sama dengan sumber Anda.",
|
||||
"sync.noTargets": "Belum ada target. Tambahkan satu untuk mulai sinkronisasi.",
|
||||
"sync.addTarget": "Tambah target",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} 件の変更",
|
||||
"sync.changes.other": "{count} 件の変更",
|
||||
"sync.checking": "変更内容を確認中…",
|
||||
"sync.migrateMcpSource": "MCP のソース設定を移行",
|
||||
"sync.nothing": "同期するものはありません。すべてのターゲットがソースと一致しています。",
|
||||
"sync.noTargets": "ターゲットがまだありません。追加すると同期できます。",
|
||||
"sync.addTarget": "ターゲットを追加",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "변경 {count}개",
|
||||
"sync.changes.other": "변경 {count}개",
|
||||
"sync.checking": "바뀔 내용을 확인하는 중…",
|
||||
"sync.migrateMcpSource": "MCP 소스 설정 마이그레이션",
|
||||
"sync.nothing": "동기화할 내용이 없습니다. 모든 대상이 소스와 같습니다.",
|
||||
"sync.noTargets": "아직 대상이 없습니다. 대상을 추가하면 동기화할 수 있습니다.",
|
||||
"sync.addTarget": "대상 추가",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} alteração",
|
||||
"sync.changes.other": "{count} alterações",
|
||||
"sync.checking": "Verificando o que vai mudar…",
|
||||
"sync.migrateMcpSource": "Migrar as configurações de origem do MCP",
|
||||
"sync.nothing": "Nada para sincronizar. Todos os destinos correspondem à sua origem.",
|
||||
"sync.noTargets": "Ainda não há destinos. Adicione um para começar a sincronizar.",
|
||||
"sync.addTarget": "Adicionar destino",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} 项变更",
|
||||
"sync.changes.other": "{count} 项变更",
|
||||
"sync.checking": "正在检查会有哪些变更…",
|
||||
"sync.migrateMcpSource": "迁移 MCP 来源设置",
|
||||
"sync.nothing": "没有需要同步的内容,所有目标都与来源一致。",
|
||||
"sync.noTargets": "还没有目标,添加一个即可开始同步。",
|
||||
"sync.addTarget": "添加目标",
|
||||
|
||||
@@ -2020,6 +2020,7 @@
|
||||
"sync.changes.one": "{count} 項變更",
|
||||
"sync.changes.other": "{count} 項變更",
|
||||
"sync.checking": "正在檢查會有哪些變更…",
|
||||
"sync.migrateMcpSource": "遷移 MCP 來源設定",
|
||||
"sync.nothing": "沒有需要同步的內容,所有目標都與來源一致。",
|
||||
"sync.noTargets": "還沒有目標,新增一個即可開始同步。",
|
||||
"sync.addTarget": "新增目標",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
import { expect, it } from 'vitest';
|
||||
import { optimisticTargets } from './optimisticTargets';
|
||||
import { queryKeys } from './queryKeys';
|
||||
import type { Skill } from '../api/client';
|
||||
|
||||
it('rolls back only the failed target edit, preserving a completed toggle and same-named agent', async () => {
|
||||
const client = new QueryClient();
|
||||
const key = queryKeys.skills.all;
|
||||
const skill = (name: string, kind: Skill['kind']): Skill => ({
|
||||
name,
|
||||
flatName: name,
|
||||
kind,
|
||||
relPath: name,
|
||||
sourcePath: '',
|
||||
isInRepo: false,
|
||||
targets: ['old'],
|
||||
});
|
||||
const a = skill('a', 'skill'),
|
||||
b = skill('b', 'skill'),
|
||||
agent = skill('a', 'agent');
|
||||
client.setQueryData(key, { resources: [a, b, agent] });
|
||||
const undo = await optimisticTargets(client, 'skill', 'a', 'new');
|
||||
const read = () => client.getQueryData<{ resources: Skill[] }>(key)!.resources;
|
||||
expect(read().map((s) => s.targets)).toEqual([['new'], ['old'], ['old']]);
|
||||
client.setQueryData(key, {
|
||||
resources: read().map((s) => (s === b ? { ...s, disabled: true } : s)),
|
||||
});
|
||||
undo?.();
|
||||
expect(read()).toEqual([a, { ...b, disabled: true }, agent]);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import type { Skill } from '../api/client';
|
||||
import { queryKeys } from './queryKeys';
|
||||
type SkillsData = { resources: Skill[] };
|
||||
|
||||
export async function optimisticTargets(
|
||||
queryClient: QueryClient,
|
||||
kind: Skill['kind'],
|
||||
name: string,
|
||||
target: string | null,
|
||||
) {
|
||||
const key = queryKeys.skills.all;
|
||||
await queryClient.cancelQueries({ queryKey: key, exact: true });
|
||||
const previous = queryClient
|
||||
.getQueryData<SkillsData>(key)
|
||||
?.resources.find((s) => s.kind === kind && s.flatName === name);
|
||||
if (!previous) return;
|
||||
const patchTargets = (targets: Skill['targets']) =>
|
||||
queryClient.setQueryData<SkillsData>(
|
||||
key,
|
||||
(list) =>
|
||||
list && {
|
||||
...list,
|
||||
resources: list.resources.map((s) =>
|
||||
s.kind === previous.kind && s.flatName === name ? { ...s, targets } : s,
|
||||
),
|
||||
},
|
||||
);
|
||||
patchTargets(target ? [target] : undefined);
|
||||
return () => patchTargets(previous.targets);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { api } from '../api/client';
|
||||
import { upgradeAndReconnect } from './upgradeWorkflow';
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
it.each([true, false])(
|
||||
'reloads only if the restarted server recovers (recovers=%s)',
|
||||
async (recovers) => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(api, 'upgradeApp').mockResolvedValue({ ok: true, updated: true });
|
||||
vi.spyOn(api, 'restartApp').mockResolvedValue({ ok: true, restarting: true });
|
||||
const health = vi.spyOn(api, 'health').mockRejectedValue(new Error('offline'));
|
||||
if (recovers)
|
||||
health
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockResolvedValueOnce({ status: 'ok', version: '1', uptime_seconds: 1 });
|
||||
const reload = vi.fn();
|
||||
const result = upgradeAndReconnect(vi.fn(), reload);
|
||||
await vi.runAllTimersAsync();
|
||||
expect(await result).toBe(recovers ? 'reloaded' : 'manual');
|
||||
expect(reload).toHaveBeenCalledTimes(recovers ? 1 : 0);
|
||||
expect(health).toHaveBeenCalledTimes(recovers ? 2 : 40);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
import { api } from '../api/client';
|
||||
|
||||
/** Preserve the UI downloaded by upgrade and reload only after the server responds. */
|
||||
export async function upgradeAndReconnect(
|
||||
onRestart: () => void,
|
||||
reload = () => window.location.reload(),
|
||||
) {
|
||||
if ((await api.upgradeApp()).devMode) return 'dev';
|
||||
onRestart();
|
||||
await api.restartApp({ clearCache: false });
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
try {
|
||||
await api.health();
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
reload();
|
||||
return 'reloaded';
|
||||
}
|
||||
return 'manual';
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upgradeAndReconnect } from '../lib/upgradeWorkflow';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
@@ -118,27 +119,16 @@ export default function DoctorPage() {
|
||||
setUpgrading(true);
|
||||
setUpgradeMessage(t('updateDialog.updating'));
|
||||
try {
|
||||
const result = await api.upgradeApp();
|
||||
if (result.devMode) {
|
||||
const outcome = await upgradeAndReconnect(() =>
|
||||
setUpgradeMessage(t('updateDialog.restarting')),
|
||||
);
|
||||
if (outcome === 'dev') {
|
||||
setUpgradeMessage(t('updateDialog.restartDev'));
|
||||
await Promise.all([refetch(), invalidate(queryClient, 'appUpgraded')]);
|
||||
setUpgrading(false);
|
||||
return;
|
||||
}
|
||||
setUpgradeMessage(t('updateDialog.restarting'));
|
||||
// The upgrade already cached the new version's UI; clearing it would force a re-download.
|
||||
await api.restartApp({ clearCache: false });
|
||||
// The server is coming back up; poll until it answers, then show the new build.
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
try {
|
||||
await api.health();
|
||||
window.location.reload();
|
||||
return;
|
||||
} catch {
|
||||
/* still restarting */
|
||||
}
|
||||
}
|
||||
if (outcome === 'reloaded') return;
|
||||
setUpgradeMessage(t('updateDialog.restartManual'));
|
||||
setUpgrading(false);
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { optimisticTargets } from '../lib/optimisticTargets';
|
||||
import { useResourceToggle } from '../hooks/useResourceToggle';
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
@@ -131,7 +133,6 @@ type MenuState =
|
||||
| { mode: 'skill'; skill: Skill; point: Point }
|
||||
| { mode: 'bulk'; names: string[]; point: Point }
|
||||
| { mode: 'add'; point: Point };
|
||||
type SkillsData = { resources: Skill[] };
|
||||
|
||||
const EMPTY: Skill[] = [];
|
||||
// ponytail: "Show more" paging instead of virtualization; add a virtual list if 1000+ rows get slow.
|
||||
@@ -622,32 +623,8 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
|
||||
const refreshAfterTargets = () => void invalidate(queryClient, 'skillSyncChanged');
|
||||
|
||||
/** Optimistic patch of the skills cache; returns the snapshot to roll back to. */
|
||||
const patch = async (fn: (skills: Skill[]) => Skill[]) => {
|
||||
await queryClient.cancelQueries({ queryKey: queryKeys.skills.all });
|
||||
const previous = queryClient.getQueryData<SkillsData>(queryKeys.skills.all);
|
||||
if (previous)
|
||||
queryClient.setQueryData<SkillsData>(queryKeys.skills.all, {
|
||||
...previous,
|
||||
resources: fn(previous.resources),
|
||||
});
|
||||
return { previous };
|
||||
};
|
||||
const rollback = (err: Error, _: unknown, ctx?: { previous?: SkillsData }) => {
|
||||
if (ctx?.previous) queryClient.setQueryData(queryKeys.skills.all, ctx.previous);
|
||||
toast(err.message, 'error');
|
||||
};
|
||||
|
||||
const toggleOne = useMutation({
|
||||
mutationFn: ({ s, disable }: { s: Skill; disable: boolean }) =>
|
||||
disable ? api.disableResource(s.flatName, s.kind) : api.enableResource(s.flatName, s.kind),
|
||||
onMutate: ({ s, disable }) =>
|
||||
patch((list) =>
|
||||
list.map((x) =>
|
||||
x.flatName === s.flatName && x.kind === s.kind ? { ...x, disabled: disable } : x,
|
||||
),
|
||||
),
|
||||
onSuccess: (_, { s, disable }) => {
|
||||
const { toggleOne, toggleMany } = useResourceToggle({
|
||||
onOne: ({ s, disable }) => {
|
||||
const kindLabel = isAgent ? 'Agent' : 'Skill';
|
||||
toast(
|
||||
t(disable ? 'resources.toast.disabled' : 'resources.toast.enabled', {
|
||||
@@ -658,20 +635,7 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
{ key: TOGGLE_TOAST },
|
||||
);
|
||||
},
|
||||
onError: rollback,
|
||||
onSettled: refreshAfterTargets,
|
||||
});
|
||||
|
||||
const toggleMany = useMutation({
|
||||
mutationFn: ({ names, enable }: { names: string[]; enable: boolean }) =>
|
||||
api.batchToggleResources(names, enable, kind),
|
||||
onMutate: ({ names, enable }) => {
|
||||
const set = new Set(names);
|
||||
return patch((list) =>
|
||||
list.map((x) => (x.kind === kind && set.has(x.flatName) ? { ...x, disabled: !enable } : x)),
|
||||
);
|
||||
},
|
||||
onSuccess: (res, { enable }) => {
|
||||
onMany: (res, { enable }) => {
|
||||
const { updated, unchanged, failed } = res.summary;
|
||||
// Name the first failure: the count alone hides why an item stayed as it was.
|
||||
const firstError = res.results.find((r) => r.error);
|
||||
@@ -695,19 +659,13 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
);
|
||||
setSelected(new Set());
|
||||
},
|
||||
onError: rollback,
|
||||
onSettled: () => void invalidate(queryClient, 'skillsToggled'),
|
||||
onError: (err) => toast(err.message, 'error'),
|
||||
});
|
||||
|
||||
const setTargets = useMutation({
|
||||
mutationFn: ({ name, target }: { name: string; target: string | null }) =>
|
||||
api.setSkillTargets(name, target),
|
||||
onMutate: ({ name, target }) =>
|
||||
patch((list) =>
|
||||
list.map((x) =>
|
||||
x.flatName === name ? { ...x, targets: target ? [target] : undefined } : x,
|
||||
),
|
||||
),
|
||||
onMutate: ({ name, target }) => optimisticTargets(queryClient, kind, name, target),
|
||||
onSuccess: (_, { name, target }) =>
|
||||
toast(
|
||||
target
|
||||
@@ -715,7 +673,10 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
: t('resources.toast.limitRemoved', { name }),
|
||||
'success',
|
||||
),
|
||||
onError: rollback,
|
||||
onError: (err, _, restoreTargets) => {
|
||||
restoreTargets?.();
|
||||
toast(err.message, 'error');
|
||||
},
|
||||
onSettled: refreshAfterTargets,
|
||||
});
|
||||
|
||||
@@ -1423,7 +1384,7 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
subject={subject}
|
||||
busy={toggleMany.isPending || toggleOne.isPending}
|
||||
onToggleAll={(list, enable) =>
|
||||
toggleMany.mutate({ names: list.map((s) => s.flatName), enable })
|
||||
toggleMany.mutate({ kind, names: list.map((s) => s.flatName), enable })
|
||||
}
|
||||
onToggleOne={(s) => toggleOne.mutate({ s, disable: !s.disabled })}
|
||||
onSetTargets={(e) => {
|
||||
@@ -1909,7 +1870,11 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
size="sm"
|
||||
disabled={toggleMany.isPending}
|
||||
onClick={() =>
|
||||
toggleMany.mutate({ names: selectedItems.map((s) => s.flatName), enable: true })
|
||||
toggleMany.mutate({
|
||||
kind,
|
||||
names: selectedItems.map((s) => s.flatName),
|
||||
enable: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
<CircleCheck size={15} />
|
||||
@@ -2134,7 +2099,7 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
|
||||
variant="danger"
|
||||
loading={toggleMany.isPending}
|
||||
onConfirm={() => {
|
||||
if (confirmDisable) toggleMany.mutate({ names: confirmDisable, enable: false });
|
||||
if (confirmDisable) toggleMany.mutate({ kind, names: confirmDisable, enable: false });
|
||||
setConfirmDisable(null);
|
||||
}}
|
||||
onCancel={() => setConfirmDisable(null)}
|
||||
|
||||
@@ -86,6 +86,33 @@ describe('Sync page folder conflicts', () => {
|
||||
vi.mocked(api.updateTarget).mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
it('shows a pending source migration even without MCP file changes', async () => {
|
||||
vi.mocked(mcpApi.list).mockResolvedValue({
|
||||
...(await mcpApi.list()),
|
||||
plan: {
|
||||
changes: [],
|
||||
blocked: false,
|
||||
migrates: true,
|
||||
revision: 'r',
|
||||
sourcePath: 'config.yaml',
|
||||
},
|
||||
});
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<I18nProvider>
|
||||
<ToastProvider>
|
||||
<SyncPage />
|
||||
</ToastProvider>
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
expect(await screen.findByRole('button', { name: 'Sync 1 change' })).toBeEnabled();
|
||||
expect(screen.getByText('Migrate MCP source settings')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/No targets yet|Nothing to sync/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('names the targets that undo each other and stops skills for the one to drop', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
|
||||
+18
-31
@@ -46,9 +46,8 @@ import {
|
||||
groupByFolder,
|
||||
groupInSync,
|
||||
HOOKS_CHANGED,
|
||||
hooksGroups,
|
||||
reviewSyncConfig,
|
||||
MCP_CHANGED,
|
||||
mcpGroups,
|
||||
otherWarnings,
|
||||
resourceGroups,
|
||||
runSync,
|
||||
@@ -216,19 +215,17 @@ export default function SyncPage() {
|
||||
skill: diff.data?.ignored_skills,
|
||||
agent: diff.data?.agent_ignored_skills,
|
||||
});
|
||||
const mcpShown = parts.has('mcp') ? mcpGroups(plan) : [];
|
||||
const hooksShown = parts.has('hooks') ? hooksGroups(hooksPlan) : [];
|
||||
const groups: ChangeGroup[] = [
|
||||
const config = reviewSyncConfig(
|
||||
parts.has('mcp') ? plan : null,
|
||||
parts.has('hooks') ? hooksPlan : null,
|
||||
);
|
||||
const resourceRows = [
|
||||
...resources.groups,
|
||||
...(parts.has('extra') ? extraGroups(extras.data?.extras ?? [], force) : []),
|
||||
...mcpShown,
|
||||
...hooksShown,
|
||||
];
|
||||
// A blocked plan applies nothing, so its rows are shown but not counted.
|
||||
const count =
|
||||
countChanges(groups) -
|
||||
(plan?.blocked ? countChanges(mcpShown) : 0) -
|
||||
(hooksPlan?.blocked ? countChanges(hooksShown) : 0);
|
||||
const groups = [...resourceRows, ...config.mcpRows, ...config.hookRows];
|
||||
const count = countChanges(resourceRows) + config.count;
|
||||
const previewEmpty = groups.length === 0 && !config.migrationOnly;
|
||||
const edited = countEdited(groups);
|
||||
const total = tally(groups.flatMap((g) => g.rows).filter((r) => r.counts));
|
||||
const loading = diff.isPending || targets.isPending;
|
||||
@@ -302,20 +299,7 @@ export default function SyncPage() {
|
||||
? 'agent'
|
||||
: null,
|
||||
extras: parts.has('extra') && !!extras.data?.extras.length,
|
||||
mcp:
|
||||
parts.has('mcp') &&
|
||||
plan &&
|
||||
!plan.blocked &&
|
||||
(plan.migrates || plan.changes.some((c) => c.action !== 'unchanged'))
|
||||
? plan
|
||||
: null,
|
||||
hooks:
|
||||
parts.has('hooks') &&
|
||||
hooksPlan &&
|
||||
!hooksPlan.blocked &&
|
||||
hooksPlan.changes.some((c) => c.action !== 'unchanged')
|
||||
? hooksPlan
|
||||
: null,
|
||||
...config.run,
|
||||
force,
|
||||
});
|
||||
setOutcome(result ?? null);
|
||||
@@ -592,7 +576,7 @@ export default function SyncPage() {
|
||||
<SyncError key={runError} error={runError} />
|
||||
</div>
|
||||
)}
|
||||
{parts.has('mcp') && plan?.blocked && (
|
||||
{config.mcpBlocked && (
|
||||
<div className="ss-note warn !items-center">
|
||||
<TriangleAlert size={16} />
|
||||
<span className="flex-1">{t('sync.mcpBlocked')}</span>
|
||||
@@ -601,7 +585,7 @@ export default function SyncPage() {
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
{parts.has('hooks') && hooksPlan?.blocked && (
|
||||
{config.hooksBlocked && (
|
||||
<div className="ss-note warn !items-center">
|
||||
<TriangleAlert size={16} />
|
||||
<span className="flex-1">{t('sync.hooksBlocked')}</span>
|
||||
@@ -653,7 +637,7 @@ export default function SyncPage() {
|
||||
/>
|
||||
))}
|
||||
|
||||
{!loading && !diff.error && groups.length > 0 && (
|
||||
{!loading && !diff.error && !previewEmpty && (
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="ss-h2">{t(plural('sync.pending', count), { count })}</h2>
|
||||
<span className="flex-1 text-[12px] text-ink-2">
|
||||
@@ -689,7 +673,7 @@ export default function SyncPage() {
|
||||
<AlertCircle size={16} />
|
||||
<SyncError error={diff.error.message} />
|
||||
</div>
|
||||
) : diffs.length === 0 && groups.length === 0 ? (
|
||||
) : diffs.length === 0 && previewEmpty ? (
|
||||
<div className="ss-r text-[13px] text-ink-2">
|
||||
<span className="flex-1">{t('sync.noTargets')}</span>
|
||||
<Link to="/targets" className="ss-btn sm">
|
||||
@@ -698,7 +682,10 @@ export default function SyncPage() {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{groups.length === 0 && (
|
||||
{config.migrationOnly && (
|
||||
<div className="ss-r text-[13px]">{t('sync.migrateMcpSource')}</div>
|
||||
)}
|
||||
{previewEmpty && (
|
||||
<div className="ss-r text-[13px]">
|
||||
<CircleCheck size={16} className="text-ok" />
|
||||
{t('sync.nothing')}
|
||||
|
||||
+3
-1
@@ -21,7 +21,7 @@ Use when changing React components, pages, CSS, responsive layouts, interactions
|
||||
| Query keys | `ui/src/lib/queryKeys.ts` |
|
||||
| Which queries a mutation makes stale | named events in `ui/src/lib/queryEvents.ts`, called as `invalidate(queryClient, '<event>')` |
|
||||
| Queries shared across pages (overview, MCP, skills, targets, diff) | `ui/src/hooks/useSharedQueries.ts` |
|
||||
| API client | `ui/src/api/client.ts` |
|
||||
| API client | Domain modules call `http.get/post/put/patch/delete` from `ui/src/api/http.ts`; pass JSON bodies as values, not serialized strings. Use `http.postRaw` only for already-serialized input. Streaming endpoints manage their own event lifecycle. `ui/src/api/client.ts` remains a compatibility facade. |
|
||||
| `?kind=` query strings | `kindQuery()` in `ui/src/api/http.ts` |
|
||||
| Translation strings | `ui/src/i18n/` |
|
||||
|
||||
@@ -29,6 +29,8 @@ The dashboard supports Clean and Playful styles plus light, dark, and system mod
|
||||
|
||||
`python3 scripts/design/tokens.py` exports the Clean tokens from `components.css` in Design System `tokens.json` format, for mockup tools that read a design system instead of the CSS. A new Clean color variable needs a usage note in that script, or the export (and its test) fails.
|
||||
|
||||
Operation hooks such as `useResourceToggle` and `useResourceMove` own requests and cache reconciliation; pages and dialogs own selection, confirmation, and translated feedback. Pass React Query's signal to cancellable reads, not writes. Keep MCP preview/revision sequencing in `mcpApi.save`, not its callers.
|
||||
|
||||
## Dashboard Composition
|
||||
|
||||
- Use `ss-wrap animate-page-in` on the page root and place `PageHeader` first.
|
||||
|
||||
Reference in New Issue
Block a user