mirror of
https://github.com/openclaw/clawhub.git
synced 2026-08-14 08:52:21 +00:00
Compare commits
65
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53214abd08 | ||
|
|
4a6f4391c4 | ||
|
|
aa0a97bd35 | ||
|
|
311bf1a88a | ||
|
|
8343f0bb23 | ||
|
|
3b73a09d36 | ||
|
|
412249d2d1 | ||
|
|
480125d859 | ||
|
|
0ab1d1e051 | ||
|
|
85374fa44b | ||
|
|
c319e46c8b | ||
|
|
f17087d1f4 | ||
|
|
da4469e1e0 | ||
|
|
42a4648475 | ||
|
|
edc8ec274b | ||
|
|
15b1a05fee | ||
|
|
1e216c03c6 | ||
|
|
0a0b2e6cb1 | ||
|
|
ac6770acff | ||
|
|
bfc87e5932 | ||
|
|
3e1bd19a45 | ||
|
|
d71b747d1c | ||
|
|
4d211fcf73 | ||
|
|
bc5ab8f3e1 | ||
|
|
bb528ea4b9 | ||
|
|
464a04c1e5 | ||
|
|
f4f8e7276f | ||
|
|
3ccf2e05f5 | ||
|
|
0ee2872f5b | ||
|
|
5112d1b215 | ||
|
|
275a170f15 | ||
|
|
17aa24baf9 | ||
|
|
f01476757a | ||
|
|
fe011d00fd | ||
|
|
30ae099825 | ||
|
|
812641342d | ||
|
|
88848c224c | ||
|
|
c107adabac | ||
|
|
38c4a673da | ||
|
|
89933951f5 | ||
|
|
e3523093b1 | ||
|
|
1faf3ee5ed | ||
|
|
286c76a05f | ||
|
|
5745b5a096 | ||
|
|
a060ae3b15 | ||
|
|
77982c5d8e | ||
|
|
4cb84df36a | ||
|
|
d82c8f66c2 | ||
|
|
43fd834d23 | ||
|
|
9b2fc48a55 | ||
|
|
a4dad5dc9d | ||
|
|
84830a268a | ||
|
|
37ef3eb7c5 | ||
|
|
7f987fcc26 | ||
|
|
a0ea45c9a6 | ||
|
|
1f5a782ecd | ||
|
|
c300d4b447 | ||
|
|
c3a6cd7356 | ||
|
|
b75e25c4d6 | ||
|
|
54383665d8 | ||
|
+22 |
697cc1a08f | ||
|
|
652beef9c1 | ||
|
|
146df7b166 | ||
|
|
8f23eb5ee8 | ||
|
|
30b263c27c |
@@ -0,0 +1,33 @@
|
||||
name: "Security Gate: Secret Scanning"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
jobs:
|
||||
trufflehog:
|
||||
name: Scan for Verified Secrets
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read # Required to scan the code in the PR
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # necessary to support the scoping requirements below
|
||||
|
||||
- name: TruffleHog OSS
|
||||
id: trufflehog
|
||||
uses: trufflesecurity/trufflehog@e64309e4514a601c7d23f336688782a229a4a754 # Pin to current stable
|
||||
with:
|
||||
path: ./
|
||||
base: ${{ github.event.pull_request.base.sha }} # scope it to the committed files
|
||||
head: ${{ github.event.pull_request.head.sha }}
|
||||
extra_args: --only-verified --debug
|
||||
|
||||
- name: Notify on Failure
|
||||
if: steps.trufflehog.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error::Verified secrets found! This PR contains live credentials that must be rotated immediately."
|
||||
echo "::notice::If these secrets are already in the commit history, they cannot be removed via a simple removal commit/push. A repository owner can contact GitHub Support to purge the cached data: https://support.github.com/contact/private-information"
|
||||
exit 1
|
||||
@@ -7,6 +7,9 @@
|
||||
- Admin: bulk restore skills from GitHub backup; reclaim squatted slugs via v1 endpoints + internal tooling (#298) (thanks @autogame-17).
|
||||
- Users: add `trustedPublisher` flag and admin mutations to bypass pending-scan auto-hide for trusted publishers (#298) (thanks @autogame-17).
|
||||
- Skills/Web: show skill owner avatar + handle on skill cards, lists, and detail pages (#312) (thanks @ianalloway).
|
||||
- Skills/Web: add file viewer for skill version files on detail page (#44) (thanks @regenrek).
|
||||
- CLI: add `uninstall` command for skills (#241) (thanks @superlowburn).
|
||||
- CI/Security: add TruffleHog pull-request scanning for verified leaked credentials (#505) (thanks @akses0).
|
||||
|
||||
### Changed
|
||||
- Quality gate: language-aware word counting (`Intl.Segmenter`) and new `cjkChars` signal to reduce false rejects for non-Latin docs.
|
||||
@@ -14,17 +17,30 @@
|
||||
- API performance: batch resolve skill/soul tags in v1 list/get endpoints (fewer action->query round-trips) (#112) (thanks @mkrokosz).
|
||||
- Skills: reserve deleted slugs for prior owners (90-day cooldown) to prevent squatting; add admin reclaim flow (#298) (thanks @autogame-17).
|
||||
- Moderation: ban flow soft-deletes owned skills (reversible) and removes them from vector search (#298) (thanks @autogame-17).
|
||||
- LLM helpers: centralize OpenAI Responses text extraction for changelog/summary/eval flows (#502) (thanks @ianalloway).
|
||||
- Rate limiting: apply authenticated quotas by user bucket (vs shared IP), emit delay-based reset headers, and improve CLI 429 guidance/retries (#412) (thanks @lc0rp).
|
||||
- Search/listing performance: cut embedding hydration and badge read bandwidth via `embeddingSkillMap` + denormalized skill badges; shift stat-doc sync to low-frequency cron (#441) (thanks @sethconvex).
|
||||
|
||||
### Fixed
|
||||
- Admin API: `POST /api/v1/users/reclaim` now performs non-destructive root-slug owner transfer
|
||||
(preserves existing skill versions/stats/metadata) and clears active slug reservations.
|
||||
- Users: sync handle on ensure when GitHub login changes (#293) (thanks @christianhpoe).
|
||||
- Users/Auth: throttle GitHub profile sync on login; also sync avatar when it changes (#312) (thanks @ianalloway).
|
||||
- Upload gate: fetch GitHub account age by immutable account ID (prevents username swaps) (#116) (thanks @mkrokosz).
|
||||
- VT fallback: activate only VT-pending hidden skills when scans are unavailable/stale; keep quality/scanner-blocked skills hidden (#300) (thanks @superlowburn).
|
||||
- API: return proper status codes for delete/undelete errors (#35) (thanks @sergical).
|
||||
- API: for owners, return clearer status/messages for hidden/soft-deleted skills instead of a generic 404.
|
||||
- Web: allow copying OpenClaw scan summary text (thanks @borisolver, #322).
|
||||
- HTTP/CORS: add preflight handler + include CORS headers on API/download errors; CLI: include auth token for owner-visible installs/updates (#146) (thanks @Grenghis-Khan).
|
||||
- CLI: clarify `logout` only removes the local token; token remains valid until revoked in the web UI (#166) (thanks @aronchick).
|
||||
- CLI: validate skill slugs used for filesystem operations (prevents path traversal) (#241) (thanks @superlowburn).
|
||||
- Skills: keep global sorting across pagination on `/skills` (thanks @CodeBBakGoSu, #98).
|
||||
- Skills: allow updating skill description/summary from frontmatter on subsequent publishes (#312) (thanks @ianalloway).
|
||||
- Skills/Web: prevent filtered pagination dead-ends and loading-state flicker on `/skills`; move highlighted browse filtering into server list query (#339) (thanks @Marvae).
|
||||
- Web: align `/skills` total count with public visibility and format header count (thanks @rknoche6, #76).
|
||||
- Skills/Web: centralize public visibility checks and keep `globalStats` skill counts in sync incrementally; remove duplicate `/skills` default-sort fallback and share browse test mocks (thanks @rknoche6, #76).
|
||||
- Moderation: clear stale `flagged.suspicious` flags when VirusTotal rescans improve to clean verdicts (#418) (thanks @Phineas1500).
|
||||
- CLI: respect `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY` env vars for outbound registry requests, with troubleshooting docs (#363) (thanks @kerrypotter).
|
||||
|
||||
## 0.6.1 - 2026-02-13
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ onlycrabs.ai is the **SOUL.md registry**: publish and share system lore the same
|
||||
|
||||
Live: `https://clawhub.ai`
|
||||
onlycrabs.ai: `https://onlycrabs.ai`
|
||||
Vision: [`VISION.md`](VISION.md)
|
||||
|
||||
## What you can do with it
|
||||
|
||||
@@ -37,6 +38,25 @@ onlycrabs.ai: `https://onlycrabs.ai`
|
||||
- Search: OpenAI embeddings (`text-embedding-3-small`) + Convex vector search.
|
||||
- API schema + routes: `packages/schema` (`clawhub-schema`).
|
||||
|
||||
## CLI
|
||||
|
||||
Common CLI flows:
|
||||
|
||||
- Auth: `clawhub login`, `clawhub whoami`
|
||||
- Discover: `clawhub search ...`, `clawhub explore`
|
||||
- Manage local installs: `clawhub install <slug>`, `clawhub uninstall <slug>`, `clawhub list`, `clawhub update --all`
|
||||
- Inspect without installing: `clawhub inspect <slug>`
|
||||
- Publish/sync: `clawhub publish <path>`, `clawhub sync`
|
||||
|
||||
Docs: `docs/quickstart.md`, `docs/cli.md`.
|
||||
|
||||
### Removal permissions
|
||||
|
||||
- `clawhub uninstall <slug>` only removes a local install on your machine.
|
||||
- Uploaded registry skills use soft-delete/restore (`clawhub delete <slug>` / `clawhub undelete <slug>` or API equivalents).
|
||||
- Soft-delete/restore is allowed for the skill owner, moderators, and admins.
|
||||
- Hard delete is admin-only (management tools / ban flows).
|
||||
|
||||
|
||||
## Telemetry
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
## OpenClaw Vision
|
||||
|
||||
OpenClaw is the AI that actually does things.
|
||||
It runs on your devices, in your channels, with your rules.
|
||||
|
||||
This document explains the current state and direction of the project.
|
||||
We are still early, so iteration is fast.
|
||||
Project overview and developer docs: [`README.md`](README.md)
|
||||
|
||||
OpenClaw started as my personal playground to learn AI and build something genuinely useful:
|
||||
an assistant that can run real tasks on my computer.
|
||||
It evolved through several names and shells: Warelay -> Clawdbot -> Moltbot -> OpenClaw.
|
||||
|
||||
The goal? A personal assistant that's easy to use, supports a wide range of platforms, and respects your privacy and security.
|
||||
|
||||
The current focus is:
|
||||
|
||||
Priority:
|
||||
- Security and safe defaults
|
||||
- Bug fixes and stability
|
||||
- Setup reliability and first-run UX
|
||||
|
||||
Next priorities:
|
||||
- Supporting all major model providers
|
||||
- Improving support for major messaging channels (and adding a few high-demand ones)
|
||||
- Performance and test infrastructure
|
||||
- Better computer-use and agent harness capabilities
|
||||
- Ergonomics across CLI and web frontend
|
||||
- Companion apps on macOS, iOS, Android, Windows, and Linux
|
||||
|
||||
## Security
|
||||
|
||||
Security in OpenClaw is a deliberate tradeoff: strong defaults without killing capability.
|
||||
The goal is to stay powerful for real work while making risky paths explicit and operator-controlled.
|
||||
|
||||
Canonical security policy and reporting:
|
||||
- https://github.com/openclaw/openclaw/blob/main/SECURITY.md
|
||||
|
||||
We prioritize secure defaults, but we also expose clear knobs for trusted high-power workflows.
|
||||
|
||||
## Plugins & Memory
|
||||
|
||||
OpenClaw has an extensive plugin API.
|
||||
Core stays lean; optional capability should usually ship as plugins.
|
||||
|
||||
Preferred plugin path is npm package distribution plus local extension loading for development.
|
||||
If you build a plugin, please host and maintain it in your own repository.
|
||||
The bar for adding optional plugins to core is intentionally high.
|
||||
|
||||
Memory is a special plugin slot where only one memory plugin can be active at a time.
|
||||
Today we ship multiple memory options; over time we plan to converge on one recommended default path.
|
||||
|
||||
### Skills
|
||||
|
||||
We still ship some bundled skills for baseline UX.
|
||||
New skills should be published to ClawHub first (`clawhub.ai`), not added to core by default.
|
||||
Core skill additions should be rare and require a strong product or security reason.
|
||||
|
||||
### MCP Support
|
||||
|
||||
OpenClaw supports MCP through `mcporter`: https://github.com/steipete/mcporter
|
||||
|
||||
This keeps MCP integration flexible and decoupled from core runtime:
|
||||
- add or change MCP servers without restarting the gateway
|
||||
- keep core tool/context surface lean
|
||||
- reduce MCP churn impact on core stability and security
|
||||
|
||||
For now, we prefer this bridge model over building first-class MCP runtime into core.
|
||||
If there is an MCP server or feature `mcporter` does not support yet, please open an issue there.
|
||||
|
||||
### Setup
|
||||
|
||||
OpenClaw is currently terminal-first by design.
|
||||
This keeps setup explicit: users see docs, auth, permissions, and security posture up front.
|
||||
|
||||
Long term, we want easier onboarding flows as hardening matures.
|
||||
We do not want convenience wrappers that hide critical security decisions from users.
|
||||
|
||||
### Why TypeScript?
|
||||
|
||||
OpenClaw is primarily an orchestration system: prompts, tools, protocols, and integrations.
|
||||
TypeScript was chosen to keep OpenClaw hackable by default.
|
||||
It is widely known, fast to iterate in, and easy to read, modify, and extend.
|
||||
|
||||
## What We Will Not Merge (For Now)
|
||||
|
||||
- New core skills when they can live on ClawHub
|
||||
- Commercial service integrations that do not clearly fit the model-provider category
|
||||
- Wrapper channels around already supported channels without a clear capability or security gap
|
||||
- First-class MCP runtime in core when `mcporter` already provides the integration path
|
||||
- Heavy orchestration layers that duplicate existing agent and tool infrastructure
|
||||
|
||||
This list is a roadmap guardrail, not a law of physics.
|
||||
Strong user demand and strong technical rationale can change it.
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"packages/clawdhub": {
|
||||
"name": "clawhub",
|
||||
"version": "0.6.1",
|
||||
"version": "0.7.0",
|
||||
"bin": {
|
||||
"clawhub": "bin/clawdhub.js",
|
||||
"clawdhub": "bin/clawdhub.js",
|
||||
|
||||
Vendored
+2
@@ -48,6 +48,7 @@ import type * as lib_githubImport from "../lib/githubImport.js";
|
||||
import type * as lib_githubProfileSync from "../lib/githubProfileSync.js";
|
||||
import type * as lib_githubRestoreHelpers from "../lib/githubRestoreHelpers.js";
|
||||
import type * as lib_githubSoulBackup from "../lib/githubSoulBackup.js";
|
||||
import type * as lib_globalStats from "../lib/globalStats.js";
|
||||
import type * as lib_httpHeaders from "../lib/httpHeaders.js";
|
||||
import type * as lib_httpRateLimit from "../lib/httpRateLimit.js";
|
||||
import type * as lib_leaderboards from "../lib/leaderboards.js";
|
||||
@@ -137,6 +138,7 @@ declare const fullApi: ApiFromModules<{
|
||||
"lib/githubProfileSync": typeof lib_githubProfileSync;
|
||||
"lib/githubRestoreHelpers": typeof lib_githubRestoreHelpers;
|
||||
"lib/githubSoulBackup": typeof lib_githubSoulBackup;
|
||||
"lib/globalStats": typeof lib_globalStats;
|
||||
"lib/httpHeaders": typeof lib_httpHeaders;
|
||||
"lib/httpRateLimit": typeof lib_httpRateLimit;
|
||||
"lib/leaderboards": typeof lib_leaderboards;
|
||||
|
||||
+21
-2
@@ -19,18 +19,37 @@ crons.interval(
|
||||
|
||||
crons.interval(
|
||||
'skill-stats-backfill',
|
||||
{ minutes: 10 },
|
||||
{ hours: 6 },
|
||||
internal.statsMaintenance.runSkillStatBackfillInternal,
|
||||
{ batchSize: 200, maxBatches: 5 },
|
||||
)
|
||||
|
||||
// Runs frequently to keep dailyStats/trending accurate,
|
||||
// but does NOT patch skill documents (only writes to skillDailyStats).
|
||||
crons.interval(
|
||||
'skill-stat-events',
|
||||
{ minutes: 5 },
|
||||
{ minutes: 15 },
|
||||
internal.skillStatEvents.processSkillStatEventsAction,
|
||||
{},
|
||||
)
|
||||
|
||||
// Syncs accumulated stat deltas to skill documents every 6 hours.
|
||||
// Runs infrequently to avoid thundering-herd reactive query invalidation.
|
||||
// Uses processedAt field to track progress (independent of the action cursor).
|
||||
crons.interval(
|
||||
'skill-doc-stat-sync',
|
||||
{ hours: 6 },
|
||||
internal.skillStatEvents.processSkillStatEventsInternal,
|
||||
{ batchSize: 500 },
|
||||
)
|
||||
|
||||
crons.interval(
|
||||
'global-stats-update',
|
||||
{ minutes: 60 },
|
||||
internal.statsMaintenance.updateGlobalStatsInternal,
|
||||
{},
|
||||
)
|
||||
|
||||
crons.interval('vt-pending-scans', { minutes: 5 }, internal.vt.pollPendingScans, { batchSize: 100 })
|
||||
|
||||
crons.interval('vt-cache-backfill', { minutes: 30 }, internal.vt.backfillActiveSkillsVTCache, {
|
||||
|
||||
@@ -435,6 +435,7 @@ export const seedSkillMutation = internalMutation({
|
||||
visibility: 'latest-approved',
|
||||
updatedAt: now,
|
||||
})
|
||||
await ctx.db.insert('embeddingSkillMap', { embeddingId, skillId })
|
||||
|
||||
await ctx.db.patch(skillId, {
|
||||
latestVersionId: versionId,
|
||||
|
||||
@@ -39,6 +39,7 @@ export type SyncGitHubBackupsResult = {
|
||||
skillsScanned: number
|
||||
skillsSkipped: number
|
||||
skillsBackedUp: number
|
||||
skillsDeleted: number
|
||||
skillsMissingVersion: number
|
||||
skillsMissingOwner: number
|
||||
errors: number
|
||||
|
||||
@@ -7,9 +7,12 @@ import type { ActionCtx } from './_generated/server'
|
||||
import { internalAction } from './_generated/server'
|
||||
import {
|
||||
backupSkillToGitHub,
|
||||
deleteGitHubSkillBackup,
|
||||
fetchGitHubSkillMeta,
|
||||
getGitHubBackupContext,
|
||||
isGitHubBackupConfigured,
|
||||
listGitHubSkillBackupEntries,
|
||||
normalizeOwner,
|
||||
} from './lib/githubBackup'
|
||||
|
||||
const DEFAULT_BATCH_SIZE = 50
|
||||
@@ -35,6 +38,7 @@ export type GitHubBackupSyncStats = {
|
||||
skillsScanned: number
|
||||
skillsSkipped: number
|
||||
skillsBackedUp: number
|
||||
skillsDeleted: number
|
||||
skillsMissingVersion: number
|
||||
skillsMissingOwner: number
|
||||
errors: number
|
||||
@@ -87,6 +91,7 @@ export async function syncGitHubBackupsInternalHandler(
|
||||
skillsScanned: 0,
|
||||
skillsSkipped: 0,
|
||||
skillsBackedUp: 0,
|
||||
skillsDeleted: 0,
|
||||
skillsMissingVersion: 0,
|
||||
skillsMissingOwner: 0,
|
||||
errors: 0,
|
||||
@@ -166,9 +171,69 @@ export async function syncGitHubBackupsInternalHandler(
|
||||
if (isDone) break
|
||||
}
|
||||
|
||||
await pruneDeletedSkillBackups(ctx, context, dryRun, stats)
|
||||
|
||||
return { stats, cursor, isDone }
|
||||
}
|
||||
|
||||
async function pruneDeletedSkillBackups(
|
||||
ctx: ActionCtx,
|
||||
context: Awaited<ReturnType<typeof getGitHubBackupContext>>,
|
||||
dryRun: boolean,
|
||||
stats: GitHubBackupSyncStats,
|
||||
) {
|
||||
let entries: Awaited<ReturnType<typeof listGitHubSkillBackupEntries>>
|
||||
try {
|
||||
entries = await listGitHubSkillBackupEntries(context)
|
||||
} catch (error) {
|
||||
console.error('GitHub backup cleanup list failed', error)
|
||||
stats.errors += 1
|
||||
return
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
const skill = (await ctx.runQuery(internal.skills.getSkillBySlugInternal, {
|
||||
slug: entry.slug,
|
||||
})) as Doc<'skills'> | null
|
||||
if (!skill || skill.softDeletedAt) {
|
||||
await deleteBackupIfNeeded(context, entry, dryRun, stats)
|
||||
continue
|
||||
}
|
||||
|
||||
const owner = (await ctx.runQuery(internal.users.getByIdInternal, {
|
||||
userId: skill.ownerUserId,
|
||||
})) as Doc<'users'> | null
|
||||
if (!owner || owner.deletedAt || owner.deactivatedAt) {
|
||||
await deleteBackupIfNeeded(context, entry, dryRun, stats)
|
||||
continue
|
||||
}
|
||||
|
||||
const ownerHandle = normalizeOwner(owner.handle ?? owner._id)
|
||||
if (ownerHandle !== entry.owner) {
|
||||
await deleteBackupIfNeeded(context, entry, dryRun, stats)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('GitHub backup cleanup failed', error)
|
||||
stats.errors += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteBackupIfNeeded(
|
||||
context: Awaited<ReturnType<typeof getGitHubBackupContext>>,
|
||||
entry: Awaited<ReturnType<typeof listGitHubSkillBackupEntries>>[number],
|
||||
dryRun: boolean,
|
||||
stats: GitHubBackupSyncStats,
|
||||
) {
|
||||
const result = dryRun
|
||||
? { deleted: true as const }
|
||||
: await deleteGitHubSkillBackup(context, entry.owner, entry.slug)
|
||||
if (result.deleted) {
|
||||
stats.skillsDeleted += 1
|
||||
}
|
||||
}
|
||||
|
||||
export const syncGitHubBackupsInternal = internalAction({
|
||||
args: {
|
||||
dryRun: v.optional(v.boolean()),
|
||||
|
||||
@@ -167,7 +167,7 @@ describe('httpApiV1 handlers', () => {
|
||||
it('users/reclaim calls reclaim mutation for admin', async () => {
|
||||
const runMutation = vi.fn(async (_mutation: unknown, args: Record<string, unknown>) => {
|
||||
if (isRateLimitArgs(args)) return okRate()
|
||||
return { ok: true }
|
||||
return { ok: true, action: 'ownership_transferred' }
|
||||
})
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ('handle' in args) return { _id: 'users:target' }
|
||||
@@ -194,12 +194,14 @@ describe('httpApiV1 handlers', () => {
|
||||
slug: 'a',
|
||||
rightfulOwnerUserId: 'users:target',
|
||||
reason: 'r',
|
||||
transferRootSlugOnly: true,
|
||||
})
|
||||
expect(reclaimCalls[1]?.[1]).toMatchObject({
|
||||
actorUserId: 'users:admin',
|
||||
slug: 'b',
|
||||
rightfulOwnerUserId: 'users:target',
|
||||
reason: 'r',
|
||||
transferRootSlugOnly: true,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1042,6 +1044,7 @@ describe('httpApiV1 handlers', () => {
|
||||
})
|
||||
|
||||
it('stars add succeeds', async () => {
|
||||
vi.mocked(getOptionalApiTokenUserId).mockResolvedValue('users:1' as never)
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: 'users:1',
|
||||
user: { handle: 'p' },
|
||||
@@ -1050,7 +1053,6 @@ describe('httpApiV1 handlers', () => {
|
||||
const runMutation = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(okRate())
|
||||
.mockResolvedValueOnce(okRate())
|
||||
.mockResolvedValueOnce({ ok: true, starred: true, alreadyStarred: false })
|
||||
const response = await __handlers.starsPostRouterV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
@@ -1066,6 +1068,7 @@ describe('httpApiV1 handlers', () => {
|
||||
})
|
||||
|
||||
it('stars delete succeeds', async () => {
|
||||
vi.mocked(getOptionalApiTokenUserId).mockResolvedValue('users:1' as never)
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: 'users:1',
|
||||
user: { handle: 'p' },
|
||||
@@ -1074,7 +1077,6 @@ describe('httpApiV1 handlers', () => {
|
||||
const runMutation = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(okRate())
|
||||
.mockResolvedValueOnce(okRate())
|
||||
.mockResolvedValueOnce({ ok: true, unstarred: true, alreadyUnstarred: false })
|
||||
const response = await __handlers.starsDeleteRouterV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
|
||||
@@ -163,7 +163,9 @@ async function handleAdminRestore(
|
||||
|
||||
/**
|
||||
* POST /api/v1/users/reclaim
|
||||
* Admin-only: reclaim squatted slugs and reserve them for the rightful owner.
|
||||
* Admin-only: reclaim root slugs for the rightful owner.
|
||||
* Default behavior is non-destructive owner transfer for existing skills
|
||||
* (preserves versions/stats/metadata) and leaves missing slugs untouched.
|
||||
* Body: { handle: string, slugs: string[], reason?: string }
|
||||
*/
|
||||
async function handleAdminReclaim(
|
||||
@@ -185,16 +187,17 @@ async function handleAdminReclaim(
|
||||
const targetUser = await ctx.runQuery(api.users.getByHandle, { handle })
|
||||
if (!targetUser?._id) return text('User not found', 404, headers)
|
||||
|
||||
const results: Array<{ slug: string; ok: boolean; error?: string }> = []
|
||||
const results: Array<{ slug: string; ok: boolean; action?: string; error?: string }> = []
|
||||
for (const slug of slugs) {
|
||||
try {
|
||||
await ctx.runMutation(internal.skills.reclaimSlugInternal, {
|
||||
const result = (await ctx.runMutation(internal.skills.reclaimSlugInternal, {
|
||||
actorUserId,
|
||||
slug: slug.trim().toLowerCase(),
|
||||
rightfulOwnerUserId: targetUser._id,
|
||||
reason,
|
||||
})
|
||||
results.push({ slug, ok: true })
|
||||
transferRootSlugOnly: true,
|
||||
})) as { action?: string }
|
||||
results.push({ slug, ok: true, action: result.action })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Reclaim failed'
|
||||
results.push({ slug, ok: false, error: message })
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@convex-dev/auth/server', () => ({
|
||||
getAuthUserId: vi.fn(),
|
||||
}))
|
||||
|
||||
const { getAuthUserId } = await import('@convex-dev/auth/server')
|
||||
const {
|
||||
assertAdmin,
|
||||
assertModerator,
|
||||
assertRole,
|
||||
requireUser,
|
||||
requireUserFromAction,
|
||||
} = await import('./access')
|
||||
|
||||
describe('access.requireUser', () => {
|
||||
it('throws when auth is missing', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue(null)
|
||||
await expect(
|
||||
requireUser({
|
||||
db: { get: vi.fn() },
|
||||
} as never),
|
||||
).rejects.toThrow('Unauthorized')
|
||||
})
|
||||
|
||||
it('throws when user is deleted/deactivated/missing', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue('users:1' as never)
|
||||
|
||||
for (const value of [null, { _id: 'users:1', deletedAt: Date.now() }, { _id: 'users:1', deactivatedAt: Date.now() }]) {
|
||||
const dbGet = vi.fn().mockResolvedValue(value as never)
|
||||
await expect(
|
||||
requireUser({
|
||||
db: { get: dbGet },
|
||||
} as never),
|
||||
).rejects.toThrow('User not found')
|
||||
}
|
||||
})
|
||||
|
||||
it('returns auth user when active', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue('users:2' as never)
|
||||
const user = { _id: 'users:2', role: 'user' }
|
||||
const dbGet = vi.fn().mockResolvedValue(user as never)
|
||||
|
||||
const result = await requireUser({
|
||||
db: { get: dbGet },
|
||||
} as never)
|
||||
|
||||
expect(dbGet).toHaveBeenCalledWith('users:2')
|
||||
expect(result).toEqual({ userId: 'users:2', user })
|
||||
})
|
||||
})
|
||||
|
||||
describe('access.requireUserFromAction', () => {
|
||||
it('throws when auth is missing', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue(null)
|
||||
await expect(
|
||||
requireUserFromAction({
|
||||
runQuery: vi.fn(),
|
||||
} as never),
|
||||
).rejects.toThrow('Unauthorized')
|
||||
})
|
||||
|
||||
it('throws when action lookup returns deleted/deactivated/missing user', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue('users:1' as never)
|
||||
|
||||
for (const value of [null, { _id: 'users:1', deletedAt: Date.now() }, { _id: 'users:1', deactivatedAt: Date.now() }]) {
|
||||
const runQuery = vi.fn().mockResolvedValue(value as never)
|
||||
await expect(
|
||||
requireUserFromAction({
|
||||
runQuery,
|
||||
} as never),
|
||||
).rejects.toThrow('User not found')
|
||||
}
|
||||
})
|
||||
|
||||
it('returns active user from action query', async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue('users:9' as never)
|
||||
const user = { _id: 'users:9', role: 'admin' }
|
||||
const runQuery = vi.fn().mockResolvedValue(user as never)
|
||||
|
||||
const result = await requireUserFromAction({
|
||||
runQuery,
|
||||
} as never)
|
||||
|
||||
expect(runQuery).toHaveBeenCalledTimes(1)
|
||||
expect(result).toEqual({ userId: 'users:9', user })
|
||||
})
|
||||
})
|
||||
|
||||
describe('access role assertions', () => {
|
||||
it('assertRole allows matching roles and rejects missing role', () => {
|
||||
expect(() => assertRole({ role: 'admin' } as never, ['admin'])).not.toThrow()
|
||||
expect(() => assertRole({ role: undefined } as never, ['admin'])).toThrow('Forbidden')
|
||||
expect(() => assertRole({ role: 'user' } as never, ['admin'])).toThrow('Forbidden')
|
||||
})
|
||||
|
||||
it('assertAdmin/assertModerator enforce expected policy', () => {
|
||||
expect(() => assertAdmin({ role: 'admin' } as never)).not.toThrow()
|
||||
expect(() => assertAdmin({ role: 'moderator' } as never)).toThrow('Forbidden')
|
||||
|
||||
expect(() => assertModerator({ role: 'admin' } as never)).not.toThrow()
|
||||
expect(() => assertModerator({ role: 'moderator' } as never)).not.toThrow()
|
||||
expect(() => assertModerator({ role: 'user' } as never)).toThrow('Forbidden')
|
||||
})
|
||||
})
|
||||
@@ -35,7 +35,7 @@ export async function getSkillBadgeMap(
|
||||
const records = await ctx.db
|
||||
.query('skillBadges')
|
||||
.withIndex('by_skill', (q) => q.eq('skillId', skillId))
|
||||
.collect()
|
||||
.take(10)
|
||||
return buildBadgeMap(records)
|
||||
}
|
||||
|
||||
|
||||
+1
-21
@@ -1,6 +1,7 @@
|
||||
import { internal } from '../_generated/api'
|
||||
import type { Doc, Id } from '../_generated/dataModel'
|
||||
import type { ActionCtx } from '../_generated/server'
|
||||
import { extractResponseText } from './openaiResponse'
|
||||
|
||||
const CHANGELOG_MODEL = process.env.OPENAI_CHANGELOG_MODEL ?? 'gpt-4.1'
|
||||
const MAX_README_CHARS = 8_000
|
||||
@@ -59,27 +60,6 @@ function pickPaths(values: string[]) {
|
||||
return values.slice(0, MAX_PATHS_IN_PROMPT)
|
||||
}
|
||||
|
||||
function extractResponseText(payload: unknown) {
|
||||
if (!payload || typeof payload !== 'object') return null
|
||||
const output = (payload as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) return null
|
||||
const chunks: string[] = []
|
||||
for (const item of output) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if ((item as { type?: unknown }).type !== 'message') continue
|
||||
const content = (item as { content?: unknown }).content
|
||||
if (!Array.isArray(content)) continue
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== 'object') continue
|
||||
if ((part as { type?: unknown }).type !== 'output_text') continue
|
||||
const text = (part as { text?: unknown }).text
|
||||
if (typeof text === 'string' && text.trim()) chunks.push(text)
|
||||
}
|
||||
}
|
||||
const joined = chunks.join('\n').trim()
|
||||
return joined || null
|
||||
}
|
||||
|
||||
async function generateWithOpenAI(args: {
|
||||
slug: string
|
||||
version: string
|
||||
|
||||
@@ -116,6 +116,7 @@ export async function syncGitHubProfile(ctx: ActionCtx, userId: Id<'users'>) {
|
||||
const payload = (await response.json()) as GitHubUser
|
||||
const newLogin = payload.login?.trim()
|
||||
const newImage = payload.avatar_url?.trim()
|
||||
|
||||
const profileName = payload.name?.trim()
|
||||
|
||||
if (!newLogin) return
|
||||
|
||||
+105
-1
@@ -74,6 +74,13 @@ export type GitHubBackupContext = {
|
||||
root: string
|
||||
}
|
||||
|
||||
export type GitHubSkillBackupEntry = {
|
||||
owner: string
|
||||
slug: string
|
||||
rootPath: string
|
||||
metaPath: string
|
||||
}
|
||||
|
||||
export function isGitHubBackupConfigured() {
|
||||
return Boolean(
|
||||
process.env.GITHUB_APP_ID &&
|
||||
@@ -108,6 +115,103 @@ export async function fetchGitHubSkillMeta(
|
||||
)
|
||||
}
|
||||
|
||||
export async function listGitHubSkillBackupEntries(
|
||||
context: GitHubBackupContext,
|
||||
): Promise<GitHubSkillBackupEntry[]> {
|
||||
const ref = await githubGet<GitRef>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/ref/heads/${context.branch}`,
|
||||
)
|
||||
const baseCommit = await githubGet<GitCommit>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/commits/${ref.object.sha}`,
|
||||
)
|
||||
const tree = await githubGet<GitTree>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/trees/${baseCommit.tree.sha}?recursive=1`,
|
||||
)
|
||||
|
||||
const prefix = context.root ? `${context.root}/` : ''
|
||||
const entries: GitHubSkillBackupEntry[] = []
|
||||
for (const entry of tree.tree ?? []) {
|
||||
if (entry.type !== 'blob' || !entry.path) continue
|
||||
if (!entry.path.startsWith(prefix) || !entry.path.endsWith(`/${META_FILENAME}`)) continue
|
||||
const relative = entry.path.slice(prefix.length)
|
||||
const segments = relative.split('/')
|
||||
if (segments.length !== 3) continue
|
||||
const [owner, slug, file] = segments
|
||||
if (file !== META_FILENAME) continue
|
||||
const rootPath = prefix ? `${prefix}${owner}/${slug}` : `${owner}/${slug}`
|
||||
entries.push({ owner, slug, rootPath, metaPath: entry.path })
|
||||
}
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
export async function deleteGitHubSkillBackup(
|
||||
context: GitHubBackupContext,
|
||||
ownerHandle: string,
|
||||
slug: string,
|
||||
) {
|
||||
const skillRoot = buildSkillRoot(context.root, ownerHandle, slug)
|
||||
const ref = await githubGet<GitRef>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/ref/heads/${context.branch}`,
|
||||
)
|
||||
const baseCommitSha = ref.object.sha
|
||||
const baseCommit = await githubGet<GitCommit>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/commits/${baseCommitSha}`,
|
||||
)
|
||||
const baseTreeSha = baseCommit.tree.sha
|
||||
const existingTree = await githubGet<GitTree>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/trees/${baseTreeSha}?recursive=1`,
|
||||
)
|
||||
|
||||
const prefix = `${skillRoot}/`
|
||||
const pathsToDelete = (existingTree.tree ?? [])
|
||||
.filter((entry) => entry.type === 'blob' && entry.path?.startsWith(prefix))
|
||||
.map((entry) => entry.path ?? '')
|
||||
.filter(Boolean)
|
||||
|
||||
if (!pathsToDelete.length) return { deleted: false as const }
|
||||
|
||||
const treeEntries = pathsToDelete.map((path) => ({
|
||||
path,
|
||||
mode: '100644' as const,
|
||||
type: 'blob' as const,
|
||||
sha: null,
|
||||
}))
|
||||
|
||||
const newTree = await githubPost<{ sha: string }>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/trees`,
|
||||
{
|
||||
base_tree: baseTreeSha,
|
||||
tree: treeEntries,
|
||||
},
|
||||
)
|
||||
|
||||
const commit = await githubPost<GitCommit>(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/commits`,
|
||||
{
|
||||
message: `delete: ${skillRoot}`,
|
||||
tree: newTree.sha,
|
||||
parents: [baseCommitSha],
|
||||
},
|
||||
)
|
||||
|
||||
await githubPatch(
|
||||
context.token,
|
||||
`/repos/${context.repoOwner}/${context.repoName}/git/refs/heads/${context.branch}`,
|
||||
{ sha: commit.sha },
|
||||
)
|
||||
|
||||
return { deleted: true as const }
|
||||
}
|
||||
|
||||
export async function backupSkillToGitHub(
|
||||
ctx: ActionCtx,
|
||||
params: BackupParams,
|
||||
@@ -397,7 +501,7 @@ function parseRepo(repo: string) {
|
||||
return [owner, name] as const
|
||||
}
|
||||
|
||||
function normalizeOwner(value: string) {
|
||||
export function normalizeOwner(value: string) {
|
||||
const normalized = value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { Doc } from '../_generated/dataModel'
|
||||
import type { MutationCtx, QueryCtx } from '../_generated/server'
|
||||
|
||||
export const GLOBAL_STATS_KEY = 'default'
|
||||
|
||||
type SkillVisibilityFields = Pick<
|
||||
Doc<'skills'>,
|
||||
'softDeletedAt' | 'moderationStatus' | 'moderationFlags'
|
||||
>
|
||||
|
||||
type GlobalStatsReadCtx = Pick<MutationCtx | QueryCtx, 'db'>
|
||||
type GlobalStatsWriteCtx = Pick<MutationCtx, 'db'>
|
||||
|
||||
export function isPublicSkillDoc(skill: SkillVisibilityFields | null | undefined) {
|
||||
if (!skill || skill.softDeletedAt) return false
|
||||
if (skill.moderationStatus && skill.moderationStatus !== 'active') return false
|
||||
if (skill.moderationFlags?.includes('blocked.malware')) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export function getPublicSkillVisibilityDelta(
|
||||
before: SkillVisibilityFields | null | undefined,
|
||||
after: SkillVisibilityFields | null | undefined,
|
||||
) {
|
||||
const beforePublic = isPublicSkillDoc(before)
|
||||
const afterPublic = isPublicSkillDoc(after)
|
||||
if (beforePublic === afterPublic) return 0
|
||||
return afterPublic ? 1 : -1
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
if (typeof error === 'string') return error
|
||||
if (error && typeof error === 'object' && 'message' in error) {
|
||||
const message = (error as { message?: unknown }).message
|
||||
if (typeof message === 'string') return message
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export function isGlobalStatsStorageNotReadyError(error: unknown) {
|
||||
const message = getErrorMessage(error).toLowerCase()
|
||||
if (!message) return false
|
||||
const referencesGlobalStats = message.includes('globalstats') || message.includes('by_key')
|
||||
if (!referencesGlobalStats) return false
|
||||
return (
|
||||
message.includes('table') ||
|
||||
message.includes('index') ||
|
||||
message.includes('schema') ||
|
||||
message.includes('not found') ||
|
||||
message.includes('does not exist') ||
|
||||
message.includes('unknown')
|
||||
)
|
||||
}
|
||||
|
||||
export async function countPublicSkillsForGlobalStats(ctx: GlobalStatsReadCtx) {
|
||||
const skills = await ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined))
|
||||
.collect()
|
||||
let count = 0
|
||||
for (const skill of skills) {
|
||||
if (isPublicSkillDoc(skill)) count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
export async function setGlobalPublicSkillsCount(
|
||||
ctx: GlobalStatsWriteCtx,
|
||||
count: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const normalizedCount = Math.max(0, Math.trunc(Number.isFinite(count) ? count : 0))
|
||||
try {
|
||||
const existing = await ctx.db
|
||||
.query('globalStats')
|
||||
.withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY))
|
||||
.unique()
|
||||
|
||||
if (existing) {
|
||||
await ctx.db.patch(existing._id, { activeSkillsCount: normalizedCount, updatedAt: now })
|
||||
} else {
|
||||
await ctx.db.insert('globalStats', {
|
||||
key: GLOBAL_STATS_KEY,
|
||||
activeSkillsCount: normalizedCount,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
if (isGlobalStatsStorageNotReadyError(error)) return
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function adjustGlobalPublicSkillsCount(
|
||||
ctx: GlobalStatsWriteCtx,
|
||||
delta: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const normalizedDelta = Math.trunc(Number.isFinite(delta) ? delta : 0)
|
||||
if (normalizedDelta === 0) return
|
||||
|
||||
let existing:
|
||||
| {
|
||||
_id: Doc<'globalStats'>['_id']
|
||||
activeSkillsCount: number
|
||||
}
|
||||
| null
|
||||
| undefined
|
||||
try {
|
||||
existing = await ctx.db
|
||||
.query('globalStats')
|
||||
.withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY))
|
||||
.unique()
|
||||
} catch (error) {
|
||||
if (isGlobalStatsStorageNotReadyError(error)) return
|
||||
throw error
|
||||
}
|
||||
|
||||
if (!existing) {
|
||||
// No baseline yet (e.g. fresh deploy). Initialize via full recount once.
|
||||
const count = await countPublicSkillsForGlobalStats(ctx)
|
||||
await setGlobalPublicSkillsCount(ctx, count, now)
|
||||
return
|
||||
}
|
||||
|
||||
const nextCount = Math.max(0, existing.activeSkillsCount + normalizedDelta)
|
||||
await ctx.db.patch(existing._id, { activeSkillsCount: nextCount, updatedAt: now })
|
||||
}
|
||||
|
||||
export async function readGlobalPublicSkillsCount(ctx: GlobalStatsReadCtx) {
|
||||
try {
|
||||
const stats = await ctx.db
|
||||
.query('globalStats')
|
||||
.withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY))
|
||||
.unique()
|
||||
return stats?.activeSkillsCount ?? null
|
||||
} catch (error) {
|
||||
if (isGlobalStatsStorageNotReadyError(error)) return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,51 @@
|
||||
/* @vitest-environment node */
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { getClientIp } from './httpRateLimit'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { applyRateLimit, getClientIp } from './httpRateLimit'
|
||||
|
||||
type MockRateLimitStatus = {
|
||||
allowed: boolean
|
||||
remaining: number
|
||||
limit: number
|
||||
resetAt: number
|
||||
}
|
||||
|
||||
type MockRateLimitPlan = {
|
||||
ip: MockRateLimitStatus
|
||||
user?: MockRateLimitStatus
|
||||
tokenValid?: boolean
|
||||
userActive?: boolean
|
||||
}
|
||||
|
||||
function makeRateLimitCtx(plan: MockRateLimitPlan) {
|
||||
const runQuery = vi.fn(async (_fn: unknown, args: Record<string, unknown>) => {
|
||||
if ('tokenHash' in args) {
|
||||
if (plan.tokenValid === false) return null
|
||||
return { _id: 'token_1', revokedAt: undefined }
|
||||
}
|
||||
if ('tokenId' in args) {
|
||||
if (plan.userActive === false) return null
|
||||
return { _id: 'users_123', deletedAt: undefined, deactivatedAt: undefined }
|
||||
}
|
||||
if ('key' in args && 'limit' in args && 'windowMs' in args) {
|
||||
const key = String(args.key)
|
||||
if (key.startsWith('ip:')) return plan.ip
|
||||
if (key.startsWith('user:')) return plan.user
|
||||
}
|
||||
throw new Error(`Unexpected runQuery args: ${JSON.stringify(args)}`)
|
||||
})
|
||||
|
||||
const runMutation = vi.fn(async (_fn: unknown, args: Record<string, unknown>) => {
|
||||
const key = String(args.key)
|
||||
const source = key.startsWith('user:') ? plan.user : plan.ip
|
||||
if (!source) throw new Error(`Missing rate limit source for ${key}`)
|
||||
return { allowed: source.allowed, remaining: source.remaining }
|
||||
})
|
||||
|
||||
return {
|
||||
runQuery,
|
||||
runMutation,
|
||||
} as unknown as Parameters<typeof applyRateLimit>[0]
|
||||
}
|
||||
|
||||
describe('getClientIp', () => {
|
||||
let prev: string | undefined
|
||||
@@ -53,4 +98,199 @@ describe('getClientIp', () => {
|
||||
process.env.TRUST_FORWARDED_IPS = 'true'
|
||||
expect(getClientIp(request)).toBe('203.0.113.9')
|
||||
})
|
||||
|
||||
it('prefers x-forwarded-for over x-real-ip when trusted mode is enabled', () => {
|
||||
const request = new Request('https://example.com', {
|
||||
headers: {
|
||||
'x-forwarded-for': '203.0.113.9, 198.51.100.2',
|
||||
'x-real-ip': '198.51.100.77',
|
||||
},
|
||||
})
|
||||
process.env.TRUST_FORWARDED_IPS = 'true'
|
||||
expect(getClientIp(request)).toBe('203.0.113.9')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRateLimit headers', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('returns delay-seconds Retry-After on 429 (not epoch)', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1_000_000)
|
||||
const runMutation = vi.fn()
|
||||
const ctx = {
|
||||
runQuery: vi.fn().mockResolvedValue({
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
limit: 20,
|
||||
resetAt: 1_030_500,
|
||||
}),
|
||||
runMutation,
|
||||
} as unknown as Parameters<typeof applyRateLimit>[0]
|
||||
const request = new Request('https://example.com', {
|
||||
headers: { 'cf-connecting-ip': '203.0.113.1' },
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect(result.response.status).toBe(429)
|
||||
expect(result.response.headers.get('Retry-After')).toBe('31')
|
||||
expect(result.response.headers.get('X-RateLimit-Reset')).toBe('1031')
|
||||
expect(result.response.headers.get('RateLimit-Reset')).toBe('31')
|
||||
expect(runMutation).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('includes rate-limit headers without Retry-After when allowed', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(2_000_000)
|
||||
const ctx = {
|
||||
runQuery: vi.fn().mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 19,
|
||||
limit: 20,
|
||||
resetAt: 2_015_000,
|
||||
}),
|
||||
runMutation: vi.fn().mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 18,
|
||||
}),
|
||||
} as unknown as Parameters<typeof applyRateLimit>[0]
|
||||
const request = new Request('https://example.com', {
|
||||
headers: { 'cf-connecting-ip': '203.0.113.1' },
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
const headers = new Headers(result.headers)
|
||||
expect(headers.get('X-RateLimit-Limit')).toBe('20')
|
||||
expect(headers.get('X-RateLimit-Remaining')).toBe('18')
|
||||
expect(headers.get('X-RateLimit-Reset')).toBe('2015')
|
||||
expect(headers.get('RateLimit-Limit')).toBe('20')
|
||||
expect(headers.get('RateLimit-Remaining')).toBe('18')
|
||||
expect(headers.get('RateLimit-Reset')).toBe('15')
|
||||
expect(headers.get('Retry-After')).toBeNull()
|
||||
})
|
||||
|
||||
it('allows authenticated users when user bucket is healthy and shared ip bucket is exhausted', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(3_000_000)
|
||||
const ctx = makeRateLimitCtx({
|
||||
ip: {
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
limit: 20,
|
||||
resetAt: 3_040_000,
|
||||
},
|
||||
user: {
|
||||
allowed: true,
|
||||
remaining: 42,
|
||||
limit: 120,
|
||||
resetAt: 3_010_000,
|
||||
},
|
||||
})
|
||||
const request = new Request('https://example.com', {
|
||||
headers: {
|
||||
authorization: 'Bearer clh_token',
|
||||
'cf-connecting-ip': '203.0.113.1',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
const headers = new Headers(result.headers)
|
||||
expect(headers.get('X-RateLimit-Limit')).toBe('120')
|
||||
expect(headers.get('X-RateLimit-Remaining')).toBe('42')
|
||||
expect(headers.get('Retry-After')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not consume ip bucket for authenticated requests', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(3_100_000)
|
||||
const ctx = makeRateLimitCtx({
|
||||
ip: {
|
||||
allowed: true,
|
||||
remaining: 19,
|
||||
limit: 20,
|
||||
resetAt: 3_140_000,
|
||||
},
|
||||
user: {
|
||||
allowed: true,
|
||||
remaining: 41,
|
||||
limit: 120,
|
||||
resetAt: 3_110_000,
|
||||
},
|
||||
})
|
||||
const request = new Request('https://example.com', {
|
||||
headers: {
|
||||
authorization: 'Bearer clh_token',
|
||||
'cf-connecting-ip': '203.0.113.1',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(true)
|
||||
const runMutation = (ctx as unknown as { runMutation: ReturnType<typeof vi.fn> }).runMutation
|
||||
const consumedKeys = runMutation.mock.calls.map(([, args]) => String(args.key))
|
||||
expect(consumedKeys.some((key) => key.startsWith('user:'))).toBe(true)
|
||||
expect(consumedKeys.some((key) => key.startsWith('ip:'))).toBe(false)
|
||||
})
|
||||
|
||||
it('denies authenticated users when user bucket is exhausted even if ip bucket is healthy', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(4_000_000)
|
||||
const ctx = makeRateLimitCtx({
|
||||
ip: {
|
||||
allowed: true,
|
||||
remaining: 19,
|
||||
limit: 20,
|
||||
resetAt: 4_020_000,
|
||||
},
|
||||
user: {
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
limit: 120,
|
||||
resetAt: 4_030_000,
|
||||
},
|
||||
})
|
||||
const request = new Request('https://example.com', {
|
||||
headers: {
|
||||
authorization: 'Bearer clh_token',
|
||||
'cf-connecting-ip': '203.0.113.1',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect(result.response.status).toBe(429)
|
||||
expect(result.response.headers.get('X-RateLimit-Limit')).toBe('120')
|
||||
expect(result.response.headers.get('X-RateLimit-Remaining')).toBe('0')
|
||||
expect(result.response.headers.get('Retry-After')).toBe('30')
|
||||
})
|
||||
|
||||
it('falls back to ip enforcement when bearer token is invalid', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(5_000_000)
|
||||
const ctx = makeRateLimitCtx({
|
||||
tokenValid: false,
|
||||
ip: {
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
limit: 20,
|
||||
resetAt: 5_030_000,
|
||||
},
|
||||
})
|
||||
const request = new Request('https://example.com', {
|
||||
headers: {
|
||||
authorization: 'Bearer invalid',
|
||||
'cf-connecting-ip': '203.0.113.1',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await applyRateLimit(ctx, request, 'download')
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect(result.response.status).toBe(429)
|
||||
expect(result.response.headers.get('X-RateLimit-Limit')).toBe('20')
|
||||
expect(result.response.headers.get('Retry-After')).toBe('30')
|
||||
})
|
||||
})
|
||||
|
||||
+64
-18
@@ -1,7 +1,7 @@
|
||||
import { internal } from '../_generated/api'
|
||||
import type { ActionCtx } from '../_generated/server'
|
||||
import { getOptionalApiTokenUserId } from './apiTokenAuth'
|
||||
import { corsHeaders, mergeHeaders } from './httpHeaders'
|
||||
import { hashToken } from './tokens'
|
||||
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000
|
||||
export const RATE_LIMITS = {
|
||||
@@ -22,17 +22,56 @@ export async function applyRateLimit(
|
||||
request: Request,
|
||||
kind: keyof typeof RATE_LIMITS,
|
||||
): Promise<{ ok: true; headers: HeadersInit } | { ok: false; response: Response }> {
|
||||
const userId = await getOptionalApiTokenUserId(ctx, request)
|
||||
const ip = getClientIp(request) ?? 'unknown'
|
||||
const ipSource = getClientIpSource(request)
|
||||
const hasClientIp = ip !== 'unknown'
|
||||
|
||||
// Authenticated requests are enforced and consumed by user bucket only to
|
||||
// avoid draining shared IP quota.
|
||||
if (userId) {
|
||||
const userResult = await checkRateLimit(ctx, `user:${userId}`, RATE_LIMITS[kind].key)
|
||||
const headers = rateHeaders(userResult)
|
||||
if (!userResult.allowed) {
|
||||
console.info('rate_limit_denied', {
|
||||
kind,
|
||||
auth: true,
|
||||
userAllowed: false,
|
||||
ipAllowed: null,
|
||||
ipSource,
|
||||
hasClientIp,
|
||||
})
|
||||
return {
|
||||
ok: false,
|
||||
response: new Response('Rate limit exceeded', {
|
||||
status: 429,
|
||||
headers: mergeHeaders(
|
||||
{
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
headers,
|
||||
corsHeaders(),
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
return { ok: true, headers }
|
||||
}
|
||||
|
||||
// Anonymous requests remain IP-enforced.
|
||||
const ipResult = await checkRateLimit(ctx, `ip:${ip}`, RATE_LIMITS[kind].ip)
|
||||
const token = parseBearerToken(request)
|
||||
const keyResult = token
|
||||
? await checkRateLimit(ctx, `key:${await hashToken(token)}`, RATE_LIMITS[kind].key)
|
||||
: null
|
||||
const headers = rateHeaders(ipResult)
|
||||
|
||||
const chosen = pickMostRestrictive(ipResult, keyResult)
|
||||
const headers = rateHeaders(chosen)
|
||||
|
||||
if (!ipResult.allowed || (keyResult && !keyResult.allowed)) {
|
||||
if (!ipResult.allowed) {
|
||||
console.info('rate_limit_denied', {
|
||||
kind,
|
||||
auth: false,
|
||||
userAllowed: null,
|
||||
ipAllowed: ipResult.allowed,
|
||||
ipSource,
|
||||
hasClientIp,
|
||||
})
|
||||
return {
|
||||
ok: false,
|
||||
response: new Response('Rate limit exceeded', {
|
||||
@@ -59,13 +98,22 @@ export function getClientIp(request: Request) {
|
||||
if (!shouldTrustForwardedIps()) return null
|
||||
|
||||
const forwarded =
|
||||
request.headers.get('x-real-ip') ??
|
||||
request.headers.get('x-forwarded-for') ??
|
||||
request.headers.get('x-real-ip') ??
|
||||
request.headers.get('fly-client-ip')
|
||||
|
||||
return splitFirstIp(forwarded)
|
||||
}
|
||||
|
||||
function getClientIpSource(request: Request) {
|
||||
if (request.headers.get('cf-connecting-ip')) return 'cf-connecting-ip'
|
||||
if (!shouldTrustForwardedIps()) return 'none'
|
||||
if (request.headers.get('x-forwarded-for')) return 'x-forwarded-for'
|
||||
if (request.headers.get('x-real-ip')) return 'x-real-ip'
|
||||
if (request.headers.get('fly-client-ip')) return 'fly-client-ip'
|
||||
return 'none'
|
||||
}
|
||||
|
||||
async function checkRateLimit(
|
||||
ctx: ActionCtx,
|
||||
key: string,
|
||||
@@ -110,20 +158,18 @@ async function checkRateLimit(
|
||||
}
|
||||
}
|
||||
|
||||
function pickMostRestrictive(primary: RateLimitResult, secondary: RateLimitResult | null) {
|
||||
if (!secondary) return primary
|
||||
if (!primary.allowed) return primary
|
||||
if (!secondary.allowed) return secondary
|
||||
return secondary.remaining < primary.remaining ? secondary : primary
|
||||
}
|
||||
|
||||
function rateHeaders(result: RateLimitResult): HeadersInit {
|
||||
const nowMs = Date.now()
|
||||
const resetSeconds = Math.ceil(result.resetAt / 1000)
|
||||
const resetDelaySeconds = Math.max(1, Math.ceil((result.resetAt - nowMs) / 1000))
|
||||
return {
|
||||
'X-RateLimit-Limit': String(result.limit),
|
||||
'X-RateLimit-Remaining': String(result.remaining),
|
||||
'X-RateLimit-Reset': String(resetSeconds),
|
||||
...(result.allowed ? {} : { 'Retry-After': String(resetSeconds) }),
|
||||
'RateLimit-Limit': String(result.limit),
|
||||
'RateLimit-Remaining': String(result.remaining),
|
||||
'RateLimit-Reset': String(resetDelaySeconds),
|
||||
...(result.allowed ? {} : { 'Retry-After': String(resetDelaySeconds) }),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractResponseText } from './openaiResponse'
|
||||
|
||||
describe('extractResponseText', () => {
|
||||
it('returns null for invalid payload shapes', () => {
|
||||
expect(extractResponseText(null)).toBeNull()
|
||||
expect(extractResponseText({})).toBeNull()
|
||||
expect(extractResponseText({ output: {} })).toBeNull()
|
||||
})
|
||||
|
||||
it('extracts output_text chunks from message content', () => {
|
||||
const payload = {
|
||||
output: [
|
||||
{ type: 'reasoning', content: [] },
|
||||
{
|
||||
type: 'message',
|
||||
content: [
|
||||
{ type: 'output_text', text: 'First line' },
|
||||
{ type: 'output_text', text: 'Second line' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
expect(extractResponseText(payload)).toBe('First line\nSecond line')
|
||||
})
|
||||
|
||||
it('ignores blank and non-output_text parts', () => {
|
||||
const payload = {
|
||||
output: [
|
||||
{
|
||||
type: 'message',
|
||||
content: [
|
||||
{ type: 'input_text', text: 'ignored' },
|
||||
{ type: 'output_text', text: ' ' },
|
||||
{ type: 'output_text', text: 'kept' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
expect(extractResponseText(payload)).toBe('kept')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
export function extractResponseText(payload: unknown): string | null {
|
||||
if (!payload || typeof payload !== 'object') return null
|
||||
const output = (payload as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) return null
|
||||
const chunks: string[] = []
|
||||
for (const item of output) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if ((item as { type?: unknown }).type !== 'message') continue
|
||||
const content = (item as { content?: unknown }).content
|
||||
if (!Array.isArray(content)) continue
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== 'object') continue
|
||||
if ((part as { type?: unknown }).type !== 'output_text') continue
|
||||
const text = (part as { text?: unknown }).text
|
||||
if (typeof text === 'string' && text.trim()) chunks.push(text)
|
||||
}
|
||||
}
|
||||
const joined = chunks.join('\n').trim()
|
||||
return joined || null
|
||||
}
|
||||
@@ -65,4 +65,32 @@ describe('public skill mapping', () => {
|
||||
comments: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns skill when moderationStatus is active', () => {
|
||||
const skill = makeSkill({ moderationStatus: 'active' })
|
||||
expect(toPublicSkill(skill)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('filters out skill when moderationStatus is hidden', () => {
|
||||
const skill = makeSkill({ moderationStatus: 'hidden' })
|
||||
expect(toPublicSkill(skill)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns skill when moderationStatus is undefined (legacy)', () => {
|
||||
const skill = makeSkill({ moderationStatus: undefined as unknown as string })
|
||||
expect(toPublicSkill(skill)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('filters out soft-deleted skills', () => {
|
||||
const skill = makeSkill({ softDeletedAt: Date.now() })
|
||||
expect(toPublicSkill(skill)).toBeNull()
|
||||
})
|
||||
|
||||
it('filters out skills with blocked.malware flag', () => {
|
||||
const skill = makeSkill({
|
||||
moderationStatus: 'active',
|
||||
moderationFlags: ['blocked.malware'],
|
||||
})
|
||||
expect(toPublicSkill(skill)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Doc } from '../_generated/dataModel'
|
||||
import { isPublicSkillDoc } from './globalStats'
|
||||
|
||||
export type PublicUser = Pick<
|
||||
Doc<'users'>,
|
||||
@@ -52,9 +53,8 @@ export function toPublicUser(user: Doc<'users'> | null | undefined): PublicUser
|
||||
}
|
||||
|
||||
export function toPublicSkill(skill: Doc<'skills'> | null | undefined): PublicSkill | null {
|
||||
if (!skill || skill.softDeletedAt) return null
|
||||
if (skill.moderationStatus && skill.moderationStatus !== 'active') return null
|
||||
if (skill.moderationFlags?.includes('blocked.malware')) return null
|
||||
if (!skill) return null
|
||||
if (!isPublicSkillDoc(skill)) return null
|
||||
const stats = {
|
||||
downloads:
|
||||
typeof skill.statsDownloads === 'number'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getFrontmatterValue, parseFrontmatter } from './skills'
|
||||
import { extractResponseText } from './openaiResponse'
|
||||
|
||||
const SKILL_SUMMARY_MODEL = process.env.OPENAI_SKILL_SUMMARY_MODEL ?? 'gpt-4.1-mini'
|
||||
const MAX_README_CHARS = 8_000
|
||||
@@ -61,27 +62,6 @@ function deriveIdentityFallback(args: { slug: string; displayName: string }) {
|
||||
return normalizeSummary(`Automation skill for ${base}.`)
|
||||
}
|
||||
|
||||
function extractResponseText(payload: unknown) {
|
||||
if (!payload || typeof payload !== 'object') return null
|
||||
const output = (payload as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) return null
|
||||
const chunks: string[] = []
|
||||
for (const item of output) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if ((item as { type?: unknown }).type !== 'message') continue
|
||||
const content = (item as { content?: unknown }).content
|
||||
if (!Array.isArray(content)) continue
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== 'object') continue
|
||||
if ((part as { type?: unknown }).type !== 'output_text') continue
|
||||
const text = (part as { text?: unknown }).text
|
||||
if (typeof text === 'string' && text.trim()) chunks.push(text)
|
||||
}
|
||||
}
|
||||
const joined = chunks.join('\n').trim()
|
||||
return joined || null
|
||||
}
|
||||
|
||||
export async function generateSkillSummary(args: {
|
||||
slug: string
|
||||
displayName: string
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { internal } from '../_generated/api'
|
||||
import type { Doc } from '../_generated/dataModel'
|
||||
import type { ActionCtx } from '../_generated/server'
|
||||
import { extractResponseText } from './openaiResponse'
|
||||
|
||||
const CHANGELOG_MODEL = process.env.OPENAI_CHANGELOG_MODEL ?? 'gpt-4.1'
|
||||
const MAX_README_CHARS = 8_000
|
||||
@@ -59,27 +60,6 @@ function pickPaths(values: string[]) {
|
||||
return values.slice(0, MAX_PATHS_IN_PROMPT)
|
||||
}
|
||||
|
||||
function extractResponseText(payload: unknown) {
|
||||
if (!payload || typeof payload !== 'object') return null
|
||||
const output = (payload as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) return null
|
||||
const chunks: string[] = []
|
||||
for (const item of output) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if ((item as { type?: unknown }).type !== 'message') continue
|
||||
const content = (item as { content?: unknown }).content
|
||||
if (!Array.isArray(content)) continue
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== 'object') continue
|
||||
if ((part as { type?: unknown }).type !== 'output_text') continue
|
||||
const text = (part as { text?: unknown }).text
|
||||
if (typeof text === 'string' && text.trim()) chunks.push(text)
|
||||
}
|
||||
}
|
||||
const joined = chunks.join('\n').trim()
|
||||
return joined || null
|
||||
}
|
||||
|
||||
async function generateWithOpenAI(args: {
|
||||
slug: string
|
||||
version: string
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildUserSearchResults } from './userSearch'
|
||||
|
||||
function makeUser(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
_id: 'users:1',
|
||||
_creationTime: 1,
|
||||
handle: 'alice',
|
||||
name: 'alice-gh',
|
||||
displayName: 'Alice',
|
||||
email: 'alice@example.com',
|
||||
...overrides,
|
||||
} as never
|
||||
}
|
||||
|
||||
describe('buildUserSearchResults', () => {
|
||||
it('returns all users when query is empty', () => {
|
||||
const users = [makeUser({ _id: 'users:1' }), makeUser({ _id: 'users:2', handle: 'bob' })]
|
||||
const result = buildUserSearchResults(users)
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.items).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('matches compact handle/search variants', () => {
|
||||
const users = [makeUser({ handle: 'alice-dev' }), makeUser({ _id: 'users:2', handle: 'bob' })]
|
||||
const result = buildUserSearchResults(users, 'alicedev')
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items[0]?.handle).toBe('alice-dev')
|
||||
})
|
||||
|
||||
it('does not throw on malformed legacy field types', () => {
|
||||
const users = [
|
||||
makeUser({
|
||||
_id: 'users:legacy',
|
||||
handle: 42,
|
||||
name: { bad: true },
|
||||
displayName: null,
|
||||
email: ['legacy@example.com'],
|
||||
}),
|
||||
makeUser({ _id: 'users:2', handle: 'carol' }),
|
||||
]
|
||||
|
||||
expect(() => buildUserSearchResults(users, 'car')).not.toThrow()
|
||||
const result = buildUserSearchResults(users, 'car')
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items[0]?._id).toBe('users:2')
|
||||
})
|
||||
|
||||
it('ranks exact id match above fuzzy matches', () => {
|
||||
const users = [
|
||||
makeUser({ _id: 'users:target', handle: 'target-user', _creationTime: 1 }),
|
||||
makeUser({ _id: 'users:2', handle: 'users:target', _creationTime: 10 }),
|
||||
]
|
||||
|
||||
const result = buildUserSearchResults(users, 'users:target')
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.items[0]?._id).toBe('users:target')
|
||||
})
|
||||
|
||||
it('uses creation time as tie-break when scores are equal', () => {
|
||||
const users = [
|
||||
makeUser({ _id: 'users:older', handle: 'alpha', _creationTime: 1 }),
|
||||
makeUser({ _id: 'users:newer', handle: 'alpha-two', _creationTime: 50 }),
|
||||
]
|
||||
|
||||
const result = buildUserSearchResults(users, 'pha')
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.items[0]?._id).toBe('users:newer')
|
||||
expect(result.items[1]?._id).toBe('users:older')
|
||||
})
|
||||
})
|
||||
@@ -14,11 +14,15 @@ function normalizeCompact(value: string) {
|
||||
return value.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
}
|
||||
|
||||
function toSearchText(value: unknown) {
|
||||
return typeof value === 'string' ? value.toLowerCase() : ''
|
||||
}
|
||||
|
||||
function scoreUser(user: Doc<'users'>, query: string, compactQuery: string) {
|
||||
const handle = user.handle?.toLowerCase() ?? ''
|
||||
const name = user.name?.toLowerCase() ?? ''
|
||||
const displayName = user.displayName?.toLowerCase() ?? ''
|
||||
const email = user.email?.toLowerCase() ?? ''
|
||||
const handle = toSearchText(user.handle)
|
||||
const name = toSearchText(user.name)
|
||||
const displayName = toSearchText(user.displayName)
|
||||
const email = toSearchText(user.email)
|
||||
const id = String(user._id).toLowerCase()
|
||||
|
||||
let score = 0
|
||||
|
||||
+1
-21
@@ -11,32 +11,12 @@ import {
|
||||
parseLlmEvalResponse,
|
||||
SECURITY_EVALUATOR_SYSTEM_PROMPT,
|
||||
} from './lib/securityPrompt'
|
||||
import { extractResponseText } from './lib/openaiResponse'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function extractResponseText(payload: unknown): string | null {
|
||||
if (!payload || typeof payload !== 'object') return null
|
||||
const output = (payload as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) return null
|
||||
const chunks: string[] = []
|
||||
for (const item of output) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if ((item as { type?: unknown }).type !== 'message') continue
|
||||
const content = (item as { content?: unknown }).content
|
||||
if (!Array.isArray(content)) continue
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== 'object') continue
|
||||
if ((part as { type?: unknown }).type !== 'output_text') continue
|
||||
const text = (part as { text?: unknown }).text
|
||||
if (typeof text === 'string' && text.trim()) chunks.push(text)
|
||||
}
|
||||
}
|
||||
const joined = chunks.join('\n').trim()
|
||||
return joined || null
|
||||
}
|
||||
|
||||
function verdictToStatus(verdict: string): string {
|
||||
switch (verdict) {
|
||||
case 'benign':
|
||||
|
||||
@@ -37,6 +37,7 @@ const {
|
||||
backfillSkillSummariesInternalHandler,
|
||||
cleanupEmptySkillsInternalHandler,
|
||||
nominateEmptySkillSpammersInternalHandler,
|
||||
upsertSkillBadgeRecordInternal,
|
||||
} = await import('./maintenance')
|
||||
const { internal } = await import('./_generated/api')
|
||||
const { generateSkillSummary } = await import('./lib/skillSummary')
|
||||
@@ -196,6 +197,81 @@ describe('maintenance backfill', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('maintenance badge denormalization', () => {
|
||||
it('upserts table badge and keeps skill.badges in sync', async () => {
|
||||
const unique = vi.fn().mockResolvedValue(null)
|
||||
const query = vi.fn().mockReturnValue({
|
||||
withIndex: () => ({ unique }),
|
||||
})
|
||||
const insert = vi.fn().mockResolvedValue('skillBadges:1')
|
||||
const get = vi.fn().mockResolvedValue({ _id: 'skills:1', badges: undefined })
|
||||
const patch = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
query,
|
||||
insert,
|
||||
get,
|
||||
patch,
|
||||
},
|
||||
} as never
|
||||
|
||||
const result = await (upsertSkillBadgeRecordInternal as { _handler: Function })._handler(ctx, {
|
||||
skillId: 'skills:1',
|
||||
kind: 'highlighted',
|
||||
byUserId: 'users:1',
|
||||
at: 123,
|
||||
})
|
||||
|
||||
expect(result).toEqual({ inserted: true })
|
||||
expect(insert).toHaveBeenCalledWith('skillBadges', {
|
||||
skillId: 'skills:1',
|
||||
kind: 'highlighted',
|
||||
byUserId: 'users:1',
|
||||
at: 123,
|
||||
})
|
||||
expect(patch).toHaveBeenCalledWith('skills:1', {
|
||||
badges: {
|
||||
highlighted: { byUserId: 'users:1', at: 123 },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('resyncs denormalized badge even when table record already exists', async () => {
|
||||
const unique = vi.fn().mockResolvedValue({ _id: 'skillBadges:existing' })
|
||||
const query = vi.fn().mockReturnValue({
|
||||
withIndex: () => ({ unique }),
|
||||
})
|
||||
const insert = vi.fn()
|
||||
const get = vi.fn().mockResolvedValue({ _id: 'skills:1', badges: {} })
|
||||
const patch = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
query,
|
||||
insert,
|
||||
get,
|
||||
patch,
|
||||
},
|
||||
} as never
|
||||
|
||||
const result = await (upsertSkillBadgeRecordInternal as { _handler: Function })._handler(ctx, {
|
||||
skillId: 'skills:1',
|
||||
kind: 'official',
|
||||
byUserId: 'users:2',
|
||||
at: 456,
|
||||
})
|
||||
|
||||
expect(result).toEqual({ inserted: false })
|
||||
expect(insert).not.toHaveBeenCalled()
|
||||
expect(patch).toHaveBeenCalledWith('skills:1', {
|
||||
badges: {
|
||||
official: { byUserId: 'users:2', at: 456 },
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('maintenance fingerprint backfill', () => {
|
||||
it('backfills fingerprint field and inserts index entry', async () => {
|
||||
const { hashSkillFiles } = await import('./lib/skills')
|
||||
|
||||
+119
-1
@@ -642,17 +642,32 @@ export const upsertSkillBadgeRecordInternal = internalMutation({
|
||||
at: v.number(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const syncDenormalizedBadge = async () => {
|
||||
const skill = await ctx.db.get(args.skillId)
|
||||
if (!skill) return
|
||||
await ctx.db.patch(args.skillId, {
|
||||
badges: {
|
||||
...(skill.badges as Record<string, unknown> | undefined),
|
||||
[args.kind]: { byUserId: args.byUserId, at: args.at },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const existing = await ctx.db
|
||||
.query('skillBadges')
|
||||
.withIndex('by_skill_kind', (q) => q.eq('skillId', args.skillId).eq('kind', args.kind))
|
||||
.unique()
|
||||
if (existing) return { inserted: false as const }
|
||||
if (existing) {
|
||||
await syncDenormalizedBadge()
|
||||
return { inserted: false as const }
|
||||
}
|
||||
await ctx.db.insert('skillBadges', {
|
||||
skillId: args.skillId,
|
||||
kind: args.kind,
|
||||
byUserId: args.byUserId,
|
||||
at: args.at,
|
||||
})
|
||||
await syncDenormalizedBadge()
|
||||
return { inserted: true as const }
|
||||
},
|
||||
})
|
||||
@@ -1411,6 +1426,109 @@ export const nominateEmptySkillSpammers: ReturnType<typeof action> = action({
|
||||
},
|
||||
})
|
||||
|
||||
// Backfill embeddingSkillMap from existing skillEmbeddings.
|
||||
// Run once after deploying the schema change:
|
||||
// npx convex run maintenance:backfillEmbeddingSkillMapInternal --prod
|
||||
export const backfillEmbeddingSkillMapInternal = internalMutation({
|
||||
args: {
|
||||
cursor: v.optional(v.string()),
|
||||
batchSize: v.optional(v.number()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const batchSize = clampInt(args.batchSize ?? 200, 10, 500)
|
||||
const { page, continueCursor, isDone } = await ctx.db
|
||||
.query('skillEmbeddings')
|
||||
.paginate({ cursor: args.cursor ?? null, numItems: batchSize })
|
||||
|
||||
let inserted = 0
|
||||
for (const embedding of page) {
|
||||
const existing = await ctx.db
|
||||
.query('embeddingSkillMap')
|
||||
.withIndex('by_embedding', (q) => q.eq('embeddingId', embedding._id))
|
||||
.unique()
|
||||
if (!existing) {
|
||||
await ctx.db.insert('embeddingSkillMap', {
|
||||
embeddingId: embedding._id,
|
||||
skillId: embedding.skillId,
|
||||
})
|
||||
inserted++
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDone) {
|
||||
await ctx.scheduler.runAfter(0, internal.maintenance.backfillEmbeddingSkillMapInternal, {
|
||||
cursor: continueCursor,
|
||||
batchSize: args.batchSize,
|
||||
})
|
||||
}
|
||||
|
||||
return { inserted, isDone, scanned: page.length }
|
||||
},
|
||||
})
|
||||
|
||||
// Sync skillBadges table → denormalized skill.badges field.
|
||||
// Run after deploying the badge-read removal to ensure all skills
|
||||
// have up-to-date badges on the skill doc itself.
|
||||
export const backfillDenormalizedBadgesInternal = internalMutation({
|
||||
args: {
|
||||
cursor: v.optional(v.string()),
|
||||
batchSize: v.optional(v.number()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const batchSize = clampInt(args.batchSize ?? 100, 10, 200)
|
||||
const { page, continueCursor, isDone } = await ctx.db
|
||||
.query('skills')
|
||||
.paginate({ cursor: args.cursor ?? null, numItems: batchSize })
|
||||
|
||||
let patched = 0
|
||||
for (const skill of page) {
|
||||
const records = await ctx.db
|
||||
.query('skillBadges')
|
||||
.withIndex('by_skill', (q) => q.eq('skillId', skill._id))
|
||||
.take(10)
|
||||
|
||||
// Build canonical badge map from the table
|
||||
const canonical: Record<string, { byUserId: Id<'users'>; at: number }> = {}
|
||||
for (const r of records) {
|
||||
canonical[r.kind] = { byUserId: r.byUserId, at: r.at }
|
||||
}
|
||||
|
||||
// Compare with existing denormalized badges (keys + values)
|
||||
const existing = (skill.badges ?? {}) as Record<
|
||||
string,
|
||||
{ byUserId?: Id<'users'>; at?: number } | undefined
|
||||
>
|
||||
const canonicalKeys = Object.keys(canonical)
|
||||
const existingKeys = Object.keys(existing).filter((k) => existing[k] !== undefined)
|
||||
const needsPatch =
|
||||
canonicalKeys.length !== existingKeys.length ||
|
||||
canonicalKeys.some((k) => {
|
||||
const current = existing[k]
|
||||
const next = canonical[k]
|
||||
return (
|
||||
!current ||
|
||||
current.byUserId !== next.byUserId ||
|
||||
current.at !== next.at
|
||||
)
|
||||
})
|
||||
|
||||
if (needsPatch) {
|
||||
await ctx.db.patch(skill._id, { badges: canonical })
|
||||
patched++
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDone) {
|
||||
await ctx.scheduler.runAfter(0, internal.maintenance.backfillDenormalizedBadgesInternal, {
|
||||
cursor: continueCursor,
|
||||
batchSize: args.batchSize,
|
||||
})
|
||||
}
|
||||
|
||||
return { patched, isDone, scanned: page.length }
|
||||
},
|
||||
})
|
||||
|
||||
function clampInt(value: number, min: number, max: number) {
|
||||
const rounded = Math.trunc(value)
|
||||
if (!Number.isFinite(rounded)) return min
|
||||
|
||||
@@ -310,6 +310,14 @@ const skillEmbeddings = defineTable({
|
||||
filterFields: ['visibility'],
|
||||
})
|
||||
|
||||
// Lightweight lookup: embeddingId → skillId (~100 bytes per doc).
|
||||
// Avoids reading full skillEmbeddings docs (~12KB each with vector)
|
||||
// during search hydration.
|
||||
const embeddingSkillMap = defineTable({
|
||||
embeddingId: v.id('skillEmbeddings'),
|
||||
skillId: v.id('skills'),
|
||||
}).index('by_embedding', ['embeddingId'])
|
||||
|
||||
const skillDailyStats = defineTable({
|
||||
skillId: v.id('skills'),
|
||||
day: v.number(),
|
||||
@@ -342,6 +350,12 @@ const skillStatBackfillState = defineTable({
|
||||
updatedAt: v.number(),
|
||||
}).index('by_key', ['key'])
|
||||
|
||||
const globalStats = defineTable({
|
||||
key: v.string(),
|
||||
activeSkillsCount: v.number(),
|
||||
updatedAt: v.number(),
|
||||
}).index('by_key', ['key'])
|
||||
|
||||
const skillStatEvents = defineTable({
|
||||
skillId: v.id('skills'),
|
||||
kind: v.union(
|
||||
@@ -570,10 +584,12 @@ export default defineSchema({
|
||||
skillBadges,
|
||||
soulVersionFingerprints,
|
||||
skillEmbeddings,
|
||||
embeddingSkillMap,
|
||||
soulEmbeddings,
|
||||
skillDailyStats,
|
||||
skillLeaderboards,
|
||||
skillStatBackfillState,
|
||||
globalStats,
|
||||
skillStatEvents,
|
||||
skillStatUpdateCursors,
|
||||
comments,
|
||||
|
||||
+16
-27
@@ -4,9 +4,8 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import { tokenize } from './lib/searchText'
|
||||
import { __test, hydrateResults, lexicalFallbackSkills, searchSkills } from './search'
|
||||
|
||||
const { generateEmbeddingMock, getSkillBadgeMapsMock } = vi.hoisted(() => ({
|
||||
const { generateEmbeddingMock } = vi.hoisted(() => ({
|
||||
generateEmbeddingMock: vi.fn(),
|
||||
getSkillBadgeMapsMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./lib/embeddings', () => ({
|
||||
@@ -14,7 +13,6 @@ vi.mock('./lib/embeddings', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('./lib/badges', () => ({
|
||||
getSkillBadgeMaps: getSkillBadgeMapsMock,
|
||||
isSkillHighlighted: (skill: { badges?: Record<string, unknown> }) =>
|
||||
Boolean(skill.badges?.highlighted),
|
||||
}))
|
||||
@@ -50,9 +48,8 @@ describe('search helpers', () => {
|
||||
]
|
||||
const runQuery = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce(fallback)
|
||||
.mockResolvedValueOnce([]) // hydrateResults
|
||||
.mockResolvedValueOnce(fallback) // lexicalFallbackSkills
|
||||
|
||||
const result = await searchSkillsHandler(
|
||||
{
|
||||
@@ -71,18 +68,15 @@ describe('search helpers', () => {
|
||||
})
|
||||
|
||||
it('applies highlightedOnly filtering in lexical fallback', async () => {
|
||||
const highlighted = makeSkillDoc({
|
||||
id: 'skills:hl',
|
||||
slug: 'orf-highlighted',
|
||||
displayName: 'ORF Highlighted',
|
||||
})
|
||||
const highlighted = {
|
||||
...makeSkillDoc({
|
||||
id: 'skills:hl',
|
||||
slug: 'orf-highlighted',
|
||||
displayName: 'ORF Highlighted',
|
||||
}),
|
||||
badges: { highlighted: { byUserId: 'users:mod', at: 1 } },
|
||||
}
|
||||
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({
|
||||
@@ -104,12 +98,6 @@ describe('search helpers', () => {
|
||||
moderationFlags: ['flagged.suspicious'],
|
||||
})
|
||||
const clean = makeSkillDoc({ id: 'skills:clean', slug: 'orf-clean', displayName: 'ORF Clean' })
|
||||
getSkillBadgeMapsMock.mockResolvedValueOnce(
|
||||
new Map([
|
||||
['skills:suspicious', {}],
|
||||
['skills:clean', {}],
|
||||
]),
|
||||
)
|
||||
|
||||
const result = await lexicalFallbackSkillsHandler(
|
||||
makeLexicalCtx({
|
||||
@@ -125,7 +113,6 @@ describe('search helpers', () => {
|
||||
|
||||
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: [],
|
||||
@@ -197,9 +184,8 @@ describe('search helpers', () => {
|
||||
|
||||
const runQuery = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(vectorEntries)
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce(fallbackEntries)
|
||||
.mockResolvedValueOnce(vectorEntries) // hydrateResults
|
||||
.mockResolvedValueOnce(fallbackEntries) // lexicalFallbackSkills
|
||||
|
||||
const result = await searchSkillsHandler(
|
||||
{
|
||||
@@ -237,6 +223,9 @@ describe('search helpers', () => {
|
||||
if (id === 'skillVersions:1') return { _id: 'skillVersions:1', version: '1.0.0' }
|
||||
return null
|
||||
}),
|
||||
query: vi.fn(() => ({
|
||||
withIndex: () => ({ unique: vi.fn().mockResolvedValue(null) }),
|
||||
})),
|
||||
},
|
||||
},
|
||||
{ embeddingIds: ['skillEmbeddings:1'], nonSuspiciousOnly: true },
|
||||
|
||||
+25
-59
@@ -3,7 +3,7 @@ import { internal } from './_generated/api'
|
||||
import type { Doc, Id } from './_generated/dataModel'
|
||||
import type { QueryCtx } from './_generated/server'
|
||||
import { action, internalQuery } from './_generated/server'
|
||||
import { getSkillBadgeMaps, isSkillHighlighted, type SkillBadgeMap } from './lib/badges'
|
||||
import { isSkillHighlighted } from './lib/badges'
|
||||
import { generateEmbedding } from './lib/embeddings'
|
||||
import { toPublicSkill, toPublicSoul, toPublicUser } from './lib/public'
|
||||
import { matchesExactTokens, tokenize } from './lib/searchText'
|
||||
@@ -40,7 +40,7 @@ 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
|
||||
const FALLBACK_SCAN_LIMIT = 500
|
||||
|
||||
function getNextCandidateLimit(current: number, max: number) {
|
||||
const next = Math.min(current * 2, max)
|
||||
@@ -149,21 +149,11 @@ export const searchSkills: ReturnType<typeof action> = action({
|
||||
results.map((result) => [result._id, result._score]),
|
||||
)
|
||||
|
||||
const badgeMapEntries = (await ctx.runQuery(internal.search.getSkillBadgeMapsInternal, {
|
||||
skillIds: hydrated.map((entry) => entry.skill._id),
|
||||
})) as Array<[Id<'skills'>, SkillBadgeMap]>
|
||||
const badgeMapBySkillId = new Map(badgeMapEntries)
|
||||
const hydratedWithBadges = hydrated.map((entry) => ({
|
||||
...entry,
|
||||
skill: {
|
||||
...entry.skill,
|
||||
badges: badgeMapBySkillId.get(entry.skill._id) ?? {},
|
||||
},
|
||||
}))
|
||||
|
||||
// Skills already have badges from their docs (via toPublicSkill).
|
||||
// No need for a separate badge table lookup.
|
||||
const filtered = args.highlightedOnly
|
||||
? hydratedWithBadges.filter((entry) => isSkillHighlighted(entry.skill))
|
||||
: hydratedWithBadges
|
||||
? hydrated.filter((entry) => isSkillHighlighted(entry.skill))
|
||||
: hydrated
|
||||
|
||||
exactMatches = filtered.filter((entry) =>
|
||||
matchesExactTokens(queryTokens, [
|
||||
@@ -215,14 +205,6 @@ export const searchSkills: ReturnType<typeof action> = action({
|
||||
},
|
||||
})
|
||||
|
||||
export const getBadgeMapsForSkills = internalQuery({
|
||||
args: { skillIds: v.array(v.id('skills')) },
|
||||
handler: async (ctx, args): Promise<Array<[Id<'skills'>, SkillBadgeMap]>> => {
|
||||
const badgeMap = await getSkillBadgeMaps(ctx, args.skillIds)
|
||||
return Array.from(badgeMap.entries())
|
||||
},
|
||||
})
|
||||
|
||||
export const hydrateResults = internalQuery({
|
||||
args: {
|
||||
embeddingIds: v.array(v.id('skillEmbeddings')),
|
||||
@@ -233,21 +215,26 @@ export const hydrateResults = internalQuery({
|
||||
|
||||
const entries: Array<SkillSearchEntry | null> = await Promise.all(
|
||||
args.embeddingIds.map(async (embeddingId) => {
|
||||
const embedding = await ctx.db.get(embeddingId)
|
||||
if (!embedding) return null
|
||||
const skill = await ctx.db.get(embedding.skillId)
|
||||
// Use lightweight lookup table (~100 bytes) instead of full embedding doc (~12KB).
|
||||
const lookup = await ctx.db
|
||||
.query('embeddingSkillMap')
|
||||
.withIndex('by_embedding', (q) => q.eq('embeddingId', embeddingId))
|
||||
.unique()
|
||||
// Fallback to full embedding doc for rows not yet backfilled.
|
||||
const skillId = lookup
|
||||
? lookup.skillId
|
||||
: await ctx.db.get(embeddingId).then((e) => e?.skillId)
|
||||
if (!skillId) return null
|
||||
const skill = await ctx.db.get(skillId)
|
||||
if (!skill || skill.softDeletedAt) return null
|
||||
if (args.nonSuspiciousOnly && isSkillSuspicious(skill)) return null
|
||||
const [version, ownerInfo] = await Promise.all([
|
||||
ctx.db.get(embedding.versionId),
|
||||
getOwnerInfo(skill.ownerUserId),
|
||||
])
|
||||
const ownerInfo = await getOwnerInfo(skill.ownerUserId)
|
||||
const publicSkill = toPublicSkill(skill)
|
||||
if (!publicSkill) return null
|
||||
return {
|
||||
embeddingId,
|
||||
skill: publicSkill,
|
||||
version,
|
||||
version: null as Doc<'skillVersions'> | null,
|
||||
ownerHandle: ownerInfo.handle,
|
||||
owner: ownerInfo.owner,
|
||||
}
|
||||
@@ -309,15 +296,12 @@ export const lexicalFallbackSkills = internalQuery({
|
||||
|
||||
const entries = await Promise.all(
|
||||
matched.map(async (skill) => {
|
||||
const [version, ownerInfo] = await Promise.all([
|
||||
skill.latestVersionId ? ctx.db.get(skill.latestVersionId) : Promise.resolve(null),
|
||||
getOwnerInfo(skill.ownerUserId),
|
||||
])
|
||||
const ownerInfo = await getOwnerInfo(skill.ownerUserId)
|
||||
const publicSkill = toPublicSkill(skill)
|
||||
if (!publicSkill) return null
|
||||
return {
|
||||
skill: publicSkill,
|
||||
version,
|
||||
version: null as Doc<'skillVersions'> | null,
|
||||
ownerHandle: ownerInfo.handle,
|
||||
owner: ownerInfo.owner,
|
||||
}
|
||||
@@ -326,21 +310,11 @@ export const lexicalFallbackSkills = internalQuery({
|
||||
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) ?? {},
|
||||
},
|
||||
}))
|
||||
|
||||
// Skills already have badges from their docs (via toPublicSkill).
|
||||
// No need for a separate badge table lookup.
|
||||
const filtered = args.highlightedOnly
|
||||
? withBadges.filter((entry) => isSkillHighlighted(entry.skill))
|
||||
: withBadges
|
||||
? validEntries.filter((entry) => isSkillHighlighted(entry.skill))
|
||||
: validEntries
|
||||
return filtered.slice(0, limit)
|
||||
},
|
||||
})
|
||||
@@ -440,14 +414,6 @@ export const hydrateSoulResults = internalQuery({
|
||||
},
|
||||
})
|
||||
|
||||
export const getSkillBadgeMapsInternal = internalQuery({
|
||||
args: { skillIds: v.array(v.id('skills')) },
|
||||
handler: async (ctx, args) => {
|
||||
const badgeMap = await getSkillBadgeMaps(ctx, args.skillIds)
|
||||
return Array.from(badgeMap.entries())
|
||||
},
|
||||
})
|
||||
|
||||
export const __test = {
|
||||
getNextCandidateLimit,
|
||||
matchesAllTokens,
|
||||
|
||||
+23
-60
@@ -3,14 +3,18 @@
|
||||
*
|
||||
* Instead of updating skill stats synchronously in the hot path (which can cause
|
||||
* contention when multiple users download/star/install the same skill), we insert
|
||||
* lightweight event records and process them in batches via a cron job.
|
||||
* lightweight event records and process them in batches via cron jobs.
|
||||
*
|
||||
* Flow:
|
||||
* 1. User action (download, star, install) → insertStatEvent() writes to skillStatEvents table
|
||||
* 2. Cron job runs every 5 minutes → processSkillStatEventsInternal() processes batches
|
||||
* 3. Events are aggregated per-skill to minimize database operations
|
||||
* 4. Stats are applied to skill documents and daily stats tables
|
||||
* 5. Events are marked as processed (kept forever for auditing)
|
||||
* Two processing paths run at different frequencies to balance freshness vs bandwidth:
|
||||
*
|
||||
* 1. **Daily stats (15-minute cron)** — `processSkillStatEventsAction`
|
||||
* Writes to skillDailyStats for trending/leaderboards. Uses a cursor in
|
||||
* skillStatUpdateCursors. Does NOT touch skill documents.
|
||||
*
|
||||
* 2. **Skill doc sync (6-hour cron)** — `processSkillStatEventsInternal`
|
||||
* Patches skill documents with accumulated stat deltas. Uses processedAt
|
||||
* field to track progress. Runs infrequently because patching skill docs
|
||||
* invalidates reactive queries for all subscribers (thundering herd).
|
||||
*/
|
||||
|
||||
import { v } from 'convex/values'
|
||||
@@ -175,7 +179,7 @@ function aggregateEvents(events: Doc<'skillStatEvents'>[]): AggregatedDeltas {
|
||||
/**
|
||||
* Process a batch of unprocessed stat events.
|
||||
*
|
||||
* Called by cron every 5 minutes. Processes up to batchSize events (default 100).
|
||||
* Called by the 6-hour cron to sync stats to skill docs. Processes up to batchSize events (default 500).
|
||||
* If the batch is full, schedules an immediate follow-up run to drain the queue.
|
||||
*
|
||||
* Processing steps:
|
||||
@@ -198,7 +202,7 @@ function aggregateEvents(events: Doc<'skillStatEvents'>[]): AggregatedDeltas {
|
||||
export const processSkillStatEventsInternal = internalMutation({
|
||||
args: { batchSize: v.optional(v.number()) },
|
||||
handler: async (ctx, args) => {
|
||||
const batchSize = args.batchSize ?? 100
|
||||
const batchSize = args.batchSize ?? 500
|
||||
const now = Date.now()
|
||||
|
||||
// Level 1: Fetch a batch of unprocessed events
|
||||
@@ -252,25 +256,13 @@ export const processSkillStatEventsInternal = internalMutation({
|
||||
installsAllTime: deltas.installsAllTime,
|
||||
installsCurrent: deltas.installsCurrent,
|
||||
})
|
||||
await ctx.db.patch(skill._id, {
|
||||
...patch,
|
||||
updatedAt: now,
|
||||
})
|
||||
// Don't update `updatedAt` — stat changes shouldn't move the
|
||||
// skill's position in the by_active_updated index.
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
}
|
||||
|
||||
// Update daily stats for trending/leaderboards
|
||||
// We use the ORIGINAL event timestamp (occurredAt) so that:
|
||||
// - A download at Mon 11:55 PM counts toward Monday's stats
|
||||
// - Even if the cron processes it on Tuesday
|
||||
//
|
||||
// Level 4: bumpDailySkillStats does its own coalescing - multiple
|
||||
// events on the same day will update the same daily record
|
||||
for (const occurredAt of deltas.downloadEvents) {
|
||||
await bumpDailySkillStats(ctx, { skillId, now: occurredAt, downloads: 1 })
|
||||
}
|
||||
for (const occurredAt of deltas.installNewEvents) {
|
||||
await bumpDailySkillStats(ctx, { skillId, now: occurredAt, installs: 1 })
|
||||
}
|
||||
// NOTE: Daily stats (skillDailyStats) are written by the 15-minute
|
||||
// action cron (processSkillStatEventsAction), not here.
|
||||
|
||||
// Mark all events for this skill as processed
|
||||
for (const event of skillEvents) {
|
||||
@@ -352,11 +344,11 @@ const skillDeltaValidator = v.object({
|
||||
})
|
||||
|
||||
/**
|
||||
* Apply aggregated stats to skills and update the cursor.
|
||||
* Write aggregated daily stats and advance the cursor.
|
||||
* This is a single atomic mutation that:
|
||||
* 1. Updates all affected skills with their aggregated deltas
|
||||
* 2. Updates daily stats for trending
|
||||
* 3. Advances the cursor to the new position
|
||||
* 1. Updates daily stats for trending/leaderboards (skillDailyStats)
|
||||
* 2. Advances the cursor to the new position
|
||||
* NOTE: Does NOT patch skill documents — that's handled by processSkillStatEventsInternal.
|
||||
*/
|
||||
export const applyAggregatedStatsAndUpdateCursor = internalMutation({
|
||||
args: {
|
||||
@@ -366,37 +358,8 @@ export const applyAggregatedStatsAndUpdateCursor = internalMutation({
|
||||
handler: async (ctx, args) => {
|
||||
const now = Date.now()
|
||||
|
||||
// Process each skill's aggregated deltas
|
||||
// Update daily stats for trending/leaderboards
|
||||
for (const delta of args.skillDeltas) {
|
||||
const skill = await ctx.db.get(delta.skillId)
|
||||
|
||||
// Skill was deleted - skip
|
||||
if (!skill) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Apply aggregated deltas to skill stats
|
||||
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,
|
||||
})
|
||||
await ctx.db.patch(skill._id, {
|
||||
...patch,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
|
||||
// Update daily stats for trending/leaderboards
|
||||
for (const occurredAt of delta.downloadEvents) {
|
||||
await bumpDailySkillStats(ctx, { skillId: delta.skillId, now: occurredAt, downloads: 1 })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { countPublicSkills } from './skills'
|
||||
|
||||
type WrappedHandler<TArgs, TResult> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<TResult>
|
||||
}
|
||||
|
||||
const countPublicSkillsHandler = (
|
||||
countPublicSkills as unknown as WrappedHandler<Record<string, never>, number>
|
||||
)._handler
|
||||
|
||||
function makeSkillsQuery(skills: Array<{ softDeletedAt?: number; moderationStatus?: string | null }>) {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_active_updated') throw new Error(`unexpected skills index ${name}`)
|
||||
return {
|
||||
collect: async () => skills,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('skills.countPublicSkills', () => {
|
||||
it('returns precomputed global stats count when available', async () => {
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === 'globalStats') {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => ({ _id: 'globalStats:1', activeSkillsCount: 123 }),
|
||||
}),
|
||||
}
|
||||
}
|
||||
if (table === 'skills') {
|
||||
return makeSkillsQuery([])
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`)
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await countPublicSkillsHandler(ctx, {})
|
||||
expect(result).toBe(123)
|
||||
})
|
||||
|
||||
it('falls back to live count when global stats row is missing', async () => {
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === 'globalStats') {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => null,
|
||||
}),
|
||||
}
|
||||
}
|
||||
if (table === 'skills') {
|
||||
return makeSkillsQuery([
|
||||
{ softDeletedAt: undefined, moderationStatus: 'active' },
|
||||
{ softDeletedAt: undefined, moderationStatus: 'hidden' },
|
||||
{ softDeletedAt: undefined, moderationStatus: 'active' },
|
||||
])
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`)
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await countPublicSkillsHandler(ctx, {})
|
||||
expect(result).toBe(2)
|
||||
})
|
||||
|
||||
it('falls back to live count when globalStats table is unavailable', async () => {
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === 'globalStats') {
|
||||
throw new Error('unexpected table globalStats')
|
||||
}
|
||||
if (table === 'skills') {
|
||||
return makeSkillsQuery([
|
||||
{ softDeletedAt: undefined, moderationStatus: 'active' },
|
||||
{ softDeletedAt: undefined, moderationStatus: 'active' },
|
||||
])
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`)
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await countPublicSkillsHandler(ctx, {})
|
||||
expect(result).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,317 @@
|
||||
/* @vitest-environment node */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { getSkillBadgeMapMock, getSkillBadgeMapsMock, isSkillHighlightedMock } = vi.hoisted(() => ({
|
||||
getSkillBadgeMapMock: vi.fn(),
|
||||
getSkillBadgeMapsMock: vi.fn(),
|
||||
isSkillHighlightedMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./lib/badges', () => ({
|
||||
getSkillBadgeMap: getSkillBadgeMapMock,
|
||||
getSkillBadgeMaps: getSkillBadgeMapsMock,
|
||||
isSkillHighlighted: isSkillHighlightedMock,
|
||||
}))
|
||||
|
||||
import { listPublicPageV2 } from './skills'
|
||||
|
||||
type ListArgs = {
|
||||
paginationOpts: { cursor: string | null; numItems: number; id?: number }
|
||||
sort?: 'newest' | 'updated' | 'downloads' | 'installs' | 'stars' | 'name'
|
||||
dir?: 'asc' | 'desc'
|
||||
highlightedOnly?: boolean
|
||||
nonSuspiciousOnly?: boolean
|
||||
}
|
||||
|
||||
type ListResult = {
|
||||
page: Array<{ skill: { slug: string } }>
|
||||
continueCursor: string | null
|
||||
isDone: boolean
|
||||
}
|
||||
|
||||
type WrappedHandler<TArgs, TResult> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<TResult>
|
||||
}
|
||||
|
||||
const listPublicPageV2Handler = (listPublicPageV2 as unknown as WrappedHandler<ListArgs, ListResult>)
|
||||
._handler
|
||||
|
||||
describe('skills.listPublicPageV2', () => {
|
||||
beforeEach(() => {
|
||||
getSkillBadgeMapMock.mockReset()
|
||||
getSkillBadgeMapsMock.mockReset()
|
||||
getSkillBadgeMapsMock.mockResolvedValue(new Map())
|
||||
isSkillHighlightedMock.mockReset()
|
||||
isSkillHighlightedMock.mockImplementation((skill: { slug?: string }) =>
|
||||
Boolean(skill.slug?.startsWith('hl-')),
|
||||
)
|
||||
})
|
||||
|
||||
it('applies highlightedOnly and nonSuspiciousOnly together', async () => {
|
||||
const highlightedClean = makeSkill('skills:hl-clean', 'hl-clean', 'users:1', 'skillVersions:1')
|
||||
const plainClean = makeSkill('skills:plain', 'plain', 'users:2', 'skillVersions:2')
|
||||
const highlightedSuspicious = makeSkill(
|
||||
'skills:hl-suspicious',
|
||||
'hl-suspicious',
|
||||
'users:3',
|
||||
'skillVersions:3',
|
||||
['flagged.suspicious'],
|
||||
)
|
||||
|
||||
const paginateMock = vi.fn().mockResolvedValue({
|
||||
page: [highlightedClean, plainClean, highlightedSuspicious],
|
||||
continueCursor: 'next-cursor',
|
||||
isDone: false,
|
||||
pageStatus: null,
|
||||
splitCursor: null,
|
||||
})
|
||||
const orderMock = vi.fn(() => ({ paginate: paginateMock }))
|
||||
const eqMock = vi.fn(() => ({}))
|
||||
const withIndexMock = vi.fn((_index: string, builder: (q: { eq: typeof eqMock }) => unknown) => {
|
||||
builder({ eq: eqMock })
|
||||
return { order: orderMock }
|
||||
})
|
||||
const getMock = vi.fn(async (id: string) => {
|
||||
if (id.startsWith('users:')) return makeUser(id)
|
||||
if (id.startsWith('skillVersions:')) return makeVersion(id)
|
||||
return null
|
||||
})
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table !== 'skills') throw new Error(`unexpected table ${table}`)
|
||||
return { withIndex: withIndexMock }
|
||||
}),
|
||||
get: getMock,
|
||||
},
|
||||
}
|
||||
|
||||
const result = await listPublicPageV2Handler(ctx, {
|
||||
paginationOpts: { cursor: null, numItems: 25 },
|
||||
sort: 'downloads',
|
||||
dir: 'desc',
|
||||
highlightedOnly: true,
|
||||
nonSuspiciousOnly: true,
|
||||
})
|
||||
|
||||
expect(result.page).toHaveLength(1)
|
||||
expect(result.page[0]?.skill.slug).toBe('hl-clean')
|
||||
expect(result.continueCursor).toBe('next-cursor')
|
||||
expect(result.isDone).toBe(false)
|
||||
expect(withIndexMock).toHaveBeenCalledWith('by_active_stats_downloads', expect.any(Function))
|
||||
expect(orderMock).toHaveBeenCalledWith('desc')
|
||||
expect(paginateMock).toHaveBeenCalledWith({ cursor: null, numItems: 25 })
|
||||
expect(eqMock).toHaveBeenCalledWith('softDeletedAt', undefined)
|
||||
})
|
||||
|
||||
it('preserves pagination cursor when filtering removes the whole page', async () => {
|
||||
const plain = makeSkill('skills:plain', 'plain', 'users:1', 'skillVersions:1')
|
||||
const paginateMock = vi.fn().mockResolvedValue({
|
||||
page: [plain],
|
||||
continueCursor: 'next-cursor',
|
||||
isDone: false,
|
||||
pageStatus: null,
|
||||
splitCursor: null,
|
||||
})
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn(() => ({
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({ paginate: paginateMock })),
|
||||
})),
|
||||
})),
|
||||
get: vi.fn(),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await listPublicPageV2Handler(ctx, {
|
||||
paginationOpts: { cursor: null, numItems: 25 },
|
||||
sort: 'downloads',
|
||||
dir: 'desc',
|
||||
highlightedOnly: true,
|
||||
nonSuspiciousOnly: false,
|
||||
})
|
||||
|
||||
expect(result.page).toEqual([])
|
||||
expect(result.continueCursor).toBe('next-cursor')
|
||||
expect(result.isDone).toBe(false)
|
||||
})
|
||||
|
||||
it('restarts pagination from first page when cursor is stale', async () => {
|
||||
const plain = makeSkill('skills:plain', 'plain', 'users:1', 'skillVersions:1')
|
||||
const paginateMock = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('Failed to parse cursor'))
|
||||
.mockResolvedValueOnce({
|
||||
page: [plain],
|
||||
continueCursor: 'next-cursor',
|
||||
isDone: false,
|
||||
pageStatus: null,
|
||||
splitCursor: null,
|
||||
})
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn(() => ({
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({ paginate: paginateMock })),
|
||||
})),
|
||||
})),
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id.startsWith('users:')) return makeUser(id)
|
||||
if (id.startsWith('skillVersions:')) return makeVersion(id)
|
||||
return null
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await listPublicPageV2Handler(ctx, {
|
||||
paginationOpts: { cursor: 'stale-cursor', numItems: 25, id: 123456 },
|
||||
sort: 'downloads',
|
||||
dir: 'desc',
|
||||
highlightedOnly: false,
|
||||
nonSuspiciousOnly: false,
|
||||
})
|
||||
|
||||
expect(result.page).toHaveLength(1)
|
||||
expect(result.page[0]?.skill.slug).toBe('plain')
|
||||
expect(result.continueCursor).toBe('next-cursor')
|
||||
expect(result.isDone).toBe(false)
|
||||
expect(paginateMock).toHaveBeenNthCalledWith(1, { cursor: 'stale-cursor', numItems: 25 })
|
||||
expect(paginateMock).toHaveBeenNthCalledWith(2, { cursor: null, numItems: 25 })
|
||||
expect(paginateMock).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: expect.any(Number),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('drops pagination id from client options on first-page queries', async () => {
|
||||
const plain = makeSkill('skills:plain', 'plain', 'users:1', 'skillVersions:1')
|
||||
const paginateMock = vi.fn().mockResolvedValue({
|
||||
page: [plain],
|
||||
continueCursor: 'next-cursor',
|
||||
isDone: false,
|
||||
pageStatus: null,
|
||||
splitCursor: null,
|
||||
})
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn(() => ({
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({ paginate: paginateMock })),
|
||||
})),
|
||||
})),
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id.startsWith('users:')) return makeUser(id)
|
||||
if (id.startsWith('skillVersions:')) return makeVersion(id)
|
||||
return null
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await listPublicPageV2Handler(ctx, {
|
||||
paginationOpts: { cursor: null, numItems: 25, id: 999_999_999 },
|
||||
sort: 'downloads',
|
||||
dir: 'desc',
|
||||
highlightedOnly: false,
|
||||
nonSuspiciousOnly: false,
|
||||
})
|
||||
|
||||
expect(result.page).toHaveLength(1)
|
||||
expect(paginateMock).toHaveBeenCalledTimes(1)
|
||||
expect(paginateMock).toHaveBeenCalledWith({ cursor: null, numItems: 25 })
|
||||
expect(paginateMock).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: expect.any(Number),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not swallow non-cursor paginate errors', async () => {
|
||||
const paginateMock = vi.fn().mockRejectedValue(new Error('database unavailable'))
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn(() => ({
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({ paginate: paginateMock })),
|
||||
})),
|
||||
})),
|
||||
get: vi.fn(),
|
||||
},
|
||||
}
|
||||
|
||||
await expect(
|
||||
listPublicPageV2Handler(ctx, {
|
||||
paginationOpts: { cursor: 'stale-cursor', numItems: 25, id: 999_999_999 },
|
||||
sort: 'downloads',
|
||||
dir: 'desc',
|
||||
highlightedOnly: false,
|
||||
nonSuspiciousOnly: false,
|
||||
}),
|
||||
).rejects.toThrow('database unavailable')
|
||||
|
||||
expect(paginateMock).toHaveBeenCalledTimes(1)
|
||||
expect(paginateMock).toHaveBeenCalledWith({ cursor: 'stale-cursor', numItems: 25 })
|
||||
})
|
||||
})
|
||||
|
||||
function makeSkill(
|
||||
id: string,
|
||||
slug: string,
|
||||
ownerUserId: string,
|
||||
latestVersionId: string,
|
||||
moderationFlags?: string[],
|
||||
) {
|
||||
return {
|
||||
_id: id,
|
||||
_creationTime: 1,
|
||||
slug,
|
||||
displayName: slug,
|
||||
summary: `${slug} summary`,
|
||||
ownerUserId,
|
||||
canonicalSkillId: undefined,
|
||||
forkOf: undefined,
|
||||
latestVersionId,
|
||||
tags: {},
|
||||
badges: {},
|
||||
stats: {
|
||||
downloads: 0,
|
||||
stars: 0,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 0,
|
||||
versions: 1,
|
||||
comments: 0,
|
||||
},
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
softDeletedAt: undefined,
|
||||
moderationStatus: 'active',
|
||||
moderationFlags,
|
||||
}
|
||||
}
|
||||
|
||||
function makeUser(id: string) {
|
||||
return {
|
||||
_id: id,
|
||||
_creationTime: 1,
|
||||
handle: 'owner',
|
||||
name: 'Owner',
|
||||
displayName: 'Owner',
|
||||
image: null,
|
||||
bio: null,
|
||||
deletedAt: undefined,
|
||||
deactivatedAt: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function makeVersion(id: string) {
|
||||
return {
|
||||
_id: id,
|
||||
_creationTime: 1,
|
||||
version: '1.0.0',
|
||||
createdAt: 1,
|
||||
changelog: '',
|
||||
changelogSource: 'user',
|
||||
parsed: {},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { getPendingScanSkillsInternal } from './skills'
|
||||
|
||||
type PendingScanResult = Array<{
|
||||
skillId: string
|
||||
versionId: string | null
|
||||
sha256hash: string | null
|
||||
checkCount: number
|
||||
}>
|
||||
|
||||
type WrappedHandler<TArgs, TResult> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<TResult>
|
||||
}
|
||||
|
||||
const getPendingScanSkillsHandler = (
|
||||
getPendingScanSkillsInternal as unknown as WrappedHandler<Record<string, unknown>, PendingScanResult>
|
||||
)._handler
|
||||
|
||||
describe('skills.getPendingScanSkillsInternal', () => {
|
||||
it('includes unresolved VT records from the oldest slice and skips finalized ones', async () => {
|
||||
const recentSkills = [
|
||||
makeSkill('skills:recent-clean', 'skillVersions:recent-clean', 'scanner.llm.clean'),
|
||||
makeSkill('skills:recent-malicious', 'skillVersions:recent-malicious', 'scanner.vt.pending'),
|
||||
]
|
||||
const oldestSkills = [
|
||||
makeSkill('skills:old-pending', 'skillVersions:old-pending', 'scanner.vt.pending'),
|
||||
makeSkill('skills:old-stale', 'skillVersions:old-stale', 'scanner.llm.clean'),
|
||||
makeSkill('skills:old-no-hash', 'skillVersions:old-no-hash', 'scanner.vt.pending'),
|
||||
]
|
||||
|
||||
const versions = new Map<string, unknown>([
|
||||
[
|
||||
'skillVersions:recent-clean',
|
||||
{ _id: 'skillVersions:recent-clean', sha256hash: 'a'.repeat(64), vtAnalysis: { status: 'clean' } },
|
||||
],
|
||||
[
|
||||
'skillVersions:recent-malicious',
|
||||
{
|
||||
_id: 'skillVersions:recent-malicious',
|
||||
sha256hash: 'b'.repeat(64),
|
||||
vtAnalysis: { status: 'malicious' },
|
||||
},
|
||||
],
|
||||
[
|
||||
'skillVersions:old-pending',
|
||||
{ _id: 'skillVersions:old-pending', sha256hash: 'c'.repeat(64), vtAnalysis: { status: 'pending' } },
|
||||
],
|
||||
[
|
||||
'skillVersions:old-stale',
|
||||
{ _id: 'skillVersions:old-stale', sha256hash: 'd'.repeat(64), vtAnalysis: { status: 'stale' } },
|
||||
],
|
||||
['skillVersions:old-no-hash', { _id: 'skillVersions:old-no-hash' }],
|
||||
])
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table !== 'skills') throw new Error(`unexpected table ${table}`)
|
||||
return {
|
||||
withIndex: (
|
||||
indexName: string,
|
||||
builder: (q: { eq: (field: string, value: unknown) => unknown }) => unknown,
|
||||
) => {
|
||||
builder({ eq: () => ({}) })
|
||||
if (indexName === 'by_active_updated') {
|
||||
return {
|
||||
order: () => ({
|
||||
take: async () => recentSkills,
|
||||
}),
|
||||
}
|
||||
}
|
||||
if (indexName === 'by_active_created') {
|
||||
return {
|
||||
order: () => ({
|
||||
take: async () => oldestSkills,
|
||||
}),
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected index ${indexName}`)
|
||||
},
|
||||
}
|
||||
}),
|
||||
get: vi.fn(async (id: string) => versions.get(id) ?? null),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await getPendingScanSkillsHandler(ctx, {
|
||||
limit: 25,
|
||||
skipRecentMinutes: 0,
|
||||
})
|
||||
|
||||
const ids = new Set(result.map((entry) => entry.skillId))
|
||||
expect(ids.has('skills:old-pending')).toBe(true)
|
||||
expect(ids.has('skills:old-stale')).toBe(true)
|
||||
expect(ids.has('skills:recent-clean')).toBe(false)
|
||||
expect(ids.has('skills:recent-malicious')).toBe(false)
|
||||
expect(ids.has('skills:old-no-hash')).toBe(false)
|
||||
})
|
||||
|
||||
it('exhaustive mode ignores recent-check suppression for manual backfills', async () => {
|
||||
const now = Date.now()
|
||||
const allSkills = [
|
||||
makeSkill('skills:recently-checked', 'skillVersions:recently-checked', 'scanner.vt.pending', now),
|
||||
]
|
||||
const versions = new Map<string, unknown>([
|
||||
[
|
||||
'skillVersions:recently-checked',
|
||||
{ _id: 'skillVersions:recently-checked', sha256hash: 'e'.repeat(64) },
|
||||
],
|
||||
])
|
||||
|
||||
const withIndex = vi.fn(
|
||||
(
|
||||
indexName: string,
|
||||
builder: (q: { eq: (field: string, value: unknown) => unknown }) => unknown,
|
||||
) => {
|
||||
builder({ eq: () => ({}) })
|
||||
if (indexName !== 'by_active_updated') throw new Error(`unexpected index ${indexName}`)
|
||||
return {
|
||||
collect: async () => allSkills,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table !== 'skills') throw new Error(`unexpected table ${table}`)
|
||||
return { withIndex }
|
||||
}),
|
||||
get: vi.fn(async (id: string) => versions.get(id) ?? null),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await getPendingScanSkillsHandler(ctx, {
|
||||
limit: 25,
|
||||
skipRecentMinutes: 60,
|
||||
exhaustive: true,
|
||||
})
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]?.skillId).toBe('skills:recently-checked')
|
||||
})
|
||||
|
||||
it('does not clamp exhaustive mode to 100 records', async () => {
|
||||
const allSkills = Array.from({ length: 150 }, (_, i) =>
|
||||
makeSkill(`skills:bulk-${i}`, `skillVersions:bulk-${i}`, 'scanner.vt.pending'),
|
||||
)
|
||||
const versions = new Map<string, unknown>(
|
||||
allSkills.map((skill) => {
|
||||
const versionId = skill.latestVersionId as string
|
||||
return [versionId, { _id: versionId, sha256hash: `${String(versionId).slice(-8)}${'f'.repeat(56)}` }]
|
||||
}),
|
||||
)
|
||||
|
||||
const withIndex = vi.fn(
|
||||
(
|
||||
indexName: string,
|
||||
builder: (q: { eq: (field: string, value: unknown) => unknown }) => unknown,
|
||||
) => {
|
||||
builder({ eq: () => ({}) })
|
||||
if (indexName !== 'by_active_updated') throw new Error(`unexpected index ${indexName}`)
|
||||
return {
|
||||
collect: async () => allSkills,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
if (table !== 'skills') throw new Error(`unexpected table ${table}`)
|
||||
return { withIndex }
|
||||
}),
|
||||
get: vi.fn(async (id: string) => versions.get(id) ?? null),
|
||||
},
|
||||
}
|
||||
|
||||
const result = await getPendingScanSkillsHandler(ctx, {
|
||||
limit: 10000,
|
||||
exhaustive: true,
|
||||
skipRecentMinutes: 0,
|
||||
})
|
||||
|
||||
expect(result).toHaveLength(150)
|
||||
})
|
||||
})
|
||||
|
||||
function makeSkill(
|
||||
id: string,
|
||||
versionId: string,
|
||||
moderationReason: string,
|
||||
scanLastCheckedAt?: number,
|
||||
) {
|
||||
return {
|
||||
_id: id,
|
||||
moderationStatus: 'active',
|
||||
moderationReason,
|
||||
latestVersionId: versionId,
|
||||
scanLastCheckedAt,
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,21 @@ const clearOwnerSuspiciousFlagsHandler = (
|
||||
clearOwnerSuspiciousFlagsInternal as unknown as WrappedHandler<Record<string, unknown>>
|
||||
)._handler
|
||||
|
||||
function buildGlobalStatsQuery(table: string) {
|
||||
if (table !== 'globalStats') return null
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_key') throw new Error(`unexpected globalStats index ${name}`)
|
||||
return {
|
||||
unique: async () => ({
|
||||
_id: 'globalStats:1',
|
||||
activeSkillsCount: 100,
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createPublishArgs(overrides?: Partial<Record<string, unknown>>) {
|
||||
return {
|
||||
userId: 'users:owner',
|
||||
@@ -67,6 +82,8 @@ describe('skills anti-spam guards', () => {
|
||||
deletedAt: undefined,
|
||||
})),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table)
|
||||
if (globalStatsQuery) return globalStatsQuery
|
||||
if (table === 'skills') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
@@ -127,6 +144,8 @@ describe('skills anti-spam guards', () => {
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table)
|
||||
if (globalStatsQuery) return globalStatsQuery
|
||||
if (table === 'skillVersions') {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
@@ -197,6 +216,8 @@ describe('skills anti-spam guards', () => {
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table)
|
||||
if (globalStatsQuery) return globalStatsQuery
|
||||
if (table === 'skillVersions') {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
@@ -265,6 +286,8 @@ describe('skills anti-spam guards', () => {
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table)
|
||||
if (globalStatsQuery) return globalStatsQuery
|
||||
if (table === 'skillVersions') {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
@@ -324,6 +347,8 @@ describe('skills anti-spam guards', () => {
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table)
|
||||
if (globalStatsQuery) return globalStatsQuery
|
||||
if (table === 'skills') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { reclaimSlugInternal } from './skills'
|
||||
|
||||
type WrappedHandler<TArgs> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<unknown>
|
||||
}
|
||||
|
||||
const reclaimSlugInternalHandler = (
|
||||
reclaimSlugInternal as unknown as WrappedHandler<Record<string, unknown>>
|
||||
)._handler
|
||||
|
||||
describe('skills reclaim ownership transfer', () => {
|
||||
it('transfers ownership in-place when transferRootSlugOnly is true', async () => {
|
||||
const now = Date.now()
|
||||
const patch = vi.fn(async () => {})
|
||||
const insert = vi.fn(async () => {})
|
||||
const runAfter = vi.fn(async () => {})
|
||||
|
||||
const existingSkill = {
|
||||
_id: 'skills:1',
|
||||
slug: 'capability-evolver',
|
||||
ownerUserId: 'users:old',
|
||||
}
|
||||
const activeReservation = {
|
||||
_id: 'reservedSlugs:1',
|
||||
slug: 'capability-evolver',
|
||||
originalOwnerUserId: 'users:old',
|
||||
deletedAt: now - 1_000,
|
||||
expiresAt: now + 10_000,
|
||||
}
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === 'users:admin') return { _id: 'users:admin', role: 'admin' }
|
||||
if (id === 'users:new') return { _id: 'users:new', role: 'user' }
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === 'skills') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_slug') throw new Error(`unexpected skills index ${name}`)
|
||||
return { unique: async () => existingSkill }
|
||||
},
|
||||
}
|
||||
}
|
||||
if (table === 'skillEmbeddings') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_skill') throw new Error(`unexpected embeddings index ${name}`)
|
||||
return {
|
||||
collect: async () => [{ _id: 'skillEmbeddings:1', skillId: 'skills:1', ownerId: 'users:old' }],
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
if (table === 'reservedSlugs') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_slug_active_deletedAt') {
|
||||
throw new Error(`unexpected reservedSlugs index ${name}`)
|
||||
}
|
||||
return {
|
||||
order: () => ({
|
||||
take: async () => [activeReservation],
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`)
|
||||
}),
|
||||
patch,
|
||||
insert,
|
||||
}
|
||||
|
||||
const result = (await reclaimSlugInternalHandler(
|
||||
{ db, scheduler: { runAfter } } as never,
|
||||
{
|
||||
actorUserId: 'users:admin',
|
||||
slug: 'Capability-Evolver',
|
||||
rightfulOwnerUserId: 'users:new',
|
||||
transferRootSlugOnly: true,
|
||||
} as never,
|
||||
)) as { ok: boolean; action: string }
|
||||
|
||||
expect(result).toEqual({ ok: true, action: 'ownership_transferred' })
|
||||
expect(runAfter).not.toHaveBeenCalled()
|
||||
expect(patch).toHaveBeenCalledWith(
|
||||
'skills:1',
|
||||
expect.objectContaining({
|
||||
ownerUserId: 'users:new',
|
||||
}),
|
||||
)
|
||||
expect(patch).toHaveBeenCalledWith(
|
||||
'skillEmbeddings:1',
|
||||
expect.objectContaining({
|
||||
ownerId: 'users:new',
|
||||
}),
|
||||
)
|
||||
expect(patch).toHaveBeenCalledWith(
|
||||
'reservedSlugs:1',
|
||||
expect.objectContaining({
|
||||
releasedAt: expect.any(Number),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns missing without reserving when transferRootSlugOnly is true and slug does not exist', async () => {
|
||||
const insert = vi.fn(async () => {})
|
||||
const patch = vi.fn(async () => {})
|
||||
const runAfter = vi.fn(async () => {})
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === 'users:admin') return { _id: 'users:admin', role: 'admin' }
|
||||
if (id === 'users:new') return { _id: 'users:new', role: 'user' }
|
||||
return null
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === 'skills') {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== 'by_slug') throw new Error(`unexpected skills index ${name}`)
|
||||
return { unique: async () => null }
|
||||
},
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`)
|
||||
}),
|
||||
patch,
|
||||
insert,
|
||||
}
|
||||
|
||||
const result = (await reclaimSlugInternalHandler(
|
||||
{ db, scheduler: { runAfter } } as never,
|
||||
{
|
||||
actorUserId: 'users:admin',
|
||||
slug: 'missing-slug',
|
||||
rightfulOwnerUserId: 'users:new',
|
||||
transferRootSlugOnly: true,
|
||||
} as never,
|
||||
)) as { ok: boolean; action: string }
|
||||
|
||||
expect(result).toEqual({ ok: true, action: 'missing' })
|
||||
expect(runAfter).not.toHaveBeenCalled()
|
||||
expect(patch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
+318
-67
@@ -17,13 +17,18 @@ import {
|
||||
getSkillBadgeMap,
|
||||
getSkillBadgeMaps,
|
||||
isSkillHighlighted,
|
||||
type SkillBadgeMap,
|
||||
} from './lib/badges'
|
||||
import { generateChangelogPreview as buildChangelogPreview } from './lib/changelog'
|
||||
import {
|
||||
canHealSkillOwnershipByGitHubProviderAccountId,
|
||||
getGitHubProviderAccountId,
|
||||
} from './lib/githubIdentity'
|
||||
import {
|
||||
adjustGlobalPublicSkillsCount,
|
||||
countPublicSkillsForGlobalStats,
|
||||
getPublicSkillVisibilityDelta,
|
||||
readGlobalPublicSkillsCount,
|
||||
} from './lib/globalStats'
|
||||
import { buildTrendingLeaderboard } from './lib/leaderboards'
|
||||
import { deriveModerationFlags } from './lib/moderation'
|
||||
import { toPublicSkill, toPublicUser } from './lib/public'
|
||||
@@ -32,6 +37,7 @@ import { scheduleNextBatchIfNeeded } from './lib/batching'
|
||||
import {
|
||||
enforceReservedSlugCooldownForNewSkill,
|
||||
getLatestActiveReservedSlug,
|
||||
listActiveReservedSlugsForSlug,
|
||||
reserveSlugForHardDeleteFinalize,
|
||||
upsertReservedSlugForRightfulOwner,
|
||||
} from './lib/reservedSlugs'
|
||||
@@ -54,7 +60,6 @@ const MAX_LIST_LIMIT = 50
|
||||
const MAX_PUBLIC_LIST_LIMIT = 200
|
||||
const MAX_LIST_BULK_LIMIT = 200
|
||||
const MAX_LIST_TAKE = 1000
|
||||
const MAX_BADGE_LOOKUP_SKILLS = 200
|
||||
const HARD_DELETE_BATCH_SIZE = 100
|
||||
const HARD_DELETE_VERSION_BATCH_SIZE = 10
|
||||
const HARD_DELETE_LEADERBOARD_BATCH_SIZE = 25
|
||||
@@ -117,6 +122,16 @@ function normalizeScannerSuspiciousReason(reason: string | undefined) {
|
||||
return `${reason.slice(0, -'.suspicious'.length)}.clean`
|
||||
}
|
||||
|
||||
async function adjustGlobalPublicCountForSkillChange(
|
||||
ctx: MutationCtx,
|
||||
previousSkill: Doc<'skills'> | null | undefined,
|
||||
nextSkill: Doc<'skills'> | null | undefined,
|
||||
) {
|
||||
const delta = getPublicSkillVisibilityDelta(previousSkill, nextSkill)
|
||||
if (delta === 0) return
|
||||
await adjustGlobalPublicSkillsCount(ctx, delta)
|
||||
}
|
||||
|
||||
async function getOwnerTrustSignals(
|
||||
ctx: QueryCtx | MutationCtx,
|
||||
owner: Doc<'users'>,
|
||||
@@ -219,7 +234,9 @@ async function hardDeleteSkillStep(
|
||||
if (Object.keys(patch).length) {
|
||||
patch.lastReviewedAt = now
|
||||
patch.updatedAt = now
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
}
|
||||
|
||||
switch (phase) {
|
||||
@@ -491,18 +508,16 @@ type ManagementSkillEntry = {
|
||||
|
||||
type BadgeKind = Doc<'skillBadges'>['kind']
|
||||
|
||||
async function buildPublicSkillEntries(ctx: QueryCtx, skills: Doc<'skills'>[]) {
|
||||
async function buildPublicSkillEntries(
|
||||
ctx: QueryCtx,
|
||||
skills: Doc<'skills'>[],
|
||||
opts?: { includeVersion?: boolean },
|
||||
) {
|
||||
const includeVersion = opts?.includeVersion ?? true
|
||||
const ownerInfoCache = new Map<
|
||||
Id<'users'>,
|
||||
Promise<{ ownerHandle: string | null; owner: ReturnType<typeof toPublicUser> | null }>
|
||||
>()
|
||||
const badgeMapBySkillId: Map<Id<'skills'>, SkillBadgeMap> = skills.length <=
|
||||
MAX_BADGE_LOOKUP_SKILLS
|
||||
? await getSkillBadgeMaps(
|
||||
ctx,
|
||||
skills.map((skill) => skill._id),
|
||||
)
|
||||
: new Map()
|
||||
|
||||
const getOwnerInfo = (ownerUserId: Id<'users'>) => {
|
||||
const cached = ownerInfoCache.get(ownerUserId)
|
||||
@@ -523,11 +538,10 @@ async function buildPublicSkillEntries(ctx: QueryCtx, skills: Doc<'skills'>[]) {
|
||||
const entries = await Promise.all(
|
||||
skills.map(async (skill) => {
|
||||
const [latestVersionDoc, ownerInfo] = await Promise.all([
|
||||
skill.latestVersionId ? ctx.db.get(skill.latestVersionId) : null,
|
||||
includeVersion && skill.latestVersionId ? ctx.db.get(skill.latestVersionId) : null,
|
||||
getOwnerInfo(skill.ownerUserId),
|
||||
])
|
||||
const badges = badgeMapBySkillId.get(skill._id) ?? {}
|
||||
const publicSkill = toPublicSkill({ ...skill, badges })
|
||||
const publicSkill = toPublicSkill(skill)
|
||||
if (!publicSkill) return null
|
||||
const latestVersion = toPublicSkillListVersion(latestVersionDoc)
|
||||
return {
|
||||
@@ -626,14 +640,24 @@ async function upsertSkillBadge(
|
||||
.unique()
|
||||
if (existing) {
|
||||
await ctx.db.patch(existing._id, { byUserId: userId, at })
|
||||
return existing._id
|
||||
} else {
|
||||
await ctx.db.insert('skillBadges', {
|
||||
skillId,
|
||||
kind,
|
||||
byUserId: userId,
|
||||
at,
|
||||
})
|
||||
}
|
||||
// Keep denormalized badges field on skill doc in sync
|
||||
const skill = await ctx.db.get(skillId)
|
||||
if (skill) {
|
||||
await ctx.db.patch(skillId, {
|
||||
badges: {
|
||||
...(skill.badges as Record<string, unknown> | undefined),
|
||||
[kind]: { byUserId: userId, at },
|
||||
},
|
||||
})
|
||||
}
|
||||
return ctx.db.insert('skillBadges', {
|
||||
skillId,
|
||||
kind,
|
||||
byUserId: userId,
|
||||
at,
|
||||
})
|
||||
}
|
||||
|
||||
async function removeSkillBadge(ctx: MutationCtx, skillId: Id<'skills'>, kind: BadgeKind) {
|
||||
@@ -644,6 +668,12 @@ async function removeSkillBadge(ctx: MutationCtx, skillId: Id<'skills'>, kind: B
|
||||
if (existing) {
|
||||
await ctx.db.delete(existing._id)
|
||||
}
|
||||
// Keep denormalized badges field on skill doc in sync
|
||||
const skill = await ctx.db.get(skillId)
|
||||
if (skill) {
|
||||
const { [kind]: _, ...remainingBadges } = (skill.badges ?? {}) as Record<string, unknown>
|
||||
await ctx.db.patch(skillId, { badges: remainingBadges })
|
||||
}
|
||||
}
|
||||
|
||||
export const getBySlug = query({
|
||||
@@ -887,7 +917,9 @@ export const clearOwnerSuspiciousFlagsInternal = internalMutation({
|
||||
patch.moderationStatus = 'active'
|
||||
}
|
||||
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
updated += 1
|
||||
}
|
||||
|
||||
@@ -1462,7 +1494,9 @@ export const report = mutation({
|
||||
})
|
||||
}
|
||||
|
||||
const nextSkill = { ...skill, ...updates }
|
||||
await ctx.db.patch(skill._id, updates)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
if (shouldAutoHide) {
|
||||
await setSkillEmbeddingsSoftDeleted(ctx, skill._id, true, now)
|
||||
@@ -1563,34 +1597,86 @@ export const listPublicPageV2 = query({
|
||||
),
|
||||
),
|
||||
dir: v.optional(v.union(v.literal('asc'), v.literal('desc'))),
|
||||
highlightedOnly: v.optional(v.boolean()),
|
||||
nonSuspiciousOnly: v.optional(v.boolean()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const sort = args.sort ?? 'newest'
|
||||
const dir = args.dir ?? (sort === 'name' ? 'asc' : 'desc')
|
||||
const paginationOpts: { cursor: string | null; numItems: number; id?: number } = {
|
||||
...args.paginationOpts,
|
||||
numItems: clampInt(args.paginationOpts.numItems, 1, MAX_PUBLIC_LIST_LIMIT),
|
||||
}
|
||||
const { numItems, cursor: initialCursor } = normalizePublicListPagination(args.paginationOpts)
|
||||
|
||||
const runPaginate = (cursor: string | null) =>
|
||||
ctx.db
|
||||
.query('skills')
|
||||
.withIndex(SORT_INDEXES[sort], (q) => q.eq('softDeletedAt', undefined))
|
||||
.order(dir)
|
||||
.paginate({ cursor, numItems })
|
||||
|
||||
// Use the index to filter out soft-deleted skills at query time.
|
||||
// softDeletedAt === undefined means active (non-deleted) skills only.
|
||||
const result = await ctx.db
|
||||
.query('skills')
|
||||
.withIndex(SORT_INDEXES[sort], (q) => q.eq('softDeletedAt', undefined))
|
||||
.order(dir)
|
||||
.paginate(paginationOpts)
|
||||
const result = await paginateWithStaleCursorRecovery(runPaginate, initialCursor)
|
||||
|
||||
const filteredPage = args.nonSuspiciousOnly
|
||||
? result.page.filter((skill) => !isSkillSuspicious(skill))
|
||||
: result.page
|
||||
const filteredPage =
|
||||
args.nonSuspiciousOnly || args.highlightedOnly
|
||||
? result.page.filter((skill) => {
|
||||
if (args.nonSuspiciousOnly && isSkillSuspicious(skill)) return false
|
||||
if (args.highlightedOnly && !isSkillHighlighted(skill)) return false
|
||||
return true
|
||||
})
|
||||
: result.page
|
||||
|
||||
// Build the public skill entries (fetch latestVersion + ownerHandle)
|
||||
const items = await buildPublicSkillEntries(ctx, filteredPage)
|
||||
// Build the public skill entries — skip version doc reads to reduce bandwidth.
|
||||
// Version data is only needed for detail pages, not the listing.
|
||||
const items = await buildPublicSkillEntries(ctx, filteredPage, { includeVersion: false })
|
||||
return { ...result, page: items }
|
||||
},
|
||||
})
|
||||
|
||||
function normalizePublicListPagination(paginationOpts: {
|
||||
cursor?: string | null
|
||||
numItems: number
|
||||
}) {
|
||||
return {
|
||||
cursor: paginationOpts.cursor ?? null,
|
||||
numItems: clampInt(paginationOpts.numItems, 1, MAX_PUBLIC_LIST_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
async function paginateWithStaleCursorRecovery<T>(
|
||||
runPaginate: (cursor: string | null) => Promise<T>,
|
||||
initialCursor: string | null,
|
||||
) {
|
||||
try {
|
||||
return await runPaginate(initialCursor)
|
||||
} catch (error) {
|
||||
// Some clients may send stale cursors after index/query argument changes.
|
||||
// Recover by restarting from the first page instead of surfacing a 500.
|
||||
if (!initialCursor || !isCursorParseError(error)) {
|
||||
throw error
|
||||
}
|
||||
return runPaginate(null)
|
||||
}
|
||||
}
|
||||
|
||||
function isCursorParseError(error: unknown) {
|
||||
if (typeof error === 'string') return error.includes('Failed to parse cursor')
|
||||
if (error && typeof error === 'object' && 'message' in error) {
|
||||
const message = (error as { message?: unknown }).message
|
||||
return typeof message === 'string' && message.includes('Failed to parse cursor')
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export const countPublicSkills = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const statsCount = await readGlobalPublicSkillsCount(ctx)
|
||||
if (typeof statsCount === 'number') return statsCount
|
||||
// Fallback for uninitialized/missing globalStats storage.
|
||||
return countPublicSkillsForGlobalStats(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
function sortToIndex(
|
||||
sort: 'downloads' | 'stars' | 'installsCurrent' | 'installsAllTime',
|
||||
):
|
||||
@@ -1682,19 +1768,47 @@ export const getSkillByIdInternal = internalQuery({
|
||||
})
|
||||
|
||||
export const getPendingScanSkillsInternal = internalQuery({
|
||||
args: { limit: v.optional(v.number()), skipRecentMinutes: v.optional(v.number()) },
|
||||
args: {
|
||||
limit: v.optional(v.number()),
|
||||
skipRecentMinutes: v.optional(v.number()),
|
||||
exhaustive: v.optional(v.boolean()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const limit = clampInt(args.limit ?? 10, 1, 100)
|
||||
const skipRecentMinutes = args.skipRecentMinutes ?? 60
|
||||
const exhaustive = args.exhaustive ?? false
|
||||
const limit = exhaustive ? Math.max(1, Math.floor(args.limit ?? 10000)) : clampInt(args.limit ?? 10, 1, 100)
|
||||
const skipRecentMinutes = exhaustive ? 0 : (args.skipRecentMinutes ?? 60)
|
||||
const skipThreshold = Date.now() - skipRecentMinutes * 60 * 1000
|
||||
|
||||
// Use an indexed query and bounded scan to avoid full-table reads under spam/high volume.
|
||||
const poolSize = Math.min(Math.max(limit * 20, 200), 1000)
|
||||
const allSkills = await ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined))
|
||||
.order('desc')
|
||||
.take(poolSize)
|
||||
let allSkills: Doc<'skills'>[] = []
|
||||
if (exhaustive) {
|
||||
// Used by manual/backfill tooling where fairness matters more than query cost.
|
||||
allSkills = await ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined))
|
||||
.collect()
|
||||
} else {
|
||||
// Mix "most recently updated" with "oldest created" slices so older pending
|
||||
// items don't starve behind high-churn records.
|
||||
const poolSize = Math.min(Math.max(limit * 20, 200), 1000)
|
||||
const [recentSkills, oldestSkills] = await Promise.all([
|
||||
ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined))
|
||||
.order('desc')
|
||||
.take(poolSize),
|
||||
ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_active_created', (q) => q.eq('softDeletedAt', undefined))
|
||||
.order('asc')
|
||||
.take(poolSize),
|
||||
])
|
||||
|
||||
const deduped = new Map<Id<'skills'>, Doc<'skills'>>()
|
||||
for (const skill of [...recentSkills, ...oldestSkills]) {
|
||||
deduped.set(skill._id, skill)
|
||||
}
|
||||
allSkills = [...deduped.values()]
|
||||
}
|
||||
|
||||
const candidates = allSkills.filter((skill) => {
|
||||
const reason = skill.moderationReason
|
||||
@@ -1709,10 +1823,11 @@ export const getPendingScanSkillsInternal = internalQuery({
|
||||
)
|
||||
})
|
||||
|
||||
// Filter out recently checked skills
|
||||
const skills = candidates.filter(
|
||||
(s) => !s.scanLastCheckedAt || s.scanLastCheckedAt < skipThreshold,
|
||||
)
|
||||
// Filter out recently checked skills unless caller explicitly disables recency filtering.
|
||||
const skills =
|
||||
skipRecentMinutes <= 0
|
||||
? candidates
|
||||
: candidates.filter((s) => !s.scanLastCheckedAt || s.scanLastCheckedAt < skipThreshold)
|
||||
|
||||
// Shuffle and take the requested limit (Fisher-Yates)
|
||||
for (let i = skills.length - 1; i > 0; i--) {
|
||||
@@ -1728,10 +1843,13 @@ export const getPendingScanSkillsInternal = internalQuery({
|
||||
checkCount: number
|
||||
}> = []
|
||||
|
||||
const FINAL_VT_STATUSES = new Set(['clean', 'malicious', 'suspicious'])
|
||||
for (const skill of selected) {
|
||||
const version = skill.latestVersionId ? await ctx.db.get(skill.latestVersionId) : null
|
||||
// Skip skills where version already has vtAnalysis or lacks sha256hash
|
||||
if (version?.vtAnalysis || !version?.sha256hash) continue
|
||||
if (!version?.sha256hash) continue
|
||||
const vtStatus = version.vtAnalysis?.status?.trim().toLowerCase()
|
||||
// Keep retrying unresolved VT results (pending/stale/error), but skip finalized outcomes.
|
||||
if (vtStatus && FINAL_VT_STATUSES.has(vtStatus)) continue
|
||||
results.push({
|
||||
skillId: skill._id,
|
||||
versionId: version?._id ?? null,
|
||||
@@ -1913,6 +2031,7 @@ export const getActiveSkillBatchForRescanInternal = internalQuery({
|
||||
versionId: Id<'skillVersions'>
|
||||
sha256hash: string
|
||||
slug: string
|
||||
wasFlagged: boolean
|
||||
}> = []
|
||||
let nextCursor = cursor
|
||||
|
||||
@@ -1933,6 +2052,8 @@ export const getActiveSkillBatchForRescanInternal = internalQuery({
|
||||
versionId: version._id,
|
||||
sha256hash: version.sha256hash,
|
||||
slug: skill.slug,
|
||||
wasFlagged:
|
||||
(skill.moderationFlags as string[] | undefined)?.includes('flagged.suspicious') ?? false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2130,9 +2251,13 @@ export const getSkillsWithNullModerationStatusInternal = internalQuery({
|
||||
export const setSkillModerationStatusActiveInternal = internalMutation({
|
||||
args: { skillId: v.id('skills') },
|
||||
handler: async (ctx, args) => {
|
||||
await ctx.db.patch(args.skillId, {
|
||||
moderationStatus: 'active',
|
||||
})
|
||||
const skill = await ctx.db.get(args.skillId)
|
||||
if (!skill) return
|
||||
|
||||
const patch: Partial<Doc<'skills'>> = { moderationStatus: 'active' }
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(args.skillId, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -2238,7 +2363,9 @@ export const applyBanToOwnedSkillsBatchInternal = internalMutation({
|
||||
hiddenCount += 1
|
||||
}
|
||||
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
await setSkillEmbeddingsSoftDeleted(ctx, skill._id, true, args.bannedAt)
|
||||
}
|
||||
|
||||
@@ -2278,7 +2405,7 @@ export const restoreOwnedSkillsForUnbanBatchInternal = internalMutation({
|
||||
continue
|
||||
}
|
||||
|
||||
await ctx.db.patch(skill._id, {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
softDeletedAt: undefined,
|
||||
moderationStatus: 'active',
|
||||
moderationReason: 'restored.unban',
|
||||
@@ -2286,7 +2413,10 @@ export const restoreOwnedSkillsForUnbanBatchInternal = internalMutation({
|
||||
hiddenBy: undefined,
|
||||
lastReviewedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
await setSkillEmbeddingsSoftDeleted(ctx, skill._id, false, now)
|
||||
restoredCount += 1
|
||||
@@ -2516,7 +2646,6 @@ export const approveSkillByHashInternal = internalMutation({
|
||||
const existingFlags: string[] = (skill.moderationFlags as string[] | undefined) ?? []
|
||||
const existingReason: string | undefined = skill.moderationReason as string | undefined
|
||||
const alreadyBlocked = existingFlags.includes('blocked.malware')
|
||||
const alreadyFlagged = existingFlags.includes('flagged.suspicious')
|
||||
const bypassSuspicious =
|
||||
isSuspicious && !alreadyBlocked && isPrivilegedOwnerForSuspiciousBypass(owner)
|
||||
|
||||
@@ -2525,8 +2654,8 @@ export const approveSkillByHashInternal = internalMutation({
|
||||
if (isMalicious || alreadyBlocked) {
|
||||
// Malicious from ANY scanner → blocked.malware (upgrade from suspicious)
|
||||
newFlags = ['blocked.malware']
|
||||
} else if ((isSuspicious || alreadyFlagged) && !bypassSuspicious) {
|
||||
// Suspicious from ANY scanner → flagged.suspicious
|
||||
} else if (isSuspicious && !bypassSuspicious) {
|
||||
// Suspicious from this scanner → flagged.suspicious
|
||||
newFlags = ['flagged.suspicious']
|
||||
} else if (isClean) {
|
||||
// Clean from this scanner — only clear if no other scanner has flagged
|
||||
@@ -2554,7 +2683,7 @@ export const approveSkillByHashInternal = internalMutation({
|
||||
'Quality gate quarantine is still active. Manual moderation review required.')
|
||||
: undefined
|
||||
|
||||
await ctx.db.patch(skill._id, {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
moderationStatus: nextModerationStatus,
|
||||
moderationReason: nextModerationReason,
|
||||
moderationFlags: newFlags,
|
||||
@@ -2563,7 +2692,10 @@ export const approveSkillByHashInternal = internalMutation({
|
||||
hiddenBy: undefined,
|
||||
lastReviewedAt: nextModerationStatus === 'hidden' ? now : undefined,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
// Auto-ban authors of malicious skills (skips moderators/admins)
|
||||
if (isMalicious && skill.ownerUserId) {
|
||||
@@ -2616,7 +2748,7 @@ export const escalateByVtInternal = internalMutation({
|
||||
newFlags = ['flagged.suspicious']
|
||||
}
|
||||
|
||||
const patch: Record<string, unknown> = {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
moderationFlags: newFlags.length ? newFlags : undefined,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
@@ -2631,7 +2763,9 @@ export const escalateByVtInternal = internalMutation({
|
||||
patch.moderationStatus = 'hidden'
|
||||
}
|
||||
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
// Auto-ban authors of malicious skills
|
||||
if (isMalicious && skill.ownerUserId) {
|
||||
@@ -2921,14 +3055,17 @@ export const setSoftDeleted = mutation({
|
||||
if (!skill) throw new Error('Skill not found')
|
||||
|
||||
const now = Date.now()
|
||||
await ctx.db.patch(skill._id, {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
softDeletedAt: args.deleted ? now : undefined,
|
||||
moderationStatus: args.deleted ? 'hidden' : 'active',
|
||||
hiddenAt: args.deleted ? now : undefined,
|
||||
hiddenBy: args.deleted ? user._id : undefined,
|
||||
lastReviewedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
await setSkillEmbeddingsSoftDeleted(ctx, skill._id, args.deleted, now)
|
||||
|
||||
@@ -2983,6 +3120,38 @@ export const changeOwner = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
async function transferSkillOwnershipAndEmbeddings(
|
||||
ctx: MutationCtx,
|
||||
params: {
|
||||
skill: Doc<'skills'>
|
||||
ownerUserId: Id<'users'>
|
||||
now: number
|
||||
},
|
||||
) {
|
||||
if (params.skill.ownerUserId === params.ownerUserId) return
|
||||
|
||||
await ctx.db.patch(params.skill._id, {
|
||||
ownerUserId: params.ownerUserId,
|
||||
lastReviewedAt: params.now,
|
||||
updatedAt: params.now,
|
||||
})
|
||||
|
||||
const embeddings = await listSkillEmbeddingsForSkill(ctx, params.skill._id)
|
||||
for (const embedding of embeddings) {
|
||||
await ctx.db.patch(embedding._id, {
|
||||
ownerId: params.ownerUserId,
|
||||
updatedAt: params.now,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseActiveReservationsForSlug(ctx: MutationCtx, slug: string, releasedAt: number) {
|
||||
const active = await listActiveReservedSlugsForSlug(ctx, slug)
|
||||
for (const reservation of active) {
|
||||
await ctx.db.patch(reservation._id, { releasedAt })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin-only: reclaim a squatted slug by hard-deleting the squatter's skill
|
||||
* and reserving the slug for the rightful owner.
|
||||
@@ -3061,6 +3230,7 @@ export const reclaimSlugInternal = internalMutation({
|
||||
slug: v.string(),
|
||||
rightfulOwnerUserId: v.id('users'),
|
||||
reason: v.optional(v.string()),
|
||||
transferRootSlugOnly: v.optional(v.boolean()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const actor = await ctx.db.get(args.actorUserId)
|
||||
@@ -3071,12 +3241,82 @@ export const reclaimSlugInternal = internalMutation({
|
||||
if (!slug) throw new Error('Slug required')
|
||||
|
||||
const now = Date.now()
|
||||
const transferRootSlugOnly = args.transferRootSlugOnly === true
|
||||
|
||||
const rightfulOwner = await ctx.db.get(args.rightfulOwnerUserId)
|
||||
if (!rightfulOwner || rightfulOwner.deletedAt || rightfulOwner.deactivatedAt) {
|
||||
throw new Error('Rightful owner not found')
|
||||
}
|
||||
|
||||
const existingSkill = await ctx.db
|
||||
.query('skills')
|
||||
.withIndex('by_slug', (q) => q.eq('slug', slug))
|
||||
.unique()
|
||||
|
||||
if (transferRootSlugOnly) {
|
||||
if (!existingSkill) {
|
||||
await ctx.db.insert('auditLogs', {
|
||||
actorUserId: args.actorUserId,
|
||||
action: 'slug.reclaim',
|
||||
targetType: 'slug',
|
||||
targetId: slug,
|
||||
metadata: {
|
||||
slug,
|
||||
rightfulOwnerUserId: args.rightfulOwnerUserId,
|
||||
transferRootSlugOnly: true,
|
||||
action: 'missing',
|
||||
reason: args.reason || undefined,
|
||||
},
|
||||
createdAt: now,
|
||||
})
|
||||
return { ok: true as const, action: 'missing' as const }
|
||||
}
|
||||
|
||||
if (existingSkill.ownerUserId === args.rightfulOwnerUserId) {
|
||||
await releaseActiveReservationsForSlug(ctx, slug, now)
|
||||
await ctx.db.insert('auditLogs', {
|
||||
actorUserId: args.actorUserId,
|
||||
action: 'slug.reclaim',
|
||||
targetType: 'slug',
|
||||
targetId: slug,
|
||||
metadata: {
|
||||
slug,
|
||||
rightfulOwnerUserId: args.rightfulOwnerUserId,
|
||||
transferRootSlugOnly: true,
|
||||
action: 'already_owned',
|
||||
reason: args.reason || undefined,
|
||||
},
|
||||
createdAt: now,
|
||||
})
|
||||
return { ok: true as const, action: 'already_owned' as const }
|
||||
}
|
||||
|
||||
await transferSkillOwnershipAndEmbeddings(ctx, {
|
||||
skill: existingSkill,
|
||||
ownerUserId: args.rightfulOwnerUserId,
|
||||
now,
|
||||
})
|
||||
await releaseActiveReservationsForSlug(ctx, slug, now)
|
||||
|
||||
await ctx.db.insert('auditLogs', {
|
||||
actorUserId: args.actorUserId,
|
||||
action: 'slug.reclaim',
|
||||
targetType: 'slug',
|
||||
targetId: slug,
|
||||
metadata: {
|
||||
slug,
|
||||
rightfulOwnerUserId: args.rightfulOwnerUserId,
|
||||
previousOwnerUserId: existingSkill.ownerUserId,
|
||||
hadSquatter: true,
|
||||
transferRootSlugOnly: true,
|
||||
action: 'ownership_transferred',
|
||||
reason: args.reason || undefined,
|
||||
},
|
||||
createdAt: now,
|
||||
})
|
||||
return { ok: true as const, action: 'ownership_transferred' as const }
|
||||
}
|
||||
|
||||
if (existingSkill && existingSkill.ownerUserId !== args.rightfulOwnerUserId) {
|
||||
await ctx.scheduler.runAfter(0, internal.skills.hardDeleteInternal, {
|
||||
skillId: existingSkill._id,
|
||||
@@ -3472,6 +3712,9 @@ export const insertVersion = internalMutation({
|
||||
updatedAt: now,
|
||||
})
|
||||
skill = await ctx.db.get(skillId)
|
||||
if (skill) {
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, null, skill)
|
||||
}
|
||||
}
|
||||
|
||||
if (!skill) throw new Error('Skill creation failed')
|
||||
@@ -3513,7 +3756,7 @@ export const insertVersion = internalMutation({
|
||||
files: args.files,
|
||||
})
|
||||
|
||||
await ctx.db.patch(skill._id, {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
displayName: args.displayName,
|
||||
summary: nextSummary ?? undefined,
|
||||
latestVersionId: versionId,
|
||||
@@ -3526,7 +3769,10 @@ export const insertVersion = internalMutation({
|
||||
quality: qualityRecord ?? skill.quality,
|
||||
moderationFlags: moderationFlags.length ? moderationFlags : undefined,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
const badgeMap = await getSkillBadgeMap(ctx, skill._id)
|
||||
const isApproved = Boolean(badgeMap.redactionApproved)
|
||||
@@ -3541,6 +3787,8 @@ export const insertVersion = internalMutation({
|
||||
visibility: embeddingVisibilityFor(true, isApproved),
|
||||
updatedAt: now,
|
||||
})
|
||||
// Lightweight lookup so search hydration can skip reading the 12KB embedding doc
|
||||
await ctx.db.insert('embeddingSkillMap', { embeddingId, skillId: skill._id })
|
||||
|
||||
if (latestBefore) {
|
||||
const previousEmbedding = await ctx.db
|
||||
@@ -3591,14 +3839,17 @@ export const setSkillSoftDeletedInternal = internalMutation({
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
await ctx.db.patch(skill._id, {
|
||||
const patch: Partial<Doc<'skills'>> = {
|
||||
softDeletedAt: args.deleted ? now : undefined,
|
||||
moderationStatus: args.deleted ? 'hidden' : 'active',
|
||||
hiddenAt: args.deleted ? now : undefined,
|
||||
hiddenBy: args.deleted ? args.userId : undefined,
|
||||
lastReviewedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}
|
||||
const nextSkill = { ...skill, ...patch }
|
||||
await ctx.db.patch(skill._id, patch)
|
||||
await adjustGlobalPublicCountForSkillChange(ctx, skill, nextSkill)
|
||||
|
||||
await setSkillEmbeddingsSoftDeleted(ctx, skill._id, args.deleted, now)
|
||||
|
||||
|
||||
@@ -3,6 +3,10 @@ import { internal } from './_generated/api'
|
||||
import type { Doc } from './_generated/dataModel'
|
||||
import type { ActionCtx } from './_generated/server'
|
||||
import { internalAction, internalMutation, internalQuery } from './_generated/server'
|
||||
import {
|
||||
countPublicSkillsForGlobalStats,
|
||||
setGlobalPublicSkillsCount,
|
||||
} from './lib/globalStats'
|
||||
|
||||
const DEFAULT_BATCH_SIZE = 200
|
||||
const MAX_BATCH_SIZE = 1000
|
||||
@@ -299,3 +303,11 @@ export const runReconcileSkillStarCountsInternal = internalAction({
|
||||
function clampInt(value: number, min: number, max: number) {
|
||||
return Math.min(Math.max(value, min), max)
|
||||
}
|
||||
|
||||
export const updateGlobalStatsInternal = internalMutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const count = await countPublicSkillsForGlobalStats(ctx)
|
||||
await setGlobalPublicSkillsCount(ctx, count)
|
||||
},
|
||||
})
|
||||
|
||||
+356
-1
@@ -6,7 +6,7 @@ vi.mock('./lib/access', async () => {
|
||||
})
|
||||
|
||||
const { requireUser } = await import('./lib/access')
|
||||
const { ensureHandler } = await import('./users')
|
||||
const { ensureHandler, list, searchInternal } = await import('./users')
|
||||
|
||||
function makeCtx() {
|
||||
const patch = vi.fn()
|
||||
@@ -14,6 +14,22 @@ function makeCtx() {
|
||||
return { ctx: { db: { patch, get } } as never, patch, get }
|
||||
}
|
||||
|
||||
function makeListCtx(users: Array<Record<string, unknown>>) {
|
||||
const take = vi.fn(async (n: number) => users.slice(0, n))
|
||||
const collect = vi.fn(async () => users)
|
||||
const order = vi.fn(() => ({ take, collect }))
|
||||
const query = vi.fn(() => ({ order }))
|
||||
const get = vi.fn()
|
||||
return {
|
||||
ctx: { db: { query, get } } as never,
|
||||
take,
|
||||
collect,
|
||||
order,
|
||||
query,
|
||||
get,
|
||||
}
|
||||
}
|
||||
|
||||
describe('ensureHandler', () => {
|
||||
afterEach(() => {
|
||||
vi.mocked(requireUser).mockReset()
|
||||
@@ -87,4 +103,343 @@ describe('ensureHandler', () => {
|
||||
updatedAt: expect.any(Number),
|
||||
})
|
||||
})
|
||||
|
||||
it('does not patch when user metadata is already normalized', async () => {
|
||||
const { ctx, patch, get } = makeCtx()
|
||||
get.mockResolvedValue({
|
||||
_id: 'users:4',
|
||||
handle: 'steady',
|
||||
displayName: 'Steady Name',
|
||||
name: 'steady',
|
||||
role: 'user',
|
||||
_creationTime: 1,
|
||||
createdAt: 1,
|
||||
})
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:4',
|
||||
user: {
|
||||
_creationTime: 1,
|
||||
handle: 'steady',
|
||||
displayName: 'Steady Name',
|
||||
name: 'steady',
|
||||
role: 'user',
|
||||
createdAt: 1,
|
||||
},
|
||||
} as never)
|
||||
|
||||
const result = await ensureHandler(ctx)
|
||||
|
||||
expect(patch).not.toHaveBeenCalled()
|
||||
expect(get).toHaveBeenCalledWith('users:4')
|
||||
expect(result).toMatchObject({ _id: 'users:4' })
|
||||
})
|
||||
|
||||
it('sets admin role when normalized handle is steipete and role is missing', async () => {
|
||||
const { ctx, patch } = makeCtx()
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: {
|
||||
_creationTime: 1,
|
||||
handle: 'steipete',
|
||||
displayName: 'steipete',
|
||||
name: 'steipete',
|
||||
role: undefined,
|
||||
createdAt: 1,
|
||||
},
|
||||
} as never)
|
||||
|
||||
await ensureHandler(ctx)
|
||||
|
||||
expect(patch).toHaveBeenCalledWith('users:admin', {
|
||||
displayName: 'steipete',
|
||||
role: 'admin',
|
||||
updatedAt: expect.any(Number),
|
||||
})
|
||||
})
|
||||
|
||||
it('derives handle/display name from email when missing', async () => {
|
||||
const { ctx, patch } = makeCtx()
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:email',
|
||||
user: {
|
||||
_creationTime: 1,
|
||||
handle: undefined,
|
||||
displayName: undefined,
|
||||
name: undefined,
|
||||
email: 'owner@example.com',
|
||||
role: undefined,
|
||||
createdAt: undefined,
|
||||
},
|
||||
} as never)
|
||||
|
||||
await ensureHandler(ctx)
|
||||
|
||||
expect(patch).toHaveBeenCalledWith('users:email', {
|
||||
handle: 'owner',
|
||||
displayName: 'owner',
|
||||
role: 'user',
|
||||
createdAt: 1,
|
||||
updatedAt: expect.any(Number),
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('users.list', () => {
|
||||
afterEach(() => {
|
||||
vi.mocked(requireUser).mockReset()
|
||||
})
|
||||
|
||||
it('uses take(limit) without full collect when search is empty', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = [
|
||||
{ _id: 'users:1', _creationTime: 3, handle: 'alice', role: 'user' },
|
||||
{ _id: 'users:2', _creationTime: 2, handle: 'bob', role: 'user' },
|
||||
{ _id: 'users:3', _creationTime: 1, handle: 'carol', role: 'user' },
|
||||
]
|
||||
const { ctx, take, collect } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
const result = (await listHandler(ctx, { limit: 2 })) as {
|
||||
items: Array<Record<string, unknown>>
|
||||
total: number
|
||||
}
|
||||
|
||||
expect(take).toHaveBeenCalledWith(2)
|
||||
expect(collect).not.toHaveBeenCalled()
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.items).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('uses bounded scan for search instead of full collect', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = [
|
||||
{ _id: 'users:1', _creationTime: 3, handle: 'alice', role: 'user' },
|
||||
{ _id: 'users:2', _creationTime: 2, handle: 'bob', role: 'user' },
|
||||
{ _id: 'users:3', _creationTime: 1, handle: 'carol', role: 'user' },
|
||||
]
|
||||
const { ctx, take, collect } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
const result = (await listHandler(ctx, { limit: 50, search: 'ali' })) as {
|
||||
items: Array<Record<string, unknown>>
|
||||
total: number
|
||||
}
|
||||
|
||||
expect(take).toHaveBeenCalledWith(500)
|
||||
expect(collect).not.toHaveBeenCalled()
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.items[0]?.handle).toBe('alice')
|
||||
})
|
||||
|
||||
it('clamps large limit and search scan size', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = Array.from({ length: 8_000 }, (_value, index) => ({
|
||||
_id: `users:${index}`,
|
||||
_creationTime: 10_000 - index,
|
||||
handle: `user-${index}`,
|
||||
role: 'user',
|
||||
}))
|
||||
const { ctx, take } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
await listHandler(ctx, { limit: 999, search: 'user' })
|
||||
|
||||
expect(take).toHaveBeenCalledWith(2_000)
|
||||
})
|
||||
|
||||
it('handles malformed legacy user fields without throwing', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = [
|
||||
{
|
||||
_id: 'users:legacy',
|
||||
_creationTime: 99,
|
||||
handle: 123,
|
||||
name: { broken: true },
|
||||
displayName: null,
|
||||
email: ['legacy@example.com'],
|
||||
role: 'user',
|
||||
},
|
||||
{
|
||||
_id: 'users:2',
|
||||
_creationTime: 98,
|
||||
handle: 'carol',
|
||||
role: 'user',
|
||||
},
|
||||
]
|
||||
const { ctx } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
await expect(listHandler(ctx, { limit: 50, search: 'car' })).resolves.toMatchObject({
|
||||
total: 1,
|
||||
items: [{ _id: 'users:2' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('treats whitespace search as empty search', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = [
|
||||
{ _id: 'users:1', _creationTime: 2, handle: 'alice', role: 'user' },
|
||||
{ _id: 'users:2', _creationTime: 1, handle: 'bob', role: 'user' },
|
||||
]
|
||||
const { ctx, take, collect } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
const result = (await listHandler(ctx, { limit: 50, search: ' ' })) as {
|
||||
items: Array<Record<string, unknown>>
|
||||
total: number
|
||||
}
|
||||
|
||||
expect(take).toHaveBeenCalledWith(50)
|
||||
expect(collect).not.toHaveBeenCalled()
|
||||
expect(result.total).toBe(2)
|
||||
})
|
||||
|
||||
it('clamps non-positive limit to one', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:admin',
|
||||
user: { _id: 'users:admin', role: 'admin' },
|
||||
} as never)
|
||||
const users = [
|
||||
{ _id: 'users:1', _creationTime: 2, handle: 'alice', role: 'user' },
|
||||
{ _id: 'users:2', _creationTime: 1, handle: 'bob', role: 'user' },
|
||||
]
|
||||
const { ctx, take } = makeListCtx(users)
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
const result = (await listHandler(ctx, { limit: 0 })) as {
|
||||
items: Array<Record<string, unknown>>
|
||||
total: number
|
||||
}
|
||||
|
||||
expect(take).toHaveBeenCalledWith(1)
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects non-admin actors', async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: 'users:basic',
|
||||
user: { _id: 'users:basic', role: 'user' },
|
||||
} as never)
|
||||
const { ctx } = makeListCtx([])
|
||||
const listHandler = (list as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> })
|
||||
._handler
|
||||
|
||||
await expect(listHandler(ctx, { limit: 10 })).rejects.toThrow('Forbidden')
|
||||
})
|
||||
})
|
||||
|
||||
describe('users.searchInternal', () => {
|
||||
it('rejects missing actor', async () => {
|
||||
const { ctx, get } = makeListCtx([])
|
||||
const handler = (
|
||||
searchInternal as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> }
|
||||
)._handler
|
||||
get.mockResolvedValue(null)
|
||||
|
||||
await expect(handler(ctx, { actorUserId: 'users:missing' })).rejects.toThrow('Unauthorized')
|
||||
})
|
||||
|
||||
it('uses bounded scan and returns mapped fields', async () => {
|
||||
const users = [
|
||||
{ _id: 'users:1', _creationTime: 2, handle: 'alice', name: 'alice', role: 'user' },
|
||||
{ _id: 'users:2', _creationTime: 1, handle: 'bob', name: 'bob', role: 'moderator' },
|
||||
]
|
||||
const { ctx, take, collect, get } = makeListCtx(users)
|
||||
const handler = (
|
||||
searchInternal as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> }
|
||||
)._handler
|
||||
get.mockResolvedValue({ _id: 'users:admin', role: 'admin' })
|
||||
|
||||
const result = (await handler(ctx, {
|
||||
actorUserId: 'users:admin',
|
||||
query: 'ali',
|
||||
limit: 25,
|
||||
})) as {
|
||||
items: Array<Record<string, unknown>>
|
||||
total: number
|
||||
}
|
||||
|
||||
expect(take).toHaveBeenCalledWith(500)
|
||||
expect(collect).not.toHaveBeenCalled()
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items).toEqual([
|
||||
{
|
||||
userId: 'users:1',
|
||||
handle: 'alice',
|
||||
displayName: null,
|
||||
name: 'alice',
|
||||
role: 'user',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects deactivated actors', async () => {
|
||||
const { ctx, get } = makeListCtx([])
|
||||
const handler = (
|
||||
searchInternal as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> }
|
||||
)._handler
|
||||
get.mockResolvedValue({ _id: 'users:ghost', role: 'admin', deactivatedAt: Date.now() })
|
||||
|
||||
await expect(handler(ctx, { actorUserId: 'users:ghost' })).rejects.toThrow('Unauthorized')
|
||||
})
|
||||
|
||||
it('rejects non-admin actors', async () => {
|
||||
const { ctx, get } = makeListCtx([])
|
||||
const handler = (
|
||||
searchInternal as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> }
|
||||
)._handler
|
||||
get.mockResolvedValue({ _id: 'users:mod', role: 'moderator' })
|
||||
|
||||
await expect(handler(ctx, { actorUserId: 'users:mod', query: 'a' })).rejects.toThrow(
|
||||
'Forbidden',
|
||||
)
|
||||
})
|
||||
|
||||
it('clamps limit for empty query and uses non-search path', async () => {
|
||||
const users = Array.from({ length: 400 }, (_value, index) => ({
|
||||
_id: `users:${index}`,
|
||||
_creationTime: 1_000 - index,
|
||||
handle: `user-${index}`,
|
||||
role: 'user',
|
||||
}))
|
||||
const { ctx, take, collect, get } = makeListCtx(users)
|
||||
const handler = (
|
||||
searchInternal as unknown as { _handler: (ctx: unknown, args: unknown) => Promise<unknown> }
|
||||
)._handler
|
||||
get.mockResolvedValue({ _id: 'users:admin', role: 'admin' })
|
||||
|
||||
const result = (await handler(ctx, {
|
||||
actorUserId: 'users:admin',
|
||||
limit: 999,
|
||||
query: ' ',
|
||||
})) as { items: Array<Record<string, unknown>>; total: number }
|
||||
|
||||
expect(take).toHaveBeenCalledWith(200)
|
||||
expect(collect).not.toHaveBeenCalled()
|
||||
expect(result.total).toBe(200)
|
||||
expect(result.items).toHaveLength(200)
|
||||
})
|
||||
})
|
||||
|
||||
+38
-9
@@ -11,6 +11,9 @@ import { buildUserSearchResults } from './lib/userSearch'
|
||||
|
||||
const DEFAULT_ROLE = 'user'
|
||||
const ADMIN_HANDLE = 'steipete'
|
||||
const MAX_USER_LIST_LIMIT = 200
|
||||
const MAX_USER_SEARCH_SCAN = 5_000
|
||||
const MIN_USER_SEARCH_SCAN = 500
|
||||
|
||||
export const getById = query({
|
||||
args: { userId: v.id('users') },
|
||||
@@ -33,10 +36,9 @@ export const searchInternal = internalQuery({
|
||||
if (!actor || actor.deletedAt || actor.deactivatedAt) throw new Error('Unauthorized')
|
||||
assertAdmin(actor)
|
||||
|
||||
const limit = Math.min(Math.max(args.limit ?? 20, 1), 200)
|
||||
const users = await ctx.db.query('users').order('desc').collect()
|
||||
const result = buildUserSearchResults(users, args.query)
|
||||
const items = result.items.slice(0, limit).map((user) => ({
|
||||
const limit = clampInt(args.limit ?? 20, 1, MAX_USER_LIST_LIMIT)
|
||||
const result = await queryUsersForAdminList(ctx, { limit, search: args.query })
|
||||
const items = result.items.map((user) => ({
|
||||
userId: user._id,
|
||||
handle: user.handle ?? null,
|
||||
displayName: user.displayName ?? null,
|
||||
@@ -268,14 +270,41 @@ export const list = query({
|
||||
handler: async (ctx, args) => {
|
||||
const { user } = await requireUser(ctx)
|
||||
assertAdmin(user)
|
||||
const limit = Math.min(Math.max(args.limit ?? 50, 1), 200)
|
||||
const query = args.search?.trim().toLowerCase()
|
||||
const users = await ctx.db.query('users').order('desc').collect()
|
||||
const result = buildUserSearchResults(users, query)
|
||||
return { items: result.items.slice(0, limit), total: result.total }
|
||||
const limit = clampInt(args.limit ?? 50, 1, MAX_USER_LIST_LIMIT)
|
||||
return queryUsersForAdminList(ctx, { limit, search: args.search })
|
||||
},
|
||||
})
|
||||
|
||||
function normalizeSearchQuery(search?: string) {
|
||||
const trimmed = search?.trim().toLowerCase()
|
||||
return trimmed ? trimmed : undefined
|
||||
}
|
||||
|
||||
function computeUserSearchScanLimit(limit: number) {
|
||||
return clampInt(limit * 10, MIN_USER_SEARCH_SCAN, MAX_USER_SEARCH_SCAN)
|
||||
}
|
||||
|
||||
async function queryUsersForAdminList(
|
||||
ctx: { db: { query: (table: 'users') => { order: (order: 'desc') => { take: (n: number) => Promise<Doc<'users'>[]> } } } },
|
||||
args: { limit: number; search?: string },
|
||||
) {
|
||||
const normalizedSearch = normalizeSearchQuery(args.search)
|
||||
const orderedUsers = ctx.db.query('users').order('desc')
|
||||
|
||||
if (!normalizedSearch) {
|
||||
const items = await orderedUsers.take(args.limit)
|
||||
return { items, total: items.length }
|
||||
}
|
||||
|
||||
const scannedUsers = await orderedUsers.take(computeUserSearchScanLimit(args.limit))
|
||||
const result = buildUserSearchResults(scannedUsers, normalizedSearch)
|
||||
return { items: result.items.slice(0, args.limit), total: result.total }
|
||||
}
|
||||
|
||||
function clampInt(value: number, min: number, max: number) {
|
||||
return Math.min(Math.max(Math.trunc(value), min), max)
|
||||
}
|
||||
|
||||
export const getByHandle = query({
|
||||
args: { handle: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { __test } from './vt'
|
||||
|
||||
describe('vt activation fallback', () => {
|
||||
it('activates only VT-pending hidden skills', () => {
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'pending.scan',
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'scanner.vt.pending',
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'pending.scan.stale',
|
||||
}),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not activate quality or scanner-hidden skills', () => {
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'quality.low',
|
||||
}),
|
||||
).toBe(false)
|
||||
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'scanner.llm.malicious',
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('does not activate blocked or already-active skills', () => {
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'hidden',
|
||||
moderationReason: 'pending.scan',
|
||||
moderationFlags: ['blocked.malware'],
|
||||
}),
|
||||
).toBe(false)
|
||||
|
||||
expect(
|
||||
__test.shouldActivateWhenVtUnavailable({
|
||||
moderationStatus: 'active',
|
||||
moderationReason: 'pending.scan',
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
+50
-2
@@ -1,6 +1,7 @@
|
||||
import { v } from 'convex/values'
|
||||
import { internal } from './_generated/api'
|
||||
import type { Id } from './_generated/dataModel'
|
||||
import type { ActionCtx } from './_generated/server'
|
||||
import { action, internalAction, internalMutation } from './_generated/server'
|
||||
import { buildDeterministicZip } from './lib/skillZip'
|
||||
|
||||
@@ -136,6 +137,13 @@ type PendingScanSkill = {
|
||||
checkCount: number
|
||||
}
|
||||
|
||||
type SkillActivationCandidate = {
|
||||
moderationStatus?: string
|
||||
moderationReason?: string
|
||||
moderationFlags?: string[]
|
||||
softDeletedAt?: number
|
||||
}
|
||||
|
||||
type PollPendingScansResult = {
|
||||
processed: number
|
||||
updated: number
|
||||
@@ -228,6 +236,23 @@ type SyncModerationReasonsResult = {
|
||||
done: boolean
|
||||
}
|
||||
|
||||
const VT_PENDING_REASONS = new Set(['pending.scan', 'scanner.vt.pending', 'pending.scan.stale'])
|
||||
|
||||
function shouldActivateWhenVtUnavailable(skill: SkillActivationCandidate | null | undefined) {
|
||||
if (!skill || skill.softDeletedAt) return false
|
||||
if (skill.moderationFlags?.includes('blocked.malware')) return false
|
||||
if (skill.moderationStatus === 'active') return false
|
||||
const reason = skill.moderationReason
|
||||
return typeof reason === 'string' && VT_PENDING_REASONS.has(reason)
|
||||
}
|
||||
|
||||
async function activateSkillWhenVtUnavailable(ctx: ActionCtx, skillId: Id<'skills'>) {
|
||||
const skill = await ctx.runQuery(internal.skills.getSkillByIdInternal, { skillId })
|
||||
if (!shouldActivateWhenVtUnavailable(skill)) return
|
||||
|
||||
await ctx.runMutation(internal.skills.setSkillModerationStatusActiveInternal, { skillId })
|
||||
}
|
||||
|
||||
export const fetchResults = action({
|
||||
args: {
|
||||
sha256hash: v.optional(v.string()),
|
||||
@@ -305,7 +330,13 @@ export const scanWithVirusTotal = internalAction({
|
||||
handler: async (ctx, args) => {
|
||||
const apiKey = process.env.VT_API_KEY
|
||||
if (!apiKey) {
|
||||
console.log('VT_API_KEY not configured, skipping scan')
|
||||
console.log('VT_API_KEY not configured, skipping scan — activating skill')
|
||||
const version = await ctx.runQuery(internal.skills.getVersionByIdInternal, {
|
||||
versionId: args.versionId,
|
||||
})
|
||||
if (version) {
|
||||
await activateSkillWhenVtUnavailable(ctx, version.skillId)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -524,6 +555,7 @@ export const pollPendingScans = internalAction({
|
||||
versionId,
|
||||
vtAnalysis: { status: 'stale', checkedAt: Date.now() },
|
||||
})
|
||||
await activateSkillWhenVtUnavailable(ctx, skillId)
|
||||
staled++
|
||||
}
|
||||
continue
|
||||
@@ -549,6 +581,7 @@ export const pollPendingScans = internalAction({
|
||||
versionId,
|
||||
vtAnalysis: { status: 'stale', checkedAt: Date.now() },
|
||||
})
|
||||
await activateSkillWhenVtUnavailable(ctx, skillId)
|
||||
staled++
|
||||
}
|
||||
continue
|
||||
@@ -650,6 +683,10 @@ async function requestRescan(apiKey: string, sha256hash: string): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
export const __test = {
|
||||
shouldActivateWhenVtUnavailable,
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfill function to process ALL pending skills at once
|
||||
* Run manually to clear backlog
|
||||
@@ -672,6 +709,8 @@ export const backfillPendingScans = internalAction({
|
||||
internal.skills.getPendingScanSkillsInternal,
|
||||
{
|
||||
limit: 10000,
|
||||
exhaustive: true,
|
||||
skipRecentMinutes: 0,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -787,7 +826,7 @@ export const rescanActiveSkills = internalAction({
|
||||
`[vt:rescan] Processing batch of ${batch.skills.length} skills (cursor=${cursor}, accumulated=${accTotal})`,
|
||||
)
|
||||
|
||||
for (const { versionId, sha256hash, slug } of batch.skills) {
|
||||
for (const { versionId, sha256hash, slug, wasFlagged } of batch.skills) {
|
||||
try {
|
||||
const vtResult = await checkExistingFile(apiKey, sha256hash)
|
||||
|
||||
@@ -834,6 +873,15 @@ export const rescanActiveSkills = internalAction({
|
||||
status,
|
||||
})
|
||||
accUpdated++
|
||||
} else if (wasFlagged && status === 'clean') {
|
||||
// Verdict improved from suspicious → clean: clear the stale moderation flag
|
||||
console.log(`[vt:rescan] ${slug}: verdict improved to clean, clearing suspicious flag`)
|
||||
await ctx.runMutation(internal.skills.approveSkillByHashInternal, {
|
||||
sha256hash,
|
||||
scanner: 'vt',
|
||||
status,
|
||||
})
|
||||
accUpdated++
|
||||
} else {
|
||||
accUnchanged++
|
||||
}
|
||||
|
||||
+31
-2
@@ -18,12 +18,41 @@ OpenAPI: `/api/v1/openapi.json`
|
||||
|
||||
## Rate limits
|
||||
|
||||
Per IP + per API key:
|
||||
Auth-aware enforcement:
|
||||
|
||||
- Anonymous requests: per IP.
|
||||
- Authenticated requests (valid Bearer token): per user bucket.
|
||||
- Missing/invalid token falls back to IP enforcement.
|
||||
|
||||
- Read: 120/min per IP, 600/min per key
|
||||
- Write: 30/min per IP, 120/min per key
|
||||
|
||||
Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` (on 429).
|
||||
Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`, `Retry-After` (on 429).
|
||||
|
||||
Semantics:
|
||||
|
||||
- `X-RateLimit-Reset`: Unix epoch seconds (absolute reset time)
|
||||
- `RateLimit-Reset`: delay seconds until reset
|
||||
- `Retry-After`: delay seconds to wait on `429`
|
||||
|
||||
Example `429`:
|
||||
|
||||
```http
|
||||
HTTP/2 429
|
||||
x-ratelimit-limit: 20
|
||||
x-ratelimit-remaining: 0
|
||||
x-ratelimit-reset: 1771404540
|
||||
ratelimit-limit: 20
|
||||
ratelimit-remaining: 0
|
||||
ratelimit-reset: 34
|
||||
retry-after: 34
|
||||
```
|
||||
|
||||
Client handling:
|
||||
|
||||
- Prefer `Retry-After` when present.
|
||||
- Otherwise use `RateLimit-Reset` or derive delay from `X-RateLimit-Reset`.
|
||||
- Add jitter to retries.
|
||||
|
||||
## Endpoints
|
||||
|
||||
|
||||
+38
-4
@@ -29,6 +29,34 @@ Env equivalents:
|
||||
- `CLAWHUB_REGISTRY` (legacy `CLAWDHUB_REGISTRY`)
|
||||
- `CLAWHUB_WORKDIR` (legacy `CLAWDHUB_WORKDIR`)
|
||||
|
||||
### HTTP proxy
|
||||
|
||||
The CLI respects standard HTTP proxy environment variables for systems behind
|
||||
corporate proxies or restricted networks:
|
||||
|
||||
- `HTTPS_PROXY` / `https_proxy`
|
||||
- `HTTP_PROXY` / `http_proxy`
|
||||
- `NO_PROXY` / `no_proxy`
|
||||
|
||||
When any of these variables is set, the CLI routes outbound requests through
|
||||
the specified proxy. `HTTPS_PROXY` is used for HTTPS requests, `HTTP_PROXY`
|
||||
for plain HTTP. `NO_PROXY` / `no_proxy` is respected to bypass the proxy for
|
||||
specific hosts or domains.
|
||||
|
||||
This is required on systems where direct outbound connections are blocked
|
||||
(e.g. Docker containers, Hetzner VPS with proxy-only internet, corporate
|
||||
firewalls).
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
export HTTPS_PROXY=http://proxy.example.com:3128
|
||||
export NO_PROXY=localhost,127.0.0.1
|
||||
clawhub search "my query"
|
||||
```
|
||||
|
||||
When no proxy variable is set, behavior is unchanged (direct connections).
|
||||
|
||||
## Config file
|
||||
|
||||
Stores your API token + cached registry URL.
|
||||
@@ -86,6 +114,12 @@ Stores your API token + cached registry URL.
|
||||
- `<workdir>/.clawhub/lock.json` (legacy `.clawdhub`)
|
||||
- `<skill>/.clawhub/origin.json` (legacy `.clawdhub`)
|
||||
|
||||
### `uninstall <slug>`
|
||||
|
||||
- Removes `<workdir>/<dir>/<slug>` and deletes the lockfile entry.
|
||||
- Interactive: asks for confirmation.
|
||||
- Non-interactive (`--no-input`): requires `--yes`.
|
||||
|
||||
### `list`
|
||||
|
||||
- Reads `<workdir>/.clawhub/lock.json` (legacy `.clawdhub`).
|
||||
@@ -105,24 +139,24 @@ Stores your API token + cached registry URL.
|
||||
|
||||
### `delete <slug>`
|
||||
|
||||
- Soft-delete a skill (moderator/admin only).
|
||||
- Soft-delete a skill (owner, moderator, or admin).
|
||||
- Calls `DELETE /api/v1/skills/{slug}`.
|
||||
- `--yes` skips confirmation.
|
||||
|
||||
### `undelete <slug>`
|
||||
|
||||
- Restore a hidden skill (moderator/admin only).
|
||||
- Restore a hidden skill (owner, moderator, or admin).
|
||||
- Calls `POST /api/v1/skills/{slug}/undelete`.
|
||||
- `--yes` skips confirmation.
|
||||
|
||||
### `hide <slug>`
|
||||
|
||||
- Hide a skill (moderator/admin only).
|
||||
- Hide a skill (owner, moderator, or admin).
|
||||
- Alias for `delete`.
|
||||
|
||||
### `unhide <slug>`
|
||||
|
||||
- Unhide a skill (moderator/admin only).
|
||||
- Unhide a skill (owner, moderator, or admin).
|
||||
- Alias for `undelete`.
|
||||
|
||||
### `ban-user <handleOrId>`
|
||||
|
||||
@@ -78,3 +78,21 @@ Then:
|
||||
clawhub login --site https://<site>
|
||||
clawhub whoami
|
||||
```
|
||||
|
||||
Rate-limit sanity checks:
|
||||
|
||||
```bash
|
||||
curl -i "https://<site>/api/v1/download?slug=gifgrep"
|
||||
```
|
||||
|
||||
Confirm headers are present:
|
||||
|
||||
- `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
|
||||
- `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`
|
||||
- `Retry-After` on `429`
|
||||
|
||||
Proxy/IP caveat:
|
||||
|
||||
- Default IP source is `cf-connecting-ip`.
|
||||
- For non-Cloudflare trusted proxy setups, set `TRUST_FORWARDED_IPS=true`.
|
||||
- If proxy headers are not forwarded/trusted correctly, multiple users may collapse into one IP and hit false-positive rate limits.
|
||||
|
||||
+39
-4
@@ -15,7 +15,11 @@ OpenAPI: `/api/v1/openapi.json`.
|
||||
|
||||
## Rate limits
|
||||
|
||||
Enforced per IP + per API key:
|
||||
Enforcement model:
|
||||
|
||||
- Anonymous requests: enforced per IP.
|
||||
- Authenticated requests (valid Bearer token): enforced per user bucket.
|
||||
- If token is missing/invalid, behavior falls back to IP enforcement.
|
||||
|
||||
- Read: 120/min per IP, 600/min per key
|
||||
- Write: 30/min per IP, 120/min per key
|
||||
@@ -23,12 +27,43 @@ Enforced per IP + per API key:
|
||||
|
||||
Headers:
|
||||
|
||||
- `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` (when limited)
|
||||
- Legacy compatibility: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
|
||||
- Standardized: `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`
|
||||
- On `429`: `Retry-After`
|
||||
|
||||
Header semantics:
|
||||
|
||||
- `X-RateLimit-Reset`: absolute Unix epoch seconds
|
||||
- `RateLimit-Reset`: seconds until reset (delay)
|
||||
- `Retry-After`: seconds to wait before retry (delay) on `429`
|
||||
|
||||
Example `429` response:
|
||||
|
||||
```http
|
||||
HTTP/2 429
|
||||
content-type: text/plain; charset=utf-8
|
||||
x-ratelimit-limit: 20
|
||||
x-ratelimit-remaining: 0
|
||||
x-ratelimit-reset: 1771404540
|
||||
ratelimit-limit: 20
|
||||
ratelimit-remaining: 0
|
||||
ratelimit-reset: 34
|
||||
retry-after: 34
|
||||
|
||||
Rate limit exceeded
|
||||
```
|
||||
|
||||
Client guidance:
|
||||
|
||||
- If `Retry-After` exists, wait that many seconds before retry.
|
||||
- Use jittered backoff to avoid synchronized retries.
|
||||
- If `Retry-After` is missing, fallback to `RateLimit-Reset` (or compute from `X-RateLimit-Reset`).
|
||||
|
||||
IP source:
|
||||
|
||||
- Uses `cf-connecting-ip` (Cloudflare) for client IP by default.
|
||||
- Set `TRUST_FORWARDED_IPS=true` to opt in to `x-real-ip`, `x-forwarded-for`, or `fly-client-ip` (non-Cloudflare deployments).
|
||||
- Set `TRUST_FORWARDED_IPS=true` to opt in to `x-forwarded-for`, `x-real-ip`, or `fly-client-ip` (non-Cloudflare deployments).
|
||||
- If you run behind a reverse proxy/load balancer, ensure real client IP headers are preserved and trusted correctly, or rate limits may be too strict due to shared proxy IPs.
|
||||
|
||||
## Public endpoints (no auth)
|
||||
|
||||
@@ -154,7 +189,7 @@ Publishes a new version.
|
||||
|
||||
### `DELETE /api/v1/skills/{slug}` / `POST /api/v1/skills/{slug}/undelete`
|
||||
|
||||
Soft-delete / restore a skill (moderator/admin only).
|
||||
Soft-delete / restore a skill (owner, moderator, or admin).
|
||||
|
||||
Status codes:
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ Install a skill into `./skills/<slug>` (if Clawdbot is configured, installs into
|
||||
```bash
|
||||
bun clawhub install <slug>
|
||||
bun clawhub list
|
||||
bun clawhub uninstall <slug> --yes
|
||||
```
|
||||
|
||||
You can also install into any folder:
|
||||
|
||||
@@ -18,6 +18,35 @@ read_when:
|
||||
- Token missing or revoked: check your config file (`CLAWHUB_CONFIG_PATH` override?).
|
||||
- Ensure requests include `Authorization: Bearer ...` (CLI does this automatically).
|
||||
|
||||
## CLI/API returns `Rate limit exceeded` (429)
|
||||
|
||||
- Read headers in the response:
|
||||
- `Retry-After` = wait seconds before retry
|
||||
- `RateLimit-Remaining` + `RateLimit-Limit` = current budget
|
||||
- `RateLimit-Reset` (or `X-RateLimit-Reset`) = reset timing
|
||||
- The CLI now includes retry hints in 429 errors (retry delay + remaining budget).
|
||||
- If many users share one egress IP (NAT/proxy), IP limit can be hit even with valid tokens.
|
||||
- For non-Cloudflare deploys behind trusted proxies, set `TRUST_FORWARDED_IPS=true` so forwarded client IPs can be used.
|
||||
|
||||
## `search` / `install` fails with `fetch failed` behind a proxy
|
||||
|
||||
If your system requires an HTTP proxy for outbound connections (e.g. corporate
|
||||
firewalls, Docker containers with proxy-only internet, Hetzner VPS), the CLI
|
||||
will fail with:
|
||||
|
||||
```
|
||||
✖ fetch failed
|
||||
Error: fetch failed
|
||||
```
|
||||
|
||||
**Fix:** Set the standard proxy environment variables:
|
||||
|
||||
```bash
|
||||
export HTTPS_PROXY=http://proxy.example.com:3128
|
||||
clawhub search "my query"
|
||||
```
|
||||
|
||||
The CLI respects `HTTPS_PROXY`, `HTTP_PROXY`, `https_proxy`, and `http_proxy`.
|
||||
## `publish` fails with `OPENAI_API_KEY is not configured`
|
||||
|
||||
- Set `OPENAI_API_KEY` in the Convex environment (not only locally).
|
||||
|
||||
@@ -42,8 +42,8 @@ test('header menu routes render', async ({ page }) => {
|
||||
}
|
||||
|
||||
if (label === 'Search') {
|
||||
await expect(page).toHaveURL(/\/?(\?|$)/)
|
||||
await expect(page.locator('h1', { hasText: 'ClawHub' })).toBeVisible()
|
||||
await expect(page).toHaveURL(/\/skills(\?|$)/)
|
||||
await expect(page.locator('h1', { hasText: 'Skills' })).toBeVisible()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clawhub",
|
||||
"version": "0.6.1",
|
||||
"version": "0.7.0",
|
||||
"description": "ClawHub CLI \\u2014 install, update, search, and publish agent skills.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -14,7 +14,14 @@ import {
|
||||
import { cmdInspect } from './cli/commands/inspect.js'
|
||||
import { cmdBanUser, cmdSetRole } from './cli/commands/moderation.js'
|
||||
import { cmdPublish } from './cli/commands/publish.js'
|
||||
import { cmdExplore, cmdInstall, cmdList, cmdSearch, cmdUpdate } from './cli/commands/skills.js'
|
||||
import {
|
||||
cmdExplore,
|
||||
cmdInstall,
|
||||
cmdList,
|
||||
cmdSearch,
|
||||
cmdUninstall,
|
||||
cmdUpdate,
|
||||
} from './cli/commands/skills.js'
|
||||
import { cmdStarSkill } from './cli/commands/star.js'
|
||||
import { cmdSync } from './cli/commands/sync.js'
|
||||
import { cmdUnstarSkill } from './cli/commands/unstar.js'
|
||||
@@ -198,6 +205,16 @@ program
|
||||
await cmdUpdate(opts, slug, options, isInputAllowed())
|
||||
})
|
||||
|
||||
program
|
||||
.command('uninstall')
|
||||
.description('Uninstall a skill')
|
||||
.argument('<slug>', 'Skill slug')
|
||||
.option('--yes', 'Skip confirmation')
|
||||
.action(async (slug, options) => {
|
||||
const opts = await resolveGlobalOpts()
|
||||
await cmdUninstall(opts, slug, options, isInputAllowed())
|
||||
})
|
||||
|
||||
program
|
||||
.command('list')
|
||||
.description('List installed skills (from lockfile)')
|
||||
|
||||
@@ -3,6 +3,7 @@ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { resolveHome } from '../homedir.js'
|
||||
import { resolveClawdbotDefaultWorkspace, resolveClawdbotSkillRoots } from './clawdbotConfig.js'
|
||||
|
||||
const originalEnv = { ...process.env }
|
||||
@@ -177,6 +178,40 @@ describe('resolveClawdbotSkillRoots', () => {
|
||||
expect(labels[resolve(openclawStateDir, 'skills')]).toBe('OpenClaw: Shared skills')
|
||||
})
|
||||
|
||||
it('uses $HOME over os.homedir() for tilde expansion', async () => {
|
||||
const base = await mkdtemp(join(tmpdir(), 'clawhub-home-override-'))
|
||||
const customHome = join(base, 'custom-home')
|
||||
const stateDir = join(base, 'state')
|
||||
const configPath = join(base, 'clawdbot.json')
|
||||
const openclawStateDir = join(base, 'openclaw-state')
|
||||
|
||||
process.env.HOME = customHome
|
||||
process.env.CLAWDBOT_STATE_DIR = stateDir
|
||||
process.env.CLAWDBOT_CONFIG_PATH = configPath
|
||||
process.env.OPENCLAW_STATE_DIR = openclawStateDir
|
||||
process.env.OPENCLAW_CONFIG_PATH = join(openclawStateDir, 'openclaw.json')
|
||||
|
||||
const config = `{
|
||||
agents: {
|
||||
defaults: { workspace: "~/my-workspace" },
|
||||
},
|
||||
}`
|
||||
await writeFile(configPath, config, 'utf8')
|
||||
|
||||
const workspace = await resolveClawdbotDefaultWorkspace()
|
||||
expect(workspace).toBe(resolve(customHome, 'my-workspace'))
|
||||
expect(resolveHome()).toBe(customHome)
|
||||
})
|
||||
|
||||
it('normalizes trailing separators in $HOME', async () => {
|
||||
const base = await mkdtemp(join(tmpdir(), 'clawhub-home-trailing-'))
|
||||
const customHome = join(base, 'custom-home')
|
||||
|
||||
process.env.HOME = `${customHome}/`
|
||||
|
||||
expect(resolveHome()).toBe(customHome)
|
||||
})
|
||||
|
||||
it('supports OpenClaw configuration files', async () => {
|
||||
const base = await mkdtemp(join(tmpdir(), 'clawhub-openclaw-'))
|
||||
const stateDir = join(base, 'openclaw-state')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { basename, join, resolve } from 'node:path'
|
||||
import JSON5 from 'json5'
|
||||
import { resolveHome } from '../homedir.js'
|
||||
|
||||
type ClawdbotConfig = {
|
||||
agent?: { workspace?: string }
|
||||
@@ -95,7 +95,7 @@ export async function resolveClawdbotDefaultWorkspace(): Promise<string | null>
|
||||
function resolveClawdbotStateDir() {
|
||||
const override = process.env.CLAWDBOT_STATE_DIR?.trim()
|
||||
if (override) return resolveUserPath(override)
|
||||
return join(homedir(), '.clawdbot')
|
||||
return join(resolveHome(), '.clawdbot')
|
||||
}
|
||||
|
||||
function resolveClawdbotConfigPath() {
|
||||
@@ -107,7 +107,7 @@ function resolveClawdbotConfigPath() {
|
||||
function resolveOpenclawStateDir() {
|
||||
const override = process.env.OPENCLAW_STATE_DIR?.trim()
|
||||
if (override) return resolveUserPath(override)
|
||||
return join(homedir(), '.openclaw')
|
||||
return join(resolveHome(), '.openclaw')
|
||||
}
|
||||
|
||||
function resolveOpenclawConfigPath() {
|
||||
@@ -120,7 +120,7 @@ function resolveUserPath(input: string) {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) return ''
|
||||
if (trimmed.startsWith('~')) {
|
||||
return resolve(trimmed.replace(/^~(?=$|[\\/])/, homedir()))
|
||||
return resolve(trimmed.replace(/^~(?=$|[\\/])/, resolveHome()))
|
||||
}
|
||||
return resolve(trimmed)
|
||||
}
|
||||
|
||||
@@ -29,14 +29,16 @@ const mockSpinner = {
|
||||
isSpinning: false,
|
||||
text: '',
|
||||
}
|
||||
const mockIsInteractive = vi.fn(() => false)
|
||||
const mockPromptConfirm = vi.fn(async () => false)
|
||||
vi.mock('../ui.js', () => ({
|
||||
createSpinner: vi.fn(() => mockSpinner),
|
||||
fail: (message: string) => {
|
||||
throw new Error(message)
|
||||
},
|
||||
formatError: (error: unknown) => (error instanceof Error ? error.message : String(error)),
|
||||
isInteractive: () => false,
|
||||
promptConfirm: vi.fn(async () => false),
|
||||
isInteractive: mockIsInteractive,
|
||||
promptConfirm: mockPromptConfirm,
|
||||
}))
|
||||
|
||||
vi.mock('../../skills.js', () => ({
|
||||
@@ -55,7 +57,7 @@ vi.mock('node:fs/promises', () => ({
|
||||
stat: vi.fn(),
|
||||
}))
|
||||
|
||||
const { clampLimit, cmdExplore, cmdInstall, cmdUpdate, formatExploreLine } = await import('./skills')
|
||||
const { clampLimit, cmdExplore, cmdInstall, cmdUninstall, cmdUpdate, formatExploreLine } = await import('./skills')
|
||||
const {
|
||||
extractZipToDir,
|
||||
hashSkillFiles,
|
||||
@@ -220,3 +222,143 @@ describe('cmdInstall', () => {
|
||||
expect(zipArgs?.token).toBe('tkn')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cmdUninstall', () => {
|
||||
it('requires --yes when input is disabled', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
|
||||
await expect(cmdUninstall(makeOpts(), 'demo', {}, false)).rejects.toThrow(/--yes/i)
|
||||
})
|
||||
|
||||
it('prompts when interactive and proceeds on confirm', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
vi.mocked(writeLockfile).mockResolvedValue()
|
||||
vi.mocked(rm).mockResolvedValue()
|
||||
mockIsInteractive.mockReturnValue(true)
|
||||
mockPromptConfirm.mockResolvedValue(true)
|
||||
|
||||
await cmdUninstall(makeOpts(), 'demo', {}, true)
|
||||
|
||||
expect(mockPromptConfirm).toHaveBeenCalledWith('Uninstall demo?')
|
||||
expect(rm).toHaveBeenCalledWith('/work/skills/demo', { recursive: true, force: true })
|
||||
expect(writeLockfile).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('prints Cancelled and does not remove when prompt declines', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
mockIsInteractive.mockReturnValue(true)
|
||||
mockPromptConfirm.mockResolvedValue(false)
|
||||
|
||||
await cmdUninstall(makeOpts(), 'demo', {}, true)
|
||||
|
||||
expect(mockLog).toHaveBeenCalledWith('Cancelled.')
|
||||
expect(rm).not.toHaveBeenCalled()
|
||||
expect(writeLockfile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects unsafe slugs', async () => {
|
||||
await expect(cmdUninstall(makeOpts(), '../evil', { yes: true }, false)).rejects.toThrow(
|
||||
/invalid slug/i,
|
||||
)
|
||||
await expect(cmdUninstall(makeOpts(), 'demo/evil', { yes: true }, false)).rejects.toThrow(
|
||||
/invalid slug/i,
|
||||
)
|
||||
})
|
||||
|
||||
it('fails when skill is not installed', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({ version: 1, skills: {} })
|
||||
|
||||
await expect(cmdUninstall(makeOpts(), 'missing', {}, false)).rejects.toThrow(
|
||||
'Not installed: missing',
|
||||
)
|
||||
})
|
||||
|
||||
it('removes skill directory and lockfile entry with --yes flag', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
vi.mocked(writeLockfile).mockResolvedValue()
|
||||
vi.mocked(rm).mockResolvedValue()
|
||||
|
||||
await cmdUninstall(makeOpts(), 'demo', { yes: true }, false)
|
||||
|
||||
expect(rm).toHaveBeenCalledWith('/work/skills/demo', { recursive: true, force: true })
|
||||
expect(writeLockfile).toHaveBeenCalledWith('/work', {
|
||||
version: 1,
|
||||
skills: {},
|
||||
})
|
||||
expect(mockSpinner.succeed).toHaveBeenCalledWith('Uninstalled demo')
|
||||
})
|
||||
|
||||
it('does not update lockfile if remove fails', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
vi.mocked(rm).mockRejectedValue(new Error('nope'))
|
||||
|
||||
await expect(cmdUninstall(makeOpts(), 'demo', { yes: true }, false)).rejects.toThrow('nope')
|
||||
|
||||
expect(writeLockfile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates lockfile after removing directory', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
vi.mocked(writeLockfile).mockResolvedValue()
|
||||
vi.mocked(rm).mockResolvedValue()
|
||||
|
||||
await cmdUninstall(makeOpts(), 'demo', { yes: true }, false)
|
||||
|
||||
const rmMock = vi.mocked(rm)
|
||||
const writeLockfileMock = vi.mocked(writeLockfile)
|
||||
expect(rmMock.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
writeLockfileMock.mock.invocationCallOrder[0],
|
||||
)
|
||||
})
|
||||
|
||||
it('removes skill and updates lockfile keeping other skills', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: {
|
||||
demo: { version: '1.0.0', installedAt: 123 },
|
||||
other: { version: '2.0.0', installedAt: 456 },
|
||||
},
|
||||
})
|
||||
vi.mocked(writeLockfile).mockResolvedValue()
|
||||
vi.mocked(rm).mockResolvedValue()
|
||||
|
||||
await cmdUninstall(makeOpts(), 'demo', { yes: true }, false)
|
||||
|
||||
expect(rm).toHaveBeenCalledWith('/work/skills/demo', { recursive: true, force: true })
|
||||
expect(writeLockfile).toHaveBeenCalledWith('/work', {
|
||||
version: 1,
|
||||
skills: { other: { version: '2.0.0', installedAt: 456 } },
|
||||
})
|
||||
})
|
||||
|
||||
it('trims slug whitespace', async () => {
|
||||
vi.mocked(readLockfile).mockResolvedValue({
|
||||
version: 1,
|
||||
skills: { demo: { version: '1.0.0', installedAt: 123 } },
|
||||
})
|
||||
vi.mocked(writeLockfile).mockResolvedValue()
|
||||
vi.mocked(rm).mockResolvedValue()
|
||||
|
||||
await cmdUninstall(makeOpts(), ' demo ', { yes: true }, false)
|
||||
|
||||
expect(rm).toHaveBeenCalledWith('/work/skills/demo', { recursive: true, force: true })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -23,6 +23,20 @@ import type { GlobalOpts, ResolveResult } from '../types.js'
|
||||
import { createSpinner, fail, formatError, isInteractive, promptConfirm } from '../ui.js'
|
||||
import { getOptionalAuthToken } from '../authToken.js'
|
||||
|
||||
function normalizeSkillSlugOrFail(raw: string) {
|
||||
const slug = raw.trim()
|
||||
if (!slug) fail('Slug required')
|
||||
// Safety: never allow path traversal or nested paths to become filesystem operations.
|
||||
if (slug.includes('/') || slug.includes('\\') || slug.includes('..')) {
|
||||
fail(`Invalid slug: ${slug}`)
|
||||
}
|
||||
return slug
|
||||
}
|
||||
|
||||
function isSafeSkillSlug(slug: string) {
|
||||
return Boolean(slug) && !slug.includes('/') && !slug.includes('\\') && !slug.includes('..')
|
||||
}
|
||||
|
||||
export async function cmdSearch(opts: GlobalOpts, query: string, limit?: number) {
|
||||
if (!query) fail('Query required')
|
||||
|
||||
@@ -59,8 +73,7 @@ export async function cmdInstall(
|
||||
versionFlag?: string,
|
||||
force = false,
|
||||
) {
|
||||
const trimmed = slug.trim()
|
||||
if (!trimmed) fail('Slug required')
|
||||
const trimmed = normalizeSkillSlugOrFail(slug)
|
||||
|
||||
const token = await getOptionalAuthToken()
|
||||
|
||||
@@ -139,19 +152,19 @@ export async function cmdUpdate(
|
||||
options: { all?: boolean; version?: string; force?: boolean },
|
||||
inputAllowed: boolean,
|
||||
) {
|
||||
const slug = slugArg?.trim()
|
||||
const slug = slugArg ? normalizeSkillSlugOrFail(slugArg) : undefined
|
||||
const all = Boolean(options.all)
|
||||
if (!slug && !all) fail('Provide <slug> or --all')
|
||||
if (slug && all) fail('Use either <slug> or --all')
|
||||
if (options.version && !slug) fail('--version requires a single <slug>')
|
||||
if (options.version && !semver.valid(options.version)) fail('--version must be valid semver')
|
||||
const allowPrompt = isInteractive() && inputAllowed !== false
|
||||
const allowPrompt = isInteractive() && inputAllowed
|
||||
|
||||
const token = await getOptionalAuthToken()
|
||||
|
||||
const registry = await getRegistry(opts, { cache: true })
|
||||
const lock = await readLockfile(opts.workdir)
|
||||
const slugs = slug ? [slug] : Object.keys(lock.skills)
|
||||
const slugs = slug ? [slug] : Object.keys(lock.skills).filter(isSafeSkillSlug)
|
||||
if (slugs.length === 0) {
|
||||
console.log('No installed skills.')
|
||||
return
|
||||
@@ -295,6 +308,45 @@ export async function cmdList(opts: GlobalOpts) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function cmdUninstall(
|
||||
opts: GlobalOpts,
|
||||
slug: string,
|
||||
options: { yes?: boolean } = {},
|
||||
inputAllowed: boolean,
|
||||
) {
|
||||
const trimmed = normalizeSkillSlugOrFail(slug)
|
||||
|
||||
const lock = await readLockfile(opts.workdir)
|
||||
if (!lock.skills[trimmed]) {
|
||||
fail(`Not installed: ${trimmed}`)
|
||||
}
|
||||
|
||||
const allowPrompt = isInteractive() && inputAllowed
|
||||
if (!options.yes) {
|
||||
if (!allowPrompt) fail('Pass --yes (no input)')
|
||||
const confirm = await promptConfirm(`Uninstall ${trimmed}?`)
|
||||
if (!confirm) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const spinner = createSpinner(`Uninstalling ${trimmed}`)
|
||||
try {
|
||||
const target = join(opts.dir, trimmed)
|
||||
|
||||
await rm(target, { recursive: true, force: true })
|
||||
|
||||
delete lock.skills[trimmed]
|
||||
await writeLockfile(opts.workdir, lock)
|
||||
|
||||
spinner.succeed(`Uninstalled ${trimmed}`)
|
||||
} catch (error) {
|
||||
spinner.fail(formatError(error))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
type ExploreSort = 'newest' | 'downloads' | 'rating' | 'installs' | 'installsAllTime' | 'trending'
|
||||
type ApiExploreSort =
|
||||
| 'updated'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { realpath } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { resolve } from 'node:path'
|
||||
import { resolveHome } from '../../homedir.js'
|
||||
import { isCancel, multiselect } from '@clack/prompts'
|
||||
import semver from 'semver'
|
||||
import { apiRequest, downloadZip } from '../../http.js'
|
||||
@@ -338,7 +338,7 @@ export function printSection(title: string, body?: string) {
|
||||
}
|
||||
|
||||
function abbreviatePath(value: string) {
|
||||
const home = homedir()
|
||||
const home = resolveHome()
|
||||
if (value.startsWith(home)) return `~${value.slice(home.length)}`
|
||||
return value
|
||||
}
|
||||
@@ -348,7 +348,7 @@ function rootTelemetryId(value: string) {
|
||||
}
|
||||
|
||||
function formatRootLabel(value: string) {
|
||||
const home = homedir()
|
||||
const home = resolveHome()
|
||||
if (value === home) return '~'
|
||||
|
||||
const normalized = value.replaceAll('\\', '/')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readdir, stat } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { basename, join, resolve } from 'node:path'
|
||||
import { resolveHome } from '../homedir.js'
|
||||
import { sanitizeSlug, titleCase } from './slug.js'
|
||||
|
||||
export type SkillFolder = {
|
||||
@@ -30,7 +30,7 @@ export async function findSkillFolders(root: string): Promise<SkillFolder[]> {
|
||||
}
|
||||
|
||||
export function getFallbackSkillRoots(workdir: string) {
|
||||
const home = homedir()
|
||||
const home = resolveHome()
|
||||
const roots = [
|
||||
// adjacent repo installs
|
||||
resolve(workdir, '..', 'clawdis', 'skills'),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { resolveHome } from './homedir.js'
|
||||
import { type GlobalConfig, GlobalConfigSchema, parseArk } from './schema/index.js'
|
||||
|
||||
/**
|
||||
@@ -27,7 +27,7 @@ export function getGlobalConfigPath() {
|
||||
process.env.CLAWHUB_CONFIG_PATH?.trim() ?? process.env.CLAWDHUB_CONFIG_PATH?.trim()
|
||||
if (override) return resolve(override)
|
||||
|
||||
const home = homedir()
|
||||
const home = resolveHome()
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
return resolveConfigPath(join(home, 'Library', 'Application Support'))
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { homedir } from 'node:os'
|
||||
import { win32 } from 'node:path'
|
||||
|
||||
/**
|
||||
* Resolve the user's home directory, preferring environment variables over
|
||||
* os.homedir(). On Linux, os.homedir() reads from /etc/passwd which can
|
||||
* return a stale path after a user rename (usermod -l). The $HOME env var
|
||||
* is set by the login process and reflects the current session.
|
||||
*/
|
||||
export function resolveHome(): string {
|
||||
if (process.platform === 'win32') {
|
||||
return normalizeHome(process.env.USERPROFILE) || normalizeHome(process.env.HOME) || homedir()
|
||||
}
|
||||
return normalizeHome(process.env.HOME) || homedir()
|
||||
}
|
||||
|
||||
function normalizeHome(value: string | undefined): string {
|
||||
const trimmed = value?.trim()
|
||||
if (!trimmed) return ''
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
const root = win32.parse(trimmed).root
|
||||
if (trimmed === root) return trimmed
|
||||
return trimmed.replace(/[\\/]+$/, '')
|
||||
}
|
||||
|
||||
if (trimmed === '/') return '/'
|
||||
return trimmed.replace(/\/+$/, '')
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
/* @vitest-environment node */
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const originalBunVersion = (process.versions as Record<string, string | undefined>).bun
|
||||
|
||||
function enableBunRuntime() {
|
||||
Object.defineProperty(process.versions, 'bun', {
|
||||
value: '1.2.3',
|
||||
configurable: true,
|
||||
})
|
||||
}
|
||||
|
||||
function restoreBunRuntime() {
|
||||
if (originalBunVersion === undefined) {
|
||||
Reflect.deleteProperty(process.versions, 'bun')
|
||||
return
|
||||
}
|
||||
Object.defineProperty(process.versions, 'bun', {
|
||||
value: originalBunVersion,
|
||||
configurable: true,
|
||||
})
|
||||
}
|
||||
|
||||
function mockImmediateTimeouts() {
|
||||
const setTimeoutMock = vi.fn((callback: () => void) => {
|
||||
callback()
|
||||
return 1 as unknown as ReturnType<typeof setTimeout>
|
||||
})
|
||||
const clearTimeoutMock = vi.fn()
|
||||
vi.stubGlobal('setTimeout', setTimeoutMock as unknown as typeof setTimeout)
|
||||
vi.stubGlobal('clearTimeout', clearTimeoutMock as typeof clearTimeout)
|
||||
return { setTimeoutMock, clearTimeoutMock }
|
||||
}
|
||||
|
||||
async function loadHttpModuleWithBunMocks(opts?: {
|
||||
spawnImpl?: ReturnType<typeof vi.fn>
|
||||
mkdtempValue?: string
|
||||
readFileValue?: Buffer | null
|
||||
}) {
|
||||
const spawnSync = opts?.spawnImpl ?? vi.fn()
|
||||
const mkdtemp = vi.fn(async () => opts?.mkdtempValue ?? '/tmp/clawhub-test')
|
||||
const rm = vi.fn(async () => undefined)
|
||||
const writeFile = vi.fn(async () => undefined)
|
||||
const readFile = vi.fn(async () => opts?.readFileValue ?? Buffer.from([1, 2, 3]))
|
||||
|
||||
vi.doMock('node:child_process', () => ({ spawnSync }))
|
||||
vi.doMock('node:fs/promises', () => ({ mkdtemp, rm, writeFile, readFile }))
|
||||
|
||||
const http = await import('./http')
|
||||
return { http, spawnSync, mkdtemp, rm, writeFile, readFile }
|
||||
}
|
||||
|
||||
describe('http bun runtime', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
enableBunRuntime()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restoreBunRuntime()
|
||||
vi.doUnmock('node:child_process')
|
||||
vi.doUnmock('node:fs/promises')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('uses curl for apiRequest GET and parses JSON', async () => {
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout: '{"ok":true}\n200',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await http.apiRequest<{ ok: boolean }>('https://registry.example', {
|
||||
method: 'GET',
|
||||
path: '/v1/ping',
|
||||
token: 'clh_token',
|
||||
})
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(spawnSync).toHaveBeenCalledTimes(1)
|
||||
const [, args] = spawnSync.mock.calls[0] as [string, string[]]
|
||||
expect(args).toContain('GET')
|
||||
expect(args).toContain('https://registry.example/v1/ping')
|
||||
expect(args).toContain('Accept: application/json')
|
||||
expect(args).toContain('Authorization: Bearer clh_token')
|
||||
})
|
||||
|
||||
it('uses curl for apiRequest POST with json body', async () => {
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout: '{"ok":true}\n200',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
|
||||
await http.apiRequest('https://registry.example', {
|
||||
method: 'POST',
|
||||
path: '/v1/ping',
|
||||
body: { a: 1 },
|
||||
})
|
||||
|
||||
const [, args] = spawnSync.mock.calls[0] as [string, string[]]
|
||||
expect(args).toContain('Content-Type: application/json')
|
||||
expect(args).toContain('--data-binary')
|
||||
expect(args).toContain('{"a":1}')
|
||||
})
|
||||
|
||||
it('retries bun apiRequest on 429 errors', async () => {
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout: 'rate limited\n429',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
|
||||
await expect(
|
||||
http.apiRequest('https://registry.example', {
|
||||
method: 'GET',
|
||||
path: '/v1/ping',
|
||||
}),
|
||||
).rejects.toThrow('rate limited')
|
||||
|
||||
expect(spawnSync).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('includes rate-limit guidance from curl metadata on 429', async () => {
|
||||
mockImmediateTimeouts()
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout:
|
||||
'rate limited\n__CLAWHUB_CURL_META__\n429\n20\n0\n1771404540\n20\n0\n34\n34\n',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
|
||||
await expect(
|
||||
http.apiRequest('https://registry.example', {
|
||||
method: 'GET',
|
||||
path: '/v1/ping',
|
||||
}),
|
||||
).rejects.toThrow(/retry in 34s.*remaining: 0\/20.*reset in 34s/i)
|
||||
|
||||
expect(spawnSync).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('does not retry bun apiRequest on 404 errors', async () => {
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout: 'missing\n404',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
|
||||
await expect(
|
||||
http.apiRequest('https://registry.example', {
|
||||
method: 'GET',
|
||||
path: '/v1/ping',
|
||||
}),
|
||||
).rejects.toThrow('missing')
|
||||
|
||||
expect(spawnSync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('supports fetchText bun path and propagates status fallback', async () => {
|
||||
const spawnSync = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce({
|
||||
status: 0,
|
||||
stdout: 'hello world\n200',
|
||||
stderr: '',
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
status: 0,
|
||||
stdout: '\n400',
|
||||
stderr: '',
|
||||
})
|
||||
const { http } = await loadHttpModuleWithBunMocks({ spawnImpl: spawnSync })
|
||||
|
||||
const text = await http.fetchText('https://registry.example', { path: '/v1/readme' })
|
||||
expect(text).toBe('hello world')
|
||||
|
||||
await expect(
|
||||
http.fetchText('https://registry.example', { path: '/v1/readme' }),
|
||||
).rejects.toThrow('HTTP 400')
|
||||
})
|
||||
|
||||
it('handles downloadZip bun path and cleans up temp dir', async () => {
|
||||
const spawnSync = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce({
|
||||
status: 0,
|
||||
stdout: '200',
|
||||
stderr: '',
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
status: 0,
|
||||
stdout: '404',
|
||||
stderr: '',
|
||||
})
|
||||
const { http, rm, readFile } = await loadHttpModuleWithBunMocks({
|
||||
spawnImpl: spawnSync,
|
||||
mkdtempValue: '/tmp/clawhub-download-abc',
|
||||
readFileValue: Buffer.from('not found'),
|
||||
})
|
||||
|
||||
const bytes = await http.downloadZip('https://registry.example', { slug: 'demo', token: 't' })
|
||||
expect(Array.from(bytes)).toEqual(Array.from(Buffer.from('not found')))
|
||||
|
||||
await expect(
|
||||
http.downloadZip('https://registry.example', { slug: 'demo', token: 't' }),
|
||||
).rejects.toThrow('not found')
|
||||
|
||||
expect(readFile).toHaveBeenCalled()
|
||||
expect(rm).toHaveBeenCalledWith('/tmp/clawhub-download-abc', {
|
||||
recursive: true,
|
||||
force: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('posts multipart form via curl in bun path', async () => {
|
||||
const spawnSync = vi.fn().mockReturnValue({
|
||||
status: 0,
|
||||
stdout: '{"ok":true}\n200',
|
||||
stderr: '',
|
||||
})
|
||||
const { http, writeFile, rm } = await loadHttpModuleWithBunMocks({
|
||||
spawnImpl: spawnSync,
|
||||
mkdtempValue: '/tmp/clawhub-upload-abc',
|
||||
})
|
||||
|
||||
const form = new FormData()
|
||||
form.append('name', 'demo')
|
||||
form.append('file', new Blob(['abc'], { type: 'text/plain' }), 'demo.txt')
|
||||
|
||||
const result = await http.apiRequestForm<{ ok: boolean }>('https://registry.example', {
|
||||
method: 'POST',
|
||||
path: '/upload',
|
||||
form,
|
||||
})
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(writeFile).toHaveBeenCalled()
|
||||
expect(rm).toHaveBeenCalledWith('/tmp/clawhub-upload-abc', { recursive: true, force: true })
|
||||
const [, args] = spawnSync.mock.calls[0] as [string, string[]]
|
||||
expect(args).toContain('-F')
|
||||
expect(args.some((arg) => arg.includes('name=demo'))).toBe(true)
|
||||
expect(args.some((arg) => arg.includes('file=@/tmp/clawhub-upload-abc/demo.txt'))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
/* @vitest-environment node */
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { apiRequest, apiRequestForm, downloadZip, fetchText } from './http'
|
||||
import { apiRequest, apiRequestForm, downloadZip, fetchText, shouldUseProxyFromEnv } from './http'
|
||||
import { ApiV1WhoamiResponseSchema } from './schema/index.js'
|
||||
|
||||
function mockImmediateTimeouts() {
|
||||
@@ -36,6 +36,35 @@ function createAbortingFetchMock() {
|
||||
})
|
||||
}
|
||||
|
||||
describe('shouldUseProxyFromEnv', () => {
|
||||
it('detects standard proxy variables', () => {
|
||||
expect(
|
||||
shouldUseProxyFromEnv({
|
||||
HTTPS_PROXY: 'http://proxy.example:3128',
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe(true)
|
||||
expect(
|
||||
shouldUseProxyFromEnv({
|
||||
HTTP_PROXY: 'http://proxy.example:3128',
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe(true)
|
||||
expect(
|
||||
shouldUseProxyFromEnv({
|
||||
https_proxy: 'http://proxy.example:3128',
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores NO_PROXY-only configs', () => {
|
||||
expect(
|
||||
shouldUseProxyFromEnv({
|
||||
NO_PROXY: 'localhost,127.0.0.1',
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe(false)
|
||||
expect(shouldUseProxyFromEnv({} as NodeJS.ProcessEnv)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('apiRequest', () => {
|
||||
it('adds bearer token and parses json', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
@@ -86,6 +115,50 @@ describe('apiRequest', () => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('includes rate-limit guidance from headers on 429', async () => {
|
||||
mockImmediateTimeouts()
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 429,
|
||||
headers: new Headers({
|
||||
'Retry-After': '34',
|
||||
'X-RateLimit-Limit': '20',
|
||||
'X-RateLimit-Remaining': '0',
|
||||
'X-RateLimit-Reset': '1771404540',
|
||||
}),
|
||||
text: async () => 'Rate limit exceeded',
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await expect(apiRequest('https://example.com', { method: 'GET', path: '/x' })).rejects.toThrow(
|
||||
/retry in 34s.*remaining: 0\/20.*reset in 34s/i,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('interprets legacy epoch Retry-After values as reset delays', async () => {
|
||||
mockImmediateTimeouts()
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1_771_404_500_000)
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 429,
|
||||
headers: new Headers({
|
||||
'Retry-After': '1771404540',
|
||||
'X-RateLimit-Limit': '20',
|
||||
'X-RateLimit-Remaining': '0',
|
||||
}),
|
||||
text: async () => 'Rate limit exceeded',
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await expect(apiRequest('https://example.com', { method: 'GET', path: '/x' })).rejects.toThrow(
|
||||
/retry in 40s.*remaining: 0\/20/i,
|
||||
)
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('falls back to HTTP status when body is empty', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
|
||||
+267
-50
@@ -3,20 +3,45 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import pRetry, { AbortError } from 'p-retry'
|
||||
import { Agent, setGlobalDispatcher } from 'undici'
|
||||
import { Agent, EnvHttpProxyAgent, setGlobalDispatcher } from 'undici'
|
||||
import type { ArkValidator } from './schema/index.js'
|
||||
import { ApiRoutes, parseArk } from './schema/index.js'
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_SECONDS = Math.ceil(REQUEST_TIMEOUT_MS / 1000)
|
||||
const RETRY_COUNT = 2
|
||||
const RETRY_BACKOFF_BASE_MS = 300
|
||||
const RETRY_BACKOFF_MAX_MS = 5_000
|
||||
const RETRY_AFTER_JITTER_MS = 250
|
||||
const CURL_META_MARKER = '__CLAWHUB_CURL_META__'
|
||||
const CURL_WRITE_OUT_FORMAT = [
|
||||
'',
|
||||
CURL_META_MARKER,
|
||||
'%{http_code}',
|
||||
'%{header:x-ratelimit-limit}',
|
||||
'%{header:x-ratelimit-remaining}',
|
||||
'%{header:x-ratelimit-reset}',
|
||||
'%{header:ratelimit-limit}',
|
||||
'%{header:ratelimit-remaining}',
|
||||
'%{header:ratelimit-reset}',
|
||||
'%{header:retry-after}',
|
||||
].join('\n')
|
||||
const isBun = typeof process !== 'undefined' && Boolean(process.versions?.bun)
|
||||
|
||||
export function shouldUseProxyFromEnv(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return Boolean(env.HTTPS_PROXY || env.HTTP_PROXY || env.https_proxy || env.http_proxy)
|
||||
}
|
||||
|
||||
if (typeof process !== 'undefined' && process.versions?.node) {
|
||||
try {
|
||||
setGlobalDispatcher(
|
||||
new Agent({
|
||||
connect: { timeout: REQUEST_TIMEOUT_MS },
|
||||
}),
|
||||
shouldUseProxyFromEnv(process.env)
|
||||
? new EnvHttpProxyAgent({
|
||||
connect: { timeout: REQUEST_TIMEOUT_MS },
|
||||
})
|
||||
: new Agent({
|
||||
connect: { timeout: REQUEST_TIMEOUT_MS },
|
||||
}),
|
||||
)
|
||||
} catch {
|
||||
// ignore dispatcher setup failures in non-node runtimes
|
||||
@@ -27,6 +52,27 @@ type RequestArgs =
|
||||
| { method: 'GET' | 'POST' | 'DELETE'; path: string; token?: string; body?: unknown }
|
||||
| { method: 'GET' | 'POST' | 'DELETE'; url: string; token?: string; body?: unknown }
|
||||
|
||||
type HeaderSource = Headers | Record<string, string> | null | undefined
|
||||
|
||||
type RateLimitInfo = {
|
||||
limit?: number
|
||||
remaining?: number
|
||||
resetDelaySeconds?: number
|
||||
retryAfterSeconds?: number
|
||||
}
|
||||
|
||||
class HttpStatusError extends Error {
|
||||
readonly status: number
|
||||
readonly rateLimit: RateLimitInfo
|
||||
|
||||
constructor(status: number, message: string, rateLimit: RateLimitInfo) {
|
||||
super(message)
|
||||
this.name = 'HttpStatusError'
|
||||
this.status = status
|
||||
this.rateLimit = rateLimit
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(registry: string, args: RequestArgs): Promise<T>
|
||||
export async function apiRequest<T>(
|
||||
registry: string,
|
||||
@@ -39,7 +85,7 @@ export async function apiRequest<T>(
|
||||
schema?: ArkValidator<T>,
|
||||
): Promise<T> {
|
||||
const url = 'url' in args ? args.url : new URL(args.path, registry).toString()
|
||||
const json = await pRetry(
|
||||
const json = await runWithRetries(
|
||||
async () => {
|
||||
if (isBun) {
|
||||
return await fetchJsonViaCurl(url, args)
|
||||
@@ -58,11 +104,10 @@ export async function apiRequest<T>(
|
||||
body,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response))
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response), response.headers)
|
||||
}
|
||||
return (await response.json()) as unknown
|
||||
},
|
||||
{ retries: 2 },
|
||||
)
|
||||
if (schema) return parseArk(schema, json, 'API response')
|
||||
return json as T
|
||||
@@ -84,7 +129,7 @@ export async function apiRequestForm<T>(
|
||||
schema?: ArkValidator<T>,
|
||||
): Promise<T> {
|
||||
const url = 'url' in args ? args.url : new URL(args.path, registry).toString()
|
||||
const json = await pRetry(
|
||||
const json = await runWithRetries(
|
||||
async () => {
|
||||
if (isBun) {
|
||||
return await fetchJsonFormViaCurl(url, args)
|
||||
@@ -98,11 +143,10 @@ export async function apiRequestForm<T>(
|
||||
body: args.form,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response))
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response), response.headers)
|
||||
}
|
||||
return (await response.json()) as unknown
|
||||
},
|
||||
{ retries: 2 },
|
||||
)
|
||||
if (schema) return parseArk(schema, json, 'API response')
|
||||
return json as T
|
||||
@@ -112,7 +156,7 @@ type TextRequestArgs = { path: string; token?: string } | { url: string; token?:
|
||||
|
||||
export async function fetchText(registry: string, args: TextRequestArgs): Promise<string> {
|
||||
const url = 'url' in args ? args.url : new URL(args.path, registry).toString()
|
||||
return pRetry(
|
||||
return runWithRetries(
|
||||
async () => {
|
||||
if (isBun) {
|
||||
return await fetchTextViaCurl(url, args)
|
||||
@@ -123,11 +167,10 @@ export async function fetchText(registry: string, args: TextRequestArgs): Promis
|
||||
const response = await fetchWithTimeout(url, { method: 'GET', headers })
|
||||
const text = await response.text()
|
||||
if (!response.ok) {
|
||||
throwHttpStatusError(response.status, text)
|
||||
throwHttpStatusError(response.status, text, response.headers)
|
||||
}
|
||||
return text
|
||||
},
|
||||
{ retries: 2 },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -138,7 +181,7 @@ export async function downloadZip(
|
||||
const url = new URL(ApiRoutes.download, registry)
|
||||
url.searchParams.set('slug', args.slug)
|
||||
if (args.version) url.searchParams.set('version', args.version)
|
||||
return pRetry(
|
||||
return runWithRetries(
|
||||
async () => {
|
||||
if (isBun) {
|
||||
return await fetchBinaryViaCurl(url.toString(), args.token)
|
||||
@@ -149,11 +192,10 @@ export async function downloadZip(
|
||||
|
||||
const response = await fetchWithTimeout(url.toString(), { method: 'GET', headers })
|
||||
if (!response.ok) {
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response))
|
||||
throwHttpStatusError(response.status, await readResponseTextSafe(response), response.headers)
|
||||
}
|
||||
return new Uint8Array(await response.arrayBuffer())
|
||||
},
|
||||
{ retries: 2 },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -171,14 +213,152 @@ async function readResponseTextSafe(response: Response): Promise<string> {
|
||||
return await response.text().catch(() => '')
|
||||
}
|
||||
|
||||
function throwHttpStatusError(status: number, text: string): never {
|
||||
const message = text || `HTTP ${status}`
|
||||
async function runWithRetries<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return await pRetry(fn, {
|
||||
retries: RETRY_COUNT,
|
||||
minTimeout: 0,
|
||||
maxTimeout: 0,
|
||||
factor: 1,
|
||||
randomize: false,
|
||||
onFailedAttempt: async (attemptError) => {
|
||||
const delayMs = getRetryDelayMs(attemptError)
|
||||
if (delayMs <= 0) return
|
||||
await sleep(delayMs)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function getRetryDelayMs(attemptError: unknown): number {
|
||||
const failed = attemptError as {
|
||||
attemptNumber?: number
|
||||
cause?: unknown
|
||||
error?: unknown
|
||||
}
|
||||
const attemptNumber = Math.max(1, Number(failed.attemptNumber ?? 1))
|
||||
const rootError = failed.cause ?? failed.error ?? attemptError
|
||||
if (rootError instanceof HttpStatusError && rootError.rateLimit.retryAfterSeconds !== undefined) {
|
||||
return rootError.rateLimit.retryAfterSeconds * 1000 + jitterMs(RETRY_AFTER_JITTER_MS)
|
||||
}
|
||||
const baseMs = Math.min(RETRY_BACKOFF_MAX_MS, RETRY_BACKOFF_BASE_MS * 2 ** (attemptNumber - 1))
|
||||
return baseMs + jitterMs(RETRY_BACKOFF_BASE_MS)
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
function jitterMs(maxMs: number): number {
|
||||
if (maxMs <= 0) return 0
|
||||
return Math.floor(Math.random() * maxMs)
|
||||
}
|
||||
|
||||
function throwHttpStatusError(status: number, text: string, headers?: HeaderSource): never {
|
||||
const rateLimit = parseRateLimitInfo(headers)
|
||||
const message = buildHttpErrorMessage(status, text, rateLimit)
|
||||
if (status === 429 || status >= 500) {
|
||||
throw new Error(message)
|
||||
throw new HttpStatusError(status, message, rateLimit)
|
||||
}
|
||||
throw new AbortError(message)
|
||||
}
|
||||
|
||||
function buildHttpErrorMessage(status: number, text: string, rateLimit: RateLimitInfo): string {
|
||||
const base = text || `HTTP ${status}`
|
||||
const details: string[] = []
|
||||
if (rateLimit.retryAfterSeconds !== undefined) {
|
||||
details.push(`retry in ${rateLimit.retryAfterSeconds}s`)
|
||||
}
|
||||
if (rateLimit.remaining !== undefined && rateLimit.limit !== undefined) {
|
||||
details.push(`remaining: ${rateLimit.remaining}/${rateLimit.limit}`)
|
||||
}
|
||||
if (rateLimit.resetDelaySeconds !== undefined) {
|
||||
details.push(`reset in ${rateLimit.resetDelaySeconds}s`)
|
||||
}
|
||||
if (details.length === 0) {
|
||||
return base
|
||||
}
|
||||
return `${base} (${details.join(', ')})`
|
||||
}
|
||||
|
||||
function parseRateLimitInfo(headers?: HeaderSource): RateLimitInfo {
|
||||
if (!headers) return {}
|
||||
const limit = parseIntHeader(getHeader(headers, 'x-ratelimit-limit') ?? getHeader(headers, 'ratelimit-limit'))
|
||||
const remaining = parseIntHeader(
|
||||
getHeader(headers, 'x-ratelimit-remaining') ?? getHeader(headers, 'ratelimit-remaining'),
|
||||
)
|
||||
const nowMs = Date.now()
|
||||
const retryAfterSeconds = parseRetryAfterSeconds(getHeader(headers, 'retry-after'), nowMs)
|
||||
const resetDelaySeconds = parseResetDelaySeconds(headers, nowMs, retryAfterSeconds)
|
||||
|
||||
return {
|
||||
limit,
|
||||
remaining,
|
||||
resetDelaySeconds,
|
||||
retryAfterSeconds,
|
||||
}
|
||||
}
|
||||
|
||||
function parseResetDelaySeconds(
|
||||
headers: HeaderSource,
|
||||
nowMs: number,
|
||||
retryAfterSeconds: number | undefined,
|
||||
): number | undefined {
|
||||
if (retryAfterSeconds !== undefined) return retryAfterSeconds
|
||||
|
||||
const standardized = parseIntHeader(getHeader(headers, 'ratelimit-reset'))
|
||||
if (standardized !== undefined) {
|
||||
return Math.max(1, standardized)
|
||||
}
|
||||
const legacyEpochSeconds = parseIntHeader(getHeader(headers, 'x-ratelimit-reset'))
|
||||
if (legacyEpochSeconds === undefined) return undefined
|
||||
const nowSeconds = Math.floor(nowMs / 1000)
|
||||
return Math.max(1, legacyEpochSeconds - nowSeconds)
|
||||
}
|
||||
|
||||
function parseRetryAfterSeconds(value: string | undefined, nowMs: number): number | undefined {
|
||||
if (!value) return undefined
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return undefined
|
||||
|
||||
const asNumber = Number(trimmed)
|
||||
if (Number.isFinite(asNumber) && asNumber >= 0) {
|
||||
// Compatibility guard for older servers that accidentally sent Unix epoch seconds.
|
||||
if (asNumber > 31_536_000) {
|
||||
const nowSeconds = Math.floor(nowMs / 1000)
|
||||
return Math.max(1, Math.ceil(asNumber - nowSeconds))
|
||||
}
|
||||
return Math.max(1, Math.ceil(asNumber))
|
||||
}
|
||||
|
||||
const asDateMs = Date.parse(trimmed)
|
||||
if (!Number.isFinite(asDateMs)) return undefined
|
||||
return Math.max(1, Math.ceil((asDateMs - nowMs) / 1000))
|
||||
}
|
||||
|
||||
function parseIntHeader(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
if (!Number.isFinite(parsed)) return undefined
|
||||
return parsed
|
||||
}
|
||||
|
||||
function getHeader(headers: HeaderSource, key: string): string | undefined {
|
||||
if (!headers) return undefined
|
||||
if (headers instanceof Headers) {
|
||||
const value = headers.get(key)
|
||||
return value === null ? undefined : value
|
||||
}
|
||||
const normalizedKey = key.toLowerCase()
|
||||
const direct = headers[normalizedKey] ?? headers[key]
|
||||
if (typeof direct === 'string' && direct.trim()) return direct.trim()
|
||||
const match = Object.entries(headers).find(
|
||||
([entryKey, entryValue]) =>
|
||||
entryKey.toLowerCase() === normalizedKey && typeof entryValue === 'string' && entryValue.trim(),
|
||||
)
|
||||
return typeof match?.[1] === 'string' ? match[1].trim() : undefined
|
||||
}
|
||||
|
||||
async function fetchJsonViaCurl(url: string, args: RequestArgs) {
|
||||
const headers = ['-H', 'Accept: application/json']
|
||||
if (args.token) {
|
||||
@@ -191,7 +371,7 @@ async function fetchJsonViaCurl(url: string, args: RequestArgs) {
|
||||
'--max-time',
|
||||
String(REQUEST_TIMEOUT_SECONDS),
|
||||
'--write-out',
|
||||
'\n%{http_code}',
|
||||
CURL_WRITE_OUT_FORMAT,
|
||||
'-X',
|
||||
args.method,
|
||||
...headers,
|
||||
@@ -206,14 +386,9 @@ async function fetchJsonViaCurl(url: string, args: RequestArgs) {
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || 'curl failed')
|
||||
}
|
||||
const output = result.stdout ?? ''
|
||||
const splitAt = output.lastIndexOf('\n')
|
||||
if (splitAt === -1) throw new Error('curl response missing status')
|
||||
const body = output.slice(0, splitAt)
|
||||
const status = Number(output.slice(splitAt + 1).trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
const { body, status, headers: responseHeaders } = parseCurlBodyAndMeta(result.stdout ?? '')
|
||||
if (status < 200 || status >= 300) {
|
||||
throwHttpStatusError(status, body)
|
||||
throwHttpStatusError(status, body, responseHeaders)
|
||||
}
|
||||
return JSON.parse(body || 'null') as unknown
|
||||
}
|
||||
@@ -246,7 +421,7 @@ async function fetchJsonFormViaCurl(url: string, args: FormRequestArgs) {
|
||||
'--max-time',
|
||||
String(REQUEST_TIMEOUT_SECONDS),
|
||||
'--write-out',
|
||||
'\n%{http_code}',
|
||||
CURL_WRITE_OUT_FORMAT,
|
||||
'-X',
|
||||
args.method,
|
||||
...headers,
|
||||
@@ -258,14 +433,9 @@ async function fetchJsonFormViaCurl(url: string, args: FormRequestArgs) {
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || 'curl failed')
|
||||
}
|
||||
const output = result.stdout ?? ''
|
||||
const splitAt = output.lastIndexOf('\n')
|
||||
if (splitAt === -1) throw new Error('curl response missing status')
|
||||
const body = output.slice(0, splitAt)
|
||||
const status = Number(output.slice(splitAt + 1).trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
const { body, status, headers: responseHeaders } = parseCurlBodyAndMeta(result.stdout ?? '')
|
||||
if (status < 200 || status >= 300) {
|
||||
throwHttpStatusError(status, body)
|
||||
throwHttpStatusError(status, body, responseHeaders)
|
||||
}
|
||||
return JSON.parse(body || 'null') as unknown
|
||||
} finally {
|
||||
@@ -285,7 +455,7 @@ async function fetchTextViaCurl(url: string, args: { token?: string }) {
|
||||
'--max-time',
|
||||
String(REQUEST_TIMEOUT_SECONDS),
|
||||
'--write-out',
|
||||
'\n%{http_code}',
|
||||
CURL_WRITE_OUT_FORMAT,
|
||||
'-X',
|
||||
'GET',
|
||||
...headers,
|
||||
@@ -295,17 +465,9 @@ async function fetchTextViaCurl(url: string, args: { token?: string }) {
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || 'curl failed')
|
||||
}
|
||||
const output = result.stdout ?? ''
|
||||
const splitAt = output.lastIndexOf('\n')
|
||||
if (splitAt === -1) throw new Error('curl response missing status')
|
||||
const body = output.slice(0, splitAt)
|
||||
const status = Number(output.slice(splitAt + 1).trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
const { body, status, headers: responseHeaders } = parseCurlBodyAndMeta(result.stdout ?? '')
|
||||
if (status < 200 || status >= 300) {
|
||||
if (status === 429 || status >= 500) {
|
||||
throw new Error(body || `HTTP ${status}`)
|
||||
}
|
||||
throw new AbortError(body || `HTTP ${status}`)
|
||||
throwHttpStatusError(status, body, responseHeaders)
|
||||
}
|
||||
return body
|
||||
}
|
||||
@@ -329,18 +491,17 @@ async function fetchBinaryViaCurl(url: string, token?: string) {
|
||||
'-o',
|
||||
filePath,
|
||||
'--write-out',
|
||||
'%{http_code}',
|
||||
CURL_WRITE_OUT_FORMAT,
|
||||
url,
|
||||
]
|
||||
const result = spawnSync('curl', curlArgs, { encoding: 'utf8' })
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || 'curl failed')
|
||||
}
|
||||
const status = Number((result.stdout ?? '').trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
const { status, headers: responseHeaders } = parseCurlBodyAndMeta(result.stdout ?? '')
|
||||
if (status < 200 || status >= 300) {
|
||||
const body = await readFileSafe(filePath)
|
||||
throwHttpStatusError(status, body ? new TextDecoder().decode(body) : '')
|
||||
throwHttpStatusError(status, body ? new TextDecoder().decode(body) : '', responseHeaders)
|
||||
}
|
||||
const bytes = await readFileSafe(filePath)
|
||||
return bytes ? new Uint8Array(bytes) : new Uint8Array()
|
||||
@@ -349,6 +510,62 @@ async function fetchBinaryViaCurl(url: string, token?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseCurlBodyAndMeta(output: string): {
|
||||
body: string
|
||||
status: number
|
||||
headers: Record<string, string>
|
||||
} {
|
||||
const marker = `\n${CURL_META_MARKER}\n`
|
||||
const markerIndex = output.lastIndexOf(marker)
|
||||
if (markerIndex === -1) {
|
||||
// Backward compatibility for older tests that only provide "<body>\n<status>".
|
||||
const splitAt = output.lastIndexOf('\n')
|
||||
if (splitAt === -1) {
|
||||
const statusOnly = Number(output.trim())
|
||||
if (!Number.isFinite(statusOnly)) throw new Error('curl response missing status')
|
||||
return { body: '', status: statusOnly, headers: {} }
|
||||
}
|
||||
const body = output.slice(0, splitAt)
|
||||
const status = Number(output.slice(splitAt + 1).trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
return { body, status, headers: {} }
|
||||
}
|
||||
|
||||
const body = output.slice(0, markerIndex)
|
||||
const meta = output.slice(markerIndex + marker.length).replace(/\r/g, '')
|
||||
const lines = meta.split('\n')
|
||||
const status = Number((lines[0] ?? '').trim())
|
||||
if (!Number.isFinite(status)) throw new Error('curl response missing status')
|
||||
|
||||
const [
|
||||
xRateLimitLimit,
|
||||
xRateLimitRemaining,
|
||||
xRateLimitReset,
|
||||
rateLimitLimit,
|
||||
rateLimitRemaining,
|
||||
rateLimitReset,
|
||||
retryAfter,
|
||||
] = lines.slice(1)
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
setHeaderIfPresent(headers, 'x-ratelimit-limit', xRateLimitLimit)
|
||||
setHeaderIfPresent(headers, 'x-ratelimit-remaining', xRateLimitRemaining)
|
||||
setHeaderIfPresent(headers, 'x-ratelimit-reset', xRateLimitReset)
|
||||
setHeaderIfPresent(headers, 'ratelimit-limit', rateLimitLimit)
|
||||
setHeaderIfPresent(headers, 'ratelimit-remaining', rateLimitRemaining)
|
||||
setHeaderIfPresent(headers, 'ratelimit-reset', rateLimitReset)
|
||||
setHeaderIfPresent(headers, 'retry-after', retryAfter)
|
||||
|
||||
return { body, status, headers }
|
||||
}
|
||||
|
||||
function setHeaderIfPresent(headers: Record<string, string>, key: string, value: string | undefined) {
|
||||
if (typeof value !== 'string') return
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return
|
||||
headers[key] = trimmed
|
||||
}
|
||||
|
||||
async function readFileSafe(path: string) {
|
||||
try {
|
||||
const { readFile } = await import('node:fs/promises')
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
export const convexReactMocks = {
|
||||
useAction: vi.fn(),
|
||||
useQuery: vi.fn(),
|
||||
usePaginatedQuery: vi.fn(),
|
||||
}
|
||||
|
||||
export function resetConvexReactMocks() {
|
||||
convexReactMocks.useAction.mockReset()
|
||||
convexReactMocks.useQuery.mockReset()
|
||||
convexReactMocks.usePaginatedQuery.mockReset()
|
||||
}
|
||||
|
||||
export function setupDefaultConvexReactMocks() {
|
||||
convexReactMocks.useAction.mockReturnValue(() => Promise.resolve([]))
|
||||
convexReactMocks.useQuery.mockReturnValue(null)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
import { SkillDetailPage } from '../components/SkillDetailPage'
|
||||
|
||||
const navigateMock = vi.fn()
|
||||
@@ -130,4 +129,57 @@ describe('SkillDetailPage', () => {
|
||||
expect(await screen.findByRole('dialog')).toBeTruthy()
|
||||
expect(screen.getByText(/Report skill/i)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('defers compare version query until compare tab is requested', async () => {
|
||||
useQueryMock.mockImplementation((_fn: unknown, args: unknown) => {
|
||||
if (args === 'skip') return undefined
|
||||
if (args && typeof args === 'object' && 'limit' in args) {
|
||||
return []
|
||||
}
|
||||
if (args && typeof args === 'object' && 'skillId' in args) return []
|
||||
if (args && typeof args === 'object' && 'slug' in args) {
|
||||
return {
|
||||
skill: {
|
||||
_id: 'skills:1',
|
||||
slug: 'weather',
|
||||
displayName: 'Weather',
|
||||
summary: 'Get current weather.',
|
||||
ownerUserId: 'users:1',
|
||||
tags: {},
|
||||
stats: { stars: 0, downloads: 0 },
|
||||
},
|
||||
owner: { handle: 'steipete', name: 'Peter' },
|
||||
latestVersion: { _id: 'skillVersions:1', version: '1.0.0', parsed: {}, files: [] },
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
|
||||
render(<SkillDetailPage slug="weather" />)
|
||||
expect(await screen.findByText('Weather')).toBeTruthy()
|
||||
|
||||
expect(
|
||||
useQueryMock.mock.calls.some(
|
||||
([, args]: [unknown, unknown]) =>
|
||||
typeof args === 'object' &&
|
||||
args !== null &&
|
||||
'limit' in args &&
|
||||
(args as { limit: number }).limit === 200,
|
||||
),
|
||||
).toBe(false)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /compare/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
useQueryMock.mock.calls.some(
|
||||
([, args]: [unknown, unknown]) =>
|
||||
typeof args === 'object' &&
|
||||
args !== null &&
|
||||
'limit' in args &&
|
||||
(args as { limit: number }).limit === 200,
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
import { act, render } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
convexReactMocks,
|
||||
resetConvexReactMocks,
|
||||
setupDefaultConvexReactMocks,
|
||||
} from './helpers/convexReactMocks'
|
||||
|
||||
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', () => ({
|
||||
@@ -20,17 +23,17 @@ vi.mock('@tanstack/react-router', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('convex/react', () => ({
|
||||
useAction: (...args: unknown[]) => useActionMock(...args),
|
||||
usePaginatedQuery: (...args: unknown[]) => usePaginatedQueryMock(...args),
|
||||
useAction: (...args: unknown[]) => convexReactMocks.useAction(...args),
|
||||
useQuery: (...args: unknown[]) => convexReactMocks.useQuery(...args),
|
||||
usePaginatedQuery: (...args: unknown[]) => convexReactMocks.usePaginatedQuery(...args),
|
||||
}))
|
||||
|
||||
describe('SkillsIndex load-more observer', () => {
|
||||
beforeEach(() => {
|
||||
usePaginatedQueryMock.mockReset()
|
||||
useActionMock.mockReset()
|
||||
resetConvexReactMocks()
|
||||
navigateMock.mockReset()
|
||||
searchMock = {}
|
||||
useActionMock.mockReturnValue(() => Promise.resolve([]))
|
||||
setupDefaultConvexReactMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -39,7 +42,7 @@ describe('SkillsIndex load-more observer', () => {
|
||||
|
||||
it('triggers one request for repeated intersection callbacks', async () => {
|
||||
const loadMorePaginated = vi.fn()
|
||||
usePaginatedQueryMock.mockReturnValue({
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [makeListResult('skill-0', 'Skill 0')],
|
||||
status: 'CanLoadMore',
|
||||
loadMore: loadMorePaginated,
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
convexReactMocks,
|
||||
resetConvexReactMocks,
|
||||
setupDefaultConvexReactMocks,
|
||||
} from './helpers/convexReactMocks'
|
||||
|
||||
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', () => ({
|
||||
@@ -20,19 +23,19 @@ vi.mock('@tanstack/react-router', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('convex/react', () => ({
|
||||
useAction: (...args: unknown[]) => useActionMock(...args),
|
||||
usePaginatedQuery: (...args: unknown[]) => usePaginatedQueryMock(...args),
|
||||
useAction: (...args: unknown[]) => convexReactMocks.useAction(...args),
|
||||
useQuery: (...args: unknown[]) => convexReactMocks.useQuery(...args),
|
||||
usePaginatedQuery: (...args: unknown[]) => convexReactMocks.usePaginatedQuery(...args),
|
||||
}))
|
||||
|
||||
describe('SkillsIndex', () => {
|
||||
beforeEach(() => {
|
||||
usePaginatedQueryMock.mockReset()
|
||||
useActionMock.mockReset()
|
||||
resetConvexReactMocks()
|
||||
navigateMock.mockReset()
|
||||
searchMock = {}
|
||||
useActionMock.mockReturnValue(() => Promise.resolve([]))
|
||||
setupDefaultConvexReactMocks()
|
||||
// Default: return empty results with Exhausted status
|
||||
usePaginatedQueryMock.mockReturnValue({
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [],
|
||||
status: 'Exhausted',
|
||||
loadMore: vi.fn(),
|
||||
@@ -47,9 +50,9 @@ describe('SkillsIndex', () => {
|
||||
it('requests the first skills page', () => {
|
||||
render(<SkillsIndex />)
|
||||
// usePaginatedQuery should be called with the API endpoint and sort/dir args
|
||||
expect(usePaginatedQueryMock).toHaveBeenCalledWith(
|
||||
expect(convexReactMocks.usePaginatedQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ sort: 'downloads', dir: 'desc', nonSuspiciousOnly: false },
|
||||
{ sort: 'downloads', dir: 'desc', highlightedOnly: false, nonSuspiciousOnly: false },
|
||||
{ initialNumItems: 25 },
|
||||
)
|
||||
})
|
||||
@@ -59,16 +62,100 @@ describe('SkillsIndex', () => {
|
||||
expect(screen.getByText('No skills match that filter.')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows loading state instead of empty state when pagination is not exhausted', () => {
|
||||
// When status is not 'Exhausted', we should show loading, not "No skills match"
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [],
|
||||
status: 'CanLoadMore',
|
||||
loadMore: vi.fn(),
|
||||
})
|
||||
render(<SkillsIndex />)
|
||||
expect(screen.getByText('Loading skills…')).toBeTruthy()
|
||||
expect(screen.queryByText('No skills match that filter.')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps load-more reachable when results are empty but pagination can continue', () => {
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [],
|
||||
status: 'CanLoadMore',
|
||||
loadMore: vi.fn(),
|
||||
})
|
||||
render(<SkillsIndex />)
|
||||
expect(screen.getByRole('button', { name: 'Load more' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows loading indicator during pagination instead of hiding load more', () => {
|
||||
// When status is 'LoadingMore', keep showing the load more area with loading text
|
||||
const mockEntry = {
|
||||
skill: {
|
||||
_id: 'test-id',
|
||||
slug: 'test-skill',
|
||||
displayName: 'Test Skill',
|
||||
stats: { downloads: 0, installsAllTime: 0, stars: 0 },
|
||||
},
|
||||
latestVersion: null,
|
||||
owner: null,
|
||||
ownerHandle: null,
|
||||
}
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [mockEntry],
|
||||
status: 'LoadingMore',
|
||||
loadMore: vi.fn(),
|
||||
})
|
||||
render(<SkillsIndex />)
|
||||
// The load more button should still be visible with loading state
|
||||
expect(screen.getByText('Loading…')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('handles LoadingMore with empty results gracefully', () => {
|
||||
// Edge case: user changes filter while loading more, results become empty
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [],
|
||||
status: 'LoadingMore',
|
||||
loadMore: vi.fn(),
|
||||
})
|
||||
render(<SkillsIndex />)
|
||||
// Should show loading message, not "No skills match"
|
||||
expect(screen.getByText('Loading skills…')).toBeTruthy()
|
||||
expect(screen.queryByText('No skills match that filter.')).toBeNull()
|
||||
// Keep the pagination control mounted so loading can continue.
|
||||
expect(screen.getByText('Loading…')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows empty state immediately when search returns no results', async () => {
|
||||
// When searching and results are empty, show "No skills match" not "Loading"
|
||||
// This tests the hasQuery condition in the empty state logic
|
||||
searchMock = { q: 'nonexistent-skill-xyz' }
|
||||
const actionFn = vi.fn().mockResolvedValue([])
|
||||
convexReactMocks.useAction.mockReturnValue(actionFn)
|
||||
// Pagination is skipped in search mode, so status stays 'LoadingFirstPage'
|
||||
convexReactMocks.usePaginatedQuery.mockReturnValue({
|
||||
results: [],
|
||||
status: 'LoadingFirstPage',
|
||||
loadMore: vi.fn(),
|
||||
})
|
||||
vi.useFakeTimers()
|
||||
|
||||
render(<SkillsIndex />)
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync()
|
||||
})
|
||||
|
||||
// Should show empty state, not loading
|
||||
expect(screen.getByText('No skills match that filter.')).toBeTruthy()
|
||||
expect(screen.queryByText('Loading skills…')).toBeNull()
|
||||
})
|
||||
|
||||
it('skips list query and calls search when query is set', async () => {
|
||||
searchMock = { q: 'remind' }
|
||||
const actionFn = vi.fn().mockResolvedValue([])
|
||||
useActionMock.mockReturnValue(actionFn)
|
||||
convexReactMocks.useAction.mockReturnValue(actionFn)
|
||||
vi.useFakeTimers()
|
||||
|
||||
render(<SkillsIndex />)
|
||||
|
||||
// usePaginatedQuery should be called with 'skip' when there's a search query
|
||||
expect(usePaginatedQueryMock).toHaveBeenCalledWith(expect.anything(), 'skip', {
|
||||
expect(convexReactMocks.usePaginatedQuery).toHaveBeenCalledWith(expect.anything(), 'skip', {
|
||||
initialNumItems: 25,
|
||||
})
|
||||
await act(async () => {
|
||||
@@ -98,7 +185,7 @@ describe('SkillsIndex', () => {
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeSearchResults(25))
|
||||
.mockResolvedValueOnce(makeSearchResults(50))
|
||||
useActionMock.mockReturnValue(actionFn)
|
||||
convexReactMocks.useAction.mockReturnValue(actionFn)
|
||||
vi.useFakeTimers()
|
||||
|
||||
render(<SkillsIndex />)
|
||||
@@ -129,7 +216,7 @@ describe('SkillsIndex', () => {
|
||||
makeSearchEntry({ slug: 'skill-b', displayName: 'Skill B', stars: 5, updatedAt: 200 }),
|
||||
makeSearchEntry({ slug: 'skill-c', displayName: 'Skill C', stars: 4, updatedAt: 999 }),
|
||||
])
|
||||
useActionMock.mockReturnValue(actionFn)
|
||||
convexReactMocks.useAction.mockReturnValue(actionFn)
|
||||
vi.useFakeTimers()
|
||||
|
||||
render(<SkillsIndex />)
|
||||
@@ -154,7 +241,7 @@ describe('SkillsIndex', () => {
|
||||
makeSearchResult('newer-low-score', 'Newer Low Score', 0.1, 2000),
|
||||
makeSearchResult('older-high-score', 'Older High Score', 0.9, 1000),
|
||||
])
|
||||
useActionMock.mockReturnValue(actionFn)
|
||||
convexReactMocks.useAction.mockReturnValue(actionFn)
|
||||
vi.useFakeTimers()
|
||||
|
||||
render(<SkillsIndex />)
|
||||
@@ -174,9 +261,20 @@ describe('SkillsIndex', () => {
|
||||
searchMock = { nonSuspicious: true }
|
||||
render(<SkillsIndex />)
|
||||
|
||||
expect(usePaginatedQueryMock).toHaveBeenCalledWith(
|
||||
expect(convexReactMocks.usePaginatedQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ sort: 'downloads', dir: 'desc', nonSuspiciousOnly: true },
|
||||
{ sort: 'downloads', dir: 'desc', highlightedOnly: false, nonSuspiciousOnly: true },
|
||||
{ initialNumItems: 25 },
|
||||
)
|
||||
})
|
||||
|
||||
it('passes highlightedOnly to list query when filter is active', () => {
|
||||
searchMock = { highlighted: true }
|
||||
render(<SkillsIndex />)
|
||||
|
||||
expect(convexReactMocks.usePaginatedQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ sort: 'downloads', dir: 'desc', highlightedOnly: true, nonSuspiciousOnly: false },
|
||||
{ initialNumItems: 25 },
|
||||
)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useMutation, useQuery } from 'convex/react'
|
||||
import { useState } from 'react'
|
||||
import { api } from '../../convex/_generated/api'
|
||||
import type { Doc, Id } from '../../convex/_generated/dataModel'
|
||||
import { isModerator } from '../lib/roles'
|
||||
|
||||
type SkillCommentsPanelProps = {
|
||||
skillId: Id<'skills'>
|
||||
isAuthenticated: boolean
|
||||
me: Doc<'users'> | null
|
||||
}
|
||||
|
||||
export function SkillCommentsPanel({ skillId, isAuthenticated, me }: SkillCommentsPanelProps) {
|
||||
const addComment = useMutation(api.comments.add)
|
||||
const removeComment = useMutation(api.comments.remove)
|
||||
const [comment, setComment] = useState('')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [submitError, setSubmitError] = useState<string | null>(null)
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null)
|
||||
const [deletingCommentId, setDeletingCommentId] = useState<Id<'comments'> | null>(null)
|
||||
const comments = useQuery(api.comments.listBySkill, { skillId, limit: 50 })
|
||||
|
||||
const submitComment = async () => {
|
||||
const body = comment.trim()
|
||||
if (!body || isSubmitting) return
|
||||
setIsSubmitting(true)
|
||||
setSubmitError(null)
|
||||
try {
|
||||
await addComment({ skillId, body })
|
||||
setComment('')
|
||||
} catch (error) {
|
||||
setSubmitError(error instanceof Error ? error.message : 'Failed to post comment')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteComment = async (commentId: Id<'comments'>) => {
|
||||
if (deletingCommentId) return
|
||||
setDeleteError(null)
|
||||
setDeletingCommentId(commentId)
|
||||
try {
|
||||
await removeComment({ commentId })
|
||||
} catch (error) {
|
||||
setDeleteError(error instanceof Error ? error.message : 'Failed to delete comment')
|
||||
} finally {
|
||||
setDeletingCommentId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h2 className="section-title" style={{ fontSize: '1.2rem', margin: 0 }}>
|
||||
Comments
|
||||
</h2>
|
||||
{isAuthenticated ? (
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void submitComment()
|
||||
}}
|
||||
className="comment-form"
|
||||
>
|
||||
<textarea
|
||||
className="comment-input"
|
||||
rows={4}
|
||||
value={comment}
|
||||
onChange={(event) => setComment(event.target.value)}
|
||||
placeholder="Leave a note…"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{submitError ? <div className="report-dialog-error">{submitError}</div> : null}
|
||||
<button className="btn comment-submit" type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Posting…' : 'Post comment'}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="section-subtitle">Sign in to comment.</p>
|
||||
)}
|
||||
{deleteError ? <div className="report-dialog-error">{deleteError}</div> : null}
|
||||
<div style={{ display: 'grid', gap: 12, marginTop: 16 }}>
|
||||
{(comments ?? []).length === 0 ? (
|
||||
<div className="stat">No comments yet.</div>
|
||||
) : (
|
||||
(comments ?? []).map((entry) => (
|
||||
<div key={entry.comment._id} className="comment-item">
|
||||
<div className="comment-body">
|
||||
<strong>@{entry.user?.handle ?? entry.user?.name ?? 'user'}</strong>
|
||||
<div className="comment-body-text">{entry.comment.body}</div>
|
||||
</div>
|
||||
{isAuthenticated && me && (me._id === entry.comment.userId || isModerator(me)) ? (
|
||||
<button
|
||||
className="btn comment-delete"
|
||||
type="button"
|
||||
onClick={() => void deleteComment(entry.comment._id)}
|
||||
disabled={Boolean(deletingCommentId) || isSubmitting}
|
||||
>
|
||||
{deletingCommentId === entry.comment._id ? 'Deleting…' : 'Delete'}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+164
-1104
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Doc, Id } from '../../convex/_generated/dataModel'
|
||||
import { SkillFilesPanel } from './SkillFilesPanel'
|
||||
|
||||
const getFileTextMock = vi.fn()
|
||||
|
||||
vi.mock('convex/react', () => ({
|
||||
useAction: () => getFileTextMock,
|
||||
}))
|
||||
|
||||
vi.mock('react-markdown', () => ({
|
||||
default: ({ children }: { children: string }) => <div>{children}</div>,
|
||||
}))
|
||||
|
||||
vi.mock('remark-gfm', () => ({
|
||||
default: {},
|
||||
}))
|
||||
|
||||
type SkillFile = Doc<'skillVersions'>['files'][number]
|
||||
|
||||
function makeFile(path: string, size: number): SkillFile {
|
||||
return { path, size } as unknown as SkillFile
|
||||
}
|
||||
|
||||
describe('SkillFilesPanel', () => {
|
||||
beforeEach(() => {
|
||||
getFileTextMock.mockReset()
|
||||
})
|
||||
|
||||
it('caches loaded files and avoids duplicate fetches', async () => {
|
||||
getFileTextMock.mockResolvedValue({
|
||||
text: 'echo hello',
|
||||
size: 10,
|
||||
sha256: 'a'.repeat(64),
|
||||
})
|
||||
|
||||
render(
|
||||
<SkillFilesPanel
|
||||
versionId={'skillVersions:1' as Id<'skillVersions'>}
|
||||
readmeContent={'# skill'}
|
||||
readmeError={null}
|
||||
latestFiles={[makeFile('scripts/run.sh', 10)]}
|
||||
/>,
|
||||
)
|
||||
|
||||
const fileButton = screen.getByRole('button', { name: /scripts\/run\.sh/i })
|
||||
fireEvent.click(fileButton)
|
||||
|
||||
await screen.findByText('echo hello')
|
||||
|
||||
fireEvent.click(fileButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getFileTextMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores stale responses when newer file selection is active', async () => {
|
||||
const resolvers: Record<string, (value: { text: string; size: number; sha256: string }) => void> = {}
|
||||
|
||||
getFileTextMock.mockImplementation(
|
||||
({ path }: { path: string }) =>
|
||||
new Promise<{ text: string; size: number; sha256: string }>((resolve) => {
|
||||
resolvers[path] = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
render(
|
||||
<SkillFilesPanel
|
||||
versionId={'skillVersions:1' as Id<'skillVersions'>}
|
||||
readmeContent={'# skill'}
|
||||
readmeError={null}
|
||||
latestFiles={[makeFile('a.txt', 5), makeFile('b.txt', 6)]}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /a\.txt/i }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /b\.txt/i }))
|
||||
|
||||
resolvers['a.txt']({ text: 'alpha', size: 5, sha256: 'b'.repeat(64) })
|
||||
resolvers['b.txt']({ text: 'beta', size: 6, sha256: 'c'.repeat(64) })
|
||||
|
||||
await screen.findByText('beta')
|
||||
expect(screen.queryByText('alpha')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import type { ClawdisSkillMetadata } from 'clawhub-schema'
|
||||
import { Package } from 'lucide-react'
|
||||
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} · <Package size={14} aria-hidden="true" />{' '}
|
||||
{formattedStats.downloads} · {formatCompactStat(skill.stats.installsCurrent ?? 0)} current
|
||||
installs · {formattedStats.installsAllTime} all-time installs
|
||||
</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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { ClawdisSkillMetadata } from 'clawhub-schema'
|
||||
import { formatInstallCommand, formatInstallLabel } from './skillDetailUtils'
|
||||
|
||||
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
|
||||
|
||||
if (!hasRuntimeRequirements && !hasInstallSpecs) return null
|
||||
|
||||
return (
|
||||
<div className="skill-hero-content">
|
||||
<div className="skill-hero-panels">
|
||||
{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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
type SkillReportDialogProps = {
|
||||
isOpen: boolean
|
||||
isSubmitting: boolean
|
||||
reportReason: string
|
||||
reportError: string | null
|
||||
onReasonChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSubmit: () => void
|
||||
}
|
||||
|
||||
export function SkillReportDialog({
|
||||
isOpen,
|
||||
isSubmitting,
|
||||
reportReason,
|
||||
reportError,
|
||||
onReasonChange,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}: SkillReportDialogProps) {
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="report-dialog-backdrop">
|
||||
<div className="report-dialog" role="dialog" aria-modal="true" aria-labelledby="report-title">
|
||||
<h2 id="report-title" className="section-title" style={{ margin: 0, fontSize: '1.1rem' }}>
|
||||
Report skill
|
||||
</h2>
|
||||
<p className="section-subtitle" style={{ margin: 0 }}>
|
||||
Describe the issue so moderators can review it quickly.
|
||||
</p>
|
||||
<form
|
||||
className="report-dialog-form"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
onSubmit()
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
className="report-dialog-textarea"
|
||||
aria-label="Report reason"
|
||||
placeholder="What should moderators know?"
|
||||
value={reportReason}
|
||||
onChange={(event) => onReasonChange(event.target.value)}
|
||||
rows={5}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{reportError ? <p className="report-dialog-error">{reportError}</p> : null}
|
||||
<div className="report-dialog-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => {
|
||||
if (!isSubmitting) onCancel()
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" className="btn" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Submitting…' : 'Submit report'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Package } from 'lucide-react'
|
||||
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} · <Package size={13} aria-hidden="true" /> {formatted.downloads}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function SkillMetricsRow({ stats }: { stats: SkillMetricsStats }) {
|
||||
const formatted = formatSkillStatsTriplet(stats)
|
||||
return (
|
||||
<>
|
||||
<span>
|
||||
<Package size={13} aria-hidden="true" /> {formatted.downloads}
|
||||
</span>
|
||||
<span>★ {formatted.stars}</span>
|
||||
<span>{stats.versions} v</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Doc } from '../../convex/_generated/dataModel'
|
||||
import { type LlmAnalysis, SecurityScanResults } from './SkillSecurityScanResults'
|
||||
|
||||
type SkillVersionsPanelProps = {
|
||||
versions: Doc<'skillVersions'>[] | undefined
|
||||
nixPlugin: boolean
|
||||
skillSlug: string
|
||||
}
|
||||
|
||||
export function SkillVersionsPanel({ versions, nixPlugin, skillSlug }: SkillVersionsPanelProps) {
|
||||
return (
|
||||
<div className="tab-body">
|
||||
<div>
|
||||
<h2 className="section-title" style={{ fontSize: '1.2rem', margin: 0 }}>
|
||||
Versions
|
||||
</h2>
|
||||
<p className="section-subtitle" style={{ margin: 0 }}>
|
||||
{nixPlugin
|
||||
? 'Review release history and changelog.'
|
||||
: 'Download older releases or scan the changelog.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="version-scroll">
|
||||
<div className="version-list">
|
||||
{(versions ?? []).map((version) => (
|
||||
<div key={version._id} className="version-row">
|
||||
<div className="version-info">
|
||||
<div>
|
||||
v{version.version} · {new Date(version.createdAt).toLocaleDateString()}
|
||||
{version.changelogSource === 'auto' ? (
|
||||
<span style={{ color: 'var(--ink-soft)' }}> · auto</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div style={{ color: '#5c554e', whiteSpace: 'pre-wrap' }}>{version.changelog}</div>
|
||||
<div className="version-scan-results">
|
||||
{version.sha256hash || version.llmAnalysis ? (
|
||||
<SecurityScanResults
|
||||
sha256hash={version.sha256hash}
|
||||
vtAnalysis={version.vtAnalysis}
|
||||
llmAnalysis={version.llmAnalysis as LlmAnalysis | undefined}
|
||||
variant="badge"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{!nixPlugin ? (
|
||||
<div className="version-actions">
|
||||
<a
|
||||
className="btn version-zip"
|
||||
href={`${import.meta.env.VITE_CONVEX_SITE_URL}/api/v1/download?slug=${skillSlug}&version=${version.version}`}
|
||||
>
|
||||
Zip
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { api } from '../../convex/_generated/api'
|
||||
import type { Doc } from '../../convex/_generated/dataModel'
|
||||
import { SoulStatsTripletLine } from './SoulStats'
|
||||
import type { PublicSoul, PublicUser } from '../lib/publicUser'
|
||||
import { isModerator } from '../lib/roles'
|
||||
import { useAuthStatus } from '../lib/useAuthStatus'
|
||||
import { stripFrontmatter } from './skillDetailUtils'
|
||||
|
||||
type SoulDetailPageProps = {
|
||||
slug: string
|
||||
@@ -113,7 +115,7 @@ export function SoulDetailPage({ slug }: SoulDetailPageProps) {
|
||||
</h1>
|
||||
<p className="section-subtitle">{soul.summary ?? 'No summary provided.'}</p>
|
||||
<div className="stat">
|
||||
⭐ {soul.stats.stars} · ⤓ {soul.stats.downloads} · {soul.stats.versions} versions
|
||||
<SoulStatsTripletLine stats={soul.stats} versionSuffix="versions" />
|
||||
</div>
|
||||
{ownerHandle ? (
|
||||
<div className="stat">
|
||||
@@ -253,11 +255,3 @@ export function SoulDetailPage({ slug }: SoulDetailPageProps) {
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function stripFrontmatter(content: string) {
|
||||
const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
if (!normalized.startsWith('---')) return content
|
||||
const endIndex = normalized.indexOf('\n---', 3)
|
||||
if (endIndex === -1) return content
|
||||
return normalized.slice(endIndex + 4).replace(/^\n+/, '')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Package } from 'lucide-react'
|
||||
import { formatSoulStatsTriplet, type SoulStatsTriplet } from '../lib/numberFormat'
|
||||
|
||||
export function SoulStatsTripletLine({
|
||||
stats,
|
||||
versionSuffix = 'v',
|
||||
}: {
|
||||
stats: SoulStatsTriplet
|
||||
versionSuffix?: 'v' | 'versions'
|
||||
}) {
|
||||
const formatted = formatSoulStatsTriplet(stats)
|
||||
return (
|
||||
<>
|
||||
⭐ {formatted.stars} · <Package size={13} aria-hidden="true" /> {formatted.downloads} ·{' '}
|
||||
{formatted.versions} {versionSuffix}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function SoulMetricsRow({ stats }: { stats: SoulStatsTriplet }) {
|
||||
const formatted = formatSoulStatsTriplet(stats)
|
||||
return (
|
||||
<>
|
||||
<span>
|
||||
<Package size={13} aria-hidden="true" /> {formatted.downloads}
|
||||
</span>
|
||||
<span>★ {formatted.stars}</span>
|
||||
<span>{formatted.versions} v</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { SkillInstallSpec } from 'clawhub-schema'
|
||||
import type { Id } from '../../convex/_generated/dataModel'
|
||||
|
||||
export function buildSkillHref(ownerHandle: string | null, ownerId: Id<'users'> | null, slug: string) {
|
||||
const owner = ownerHandle?.trim() || (ownerId ? String(ownerId) : 'unknown')
|
||||
return `/${owner}/${slug}`
|
||||
}
|
||||
|
||||
export function formatConfigSnippet(raw: string) {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed || raw.includes('\n')) return raw
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
return JSON.stringify(parsed, null, 2)
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
|
||||
let out = ''
|
||||
let indent = 0
|
||||
let inString = false
|
||||
let isEscaped = false
|
||||
|
||||
const newline = () => {
|
||||
out = out.replace(/[ \t]+$/u, '')
|
||||
out += `\n${' '.repeat(indent * 2)}`
|
||||
}
|
||||
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const ch = raw[i]
|
||||
if (inString) {
|
||||
out += ch
|
||||
if (isEscaped) {
|
||||
isEscaped = false
|
||||
} else if (ch === '\\') {
|
||||
isEscaped = true
|
||||
} else if (ch === '"') {
|
||||
inString = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '"') {
|
||||
inString = true
|
||||
out += ch
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '{' || ch === '[') {
|
||||
out += ch
|
||||
indent += 1
|
||||
newline()
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '}' || ch === ']') {
|
||||
indent = Math.max(0, indent - 1)
|
||||
newline()
|
||||
out += ch
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === ';' || ch === ',') {
|
||||
out += ch
|
||||
newline()
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '\n' || ch === '\r' || ch === '\t') {
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === ' ') {
|
||||
if (out.endsWith(' ') || out.endsWith('\n')) {
|
||||
continue
|
||||
}
|
||||
out += ' '
|
||||
continue
|
||||
}
|
||||
|
||||
out += ch
|
||||
}
|
||||
|
||||
return out.trim()
|
||||
}
|
||||
|
||||
export function stripFrontmatter(content: string) {
|
||||
const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
if (!normalized.startsWith('---')) return content
|
||||
const endIndex = normalized.indexOf('\n---', 3)
|
||||
if (endIndex === -1) return content
|
||||
return normalized.slice(endIndex + 4).replace(/^\n+/, '')
|
||||
}
|
||||
|
||||
export function formatOsList(os?: string[]) {
|
||||
if (!os?.length) return []
|
||||
return os.map((entry) => {
|
||||
const key = entry.trim().toLowerCase()
|
||||
if (key === 'darwin' || key === 'macos' || key === 'mac') return 'macOS'
|
||||
if (key === 'linux') return 'Linux'
|
||||
if (key === 'windows' || key === 'win32') return 'Windows'
|
||||
return entry
|
||||
})
|
||||
}
|
||||
|
||||
export function formatInstallLabel(spec: SkillInstallSpec) {
|
||||
if (spec.kind === 'brew') return 'Homebrew'
|
||||
if (spec.kind === 'node') return 'Node'
|
||||
if (spec.kind === 'go') return 'Go'
|
||||
if (spec.kind === 'uv') return 'uv'
|
||||
return 'Install'
|
||||
}
|
||||
|
||||
export function formatInstallCommand(spec: SkillInstallSpec) {
|
||||
if (spec.kind === 'brew' && spec.formula) {
|
||||
if (spec.tap && !spec.formula.includes('/')) {
|
||||
return `brew install ${spec.tap}/${spec.formula}`
|
||||
}
|
||||
return `brew install ${spec.formula}`
|
||||
}
|
||||
if (spec.kind === 'node' && spec.package) {
|
||||
return `npm i -g ${spec.package}`
|
||||
}
|
||||
if (spec.kind === 'go' && spec.module) {
|
||||
return `go install ${spec.module}`
|
||||
}
|
||||
if (spec.kind === 'uv' && spec.package) {
|
||||
return `uv tool install ${spec.package}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number) {
|
||||
if (!Number.isFinite(bytes)) return '—'
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
const units = ['KB', 'MB', 'GB']
|
||||
let value = bytes / 1024
|
||||
let unitIndex = 0
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024
|
||||
unitIndex += 1
|
||||
}
|
||||
return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unitIndex]}`
|
||||
}
|
||||
|
||||
export function formatNixInstallSnippet(plugin: string) {
|
||||
const snippet = `programs.clawdbot.plugins = [ { source = "${plugin}"; } ];`
|
||||
return formatConfigSnippet(snippet)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
formatCompactStat,
|
||||
formatSkillStatsTriplet,
|
||||
formatSoulStatsTriplet,
|
||||
type SkillStatsTriplet,
|
||||
type SoulStatsTriplet,
|
||||
} from './numberFormat'
|
||||
|
||||
describe('formatCompactStat', () => {
|
||||
it('keeps small values as whole numbers', () => {
|
||||
expect(formatCompactStat(0)).toBe('0')
|
||||
expect(formatCompactStat(999)).toBe('999')
|
||||
})
|
||||
|
||||
it('formats thousands with lowercase k', () => {
|
||||
expect(formatCompactStat(1_000)).toBe('1k')
|
||||
expect(formatCompactStat(1_250)).toBe('1.3k')
|
||||
expect(formatCompactStat(23_683)).toBe('23.7k')
|
||||
expect(formatCompactStat(236_830)).toBe('237k')
|
||||
})
|
||||
|
||||
it('formats millions with uppercase M', () => {
|
||||
expect(formatCompactStat(1_000_000)).toBe('1M')
|
||||
expect(formatCompactStat(2_360_000)).toBe('2.4M')
|
||||
expect(formatCompactStat(23_683_000)).toBe('23.7M')
|
||||
})
|
||||
|
||||
it('carries rounded thousands into millions', () => {
|
||||
expect(formatCompactStat(999_499)).toBe('999k')
|
||||
expect(formatCompactStat(999_500)).toBe('1M')
|
||||
expect(formatCompactStat(999_949)).toBe('1M')
|
||||
expect(formatCompactStat(-999_499)).toBe('-999k')
|
||||
expect(formatCompactStat(-999_500)).toBe('-1M')
|
||||
expect(formatCompactStat(-999_949)).toBe('-1M')
|
||||
})
|
||||
|
||||
it('preserves sign for negative values', () => {
|
||||
expect(formatCompactStat(-1_500)).toBe('-1.5k')
|
||||
expect(formatCompactStat(-2_500_000)).toBe('-2.5M')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stats triplet formatters', () => {
|
||||
it('formats skill triplet consistently', () => {
|
||||
const stats: SkillStatsTriplet = { stars: 12_340, downloads: 23_683, installsAllTime: 1_045_000 }
|
||||
|
||||
expect(formatSkillStatsTriplet(stats)).toEqual({
|
||||
stars: '12.3k',
|
||||
downloads: '23.7k',
|
||||
installsAllTime: '1M',
|
||||
})
|
||||
})
|
||||
|
||||
it('formats soul triplet consistently', () => {
|
||||
const stats: SoulStatsTriplet = { stars: 3_540, downloads: 78_010, versions: 4 }
|
||||
|
||||
expect(formatSoulStatsTriplet(stats)).toEqual({
|
||||
stars: '3.5k',
|
||||
downloads: '78k',
|
||||
versions: 4,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
export type SkillStatsTriplet = {
|
||||
stars: number
|
||||
downloads: number
|
||||
installsAllTime?: number | null
|
||||
}
|
||||
|
||||
export type SoulStatsTriplet = {
|
||||
stars: number
|
||||
downloads: number
|
||||
versions: number
|
||||
}
|
||||
|
||||
const THOUSAND = 1_000
|
||||
const MILLION = 1_000_000
|
||||
|
||||
export function formatCompactStat(value: number): string {
|
||||
if (!Number.isFinite(value)) return '0'
|
||||
const sign = value < 0 ? '-' : ''
|
||||
const absolute = Math.abs(value)
|
||||
|
||||
if (absolute < THOUSAND) {
|
||||
return `${Math.round(value)}`
|
||||
}
|
||||
|
||||
if (absolute < MILLION) {
|
||||
const { formatted, rounded } = formatUnit(absolute / THOUSAND)
|
||||
if (rounded >= THOUSAND) {
|
||||
return `${sign}1M`
|
||||
}
|
||||
return `${sign}${formatted}k`
|
||||
}
|
||||
|
||||
return `${sign}${formatUnit(absolute / MILLION).formatted}M`
|
||||
}
|
||||
|
||||
export function formatSkillStatsTriplet(stats: SkillStatsTriplet) {
|
||||
return {
|
||||
stars: formatCompactStat(stats.stars),
|
||||
downloads: formatCompactStat(stats.downloads),
|
||||
installsAllTime: formatCompactStat(stats.installsAllTime ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSoulStatsTriplet(stats: SoulStatsTriplet) {
|
||||
return {
|
||||
stars: formatCompactStat(stats.stars),
|
||||
downloads: formatCompactStat(stats.downloads),
|
||||
versions: stats.versions,
|
||||
}
|
||||
}
|
||||
|
||||
function formatUnit(scaled: number): { formatted: string; rounded: number } {
|
||||
const decimals = scaled < 100 ? 1 : 0
|
||||
const factor = 10 ** decimals
|
||||
const rounded = Math.round(scaled * factor) / factor
|
||||
return {
|
||||
formatted: stripTrailingZero(rounded.toFixed(decimals)),
|
||||
rounded,
|
||||
}
|
||||
}
|
||||
|
||||
function stripTrailingZero(value: string): string {
|
||||
return value.replace(/\.0$/, '')
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useQuery } from 'convex/react'
|
||||
import { Clock, Package, Plus, Upload } from 'lucide-react'
|
||||
import { api } from '../../convex/_generated/api'
|
||||
import type { Doc } from '../../convex/_generated/dataModel'
|
||||
import { formatCompactStat } from '../lib/numberFormat'
|
||||
import type { PublicSkill } from '../lib/publicUser'
|
||||
|
||||
type DashboardSkill = PublicSkill & { pendingReview?: boolean }
|
||||
@@ -84,8 +85,10 @@ function SkillCard({ skill, ownerHandle }: { skill: DashboardSkill; ownerHandle:
|
||||
</div>
|
||||
{skill.summary && <p className="dashboard-skill-description">{skill.summary}</p>}
|
||||
<div className="dashboard-skill-stats">
|
||||
<span>⤓ {skill.stats.downloads}</span>
|
||||
<span>★ {skill.stats.stars}</span>
|
||||
<span>
|
||||
<Package size={13} aria-hidden="true" /> {formatCompactStat(skill.stats.downloads)}
|
||||
</span>
|
||||
<span>★ {formatCompactStat(skill.stats.stars)}</span>
|
||||
<span>{skill.stats.versions} v</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,9 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { api } from '../../convex/_generated/api'
|
||||
import { InstallSwitcher } from '../components/InstallSwitcher'
|
||||
import { SkillCard } from '../components/SkillCard'
|
||||
import { SkillStatsTripletLine } from '../components/SkillStats'
|
||||
import { SoulCard } from '../components/SoulCard'
|
||||
import { SoulStatsTripletLine } from '../components/SoulStats'
|
||||
import { UserBadge } from '../components/UserBadge'
|
||||
import { getSkillBadges } from '../lib/badges'
|
||||
import type { PublicSkill, PublicSoul, PublicUser } from '../lib/publicUser'
|
||||
@@ -100,8 +102,7 @@ function SkillsHome() {
|
||||
link={false}
|
||||
/>
|
||||
<div className="stat">
|
||||
⭐ {entry.skill.stats.stars} · ⤓ {entry.skill.stats.downloads} · ⤒{' '}
|
||||
{entry.skill.stats.installsAllTime ?? 0}
|
||||
<SkillStatsTripletLine stats={entry.skill.stats} />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -132,8 +133,7 @@ function SkillsHome() {
|
||||
link={false}
|
||||
/>
|
||||
<div className="stat">
|
||||
⭐ {entry.skill.stats.stars} · ⤓ {entry.skill.stats.downloads} · ⤒{' '}
|
||||
{entry.skill.stats.installsAllTime ?? 0}
|
||||
<SkillStatsTripletLine stats={entry.skill.stats} />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -253,7 +253,7 @@ function OnlyCrabsHome() {
|
||||
summaryFallback="A SOUL.md bundle."
|
||||
meta={
|
||||
<div className="stat">
|
||||
⭐ {soul.stats.stars} · ⤓ {soul.stats.downloads} · {soul.stats.versions} v
|
||||
<SoulStatsTripletLine stats={soul.stats} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
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 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)}
|
||||
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 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>
|
||||
))}
|
||||
</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>
|
||||
</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}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export const sortKeys = [
|
||||
'relevance',
|
||||
'newest',
|
||||
'downloads',
|
||||
'installs',
|
||||
'stars',
|
||||
'name',
|
||||
'updated',
|
||||
] as const
|
||||
|
||||
export type SortKey = (typeof sortKeys)[number]
|
||||
export type ListSortKey = Exclude<SortKey, 'relevance'>
|
||||
export type SortDir = 'asc' | 'desc'
|
||||
|
||||
export function parseSort(value: unknown): SortKey {
|
||||
if (typeof value !== 'string') return 'downloads'
|
||||
if ((sortKeys as readonly string[]).includes(value)) return value as SortKey
|
||||
return 'downloads'
|
||||
}
|
||||
|
||||
export function parseDir(value: unknown, sort: SortKey): SortDir {
|
||||
if (value === 'asc' || value === 'desc') return value
|
||||
return sort === 'name' ? 'asc' : 'desc'
|
||||
}
|
||||
|
||||
export function toListSort(sort: SortKey): ListSortKey {
|
||||
return sort === 'relevance' ? 'downloads' : sort
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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)}`
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import { useAction, usePaginatedQuery } from 'convex/react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react'
|
||||
import { api } from '../../../convex/_generated/api'
|
||||
import { parseDir, parseSort, toListSort, type SortDir, type SortKey } from './-params'
|
||||
import type { SkillListEntry, SkillSearchEntry } from './-types'
|
||||
|
||||
const pageSize = 25
|
||||
|
||||
type SkillsView = 'cards' | 'list'
|
||||
|
||||
export type SkillsSearchState = {
|
||||
q?: string
|
||||
sort?: SortKey
|
||||
dir?: SortDir
|
||||
highlighted?: boolean
|
||||
nonSuspicious?: boolean
|
||||
view?: SkillsView
|
||||
focus?: 'search'
|
||||
}
|
||||
|
||||
type SkillsNavigate = (options: {
|
||||
search: (prev: SkillsSearchState) => SkillsSearchState
|
||||
replace?: boolean
|
||||
}) => void | Promise<void>
|
||||
|
||||
export function useSkillsBrowseModel({
|
||||
search,
|
||||
navigate,
|
||||
searchInputRef,
|
||||
}: {
|
||||
search: SkillsSearchState
|
||||
navigate: SkillsNavigate
|
||||
searchInputRef: RefObject<HTMLInputElement | null>
|
||||
}) {
|
||||
const [query, setQuery] = useState(search.q ?? '')
|
||||
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 view: SkillsView = search.view ?? 'list'
|
||||
const highlightedOnly = search.highlighted ?? false
|
||||
const nonSuspiciousOnly = search.nonSuspicious ?? false
|
||||
const searchSkills = useAction(api.search.searchSkills)
|
||||
|
||||
const trimmedQuery = useMemo(() => query.trim(), [query])
|
||||
const hasQuery = trimmedQuery.length > 0
|
||||
const sort: SortKey =
|
||||
search.sort === 'relevance' && !hasQuery
|
||||
? 'downloads'
|
||||
: (search.sort ?? (hasQuery ? 'relevance' : 'downloads'))
|
||||
const listSort = toListSort(sort)
|
||||
const dir = parseDir(search.dir, sort)
|
||||
const searchKey = trimmedQuery
|
||||
? `${trimmedQuery}::${highlightedOnly ? '1' : '0'}::${nonSuspiciousOnly ? '1' : '0'}`
|
||||
: ''
|
||||
|
||||
const {
|
||||
results: paginatedResults,
|
||||
status: paginationStatus,
|
||||
loadMore: loadMorePaginated,
|
||||
} = usePaginatedQuery(
|
||||
api.skills.listPublicPageV2,
|
||||
hasQuery ? 'skip' : { sort: listSort, dir, highlightedOnly, nonSuspiciousOnly },
|
||||
{
|
||||
initialNumItems: pageSize,
|
||||
},
|
||||
)
|
||||
|
||||
const isLoadingList = paginationStatus === 'LoadingFirstPage'
|
||||
const canLoadMoreList = paginationStatus === 'CanLoadMore'
|
||||
const isLoadingMoreList = paginationStatus === 'LoadingMore'
|
||||
|
||||
useEffect(() => {
|
||||
setQuery(search.q ?? '')
|
||||
}, [search.q])
|
||||
|
||||
useEffect(() => {
|
||||
if (search.focus === 'search' && searchInputRef.current) {
|
||||
searchInputRef.current.focus()
|
||||
void navigate({ search: (prev) => ({ ...prev, focus: undefined }), replace: true })
|
||||
}
|
||||
}, [navigate, search.focus, searchInputRef])
|
||||
|
||||
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,
|
||||
nonSuspiciousOnly,
|
||||
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, nonSuspiciousOnly, searchLimit, searchSkills, trimmedQuery])
|
||||
|
||||
const baseItems = useMemo(() => {
|
||||
if (hasQuery) {
|
||||
return searchResults.map((entry) => ({
|
||||
skill: entry.skill,
|
||||
latestVersion: entry.version,
|
||||
ownerHandle: entry.ownerHandle ?? null,
|
||||
owner: entry.owner ?? null,
|
||||
searchScore: entry.score,
|
||||
}))
|
||||
}
|
||||
return paginatedResults as Array<SkillListEntry>
|
||||
}, [hasQuery, paginatedResults, searchResults])
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
if (!hasQuery) {
|
||||
return baseItems
|
||||
}
|
||||
const multiplier = dir === 'asc' ? 1 : -1
|
||||
const results = [...baseItems]
|
||||
results.sort((a, b) => {
|
||||
const tieBreak = () => {
|
||||
const updated = (a.skill.updatedAt - b.skill.updatedAt) * multiplier
|
||||
if (updated !== 0) return updated
|
||||
return a.skill.slug.localeCompare(b.skill.slug)
|
||||
}
|
||||
switch (sort) {
|
||||
case 'relevance':
|
||||
return ((a.searchScore ?? 0) - (b.searchScore ?? 0)) * multiplier
|
||||
case 'downloads':
|
||||
return (a.skill.stats.downloads - b.skill.stats.downloads) * multiplier || tieBreak()
|
||||
case 'installs':
|
||||
return (
|
||||
((a.skill.stats.installsAllTime ?? 0) - (b.skill.stats.installsAllTime ?? 0)) * multiplier ||
|
||||
tieBreak()
|
||||
)
|
||||
case 'stars':
|
||||
return (a.skill.stats.stars - b.skill.stats.stars) * multiplier || tieBreak()
|
||||
case 'updated':
|
||||
return (
|
||||
(a.skill.updatedAt - b.skill.updatedAt) * multiplier || a.skill.slug.localeCompare(b.skill.slug)
|
||||
)
|
||||
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 || a.skill.slug.localeCompare(b.skill.slug)
|
||||
)
|
||||
}
|
||||
})
|
||||
return results
|
||||
}, [baseItems, dir, hasQuery, 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])
|
||||
|
||||
const onQueryChange = useCallback(
|
||||
(next: string) => {
|
||||
const trimmed = next.trim()
|
||||
setQuery(next)
|
||||
void navigate({
|
||||
search: (prev) => ({ ...prev, q: trimmed ? next : undefined }),
|
||||
replace: true,
|
||||
})
|
||||
},
|
||||
[navigate],
|
||||
)
|
||||
|
||||
const onToggleHighlighted = useCallback(() => {
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
highlighted: prev.highlighted ? undefined : true,
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}, [navigate])
|
||||
|
||||
const onToggleNonSuspicious = useCallback(() => {
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
nonSuspicious: prev.nonSuspicious ? undefined : true,
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}, [navigate])
|
||||
|
||||
const onSortChange = useCallback(
|
||||
(value: string) => {
|
||||
const nextSort = parseSort(value)
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
sort: nextSort,
|
||||
dir: parseDir(prev.dir, nextSort),
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
},
|
||||
[navigate],
|
||||
)
|
||||
|
||||
const onToggleDir = useCallback(() => {
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
dir: parseDir(prev.dir, sort) === 'asc' ? 'desc' : 'asc',
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}, [navigate, sort])
|
||||
|
||||
const onToggleView = useCallback(() => {
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
view: prev.view === 'cards' ? undefined : 'cards',
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}, [navigate])
|
||||
|
||||
const activeFilters: string[] = []
|
||||
if (highlightedOnly) activeFilters.push('highlighted')
|
||||
if (nonSuspiciousOnly) activeFilters.push('non-suspicious')
|
||||
|
||||
return {
|
||||
activeFilters,
|
||||
canAutoLoad,
|
||||
canLoadMore,
|
||||
dir,
|
||||
hasQuery,
|
||||
highlightedOnly,
|
||||
isLoadingMore,
|
||||
isLoadingSkills,
|
||||
loadMore,
|
||||
loadMoreRef,
|
||||
nonSuspiciousOnly,
|
||||
onQueryChange,
|
||||
onSortChange,
|
||||
onToggleDir,
|
||||
onToggleHighlighted,
|
||||
onToggleNonSuspicious,
|
||||
onToggleView,
|
||||
paginationStatus,
|
||||
query,
|
||||
sort,
|
||||
sorted,
|
||||
view,
|
||||
}
|
||||
}
|
||||
+46
-489
@@ -1,74 +1,11 @@
|
||||
import { createFileRoute, Link, redirect } from '@tanstack/react-router'
|
||||
import { useAction, usePaginatedQuery } from 'convex/react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
import { useQuery } from 'convex/react'
|
||||
import { useRef } from 'react'
|
||||
import { api } from '../../../convex/_generated/api'
|
||||
import type { Doc } from '../../../convex/_generated/dataModel'
|
||||
import { SkillCard } from '../../components/SkillCard'
|
||||
import { UserBadge } from '../../components/UserBadge'
|
||||
import { getSkillBadges, isSkillHighlighted } from '../../lib/badges'
|
||||
import type { PublicSkill, PublicUser } from '../../lib/publicUser'
|
||||
|
||||
const sortKeys = [
|
||||
'relevance',
|
||||
'newest',
|
||||
'downloads',
|
||||
'installs',
|
||||
'stars',
|
||||
'name',
|
||||
'updated',
|
||||
] as const
|
||||
const pageSize = 25
|
||||
type SortKey = (typeof sortKeys)[number]
|
||||
type ListSortKey = Exclude<SortKey, 'relevance'>
|
||||
type SortDir = 'asc' | 'desc'
|
||||
|
||||
function parseSort(value: unknown): SortKey {
|
||||
if (typeof value !== 'string') return 'downloads'
|
||||
if ((sortKeys as readonly string[]).includes(value)) return value as SortKey
|
||||
return 'downloads'
|
||||
}
|
||||
|
||||
function parseDir(value: unknown, sort: SortKey): SortDir {
|
||||
if (value === 'asc' || value === 'desc') return value
|
||||
return sort === 'name' ? 'asc' : 'desc'
|
||||
}
|
||||
|
||||
function toListSort(sort: SortKey): ListSortKey {
|
||||
return sort === 'relevance' ? 'downloads' : sort
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
type SkillSearchEntry = {
|
||||
skill: PublicSkill
|
||||
version: Doc<'skillVersions'> | null
|
||||
score: number
|
||||
ownerHandle?: string | null
|
||||
owner?: PublicUser | null
|
||||
}
|
||||
|
||||
function buildSkillHref(skill: PublicSkill, ownerHandle?: string | null) {
|
||||
const owner = ownerHandle?.trim() || String(skill.ownerUserId)
|
||||
return `/${encodeURIComponent(owner)}/${encodeURIComponent(skill.slug)}`
|
||||
}
|
||||
import { parseSort } from './-params'
|
||||
import { SkillsResults } from './-SkillsResults'
|
||||
import { SkillsToolbar } from './-SkillsToolbar'
|
||||
import { useSkillsBrowseModel } from './-useSkillsBrowseModel'
|
||||
|
||||
export const Route = createFileRoute('/skills/')({
|
||||
validateSearch: (search) => {
|
||||
@@ -113,439 +50,59 @@ export const Route = createFileRoute('/skills/')({
|
||||
export function SkillsIndex() {
|
||||
const navigate = Route.useNavigate()
|
||||
const search = Route.useSearch()
|
||||
const [query, setQuery] = useState(search.q ?? '')
|
||||
const view = search.view ?? 'list'
|
||||
const highlightedOnly = search.highlighted ?? false
|
||||
const nonSuspiciousOnly = search.nonSuspicious ?? 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 searchInputRef = useRef<HTMLInputElement>(null)
|
||||
const trimmedQuery = useMemo(() => query.trim(), [query])
|
||||
const hasQuery = trimmedQuery.length > 0
|
||||
const sort =
|
||||
search.sort === 'relevance' && !hasQuery
|
||||
? 'downloads'
|
||||
: (search.sort ?? (hasQuery ? 'relevance' : 'downloads'))
|
||||
const listSort = toListSort(sort)
|
||||
const dir = parseDir(search.dir, sort)
|
||||
const searchKey = trimmedQuery
|
||||
? `${trimmedQuery}::${highlightedOnly ? '1' : '0'}::${nonSuspiciousOnly ? '1' : '0'}`
|
||||
: ''
|
||||
const totalSkills = useQuery(api.skills.countPublicSkills)
|
||||
const totalSkillsText =
|
||||
typeof totalSkills === 'number' ? totalSkills.toLocaleString('en-US') : null
|
||||
|
||||
const {
|
||||
results: paginatedResults,
|
||||
status: paginationStatus,
|
||||
loadMore: loadMorePaginated,
|
||||
} = usePaginatedQuery(
|
||||
api.skills.listPublicPageV2,
|
||||
hasQuery ? 'skip' : { sort: listSort, dir, nonSuspiciousOnly },
|
||||
{
|
||||
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])
|
||||
|
||||
// Defense-in-depth for stale client bundles: always normalize browse mode to downloads sort.
|
||||
useEffect(() => {
|
||||
if (hasQuery || search.sort) return
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
sort: 'downloads',
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}, [hasQuery, navigate, search.sort])
|
||||
|
||||
// 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,
|
||||
nonSuspiciousOnly,
|
||||
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, nonSuspiciousOnly, searchLimit, searchSkills, trimmedQuery])
|
||||
|
||||
const baseItems = useMemo(() => {
|
||||
if (hasQuery) {
|
||||
return searchResults.map((entry) => ({
|
||||
skill: entry.skill,
|
||||
latestVersion: entry.version,
|
||||
ownerHandle: entry.ownerHandle ?? null,
|
||||
owner: entry.owner ?? 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(() => {
|
||||
if (!hasQuery) {
|
||||
return filtered
|
||||
}
|
||||
const multiplier = dir === 'asc' ? 1 : -1
|
||||
const results = [...filtered]
|
||||
results.sort((a, b) => {
|
||||
const tieBreak = () => {
|
||||
const updated = (a.skill.updatedAt - b.skill.updatedAt) * multiplier
|
||||
if (updated !== 0) return updated
|
||||
return a.skill.slug.localeCompare(b.skill.slug)
|
||||
}
|
||||
switch (sort) {
|
||||
case 'relevance':
|
||||
return ((a.searchScore ?? 0) - (b.searchScore ?? 0)) * multiplier
|
||||
case 'downloads':
|
||||
return (a.skill.stats.downloads - b.skill.stats.downloads) * multiplier || tieBreak()
|
||||
case 'installs':
|
||||
return (
|
||||
((a.skill.stats.installsAllTime ?? 0) - (b.skill.stats.installsAllTime ?? 0)) *
|
||||
multiplier || tieBreak()
|
||||
)
|
||||
case 'stars':
|
||||
return (a.skill.stats.stars - b.skill.stats.stars) * multiplier || tieBreak()
|
||||
case 'updated':
|
||||
return (
|
||||
(a.skill.updatedAt - b.skill.updatedAt) * multiplier ||
|
||||
a.skill.slug.localeCompare(b.skill.slug)
|
||||
)
|
||||
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 ||
|
||||
a.skill.slug.localeCompare(b.skill.slug)
|
||||
)
|
||||
}
|
||||
})
|
||||
return results
|
||||
}, [dir, filtered, hasQuery, 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])
|
||||
|
||||
const activeFilters: string[] = []
|
||||
if (highlightedOnly) activeFilters.push('highlighted')
|
||||
if (nonSuspiciousOnly) activeFilters.push('non-suspicious')
|
||||
const model = useSkillsBrowseModel({
|
||||
navigate,
|
||||
search,
|
||||
searchInputRef,
|
||||
})
|
||||
|
||||
return (
|
||||
<main className="section">
|
||||
<header className="skills-header-top">
|
||||
<h1 className="section-title" style={{ marginBottom: 8 }}>
|
||||
Skills
|
||||
{totalSkillsText && <span style={{ opacity: 0.55 }}>{` (${totalSkillsText})`}</span>}
|
||||
</h1>
|
||||
<p className="section-subtitle" style={{ marginBottom: 0 }}>
|
||||
{isLoadingSkills
|
||||
{model.isLoadingSkills
|
||||
? 'Loading skills…'
|
||||
: `Browse the skill library${activeFilters.length ? ` (${activeFilters.join(', ')})` : ''}.`}
|
||||
: `Browse the skill library${model.activeFilters.length ? ` (${model.activeFilters.join(', ')})` : ''}.`}
|
||||
</p>
|
||||
</header>
|
||||
<div className="skills-container">
|
||||
<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>
|
||||
<button
|
||||
className={`search-filter-button${nonSuspiciousOnly ? ' is-active' : ''}`}
|
||||
type="button"
|
||||
aria-pressed={nonSuspiciousOnly}
|
||||
onClick={() => {
|
||||
void navigate({
|
||||
search: (prev) => ({
|
||||
...prev,
|
||||
nonSuspicious: nonSuspiciousOnly ? undefined : true,
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}}
|
||||
>
|
||||
Hide suspicious
|
||||
</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>
|
||||
|
||||
{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 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">
|
||||
⭐ {skill.stats.stars} · ⤓ {skill.stats.downloads} · ⤒{' '}
|
||||
{skill.stats.installsAllTime ?? 0}
|
||||
</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">
|
||||
<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}
|
||||
<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>
|
||||
</main>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useAction, useQuery } from 'convex/react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { api } from '../../../convex/_generated/api'
|
||||
import { SoulMetricsRow, SoulStatsTripletLine } from '../../components/SoulStats'
|
||||
import { SoulCard } from '../../components/SoulCard'
|
||||
import type { PublicSoul } from '../../lib/publicUser'
|
||||
|
||||
@@ -207,7 +208,7 @@ function SoulsIndex() {
|
||||
summaryFallback="A SOUL.md bundle."
|
||||
meta={
|
||||
<div className="stat">
|
||||
⭐ {soul.stats.stars} · ⤓ {soul.stats.downloads} · {soul.stats.versions} v
|
||||
<SoulStatsTripletLine stats={soul.stats} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
@@ -230,9 +231,7 @@ function SoulsIndex() {
|
||||
<div className="skills-row-summary">{soul.summary ?? 'SOUL.md bundle.'}</div>
|
||||
</div>
|
||||
<div className="skills-row-metrics">
|
||||
<span>⤓ {soul.stats.downloads}</span>
|
||||
<span>★ {soul.stats.stars}</span>
|
||||
<span>{soul.stats.versions} v</span>
|
||||
<SoulMetricsRow stats={soul.stats} />
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useMutation, useQuery } from 'convex/react'
|
||||
import { api } from '../../convex/_generated/api'
|
||||
import type { Doc } from '../../convex/_generated/dataModel'
|
||||
import { formatCompactStat } from '../lib/numberFormat'
|
||||
import type { PublicSkill } from '../lib/publicUser'
|
||||
|
||||
export const Route = createFileRoute('/stars')({
|
||||
@@ -41,7 +42,7 @@ function Stars() {
|
||||
<h3 className="skill-card-title">{skill.displayName}</h3>
|
||||
</Link>
|
||||
<div className="skill-card-footer skill-card-footer-inline">
|
||||
<span className="stat">⭐ {skill.stats.stars}</span>
|
||||
<span className="stat">⭐ {formatCompactStat(skill.stats.stars)}</span>
|
||||
<button
|
||||
className="star-toggle is-active"
|
||||
type="button"
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'
|
||||
import { api } from '../../../convex/_generated/api'
|
||||
import type { Doc } from '../../../convex/_generated/dataModel'
|
||||
import { SkillCard } from '../../components/SkillCard'
|
||||
import { SkillStatsTripletLine } from '../../components/SkillStats'
|
||||
import { getSkillBadges } from '../../lib/badges'
|
||||
import type { PublicSkill, PublicUser } from '../../lib/publicUser'
|
||||
|
||||
@@ -125,8 +126,7 @@ function UserProfile() {
|
||||
summaryFallback="Agent-ready skill pack."
|
||||
meta={
|
||||
<div className="stat">
|
||||
⭐ {skill.stats.stars} · ⤓ {skill.stats.downloads} · ⤒{' '}
|
||||
{skill.stats.installsAllTime ?? 0}
|
||||
<SkillStatsTripletLine stats={skill.stats} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
@@ -155,8 +155,7 @@ function UserProfile() {
|
||||
summaryFallback="Agent-ready skill pack."
|
||||
meta={
|
||||
<div className="stat">
|
||||
⭐ {skill.stats.stars} · ⤓ {skill.stats.downloads} · ⤒{' '}
|
||||
{skill.stats.installsAllTime ?? 0}
|
||||
<SkillStatsTripletLine stats={skill.stats} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
+64
-1
@@ -2289,6 +2289,66 @@ code {
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.file-browser {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
@media (min-width: 900px) {
|
||||
.file-browser {
|
||||
grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.3fr);
|
||||
align-items: start;
|
||||
}
|
||||
}
|
||||
|
||||
.file-row-button {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--surface-muted);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.file-row-button:focus-visible {
|
||||
outline: 3px solid rgba(255, 107, 74, 0.25);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.file-row-button.is-active {
|
||||
border-color: var(--ink);
|
||||
box-shadow: 0 8px 18px rgba(29, 26, 23, 0.12);
|
||||
}
|
||||
|
||||
.file-viewer {
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--surface);
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.file-viewer-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.file-viewer-body {
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.file-viewer-code {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.9rem;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.version-scroll {
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
@@ -3604,7 +3664,7 @@ html.theme-transition::view-transition-new(theme) {
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
user-select: text;
|
||||
border-radius: 12px;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
@@ -3625,6 +3685,7 @@ html.theme-transition::view-transition-new(theme) {
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.analysis-detail-toggle .chevron {
|
||||
@@ -3640,6 +3701,8 @@ html.theme-transition::view-transition-new(theme) {
|
||||
color: var(--ink);
|
||||
line-height: 1.45;
|
||||
flex: 1;
|
||||
cursor: text;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.analysis-body {
|
||||
|
||||
Reference in New Issue
Block a user