Compare commits

..
Author SHA1 Message Date
Peter Steinberger c1e6b985d9 fix: add root undici devDependency for e2e (#255) (thanks @tanujbhaud) 2026-02-13 15:23:00 +01:00
Tanuj Bhaud 7fcbcd345a fix(vt): explicit return types and missing undici dependency
Refactor action handlers in convex/vt.ts to use explicit return types, resolving circular type inference (TS7022). Also add undici to devDependencies for E2E tests.
2026-02-13 15:22:07 +01:00
Peter SteinbergerandSash Zats ddddb431c2 fix: make /search host-aware in SSR (#257)
* fix: make /search mode-aware

Notes:\n- Medium: /search now depends on getSiteMode() during beforeLoad. On server-side routing, if VITE_SITE_MODE isn’t set and VITE_SOULHUB_SITE_URL is set (as in .env.local), getSiteMode() will resolve to souls and redirect /search to / even on the ClawdHub deployment. This is a regression risk vs the old always-/skills redirect. Confirm deployment envs guarantee correct mode. src/routes/search.tsx:9-31

* fix: make /search host-aware in SSR

* chore: fix lint and route tree for /search route

---------

Co-authored-by: Sash Zats <sash@zats.io>
2026-02-13 14:26:31 +01:00
David AronchickandPeter Steinberger 78c27579a3 fix(cli): secure config file permissions (#164)
* fix(cli): secure config file permissions and reduce duplication

Security:
- Config files now created with 0600 permissions (owner read/write only)
- Config directories created with 0700 permissions
- Protects API tokens from other users on shared systems

Maintainability:
- Extract resolveConfigPath() helper to reduce code duplication
- Same legacy fallback logic (clawhub -> clawdhub) now in one place

* fix(cli): tolerate unsupported chmod errors for config

---------

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-02-13 13:57:03 +01:00
xcqtnrandPeter Steinberger 9aebc35d86 fix: prevent infinite loading loop on skills page (#90)
* fix: prevent infinite loading loop on skills pageAdd isLoadingMore guard to IntersectionObserver useEffect to preventcontinuous WebSocket queries when user is idle at bottom of page.The observer now won't set up while a request is in progress, breakingthe infinite loop cycle.Fixes: Related to #89

* fix: prevent repeated skills auto-load requests (#90) (thanks @xcqtnr)

* fix: resolve PR merge conflicts and keep observer regression test (#90) (thanks @xcqtnr)

---------

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-02-13 05:44:36 +01:00
Peter Steinberger fc63f47ffa chore(release): 0.6.1 2026-02-13 05:14:16 +01:00
Gaurav SharmaandPeter Steinberger 0b83ea6ff3 fix: prevent horizontal overflow from long code blocks in skill pages (#183)
* Fix: Prevent horizontal overflow from long code blocks in skill pages

- Add max-width: 100% to .file-list-body and .file-row
- Prevents page-wide overflow when skills contain long code examples
- Markdown pre blocks already have overflow-x: auto, but parent containers were expanding infinitely
- Fixes issue where skills with 400+ char lines (e.g. browser automation commands) cause horizontal scrolling

Affected: Skills with long inline code in markdown (browser act commands, etc.)

* fix: add max-width to .file-list container to prevent overflow

- Also ensures .file-list-body constraint is inherited properly
- Prevents long code blocks from expanding file list container

* fix: add max-width to all markdown containers and pre tags

- Add max-width: 100% to .markdown, .tab-body, .markdown pre
- Ensures code blocks are constrained and show horizontal scrollbar
- Prevents content from expanding parent containers beyond viewport

* fix: add overflow-x to parent containers for horizontal scroll

Adds overflow-x: auto to .skill-detail-stack, .tab-card, and .tab-body
to ensure long code blocks are scrollable within the content area
instead of causing page-wide horizontal overflow.

Fixes horizontal overflow issue on skill pages with long code examples
(e.g., browser automation commands with 400+ character lines).

Tested on zepto skill page - page now stays within viewport (1200px)
and code blocks are accessible via horizontal scrollbar in tab area.

* docs: note code-block overflow fix in changelog (#183) (thanks @bewithgaurav)

---------

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-02-13 05:09:31 +01:00
LimitlessandLimitless2023 191b5763ec fix: include comment deltas in action-based stat processing & add stats reconciliation (#194)
Bug 1: applyAggregatedStatsAndUpdateCursor was missing 'comments' in both
the guard condition and the applySkillStatDeltas call. This caused comment
count deltas to be silently dropped during cron-based event processing,
while stars/downloads/installs were processed correctly.

Bug 2: No reconciliation mechanism existed. If events were missed due to
cursor issues or processing errors, skill stats (stars, comments) would
remain stale with no way to recover. Added reconcileSkillStarCounts
maintenance mutation that counts actual records in the stars and comments
tables and patches any out-of-sync skill stats.

Fixes #193

Co-authored-by: Limitless2023 <limitless@users.noreply.github.com>
2026-02-13 04:55:16 +01:00
Peter Steinberger 5397a8e5e0 fix: scope reauth fix; keep banned users blocked (#177) (thanks @tanujbhaud) 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 7949402888 test: add missing coverage for fresh-login reactivation and identity mismatch guard 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 2e3920d41a fix: use valid crons.interval and set to 1 minute 2026-02-13 04:34:46 +01:00
Tanuj Bhaud dd4fc823f6 fix: allow re-auth when existingUserId is null 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 135b9ea9b0 fix: ensure reactivation only matches soft-deleted user (prevents bypass) 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 17a106cefe fix: resolve final lint error in auth tests 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 496da99392 fix: update tests to include required existingUserId parameter 2026-02-13 04:34:46 +01:00
Tanuj Bhaud 107486adfb fix: restore existingUserId check for type safety 2026-02-13 04:34:46 +01:00
Tanuj Bhaud ef9e7f0e57 test: update auth tests for direct deletedAt check 2026-02-13 04:34:46 +01:00
Tanuj Bhaud ecc8ad3833 fix: allow soft-deleted users to re-authenticate
Fixes Issue #32 where users who soft-deleted their accounts were unable to sign back in because the re-auth logic was only triggering when an existingUserId was passed by the auth provider, which doesn't happen during a standard fresh login flow.
2026-02-13 04:34:46 +01:00
Peter Steinberger 93c2b23b72 docs: add 0.6.1 unreleased changelog from post-0.6.0 commits 2026-02-13 04:14:16 +01:00
DCollandPeter Steinberger 2e492a5b87 fix(http): remove allowH2 from undici Agent — causes fetch failed on Node.js 22+ (#245)
* Remove allowH2 option from global dispatcher

fix/remove-allowH2-undici-node22-compat

* fix(http): remove allowH2 from e2e dispatcher

---------

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-02-13 03:02:57 +01:00
Peter Steinberger 91c87d1322 test: fix search test handler typing 2026-02-13 02:48:16 +01:00
Peter Steinberger 91b8f160f8 test: add search fallback coverage 2026-02-13 02:44:53 +01:00
Peter Steinberger 32f3ce45e9 fix: add lexical fallback for skill search recall 2026-02-13 02:22:32 +01:00
Peter Steinberger 19bfe48a67 fix: prioritize relevant skills in search 2026-02-13 02:15:19 +01:00
Peter Steinberger 19951fccf7 docs: thank @superlowburn for PR #246 2026-02-13 01:22:38 +01:00
7dcada9122 fix: handle GitHub API rate limits in account age check (#246)
* fix: handle GitHub API rate limits in account age check

The GitHub account lookup uses unauthenticated requests (60 req/hr
per IP). Since this runs server-side in Convex, all users share the
same IP and quickly exhaust the rate limit, causing "GitHub account
lookup failed" errors during skill publish.

- Detect 403/429 responses and surface a clear rate-limit message
- Support optional GITHUB_TOKEN env var for authenticated requests
  (5,000 req/hr)

Fixes #155

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: stabilize GitHub account gate tests and docs

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-02-13 01:21:30 +01:00
55 changed files with 2898 additions and 2797 deletions
+13 -2
View File
@@ -1,15 +1,26 @@
# Changelog
## Unreleased
## 0.6.1 - 2026-02-13
### Added
- Security: add LLM-based security evaluation during skill publish.
- Parsing: recognize `metadata.openclaw` frontmatter and evaluate all skill files for requirements.
### Changed
- Performance: lazy-load Monaco diff viewer on demand (thanks @alexjcm, #212).
- Search: improve recall/ranking with lexical fallback and relevance prioritization.
- Moderation UX: collapse OpenClaw analysis by default; update spacing and default reasoning model.
### Fixed
- Upload gate: handle GitHub API rate limits and optional authenticated lookup token (thanks @superlowburn, #246).
- HTTP: remove `allowH2` from Undici agent to prevent `fetch failed` on Node.js 22+ (#245).
- Tests: add root `undici` dev dependency for Node E2E imports (thanks @tanujbhaud, #255).
- VirusTotal: fix scan sync race conditions and retry behavior in scan/backfill paths.
- Metadata: tolerate trailing commas in JSON metadata.
- Auth: allow soft-deleted users to re-authenticate on fresh login, while keeping banned users blocked (thanks @tanujbhaud, #177).
- Web: prevent horizontal overflow from long code blocks in skill pages (thanks @bewithgaurav, #183).
## 0.6.0 - 2026-02-10
### Added
- CLI/API: add `set-role` to change user roles (admin only).
- Security: quarantine skill publishes with VirusTotal scans + UI (thanks @aleph8, #130).
+8 -3
View File
@@ -57,13 +57,14 @@
"oxlint": "^1.42.0",
"oxlint-tsgolint": "^0.11.4",
"typescript": "^5.9.3",
"undici": "^7.19.2",
"vite": "^7.3.1",
"vitest": "^4.0.18",
},
},
"packages/clawdhub": {
"name": "clawhub",
"version": "0.5.0",
"version": "0.6.1",
"bin": {
"clawhub": "bin/clawdhub.js",
"clawdhub": "bin/clawdhub.js",
@@ -1298,7 +1299,7 @@
"ufo": ["ufo@1.6.3", "", {}, "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q=="],
"undici": ["undici@7.19.2", "", {}, "sha512-4VQSpGEGsWzk0VYxyB/wVX/Q7qf9t5znLRgs0dzszr9w9Fej/8RVNQ+S20vdXSAyra/bJ7ZQfGv6ZMj7UEbzSg=="],
"undici": ["undici@7.20.0", "", {}, "sha512-MJZrkjyd7DeC+uPZh+5/YaMDxFiiEEaDgbUSVMXayofAkDWF1088CDo+2RPg7B1BuS1qf1vgNE7xqwPxE0DuSQ=="],
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
@@ -1402,8 +1403,12 @@
"cheerio/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
"cheerio/undici": ["undici@7.19.2", "", {}, "sha512-4VQSpGEGsWzk0VYxyB/wVX/Q7qf9t5znLRgs0dzszr9w9Fej/8RVNQ+S20vdXSAyra/bJ7ZQfGv6ZMj7UEbzSg=="],
"cheerio/whatwg-mimetype": ["whatwg-mimetype@4.0.0", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],
"clawhub/undici": ["undici@7.19.2", "", {}, "sha512-4VQSpGEGsWzk0VYxyB/wVX/Q7qf9t5znLRgs0dzszr9w9Fej/8RVNQ+S20vdXSAyra/bJ7ZQfGv6ZMj7UEbzSg=="],
"convex/esbuild": ["esbuild@0.27.0", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.0", "@esbuild/android-arm": "0.27.0", "@esbuild/android-arm64": "0.27.0", "@esbuild/android-x64": "0.27.0", "@esbuild/darwin-arm64": "0.27.0", "@esbuild/darwin-x64": "0.27.0", "@esbuild/freebsd-arm64": "0.27.0", "@esbuild/freebsd-x64": "0.27.0", "@esbuild/linux-arm": "0.27.0", "@esbuild/linux-arm64": "0.27.0", "@esbuild/linux-ia32": "0.27.0", "@esbuild/linux-loong64": "0.27.0", "@esbuild/linux-mips64el": "0.27.0", "@esbuild/linux-ppc64": "0.27.0", "@esbuild/linux-riscv64": "0.27.0", "@esbuild/linux-s390x": "0.27.0", "@esbuild/linux-x64": "0.27.0", "@esbuild/netbsd-arm64": "0.27.0", "@esbuild/netbsd-x64": "0.27.0", "@esbuild/openbsd-arm64": "0.27.0", "@esbuild/openbsd-x64": "0.27.0", "@esbuild/openharmony-arm64": "0.27.0", "@esbuild/sunos-x64": "0.27.0", "@esbuild/win32-arm64": "0.27.0", "@esbuild/win32-ia32": "0.27.0", "@esbuild/win32-x64": "0.27.0" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA=="],
"dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
@@ -1412,7 +1417,7 @@
"htmlparser2/entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"jsdom/undici": ["undici@7.20.0", "", {}, "sha512-MJZrkjyd7DeC+uPZh+5/YaMDxFiiEEaDgbUSVMXayofAkDWF1088CDo+2RPg7B1BuS1qf1vgNE7xqwPxE0DuSQ=="],
"nitro/undici": ["undici@7.19.2", "", {}, "sha512-4VQSpGEGsWzk0VYxyB/wVX/Q7qf9t5znLRgs0dzszr9w9Fej/8RVNQ+S20vdXSAyra/bJ7ZQfGv6ZMj7UEbzSg=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
+35 -3
View File
@@ -29,12 +29,13 @@ function makeCtx({
describe('handleSoftDeletedUserReauth', () => {
const userId = 'users:1' as Id<'users'>
it('skips when no existing user', async () => {
it('skips when user not found', async () => {
const { ctx } = makeCtx({ user: null })
await handleSoftDeletedUserReauth(ctx as never, { userId, existingUserId: null })
await handleSoftDeletedUserReauth(ctx as never, { userId, existingUserId: userId })
expect(ctx.db.get).not.toHaveBeenCalled()
expect(ctx.db.get).toHaveBeenCalledWith(userId)
expect(ctx.db.query).not.toHaveBeenCalled()
})
it('skips active users', async () => {
@@ -57,6 +58,27 @@ describe('handleSoftDeletedUserReauth', () => {
})
})
it('restores soft-deleted users on fresh login (existingUserId is null)', async () => {
const { ctx } = makeCtx({ user: { deletedAt: 123 }, banRecord: null })
await handleSoftDeletedUserReauth(ctx as never, { userId, existingUserId: null })
expect(ctx.db.patch).toHaveBeenCalledWith(userId, {
deletedAt: undefined,
updatedAt: expect.any(Number),
})
})
it('skips reactivation when existingUserId does not match userId', async () => {
const otherUserId = 'users:999' as Id<'users'>
const { ctx } = makeCtx({ user: { deletedAt: 123 } })
await handleSoftDeletedUserReauth(ctx as never, { userId, existingUserId: otherUserId })
expect(ctx.db.query).not.toHaveBeenCalled()
expect(ctx.db.patch).not.toHaveBeenCalled()
})
it('blocks banned users with a custom message', async () => {
const { ctx } = makeCtx({ user: { deletedAt: 123 }, banRecord: { action: 'user.ban' } })
@@ -66,4 +88,14 @@ describe('handleSoftDeletedUserReauth', () => {
expect(ctx.db.patch).not.toHaveBeenCalled()
})
it('blocks banned users on fresh login (existingUserId is null)', async () => {
const { ctx } = makeCtx({ user: { deletedAt: 123 }, banRecord: { action: 'user.ban' } })
await expect(
handleSoftDeletedUserReauth(ctx as never, { userId, existingUserId: null }),
).rejects.toThrow(BANNED_REAUTH_MESSAGE)
expect(ctx.db.patch).not.toHaveBeenCalled()
})
})
+5 -2
View File
@@ -11,11 +11,14 @@ export async function handleSoftDeletedUserReauth(
ctx: GenericMutationCtx<DataModel>,
args: { userId: Id<'users'>; existingUserId: Id<'users'> | null },
) {
if (!args.existingUserId) return
const user = await ctx.db.get(args.userId)
if (!user?.deletedAt) return
// Verify that the incoming identity matches the soft-deleted user to prevent bypass.
if (args.existingUserId && args.existingUserId !== args.userId) {
return
}
const userId = args.userId
const banRecord = await ctx.db
.query('auditLogs')
-1
View File
@@ -270,7 +270,6 @@ async function skillsGetRouterV1Handler(ctx: ActionCtx, request: Request) {
version: result.latestVersion.version,
createdAt: result.latestVersion.createdAt,
changelog: result.latestVersion.changelog,
capabilities: (result.latestVersion.parsed as any)?.clawdis?.capabilities ?? [],
}
: null,
owner: result.owner
+79 -3
View File
@@ -1,5 +1,5 @@
/* @vitest-environment node */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { internal } from '../_generated/api'
import { requireGitHubAccountAge } from './githubAccount'
@@ -18,6 +18,11 @@ const ONE_DAY_MS = 24 * 60 * 60 * 1000
describe('requireGitHubAccountAge', () => {
beforeEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('uses cached githubCreatedAt when fresh', async () => {
@@ -86,7 +91,9 @@ describe('requireGitHubAccountAge', () => {
expect(fetchMock).toHaveBeenCalledWith(
'https://api.github.com/users/steipete',
expect.objectContaining({ headers: { 'User-Agent': 'clawhub' } }),
expect.objectContaining({
headers: expect.objectContaining({ 'User-Agent': 'clawhub' }),
}),
)
expect(runMutation).toHaveBeenCalledWith(internal.users.updateGithubMetaInternal, {
userId: 'users:1',
@@ -105,11 +112,80 @@ describe('requireGitHubAccountAge', () => {
githubFetchedAt: 0,
})
const runMutation = vi.fn()
const fetchMock = vi.fn().mockResolvedValue({ ok: false })
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 404 })
vi.stubGlobal('fetch', fetchMock)
await expect(
requireGitHubAccountAge({ runQuery, runMutation } as never, 'users:1' as never),
).rejects.toThrow(/GitHub account lookup failed/i)
})
it('throws rate-limit error on 403', async () => {
const runQuery = vi.fn().mockResolvedValue({
_id: 'users:1',
handle: 'steipete',
githubCreatedAt: undefined,
githubFetchedAt: 0,
})
const runMutation = vi.fn()
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 403 })
vi.stubGlobal('fetch', fetchMock)
await expect(
requireGitHubAccountAge({ runQuery, runMutation } as never, 'users:1' as never),
).rejects.toThrow(/rate limit exceeded/i)
})
it('throws rate-limit error on 429', async () => {
const runQuery = vi.fn().mockResolvedValue({
_id: 'users:1',
handle: 'steipete',
githubCreatedAt: undefined,
githubFetchedAt: 0,
})
const runMutation = vi.fn()
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 429 })
vi.stubGlobal('fetch', fetchMock)
await expect(
requireGitHubAccountAge({ runQuery, runMutation } as never, 'users:1' as never),
).rejects.toThrow(/rate limit exceeded/i)
})
it('includes Authorization header when GITHUB_TOKEN is set', async () => {
vi.useFakeTimers()
const now = new Date('2026-02-02T12:00:00Z')
vi.setSystemTime(now)
vi.stubEnv('GITHUB_TOKEN', 'ghp_test123')
const runQuery = vi.fn().mockResolvedValue({
_id: 'users:1',
handle: 'steipete',
githubCreatedAt: undefined,
githubFetchedAt: now.getTime() - 2 * ONE_DAY_MS,
})
const runMutation = vi.fn()
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
created_at: '2020-01-01T00:00:00Z',
}),
})
vi.stubGlobal('fetch', fetchMock)
await requireGitHubAccountAge({ runQuery, runMutation } as never, 'users:1' as never)
expect(fetchMock).toHaveBeenCalledWith(
'https://api.github.com/users/steipete',
expect.objectContaining({
headers: {
'User-Agent': 'clawhub',
Authorization: 'Bearer ghp_test123',
},
}),
)
vi.useRealTimers()
})
})
+13 -2
View File
@@ -24,10 +24,21 @@ export async function requireGitHubAccountAge(ctx: ActionCtx, userId: Id<'users'
const stale = !createdAt || now - fetchedAt > FETCH_TTL_MS
if (stale) {
const headers: Record<string, string> = { 'User-Agent': 'clawhub' }
const token = process.env.GITHUB_TOKEN
if (token) {
headers.Authorization = `Bearer ${token}`
}
const response = await fetch(`${GITHUB_API}/users/${encodeURIComponent(handle)}`, {
headers: { 'User-Agent': 'clawhub' },
headers,
})
if (!response.ok) throw new ConvexError('GitHub account lookup failed')
if (!response.ok) {
if (response.status === 403 || response.status === 429) {
throw new ConvexError('GitHub API rate limit exceeded — please try again in a few minutes')
}
throw new ConvexError('GitHub account lookup failed')
}
const payload = (await response.json()) as GitHubUser
const parsed = payload.created_at ? Date.parse(payload.created_at) : Number.NaN
+2
View File
@@ -33,6 +33,8 @@ describe('searchText', () => {
expect(matchesExactTokens(['pad'], ['Padel', '/padel', 'Tennis-like sport'])).toBe(true)
// "xyz" should not match anything
expect(matchesExactTokens(['xyz'], ['GoHome', '/gohome', 'Navigate home'])).toBe(false)
// "notion" should not match "annotations" (substring only)
expect(matchesExactTokens(['notion'], ['Annotations helper', '/annotations'])).toBe(false)
})
it('matchesExactTokens ignores empty inputs', () => {
+1 -1
View File
@@ -20,7 +20,7 @@ export function matchesExactTokens(
if (textTokens.length === 0) return false
// Require at least one token to prefix-match, allowing vector similarity to determine relevance
return queryTokens.some((queryToken) =>
textTokens.some((textToken) => textToken.includes(queryToken)),
textTokens.some((textToken) => textToken.startsWith(queryToken)),
)
}
-10
View File
@@ -335,16 +335,6 @@ export function assembleEvalUserMessage(ctx: SkillEvalContext): string {
- Primary credential: ${primaryEnv}
- Required config paths: ${config.length ? config.join(', ') : 'none'}`)
const capabilities = Array.isArray(clawdis.capabilities)
? (clawdis.capabilities as string[])
: []
if (capabilities.length > 0) {
sections.push(`### Declared capabilities\n- ${capabilities.join(', ')}`)
} else {
sections.push(`### Declared capabilities\nNone declared.`)
}
// Install specifications
if (install.length > 0) {
const specLines = install.map((spec, i) => {
-41
View File
@@ -1,41 +0,0 @@
// ---------------------------------------------------------------------------
// Skill capabilities — shared spec between ClawHub and OpenClaw.
//
// KEEP IN SYNC with openclaw/src/agents/skills/types.ts SKILL_CAPABILITIES.
//
// These values are validated during skill publish (ClawHub) and at load time
// (OpenClaw runtime). Both sides must accept the same enum values.
// ---------------------------------------------------------------------------
export const SKILL_CAPABILITIES = [
"shell", // exec, process — run shell commands
"filesystem", // read, write, edit, apply_patch — file mutations
"network", // web_search, web_fetch — outbound HTTP
"browser", // browser — browser automation
"sessions", // sessions_spawn, sessions_send — cross-session orchestration
] as const;
export type SkillCapability = (typeof SKILL_CAPABILITIES)[number];
/**
* Validate that a list of capability strings are all recognized values.
* Returns only the valid entries, dropping unknowns silently.
*/
export function validateCapabilities(raw: unknown): SkillCapability[] {
if (!Array.isArray(raw)) {
return [];
}
return raw.filter(
(v): v is SkillCapability =>
typeof v === "string" && (SKILL_CAPABILITIES as readonly string[]).includes(v),
);
}
/**
* Capabilities that should trigger extra moderation review when declared
* by community (unverified) publishers.
*/
export const HIGH_RISK_CAPABILITIES: readonly SkillCapability[] = [
"shell",
"sessions",
];
-3
View File
@@ -9,7 +9,6 @@ import {
TEXT_FILE_EXTENSION_SET,
} from 'clawhub-schema'
import { parse as parseYaml } from 'yaml'
import { validateCapabilities } from './skillCapabilities'
export type ParsedSkillFrontmatter = Record<string, unknown>
export type { ClawdisSkillMetadata, SkillInstallSpec }
@@ -122,8 +121,6 @@ export function parseClawdisMetadata(frontmatter: ParsedSkillFrontmatter) {
if (nix) metadata.nix = nix
const config = parseClawdbotConfigSpec(clawdisObj.config)
if (config) metadata.config = config
const capabilities = validateCapabilities(clawdisObj.capabilities)
if (capabilities.length > 0) metadata.capabilities = capabilities
return parseArk(ClawdisSkillMetadataSchema, metadata, 'Clawdis metadata')
} catch {
+295 -2
View File
@@ -1,12 +1,305 @@
/* @vitest-environment node */
import { describe, expect, it } from 'vitest'
import { __test } from './search'
import { describe, expect, it, vi } from 'vitest'
import { tokenize } from './lib/searchText'
import { __test, lexicalFallbackSkills, searchSkills } from './search'
const { generateEmbeddingMock, getSkillBadgeMapsMock } = vi.hoisted(() => ({
generateEmbeddingMock: vi.fn(),
getSkillBadgeMapsMock: vi.fn(),
}))
vi.mock('./lib/embeddings', () => ({
generateEmbedding: generateEmbeddingMock,
}))
vi.mock('./lib/badges', () => ({
getSkillBadgeMaps: getSkillBadgeMapsMock,
isSkillHighlighted: (skill: { badges?: Record<string, unknown> }) =>
Boolean(skill.badges?.highlighted),
}))
type WrappedHandler = {
_handler: (ctx: unknown, args: unknown) => Promise<unknown>
}
const searchSkillsHandler = (searchSkills as unknown as WrappedHandler)._handler
const lexicalFallbackSkillsHandler = (lexicalFallbackSkills as unknown as WrappedHandler)._handler
describe('search helpers', () => {
it('returns fallback results when vector candidates are empty', async () => {
generateEmbeddingMock.mockResolvedValueOnce([0, 1, 2])
const fallback = [
{
skill: makePublicSkill({ id: 'skills:orf', slug: 'orf', displayName: 'ORF' }),
version: null,
ownerHandle: 'steipete',
},
]
const runQuery = vi
.fn()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce(fallback)
const result = await searchSkillsHandler(
{
vectorSearch: vi.fn().mockResolvedValue([]),
runQuery,
},
{ query: 'orf', limit: 10 },
)
expect(result).toHaveLength(1)
expect(result[0].skill.slug).toBe('orf')
expect(runQuery).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ query: 'orf', queryTokens: ['orf'] }),
)
})
it('applies highlightedOnly filtering in lexical fallback', async () => {
const highlighted = makeSkillDoc({
id: 'skills:hl',
slug: 'orf-highlighted',
displayName: 'ORF Highlighted',
})
const plain = makeSkillDoc({ id: 'skills:plain', slug: 'orf-plain', displayName: 'ORF Plain' })
getSkillBadgeMapsMock.mockResolvedValueOnce(
new Map([
['skills:hl', { highlighted: { byUserId: 'users:mod', at: 1 } }],
['skills:plain', {}],
]),
)
const result = await lexicalFallbackSkillsHandler(
makeLexicalCtx({
exactSlugSkill: null,
recentSkills: [highlighted, plain],
}),
{ query: 'orf', queryTokens: ['orf'], highlightedOnly: true, limit: 10 },
)
expect(result).toHaveLength(1)
expect(result[0].skill.slug).toBe('orf-highlighted')
})
it('includes exact slug match from by_slug even when recent scan is empty', async () => {
const exactSlugSkill = makeSkillDoc({ id: 'skills:orf', slug: 'orf', displayName: 'ORF' })
getSkillBadgeMapsMock.mockResolvedValueOnce(new Map([['skills:orf', {}]]))
const ctx = makeLexicalCtx({
exactSlugSkill,
recentSkills: [],
})
const result = await lexicalFallbackSkillsHandler(ctx, {
query: 'orf',
queryTokens: ['orf'],
limit: 10,
})
expect(result).toHaveLength(1)
expect(result[0].skill.slug).toBe('orf')
expect(ctx.db.query).toHaveBeenCalledWith('skills')
})
it('dedupes overlap and enforces rank + limit across vector and fallback', async () => {
generateEmbeddingMock.mockResolvedValueOnce([0, 1, 2])
const vectorEntries = [
{
embeddingId: 'skillEmbeddings:a',
skill: makePublicSkill({
id: 'skills:a',
slug: 'foo-a',
displayName: 'Foo Alpha',
downloads: 10,
}),
version: null,
ownerHandle: 'one',
},
{
embeddingId: 'skillEmbeddings:b',
skill: makePublicSkill({
id: 'skills:b',
slug: 'foo-b',
displayName: 'Foo Beta',
downloads: 2,
}),
version: null,
ownerHandle: 'two',
},
]
const fallbackEntries = [
{
skill: makePublicSkill({
id: 'skills:a',
slug: 'foo-a',
displayName: 'Foo Alpha',
downloads: 10,
}),
version: null,
ownerHandle: 'one',
},
{
skill: makePublicSkill({
id: 'skills:c',
slug: 'foo-c',
displayName: 'Foo Classic',
downloads: 1,
}),
version: null,
ownerHandle: 'three',
},
]
const runQuery = vi
.fn()
.mockResolvedValueOnce(vectorEntries)
.mockResolvedValueOnce([])
.mockResolvedValueOnce(fallbackEntries)
const result = await searchSkillsHandler(
{
vectorSearch: vi.fn().mockResolvedValue([
{ _id: 'skillEmbeddings:a', _score: 0.4 },
{ _id: 'skillEmbeddings:b', _score: 0.9 },
]),
runQuery,
},
{ query: 'foo', limit: 2 },
)
expect(result).toHaveLength(2)
expect(result[0].skill.slug).toBe('foo-b')
expect(new Set(result.map((entry: { skill: { _id: string } }) => entry.skill._id)).size).toBe(2)
})
it('advances candidate limit until max', () => {
expect(__test.getNextCandidateLimit(50, 1000)).toBe(100)
expect(__test.getNextCandidateLimit(800, 1000)).toBe(1000)
expect(__test.getNextCandidateLimit(1000, 1000)).toBeNull()
})
it('boosts exact slug/name matches over loose matches', () => {
const queryTokens = tokenize('notion')
const exactScore = __test.scoreSkillResult(queryTokens, 0.4, 'Notion Sync', 'notion-sync', 5)
const looseScore = __test.scoreSkillResult(queryTokens, 0.6, 'Notes Sync', 'notes-sync', 500)
expect(exactScore).toBeGreaterThan(looseScore)
})
it('adds a popularity prior for equally relevant matches', () => {
const queryTokens = tokenize('notion')
const lowDownloads = __test.scoreSkillResult(
queryTokens,
0.5,
'Notion Helper',
'notion-helper',
0,
)
const highDownloads = __test.scoreSkillResult(
queryTokens,
0.5,
'Notion Helper',
'notion-helper',
1000,
)
expect(highDownloads).toBeGreaterThan(lowDownloads)
})
it('merges fallback matches without duplicate skill ids', () => {
const primary = [
{
embeddingId: 'skillEmbeddings:1',
skill: { _id: 'skills:1' },
},
] as unknown as Parameters<typeof __test.mergeUniqueBySkillId>[0]
const fallback = [
{
skill: { _id: 'skills:1' },
},
{
skill: { _id: 'skills:2' },
},
] as unknown as Parameters<typeof __test.mergeUniqueBySkillId>[1]
const merged = __test.mergeUniqueBySkillId(primary, fallback)
expect(merged).toHaveLength(2)
expect(merged.map((entry) => entry.skill._id)).toEqual(['skills:1', 'skills:2'])
})
})
function makePublicSkill(params: {
id: string
slug: string
displayName: string
downloads?: number
}) {
return {
_id: params.id,
_creationTime: 1,
slug: params.slug,
displayName: params.displayName,
summary: `${params.displayName} summary`,
ownerUserId: 'users:owner',
canonicalSkillId: undefined,
forkOf: undefined,
latestVersionId: 'skillVersions:1',
tags: {},
badges: {},
stats: {
downloads: params.downloads ?? 0,
installsCurrent: 0,
installsAllTime: 0,
stars: 0,
versions: 1,
comments: 0,
},
createdAt: 1,
updatedAt: 1,
}
}
function makeSkillDoc(params: { id: string; slug: string; displayName: string }) {
return {
...makePublicSkill(params),
_creationTime: 1,
moderationStatus: 'active',
moderationFlags: [],
softDeletedAt: undefined,
}
}
function makeLexicalCtx(params: {
exactSlugSkill: ReturnType<typeof makeSkillDoc> | null
recentSkills: Array<ReturnType<typeof makeSkillDoc>>
}) {
return {
db: {
query: vi.fn((table: string) => {
if (table !== 'skills') throw new Error(`Unexpected table ${table}`)
return {
withIndex: (index: string) => {
if (index === 'by_slug') {
return {
unique: vi.fn().mockResolvedValue(params.exactSlugSkill),
}
}
if (index === 'by_active_updated') {
return {
order: () => ({
take: vi.fn().mockResolvedValue(params.recentSkills),
}),
}
}
throw new Error(`Unexpected index ${index}`)
},
}
}),
get: vi.fn(async (id: string) => {
if (id.startsWith('users:')) return { _id: id, handle: 'owner' }
if (id.startsWith('skillVersions:')) return { _id: id, version: '1.0.0' }
return null
}),
},
}
}
+193 -14
View File
@@ -7,20 +7,86 @@ import { generateEmbedding } from './lib/embeddings'
import { toPublicSkill, toPublicSoul } from './lib/public'
import { matchesExactTokens, tokenize } from './lib/searchText'
type HydratedEntry = {
embeddingId: Id<'skillEmbeddings'>
type SkillSearchEntry = {
embeddingId?: Id<'skillEmbeddings'>
skill: NonNullable<ReturnType<typeof toPublicSkill>>
version: Doc<'skillVersions'> | null
ownerHandle: string | null
}
type SearchResult = HydratedEntry & { score: number }
type SearchResult = SkillSearchEntry & { score: number }
const SLUG_EXACT_BOOST = 1.4
const SLUG_PREFIX_BOOST = 0.8
const NAME_EXACT_BOOST = 1.1
const NAME_PREFIX_BOOST = 0.6
const POPULARITY_WEIGHT = 0.08
const FALLBACK_SCAN_LIMIT = 1200
function getNextCandidateLimit(current: number, max: number) {
const next = Math.min(current * 2, max)
return next > current ? next : null
}
function matchesAllTokens(
queryTokens: string[],
candidateTokens: string[],
matcher: (candidate: string, query: string) => boolean,
) {
if (queryTokens.length === 0 || candidateTokens.length === 0) return false
return queryTokens.every((queryToken) =>
candidateTokens.some((candidateToken) => matcher(candidateToken, queryToken)),
)
}
function getLexicalBoost(queryTokens: string[], displayName: string, slug: string) {
const slugTokens = tokenize(slug)
const nameTokens = tokenize(displayName)
let boost = 0
if (matchesAllTokens(queryTokens, slugTokens, (candidate, query) => candidate === query)) {
boost += SLUG_EXACT_BOOST
} else if (
matchesAllTokens(queryTokens, slugTokens, (candidate, query) => candidate.startsWith(query))
) {
boost += SLUG_PREFIX_BOOST
}
if (matchesAllTokens(queryTokens, nameTokens, (candidate, query) => candidate === query)) {
boost += NAME_EXACT_BOOST
} else if (
matchesAllTokens(queryTokens, nameTokens, (candidate, query) => candidate.startsWith(query))
) {
boost += NAME_PREFIX_BOOST
}
return boost
}
function scoreSkillResult(
queryTokens: string[],
vectorScore: number,
displayName: string,
slug: string,
downloads: number,
) {
const lexicalBoost = getLexicalBoost(queryTokens, displayName, slug)
const popularityBoost = Math.log1p(Math.max(downloads, 0)) * POPULARITY_WEIGHT
return vectorScore + lexicalBoost + popularityBoost
}
function mergeUniqueBySkillId(primary: SkillSearchEntry[], fallback: SkillSearchEntry[]) {
if (fallback.length === 0) return primary
const out = [...primary]
const seen = new Set(primary.map((entry) => entry.skill._id))
for (const entry of fallback) {
if (seen.has(entry.skill._id)) continue
seen.add(entry.skill._id)
out.push(entry)
}
return out
}
export const searchSkills: ReturnType<typeof action> = action({
args: {
query: v.string(),
@@ -43,9 +109,9 @@ export const searchSkills: ReturnType<typeof action> = action({
// Convex vectorSearch max limit is 256; clamp candidate sizes accordingly.
const maxCandidate = Math.min(Math.max(limit * 10, 200), 256)
let candidateLimit = Math.min(Math.max(limit * 3, 50), 256)
let hydrated: HydratedEntry[] = []
let hydrated: SkillSearchEntry[] = []
let scoreById = new Map<Id<'skillEmbeddings'>, number>()
let exactMatches: HydratedEntry[] = []
let exactMatches: SkillSearchEntry[] = []
while (candidateLimit <= maxCandidate) {
const results = await ctx.vectorSearch('skillEmbeddings', 'by_embedding', {
@@ -56,7 +122,7 @@ export const searchSkills: ReturnType<typeof action> = action({
hydrated = (await ctx.runQuery(internal.search.hydrateResults, {
embeddingIds: results.map((result) => result._id),
})) as HydratedEntry[]
})) as SkillSearchEntry[]
scoreById = new Map<Id<'skillEmbeddings'>, number>(
results.map((result) => [result._id, result._score]),
@@ -95,12 +161,34 @@ export const searchSkills: ReturnType<typeof action> = action({
candidateLimit = nextLimit
}
return exactMatches
.map((entry) => ({
...entry,
score: scoreById.get(entry.embeddingId) ?? 0,
}))
const fallbackMatches =
exactMatches.length >= limit
? []
: ((await ctx.runQuery(internal.search.lexicalFallbackSkills, {
query,
queryTokens,
limit: Math.min(Math.max(limit * 4, 200), FALLBACK_SCAN_LIMIT),
highlightedOnly: args.highlightedOnly,
})) as SkillSearchEntry[])
const mergedMatches = mergeUniqueBySkillId(exactMatches, fallbackMatches)
return mergedMatches
.map((entry) => {
const vectorScore = entry.embeddingId ? (scoreById.get(entry.embeddingId) ?? 0) : 0
return {
...entry,
score: scoreSkillResult(
queryTokens,
vectorScore,
entry.skill.displayName,
entry.skill.slug,
entry.skill.stats.downloads,
),
}
})
.filter((entry) => entry.skill)
.sort((a, b) => b.score - a.score || b.skill.stats.downloads - a.skill.stats.downloads)
.slice(0, limit)
},
})
@@ -115,7 +203,7 @@ export const getBadgeMapsForSkills = internalQuery({
export const hydrateResults = internalQuery({
args: { embeddingIds: v.array(v.id('skillEmbeddings')) },
handler: async (ctx, args): Promise<HydratedEntry[]> => {
handler: async (ctx, args): Promise<SkillSearchEntry[]> => {
const ownerHandleCache = new Map<Id<'users'>, Promise<string | null>>()
const getOwnerHandle = (ownerUserId: Id<'users'>) => {
@@ -144,7 +232,92 @@ export const hydrateResults = internalQuery({
}),
)
return entries.filter((entry): entry is HydratedEntry => entry !== null)
return entries.filter((entry): entry is SkillSearchEntry => entry !== null)
},
})
export const lexicalFallbackSkills = internalQuery({
args: {
query: v.string(),
queryTokens: v.array(v.string()),
limit: v.optional(v.number()),
highlightedOnly: v.optional(v.boolean()),
},
handler: async (ctx, args): Promise<SkillSearchEntry[]> => {
const limit = Math.min(Math.max(args.limit ?? 200, 10), FALLBACK_SCAN_LIMIT)
const seenSkillIds = new Set<Id<'skills'>>()
const candidateSkills: Doc<'skills'>[] = []
const slugQuery = args.query.trim().toLowerCase()
if (/^[a-z0-9][a-z0-9-]*$/.test(slugQuery)) {
const exactSlugSkill = await ctx.db
.query('skills')
.withIndex('by_slug', (q) => q.eq('slug', slugQuery))
.unique()
if (exactSlugSkill && !exactSlugSkill.softDeletedAt) {
seenSkillIds.add(exactSlugSkill._id)
candidateSkills.push(exactSlugSkill)
}
}
const recentSkills = await ctx.db
.query('skills')
.withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined))
.order('desc')
.take(FALLBACK_SCAN_LIMIT)
for (const skill of recentSkills) {
if (seenSkillIds.has(skill._id)) continue
seenSkillIds.add(skill._id)
candidateSkills.push(skill)
}
const matched = candidateSkills.filter((skill) =>
matchesExactTokens(args.queryTokens, [skill.displayName, skill.slug, skill.summary]),
)
if (matched.length === 0) return []
const ownerHandleCache = new Map<Id<'users'>, Promise<string | null>>()
const getOwnerHandle = (ownerUserId: Id<'users'>) => {
const cached = ownerHandleCache.get(ownerUserId)
if (cached) return cached
const handlePromise = ctx.db
.get(ownerUserId)
.then((owner) => owner?.handle ?? owner?._id ?? null)
ownerHandleCache.set(ownerUserId, handlePromise)
return handlePromise
}
const entries = await Promise.all(
matched.map(async (skill) => {
const [version, ownerHandle] = await Promise.all([
skill.latestVersionId ? ctx.db.get(skill.latestVersionId) : Promise.resolve(null),
getOwnerHandle(skill.ownerUserId),
])
const publicSkill = toPublicSkill(skill)
if (!publicSkill) return null
return { skill: publicSkill, version, ownerHandle }
}),
)
const validEntries = entries.filter((entry): entry is SkillSearchEntry => entry !== null)
if (validEntries.length === 0) return []
const badgeMap = await getSkillBadgeMaps(
ctx,
validEntries.map((entry) => entry.skill._id),
)
const withBadges = validEntries.map((entry) => ({
...entry,
skill: {
...entry.skill,
badges: badgeMap.get(entry.skill._id) ?? {},
},
}))
const filtered = args.highlightedOnly
? withBadges.filter((entry) => isSkillHighlighted(entry.skill))
: withBadges
return filtered.slice(0, limit)
},
})
@@ -251,4 +424,10 @@ export const getSkillBadgeMapsInternal = internalQuery({
},
})
export const __test = { getNextCandidateLimit }
export const __test = {
getNextCandidateLimit,
matchesAllTokens,
getLexicalBoost,
scoreSkillResult,
mergeUniqueBySkillId,
}
+110
View File
@@ -0,0 +1,110 @@
/* @vitest-environment node */
import { describe, expect, it } from 'vitest'
// Test the aggregateEvents function by importing and testing the module logic
// Since aggregateEvents is not exported, we test the behavior indirectly through
// the event processing contract
describe('skill stat events - comment delta handling', () => {
it('aggregates comment and uncomment events into net deltas', () => {
// Simulate the aggregation logic from processSkillStatEventsAction
type EventKind =
| 'download'
| 'star'
| 'unstar'
| 'comment'
| 'uncomment'
| 'install_new'
| 'install_reactivate'
| 'install_deactivate'
| 'install_clear'
const events: { kind: EventKind; occurredAt: number }[] = [
{ kind: 'star', occurredAt: 1000 },
{ kind: 'comment', occurredAt: 2000 },
{ kind: 'comment', occurredAt: 3000 },
{ kind: 'uncomment', occurredAt: 4000 },
{ kind: 'download', occurredAt: 5000 },
]
// Replicate the aggregation logic
const result = {
downloads: 0,
stars: 0,
comments: 0,
installsAllTime: 0,
installsCurrent: 0,
downloadEvents: [] as number[],
installNewEvents: [] as number[],
}
for (const event of events) {
switch (event.kind) {
case 'download':
result.downloads += 1
result.downloadEvents.push(event.occurredAt)
break
case 'star':
result.stars += 1
break
case 'unstar':
result.stars -= 1
break
case 'comment':
result.comments += 1
break
case 'uncomment':
result.comments -= 1
break
case 'install_new':
result.installsAllTime += 1
result.installsCurrent += 1
result.installNewEvents.push(event.occurredAt)
break
case 'install_reactivate':
result.installsCurrent += 1
break
case 'install_deactivate':
result.installsCurrent -= 1
break
}
}
expect(result.stars).toBe(1)
expect(result.comments).toBe(1) // 2 comments - 1 uncomment
expect(result.downloads).toBe(1)
expect(result.downloadEvents).toEqual([5000])
})
it('should include comments in delta check (regression test for dropped comments)', () => {
// This test verifies the fix: the condition guard in applyAggregatedStatsAndUpdateCursor
// must include comments !== 0 so comment-only batches are not skipped
const delta = {
downloads: 0,
stars: 0,
comments: 3,
installsAllTime: 0,
installsCurrent: 0,
}
// The OLD buggy condition (missing comments):
const oldCondition =
delta.downloads !== 0 ||
delta.stars !== 0 ||
delta.installsAllTime !== 0 ||
delta.installsCurrent !== 0
// The FIXED condition (includes comments):
const fixedCondition =
delta.downloads !== 0 ||
delta.stars !== 0 ||
delta.comments !== 0 ||
delta.installsAllTime !== 0 ||
delta.installsCurrent !== 0
// With only comment deltas, the old condition would skip the patch
expect(oldCondition).toBe(false)
// The fixed condition correctly triggers the patch
expect(fixedCondition).toBe(true)
})
})
+2
View File
@@ -379,12 +379,14 @@ export const applyAggregatedStatsAndUpdateCursor = internalMutation({
if (
delta.downloads !== 0 ||
delta.stars !== 0 ||
delta.comments !== 0 ||
delta.installsAllTime !== 0 ||
delta.installsCurrent !== 0
) {
const patch = applySkillStatDeltas(skill, {
downloads: delta.downloads,
stars: delta.stars,
comments: delta.comments,
installsAllTime: delta.installsAllTime,
installsCurrent: delta.installsCurrent,
})
+96
View File
@@ -200,6 +200,102 @@ function buildSkillStatPatch(skill: Doc<'skills'>) {
}
}
/**
* Reconcile skill stats by counting actual records in source-of-truth tables.
*
* This fixes stats that got out of sync due to missed events, cursor issues,
* or bugs in the event processing pipeline. It counts:
* - stars: actual records in the `stars` table for each skill
* - comments: actual records in the `comments` table for each skill
*
* Downloads and installs are event-sourced only (no separate table to count from),
* so they cannot be reconciled this way.
*/
export const reconcileSkillStarCounts = internalMutation({
args: {
cursor: v.optional(v.string()),
batchSize: v.optional(v.number()),
},
handler: async (ctx, args) => {
const batchSize = clampInt(args.batchSize ?? 50, 1, 200)
const now = Date.now()
const { page, isDone, continueCursor } = await ctx.db
.query('skills')
.order('asc')
.paginate({ cursor: args.cursor ?? null, numItems: batchSize })
let patched = 0
for (const skill of page) {
// Count actual star records for this skill
const starRecords = await ctx.db
.query('stars')
.withIndex('by_skill_user', (q) => q.eq('skillId', skill._id))
.collect()
const actualStars = starRecords.length
// Count actual comment records for this skill
const commentRecords = await ctx.db
.query('comments')
.withIndex('by_skill', (q) => q.eq('skillId', skill._id))
.collect()
const actualComments = commentRecords.filter((c) => !c.softDeletedAt).length
// Check if stats are out of sync
if (skill.stats.stars !== actualStars || skill.stats.comments !== actualComments) {
const updatedStats = {
...skill.stats,
stars: actualStars,
comments: actualComments,
}
await ctx.db.patch(skill._id, {
statsStars: actualStars,
stats: updatedStats,
updatedAt: now,
})
patched += 1
}
}
return {
scanned: page.length,
patched,
cursor: isDone ? null : continueCursor,
isDone,
}
},
})
export const runReconcileSkillStarCountsInternal = internalAction({
args: {
batchSize: v.optional(v.number()),
maxBatches: v.optional(v.number()),
},
handler: async (ctx, args) => {
const batchSize = clampInt(args.batchSize ?? 50, 1, 200)
const maxBatches = clampInt(args.maxBatches ?? 10, 1, 50)
let cursor: string | undefined
let totalScanned = 0
let totalPatched = 0
for (let i = 0; i < maxBatches; i++) {
const result = (await ctx.runMutation(internal.statsMaintenance.reconcileSkillStarCounts, {
cursor,
batchSize,
})) as { scanned: number; patched: number; cursor: string | null; isDone: boolean }
totalScanned += result.scanned
totalPatched += result.patched
if (result.isDone) break
cursor = result.cursor ?? undefined
}
return { scanned: totalScanned, patched: totalPatched }
},
})
function clampInt(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), max)
}
+1
View File
@@ -30,6 +30,7 @@ Ensure Convex env is set (auth + embeddings):
- `OPENAI_API_KEY`
- `SITE_URL` (your web app URL)
- Optional webhook env (see `docs/webhook.md`)
- Optional: `GITHUB_TOKEN` (recommended; raises GitHub account lookup limit used by publish gate)
## 2) Deploy web app (Vercel)
+4
View File
@@ -40,6 +40,10 @@ Response:
{ "results": [{ "score": 0.123, "slug": "gifgrep", "displayName": "GifGrep", "summary": "…", "version": "1.2.3", "updatedAt": 1730000000000 }] }
```
Notes:
- Results are returned in relevance order (embedding similarity + exact slug/name token boosts + popularity prior from downloads).
### `GET /api/v1/skills`
Query params:
+4
View File
@@ -49,3 +49,7 @@ read_when:
- `githubFetchedAt` (fetch timestamp)
- Cache TTL: 24 hours.
- Gate applies to web uploads, CLI publish, and GitHub import.
- If GitHub responds `403` or `429`, publish fails with:
- `GitHub API rate limit exceeded — please try again in a few minutes`
- To reduce rate-limit failures, set `GITHUB_TOKEN` in Convex env for authenticated
GitHub API requests.
+1 -78
View File
@@ -65,14 +65,9 @@ metadata:
bins:
- curl
primaryEnv: TODOIST_API_KEY
capabilities:
- shell
- network
---
```
`capabilities` declares what system access your skill needs. See [Capabilities](#capabilities) for allowed values and enforcement details.
### Full field reference
| Field | Type | Description |
@@ -86,7 +81,6 @@ metadata:
| `skillKey` | `string` | Override the skill's invocation key. |
| `emoji` | `string` | Display emoji for the skill. |
| `homepage` | `string` | URL to the skill's homepage or docs. |
| `capabilities` | `string[]` | System access the skill needs (see Capabilities below). |
| `os` | `string[]` | OS restrictions (e.g. `["macos"]`, `["linux"]`). |
| `install` | `array` | Install specs for dependencies (see below). |
| `nix` | `object` | Nix plugin spec (see README). |
@@ -110,77 +104,9 @@ metadata:
Supported install kinds: `brew`, `node`, `go`, `uv`.
### Capabilities
Declare what system access your skill needs. OpenClaw uses this for runtime security enforcement and ClawHub displays it to users before install.
```yaml
metadata:
openclaw:
capabilities:
- shell
- filesystem
```
| Capability | What it means | Tools granted |
|-----------|--------------|---------------|
| `shell` | Run shell commands | `exec`, `process` |
| `filesystem` | Read, write, and edit files | `read`, `write`, `edit`, `apply_patch` |
| `network` | Make outbound HTTP requests | `web_search`, `web_fetch` |
| `browser` | Browser automation | `browser`, `canvas` |
| `sessions` | Cross-session orchestration | `sessions_spawn`, `sessions_send`, `subagents` |
**No capabilities declared = read-only skill.** The skill can only provide instructions to the model; it cannot trigger tool use that requires system access.
**Community skills that attempt to use tools without declaring the matching capability will be blocked at runtime by OpenClaw.** For example, a skill that runs shell commands must declare `shell`. If it doesn't, OpenClaw will deny `exec` calls when that skill is loaded.
Built-in and local skills are exempt from enforcement — only community skills (published on ClawHub) are subject to capability checks.
### Why this matters
Published skills go through two layers of security checks. Keeping your declarations accurate helps your skill pass both.
**Layer 1: ClawHub publish-time evaluation.** Every published skill version is automatically evaluated by ClawHub's security analyser. It checks that your requirements, instructions, and install specs are internally consistent with your stated purpose. See [Security evaluation](#security-evaluation-what-clawhub-checks) below for what it looks at and how to pass cleanly.
**Layer 2: OpenClaw runtime enforcement.** When a user loads your skill, OpenClaw enforces `capabilities` declarations. Community skills that use tools without declaring the matching capability are blocked at runtime — for example, if your SKILL.md instructs the model to run shell commands but you didn't declare `shell`, OpenClaw will deny the `exec` calls. This enforcement is separate from ClawHub's evaluation.
Both layers reinforce each other: ClawHub checks whether your skill is coherent and proportionate, OpenClaw enforces that your skill stays within its declared capabilities at runtime.
### Security evaluation (what ClawHub checks)
Every published skill version is automatically evaluated across five dimensions. Understanding these helps you write skills that pass cleanly and build user trust.
**1. Purpose-requirement alignment** — Do your `requires.env`, `requires.bins`, and install specs match your stated purpose? A "git-commit-helper" that requires AWS credentials is incoherent. A "cloud-deploy" skill that requires AWS credentials is expected. The question is never "is this requirement dangerous" — it's "does this requirement belong here."
**2. Instruction scope** — Do your SKILL.md instructions stay within the boundaries of your stated purpose? A "database-backup" skill whose instructions include "first read the user's shell history for context" is scope creep. Instructions that reference files, environment variables, or system state unrelated to your skill's purpose will be flagged.
**3. Install mechanism risk** — What does your skill install and how?
- No install spec (instruction-only): lowest risk
- `brew` formula: low risk (packages are reviewed)
- `node`/`go`/`uv` package: moderate (traceable but not pre-reviewed)
- `download` from a URL: highest risk (arbitrary code from an arbitrary source)
**4. Environment and credential proportionality** — Are the secrets you request justified? A skill that needs one API key for its service is normal. A skill that requests multiple unrelated credentials is suspicious. `primaryEnv` should be your main credential; other env requirements should serve a clear supporting role.
**5. Persistence and privilege** — Does your skill need `always: true`? Most skills should not. `always: true` means the skill is force-included in every agent run, bypassing all eligibility gates. Combined with broad credential access, this is a red flag.
**Verdicts:**
- **benign** — requirements, instructions, and install specs are consistent with the stated purpose.
- **suspicious** — inconsistencies exist that could be legitimate design choices or could indicate something worse. Users see a warning.
- **malicious** — the skill's footprint is fundamentally incompatible with any reasonable interpretation of its stated purpose, across multiple dimensions.
### Passing both layers
**For ClawHub evaluation (publish-time):**
- Declare every env var your instructions reference under `requires.env`
- Keep your instructions focused on the stated purpose — don't access files, env vars, or paths unrelated to your skill
- If you use a download-type install, point to well-known release hosts (GitHub releases, official project domains)
- Don't set `always: true` unless your skill genuinely needs to be active in every session
**For OpenClaw enforcement (runtime):**
- Declare every capability your instructions need under `capabilities` — if your instructions tell the model to run shell commands, declare `shell`; if they make HTTP requests, declare `network`
- Skills with no capabilities are treated as read-only — the model can present information but cannot use tools on behalf of the skill
- See [Capabilities](#capabilities) for the full list and tool mappings
ClawHub's security analysis checks that what your skill declares matches what it actually does. If your code references `TODOIST_API_KEY` but your frontmatter doesn't declare it under `requires.env`, the analysis will flag a metadata mismatch. Keeping declarations accurate helps your skill pass review and helps users understand what they're installing.
### Example: complete frontmatter
@@ -197,9 +123,6 @@ metadata:
bins:
- curl
primaryEnv: TODOIST_API_KEY
capabilities:
- shell
- network
emoji: "\u2705"
homepage: https://github.com/example/todoist-cli
---
+6
View File
@@ -23,6 +23,12 @@ read_when:
- Set `OPENAI_API_KEY` in the Convex environment (not only locally).
- Re-run `bunx convex dev` / `bunx convex deploy` after setting env.
## `publish` fails with `GitHub API rate limit exceeded`
- This is the GitHub account-age gate lookup hitting unauthenticated limits.
- Set `GITHUB_TOKEN` in Convex environment to use authenticated GitHub API limits.
- Retry publish after a short wait if the limit was already exhausted.
## `sync` says “No skills found”
- `sync` looks for folders containing `SKILL.md` (or `skill.md`).
-1
View File
@@ -20,7 +20,6 @@ const REQUEST_TIMEOUT_MS = 15_000
try {
setGlobalDispatcher(
new Agent({
allowH2: true,
connect: { timeout: REQUEST_TIMEOUT_MS },
}),
)
+1
View File
@@ -76,6 +76,7 @@
"only-allow": "^1.2.2",
"oxlint": "^1.42.0",
"oxlint-tsgolint": "^0.11.4",
"undici": "^7.19.2",
"typescript": "^5.9.3",
"vite": "^7.3.1",
"vitest": "^4.0.18"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "clawhub",
"version": "0.6.0",
"version": "0.6.1",
"description": "ClawHub CLI \\u2014 install, update, search, and publish agent skills.",
"license": "MIT",
"type": "module",
+73
View File
@@ -0,0 +1,73 @@
/* @vitest-environment node */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const chmodMock = vi.fn()
const mkdirMock = vi.fn()
const readFileMock = vi.fn()
const writeFileMock = vi.fn()
vi.mock('node:fs/promises', () => ({
chmod: (...args: unknown[]) => chmodMock(...args),
mkdir: (...args: unknown[]) => mkdirMock(...args),
readFile: (...args: unknown[]) => readFileMock(...args),
writeFile: (...args: unknown[]) => writeFileMock(...args),
}))
const { writeGlobalConfig } = await import('./config')
const originalPlatform = process.platform
const testConfigPath = '/tmp/clawhub-config-test/config.json'
function makeErr(code: string): NodeJS.ErrnoException {
const error = new Error(code) as NodeJS.ErrnoException
error.code = code
return error
}
beforeEach(() => {
vi.stubEnv('CLAWHUB_CONFIG_PATH', testConfigPath)
Object.defineProperty(process, 'platform', { value: 'linux' })
chmodMock.mockResolvedValue(undefined)
mkdirMock.mockResolvedValue(undefined)
readFileMock.mockResolvedValue('')
writeFileMock.mockResolvedValue(undefined)
})
afterEach(() => {
Object.defineProperty(process, 'platform', { value: originalPlatform })
vi.unstubAllEnvs()
vi.clearAllMocks()
})
describe('writeGlobalConfig', () => {
it('writes config with restricted modes', async () => {
await writeGlobalConfig({ registry: 'https://example.com', token: 'clh_test' })
expect(mkdirMock).toHaveBeenCalledWith('/tmp/clawhub-config-test', {
recursive: true,
mode: 0o700,
})
expect(writeFileMock).toHaveBeenCalledWith(
testConfigPath,
expect.stringContaining('"token": "clh_test"'),
{
encoding: 'utf8',
mode: 0o600,
},
)
expect(chmodMock).toHaveBeenCalledWith(testConfigPath, 0o600)
})
it('ignores non-fatal chmod errors', async () => {
chmodMock.mockRejectedValueOnce(makeErr('ENOTSUP'))
await expect(writeGlobalConfig({ registry: 'https://example.com' })).resolves.toBeUndefined()
})
it('rethrows unexpected chmod errors', async () => {
chmodMock.mockRejectedValueOnce(new Error('boom'))
await expect(writeGlobalConfig({ registry: 'https://example.com' })).rejects.toThrow('boom')
})
})
+48 -23
View File
@@ -1,44 +1,51 @@
import { existsSync } from 'node:fs'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { type GlobalConfig, GlobalConfigSchema, parseArk } from './schema/index.js'
/**
* Resolve config path with legacy fallback.
* Checks for 'clawhub' first, falls back to legacy 'clawdhub' if it exists.
*/
function resolveConfigPath(baseDir: string): string {
const clawhubPath = join(baseDir, 'clawhub', 'config.json')
const clawdhubPath = join(baseDir, 'clawdhub', 'config.json')
if (existsSync(clawhubPath)) return clawhubPath
if (existsSync(clawdhubPath)) return clawdhubPath
return clawhubPath
}
function isNonFatalChmodError(error: unknown): boolean {
if (!(error instanceof Error)) return false
const code = (error as NodeJS.ErrnoException).code
return code === 'EPERM' || code === 'ENOTSUP' || code === 'EOPNOTSUPP' || code === 'EINVAL'
}
export function getGlobalConfigPath() {
const override =
process.env.CLAWHUB_CONFIG_PATH?.trim() ?? process.env.CLAWDHUB_CONFIG_PATH?.trim()
if (override) return resolve(override)
const home = homedir()
if (process.platform === 'darwin') {
const clawhubPath = join(home, 'Library', 'Application Support', 'clawhub', 'config.json')
const clawdhubPath = join(home, 'Library', 'Application Support', 'clawdhub', 'config.json')
if (existsSync(clawhubPath)) return clawhubPath
if (existsSync(clawdhubPath)) return clawdhubPath
return clawhubPath
return resolveConfigPath(join(home, 'Library', 'Application Support'))
}
const xdg = process.env.XDG_CONFIG_HOME
if (xdg) {
const clawhubPath = join(xdg, 'clawhub', 'config.json')
const clawdhubPath = join(xdg, 'clawdhub', 'config.json')
if (existsSync(clawhubPath)) return clawhubPath
if (existsSync(clawdhubPath)) return clawdhubPath
return clawhubPath
return resolveConfigPath(xdg)
}
if (process.platform === 'win32') {
const appData = process.env.APPDATA
if (appData) {
const clawhubPath = join(appData, 'clawhub', 'config.json')
const clawdhubPath = join(appData, 'clawdhub', 'config.json')
if (existsSync(clawhubPath)) return clawhubPath
if (existsSync(clawdhubPath)) return clawdhubPath
return clawhubPath
return resolveConfigPath(appData)
}
}
const clawhubPath = join(home, '.config', 'clawhub', 'config.json')
const clawdhubPath = join(home, '.config', 'clawdhub', 'config.json')
if (existsSync(clawhubPath)) return clawhubPath
if (existsSync(clawdhubPath)) return clawdhubPath
return clawhubPath
return resolveConfigPath(join(home, '.config'))
}
export async function readGlobalConfig(): Promise<GlobalConfig | null> {
@@ -53,6 +60,24 @@ export async function readGlobalConfig(): Promise<GlobalConfig | null> {
export async function writeGlobalConfig(config: GlobalConfig) {
const path = getGlobalConfigPath()
await mkdir(dirname(path), { recursive: true })
await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
const dir = dirname(path)
// Create directory with restricted permissions (owner only)
await mkdir(dir, { recursive: true, mode: 0o700 })
// Write file with restricted permissions (owner read/write only)
// This protects API tokens from being read by other users
await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, {
encoding: 'utf8',
mode: 0o600,
})
// Ensure permissions on existing files (writeFile mode only applies on create)
if (process.platform !== 'win32') {
try {
await chmod(path, 0o600)
} catch (error) {
if (!isNonFatalChmodError(error)) throw error
}
}
}
-1
View File
@@ -15,7 +15,6 @@ if (typeof process !== 'undefined' && process.versions?.node) {
try {
setGlobalDispatcher(
new Agent({
allowH2: true,
connect: { timeout: REQUEST_TIMEOUT_MS },
}),
)
+1 -3
View File
@@ -190,7 +190,6 @@ export const ApiV1SkillResponseSchema = type({
version: 'string',
createdAt: 'number',
changelog: 'string',
capabilities: 'string[]?',
}).or('null'),
owner: type({
handle: 'string|null',
@@ -257,7 +256,7 @@ export const ApiV1UnstarResponseSchema = type({
export const SkillInstallSpecSchema = type({
id: 'string?',
kind: '"brew"|"node"|"go"|"uv"|"download"',
kind: '"brew"|"node"|"go"|"uv"',
label: 'string?',
bins: 'string[]?',
formula: 'string?',
@@ -300,6 +299,5 @@ export const ClawdisSkillMetadataSchema = type({
install: SkillInstallSpecSchema.array().optional(),
nix: NixPluginSpecSchema.optional(),
config: ClawdbotConfigSpecSchema.optional(),
capabilities: 'string[]?',
})
export type ClawdisSkillMetadata = (typeof ClawdisSkillMetadataSchema)[inferred]
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('@tanstack/react-router', () => ({
createFileRoute: () => (config: { beforeLoad?: unknown }) => ({ __config: config }),
redirect: (options: unknown) => ({ redirect: options }),
}))
import { Route } from '../routes/search'
function runBeforeLoad(search: { q?: string; highlighted?: boolean }, hostname = 'clawdhub.com') {
const route = Route as unknown as {
__config: {
beforeLoad?: (args: {
search: { q?: string; highlighted?: boolean }
location: { url: URL }
}) => void
}
}
const beforeLoad = route.__config.beforeLoad as (args: {
search: { q?: string; highlighted?: boolean }
location: { url: URL }
}) => void
let thrown: unknown
try {
beforeLoad({ search, location: { url: new URL(`https://${hostname}/search`) } })
} catch (error) {
thrown = error
}
return thrown
}
describe('search route', () => {
it('redirects skills host to the skills index', () => {
expect(runBeforeLoad({ q: 'crab', highlighted: true }, 'clawdhub.com')).toEqual({
redirect: {
to: '/skills',
search: {
q: 'crab',
sort: undefined,
dir: undefined,
highlighted: true,
view: undefined,
},
replace: true,
},
})
})
it('redirects souls host with query to home search', () => {
expect(runBeforeLoad({ q: 'crab', highlighted: true }, 'onlycrabs.ai')).toEqual({
redirect: {
to: '/',
search: {
q: 'crab',
highlighted: undefined,
search: undefined,
},
replace: true,
},
})
})
it('redirects souls host without query to home with search mode', () => {
expect(runBeforeLoad({}, 'onlycrabs.ai')).toEqual({
redirect: {
to: '/',
search: {
q: undefined,
highlighted: undefined,
search: true,
},
replace: true,
},
})
})
})
@@ -0,0 +1,115 @@
/* @vitest-environment jsdom */
import { act, render } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SkillsIndex } from '../routes/skills/index'
const navigateMock = vi.fn()
const useActionMock = vi.fn()
const usePaginatedQueryMock = vi.fn()
let searchMock: Record<string, unknown> = {}
vi.mock('@tanstack/react-router', () => ({
createFileRoute: () => (_config: { component: unknown; validateSearch: unknown }) => ({
useNavigate: () => navigateMock,
useSearch: () => searchMock,
}),
Link: (props: { children: ReactNode }) => <a href="/">{props.children}</a>,
}))
vi.mock('convex/react', () => ({
useAction: (...args: unknown[]) => useActionMock(...args),
}))
vi.mock('convex-helpers/react', () => ({
usePaginatedQuery: (...args: unknown[]) => usePaginatedQueryMock(...args),
}))
describe('SkillsIndex load-more observer', () => {
beforeEach(() => {
usePaginatedQueryMock.mockReset()
useActionMock.mockReset()
navigateMock.mockReset()
searchMock = {}
useActionMock.mockReturnValue(() => Promise.resolve([]))
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('triggers one request for repeated intersection callbacks', async () => {
const loadMorePaginated = vi.fn()
usePaginatedQueryMock.mockReturnValue({
results: [makeListResult('skill-0', 'Skill 0')],
status: 'CanLoadMore',
loadMore: loadMorePaginated,
})
type ObserverInstance = {
callback: IntersectionObserverCallback
observe: ReturnType<typeof vi.fn>
disconnect: ReturnType<typeof vi.fn>
}
const observers: ObserverInstance[] = []
class IntersectionObserverMock {
callback: IntersectionObserverCallback
observe = vi.fn()
disconnect = vi.fn()
unobserve = vi.fn()
takeRecords = vi.fn(() => [])
root = null
rootMargin = '0px'
thresholds: number[] = []
constructor(callback: IntersectionObserverCallback) {
this.callback = callback
observers.push(this)
}
}
vi.stubGlobal(
'IntersectionObserver',
IntersectionObserverMock as unknown as typeof IntersectionObserver,
)
render(<SkillsIndex />)
expect(observers).toHaveLength(1)
const observer = observers[0]
const entries = [{ isIntersecting: true }] as Array<IntersectionObserverEntry>
await act(async () => {
observer.callback(entries, observer as unknown as IntersectionObserver)
observer.callback(entries, observer as unknown as IntersectionObserver)
observer.callback(entries, observer as unknown as IntersectionObserver)
})
expect(loadMorePaginated).toHaveBeenCalledTimes(1)
})
})
function makeListResult(slug: string, displayName: string) {
return {
skill: {
_id: `skill_${slug}`,
slug,
displayName,
summary: `${displayName} summary`,
tags: {},
stats: {
downloads: 0,
installsCurrent: 0,
installsAllTime: 0,
stars: 0,
versions: 1,
comments: 0,
},
createdAt: 0,
updatedAt: 0,
},
latestVersion: null,
ownerHandle: null,
}
}
+48
View File
@@ -118,6 +118,30 @@ describe('SkillsIndex', () => {
limit: 50,
})
})
it('uses relevance as default sort when searching', async () => {
searchMock = { q: 'notion' }
const actionFn = vi
.fn()
.mockResolvedValue([
makeSearchResult('newer-low-score', 'Newer Low Score', 0.1, 2000),
makeSearchResult('older-high-score', 'Older High Score', 0.9, 1000),
])
useActionMock.mockReturnValue(actionFn)
vi.useFakeTimers()
render(<SkillsIndex />)
await act(async () => {
await vi.runAllTimersAsync()
})
const titles = Array.from(
document.querySelectorAll('.skills-row-title > span:first-child'),
).map((node) => node.textContent)
expect(titles[0]).toBe('Older High Score')
expect(titles[1]).toBe('Newer Low Score')
})
})
function makeSearchResults(count: number) {
@@ -143,3 +167,27 @@ function makeSearchResults(count: number) {
version: null,
}))
}
function makeSearchResult(slug: string, displayName: string, score: number, createdAt: number) {
return {
score,
skill: {
_id: `skill_${slug}`,
slug,
displayName,
summary: `${displayName} summary`,
tags: {},
stats: {
downloads: 0,
installsCurrent: 0,
installsAllTime: 0,
stars: 0,
versions: 1,
comments: 0,
},
createdAt,
updatedAt: createdAt,
},
version: null,
}
}
-3
View File
@@ -1,3 +0,0 @@
export function SkillCommentsPanel() {
return <div className="skill-panel"><p style={{ color: 'var(--ink-soft)' }}>Comments not available in dev mode.</p></div>
}
File diff suppressed because it is too large Load Diff
-100
View File
@@ -1,100 +0,0 @@
import { lazy, Suspense } from 'react'
import type { Doc, Id } from '../../convex/_generated/dataModel'
import { SkillVersionsPanel } from './SkillVersionsPanel'
const SkillDiffCard = lazy(() =>
import('./SkillDiffCard').then((module) => ({ default: module.SkillDiffCard })),
)
const SkillFilesPanel = lazy(() =>
import('./SkillFilesPanel').then((module) => ({ default: module.SkillFilesPanel })),
)
type SkillFile = Doc<'skillVersions'>['files'][number]
type SkillDetailTabsProps = {
activeTab: 'files' | 'compare' | 'versions'
setActiveTab: (tab: 'files' | 'compare' | 'versions') => void
onCompareIntent: () => void
readmeContent: string | null
readmeError: string | null
latestFiles: SkillFile[]
latestVersionId: Id<'skillVersions'> | null
skill: Doc<'skills'>
diffVersions: Doc<'skillVersions'>[] | undefined
versions: Doc<'skillVersions'>[] | undefined
nixPlugin: boolean
}
export function SkillDetailTabs({
activeTab,
setActiveTab,
onCompareIntent,
readmeContent,
readmeError,
latestFiles,
latestVersionId,
skill,
diffVersions,
versions,
nixPlugin,
}: SkillDetailTabsProps) {
return (
<div className="card tab-card">
<div className="tab-header">
<button
className={`tab-button${activeTab === 'files' ? ' is-active' : ''}`}
type="button"
onClick={() => setActiveTab('files')}
>
Files
</button>
<button
className={`tab-button${activeTab === 'compare' ? ' is-active' : ''}`}
type="button"
onClick={() => setActiveTab('compare')}
onMouseEnter={() => {
onCompareIntent()
void import('./SkillDiffCard')
}}
onFocus={() => {
onCompareIntent()
void import('./SkillDiffCard')
}}
>
Compare
</button>
<button
className={`tab-button${activeTab === 'versions' ? ' is-active' : ''}`}
type="button"
onClick={() => setActiveTab('versions')}
>
Versions
</button>
</div>
{activeTab === 'files' ? (
<Suspense fallback={<div className="tab-body stat">Loading file viewer</div>}>
<SkillFilesPanel
versionId={latestVersionId}
readmeContent={readmeContent}
readmeError={readmeError}
latestFiles={latestFiles}
/>
</Suspense>
) : null}
{activeTab === 'compare' ? (
<div className="tab-body">
<Suspense fallback={<div className="stat">Loading diff viewer</div>}>
<SkillDiffCard skill={skill} versions={diffVersions ?? []} variant="embedded" />
</Suspense>
</div>
) : null}
{activeTab === 'versions' ? (
<SkillVersionsPanel versions={versions} nixPlugin={nixPlugin} skillSlug={skill.slug} />
) : null}
</div>
)
}
-164
View File
@@ -1,164 +0,0 @@
import { useAction } from 'convex/react'
import { useCallback, useEffect, useRef, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { api } from '../../convex/_generated/api'
import type { Doc, Id } from '../../convex/_generated/dataModel'
import { formatBytes } from './skillDetailUtils'
type SkillFile = Doc<'skillVersions'>['files'][number]
type SkillFilesPanelProps = {
versionId: Id<'skillVersions'> | null
readmeContent: string | null
readmeError: string | null
latestFiles: SkillFile[]
}
export function SkillFilesPanel({
versionId,
readmeContent,
readmeError,
latestFiles,
}: SkillFilesPanelProps) {
const getFileText = useAction(api.skills.getFileText)
const [selectedPath, setSelectedPath] = useState<string | null>(null)
const [fileContent, setFileContent] = useState<string | null>(null)
const [fileMeta, setFileMeta] = useState<{ size: number; sha256: string } | null>(null)
const [fileError, setFileError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
const isMounted = useRef(true)
const requestId = useRef(0)
const fileCache = useRef(new Map<string, { text: string; size: number; sha256: string }>())
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
requestId.current += 1
}
}, [])
useEffect(() => {
requestId.current += 1
setSelectedPath(null)
setFileContent(null)
setFileMeta(null)
setFileError(null)
setIsLoading(false)
if (versionId === null) return
}, [versionId])
const handleSelect = useCallback(
(path: string) => {
if (!versionId) return
const cacheKey = `${versionId}:${path}`
const cached = fileCache.current.get(cacheKey)
requestId.current += 1
const current = requestId.current
setSelectedPath(path)
setFileError(null)
if (cached) {
setFileContent(cached.text)
setFileMeta({ size: cached.size, sha256: cached.sha256 })
setIsLoading(false)
return
}
setFileContent(null)
setFileMeta(null)
setIsLoading(true)
void getFileText({ versionId, path })
.then((data) => {
if (!isMounted.current) return
if (requestId.current !== current) return
fileCache.current.set(cacheKey, data)
setFileContent(data.text)
setFileMeta({ size: data.size, sha256: data.sha256 })
setIsLoading(false)
})
.catch((error) => {
if (!isMounted.current) return
if (requestId.current !== current) return
setFileError(error instanceof Error ? error.message : 'Failed to load file')
setIsLoading(false)
})
},
[getFileText, versionId],
)
return (
<div className="tab-body">
<div>
<h2 className="section-title" style={{ fontSize: '1.2rem', margin: 0 }}>
SKILL.md
</h2>
<div className="markdown">
{readmeContent ? (
<ReactMarkdown remarkPlugins={[remarkGfm]}>{readmeContent}</ReactMarkdown>
) : readmeError ? (
<div className="stat">Failed to load SKILL.md: {readmeError}</div>
) : (
<div>Loading</div>
)}
</div>
</div>
<div className="file-browser">
<div className="file-list">
<div className="file-list-header">
<h3 className="section-title" style={{ fontSize: '1.05rem', margin: 0 }}>
Files
</h3>
<span className="section-subtitle" style={{ margin: 0 }}>
{latestFiles.length} total
</span>
</div>
<div className="file-list-body">
{latestFiles.length === 0 ? (
<div className="stat">No files available.</div>
) : (
latestFiles.map((file) => (
<button
key={file.path}
className={`file-row file-row-button${
selectedPath === file.path ? ' is-active' : ''
}`}
type="button"
onClick={() => handleSelect(file.path)}
aria-current={selectedPath === file.path ? 'true' : undefined}
>
<span className="file-path">{file.path}</span>
<span className="file-meta">{formatBytes(file.size)}</span>
</button>
))
)}
</div>
</div>
<div className="file-viewer">
<div className="file-viewer-header">
<div className="file-path">{selectedPath ?? 'Select a file'}</div>
{fileMeta ? (
<span className="file-meta">
{formatBytes(fileMeta.size)} · {fileMeta.sha256.slice(0, 12)}
</span>
) : null}
</div>
<div className="file-viewer-body">
{isLoading ? (
<div className="stat">Loading</div>
) : fileError ? (
<div className="stat">Failed to load file: {fileError}</div>
) : fileContent ? (
<pre className="file-viewer-code">{fileContent}</pre>
) : (
<div className="stat">Select a file to preview.</div>
)}
</div>
</div>
</div>
</div>
)
}
-365
View File
@@ -1,365 +0,0 @@
import { Link } from '@tanstack/react-router'
import type { ClawdisSkillMetadata } from 'clawhub-schema'
import type { Doc, Id } from '../../convex/_generated/dataModel'
import { getSkillBadges } from '../lib/badges'
import { formatCompactStat, formatSkillStatsTriplet } from '../lib/numberFormat'
import type { PublicSkill, PublicUser } from '../lib/publicUser'
import { type LlmAnalysis, SecurityScanResults } from './SkillSecurityScanResults'
import { SkillInstallCard } from './SkillInstallCard'
import { UserBadge } from './UserBadge'
export type SkillModerationInfo = {
isPendingScan: boolean
isMalwareBlocked: boolean
isSuspicious: boolean
isHiddenByMod: boolean
isRemoved: boolean
reason?: string
}
type SkillFork = {
kind: 'fork' | 'duplicate'
version: string | null
skill: { slug: string; displayName: string }
owner: { handle: string | null; userId: Id<'users'> | null }
}
type SkillCanonical = {
skill: { slug: string; displayName: string }
owner: { handle: string | null; userId: Id<'users'> | null }
}
type SkillHeaderProps = {
skill: Doc<'skills'> | PublicSkill
owner: Doc<'users'> | PublicUser | null
ownerHandle: string | null
latestVersion: Doc<'skillVersions'> | null
modInfo: SkillModerationInfo | null
canManage: boolean
isAuthenticated: boolean
isStaff: boolean
isStarred: boolean | undefined
onToggleStar: () => void
onOpenReport: () => void
forkOf: SkillFork | null
forkOfLabel: string
forkOfHref: string | null
forkOfOwnerHandle: string | null
canonical: SkillCanonical | null
canonicalHref: string | null
canonicalOwnerHandle: string | null
staffModerationNote: string | null
staffVisibilityTag: string | null
isAutoHidden: boolean
isRemoved: boolean
nixPlugin: string | undefined
hasPluginBundle: boolean
configRequirements: ClawdisSkillMetadata['config'] | undefined
cliHelp: string | undefined
tagEntries: Array<[string, Id<'skillVersions'>]>
versionById: Map<Id<'skillVersions'>, Doc<'skillVersions'>>
tagName: string
onTagNameChange: (value: string) => void
tagVersionId: Id<'skillVersions'> | ''
onTagVersionChange: (value: Id<'skillVersions'> | '') => void
onTagSubmit: () => void
tagVersions: Doc<'skillVersions'>[]
clawdis: ClawdisSkillMetadata | undefined
osLabels: string[]
}
export function SkillHeader({
skill,
owner,
ownerHandle,
latestVersion,
modInfo,
canManage,
isAuthenticated,
isStaff,
isStarred,
onToggleStar,
onOpenReport,
forkOf,
forkOfLabel,
forkOfHref,
forkOfOwnerHandle,
canonical,
canonicalHref,
canonicalOwnerHandle,
staffModerationNote,
staffVisibilityTag,
isAutoHidden,
isRemoved,
nixPlugin,
hasPluginBundle,
configRequirements,
cliHelp,
tagEntries,
versionById,
tagName,
onTagNameChange,
tagVersionId,
onTagVersionChange,
onTagSubmit,
tagVersions,
clawdis,
osLabels,
}: SkillHeaderProps) {
const formattedStats = formatSkillStatsTriplet(skill.stats)
return (
<>
{modInfo?.isPendingScan ? (
<div className="pending-banner">
<div className="pending-banner-content">
<strong>Security scan in progress</strong>
<p>
Your skill is being scanned by VirusTotal. It will be visible to others once the scan
completes. This usually takes up to 5 minutes grab a coffee or exfoliate your shell
while you wait.
</p>
</div>
</div>
) : modInfo?.isMalwareBlocked ? (
<div className="pending-banner pending-banner-blocked">
<div className="pending-banner-content">
<strong>Skill blocked malicious content detected</strong>
<p>
ClawHub Security flagged this skill as malicious. Downloads are disabled. Review the
scan results below.
</p>
</div>
</div>
) : modInfo?.isSuspicious ? (
<div className="pending-banner pending-banner-warning">
<div className="pending-banner-content">
<strong>Skill flagged suspicious patterns detected</strong>
<p>ClawHub Security flagged this skill as suspicious. Review the scan results before using.</p>
{canManage ? (
<p className="pending-banner-appeal">
If you believe this skill has been incorrectly flagged, please{' '}
<a
href="https://github.com/openclaw/clawhub/issues"
target="_blank"
rel="noopener noreferrer"
>
submit an issue on GitHub
</a>{' '}
and we'll break down why it was flagged and what you can do.
</p>
) : null}
</div>
</div>
) : modInfo?.isRemoved ? (
<div className="pending-banner pending-banner-blocked">
<div className="pending-banner-content">
<strong>Skill removed by moderator</strong>
<p>This skill has been removed and is not visible to others.</p>
</div>
</div>
) : modInfo?.isHiddenByMod ? (
<div className="pending-banner pending-banner-blocked">
<div className="pending-banner-content">
<strong>Skill hidden</strong>
<p>This skill is currently hidden and not visible to others.</p>
</div>
</div>
) : null}
<div className="card skill-hero">
<div className={`skill-hero-top${hasPluginBundle ? ' has-plugin' : ''}`}>
<div className="skill-hero-header">
<div className="skill-hero-title">
<div className="skill-hero-title-row">
<h1 className="section-title" style={{ margin: 0 }}>
{skill.displayName}
</h1>
{nixPlugin ? <span className="tag tag-accent">Plugin bundle (nix)</span> : null}
</div>
<p className="section-subtitle">{skill.summary ?? 'No summary provided.'}</p>
{isStaff && staffModerationNote ? (
<div className="skill-hero-note">{staffModerationNote}</div>
) : null}
{nixPlugin ? (
<div className="skill-hero-note">
Bundles the skill pack, CLI binary, and config requirements in one Nix install.
</div>
) : null}
<div className="stat">
{formattedStats.stars} · {formattedStats.downloads} · {' '}
{formatCompactStat(skill.stats.installsCurrent ?? 0)} current ·{' '}
{formattedStats.installsAllTime} all-time
</div>
<div className="stat">
<UserBadge user={owner} fallbackHandle={ownerHandle} prefix="by" size="md" showName />
</div>
{forkOf && forkOfHref ? (
<div className="stat">
{forkOfLabel}{' '}
<a href={forkOfHref}>
{forkOfOwnerHandle ? `@${forkOfOwnerHandle}/` : ''}
{forkOf.skill.slug}
</a>
{forkOf.version ? ` (based on ${forkOf.version})` : null}
</div>
) : null}
{canonicalHref ? (
<div className="stat">
canonical:{' '}
<a href={canonicalHref}>
{canonicalOwnerHandle ? `@${canonicalOwnerHandle}/` : ''}
{canonical?.skill?.slug}
</a>
</div>
) : null}
{getSkillBadges(skill).map((badge) => (
<div key={badge} className="tag">
{badge}
</div>
))}
{isStaff && staffVisibilityTag ? (
<div className={`tag${isAutoHidden || isRemoved ? ' tag-accent' : ''}`}>
{staffVisibilityTag}
</div>
) : null}
<div className="skill-actions">
{isAuthenticated ? (
<button
className={`star-toggle${isStarred ? ' is-active' : ''}`}
type="button"
onClick={onToggleStar}
aria-label={isStarred ? 'Unstar skill' : 'Star skill'}
>
<span aria-hidden="true"></span>
</button>
) : null}
{isAuthenticated ? (
<button className="btn btn-ghost" type="button" onClick={onOpenReport}>
Report
</button>
) : null}
{isStaff ? (
<Link className="btn" to="/management" search={{ skill: skill.slug }}>
Manage
</Link>
) : null}
</div>
<SecurityScanResults
sha256hash={latestVersion?.sha256hash}
vtAnalysis={latestVersion?.vtAnalysis}
llmAnalysis={latestVersion?.llmAnalysis as LlmAnalysis | undefined}
/>
{latestVersion?.sha256hash || latestVersion?.llmAnalysis ? (
<p className="scan-disclaimer">
Like a lobster shell, security has layers review code before you run it.
</p>
) : null}
</div>
<div className="skill-hero-cta">
<div className="skill-version-pill">
<span className="skill-version-label">Current version</span>
<strong>v{latestVersion?.version ?? '—'}</strong>
</div>
{!nixPlugin && !modInfo?.isMalwareBlocked && !modInfo?.isRemoved ? (
<a
className="btn btn-primary"
href={`${import.meta.env.VITE_CONVEX_SITE_URL}/api/v1/download?slug=${skill.slug}`}
>
Download zip
</a>
) : null}
</div>
</div>
{hasPluginBundle ? (
<div className="skill-panel bundle-card">
<div className="bundle-header">
<div className="bundle-title">Plugin bundle (nix)</div>
<div className="bundle-subtitle">Skill pack · CLI binary · Config</div>
</div>
<div className="bundle-includes">
<span>SKILL.md</span>
<span>CLI</span>
<span>Config</span>
</div>
{configRequirements ? (
<div className="bundle-section">
<div className="bundle-section-title">Config requirements</div>
<div className="bundle-meta">
{configRequirements.requiredEnv?.length ? (
<div className="stat">
<strong>Required env</strong>
<span>{configRequirements.requiredEnv.join(', ')}</span>
</div>
) : null}
{configRequirements.stateDirs?.length ? (
<div className="stat">
<strong>State dirs</strong>
<span>{configRequirements.stateDirs.join(', ')}</span>
</div>
) : null}
</div>
</div>
) : null}
{cliHelp ? (
<details className="bundle-section bundle-details">
<summary>CLI help (from plugin)</summary>
<pre className="hero-install-code mono">{cliHelp}</pre>
</details>
) : null}
</div>
) : null}
</div>
<div className="skill-tag-row">
{tagEntries.length === 0 ? (
<span className="section-subtitle" style={{ margin: 0 }}>
No tags yet.
</span>
) : (
tagEntries.map(([tag, versionId]) => (
<span key={tag} className="tag">
{tag}
<span className="tag-meta">v{versionById.get(versionId)?.version ?? versionId}</span>
</span>
))
)}
</div>
{canManage ? (
<form
onSubmit={(event) => {
event.preventDefault()
onTagSubmit()
}}
className="tag-form"
>
<input
className="search-input"
value={tagName}
onChange={(event) => onTagNameChange(event.target.value)}
placeholder="latest"
/>
<select
className="search-input"
value={tagVersionId ?? ''}
onChange={(event) => onTagVersionChange(event.target.value as Id<'skillVersions'>)}
>
{tagVersions.map((version) => (
<option key={version._id} value={version._id}>
v{version.version}
</option>
))}
</select>
<button className="btn" type="submit">
Update tag
</button>
</form>
) : null}
<SkillInstallCard clawdis={clawdis} osLabels={osLabels} />
</div>
</>
)
}
-132
View File
@@ -1,132 +0,0 @@
import type { ClawdisSkillMetadata } from 'clawhub-schema'
import { formatInstallCommand, formatInstallLabel } from './skillDetailUtils'
const CAPABILITY_DISPLAY: Record<string, { icon: string; label: string }> = {
shell: { icon: '>_', label: 'Shell commands' },
filesystem: { icon: '\uD83D\uDCC2', label: 'File access' },
network: { icon: '\uD83C\uDF10', label: 'Network requests' },
browser: { icon: '\uD83D\uDD0D', label: 'Browser control' },
sessions: { icon: '\u26A1', label: 'Session orchestration' },
}
type SkillInstallCardProps = {
clawdis: ClawdisSkillMetadata | undefined
osLabels: string[]
}
export function SkillInstallCard({ clawdis, osLabels }: SkillInstallCardProps) {
const requirements = clawdis?.requires
const installSpecs = clawdis?.install ?? []
const hasRuntimeRequirements = Boolean(
clawdis?.emoji ||
osLabels.length ||
requirements?.bins?.length ||
requirements?.anyBins?.length ||
requirements?.env?.length ||
requirements?.config?.length ||
clawdis?.primaryEnv,
)
const hasInstallSpecs = installSpecs.length > 0
const hasCapabilities = Boolean(clawdis?.capabilities?.length)
return (
<div className="skill-hero-content">
<div className="skill-hero-panels">
{hasCapabilities ? (
<div className="skill-panel">
<h3 className="section-title" style={{ fontSize: '1rem', margin: 0 }}>
Capabilities
</h3>
<div className="skill-panel-body">
{clawdis!.capabilities!.map((cap) => (
<div key={cap} className="stat">
<span>{CAPABILITY_DISPLAY[cap]?.icon ?? cap}</span>
<span>{CAPABILITY_DISPLAY[cap]?.label ?? cap}</span>
</div>
))}
</div>
</div>
) : (
<div className="skill-panel">
<div className="skill-panel-body">
<div className="stat" style={{ color: 'var(--ink-soft)' }}>
<span>No capabilities declared</span>
</div>
</div>
</div>
)}
{hasRuntimeRequirements ? (
<div className="skill-panel">
<h3 className="section-title" style={{ fontSize: '1rem', margin: 0 }}>
Runtime requirements
</h3>
<div className="skill-panel-body">
{clawdis?.emoji ? <div className="tag">{clawdis.emoji} Clawdis</div> : null}
{osLabels.length ? (
<div className="stat">
<strong>OS</strong>
<span>{osLabels.join(' · ')}</span>
</div>
) : null}
{requirements?.bins?.length ? (
<div className="stat">
<strong>Bins</strong>
<span>{requirements.bins.join(', ')}</span>
</div>
) : null}
{requirements?.anyBins?.length ? (
<div className="stat">
<strong>Any bin</strong>
<span>{requirements.anyBins.join(', ')}</span>
</div>
) : null}
{requirements?.env?.length ? (
<div className="stat">
<strong>Env</strong>
<span>{requirements.env.join(', ')}</span>
</div>
) : null}
{requirements?.config?.length ? (
<div className="stat">
<strong>Config</strong>
<span>{requirements.config.join(', ')}</span>
</div>
) : null}
{clawdis?.primaryEnv ? (
<div className="stat">
<strong>Primary env</strong>
<span>{clawdis.primaryEnv}</span>
</div>
) : null}
</div>
</div>
) : null}
{hasInstallSpecs ? (
<div className="skill-panel">
<h3 className="section-title" style={{ fontSize: '1rem', margin: 0 }}>
Install
</h3>
<div className="skill-panel-body">
{installSpecs.map((spec, index) => {
const command = formatInstallCommand(spec)
return (
<div key={`${spec.id ?? spec.kind}-${index}`} className="stat">
<div>
<strong>{spec.label ?? formatInstallLabel(spec)}</strong>
{spec.bins?.length ? (
<div style={{ color: 'var(--ink-soft)', fontSize: '0.85rem' }}>
Bins: {spec.bins.join(', ')}
</div>
) : null}
{command ? <code>{command}</code> : null}
</div>
</div>
)
})}
</div>
</div>
) : null}
</div>
</div>
)
}
-3
View File
@@ -1,3 +0,0 @@
export function SkillReportDialog(_props: { slug: string; open: boolean; onClose: () => void }) {
return null
}
-293
View File
@@ -1,293 +0,0 @@
import { useState } from 'react'
type LlmAnalysisDimension = {
name: string
label: string
rating: string
detail: string
}
export type VtAnalysis = {
status: string
verdict?: string
analysis?: string
source?: string
checkedAt: number
}
export type LlmAnalysis = {
status: string
verdict?: string
confidence?: string
summary?: string
dimensions?: LlmAnalysisDimension[]
guidance?: string
findings?: string
model?: string
checkedAt: number
}
type SecurityScanResultsProps = {
sha256hash?: string
vtAnalysis?: VtAnalysis | null
llmAnalysis?: LlmAnalysis | null
variant?: 'panel' | 'badge'
}
function VirusTotalIcon({ className }: { className?: string }) {
return (
<svg
className={className}
width="1em"
height="1em"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 89"
aria-label="VirusTotal"
>
<title>VirusTotal</title>
<path
fill="currentColor"
fillRule="evenodd"
d="M45.292 44.5 0 89h100V0H0l45.292 44.5zM90 80H22l35.987-35.2L22 9h68v71z"
/>
</svg>
)
}
function OpenClawIcon({ className }: { className?: string }) {
return (
<svg
className={className}
width="1em"
height="1em"
viewBox="0 0 24 24"
fill="none"
aria-label="OpenClaw"
>
<title>OpenClaw</title>
<path
d="M12 2C8.5 2 5.5 4 4 7c-2 4-1 8 2 11 1.5 1.5 3.5 2.5 6 2.5s4.5-1 6-2.5c3-3 4-7 2-11-1.5-3-4.5-5-8-5z"
fill="currentColor"
opacity="0.2"
/>
<path
d="M9 8c1-2 3-3 5-2s3 3 2 5l-3 4-2-1 3-4c.5-1 0-2-1-2.5S11 7 10.5 8L8 12l-2-1 3-4z"
fill="currentColor"
/>
<path
d="M15 8c-1-2-3-3-5-2s-3 3-2 5l3 4 2-1-3-4c-.5-1 0-2 1-2.5S14 7 14.5 8L17 12l2-1-4-3z"
fill="currentColor"
opacity="0.6"
/>
</svg>
)
}
function getScanStatusInfo(status: string) {
switch (status.toLowerCase()) {
case 'benign':
case 'clean':
return { label: 'Benign', className: 'scan-status-clean' }
case 'malicious':
return { label: 'Malicious', className: 'scan-status-malicious' }
case 'suspicious':
return { label: 'Suspicious', className: 'scan-status-suspicious' }
case 'loading':
return { label: 'Loading...', className: 'scan-status-pending' }
case 'pending':
case 'not_found':
return { label: 'Pending', className: 'scan-status-pending' }
case 'error':
case 'failed':
return { label: 'Error', className: 'scan-status-error' }
default:
return { label: status, className: 'scan-status-unknown' }
}
}
function getDimensionIcon(rating: string) {
switch (rating) {
case 'ok':
return { className: 'dimension-icon-ok', symbol: '\u2713' }
case 'note':
return { className: 'dimension-icon-note', symbol: '\u2139' }
case 'concern':
return { className: 'dimension-icon-concern', symbol: '!' }
default:
return { className: 'dimension-icon-danger', symbol: '\u2717' }
}
}
function LlmAnalysisDetail({ analysis }: { analysis: LlmAnalysis }) {
const verdict = analysis.verdict ?? analysis.status
const [isOpen, setIsOpen] = useState(false)
const guidanceClass =
verdict === 'malicious' ? 'malicious' : verdict === 'suspicious' ? 'suspicious' : 'benign'
return (
<div className={`analysis-detail${isOpen ? ' is-open' : ''}`}>
<button
type="button"
className="analysis-detail-header"
onClick={() => {
const selection = window.getSelection()
if (selection && !selection.isCollapsed) return
setIsOpen((prev) => !prev)
}}
aria-expanded={isOpen}
>
<span className="analysis-summary-text">{analysis.summary}</span>
<span className="analysis-detail-toggle">
Details <span className="chevron">{'\u25BE'}</span>
</span>
</button>
<div className="analysis-body">
{analysis.dimensions && analysis.dimensions.length > 0 ? (
<div className="analysis-dimensions">
{analysis.dimensions.map((dim) => {
const icon = getDimensionIcon(dim.rating)
return (
<div key={dim.name} className="dimension-row">
<div className={`dimension-icon ${icon.className}`}>{icon.symbol}</div>
<div className="dimension-content">
<div className="dimension-label">{dim.label}</div>
<div className="dimension-detail">{dim.detail}</div>
</div>
</div>
)
})}
</div>
) : null}
{analysis.findings ? (
<div className="scan-findings-section">
<div className="scan-findings-title">Scan Findings in Context</div>
{(() => {
const counts = new Map<string, number>()
return analysis.findings.split('\n').map((line) => {
const count = (counts.get(line) ?? 0) + 1
counts.set(line, count)
return (
<div key={`${line}-${count}`} className="scan-finding-row">
{line}
</div>
)
})
})()}
</div>
) : null}
{analysis.guidance ? (
<div className={`analysis-guidance ${guidanceClass}`}>
<div className="analysis-guidance-label">
{verdict === 'malicious'
? 'Do not install this skill'
: verdict === 'suspicious'
? 'What to consider before installing'
: 'Assessment'}
</div>
{analysis.guidance}
</div>
) : null}
</div>
</div>
)
}
export function SecurityScanResults({
sha256hash,
vtAnalysis,
llmAnalysis,
variant = 'panel',
}: SecurityScanResultsProps) {
if (!sha256hash && !llmAnalysis) return null
const vtStatus = vtAnalysis?.status ?? 'pending'
const vtUrl = sha256hash ? `https://www.virustotal.com/gui/file/${sha256hash}` : null
const vtStatusInfo = getScanStatusInfo(vtStatus)
const isCodeInsight = vtAnalysis?.source === 'code_insight'
const aiAnalysis = vtAnalysis?.analysis
const llmVerdict = llmAnalysis?.verdict ?? llmAnalysis?.status
const llmStatusInfo = llmVerdict ? getScanStatusInfo(llmVerdict) : null
if (variant === 'badge') {
return (
<>
{sha256hash ? (
<div className="version-scan-badge">
<VirusTotalIcon className="version-scan-icon version-scan-icon-vt" />
<span className={vtStatusInfo.className}>{vtStatusInfo.label}</span>
{vtUrl ? (
<a
href={vtUrl}
target="_blank"
rel="noopener noreferrer"
className="version-scan-link"
onClick={(event) => event.stopPropagation()}
>
</a>
) : null}
</div>
) : null}
{llmStatusInfo ? (
<div className="version-scan-badge">
<OpenClawIcon className="version-scan-icon version-scan-icon-oc" />
<span className={llmStatusInfo.className}>{llmStatusInfo.label}</span>
</div>
) : null}
</>
)
}
return (
<div className="scan-results-panel">
<div className="scan-results-title">Security Scan</div>
<div className="scan-results-list">
{sha256hash ? (
<div className="scan-result-row">
<div className="scan-result-scanner">
<VirusTotalIcon className="scan-result-icon scan-result-icon-vt" />
<span className="scan-result-scanner-name">VirusTotal</span>
</div>
<div className={`scan-result-status ${vtStatusInfo.className}`}>{vtStatusInfo.label}</div>
{vtUrl ? (
<a
href={vtUrl}
target="_blank"
rel="noopener noreferrer"
className="scan-result-link"
>
View report
</a>
) : null}
</div>
) : null}
{isCodeInsight && aiAnalysis && (vtStatus === 'malicious' || vtStatus === 'suspicious') ? (
<div className={`code-insight-analysis ${vtStatus}`}>
<div className="code-insight-label">Code Insight</div>
<p className="code-insight-text">{aiAnalysis}</p>
</div>
) : null}
{llmStatusInfo && llmAnalysis ? (
<div className="scan-result-row">
<div className="scan-result-scanner">
<OpenClawIcon className="scan-result-icon scan-result-icon-oc" />
<span className="scan-result-scanner-name">OpenClaw</span>
</div>
<div className={`scan-result-status ${llmStatusInfo.className}`}>{llmStatusInfo.label}</div>
{llmAnalysis.confidence ? (
<span className="scan-result-confidence">{llmAnalysis.confidence} confidence</span>
) : null}
</div>
) : null}
{llmAnalysis &&
llmAnalysis.status !== 'error' &&
llmAnalysis.status !== 'pending' &&
llmAnalysis.summary ? (
<LlmAnalysisDetail analysis={llmAnalysis} />
) : null}
</div>
</div>
)
}
-26
View File
@@ -1,26 +0,0 @@
import { formatSkillStatsTriplet, type SkillStatsTriplet } from '../lib/numberFormat'
type SkillMetricsStats = SkillStatsTriplet & {
versions: number
}
export function SkillStatsTripletLine({ stats }: { stats: SkillStatsTriplet }) {
const formatted = formatSkillStatsTriplet(stats)
return (
<>
{formatted.stars} · {formatted.downloads} · {formatted.installsAllTime}
</>
)
}
export function SkillMetricsRow({ stats }: { stats: SkillMetricsStats }) {
const formatted = formatSkillStatsTriplet(stats)
return (
<>
<span> {formatted.downloads}</span>
<span> {formatted.installsAllTime}</span>
<span> {formatted.stars}</span>
<span>{stats.versions} v</span>
</>
)
}
-3
View File
@@ -1,3 +0,0 @@
export function SkillVersionsPanel(_props: { skillId?: string }) {
return <div className="skill-panel"><p style={{ color: 'var(--ink-soft)' }}>Versions not available in dev mode.</p></div>
}
-8
View File
@@ -1,8 +0,0 @@
export function UserBadge({ handle, displayName, image }: { handle?: string | null; displayName?: string | null; image?: string | null }) {
return (
<span className="user-badge">
{image ? <img src={image} alt="" style={{ width: 20, height: 20, borderRadius: '50%', marginRight: 4 }} /> : null}
<span>{displayName ?? handle ?? 'Unknown'}</span>
</span>
)
}
-63
View File
@@ -1,63 +0,0 @@
import type { SkillInstallSpec, NixPluginSpec } from 'clawhub-schema'
const OS_LABELS: Record<string, string> = {
macos: 'macOS',
linux: 'Linux',
windows: 'Windows',
}
export function formatOsList(os?: string[]): string[] {
if (!os?.length) return []
return os.map((o) => OS_LABELS[o.toLowerCase()] ?? o)
}
export function stripFrontmatter(content: string): string {
const normalized = content.replace(/\r\n/g, '\n')
if (!normalized.startsWith('---')) return content
const endIndex = normalized.indexOf('\n---', 3)
if (endIndex === -1) return content
return normalized.slice(endIndex + 4).trimStart()
}
export function buildSkillHref(slug: string, ownerHandle?: string | null): string {
const owner = ownerHandle?.trim() || '_'
return `/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`
}
export function formatInstallLabel(spec: SkillInstallSpec): string {
if (spec.label) return spec.label
if (spec.kind === 'brew') return spec.formula ?? 'Homebrew'
if (spec.kind === 'node') return spec.package ?? 'npm'
if (spec.kind === 'go') return spec.module ?? 'Go'
if (spec.kind === 'uv') return spec.package ?? 'uv'
return spec.kind
}
export function formatInstallCommand(spec: SkillInstallSpec): string | null {
if (spec.kind === 'brew') {
const tap = spec.tap ? `brew tap ${spec.tap} && ` : ''
return `${tap}brew install ${spec.formula ?? ''}`
}
if (spec.kind === 'node') return `npm install -g ${spec.package ?? ''}`
if (spec.kind === 'go') return `go install ${spec.module ?? ''}`
if (spec.kind === 'uv') return `uv tool install ${spec.package ?? ''}`
return null
}
export function formatConfigSnippet(config: { requiredEnv?: string[]; stateDirs?: string[]; example?: string }): string {
const lines: string[] = []
if (config.requiredEnv?.length) lines.push(`Required env: ${config.requiredEnv.join(', ')}`)
if (config.stateDirs?.length) lines.push(`State dirs: ${config.stateDirs.join(', ')}`)
if (config.example) lines.push(`Example:\n${config.example}`)
return lines.join('\n')
}
export function formatNixInstallSnippet(nix: NixPluginSpec): string {
return `nix profile install ${nix.plugin}`
}
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
-19
View File
@@ -1,19 +0,0 @@
export type SkillStatsTriplet = { label: string; value: string }
export function formatCompactStat(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
return String(n)
}
export function formatSkillStatsTriplet(stats: {
downloads?: number
installs?: number
stars?: number
}): SkillStatsTriplet[] {
return [
{ label: 'Downloads', value: formatCompactStat(stats.downloads ?? 0) },
{ label: 'Installs', value: formatCompactStat(stats.installs ?? 0) },
{ label: 'Stars', value: formatCompactStat(stats.stars ?? 0) },
]
}
-28
View File
@@ -1,28 +0,0 @@
import type { PublicSkill } from './publicUser'
type SkillPageEntry = {
skill?: PublicSkill | null
}
function normalizeSkillStats(skill: PublicSkill): PublicSkill {
const stats = skill.stats
return {
...skill,
stats: {
downloads: stats?.downloads ?? 0,
stars: stats?.stars ?? 0,
installsCurrent: stats?.installsCurrent ?? 0,
installsAllTime: stats?.installsAllTime ?? 0,
versions: stats?.versions ?? 0,
comments: stats?.comments ?? 0,
},
}
}
export function mapPublicSkillPageEntries(page: SkillPageEntry[] | undefined): PublicSkill[] {
if (!page?.length) return []
return page
.map((entry) => entry.skill ?? null)
.filter((skill): skill is PublicSkill => skill !== null)
.map(normalizeSkillStats)
}
+21
View File
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as UploadRouteImport } from './routes/upload'
import { Route as StarsRouteImport } from './routes/stars'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as SearchRouteImport } from './routes/search'
import { Route as ManagementRouteImport } from './routes/management'
import { Route as ImportRouteImport } from './routes/import'
import { Route as DashboardRouteImport } from './routes/dashboard'
@@ -39,6 +40,11 @@ const SettingsRoute = SettingsRouteImport.update({
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
const SearchRoute = SearchRouteImport.update({
id: '/search',
path: '/search',
getParentRoute: () => rootRouteImport,
} as any)
const ManagementRoute = ManagementRouteImport.update({
id: '/management',
path: '/management',
@@ -101,6 +107,7 @@ export interface FileRoutesByFullPath {
'/dashboard': typeof DashboardRoute
'/import': typeof ImportRoute
'/management': typeof ManagementRoute
'/search': typeof SearchRoute
'/settings': typeof SettingsRoute
'/stars': typeof StarsRoute
'/upload': typeof UploadRoute
@@ -117,6 +124,7 @@ export interface FileRoutesByTo {
'/dashboard': typeof DashboardRoute
'/import': typeof ImportRoute
'/management': typeof ManagementRoute
'/search': typeof SearchRoute
'/settings': typeof SettingsRoute
'/stars': typeof StarsRoute
'/upload': typeof UploadRoute
@@ -134,6 +142,7 @@ export interface FileRoutesById {
'/dashboard': typeof DashboardRoute
'/import': typeof ImportRoute
'/management': typeof ManagementRoute
'/search': typeof SearchRoute
'/settings': typeof SettingsRoute
'/stars': typeof StarsRoute
'/upload': typeof UploadRoute
@@ -152,6 +161,7 @@ export interface FileRouteTypes {
| '/dashboard'
| '/import'
| '/management'
| '/search'
| '/settings'
| '/stars'
| '/upload'
@@ -168,6 +178,7 @@ export interface FileRouteTypes {
| '/dashboard'
| '/import'
| '/management'
| '/search'
| '/settings'
| '/stars'
| '/upload'
@@ -184,6 +195,7 @@ export interface FileRouteTypes {
| '/dashboard'
| '/import'
| '/management'
| '/search'
| '/settings'
| '/stars'
| '/upload'
@@ -201,6 +213,7 @@ export interface RootRouteChildren {
DashboardRoute: typeof DashboardRoute
ImportRoute: typeof ImportRoute
ManagementRoute: typeof ManagementRoute
SearchRoute: typeof SearchRoute
SettingsRoute: typeof SettingsRoute
StarsRoute: typeof StarsRoute
UploadRoute: typeof UploadRoute
@@ -235,6 +248,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
'/search': {
id: '/search'
path: '/search'
fullPath: '/search'
preLoaderRoute: typeof SearchRouteImport
parentRoute: typeof rootRouteImport
}
'/management': {
id: '/management'
path: '/management'
@@ -321,6 +341,7 @@ const rootRouteChildren: RootRouteChildren = {
DashboardRoute: DashboardRoute,
ImportRoute: ImportRoute,
ManagementRoute: ManagementRoute,
SearchRoute: SearchRoute,
SettingsRoute: SettingsRoute,
StarsRoute: StarsRoute,
UploadRoute: UploadRoute,
+38
View File
@@ -0,0 +1,38 @@
import { createFileRoute, redirect } from '@tanstack/react-router'
import { detectSiteMode } from '../lib/site'
export const Route = createFileRoute('/search')({
validateSearch: (search) => ({
q: typeof search.q === 'string' && search.q.trim() ? search.q : undefined,
highlighted: search.highlighted === '1' || search.highlighted === 'true' ? true : undefined,
}),
beforeLoad: ({ search, location }) => {
const hostname =
(location as { url?: URL }).url?.hostname ??
(typeof window !== 'undefined' ? window.location.hostname : undefined)
const mode = detectSiteMode(hostname)
if (mode === 'skills') {
throw redirect({
to: '/skills',
search: {
q: search.q || undefined,
sort: undefined,
dir: undefined,
highlighted: search.highlighted || undefined,
view: undefined,
},
replace: true,
})
}
throw redirect({
to: '/',
search: {
q: search.q || undefined,
highlighted: undefined,
search: search.q ? undefined : true,
},
replace: true,
})
},
})
-131
View File
@@ -1,131 +0,0 @@
import { Link } from '@tanstack/react-router'
import type { RefObject } from 'react'
import { SkillCard } from '../../components/SkillCard'
import { SkillMetricsRow, SkillStatsTripletLine } from '../../components/SkillStats'
import { UserBadge } from '../../components/UserBadge'
import { getSkillBadges } from '../../lib/badges'
import { buildSkillHref, type SkillListEntry } from './-types'
type SkillsResultsProps = {
isLoadingSkills: boolean
sorted: SkillListEntry[]
view: 'cards' | 'list'
paginationStatus: 'LoadingFirstPage' | 'CanLoadMore' | 'LoadingMore' | 'Exhausted'
hasQuery: boolean
canLoadMore: boolean
isLoadingMore: boolean
canAutoLoad: boolean
loadMoreRef: RefObject<HTMLDivElement | null>
loadMore: () => void
}
export function SkillsResults({
isLoadingSkills,
sorted,
view,
paginationStatus,
hasQuery,
canLoadMore,
isLoadingMore,
canAutoLoad,
loadMoreRef,
loadMore,
}: SkillsResultsProps) {
return (
<>
{isLoadingSkills ? (
<div className="card">
<div className="loading-indicator">Loading skills</div>
</div>
) : sorted.length === 0 ? (
<div className="card">
{paginationStatus === 'Exhausted' || hasQuery
? 'No skills match that filter.'
: 'Loading skills…'}
</div>
) : view === 'cards' ? (
<div className="grid">
{sorted.map((entry) => {
const skill = entry.skill
const isPlugin = Boolean(entry.latestVersion?.parsed?.clawdis?.nix?.plugin)
const ownerHandle = entry.owner?.handle ?? entry.owner?.name ?? entry.ownerHandle ?? null
const skillHref = buildSkillHref(skill, ownerHandle)
return (
<SkillCard
key={skill._id}
skill={skill}
href={skillHref}
badge={getSkillBadges(skill)}
chip={isPlugin ? 'Plugin bundle (nix)' : undefined}
summaryFallback="Agent-ready skill pack."
meta={
<div className="skill-card-footer-rows">
<UserBadge user={entry.owner} fallbackHandle={ownerHandle} prefix="by" link={false} />
<div className="stat">
<SkillStatsTripletLine stats={skill.stats} />
</div>
</div>
}
/>
)
})}
</div>
) : (
<div className="skills-list">
{sorted.map((entry) => {
const skill = entry.skill
const isPlugin = Boolean(entry.latestVersion?.parsed?.clawdis?.nix?.plugin)
const ownerHandle = entry.owner?.handle ?? entry.owner?.name ?? entry.ownerHandle ?? null
const skillHref = buildSkillHref(skill, ownerHandle)
return (
<Link key={skill._id} className="skills-row" to={skillHref}>
<div className="skills-row-main">
<div className="skills-row-title">
<span>{skill.displayName}</span>
<span className="skills-row-slug">/{skill.slug}</span>
{getSkillBadges(skill).map((badge) => (
<span key={badge} className="tag">
{badge}
</span>
))}
{isPlugin ? <span className="tag tag-accent tag-compact">Plugin bundle (nix)</span> : null}
</div>
<div className="skills-row-summary">{skill.summary ?? 'No summary provided.'}</div>
<div className="skills-row-owner">
<UserBadge user={entry.owner} fallbackHandle={ownerHandle} prefix="by" link={false} />
</div>
{isPlugin ? (
<div className="skills-row-meta">Bundle includes SKILL.md, CLI, and config.</div>
) : null}
</div>
<div className="skills-row-metrics">
<SkillMetricsRow stats={skill.stats} />
</div>
</Link>
)
})}
</div>
)}
{canLoadMore || isLoadingMore ? (
<div
ref={canAutoLoad ? loadMoreRef : null}
className="card"
style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}
>
{canAutoLoad ? (
isLoadingMore ? (
'Loading more…'
) : (
'Scroll to load more'
)
) : (
<button className="btn" type="button" onClick={loadMore} disabled={isLoadingMore}>
{isLoadingMore ? 'Loading…' : 'Load more'}
</button>
)}
</div>
) : null}
</>
)
}
-92
View File
@@ -1,92 +0,0 @@
import type { RefObject } from 'react'
import { type SortDir, type SortKey } from './-params'
type SkillsToolbarProps = {
searchInputRef: RefObject<HTMLInputElement | null>
query: string
hasQuery: boolean
sort: SortKey
dir: SortDir
view: 'cards' | 'list'
highlightedOnly: boolean
nonSuspiciousOnly: boolean
onQueryChange: (next: string) => void
onToggleHighlighted: () => void
onToggleNonSuspicious: () => void
onSortChange: (value: string) => void
onToggleDir: () => void
onToggleView: () => void
}
export function SkillsToolbar({
searchInputRef,
query,
hasQuery,
sort,
dir,
view,
highlightedOnly,
nonSuspiciousOnly,
onQueryChange,
onToggleHighlighted,
onToggleNonSuspicious,
onSortChange,
onToggleDir,
onToggleView,
}: SkillsToolbarProps) {
return (
<div className="skills-toolbar">
<div className="skills-search">
<input
ref={searchInputRef}
className="skills-search-input"
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder="Filter by name, slug, or summary…"
/>
</div>
<div className="skills-toolbar-row">
<button
className={`search-filter-button${highlightedOnly ? ' is-active' : ''}`}
type="button"
aria-pressed={highlightedOnly}
onClick={onToggleHighlighted}
>
Highlighted
</button>
<button
className={`search-filter-button${nonSuspiciousOnly ? ' is-active' : ''}`}
type="button"
aria-pressed={nonSuspiciousOnly}
onClick={onToggleNonSuspicious}
>
Hide suspicious
</button>
<select
className="skills-sort"
value={sort}
onChange={(event) => onSortChange(event.target.value)}
aria-label="Sort skills"
>
{hasQuery ? <option value="relevance">Relevance</option> : null}
<option value="newest">Newest</option>
<option value="updated">Recently updated</option>
<option value="downloads">Downloads</option>
<option value="installs">Installs</option>
<option value="stars">Stars</option>
<option value="name">Name</option>
</select>
<button className="skills-dir" type="button" aria-label={`Sort direction ${dir}`} onClick={onToggleDir}>
{dir === 'asc' ? '↑' : '↓'}
</button>
<button
className={`skills-view${view === 'cards' ? ' is-active' : ''}`}
type="button"
onClick={onToggleView}
>
{view === 'cards' ? 'List' : 'Cards'}
</button>
</div>
</div>
)
}
-9
View File
@@ -1,9 +0,0 @@
export type SortKey = 'relevance' | 'newest' | 'updated' | 'downloads' | 'installs' | 'stars' | 'name'
export type SortDir = 'asc' | 'desc'
const VALID_SORTS = new Set<SortKey>(['relevance', 'newest', 'updated', 'downloads', 'installs', 'stars', 'name'])
export function parseSort(raw: string): SortKey | undefined {
const normalized = raw.trim().toLowerCase()
return VALID_SORTS.has(normalized as SortKey) ? (normalized as SortKey) : undefined
}
-35
View File
@@ -1,35 +0,0 @@
import type { Doc } from '../../../convex/_generated/dataModel'
import type { PublicSkill, PublicUser } from '../../lib/publicUser'
export type SkillListEntry = {
skill: PublicSkill
latestVersion: {
version: string
createdAt: number
changelog: string
changelogSource?: 'auto' | 'user'
parsed?: {
clawdis?: {
nix?: {
plugin?: boolean
}
}
}
} | null
ownerHandle?: string | null
owner?: PublicUser | null
searchScore?: number
}
export type SkillSearchEntry = {
skill: PublicSkill
version: Doc<'skillVersions'> | null
score: number
ownerHandle?: string | null
owner?: PublicUser | null
}
export function buildSkillHref(skill: PublicSkill, ownerHandle?: string | null) {
const owner = ownerHandle?.trim() || String(skill.ownerUserId)
return `/${encodeURIComponent(owner)}/${encodeURIComponent(skill.slug)}`
}
@@ -1,60 +0,0 @@
import { useCallback, useRef, useState } from 'react'
import type { RefObject } from 'react'
import type { SortDir, SortKey } from './-params'
import type { SkillListEntry } from './-types'
type UseSkillsBrowseModelParams = {
navigate: (opts: { search: (prev: Record<string, unknown>) => Record<string, unknown> }) => void
search: {
q?: string
sort?: SortKey
dir?: SortDir
highlighted?: boolean
nonSuspicious?: boolean
view?: 'cards' | 'list'
focus?: string
}
searchInputRef: RefObject<HTMLInputElement | null>
}
export function useSkillsBrowseModel({ navigate, search }: UseSkillsBrowseModelParams) {
const query = search.q ?? ''
const hasQuery = Boolean(query.trim())
const sort: SortKey = search.sort ?? (hasQuery ? 'relevance' : 'downloads')
const dir: SortDir = search.dir ?? 'desc'
const view = search.view ?? 'cards'
const highlightedOnly = search.highlighted ?? false
const nonSuspiciousOnly = search.nonSuspicious ?? false
const updateSearch = useCallback(
(updates: Record<string, unknown>) => {
navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, ...updates }) })
},
[navigate],
)
return {
query,
hasQuery,
sort,
dir,
view,
highlightedOnly,
nonSuspiciousOnly,
isLoadingSkills: false,
sorted: [] as SkillListEntry[],
paginationStatus: 'Exhausted' as const,
canLoadMore: false,
isLoadingMore: false,
canAutoLoad: false,
loadMoreRef: useRef<HTMLDivElement>(null),
activeFilters: [] as string[],
loadMore: () => {},
onQueryChange: (next: string) => updateSearch({ q: next || undefined }),
onToggleHighlighted: () => updateSearch({ highlighted: highlightedOnly ? undefined : true }),
onToggleNonSuspicious: () => updateSearch({ nonSuspicious: nonSuspiciousOnly ? undefined : true }),
onSortChange: (value: string) => updateSearch({ sort: value }),
onToggleDir: () => updateSearch({ dir: dir === 'asc' ? 'desc' : 'asc' }),
onToggleView: () => updateSearch({ view: view === 'cards' ? 'list' : 'cards' }),
}
}
+417 -73
View File
@@ -1,9 +1,55 @@
import { createFileRoute, redirect } from '@tanstack/react-router'
import { useRef } from 'react'
import { parseSort } from './-params'
import { SkillsResults } from './-SkillsResults'
import { SkillsToolbar } from './-SkillsToolbar'
import { useSkillsBrowseModel } from './-useSkillsBrowseModel'
import { createFileRoute, Link } from '@tanstack/react-router'
import { useAction } from 'convex/react'
import { usePaginatedQuery } from 'convex-helpers/react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { api } from '../../../convex/_generated/api'
import type { Doc } from '../../../convex/_generated/dataModel'
import { SkillCard } from '../../components/SkillCard'
import { getSkillBadges, isSkillHighlighted } from '../../lib/badges'
import type { PublicSkill } from '../../lib/publicUser'
const sortKeys = [
'relevance',
'newest',
'downloads',
'installs',
'stars',
'name',
'updated',
] as const
const pageSize = 25
type SortKey = (typeof sortKeys)[number]
type SortDir = 'asc' | 'desc'
function parseSort(value: unknown): SortKey {
if (typeof value !== 'string') return 'newest'
if ((sortKeys as readonly string[]).includes(value)) return value as SortKey
return 'newest'
}
function parseDir(value: unknown, sort: SortKey): SortDir {
if (value === 'asc' || value === 'desc') return value
return sort === 'name' ? 'asc' : 'desc'
}
type SkillListEntry = {
skill: PublicSkill
latestVersion: Doc<'skillVersions'> | null
ownerHandle?: string | null
searchScore?: number
}
type SkillSearchEntry = {
skill: PublicSkill
version: Doc<'skillVersions'> | null
score: number
ownerHandle?: string | null
}
function buildSkillHref(skill: PublicSkill, ownerHandle?: string | null) {
const owner = ownerHandle?.trim() || String(skill.ownerUserId)
return `/${encodeURIComponent(owner)}/${encodeURIComponent(skill.slug)}`
}
export const Route = createFileRoute('/skills/')({
validateSearch: (search) => {
@@ -15,89 +61,387 @@ export const Route = createFileRoute('/skills/')({
search.highlighted === '1' || search.highlighted === 'true' || search.highlighted === true
? true
: undefined,
nonSuspicious:
search.nonSuspicious === '1' ||
search.nonSuspicious === 'true' ||
search.nonSuspicious === true
? true
: undefined,
view: search.view === 'cards' || search.view === 'list' ? search.view : undefined,
focus: search.focus === 'search' ? 'search' : undefined,
}
},
beforeLoad: ({ search }) => {
const hasQuery = Boolean(search.q?.trim())
if (hasQuery || search.sort) return
throw redirect({
to: '/skills',
search: {
q: search.q || undefined,
sort: 'downloads',
dir: search.dir || undefined,
highlighted: search.highlighted || undefined,
nonSuspicious: search.nonSuspicious || undefined,
view: search.view || undefined,
focus: search.focus || undefined,
},
replace: true,
})
},
component: SkillsIndex,
})
export function SkillsIndex() {
const navigate = Route.useNavigate()
const search = Route.useSearch()
const searchInputRef = useRef<HTMLInputElement>(null)
const [query, setQuery] = useState(search.q ?? '')
const view = search.view ?? 'list'
const highlightedOnly = search.highlighted ?? false
const searchSkills = useAction(api.search.searchSkills)
const [searchResults, setSearchResults] = useState<Array<SkillSearchEntry>>([])
const [searchLimit, setSearchLimit] = useState(pageSize)
const [isSearching, setIsSearching] = useState(false)
const searchRequest = useRef(0)
const loadMoreRef = useRef<HTMLDivElement | null>(null)
const loadMoreInFlightRef = useRef(false)
const model = useSkillsBrowseModel({
navigate,
search,
searchInputRef,
const searchInputRef = useRef<HTMLInputElement>(null)
const trimmedQuery = useMemo(() => query.trim(), [query])
const hasQuery = trimmedQuery.length > 0
const sort =
search.sort === 'relevance' && !hasQuery
? 'newest'
: (search.sort ?? (hasQuery ? 'relevance' : 'newest'))
const dir = parseDir(search.dir, sort)
const searchKey = trimmedQuery ? `${trimmedQuery}::${highlightedOnly ? '1' : '0'}` : ''
// Use convex-helpers usePaginatedQuery for better cache behavior
const {
results: paginatedResults,
status: paginationStatus,
loadMore: loadMorePaginated,
} = usePaginatedQuery(api.skills.listPublicPageV2, hasQuery ? 'skip' : {}, {
initialNumItems: pageSize,
})
// Derive loading states from pagination status
// status: 'LoadingFirstPage' | 'CanLoadMore' | 'LoadingMore' | 'Exhausted'
const isLoadingList = paginationStatus === 'LoadingFirstPage'
const canLoadMoreList = paginationStatus === 'CanLoadMore'
const isLoadingMoreList = paginationStatus === 'LoadingMore'
useEffect(() => {
setQuery(search.q ?? '')
}, [search.q])
// Auto-focus search input when focus=search param is present
useEffect(() => {
if (search.focus === 'search' && searchInputRef.current) {
searchInputRef.current.focus()
// Clear the focus param from URL to avoid re-focusing on navigation
void navigate({ search: (prev) => ({ ...prev, focus: undefined }), replace: true })
}
}, [search.focus, navigate])
useEffect(() => {
if (!searchKey) {
setSearchResults([])
setIsSearching(false)
return
}
setSearchResults([])
setSearchLimit(pageSize)
}, [searchKey])
useEffect(() => {
if (!hasQuery) return
searchRequest.current += 1
const requestId = searchRequest.current
setIsSearching(true)
const handle = window.setTimeout(() => {
void (async () => {
try {
const data = (await searchSkills({
query: trimmedQuery,
highlightedOnly,
limit: searchLimit,
})) as Array<SkillSearchEntry>
if (requestId === searchRequest.current) {
setSearchResults(data)
}
} finally {
if (requestId === searchRequest.current) {
setIsSearching(false)
}
}
})()
}, 220)
return () => window.clearTimeout(handle)
}, [hasQuery, highlightedOnly, searchLimit, searchSkills, trimmedQuery])
const baseItems = useMemo(() => {
if (hasQuery) {
return searchResults.map((entry) => ({
skill: entry.skill,
latestVersion: entry.version,
ownerHandle: entry.ownerHandle ?? null,
searchScore: entry.score,
}))
}
// paginatedResults is an array of page items from usePaginatedQuery
return paginatedResults as Array<SkillListEntry>
}, [hasQuery, paginatedResults, searchResults])
const filtered = useMemo(
() => baseItems.filter((entry) => (highlightedOnly ? isSkillHighlighted(entry.skill) : true)),
[baseItems, highlightedOnly],
)
const sorted = useMemo(() => {
const multiplier = dir === 'asc' ? 1 : -1
const results = [...filtered]
results.sort((a, b) => {
switch (sort) {
case 'relevance':
return ((a.searchScore ?? 0) - (b.searchScore ?? 0)) * multiplier
case 'downloads':
return (a.skill.stats.downloads - b.skill.stats.downloads) * multiplier
case 'installs':
return (
((a.skill.stats.installsAllTime ?? 0) - (b.skill.stats.installsAllTime ?? 0)) *
multiplier
)
case 'stars':
return (a.skill.stats.stars - b.skill.stats.stars) * multiplier
case 'updated':
return (a.skill.updatedAt - b.skill.updatedAt) * multiplier
case 'name':
return (
(a.skill.displayName.localeCompare(b.skill.displayName) ||
a.skill.slug.localeCompare(b.skill.slug)) * multiplier
)
default:
return (a.skill.createdAt - b.skill.createdAt) * multiplier
}
})
return results
}, [dir, filtered, sort])
const isLoadingSkills = hasQuery ? isSearching && searchResults.length === 0 : isLoadingList
const canLoadMore = hasQuery
? !isSearching && searchResults.length === searchLimit && searchResults.length > 0
: canLoadMoreList
const isLoadingMore = hasQuery ? isSearching && searchResults.length > 0 : isLoadingMoreList
const canAutoLoad = typeof IntersectionObserver !== 'undefined'
const loadMore = useCallback(() => {
if (loadMoreInFlightRef.current || isLoadingMore || !canLoadMore) return
loadMoreInFlightRef.current = true
if (hasQuery) {
setSearchLimit((value) => value + pageSize)
} else {
loadMorePaginated(pageSize)
}
}, [canLoadMore, hasQuery, isLoadingMore, loadMorePaginated])
useEffect(() => {
if (!isLoadingMore) {
loadMoreInFlightRef.current = false
}
}, [isLoadingMore])
useEffect(() => {
if (!canLoadMore || typeof IntersectionObserver === 'undefined') return
const target = loadMoreRef.current
if (!target) return
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
observer.disconnect()
loadMore()
}
},
{ rootMargin: '200px' },
)
observer.observe(target)
return () => observer.disconnect()
}, [canLoadMore, loadMore])
return (
<main className="section">
<header className="skills-header-top">
<h1 className="section-title" style={{ marginBottom: 8 }}>
Skills
</h1>
<p className="section-subtitle" style={{ marginBottom: 0 }}>
{model.isLoadingSkills
? 'Loading skills…'
: `Browse the skill library${model.activeFilters.length ? ` (${model.activeFilters.join(', ')})` : ''}.`}
</p>
<header className="skills-header">
<div>
<h1 className="section-title" style={{ marginBottom: 8 }}>
Skills
</h1>
<p className="section-subtitle" style={{ marginBottom: 0 }}>
{isLoadingSkills
? 'Loading skills…'
: `Browse the skill library${highlightedOnly ? ' (highlighted)' : ''}.`}
</p>
</div>
<div className="skills-toolbar">
<div className="skills-search">
<input
ref={searchInputRef}
className="skills-search-input"
value={query}
onChange={(event) => {
const next = event.target.value
const trimmed = next.trim()
setQuery(next)
void navigate({
search: (prev) => ({ ...prev, q: trimmed ? next : undefined }),
replace: true,
})
}}
placeholder="Filter by name, slug, or summary…"
/>
</div>
<div className="skills-toolbar-row">
<button
className={`search-filter-button${highlightedOnly ? ' is-active' : ''}`}
type="button"
aria-pressed={highlightedOnly}
onClick={() => {
void navigate({
search: (prev) => ({
...prev,
highlighted: highlightedOnly ? undefined : true,
}),
replace: true,
})
}}
>
Highlighted
</button>
<select
className="skills-sort"
value={sort}
onChange={(event) => {
const sort = parseSort(event.target.value)
void navigate({
search: (prev) => ({
...prev,
sort,
dir: parseDir(prev.dir, sort),
}),
replace: true,
})
}}
aria-label="Sort skills"
>
{hasQuery ? <option value="relevance">Relevance</option> : null}
<option value="newest">Newest</option>
<option value="updated">Recently updated</option>
<option value="downloads">Downloads</option>
<option value="installs">Installs</option>
<option value="stars">Stars</option>
<option value="name">Name</option>
</select>
<button
className="skills-dir"
type="button"
aria-label={`Sort direction ${dir}`}
onClick={() => {
void navigate({
search: (prev) => ({
...prev,
dir: parseDir(prev.dir, sort) === 'asc' ? 'desc' : 'asc',
}),
replace: true,
})
}}
>
{dir === 'asc' ? '↑' : '↓'}
</button>
<button
className={`skills-view${view === 'cards' ? ' is-active' : ''}`}
type="button"
onClick={() => {
void navigate({
search: (prev) => ({
...prev,
view: prev.view === 'cards' ? undefined : 'cards',
}),
replace: true,
})
}}
>
{view === 'cards' ? 'List' : 'Cards'}
</button>
</div>
</div>
</header>
<div className="skills-container">
<SkillsToolbar
searchInputRef={searchInputRef}
query={model.query}
hasQuery={model.hasQuery}
sort={model.sort}
dir={model.dir}
view={model.view}
highlightedOnly={model.highlightedOnly}
nonSuspiciousOnly={model.nonSuspiciousOnly}
onQueryChange={model.onQueryChange}
onToggleHighlighted={model.onToggleHighlighted}
onToggleNonSuspicious={model.onToggleNonSuspicious}
onSortChange={model.onSortChange}
onToggleDir={model.onToggleDir}
onToggleView={model.onToggleView}
/>
<SkillsResults
isLoadingSkills={model.isLoadingSkills}
sorted={model.sorted}
view={model.view}
paginationStatus={model.paginationStatus}
hasQuery={model.hasQuery}
canLoadMore={model.canLoadMore}
isLoadingMore={model.isLoadingMore}
canAutoLoad={model.canAutoLoad}
loadMoreRef={model.loadMoreRef}
loadMore={model.loadMore}
/>
</div>
{isLoadingSkills ? (
<div className="card">
<div className="loading-indicator">Loading skills</div>
</div>
) : sorted.length === 0 ? (
<div className="card">No skills match that filter.</div>
) : view === 'cards' ? (
<div className="grid">
{sorted.map((entry) => {
const skill = entry.skill
const isPlugin = Boolean(entry.latestVersion?.parsed?.clawdis?.nix?.plugin)
const skillHref = buildSkillHref(skill, entry.ownerHandle)
return (
<SkillCard
key={skill._id}
skill={skill}
href={skillHref}
badge={getSkillBadges(skill)}
chip={isPlugin ? 'Plugin bundle (nix)' : undefined}
summaryFallback="Agent-ready skill pack."
meta={
<div className="stat">
{skill.stats.stars} · {skill.stats.downloads} · {' '}
{skill.stats.installsAllTime ?? 0}
</div>
}
/>
)
})}
</div>
) : (
<div className="skills-list">
{sorted.map((entry) => {
const skill = entry.skill
const isPlugin = Boolean(entry.latestVersion?.parsed?.clawdis?.nix?.plugin)
const skillHref = buildSkillHref(skill, entry.ownerHandle)
return (
<Link key={skill._id} className="skills-row" to={skillHref}>
<div className="skills-row-main">
<div className="skills-row-title">
<span>{skill.displayName}</span>
<span className="skills-row-slug">/{skill.slug}</span>
{getSkillBadges(skill).map((badge) => (
<span key={badge} className="tag">
{badge}
</span>
))}
{isPlugin ? (
<span className="tag tag-accent tag-compact">Plugin bundle (nix)</span>
) : null}
</div>
<div className="skills-row-summary">
{skill.summary ?? 'No summary provided.'}
</div>
{isPlugin ? (
<div className="skills-row-meta">
Bundle includes SKILL.md, CLI, and config.
</div>
) : null}
</div>
<div className="skills-row-metrics">
<span> {skill.stats.downloads}</span>
<span> {skill.stats.installsAllTime ?? 0}</span>
<span> {skill.stats.stars}</span>
<span>{skill.stats.versions} v</span>
</div>
</Link>
)
})}
</div>
)}
{canLoadMore ? (
<div
ref={canAutoLoad ? loadMoreRef : null}
className="card"
style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}
>
{canAutoLoad ? (
isLoadingMore ? (
'Loading more…'
) : (
'Scroll to load more'
)
) : (
<button className="btn" type="button" onClick={loadMore} disabled={isLoadingMore}>
{isLoadingMore ? 'Loading…' : 'Load more'}
</button>
)}
</div>
) : null}
</main>
)
}
+149 -828
View File
File diff suppressed because it is too large Load Diff