build(ui): adopt Oxc formatting and type-aware linting (#956)

Format the dashboard with Oxfmt and use tsrs for project builds and Oxlint type analysis. Fix the initial typed findings and check formatting and typed lint in CI to keep new changes consistent.
This commit is contained in:
Willie
2026-11-18 22:37:24 +08:00
committed by GitHub
parent f8d768a256
commit 67639e54f8
404 changed files with 46462 additions and 12333 deletions
+1 -2
View File
@@ -23,8 +23,7 @@
"extensions": [
"golang.go",
"bradlc.vscode-tailwindcss",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
"oxc.oxc-vscode"
]
}
}
+22
View File
@@ -65,6 +65,28 @@ jobs:
env:
SKILLSHARE_TEST_BINARY: ${{ github.workspace }}/bin/skillshare
dashboard-check:
if: *not-release-duplicate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
- uses: pnpm/action-setup@v4
with:
version: 12.6.0
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: pnpm
cache-dependency-path: ui/pnpm-lock.yaml
- name: Check dashboard formatting and type-aware lint
working-directory: ui
run: |
pnpm install --frozen-lockfile
pnpm format:check
pnpm lint:typed
integration-test:
if: *not-release-duplicate
runs-on: ${{ matrix.os }}
+3 -3
View File
@@ -18,8 +18,8 @@ import sys
ROOT = Path(__file__).resolve().parents[2]
CSS_PATH = "ui/src/components.css"
LIGHT = ':root:not([data-theme="playful"])'
DARK = ':root:not([data-theme="playful"]).dark'
LIGHT = ":root:not([data-theme='playful'])"
DARK = LIGHT + ".dark"
# Every Clean color variable needs a usage note here, or the export fails.
COLOR_USAGE = {
@@ -80,7 +80,7 @@ SHADOW_USAGE = {
def block(css, selector):
match = re.search(r"^" + re.escape(selector) + r" \{", css, re.M)
match = re.search(r"^[ \t]*" + re.escape(selector) + r" \{", css, re.M)
if not match:
raise ValueError(f"{CSS_PATH}: no rule for {selector}")
return css[match.start():css.index("}", match.start())]
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"singleQuote": true,
"printWidth": 100,
"sortImports": false,
"ignorePatterns": ["dist/**", "public/**", "src/assets/**", "pnpm-lock.yaml"]
}
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "react", "oxc", "unicorn"],
"categories": {
"correctness": "error"
},
"rules": {
"react/rules-of-hooks": "error",
"react/exhaustive-deps": "warn",
"react/only-export-components": [
"warn",
{
"allowConstantExport": true
}
],
"typescript/no-explicit-any": "warn",
"react/preserve-manual-memoization": "warn",
"react/purity": "warn",
"react/refs": "warn",
"react/set-state-in-effect": "warn"
},
"ignorePatterns": ["dist/**", "public/**"]
}
+7 -71
View File
@@ -1,73 +1,9 @@
# React + TypeScript + Vite
# Dashboard development
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
From `ui/` inside the devcontainer:
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
- `pnpm lint` checks TypeScript and React code with Oxlint.
- `pnpm lint:typed` runs the same configuration with type information from tsrs. CI runs this check and `pnpm format:check` for the dashboard.
- `pnpm format` applies Oxfmt; `pnpm format:check` checks formatting without writing.
- `pnpm typecheck` checks project references with tsrs. `pnpm build` runs it before Vite.
- `pnpm test` runs the dashboard tests with Vitest.
-31
View File
@@ -1,31 +0,0 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'react-refresh/only-export-components': 'warn',
'react-hooks/preserve-manual-memoization': 'warn',
'react-hooks/purity': 'warn',
'react-hooks/refs': 'warn',
'react-hooks/set-state-in-effect': 'warn',
},
},
])
+13 -6
View File
@@ -14,19 +14,24 @@
<!-- Body text uses the system font. Kalam is only for Playful headings. -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&display=swap" rel="stylesheet" />
<link
href="https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&display=swap"
rel="stylesheet"
/>
<script>
// FOUC prevention: handle Clean theme + dark mode before first paint
// Default is Playful (already set on <html>); only remove for explicit Clean
// URL ?theme= param overrides localStorage (values: dark, light, playful, clean).
// ?mode= (dark, light) and ?style= (playful, clean) name one axis each and win over it.
(function() {
(function () {
var q = new URLSearchParams(location.search);
var get = function(key) { return (q.get(key) || '').toLowerCase(); };
[get('theme'), get('mode')].forEach(function(p) {
var get = function (key) {
return (q.get(key) || '').toLowerCase();
};
[get('theme'), get('mode')].forEach(function (p) {
if (p === 'dark' || p === 'light') localStorage.setItem('skillshare-theme-preference', p);
});
[get('theme'), get('style')].forEach(function(p) {
[get('theme'), get('style')].forEach(function (p) {
if (p === 'playful' || p === 'clean') localStorage.setItem('skillshare-style', p);
});
var style = localStorage.getItem('skillshare-style');
@@ -34,7 +39,9 @@
if (style === 'clean') {
document.documentElement.removeAttribute('data-theme');
}
var dark = pref === 'dark' || (pref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
var dark =
pref === 'dark' ||
(pref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
if (dark) document.documentElement.classList.add('dark');
})();
</script>
+10 -10
View File
@@ -1,12 +1,16 @@
{
"name": "ui",
"private": true,
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"build": "pnpm typecheck && vite build",
"typecheck": "tsrs -b",
"lint": "oxlint .",
"lint:typed": "oxlint --type-aware .",
"format": "oxfmt --write",
"format:check": "oxfmt --check",
"preview": "vite preview",
"test": "vitest run"
},
@@ -39,7 +43,6 @@
"yaml": "^2.8.2"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@tanstack/react-query-devtools": "^5.91.3",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
@@ -48,13 +51,10 @@
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"jsdom": "^28.1.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.70.0",
"oxfmt": "^0.79.0",
"oxlint": "^1.94.0",
"tsrs": "0.25.0-ts7.1.0-beta",
"vite": "^8.3.1",
"vitest": "^4.1.0"
}
+535 -1170
View File
File diff suppressed because it is too large Load Diff
+216 -28
View File
@@ -1,5 +1,14 @@
import { lazy, Suspense } from 'react';
import { createBrowserRouter, RouterProvider, Routes, Route, Navigate, useRouteError, useParams, useSearchParams } from 'react-router-dom';
import {
createBrowserRouter,
RouterProvider,
Routes,
Route,
Navigate,
useRouteError,
useParams,
useSearchParams,
} from 'react-router-dom';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { queryClient } from './lib/queryClient';
@@ -46,7 +55,8 @@ function Lazy({ children }: { children: React.ReactNode }) {
function LegacyResourceRedirect() {
const { name } = useParams();
const [params] = useSearchParams();
const base = params.get('kind') === 'agent' || params.get('tab') === 'agents' ? '/agents' : '/skills';
const base =
params.get('kind') === 'agent' || params.get('tab') === 'agents' ? '/agents' : '/skills';
return <Navigate to={name ? `${base}/${encodeURIComponent(name)}` : base} replace />;
}
@@ -63,7 +73,9 @@ function LegacyTargetRedirect() {
const target = name ?? params.get('target');
if (!target) return <Navigate to="/targets" replace />;
const agents = params.get('kind') === 'agent' || params.get('scope') === 'agent';
return <Navigate to={`/targets/${encodeURIComponent(target)}${agents ? '?tab=agents' : ''}`} replace />;
return (
<Navigate to={`/targets/${encodeURIComponent(target)}${agents ? '?tab=agents' : ''}`} replace />
);
}
function AppRoutes() {
@@ -77,41 +89,202 @@ function AppRoutes() {
<Routes>
<Route element={<Layout />}>
<Route index element={<DashboardPage />} />
<Route path="skills" element={<Lazy><ResourcesPage key="skill" kind="skill" /></Lazy>} />
<Route path="hubs" element={<Lazy><HubPage /></Lazy>} />
<Route path="skills/new" element={<Lazy><NewSkillPage /></Lazy>} />
<Route path="skills/:name" element={<Lazy><ResourceDetailPage /></Lazy>} />
<Route path="agents" element={<Lazy><ResourcesPage key="agent" kind="agent" /></Lazy>} />
<Route path="agents/:name" element={<Lazy><ResourceDetailPage /></Lazy>} />
<Route
path="skills"
element={
<Lazy>
<ResourcesPage key="skill" kind="skill" />
</Lazy>
}
/>
<Route
path="hubs"
element={
<Lazy>
<HubPage />
</Lazy>
}
/>
<Route
path="skills/new"
element={
<Lazy>
<NewSkillPage />
</Lazy>
}
/>
<Route
path="skills/:name"
element={
<Lazy>
<ResourceDetailPage />
</Lazy>
}
/>
<Route
path="agents"
element={
<Lazy>
<ResourcesPage key="agent" kind="agent" />
</Lazy>
}
/>
<Route
path="agents/:name"
element={
<Lazy>
<ResourceDetailPage />
</Lazy>
}
/>
<Route path="resources" element={<LegacyResourceRedirect />} />
<Route path="resources/new" element={<Navigate to="/skills/new" replace />} />
<Route path="resources/:name" element={<LegacyResourceRedirect />} />
<Route path="uninstall" element={<Navigate to="/skills" replace />} />
<Route path="targets" element={<Lazy><TargetsPage /></Lazy>} />
<Route path="targets/:name" element={<Lazy><TargetDetailPage /></Lazy>} />
<Route
path="targets"
element={
<Lazy>
<TargetsPage />
</Lazy>
}
/>
<Route
path="targets/:name"
element={
<Lazy>
<TargetDetailPage />
</Lazy>
}
/>
<Route path="targets/:name/filters" element={<LegacyTargetRedirect />} />
<Route path="extras" element={<Lazy><ExtrasPage /></Lazy>} />
<Route
path="extras"
element={
<Lazy>
<ExtrasPage />
</Lazy>
}
/>
<Route path="extras/instructions/:name" element={<LegacySharedInstructionRedirect />} />
<Route path="plugins" element={<Lazy><PluginsPage /></Lazy>} />
<Route path="projects" element={<Lazy><ProjectsPage /></Lazy>} />
<Route path="projects/:root" element={<Lazy><ProjectDetailPage /></Lazy>} />
<Route path="mcp" element={<Lazy><MCPPage /></Lazy>} />
<Route path="hooks" element={<Lazy><HooksPage /></Lazy>} />
<Route path="sync" element={<Lazy><SyncPage /></Lazy>} />
<Route
path="plugins"
element={
<Lazy>
<PluginsPage />
</Lazy>
}
/>
<Route
path="projects"
element={
<Lazy>
<ProjectsPage />
</Lazy>
}
/>
<Route
path="projects/:root"
element={
<Lazy>
<ProjectDetailPage />
</Lazy>
}
/>
<Route
path="mcp"
element={
<Lazy>
<MCPPage />
</Lazy>
}
/>
<Route
path="hooks"
element={
<Lazy>
<HooksPage />
</Lazy>
}
/>
<Route
path="sync"
element={
<Lazy>
<SyncPage />
</Lazy>
}
/>
<Route path="collect" element={<LegacyTargetRedirect />} />
<Route path="backup" element={<Lazy><BackupPage /></Lazy>} />
<Route
path="backup"
element={
<Lazy>
<BackupPage />
</Lazy>
}
/>
<Route path="trash" element={<Navigate to="/skills?tab=trash" replace />} />
<Route path="git" element={<Lazy><GitSyncPage /></Lazy>} />
<Route
path="git"
element={
<Lazy>
<GitSyncPage />
</Lazy>
}
/>
<Route path="search" element={<Navigate to="/skills?install=search" replace />} />
<Route path="install" element={<Navigate to="/skills?install=url" replace />} />
<Route path="update" element={<Navigate to="/skills?tab=updates" replace />} />
<Route path="audit" element={<Lazy><AuditPage /></Lazy>} />
<Route path="audit/rules" element={<Lazy><AuditRulesPage /></Lazy>} />
<Route
path="audit"
element={
<Lazy>
<AuditPage />
</Lazy>
}
/>
<Route
path="audit/rules"
element={
<Lazy>
<AuditRulesPage />
</Lazy>
}
/>
<Route path="analyze" element={<Navigate to="/skills?tab=analyze" replace />} />
<Route path="log" element={<Lazy><LogPage /></Lazy>} />
<Route path="settings" element={<Lazy><SettingsPage /></Lazy>} />
<Route path="config" element={<Lazy><ConfigPage /></Lazy>} />
<Route path="doctor" element={<Lazy><DoctorPage /></Lazy>} />
<Route
path="log"
element={
<Lazy>
<LogPage />
</Lazy>
}
/>
<Route
path="settings"
element={
<Lazy>
<SettingsPage />
</Lazy>
}
/>
<Route
path="config"
element={
<Lazy>
<ConfigPage />
</Lazy>
}
/>
<Route
path="doctor"
element={
<Lazy>
<DoctorPage />
</Lazy>
}
/>
</Route>
</Routes>
</TourProvider>
@@ -120,9 +293,24 @@ function AppRoutes() {
}
// Forward router failures to the same fallback as render failures.
function RouteError(): never { throw useRouteError(); }
function RouteError(): never {
throw useRouteError();
}
const router = createBrowserRouter([{ path: "*", element: <AppRoutes />, errorElement: <ErrorBoundary><RouteError /></ErrorBoundary> }], { basename: BASE_PATH });
const router = createBrowserRouter(
[
{
path: '*',
element: <AppRoutes />,
errorElement: (
<ErrorBoundary>
<RouteError />
</ErrorBoundary>
),
},
],
{ basename: BASE_PATH },
);
export default function App() {
return (
+21 -9
View File
@@ -1,11 +1,18 @@
import { apiFetch, BASE, createSSEStream, kindQuery } from './http';
import type { AuditAllResponse, AuditPolicy, AuditRulesResponse, AuditSkillResponse, CompiledRulesResponse } from './types/audit';
import type {
AuditAllResponse,
AuditPolicy,
AuditRulesResponse,
AuditSkillResponse,
CompiledRulesResponse,
} from './types/audit';
export const auditApi = {
auditAll: (kind?: 'skills' | 'agents') =>
apiFetch<AuditAllResponse>(`/audit${kindQuery(kind)}`),
auditAll: (kind?: 'skills' | 'agents') => apiFetch<AuditAllResponse>(`/audit${kindQuery(kind)}`),
auditSkill: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<AuditSkillResponse>(`/audit/${encodeURIComponent(name)}${kindQuery(kind === 'agent' ? kind : undefined)}`),
apiFetch<AuditSkillResponse>(
`/audit/${encodeURIComponent(name)}${kindQuery(kind === 'agent' ? kind : undefined)}`,
),
auditAllStream: (
onStart: (total: number) => void,
onProgress: (scanned: number) => void,
@@ -13,11 +20,16 @@ export const auditApi = {
onError: (err: Error) => void,
kind?: 'skills' | 'agents',
): EventSource =>
createSSEStream(BASE + `/audit/stream${kindQuery(kind)}`, {
start: (d) => onStart(d.total),
progress: (d) => onProgress(d.scanned),
done: onDone,
}, onError, 'Audit stream failed'),
createSSEStream(
BASE + `/audit/stream${kindQuery(kind)}`,
{
start: (d) => onStart(d.total),
progress: (d) => onProgress(d.scanned),
done: onDone,
},
onError,
'Audit stream failed',
),
getAuditRules: () => apiFetch<AuditRulesResponse>('/audit/rules'),
putAuditRules: (raw: string) =>
apiFetch<{ success: boolean }>('/audit/rules', {
+22 -15
View File
@@ -1,5 +1,11 @@
import { apiFetch, kindQuery } from './http';
import type { BackupListResponse, FileBackup, FileBackupVersions, RestoreValidateResponse, TrashListResponse } from './types/backups';
import type {
BackupListResponse,
FileBackup,
FileBackupVersions,
RestoreValidateResponse,
TrashListResponse,
} from './types/backups';
export const backupsApi = {
listBackups: () => apiFetch<BackupListResponse>('/backups'),
@@ -23,13 +29,17 @@ export const backupsApi = {
deleteAllBackups: () =>
apiFetch<{ success: boolean; removed: number }>('/backups', { method: 'DELETE' }),
deleteBackup: (timestamp: string) =>
apiFetch<{ success: boolean }>(`/backups/${encodeURIComponent(timestamp)}`, { method: 'DELETE' }),
apiFetch<{ success: boolean }>(`/backups/${encodeURIComponent(timestamp)}`, {
method: 'DELETE',
}),
// File history: earlier versions of single files skillshare rewrote
listFileBackups: () => apiFetch<{ files: FileBackup[] }>('/file-backups'),
getFileBackupVersions: (path: string) =>
apiFetch<FileBackupVersions>(`/file-backups/versions?path=${encodeURIComponent(path)}`),
getFileBackupVersion: (path: string, id: string) =>
apiFetch<{ content: string; current: string }>(`/file-backups/version?path=${encodeURIComponent(path)}&id=${encodeURIComponent(id)}`),
apiFetch<{ 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',
@@ -37,18 +47,15 @@ export const backupsApi = {
}),
listTrash: () => apiFetch<TrashListResponse>('/trash'),
restoreTrash: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ success: boolean }>(
`/trash/${encodeURIComponent(name)}/restore${kindQuery(kind)}`,
{ method: 'POST' },
),
apiFetch<{ success: boolean }>(`/trash/${encodeURIComponent(name)}/restore${kindQuery(kind)}`, {
method: 'POST',
}),
deleteTrash: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ success: boolean }>(
`/trash/${encodeURIComponent(name)}${kindQuery(kind)}`,
{ method: 'DELETE' },
),
apiFetch<{ success: boolean }>(`/trash/${encodeURIComponent(name)}${kindQuery(kind)}`, {
method: 'DELETE',
}),
emptyTrash: (kind: 'skill' | 'agent' | 'all' = 'all') =>
apiFetch<{ success: boolean; removed: number }>(
`/trash/empty${kindQuery(kind)}`,
{ method: 'POST' },
),
apiFetch<{ success: boolean; removed: number }>(`/trash/empty${kindQuery(kind)}`, {
method: 'POST',
}),
};
+24 -12
View File
@@ -3,13 +3,19 @@ import { parseApiErrorPayload } from './client';
describe('parseApiErrorPayload', () => {
it('parses the new structured error format', () => {
expect(parseApiErrorPayload({
error: {
code: 'target.not_found',
message: 'target not found: claude',
params: { target: 'claude' },
},
}, 404, 'Not Found')).toEqual({
expect(
parseApiErrorPayload(
{
error: {
code: 'target.not_found',
message: 'target not found: claude',
params: { target: 'claude' },
},
},
404,
'Not Found',
),
).toEqual({
code: 'target.not_found',
message: 'target not found: claude',
params: { target: 'claude' },
@@ -17,11 +23,17 @@ describe('parseApiErrorPayload', () => {
});
it('parses legacy string errors with sidecar codes', () => {
expect(parseApiErrorPayload({
error: 'target not found: claude',
error_code: 'target.not_found',
error_params: { target: 'claude' },
}, 404, 'Not Found')).toEqual({
expect(
parseApiErrorPayload(
{
error: 'target not found: claude',
error_code: 'target.not_found',
error_params: { target: 'claude' },
},
404,
'Not Found',
),
).toEqual({
code: 'target.not_found',
message: 'target not found: claude',
params: { target: 'claude' },
+4 -8
View File
@@ -46,12 +46,8 @@ export const api = {
...gitApi,
// Aliases go through `api` so tests that replace it still intercept them.
getSkill: (name: string, kind?: 'skill' | 'agent') =>
api.getResource(name, kind),
deleteSkill: (name: string, kind?: 'skill' | 'agent') =>
api.deleteResource(name, kind),
disableSkill: (name: string, kind?: 'skill' | 'agent') =>
api.disableResource(name, kind),
enableSkill: (name: string, kind?: 'skill' | 'agent') =>
api.enableResource(name, kind),
getSkill: (name: string, kind?: 'skill' | 'agent') => api.getResource(name, kind),
deleteSkill: (name: string, kind?: 'skill' | 'agent') => api.deleteResource(name, kind),
disableSkill: (name: string, kind?: 'skill' | 'agent') => api.disableResource(name, kind),
enableSkill: (name: string, kind?: 'skill' | 'agent') => api.enableResource(name, kind),
};
+13 -2
View File
@@ -1,10 +1,21 @@
import { apiFetch } from './http';
import type { AgentignoreResponse, AvailableTarget, ConfigSaveResponse, SkillignoreResponse } from './types/config';
import type {
AgentignoreResponse,
AvailableTarget,
ConfigSaveResponse,
SkillignoreResponse,
} from './types/config';
export const configApi = {
getConfig: () => apiFetch<{ config: unknown; raw: string }>('/config'),
/** Settings the Settings page owns; the rest of config.yaml stays untouched. */
patchConfig: (body: { mode?: string; logMaxEntries?: number; backupMaxCount?: number; backupMaxSizeMB?: number; autoUpdateCheck?: boolean }) =>
patchConfig: (body: {
mode?: string;
logMaxEntries?: number;
backupMaxCount?: number;
backupMaxSizeMB?: number;
autoUpdateCheck?: boolean;
}) =>
apiFetch<{ mode: string; logMaxEntries: number | null }>('/config', {
method: 'PATCH',
body: JSON.stringify(body),
+50 -12
View File
@@ -1,16 +1,31 @@
import { apiFetch } from './http';
import type { ExtensionInfo, Extra, ExtraDiffResult, ExtraEditResult, ExtraFilterEntry, ExtrasSyncResult } from './types/extras';
import type {
ExtensionInfo,
Extra,
ExtraDiffResult,
ExtraEditResult,
ExtraFilterEntry,
ExtrasSyncResult,
} from './types/extras';
export const extrasApi = {
listExtras: () => apiFetch<{ extras: Extra[] }>('/extras'),
diffExtras: (name?: string) =>
apiFetch<{ extras: ExtraDiffResult[] }>(`/extras/diff${name ? '?name=' + encodeURIComponent(name) : ''}`),
apiFetch<{ 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 }>;
targets: Array<{
path: string;
mode: string;
flatten?: boolean;
extension?: string;
as?: string;
}>;
}) =>
apiFetch<{ success: boolean }>('/extras', {
method: 'POST',
@@ -31,14 +46,19 @@ export const extrasApi = {
method: 'POST',
body: JSON.stringify({ name }),
}),
openExtensionsDir: () =>
apiFetch<{ path: string }>('/extensions/open', { method: 'POST' }),
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)
setExtraMode: (name: string, target: string, mode: string, flatten?: boolean, extension?: string) =>
setExtraMode: (
name: string,
target: string,
mode: string,
flatten?: boolean,
extension?: string,
) =>
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/mode`, {
method: 'PATCH',
body: JSON.stringify({
@@ -48,18 +68,36 @@ export const extrasApi = {
...(extension !== undefined && { extension }),
}),
}),
addExtraTarget: (name: string, target: { path: string; mode?: string; flatten?: boolean; as?: string }) =>
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),
}),
previewExtraFilter: (name: string, include: string[], exclude: string[]) =>
apiFetch<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(`/extras/${encodeURIComponent(name)}/preview`, {
method: 'POST',
body: JSON.stringify({ include, exclude }),
}),
apiFetch<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(
`/extras/${encodeURIComponent(name)}/preview`,
{
method: 'POST',
body: JSON.stringify({ 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[] }) =>
editExtraTarget: (
name: string,
path: string,
target: {
path: string;
mode: string;
flatten: boolean;
extension: string;
as: string;
include: string[];
exclude: string[];
},
) =>
apiFetch<ExtraEditResult>(`/extras/${encodeURIComponent(name)}/targets`, {
method: 'PUT',
body: JSON.stringify({ path, target }),
+14 -2
View File
@@ -1,5 +1,12 @@
import { apiFetch } from './http';
import type { GitBranches, GitCheckoutResponse, GitPullResolution, GitStatus, PullResponse, PushResponse } from './types/git';
import type {
GitBranches,
GitCheckoutResponse,
GitPullResolution,
GitStatus,
PullResponse,
PushResponse,
} from './types/git';
export const gitApi = {
gitStatus: () => apiFetch<GitStatus>('/git/status'),
@@ -36,7 +43,12 @@ export const gitApi = {
body: JSON.stringify(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 }) =>
pull: (opts?: {
dryRun?: boolean;
force?: boolean;
resolution?: GitPullResolution;
alwaysSync?: boolean;
}) =>
apiFetch<PullResponse>('/pull', {
method: 'POST',
body: JSON.stringify(opts ?? {}),
+173 -35
View File
@@ -1,14 +1,28 @@
import { apiFetch } from './client';
/** The Agents hooks can be managed for, in display order. */
export const hookAgents = ['claude', 'codex', 'gemini', 'copilot', 'cursor', 'droid', 'qwen', 'antigravity', 'pi', 'omp', 'amp', 'opencode', 'git'] as const;
export const hookAgents = [
'claude',
'codex',
'gemini',
'copilot',
'cursor',
'droid',
'qwen',
'antigravity',
'pi',
'omp',
'amp',
'opencode',
'git',
] as const;
export type HookAgent = (typeof hookAgents)[number];
/** Agents whose hooks are one standalone native TypeScript/JavaScript file, not a command event map. */
export const hookCodeAgents: readonly string[] = ['pi', 'omp', 'amp', 'opencode'];
/** One Agent's part of a hook. Command Agents fill `events`, code Agents fill `code`. */
export interface HookBinding {
commands?: Record<string, { events: string[]; command: string; parallel?: boolean }>;
commands?: Record<string, { events: string[]; command: string; parallel?: boolean }>;
/** The Agent's own event map, passed through as written. */
events?: Record<string, unknown>;
code?: string;
@@ -41,35 +55,118 @@ export interface HookMutation {
}
/** `root`: the hooks.projects root a native file belongs to; left out for the global files. */
/** Events a change adds to, updates in, or removes from a shared hooks file. */
export interface HookEventChanges { added?: string[]; updated?: string[]; removed?: string[] }
export interface HookChange { target: string; path: string; name: string; root?: string; action: string; message?: string; inactiveReason?: string; events?: HookEventChanges }
export interface HookEventChanges {
added?: string[];
updated?: string[];
removed?: string[];
}
export interface HookChange {
target: string;
path: string;
name: string;
root?: string;
action: string;
message?: string;
inactiveReason?: string;
events?: HookEventChanges;
}
/** `fingerprint` covers the hook content the plan proposes, which `changes` (no contents) cannot show: equal shape, different command, different fingerprint. */
/** `warnings`: advisory only, such as event names an Agent does not document; they never block. */
export interface HookPlan { revision: string; fingerprint: string; sourcePath: string; blocked: boolean; changes: HookChange[]; warnings?: string[] }
export interface HookCatalogEvent { name: string; description: string; matcher: boolean }
export interface HookPlan {
revision: string;
fingerprint: string;
sourcePath: string;
blocked: boolean;
changes: HookChange[];
warnings?: string[];
}
export interface HookCatalogEvent {
name: string;
description: string;
matcher: boolean;
}
/** A command Agent's documented events; code Agents are not listed. */
export interface HookAgentCatalog { events: HookCatalogEvent[]; timeoutUnit: 'seconds' | 'milliseconds' | '' }
export interface HookAgentCatalog {
events: HookCatalogEvent[];
timeoutUnit: 'seconds' | 'milliseconds' | '';
}
/** A native file the preview would change: full text now (`""` when missing) and exactly what sync writes (`""` when removed). */
export interface HookFileDiff { target: string; path: string; root?: string; before: string; after: string }
export interface HookFileDiff {
target: string;
path: string;
root?: string;
before: string;
after: string;
}
/** Only POST /hooks/preview carries `files`. */
export type HookPreview = HookPlan & { files?: HookFileDiff[] };
export interface HookResult { plan?: HookPlan; applied: string[]; backupIds: string[] }
export interface HookTargetDef { name: string; agent?: string; kind: string; note?: string }
export interface HookResult {
plan?: HookPlan;
applied: string[];
backupIds: string[];
}
export interface HookTargetDef {
name: string;
agent?: string;
kind: string;
note?: string;
}
/** Hooks in an Agent's native configuration that Skillshare does not manage. */
export interface HookUnmanaged { target: string; path: string; names: string[]; project?: string }
export interface HookBackup { id: string; target: string; path: string; root?: string; time?: string }
export interface HookUnmanaged {
target: string;
path: string;
names: string[];
project?: string;
}
export interface HookBackup {
id: string;
target: string;
path: string;
root?: string;
time?: string;
}
/** `editable`: the hook can be changed or removed in its target file without importing it. `source`: the Antigravity block or Copilot file it was read from. */
export interface HookCandidate { name: string; entry: HookEntry; problems: string[]; warnings: string[]; editable?: boolean; source?: string }
export interface HookCandidate {
name: string;
entry: HookEntry;
problems: string[];
warnings: string[];
editable?: boolean;
source?: string;
}
/** A change to hooks Skillshare does not manage: `before` as the import listed them, `after` their replacement (left out removes them). `source` is the candidate's. */
export interface HookNativeEdit { target: string; root?: string; source?: string; before: Record<string, unknown>; after?: Record<string, unknown> }
export interface HookImportRequest { from: string; content?: string; name?: string; /** Reads the Agent's file under this hooks.projects root. */ root?: string }
export interface HookNativeEdit {
target: string;
root?: string;
source?: string;
before: Record<string, unknown>;
after?: Record<string, unknown>;
}
export interface HookImportRequest {
from: string;
content?: string;
name?: string;
/** Reads the Agent's file under this hooks.projects root. */ root?: string;
}
/** One root under hooks.projects: hooks that live in that folder's own native files. */
export interface HookProject { entries?: Record<string, HookEntry> }
export interface HookRendered { target: string; path?: string; content?: string; error?: string }
export interface HookProject {
entries?: Record<string, HookEntry>;
}
export interface HookRendered {
target: string;
path?: string;
content?: string;
error?: string;
}
export interface HookInventory {
git?: HookGitInfo;
projectGit?: Record<string, HookGitInfo>;
source: { path: string; configPath: string; entries: Record<string, HookEntry>; projects?: Record<string, HookProject> };
git?: HookGitInfo;
projectGit?: Record<string, HookGitInfo>;
source: {
path: string;
configPath: string;
entries: Record<string, HookEntry>;
projects?: Record<string, HookProject>;
};
/** Project roots that also have their own .skillshare/config.yaml. */
projectConfigs?: string[];
targets: HookTargetDef[];
@@ -83,43 +180,84 @@ export interface HookInventory {
}
export interface HookGitInfo {
version: string; configHooks: boolean; parallel: boolean; hooksFile: string;
include: { target: string; resolved: string; present: boolean; owned: boolean; writable: boolean; lines: string; conditional?: boolean; active?: boolean };
hooksPath: { value: string; origin: string }; reason?: string;
version: string;
configHooks: boolean;
parallel: boolean;
hooksFile: string;
include: {
target: string;
resolved: string;
present: boolean;
owned: boolean;
writable: boolean;
lines: string;
conditional?: boolean;
active?: boolean;
};
hooksPath: { value: string; origin: string };
reason?: string;
}
/** One Codex hook Skillshare owns. `needed`: not trusted yet or its command changed; `unchanged`: already trusted; `trusted`: recorded by this call. */
export interface CodexTrustHook { target: string; entry: string; key: string; command?: string; action: 'needed' | 'unchanged' | 'trusted'; disabled?: boolean }
export interface CodexTrustPlan { hooks: CodexTrustHook[]; revision: string; /** Homes Codex could not list; their hooks are left out. */ failed?: { target: string; error: string }[] }
export interface CodexTrustHook {
target: string;
entry: string;
key: string;
command?: string;
action: 'needed' | 'unchanged' | 'trusted';
disabled?: boolean;
}
export interface CodexTrustPlan {
hooks: CodexTrustHook[];
revision: string;
/** Homes Codex could not list; their hooks are left out. */ failed?: {
target: string;
error: string;
}[];
}
const post = <T,>(path: string, body: unknown) => apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
const post = <T>(path: string, body: unknown) =>
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
export const hooksApi = {
list: () => apiFetch<HookInventory>('/hooks'),
catalog: () => apiFetch<Record<string, HookAgentCatalog>>('/hooks/catalog'),
/** An empty mutation previews synchronizing the current source. */
preview: (mutation: HookMutation = {}) => post<HookPreview>('/hooks/preview', { mutation }),
configure: (mutation: HookMutation, revision: string, sync: boolean) => post<HookResult>('/hooks', { mutation, revision, sync }),
configure: (mutation: HookMutation, revision: string, sync: boolean) =>
post<HookResult>('/hooks', { mutation, revision, sync }),
/** Save to the source only. The server refuses a write it has not previewed; the revision also catches concurrent edits. */
save: async (mutation: HookMutation) =>
post<HookResult>('/hooks', { mutation, revision: (await post<HookPlan>('/hooks/preview', { mutation })).revision, sync: false }),
post<HookResult>('/hooks', {
mutation,
revision: (await post<HookPlan>('/hooks/preview', { mutation })).revision,
sync: false,
}),
/** Each Agent's native contribution of one hook, as sync would write it: its own file(s) and scripts only, never the shared settings. Writes nothing. */
render: (mutation: HookMutation) => post<{ rendered: HookRendered[] }>('/hooks/render', { mutation }),
render: (mutation: HookMutation) =>
post<{ rendered: HookRendered[] }>('/hooks/render', { mutation }),
/** Apply only the changes of one hooks.projects root; the global scope and other projects stay pending. */
syncProject: (root: string, revision: string) => post<HookResult>('/hooks', { mutation: {}, revision, sync: true, root }),
syncProject: (root: string, revision: string) =>
post<HookResult>('/hooks', { mutation: {}, revision, sync: true, root }),
/** Reads native configuration or code, or the pasted `content`; nothing is executed. */
import: async (body: HookImportRequest) => {
const res = await post<{ candidates: HookCandidate[] } | HookCandidate[]>('/hooks/import', body);
return Array.isArray(res) ? res : res.candidates ?? [];
const res = await post<{ candidates: HookCandidate[] } | HookCandidate[]>(
'/hooks/import',
body,
);
return Array.isArray(res) ? res : (res.candidates ?? []);
},
/** What editing or removing unmanaged hooks would write to their target files. Writes nothing. */
previewNative: (edits: HookNativeEdit[]) => post<HookPreview>('/hooks/native/preview', { edits }),
/** Writes previewed edits, with a backup per file. The hooks stay unmanaged. */
applyNative: (edits: HookNativeEdit[], revision: string) => post<HookResult>('/hooks/native', { edits, revision }),
applyNative: (edits: HookNativeEdit[], revision: string) =>
post<HookResult>('/hooks/native', { edits, revision }),
/** Starts a Codex process to list the hooks, so call it only when the user asks. Global scope only. */
previewCodexTrust: () => post<CodexTrustPlan>('/hooks/codex-trust/preview', {}),
/** Records trust for the previewed hooks. Refused (409) when they changed since the preview. */
trustCodex: (revision: string) => post<CodexTrustPlan>('/hooks/codex-trust', { revision }),
previewRestore: (backupId: string) => post<HookPlan>('/hooks/restore', { backupId, preview: true }),
restore: (backupId: string, revision: string) => post<HookResult>('/hooks/restore', { backupId, revision }),
previewRestore: (backupId: string) =>
post<HookPlan>('/hooks/restore', { backupId, preview: true }),
restore: (backupId: string, revision: string) =>
post<HookResult>('/hooks/restore', { backupId, revision }),
};
+35 -19
View File
@@ -45,28 +45,36 @@ function defaultErrorCode(status: number): string {
}
}
export function parseApiErrorPayload(data: any, status: number, statusText: string): ParsedApiError {
export function parseApiErrorPayload(
data: any,
status: number,
statusText: string,
): ParsedApiError {
const rawError = data?.error;
if (rawError && typeof rawError === 'object') {
const code = typeof rawError.code === 'string' ? rawError.code : defaultErrorCode(status);
const message = typeof rawError.message === 'string' ? rawError.message : statusText || 'Request failed';
const params = rawError.params && typeof rawError.params === 'object'
? rawError.params as Record<string, unknown>
: undefined;
const message =
typeof rawError.message === 'string' ? rawError.message : statusText || 'Request failed';
const params =
rawError.params && typeof rawError.params === 'object'
? (rawError.params as Record<string, unknown>)
: undefined;
return { code, message, params };
}
const message = typeof rawError === 'string' ? rawError : statusText || 'Request failed';
const code = typeof data?.error_code === 'string'
? data.error_code
: typeof data?.code === 'string'
? data.code
: defaultErrorCode(status);
const params = data?.error_params && typeof data.error_params === 'object'
? data.error_params as Record<string, unknown>
: data?.params && typeof data.params === 'object'
? data.params as Record<string, unknown>
: undefined;
const code =
typeof data?.error_code === 'string'
? data.error_code
: typeof data?.code === 'string'
? data.code
: defaultErrorCode(status);
const params =
data?.error_params && typeof data.error_params === 'object'
? (data.error_params as Record<string, unknown>)
: data?.params && typeof data.params === 'object'
? (data.params as Record<string, unknown>)
: undefined;
return { code, message, params };
}
@@ -89,9 +97,13 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
}
const text = await res.text();
if (!text) {
throw new ApiError(res.status || 502, 'Empty response from server (request may have timed out)', {
code: 'empty_response',
});
throw new ApiError(
res.status || 502,
'Empty response from server (request may have timed out)',
{
code: 'empty_response',
},
);
}
let data: any;
try {
@@ -145,7 +157,11 @@ export function createSSEStream(
const data = (e as MessageEvent).data;
let reason: unknown;
if (typeof data === 'string') {
try { reason = JSON.parse(data)?.error; } catch { /* not JSON: use the fallback message */ }
try {
reason = JSON.parse(data)?.error;
} catch {
/* not JSON: use the fallback message */
}
}
onError(new Error(typeof reason === 'string' && reason ? reason : errorMessage));
});
+3 -2
View File
@@ -3,7 +3,8 @@ import { hubAddCommand } from './hubDrafts';
describe('Hub sharing command', () => {
it('quotes shell metacharacters as data', () => {
expect(hubAddCommand('https://host/hub.json', "team's $(touch /tmp/no)"))
.toBe(`skillshare hub add 'https://host/hub.json' --label 'team'"'"'s $(touch /tmp/no)'`);
expect(hubAddCommand('https://host/hub.json', "team's $(touch /tmp/no)")).toBe(
`skillshare hub add 'https://host/hub.json' --label 'team'"'"'s $(touch /tmp/no)'`,
);
});
});
+26 -6
View File
@@ -2,7 +2,14 @@ import { apiFetch } from './client';
export interface HubEntry {
id: string;
data: { name?: string; description?: string; source?: string; skill?: string; tags?: string[]; [key: string]: unknown };
data: {
name?: string;
description?: string;
source?: string;
skill?: string;
tags?: string[];
[key: string]: unknown;
};
}
export interface HubDraft {
id: string;
@@ -13,7 +20,10 @@ export interface HubDraft {
entries: HubEntry[];
fields: Record<string, unknown>;
}
export interface HubProblem { entryId: string; code: string }
export interface HubProblem {
entryId: string;
code: string;
}
export interface DraftResponse {
draft: HubDraft;
problems: HubProblem[];
@@ -36,17 +46,27 @@ export const hubDrafts = {
get: (id: string) => apiFetch<DraftResponse>(`${root}/${encodeURIComponent(id)}`),
candidates: () => apiFetch<HubEntry[]>(`${root}/candidates`),
create: (draft: Partial<HubDraft>) => apiFetch<DraftResponse>(root, json('POST', draft)),
save: (draft: HubDraft) => apiFetch<DraftResponse>(`${root}/${encodeURIComponent(draft.id)}`, json('PUT', draft)),
remove: (draft: HubDraft) => apiFetch(`${root}/${encodeURIComponent(draft.id)}?revision=${encodeURIComponent(draft.revision)}`, { method: 'DELETE' }),
save: (draft: HubDraft) =>
apiFetch<DraftResponse>(`${root}/${encodeURIComponent(draft.id)}`, json('PUT', draft)),
remove: (draft: HubDraft) =>
apiFetch(
`${root}/${encodeURIComponent(draft.id)}?revision=${encodeURIComponent(draft.revision)}`,
{ method: 'DELETE' },
),
import: (raw: string) => apiFetch<DraftResponse>(`${root}/import`, { method: 'POST', body: raw }),
export: (draft: HubDraft) => apiFetch<Record<string, unknown>>(`${root}/${encodeURIComponent(draft.id)}/export`, json('POST', { revision: draft.revision })),
export: (draft: HubDraft) =>
apiFetch<Record<string, unknown>>(
`${root}/${encodeURIComponent(draft.id)}/export`,
json('POST', { revision: draft.revision }),
),
};
/** Lists a source's branches and tags; with `ref` ("" = default branch), also returns the source rewritten to it. */
export const hubRefs = (source: string, ref?: string) =>
apiFetch<HubRefs>('/hub/refs', json('POST', ref === undefined ? { source } : { source, ref }));
/** Lists a git source's branches and tags, also when its URL cannot pin a ref (SSH, other hosts). */
export const gitRefs = (source: string) => apiFetch<HubRefs>('/hub/refs', json('POST', { source, anyGit: true }));
export const gitRefs = (source: string) =>
apiFetch<HubRefs>('/hub/refs', json('POST', { source, anyGit: true }));
export function hubAddCommand(location: string, label: string): string {
const quote = (s: string) => `'${s.replace(/'/g, `'"'"'`)}'`;
+52 -12
View File
@@ -1,5 +1,18 @@
import { apiFetch, BASE, createSSEStream } from './http';
import type { BatchInstallResult, CheckResult, ConfigEntry, DiscoverResult, DiscoveredSkill, HubConfigResponse, HubIndex, HubSavedEntry, InstallFromConfigResult, InstallResult, SearchResult, SkillPreview } from './types/install';
import type {
BatchInstallResult,
CheckResult,
ConfigEntry,
DiscoverResult,
DiscoveredSkill,
HubConfigResponse,
HubIndex,
HubSavedEntry,
InstallFromConfigResult,
InstallResult,
SearchResult,
SkillPreview,
} from './types/install';
export const installApi = {
hubIndex: () => apiFetch<HubIndex>('/hub/index'),
@@ -21,7 +34,9 @@ export const installApi = {
search: (q: string, limit = 20) =>
apiFetch<{ results: SearchResult[] }>(`/search?q=${encodeURIComponent(q)}&limit=${limit}`),
searchHub: (q: string, hubURL: string) =>
apiFetch<{ results: SearchResult[] }>(`/search?q=${encodeURIComponent(q)}&hub=${encodeURIComponent(hubURL)}`),
apiFetch<{ results: SearchResult[] }>(
`/search?q=${encodeURIComponent(q)}&hub=${encodeURIComponent(hubURL)}`,
),
preview: (source: string) =>
apiFetch<SkillPreview>(`/preview?source=${encodeURIComponent(source)}`),
check: () => apiFetch<CheckResult>('/check'),
@@ -32,26 +47,51 @@ export const installApi = {
onDone: (data: CheckResult) => void,
onError: (err: Error) => void,
): EventSource =>
createSSEStream(BASE + '/check/stream', {
discovering: () => onDiscovering(),
start: (d) => onStart(d.total),
progress: (d) => onProgress(d.checked),
done: onDone,
}, onError, 'Check stream failed'),
createSSEStream(
BASE + '/check/stream',
{
discovering: () => onDiscovering(),
start: (d) => onStart(d.total),
progress: (d) => onProgress(d.checked),
done: onDone,
},
onError,
'Check stream failed',
),
discover: (source: string, branch?: string) =>
apiFetch<DiscoverResult>('/discover', {
method: 'POST',
body: JSON.stringify({ source, branch }),
}),
install: (opts: { source: string; name?: string; force?: boolean; skipAudit?: boolean; track?: boolean; into?: string; branch?: string; kind?: 'skill' | 'agent' }) =>
install: (opts: {
source: string;
name?: string;
force?: boolean;
skipAudit?: boolean;
track?: boolean;
into?: string;
branch?: string;
kind?: 'skill' | 'agent';
}) =>
apiFetch<InstallResult>('/install', {
method: 'POST',
body: JSON.stringify(opts),
}),
// Entries recorded in config but not on disk (bare `skillshare install`)
missingConfigEntries: () => apiFetch<{ entries: ConfigEntry[]; file: string }>('/install/missing'),
installFromConfig: () => apiFetch<InstallFromConfigResult>('/install/from-config', { method: 'POST' }),
installBatch: (opts: { source: string; skills: DiscoveredSkill[]; force?: boolean; skipAudit?: boolean; into?: string; name?: string; branch?: string; kind?: 'skill' | 'agent' }) =>
missingConfigEntries: () =>
apiFetch<{ entries: ConfigEntry[]; file: string }>('/install/missing'),
installFromConfig: () =>
apiFetch<InstallFromConfigResult>('/install/from-config', { method: 'POST' }),
installBatch: (opts: {
source: string;
skills: DiscoveredSkill[];
force?: boolean;
skipAudit?: boolean;
into?: string;
name?: string;
branch?: string;
kind?: 'skill' | 'agent';
}) =>
apiFetch<BatchInstallResult>('/install/batch', {
method: 'POST',
body: JSON.stringify(opts),
+113 -43
View File
@@ -1,5 +1,18 @@
import { apiFetch } from './http';
import type { ConvertMethod, InstructionsChange, InstructionsWarning, ProjectInstructions, SharedCopyResult, SharedInstructionsFile, SharedInstructionsTarget, SharedRestorePreview, TargetFile, TargetFileList, TargetInstructions, TargetInstructionsSetup } from './types/instructions';
import type {
ConvertMethod,
InstructionsChange,
InstructionsWarning,
ProjectInstructions,
SharedCopyResult,
SharedInstructionsFile,
SharedInstructionsTarget,
SharedRestorePreview,
TargetFile,
TargetFileList,
TargetInstructions,
TargetInstructionsSetup,
} from './types/instructions';
export const instructionsApi = {
getTargetInstructions: (name: string) =>
@@ -9,84 +22,141 @@ export const instructionsApi = {
method: 'PUT',
body: JSON.stringify({ content }),
}),
convertTargetInstructions: (name: string, body: { method: ConvertMethod; keep_tool_lines: boolean; share_as?: string; share_into?: string; apply: boolean }) =>
apiFetch<{ changes: InstructionsChange[] }>(`/targets/${encodeURIComponent(name)}/instructions/convert`, {
method: 'POST',
body: JSON.stringify(body),
}),
convertTargetInstructions: (
name: string,
body: {
method: ConvertMethod;
keep_tool_lines: boolean;
share_as?: string;
share_into?: string;
apply: boolean;
},
) =>
apiFetch<{ changes: InstructionsChange[] }>(
`/targets/${encodeURIComponent(name)}/instructions/convert`,
{
method: 'POST',
body: JSON.stringify(body),
},
),
setTargetInstructionsSetup: (name: string, setup: TargetInstructionsSetup) =>
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`, {
method: 'PUT',
body: JSON.stringify(setup),
}),
removeTargetInstructionsSetup: (name: string) =>
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`, { method: 'DELETE' }),
apiFetch<{ success: boolean }>(`/targets/${encodeURIComponent(name)}/instructions/setup`, {
method: 'DELETE',
}),
// A target's other files
listTargetFiles: (name: string) =>
apiFetch<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`),
getTargetFile: (name: string, path: string) =>
apiFetch<TargetFile & { content: string }>(`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`),
apiFetch<TargetFile & { content: string }>(
`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`,
),
putTargetFile: (name: string, path: string, content: string) =>
apiFetch<TargetFile & { content: string }>(`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`, {
method: 'PUT',
body: JSON.stringify({ content }),
}),
apiFetch<TargetFile & { content: string }>(
`/targets/${encodeURIComponent(name)}/files/content?path=${encodeURIComponent(path)}`,
{
method: 'PUT',
body: JSON.stringify({ content }),
},
),
addTargetFile: (name: string, path: string) =>
apiFetch<TargetFileList>(`/targets/${encodeURIComponent(name)}/files`, {
method: 'POST',
body: JSON.stringify({ path }),
}),
removeTargetFile: (name: string, path: string) =>
apiFetch<TargetFileList>(`/targets/${encodeURIComponent(name)}/files?path=${encodeURIComponent(path)}`, { method: 'DELETE' }),
apiFetch<TargetFileList>(
`/targets/${encodeURIComponent(name)}/files?path=${encodeURIComponent(path)}`,
{ method: 'DELETE' },
),
listSharedInstructions: () =>
apiFetch<{ files: SharedInstructionsFile[]; targets: SharedInstructionsTarget[]; file_links: boolean }>('/instructions'),
apiFetch<{
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),
}),
getSharedInstructionsContent: (name: string) =>
apiFetch<{ name: string; path: string; exists: boolean; content: string }>(`/instructions/${encodeURIComponent(name)}/content`),
apiFetch<{ 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[] }>(`/instructions/${encodeURIComponent(name)}/content`, {
method: 'PUT',
body: JSON.stringify({ content }),
}),
apiFetch<{ success: boolean; copies?: SharedCopyResult[] }>(
`/instructions/${encodeURIComponent(name)}/content`,
{
method: 'PUT',
body: JSON.stringify({ 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[] }>('/instructions/assign', {
method: 'POST',
body: JSON.stringify({ targets, extras }),
}),
apiFetch<{ success: boolean; errors: string[]; warnings?: InstructionsWarning[] }>(
'/instructions/assign',
{
method: 'POST',
body: JSON.stringify({ targets, extras }),
},
),
restoreSharedInstructions: (name: string, target: string) =>
apiFetch<{ success: boolean; errors: string[] }>(`/instructions/${encodeURIComponent(name)}/restore`, {
method: 'POST',
body: JSON.stringify({ target }),
}),
apiFetch<{ success: boolean; errors: string[] }>(
`/instructions/${encodeURIComponent(name)}/restore`,
{
method: 'POST',
body: JSON.stringify({ target }),
},
),
setSharedInstructionsMode: (name: string, target: string, mode: string) =>
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(`/instructions/${encodeURIComponent(name)}/targets/${encodeURIComponent(target)}/mode`, {
method: 'PUT',
body: JSON.stringify({ mode }),
}),
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
`/instructions/${encodeURIComponent(name)}/targets/${encodeURIComponent(target)}/mode`,
{
method: 'PUT',
body: JSON.stringify({ mode }),
},
),
getSharedRestorePreview: (name: string, target: string) =>
apiFetch<SharedRestorePreview>(`/instructions/${encodeURIComponent(name)}/restore-preview?target=${encodeURIComponent(target)}`),
apiFetch<SharedRestorePreview>(
`/instructions/${encodeURIComponent(name)}/restore-preview?target=${encodeURIComponent(target)}`,
),
addInstructionLocation: (name: string, body: { path: string; as?: string; mode?: string }) =>
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(`/instructions/${encodeURIComponent(name)}/locations`, {
method: 'POST',
body: JSON.stringify(body),
}),
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
`/instructions/${encodeURIComponent(name)}/locations`,
{
method: 'POST',
body: JSON.stringify(body),
},
),
setInstructionLocationMode: (name: string, path: string, mode: string) =>
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(`/instructions/${encodeURIComponent(name)}/locations/mode`, {
method: 'PUT',
body: JSON.stringify({ path, mode }),
}),
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
`/instructions/${encodeURIComponent(name)}/locations/mode`,
{
method: 'PUT',
body: JSON.stringify({ path, mode }),
},
),
removeInstructionLocation: (name: string, path: string) =>
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(`/instructions/${encodeURIComponent(name)}/locations?path=${encodeURIComponent(path)}`, { method: 'DELETE' }),
apiFetch<{ success: boolean; warnings?: InstructionsWarning[] }>(
`/instructions/${encodeURIComponent(name)}/locations?path=${encodeURIComponent(path)}`,
{ method: 'DELETE' },
),
getLocationRestorePreview: (name: string, path: string) =>
apiFetch<SharedRestorePreview>(`/instructions/${encodeURIComponent(name)}/locations/restore-preview?path=${encodeURIComponent(path)}`),
apiFetch<SharedRestorePreview>(
`/instructions/${encodeURIComponent(name)}/locations/restore-preview?path=${encodeURIComponent(path)}`,
),
/** Settles a modified target, or a location when `on` has its `path`. */
resolveSharedInstructions: (name: string, on: { target: string } | { path: string }, action: 'collect' | 'reapply') =>
resolveSharedInstructions: (
name: string,
on: { target: string } | { path: string },
action: 'collect' | 'reapply',
) =>
apiFetch<{ success: boolean }>(`/instructions/${encodeURIComponent(name)}/resolve`, {
method: 'POST',
body: JSON.stringify({ ...on, action }),
+4 -1
View File
@@ -3,7 +3,10 @@ import { apiFetch } from './http';
import { auditApi } from './audit';
import { resourcesApi } from './resources';
vi.mock('./http', async (load) => ({ ...await load<typeof import('./http')>(), apiFetch: vi.fn() }));
vi.mock('./http', async (load) => ({
...(await load<typeof import('./http')>()),
apiFetch: vi.fn(),
}));
// The kind unions are closed today; a cast stands in for a value that needs escaping.
const odd = 'a&b' as 'skill';
+5 -1
View File
@@ -2,7 +2,11 @@ import { apiFetch } from './http';
import type { LogListResponse, LogStatsResponse } from './types/log';
export const logApi = {
listLog: (type?: string, limit?: number, filters?: { cmd?: string; status?: string; since?: string }) => {
listLog: (
type?: string,
limit?: number,
filters?: { cmd?: string; status?: string; since?: string },
) => {
const params = new URLSearchParams();
params.set('type', type ?? 'ops');
params.set('limit', String(limit ?? 100));
+11 -2
View File
@@ -6,10 +6,19 @@ vi.mock('./client', () => ({ apiFetch: vi.fn() }));
describe('mcpApi.save', () => {
it('previews the mutation and saves with its revision', async () => {
vi.mocked(apiFetch).mockResolvedValueOnce({ revision: 'rev-1' }).mockResolvedValueOnce({ applied: [] });
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, JSON.parse(String(init?.body))])).toEqual([
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 }],
]);
+141 -36
View File
@@ -1,13 +1,44 @@
import { apiFetch } from './client';
export const mcpTargets = ['claude', 'codex', 'cursor', 'vscode', 'opencode', 'kilocode', 'grok', 'antigravity', 'amp', 'claude-desktop', 'cline', 'copilot', 'factory', 'gemini', 'goose', 'hermes', 'junie', 'kiro', 'lmstudio', 'warp', 'windsurf', 'pi', 'omp'] as const;
export const mcpTargets = [
'claude',
'codex',
'cursor',
'vscode',
'opencode',
'kilocode',
'grok',
'antigravity',
'amp',
'claude-desktop',
'cline',
'copilot',
'factory',
'gemini',
'goose',
'hermes',
'junie',
'kiro',
'lmstudio',
'warp',
'windsurf',
'pi',
'omp',
] as const;
export type MCPValue = string | { fromEnv: string };
/** A scope's defaults. A save replaces them, so a value left out is cleared. */
export interface MCPSettings { targets?: string[] }
export interface MCPSettings {
targets?: string[];
}
/** One root under the global config's mcp.projects. */
export interface MCPProject extends MCPSettings { servers?: Record<string, MCPServer> }
export interface MCPProject extends MCPSettings {
servers?: Record<string, MCPServer>;
}
/** Which of a server's tools reach the model, written once and translated per Agent. Names may use `*`. */
export interface MCPToolPolicy { allow?: string[]; deny?: string[] }
export interface MCPToolPolicy {
allow?: string[];
deny?: string[];
}
export interface MCPServer {
command?: string;
args?: string[];
@@ -48,51 +79,125 @@ export interface MCPPlan {
/** Syncing also saves the config without the settings 0.23.0 retired, even when no Agent file changes. */
migrates?: boolean;
/** `switch`: the entry only turns a global server off for one project, so adding it turns the server off there. */
changes: { target: string; path: string; name: string; root?: string; switch?: boolean; action: string; message?: string; fields?: { added?: string[]; updated?: string[]; removed?: string[] } }[];
changes: {
target: string;
path: string;
name: string;
root?: string;
switch?: boolean;
action: string;
message?: string;
fields?: { added?: string[]; updated?: string[]; removed?: string[] };
}[];
}
/** `migrated`: config files the sync also saved without the settings 0.23.0 retired, and each one's backup. */
export interface MCPResult { plan?: MCPPlan; applied: string[]; backupIds: string[]; migrated?: { path: string; backup?: string }[] }
export interface MCPResult {
plan?: MCPPlan;
applied: string[];
backupIds: string[];
migrated?: { path: string; backup?: string }[];
}
/** Servers in one Agent file that skillshare does not manage; `project` is a root under mcp.projects. */
export interface MCPUnmanaged { target: string; project?: string; path: string; names: string[] }
export interface MCPUnmanaged {
target: string;
project?: string;
path: string;
names: string[];
}
/** `servers`: what the write the backup was taken before changed; `time`: when it was taken. */
export interface MCPBackup { id: string; target: string; path: string; time?: string; servers?: { name: string; change: 'added' | 'changed' | 'removed' }[] }
export interface MCPCandidate { name: string; server: MCPServer; problems: string[]; warnings: string[]; from?: string }
export interface MCPBackup {
id: string;
target: string;
path: string;
time?: string;
servers?: { name: string; change: 'added' | 'changed' | 'removed' }[];
}
export interface MCPCandidate {
name: string;
server: MCPServer;
problems: string[];
warnings: string[];
from?: string;
}
/** `piExtension` only tells Pi's files apart: `builtin` is mcp.json, `pi-mcp-adapter` the legacy mcp-adapter.json. */
export interface MCPImportSource { target: string; path: string; piExtension?: string }
const post = <T,>(path: string, body: unknown) => apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
export interface MCPImportSource {
target: string;
path: string;
piExtension?: string;
}
const post = <T>(path: string, body: unknown) =>
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
export const mcpApi = {
list: () => apiFetch<{
source: { path: string; configPath: string; targets: string[] | null; servers: Record<string, MCPServer>; projects?: Record<string, MCPProject>; /** Targets that are another config folder of an Agent, by name */ accounts?: Record<string, { agent: string; configDir: string }>;
/** Settings the config still has that no longer apply, worded by the server in English. */
notices?: string[] };
/** Project roots that also have their own .skillshare/config.yaml. */
projectConfigs: string[];
paths: Record<string, string>; detected: string[];
/** This browser runs on the dashboard's machine, so it can open files and folders there. */
local: boolean;
/** Targets whose file in `paths` exists and this browser, on the dashboard's machine, can open. */
openable: string[];
/** For each mcp.projects root: its Agents' paths, and the targets whose file exists there, whoever views them. */
projectPaths: Record<string, Record<string, string>>; projectExisting: Record<string, string[]>; plan: MCPPlan | null; previewError: string;
/** Native import files by scope: the empty key is this config, others are project roots. */
importSources?: Record<string, MCPImportSource[]>;
backups: MCPBackup[];
unmanaged: MCPUnmanaged[];
}>('/mcp'),
list: () =>
apiFetch<{
source: {
path: string;
configPath: string;
targets: string[] | null;
servers: Record<string, MCPServer>;
projects?: Record<string, MCPProject>;
/** Targets that are another config folder of an Agent, by name */ accounts?: Record<
string,
{ agent: string; configDir: string }
>;
/** Settings the config still has that no longer apply, worded by the server in English. */
notices?: string[];
};
/** Project roots that also have their own .skillshare/config.yaml. */
projectConfigs: string[];
paths: Record<string, string>;
detected: string[];
/** This browser runs on the dashboard's machine, so it can open files and folders there. */
local: boolean;
/** Targets whose file in `paths` exists and this browser, on the dashboard's machine, can open. */
openable: string[];
/** For each mcp.projects root: its Agents' paths, and the targets whose file exists there, whoever views them. */
projectPaths: Record<string, Record<string, string>>;
projectExisting: Record<string, string[]>;
plan: MCPPlan | null;
previewError: string;
/** Native import files by scope: the empty key is this config, others are project roots. */
importSources?: Record<string, MCPImportSource[]>;
backups: MCPBackup[];
unmanaged: MCPUnmanaged[];
}>('/mcp'),
preview: (mutation: MCPMutation = {}) => post<MCPPlan>('/mcp/preview', { mutation }),
configure: (mutation: MCPMutation, revision: string, sync: boolean) => post<MCPResult>('/mcp', { mutation, revision, sync }),
configure: (mutation: MCPMutation, revision: string, sync: boolean) =>
post<MCPResult>('/mcp', { mutation, revision, sync }),
/** Apply only the changes of one mcp.projects root; the global scope and other projects stay pending. */
syncProject: (root: string, revision: string) => post<MCPResult>('/mcp', { mutation: {}, revision, sync: true, root }),
syncProject: (root: string, revision: string) =>
post<MCPResult>('/mcp', { mutation: {}, revision, sync: true, root }),
/** Save to the source only. The server refuses a write it has not previewed; the revision also catches concurrent edits. */
save: async (mutation: MCPMutation) =>
post<MCPResult>('/mcp', { mutation, revision: (await post<MCPPlan>('/mcp/preview', { mutation })).revision, sync: false }),
post<MCPResult>('/mcp', {
mutation,
revision: (await post<MCPPlan>('/mcp/preview', { mutation })).revision,
sync: false,
}),
/** One server as each of its targets' config files would hold it. Reads configuration only; no server is executed and no file is written. */
/** `toolGaps`: the parts of the server's tool policy that Agent does not apply. */
render: (mutation: MCPMutation) => post<{ rendered: { target: string; path: string; content?: string; error?: string; toolGaps?: string[] }[] }>('/mcp/render', { mutation }),
render: (mutation: MCPMutation) =>
post<{
rendered: {
target: string;
path: string;
content?: string;
error?: string;
toolGaps?: string[];
}[];
}>('/mcp/render', { mutation }),
/** `root` reads the `from` target's file in that mcp.projects root. */
import: (body: { from?: string; content?: string; name?: string; root?: string; piExtension?: string }) => post<{ candidates: MCPCandidate[] }>('/mcp/import', body),
import: (body: {
from?: string;
content?: string;
name?: string;
root?: string;
piExtension?: string;
}) => post<{ candidates: MCPCandidate[] }>('/mcp/import', body),
previewRestore: (backupId: string) => post<MCPPlan>('/mcp/restore', { backupId, preview: true }),
restore: (backupId: string, revision: string) => post<MCPResult>('/mcp/restore', { backupId, revision }),
restore: (backupId: string, revision: string) =>
post<MCPResult>('/mcp/restore', { backupId, revision }),
/** Open one Agent's config file, as listed in `paths` or `projectPaths`, the way the skill page opens a skill; `folder` opens its directory instead. */
open: (target: string, opts: { project?: string; folder?: boolean } = {}) => post<{ editor: string; path: string; pid: number }>('/mcp/open', { target, ...opts }),
open: (target: string, opts: { project?: string; folder?: boolean } = {}) =>
post<{ editor: string; path: string; pid: number }>('/mcp/open', { target, ...opts }),
};
+18 -4
View File
@@ -11,15 +11,29 @@ export interface MCPCheckFinding {
}
/** `project` is the mcp.projects root a server belongs to; absent for a global server. */
/** `live`: what the server reported when probed, only with `?live=1`. */
export interface MCPCheckServer { name: string; project?: string; ok: boolean; findings: MCPCheckFinding[]; live?: { tools: number; toolNames?: string[] } }
export interface MCPCheckReport { servers: MCPCheckServer[]; summary: { errors: number; warnings: number } }
export interface MCPCheckServer {
name: string;
project?: string;
ok: boolean;
findings: MCPCheckFinding[];
live?: { tools: number; toolNames?: string[] };
}
export interface MCPCheckReport {
servers: MCPCheckServer[];
summary: { errors: number; warnings: number };
}
/** Why a probe failed, for the dashboard to phrase; `error` is the raw detail. */
export type MCPProbeErrorKind = 'connect' | 'timeout' | 'auth' | 'protocol' | 'command' | 'unknown';
export interface MCPProbe { live?: { tools: number; toolNames?: string[] }; errorKind?: MCPProbeErrorKind; error?: string }
export interface MCPProbe {
live?: { tools: number; toolNames?: string[] };
errorKind?: MCPProbeErrorKind;
error?: string;
}
export const mcpCheckApi = {
/** Read-only. Findings that are errors still resolve; only a check that cannot run rejects. */
run: () => apiFetch<MCPCheckReport>('/mcp/check'),
/** Starts the server as the form describes it, saved or not, and asks for its tools. Saves nothing. */
probe: (mutation: MCPMutation) => apiFetch<MCPProbe>('/mcp/probe', { method: 'POST', body: JSON.stringify({ mutation }) }),
probe: (mutation: MCPMutation) =>
apiFetch<MCPProbe>('/mcp/probe', { method: 'POST', body: JSON.stringify({ mutation }) }),
};
+53 -22
View File
@@ -40,7 +40,14 @@ export interface MemoryGuidancePlan {
token: string;
changes: { path: string; before: string; after: string; targets: string[]; created: boolean }[];
skipped: { target: string; reason: string }[];
warnings: { code: string; path: string; targets?: string[]; target?: string; limit?: number; chars?: number }[];
warnings: {
code: string;
path: string;
targets?: string[];
target?: string;
limit?: number;
chars?: number;
}[];
}
export interface MemoryNotesResponse {
@@ -60,26 +67,50 @@ export interface MemoryOverviewResponse {
export const memoryApi = {
getMemoryOverview: () => apiFetch<MemoryOverviewResponse>('/extras/memory/recent'),
listMemoryNotes: (search = '') => apiFetch<MemoryNotesResponse>(`/extras/memory/notes?search=${encodeURIComponent(search)}`),
initMemory: () => apiFetch<{ success: boolean; root: string }>('/extras/memory/init', { method: 'POST' }),
listMemoryNotes: (search = '') =>
apiFetch<MemoryNotesResponse>(`/extras/memory/notes?search=${encodeURIComponent(search)}`),
initMemory: () =>
apiFetch<{ success: boolean; root: string }>('/extras/memory/init', { method: 'POST' }),
getMemoryGuidance: () => apiFetch<MemoryGuidance>('/extras/memory/guidance'),
planMemoryGuidance: (targets: string[], modes: Record<string, MemoryUpdateMode>) => apiFetch<MemoryGuidancePlan>('/extras/memory/guidance/plan', {
method: 'POST', body: JSON.stringify({ targets, modes }),
}),
applyMemoryGuidance: (targets: string[], modes: Record<string, MemoryUpdateMode>, token: string) => apiFetch<{ success: boolean; applied: string[]; errors: { path: string; error: string }[]; targets: MemoryGuidanceTarget[] }>('/extras/memory/guidance/apply', {
method: 'POST', body: JSON.stringify({ targets, modes, token }),
}),
linkMemoryIndex: (path: string, version: string) => apiFetch<MemoryNote>('/extras/memory/index', {
method: 'PUT', body: JSON.stringify({ path, version }),
}),
readMemoryNote: (path: string) => apiFetch<MemoryNote>(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`),
writeMemoryNote: (path: string, content: string, version: string) => apiFetch<MemoryNote>('/extras/memory/notes/content', {
method: 'PUT', body: JSON.stringify({ path, content, version }),
}),
moveMemoryNote: (path: string, newPath: string, version: string) => apiFetch<MemoryNote>('/extras/memory/move', {
method: 'POST', body: JSON.stringify({ 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 }),
}),
planMemoryGuidance: (targets: string[], modes: Record<string, MemoryUpdateMode>) =>
apiFetch<MemoryGuidancePlan>('/extras/memory/guidance/plan', {
method: 'POST',
body: JSON.stringify({ targets, modes }),
}),
applyMemoryGuidance: (
targets: string[],
modes: Record<string, MemoryUpdateMode>,
token: string,
) =>
apiFetch<{
success: boolean;
applied: string[];
errors: { path: string; error: string }[];
targets: MemoryGuidanceTarget[];
}>('/extras/memory/guidance/apply', {
method: 'POST',
body: JSON.stringify({ targets, modes, token }),
}),
linkMemoryIndex: (path: string, version: string) =>
apiFetch<MemoryNote>('/extras/memory/index', {
method: 'PUT',
body: JSON.stringify({ path, version }),
}),
readMemoryNote: (path: string) =>
apiFetch<MemoryNote>(`/extras/memory/notes/content?path=${encodeURIComponent(path)}`),
writeMemoryNote: (path: string, content: string, version: string) =>
apiFetch<MemoryNote>('/extras/memory/notes/content', {
method: 'PUT',
body: JSON.stringify({ path, content, version }),
}),
moveMemoryNote: (path: string, newPath: string, version: string) =>
apiFetch<MemoryNote>('/extras/memory/move', {
method: 'POST',
body: JSON.stringify({ 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 }),
}),
};
+14 -5
View File
@@ -45,7 +45,10 @@ export interface OmpExtensionsView {
rows: OmpExtensionRow[];
}
export interface OmpExtensionChange { key: string; enabled: boolean }
export interface OmpExtensionChange {
key: string;
enabled: boolean;
}
/** The preview's `revision` is a plan token; apply sends it back, so only that reviewed plan is written. */
export interface OmpExtensionsPlan {
@@ -58,15 +61,21 @@ export interface OmpExtensionsPlan {
const base = (target: string) => `/targets/${encodeURIComponent(target)}/omp-extensions`;
const post = (target: string, verb: string, changes: OmpExtensionChange[], revision: string) =>
apiFetch<OmpExtensionsPlan>(`${base(target)}/${verb}`, { method: 'POST', body: JSON.stringify({ changes, revision }) });
apiFetch<OmpExtensionsPlan>(`${base(target)}/${verb}`, {
method: 'POST',
body: JSON.stringify({ changes, revision }),
});
export const ompExtensionsApi = {
get: (target: string) => apiFetch<OmpExtensionsView>(base(target)),
/** Writes nothing; `revision` is the view's. */
preview: (target: string, changes: OmpExtensionChange[], revision: string) => post(target, 'preview', changes, revision),
preview: (target: string, changes: OmpExtensionChange[], revision: string) =>
post(target, 'preview', changes, revision),
/** `revision` is the previewed plan's. */
apply: (target: string, changes: OmpExtensionChange[], revision: string) => post(target, 'apply', changes, revision),
apply: (target: string, changes: OmpExtensionChange[], revision: string) =>
post(target, 'apply', changes, revision),
};
/** A target whose Agent is Oh My Pi: omp itself or an omp account. A project's omp has its tab on the project page. */
export const isOmpTarget = (t: { name: string; agent?: string }) => t.name === 'omp' || t.agent === 'omp';
export const isOmpTarget = (t: { name: string; agent?: string }) =>
t.name === 'omp' || t.agent === 'omp';
+44 -8
View File
@@ -47,7 +47,13 @@ export interface PiExtensionFolder {
/** Project view only: whose settings decide these rows. */
scope?: 'global' | 'project';
problem?: string;
rows: { path: string; file: 'present' | 'missing'; selection: PiSelection; provenance: 'native' | 'extras'; extra?: string }[];
rows: {
path: string;
file: 'present' | 'missing';
selection: PiSelection;
provenance: 'native' | 'extras';
extra?: string;
}[];
}
export interface PiExtensionsView {
@@ -72,17 +78,40 @@ export interface PiExtensionsView {
* project, a global package is changed by a new project override; the global file is
* never written.
*/
export interface PiExtensionChange { scope: 'global' | 'project'; index: number; source: string; path: string; action: PiExtensionAction }
export interface PiExtensionChange {
scope: 'global' | 'project';
index: number;
source: string;
path: string;
action: PiExtensionAction;
}
export interface PiExtensionsPlan {
revision: string;
settingsPath: string;
entries: {
scope?: 'global' | 'project'; index: number; source: string; identity: string; before: string[] | null; after: string[] | null; converted: boolean; keptKeys: string[];
scope?: 'global' | 'project';
index: number;
source: string;
identity: string;
before: string[] | null;
after: string[] | null;
converted: boolean;
keptKeys: string[];
/** Project only: a new override written with `reference` as its source, or an override left with no rule and removed. */
created?: boolean; removed?: boolean; reference?: string;
created?: boolean;
removed?: boolean;
reference?: string;
}[];
rows: {
scope?: 'global' | 'project';
index: number;
path: string;
before: PiSelection;
after: PiSelection;
removed: string[];
added: string[];
}[];
rows: { scope?: 'global' | 'project'; index: number; path: string; before: PiSelection; after: PiSelection; removed: string[]; added: string[] }[];
backupId?: string;
}
@@ -92,10 +121,17 @@ export const piExtensionsApi = {
get: (target: string) => apiFetch<PiExtensionsView>(base(target)),
/** Writes nothing; the plan's revision is what apply checks the file against. */
preview: (target: string, changes: PiExtensionChange[]) =>
apiFetch<PiExtensionsPlan>(`${base(target)}/preview`, { method: 'POST', body: JSON.stringify({ changes }) }),
apiFetch<PiExtensionsPlan>(`${base(target)}/preview`, {
method: 'POST',
body: JSON.stringify({ changes }),
}),
apply: (target: string, changes: PiExtensionChange[], revision: string) =>
apiFetch<PiExtensionsPlan>(`${base(target)}/apply`, { method: 'POST', body: JSON.stringify({ changes, revision }) }),
apiFetch<PiExtensionsPlan>(`${base(target)}/apply`, {
method: 'POST',
body: JSON.stringify({ 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. */
export const isPiTarget = (t: { name: string; agent?: string }) => t.name === 'pi' || t.agent === 'pi';
export const isPiTarget = (t: { name: string; agent?: string }) =>
t.name === 'pi' || t.agent === 'pi';
+74 -23
View File
@@ -1,6 +1,13 @@
import { describe, expect, it, vi } from 'vitest';
import { apiFetch } from './client';
import { type PluginBinding, bindingStatus, piShareCommand, pluginShareCommand, pluginsApi, syncAction } from './plugins';
import {
type PluginBinding,
bindingStatus,
piShareCommand,
pluginShareCommand,
pluginsApi,
syncAction,
} from './plugins';
vi.mock('./client', () => ({ apiFetch: vi.fn() }));
@@ -8,7 +15,15 @@ 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 }],
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([]);
@@ -17,11 +32,20 @@ describe('pluginsApi.list', () => {
describe('pluginShareCommand', () => {
it('adds the plugin from its source with what picked it there', () => {
expect(pluginShareCommand('mine', { source: 'https://github.com/owner/market.git', plugin: 'demo', sourceRef: 'v1.2' }))
.toBe('skillshare plugin add https://github.com/owner/market.git --plugin demo --name mine --source-ref v1.2 -g');
expect(
pluginShareCommand('mine', {
source: 'https://github.com/owner/market.git',
plugin: 'demo',
sourceRef: 'v1.2',
}),
).toBe(
'skillshare plugin add https://github.com/owner/market.git --plugin demo --name mine --source-ref v1.2 -g',
);
});
it('quotes values the shell would split', () => {
expect(pluginShareCommand('demo', { source: 'https://example.com/a b.git' })).toBe("skillshare plugin add 'https://example.com/a b.git' -g");
expect(pluginShareCommand('demo', { source: 'https://example.com/a b.git' })).toBe(
"skillshare plugin add 'https://example.com/a b.git' -g",
);
});
it('offers nothing for a local directory', () => {
expect(pluginShareCommand('demo', { source: '/Users/me/plugins/demo' })).toBe('');
@@ -30,13 +54,19 @@ describe('pluginShareCommand', () => {
describe('piShareCommand', () => {
it('names the built-in Pi target when nobody is asked', () => {
expect(piShareCommand('pi-subagents', 'npm:pi-subagents', false)).toBe('skillshare plugin add npm:pi-subagents --target pi -g');
expect(piShareCommand('pi-subagents', 'npm:pi-subagents', false)).toBe(
'skillshare plugin add npm:pi-subagents --target pi -g',
);
});
it('leaves the target to the prompt when asking', () => {
expect(piShareCommand('tools', 'npm:@acme/tools@1.2.0', true)).toBe('skillshare plugin add npm:@acme/tools@1.2.0 -g');
expect(piShareCommand('tools', 'npm:@acme/tools@1.2.0', true)).toBe(
'skillshare plugin add npm:@acme/tools@1.2.0 -g',
);
});
it('keeps a name the package would not get by itself', () => {
expect(piShareCommand('mine', 'npm:@acme/tools', false)).toBe('skillshare plugin add npm:@acme/tools --name mine --target pi -g');
expect(piShareCommand('mine', 'npm:@acme/tools', false)).toBe(
'skillshare plugin add npm:@acme/tools --name mine --target pi -g',
);
});
it('offers nothing for a package that is not from npm', () => {
expect(piShareCommand('demo', '/Users/me/pkgs/demo', false)).toBe('');
@@ -44,20 +74,29 @@ describe('piShareCommand', () => {
});
describe('syncAction', () => {
const host = (managedMarketplaces?: string[]) => ({ target: 'claude' as const, version: '1', status: 'ready', installed: [], managedMarketplaces });
const excluded = { id: 'demo@skillshare-demo-0123', source: 'https://example.com/demo', sync: false };
const host = (managedMarketplaces?: string[]) => ({
target: 'claude' as const,
version: '1',
status: 'ready',
installed: [],
managedMarketplaces,
});
const excluded = {
id: 'demo@skillshare-demo-0123',
source: 'https://example.com/demo',
sync: false,
};
it('still has work for an excluded plugin whose Skillshare marketplace is left', () => {
expect(syncAction(excluded, host(['skillshare-demo-0123']))).toBe('uninstall');
});
it('leaves an excluded plugin alone when its marketplace is gone or not Skillshare\'s', () => {
it("leaves an excluded plugin alone when its marketplace is gone or not Skillshare's", () => {
expect(syncAction(excluded, host([]))).toBe('');
});
it('never claims an imported plugin\'s marketplace', () => {
it("never claims an imported plugin's marketplace", () => {
expect(syncAction({ id: 'demo@team', sync: false }, host(['team']))).toBe('');
});
});
describe('host-local bindings', () => {
const host = { target: 'omp', version: '1', status: 'ready', installed: [] };
it('keeps an unbound import visible without proposing an install', () => {
@@ -86,18 +125,30 @@ describe('host-local bindings', () => {
});
});
describe('shared ref reconciliation', () => {
const binding: PluginBinding = { id: '/local/old', source: 'owner/repo', refChanged: true };
const ready = { target: 'pi', version: '1', status: 'ready', installed: [{ id: binding.id, enabled: true }] };
const ready = {
target: 'pi',
version: '1',
status: 'ready',
installed: [{ id: binding.id, enabled: true }],
};
it.each([
[{}, ready, 'update'], [{}, { ...ready, installed: [] }, 'install'],
[{ sync: false }, ready, 'uninstall'], [{ sync: false }, { ...ready, installed: [] }, ''],
[{ cleanup: true }, ready, 'remove'], [{ contextChanged: true }, ready, ''],
[{ imported: true, id: '' }, ready, ''], [{ pending: 'remove' }, ready, 'update'],
[{}, undefined, ''], [{}, { ...ready, status: 'missing', installed: [] }, 'install'],
[{}, ready, 'update'],
[{}, { ...ready, installed: [] }, 'install'],
[{ sync: false }, ready, 'uninstall'],
[{ sync: false }, { ...ready, installed: [] }, ''],
[{ cleanup: true }, ready, 'remove'],
[{ contextChanged: true }, ready, ''],
[{ imported: true, id: '' }, ready, ''],
[{ pending: 'remove' }, ready, 'update'],
[{}, undefined, ''],
[{}, { ...ready, status: 'missing', installed: [] }, 'install'],
[{}, { ...ready, error: 'unavailable' }, ''],
] as [Partial<PluginBinding>, typeof ready | undefined, string][])('keeps reconciliation precedence: %o / %o', (changes, host, action) => {
expect(syncAction({ ...binding, ...changes }, host)).toBe(action);
});
] as [Partial<PluginBinding>, typeof ready | undefined, string][])(
'keeps reconciliation precedence: %o / %o',
(changes, host, action) => {
expect(syncAction({ ...binding, ...changes }, host)).toBe(action);
},
);
});
+253 -40
View File
@@ -3,20 +3,91 @@ import { BASE, createSSEStream, parseApiErrorPayload } from './http';
export type PluginTarget = string;
/** `npm`: the target installs npm:<package> sources (Pi, or a Pi account that runs pi). */
export interface PluginTargetDefinition { target: string; label: string; project: boolean; operations: string[]; reason?: string; reasonKey?: string; npm?: boolean }
export const targetMap = (definitions: PluginTargetDefinition[] = []) => Object.fromEntries(definitions.map((d) => [d.target, d]));
export type PluginAction = 'add' | 'import' | 'unimport' | 'sync' | 'check' | 'update' | 'remove' | 'enable' | 'disable';
export interface PluginRequest { action: PluginAction; name?: string; source?: string; sourceRef?: string; entry?: string; plugin?: string; targets?: PluginTarget[]; from?: PluginTarget }
export interface PluginBinding { refChanged?: boolean; imported?: boolean; importRetained?: boolean; cleanup?: boolean; contextChanged?: boolean; piRegistration?: string; id: string; source?: string; sourceRef?: string; commit?: string; entry?: string; plugin?: string; digest?: string; version?: string; pending?: string; sync?: boolean; components?: string[] }
export interface NativePlugin { id: string; version?: string; enabled: boolean; enabledKnown?: boolean; scope?: string; filtered?: boolean; importable?: boolean }
export interface PluginPackage { version?: string; source?: string; sourceRef?: string; plugin?: string; entry?: string; bindings: Partial<Record<PluginTarget, PluginBinding>> }
export interface PluginTargetDefinition {
target: string;
label: string;
project: boolean;
operations: string[];
reason?: string;
reasonKey?: string;
npm?: boolean;
}
export const targetMap = (definitions: PluginTargetDefinition[] = []) =>
Object.fromEntries(definitions.map((d) => [d.target, d]));
export type PluginAction =
| 'add'
| 'import'
| 'unimport'
| 'sync'
| 'check'
| 'update'
| 'remove'
| 'enable'
| 'disable';
export interface PluginRequest {
action: PluginAction;
name?: string;
source?: string;
sourceRef?: string;
entry?: string;
plugin?: string;
targets?: PluginTarget[];
from?: PluginTarget;
}
export interface PluginBinding {
refChanged?: boolean;
imported?: boolean;
importRetained?: boolean;
cleanup?: boolean;
contextChanged?: boolean;
piRegistration?: string;
id: string;
source?: string;
sourceRef?: string;
commit?: string;
entry?: string;
plugin?: string;
digest?: string;
version?: string;
pending?: string;
sync?: boolean;
components?: string[];
}
export interface NativePlugin {
id: string;
version?: string;
enabled: boolean;
enabledKnown?: boolean;
scope?: string;
filtered?: boolean;
importable?: boolean;
}
export interface PluginPackage {
version?: string;
source?: string;
sourceRef?: string;
plugin?: string;
entry?: string;
bindings: Partial<Record<PluginTarget, PluginBinding>>;
}
export interface PluginInventory {
targetDefinitions?: PluginTargetDefinition[];
/** `source` and the rest are set when the plugin was added, so it stays managed with no Agent bound. */
packages: Record<string, PluginPackage>;
/** `status`: 'ready' | 'missing' (its CLI is not on PATH here) | 'blocked' (deal with it in the Agent). */
/** `managedMarketplaces`: the Claude/Codex marketplaces Skillshare registered from its own state directory. */
hosts: { target: PluginTarget; version: string; status: string; error?: string; errorKey?: string; errorArgs?: Record<string, string>; note?: string; noteKey?: string; installed: NativePlugin[]; managedMarketplaces?: string[] }[];
hosts: {
target: PluginTarget;
version: string;
status: string;
error?: string;
errorKey?: string;
errorArgs?: Record<string, string>;
note?: string;
noteKey?: string;
installed: NativePlugin[];
managedMarketplaces?: string[];
}[];
}
/**
* What Sync would do to one binding, '' when nothing. Without `host` (the Agents have not
@@ -29,7 +100,11 @@ export const syncAction = (b: PluginBinding, host?: PluginInventory['hosts'][num
if (b.imported && !b.id) return '';
const exists = host?.installed.some((i) => i.id === b.id);
// The plugin is gone but the marketplace Skillshare registered for it is still there.
const leftover = !exists && !!b.source && b.id.includes('@') && !!host?.managedMarketplaces?.includes(b.id.slice(b.id.indexOf('@') + 1));
const leftover =
!exists &&
!!b.source &&
b.id.includes('@') &&
!!host?.managedMarketplaces?.includes(b.id.slice(b.id.indexOf('@') + 1));
if (b.cleanup) return host && !host.error ? 'remove' : '';
if (b.sync === false) return exists || leftover ? 'uninstall' : '';
if (b.refChanged && host?.status === 'ready' && !host.error) return exists ? 'update' : 'install';
@@ -46,17 +121,25 @@ export const bindingStatus = (b: PluginBinding, host?: PluginInventory['hosts'][
if (!host) return '';
if (host.error) return 'plugins.unverified';
const installed = host.installed.find((i) => i.id === b.id);
return installed && installed.enabledKnown !== false && !installed.enabled ? 'plugins.nativeDisabled' : '';
return installed && installed.enabledKnown !== false && !installed.enabled
? 'plugins.nativeDisabled'
: '';
};
/**
* A binding's version: what config recorded, else what the Agent reports installed. On a Pi
* target Pi's answer comes first: it reads each installed package's package.json, npm, git or
* local, and a version recorded at import goes stale with the next pi update.
*/
export const bindingVersion = (inventory: Pick<PluginInventory, 'hosts' | 'targetDefinitions'>, target: PluginTarget, b: PluginBinding) => {
const installed = inventory.hosts.find((h) => h.target === target)?.installed.find((i) => i.id === b.id)?.version;
export const bindingVersion = (
inventory: Pick<PluginInventory, 'hosts' | 'targetDefinitions'>,
target: PluginTarget,
b: PluginBinding,
) => {
const installed = inventory.hosts
.find((h) => h.target === target)
?.installed.find((i) => i.id === b.id)?.version;
const pi = inventory.targetDefinitions?.some((d) => d.target === target && d.npm);
return pi ? installed ?? b.version : b.version ?? installed;
return pi ? (installed ?? b.version) : (b.version ?? installed);
};
/**
* The command that adds this plugin from its source on another machine, '' when the source is a
@@ -64,10 +147,23 @@ export const bindingVersion = (inventory: Pick<PluginInventory, 'hosts' | 'targe
* adds globally: run inside a project with its own config, it would otherwise land in that project.
*/
const quote = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'"'"'`)}'`);
export const pluginShareCommand = (name: string, p: { source?: string; sourceRef?: string; plugin?: string; entry?: string }) => {
export const pluginShareCommand = (
name: string,
p: { source?: string; sourceRef?: string; plugin?: string; entry?: string },
) => {
if (!p.source?.startsWith('https://')) return '';
const flags: [string, string | undefined][] = [['--plugin', p.plugin], ['--name', p.plugin && p.plugin !== name ? name : undefined], ['--source-ref', p.sourceRef], ['--entry', p.entry]];
return ['skillshare plugin add', quote(p.source), ...flags.filter(([, v]) => v).map(([flag, v]) => `${flag} ${quote(v!)}`), '-g'].join(' ');
const flags: [string, string | undefined][] = [
['--plugin', p.plugin],
['--name', p.plugin && p.plugin !== name ? name : undefined],
['--source-ref', p.sourceRef],
['--entry', p.entry],
];
return [
'skillshare plugin add',
quote(p.source),
...flags.filter(([, v]) => v).map(([flag, v]) => `${flag} ${quote(v!)}`),
'-g',
].join(' ');
};
/** The name an npm source is recorded under when none is given, as the server derives it (npmSpec): the package name without its version or @scope. */
export function npmDefaultName(source: string) {
@@ -84,15 +180,77 @@ export function npmDefaultName(source: string) {
export const piShareCommand = (name: string, id: string, ask: boolean) => {
if (!/^npm:\S+$/.test(id)) return '';
const named = npmDefaultName(id) === name ? [] : [`--name ${quote(name)}`];
return ['skillshare plugin add', quote(id), ...named, ...(ask ? [] : ['--target pi']), '-g'].join(' ');
return ['skillshare plugin add', quote(id), ...named, ...(ask ? [] : ['--target pi']), '-g'].join(
' ',
);
};
export interface PluginCandidate { name: string; description: string; version: string; targets: PluginTarget[]; components: string[]; problem?: string; problemKey?: string; problemArgs?: Record<string, string>; targetInfo?: Record<string, { manifest: string; path?: string; version?: string; logo?: string; entry?: string; components: string[]; problem?: string; problemKey?: string; problemArgs?: Record<string, string> }> }
export interface PluginCandidate {
name: string;
description: string;
version: string;
targets: PluginTarget[];
components: string[];
problem?: string;
problemKey?: string;
problemArgs?: Record<string, string>;
targetInfo?: Record<
string,
{
manifest: string;
path?: string;
version?: string;
logo?: string;
entry?: string;
components: string[];
problem?: string;
problemKey?: string;
problemArgs?: Record<string, string>;
}
>;
}
export interface PluginDiscovery {
warnings?: string[]; source: string; sourceRef?: string; commit?: string; targetDefinitions?: PluginTargetDefinition[]; digest: string; candidates: PluginCandidate[] }
export interface PluginPlan { revision: string; blocked: boolean; changes: { name: string; target: PluginTarget; id: string; action: string; failed?: boolean; guidance?: boolean; message?: string; messageKey?: string; messageArgs?: Record<string, string>; components?: string[]; preservedKeys?: string[]; logo?: string; binding?: PluginBinding }[] }
export interface PluginOutcome { name: string; target: PluginTarget; status: string; guidance?: boolean; message?: string; messageKey?: string; messageArgs?: Record<string, string> }
warnings?: string[];
source: string;
sourceRef?: string;
commit?: string;
targetDefinitions?: PluginTargetDefinition[];
digest: string;
candidates: PluginCandidate[];
}
export interface PluginPlan {
revision: string;
blocked: boolean;
changes: {
name: string;
target: PluginTarget;
id: string;
action: string;
failed?: boolean;
guidance?: boolean;
message?: string;
messageKey?: string;
messageArgs?: Record<string, string>;
components?: string[];
preservedKeys?: string[];
logo?: string;
binding?: PluginBinding;
}[];
}
export interface PluginOutcome {
name: string;
target: PluginTarget;
status: string;
guidance?: boolean;
message?: string;
messageKey?: string;
messageArgs?: Record<string, string>;
}
export interface PluginRun { name: string; target: string; version?: string }
export interface PluginRun {
name: string;
target: string;
version?: string;
}
/** Rows that differ only by Agent become one row naming every Agent; `key` says what else must match. */
export function byPlugin<R extends PluginRun>(rows: R[], key: (r: R) => string = () => '') {
@@ -105,29 +263,66 @@ export function byPlugin<R extends PluginRun>(rows: R[], key: (r: R) => string =
}
return [...groups.values()];
}
export interface PluginResult { result: { results: PluginOutcome[] } | null; failure: string }
export interface PluginResult {
result: { results: PluginOutcome[] } | null;
failure: string;
}
/** What a check showed for one Agent of a plugin: the version an update would bring, and the source it came from. */
export interface PluginUpdate { version: string; commit?: string; digest?: string; id?: string; source?: string; sourceRef?: string; plugin?: string; entry?: string }
export interface PluginUpdate {
version: string;
commit?: string;
digest?: string;
id?: string;
source?: string;
sourceRef?: string;
plugin?: string;
entry?: string;
}
/** One plugin of a batch update, with what the check showed per Agent so a source that moved since is not installed. */
export interface PluginUpdateItem { name: string; targets: PluginTarget[]; seen?: Record<PluginTarget, PluginUpdate> }
export interface PluginUpdateItem {
name: string;
targets: PluginTarget[];
seen?: Record<PluginTarget, PluginUpdate>;
}
export type PluginUpdateEvent =
| { event: 'start'; name: string }
| { event: 'plan'; name: string; plan: PluginPlan }
| { event: 'result'; name: string; plan: PluginPlan | null; result: PluginResult['result']; failure: string; stale: boolean }
| {
event: 'result';
name: string;
plan: PluginPlan | null;
result: PluginResult['result'];
failure: string;
stale: boolean;
}
| { event: 'done'; failure: string };
/** One plugin's answer from the update check: its plan, or why it could not be checked. */
export interface PluginCheckEvent { name: string; plan: PluginPlan | null; error?: string; error_code?: string; error_params?: Record<string, string> }
export interface PluginCheckEvent {
name: string;
plan: PluginPlan | null;
error?: string;
error_code?: string;
error_params?: Record<string, string>;
}
/** Reads the server's event stream for a batch update until `done`. EventSource (createSSEStream) cannot POST the picks, so fetch reads the stream. */
async function updateStream(items: PluginUpdateItem[], on: (e: PluginUpdateEvent) => void) {
const res = await fetch(BASE + '/plugins/update/stream', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ items }) });
if (!res.ok || !res.body) throw new Error(parseApiErrorPayload(await res.json().catch(() => null), res.status, res.statusText).message);
const res = await fetch(BASE + '/plugins/update/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items }),
});
if (!res.ok || !res.body)
throw new Error(
parseApiErrorPayload(await res.json().catch(() => null), res.status, res.statusText).message,
);
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
for (;;) {
const { value, done } = await reader.read();
if (done) throw new Error('The update stream closed before it finished; refresh to see what changed.');
if (done)
throw new Error('The update stream closed before it finished; refresh to see what changed.');
buffer += value;
for (let end = buffer.indexOf('\n\n'); end >= 0; end = buffer.indexOf('\n\n')) {
const block = buffer.slice(0, end);
@@ -141,27 +336,45 @@ async function updateStream(items: PluginUpdateItem[], on: (e: PluginUpdateEvent
}
}
const post = <T,>(path: string, body: unknown) => apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
const post = <T>(path: string, body: unknown) =>
apiFetch<T>(path, { method: 'POST', body: JSON.stringify(body) });
export const pluginsApi = {
/** `hosts: false` answers from config alone, without waiting on any Agent's CLI; `hosts` comes back empty. */
list: (hosts = true) =>
apiFetch<PluginInventory>(hosts ? '/plugins' : '/plugins?hosts=false').then((inv) => ({
...inv,
// A failed inventory could arrive as null; one Agent must not break the whole page.
hosts: inv.hosts.map((h) => ({ ...h, installed: (h.installed as NativePlugin[] | null) ?? [] })),
hosts: inv.hosts.map((h) => ({
...h,
installed: (h.installed as NativePlugin[] | null) ?? [],
})),
})),
/** `name` is a plugin already managed here: its reviewed copy answers instead of downloading the source again. */
discover: (source: string, sourceRef?: string, entry?: string, name?: string) => post<PluginDiscovery>('/plugins/discover', { source, sourceRef, entry, name }),
discover: (source: string, sourceRef?: string, entry?: string, name?: string) =>
post<PluginDiscovery>('/plugins/discover', { source, sourceRef, entry, name }),
/** The reviewed local copy of the plugin's source; empty for an imported plugin, which has none. */
files: (name: string) => apiFetch<{ files: string[] }>(`/plugins/${encodeURIComponent(name)}/files`),
file: (name: string, path: string) => apiFetch<{ content: string }>(`/plugins/${encodeURIComponent(name)}/files/${path.split('/').map(encodeURIComponent).join('/')}`),
files: (name: string) =>
apiFetch<{ files: string[] }>(`/plugins/${encodeURIComponent(name)}/files`),
file: (name: string, path: string) =>
apiFetch<{ content: string }>(
`/plugins/${encodeURIComponent(name)}/files/${path.split('/').map(encodeURIComponent).join('/')}`,
),
preview: (request: PluginRequest) => post<PluginPlan>('/plugins/preview', { request }),
/** Checks every plugin at once on the server; each plugin's answer arrives through `on` as soon as it is ready. */
check: (on: (e: PluginCheckEvent) => void) => new Promise<void>((resolve, reject) => {
createSSEStream(BASE + '/plugins/check/stream', { plan: on, done: (d: { failure: string }) => (d.failure ? reject(new Error(d.failure)) : resolve()) },
reject, 'The update check stopped before it finished.');
}),
apply: (request: PluginRequest, revision: string) => post<PluginResult>('/plugins/apply', { request, revision }),
check: (on: (e: PluginCheckEvent) => void) =>
new Promise<void>((resolve, reject) => {
createSSEStream(
BASE + '/plugins/check/stream',
{
plan: on,
done: (d: { failure: string }) => (d.failure ? reject(new Error(d.failure)) : resolve()),
},
reject,
'The update check stopped before it finished.',
);
}),
apply: (request: PluginRequest, revision: string) =>
post<PluginResult>('/plugins/apply', { request, revision }),
/** Updates the plugins one after another on the server; each one's progress arrives through `on`. */
update: updateStream,
/** The plugin under way finishes; no other starts. */
+28 -8
View File
@@ -10,12 +10,25 @@ describe('source links API', () => {
vi.stubGlobal('fetch', fetch);
const body = { path: '/work/team', name: '_team', enable: true };
expect(await resourcesApi.createSourceLink(body)).toEqual(result);
expect(fetch).toHaveBeenCalledWith('/api/source-links', expect.objectContaining({ method: 'POST', body: JSON.stringify(body) }));
expect(fetch).toHaveBeenCalledWith(
'/api/source-links',
expect.objectContaining({ method: 'POST', body: JSON.stringify(body) }),
);
});
it('preserves the HTTP 400 guard message', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'target is missing' }), { status: 400 })));
await expect(resourcesApi.createSourceLink({ path: '/missing' })).rejects.toMatchObject({ status: 400, message: 'target is missing' });
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ error: 'target is missing' }), { status: 400 }),
),
);
await expect(resourcesApi.createSourceLink({ path: '/missing' })).rejects.toMatchObject({
status: 400,
message: 'target is missing',
});
});
it('deletes the encoded first-level link name', async () => {
@@ -23,21 +36,28 @@ describe('source links API', () => {
const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify(result)));
vi.stubGlobal('fetch', fetch);
expect(await resourcesApi.removeSourceLink('_my team')).toEqual(result);
expect(fetch).toHaveBeenCalledWith('/api/source-links/_my%20team', expect.objectContaining({ method: 'DELETE' }));
expect(fetch).toHaveBeenCalledWith(
'/api/source-links/_my%20team',
expect.objectContaining({ method: 'DELETE' }),
);
});
});
describe('repo removal intent', () => {
afterEach(() => vi.unstubAllGlobals());
it.each<[boolean, boolean, string]>([
[false, false, ''], [true, false, '?force=true'],
[false, true, '?recordOnly=true'], [true, true, '?force=true&recordOnly=true'],
[false, false, ''],
[true, false, '?force=true'],
[false, true, '?recordOnly=true'],
[true, true, '?force=true&recordOnly=true'],
])('encodes force=%s and recordOnly=%s', async (force, recordOnly, query) => {
const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ success: true })));
vi.stubGlobal('fetch', fetch);
await resourcesApi.deleteRepo('org/_team', force, recordOnly);
expect(fetch).toHaveBeenCalledWith(`/api/repos/org%2F_team${query}`, expect.objectContaining({ method: 'DELETE' }));
expect(fetch).toHaveBeenCalledWith(
`/api/repos/org%2F_team${query}`,
expect.objectContaining({ method: 'DELETE' }),
);
});
});
+46 -17
View File
@@ -1,32 +1,58 @@
import { apiFetch, kindQuery } from './http';
import type { BatchToggleResult, MoveRequest, MoveResult, BatchUninstallRequest, BatchUninstallResult, CollectResult, CollectScanResult, CreateSkillRequest, CreateSkillResponse, Overview, LinkedRepo, LocalFileChange, Skill, SkillFileContent, SourceLink, SourceLinkRequest, SourceLinkResult, TemplatesResponse } from './types/resources';
import type {
BatchToggleResult,
MoveRequest,
MoveResult,
BatchUninstallRequest,
BatchUninstallResult,
CollectResult,
CollectScanResult,
CreateSkillRequest,
CreateSkillResponse,
Overview,
LinkedRepo,
LocalFileChange,
Skill,
SkillFileContent,
SourceLink,
SourceLinkRequest,
SourceLinkResult,
TemplatesResponse,
} from './types/resources';
export const resourcesApi = {
createSourceLink: (body: SourceLinkRequest) =>
apiFetch<SourceLinkResult>('/source-links', { method: 'POST', body: JSON.stringify(body) }),
removeSourceLink: (name: string) =>
apiFetch<{ success: boolean; name: string; warning?: string }>(`/source-links/${encodeURIComponent(name)}`, { method: 'DELETE' }),
apiFetch<{ success: boolean; name: string; warning?: string }>(
`/source-links/${encodeURIComponent(name)}`,
{ method: 'DELETE' },
),
getOverview: () => apiFetch<Overview>('/overview'),
listSkills: (kind?: 'skill' | 'agent') =>
apiFetch<{ resources: Skill[]; sourceLinks?: SourceLink[]; sourceLinkWarnings?: string[]; linked_repos?: LinkedRepo[] }>(`/resources${kindQuery(kind)}`),
apiFetch<{
resources: Skill[];
sourceLinks?: SourceLink[];
sourceLinkWarnings?: string[];
linked_repos?: LinkedRepo[];
}>(`/resources${kindQuery(kind)}`),
getResource: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ resource: Skill; skillMdContent: string; files: string[] }>(
`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`
`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`,
),
deleteResource: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ success: boolean }>(
`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`,
{ method: 'DELETE' }
),
apiFetch<{ success: boolean }>(`/resources/${encodeURIComponent(name)}${kindQuery(kind)}`, {
method: 'DELETE',
}),
disableResource: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ success: boolean; name: string; disabled: boolean }>(
`/resources/${encodeURIComponent(name)}/disable${kindQuery(kind)}`,
{ method: 'POST' }
{ method: 'POST' },
),
enableResource: (name: string, kind?: 'skill' | 'agent') =>
apiFetch<{ success: boolean; name: string; disabled: boolean }>(
`/resources/${encodeURIComponent(name)}/enable${kindQuery(kind)}`,
{ method: 'POST' }
{ method: 'POST' },
),
batchUninstall: (opts: BatchUninstallRequest) =>
apiFetch<BatchUninstallResult>('/uninstall/batch', {
@@ -72,7 +98,10 @@ export const resourcesApi = {
}),
// Repo uninstall
deleteRepo: (name: string, force = false, recordOnly = false) =>
apiFetch<{ success: boolean; name: string; movedToTrash: boolean }>(`/repos/${encodeURIComponent(name)}${force ? '?force=true' : ''}${recordOnly ? `${force ? '&' : '?'}recordOnly=true` : ''}`, { method: 'DELETE' }),
apiFetch<{ success: boolean; name: string; movedToTrash: boolean }>(
`/repos/${encodeURIComponent(name)}${force ? '?force=true' : ''}${recordOnly ? `${force ? '&' : '?'}recordOnly=true` : ''}`,
{ method: 'DELETE' },
),
// Skill file content
getSkillFile: (skillName: string, filepath: string) =>
apiFetch<SkillFileContent>(`/resources/${encodeURIComponent(skillName)}/files/${filepath}`),
@@ -100,16 +129,13 @@ export const resourcesApi = {
},
),
// Launch an external editor (VS Code / Cursor / $EDITOR) against the skill file.
openSkillInEditor: (
name: string,
opts?: { editor?: string; kind?: 'skill' | 'agent' }
) =>
openSkillInEditor: (name: string, opts?: { editor?: string; kind?: 'skill' | 'agent' }) =>
apiFetch<{ editor: string; path: string; pid: number }>(
`/resources/${encodeURIComponent(name)}/open-in-editor${kindQuery(opts?.kind)}`,
{
method: 'POST',
body: JSON.stringify({ editor: opts?.editor ?? 'auto' }),
}
},
),
collectScan: (target?: string, kind?: 'skill' | 'agent') => {
const params = new URLSearchParams();
@@ -118,7 +144,10 @@ export const resourcesApi = {
const qs = params.toString();
return apiFetch<CollectScanResult>(`/collect/scan${qs ? '?' + qs : ''}`);
},
collect: (opts: { skills: { name: string; targetName: string; kind?: string }[]; force?: boolean }) =>
collect: (opts: {
skills: { name: string; targetName: string; kind?: string }[];
force?: boolean;
}) =>
apiFetch<CollectResult>('/collect', {
method: 'POST',
body: JSON.stringify(opts),
+5 -1
View File
@@ -17,7 +17,11 @@ it("reports the server's error event with its message", () => {
const onError = vi.fn();
createSSEStream('/api/x/stream', {}, onError, 'Stream failed');
FakeEventSource.last.dispatchEvent(new MessageEvent('error', { data: JSON.stringify({ error: 'doctor check failed: exit status 2' }) }));
FakeEventSource.last.dispatchEvent(
new MessageEvent('error', {
data: JSON.stringify({ error: 'doctor check failed: exit status 2' }),
}),
);
expect(onError).toHaveBeenCalledWith(new Error('doctor check failed: exit status 2'));
});
+29 -10
View File
@@ -1,12 +1,24 @@
import { apiFetch, BASE, createSSEStream } from './http';
import type { DiffTarget, FolderConflict, IgnoreSources, SyncMatrixEntry, SyncResponse } from './types/sync';
import type {
DiffTarget,
FolderConflict,
IgnoreSources,
SyncMatrixEntry,
SyncResponse,
} from './types/sync';
export const syncApi = {
getSyncMatrix: (target?: string) =>
apiFetch<{ entries: SyncMatrixEntry[] }>(
`/sync-matrix${target ? '?target=' + encodeURIComponent(target) : ''}`
`/sync-matrix${target ? '?target=' + encodeURIComponent(target) : ''}`,
),
previewSyncMatrix: (target: string, include: string[], exclude: string[], agentInclude?: string[], agentExclude?: string[]) =>
previewSyncMatrix: (
target: string,
include: string[],
exclude: string[],
agentInclude?: string[],
agentExclude?: string[],
) =>
apiFetch<{ entries: SyncMatrixEntry[] }>('/sync-matrix/preview', {
method: 'POST',
body: JSON.stringify({
@@ -24,7 +36,9 @@ export const syncApi = {
body: JSON.stringify(opts),
}),
diff: (target?: string) =>
apiFetch<{ diffs: DiffTarget[]; folder_conflicts?: FolderConflict[] } & IgnoreSources>(`/diff${target ? '?target=' + encodeURIComponent(target) : ''}`),
apiFetch<{ diffs: DiffTarget[]; folder_conflicts?: FolderConflict[] } & IgnoreSources>(
`/diff${target ? '?target=' + encodeURIComponent(target) : ''}`,
),
diffStream: (
onDiscovering: () => void,
onStart: (total: number) => void,
@@ -32,10 +46,15 @@ export const syncApi = {
onDone: (data: { diffs: DiffTarget[] } & IgnoreSources) => void,
onError: (err: Error) => void,
): EventSource =>
createSSEStream(BASE + '/diff/stream', {
discovering: () => onDiscovering(),
start: (d) => onStart(d.total),
result: (d) => onResult(d.diff, d.checked),
done: onDone,
}, onError, 'Diff stream failed'),
createSSEStream(
BASE + '/diff/stream',
{
discovering: () => onDiscovering(),
start: (d) => onStart(d.total),
result: (d) => onResult(d.diff, d.checked),
done: onDone,
},
onError,
'Diff stream failed',
),
};
+24 -5
View File
@@ -1,10 +1,24 @@
import { apiFetch, BASE, createSSEStream } from './http';
import type { AnalyzeResponse, DoctorCheck, DoctorResponse, VersionCheck } from './types/diagnostics';
import type {
AnalyzeResponse,
DoctorCheck,
DoctorResponse,
VersionCheck,
} from './types/diagnostics';
export const systemApi = {
getUpdatePolicy: () => apiFetch<{ enabled: boolean; configured: boolean; envOverride: boolean }>('/update-settings'),
getVersionCheck: (manual = false) => apiFetch<VersionCheck>(manual ? '/version?manual=true' : '/version'),
upgradeApp: () => apiFetch<{ ok: boolean; updated: boolean; devMode?: boolean; latestVersion?: string; output?: string }>('/upgrade', { method: 'POST' }),
getUpdatePolicy: () =>
apiFetch<{ enabled: boolean; configured: boolean; envOverride: boolean }>('/update-settings'),
getVersionCheck: (manual = false) =>
apiFetch<VersionCheck>(manual ? '/version?manual=true' : '/version'),
upgradeApp: () =>
apiFetch<{
ok: boolean;
updated: boolean;
devMode?: boolean;
latestVersion?: string;
output?: string;
}>('/upgrade', { method: 'POST' }),
restartApp: (opts?: { clearCache?: boolean }) =>
apiFetch<{ ok: boolean; restarting: boolean }>('/restart', {
method: 'POST',
@@ -14,7 +28,12 @@ export const systemApi = {
/** Runs doctor, passing each check to onCheck as it is found; resolves with the full result. */
doctorStream: (onCheck: (check: DoctorCheck) => void, signal?: AbortSignal) =>
new Promise<DoctorResponse>((resolve, reject) => {
const es = createSSEStream(BASE + '/doctor/stream', { check: onCheck, done: resolve }, reject, 'Health check failed');
const es = createSSEStream(
BASE + '/doctor/stream',
{ check: onCheck, done: resolve },
reject,
'Health check failed',
);
signal?.addEventListener('abort', () => es.close());
}),
analyze: () => apiFetch<AnalyzeResponse>('/analyze'),
+59 -10
View File
@@ -1,27 +1,76 @@
import { apiFetch } from './http';
import type { TargetInstructionsSetup } from './types/instructions';
import type { ProjectInput, ProjectList, ProjectMutation, SkillsDetach, SkillsOffPreview, Target } from './types/targets';
import type {
ProjectInput,
ProjectList,
ProjectMutation,
SkillsDetach,
SkillsOffPreview,
Target,
} from './types/targets';
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 }>(`/targets${scope ? `?scope=${scope}` : ''}`),
listTargets: (scope?: 'projects' | 'all') =>
apiFetch<{ targets: Target[]; sourceSkillCount: number }>(
`/targets${scope ? `?scope=${scope}` : ''}`,
),
listProjects: () => apiFetch<ProjectList>('/projects'),
saveProject: (project: ProjectInput) => apiFetch<ProjectMutation>('/projects', { method: 'PUT', body: JSON.stringify(project) }),
removeProject: (root: string, shared = false) => apiFetch<ProjectMutation>(`/projects?root=${encodeURIComponent(root)}${shared ? '&shared=true' : ''}`, { method: 'DELETE' }),
convertProject: (root: string) => apiFetch<ProjectMutation>('/projects/convert', { method: 'POST', body: JSON.stringify({ root }) }),
saveProject: (project: ProjectInput) =>
apiFetch<ProjectMutation>('/projects', { method: 'PUT', body: JSON.stringify(project) }),
removeProject: (root: string, shared = false) =>
apiFetch<ProjectMutation>(
`/projects?root=${encodeURIComponent(root)}${shared ? '&shared=true' : ''}`,
{ method: 'DELETE' },
),
convertProject: (root: string) =>
apiFetch<ProjectMutation>('/projects/convert', {
method: 'POST',
body: JSON.stringify({ root }),
}),
/** skillsEnabled false adds a target that skillshare writes no skills to, and creates no skills folder. */
addTarget: (name: string, path: string, agentPath?: string, instructions?: TargetInstructionsSetup, skillsEnabled = true) =>
addTarget: (
name: string,
path: string,
agentPath?: string,
instructions?: TargetInstructionsSetup,
skillsEnabled = true,
) =>
apiFetch<{ success: boolean }>('/targets', {
method: 'POST',
body: JSON.stringify({ name, path, ...(agentPath && { agentPath }), ...(instructions && { instructions }), ...(!skillsEnabled && { skills_enabled: false }) }),
body: JSON.stringify({
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 }) }) }),
apiFetch<{ success: boolean }>('/targets', {
method: 'POST',
body: JSON.stringify({ name, agent, configDir, ...(cli && { cli }) }),
}),
removeTarget: (name: string) =>
apiFetch<{ success: boolean; warnings?: string[] }>(`/targets/${encodeURIComponent(name)}`, { method: 'DELETE' }),
apiFetch<{ success: boolean; warnings?: string[] }>(`/targets/${encodeURIComponent(name)}`, {
method: 'DELETE',
}),
/** skills_enabled false also removes the links skillshare made in the skills folder; detach says what went and what stayed. */
updateTarget: (name: string, opts: { include?: string[]; exclude?: string[]; mode?: string; target_naming?: string; agent_mode?: string; agent_include?: string[]; agent_exclude?: string[]; agent_extension?: string; skills_enabled?: boolean }) =>
updateTarget: (
name: string,
opts: {
include?: string[];
exclude?: string[];
mode?: string;
target_naming?: string;
agent_mode?: string;
agent_include?: string[];
agent_exclude?: string[];
agent_extension?: string;
skills_enabled?: boolean;
},
) =>
apiFetch<{ success: boolean; detach?: SkillsDetach }>(`/targets/${encodeURIComponent(name)}`, {
method: 'PATCH',
body: JSON.stringify(opts),
+4 -4
View File
@@ -3,19 +3,19 @@ export interface ExtraTarget {
path: string;
mode: string;
flatten: boolean;
extension?: string; // transform extension name; presence implies copy mode
extension?: string; // transform extension name; presence implies copy mode
as?: string; // single-file extra: target filename
include?: string[];
exclude?: string[];
file_count: number; // source files this target syncs after include/exclude
status: string; // "synced" | "drift" | "modified" | "not synced" | "no source"
status: string; // "synced" | "drift" | "modified" | "not synced" | "no source"
}
export interface Extra {
name: string;
file?: string; // single-file extra: the file in source_dir (AGENTS.md ones are shared instruction files)
source_dir: string;
source_type: "per-extra" | "extras_source" | "default";
source_type: 'per-extra' | 'extras_source' | 'default';
file_count: number;
source_exists: boolean;
targets: ExtraTarget[];
@@ -43,7 +43,7 @@ export interface ExtensionInfo {
}
export interface ExtraDiffItem {
action: string; // "create" | "update" | "prune"
action: string; // "create" | "update" | "prune"
file: string;
reason: string;
}
+5 -1
View File
@@ -27,7 +27,11 @@ export interface Project {
hasOwnConfig: boolean;
}
export type ProjectInput = Pick<Project, 'root' | 'targets' | 'skills' | 'agents'> & { name?: string; create?: boolean; /** Where a new project is saved; used only with `create`. */ storage?: ProjectStorage };
export type ProjectInput = Pick<Project, 'root' | 'targets' | 'skills' | 'agents'> & {
name?: string;
create?: boolean;
/** Where a new project is saved; used only with `create`. */ storage?: ProjectStorage;
};
export type ProjectStorage = 'shared' | 'local';
-1
View File
@@ -15,4 +15,3 @@ export interface UpdateStreamSummary {
errors: number;
skipped: number;
}
+18 -6
View File
@@ -2,7 +2,14 @@ import { apiFetch, BASE, createSSEStream } from './http';
import type { UpdateResultItem, UpdateStreamSummary } from './types/update';
export const updateApi = {
update: (opts: { name?: string; kind?: 'skill' | 'agent'; force?: boolean; all?: boolean; skipAudit?: boolean; branch?: string }) =>
update: (opts: {
name?: string;
kind?: 'skill' | 'agent';
force?: boolean;
all?: boolean;
skipAudit?: boolean;
branch?: string;
}) =>
apiFetch<{ results: UpdateResultItem[] }>('/update', {
method: 'POST',
body: JSON.stringify(opts),
@@ -19,10 +26,15 @@ export const updateApi = {
if (opts?.kind) params.set('kind', opts.kind);
if (opts?.force) params.set('force', 'true');
if (opts?.skipAudit) params.set('skipAudit', 'true');
return createSSEStream(`${BASE}/update/stream?${params.toString()}`, {
start: (d) => onStart(d.total),
result: onResult,
done: onDone,
}, onError, 'Update stream failed');
return createSSEStream(
`${BASE}/update/stream?${params.toString()}`,
{
start: (d) => onStart(d.total),
result: onResult,
done: onDone,
},
onError,
'Update stream failed',
);
},
};
+3679 -783
View File
File diff suppressed because it is too large Load Diff
+34 -4
View File
@@ -140,13 +140,43 @@ export default function AgentIcon({ target, size = 16 }: { target: string; size?
// universal is the cross-client ~/.agents/skills convention: the Agent Skills hexagon in a
// multi-color gradient so the shared path stands apart from single-vendor marks.
if (target === 'universal') {
return <span aria-hidden="true" className="inline-block shrink-0 bg-linear-135/oklch from-[#dc4538] via-[#f0b840] to-[#5cc98a] [clip-path:polygon(50%_2%,92%_26%,92%_74%,50%_98%,8%_74%,8%_26%)]" style={{ width: size, height: size }} />;
return (
<span
aria-hidden="true"
className="inline-block shrink-0 bg-linear-135/oklch from-[#dc4538] via-[#f0b840] to-[#5cc98a] [clip-path:polygon(50%_2%,92%_26%,92%_74%,50%_98%,8%_74%,8%_26%)]"
style={{ width: size, height: size }}
/>
);
}
if (colored[target]) return <img src={colored[target]} alt="" aria-hidden="true" width={size} height={size} className="shrink-0" />;
if (colored[target])
return (
<img
src={colored[target]}
alt=""
aria-hidden="true"
width={size}
height={size}
className="shrink-0"
/>
);
const src = mono[target];
if (!src) {
return <span aria-hidden="true" className="inline-flex items-center justify-center shrink-0 rounded-[var(--radius-sm)] bg-muted/60 font-bold uppercase text-pencil-light" style={{ width: size, height: size, fontSize: size * 0.55 }}>{target[0]}</span>;
return (
<span
aria-hidden="true"
className="inline-flex items-center justify-center shrink-0 rounded-[var(--radius-sm)] bg-muted/60 font-bold uppercase text-pencil-light"
style={{ width: size, height: size, fontSize: size * 0.55 }}
>
{target[0]}
</span>
);
}
const mask = `url("${src}") center / contain no-repeat`;
return <span aria-hidden="true" className="inline-block shrink-0 bg-current" style={{ width: size, height: size, mask, WebkitMask: mask }} />;
return (
<span
aria-hidden="true"
className="inline-block shrink-0 bg-current"
style={{ width: size, height: size, mask, WebkitMask: mask }}
/>
);
}
+14 -2
View File
@@ -5,9 +5,21 @@ interface BadgeProps {
dot?: boolean;
}
const variants = { default: '', success: 'ok', warning: 'warn', danger: 'bad', info: 'inf', accent: 'warn' };
const variants = {
default: '',
success: 'ok',
warning: 'warn',
danger: 'bad',
info: 'inf',
accent: 'warn',
};
export default function Badge({ children, variant = 'default', size = 'sm', dot = false }: BadgeProps) {
export default function Badge({
children,
variant = 'default',
size = 'sm',
dot = false,
}: BadgeProps) {
return (
<span className={`ss-tag ${variants[variant]} ${size === 'md' ? 'h-[22px] px-2 text-xs' : ''}`}>
{dot && <span className="w-1.5 h-1.5 rounded-full bg-current" />}
+6 -1
View File
@@ -40,7 +40,12 @@ export default function Button({
disabled={disabled || loading}
{...props}
>
{loading && (isLink ? <Spinner size="sm" className="text-current" /> : <span className="spin animate-spin" aria-hidden="true" />)}
{loading &&
(isLink ? (
<Spinner size="sm" className="text-current" />
) : (
<span className="spin animate-spin" aria-hidden="true" />
))}
{children}
</button>
);
+10 -1
View File
@@ -31,7 +31,16 @@ export default function Card({
return (
<div
onClick={onClick}
onKeyDown={interactive ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick!(); } } : undefined}
onKeyDown={
interactive
? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onClick!();
}
}
: undefined
}
role={interactive ? 'button' : undefined}
tabIndex={interactive ? 0 : undefined}
className={`ss-box relative ${paddingClasses[padding]} ${overflow ? '' : 'overflow-hidden'} ${variant === 'outlined' ? 'bg-transparent shadow-none' : ''} ${hover ? 'cursor-pointer transition-transform hover:-translate-y-px' : ''} ${className}`}
+10 -2
View File
@@ -39,9 +39,17 @@ export function Checkbox({
className="sr-only ss-chk-input"
/>
<span className={`ss-chk ${checked || indeterminate ? 'on' : ''}`}>
{indeterminate ? <Minus size={12} strokeWidth={3} /> : checked ? <Check size={12} strokeWidth={3} /> : null}
{indeterminate ? (
<Minus size={12} strokeWidth={3} />
) : checked ? (
<Check size={12} strokeWidth={3} />
) : null}
</span>
<span
className={hideLabel ? 'sr-only' : `${size === 'sm' ? 'text-[13px]' : 'text-sm'} text-ink`}
>
{label}
</span>
<span className={hideLabel ? 'sr-only' : `${size === 'sm' ? 'text-[13px]' : 'text-sm'} text-ink`}>{label}</span>
</label>
);
}
+88 -16
View File
@@ -19,17 +19,48 @@ const chrome = EditorView.theme({
'&.cm-focused': { outline: 'none' },
'.cm-scroller': { backgroundColor: 'inherit', fontFamily: 'var(--fm)', lineHeight: '1.65' },
'.cm-content': { padding: '10px 0', caretColor: 'var(--ink)' },
'.cm-gutters': { backgroundColor: 'inherit', border: 'none', color: 'var(--ink-3)', paddingLeft: '4px' },
'.cm-gutters': {
backgroundColor: 'inherit',
border: 'none',
color: 'var(--ink-3)',
paddingLeft: '4px',
},
'.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'transparent' },
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground, ::selection': { backgroundColor: 'var(--accent-bg) !important' },
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground, ::selection': {
backgroundColor: 'var(--accent-bg) !important',
},
'.cm-matchingBracket': { backgroundColor: 'var(--accent-bg)', outline: 'none' },
'.cm-placeholder': { color: 'var(--ink-3)' },
'.cm-lintRange-error': { backgroundImage: 'none', textDecoration: 'underline wavy var(--bad)', textUnderlineOffset: '3px' },
'.cm-lintRange-warning': { backgroundImage: 'none', textDecoration: 'underline wavy var(--ink-3)', textUnderlineOffset: '3px' },
'.cm-tooltip': { backgroundColor: 'var(--surface)', color: 'var(--ink)', border: '1px solid var(--line)', borderRadius: '8px', fontFamily: 'var(--f)', fontSize: '12.5px', overflow: 'hidden' },
'.cm-lintRange-error': {
backgroundImage: 'none',
textDecoration: 'underline wavy var(--bad)',
textUnderlineOffset: '3px',
},
'.cm-lintRange-warning': {
backgroundImage: 'none',
textDecoration: 'underline wavy var(--ink-3)',
textUnderlineOffset: '3px',
},
'.cm-tooltip': {
backgroundColor: 'var(--surface)',
color: 'var(--ink)',
border: '1px solid var(--line)',
borderRadius: '8px',
fontFamily: 'var(--f)',
fontSize: '12.5px',
overflow: 'hidden',
},
'.cm-tooltip-autocomplete > ul > li': { padding: '3px 10px !important', fontFamily: 'var(--fm)' },
'.cm-tooltip-autocomplete > ul > li[aria-selected]': { backgroundColor: 'var(--sel)', color: 'var(--sel-ink)' },
'.cm-completionDetail': { marginLeft: '12px', fontFamily: 'var(--f)', fontStyle: 'normal', color: 'var(--ink-3)' },
'.cm-tooltip-autocomplete > ul > li[aria-selected]': {
backgroundColor: 'var(--sel)',
color: 'var(--sel-ink)',
},
'.cm-completionDetail': {
marginLeft: '12px',
fontFamily: 'var(--f)',
fontStyle: 'normal',
color: 'var(--ink-3)',
},
'.cm-diagnostic': { padding: '6px 10px', borderLeft: 'none' },
'.cm-diagnostic-error': { color: 'var(--bad)' },
'.cm-diagnostic-warning': { color: 'var(--ink-2)' },
@@ -37,9 +68,24 @@ const chrome = EditorView.theme({
'.cm-marked .cm-gutterElement, .cm-gutterElement.cm-marked': { color: 'var(--warn)' },
// A noted line holds its floating note, so a note that does not fit drops under this line, not beside the next.
'.cm-noted': { display: 'flow-root' },
'.cm-block': { backgroundColor: 'var(--sunken)', boxShadow: 'inset 3px 0 0 color-mix(in srgb, var(--ink-3) 40%, transparent)' },
'.cm-block': {
backgroundColor: 'var(--sunken)',
boxShadow: 'inset 3px 0 0 color-mix(in srgb, var(--ink-3) 40%, transparent)',
},
// Floats right of the line's last row: with wrapping it drops below rather than overlap, and a long note is cut short.
'.cm-note': { float: 'right', maxWidth: '50%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingLeft: '16px', paddingRight: '16px', fontFamily: 'var(--f)', fontSize: '12px', color: 'var(--ink-3)', userSelect: 'none' },
'.cm-note': {
float: 'right',
maxWidth: '50%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
paddingLeft: '16px',
paddingRight: '16px',
fontFamily: 'var(--f)',
fontSize: '12px',
color: 'var(--ink-3)',
userSelect: 'none',
},
});
/** How lineDecor styles one line: block tints it, note adds muted text at its right end. */
@@ -51,7 +97,9 @@ class NoteWidget extends WidgetType {
super();
this.text = text;
}
eq(other: NoteWidget) { return other.text === this.text; }
eq(other: NoteWidget) {
return other.text === this.text;
}
toDOM() {
const el = document.createElement('span');
el.className = 'cm-note';
@@ -72,8 +120,10 @@ function decorateLines(lineDecor: (lines: string[]) => LineDecor[]) {
for (const [i, d] of lineDecor(lines).entries()) {
if (!d) continue;
const line = state.doc.line(i + 1);
if (d.block || d.note) ranges.push((d.block ? (d.note ? blockNoted : block) : noted).range(line.from));
if (d.note) ranges.push(Decoration.widget({ widget: new NoteWidget(d.note), side: 1 }).range(line.to));
if (d.block || d.note)
ranges.push((d.block ? (d.note ? blockNoted : block) : noted).range(line.from));
if (d.note)
ranges.push(Decoration.widget({ widget: new NoteWidget(d.note), side: 1 }).range(line.to));
}
return Decoration.set(ranges, true);
};
@@ -120,7 +170,23 @@ interface Props {
completions?: CompletionSource;
}
export default function CodeEditor({ value, onChange, lang = '', placeholder, ariaLabel, disabled = false, className = '', minHeight = '140px', maxHeight = '320px', markLine, lineDecor, wrap = false, fill = false, lint, completions }: Props) {
export default function CodeEditor({
value,
onChange,
lang = '',
placeholder,
ariaLabel,
disabled = false,
className = '',
minHeight = '140px',
maxHeight = '320px',
markLine,
lineDecor,
wrap = false,
fill = false,
lint,
completions,
}: Props) {
const extensions = useMemo(
() => [
chrome,
@@ -128,8 +194,12 @@ export default function CodeEditor({ value, onChange, lang = '', placeholder, ar
EditorView.contentAttributes.of({ 'aria-label': ariaLabel }),
...(lang === 'json' ? [json()] : []),
...(lang === 'yaml' ? [yaml()] : []),
...(lang === 'typescript' || lang === 'javascript' ? [javascript({ typescript: lang === 'typescript' })] : []),
...(lint ? [linter((view) => lint(view.state.doc.toString()), { delay: 250 }), lintGutter()] : []),
...(lang === 'typescript' || lang === 'javascript'
? [javascript({ typescript: lang === 'typescript' })]
: []),
...(lint
? [linter((view) => lint(view.state.doc.toString()), { delay: 250 }), lintGutter()]
: []),
...(completions ? [autocompletion({ override: [completions], icons: false })] : []),
...(markLine ? [markLines(markLine)] : []),
...(lineDecor ? [decorateLines(lineDecor)] : []),
@@ -138,7 +208,9 @@ export default function CodeEditor({ value, onChange, lang = '', placeholder, ar
[lang, ariaLabel, markLine, lineDecor, wrap, lint, completions],
);
return (
<div className={`ss-code !overflow-hidden !p-0 !whitespace-normal focus-within:!border-[var(--accent)] ${className}`}>
<div
className={`ss-code !overflow-hidden !p-0 !whitespace-normal focus-within:!border-[var(--accent)] ${className}`}
>
<CodeMirror
className={`bg-inherit ${fill ? 'h-full' : ''}`}
value={value}
+16 -4
View File
@@ -15,7 +15,14 @@ interface Props {
}
/** Read-only code with line numbers. Markdown wraps (prose lines are long); code scrolls sideways. */
export default function CodeView({ content, lang = '', line = 0, marks, tints, className = '' }: Props) {
export default function CodeView({
content,
lang = '',
line = 0,
marks,
tints,
className = '',
}: Props) {
const box = useRef<HTMLDivElement>(null);
const cur = useRef<HTMLDivElement>(null);
const lines = useMemo(() => highlightLines(content.replace(/\n$/, ''), lang), [content, lang]);
@@ -27,7 +34,8 @@ export default function CodeView({ content, lang = '', line = 0, marks, tints, c
useEffect(() => {
// Scroll the box only, so jumping to a line does not move the page
if (box.current && cur.current) box.current.scrollTop = cur.current.offsetTop - box.current.clientHeight / 2;
if (box.current && cur.current)
box.current.scrollTop = cur.current.offsetTop - box.current.clientHeight / 2;
}, [content, target]);
return (
@@ -39,8 +47,12 @@ export default function CodeView({ content, lang = '', line = 0, marks, tints, c
ref={i + 1 === target ? cur : undefined}
className={`grid grid-cols-[auto_minmax(0,1fr)] ${i + 1 === line || tinted.has(i + 1) ? 'cur' : marked.has(i + 1) ? 'mark' : ''}`}
>
<span className="ln text-right" style={{ minWidth: `${digits}ch` }}>{i + 1}</span>
<span className={wrap ? 'whitespace-pre-wrap [overflow-wrap:anywhere]' : ''}>{node}</span>
<span className="ln text-right" style={{ minWidth: `${digits}ch` }}>
{i + 1}
</span>
<span className={wrap ? 'whitespace-pre-wrap [overflow-wrap:anywhere]' : ''}>
{node}
</span>
</div>
))}
</div>
+173 -36
View File
@@ -1,6 +1,15 @@
import { useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowDownToLine, Bot, CircleCheck, CircleMinus, CircleX, Puzzle, RefreshCw, X } from 'lucide-react';
import {
ArrowDownToLine,
Bot,
CircleCheck,
CircleMinus,
CircleX,
Puzzle,
RefreshCw,
X,
} from 'lucide-react';
import { api, type LocalSkillInfo } from '../api/client';
import { queryKeys } from '../lib/queryKeys';
import { formatSize } from '../lib/format';
@@ -20,13 +29,24 @@ type Kind = 'skill' | 'agent';
type Outcome = { item: LocalSkillInfo; outcome: 'pulled' | 'skipped' | 'failed'; error?: string };
const keyOf = (i: LocalSkillInfo) => `${i.targetName}/${i.kind ?? 'skill'}/${i.name}`;
const displayName = (i: LocalSkillInfo) => (i.kind === 'agent' ? formatAgentDisplayName(i.name) : i.name);
const displayName = (i: LocalSkillInfo) =>
i.kind === 'agent' ? formatAgentDisplayName(i.name) : i.name;
const KindMark = ({ kind }: { kind?: string }) => (
<span className={`ss-cat sm ${kind === 'agent' ? 'agent' : 'skill'}`}>{kind === 'agent' ? <Bot size={14} /> : <Puzzle size={14} />}</span>
<span className={`ss-cat sm ${kind === 'agent' ? 'agent' : 'skill'}`}>
{kind === 'agent' ? <Bot size={14} /> : <Puzzle size={14} />}
</span>
);
/** Moves skills and agents created inside targets into the source. Without `target` it scans every target. */
export default function CollectDialog({ target, kind, onClose }: { target?: string; kind?: Kind; onClose: () => void }) {
export default function CollectDialog({
target,
kind,
onClose,
}: {
target?: string;
kind?: Kind;
onClose: () => void;
}) {
const t = useT();
const queryClient = useQueryClient();
const [scope, setScope] = useState<Kind | 'both'>(kind ?? 'both');
@@ -42,7 +62,10 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
staleTime: 0,
});
const source = useSkillsQuery();
const taken = useMemo(() => new Set((source.data?.resources ?? []).map((r) => `${r.kind}/${r.relPath}`)), [source.data]);
const taken = useMemo(
() => new Set((source.data?.resources ?? []).map((r) => `${r.kind}/${r.relPath}`)),
[source.data],
);
const conflict = (i: LocalSkillInfo) => taken.has(`${i.kind ?? 'skill'}/${i.name}`);
const groups = (scan.data?.targets ?? []).filter((g) => g.skills.length > 0);
@@ -64,12 +87,22 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
const outcomes: Outcome[] = [];
try {
// A name the source already has is only collected with force, which replaces the source copy.
for (const [group, force] of [[chosenItems.filter((i) => !conflict(i)), false], [chosenItems.filter(conflict), true]] as const) {
for (const [group, force] of [
[chosenItems.filter((i) => !conflict(i)), false],
[chosenItems.filter(conflict), true],
] as const) {
if (!group.length) continue;
const res = await api.collect({ skills: group.map((i) => ({ name: i.name, targetName: i.targetName, kind: i.kind })), force });
const res = await api.collect({
skills: group.map((i) => ({ name: i.name, targetName: i.targetName, kind: i.kind })),
force,
});
for (const item of group) {
const failure = res.failed?.[item.name];
outcomes.push(failure ? { item, outcome: 'failed', error: failure } : { item, outcome: res.pulled?.includes(item.name) ? 'pulled' : 'skipped' });
outcomes.push(
failure
? { item, outcome: 'failed', error: failure }
: { item, outcome: res.pulled?.includes(item.name) ? 'pulled' : 'skipped' },
);
}
}
setResults(outcomes);
@@ -88,23 +121,52 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
const count = (o: Outcome['outcome']) => results.filter((r) => r.outcome === o).length;
const pulled = count('pulled');
return (
<DialogShell open onClose={onClose} padding="none" ariaLabel={t('collectDialog.results')} className="!max-w-[560px]">
<DialogShell
open
onClose={onClose}
padding="none"
ariaLabel={t('collectDialog.results')}
className="!max-w-[560px]"
>
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{t('collectDialog.results')}</h2>
<p className="text-[13px] text-ink-2">{t('collectDialog.resultsSummary', { pulled, skipped: count('skipped'), failed: count('failed') })}</p>
<p className="text-[13px] text-ink-2">
{t('collectDialog.resultsSummary', {
pulled,
skipped: count('skipped'),
failed: count('failed'),
})}
</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose}><X size={16} /></button>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose}>
<X size={16} />
</button>
</div>
<div className="db">
<div className="ss-list !shadow-none">
{results.map(({ item, outcome, error: why }) => (
<div key={keyOf(item)} className="ss-r !min-h-11">
{outcome === 'pulled' ? <CircleCheck size={16} className="shrink-0 text-ok" /> : outcome === 'skipped' ? <CircleMinus size={16} className="shrink-0 text-ink-3" /> : <CircleX size={16} className="shrink-0 text-bad" />}
{outcome === 'pulled' ? (
<CircleCheck size={16} className="shrink-0 text-ok" />
) : outcome === 'skipped' ? (
<CircleMinus size={16} className="shrink-0 text-ink-3" />
) : (
<CircleX size={16} className="shrink-0 text-bad" />
)}
<KindMark kind={item.kind} />
<span className="min-w-0 flex-1 truncate font-mono text-[13px] font-semibold">{displayName(item)}</span>
<span className={`min-w-0 truncate text-[13px] ${outcome === 'failed' ? 'text-bad' : 'text-ink-2'}`} title={why}>
{outcome === 'pulled' ? t('collectDialog.pulled') : outcome === 'skipped' ? t('collectDialog.skipped') : t('collectDialog.failed', { error: why ?? '' })}
<span className="min-w-0 flex-1 truncate font-mono text-[13px] font-semibold">
{displayName(item)}
</span>
<span
className={`min-w-0 truncate text-[13px] ${outcome === 'failed' ? 'text-bad' : 'text-ink-2'}`}
title={why}
>
{outcome === 'pulled'
? t('collectDialog.pulled')
: outcome === 'skipped'
? t('collectDialog.skipped')
: t('collectDialog.failed', { error: why ?? '' })}
</span>
</div>
))}
@@ -112,22 +174,46 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
{pulled > 0 && <p className="text-[13px] text-ink-2">{t('collectDialog.pulledHint')}</p>}
</div>
<div className="df">
<Button variant="ghost" onClick={onClose}>{t('common.close')}</Button>
{pulled > 0 && <Button variant="primary" onClick={() => setSyncing(true)}><RefreshCw size={15} />{t('syncPreview.syncNowButton')}</Button>}
<Button variant="ghost" onClick={onClose}>
{t('common.close')}
</Button>
{pulled > 0 && (
<Button variant="primary" onClick={() => setSyncing(true)}>
<RefreshCw size={15} />
{t('syncPreview.syncNowButton')}
</Button>
)}
</div>
</DialogShell>
);
}
const title = target ? t('collectDialog.titleFrom', { name: target }) : t('collectDialog.titleAll');
const title = target
? t('collectDialog.titleFrom', { name: target })
: t('collectDialog.titleAll');
return (
<DialogShell open onClose={onClose} padding="none" preventClose={busy} ariaLabel={title} className="!max-w-[620px]">
<DialogShell
open
onClose={onClose}
padding="none"
preventClose={busy}
ariaLabel={title}
className="!max-w-[620px]"
>
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{title}</h2>
<p className="text-[13px] text-ink-2">{t(`collectDialog.subtitle.${kind ?? 'all'}`)}</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={busy}><X size={16} /></button>
<button
type="button"
className="ss-ib"
aria-label={t('common.close')}
onClick={onClose}
disabled={busy}
>
<X size={16} />
</button>
</div>
<div className="db">
{!kind && (
@@ -135,22 +221,44 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
<span className="text-[13px] text-ink-2">{t('collectDialog.lookFor')}</span>
<SegmentedControl
value={scope}
onChange={(v) => { setScope(v); setPicked(null); }}
options={[{ value: 'skill', label: 'Skills' }, { value: 'agent', label: 'Agents' }, { value: 'both', label: t('collectDialog.both') }]}
onChange={(v) => {
setScope(v);
setPicked(null);
}}
options={[
{ value: 'skill', label: 'Skills' },
{ value: 'agent', label: 'Agents' },
{ value: 'both', label: t('collectDialog.both') },
]}
/>
<span className="flex-1" />
<Button variant="secondary" size="sm" onClick={() => void scan.refetch()} loading={scan.isFetching} disabled={busy}>
<Button
variant="secondary"
size="sm"
onClick={() => void scan.refetch()}
loading={scan.isFetching}
disabled={busy}
>
{!scan.isFetching && <RefreshCw size={14} />}
{t('collectDialog.scanAgain')}
</Button>
</div>
)}
{scan.isPending ? (
<div className="flex items-center gap-2 text-[13px] text-ink-2"><Spinner size="sm" />{t('collectDialog.scanning')}</div>
<div className="flex items-center gap-2 text-[13px] text-ink-2">
<Spinner size="sm" />
{t('collectDialog.scanning')}
</div>
) : scan.error ? (
<div className="ss-note bad"><span className="flex-1">{scan.error.message}</span></div>
<div className="ss-note bad">
<span className="flex-1">{scan.error.message}</span>
</div>
) : items.length === 0 ? (
<div className="ss-note inf"><span className="flex-1">{t(target ? 'collectDialog.emptyTarget' : 'collectDialog.emptyAll')}</span></div>
<div className="ss-note inf">
<span className="flex-1">
{t(target ? 'collectDialog.emptyTarget' : 'collectDialog.emptyAll')}
</span>
</div>
) : (
<div className="ss-list max-h-[360px] overflow-y-auto !shadow-none">
<div className="ss-lh !px-4">
@@ -162,7 +270,9 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
disabled={busy}
/>
<span className="flex-1" />
<span>{t('collectDialog.selected', { selected: chosenItems.length, total: items.length })}</span>
<span>
{t('collectDialog.selected', { selected: chosenItems.length, total: items.length })}
</span>
</div>
{groups.map((g) => (
<div key={g.targetName} className="contents">
@@ -170,7 +280,9 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
<div className="ss-gh">
<AgentIcon target={g.targetName} size={18} />
<span className="font-semibold">{g.targetName}</span>
<span className="text-ink-3">{t('collectDialog.groupCount', { count: g.skills.length })}</span>
<span className="text-ink-3">
{t('collectDialog.groupCount', { count: g.skills.length })}
</span>
</div>
)}
{g.skills.map((item) => {
@@ -179,11 +291,26 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
const clash = conflict(item);
return (
<div key={key} className={`ss-r !min-h-11 ${on ? 'sel' : ''}`}>
<Checkbox label={displayName(item)} hideLabel checked={on} onChange={() => toggle(key)} disabled={busy} />
<Checkbox
label={displayName(item)}
hideLabel
checked={on}
onChange={() => toggle(key)}
disabled={busy}
/>
<KindMark kind={item.kind} />
<span className="w-[180px] shrink-0 truncate font-mono text-[13px] font-semibold" title={displayName(item)}>{displayName(item)}</span>
<span className={`min-w-0 flex-1 truncate text-[13px] ${clash && on ? 'text-warn' : 'text-ink-2'}`}>
{clash ? t(on ? 'collectDialog.replaces' : 'collectDialog.exists') : formatSize(item.size)}
<span
className="w-[180px] shrink-0 truncate font-mono text-[13px] font-semibold"
title={displayName(item)}
>
{displayName(item)}
</span>
<span
className={`min-w-0 flex-1 truncate text-[13px] ${clash && on ? 'text-warn' : 'text-ink-2'}`}
>
{clash
? t(on ? 'collectDialog.replaces' : 'collectDialog.exists')
: formatSize(item.size)}
</span>
</div>
);
@@ -192,14 +319,24 @@ export default function CollectDialog({ target, kind, onClose }: { target?: stri
))}
</div>
)}
{error && <div className="ss-note bad"><span className="flex-1">{error}</span></div>}
{items.length > 0 && <p className="text-[13px] leading-relaxed text-ink-2">{t('collectDialog.hint')}</p>}
{error && (
<div className="ss-note bad">
<span className="flex-1">{error}</span>
</div>
)}
{items.length > 0 && (
<p className="text-[13px] leading-relaxed text-ink-2">{t('collectDialog.hint')}</p>
)}
</div>
<div className="df">
<Button variant="ghost" onClick={onClose} disabled={busy}>{t('common.cancel')}</Button>
<Button variant="ghost" onClick={onClose} disabled={busy}>
{t('common.cancel')}
</Button>
<Button variant="primary" onClick={run} loading={busy} disabled={chosenItems.length === 0}>
{!busy && <ArrowDownToLine size={15} />}
{t(plural(`collectDialog.run.${noun}`, chosenItems.length), { count: chosenItems.length })}
{t(plural(`collectDialog.run.${noun}`, chosenItems.length), {
count: chosenItems.length,
})}
</Button>
</div>
</DialogShell>
+66 -17
View File
@@ -7,32 +7,56 @@ import { plural, useT } from '../i18n';
import { useInstallFromConfig } from '../hooks/useInstallFromConfig';
/** Rows finish one after another, so results read top to bottom. */
const stagger = (i: number): CSSProperties => ({ animationDelay: `${i * 50}ms`, animationFillMode: 'both' });
const stagger = (i: number): CSSProperties => ({
animationDelay: `${i * 50}ms`,
animationFillMode: 'both',
});
/** Install dialog section: what config records but the disk lacks, installed in one go. */
export default function ConfigInstallPanel() {
const t = useT();
const { entries, file, phase, done, failed, summary, contents, error, run, dismiss } = useInstallFromConfig();
const { entries, file, phase, done, failed, summary, contents, error, run, dismiss } =
useInstallFromConfig();
if (entries.length === 0) return null;
let icon = <FolderDown size={16} />;
let tone = '';
let title = t(plural('install.fromConfig.title', entries.length), { count: entries.length, file });
let title = t(plural('install.fromConfig.title', entries.length), {
count: entries.length,
file,
});
let sub = t('install.fromConfig.hint', { items: contents });
let action: ReactNode = <Button variant="primary" size="sm" onClick={run}><Download size={14} />{t('install.fromConfig.installAll')}</Button>;
let action: ReactNode = (
<Button variant="primary" size="sm" onClick={run}>
<Download size={14} />
{t('install.fromConfig.installAll')}
</Button>
);
if (phase === 'running') {
icon = <Download size={16} />;
title = t('install.fromConfig.installing', { file });
sub = t('install.audited');
action = null;
} else if (done) {
icon = failed.size ? <CircleAlert size={16} className="ss-pop" /> : <Check size={16} strokeWidth={2.6} className="ss-pop" />;
icon = failed.size ? (
<CircleAlert size={16} className="ss-pop" />
) : (
<Check size={16} strokeWidth={2.6} className="ss-pop" />
);
tone = failed.size ? 'warn' : 'ok';
title = summary;
sub = t(failed.size ? 'install.fromConfig.failedHint' : 'install.fromConfig.syncHint', { file });
action = failed.size
? <Button variant="secondary" size="sm" onClick={run}>{t('install.preview.retry')}</Button>
: <Button variant="secondary" size="sm" onClick={dismiss}>{t('install.done')}</Button>;
sub = t(failed.size ? 'install.fromConfig.failedHint' : 'install.fromConfig.syncHint', {
file,
});
action = failed.size ? (
<Button variant="secondary" size="sm" onClick={run}>
{t('install.preview.retry')}
</Button>
) : (
<Button variant="secondary" size="sm" onClick={dismiss}>
{t('install.done')}
</Button>
);
} else if (error) {
tone = 'bad';
icon = <CircleAlert size={16} />;
@@ -57,17 +81,42 @@ export default function ConfigInstallPanel() {
const bad = done && failed.has(e.name);
const row = phase === 'running' ? 'updating' : done && !bad ? 'flash' : '';
return (
<div key={e.name} className={`ss-r relative !min-h-10 ${row}`} style={done ? stagger(i) : undefined}>
{e.tracked
? <span className="w-[22px] grid place-items-center text-ink-2"><GitBranch size={15} /></span>
: <span className="ss-cat sm skill"><Puzzle size={13} /></span>}
<div
key={e.name}
className={`ss-r relative !min-h-10 ${row}`}
style={done ? stagger(i) : undefined}
>
{e.tracked ? (
<span className="w-[22px] grid place-items-center text-ink-2">
<GitBranch size={15} />
</span>
) : (
<span className="ss-cat sm skill">
<Puzzle size={13} />
</span>
)}
<span className="nm m truncate shrink-0 max-w-[55%]">{e.name}</span>
{e.tracked && <span className="ss-tag">tracked</span>}
<span className="min-w-0 flex-1 truncate font-mono text-xs text-ink-3">{parseRemoteURL(e.source)?.ownerRepo ?? e.source}</span>
<span className="min-w-0 flex-1 truncate font-mono text-xs text-ink-3">
{parseRemoteURL(e.source)?.ownerRepo ?? e.source}
</span>
<span className="w-5 grid place-items-center">
{done && (bad
? <X size={15} strokeWidth={2.6} className="ss-pop text-bad" style={stagger(i)} />
: <Check size={15} strokeWidth={2.6} className="ss-pop text-ok" style={stagger(i)} />)}
{done &&
(bad ? (
<X
size={15}
strokeWidth={2.6}
className="ss-pop text-bad"
style={stagger(i)}
/>
) : (
<Check
size={15}
strokeWidth={2.6}
className="ss-pop text-ok"
style={stagger(i)}
/>
))}
</span>
</div>
);
+13 -2
View File
@@ -32,7 +32,14 @@ export default function ConfirmDialog({
const resolvedCancelText = cancelText ?? t('common.cancel');
const resolvedConfirmText = confirmText ?? t('common.confirm');
return (
<DialogShell open={open} onClose={onCancel} maxWidth={wide ? '2xl' : 'md'} padding="none" preventClose={loading} ariaLabel={title}>
<DialogShell
open={open}
onClose={onCancel}
maxWidth={wide ? '2xl' : 'md'}
padding="none"
preventClose={loading}
ariaLabel={title}
>
<div className="dh">
<h2 className="ss-h2">{title}</h2>
</div>
@@ -43,7 +50,11 @@ export default function ConfirmDialog({
{resolvedCancelText}
</Button>
)}
<Button variant={variant === 'danger' ? 'danger' : 'primary'} onClick={onConfirm} loading={loading}>
<Button
variant={variant === 'danger' ? 'danger' : 'primary'}
onClick={onConfirm}
loading={loading}
>
{resolvedConfirmText}
</Button>
</div>
+2 -1
View File
@@ -17,7 +17,8 @@ interface CopyButtonProps {
strokeWidth?: number;
}
const baseClassName = 'inline-flex items-center gap-0.5 text-pencil-light hover:text-pencil transition-all duration-150 cursor-pointer shrink-0 active:scale-95 focus-visible:ring-2 focus-visible:ring-pencil/20 rounded-sm';
const baseClassName =
'inline-flex items-center gap-0.5 text-pencil-light hover:text-pencil transition-all duration-150 cursor-pointer shrink-0 active:scale-95 focus-visible:ring-2 focus-visible:ring-pencil/20 rounded-sm';
export default function CopyButton({
value,
+3 -1
View File
@@ -64,7 +64,9 @@ export default function DialogShell({
if (!open) return;
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = prev; };
return () => {
document.body.style.overflow = prev;
};
}, [open]);
if (!open) return null;
+12 -1
View File
@@ -1,7 +1,18 @@
/** The check that ends a run: drawn once, short arm first. Lucide's path runs the other way. */
export default function DrawnCheck({ size = 20 }: { size?: number }) {
return (
<svg className="ss-draw" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.6} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<svg
className="ss-draw"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2.6}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M4 12l5 5L20 6" />
</svg>
);
+2 -8
View File
@@ -26,14 +26,8 @@ export class ErrorBoundary extends Component<Props, State> {
<div className="flex items-start gap-3">
<AlertTriangle size={24} className="text-danger shrink-0 mt-0.5" />
<div>
<h2
className="text-xl font-bold text-pencil mb-2"
>
Something went wrong
</h2>
<p
className="text-pencil-light mb-4"
>
<h2 className="text-xl font-bold text-pencil mb-2">Something went wrong</h2>
<p className="text-pencil-light mb-4">
{this.state.error?.message || 'An unexpected error occurred.'}
</p>
<Button variant="secondary" onClick={() => window.location.reload()}>
+20 -4
View File
@@ -2,17 +2,31 @@ import { ArrowDown, Info } from 'lucide-react';
import { useT } from '../i18n';
import { SEV, type Finding } from '../lib/auditMessage';
export default function FindingList({ findings, header, showName }: { findings: Finding[]; header: string; showName: boolean }) {
export default function FindingList({
findings,
header,
showName,
}: {
findings: Finding[];
header: string;
showName: boolean;
}) {
const t = useT();
return (
<div className="ss-list !shadow-none max-h-[320px] !overflow-y-auto">
<div className="ss-lh"><span className="flex-1">{header}</span></div>
<div className="ss-lh">
<span className="flex-1">{header}</span>
</div>
{findings.map((f, i) => {
const where = [showName && f.name, f.where].filter(Boolean).join(' · ');
return (
<div key={i} className="ss-r !min-h-12">
<span className="w-[74px] shrink-0">
{f.severity ? <span className={`ss-sev ${SEV[f.severity]}`}>{f.severity}</span> : <Info size={15} className="text-ink-3" />}
{f.severity ? (
<span className={`ss-sev ${SEV[f.severity]}`}>{f.severity}</span>
) : (
<Info size={15} className="text-ink-3" />
)}
</span>
<div className="flex min-w-0 flex-1 flex-col gap-px">
<span className="break-words font-semibold">{f.message}</span>
@@ -23,7 +37,9 @@ export default function FindingList({ findings, header, showName }: { findings:
</span>
)}
{where && <span className="truncate font-mono text-xs text-ink-3">{where}</span>}
{f.snippet && <span className="truncate font-mono text-xs text-ink-3">{f.snippet}</span>}
{f.snippet && (
<span className="truncate font-mono text-xs text-ink-3">{f.snippet}</span>
)}
</div>
</div>
);
+25 -3
View File
@@ -34,12 +34,34 @@ interface FolderPickerProps {
}
/** Pick the source root or an existing folder; "New folder…" hands over to the caller's new-folder step. */
export default function FolderPicker({ label, kind, value, onChange, folders, rootCount, disabledPaths, onNewFolder, placeholder, caption, hint }: FolderPickerProps) {
export default function FolderPicker({
label,
kind,
value,
onChange,
folders,
rootCount,
disabledPaths,
onNewFolder,
placeholder,
caption,
hint,
}: FolderPickerProps) {
const t = useT();
const isNew = value !== null && value !== '' && !folders.some((f) => f.path === value);
const options: SelectOption[] = [
...folderOptions(t, kind, folders, rootCount, disabledPaths),
...(isNew ? [{ value: value!, label: value!, mono: true, icon: <Folder size={14} />, trailing: t('folderPicker.newTag') }] : []),
...(isNew
? [
{
value: value!,
label: value!,
mono: true,
icon: <Folder size={14} />,
trailing: t('folderPicker.newTag'),
},
]
: []),
{ value: NEW, label: t('folderPicker.new'), icon: <FolderPlus size={14} />, separated: true },
];
return (
@@ -49,7 +71,7 @@ export default function FolderPicker({ label, kind, value, onChange, folders, ro
value={value ?? NONE}
placeholder={placeholder}
options={options}
onChange={(v) => (v === NEW ? onNewFolder(isNew ? '' : value ?? '') : onChange(v))}
onChange={(v) => (v === NEW ? onNewFolder(isNew ? '' : (value ?? '')) : onChange(v))}
/>
{caption && <span className="hp">{caption}</span>}
{hint && <span className="hp font-mono">{hint}</span>}
+10 -2
View File
@@ -18,7 +18,11 @@ export function Input({ label, className = '', id, size = 'md', ...props }: Inpu
return (
<div className={label ? 'ss-fld' : undefined}>
{label && <label htmlFor={inputId}>{label}</label>}
<input id={inputId} className={`${control} ${size === 'sm' ? 'h-[30px] text-xs' : ''} ${className}`} {...props} />
<input
id={inputId}
className={`${control} ${size === 'sm' ? 'h-[30px] text-xs' : ''} ${className}`}
{...props}
/>
</div>
);
}
@@ -34,7 +38,11 @@ export function Textarea({ label, className = '', id, size = 'md', ...props }: T
return (
<div className={label ? 'ss-fld' : undefined}>
{label && <label htmlFor={inputId}>{label}</label>}
<textarea id={inputId} className={`${control} area resize-y ${size === 'sm' ? 'text-xs' : ''} ${className}`} {...props} />
<textarea
id={inputId}
className={`${control} area resize-y ${size === 'sm' ? 'text-xs' : ''} ${className}`}
{...props}
/>
</div>
);
}
+174 -41
View File
@@ -30,12 +30,12 @@ function renderDialog(initialTab: 'search' | 'url', onClose: () => void = () =>
return render(
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<I18nProvider>
<ToastProvider>
<InstallDialog kind="skill" initialTab={initialTab} onClose={onClose} />
</ToastProvider>
</I18nProvider>
</QueryClientProvider>
<I18nProvider>
<ToastProvider>
<InstallDialog kind="skill" initialTab={initialTab} onClose={onClose} />
</ToastProvider>
</I18nProvider>
</QueryClientProvider>
</MemoryRouter>,
);
}
@@ -48,8 +48,18 @@ describe('InstallDialog', () => {
});
it('installs only the skills left selected after discovery', async () => {
vi.mocked(api.discover).mockResolvedValue({ needsSelection: true, skills: [{ name: 'pdf', path: 'pdf' }, { name: 'docx', path: 'docx' }], agents: [] });
vi.mocked(api.installBatch).mockResolvedValue({ results: [{ name: 'docx', action: 'installed' }], summary: 'Installed 1' });
vi.mocked(api.discover).mockResolvedValue({
needsSelection: true,
skills: [
{ name: 'pdf', path: 'pdf' },
{ name: 'docx', path: 'docx' },
],
agents: [],
});
vi.mocked(api.installBatch).mockResolvedValue({
results: [{ name: 'docx', action: 'installed' }],
summary: 'Installed 1',
});
const user = userEvent.setup();
renderDialog('url');
@@ -58,16 +68,38 @@ describe('InstallDialog', () => {
await user.click(await screen.findByRole('checkbox', { name: 'pdf' }));
await user.click(screen.getByRole('button', { name: /install 1 skill$/i }));
await waitFor(() => expect(api.installBatch).toHaveBeenCalledWith(
expect.objectContaining({ source: 'anthropics/skills', skills: [expect.objectContaining({ name: 'docx' })] }),
));
await waitFor(() =>
expect(api.installBatch).toHaveBeenCalledWith(
expect.objectContaining({
source: 'anthropics/skills',
skills: [expect.objectContaining({ name: 'docx' })],
}),
),
);
});
it('leaves a skill unselected when it is installed under the source the server records for its host', async () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [{ name: 'pdf', kind: 'skill', flatName: 'pdf', relPath: 'pdf', sourcePath: '/s/pdf', isInRepo: false, source: 'https://gitlab.com/team/skills.git/pdf' }],
resources: [
{
name: 'pdf',
kind: 'skill',
flatName: 'pdf',
relPath: 'pdf',
sourcePath: '/s/pdf',
isInRepo: false,
source: 'https://gitlab.com/team/skills.git/pdf',
},
],
});
vi.mocked(api.discover).mockResolvedValue({
needsSelection: true,
skills: [
{ name: 'pdf', path: 'pdf' },
{ name: 'docx', path: 'docx' },
],
agents: [],
});
vi.mocked(api.discover).mockResolvedValue({ needsSelection: true, skills: [{ name: 'pdf', path: 'pdf' }, { name: 'docx', path: 'docx' }], agents: [] });
const user = userEvent.setup();
renderDialog('url');
@@ -79,8 +111,15 @@ describe('InstallDialog', () => {
});
it('reports a kept skill as already installed, not as installed', async () => {
vi.mocked(api.discover).mockResolvedValue({ needsSelection: true, skills: [{ name: 'deploy', path: 'deploy' }], agents: [] });
vi.mocked(api.installBatch).mockResolvedValue({ results: [{ name: 'deploy', action: 'skipped' }], summary: 'Installed 0 of 1 skills' });
vi.mocked(api.discover).mockResolvedValue({
needsSelection: true,
skills: [{ name: 'deploy', path: 'deploy' }],
agents: [],
});
vi.mocked(api.installBatch).mockResolvedValue({
results: [{ name: 'deploy', action: 'skipped' }],
summary: 'Installed 0 of 1 skills',
});
const onClose = vi.fn();
const user = userEvent.setup();
renderDialog('url', onClose);
@@ -94,16 +133,26 @@ describe('InstallDialog', () => {
});
it('force installs only the skill the audit blocked', async () => {
vi.mocked(api.discover).mockResolvedValue({ needsSelection: true, skills: [{ name: 'deploy', path: 'deploy' }], agents: [] });
vi.mocked(api.discover).mockResolvedValue({
needsSelection: true,
skills: [{ name: 'deploy', path: 'deploy' }],
agents: [],
});
vi.mocked(api.installBatch)
.mockResolvedValueOnce({
results: [{
name: 'deploy',
error: 'security audit failed — findings at/above HIGH detected:\n HIGH: Downloads and runs a remote script (scripts/setup.sh:14)\n "curl x | sh"\n\nUse --force to override',
}],
results: [
{
name: 'deploy',
error:
'security audit failed — findings at/above HIGH detected:\n HIGH: Downloads and runs a remote script (scripts/setup.sh:14)\n "curl x | sh"\n\nUse --force to override',
},
],
summary: '',
})
.mockResolvedValueOnce({ results: [{ name: 'deploy', action: 'installed' }], summary: 'Installed 1' });
.mockResolvedValueOnce({
results: [{ name: 'deploy', action: 'installed' }],
summary: 'Installed 1',
});
const user = userEvent.setup();
renderDialog('url');
@@ -113,9 +162,14 @@ describe('InstallDialog', () => {
expect(await screen.findByText('Downloads and runs a remote script')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /force install/i }));
await waitFor(() => expect(api.installBatch).toHaveBeenLastCalledWith(
expect.objectContaining({ force: true, skills: [expect.objectContaining({ name: 'deploy' })] }),
));
await waitFor(() =>
expect(api.installBatch).toHaveBeenLastCalledWith(
expect.objectContaining({
force: true,
skills: [expect.objectContaining({ name: 'deploy' })],
}),
),
);
});
it('reports an empty source instead of installing it when Find skills discovers nothing', async () => {
@@ -126,22 +180,43 @@ describe('InstallDialog', () => {
await user.type(screen.getByLabelText(/git url/i), 'acme/notes');
await user.click(screen.getByRole('button', { name: /find skills/i }));
expect(await screen.findByText('No skills or agents found in acme/notes. Nothing was installed.')).toBeInTheDocument();
expect(
await screen.findByText('No skills or agents found in acme/notes. Nothing was installed.'),
).toBeInTheDocument();
expect(api.install).not.toHaveBeenCalled();
});
it('installs just the skill a hub entry names', async () => {
vi.mocked(api.getHubConfig).mockResolvedValue({ hubs: [{ label: 'Acme', url: 'https://acme.dev/hub.json' }], default: 'Acme' });
vi.mocked(api.getHubConfig).mockResolvedValue({
hubs: [{ label: 'Acme', url: 'https://acme.dev/hub.json' }],
default: 'Acme',
});
vi.mocked(api.searchHub).mockResolvedValue({
results: [{ name: 'pdf', description: 'Read PDFs', source: 'anthropics/skills', skill: 'pdf', stars: 0, owner: 'anthropics', repo: 'skills' }],
results: [
{
name: 'pdf',
description: 'Read PDFs',
source: 'anthropics/skills',
skill: 'pdf',
stars: 0,
owner: 'anthropics',
repo: 'skills',
},
],
});
vi.mocked(api.discover).mockResolvedValue({
needsSelection: true,
skills: [{ name: 'pdf', path: 'pdf' }, { name: 'docx', path: 'docx' }],
skills: [
{ name: 'pdf', path: 'pdf' },
{ name: 'docx', path: 'docx' },
],
agents: [],
warnings: ['skipped git submodule "vendor/up"'],
});
vi.mocked(api.installBatch).mockResolvedValue({ results: [{ name: 'pdf', action: 'installed' }], summary: 'Installed 1' });
vi.mocked(api.installBatch).mockResolvedValue({
results: [{ name: 'pdf', action: 'installed' }],
summary: 'Installed 1',
});
const user = userEvent.setup();
renderDialog('search');
@@ -149,20 +224,48 @@ describe('InstallDialog', () => {
await user.type(screen.getByLabelText(/search skills/i), 'pdf{Enter}');
await user.click(await screen.findByRole('button', { name: /^install$/i }));
await waitFor(() => expect(api.installBatch).toHaveBeenCalledWith(
expect.objectContaining({ source: 'anthropics/skills', skills: [expect.objectContaining({ name: 'pdf' })] }),
));
await waitFor(() =>
expect(api.installBatch).toHaveBeenCalledWith(
expect.objectContaining({
source: 'anthropics/skills',
skills: [expect.objectContaining({ name: 'pdf' })],
}),
),
);
expect(api.searchHub).toHaveBeenCalledWith('pdf', 'https://acme.dev/hub.json');
expect(screen.getByText(/skipped git submodule "vendor\/up"/)).toBeInTheDocument();
});
it('shows a hub entry as installed when its skill is recorded under the source the server writes for its host', async () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [{ name: 'pdf', kind: 'skill', flatName: 'pdf', relPath: 'pdf', sourcePath: '/s/pdf', isInRepo: false, source: 'https://gitlab.com/team/skills.git/pdf' }],
resources: [
{
name: 'pdf',
kind: 'skill',
flatName: 'pdf',
relPath: 'pdf',
sourcePath: '/s/pdf',
isInRepo: false,
source: 'https://gitlab.com/team/skills.git/pdf',
},
],
});
vi.mocked(api.getHubConfig).mockResolvedValue({
hubs: [{ label: 'Acme', url: 'https://acme.dev/hub.json' }],
default: 'Acme',
});
vi.mocked(api.getHubConfig).mockResolvedValue({ hubs: [{ label: 'Acme', url: 'https://acme.dev/hub.json' }], default: 'Acme' });
vi.mocked(api.searchHub).mockResolvedValue({
results: [{ name: 'pdf', description: 'Read PDFs', source: 'https://gitlab.com/team/skills', skill: 'pdf', stars: 0, owner: 'team', repo: 'skills' }],
results: [
{
name: 'pdf',
description: 'Read PDFs',
source: 'https://gitlab.com/team/skills',
skill: 'pdf',
stars: 0,
owner: 'team',
repo: 'skills',
},
],
});
const user = userEvent.setup();
renderDialog('search');
@@ -176,11 +279,22 @@ describe('InstallDialog', () => {
it('sends the folder picked from the existing ones as `into`', async () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [{ name: 'demo', kind: 'skill', flatName: 'frontend__demo', relPath: 'frontend/demo', sourcePath: '/s/frontend/demo', isInRepo: false }],
resources: [
{
name: 'demo',
kind: 'skill',
flatName: 'frontend__demo',
relPath: 'frontend/demo',
sourcePath: '/s/frontend/demo',
isInRepo: false,
},
],
});
// jsdom has no scrollIntoView, which the dropdown calls on its focused option.
HTMLElement.prototype.scrollIntoView = vi.fn();
vi.mocked(api.install).mockResolvedValue({ skillName: 'team' } as Awaited<ReturnType<typeof api.install>>);
vi.mocked(api.install).mockResolvedValue({ skillName: 'team' } as Awaited<
ReturnType<typeof api.install>
>);
const user = userEvent.setup();
renderDialog('url');
@@ -191,14 +305,29 @@ describe('InstallDialog', () => {
await user.click(await screen.findByRole('option', { name: /^frontend/ }));
await user.click(screen.getByRole('button', { name: /install repo/i }));
await waitFor(() => expect(api.install).toHaveBeenCalledWith(expect.objectContaining({ source: 'acme/team-skills', into: 'frontend' })));
await waitFor(() =>
expect(api.install).toHaveBeenCalledWith(
expect.objectContaining({ source: 'acme/team-skills', into: 'frontend' }),
),
);
});
it('makes a new folder in the picked folder through the new-folder step', async () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [{ name: 'demo', kind: 'skill', flatName: 'frontend__demo', relPath: 'frontend/demo', sourcePath: '/s/frontend/demo', isInRepo: false }],
resources: [
{
name: 'demo',
kind: 'skill',
flatName: 'frontend__demo',
relPath: 'frontend/demo',
sourcePath: '/s/frontend/demo',
isInRepo: false,
},
],
});
vi.mocked(api.install).mockResolvedValue({ skillName: 'team' } as Awaited<ReturnType<typeof api.install>>);
vi.mocked(api.install).mockResolvedValue({ skillName: 'team' } as Awaited<
ReturnType<typeof api.install>
>);
HTMLElement.prototype.scrollIntoView = vi.fn();
const user = userEvent.setup();
renderDialog('url');
@@ -217,7 +346,11 @@ describe('InstallDialog', () => {
await user.click(screen.getByRole('button', { name: /use this folder/i }));
await user.click(screen.getByRole('button', { name: /install repo/i }));
await waitFor(() => expect(api.install).toHaveBeenCalledWith(expect.objectContaining({ into: 'frontend/office' })));
await waitFor(() =>
expect(api.install).toHaveBeenCalledWith(
expect.objectContaining({ into: 'frontend/office' }),
),
);
});
it('keeps "Use this folder" disabled while the name is not a legal folder name', async () => {
File diff suppressed because it is too large Load Diff
+21 -5
View File
@@ -12,11 +12,23 @@ interface KeyboardShortcutsModalProps {
export default function KeyboardShortcutsModal({ open, onClose }: KeyboardShortcutsModalProps) {
const t = useT();
const groups = [
{ labelKey: 'shortcuts.general', entries: SHORTCUT_ENTRIES.filter((e) => !e.keys.startsWith('g ')) },
{ labelKey: 'shortcuts.goTo', entries: SHORTCUT_ENTRIES.filter((e) => e.keys.startsWith('g ')) },
{
labelKey: 'shortcuts.general',
entries: SHORTCUT_ENTRIES.filter((e) => !e.keys.startsWith('g ')),
},
{
labelKey: 'shortcuts.goTo',
entries: SHORTCUT_ENTRIES.filter((e) => e.keys.startsWith('g ')),
},
];
return (
<DialogShell open={open} onClose={onClose} maxWidth="3xl" padding="none" ariaLabel={t('shortcuts.title')}>
<DialogShell
open={open}
onClose={onClose}
maxWidth="3xl"
padding="none"
ariaLabel={t('shortcuts.title')}
>
<div className="dh">
<h2 className="ss-h2">{t('shortcuts.title')}</h2>
<button type="button" className="ss-ib" onClick={onClose} aria-label={t('common.close')}>
@@ -48,11 +60,15 @@ export default function KeyboardShortcutsModal({ open, onClose }: KeyboardShortc
/** Renders a key combo like "g d" or "Mod+S" as key tags */
function ShortcutKeys({ keys }: { keys: string }) {
const parts = keys.startsWith('Mod+') ? [isMacOS() ? '⌘' : 'Ctrl', keys.slice(4)] : keys.split(' ');
const parts = keys.startsWith('Mod+')
? [isMacOS() ? '⌘' : 'Ctrl', keys.slice(4)]
: keys.split(' ');
return (
<span className="flex items-center gap-1">
{parts.map((part, i) => (
<kbd key={i} className="ss-tag min-w-6 justify-center">{part}</kbd>
<kbd key={i} className="ss-tag min-w-6 justify-center">
{part}
</kbd>
))}
</span>
);
+5 -2
View File
@@ -69,7 +69,8 @@ export default function LanguagePopover() {
ref={panelRef}
role="radiogroup"
aria-label={t('language.settings')}
{...menu.exitProps} className={`ss-menu absolute left-0 bottom-full mb-3 z-50 origin-bottom-left !w-[300px] max-w-[calc(100vw-6rem)] max-h-[calc(100dvh-8rem)] overflow-y-auto ${menu.motion}`}
{...menu.exitProps}
className={`ss-menu absolute left-0 bottom-full mb-3 z-50 origin-bottom-left !w-[300px] max-w-[calc(100vw-6rem)] max-h-[calc(100dvh-8rem)] overflow-y-auto ${menu.motion}`}
>
{localeOptions.map((entry) => {
const on = locale === entry.code;
@@ -85,7 +86,9 @@ export default function LanguagePopover() {
tabIndex={on ? 0 : -1}
>
<span className="whitespace-nowrap">{entry.nativeName}</span>
<span className="ml-auto text-xs text-ink-3 whitespace-nowrap">{english !== entry.nativeName ? t(`language.${entry.code}`) : ''}</span>
<span className="ml-auto text-xs text-ink-3 whitespace-nowrap">
{english !== entry.nativeName ? t(`language.${entry.code}`) : ''}
</span>
{on ? <Check size={14} /> : <span className="w-3.5" />}
</button>
);
+70 -18
View File
@@ -8,14 +8,27 @@ import Layout from './Layout';
vi.mock('../api/client', async (load) => {
const actual = await load<typeof import('../api/client')>();
return { ...actual, api: { ...actual.api, listTargets: vi.fn(), diffExtras: vi.fn(() => new Promise(() => {})), gitStatus: vi.fn(() => new Promise(() => {})) } };
return {
...actual,
api: {
...actual.api,
listTargets: vi.fn(),
diffExtras: vi.fn(() => new Promise(() => {})),
gitStatus: vi.fn(() => new Promise(() => {})),
},
};
});
vi.mock('../hooks/useSharedQueries', async (load) => ({
...await load<typeof import('../hooks/useSharedQueries')>(),
useOverviewQuery: () => ({}), useDiffQuery: () => ({}), useMcpQuery: () => ({}), useHooksQuery: () => ({}),
...(await load<typeof import('../hooks/useSharedQueries')>()),
useOverviewQuery: () => ({}),
useDiffQuery: () => ({}),
useMcpQuery: () => ({}),
useHooksQuery: () => ({}),
}));
vi.mock('../context/AppContext', () => ({ useAppContext: () => ({ isProjectMode: false }) }));
vi.mock('../hooks/useGlobalShortcuts', () => ({ useGlobalShortcuts: () => ({ modifierHeld: false }) }));
vi.mock('../hooks/useGlobalShortcuts', () => ({
useGlobalShortcuts: () => ({ modifierHeld: false }),
}));
vi.mock('../i18n', () => ({ useT: () => (key: string) => key }));
vi.mock('./tour', () => ({ useTour: () => ({ startTour: vi.fn() }) }));
vi.mock('./KeyboardShortcutsModal', () => ({ default: () => null }));
@@ -27,32 +40,71 @@ vi.mock('./ShortcutHUD', () => ({ default: () => null }));
vi.mock('./UpdateDialog', () => ({ default: () => null }));
it('shows account logos from default targets while all targets are pending', async () => {
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }));
vi.stubGlobal('matchMedia', () => ({
matches: false,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
}));
let resolveAll!: (value: Awaited<ReturnType<typeof api.listTargets>>) => void;
vi.mocked(api.listTargets).mockImplementation((scope) => scope === 'all'
? new Promise((resolve) => { resolveAll = resolve; })
: Promise.resolve({ targets: [{ name: 'codex-2', agent: 'codex' }], sourceSkillCount: 0 } as Awaited<ReturnType<typeof api.listTargets>>));
vi.mocked(api.listTargets).mockImplementation((scope) =>
scope === 'all'
? new Promise((resolve) => {
resolveAll = resolve;
})
: Promise.resolve({
targets: [{ name: 'codex-2', agent: 'codex' }],
sourceSkillCount: 0,
} as Awaited<ReturnType<typeof api.listTargets>>),
);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={client}>
<MemoryRouter>
<Routes><Route element={<Layout />}><Route path="/" element={<>
<div data-testid="account"><AgentIcon target="codex-2" /></div>
<div data-testid="project"><AgentIcon target="project@codex-2" /></div>
<div data-testid="codex"><AgentIcon target="codex" /></div>
<div data-testid="other"><AgentIcon target="project@other-account" /></div>
<div data-testid="claude"><AgentIcon target="claude" /></div>
</>} /></Route></Routes>
<Routes>
<Route element={<Layout />}>
<Route
path="/"
element={
<>
<div data-testid="account">
<AgentIcon target="codex-2" />
</div>
<div data-testid="project">
<AgentIcon target="project@codex-2" />
</div>
<div data-testid="codex">
<AgentIcon target="codex" />
</div>
<div data-testid="other">
<AgentIcon target="project@other-account" />
</div>
<div data-testid="claude">
<AgentIcon target="claude" />
</div>
</>
}
/>
</Route>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
const logo = screen.getByTestId('codex').querySelector('img')!.getAttribute('src');
await waitFor(() => expect(screen.getByTestId('account').querySelector('img')).toHaveAttribute('src', logo));
await waitFor(() =>
expect(screen.getByTestId('account').querySelector('img')).toHaveAttribute('src', logo),
);
expect(screen.getByTestId('project').querySelector('img')).toHaveAttribute('src', logo);
expect(api.listTargets).toHaveBeenCalledWith('all');
await act(async () => resolveAll({ targets: [{ name: 'other-account', agent: 'claude' }], sourceSkillCount: 0 } as Awaited<ReturnType<typeof api.listTargets>>));
await act(async () =>
resolveAll({
targets: [{ name: 'other-account', agent: 'claude' }],
sourceSkillCount: 0,
} as Awaited<ReturnType<typeof api.listTargets>>),
);
const claudeLogo = screen.getByTestId('claude').querySelector('img')!.getAttribute('src');
await waitFor(() => expect(screen.getByTestId('other').querySelector('img')).toHaveAttribute('src', claudeLogo));
await waitFor(() =>
expect(screen.getByTestId('other').querySelector('img')).toHaveAttribute('src', claudeLogo),
);
expect(screen.getByTestId('account').querySelector('img')).toHaveAttribute('src', logo);
vi.unstubAllGlobals();
});
+204 -66
View File
@@ -38,7 +38,13 @@ import { useTour } from './tour';
import UpdateDialog from './UpdateDialog';
import { useT } from '../i18n';
import { shortenHome } from '../lib/paths';
import { useDiffQuery, useHooksQuery, useMcpQuery, useOverviewQuery, useSyncedTargetsQuery } from '../hooks/useSharedQueries';
import {
useDiffQuery,
useHooksQuery,
useMcpQuery,
useOverviewQuery,
useSyncedTargetsQuery,
} from '../hooks/useSharedQueries';
interface NavItem {
to: string;
@@ -79,14 +85,21 @@ const navGroups: { labelKey?: string; items: NavItem[] }[] = [
labelKey: 'layout.group.maintain',
items: [
{ to: '/audit', icon: ShieldCheck, labelKey: 'layout.nav.audit' },
{ to: '/settings', icon: Settings, labelKey: 'layout.nav.settings', also: ['/config', '/backup', '/log', '/doctor'] },
{
to: '/settings',
icon: Settings,
labelKey: 'layout.nav.settings',
also: ['/config', '/backup', '/log', '/doctor'],
},
],
},
];
function isActive(item: NavItem, pathname: string): boolean {
if (item.to === '/') return pathname === '/';
return [item.to, ...(item.also ?? [])].some((p) => pathname === p || pathname.startsWith(`${p}/`));
return [item.to, ...(item.also ?? [])].some(
(p) => pathname === p || pathname.startsWith(`${p}/`),
);
}
export default function Layout() {
@@ -107,7 +120,9 @@ export default function Layout() {
useEffect(() => {
const desktop = window.matchMedia('(min-width: 768px)');
const onResize = () => { if (desktop.matches) setNavigationOpen(false); };
const onResize = () => {
if (desktop.matches) setNavigationOpen(false);
};
desktop.addEventListener('change', onResize);
return () => desktop.removeEventListener('change', onResize);
}, []);
@@ -118,70 +133,139 @@ export default function Layout() {
if (navigationOpen) closeNavigation();
setShortcutsOpen((v) => !v);
}, [navigationOpen, closeNavigation]);
const handleNavigate = useCallback((path: string) => {
if (navigationOpen) closeNavigation();
nav(path);
}, [navigationOpen, closeNavigation, nav]);
const { modifierHeld } = useGlobalShortcuts({ onToggleHelp: toggleShortcuts, onNavigate: handleNavigate });
const handleNavigate = useCallback(
(path: string) => {
if (navigationOpen) closeNavigation();
void nav(path);
},
[navigationOpen, closeNavigation, nav],
);
const { modifierHeld } = useGlobalShortcuts({
onToggleHelp: toggleShortcuts,
onNavigate: handleNavigate,
});
const { data: overview } = useOverviewQuery();
const version = overview?.version;
const home = isProjectMode ? projectRoot : overview?.configDir;
const counts = useNavCounts(isProjectMode);
const { data: targets } = useQuery({ queryKey: queryKeys.targets.all, queryFn: () => api.listTargets(), staleTime: staleTimes.targets });
const { data: targets } = useQuery({
queryKey: queryKeys.targets.all,
queryFn: () => api.listTargets(),
staleTime: staleTimes.targets,
});
// Shares the badge query, so this costs no request.
const { data: synced } = useSyncedTargetsQuery();
const targetAgents = useMemo(() => Object.fromEntries([...(synced?.targets ?? []), ...(targets?.targets ?? [])].flatMap((x) => (x.agent ? [[x.name, x.agent]] : []))), [synced, targets]);
const targetAgents = useMemo(
() =>
Object.fromEntries(
[...(synced?.targets ?? []), ...(targets?.targets ?? [])].flatMap((x) =>
x.agent ? [[x.name, x.agent]] : [],
),
),
[synced, targets],
);
const sidebar = (
<>
<div className="ss-wm">
<b>{t('app.name')}</b>
<svg className="ss-squig ss-only-playful" width="112" height="7" viewBox="0 0 112 7" aria-hidden="true">
<path d="M1 4 Q 8 0 15 4 T 29 4 T 43 4 T 57 4 T 71 4 T 85 4 T 99 4 T 111 4" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
</svg>
<div className="group flex items-center gap-1 min-w-0">
<span className="truncate" title={home}>{t(isProjectMode ? 'app.project' : 'app.global')}{home && ` · ${shortenHome(home)}`}</span>
{/* The label is truncated, so the tooltip is the only place the full path shows — copying saves retyping it. */}
{home && <CopyButton value={home} title={t('common.copyPath')} copiedLabel="" className="md:pointer-fine:opacity-0 group-hover:opacity-100 focus-visible:opacity-100" />}
</div>
</div>
<nav className="flex-1 min-h-0 overflow-y-auto -mx-1 px-1">
{navGroups.map((group, i) => {
const items = group.items.filter((item) => !(isProjectMode && item.hideInProject));
return (
<div key={i}>
{group.labelKey && <div className="ss-nvg">{t(group.labelKey)}</div>}
{items.map((item) => {
const Icon = item.icon;
const active = isActive(item, location.pathname);
return (
<Link key={item.to} to={item.to} onClick={() => { if (navigationOpen) closeNavigation(); }} className={`ss-nv ${active ? 'on' : ''}`} aria-current={active ? 'page' : undefined}>
<Icon size={16} />
<span>{t(item.labelKey)}</span>
{counts[item.to] > 0 && <span className="n">{counts[item.to]}</span>}
</Link>
);
})}
</div>
);
})}
</nav>
<div className="ss-sidefoot">
<span className="flex items-center gap-0.5">
<ThemePopover />
<LanguagePopover />
<button type="button" className="ss-ib" data-tour="shortcuts-btn" onClick={toggleShortcuts} aria-label={t('shortcuts.title')} title={t('shortcuts.title')} aria-keyshortcuts="?">
<Keyboard size={16} />
</button>
<button type="button" className="ss-ib" onClick={() => { if (navigationOpen) closeNavigation(); startTour(); }} aria-label={t('layout.tools.quickTour')} title={t('layout.tools.quickTour')}>
<Compass size={16} />
</button>
<div className="ss-wm">
<b>{t('app.name')}</b>
<svg
className="ss-squig ss-only-playful"
width="112"
height="7"
viewBox="0 0 112 7"
aria-hidden="true"
>
<path
d="M1 4 Q 8 0 15 4 T 29 4 T 43 4 T 57 4 T 71 4 T 85 4 T 99 4 T 111 4"
fill="none"
stroke="currentColor"
strokeWidth="2.2"
strokeLinecap="round"
/>
</svg>
<div className="group flex items-center gap-1 min-w-0">
<span className="truncate" title={home}>
{t(isProjectMode ? 'app.project' : 'app.global')}
{home && ` · ${shortenHome(home)}`}
</span>
{version && <span className="font-mono text-[11px] text-ink-3">{/^\d/.test(version) ? `v${version}` : version}</span>}
{/* The label is truncated, so the tooltip is the only place the full path shows — copying saves retyping it. */}
{home && (
<CopyButton
value={home}
title={t('common.copyPath')}
copiedLabel=""
className="md:pointer-fine:opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
/>
)}
</div>
</div>
<nav className="flex-1 min-h-0 overflow-y-auto -mx-1 px-1">
{navGroups.map((group, i) => {
const items = group.items.filter((item) => !(isProjectMode && item.hideInProject));
return (
<div key={i}>
{group.labelKey && <div className="ss-nvg">{t(group.labelKey)}</div>}
{items.map((item) => {
const Icon = item.icon;
const active = isActive(item, location.pathname);
return (
<Link
key={item.to}
to={item.to}
onClick={() => {
if (navigationOpen) closeNavigation();
}}
className={`ss-nv ${active ? 'on' : ''}`}
aria-current={active ? 'page' : undefined}
>
<Icon size={16} />
<span>{t(item.labelKey)}</span>
{counts[item.to] > 0 && <span className="n">{counts[item.to]}</span>}
</Link>
);
})}
</div>
);
})}
</nav>
<div className="ss-sidefoot">
<span className="flex items-center gap-0.5">
<ThemePopover />
<LanguagePopover />
<button
type="button"
className="ss-ib"
data-tour="shortcuts-btn"
onClick={toggleShortcuts}
aria-label={t('shortcuts.title')}
title={t('shortcuts.title')}
aria-keyshortcuts="?"
>
<Keyboard size={16} />
</button>
<button
type="button"
className="ss-ib"
onClick={() => {
if (navigationOpen) closeNavigation();
startTour();
}}
aria-label={t('layout.tools.quickTour')}
title={t('layout.tools.quickTour')}
>
<Compass size={16} />
</button>
</span>
{version && (
<span className="font-mono text-[11px] text-ink-3">
{/^\d/.test(version) ? `v${version}` : version}
</span>
)}
</div>
</>
);
@@ -189,15 +273,34 @@ export default function Layout() {
<div className="min-h-screen">
<aside className="ss-side fixed top-0 left-0 z-30 h-screen hidden md:flex">{sidebar}</aside>
<header className="flex items-center gap-3 px-4 py-3 border-b border-line bg-side md:hidden">
<button ref={menuButton} type="button" className="ss-ib" aria-label={t('layout.navigation')} aria-expanded={navigationOpen} aria-controls="mobile-navigation" onClick={() => setNavigationOpen(true)}>
<button
ref={menuButton}
type="button"
className="ss-ib"
aria-label={t('layout.navigation')}
aria-expanded={navigationOpen}
aria-controls="mobile-navigation"
onClick={() => setNavigationOpen(true)}
>
<Menu size={20} />
</button>
<b>{t('app.name')}</b>
</header>
<DialogShell open={navigationOpen} onClose={closeNavigation} ariaLabel={t('layout.navigation')} maxWidth="sm" padding="none" className="ss-side !w-full h-[calc(100dvh-2rem)]">
<DialogShell
open={navigationOpen}
onClose={closeNavigation}
ariaLabel={t('layout.navigation')}
maxWidth="sm"
padding="none"
className="ss-side !w-full h-[calc(100dvh-2rem)]"
>
<div id="mobile-navigation" className="flex flex-col flex-1 min-h-0">
<div className="flex justify-end">
<IconButton icon={<X size={18} />} label={t('common.close')} onClick={closeNavigation} />
<IconButton
icon={<X size={18} />}
label={t('common.close')}
onClick={closeNavigation}
/>
</div>
{sidebar}
</div>
@@ -205,7 +308,9 @@ export default function Layout() {
<main className="min-w-0 px-4 py-6 md:ml-[232px] md:px-12 md:py-10">
<div className="max-w-[1080px] mx-auto">
<TargetAgents.Provider value={targetAgents}><Outlet /></TargetAgents.Provider>
<TargetAgents.Provider value={targetAgents}>
<Outlet />
</TargetAgents.Provider>
</div>
</main>
@@ -226,18 +331,51 @@ const live = { refetchInterval: 15_000, refetchOnWindowFocus: true } as const;
function useNavCounts(isProjectMode: boolean): Record<string, number> {
const targets = useSyncedTargetsQuery(live);
const diff = useDiffQuery(live);
const extras = useQuery({ queryKey: queryKeys.extrasDiff(), queryFn: () => api.diffExtras(), staleTime: staleTimes.extras, ...live });
const extras = useQuery({
queryKey: queryKeys.extrasDiff(),
queryFn: () => api.diffExtras(),
staleTime: staleTimes.extras,
...live,
});
const mcp = useMcpQuery({ staleTime: staleTimes.extras, ...live });
const hooks = useHooksQuery({ staleTime: staleTimes.extras, ...live });
const git = useQuery({ queryKey: queryKeys.gitStatus, queryFn: () => api.gitStatus(), staleTime: staleTimes.gitStatus, enabled: !isProjectMode, ...live });
const git = useQuery({
queryKey: queryKeys.gitStatus,
queryFn: () => api.gitStatus(),
staleTime: staleTimes.gitStatus,
enabled: !isProjectMode,
...live,
});
// Scans are expensive, so the badge only reads one the Audit page already ran.
const auditSkills = useQuery<AuditAllResponse>({ queryKey: queryKeys.audit.all('skills'), queryFn: () => api.auditAll('skills'), enabled: false });
const auditAgents = useQuery<AuditAllResponse>({ queryKey: queryKeys.audit.all('agents'), queryFn: () => api.auditAll('agents'), enabled: false });
const auditSkills = useQuery<AuditAllResponse>({
queryKey: queryKeys.audit.all('skills'),
queryFn: () => api.auditAll('skills'),
enabled: false,
});
const auditAgents = useQuery<AuditAllResponse>({
queryKey: queryKeys.audit.all('agents'),
queryFn: () => api.auditAll('agents'),
enabled: false,
});
const status = git.data;
return {
'/sync': diff.data ? pendingCount(diff.data.diffs, targets.data?.targets ?? [], extras.data?.extras ?? [], mcp.data?.plan, hooks.data?.plan) : 0,
'/git': !status?.isRepo ? 0 : status.isDirty ? status.files.length : status.hasRemote ? status.ahead : 0,
'/sync': diff.data
? pendingCount(
diff.data.diffs,
targets.data?.targets ?? [],
extras.data?.extras ?? [],
mcp.data?.plan,
hooks.data?.plan,
)
: 0,
'/git': !status?.isRepo
? 0
: status.isDirty
? status.files.length
: status.hasRemote
? status.ahead
: 0,
'/audit': (auditSkills.data?.summary.failed ?? 0) + (auditAgents.data?.summary.failed ?? 0),
};
}
+10 -4
View File
@@ -2,12 +2,18 @@ import { render } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import MarkdownView from './MarkdownView';
const view = (md: string, breaks?: boolean) => render(<MarkdownView breaks={breaks}>{md}</MarkdownView>).container;
const view = (md: string, breaks?: boolean) =>
render(<MarkdownView breaks={breaks}>{md}</MarkdownView>).container;
describe('MarkdownView', () => {
it('renders HTML such as <details> but drops scripts and event handlers', () => {
const html = view('<details><summary>More</summary>\n\nhidden\n\n</details>\n\n<script>alert(1)</script>\n<img src="x" onerror="alert(1)">').innerHTML;
expect([html.includes('<details>'), html.includes('<script'), html.includes('onerror')]).toEqual([true, false, false]);
const html = view(
'<details><summary>More</summary>\n\nhidden\n\n</details>\n\n<script>alert(1)</script>\n<img src="x" onerror="alert(1)">',
).innerHTML;
expect([
html.includes('<details>'),
html.includes('<script'),
html.includes('onerror'),
]).toEqual([true, false, false]);
});
});
+142 -25
View File
@@ -1,3 +1,4 @@
import { scalarText } from '../lib/scalarText';
import { Fragment, isValidElement, useMemo, type ReactNode } from 'react';
import { Info, Lightbulb, MessageSquareWarning, OctagonAlert, TriangleAlert } from 'lucide-react';
import Markdown, { type Components, type Options } from 'react-markdown';
@@ -15,40 +16,92 @@ import SegmentedControl from './SegmentedControl';
const base: Components = {
p: ({ children }) => <p>{highlightArgs(children)}</p>,
li: ({ children, className, id }) => <li className={className} id={id}>{highlightArgs(children)}</li>,
li: ({ children, className, id }) => (
<li className={className} id={id}>
{highlightArgs(children)}
</li>
),
pre: ({ children }) => {
const code = isValidElement<{ className?: string; children?: ReactNode }>(children) ? children.props : undefined;
const code = isValidElement<{ className?: string; children?: ReactNode }>(children)
? children.props
: undefined;
const lang = code?.className?.match(/language-([\w+-]+)/)?.[1] ?? '';
const lines = highlightLines(String(code?.children ?? '').replace(/\n$/, ''), lang);
const lines = highlightLines(
(typeof code?.children === 'string' ? code.children : '').replace(/\n$/, ''),
lang,
);
return (
<div className="ss-pre">
{lang && <span className="lang">{lang}</span>}
<pre><code>{lines.map((l, i) => <Fragment key={i}>{i > 0 && '\n'}{l}</Fragment>)}</code></pre>
<pre>
<code>
{lines.map((l, i) => (
<Fragment key={i}>
{i > 0 && '\n'}
{l}
</Fragment>
))}
</code>
</pre>
</div>
);
},
// Links out open in a new tab so the dashboard stays; in-page ones (footnotes) keep their attributes.
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- node is react-markdown's syntax tree, not an <a> attribute
a: ({ node: _node, ...props }) => props.href?.startsWith('#') ? <a {...props} /> : <a {...props} target="_blank" rel="noopener noreferrer" />,
a: ({ node: _node, ...props }) =>
props.href?.startsWith('#') ? (
<a {...props} />
) : (
<a {...props} target="_blank" rel="noopener noreferrer" />
),
// Short inline code such as -g or --force never splits at its hyphen; long paths still wrap.
code: ({ className, children }) => <code className={typeof children === 'string' && children.length <= 24 ? `${className ?? ''} nw` : className}>{children}</code>,
table: ({ children }) => <div className="ss-tbl"><table>{children}</table></div>,
code: ({ className, children }) => (
<code
className={
typeof children === 'string' && children.length <= 24 ? `${className ?? ''} nw` : className
}
>
{children}
</code>
),
table: ({ children }) => (
<div className="ss-tbl">
<table>{children}</table>
</div>
),
blockquote: ({ children, ...props }) => {
const kind = (props as Record<string, unknown>)['data-alert'] as keyof typeof ALERTS | undefined;
const kind = (props as Record<string, unknown>)['data-alert'] as
| keyof typeof ALERTS
| undefined;
if (!kind) return <blockquote>{children}</blockquote>;
const Icon = ALERTS[kind];
return (
<blockquote className={`alert ${kind}`}>
<p className="alert-title"><Icon size={15} aria-hidden="true" />{kind[0].toUpperCase() + kind.slice(1)}</p>
<p className="alert-title">
<Icon size={15} aria-hidden="true" />
{kind[0].toUpperCase() + kind.slice(1)}
</p>
{children}
</blockquote>
);
},
};
const ALERTS = { note: Info, tip: Lightbulb, important: MessageSquareWarning, warning: TriangleAlert, caution: OctagonAlert };
const ALERTS = {
note: Info,
tip: Lightbulb,
important: MessageSquareWarning,
warning: TriangleAlert,
caution: OctagonAlert,
};
type HNode = { type: string; tagName?: string; value?: string; properties?: Record<string, unknown>; children?: HNode[] };
type HNode = {
type: string;
tagName?: string;
value?: string;
properties?: Record<string, unknown>;
children?: HNode[];
};
const ALERT_MARK = /^\[!(note|tip|important|warning|caution)\]/i;
/** GitHub alerts: a blockquote opening with [!NOTE] and the like gets data-alert, and the marker is dropped. */
@@ -62,7 +115,11 @@ function rehypeAlerts() {
if (!p?.children || !first || !m) return;
first.value = first.value!.slice(m[0].length);
const rest = p.children;
while (rest.length && (rest[0].tagName === 'br' || (rest[0].type === 'text' && !rest[0].value!.trim()))) rest.shift();
while (
rest.length &&
(rest[0].tagName === 'br' || (rest[0].type === 'text' && !rest[0].value!.trim()))
)
rest.shift();
if (rest[0]?.type === 'text') rest[0].value = rest[0].value!.trimStart();
if (!rest.length) node.children = node.children.filter((c) => c !== p);
node.properties = { ...node.properties, dataAlert: m[1].toLowerCase() };
@@ -73,7 +130,15 @@ function rehypeAlerts() {
type MNode = { type: string; value?: string; children?: MNode[]; data?: { hName?: string } };
const CONTAINER_OPEN = /^:::[ \t]*(\w+)[ \t]*(?:\n|$)/;
const CONTAINER_CLOSE = /(?:^|\n):::[ \t]*$/;
const CONTAINER_KIND: Record<string, string> = { note: 'NOTE', info: 'NOTE', tip: 'TIP', important: 'IMPORTANT', warning: 'WARNING', caution: 'CAUTION', danger: 'CAUTION' };
const CONTAINER_KIND: Record<string, string> = {
note: 'NOTE',
info: 'NOTE',
tip: 'TIP',
important: 'IMPORTANT',
warning: 'WARNING',
caution: 'CAUTION',
danger: 'CAUTION',
};
/** ::: warning … ::: containers (VitePress, Docusaurus) become the matching GitHub alert. */
function remarkContainers() {
@@ -86,15 +151,27 @@ function remarkContainers() {
if (!head || !m || !kind) continue;
const end = kids.findIndex((k, j) => {
const last = j >= i && k.type === 'paragraph' ? k.children?.at(-1) : undefined;
return last?.type === 'text' && CONTAINER_CLOSE.test(last.value!) && !(last === head && head.value!.trim() === m[0].trim());
return (
last?.type === 'text' &&
CONTAINER_CLOSE.test(last.value!) &&
!(last === head && head.value!.trim() === m[0].trim())
);
});
if (end === -1) continue;
head.value = head.value!.slice(m[0].length);
const last = kids[end].children!.at(-1)!;
last.value = last.value!.replace(CONTAINER_CLOSE, '');
const body = kids.slice(i, end + 1).map((k) => ({ ...k, children: k.children?.filter((c) => c.type !== 'text' || c.value) }))
const body = kids
.slice(i, end + 1)
.map((k) => ({ ...k, children: k.children?.filter((c) => c.type !== 'text' || c.value) }))
.filter((k) => k.type !== 'paragraph' || k.children?.length);
kids.splice(i, end - i + 1, { type: 'blockquote', children: [{ type: 'paragraph', children: [{ type: 'text', value: `[!${kind}]` }] }, ...body] });
kids.splice(i, end - i + 1, {
type: 'blockquote',
children: [
{ type: 'paragraph', children: [{ type: 'text', value: `[!${kind}]` }] },
...body,
],
});
}
};
}
@@ -116,7 +193,11 @@ function remarkInlineMarks() {
for (const m of c.value!.matchAll(INLINE_MARKS)) {
const g = m.slice(1).findIndex((x) => x !== undefined);
if (m.index > at) out.push({ type: 'text', value: c.value!.slice(at, m.index) });
out.push({ type: 'emphasis', data: { hName: INLINE_TAGS[g] }, children: [{ type: 'text', value: m[g + 1] }] });
out.push({
type: 'emphasis',
data: { hName: INLINE_TAGS[g] },
children: [{ type: 'text', value: m[g + 1] }],
});
at = m.index + m[0].length;
}
if (!out.length) return [c];
@@ -132,7 +213,8 @@ function rehypeLocalLinks() {
const visit = (node: HNode) => {
node.children?.forEach(visit);
const href = node.tagName === 'a' ? node.properties?.href : undefined;
if (typeof href === 'string' && href.startsWith('#') && !href.startsWith('#user-content-')) node.properties!.href = `#user-content-${href.slice(1)}`;
if (typeof href === 'string' && href.startsWith('#') && !href.startsWith('#user-content-'))
node.properties!.href = `#user-content-${href.slice(1)}`;
};
return visit;
}
@@ -148,7 +230,13 @@ function isYamlMap(text: string) {
}
const cell = (v: unknown): string =>
v == null ? '' : Array.isArray(v) ? v.map(cell).join(', ') : typeof v === 'object' ? JSON.stringify(v) : String(v);
v == null
? ''
: Array.isArray(v)
? v.map(cell).join(', ')
: typeof v === 'object'
? JSON.stringify(v)
: scalarText(v);
interface Props {
children: string;
@@ -163,9 +251,19 @@ interface Props {
// Raw HTML such as <details> renders, but sanitized: shown files can come from anyone's skills.
type PluggableList = NonNullable<Options['remarkPlugins']>;
const schema = { ...defaultSchema, tagNames: [...defaultSchema.tagNames!, 'mark'] };
const rehypePlugins = [rehypeRaw, [rehypeSanitize, schema], rehypeAlerts, rehypeLocalLinks] as PluggableList;
const rehypePlugins = [
rehypeRaw,
[rehypeSanitize, schema],
rehypeAlerts,
rehypeLocalLinks,
] as PluggableList;
// A single ~ is left for ~sub~, as markdown-it reads it; ~~strike~~ still works.
const remarkPlugins = [[remarkGfm, { singleTilde: false }], remarkGemoji, remarkContainers, remarkInlineMarks] as PluggableList;
const remarkPlugins = [
[remarkGfm, { singleTilde: false }],
remarkGemoji,
remarkContainers,
remarkInlineMarks,
] as PluggableList;
const remarkWithBreaks = [...remarkPlugins, remarkBreaks];
const remarkRehypeOptions = { clobberPrefix: '' };
@@ -177,12 +275,19 @@ function splitFrontmatter(md: string): { rows: string[][]; body: string } {
const rows = Object.entries(parsed.frontmatter).flatMap(([k, v]) =>
v && typeof v === 'object' && !Array.isArray(v)
? Object.entries(v).map(([sub, x]) => [`${k}.${sub}`, cell(x)])
: [[k, cell(v)]]);
: [[k, cell(v)]],
);
return { rows, body: parsed.body };
}
/** Rendered markdown. A frontmatter block at the top is shown as a key/value table, like GitHub does. */
export default function MarkdownView({ children, components, size, breaks, className = '' }: Props) {
export default function MarkdownView({
children,
components,
size,
breaks,
className = '',
}: Props) {
const { rows, body } = useMemo(() => splitFrontmatter(children), [children]);
return (
@@ -191,12 +296,24 @@ export default function MarkdownView({ children, components, size, breaks, class
<div className="ss-tbl fm">
<table>
<tbody>
{rows.map(([k, v]) => <tr key={k}><th>{k}</th><td>{v}</td></tr>)}
{rows.map(([k, v]) => (
<tr key={k}>
<th>{k}</th>
<td>{v}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<Markdown remarkPlugins={breaks ? remarkWithBreaks : remarkPlugins} rehypePlugins={rehypePlugins} remarkRehypeOptions={remarkRehypeOptions} components={{ ...base, ...components }}>{body}</Markdown>
<Markdown
remarkPlugins={breaks ? remarkWithBreaks : remarkPlugins}
rehypePlugins={rehypePlugins}
remarkRehypeOptions={remarkRehypeOptions}
components={{ ...base, ...components }}
>
{body}
</Markdown>
</div>
);
}
+30 -6
View File
@@ -22,13 +22,29 @@ interface NewFolderFieldsProps {
}
/** The new-folder step of the folder picker: where, what name, and the path and link names that come out. */
export default function NewFolderFields({ kind, folders, rootCount, disabledPaths, parent, name, skill, onParent, onName, onSubmit }: NewFolderFieldsProps) {
export default function NewFolderFields({
kind,
folders,
rootCount,
disabledPaths,
parent,
name,
skill,
onParent,
onName,
onSubmit,
}: NewFolderFieldsProps) {
const t = useT();
const path = newFolderPath(parent, name);
const invalid = name !== '' && path === null;
return (
<div className="flex flex-col gap-[18px]">
<Select label={t('folderPicker.inside')} value={parent} onChange={onParent} options={folderOptions(t, kind, folders, rootCount, disabledPaths)} />
<Select
label={t('folderPicker.inside')}
value={parent}
onChange={onParent}
options={folderOptions(t, kind, folders, rootCount, disabledPaths)}
/>
<div className="flex flex-col gap-1.5">
<Input
autoFocus
@@ -41,16 +57,24 @@ export default function NewFolderFields({ kind, folders, rootCount, disabledPath
aria-invalid={invalid}
aria-describedby="folder-name-rule"
/>
<span id="folder-name-rule" className={`text-xs ${invalid ? 'text-bad' : 'text-ink-3'}`}>{t('folderPicker.nameRule')}</span>
<span id="folder-name-rule" className={`text-xs ${invalid ? 'text-bad' : 'text-ink-3'}`}>
{t('folderPicker.nameRule')}
</span>
</div>
<div className="ss-list !shadow-none">
<div className="ss-r text-xs font-semibold text-ink-3">{t('folderPicker.result')}</div>
<div className="ss-r">
<span className="w-[88px] shrink-0 text-[13px] text-ink-2">{t('folderPicker.resultFolder')}</span>
<span className="min-w-0 truncate font-mono text-[13px] font-semibold">{path ?? '—'}</span>
<span className="w-[88px] shrink-0 text-[13px] text-ink-2">
{t('folderPicker.resultFolder')}
</span>
<span className="min-w-0 truncate font-mono text-[13px] font-semibold">
{path ?? '—'}
</span>
</div>
<div className="ss-r">
<span className="w-[88px] shrink-0 text-[13px] text-ink-2">{t('folderPicker.resultLink')}</span>
<span className="w-[88px] shrink-0 text-[13px] text-ink-2">
{t('folderPicker.resultLink')}
</span>
<span className="min-w-0 truncate font-mono text-[13px]">
{path ? linkPrefix(path) : '—'}
{path && (skill ?? <span className="text-ink-3">&lt;skill&gt;</span>)}
+18 -4
View File
@@ -18,7 +18,15 @@ interface PageHeaderProps {
mono?: boolean;
}
export default function PageHeader({ title, subtitle, actions, className = '', backTo, crumbs, mono }: PageHeaderProps) {
export default function PageHeader({
title,
subtitle,
actions,
className = '',
backTo,
crumbs,
mono,
}: PageHeaderProps) {
const t = useT();
return (
<div className={`ss-pgh flex flex-col gap-3 ${className}`}>
@@ -34,9 +42,13 @@ export default function PageHeader({ title, subtitle, actions, className = '', b
<Fragment key={i}>
{i > 0 && <ChevronRight size={13} />}
{c.to ? (
<Link to={c.to} className="hover:text-ink">{c.label}</Link>
<Link to={c.to} className="hover:text-ink">
{c.label}
</Link>
) : c.onClick ? (
<button type="button" className="cursor-pointer hover:text-ink" onClick={c.onClick}>{c.label}</button>
<button type="button" className="cursor-pointer hover:text-ink" onClick={c.onClick}>
{c.label}
</button>
) : (
<span aria-current="page">{c.label}</span>
)}
@@ -46,7 +58,9 @@ export default function PageHeader({ title, subtitle, actions, className = '', b
)}
<div className="ss-ph">
<div className="tt min-w-0">
<h1 className="ss-h1"><span className={mono ? 'm' : undefined}>{title}</span></h1>
<h1 className="ss-h1">
<span className={mono ? 'm' : undefined}>{title}</span>
</h1>
{subtitle && <p>{subtitle}</p>}
</div>
{actions && <div className="flex shrink-0 items-center gap-2">{actions}</div>}
+24 -4
View File
@@ -18,7 +18,13 @@ interface PaginationProps {
pageSize?: PageSizeConfig;
}
export default function Pagination({ page, totalPages, onPageChange, rangeText, pageSize }: PaginationProps) {
export default function Pagination({
page,
totalPages,
onPageChange,
rangeText,
pageSize,
}: PaginationProps) {
const t = useT();
return (
<div className="flex items-center justify-between pt-4 mt-4 [border-top:var(--sep)]">
@@ -37,11 +43,25 @@ export default function Pagination({ page, totalPages, onPageChange, rangeText,
</div>
<div className="ss-pager">
<button type="button" className="ss-ib" onClick={() => onPageChange(Math.max(0, page - 1))} disabled={page === 0} aria-label={t('pagination.previous')}>
<button
type="button"
className="ss-ib"
onClick={() => onPageChange(Math.max(0, page - 1))}
disabled={page === 0}
aria-label={t('pagination.previous')}
>
<ChevronLeft size={16} />
</button>
<span className="!cursor-default font-mono">{page + 1} / {totalPages}</span>
<button type="button" className="ss-ib" onClick={() => onPageChange(Math.min(totalPages - 1, page + 1))} disabled={page >= totalPages - 1} aria-label={t('pagination.next')}>
<span className="!cursor-default font-mono">
{page + 1} / {totalPages}
</span>
<button
type="button"
className="ss-ib"
onClick={() => onPageChange(Math.min(totalPages - 1, page + 1))}
disabled={page >= totalPages - 1}
aria-label={t('pagination.next')}
>
<ChevronRight size={16} />
</button>
</div>
+25 -5
View File
@@ -6,8 +6,18 @@ import { useState } from 'react';
* is given time to arrive, then the bar fades and its slot closes, so it never needs unmounting.
* `className` sets `--bar-gap` to the parent's gap, which the closed slot then takes back.
*/
export default function ProgressBar({ active, value, max = 100, label, className = '' }: {
active: boolean; value?: number; max?: number; label?: string; className?: string;
export default function ProgressBar({
active,
value,
max = 100,
label,
className = '',
}: {
active: boolean;
value?: number;
max?: number;
label?: string;
className?: string;
}) {
// A new run gets a new bar, so its fill starts empty instead of sliding back from the last run.
const [run, setRun] = useState(0);
@@ -21,10 +31,20 @@ export default function ProgressBar({ active, value, max = 100, label, className
if (active && counted !== (value !== undefined)) setCounted(value !== undefined);
const part = counted && max > 0 ? Math.min(Math.max((value ?? 0) / max, 0), 1) : 0;
return (
<span className={`ss-barslot ${active ? '' : 'shut'} ${className}`} aria-hidden={!active || undefined}>
<span
className={`ss-barslot ${active ? '' : 'shut'} ${className}`}
aria-hidden={!active || undefined}
>
<span>
<span key={run} className={`ss-bar ${counted ? '' : 'indet'} ${active ? '' : 'end'}`} role="progressbar"
aria-label={label} aria-valuemin={0} aria-valuemax={max} aria-valuenow={counted ? value : undefined}>
<span
key={run}
className={`ss-bar ${counted ? '' : 'indet'} ${active ? '' : 'end'}`}
role="progressbar"
aria-label={label}
aria-valuemin={0}
aria-valuemax={max}
aria-valuenow={counted ? value : undefined}
>
{counted && <i style={{ transform: `translateX(${(part - 1) * 100}%)` }} />}
</span>
</span>
+14 -2
View File
@@ -5,7 +5,15 @@ import type { ReactNode } from 'react';
* Grows a block in when it opens and keeps it, inert, while it shrinks away after it closes.
* The caller renders the children only while open; during the shrink the last ones stay on screen.
*/
export default function Reveal({ open, className = '', children }: { open: boolean; className?: string; children: ReactNode }) {
export default function Reveal({
open,
className = '',
children,
}: {
open: boolean;
className?: string;
children: ReactNode;
}) {
const [held, setHeld] = useState<ReactNode>(open ? children : null);
if (open && children !== held) setHeld(children);
useEffect(() => {
@@ -16,7 +24,11 @@ export default function Reveal({ open, className = '', children }: { open: boole
}, [open]);
if (!open && held == null) return null;
return (
<div className={`ss-collapse grow ${open ? '' : 'shut'} ${className}`} inert={!open} aria-hidden={!open || undefined}>
<div
className={`ss-collapse grow ${open ? '' : 'shut'} ${className}`}
inert={!open}
aria-hidden={!open || undefined}
>
<div>{open ? children : held}</div>
</div>
);
+7 -1
View File
@@ -17,7 +17,13 @@ export default function ScrollToTop({ threshold = 400 }: { threshold?: number })
if (!visible) return null;
const label = t('common.scrollToTop');
return (
<button type="button" className="ss-top animate-fade-in" aria-label={label} title={label} onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
<button
type="button"
className="ss-top animate-fade-in"
aria-label={label}
title={label}
onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
>
<ArrowUp size={18} />
</button>
);
+7 -1
View File
@@ -22,7 +22,13 @@ interface SegmentedControlProps<T extends string> {
className?: string;
}
export default function SegmentedControl<T extends string>({ value, onChange, options, colorFn, className = '' }: SegmentedControlProps<T>) {
export default function SegmentedControl<T extends string>({
value,
onChange,
options,
colorFn,
className = '',
}: SegmentedControlProps<T>) {
return (
<div ref={segSlide} className={`ss-seg flex-wrap ${className}`}>
{options.map((opt) => {
+316 -182
View File
@@ -81,7 +81,27 @@ interface DropdownPos {
bottom?: number;
}
export function Select({ label, ariaLabel, value = '', onChange, values, onChangeValues, placeholder, options, className = '', size = 'md', disabled = false, prefix, chip, align = 'start', columns = false, invalid = false, quiet = false, up = false, search }: SelectProps) {
export function Select({
label,
ariaLabel,
value = '',
onChange,
values,
onChangeValues,
placeholder,
options,
className = '',
size = 'md',
disabled = false,
prefix,
chip,
align = 'start',
columns = false,
invalid = false,
quiet = false,
up = false,
search,
}: SelectProps) {
const labelId = useId();
const listId = useId();
const [open, setOpen] = useState(false);
@@ -93,11 +113,17 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
const listRef = useRef<HTMLUListElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const needle = query.trim().toLowerCase();
const shown = needle ? options.filter((o) => o.label.toLowerCase().includes(needle) || o.value.toLowerCase().includes(needle)) : options;
const shown = needle
? options.filter(
(o) => o.label.toLowerCase().includes(needle) || o.value.toLowerCase().includes(needle),
)
: options;
const isOn = (v: string) => (values ? values.includes(v) : v === value);
const chosen = options.filter((o) => isOn(o.value));
const selectedLabel = values ? chosen.map((o) => o.label).join(', ') : chosen[0]?.label ?? value;
const selectedLabel = values
? chosen.map((o) => o.label).join(', ')
: (chosen[0]?.label ?? value);
// Options with descriptions need room to read; widen the popup to ~15rem
// (matching the dropdownWidth estimate below) so descriptions wrap nicely.
const hasDescriptions = options.some((o) => o.description);
@@ -110,11 +136,17 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
if (!triggerRef.current) return;
const rect = triggerRef.current.getBoundingClientRect();
const dropdownHeight = Math.min(options.length * 48, 256); // rough est, max 16rem
const minWidth = columns ? Math.max(rect.width, 520) : quiet ? Math.max(rect.width, 460) : hasDescriptions ? Math.max(rect.width, 240) : rect.width;
const minWidth = columns
? Math.max(rect.width, 520)
: quiet
? Math.max(rect.width, 460)
: hasDescriptions
? Math.max(rect.width, 240)
: rect.width;
// Vertical: prefer below, flip up if not enough space below but enough above.
const spaceBelow = window.innerHeight - rect.bottom;
const dropUp = up || spaceBelow < dropdownHeight + 8 && rect.top > dropdownHeight;
const dropUp = up || (spaceBelow < dropdownHeight + 8 && rect.top > dropdownHeight);
// Horizontal: left-align to the trigger (or right-align with align="end",
// so a wide menu grows leftward); clamp so the popup never overflows
@@ -125,7 +157,9 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
}
setPos({
...(align === 'end' ? { right: document.documentElement.clientWidth - rect.right } : { left }),
...(align === 'end'
? { right: document.documentElement.clientWidth - rect.right }
: { left }),
minWidth,
top: dropUp ? undefined : rect.bottom + 4,
bottom: dropUp ? window.innerHeight - rect.top + 4 : undefined,
@@ -162,8 +196,10 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
const handler = (e: MouseEvent) => {
const target = e.target as Node;
if (
triggerRef.current && !triggerRef.current.contains(target) &&
listRef.current && !listRef.current.contains(target) &&
triggerRef.current &&
!triggerRef.current.contains(target) &&
listRef.current &&
!listRef.current.contains(target) &&
!menuRef.current?.contains(target)
) {
setOpen(false);
@@ -182,142 +218,204 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
}
}, [open, focusIdx]);
const select = useCallback((val: string) => {
if (options.find((o) => o.value === val)?.disabled) return;
if (values) {
// Option order, so the saved list does not depend on the click order.
onChangeValues?.(options.map((o) => o.value).filter((v) => (v === val ? !values.includes(v) : values.includes(v))));
return;
}
onChange?.(val);
setOpen(false);
}, [onChange, onChangeValues, values, options]);
const select = useCallback(
(val: string) => {
if (options.find((o) => o.value === val)?.disabled) return;
if (values) {
// Option order, so the saved list does not depend on the click order.
onChangeValues?.(
options
.map((o) => o.value)
.filter((v) => (v === val ? !values.includes(v) : values.includes(v))),
);
return;
}
onChange?.(val);
setOpen(false);
},
[onChange, onChangeValues, values, options],
);
// Closing returns focus to the trigger when it was in the search box.
const close = useCallback(() => {
setOpen(false);
if (!search) return;
if (menuRef.current?.contains(document.activeElement)) triggerRef.current?.querySelector('button')?.focus();
if (menuRef.current?.contains(document.activeElement))
triggerRef.current?.querySelector('button')?.focus();
}, [search]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (!open) {
openMenu();
setFocusIdx(0);
} else {
setFocusIdx((i) => Math.min(i + 1, shown.length - 1));
}
break;
case 'ArrowUp':
e.preventDefault();
if (open) {
setFocusIdx((i) => Math.max(i - 1, 0));
}
break;
case 'Enter':
case ' ':
// Typing a space into the search box is text, not a pick.
if (e.key === ' ' && search && open) break;
e.preventDefault();
if (open && focusIdx >= 0 && shown[focusIdx]) {
select(shown[focusIdx].value);
} else {
openMenu();
setFocusIdx(Math.max(0, options.findIndex((o) => isOn(o.value))));
}
break;
case 'Escape':
// An open menu takes the key; the dialog around it stays.
if (open) e.stopPropagation();
close();
break;
case 'Tab':
// The menu sits outside the dialog, so Tab from the search box would leave it; close and move on from the trigger.
if (open && search) close();
break;
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- isOn reads value and values
}, [open, focusIdx, options, shown, search, value, values, select, openMenu, close]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (!open) {
openMenu();
setFocusIdx(0);
} else {
setFocusIdx((i) => Math.min(i + 1, shown.length - 1));
}
break;
case 'ArrowUp':
e.preventDefault();
if (open) {
setFocusIdx((i) => Math.max(i - 1, 0));
}
break;
case 'Enter':
case ' ':
// Typing a space into the search box is text, not a pick.
if (e.key === ' ' && search && open) break;
e.preventDefault();
if (open && focusIdx >= 0 && shown[focusIdx]) {
select(shown[focusIdx].value);
} else {
openMenu();
setFocusIdx(
Math.max(
0,
options.findIndex((o) => isOn(o.value)),
),
);
}
break;
case 'Escape':
// An open menu takes the key; the dialog around it stays.
if (open) e.stopPropagation();
close();
break;
case 'Tab':
// The menu sits outside the dialog, so Tab from the search box would leave it; close and move on from the trigger.
if (open && search) close();
break;
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- isOn reads value and values
},
[open, focusIdx, options, shown, search, value, values, select, openMenu, close],
);
const toggle = () => {
if (disabled) return;
if (open) { close(); }
else { openMenu(); setFocusIdx(options.findIndex((o) => isOn(o.value))); }
if (open) {
close();
} else {
openMenu();
setFocusIdx(options.findIndex((o) => isOn(o.value)));
}
};
const maxHeight = columns ? '20rem' : '16rem';
const menuClass = `ss-menu fixed z-[9999] !w-auto ${menu.motion} ${size === 'sm' ? 'text-xs' : 'text-[13px]'}`;
// At least as wide as the trigger; wider for description options so they
// wrap nicely. Bounded so long descriptions never stretch the dropdown
// across the page.
const menuStyle = pos ? {
left: pos.left,
right: pos.right,
top: pos.top,
bottom: pos.bottom,
minWidth: pos.minWidth,
transformOrigin: `${pos.bottom !== undefined ? 'bottom' : 'top'} ${pos.right !== undefined ? 'right' : 'left'}`,
maxWidth: columns ? 'min(40rem, calc(100vw - 1rem))' : quiet ? 'min(30rem, calc(100vw - 1rem))' : 'min(22rem, calc(100vw - 1rem))',
} : undefined;
const menuStyle = pos
? {
left: pos.left,
right: pos.right,
top: pos.top,
bottom: pos.bottom,
minWidth: pos.minWidth,
transformOrigin: `${pos.bottom !== undefined ? 'bottom' : 'top'} ${pos.right !== undefined ? 'right' : 'left'}`,
maxWidth: columns
? 'min(40rem, calc(100vw - 1rem))'
: quiet
? 'min(30rem, calc(100vw - 1rem))'
: 'min(22rem, calc(100vw - 1rem))',
}
: undefined;
const menuList = pos && (
<ul
ref={listRef}
id={listId}
role="listbox"
aria-label={search ? ariaLabel ?? label : undefined}
aria-multiselectable={values ? true : undefined}
{...(search ? {} : menu.exitProps)}
className={search ? 'flex min-h-0 flex-col overflow-auto' : `${menuClass} overflow-auto`}
style={search ? { maxHeight } : { ...menuStyle, maxHeight }}
>
{shown.map((opt, i) => {
const isSelected = isOn(opt.value);
const isFocused = i === focusIdx;
const heading = opt.group && opt.group !== shown[i - 1]?.group ? opt.group : '';
return (
<Fragment key={opt.value}>
{heading && <li role="presentation" className="px-2 pt-2 pb-1 text-xs font-semibold text-ink-3">{heading}</li>}
{opt.separated && <li role="presentation" className="mx-1.5 my-1 h-px shrink-0 bg-line-soft" />}
<li
role="option"
aria-selected={isSelected}
aria-disabled={opt.disabled || undefined}
className={`min-h-8 shrink-0 rounded-[7px] flex ${quiet ? 'items-start gap-2.5 p-2.5' : 'items-center gap-2 px-2 py-1.5'} ${opt.disabled ? 'cursor-not-allowed text-ink-3' : isFocused ? 'cursor-pointer bg-sel text-sel-ink' : isSelected || quiet ? 'cursor-pointer text-ink' : 'cursor-pointer text-ink-2'}`}
onMouseEnter={() => setFocusIdx(i)}
onMouseDown={(e) => { e.preventDefault(); select(opt.value); }}
<ul
ref={listRef}
id={listId}
role="listbox"
aria-label={search ? (ariaLabel ?? label) : undefined}
aria-multiselectable={values ? true : undefined}
{...(search ? {} : menu.exitProps)}
className={search ? 'flex min-h-0 flex-col overflow-auto' : `${menuClass} overflow-auto`}
style={search ? { maxHeight } : { ...menuStyle, maxHeight }}
>
{shown.map((opt, i) => {
const isSelected = isOn(opt.value);
const isFocused = i === focusIdx;
const heading = opt.group && opt.group !== shown[i - 1]?.group ? opt.group : '';
return (
<Fragment key={opt.value}>
{heading && (
<li role="presentation" className="px-2 pt-2 pb-1 text-xs font-semibold text-ink-3">
{heading}
</li>
)}
{opt.separated && (
<li role="presentation" className="mx-1.5 my-1 h-px shrink-0 bg-line-soft" />
)}
<li
role="option"
aria-selected={isSelected}
aria-disabled={opt.disabled || undefined}
className={`min-h-8 shrink-0 rounded-[7px] flex ${quiet ? 'items-start gap-2.5 p-2.5' : 'items-center gap-2 px-2 py-1.5'} ${opt.disabled ? 'cursor-not-allowed text-ink-3' : isFocused ? 'cursor-pointer bg-sel text-sel-ink' : isSelected || quiet ? 'cursor-pointer text-ink' : 'cursor-pointer text-ink-2'}`}
onMouseEnter={() => setFocusIdx(i)}
onMouseDown={(e) => {
e.preventDefault();
select(opt.value);
}}
>
<span
className={`w-4 shrink-0 flex items-center justify-center ${quiet ? 'h-5' : ''}`}
>
<span className={`w-4 shrink-0 flex items-center justify-center ${quiet ? 'h-5' : ''}`}>
{isSelected && <Check size={quiet ? 16 : size === 'sm' ? 12 : 14} />}
</span>
{opt.icon && <span className="flex shrink-0 items-center">{opt.icon}</span>}
{columns ? (
<>
<span className={`w-[160px] shrink-0 truncate font-mono ${isSelected ? 'font-medium' : ''}`}>{opt.label}</span>
<span className={`min-w-0 flex-1 truncate ${isFocused && !opt.disabled ? '' : 'text-ink-2'}`}>{opt.description}</span>
{opt.badge && <span className="ss-tag shrink-0 !font-sans">{opt.badge}</span>}
</>
) : (
{isSelected && <Check size={quiet ? 16 : size === 'sm' ? 12 : 14} />}
</span>
{opt.icon && <span className="flex shrink-0 items-center">{opt.icon}</span>}
{columns ? (
<>
<span
className={`w-[160px] shrink-0 truncate font-mono ${isSelected ? 'font-medium' : ''}`}
>
{opt.label}
</span>
<span
className={`min-w-0 flex-1 truncate ${isFocused && !opt.disabled ? '' : 'text-ink-2'}`}
>
{opt.description}
</span>
{opt.badge && <span className="ss-tag shrink-0 !font-sans">{opt.badge}</span>}
</>
) : (
<span className="flex-1 min-w-0">
<span className={`block truncate ${opt.mono ? 'font-mono' : ''} ${quiet ? `font-semibold leading-5 ${opt.mono ? 'text-[13px]' : 'text-sm'}` : isSelected ? 'font-medium' : ''}`}>
<span
className={`block truncate ${opt.mono ? 'font-mono' : ''} ${quiet ? `font-semibold leading-5 ${opt.mono ? 'text-[13px]' : 'text-sm'}` : isSelected ? 'font-medium' : ''}`}
>
{opt.label}
{opt.note && <span className="font-normal opacity-70"> {opt.note}</span>}
</span>
{opt.description && (
<span className={`block mt-0.5 ${quiet ? 'text-[13px] text-ink-2' : `text-xs ${isFocused && !opt.disabled ? 'opacity-70' : 'text-ink-3'}`}`}>
<span
className={`block mt-0.5 ${quiet ? 'text-[13px] text-ink-2' : `text-xs ${isFocused && !opt.disabled ? 'opacity-70' : 'text-ink-3'}`}`}
>
{opt.description}
</span>
)}
{opt.detail && <span className="mt-0.5 block truncate font-mono text-xs text-ink-3" title={opt.detailTitle}>{opt.detail}</span>}
{opt.detail && (
<span
className="mt-0.5 block truncate font-mono text-xs text-ink-3"
title={opt.detailTitle}
>
{opt.detail}
</span>
)}
</span>
)}
{opt.trailing && <span className={`shrink-0 text-xs ${isFocused && !opt.disabled ? 'opacity-70' : 'text-ink-3'}`}>{opt.trailing}</span>}
</li>
</Fragment>
);
})}
</ul>
)}
{opt.trailing && (
<span
className={`shrink-0 text-xs ${isFocused && !opt.disabled ? 'opacity-70' : 'text-ink-3'}`}
>
{opt.trailing}
</span>
)}
</li>
</Fragment>
);
})}
</ul>
);
const chipSet = chip && value !== chip.clearValue;
@@ -342,10 +440,19 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
aria-haspopup="listbox"
>
<span className={chipSet ? 'p shrink-0' : 'shrink-0'}>{prefix}</span>
{chipSet ? <span className="truncate">{selectedLabel}</span> : <ChevronDown size={13} strokeWidth={2} className="shrink-0" />}
{chipSet ? (
<span className="truncate">{selectedLabel}</span>
) : (
<ChevronDown size={13} strokeWidth={2} className="shrink-0" />
)}
</button>
{chipSet && (
<button type="button" className="x" aria-label={chip.clearLabel} onClick={() => onChange?.(chip.clearValue)}>
<button
type="button"
className="x"
aria-label={chip.clearLabel}
onClick={() => onChange?.(chip.clearValue)}
>
<X size={12} strokeWidth={2.4} />
</button>
)}
@@ -363,73 +470,100 @@ export function Select({ label, ariaLabel, value = '', onChange, values, onChang
aria-haspopup="listbox"
>
<span className="truncate">{chosen[0]?.triggerLabel ?? selectedLabel}</span>
<ChevronDown size={14} className={`shrink-0 text-ink-2 transition-transform duration-200 ${open ? 'rotate-180' : ''}`} />
<ChevronDown
size={14}
className={`shrink-0 text-ink-2 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
/>
</button>
) : (
<button
type="button"
disabled={disabled}
onClick={toggle}
onKeyDown={handleKeyDown}
className={`ss-inp w-full justify-between text-left outline-none ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${selectTriggerSizes[size]} ${open ? 'border-accent' : ''} ${invalid ? 'err' : ''}`}
role="combobox"
aria-invalid={invalid || undefined}
aria-labelledby={label ? labelId : undefined}
aria-label={label ? undefined : ariaLabel}
aria-expanded={open}
aria-haspopup="listbox"
>
<span className="flex items-center gap-1.5 min-w-0">
{prefix && <span className="text-ink-3 shrink-0">{prefix}</span>}
{chosen.some((o) => o.icon) && (
<span className={values ? 'ss-stack shrink-0' : 'flex shrink-0 items-center'}>
{chosen.slice(0, 6).map((o) => <span key={o.value} className={values ? 'ss-at' : 'flex items-center'}>{o.icon}</span>)}
<button
type="button"
disabled={disabled}
onClick={toggle}
onKeyDown={handleKeyDown}
className={`ss-inp w-full justify-between text-left outline-none ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${selectTriggerSizes[size]} ${open ? 'border-accent' : ''} ${invalid ? 'err' : ''}`}
role="combobox"
aria-invalid={invalid || undefined}
aria-labelledby={label ? labelId : undefined}
aria-label={label ? undefined : ariaLabel}
aria-expanded={open}
aria-haspopup="listbox"
>
<span className="flex items-center gap-1.5 min-w-0">
{prefix && <span className="text-ink-3 shrink-0">{prefix}</span>}
{chosen.some((o) => o.icon) && (
<span className={values ? 'ss-stack shrink-0' : 'flex shrink-0 items-center'}>
{chosen.slice(0, 6).map((o) => (
<span key={o.value} className={values ? 'ss-at' : 'flex items-center'}>
{o.icon}
</span>
))}
</span>
)}
<span
className={`truncate ${columns || chosen[0]?.mono ? 'font-mono' : ''} ${chosen.length === 0 && placeholder ? 'text-ink-3' : ''}`}
>
{chosen.length === 0 && placeholder ? placeholder : selectedLabel}
</span>
)}
<span className={`truncate ${columns || chosen[0]?.mono ? 'font-mono' : ''} ${chosen.length === 0 && placeholder ? 'text-ink-3' : ''}`}>{chosen.length === 0 && placeholder ? placeholder : selectedLabel}</span>
</span>
<ChevronDown
size={size === 'sm' ? 13 : 15}
strokeWidth={2}
className={`shrink-0 text-ink-3 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
/>
</button>
)}
{menu.shown && pos && createPortal(
search ? (
<div key={open ? 'open' : 'closing'} ref={menuRef} {...menu.exitProps} className={menuClass} style={menuStyle}>
<label className="mb-1 flex h-8 shrink-0 items-center gap-2 rounded-[7px] bg-sunken px-2 text-ink-3">
<Search size={14} aria-hidden className="shrink-0" />
<input
autoFocus
type="search"
value={query}
onChange={(e) => { setQuery(e.target.value); setFocusIdx(0); }}
onKeyDown={handleKeyDown}
placeholder={search.placeholder}
aria-label={search.placeholder}
aria-controls={listId}
className="min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-3 [&::-webkit-search-cancel-button]:appearance-none"
/>
{query && (
<button
type="button"
// Keep focus in the search box.
onMouseDown={(e) => e.preventDefault()}
onClick={() => { setQuery(''); setFocusIdx(0); }}
aria-label={search.clear}
className="grid size-5 shrink-0 cursor-pointer place-items-center rounded-[5px] text-ink-3 hover:text-ink"
>
<X size={13} aria-hidden />
</button>
)}
</label>
{menuList}
{shown.length === 0 && <p className="px-2 py-1.5 text-ink-3">{search.empty}</p>}
</div>
) : menuList,
document.body,
</span>
<ChevronDown
size={size === 'sm' ? 13 : 15}
strokeWidth={2}
className={`shrink-0 text-ink-3 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
/>
</button>
)}
{menu.shown &&
pos &&
createPortal(
search ? (
<div
key={open ? 'open' : 'closing'}
ref={menuRef}
{...menu.exitProps}
className={menuClass}
style={menuStyle}
>
<label className="mb-1 flex h-8 shrink-0 items-center gap-2 rounded-[7px] bg-sunken px-2 text-ink-3">
<Search size={14} aria-hidden className="shrink-0" />
<input
autoFocus
type="search"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setFocusIdx(0);
}}
onKeyDown={handleKeyDown}
placeholder={search.placeholder}
aria-label={search.placeholder}
aria-controls={listId}
className="min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-3 [&::-webkit-search-cancel-button]:appearance-none"
/>
{query && (
<button
type="button"
// Keep focus in the search box.
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
setQuery('');
setFocusIdx(0);
}}
aria-label={search.clear}
className="grid size-5 shrink-0 cursor-pointer place-items-center rounded-[5px] text-ink-3 hover:text-ink"
>
<X size={13} aria-hidden />
</button>
)}
</label>
{menuList}
{shown.length === 0 && <p className="px-2 py-1.5 text-ink-3">{search.empty}</p>}
</div>
) : (
menuList
),
document.body,
)}
</div>
);
}
+9 -18
View File
@@ -9,28 +9,15 @@ export default function Skeleton({ className = '', variant = 'text', style }: Sk
if (variant === 'circle') {
return (
<div
className={`${base} w-12 h-12 ${className}`}
style={{ borderRadius: '50%', ...style }}
/>
<div className={`${base} w-12 h-12 ${className}`} style={{ borderRadius: '50%', ...style }} />
);
}
if (variant === 'card') {
return (
<div
className={`${base} h-32 rounded-[var(--r-box)] ${className}`}
style={style}
/>
);
return <div className={`${base} h-32 rounded-[var(--r-box)] ${className}`} style={style} />;
}
return (
<div
className={`${base} h-4 rounded-[5px] ${className}`}
style={style}
/>
);
return <div className={`${base} h-4 rounded-[5px] ${className}`} style={style} />;
}
/** A full loading skeleton for a page */
@@ -86,10 +73,14 @@ export function SkillDetailSkeleton() {
</div>
<div className="flex flex-col gap-7">
<div className="ss-box space-y-3">
{Array.from({ length: 7 }, (_, i) => <Skeleton key={i} className="w-full h-4" style={{ animationDelay: `${i * 50}ms` }} />)}
{Array.from({ length: 7 }, (_, i) => (
<Skeleton key={i} className="w-full h-4" style={{ animationDelay: `${i * 50}ms` }} />
))}
</div>
<div className="ss-box space-y-3">
{Array.from({ length: 4 }, (_, i) => <Skeleton key={i} className="w-full h-8" style={{ animationDelay: `${i * 50}ms` }} />)}
{Array.from({ length: 4 }, (_, i) => (
<Skeleton key={i} className="w-full h-8" style={{ animationDelay: `${i * 50}ms` }} />
))}
</div>
</div>
</div>
+5 -1
View File
@@ -28,5 +28,9 @@ const config: Record<SourceType, { label: string; variant: 'default' | 'info' }>
export default function SourceBadge({ type, isInRepo, size = 'sm' }: SourceBadgeProps) {
const source = resolveSource(type, isInRepo);
const { label, variant } = config[source];
return <Badge variant={variant} size={size}>{label}</Badge>;
return (
<Badge variant={variant} size={size}>
{label}
</Badge>
);
}
+40 -6
View File
@@ -8,15 +8,49 @@ import Tooltip from './Tooltip';
* Opens the source config in the Config page at `section`, the top-level key the page manages; a separate
* source file (sources.mcp) has no editor there, so a click copies its path.
*/
export default function SourcePathButton({ path, configPath, section }: { path: string; configPath: string; section: string }) {
export default function SourcePathButton({
path,
configPath,
section,
}: {
path: string;
configPath: string;
section: string;
}) {
const t = useT();
const { toast } = useToast();
const label = <><FileCog size={15} />{path.split(/[\\/]/).pop()}</>;
const label = (
<>
<FileCog size={15} />
{path.split(/[\\/]/).pop()}
</>
);
return (
<Tooltip content={<><span className="font-sans">{t('mcp.source')}: </span><span className="font-mono">{path}</span></>}>
{path === configPath
? <Link to={`/config?section=${section}`} className="ss-btn ghost">{label}</Link>
: <button type="button" className="ss-btn ghost" aria-label={t('mcp.copySource')} onClick={() => { void navigator.clipboard?.writeText(path); toast(t('mcp.copied'), 'success'); }}>{label}</button>}
<Tooltip
content={
<>
<span className="font-sans">{t('mcp.source')}: </span>
<span className="font-mono">{path}</span>
</>
}
>
{path === configPath ? (
<Link to={`/config?section=${section}`} className="ss-btn ghost">
{label}
</Link>
) : (
<button
type="button"
className="ss-btn ghost"
aria-label={t('mcp.copySource')}
onClick={() => {
void navigator.clipboard?.writeText(path);
toast(t('mcp.copied'), 'success');
}}
>
{label}
</button>
)}
</Tooltip>
);
}
+117 -16
View File
@@ -21,17 +21,45 @@ const PANE = 'sticky top-6 max-h-[calc(100vh-11rem)]';
* flex item go below its content height, and it would be squashed instead of scrolled.
* `pageScroll` keeps the list in the page's own scroll, for a page that has more above it.
*/
export function RailLayout({ rail, children, pageScroll, className = '' }: { rail: ReactNode; children: ReactNode; pageScroll?: boolean; /** Extra classes on the grid, for a page that needs its own narrow-width layout. */ className?: string }) {
export function RailLayout({
rail,
children,
pageScroll,
className = '',
}: {
rail: ReactNode;
children: ReactNode;
pageScroll?: boolean;
/** Extra classes on the grid, for a page that needs its own narrow-width layout. */ className?: string;
}) {
return (
<div className={`grid grid-cols-[minmax(0,1fr)_320px] items-start gap-8 ${className}`}>
<div className={pageScroll ? 'flex min-w-0 flex-col gap-3' : `${PANE} -m-2 flex min-w-0 flex-col gap-3 overflow-y-auto p-2 [&>*]:shrink-0`}>{children}</div>
<div
className={
pageScroll
? 'flex min-w-0 flex-col gap-3'
: `${PANE} -m-2 flex min-w-0 flex-col gap-3 overflow-y-auto p-2 [&>*]:shrink-0`
}
>
{children}
</div>
<aside className={`${PANE} flex flex-col gap-7`}>{rail}</aside>
</div>
);
}
/** A titled part of the rail. The title stays; the groups under it take the height that is left and scroll. */
export function RailSection({ title, count, action, children }: { title: string; count: number; action?: ReactNode; children: ReactNode }) {
export function RailSection({
title,
count,
action,
children,
}: {
title: string;
count: number;
action?: ReactNode;
children: ReactNode;
}) {
return (
<div className="flex min-h-0 flex-col gap-3.5">
<div className="flex min-h-6 items-center gap-2">
@@ -45,15 +73,28 @@ export function RailSection({ title, count, action, children }: { title: string;
}
/** `warn` tints the box. It is the only colour in the rail, so pending work is seen first. `plain` marks pending work without colour. */
export function SyncBox({ tone, state, children }: { tone: 'ok' | 'warn' | 'busy' | 'plain'; state: string; children: ReactNode }) {
export function SyncBox({
tone,
state,
children,
}: {
tone: 'ok' | 'warn' | 'busy' | 'plain';
state: string;
children: ReactNode;
}) {
const t = useT();
return (
<div className={`ss-box flex shrink-0 flex-col gap-3 ${tone === 'warn' ? 'bg-warn-bg' : ''}`}>
<div className="flex items-center justify-between gap-2">
<h3 className="text-[15px] font-semibold">{t('sync.title')}</h3>
{tone === 'busy'
? <span className="flex items-center gap-1.5 text-[13px] text-ink-3"><Spinner size="sm" />{state}</span>
: <span className={`ss-st ${tone}`}>{state}</span>}
{tone === 'busy' ? (
<span className="flex items-center gap-1.5 text-[13px] text-ink-3">
<Spinner size="sm" />
{state}
</span>
) : (
<span className={`ss-st ${tone}`}>{state}</span>
)}
</div>
{children}
</div>
@@ -61,10 +102,25 @@ export function SyncBox({ tone, state, children }: { tone: 'ok' | 'warn' | 'busy
}
/** What Sync will do, or did, to one Agent. `word` is the CLI's own term, so it stays English. */
export function RailLine({ name, agent, word, bad }: { name: string; agent: string; word: string; bad?: boolean }) {
export function RailLine({
name,
agent,
word,
bad,
}: {
name: string;
agent: string;
word: string;
bad?: boolean;
}) {
return (
<div className="flex items-baseline gap-1.5 text-[13px] text-ink-2">
<span className="max-w-[45%] shrink-0 truncate font-mono text-[12.5px] font-semibold text-ink" title={name}>{name}</span>
<span
className="max-w-[45%] shrink-0 truncate font-mono text-[12.5px] font-semibold text-ink"
title={name}
>
{name}
</span>
<span className="min-w-0 flex-1 truncate">→ {agent}</span>
<span className={`shrink-0 font-mono text-xs ${bad ? 'text-bad' : 'text-ink'}`}>{word}</span>
</div>
@@ -72,7 +128,19 @@ export function RailLine({ name, agent, word, bad }: { name: string; agent: stri
}
/** A labelled run of rows. Groups are told apart by a separator and a small label, not a box each. */
export function RailGroup({ label, count, right, foot, children }: { label: string; count?: number; right?: ReactNode; foot?: string; children?: ReactNode }) {
export function RailGroup({
label,
count,
right,
foot,
children,
}: {
label: string;
count?: number;
right?: ReactNode;
foot?: string;
children?: ReactNode;
}) {
return (
<div className="flex flex-col gap-1.5 pt-3.5 [border-top:var(--sep)] first:pt-0 first:[border-top:0]">
<div className="flex min-h-5 items-center gap-1.5 text-xs font-semibold text-ink-3">
@@ -91,13 +159,33 @@ export function RailGroup({ label, count, right, foot, children }: { label: stri
* until one is asked about. `right` sits inside that button, so it must not be interactive.
* `path` shows in full under the name, wrapping instead of being cut short.
*/
export function RailRow({ target, label, dim, sub, path, right, detail }: { target: string; label: string; dim?: boolean; sub?: string; path?: string; right?: ReactNode; detail?: ReactNode }) {
export function RailRow({
target,
label,
dim,
sub,
path,
right,
detail,
}: {
target: string;
label: string;
dim?: boolean;
sub?: string;
path?: string;
right?: ReactNode;
detail?: ReactNode;
}) {
const [open, setOpen] = useState(false);
const head = (
<>
<span className={`ss-at !h-[22px] !w-[22px] !rounded-md ${dim ? 'opacity-55' : ''}`}><AgentIcon target={target} size={13} /></span>
<span className={`ss-at !h-[22px] !w-[22px] !rounded-md ${dim ? 'opacity-55' : ''}`}>
<AgentIcon target={target} size={13} />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-px">
<span className={`truncate text-[13.5px] font-medium ${dim ? 'text-ink-2' : ''}`}>{label}</span>
<span className={`truncate text-[13.5px] font-medium ${dim ? 'text-ink-2' : ''}`}>
{label}
</span>
{sub && !open && <span className="truncate text-xs text-ink-3">{sub}</span>}
{path && <span className="break-all font-mono text-xs text-ink-3">{path}</span>}
</span>
@@ -107,11 +195,24 @@ export function RailRow({ target, label, dim, sub, path, right, detail }: { targ
if (!detail) return <div className="flex min-h-8 items-center gap-2.5 py-1">{head}</div>;
return (
<>
<button type="button" aria-expanded={open} aria-label={label} className="group flex min-h-8 w-full items-center gap-2.5 py-1 text-left" onClick={() => setOpen(!open)}>
<button
type="button"
aria-expanded={open}
aria-label={label}
className="group flex min-h-8 w-full items-center gap-2.5 py-1 text-left"
onClick={() => setOpen(!open)}
>
{head}
<ChevronDown size={14} className={`shrink-0 text-ink-3 ${open ? 'rotate-180' : 'opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100'}`} />
<ChevronDown
size={14}
className={`shrink-0 text-ink-3 ${open ? 'rotate-180' : 'opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100'}`}
/>
</button>
{open && <div className="mb-2 ml-8 mt-0.5 flex flex-col items-start gap-1.5 rounded-md bg-sunken px-3 py-2.5 text-[12.5px] leading-relaxed text-ink-2">{detail}</div>}
{open && (
<div className="mb-2 ml-8 mt-0.5 flex flex-col items-start gap-1.5 rounded-md bg-sunken px-3 py-2.5 text-[12.5px] leading-relaxed text-ink-2">
{detail}
</div>
)}
</>
);
}
+13 -10
View File
@@ -15,16 +15,19 @@ interface StreamProgressBarProps {
}
export default function StreamProgressBar({
count, total, startTime,
icon: Icon, iconClassName = 'animate-spin',
labelDiscovering, labelRunning, units,
count,
total,
startTime,
icon: Icon,
iconClassName = 'animate-spin',
labelDiscovering,
labelRunning,
units,
}: StreamProgressBarProps) {
const t = useT();
const pct = total > 0 ? Math.min((count / total) * 100, 100) : 0;
const elapsed = (Date.now() - startTime) / 1000;
const eta = count > 0 && pct < 100
? Math.round((elapsed / count) * (total - count))
: null;
const eta = count > 0 && pct < 100 ? Math.round((elapsed / count) * (total - count)) : null;
return (
<Card variant="outlined">
@@ -37,9 +40,7 @@ export default function StreamProgressBar({
</span>
</div>
{total > 0 && (
<span className="text-sm text-pencil-light font-mono">
{Math.round(pct)}%
</span>
<span className="text-sm text-pencil-light font-mono">{Math.round(pct)}%</span>
)}
</div>
{total > 0 && (
@@ -58,7 +59,9 @@ export default function StreamProgressBar({
/>
</div>
<div className="flex items-center justify-between text-sm text-pencil-light">
<span>{count} / {total} {units}</span>
<span>
{count} / {total} {units}
</span>
{eta !== null && <span>{t('streamProgress.remaining', { eta })}</span>}
</div>
</>
+87 -15
View File
@@ -27,7 +27,12 @@ interface SyncPreviewModalProps {
* Previews from /api/diff, the same data as the Sync page and the pending dots, so the counts agree:
* a dry-run reports every existing link as linked again.
*/
export default function SyncPreviewModal({ open, onClose, kind, className }: SyncPreviewModalProps) {
export default function SyncPreviewModal({
open,
onClose,
kind,
className,
}: SyncPreviewModalProps) {
const t = useT();
const queryClient = useQueryClient();
const navigate = useNavigate();
@@ -71,23 +76,44 @@ export default function SyncPreviewModal({ open, onClose, kind, className }: Syn
const ignored = { skill: diff.data?.ignored_skills, agent: diff.data?.agent_ignored_skills };
const { groups, inSync } = resourceGroups(diff.data?.diffs ?? [], list, parts, false, ignored);
// Targets without an agents folder never get agents, so they are not "up to date" for them.
const upToDate = kind === 'agent' ? inSync.filter((n) => list.find((tg) => tg.name === n)?.agentPath) : inSync;
const upToDate =
kind === 'agent' ? inSync.filter((n) => list.find((tg) => tg.name === n)?.agentPath) : inSync;
const loading = diff.isFetching || targets.isPending;
const loadError = error ?? diff.error?.message ?? targets.error?.message;
const count = countChanges(groups);
const noTargets = !loading && list.length === 0;
const canSync = !loading && !loadError && count > 0;
const title = synced ? t('syncPreview.titleComplete') : kind ? t(`syncPreview.title.${kind}`) : t('syncPreview.titlePreview');
const title = synced
? t('syncPreview.titleComplete')
: kind
? t(`syncPreview.title.${kind}`)
: t('syncPreview.titlePreview');
return (
<DialogShell open={open} onClose={onClose} maxWidth="2xl" padding="none" preventClose={syncing} ariaLabel={title} className={className}>
<DialogShell
open={open}
onClose={onClose}
maxWidth="2xl"
padding="none"
preventClose={syncing}
ariaLabel={title}
className={className}
>
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{title}</h2>
{kind && !synced && <p className="text-[13px] text-ink-2">{t(`syncPreview.scope.${kind}`)}</p>}
{kind && !synced && (
<p className="text-[13px] text-ink-2">{t(`syncPreview.scope.${kind}`)}</p>
)}
</div>
{!loading && !synced && (
<button type="button" className="ss-ib" onClick={() => void diff.refetch()} title={t('syncPreview.refreshPreview')} aria-label={t('syncPreview.refreshPreview')}>
<button
type="button"
className="ss-ib"
onClick={() => void diff.refetch()}
title={t('syncPreview.refreshPreview')}
aria-label={t('syncPreview.refreshPreview')}
>
<RefreshCw size={16} />
</button>
)}
@@ -96,17 +122,39 @@ export default function SyncPreviewModal({ open, onClose, kind, className }: Syn
<div className="db">
{synced ? (
<>
<div className="ss-note inf"><CircleCheck size={16} /><span className="flex-1">{t('syncPreview.completed')}</span></div>
{warnings.map((w) => <div key={w} className="ss-note warn"><TriangleAlert size={16} /><span className="flex-1">{w}</span></div>)}
<div className="ss-note inf">
<CircleCheck size={16} />
<span className="flex-1">{t('syncPreview.completed')}</span>
</div>
{warnings.map((w) => (
<div key={w} className="ss-note warn">
<TriangleAlert size={16} />
<span className="flex-1">{w}</span>
</div>
))}
<UnmatchedNotices items={unmatched} />
</>
) : loading ? (
<div className="ss-list"><div className="ss-r gap-2 text-[13px] text-ink-2"><Spinner size="sm" />{t('sync.checking')}</div></div>
<div className="ss-list">
<div className="ss-r gap-2 text-[13px] text-ink-2">
<Spinner size="sm" />
{t('sync.checking')}
</div>
</div>
) : loadError ? (
<div className="ss-note bad">
<AlertCircle size={16} />
<span className="flex-1">{loadError}</span>
<Button variant="secondary" size="sm" onClick={() => { setError(null); void diff.refetch(); }}>{t('syncPreview.retryButton')}</Button>
<Button
variant="secondary"
size="sm"
onClick={() => {
setError(null);
void diff.refetch();
}}
>
{t('syncPreview.retryButton')}
</Button>
</div>
) : noTargets ? (
<SyncUpToDate text={t('syncPreview.noTargets')} />
@@ -114,21 +162,45 @@ export default function SyncPreviewModal({ open, onClose, kind, className }: Syn
<SyncUpToDate text={t('syncPreview.allUpToDate')} />
) : (
// One row per target can outgrow the dialog; scroll the list so the buttons stay reachable
<SyncResultList groups={groups} inSync={upToDate} className="max-h-[50vh] !overflow-y-auto" />
<SyncResultList
groups={groups}
inSync={upToDate}
className="max-h-[50vh] !overflow-y-auto"
/>
)}
</div>
<div className="df">
{synced || (!loading && !loadError && !canSync) ? (
<Button variant="primary" onClick={onClose}>{t('syncPreview.closeButton')}</Button>
<Button variant="primary" onClick={onClose}>
{t('syncPreview.closeButton')}
</Button>
) : (
<>
<Button variant="secondary" onClick={onClose} disabled={syncing}>{t('syncPreview.cancelButton')}</Button>
{canSync && <Button onClick={handleSync} loading={syncing}>{t('syncPreview.syncNowButton')}</Button>}
<Button variant="secondary" onClick={onClose} disabled={syncing}>
{t('syncPreview.cancelButton')}
</Button>
{canSync && (
<Button onClick={handleSync} loading={syncing}>
{t('syncPreview.syncNowButton')}
</Button>
)}
</>
)}
{/* Last in DOM so the dialog's initial focus lands on a button; order-first keeps it on the left. */}
{kind && <button type="button" className="ss-more order-first mr-auto" onClick={() => { onClose(); navigate('/sync'); }} disabled={syncing}>{t('syncPreview.openSyncPage')}</button>}
{kind && (
<button
type="button"
className="ss-more order-first mr-auto"
onClick={() => {
onClose();
void navigate('/sync');
}}
disabled={syncing}
>
{t('syncPreview.openSyncPage')}
</button>
)}
</div>
</DialogShell>
);
+61 -14
View File
@@ -13,23 +13,35 @@ import { shortenHome } from '../lib/paths';
export function SyncUpToDate({ text }: { text: string }) {
return (
<div className="flex flex-col items-center gap-3 py-8 text-center">
<span className="grid size-12 place-items-center rounded-full bg-ok-bg text-ok"><CircleCheck size={24} /></span>
<span className="grid size-12 place-items-center rounded-full bg-ok-bg text-ok">
<CircleCheck size={24} />
</span>
<p className="text-[14px] text-ink-2">{text}</p>
</div>
);
}
/** One compact row per target with changes; targets already in sync fold into a single closing line. */
export default function SyncResultList({ groups, inSync, className = '' }: { groups: ChangeGroup[]; inSync: string[]; className?: string }) {
export default function SyncResultList({
groups,
inSync,
className = '',
}: {
groups: ChangeGroup[];
inSync: string[];
className?: string;
}) {
const t = useT();
// A folder name is enough unless two projects share it.
const projects = [...new Set(groups.flatMap((g) => g.project ?? []))];
const projectLabel = (p: string) => (projects.some((q) => q !== p && baseName(q) === baseName(p)) ? shortenHome(p) : baseName(p));
const projectLabel = (p: string) =>
projects.some((q) => q !== p && baseName(q) === baseName(p)) ? shortenHome(p) : baseName(p);
return (
<div className={`ss-list ${className}`}>
{groups.map((g) => {
const count = (match: (r: ChangeGroup['rows'][number]) => boolean) => g.rows.filter(match).length;
const count = (match: (r: ChangeGroup['rows'][number]) => boolean) =>
g.rows.filter(match).length;
const folder = count((r) => r.text === 'sync.row.folder');
// An MCP switch adds or removes no server: it turns a global one off in a project, or back on.
const off = count((r) => r.icon === 'add' && r.switch === true);
@@ -45,20 +57,55 @@ export default function SyncResultList({ groups, inSync, className = '' }: { gro
const listed = mcp || hooks;
return (
<div key={g.key} className="ss-r">
<span className="ss-at"><AgentIcon target={g.name} size={15} /></span>
<span className={`min-w-0 truncate text-[13px] font-semibold ${listed ? 'shrink-0' : 'flex-1'}`} title={g.path ?? g.name}>{mcp ? targetLabel(g.name) : hooks ? hookLabel(g.name) : g.name}</span>
<span className="ss-at">
<AgentIcon target={g.name} size={15} />
</span>
<span
className={`min-w-0 truncate text-[13px] font-semibold ${listed ? 'shrink-0' : 'flex-1'}`}
title={g.path ?? g.name}
>
{mcp ? targetLabel(g.name) : hooks ? hookLabel(g.name) : g.name}
</span>
{/* One Agent file holds many servers: name the ones that change, and the project the file is for. */}
{listed && <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-ink-3">{[g.project && projectLabel(g.project), g.rows.map((r) => r.name).join(', ')].filter(Boolean).join(' · ')}</span>}
{listed && (
<span className="min-w-0 flex-1 truncate font-mono text-[12px] text-ink-3">
{[g.project && projectLabel(g.project), g.rows.map((r) => r.name).join(', ')]
.filter(Boolean)
.join(' · ')}
</span>
)}
<span className="flex shrink-0 flex-wrap justify-end gap-1.5">
{folder > 0 && <span className="ss-tag inf">{t('syncResult.dirCreated')}</span>}
{linked > 0 && <span className="ss-tag ok">{t(listed ? 'syncResult.mcp.add' : 'syncResult.linked', { count: linked })}</span>}
{updated > 0 && <span className="ss-tag inf">{t(listed ? 'syncResult.mcp.update' : 'syncResult.updated', { count: updated })}</span>}
{adopted > 0 && <span className="ss-tag inf">{t('syncResult.mcp.adopt', { count: adopted })}</span>}
{pruned > 0 && <span className="ss-tag warn">{t(listed ? 'syncResult.mcp.remove' : 'syncResult.pruned', { count: pruned })}</span>}
{off > 0 && <span className="ss-tag warn">{t('syncResult.mcp.off', { count: off })}</span>}
{linked > 0 && (
<span className="ss-tag ok">
{t(listed ? 'syncResult.mcp.add' : 'syncResult.linked', { count: linked })}
</span>
)}
{updated > 0 && (
<span className="ss-tag inf">
{t(listed ? 'syncResult.mcp.update' : 'syncResult.updated', { count: updated })}
</span>
)}
{adopted > 0 && (
<span className="ss-tag inf">{t('syncResult.mcp.adopt', { count: adopted })}</span>
)}
{pruned > 0 && (
<span className="ss-tag warn">
{t(listed ? 'syncResult.mcp.remove' : 'syncResult.pruned', { count: pruned })}
</span>
)}
{off > 0 && (
<span className="ss-tag warn">{t('syncResult.mcp.off', { count: off })}</span>
)}
{on > 0 && <span className="ss-tag ok">{t('syncResult.mcp.on', { count: on })}</span>}
{kept > 0 && <span className="ss-tag">{t('syncResult.skipped', { count: kept })}</span>}
{conflict > 0 && <span className="ss-tag bad">{t('syncResult.mcp.conflict', { count: conflict })}</span>}
{kept > 0 && (
<span className="ss-tag">{t('syncResult.skipped', { count: kept })}</span>
)}
{conflict > 0 && (
<span className="ss-tag bad">
{t('syncResult.mcp.conflict', { count: conflict })}
</span>
)}
</span>
</div>
);
+99 -52
View File
@@ -84,7 +84,11 @@ export function SkillContextMenu({
left = Math.max(8, anchorPoint.x - rect.width);
}
// Grow out of the corner that touches the anchor, whichever way the menu flipped.
setPosition({ top, left, origin: `${top < anchorPoint.y ? 'bottom' : 'top'} ${left < anchorPoint.x ? 'right' : 'left'}` });
setPosition({
top,
left,
origin: `${top < anchorPoint.y ? 'bottom' : 'top'} ${left < anchorPoint.x ? 'right' : 'left'}`,
});
}, [open, anchorPoint, align]);
// Close on Escape (submenu first, then parent)
@@ -115,11 +119,20 @@ export function SkillContextMenu({
// propagate to underlying Links — first click only dismisses the menu.
return createPortal(
<>
{open && <div
className="fixed inset-0 z-[99]"
onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); onClose(); }}
onContextMenu={(e) => { e.preventDefault(); onClose(); }}
/>}
{open && (
<div
className="fixed inset-0 z-[99]"
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
onClose();
}}
onContextMenu={(e) => {
e.preventDefault();
onClose();
}}
/>
)}
<div
ref={menuRef}
{...menu.exitProps}
@@ -146,16 +159,26 @@ export function SkillContextMenu({
type="button"
className={`${item.danger ? 'dng' : ''} ${item.description ? '!h-auto max-w-[340px] py-1.5' : ''}`}
role="menuitem"
onMouseDown={(e) => { e.preventDefault(); item.onSelect?.(); onClose(); }}
onMouseDown={(e) => {
e.preventDefault();
item.onSelect?.();
onClose();
}}
onMouseEnter={() => setExpandedKey(null)}
>
{item.icon && <span className="w-4 shrink-0 flex items-center justify-center">{item.icon}</span>}
{item.icon && (
<span className="w-4 shrink-0 flex items-center justify-center">{item.icon}</span>
)}
{item.description ? (
<span className="flex min-w-0 flex-col gap-0.5">
<span className={item.mono ? 'font-mono' : ''}>{item.label}</span>
<span className="text-xs font-normal leading-snug text-ink-3">{item.description}</span>
<span className="text-xs font-normal leading-snug text-ink-3">
{item.description}
</span>
</span>
) : item.label}
) : (
item.label
)}
</button>
)}
</Fragment>
@@ -215,10 +238,19 @@ function SubmenuTrigger({
// Hover intent: collapse after delay when mouse leaves
const collapseTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(collapseTimer.current), []);
const handleEnter = () => { clearTimeout(collapseTimer.current); onExpand(); };
const handleLeave = () => { collapseTimer.current = setTimeout(onCollapse, 180); };
const handleSubEnter = () => { clearTimeout(collapseTimer.current); };
const handleSubLeave = () => { collapseTimer.current = setTimeout(onCollapse, 180); };
const handleEnter = () => {
clearTimeout(collapseTimer.current);
onExpand();
};
const handleLeave = () => {
collapseTimer.current = setTimeout(onCollapse, 180);
};
const handleSubEnter = () => {
clearTimeout(collapseTimer.current);
};
const handleSubLeave = () => {
collapseTimer.current = setTimeout(onCollapse, 180);
};
return (
<>
@@ -233,36 +265,46 @@ function SubmenuTrigger({
onMouseLeave={handleLeave}
onClick={handleEnter}
>
{item.icon && <span className="w-4 shrink-0 flex items-center justify-center">{item.icon}</span>}
{item.icon && (
<span className="w-4 shrink-0 flex items-center justify-center">{item.icon}</span>
)}
<span className="flex-1">{item.label}</span>
<ChevronRight size={14} className="shrink-0 text-ink-3" />
</button>
{/* Submenu panel — portaled to body to escape parent's transform containing block */}
{expanded && subPos && createPortal(
<div
{...(closing ? { inert: true, 'aria-hidden': true } : {})}
className={`ss-menu fixed z-[101] !w-auto min-w-[176px] max-h-64 overflow-y-auto ${closing ? 'animate-dropdown-out' : ''}`}
style={{ top: subPos.top, left: subPos.left }}
role="menu"
onMouseEnter={handleSubEnter}
onMouseLeave={handleSubLeave}
>
{item.items?.map((sub) => (
<button
type="button"
key={sub.key}
role="menuitemradio"
aria-checked={!!sub.selected}
onMouseDown={(e) => { e.preventDefault(); sub.onSelect(); onClose(); }}
>
<span className="w-4 shrink-0 flex items-center justify-center">{sub.selected && <Check size={14} />}</span>
<span className={sub.selected ? 'font-semibold' : ''}>{sub.label}</span>
</button>
))}
</div>,
document.body,
)}
{expanded &&
subPos &&
createPortal(
<div
{...(closing ? { inert: true, 'aria-hidden': true } : {})}
className={`ss-menu fixed z-[101] !w-auto min-w-[176px] max-h-64 overflow-y-auto ${closing ? 'animate-dropdown-out' : ''}`}
style={{ top: subPos.top, left: subPos.left }}
role="menu"
onMouseEnter={handleSubEnter}
onMouseLeave={handleSubLeave}
>
{item.items?.map((sub) => (
<button
type="button"
key={sub.key}
role="menuitemradio"
aria-checked={!!sub.selected}
onMouseDown={(e) => {
e.preventDefault();
sub.onSelect();
onClose();
}}
>
<span className="w-4 shrink-0 flex items-center justify-center">
{sub.selected && <Check size={14} />}
</span>
<span className={sub.selected ? 'font-semibold' : ''}>{sub.label}</span>
</button>
))}
</div>,
document.body,
)}
</>
);
}
@@ -272,8 +314,8 @@ function SubmenuTrigger({
/* ------------------------------------------------------------------ */
interface TargetMenuProps {
currentTargets: string[] | null; // null = All
isUniform?: boolean; // for folders
currentTargets: string[] | null; // null = All
isUniform?: boolean; // for folders
showTargets?: boolean;
/** Menu item label. Defaults to "Available in...". */
label?: string;
@@ -301,7 +343,12 @@ export default function TargetMenu({
}: TargetMenuProps) {
const t = useT();
// The configured targets, not the known tools: a custom target is in no built-in list.
const { data } = useQuery({ queryKey: queryKeys.targets.all, queryFn: () => api.listTargets(), staleTime: staleTimes.targets, enabled: open });
const { data } = useQuery({
queryKey: queryKeys.targets.all,
queryFn: () => api.listTargets(),
staleTime: staleTimes.targets,
enabled: open,
});
const targets = [...(data?.targets ?? [])].sort((a, b) => a.name.localeCompare(b.name));
const isAllSelected = isUniform && (!currentTargets || currentTargets.length === 0);
@@ -322,18 +369,18 @@ export default function TargetMenu({
];
const items: ContextMenuItem[] = flat
? targetItems.map((sub) => ({ key: sub.key, label: sub.label, icon: sub.selected ? <Check size={14} /> : <span />, onSelect: sub.onSelect }))
: showTargets ? [{ key: 'set-target', label, icon: <Target size={14} />, items: targetItems }] : [];
? targetItems.map((sub) => ({
key: sub.key,
label: sub.label,
icon: sub.selected ? <Check size={14} /> : <span />,
onSelect: sub.onSelect,
}))
: showTargets
? [{ key: 'set-target', label, icon: <Target size={14} />, items: targetItems }]
: [];
items.push(...(extraItems ?? []));
if (items.length === 0) return null;
return (
<SkillContextMenu
items={items}
anchorPoint={anchorPoint}
open={open}
onClose={onClose}
/>
);
return <SkillContextMenu items={items} anchorPoint={anchorPoint} open={open} onClose={onClose} />;
}
+30 -14
View File
@@ -70,19 +70,27 @@ export default function ThemePopover() {
// Focus the selected style on open
useEffect(() => {
if (!open || !panelRef.current) return;
(panelRef.current.querySelector('[role="radio"][aria-checked="true"]') as HTMLElement | null)?.focus();
(
panelRef.current.querySelector('[role="radio"][aria-checked="true"]') as HTMLElement | null
)?.focus();
}, [open]);
const handleKeyDown = useCallback((e: React.KeyboardEvent, group: 'style' | 'mode') => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
e.preventDefault();
const items = group === 'style' ? styles : modes;
const current = group === 'style' ? style : modePreference;
const idx = items.findIndex((i) => i.value === current);
const next = e.key === 'ArrowRight' ? items[(idx + 1) % items.length] : items[(idx - 1 + items.length) % items.length];
if (group === 'style') setStyle(next.value as Style);
else setModePreference(next.value as ModePreference);
}, [style, modePreference, setStyle, setModePreference]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent, group: 'style' | 'mode') => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
e.preventDefault();
const items = group === 'style' ? styles : modes;
const current = group === 'style' ? style : modePreference;
const idx = items.findIndex((i) => i.value === current);
const next =
e.key === 'ArrowRight'
? items[(idx + 1) % items.length]
: items[(idx - 1 + items.length) % items.length];
if (group === 'style') setStyle(next.value as Style);
else setModePreference(next.value as ModePreference);
},
[style, modePreference, setStyle, setModePreference],
);
return (
<div ref={containerRef} className="relative">
@@ -103,7 +111,8 @@ export default function ThemePopover() {
ref={panelRef}
role="dialog"
aria-label={t('theme.settings')}
{...menu.exitProps} className={`ss-menu absolute left-0 bottom-full mb-3 z-50 origin-bottom-left !w-[264px] !p-3 gap-2 ${menu.motion}`}
{...menu.exitProps}
className={`ss-menu absolute left-0 bottom-full mb-3 z-50 origin-bottom-left !w-[264px] !p-3 gap-2 ${menu.motion}`}
>
<span className="text-xs font-semibold text-ink-3">{t('theme.style')}</span>
<div role="radiogroup" aria-label={t('theme.style')} className="flex gap-1.5">
@@ -121,7 +130,9 @@ export default function ThemePopover() {
className={`flex-1 flex flex-col gap-1.5 p-1.5 rounded-[10px] border-2 cursor-pointer focus-visible:outline-2 focus-visible:outline-link ${on ? 'border-link' : 'border-transparent hover:bg-sunken'}`}
>
<StyleThumb value={s.value} />
<span className={`flex items-center justify-between px-0.5 text-[13px] ${on ? 'font-semibold text-ink' : 'text-ink-2'}`}>
<span
className={`flex items-center justify-between px-0.5 text-[13px] ${on ? 'font-semibold text-ink' : 'text-ink-2'}`}
>
{t(s.label)}
{on && <Check size={14} />}
</span>
@@ -130,7 +141,12 @@ export default function ThemePopover() {
})}
</div>
<span className="text-xs font-semibold text-ink-3 mt-1">{t('theme.mode')}</span>
<div ref={segSlide} role="radiogroup" aria-label={t('theme.mode')} className="ss-seg !flex">
<div
ref={segSlide}
role="radiogroup"
aria-label={t('theme.mode')}
className="ss-seg !flex"
>
{modes.map((m) => {
const on = modePreference === m.value;
const Icon = m.icon;
+36 -17
View File
@@ -1,4 +1,12 @@
import { createContext, useContext, useState, useCallback, useRef, useEffect, type ReactNode } from 'react';
import {
createContext,
useContext,
useState,
useCallback,
useRef,
useEffect,
type ReactNode,
} from 'react';
import { X, CheckCircle, AlertTriangle, XCircle, Info } from 'lucide-react';
interface Toast {
@@ -48,13 +56,7 @@ const iconColors = {
const TOAST_DURATION = 4000;
const EXIT_DURATION = 200;
function ToastItem({
toast: t,
onRemove,
}: {
toast: Toast;
onRemove: (id: number) => void;
}) {
function ToastItem({ toast: t, onRemove }: { toast: Toast; onRemove: (id: number) => void }) {
const Icon = icons[t.type];
// Errors/warnings often carry longer text — give them more time to read.
const duration = t.type === 'error' || t.type === 'warning' ? 8000 : TOAST_DURATION;
@@ -83,14 +85,22 @@ function ToastItem({
useEffect(() => {
startTimer();
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, [startTimer]);
return (
<div
className={`ss-toast relative !flex !h-auto min-h-[42px] !items-start py-2.5 overflow-hidden ${exiting ? 'animate-toast-out' : 'animate-toast-in'}`}
onMouseEnter={() => { setPaused(true); pauseTimer(); }}
onMouseLeave={() => { setPaused(false); startTimer(); }}
onMouseEnter={() => {
setPaused(true);
pauseTimer();
}}
onMouseLeave={() => {
setPaused(false);
startTimer();
}}
>
<Icon size={16} className={`shrink-0 mt-px ${iconColors[t.type]}`} />
<div className="flex-1 min-w-0">
@@ -122,11 +132,17 @@ function ToastItem({
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const addToast = useCallback((message: string, type: Toast['type'] = 'info', opts?: ToastOptions) => {
const id = nextId++;
const key = opts?.key;
setToasts((prev) => [...prev.filter((t) => !key || t.key !== key), { id, message, type, title: opts?.title, key }]);
}, []);
const addToast = useCallback(
(message: string, type: Toast['type'] = 'info', opts?: ToastOptions) => {
const id = nextId++;
const key = opts?.key;
setToasts((prev) => [
...prev.filter((t) => !key || t.key !== key),
{ id, message, type, title: opts?.title, key },
]);
},
[],
);
const removeToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
@@ -136,7 +152,10 @@ export function ToastProvider({ children }: { children: ReactNode }) {
<ToastContext.Provider value={{ toast: addToast }}>
{children}
{/* Toast container */}
<div data-toast-container className="fixed bottom-7 left-1/2 -translate-x-1/2 z-[70] flex flex-col items-center gap-2 w-[min(36rem,calc(100vw-3rem))]">
<div
data-toast-container
className="fixed bottom-7 left-1/2 -translate-x-1/2 z-[70] flex flex-col items-center gap-2 w-[min(36rem,calc(100vw-3rem))]"
>
{toasts.map((t) => (
<ToastItem key={t.id} toast={t} onRemove={removeToast} />
))}
+60 -38
View File
@@ -14,7 +14,14 @@ interface TooltipProps {
const OFFSET = 12;
const MARGIN = 8;
export default function Tooltip({ children, content, side = 'bottom', followCursor, delay = 200, block }: TooltipProps) {
export default function Tooltip({
children,
content,
side = 'bottom',
followCursor,
delay = 200,
block,
}: TooltipProps) {
// `above` is where the tip's bottom edge goes when it does not fit below its anchor.
const [pos, setPos] = useState<{ x: number; y: number; above?: number } | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
@@ -45,27 +52,30 @@ export default function Tooltip({ children, content, side = 'bottom', followCurs
el.style.visibility = 'visible';
}, [pos]);
const show = useCallback((e: React.MouseEvent | React.FocusEvent) => {
// Hover and focus can both start one; only the latest timer may fire.
if (timerRef.current) clearTimeout(timerRef.current);
if (followCursor) {
const { clientX, clientY } = e as React.MouseEvent;
latestCursor.current = { x: clientX + OFFSET, y: clientY + OFFSET };
timerRef.current = setTimeout(() => {
visibleRef.current = true;
setPos({ ...latestCursor.current });
}, delay);
} else {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
timerRef.current = setTimeout(() => {
setPos({
x: rect.left,
y: side === 'top' ? rect.top - 4 : rect.bottom + 4,
above: rect.top - 4,
});
}, delay);
}
}, [side, followCursor, delay]);
const show = useCallback(
(e: React.MouseEvent | React.FocusEvent) => {
// Hover and focus can both start one; only the latest timer may fire.
if (timerRef.current) clearTimeout(timerRef.current);
if (followCursor) {
const { clientX, clientY } = e as React.MouseEvent;
latestCursor.current = { x: clientX + OFFSET, y: clientY + OFFSET };
timerRef.current = setTimeout(() => {
visibleRef.current = true;
setPos({ ...latestCursor.current });
}, delay);
} else {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
timerRef.current = setTimeout(() => {
setPos({
x: rect.left,
y: side === 'top' ? rect.top - 4 : rect.bottom + 4,
above: rect.top - 4,
});
}, delay);
}
},
[side, followCursor, delay],
);
const move = useCallback((e: React.MouseEvent) => {
latestCursor.current = { x: e.clientX + OFFSET, y: e.clientY + OFFSET };
@@ -85,28 +95,40 @@ export default function Tooltip({ children, content, side = 'bottom', followCurs
setPos(null);
}, []);
useEffect(() => () => {
if (timerRef.current) clearTimeout(timerRef.current);
if (rafRef.current !== undefined) cancelAnimationFrame(rafRef.current);
}, []);
useEffect(
() => () => {
if (timerRef.current) clearTimeout(timerRef.current);
if (rafRef.current !== undefined) cancelAnimationFrame(rafRef.current);
},
[],
);
return (
<>
<span className={block ? 'block' : undefined} onMouseEnter={show} onMouseLeave={hide} onMouseMove={followCursor ? move : undefined} onFocus={followCursor ? undefined : show} onBlur={hide}>
<span
className={block ? 'block' : undefined}
onMouseEnter={show}
onMouseLeave={hide}
onMouseMove={followCursor ? move : undefined}
onFocus={followCursor ? undefined : show}
onBlur={hide}
>
{children}
</span>
{/* No content leaves the wrapper in place, so a caller can keep its tree stable while the text loads. */}
{pos && content && createPortal(
<div
ref={tooltipRef}
role="tooltip"
className="ss-tip fixed z-[9999] max-w-sm whitespace-pre-line pointer-events-none animate-fade-in"
style={{ left: 0, top: 0, visibility: 'hidden' }}
>
{content}
</div>,
document.body,
)}
{pos &&
content &&
createPortal(
<div
ref={tooltipRef}
role="tooltip"
className="ss-tip fixed z-[9999] max-w-sm whitespace-pre-line pointer-events-none animate-fade-in"
style={{ left: 0, top: 0, visibility: 'hidden' }}
>
{content}
</div>,
document.body,
)}
</>
);
}
+10 -2
View File
@@ -27,7 +27,10 @@ export default function TruncateTip() {
hide();
if (!el || el.hasAttribute('title') || el.scrollWidth <= el.clientWidth) return;
current = el;
timer = setTimeout(() => setTip({ text: el.textContent ?? '', rect: el.getBoundingClientRect() }), DELAY);
timer = setTimeout(
() => setTip({ text: el.textContent ?? '', rect: el.getBoundingClientRect() }),
DELAY,
);
};
const out = (e: MouseEvent) => {
if (!e.relatedTarget) hide();
@@ -58,7 +61,12 @@ export default function TruncateTip() {
if (!tip) return null;
return createPortal(
<div ref={ref} role="tooltip" className="ss-tip pointer-events-none fixed z-[9999] max-w-sm break-words animate-fade-in" style={{ left: 0, top: 0, visibility: 'hidden' }}>
<div
ref={ref}
role="tooltip"
className="ss-tip pointer-events-none fixed z-[9999] max-w-sm break-words animate-fade-in"
style={{ left: 0, top: 0, visibility: 'hidden' }}
>
{tip.text}
</div>,
document.body,
+30 -6
View File
@@ -12,7 +12,9 @@ vi.mock('../api/client', async (importOriginal) => {
...actual,
api: {
...actual.api,
getUpdatePolicy: vi.fn().mockResolvedValue({ enabled: true, configured: true, envOverride: false }),
getUpdatePolicy: vi
.fn()
.mockResolvedValue({ enabled: true, configured: true, envOverride: false }),
getVersionCheck: vi.fn().mockResolvedValue({
cliVersion: '0.21.12',
cliLatest: '0.21.13',
@@ -31,13 +33,35 @@ vi.mock('../api/client', async (importOriginal) => {
describe('UpdateDialog', () => {
it('allows an explicitly requested upgrade while automatic checks are disabled', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
vi.mocked(api.getUpdatePolicy).mockResolvedValueOnce({ enabled: false, configured: false, envOverride: false });
vi.mocked(api.upgradeApp).mockResolvedValueOnce({ ok: true, updated: true, devMode: true, latestVersion: '9.9.9' });
vi.mocked(api.getUpdatePolicy).mockResolvedValueOnce({
enabled: false,
configured: false,
envOverride: false,
});
vi.mocked(api.upgradeApp).mockResolvedValueOnce({
ok: true,
updated: true,
devMode: true,
latestVersion: '9.9.9',
});
const onDismiss = vi.fn();
render(
<QueryClientProvider client={queryClient}><I18nProvider>
<UpdateDialog onDismiss={onDismiss} manualData={{ autoCheckEnabled: false, cliDevMode: true, cliVersion: '1.0.0', cliLatest: '9.9.9', cliUpdateAvailable: true, skillVersion: '', skillUpdateAvailable: false }} />
</I18nProvider></QueryClientProvider>,
<QueryClientProvider client={queryClient}>
<I18nProvider>
<UpdateDialog
onDismiss={onDismiss}
manualData={{
autoCheckEnabled: false,
cliDevMode: true,
cliVersion: '1.0.0',
cliLatest: '9.9.9',
cliUpdateAvailable: true,
skillVersion: '',
skillUpdateAvailable: false,
}}
/>
</I18nProvider>
</QueryClientProvider>,
);
await userEvent.click(await screen.findByRole('button', { name: /Update now/ }));
await waitFor(() => expect(api.upgradeApp).toHaveBeenCalled());
+46 -10
View File
@@ -22,7 +22,10 @@ const mockData: VersionCheck = {
skillUpdateAvailable: true,
};
export default function UpdateDialog({ manualData, onDismiss }: { manualData?: VersionCheck; onDismiss?: () => void } = {}) {
export default function UpdateDialog({
manualData,
onDismiss,
}: { manualData?: VersionCheck; onDismiss?: () => void } = {}) {
const t = useT();
const policy = useUpdatePolicy();
const [open, setOpen] = useState(false);
@@ -41,14 +44,20 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
const data = manualData ?? (isMockMode ? mockData : realData);
// Dev builds always report a simulated update; stay quiet unless ?update-test asks for the flow.
const hasUpdate = (!!manualData || isMockMode || policy.data?.enabled === true) && (!!manualData || data?.autoCheckEnabled !== false) && (!!manualData || !data?.cliDevMode) && (data?.cliUpdateAvailable || data?.skillUpdateAvailable);
const hasUpdate =
(!!manualData || isMockMode || policy.data?.enabled === true) &&
(!!manualData || data?.autoCheckEnabled !== false) &&
(!!manualData || !data?.cliDevMode) &&
(data?.cliUpdateAvailable || data?.skillUpdateAvailable);
useEffect(() => {
if (!hasUpdate) return;
if (!isMockMode && !manualData) {
try {
if (sessionStorage.getItem(DISMISSED_KEY)) return;
} catch { /* storage unavailable */ }
} catch {
/* storage unavailable */
}
}
setOpen(true);
}, [hasUpdate, isMockMode, manualData]);
@@ -60,7 +69,9 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
setOpen(false);
onDismiss?.();
if (manualData) return;
try { sessionStorage.setItem(DISMISSED_KEY, '1'); } catch {
try {
sessionStorage.setItem(DISMISSED_KEY, '1');
} catch {
// Ignore storage access failures.
}
};
@@ -86,7 +97,13 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
await new Promise((resolve) => setTimeout(resolve, 500));
}
}
setStatus(t('updateDialog.restartManual', {}, 'Updated. Restart with skillshare ui start if this page does not reconnect.'));
setStatus(
t(
'updateDialog.restartManual',
{},
'Updated. Restart with skillshare ui start if this page does not reconnect.',
),
);
setUpdating(false);
};
@@ -114,10 +131,23 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
};
return (
<DialogShell open={open} onClose={dismiss} maxWidth="md" padding="none" preventClose={updating} ariaLabel={t('updateDialog.newVersion')}>
<DialogShell
open={open}
onClose={dismiss}
maxWidth="md"
padding="none"
preventClose={updating}
ariaLabel={t('updateDialog.newVersion')}
>
<div className="dh">
<h2 className="ss-h2">{t('updateDialog.newVersion')}</h2>
<button type="button" className="ss-ib" onClick={dismiss} aria-label={t('common.close')} disabled={updating}>
<button
type="button"
className="ss-ib"
onClick={dismiss}
aria-label={t('common.close')}
disabled={updating}
>
<X size={16} />
</button>
</div>
@@ -126,13 +156,17 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
{data.cliUpdateAvailable && (
<>
<dt>CLI</dt>
<dd className="font-mono">{data.cliVersion} → <b>{data.cliLatest}</b></dd>
<dd className="font-mono">
{data.cliVersion} → <b>{data.cliLatest}</b>
</dd>
</>
)}
{data.skillUpdateAvailable && (
<>
<dt>Skill</dt>
<dd className="font-mono">{data.skillVersion} → <b>{data.skillLatest}</b></dd>
<dd className="font-mono">
{data.skillVersion} → <b>{data.skillLatest}</b>
</dd>
</>
)}
</dl>
@@ -148,7 +182,9 @@ export default function UpdateDialog({ manualData, onDismiss }: { manualData?: V
{nixNote && <p className="text-[13px] text-ink-2">{nixNote}</p>}
</div>
<p className="text-[13px] text-ink-2">{t('updateDialog.restartNote')}</p>
{status && <p className={`text-[13px] ${updating ? 'text-ink-2' : 'text-bad'}`}>{status}</p>}
{status && (
<p className={`text-[13px] ${updating ? 'text-ink-2' : 'text-bad'}`}>{status}</p>
)}
</div>
<div className="df">
<Button variant="ghost" onClick={dismiss} disabled={updating}>
+222 -44
View File
@@ -18,41 +18,86 @@ import { segSlide } from '../../lib/segSlide';
const STEP = 100;
const MANAGED_ONLY_KEY = 'skillshare:analyze-managed-only';
/** Thousands collapse to "3.4k" so the column stays one glance wide; smaller counts stay exact. */
const kTokens = (n: number) => (n < 1000 ? n.toLocaleString() : n >= 10000 ? `${Math.round(n / 1000)}k` : `${(n / 1000).toFixed(1)}k`);
const kTokens = (n: number) =>
n < 1000
? n.toLocaleString()
: n >= 10000
? `${Math.round(n / 1000)}k`
: `${(n / 1000).toFixed(1)}k`;
/** "description-length" reads as "description length" — the full sentence waits in the dialog. */
const ruleLabel = (rule: string) => rule.replace(/-/g, ' ');
/** A local skill's path is wherever the tool put it (e.g. synced/<org>_<uuid>/docx), so show just its folder. */
const skillLabel = (s: AnalyzeSkill) => (s.local ? s.path.split('/').pop() || s.path : formatSkillDisplayName(s.name));
const skillLabel = (s: AnalyzeSkill) =>
s.local ? s.path.split('/').pop() || s.path : formatSkillDisplayName(s.name);
/** Project targets are named `project@tool`; own targets have no `@`. */
const projectOf = (name: string) => (name.includes('@') ? name.slice(0, name.lastIndexOf('@')) : '');
const projectOf = (name: string) =>
name.includes('@') ? name.slice(0, name.lastIndexOf('@')) : '';
/** Exact name first. A project link may name a tool that shares its folder with another, so any target of that project will do. */
function pickTarget(targets: AnalyzeTarget[], want: string) {
const project = projectOf(want);
return targets.find((x) => x.name === want) ?? (project ? targets.find((x) => projectOf(x.name) === project) : undefined) ?? targets[0];
return (
targets.find((x) => x.name === want) ??
(project ? targets.find((x) => projectOf(x.name) === project) : undefined) ??
targets[0]
);
}
/** Context cost of the skills a target loads: descriptions always, bodies on demand. */
export default function AnalyzePanel() {
const t = useT();
const { data, isPending, error } = useQuery({ queryKey: queryKeys.analyze, queryFn: () => api.analyze(), staleTime: staleTimes.analyze });
const { data, isPending, error } = useQuery({
queryKey: queryKeys.analyze,
queryFn: () => api.analyze(),
staleTime: staleTimes.analyze,
});
// The target lives in the URL so target and project pages can deep-link here.
const [params, setParams] = useSearchParams();
const target = params.get('target') ?? '';
const setTarget = (v: string) => setParams((p) => { p.set('target', v); return p; }, { replace: true });
const setTarget = (v: string) =>
setParams(
(p) => {
p.set('target', v);
return p;
},
{ replace: true },
);
const [search, setSearch] = useState('');
const [onlyIssues, setOnlyIssues] = useState(false);
const [managedOnly, setManagedOnly] = useState(() => {
try { return localStorage.getItem(MANAGED_ONLY_KEY) === '1'; } catch { return false; }
try {
return localStorage.getItem(MANAGED_ONLY_KEY) === '1';
} catch {
return false;
}
});
const [limit, setLimit] = useState(STEP);
const [detail, setDetail] = useState<AnalyzeSkill | null>(null);
if (isPending) return <div className="ss-note inf !items-center"><Spinner size="sm" />{t('analyze.loading')}</div>;
if (error) return <div className="ss-note bad"><AlertCircle size={16} /><span className="flex-1 break-words">{(error as Error).message}</span></div>;
if (isPending)
return (
<div className="ss-note inf !items-center">
<Spinner size="sm" />
{t('analyze.loading')}
</div>
);
if (error)
return (
<div className="ss-note bad">
<AlertCircle size={16} />
<span className="flex-1 break-words">{(error as Error).message}</span>
</div>
);
const targets = data?.targets ?? [];
if (targets.length === 0) return <EmptyState icon={Puzzle} title={t('analyze.empty.title')} description={t('analyze.empty.description')} />;
if (targets.length === 0)
return (
<EmptyState
icon={Puzzle}
title={t('analyze.empty.title')}
description={t('analyze.empty.description')}
/>
);
const current = pickTarget(targets, target);
// Own targets first, project targets (`project@tool`) after, each keeping the API's heaviest-first order.
@@ -60,19 +105,29 @@ export default function AnalyzePanel() {
.sort((a, b) => Number(Boolean(projectOf(a.name))) - Number(Boolean(projectOf(b.name))))
.map((x) => ({ value: x.name, label: x.name, icon: <AgentIcon target={x.name} size={15} /> }));
const hasLocal = current.skills.some((s) => s.local);
const skills = current.skills.filter((s) => !(managedOnly && s.local)).sort((a, b) => b.body_tokens - a.body_tokens);
const skills = current.skills
.filter((s) => !(managedOnly && s.local))
.sort((a, b) => b.body_tokens - a.body_tokens);
// Summed here rather than read from the API totals so they follow the managed-only switch.
const alwaysLoaded = skills.reduce((n, s) => n + s.description_tokens, 0);
const onDemand = skills.reduce((n, s) => n + s.body_tokens, 0);
const toggleManagedOnly = (on: boolean) => {
setManagedOnly(on);
setLimit(STEP);
try { localStorage.setItem(MANAGED_ONLY_KEY, on ? '1' : '0'); } catch { /* storage unavailable */ }
try {
localStorage.setItem(MANAGED_ONLY_KEY, on ? '1' : '0');
} catch {
/* storage unavailable */
}
};
const issueCount = skills.filter((s) => s.lint_issues?.length).length;
const heaviest = skills[0]?.body_tokens ?? 0;
const term = search.trim().toLowerCase();
const filtered = skills.filter((s) => (!onlyIssues || s.lint_issues?.length) && (!term || skillLabel(s).toLowerCase().includes(term)));
const filtered = skills.filter(
(s) =>
(!onlyIssues || s.lint_issues?.length) &&
(!term || skillLabel(s).toLowerCase().includes(term)),
);
return (
<div className="flex flex-col gap-5">
@@ -80,7 +135,10 @@ export default function AnalyzePanel() {
<p className="max-w-[640px] text-[13px] leading-relaxed text-ink-2">{t('analyze.intro')}</p>
<Select
value={current.name}
onChange={(v) => { setTarget(v); setLimit(STEP); }}
onChange={(v) => {
setTarget(v);
setLimit(STEP);
}}
prefix={t('analyze.target')}
className="w-[260px] shrink-0"
options={options}
@@ -100,9 +158,21 @@ export default function AnalyzePanel() {
<span className="text-[13px] text-ink-2">{t('analyze.stat.onDemand')}</span>
</span>
</div>
<button type="button" aria-pressed={onlyIssues} disabled={issueCount === 0} onClick={() => { setOnlyIssues(!onlyIssues); setLimit(STEP); }}>
<button
type="button"
aria-pressed={onlyIssues}
disabled={issueCount === 0}
onClick={() => {
setOnlyIssues(!onlyIssues);
setLimit(STEP);
}}
>
<span className="flex flex-col items-start gap-[3px]">
<b className={issueCount === 0 ? 'text-ink-3' : onlyIssues ? 'text-accent' : 'text-warn'}>{issueCount}</b>
<b
className={issueCount === 0 ? 'text-ink-3' : onlyIssues ? 'text-accent' : 'text-warn'}
>
{issueCount}
</b>
<span className="text-[13px] text-ink-2">{t('analyze.stat.issues')}</span>
</span>
</button>
@@ -111,50 +181,116 @@ export default function AnalyzePanel() {
<div className="flex flex-wrap items-center gap-2">
<label className="ss-inp w-[220px] shrink-0">
<Search size={15} className="text-ink-3" />
<input value={search} onChange={(e) => { setSearch(e.target.value); setLimit(STEP); }} placeholder={t('analyze.search')} aria-label={t('analyze.search')} />
<input
value={search}
onChange={(e) => {
setSearch(e.target.value);
setLimit(STEP);
}}
placeholder={t('analyze.search')}
aria-label={t('analyze.search')}
/>
</label>
<div ref={segSlide} className="ss-seg" role="tablist">
<button type="button" role="tab" aria-selected={!onlyIssues} className={onlyIssues ? '' : 'on'} onClick={() => { setOnlyIssues(false); setLimit(STEP); }}>
<button
type="button"
role="tab"
aria-selected={!onlyIssues}
className={onlyIssues ? '' : 'on'}
onClick={() => {
setOnlyIssues(false);
setLimit(STEP);
}}
>
{t('analyze.filter.all')}
</button>
<button type="button" role="tab" aria-selected={onlyIssues} className={onlyIssues ? 'on' : ''} disabled={issueCount === 0} onClick={() => { setOnlyIssues(true); setLimit(STEP); }}>
<button
type="button"
role="tab"
aria-selected={onlyIssues}
className={onlyIssues ? 'on' : ''}
disabled={issueCount === 0}
onClick={() => {
setOnlyIssues(true);
setLimit(STEP);
}}
>
{t('analyze.filter.issues')}
{issueCount > 0 && <span className="ss-cnt">{issueCount}</span>}
</button>
</div>
{hasLocal && <Checkbox size="sm" className="ml-2" label={t('analyze.filter.managedOnly')} checked={managedOnly} onChange={toggleManagedOnly} />}
{hasLocal && (
<Checkbox
size="sm"
className="ml-2"
label={t('analyze.filter.managedOnly')}
checked={managedOnly}
onChange={toggleManagedOnly}
/>
)}
</div>
{filtered.length === 0 ? (
<EmptyState icon={Search} title={t('analyze.noMatch.title')} description={t('analyze.noMatch.description')} />
<EmptyState
icon={Search}
title={t('analyze.noMatch.title')}
description={t('analyze.noMatch.description')}
/>
) : (
<div className="ss-list">
<div className="ss-lh">
<span className="w-[34px]" />
<span className="flex-1">{t('analyze.col.skill')}</span>
<span className="w-[110px]">{t('analyze.col.alwaysLoaded')}</span>
<span className="flex w-[240px] items-center gap-1.5">{t('analyze.col.onDemand')}<ArrowDown size={13} /></span>
<span className="flex w-[240px] items-center gap-1.5">
{t('analyze.col.onDemand')}
<ArrowDown size={13} />
</span>
</div>
{filtered.slice(0, limit).map((s) => (
<button key={s.name} type="button" className="ss-r w-full text-left" onClick={() => setDetail(s)}>
<span className="ss-cat sm skill"><Puzzle size={14} /></span>
<span className="nm m truncate" title={s.local ? s.path : undefined}>{skillLabel(s)}</span>
<button
key={s.name}
type="button"
className="ss-r w-full text-left"
onClick={() => setDetail(s)}
>
<span className="ss-cat sm skill">
<Puzzle size={14} />
</span>
<span className="nm m truncate" title={s.local ? s.path : undefined}>
{skillLabel(s)}
</span>
{s.lint_issues?.length ? (
<span className="ss-tag warn shrink-0" title={s.lint_issues.map((i) => i.message).join(' · ')}>{ruleLabel(s.lint_issues[0].rule)}</span>
<span
className="ss-tag warn shrink-0"
title={s.lint_issues.map((i) => i.message).join(' · ')}
>
{ruleLabel(s.lint_issues[0].rule)}
</span>
) : null}
{s.local && <span className="ss-tag shrink-0">{t('analyze.tag.local')}</span>}
{s.disabled && <span className="ss-tag warn shrink-0">{t('analyze.tag.disabled')}</span>}
{s.disabled && (
<span className="ss-tag warn shrink-0">{t('analyze.tag.disabled')}</span>
)}
<span className="flex-1" />
<span className="w-[110px] font-mono text-[13px]">{s.description_tokens.toLocaleString()}</span>
<span className="w-[110px] font-mono text-[13px]">
{s.description_tokens.toLocaleString()}
</span>
<span className="flex w-[240px] items-center gap-2.5">
<span className="ss-prog flex-1"><i style={{ width: `${heaviest ? (s.body_tokens / heaviest) * 100 : 0}%` }} /></span>
<span className="w-[38px] text-right font-mono text-[13px]">{kTokens(s.body_tokens)}</span>
<span className="ss-prog flex-1">
<i style={{ width: `${heaviest ? (s.body_tokens / heaviest) * 100 : 0}%` }} />
</span>
<span className="w-[38px] text-right font-mono text-[13px]">
{kTokens(s.body_tokens)}
</span>
</span>
</button>
))}
{filtered.length > limit && (
<div className="ss-r justify-center">
<Button variant="ghost" size="sm" onClick={() => setLimit((l) => l + STEP)}>{t('resources.showMore')}</Button>
<Button variant="ghost" size="sm" onClick={() => setLimit((l) => l + STEP)}>
{t('resources.showMore')}
</Button>
</div>
)}
</div>
@@ -170,39 +306,72 @@ export default function AnalyzePanel() {
function SkillDialog({ skill, onClose }: { skill: AnalyzeSkill; onClose: () => void }) {
const t = useT();
return (
<DialogShell open onClose={onClose} padding="none" ariaLabel={skill.name} className="!max-w-[560px]">
<DialogShell
open
onClose={onClose}
padding="none"
ariaLabel={skill.name}
className="!max-w-[560px]"
>
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2 font-mono">{skillLabel(skill)}</h2>
{skill.local && <p className="font-mono text-[12.5px] text-ink-3 break-all">{skill.path}</p>}
<h2 className="ss-h2 font-mono">{skillLabel(skill)}</h2>
{skill.local && (
<p className="font-mono text-[12.5px] text-ink-3 break-all">{skill.path}</p>
)}
<p className="text-[13px] text-ink-2">{t('analyze.detail.subtitle')}</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose}><X size={16} /></button>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose}>
<X size={16} />
</button>
</div>
<div className="db">
<dl className="ss-kv !grid-cols-[150px_minmax(0,1fr)]">
<dt>{t('analyze.col.alwaysLoaded')}</dt>
<dd><span className="font-mono font-semibold">{skill.description_tokens.toLocaleString()}</span> {t('analyze.detail.alwaysLoadedDesc')}</dd>
<dd>
<span className="font-mono font-semibold">
{skill.description_tokens.toLocaleString()}
</span>{' '}
{t('analyze.detail.alwaysLoadedDesc')}
</dd>
<dt>{t('analyze.col.onDemand')}</dt>
<dd><span className="font-mono font-semibold">{kTokens(skill.body_tokens)}</span> {t('analyze.detail.onDemandDesc')}</dd>
<dd>
<span className="font-mono font-semibold">{kTokens(skill.body_tokens)}</span>{' '}
{t('analyze.detail.onDemandDesc')}
</dd>
{skill.targets?.length ? (
<>
<dt>{t('analyze.detail.restrictedTo')}</dt>
<dd className="flex flex-wrap items-center gap-1.5">
{skill.targets.map((name) => <span key={name} className="ss-at"><AgentIcon target={name} size={15} /></span>)}
{skill.targets.map((name) => (
<span key={name} className="ss-at">
<AgentIcon target={name} size={15} />
</span>
))}
<span className="text-[13px] text-ink-2">{skill.targets.join(', ')}</span>
</dd>
</>
) : null}
</dl>
{skill.local && <div className="ss-note inf"><span className="flex-1">{t('analyze.detail.local')}</span></div>}
{skill.disabled && <div className="ss-note warn"><AlertTriangle size={16} /><span className="flex-1">{t('analyze.detail.disabled')}</span></div>}
{skill.local && (
<div className="ss-note inf">
<span className="flex-1">{t('analyze.detail.local')}</span>
</div>
)}
{skill.disabled && (
<div className="ss-note warn">
<AlertTriangle size={16} />
<span className="flex-1">{t('analyze.detail.disabled')}</span>
</div>
)}
{skill.description && (
<div className="ss-fld">
<label>{t('analyze.detail.descriptionPreview')}</label>
<div className="ss-box max-h-[120px] overflow-y-auto !px-3.5 !py-3 !shadow-none text-[13px] leading-relaxed">{skill.description}</div>
<div className="ss-box max-h-[120px] overflow-y-auto !px-3.5 !py-3 !shadow-none text-[13px] leading-relaxed">
{skill.description}
</div>
</div>
)}
@@ -210,7 +379,10 @@ function SkillDialog({ skill, onClose }: { skill: AnalyzeSkill; onClose: () => v
<div className="ss-fld">
<label>{t('analyze.detail.qualityIssues')}</label>
{skill.lint_issues.map((issue) => (
<div key={issue.rule} className={`ss-note ${issue.severity === 'error' ? 'bad' : 'warn'}`}>
<div
key={issue.rule}
className={`ss-note ${issue.severity === 'error' ? 'bad' : 'warn'}`}
>
<AlertTriangle size={16} />
<span className="flex-1">{issue.message}</span>
</div>
@@ -222,8 +394,14 @@ function SkillDialog({ skill, onClose }: { skill: AnalyzeSkill; onClose: () => v
</div>
<div className="df">
<span className="flex-1" />
<Button variant="ghost" onClick={onClose}>{t('common.close')}</Button>
{!skill.local && <Link to={`/skills/${encodeURIComponent(skill.name)}`} className="ss-btn pri">{t('analyze.detail.viewSkill')}</Link>}
<Button variant="ghost" onClick={onClose}>
{t('common.close')}
</Button>
{!skill.local && (
<Link to={`/skills/${encodeURIComponent(skill.name)}`} className="ss-btn pri">
{t('analyze.detail.viewSkill')}
</Link>
)}
</div>
</DialogShell>
);
@@ -73,8 +73,11 @@ export default function AuditAssistantPanel({
<span className={`ss-st ${errorCount > 0 ? 'bad' : 'warn'}`}>
{[
errorCount > 0 && t(plural('config.panel.errors', errorCount), { count: errorCount }),
warningCount > 0 && t(plural('config.panel.warnings', warningCount), { count: warningCount }),
].filter(Boolean).join(', ')}
warningCount > 0 &&
t(plural('config.panel.warnings', warningCount), { count: warningCount }),
]
.filter(Boolean)
.join(', ')}
</span>
)}
<span className="text-xs text-ink-3">
@@ -95,22 +98,47 @@ export default function AuditAssistantPanel({
</>
) : (
<>
<div ref={segSlide} className="ss-seg self-start" role="radiogroup" aria-label={t('audit.tab.rules')}>
<div
ref={segSlide}
className="ss-seg self-start"
role="radiogroup"
aria-label={t('audit.tab.rules')}
>
{VIEWS.map((v) => (
<button key={v} type="button" role="radio" aria-checked={view === v} className={view === v ? 'on' : ''} onClick={() => setView(v)}>
<button
key={v}
type="button"
role="radio"
aria-checked={view === v}
className={view === v ? 'on' : ''}
onClick={() => setView(v)}
>
{t(`config.panel.tab.${v}`)}
</button>
))}
</div>
<div className="max-h-[420px] overflow-y-auto">
{view === 'field' ? (
fieldPath ? <FieldDocs fieldPath={fieldPath} docs={auditFieldDocs} /> : <p className="text-[13px] text-ink-3">{t('config.panel.fieldHint')}</p>
fieldPath ? (
<FieldDocs fieldPath={fieldPath} docs={auditFieldDocs} />
) : (
<p className="text-[13px] text-ink-3">{t('config.panel.fieldHint')}</p>
)
) : view === 'structure' ? (
<StructureTree source={source} cursorLine={cursorLine} parseError={false} onClickNode={jumpToLine} />
<StructureTree
source={source}
cursorLine={cursorLine}
parseError={false}
onClickNode={jumpToLine}
/>
) : view === 'changes' ? (
<DiffPreview diff={diff} onClickLine={jumpToLine} onRevert={onRevert} />
) : (
<RegexTester pattern={pattern} excludePattern={cursorExclude} onPatternChange={setPattern} />
<RegexTester
pattern={pattern}
excludePattern={cursorExclude}
onPatternChange={setPattern}
/>
)}
</div>
</>
+5 -3
View File
@@ -12,7 +12,7 @@ export default function AuditOverview({ stats, compiledRules }: AuditOverviewPro
// Count per severity from compiledRules
const severityCounts = compiledRules
? SEVERITY_ORDER.reduce<Record<string, number>>((acc, sev) => {
acc[sev] = compiledRules.filter(r => r.severity === sev).length;
acc[sev] = compiledRules.filter((r) => r.severity === sev).length;
return acc;
}, {})
: null;
@@ -22,7 +22,9 @@ export default function AuditOverview({ stats, compiledRules }: AuditOverviewPro
{/* Header */}
<div className="flex items-center gap-1.5">
<ShieldCheck size={13} strokeWidth={2} className="text-pencil-light" />
<span className="text-xs uppercase tracking-wider text-pencil-light font-medium">Overview</span>
<span className="text-xs uppercase tracking-wider text-pencil-light font-medium">
Overview
</span>
</div>
<div className="border-t border-dashed border-pencil-light/30" />
@@ -61,7 +63,7 @@ export default function AuditOverview({ stats, compiledRules }: AuditOverviewPro
<div className="border-t border-dashed border-pencil-light/30" />
<div className="space-y-1.5">
{SEVERITY_ORDER.filter(sev => severityCounts[sev] > 0).map(sev => (
{SEVERITY_ORDER.filter((sev) => severityCounts[sev] > 0).map((sev) => (
<div key={sev} className="flex items-center gap-2">
<span
className="w-1.5 h-1.5 rounded-full flex-shrink-0"
+3 -3
View File
@@ -13,7 +13,7 @@ interface PatternSummaryProps {
function getMaxSeverity(rules: CompiledRule[]): string {
for (const sev of SEVERITY_ORDER) {
if (rules.some(r => r.severity === sev)) return sev;
if (rules.some((r) => r.severity === sev)) return sev;
}
return 'INFO';
}
@@ -24,7 +24,7 @@ export default function PatternSummary({
onTogglePattern,
isToggling,
}: PatternSummaryProps) {
const enabledCount = rules.filter(r => r.enabled).length;
const enabledCount = rules.filter((r) => r.enabled).length;
const disabledCount = rules.length - enabledCount;
const maxSeverity = getMaxSeverity(rules);
@@ -59,7 +59,7 @@ export default function PatternSummary({
{/* Rule list */}
<div className="space-y-0">
{rules.map(rule => (
{rules.map((rule) => (
<div key={rule.id} className="flex items-center gap-2 py-0.5">
<span
className={`w-2 h-2 rounded-full flex-shrink-0 ${
+22 -6
View File
@@ -9,7 +9,11 @@ interface RegexTesterProps {
}
/** Try a rule's regex against pasted lines before saving it. */
export default function RegexTester({ pattern, excludePattern, onPatternChange }: RegexTesterProps) {
export default function RegexTester({
pattern,
excludePattern,
onPatternChange,
}: RegexTesterProps) {
const t = useT();
const [testInput, setTestInput] = useState('');
const { matches, error, isGoSpecific } = useRegexTester(pattern, testInput, excludePattern);
@@ -41,24 +45,32 @@ export default function RegexTester({ pattern, excludePattern, onPatternChange }
/>
</label>
{pattern && isGoSpecific && <span className="ss-st warn wrap">{t('auditRules.regex.goSpecific')}</span>}
{pattern && isGoSpecific && (
<span className="ss-st warn wrap">{t('auditRules.regex.goSpecific')}</span>
)}
{pattern && !isGoSpecific && error && <span className="ss-st bad wrap">{error}</span>}
{pattern && !isGoSpecific && !error && testInput && (
<div className="ss-list !shadow-none">
{matches.map((lm, i) => (
<div key={i} className="ss-r !min-h-[30px] !px-2.5">
<span className={`ss-st ${lm.matched && !lm.excluded ? 'ok' : lm.matched ? 'warn' : 'off'}`}>
<span
className={`ss-st ${lm.matched && !lm.excluded ? 'ok' : lm.matched ? 'warn' : 'off'}`}
>
{lm.matched && !lm.excluded ? 'Match' : lm.matched ? 'Excluded' : 'No match'}
</span>
{lm.matched && !lm.excluded && lm.matchStart != null && lm.matchEnd != null ? (
<span className="min-w-0 flex-1 truncate font-mono text-[12.5px]">
{lm.content.slice(0, lm.matchStart)}
<mark className="rounded-sm bg-ok-bg text-ok">{lm.content.slice(lm.matchStart, lm.matchEnd)}</mark>
<mark className="rounded-sm bg-ok-bg text-ok">
{lm.content.slice(lm.matchStart, lm.matchEnd)}
</mark>
{lm.content.slice(lm.matchEnd)}
</span>
) : (
<span className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-ink-3">{lm.content}</span>
<span className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-ink-3">
{lm.content}
</span>
)}
</div>
))}
@@ -69,7 +81,11 @@ export default function RegexTester({ pattern, excludePattern, onPatternChange }
<div className="ss-kv">
<span>Exclude</span>
<code className="font-mono text-[12.5px] break-all">{excludePattern}</code>
<span>{t(plural('auditRules.regex.suppressed', excludedLines.length), { count: excludedLines.length })}</span>
<span>
{t(plural('auditRules.regex.suppressed', excludedLines.length), {
count: excludedLines.length,
})}
</span>
</div>
)}
</div>
+12 -10
View File
@@ -1,7 +1,13 @@
import { radius } from '../../design';
import { riskColor, riskBgColor } from './helpers';
export default function RiskMeter({ riskLabel, riskScore }: { riskLabel: string; riskScore: number }) {
export default function RiskMeter({
riskLabel,
riskScore,
}: {
riskLabel: string;
riskScore: number;
}) {
const color = riskColor(riskLabel);
return (
@@ -17,19 +23,13 @@ export default function RiskMeter({ riskLabel, riskScore }: { riskLabel: string;
<span className="text-[10px] text-pencil-light uppercase tracking-wide leading-none">
Risk
</span>
<span
className="text-sm font-bold leading-none"
style={{ color }}
>
<span className="text-sm font-bold leading-none" style={{ color }}>
{riskLabel.toUpperCase()}
</span>
</div>
{/* Mini bar */}
<div className="flex flex-col items-end gap-0.5">
<div
className="w-12 h-1.5 bg-muted/50 overflow-hidden"
style={{ borderRadius: '999px' }}
>
<div className="w-12 h-1.5 bg-muted/50 overflow-hidden" style={{ borderRadius: '999px' }}>
<div
className="h-full"
style={{
@@ -39,7 +39,9 @@ export default function RiskMeter({ riskLabel, riskScore }: { riskLabel: string;
}}
/>
</div>
<span className="text-[10px] text-pencil-light leading-none font-mono">{riskScore}/100</span>
<span className="text-[10px] text-pencil-light leading-none font-mono">
{riskScore}/100
</span>
</div>
</div>
);
+7 -6
View File
@@ -13,9 +13,12 @@ interface RuleDetailCardProps {
function sourceBadgeVariant(source: string): 'default' | 'accent' | 'info' {
switch (source) {
case 'global': return 'accent';
case 'project': return 'info';
default: return 'default';
case 'global':
return 'accent';
case 'project':
return 'info';
default:
return 'default';
}
}
@@ -33,9 +36,7 @@ export default function RuleDetailCard({ rule, onTestRegex, onEditInYaml }: Rule
<div className="flex items-center gap-2">
<span className="text-xs text-pencil-light">Source</span>
<Badge variant={sourceBadgeVariant(rule.source)}>{rule.source}</Badge>
{rule.source !== 'builtin' && (
<Badge variant="warning">Overridden by {rule.source}</Badge>
)}
{rule.source !== 'builtin' && <Badge variant="warning">Overridden by {rule.source}</Badge>}
</div>
{/* Disabled badge */}
+20 -10
View File
@@ -2,20 +2,30 @@ import { palette } from '../../design';
export function riskColor(risk: string): string {
switch (risk) {
case 'critical': return palette.danger;
case 'high': return palette.warning;
case 'medium': return palette.info;
case 'low': return palette.success;
default: return palette.success;
case 'critical':
return palette.danger;
case 'high':
return palette.warning;
case 'medium':
return palette.info;
case 'low':
return palette.success;
default:
return palette.success;
}
}
export function riskBgColor(risk: string): string {
switch (risk) {
case 'critical': return 'rgba(192, 57, 43, 0.06)';
case 'high': return 'rgba(212, 135, 14, 0.06)';
case 'medium': return 'rgba(45, 93, 161, 0.06)';
case 'low': return 'rgba(46, 139, 87, 0.06)';
default: return 'rgba(46, 139, 87, 0.06)';
case 'critical':
return 'rgba(192, 57, 43, 0.06)';
case 'high':
return 'rgba(212, 135, 14, 0.06)';
case 'medium':
return 'rgba(45, 93, 161, 0.06)';
case 'low':
return 'rgba(46, 139, 87, 0.06)';
default:
return 'rgba(46, 139, 87, 0.06)';
}
}

Some files were not shown because too many files have changed in this diff Show More