From 96b6acff28b70f2cef46de3ca62b3c529f318aa2 Mon Sep 17 00:00:00 2001 From: Willie Date: Thu, 19 Nov 2026 00:48:18 +0800 Subject: [PATCH] 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. --- ui/src/api/audit.ts | 42 ++---- ui/src/api/backups.ts | 54 +++----- ui/src/api/config.ts | 34 ++--- ui/src/api/extras.test.ts | 43 ++++++ ui/src/api/extras.ts | 118 +++++------------ ui/src/api/git.ts | 48 ++----- ui/src/api/hooks.ts | 36 +++-- ui/src/api/http.ts | 20 ++- ui/src/api/hubDrafts.ts | 30 ++--- ui/src/api/install.ts | 50 +++---- ui/src/api/instructions.ts | 123 ++++++------------ ui/src/api/kindQuery.test.ts | 20 +-- ui/src/api/log.ts | 9 +- ui/src/api/mcp.test.ts | 42 +++--- ui/src/api/mcp.ts | 28 ++-- ui/src/api/mcpCheck.ts | 7 +- ui/src/api/memory.ts | 46 +++---- ui/src/api/ompExtensions.ts | 9 +- ui/src/api/piExtensions.ts | 14 +- ui/src/api/plugins.test.ts | 34 ++--- ui/src/api/plugins.ts | 18 ++- ui/src/api/resources.test.ts | 22 ++++ ui/src/api/resources.ts | 101 +++++--------- ui/src/api/sync.ts | 26 ++-- ui/src/api/system.ts | 19 ++- ui/src/api/targets.ts | 52 +++----- ui/src/api/types/extras.ts | 30 ++++- ui/src/api/update.ts | 8 +- ui/src/components/UpdateDialog.tsx | 42 +++--- .../components/projects/ProjectSyncDialog.tsx | 42 ++---- ui/src/components/resources/MoveDialog.tsx | 35 +---- ui/src/components/sync/syncView.test.ts | 29 +++++ ui/src/components/sync/syncView.ts | 48 ++++++- .../__tests__/useResourceToggle.test.tsx | 69 ++++++++++ ui/src/hooks/useResourceMove.ts | 39 ++++++ ui/src/hooks/useResourceToggle.ts | 94 +++++++++++++ ui/src/hooks/useSharedQueries.ts | 2 +- ui/src/i18n/locales/de.json | 1 + ui/src/i18n/locales/en.json | 1 + ui/src/i18n/locales/es.json | 1 + ui/src/i18n/locales/fa.json | 1 + ui/src/i18n/locales/fr.json | 1 + ui/src/i18n/locales/id.json | 1 + ui/src/i18n/locales/ja.json | 1 + ui/src/i18n/locales/ko.json | 1 + ui/src/i18n/locales/pt-BR.json | 1 + ui/src/i18n/locales/zh-CN.json | 1 + ui/src/i18n/locales/zh-TW.json | 1 + ui/src/lib/optimisticTargets.test.ts | 31 +++++ ui/src/lib/optimisticTargets.ts | 31 +++++ ui/src/lib/upgradeWorkflow.test.ts | 26 ++++ ui/src/lib/upgradeWorkflow.ts | 22 ++++ ui/src/pages/DoctorPage.tsx | 22 +--- ui/src/pages/ResourcesPage.tsx | 71 +++------- ui/src/pages/SyncPage.test.tsx | 27 ++++ ui/src/pages/SyncPage.tsx | 49 +++---- wiki/frontend.md | 4 +- 57 files changed, 952 insertions(+), 825 deletions(-) create mode 100644 ui/src/api/extras.test.ts create mode 100644 ui/src/hooks/__tests__/useResourceToggle.test.tsx create mode 100644 ui/src/hooks/useResourceMove.ts create mode 100644 ui/src/hooks/useResourceToggle.ts create mode 100644 ui/src/lib/optimisticTargets.test.ts create mode 100644 ui/src/lib/optimisticTargets.ts create mode 100644 ui/src/lib/upgradeWorkflow.test.ts create mode 100644 ui/src/lib/upgradeWorkflow.ts diff --git a/ui/src/api/audit.ts b/ui/src/api/audit.ts index 5fb4c5467..16f6963cb 100644 --- a/ui/src/api/audit.ts +++ b/ui/src/api/audit.ts @@ -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(`/audit${kindQuery(kind)}`), + auditAll: (kind?: 'skills' | 'agents') => http.get(`/audit${kindQuery(kind)}`), auditSkill: (name: string, kind?: 'skill' | 'agent') => - apiFetch( + http.get( `/audit/${encodeURIComponent(name)}${kindQuery(kind === 'agent' ? kind : undefined)}`, ), auditAllStream: ( @@ -30,36 +30,16 @@ export const auditApi = { onError, 'Audit stream failed', ), - getAuditRules: () => apiFetch('/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('/audit/rules/compiled'), + getAuditRules: () => http.get('/audit/rules'), + putAuditRules: (raw: string) => http.put<{ success: boolean }>('/audit/rules', { raw }), + initAuditRules: () => http.post<{ success: boolean; path: string }>('/audit/rules'), + getCompiledRules: () => http.get('/audit/rules/compiled'), /** Severity at which install and sync refuse a resource. */ setAuditThreshold: (blockThreshold: string) => - apiFetch('/audit/policy', { - method: 'PATCH', - body: JSON.stringify({ blockThreshold }), - }), + http.patch('/audit/policy', { blockThreshold }), /** Preset for how strict a scan is: default, strict, or permissive. */ - setAuditProfile: (profile: string) => - apiFetch('/audit/policy', { - method: 'PATCH', - body: JSON.stringify({ profile }), - }), + setAuditProfile: (profile: string) => http.patch('/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'), }; diff --git a/ui/src/api/backups.ts b/ui/src/api/backups.ts index 9f0e1baa3..7a0bd23ef 100644 --- a/ui/src/api/backups.ts +++ b/ui/src/api/backups.ts @@ -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('/backups'), + listBackups: () => http.get('/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('/restore/validate', { - method: 'POST', - body: JSON.stringify(opts), - }), - deleteAllBackups: () => - apiFetch<{ success: boolean; removed: number }>('/backups', { method: 'DELETE' }), + http.post('/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(`/file-backups/versions?path=${encodeURIComponent(path)}`), + http.get(`/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('/trash'), + http.post<{ success: boolean; backup_id?: string }>('/file-backups/restore', body), + listTrash: () => http.get('/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)}`), }; diff --git a/ui/src/api/config.ts b/ui/src/api/config.ts index c988a9bc0..289f56d27 100644 --- a/ui/src/api/config.ts +++ b/ui/src/api/config.ts @@ -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('/config', { - method: 'PUT', - body: JSON.stringify({ raw }), - }), - availableTargets: () => apiFetch<{ targets: AvailableTarget[] }>('/config/available-targets'), - getSkillignore: () => apiFetch('/skillignore'), - putSkillignore: (raw: string) => - apiFetch<{ success: boolean }>('/skillignore', { - method: 'PUT', - body: JSON.stringify({ raw }), - }), - getAgentignore: () => apiFetch('/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('/config', { raw }), + availableTargets: () => http.get<{ targets: AvailableTarget[] }>('/config/available-targets'), + getSkillignore: () => http.get('/skillignore'), + putSkillignore: (raw: string) => http.put<{ success: boolean }>('/skillignore', { raw }), + getAgentignore: () => http.get('/agentignore'), + putAgentignore: (raw: string) => http.put<{ success: boolean }>('/agentignore', { raw }), }; diff --git a/ui/src/api/extras.test.ts b/ui/src/api/extras.test.ts new file mode 100644 index 000000000..1642338e8 --- /dev/null +++ b/ui/src/api/extras.test.ts @@ -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' }], + ]); +}); diff --git a/ui/src/api/extras.ts b/ui/src/api/extras.ts index 07ae1629b..a28b0bd5c 100644 --- a/ui/src/api/extras.ts +++ b/ui/src/api/extras.ts @@ -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('/extras', input), + syncExtras: (options: { name?: string; dry_run?: boolean; force?: boolean } = {}) => + http.post<{ extras: ExtrasSyncResult[] }>('/extras/sync', options), + deleteExtra: (name: string) => http.delete(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(`${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(`${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(`/extras/${encodeURIComponent(name)}/targets`, { - method: 'PUT', - body: JSON.stringify({ path, target }), - }), + editExtraTarget: (name: string, path: string, target: EditExtraTarget) => + http.put(`${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(`/extras/${encodeURIComponent(name)}`, { - method: 'PATCH', - body: JSON.stringify(data), - }), + http.patch(extraPath(name), data), removeExtraTarget: (name: string, path: string) => - apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/targets`, { - method: 'DELETE', - body: JSON.stringify({ path }), - }), + http.delete(`${extraPath(name)}/targets`, { path }), + + listExtraExtensions: () => http.get<{ extensions: string[] }>('/extras/extensions'), + listExtensions: () => http.get<{ extensions: ExtensionInfo[] }>('/extensions'), + installExtension: (name: string) => + http.post('/extensions/install', { name }), + openExtensionsDir: () => http.post<{ path: string }>('/extensions/open'), + removeExtension: (name: string) => + http.delete(`/extensions/${encodeURIComponent(name)}`), }; diff --git a/ui/src/api/git.ts b/ui/src/api/git.ts index c9d609c63..7e8cb33fd 100644 --- a/ui/src/api/git.ts +++ b/ui/src/api/git.ts @@ -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('/git/status'), + gitStatus: () => http.get('/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(`/git/branches${opts?.fetch ? '?fetch=true' : ''}`), - gitCheckout: (branch: string) => - apiFetch('/git/checkout', { - method: 'POST', - body: JSON.stringify({ branch }), - }), + http.get(`/git/branches${opts?.fetch ? '?fetch=true' : ''}`), + gitCheckout: (branch: string) => http.post('/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('/git/commit', { - method: 'POST', - body: JSON.stringify(opts), - }), - gitDiscard: (opts: { dryRun?: boolean }) => - apiFetch('/git/discard', { - method: 'POST', - body: JSON.stringify(opts), - }), - push: (opts: { message?: string; dryRun?: boolean }) => - apiFetch('/push', { - method: 'POST', - body: JSON.stringify(opts), - }), + http.post('/git/commit', opts), + gitDiscard: (opts: { dryRun?: boolean }) => http.post('/git/discard', opts), + push: (opts: { message?: string; dryRun?: boolean }) => http.post('/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('/pull', { - method: 'POST', - body: JSON.stringify(opts ?? {}), - }), + }) => http.post('/pull', opts ?? {}), }; diff --git a/ui/src/api/hooks.ts b/ui/src/api/hooks.ts index ecd05e8ff..b356cfcbf 100644 --- a/ui/src/api/hooks.ts +++ b/ui/src/api/hooks.ts @@ -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 = (path: string, body: unknown) => - apiFetch(path, { method: 'POST', body: JSON.stringify(body) }); - export const hooksApi = { - list: () => apiFetch('/hooks'), - catalog: () => apiFetch>('/hooks/catalog'), + list: () => http.get('/hooks'), + catalog: () => http.get>('/hooks/catalog'), /** An empty mutation previews synchronizing the current source. */ - preview: (mutation: HookMutation = {}) => post('/hooks/preview', { mutation }), + preview: (mutation: HookMutation = {}) => http.post('/hooks/preview', { mutation }), configure: (mutation: HookMutation, revision: string, sync: boolean) => - post('/hooks', { mutation, revision, sync }), + http.post('/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('/hooks', { + http.post('/hooks', { mutation, - revision: (await post('/hooks/preview', { mutation })).revision, + revision: (await http.post('/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('/hooks', { mutation: {}, revision, sync: true, root }), + http.post('/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('/hooks/native/preview', { edits }), + previewNative: (edits: HookNativeEdit[]) => + http.post('/hooks/native/preview', { edits }), /** Writes previewed edits, with a backup per file. The hooks stay unmanaged. */ applyNative: (edits: HookNativeEdit[], revision: string) => - post('/hooks/native', { edits, revision }), + http.post('/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('/hooks/codex-trust/preview', {}), + previewCodexTrust: () => http.post('/hooks/codex-trust/preview', {}), /** Records trust for the previewed hooks. Refused (409) when they changed since the preview. */ - trustCodex: (revision: string) => post('/hooks/codex-trust', { revision }), + trustCodex: (revision: string) => http.post('/hooks/codex-trust', { revision }), previewRestore: (backupId: string) => - post('/hooks/restore', { backupId, preview: true }), + http.post('/hooks/restore', { backupId, preview: true }), restore: (backupId: string, revision: string) => - post('/hooks/restore', { backupId, revision }), + http.post('/hooks/restore', { backupId, revision }), }; diff --git a/ui/src/api/http.ts b/ui/src/api/http.ts index 40048fe15..69aecb230 100644 --- a/ui/src/api/http.ts +++ b/ui/src/api/http.ts @@ -90,7 +90,8 @@ export async function apiFetch(path: string, init?: RequestInit): Promise 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(path: string, init?: RequestInit): Promise return data as T; } +export type SuccessResponse = { success: boolean }; + +function jsonRequest(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE') { + return (path: string, body?: unknown) => + apiFetch(path, { method, body: JSON.stringify(body) }); +} + +export const http = { + get: (path: string, signal?: AbortSignal) => apiFetch(path, { signal }), + // Import already-serialized JSON without quoting it a second time. + postRaw: (path: string, body: string) => apiFetch(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. diff --git a/ui/src/api/hubDrafts.ts b/ui/src/api/hubDrafts.ts index 8b26759fd..b4b01accd 100644 --- a/ui/src/api/hubDrafts.ts +++ b/ui/src/api/hubDrafts.ts @@ -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(root), - get: (id: string) => apiFetch(`${root}/${encodeURIComponent(id)}`), - candidates: () => apiFetch(`${root}/candidates`), - create: (draft: Partial) => apiFetch(root, json('POST', draft)), + list: () => http.get(root), + get: (id: string) => http.get(`${root}/${encodeURIComponent(id)}`), + candidates: () => http.get(`${root}/candidates`), + create: (draft: Partial) => http.post(root, draft), save: (draft: HubDraft) => - apiFetch(`${root}/${encodeURIComponent(draft.id)}`, json('PUT', draft)), + http.put(`${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(`${root}/import`, { method: 'POST', body: raw }), + import: (raw: string) => http.postRaw(`${root}/import`, raw), export: (draft: HubDraft) => - apiFetch>( - `${root}/${encodeURIComponent(draft.id)}/export`, - json('POST', { revision: draft.revision }), - ), + http.post>(`${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('/hub/refs', json('POST', ref === undefined ? { source } : { source, ref })); + http.post('/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('/hub/refs', json('POST', { source, anyGit: true })); + http.post('/hub/refs', { source, anyGit: true }); export function hubAddCommand(location: string, label: string): string { const quote = (s: string) => `'${s.replace(/'/g, `'"'"'`)}'`; diff --git a/ui/src/api/install.ts b/ui/src/api/install.ts index c5ede98ce..5ea0d8ec0 100644 --- a/ui/src/api/install.ts +++ b/ui/src/api/install.ts @@ -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('/hub/index'), - getHubConfig: () => apiFetch('/hub/saved'), + hubIndex: () => http.get('/hub/index'), + getHubConfig: () => http.get('/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(`/preview?source=${encodeURIComponent(source)}`), - check: () => apiFetch('/check'), + http.get(`/preview?source=${encodeURIComponent(source)}`), + check: () => http.get('/check'), checkStream: ( onDiscovering: () => void, onStart: (total: number) => void, @@ -59,10 +51,7 @@ export const installApi = { 'Check stream failed', ), discover: (source: string, branch?: string) => - apiFetch('/discover', { - method: 'POST', - body: JSON.stringify({ source, branch }), - }), + http.post('/discover', { source, branch }), install: (opts: { source: string; name?: string; @@ -72,16 +61,11 @@ export const installApi = { into?: string; branch?: string; kind?: 'skill' | 'agent'; - }) => - apiFetch('/install', { - method: 'POST', - body: JSON.stringify(opts), - }), + }) => http.post('/install', opts), // Entries recorded in config but not on disk (bare `skillshare install`) missingConfigEntries: () => - apiFetch<{ entries: ConfigEntry[]; file: string }>('/install/missing'), - installFromConfig: () => - apiFetch('/install/from-config', { method: 'POST' }), + http.get<{ entries: ConfigEntry[]; file: string }>('/install/missing'), + installFromConfig: () => http.post('/install/from-config'), installBatch: (opts: { source: string; skills: DiscoveredSkill[]; @@ -91,9 +75,5 @@ export const installApi = { name?: string; branch?: string; kind?: 'skill' | 'agent'; - }) => - apiFetch('/install/batch', { - method: 'POST', - body: JSON.stringify(opts), - }), + }) => http.post('/install/batch', opts), }; diff --git a/ui/src/api/instructions.ts b/ui/src/api/instructions.ts index 4f8fca4fd..d6a158aa6 100644 --- a/ui/src/api/instructions.ts +++ b/ui/src/api/instructions.ts @@ -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(`/targets/${encodeURIComponent(name)}/instructions`), + http.get(`/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(`/targets/${encodeURIComponent(name)}/files`), + http.get(`/targets/${encodeURIComponent(name)}/files`), getTargetFile: (name: string, path: string) => - apiFetch( + http.get( `/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`, ), putTargetFile: (name: string, path: string, content: string) => - apiFetch( + http.put( `/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`, - { - method: 'PUT', - body: JSON.stringify({ content }), - }, + { content }, ), addTargetFile: (name: string, path: string) => - apiFetch(`/targets/${encodeURIComponent(name)}/files`, { - method: 'POST', - body: JSON.stringify({ path }), - }), + http.post(`/targets/${encodeURIComponent(name)}/files`, { path }), removeTargetFile: (name: string, path: string) => - apiFetch( + http.delete( `/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( + http.get( `/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( + http.get( `/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('/instructions/project'), + getProjectInstructions: () => http.get('/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 }), }; diff --git a/ui/src/api/kindQuery.test.ts b/ui/src/api/kindQuery.test.ts index 9523bd949..ace3a3865 100644 --- a/ui/src/api/kindQuery.test.ts +++ b/ui/src/api/kindQuery.test.ts @@ -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()), - apiFetch: vi.fn(), -})); +const fetch = vi.fn(); // 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']); }); }); diff --git a/ui/src/api/log.ts b/ui/src/api/log.ts index 97bd12856..2e8bf1e19 100644 --- a/ui/src/api/log.ts +++ b/ui/src/api/log.ts @@ -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(`/log?${params.toString()}`); + return http.get(`/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(`/log/stats?${params.toString()}`); + return http.get(`/log/stats?${params.toString()}`); }, }; diff --git a/ui/src/api/mcp.test.ts b/ui/src/api/mcp.test.ts index 823b0dcc6..093f26e3c 100644 --- a/ui/src/api/mcp.test.ts +++ b/ui/src/api/mcp.test.ts @@ -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() + .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 }], + ]); }); diff --git a/ui/src/api/mcp.ts b/ui/src/api/mcp.ts index f91773d28..4647d57b1 100644 --- a/ui/src/api/mcp.ts +++ b/ui/src/api/mcp.ts @@ -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 = (path: string, body: unknown) => - apiFetch(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('/mcp/preview', { mutation }), + preview: (mutation: MCPMutation = {}) => http.post('/mcp/preview', { mutation }), configure: (mutation: MCPMutation, revision: string, sync: boolean) => - post('/mcp', { mutation, revision, sync }), + http.post('/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('/mcp', { mutation: {}, revision, sync: true, root }), + http.post('/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('/mcp', { + http.post('/mcp', { mutation, - revision: (await post('/mcp/preview', { mutation })).revision, + revision: (await http.post('/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('/mcp/restore', { backupId, preview: true }), + }) => http.post<{ candidates: MCPCandidate[] }>('/mcp/import', body), + previewRestore: (backupId: string) => + http.post('/mcp/restore', { backupId, preview: true }), restore: (backupId: string, revision: string) => - post('/mcp/restore', { backupId, revision }), + http.post('/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 }), }; diff --git a/ui/src/api/mcpCheck.ts b/ui/src/api/mcpCheck.ts index c72badcef..1f59f4462 100644 --- a/ui/src/api/mcpCheck.ts +++ b/ui/src/api/mcpCheck.ts @@ -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('/mcp/check'), + run: () => http.get('/mcp/check'), /** Starts the server as the form describes it, saved or not, and asks for its tools. Saves nothing. */ - probe: (mutation: MCPMutation) => - apiFetch('/mcp/probe', { method: 'POST', body: JSON.stringify({ mutation }) }), + probe: (mutation: MCPMutation) => http.post('/mcp/probe', { mutation }), }; diff --git a/ui/src/api/memory.ts b/ui/src/api/memory.ts index badf6eef1..1f1ea870f 100644 --- a/ui/src/api/memory.ts +++ b/ui/src/api/memory.ts @@ -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('/extras/memory/recent'), + getMemoryOverview: () => http.get('/extras/memory/recent'), listMemoryNotes: (search = '') => - apiFetch(`/extras/memory/notes?search=${encodeURIComponent(search)}`), - initMemory: () => - apiFetch<{ success: boolean; root: string }>('/extras/memory/init', { method: 'POST' }), - getMemoryGuidance: () => apiFetch('/extras/memory/guidance'), + http.get(`/extras/memory/notes?search=${encodeURIComponent(search)}`), + initMemory: () => http.post<{ success: boolean; root: string }>('/extras/memory/init'), + getMemoryGuidance: () => http.get('/extras/memory/guidance'), planMemoryGuidance: (targets: string[], modes: Record) => - apiFetch('/extras/memory/guidance/plan', { - method: 'POST', - body: JSON.stringify({ targets, modes }), - }), + http.post('/extras/memory/guidance/plan', { targets, modes }), applyMemoryGuidance: ( targets: string[], modes: Record, 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('/extras/memory/index', { - method: 'PUT', - body: JSON.stringify({ path, version }), - }), + http.put('/extras/memory/index', { path, version }), readMemoryNote: (path: string) => - apiFetch(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`), + http.get(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`), writeMemoryNote: (path: string, content: string, version: string) => - apiFetch('/extras/memory/notes/content', { - method: 'PUT', - body: JSON.stringify({ path, content, version }), - }), + http.put('/extras/memory/notes/content', { path, content, version }), moveMemoryNote: (path: string, newPath: string, version: string) => - apiFetch('/extras/memory/move', { - method: 'POST', - body: JSON.stringify({ path, new_path: newPath, version }), - }), + http.post('/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, }), }; diff --git a/ui/src/api/ompExtensions.ts b/ui/src/api/ompExtensions.ts index d7ccbc61a..5ff77b3f8 100644 --- a/ui/src/api/ompExtensions.ts +++ b/ui/src/api/ompExtensions.ts @@ -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(`${base(target)}/${verb}`, { - method: 'POST', - body: JSON.stringify({ changes, revision }), - }); + http.post(`${base(target)}/${verb}`, { changes, revision }); export const ompExtensionsApi = { - get: (target: string) => apiFetch(base(target)), + get: (target: string) => http.get(base(target)), /** Writes nothing; `revision` is the view's. */ preview: (target: string, changes: OmpExtensionChange[], revision: string) => post(target, 'preview', changes, revision), diff --git a/ui/src/api/piExtensions.ts b/ui/src/api/piExtensions.ts index 0cf6c355f..94c6a2500 100644 --- a/ui/src/api/piExtensions.ts +++ b/ui/src/api/piExtensions.ts @@ -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(base(target)), + get: (target: string) => http.get(base(target)), /** Writes nothing; the plan's revision is what apply checks the file against. */ preview: (target: string, changes: PiExtensionChange[]) => - apiFetch(`${base(target)}/preview`, { - method: 'POST', - body: JSON.stringify({ changes }), - }), + http.post(`${base(target)}/preview`, { changes }), apply: (target: string, changes: PiExtensionChange[], revision: string) => - apiFetch(`${base(target)}/apply`, { - method: 'POST', - body: JSON.stringify({ changes, revision }), - }), + http.post(`${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. */ diff --git a/ui/src/api/plugins.test.ts b/ui/src/api/plugins.test.ts index 5da5a8b03..275637d4c 100644 --- a/ui/src/api/plugins.test.ts +++ b/ui/src/api/plugins.test.ts @@ -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([]); }); diff --git a/ui/src/api/plugins.ts b/ui/src/api/plugins.ts index ef40a4387..a4b6229d4 100644 --- a/ui/src/api/plugins.ts +++ b/ui/src/api/plugins.ts @@ -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 = (path: string, body: unknown) => - apiFetch(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(hosts ? '/plugins' : '/plugins?hosts=false').then((inv) => ({ + http.get(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('/plugins/discover', { source, sourceRef, entry, name }), + http.post('/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('/plugins/preview', { request }), + preview: (request: PluginRequest) => http.post('/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((resolve, reject) => { @@ -374,9 +372,9 @@ export const pluginsApi = { ); }), apply: (request: PluginRequest, revision: string) => - post('/plugins/apply', { request, revision }), + http.post('/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', {}), }; diff --git a/ui/src/api/resources.test.ts b/ui/src/api/resources.test.ts index cd9280fe7..6e1fb6f8f 100644 --- a/ui/src/api/resources.test.ts +++ b/ui/src/api/resources.test.ts @@ -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( + (_, 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()); diff --git a/ui/src/api/resources.ts b/ui/src/api/resources.ts index 2427ce7d7..48b254b1f 100644 --- a/ui/src/api/resources.ts +++ b/ui/src/api/resources.ts @@ -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('/source-links', { method: 'POST', body: JSON.stringify(body) }), + createSourceLink: (body: SourceLinkRequest) => http.post('/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'), - listSkills: (kind?: 'skill' | 'agent') => - apiFetch<{ + getOverview: () => http.get('/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('/uninstall/batch', { - method: 'POST', - body: JSON.stringify(opts), - }), - moveResources: (opts: MoveRequest) => - apiFetch('/resources/batch/move', { - method: 'POST', - body: JSON.stringify(opts), - }), + http.post('/uninstall/batch', opts), + moveResources: (opts: MoveRequest) => http.post('/resources/batch/move', opts), getTemplates: async () => { - const res = await apiFetch('/resources/templates'); + const res = await http.get('/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) => - 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('/resources', { - method: 'POST', - body: JSON.stringify(data), - }), + createSkill: (data: CreateSkillRequest) => http.post('/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('/resources/batch/toggle', { - method: 'POST', - body: JSON.stringify({ names, enable, kind }), - }), + http.post('/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(`/resources/${encodeURIComponent(skillName)}/files/${filepath}`), + http.get(`/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(`/collect/scan${qs ? '?' + qs : ''}`); + return http.get(`/collect/scan${qs ? '?' + qs : ''}`); }, collect: (opts: { skills: { name: string; targetName: string; kind?: string }[]; force?: boolean; - }) => - apiFetch('/collect', { - method: 'POST', - body: JSON.stringify(opts), - }), + }) => http.post('/collect', opts), }; diff --git a/ui/src/api/sync.ts b/ui/src/api/sync.ts index ce5c62392..02530892c 100644 --- a/ui/src/api/sync.ts +++ b/ui/src/api/sync.ts @@ -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('/sync', { - method: 'POST', - body: JSON.stringify(opts), - }), + http.post('/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: ( diff --git a/ui/src/api/system.ts b/ui/src/api/system.ts index eea49964b..19c589199 100644 --- a/ui/src/api/system.ts +++ b/ui/src/api/system.ts @@ -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(manual ? '/version?manual=true' : '/version'), + http.get(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((resolve, reject) => { @@ -36,5 +35,5 @@ export const systemApi = { ); signal?.addEventListener('abort', () => es.close()); }), - analyze: () => apiFetch('/analyze'), + analyze: () => http.get('/analyze'), }; diff --git a/ui/src/api/targets.ts b/ui/src/api/targets.ts index 4e2d3e195..09742a4ef 100644 --- a/ui/src/api/targets.ts +++ b/ui/src/api/targets.ts @@ -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('/projects'), - saveProject: (project: ProjectInput) => - apiFetch('/projects', { method: 'PUT', body: JSON.stringify(project) }), + listProjects: () => http.get('/projects'), + saveProject: (project: ProjectInput) => http.put('/projects', project), removeProject: (root: string, shared = false) => - apiFetch( + http.delete( `/projects?root=${encodeURIComponent(root)}${shared ? '&shared=true' : ''}`, - { method: 'DELETE' }, ), - convertProject: (root: string) => - apiFetch('/projects/convert', { - method: 'POST', - body: JSON.stringify({ root }), - }), + convertProject: (root: string) => http.post('/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(`/targets/${encodeURIComponent(name)}/skills-off-preview`), + http.get(`/targets/${encodeURIComponent(name)}/skills-off-preview`), }; diff --git a/ui/src/api/types/extras.ts b/ui/src/api/types/extras.ts index 04eef9d71..323c29067 100644 --- a/ui/src/api/types/extras.ts +++ b/ui/src/api/types/extras.ts @@ -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; diff --git a/ui/src/api/update.ts b/ui/src/api/update.ts index 5aa12905c..e957fe003 100644 --- a/ui/src/api/update.ts +++ b/ui/src/api/update.ts @@ -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, diff --git a/ui/src/components/UpdateDialog.tsx b/ui/src/components/UpdateDialog.tsx index df770f7c4..cd334d64f 100644 --- a/ui/src/components/UpdateDialog.tsx +++ b/ui/src/components/UpdateDialog.tsx @@ -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); diff --git a/ui/src/components/projects/ProjectSyncDialog.tsx b/ui/src/components/projects/ProjectSyncDialog.tsx index a9378e55b..5996cf43f 100644 --- a/ui/src/components/projects/ProjectSyncDialog.tsx +++ b/ui/src/components/projects/ProjectSyncDialog.tsx @@ -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 }, }); diff --git a/ui/src/components/resources/MoveDialog.tsx b/ui/src/components/resources/MoveDialog.tsx index 2218e48f6..49e4e8ea1 100644 --- a/ui/src/components/resources/MoveDialog.tsx +++ b/ui/src/components/resources/MoveDialog.tsx @@ -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(null); const [naming, setNaming] = useState(false); - const [running, setRunning] = useState(false); const [results, setResults] = useState(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); } }; diff --git a/ui/src/components/sync/syncView.test.ts b/ui/src/components/sync/syncView.test.ts index 490b1c699..0567bcbe7 100644 --- a/ui/src/components/sync/syncView.test.ts +++ b/ui/src/components/sync/syncView.test.ts @@ -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: [] }); diff --git a/ui/src/components/sync/syncView.ts b/ui/src/components/sync/syncView.ts index 58d07a2a8..d220d2037 100644 --- a/ui/src/components/sync/syncView.ts +++ b/ui/src/components/sync/syncView.ts @@ -369,12 +369,12 @@ export function pendingCount( hooks?: HookPlan | null, ): number { const parts = new Set(['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) diff --git a/ui/src/hooks/__tests__/useResourceToggle.test.tsx b/ui/src/hooks/__tests__/useResourceToggle.test.tsx new file mode 100644 index 000000000..a26c0d807 --- /dev/null +++ b/ui/src/hooks/__tests__/useResourceToggle.test.tsx @@ -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 }) => ( + {children} + ), + }); + 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]); +}); diff --git a/ui/src/hooks/useResourceMove.ts b/ui/src/hooks/useResourceMove.ts new file mode 100644 index 000000000..3a06d6526 --- /dev/null +++ b/ui/src/hooks/useResourceMove.ts @@ -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 }; +} diff --git a/ui/src/hooks/useResourceToggle.ts b/ui/src/hooks/useResourceToggle.ts new file mode 100644 index 000000000..e3a6aeabf --- /dev/null +++ b/ui/src/hooks/useResourceToggle.ts @@ -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>; + +// 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( + kind: Skill['kind'], + names: string[], + disabled: boolean, + request: () => Promise, + failedNames?: (result: T) => string[], + ) { + await client.cancelQueries({ queryKey, exact: true }); + const selected = new Set(names); + const previous = new Map(); + client.setQueryData( + 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) { + if (!failed.size) return; + client.setQueryData( + 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 }; +} diff --git a/ui/src/hooks/useSharedQueries.ts b/ui/src/hooks/useSharedQueries.ts index a88509a7a..6f81fbb91 100644 --- a/ui/src/hooks/useSharedQueries.ts +++ b/ui/src/hooks/useSharedQueries.ts @@ -28,7 +28,7 @@ export const useHooksQuery = (options?: Options>) => export const useSkillsQuery = (options?: Options>) => useQuery({ queryKey: queryKeys.skills.all, - queryFn: () => api.listSkills(), + queryFn: ({ signal }) => api.listSkills(undefined, signal), staleTime: staleTimes.skills, ...options, }); diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index fc5bae782..5904c20a1 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -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", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 8fa73e5e4..41470621f 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -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", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index 23bffbded..e0226a439 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -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", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index 7052f6953..8db3099a5 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -2020,6 +2020,7 @@ "sync.changes.one": "{count} تغییر", "sync.changes.other": "{count} تغییر", "sync.checking": "در حال بررسی تغییرات…", + "sync.migrateMcpSource": "انتقال تنظیمات منبع MCP", "sync.nothing": "چیزی برای همگام‌سازی نیست. همه هدف‌ها با منبع شما یکسان‌اند.", "sync.noTargets": "هنوز هدفی ندارید. برای شروع همگام‌سازی یکی اضافه کنید.", "sync.addTarget": "افزودن هدف", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index 030a7c645..88ab60a47 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -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", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index b28c63a78..5dbf7f38e 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -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", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 388100dfb..7fb6d4dd6 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -2020,6 +2020,7 @@ "sync.changes.one": "{count} 件の変更", "sync.changes.other": "{count} 件の変更", "sync.checking": "変更内容を確認中…", + "sync.migrateMcpSource": "MCP のソース設定を移行", "sync.nothing": "同期するものはありません。すべてのターゲットがソースと一致しています。", "sync.noTargets": "ターゲットがまだありません。追加すると同期できます。", "sync.addTarget": "ターゲットを追加", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index 620b2d3ad..7068fcb8f 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -2020,6 +2020,7 @@ "sync.changes.one": "변경 {count}개", "sync.changes.other": "변경 {count}개", "sync.checking": "바뀔 내용을 확인하는 중…", + "sync.migrateMcpSource": "MCP 소스 설정 마이그레이션", "sync.nothing": "동기화할 내용이 없습니다. 모든 대상이 소스와 같습니다.", "sync.noTargets": "아직 대상이 없습니다. 대상을 추가하면 동기화할 수 있습니다.", "sync.addTarget": "대상 추가", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index d91608c49..7035cbb19 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -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", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index e70a35960..ac66f82ea 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -2020,6 +2020,7 @@ "sync.changes.one": "{count} 项变更", "sync.changes.other": "{count} 项变更", "sync.checking": "正在检查会有哪些变更…", + "sync.migrateMcpSource": "迁移 MCP 来源设置", "sync.nothing": "没有需要同步的内容,所有目标都与来源一致。", "sync.noTargets": "还没有目标,添加一个即可开始同步。", "sync.addTarget": "添加目标", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 412a97db0..7fc76b3a4 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -2020,6 +2020,7 @@ "sync.changes.one": "{count} 項變更", "sync.changes.other": "{count} 項變更", "sync.checking": "正在檢查會有哪些變更…", + "sync.migrateMcpSource": "遷移 MCP 來源設定", "sync.nothing": "沒有需要同步的內容,所有目標都與來源一致。", "sync.noTargets": "還沒有目標,新增一個即可開始同步。", "sync.addTarget": "新增目標", diff --git a/ui/src/lib/optimisticTargets.test.ts b/ui/src/lib/optimisticTargets.test.ts new file mode 100644 index 000000000..7768a6d26 --- /dev/null +++ b/ui/src/lib/optimisticTargets.test.ts @@ -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]); +}); diff --git a/ui/src/lib/optimisticTargets.ts b/ui/src/lib/optimisticTargets.ts new file mode 100644 index 000000000..1abf9a336 --- /dev/null +++ b/ui/src/lib/optimisticTargets.ts @@ -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(key) + ?.resources.find((s) => s.kind === kind && s.flatName === name); + if (!previous) return; + const patchTargets = (targets: Skill['targets']) => + queryClient.setQueryData( + 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); +} diff --git a/ui/src/lib/upgradeWorkflow.test.ts b/ui/src/lib/upgradeWorkflow.test.ts new file mode 100644 index 000000000..c6a153534 --- /dev/null +++ b/ui/src/lib/upgradeWorkflow.test.ts @@ -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); + }, +); diff --git a/ui/src/lib/upgradeWorkflow.ts b/ui/src/lib/upgradeWorkflow.ts new file mode 100644 index 000000000..ae65ee89c --- /dev/null +++ b/ui/src/lib/upgradeWorkflow.ts @@ -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'; +} diff --git a/ui/src/pages/DoctorPage.tsx b/ui/src/pages/DoctorPage.tsx index 812bb1ea3..0da5c6fd7 100644 --- a/ui/src/pages/DoctorPage.tsx +++ b/ui/src/pages/DoctorPage.tsx @@ -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) { diff --git a/ui/src/pages/ResourcesPage.tsx b/ui/src/pages/ResourcesPage.tsx index ae7f2cdd1..edcd4643f 100644 --- a/ui/src/pages/ResourcesPage.tsx +++ b/ui/src/pages/ResourcesPage.tsx @@ -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(queryKeys.skills.all); - if (previous) - queryClient.setQueryData(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, + }) } > @@ -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)} diff --git a/ui/src/pages/SyncPage.test.tsx b/ui/src/pages/SyncPage.test.tsx index 1bfa9b1ca..31b94c76b 100644 --- a/ui/src/pages/SyncPage.test.tsx +++ b/ui/src/pages/SyncPage.test.tsx @@ -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( + + + + + + + + + , + ); + 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( diff --git a/ui/src/pages/SyncPage.tsx b/ui/src/pages/SyncPage.tsx index 7088bd5d7..81541f2ca 100644 --- a/ui/src/pages/SyncPage.tsx +++ b/ui/src/pages/SyncPage.tsx @@ -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() { )} - {parts.has('mcp') && plan?.blocked && ( + {config.mcpBlocked && (
{t('sync.mcpBlocked')} @@ -601,7 +585,7 @@ export default function SyncPage() {
)} - {parts.has('hooks') && hooksPlan?.blocked && ( + {config.hooksBlocked && (
{t('sync.hooksBlocked')} @@ -653,7 +637,7 @@ export default function SyncPage() { /> ))} - {!loading && !diff.error && groups.length > 0 && ( + {!loading && !diff.error && !previewEmpty && (

{t(plural('sync.pending', count), { count })}

@@ -689,7 +673,7 @@ export default function SyncPage() {
- ) : diffs.length === 0 && groups.length === 0 ? ( + ) : diffs.length === 0 && previewEmpty ? (
{t('sync.noTargets')} @@ -698,7 +682,10 @@ export default function SyncPage() {
) : ( <> - {groups.length === 0 && ( + {config.migrationOnly && ( +
{t('sync.migrateMcpSource')}
+ )} + {previewEmpty && (
{t('sync.nothing')} diff --git a/wiki/frontend.md b/wiki/frontend.md index fef2abc84..8f5762cd3 100644 --- a/wiki/frontend.md +++ b/wiki/frontend.md @@ -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, '')` | | 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.