Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Hub: filters, popular order, forks, full-screen output, source files and a feed that does not jump (#1083)

Jacob Pham532f73908cfc
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index a0797a4fd..2c6db3c14 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -29,6 +29,8 @@ model CommunityHarness {
@@index([autonomousEnv, deletedAt, createdAt])
@@index([autonomousEnv, authorId])
+ @@index([autonomousEnv, forkedFrom])
+ @@index([autonomousEnv, category, deletedAt, createdAt])
@@map("community_harnesses")
}
diff --git a/backend/src/lib/communityFeed.ts b/backend/src/lib/communityFeed.ts
new file mode 100644
index 000000000..9be096453
--- /dev/null
+++ b/backend/src/lib/communityFeed.ts
@@ -0,0 +1,61 @@
+import { prisma } from './prisma.js'
+
+export const feedSorts = ['newest', 'popular'] as const
+export type FeedSort = typeof feedSorts[number]
+
+/** What a feed card reads: never the files or the cover's bytes. */
+const feedSelect = { id: true, title: true, description: true, category: true, engine: true, harnessId: true, authorId: true, authorName: true, forkedFrom: true, createdAt: true } as const
+const feedPageSize = 30
+
+type FeedWhere = NonNullable<Parameters<typeof prisma.communityHarness.findMany>[0]>['where']
+type FeedRow = Awaited<ReturnType<typeof newestPage>>[number]
+const newest = [{ createdAt: 'desc' as const }, { id: 'desc' as const }]
+
+/** One page newest first, the indexed order, after the last id read. One row more tells whether there is another page. */
+function newestPage(where: FeedWhere, cursor?: string) {
+ return prisma.communityHarness.findMany({
+ where, select: feedSelect, orderBy: newest, take: feedPageSize + 1,
+ ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
+ })
+}
+
+/**
+ * One page most liked first, newest first among equals, after the last id read. A page whose last
+ * harness has since gone ends the feed rather than starting it over.
+ * TODO(BE): this ranks every matching publication for each page; keep a like count on the
+ * publication (and index it) once the feed outgrows that.
+ */
+async function popularPage(where: FeedWhere, autonomousEnv: string, cursor?: string): Promise<FeedRow[]> {
+ const ids = (await prisma.communityHarness.findMany({ where, select: { id: true }, orderBy: newest })).map(row => row.id)
+ const likes = await prisma.communityLike.groupBy({ by: ['harnessId'], where: { autonomousEnv, harnessId: { in: ids } }, _count: { _all: true } })
+ const count = new Map(likes.map(row => [row.harnessId, row._count._all]))
+ // Array sort is stable, so equals keep the newest-first order they were read in.
+ const ranked = [...ids].sort((a, b) => (count.get(b) ?? 0) - (count.get(a) ?? 0))
+ const start = cursor ? ranked.indexOf(cursor) + 1 : 0
+ if (cursor && !start) return []
+ const pageIds = ranked.slice(start, start + feedPageSize + 1)
+ const rows = new Map((await prisma.communityHarness.findMany({ where: { id: { in: pageIds } }, select: feedSelect })).map(row => [row.id, row]))
+ return pageIds.flatMap(id => rows.get(id) ?? [])
+}
+
+/** A feed page in the reader's order, and the cursor for the next one (null on the last). */
+export async function feedPage(where: FeedWhere, autonomousEnv: string, sort: FeedSort, cursor?: string) {
+ const rows = sort === 'popular' ? await popularPage(where, autonomousEnv, cursor) : await newestPage(where, cursor)
+ const page = rows.slice(0, feedPageSize)
+ return { page, nextCursor: rows.length > feedPageSize ? page[page.length - 1].id : null }
+}
+
+/** Likes, comments and public forks of each harness, and which of them the reader likes. */
+export async function feedStats(ids: string[], autonomousEnv: string, userId?: string) {
+ const [likes, comments, forks, liked] = await Promise.all([
+ prisma.communityLike.groupBy({ by: ['harnessId'], where: { autonomousEnv, harnessId: { in: ids } }, _count: { _all: true } }),
+ prisma.communityComment.groupBy({ by: ['harnessId'], where: { autonomousEnv, harnessId: { in: ids } }, _count: { _all: true } }),
+ prisma.communityHarness.groupBy({ by: ['forkedFrom'], where: { autonomousEnv, deletedAt: null, forkedFrom: { in: ids } }, _count: { _all: true } }),
+ userId ? prisma.communityLike.findMany({ where: { autonomousEnv, userId, harnessId: { in: ids } }, select: { harnessId: true } }) : [],
+ ])
+ const likeCount = new Map(likes.map(row => [row.harnessId, row._count._all]))
+ const commentCount = new Map(comments.map(row => [row.harnessId, row._count._all]))
+ const forkCount = new Map(forks.map(row => [row.forkedFrom, row._count._all]))
+ const likedIds = new Set(liked.map(row => row.harnessId))
+ return Object.fromEntries(ids.map(id => [id, { likes: likeCount.get(id) ?? 0, comments: commentCount.get(id) ?? 0, forks: forkCount.get(id) ?? 0, liked: likedIds.has(id) }]))
+}
diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.ts
index 9d156c6e3..48282aa48 100644
--- a/backend/src/routes/community.test.ts
+++ b/backend/src/routes/community.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance, type InjectOptions } from 'fastify'
type Row = Record<string, unknown> & { id: string; createdAt: Date }
-type Query = { where?: Record<string, unknown>; select?: Record<string, boolean>; take?: number; skip?: number; cursor?: { id: string }; orderBy?: unknown }
+type Query = { where?: Record<string, unknown>; select?: Record<string, boolean>; take?: number; skip?: number; cursor?: { id: string }; orderBy?: unknown; by?: string[] }
const db = vi.hoisted(() => {
function matches(row: Row, where: Record<string, unknown> = {}): boolean {
return Object.entries(where).every(([key, value]) => {
@@ -34,8 +34,9 @@ const db = vi.hoisted(() => {
count: vi.fn(async (query: Query) => find(query).length),
groupBy: vi.fn(async (query: Query) => {
const counts = new Map<string, number>()
- for (const row of find(query)) counts.set(row.harnessId as string, (counts.get(row.harnessId as string) || 0) + 1)
- return [...counts].map(([harnessId, count]) => ({ harnessId, _count: { _all: count } }))
+ const key = query.by?.[0] ?? 'harnessId'
+ for (const row of find(query)) counts.set(row[key] as string, (counts.get(row[key] as string) || 0) + 1)
+ return [...counts].map(([value, count]) => ({ [key]: value, _count: { _all: count } }))
}),
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => { const row = { id: crypto.randomUUID(), createdAt: new Date(), ...data } as Row; rows.push(row); return row }),
upsert: vi.fn(async ({ where, create, update }: { where: Record<string, unknown>; create: Record<string, unknown>; update: Record<string, unknown> }) => {
@@ -89,7 +90,7 @@ describe('publications and access', () => {
expect(reply.json().data.comment).toMatchObject({ creator: true, parentId: comment.id, parentAuthorName: 'Bob' })
const feed = (await call('GET', 'harnesses?mine=true', 'alice')).json().data
expect(feed.harnesses.map((row: Row) => row.id)).toEqual([id])
- expect(feed.stats[id]).toEqual({ likes: 1, comments: 2, liked: false })
+ expect(feed.stats[id]).toEqual({ likes: 1, comments: 2, forks: 0, liked: false })
expect((await call('GET', 'harnesses?mine=true', 'bob')).json().data.harnesses).toEqual([])
expect((await call('GET', 'harnesses?mine=true')).statusCode).toBe(401)
})
@@ -251,4 +252,58 @@ describe('persistent social actions', () => {
expect((await call('PUT', 'creators/bob/follow', 'bob', { following: true })).statusCode).toBe(400)
expect((await call('PUT', 'creators/nobody/follow', 'bob', { following: true })).statusCode).toBe(404)
})
+ it('narrows the feed to one category, rejecting one the Hub does not offer', async () => {
+ await publish('alice', { ...sample, title: 'A game', category: 'Games' }); await publish('alice', { ...sample, title: 'An app' })
+ const titles = async (query: string) => (await call('GET', `harnesses?${query}`)).json().data.harnesses.map((row: { title: string }) => row.title)
+ expect(await titles('category=Games')).toEqual(['A game'])
+ expect(await titles('category=Games&q=app')).toEqual([])
+ expect((await call('GET', 'harnesses?category=Spam')).statusCode).toBe(400)
+ expect((await call('GET', 'harnesses?sort=oldest')).statusCode).toBe(400)
+ })
+ it('orders the feed by likes, newest first among equals, and pages in that order', async () => {
+ const quiet = await publish('alice', { ...sample, title: 'Quiet' })
+ const liked = await publish('alice', { ...sample, title: 'Liked' })
+ const loved = await publish('bob', { ...sample, title: 'Loved' })
+ const newest = await publish('bob', { ...sample, title: 'Newest' })
+ // Published within one millisecond, they would tie: give each its own second, in publishing order.
+ db.communityHarness.rows.forEach((row, index) => { row.createdAt = new Date(Date.now() + index * 1000) })
+ await call('PUT', `harnesses/${liked}/like`, 'bob', { liked: true })
+ for (const token of ['alice', 'bob']) await call('PUT', `harnesses/${loved}/like`, token, { liked: true })
+ const first = (await call('GET', 'harnesses?sort=popular')).json().data
+ expect(first.harnesses.map((row: Row) => row.id)).toEqual([loved, liked, newest, quiet])
+ expect(first.nextCursor).toBeNull()
+ expect(first.harnesses[0]).not.toHaveProperty('files')
+ expect(first.stats[loved]).toMatchObject({ likes: 2 })
+ // A page after a harness that has gone ends the feed rather than starting it over.
+ await call('DELETE', `harnesses/${liked}`, 'alice')
+ expect((await call('GET', `harnesses?sort=popular&cursor=${liked}`)).json().data.harnesses).toEqual([])
+ })
+ it('pages a popular feed past thirty publications without repeating one', async () => {
+ for (let i = 0; i < 31; i++) db.communityHarness.rows.push({ ...sample, id: crypto.randomUUID(), createdAt: new Date(Date.now() - i * 1000), autonomousEnv: 'prod', authorId: 'alice', authorName: 'Alice', deletedAt: null, credits: [] })
+ const first = (await call('GET', 'harnesses?sort=popular')).json().data
+ expect(first.harnesses).toHaveLength(30)
+ const second = (await call('GET', `harnesses?sort=popular&cursor=${first.nextCursor}`)).json().data
+ expect(second.harnesses).toHaveLength(1); expect(second.nextCursor).toBeNull()
+ expect(first.harnesses.map((row: Row) => row.id)).not.toContain(second.harnesses[0].id)
+ })
+ it('counts and lists a harness’s public forks, and every comment beyond the latest hundred', async () => {
+ const id = await publish('alice')
+ const fork = await publish('bob', { ...sample, title: 'My version', forkedFrom: id } as typeof sample)
+ await publish('bob', { ...sample, title: 'Gone', forkedFrom: id } as typeof sample).then(gone => call('DELETE', `harnesses/${gone}`, 'bob'))
+ expect((await call('GET', 'harnesses')).json().data.stats[id]).toMatchObject({ forks: 1 })
+ const forks = (await call('GET', `harnesses?forkedFrom=${id}`)).json().data.harnesses
+ expect(forks.map((row: Row) => row.id)).toEqual([fork])
+ for (let i = 0; i < 101; i++) db.communityComment.rows.push({ id: crypto.randomUUID(), createdAt: new Date(Date.now() + i), autonomousEnv: 'prod', harnessId: id, userId: 'bob', authorName: 'Bob', body: `${i}`, clientId: crypto.randomUUID() })
+ const social = (await call('GET', `harnesses/${id}/social`)).json().data.social
+ expect(social).toMatchObject({ forks: 1, commentCount: 101 })
+ expect(social.comments).toHaveLength(100)
+ })
+ it('sends a harness page only its output when asked', async () => {
+ const payload = { ...sample, files: [...sample.files, { path: 'src/app.js', content: 'console.log(1)' }] }
+ const id = await publish('alice', payload)
+ expect((await call('GET', `harnesses/${id}?files=viewer`)).json().data.harness.files).toEqual(sample.files)
+ expect((await call('GET', `harnesses/${id}`)).json().data.harness.files).toEqual(payload.files)
+ expect(isPublicCommunityRead('GET', `/api/community/harnesses/${id}?files=viewer`)).toBe(true)
+ expect((await call('GET', `harnesses/${id}?files=all`)).statusCode).toBe(400)
+ })
})
diff --git a/backend/src/routes/community.ts b/backend/src/routes/community.ts
index 3eb84ceb9..5dc641f97 100644
--- a/backend/src/routes/community.ts
+++ b/backend/src/routes/community.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import { prisma } from '../lib/prisma.js'
import { parseAutonomousEnvironment } from '../lib/autonomousEnvironment.js'
import { communityStarters } from '../lib/communityAccess.js'
+import { feedPage, feedSorts, feedStats } from '../lib/communityFeed.js'
import { communityCategories, communityEngines, communityHarnessIds, communityHarnessMarkers, communityLimits, communityPathPattern, communityReservedName } from '../lib/communityContract.js'
import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
@@ -33,6 +34,11 @@ function searchWhere(q?: string) {
if (!q) return {}
return { OR: searchFields.map(field => ({ [field]: { contains: q, mode: 'insensitive' as const } })) }
}
+/** A publication with only the page readers see: what a harness page draws, without megabytes of source. */
+function withViewerOnly<T extends { files: unknown; viewerPath: string }>(post: T): T {
+ const files = Array.isArray(post.files) ? post.files.filter(file => (file as { path?: unknown } | null)?.path === post.viewerPath) : []
+ return { ...post, files }
+}
const params = z.object({ id: identifier })
const file = z.object({
path: z.string().regex(communityPathPattern).refine(path =>
@@ -85,14 +91,17 @@ type Publication = NonNullable<Awaited<ReturnType<typeof publication>>>
async function socialState(post: Publication, autonomousEnv: string, userId: string | undefined) {
const harnessId = post.id
- const [likes, liked, comments, follow] = await Promise.all([
+ const [likes, liked, comments, follow, commentCount, forks] = await Promise.all([
prisma.communityLike.count({ where: { autonomousEnv, harnessId } }),
userId ? prisma.communityLike.findUnique({ where: { autonomousEnv_harnessId_userId: { autonomousEnv, harnessId, userId } } }) : null,
prisma.communityComment.findMany({ where: { autonomousEnv, harnessId }, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 100 }),
userId ? prisma.communityFollow.findUnique({ where: { autonomousEnv_authorId_userId: { autonomousEnv, authorId: post.authorId, userId } } }) : null,
+ // The comments above are the latest 100; these say how many there are in all, and how many public forks.
+ prisma.communityComment.count({ where: { autonomousEnv, harnessId } }),
+ prisma.communityHarness.count({ where: { autonomousEnv, deletedAt: null, forkedFrom: harnessId } }),
])
return {
- likes, liked: !!liked, following: !!follow, signedIn: !!userId, mine: post.authorId === userId,
+ likes, liked: !!liked, following: !!follow, signedIn: !!userId, mine: post.authorId === userId, commentCount, forks,
comments: comments.reverse().map(row => ({ id: row.id, body: row.body, authorName: row.authorName, createdAt: row.createdAt, parentId: row.parentId, parentAuthorName: row.parentAuthorName, creator: row.userId === post.authorId, mine: row.userId === userId || post.authorId === userId })),
}
}
@@ -105,37 +114,41 @@ async function publication(id: string, autonomousEnv: string) {
export async function communityRoutes(app: FastifyInstance): Promise<void> {
app.addHook('onSend', async (_req, reply) => { reply.header('Cache-Control', 'no-store') })
- const feedQuery = z.object({ cursor: z.string().uuid().optional(), following: z.enum(['true', 'false']).optional(), mine: z.enum(['true', 'false']).optional(), q: z.string().trim().min(1).max(searchMaxChars).optional() }).strict()
+ const feedQuery = z.object({
+ cursor: z.string().uuid().optional(), following: z.enum(['true', 'false']).optional(), mine: z.enum(['true', 'false']).optional(),
+ q: z.string().trim().min(1).max(searchMaxChars).optional(), category: z.enum(communityCategories).optional(),
+ sort: z.enum(feedSorts).optional(), forkedFrom: identifier.optional(),
+ }).strict()
app.get<{ Querystring: z.infer<typeof feedQuery> }>('/api/community/harnesses', { preHandler: validateQuery(feedQuery) }, async (req, reply) => {
const autonomousEnv = environment(req)
if ((req.query.following === 'true' || req.query.mine === 'true') && !req.user) return sendError(reply, 'Sign in to see your harnesses and creators you follow.', 'UNAUTHORIZED', 401)
const follows = req.user ? await prisma.communityFollow.findMany({ where: { autonomousEnv, userId: req.user.sub }, select: { authorId: true } }) : []
- const rows = await prisma.communityHarness.findMany({
- where: { autonomousEnv, deletedAt: null, ...(req.query.following === 'true' ? { authorId: { in: follows.map(row => row.authorId) } } : {}), ...(req.query.mine === 'true' ? { authorId: req.user!.sub } : {}), ...searchWhere(req.query.q) },
- select: { id: true, title: true, description: true, category: true, engine: true, harnessId: true, authorId: true, authorName: true, forkedFrom: true, createdAt: true },
- orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 31,
- ...(req.query.cursor ? { cursor: { id: req.query.cursor }, skip: 1 } : {}),
- })
- const page = rows.slice(0, 30), ids = [...page.map(row => row.id), ...communityStarters]
- const [likes, comments, liked, covered] = await Promise.all([
- prisma.communityLike.groupBy({ by: ['harnessId'], where: { autonomousEnv, harnessId: { in: ids } }, _count: { _all: true } }),
- prisma.communityComment.groupBy({ by: ['harnessId'], where: { autonomousEnv, harnessId: { in: ids } }, _count: { _all: true } }),
- req.user ? prisma.communityLike.findMany({ where: { autonomousEnv, userId: req.user.sub, harnessId: { in: ids } }, select: { harnessId: true } }) : [],
+ const { following, mine, q, category, forkedFrom, sort = 'newest', cursor } = req.query
+ const where = {
+ autonomousEnv, deletedAt: null, ...searchWhere(q),
+ ...(following === 'true' ? { authorId: { in: follows.map(row => row.authorId) } } : {}), ...(mine === 'true' ? { authorId: req.user!.sub } : {}),
+ ...(category ? { category } : {}), ...(forkedFrom ? { forkedFrom } : {}),
+ }
+ const { page, nextCursor } = await feedPage(where, autonomousEnv, sort, cursor)
+ const ids = [...page.map(row => row.id), ...communityStarters]
+ const [stats, covered] = await Promise.all([
+ feedStats(ids, autonomousEnv, req.user?.sub),
// Which have a cover, without reading one: a page of them is megabytes of base64.
prisma.communityHarness.findMany({ where: { id: { in: page.map(row => row.id) }, cover: { isSet: true, not: null } }, select: { id: true } }),
])
const withCover = new Set(covered.map(row => row.id))
- const stats = Object.fromEntries(ids.map(id => [id, { likes: likes.find(row => row.harnessId === id)?._count._all ?? 0, comments: comments.find(row => row.harnessId === id)?._count._all ?? 0, liked: liked.some(row => row.harnessId === id) }]))
- sendSuccess(reply, { harnesses: page.map(row => withCoverPath({ ...row, cover: withCover.has(row.id) ? 'set' : null })), stats, signedIn: !!req.user, nextCursor: rows.length > 30 ? rows[29].id : null, following: follows.map(row => row.authorId) })
+ sendSuccess(reply, { harnesses: page.map(row => withCoverPath({ ...row, cover: withCover.has(row.id) ? 'set' : null })), stats, signedIn: !!req.user, nextCursor, following: follows.map(row => row.authorId) })
})
- app.get<{ Params: z.infer<typeof params> }>('/api/community/harnesses/:id', { preHandler: validateParams(params) }, async (req, reply) => {
+ // `files=viewer` sends only the output page: a harness page draws nothing else.
+ const harnessQuery = z.object({ files: z.enum(['viewer']).optional() })
+ app.get<{ Params: z.infer<typeof params>; Querystring: z.infer<typeof harnessQuery> }>('/api/community/harnesses/:id', { preHandler: [validateParams(params), validateQuery(harnessQuery)] }, async (req, reply) => {
const autonomousEnv = environment(req), harnessId = req.params.id
const post = await publication(harnessId, autonomousEnv)
if (!post) return sendError(reply, 'This harness is unavailable.', 'NOT_FOUND', 404)
sendSuccess(reply, {
// A starter's files are the website's own; only a publication is stored here.
- harness: 'title' in post ? withCoverPath(post) : null,
+ harness: 'title' in post ? withCoverPath(req.query.files === 'viewer' ? withViewerOnly(post) : post) : null,
social: await socialState(post, autonomousEnv, req.user?.sub),
})
})
diff --git a/website/README.md b/website/README.md
index afb8c247c..bd0ada7ea 100644
--- a/website/README.md
+++ b/website/README.md
@@ -16,8 +16,8 @@ retired; only the host routes below were kept.
| `/os` | The Harness operating system landing page: plain HTML/CSS, local fonts and screenshots in `public/os/` |
| `/os/latest` | Redirect to the newest complete published OS release; OS tags only, stable preferred, five-minute server lookup cache |
| `/desktop` | Desktop download page |
-| `/hub`, `/hub/following`, `/hub/yours` | Public three-column gallery, followed creators, and your publications |
-| `/hub/:id` | Full-page output viewer and published conversation, with likes and comments |
+| `/hub`, `/hub/following`, `/hub/yours` | Public three-column gallery, followed creators, and your publications; `?q=`, `?category=` and `?sort=popular` narrow and order them |
+| `/hub/:id` | Full-page output viewer (full screen) beside the published conversation, comments or source files, with likes, a copyable link and the harness's public forks |
| `/hub/:id/fork`, `/hub/:id/download` | Desktop handoff fallback and an optional project ZIP |
| `/hub/:id/snapshot` | Public, bounded snapshot consumed by the desktop handoff |
| `/hub/import` | One-use desktop handoff into a private browser draft |
@@ -35,7 +35,8 @@ The CLI installer is `cli/scripts/install.sh`. The desktop installer's source is
The community requires the corresponding backend release and its four `community_*` collections
and indexes in `backend/prisma/schema.prisma`. Deploy that backend before exposing the website's
-social and publishing actions. Eighteen local examples remain browsable if
+social and publishing actions. The feed's category, order and forks filters need a backend that
+accepts them (it rejects unknown feed parameters), so deploy the backend first. Eighteen local examples remain browsable if
the API is unavailable. Their published briefs are labeled as examples; engagement starts at zero.
Push a `vX.Y.Z_web` tag — `make release-web` from the repo root cuts the next one.
diff --git a/website/src/app/hub/[id]/fork/page.tsx b/website/src/app/hub/[id]/fork/page.tsx
index 36d5e4d95..5a31f12bb 100644
--- a/website/src/app/hub/[id]/fork/page.tsx
+++ b/website/src/app/hub/[id]/fork/page.tsx
@@ -8,7 +8,7 @@ import { HarnessTags } from '../../components/HarnessTags';
import styles from '../../community.module.css';
export default async function ForkPage({ params }: { params: Promise<{ id: string }> }) {
- const { id } = await params, harness = await getPublicHarness(id);
+ const { id } = await params, harness = await getPublicHarness(id, { viewerOnly: true });
if (!harness) notFound();
return <><Header /><main className={`${styles.wrap} ${styles.fork}`}>
<Link href={`/hub/${id}`} className={styles.back}><ArrowLeft /> {harness.title}</Link>
diff --git a/website/src/app/hub/[id]/page.tsx b/website/src/app/hub/[id]/page.tsx
index 9a6f73edb..72adc27dd 100644
--- a/website/src/app/hub/[id]/page.tsx
+++ b/website/src/app/hub/[id]/page.tsx
@@ -11,21 +11,26 @@ const validId = (id: string) => /^starter-[a-z-]+$/.test(id) || /^[a-f0-9-]{36}$
/**
* Read once per request, for the metadata and the page. The server asks as a production reader, so a
* staging publication (or an outage) comes back null and the page loads it in the browser instead.
+ * The page draws only the output; the other files reach a fork through its own routes.
*/
const readHarness = cache(async (id: string): Promise<OpenHarness | null> => {
if (!validId(id)) return null;
// A slow backend must not hold the page: past this, the browser loads the harness itself.
- return getPublicHarness(id, 2500).catch(() => null);
+ return getPublicHarness(id, { timeoutMs: 2500, viewerOnly: true }).catch(() => null);
});
-/** The page draws only the output; the other files reach a fork through its own routes. */
-function forViewer(harness: OpenHarness): OpenHarness {
- return { ...harness, files: harness.files.filter(file => file.path === harness.viewerPath) };
-}
+/** A link preview's image: link unfurlers read raster covers, not a starter's SVG. */
+const shareImage = (harness: OpenHarness) => harness.cover && !harness.cover.endsWith('.svg') ? harness.cover : undefined;
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const harness = await readHarness((await params).id);
- return { title: harness?.title || 'Open harness', description: harness?.description };
+ if (!harness) return { title: 'Open harness' };
+ const image = shareImage(harness), title = harness.title, description = harness.description;
+ return {
+ title, description,
+ openGraph: { type: 'article', title, description, authors: [harness.authorName], ...(image ? { images: [{ url: image, width: 900, height: 600 }] } : {}) },
+ twitter: { card: image ? 'summary_large_image' : 'summary', title, description },
+ };
}
export default async function HarnessPage({ params, searchParams }: Props) {
@@ -33,5 +38,5 @@ export default async function HarnessPage({ params, searchParams }: Props) {
if (!validId(id)) notFound();
const initial = await readHarness(id);
if (id.startsWith('starter-') && !initial) notFound();
- return <Detail key={id} id={id} initial={initial && forViewer(initial)} initialComments={(await searchParams).comments !== undefined} />;
+ return <Detail key={id} id={id} initial={initial} initialComments={(await searchParams).comments !== undefined} />;
}
diff --git a/website/src/app/hub/community.module.css b/website/src/app/hub/community.module.css
index a81d2007d..3e2847fb6 100644
--- a/website/src/app/hub/community.module.css
+++ b/website/src/app/hub/community.module.css
@@ -61,7 +61,7 @@
.liked{color:#b7495c!important}
.liked svg{fill:currentColor}
.split{display:grid;grid-template-columns:minmax(0,7fr) minmax(0,3fr);align-items:start;min-height:690px}
-.viewer{width:100%;min-width:0;background:#f7f7f7}
+.viewer{position:relative;width:100%;min-width:0;background:#f7f7f7}
.viewer iframe{display:block;width:100%;height:690px;border:0;background:#f7f7f7}
.chat{min-width:0;padding-left:29px}
.chatHead{display:flex;justify-content:space-between;align-items:center;gap:14px;margin:0 0 30px;font-size:12px}
@@ -137,3 +137,35 @@
@media(max-width:760px){.recording{height:auto;aspect-ratio:4/3}}
.fileRow>details{flex:1;min-width:0}.sourceText{max-height:320px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;background:#f6f6f4;padding:14px;font:11px/1.7 ui-monospace,monospace}
+
+/* Feed filters: one category at a time, and the order. */
+.filters{display:flex;align-items:center;justify-content:space-between;gap:20px;margin:0 0 38px}
+.chips{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;min-width:0}
+.chips::-webkit-scrollbar{display:none}
+.page .chips button,.page .sort button{padding:6px 12px;font-size:13px;color:#777;white-space:nowrap;border-radius:999px;transition:background-color .15s,color .15s}
+.page .chips button:hover,.page .sort button:hover{color:#242424;background:#f4f4f2}
+.page .chips button[aria-pressed=true]{background:#242424;color:#fff}
+.sort{display:flex;gap:2px;padding:3px;border-radius:999px;background:#f4f4f2;flex-shrink:0}
+.page .sort button{padding:4px 12px}
+.page .sort button[aria-pressed=true]{background:#fff;color:#242424;box-shadow:0 1px 3px rgba(36,36,36,.12)}
+/* The first page's placeholders. */
+.skeleton .cover,.skeleton span{background:linear-gradient(100deg,#efeeeb 40%,#f7f6f3 50%,#efeeeb 60%) 0 0/200% 100%;animation:shimmer 1.4s linear infinite}
+.skeleton span{display:block;height:14px;margin-top:12px;width:62%}
+.skeleton span:last-child{width:84%;height:12px;margin-top:8px}
+@keyframes shimmer{to{background-position:-200% 0}}
+@media(prefers-reduced-motion:reduce){.skeleton .cover,.skeleton span{animation:none}}
+/* The output's full-screen control: a glass chip over its corner. */
+.page .viewerButton{position:absolute;top:12px;right:12px;display:inline-flex;padding:8px;border-radius:10px;color:#242424;background:rgba(255,255,255,.62);-webkit-backdrop-filter:saturate(180%) blur(14px);backdrop-filter:saturate(180%) blur(14px);box-shadow:0 1px 0 rgba(255,255,255,.7) inset,0 4px 14px rgba(36,36,36,.12);opacity:.72;transition:opacity .15s,transform .15s}
+.page .viewerButton:hover{opacity:1;transform:scale(1.04)}
+.viewerButton svg{width:16px;height:16px}
+.viewer:fullscreen{background:#fff}
+.viewer:fullscreen iframe{height:100%}
+/* Source files beside the output. */
+.sourceFile{border-bottom:1px solid #efefed;font-size:12px}
+.sourceFile summary{display:flex;align-items:center;gap:12px;padding:10px 0;cursor:pointer}
+.sourceFile summary code{flex:1;min-width:0;overflow-wrap:anywhere}
+.sourceFile summary small{color:#999;font-size:11px}
+.sourceFile pre{margin-bottom:12px}
+.forks{margin-top:70px}
+.forks h2{font-size:17px;font-weight:400;margin-bottom:26px}
+@media(max-width:760px){.filters{flex-direction:column;align-items:stretch;margin:0 0 26px;gap:12px}.sort{align-self:flex-start}.forks{margin-top:50px}}
diff --git a/website/src/app/hub/components/Comments.tsx b/website/src/app/hub/components/Comments.tsx
index 87fd97d53..63b526898 100644
--- a/website/src/app/hub/components/Comments.tsx
+++ b/website/src/app/hub/components/Comments.tsx
@@ -1,5 +1,6 @@
'use client';
import { useRef, useState } from 'react';
+import { commentTotal, threadComments } from '@/lib/community/comments';
import type { HarnessComment, SocialState } from '@/lib/community/types';
import { SignIn } from './Header';
import styles from '../community.module.css';
@@ -23,7 +24,7 @@ function Comment({ comment, busy, canReply, onReply, onRemove }: { comment: Harn
</article>;
}
-/** The conversation under a harness: the comments, and a form to add one or reply to one. */
+/** The conversation under a harness: the comments, each reply under its thread, and a form to add one or reply to one. */
export function Comments({ social, ready, busy, onRetry, onRemove, onPost }: Props) {
const [draft, setDraft] = useState(''), [replyTo, setReplyTo] = useState<HarnessComment | null>(null);
// Kept across a failed post, so a retry of the same text is recognised as the same comment.
@@ -38,7 +39,8 @@ export function Comments({ social, ready, busy, onRetry, onRemove, onPost }: Pro
return <>
{!ready && <p className={styles.notice}>Comments are unavailable right now. <button onClick={onRetry}>Retry</button></p>}
{ready && !social.comments.length && <p className={styles.notice}>What would you make from here?</p>}
- {social.comments.map(comment => <Comment key={comment.id} comment={comment} busy={busy} canReply={social.signedIn} onReply={() => reply(comment)} onRemove={() => onRemove(comment)} />)}
+ {ready && commentTotal(social) > social.comments.length && <p className={styles.notice}>Showing the latest {social.comments.length} of {commentTotal(social)} comments.</p>}
+ {threadComments(social.comments).map(comment => <Comment key={comment.id} comment={comment} busy={busy} canReply={social.signedIn} onReply={() => reply(comment)} onRemove={() => onRemove(comment)} />)}
{social.signedIn ? <form className={styles.commentForm} onSubmit={event => { event.preventDefault(); void submit(); }}>
<label htmlFor="comment">{replyTo ? `Reply to ${replyTo.authorName}` : 'Join the conversation'}</label>
{replyTo && <button type="button" className={styles.replyButton} onClick={() => reply(null)}>Cancel reply</button>}
diff --git a/website/src/app/hub/components/Detail.tsx b/website/src/app/hub/components/Detail.tsx
index 59f36f197..9f9713134 100644
--- a/website/src/app/hub/components/Detail.tsx
+++ b/website/src/app/hub/components/Detail.tsx
@@ -1,48 +1,33 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
-import { ArrowLeft, GitFork, Heart, MessageCircle, X } from 'lucide-react';
-import { previewDocument } from '@/lib/community/preview';
+import { ArrowLeft } from 'lucide-react';
import type { OpenHarness } from '@/lib/community/types';
-import { Comments } from './Comments';
-import { ForkButton } from './ForkButton';
-import { HarnessTags } from './HarnessTags';
+import { DetailHead, type Panel } from './DetailHead';
+import { Forks } from './Forks';
import { Header } from './Header';
-import { Transcript } from './Transcript';
+import { SidePanel } from './SidePanel';
import { useHarnessDetail } from './useHarnessDetail';
+import { Viewer } from './Viewer';
import styles from '../community.module.css';
-/** The output beside its source conversation, or a starter's recorded run. */
-function Viewer({ harness }: { harness: OpenHarness }) {
- const html = harness.files.find(file => file.path === harness.viewerPath)?.content || '';
- return <section className={styles.viewer} aria-label="Output viewer">{harness.recording
- ? <video className={styles.recording} controls playsInline preload="metadata" poster={harness.cover} aria-label={`${harness.title} recorded run`} src={harness.recording} />
- : <iframe title={`${harness.title} output`} srcDoc={previewDocument(html)} sandbox={harness.example ? 'allow-scripts allow-downloads allow-modals' : 'allow-scripts'} referrerPolicy="no-referrer" />}</section>;
-}
-
export default function Detail({ id, initial, initialComments = false }: { id: string; initial: OpenHarness | null; initialComments?: boolean }) {
- const [comments, setComments] = useState(initialComments);
- const page = useHarnessDetail(id, initial, () => setComments(true));
+ const [panel, setPanel] = useState<Panel>(initialComments ? 'comments' : 'log');
+ const page = useHarnessDetail(id, initial, () => setPanel('comments'));
const { harness, social, ready, busy } = page;
if (page.unavailable) return <><Header /><main className={`${styles.wrap} ${styles.empty}`}><h1>This harness is unavailable.</h1><Link className={styles.textLink} href="/hub">Back to Explore</Link></main></>;
if (!harness) return <><Header /><main className={`${styles.wrap} ${styles.loading}`}>{page.error || 'Loading harness…'}{page.error && <button onClick={() => void page.load()}>Retry</button>}</main></>;
const unpublish = () => { if (window.confirm('Remove this harness from the public feed? Existing downloaded forks remain with their owners.')) void page.unpublish(); };
+ // A panel's button opens it; pressed again, it returns to the chat log.
+ const toggle = (next: Panel) => setPanel(current => current === next ? 'log' : next);
return <><Header /><main className={`${styles.wrap} ${styles.detail}`}>
<Link className={styles.back} href="/hub"><ArrowLeft /> All harnesses</Link>
- <header className={styles.detailHead}><div className={styles.identity}><h1>{harness.title}</h1><div className={styles.byline}>
- <span>{harness.authorName}</span>{!social.mine && <button className={styles.follow} disabled={busy} aria-pressed={social.following} onClick={() => void page.follow()}>{social.following ? 'Following' : 'Follow'}</button>}
- {harness.forkedFrom && <Link className={styles.textLink} href={`/hub/${harness.forkedFrom}`}>Forked from an open harness</Link>}
- </div></div><div className={styles.actions}>
- <button className={social.liked ? styles.liked : ''} disabled={busy} aria-label={social.liked ? 'Unlike harness' : 'Like harness'} aria-pressed={social.liked} onClick={() => void page.like()}><Heart /><span>{ready ? social.likes : 'Like'}</span></button>
- <button aria-label="Comments" aria-pressed={comments} onClick={() => setComments(value => !value)}><MessageCircle /><span>{ready ? social.comments.length : 'Comments'}</span></button>
- <ForkButton id={id}><GitFork /> Fork</ForkButton>
- </div></header>
+ <DetailHead harness={harness} social={social} ready={ready} busy={busy} panel={panel} onFollow={() => void page.follow()} onLike={() => void page.like()} onPanel={toggle} />
<div className={styles.split}><Viewer harness={harness} />
- <aside className={styles.chat} aria-label={comments ? 'Comments' : 'Agent chat log'}>
- <div className={styles.chatHead}><h2>{comments ? `Comments${ready ? ` · ${social.comments.length}` : ''}` : 'Chat log'}</h2>{comments ? <button className={styles.icon} onClick={() => setComments(false)} aria-label="Back to chat log"><X /></button> : <HarnessTags harness={harness} />}</div>
- {comments ? <Comments social={social} ready={ready} busy={busy} onRetry={() => void page.load()} onRemove={comment => void page.removeComment(comment)} onPost={page.postComment} /> : <Transcript harness={harness} />}
- {page.error && <p className={styles.error} role="alert">{page.error}</p>}
- </aside></div>
+ <SidePanel harness={harness} social={social} ready={ready} busy={busy} panel={panel} error={page.error}
+ onClose={() => setPanel('log')} onRetry={() => void page.load()} onRemove={comment => void page.removeComment(comment)} onPost={page.postComment} />
+ </div>
+ {!!social.forks && <Forks id={id} count={social.forks} />}
{social.mine && <div className={styles.manage}><button disabled={busy} onClick={unpublish}>Unpublish this harness</button></div>}
</main></>;
}
diff --git a/website/src/app/hub/components/DetailHead.tsx b/website/src/app/hub/components/DetailHead.tsx
new file mode 100644
index 000000000..d6e2dc282
--- /dev/null
+++ b/website/src/app/hub/components/DetailHead.tsx
@@ -0,0 +1,35 @@
+'use client';
+import Link from 'next/link';
+import { FileCode2, GitFork, Heart, MessageCircle } from 'lucide-react';
+import { commentTotal } from '@/lib/community/comments';
+import type { OpenHarness, SocialState } from '@/lib/community/types';
+import { ForkButton } from './ForkButton';
+import { ShareButton } from './ShareButton';
+import styles from '../community.module.css';
+
+/** What the side of a harness page shows beside its output. */
+export type Panel = 'log' | 'comments' | 'files';
+
+type Props = {
+ harness: OpenHarness; social: SocialState; ready: boolean; busy: boolean; panel: Panel;
+ onFollow: () => void; onLike: () => void; onPanel: (panel: Panel) => void;
+};
+
+/** The harness's title and creator, and what a reader can do with it. */
+export function DetailHead({ harness, social, ready, busy, panel, onFollow, onLike, onPanel }: Props) {
+ return <header className={styles.detailHead}>
+ <div className={styles.identity}><h1>{harness.title}</h1><div className={styles.byline}>
+ <span>{harness.authorName}</span>
+ {!social.mine && <button className={styles.follow} disabled={busy} aria-pressed={social.following} onClick={onFollow}>{social.following ? 'Following' : 'Follow'}</button>}
+ {harness.forkedFrom && <Link className={styles.textLink} href={`/hub/${harness.forkedFrom}`}>Forked from an open harness</Link>}
+ {!!social.forks && <a className={styles.textLink} href="#forks">{social.forks === 1 ? '1 fork' : `${social.forks} forks`}</a>}
+ </div></div>
+ <div className={styles.actions}>
+ <button className={social.liked ? styles.liked : ''} disabled={busy} aria-label={social.liked ? 'Unlike harness' : 'Like harness'} aria-pressed={social.liked} onClick={onLike}><Heart /><span>{ready ? social.likes : 'Like'}</span></button>
+ <button aria-label="Comments" aria-pressed={panel === 'comments'} onClick={() => onPanel('comments')}><MessageCircle /><span>{ready ? commentTotal(social) : 'Comments'}</span></button>
+ <button aria-label="Source files" aria-pressed={panel === 'files'} onClick={() => onPanel('files')}><FileCode2 /><span>Files</span></button>
+ <ShareButton id={harness.id} />
+ <ForkButton id={harness.id}><GitFork /> Fork</ForkButton>
+ </div>
+ </header>;
+}
diff --git a/website/src/app/hub/components/Feed.tsx b/website/src/app/hub/components/Feed.tsx
index b627858f9..b6557e0ab 100644
--- a/website/src/app/hub/components/Feed.tsx
+++ b/website/src/app/hub/components/Feed.tsx
@@ -1,47 +1,48 @@
'use client';
import Link from 'next/link';
-import { Heart, MessageCircle } from 'lucide-react';
+import { defaultFeedView, type FeedView } from '@/lib/community/feed';
import { starterHarnesses } from '@/lib/community/starters';
import type { HarnessSummary } from '@/lib/community/types';
+import { FeedCard, FeedSkeleton } from './FeedCard';
+import { FeedFilters } from './FeedFilters';
import { Header, SignIn } from './Header';
-import { HarnessTags } from './HarnessTags';
-import { useFeed, type Stats } from './useFeed';
-import { useFeedSearch } from './useFeedSearch';
+import { useFeed } from './useFeed';
+import { useFeedView } from './useFeedView';
import styles from '../community.module.css';
-/** One harness in the grid: its cover, introduction, tags, likes and comments. */
-function FeedCard({ item, stats, onLike }: { item: HarnessSummary; stats?: Stats; onLike: () => void }) {
- return <article className={styles.card}>
- <Link href={`/hub/${item.id}`} aria-label={`Open ${item.title}`}>
- {item.cover ? <img className={styles.cover} src={item.cover} alt="" width={900} height={600} loading="lazy" /> : <div className={styles.blankCover}>{item.title}</div>}
- <h2>{item.title}</h2><p>{item.description}</p>
- </Link>
- <div className={styles.cardMeta}><small>{item.authorName}{item.example ? ' · Starter' : ''}</small><HarnessTags harness={item} /></div>
- <div className={styles.cardSocial}>
- <button className={stats?.liked ? styles.liked : ''} aria-label={`${stats?.liked ? 'Unlike' : 'Like'} ${item.title}`} aria-pressed={!!stats?.liked} onClick={onLike}><Heart />{stats?.likes || 0}</button>
- <Link href={`/hub/${item.id}?comments=1`} aria-label={`Comments on ${item.title}`}><MessageCircle />{stats?.comments || 0}</Link>
- </div>
- </article>;
+/** Starters are the website's own, so they are matched here; publications are matched by the server. */
+function matches(item: HarnessSummary, { query, category }: FeedView) {
+ if (category && item.category !== category) return false;
+ return `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase());
}
-/** Starters are the website's own, so they are matched here; publications are matched by the server. */
-const matches = (item: HarnessSummary, query: string) => `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase());
+function EmptyFeed({ narrowed, mine }: { narrowed: boolean; mine: boolean }) {
+ if (narrowed) return <div className={styles.empty}><h1>Nothing here yet.</h1><p>Try a different search or category.</p></div>;
+ if (mine) return <div className={styles.empty}><h1>Your next idea belongs here.</h1><p>Publish a harness to give someone a place to begin.</p><Link className={styles.textLink} href="/hub/publish">Publish a harness</Link></div>;
+ return <div className={styles.empty}><h1>Your people. Their next ideas.</h1><p>Follow a creator from a harness page to see their work here.</p></div>;
+}
+
+type Props = { following?: boolean; mine?: boolean; initialView?: FeedView };
-export default function Feed({ following = false, mine = false, initialQuery = '' }: { following?: boolean; mine?: boolean; initialQuery?: string }) {
- const search = useFeedSearch(initialQuery), query = search.term;
- const { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like } = useFeed({ following, mine, query });
+export default function Feed({ following = false, mine = false, initialView = defaultFeedView }: Props) {
+ const search = useFeedView(initialView), { view } = search;
+ const { posts, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like } = useFeed({ following, mine, ...view });
+ const narrowed = !!(view.query || view.category);
// Starters follow the last page: drawn sooner, every page loaded while scrolling would land above
- // them. A search or a failed page shows them at once: there is nothing to scroll past.
- const starters = mine || (cursor && !query && !error) ? [] : following ? starterHarnesses.filter(item => follows.includes(item.authorId)) : starterHarnesses;
- const visible = [...posts, ...starters.filter(item => matches(item, query))];
+ // them. A narrowed view or a failed page shows them at once: there is nothing to scroll past.
+ const starters = !settled || mine || (cursor && !narrowed && !error) ? [] : following ? starterHarnesses.filter(item => follows.includes(item.authorId)) : starterHarnesses;
+ const visible = [...posts, ...starters.filter(item => matches(item, view))];
return <><Header tab={mine ? 'yours' : following ? 'following' : 'explore'} search={{ value: search.query, onChange: search.setQuery, onClear: search.clear }} />
<main className={`${styles.wrap} ${styles.feed}`}>
{mine && <div className={styles.feedIntro}><h1>Your harnesses</h1><p>See what people like, join the conversation, and share your next version.</p></div>}
+ <FeedFilters category={view.category} sort={view.sort} onCategory={search.setCategory} onSort={search.setSort} />
{error && <p className={styles.notice} role="status">{error}<button onClick={() => void load()}>Retry</button></p>}
{likeError && <p className={styles.notice} role="status">{likeError}</p>}
{signedOut && <SignIn action={following ? 'see creators you follow' : 'join the Hub'} />}
- <div className={styles.grid}>{visible.map(item => <FeedCard key={item.id} item={item} stats={stats[item.id]} onLike={() => void like(item.id)} />)}</div>
- {!visible.length && !busy && !signedOut && <div className={styles.empty}><h1>{query ? 'Nothing here yet.' : mine ? 'Your next idea belongs here.' : 'Your people. Their next ideas.'}</h1><p>{query ? 'Try a different search.' : mine ? 'Publish a harness to give someone a place to begin.' : 'Follow a creator from a harness page to see their work here.'}</p>{mine && <Link className={styles.textLink} href="/hub/publish">Publish a harness</Link>}</div>}
+ <div className={styles.grid} aria-busy={!settled}>
+ {settled ? visible.map(item => <FeedCard key={item.id} item={item} stats={stats[item.id]} liking={liking.has(item.id)} onLike={() => void like(item.id)} />) : <FeedSkeleton />}
+ </div>
+ {settled && !visible.length && !busy && !signedOut && <EmptyFeed narrowed={narrowed} mine={mine} />}
<div ref={more}>{cursor && <button className={styles.more} disabled={busy} onClick={() => void load(cursor)}>{busy ? 'Loading…' : 'More harnesses'}</button>}</div>
</main></>;
}
diff --git a/website/src/app/hub/components/FeedCard.tsx b/website/src/app/hub/components/FeedCard.tsx
new file mode 100644
index 000000000..e5a9cdaa7
--- /dev/null
+++ b/website/src/app/hub/components/FeedCard.tsx
@@ -0,0 +1,30 @@
+'use client';
+import Link from 'next/link';
+import { GitFork, Heart, MessageCircle } from 'lucide-react';
+import type { HarnessSummary } from '@/lib/community/types';
+import { HarnessTags } from './HarnessTags';
+import type { Stats } from './useFeed';
+import styles from '../community.module.css';
+
+type Props = { item: HarnessSummary; stats?: Stats; liking: boolean; onLike: () => void };
+
+/** One harness in a grid: its cover, introduction, tags, likes, comments and, once it has some, forks. */
+export function FeedCard({ item, stats, liking, onLike }: Props) {
+ return <article className={styles.card}>
+ <Link href={`/hub/${item.id}`} aria-label={`Open ${item.title}`}>
+ {item.cover ? <img className={styles.cover} src={item.cover} alt="" width={900} height={600} loading="lazy" /> : <div className={styles.blankCover}>{item.title}</div>}
+ <h2>{item.title}</h2><p>{item.description}</p>
+ </Link>
+ <div className={styles.cardMeta}><small>{item.authorName}{item.example ? ' · Starter' : ''}</small><HarnessTags harness={item} /></div>
+ <div className={styles.cardSocial}>
+ <button className={stats?.liked ? styles.liked : ''} aria-label={`${stats?.liked ? 'Unlike' : 'Like'} ${item.title}`} aria-pressed={!!stats?.liked} aria-busy={liking} disabled={liking} onClick={onLike}><Heart />{stats?.likes || 0}</button>
+ <Link href={`/hub/${item.id}?comments=1`} aria-label={`Comments on ${item.title}`}><MessageCircle />{stats?.comments || 0}</Link>
+ {!!stats?.forks && <Link href={`/hub/${item.id}#forks`} aria-label={`Forks of ${item.title}`}><GitFork />{stats.forks}</Link>}
+ </div>
+ </article>;
+}
+
+/** Placeholder cards while the first page is on its way, so the grid does not jump when it lands. */
+export function FeedSkeleton({ count = 6 }: { count?: number }) {
+ return <>{Array.from({ length: count }, (_, index) => <div key={index} className={`${styles.card} ${styles.skeleton}`} aria-hidden><div className={styles.cover} /><span /><span /></div>)}</>;
+}
diff --git a/website/src/app/hub/components/FeedFilters.tsx b/website/src/app/hub/components/FeedFilters.tsx
new file mode 100644
index 000000000..25e771fda
--- /dev/null
+++ b/website/src/app/hub/components/FeedFilters.tsx
@@ -0,0 +1,20 @@
+'use client';
+import { communityCategories } from '@/lib/community/contract';
+import { feedSorts, type FeedSort } from '@/lib/community/feed';
+import styles from '../community.module.css';
+
+type Props = { category: string; sort: FeedSort; onCategory: (category: string) => void; onSort: (sort: FeedSort) => void };
+
+const sortLabels: Record<FeedSort, string> = { newest: 'Newest', popular: 'Popular' };
+
+/** One category at a time (All clears it), and the order: newest first or most liked first. */
+export function FeedFilters({ category, sort, onCategory, onSort }: Props) {
+ return <div className={styles.filters}>
+ <div className={styles.chips} role="group" aria-label="Category">
+ {['', ...communityCategories].map(value => <button key={value || 'all'} type="button" aria-pressed={category === value} onClick={() => onCategory(value)}>{value || 'All'}</button>)}
+ </div>
+ <div className={styles.sort} role="group" aria-label="Order">
+ {feedSorts.map(value => <button key={value} type="button" aria-pressed={sort === value} onClick={() => onSort(value)}>{sortLabels[value]}</button>)}
+ </div>
+ </div>;
+}
diff --git a/website/src/app/hub/components/Forks.tsx b/website/src/app/hub/components/Forks.tsx
new file mode 100644
index 000000000..ddfd3e03a
--- /dev/null
+++ b/website/src/app/hub/components/Forks.tsx
@@ -0,0 +1,18 @@
+'use client';
+import { FeedCard, FeedSkeleton } from './FeedCard';
+import { useFeed } from './useFeed';
+import styles from '../community.module.css';
+
+/** The public versions people made from this harness, newest first, paged like a feed. */
+export function Forks({ id, count }: { id: string; count: number }) {
+ const { posts, stats, cursor, settled, error, likeError, liking, busy, more, load, like } = useFeed({ forkedFrom: id });
+ return <section id="forks" className={styles.forks} aria-label="Forks">
+ <h2>Forks · {count}</h2>
+ {error && <p className={styles.notice} role="status">The forks could not be loaded.<button onClick={() => void load()}>Retry</button></p>}
+ {likeError && <p className={styles.notice} role="status">{likeError}</p>}
+ <div className={styles.grid} aria-busy={!settled}>
+ {settled ? posts.map(item => <FeedCard key={item.id} item={item} stats={stats[item.id]} liking={liking.has(item.id)} onLike={() => void like(item.id)} />) : <FeedSkeleton count={3} />}
+ </div>
+ <div ref={more}>{cursor && <button className={styles.more} disabled={busy} onClick={() => void load(cursor)}>{busy ? 'Loading…' : 'More forks'}</button>}</div>
+ </section>;
+}
diff --git a/website/src/app/hub/components/HarnessFiles.tsx b/website/src/app/hub/components/HarnessFiles.tsx
new file mode 100644
index 000000000..ca7fab234
--- /dev/null
+++ b/website/src/app/hub/components/HarnessFiles.tsx
@@ -0,0 +1,31 @@
+'use client';
+import { useState } from 'react';
+import type { SourceFile } from '@/lib/community/types';
+import styles from '../community.module.css';
+
+/** A file's size on disk: base64 holds three bytes in every four characters. */
+const size = (file: SourceFile) => {
+ const bytes = file.encoding ? Math.floor(file.content.length * 3 / 4) : new TextEncoder().encode(file.content).length;
+ return bytes < 1024 ? `${bytes} B` : `${Math.ceil(bytes / 1024)} KB`;
+};
+
+/** One file, its text drawn only once it is opened: a project's files run to megabytes. */
+function SourceFileRow({ file }: { file: SourceFile }) {
+ const [open, setOpen] = useState(false);
+ return <details className={styles.sourceFile} onToggle={event => setOpen(event.currentTarget.open)}>
+ <summary><code>{file.path}</code><small>{size(file)}</small></summary>
+ {open && (file.encoding ? <p className={styles.contextNote}>A binary file. Download the project to open it.</p> : <pre className={styles.sourceText}>{file.content}</pre>)}
+ </details>;
+}
+
+type Props = { id: string; files: SourceFile[] | null; error: string; onRetry: () => void };
+
+/** The project behind the output, readable here; the ZIP is for working on it in another editor. */
+export function HarnessFiles({ id, files, error, onRetry }: Props) {
+ if (error) return <p className={styles.notice} role="status">{error}<button onClick={onRetry}>Retry</button></p>;
+ if (!files) return <p className={styles.contextNote}>Loading files…</p>;
+ return <div>
+ {files.map(file => <SourceFileRow key={file.path} file={file} />)}
+ <p className={styles.contextNote}><a className={styles.textLink} href={`/hub/${id}/download`}>Download a ZIP</a> to open the project in another editor.</p>
+ </div>;
+}
diff --git a/website/src/app/hub/components/SearchField.tsx b/website/src/app/hub/components/SearchField.tsx
index 0c44a9645..0555b0735 100644
--- a/website/src/app/hub/components/SearchField.tsx
+++ b/website/src/app/hub/components/SearchField.tsx
@@ -1,7 +1,7 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Search, X } from 'lucide-react';
-import { searchMaxChars } from '@/lib/community/search';
+import { searchMaxChars } from '@/lib/community/feed';
import styles from '../community.module.css';
export type SearchFieldProps = { value: string; onChange: (value: string) => void; onClear: () => void };
diff --git a/website/src/app/hub/components/ShareButton.tsx b/website/src/app/hub/components/ShareButton.tsx
new file mode 100644
index 000000000..722ed97ea
--- /dev/null
+++ b/website/src/app/hub/components/ShareButton.tsx
@@ -0,0 +1,22 @@
+'use client';
+import { useEffect, useState } from 'react';
+import { Check, Link2 } from 'lucide-react';
+
+type Copy = 'idle' | 'copied' | 'failed';
+const labels: Record<Copy, string> = { idle: 'Share', copied: 'Link copied', failed: 'Copy failed' };
+
+/** Copies the harness's address, and says so for two seconds. */
+export function ShareButton({ id }: { id: string }) {
+ const [copy, setCopy] = useState<Copy>('idle');
+ useEffect(() => {
+ if (copy === 'idle') return;
+ const timer = setTimeout(() => setCopy('idle'), 2000);
+ return () => clearTimeout(timer);
+ }, [copy]);
+ async function share() {
+ try { await navigator.clipboard.writeText(`${window.location.origin}/hub/${id}`); setCopy('copied'); } catch { setCopy('failed'); }
+ }
+ return <button type="button" aria-label="Copy link to this harness" onClick={() => void share()}>
+ {copy === 'copied' ? <Check /> : <Link2 />}<span aria-live="polite">{labels[copy]}</span>
+ </button>;
+}
diff --git a/website/src/app/hub/components/SidePanel.tsx b/website/src/app/hub/components/SidePanel.tsx
new file mode 100644
index 000000000..67f9fcf81
--- /dev/null
+++ b/website/src/app/hub/components/SidePanel.tsx
@@ -0,0 +1,32 @@
+'use client';
+import { X } from 'lucide-react';
+import { commentTotal } from '@/lib/community/comments';
+import type { HarnessComment, OpenHarness, SocialState } from '@/lib/community/types';
+import { Comments } from './Comments';
+import type { Panel } from './DetailHead';
+import { HarnessFiles } from './HarnessFiles';
+import { HarnessTags } from './HarnessTags';
+import { Transcript } from './Transcript';
+import { useHarnessFiles } from './useHarnessFiles';
+import styles from '../community.module.css';
+
+type Props = {
+ harness: OpenHarness; social: SocialState; ready: boolean; busy: boolean; panel: Panel; error: string;
+ onClose: () => void; onRetry: () => void; onRemove: (comment: HarnessComment) => void;
+ onPost: (body: string, clientId: string, parentId?: string) => Promise<boolean>;
+};
+
+const titles: Record<Panel, string> = { log: 'Chat log', comments: 'Comments', files: 'Source files' };
+
+/** Beside the output: the agent's chat log, or the comments, or the project's files. */
+export function SidePanel({ harness, social, ready, busy, panel, error, onClose, onRetry, onRemove, onPost }: Props) {
+ const files = useHarnessFiles(harness.id, panel === 'files');
+ const title = panel === 'comments' && ready ? `Comments · ${commentTotal(social)}` : titles[panel];
+ return <aside className={styles.chat} aria-label={panel === 'log' ? 'Agent chat log' : titles[panel]}>
+ <div className={styles.chatHead}><h2>{title}</h2>{panel === 'log' ? <HarnessTags harness={harness} /> : <button className={styles.icon} onClick={onClose} aria-label="Back to chat log"><X /></button>}</div>
+ {panel === 'log' && <Transcript harness={harness} />}
+ {panel === 'comments' && <Comments social={social} ready={ready} busy={busy} onRetry={onRetry} onRemove={onRemove} onPost={onPost} />}
+ {panel === 'files' && <HarnessFiles id={harness.id} files={files.files} error={files.error} onRetry={() => void files.load()} />}
+ {error && <p className={styles.error} role="alert">{error}</p>}
+ </aside>;
+}
diff --git a/website/src/app/hub/components/Viewer.tsx b/website/src/app/hub/components/Viewer.tsx
new file mode 100644
index 000000000..14750e229
--- /dev/null
+++ b/website/src/app/hub/components/Viewer.tsx
@@ -0,0 +1,37 @@
+'use client';
+import { useRef, useSyncExternalStore, type RefObject } from 'react';
+import { Maximize2, Minimize2 } from 'lucide-react';
+import { previewDocument } from '@/lib/community/preview';
+import type { OpenHarness } from '@/lib/community/types';
+import styles from '../community.module.css';
+
+const onFullscreenChange = (notify: () => void) => {
+ document.addEventListener('fullscreenchange', notify);
+ return () => document.removeEventListener('fullscreenchange', notify);
+};
+
+/** Whether `target` fills the screen, and a toggle for it. The server draws no toggle. */
+function useFullscreen(target: RefObject<HTMLElement | null>) {
+ const supported = useSyncExternalStore(onFullscreenChange, () => document.fullscreenEnabled, () => false);
+ const active = useSyncExternalStore(onFullscreenChange, () => !!target.current && document.fullscreenElement === target.current, () => false);
+ const toggle = () => { void (document.fullscreenElement ? document.exitFullscreen() : target.current?.requestFullscreen()); };
+ return { supported, active, toggle };
+}
+
+/**
+ * The output beside its source conversation, or a starter's recorded run. The output can fill the
+ * screen; it never opens in its own tab, where it would run on the Hub's origin instead of in the sandbox.
+ */
+export function Viewer({ harness }: { harness: OpenHarness }) {
+ const section = useRef<HTMLElement>(null), fullscreen = useFullscreen(section);
+ const html = harness.files.find(file => file.path === harness.viewerPath)?.content || '';
+ if (harness.recording) return <section className={styles.viewer} aria-label="Output viewer">
+ <video className={styles.recording} controls playsInline preload="metadata" poster={harness.cover} aria-label={`${harness.title} recorded run`} src={harness.recording} />
+ </section>;
+ return <section ref={section} className={styles.viewer} aria-label="Output viewer">
+ <iframe title={`${harness.title} output`} srcDoc={previewDocument(html)} sandbox={harness.example ? 'allow-scripts allow-downloads allow-modals' : 'allow-scripts'} referrerPolicy="no-referrer" />
+ {fullscreen.supported && <button type="button" className={styles.viewerButton} onClick={fullscreen.toggle} aria-label={fullscreen.active ? 'Exit full screen' : 'View output full screen'} title={fullscreen.active ? 'Exit full screen' : 'Full screen'}>
+ {fullscreen.active ? <Minimize2 /> : <Maximize2 />}
+ </button>}
+ </section>;
+}
diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsx
index 50bfd30d6..e407d3ddc 100644
--- a/website/src/app/hub/components/community.spec.tsx
+++ b/website/src/app/hub/components/community.spec.tsx
@@ -8,7 +8,8 @@ import type { OpenHarness } from '@/lib/community/types';
const request = vi.hoisted(() => vi.fn());
vi.mock('@/lib/community/client', async importActual => ({ ...await importActual<typeof import('@/lib/community/client')>(), communityRequest: request }));
const sample: OpenHarness = { id: 'starter-orbit', title: 'Orbit', description: 'A small model', category: 'Experiments', engine: 'Codex', authorId: 'harness', authorName: 'Harness', createdAt: '2026-10-05', files: [{ path: 'index.html', content: '<h1>Orbit</h1>' }], viewerPath: 'index.html', conversation: [{ role: 'user', text: 'Make an orbit.' }], example: true };
-beforeEach(() => request.mockReset());
+// A block, not an expression: vitest runs a function returned from beforeEach as the test's cleanup.
+beforeEach(() => { request.mockReset(); });
describe('community navigation', () => {
it('lets creators reply to a specific comment without replacing the output', async () => {
const comment = { id: 'comment-1', body: 'How did you make this?', authorName: 'Bob', mine: false, createdAt: '2026-10-06' };
@@ -39,6 +40,9 @@ describe('community navigation', () => {
it('renders eighteen linked starter projects, with no fake engagement, and searches them', async () => {
request.mockResolvedValue({ harnesses: [], nextCursor: null, following: [] });
render(<Feed />);
+ // Nothing is drawn under the first page until it answers: the grid would jump when it lands.
+ expect(screen.queryAllByRole('link', { name: /^Open / })).toHaveLength(0);
+ await screen.findByRole('link', { name: 'Open One more jump' });
expect(screen.getAllByRole('link', { name: /^Open / }).filter(link => link.getAttribute('href')?.startsWith('/hub/starter-'))).toHaveLength(18);
expect(screen.getByRole('link', { name: 'Open One more jump' })).toHaveAttribute('href', '/hub/starter-moonlight');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
@@ -109,16 +113,22 @@ describe('community navigation', () => {
request.mockResolvedValueOnce({ harness: { ...sample, id }, social: emptySocial }).mockResolvedValue({ social: { ...emptySocial, likes: 3 } });
render(<Detail id={id} initial={null} />);
await screen.findByTitle('Orbit output');
- expect(request).toHaveBeenLastCalledWith(`harnesses/${id}`);
- act(() => { window.dispatchEvent(new Event('focus')); });
+ expect(request).toHaveBeenLastCalledWith(`harnesses/${id}?files=viewer`);
+ // Coming back within half a minute (or clicking out of the output) reads nothing.
+ act(() => { document.dispatchEvent(new Event('visibilitychange')); window.dispatchEvent(new Event('focus')); });
+ expect(request).toHaveBeenCalledTimes(1);
+ const now = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(now + 31_000);
+ act(() => { document.dispatchEvent(new Event('visibilitychange')); });
await waitFor(() => expect(screen.getByRole('button', { name: 'Like harness' })).toHaveTextContent('3'));
expect(request).toHaveBeenLastCalledWith(`harnesses/${id}/social`);
+ vi.restoreAllMocks();
});
it('still loads beside a backend that has no social route yet', async () => {
request.mockRejectedValueOnce(new CommunityError('Not found.', 404)).mockResolvedValueOnce({ harness: null, social: { ...emptySocial, likes: 2 } });
render(<Detail id={sample.id} initial={sample} />);
await waitFor(() => expect(screen.getByRole('button', { name: 'Like harness' })).toHaveTextContent('2'));
- expect(request.mock.calls.map(call => call[0])).toEqual(['harnesses/starter-orbit/social', 'harnesses/starter-orbit']);
+ expect(request.mock.calls.map(call => call[0])).toEqual(['harnesses/starter-orbit/social', 'harnesses/starter-orbit?files=viewer']);
expect(screen.queryByText('This harness is unavailable.')).not.toBeInTheDocument();
});
it('does not pretend a signed-out like succeeded', async () => {
@@ -139,4 +149,72 @@ describe('community navigation', () => {
await waitFor(() => expect(screen.getByRole('button', { name: 'Unlike harness' })).toHaveTextContent('1'));
expect(request).toHaveBeenLastCalledWith('harnesses/starter-orbit/like', { method: 'PUT', body: { liked: true } });
});
+ it('narrows the feed by category and order, for publications and starters alike', async () => {
+ request.mockResolvedValue({ harnesses: [], nextCursor: null, following: [], stats: {} });
+ render(<Feed />);
+ await screen.findByRole('link', { name: 'Open One more jump' });
+ fireEvent.click(screen.getByRole('button', { name: 'Music' }));
+ await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?category=Music'));
+ expect(screen.getByRole('link', { name: 'Open Blue hour' })).toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Open One more jump' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Popular' }));
+ await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?category=Music&sort=popular'));
+ expect(window.location.search).toBe('?category=Music&sort=popular');
+ fireEvent.click(screen.getByRole('button', { name: 'All' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Newest' }));
+ await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?'));
+ expect(window.location.search).toBe('');
+ });
+ it('holds a feed like until the server answers, and shows the forks a card has', async () => {
+ request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'first' }], nextCursor: null, following: [], stats: { first: { likes: 1, comments: 0, liked: false, forks: 2 } }, signedIn: true });
+ render(<Feed mine />);
+ await screen.findByRole('link', { name: 'Forks of Orbit' });
+ let answer: (value: unknown) => void = () => {};
+ request.mockReturnValueOnce(new Promise(resolve => { answer = resolve; }));
+ fireEvent.click(screen.getByRole('button', { name: 'Like Orbit' }));
+ expect(screen.getByRole('button', { name: 'Like Orbit' })).toBeDisabled();
+ await act(async () => answer({ liked: true, likes: 2 }));
+ expect(screen.getByRole('button', { name: 'Unlike Orbit' })).toHaveTextContent('2');
+ expect(screen.getByRole('button', { name: 'Unlike Orbit' })).toBeEnabled();
+ });
+ it('counts every comment, threads replies, and lists the forks', async () => {
+ const parent = { id: 'c1', body: 'First', authorName: 'Bob', mine: false, createdAt: '2026-10-06' };
+ const other = { id: 'c2', body: 'Second', authorName: 'Cy', mine: false, createdAt: '2026-10-07' };
+ const reply = { id: 'c3', body: 'Reply', authorName: 'Alice', mine: false, createdAt: '2026-10-08', parentId: 'c1', parentAuthorName: 'Bob' };
+ request.mockImplementation(async (path: string) => { return path.startsWith('harnesses?')
+ ? { harnesses: [{ ...sample, id: 'fork-1', title: 'My orbit' }], nextCursor: null, following: [], stats: {} }
+ : { harness: null, social: { ...emptySocial, comments: [parent, other, reply], commentCount: 140, forks: 1 } }; });
+ render(<Detail id={sample.id} initial={sample} initialComments />);
+ await screen.findByText('Showing the latest 3 of 140 comments.');
+ expect(screen.getByRole('heading', { name: 'Comments · 140' })).toBeInTheDocument();
+ expect(screen.getAllByText(/^(First|Second|Reply)$/).map(node => node.textContent)).toEqual(['First', 'Reply', 'Second']);
+ expect(screen.getByRole('link', { name: '1 fork' })).toHaveAttribute('href', '#forks');
+ await screen.findByRole('link', { name: 'Open My orbit' });
+ expect(request).toHaveBeenCalledWith('harnesses?forkedFrom=starter-orbit');
+ });
+ it('reads source files only when the reader opens them', async () => {
+ request.mockResolvedValue({ harness: null, social: emptySocial });
+ const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ version: 1, harness: { ...sample, files: [...sample.files, { path: 'src/orbit.js', content: 'const radius = 3;' }] } }));
+ render(<Detail id={sample.id} initial={sample} />);
+ await act(async () => {});
+ expect(fetcher).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Source files' }));
+ await screen.findByText('src/orbit.js');
+ expect(fetcher).toHaveBeenCalledWith('/hub/starter-orbit/snapshot', { cache: 'no-store' });
+ expect(screen.queryByText('const radius = 3;')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText('src/orbit.js'));
+ expect(await screen.findByText('const radius = 3;')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Source files' }));
+ expect(screen.getByText('Make an orbit.')).toBeInTheDocument();
+ fetcher.mockRestore();
+ });
+ it('copies the harness link', async () => {
+ request.mockResolvedValue({ harness: null, social: emptySocial });
+ const writeText = vi.fn(async () => {});
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ render(<Detail id={sample.id} initial={sample} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Copy link to this harness' }));
+ await screen.findByText('Link copied');
+ expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/hub/starter-orbit`);
+ });
});
diff --git a/website/src/app/hub/components/useFeed.ts b/website/src/app/hub/components/useFeed.ts
index a9cc6559c..15dbb097e 100644
--- a/website/src/app/hub/components/useFeed.ts
+++ b/website/src/app/hub/components/useFeed.ts
@@ -1,29 +1,32 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { communityRequest, CommunityError } from '@/lib/community/client';
+import { feedPath, type FeedQuery } from '@/lib/community/feed';
import type { HarnessSummary } from '@/lib/community/types';
-export type Stats = { likes: number; comments: number; liked: boolean };
+/** `forks` comes from a backend that counts them; an older one leaves it out. */
+export type Stats = { likes: number; comments: number; liked: boolean; forks?: number };
type FeedResult = { harnesses: HarnessSummary[]; nextCursor: string | null; following: string[]; stats?: Record<string, Stats>; signedIn?: boolean };
/**
- * One feed's pages, their likes and comment counts, and the reader's likes. Pages load as `more`
- * scrolls into view; a newer load supersedes an older one, and a sign-in, a sign-out or a new search
- * (`query`, matched by the server across every publication) reloads.
+ * One feed's pages, their likes, comments and forks, and the reader's likes. Pages load as `more`
+ * scrolls into view; a newer load supersedes an older one, and a sign-in, a sign-out or a new view
+ * (matched by the server across every publication) reloads. `settled` turns true once the first
+ * page has answered, so what is drawn under the pages waits for them instead of jumping.
*/
-export function useFeed({ following, mine, query }: { following: boolean; mine: boolean; query: string }) {
+export function useFeed({ following, mine, forkedFrom, query, category, sort }: FeedQuery) {
const [posts, setPosts] = useState<HarnessSummary[]>([]), [follows, setFollows] = useState<string[]>([]);
const [stats, setStats] = useState<Record<string, Stats>>({}), [signedIn, setSignedIn] = useState(false);
- const [cursor, setCursor] = useState<string | null>(null);
+ const [cursor, setCursor] = useState<string | null>(null), [settled, setSettled] = useState(false);
const [error, setError] = useState(''), [likeError, setLikeError] = useState(''), [signedOut, setSignedOut] = useState(false), [busy, setBusy] = useState(false);
+ const [liking, setLiking] = useState<ReadonlySet<string>>(new Set());
const generation = useRef(0), loading = useRef(false), pendingLikes = useRef(new Set<string>()), more = useRef<HTMLDivElement>(null);
const load = useCallback(async (after?: string) => {
if (after && loading.current) return;
const requestId = ++generation.current;
loading.current = true; setBusy(true); setError(''); setSignedOut(false);
try {
- const params = new URLSearchParams(); if (following) params.set('following', 'true'); if (mine) params.set('mine', 'true'); if (query) params.set('q', query); if (after) params.set('cursor', after);
- const result = await communityRequest<FeedResult>(`harnesses?${params}`);
+ const result = await communityRequest<FeedResult>(feedPath({ following, mine, forkedFrom, query, category, sort }, after));
if (requestId !== generation.current) return;
setPosts(previous => after ? [...previous, ...result.harnesses.filter(item => !previous.some(p => p.id === item.id))] : result.harnesses);
setStats(previous => after ? { ...previous, ...result.stats } : result.stats || {});
@@ -32,8 +35,8 @@ export function useFeed({ following, mine, query }: { following: boolean; mine:
if (requestId !== generation.current) return;
if (e instanceof CommunityError && e.status === 401) setSignedOut(true);
else setError('Community posts are temporarily unavailable. You can still explore and fork the starter projects.');
- } finally { if (requestId === generation.current) { loading.current = false; setBusy(false); } }
- }, [following, mine, query]);
+ } finally { if (requestId === generation.current) { loading.current = false; setBusy(false); setSettled(true); } }
+ }, [following, mine, forkedFrom, query, category, sort]);
useEffect(() => {
void load(); const reload = () => { void load(); };
window.addEventListener('storage', reload); window.addEventListener('harness-session', reload);
@@ -44,10 +47,15 @@ export function useFeed({ following, mine, query }: { following: boolean; mine:
const observer = new IntersectionObserver(entries => { if (entries.some(entry => entry.isIntersecting)) void load(cursor); }, { rootMargin: '500px' });
observer.observe(more.current); return () => observer.disconnect();
}, [cursor, busy, error, load]);
+ /** Marks a like as sent or answered: the ref stops a second click at once, the state draws it. */
+ const pending = (id: string, sending: boolean) => {
+ if (sending) pendingLikes.current.add(id); else pendingLikes.current.delete(id);
+ setLiking(new Set(pendingLikes.current));
+ };
async function like(id: string) {
if (!signedIn) { setSignedOut(true); return; }
if (pendingLikes.current.has(id)) return;
- pendingLikes.current.add(id); setLikeError('');
+ pending(id, true); setLikeError('');
try {
const result = await communityRequest<{ liked: boolean; likes: number }>(`harnesses/${id}/like`, { method: 'PUT', body: { liked: !stats[id]?.liked } });
setStats(previous => ({ ...previous, [id]: { ...previous[id], comments: previous[id]?.comments || 0, ...result } }));
@@ -55,7 +63,7 @@ export function useFeed({ following, mine, query }: { following: boolean; mine:
if (e instanceof CommunityError && e.status === 401) setSignedOut(true);
// Not the feed's error: that one offers to reload the feed and pauses its paging.
else setLikeError(e instanceof Error ? e.message : 'Could not save your like. Try again.');
- } finally { pendingLikes.current.delete(id); }
+ } finally { pending(id, false); }
}
- return { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like };
+ return { posts, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like };
}
diff --git a/website/src/app/hub/components/useFeedSearch.ts b/website/src/app/hub/components/useFeedSearch.ts
deleted file mode 100644
index 623bc08cd..000000000
--- a/website/src/app/hub/components/useFeedSearch.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-'use client';
-import { useEffect, useState } from 'react';
-
-const settleMs = 250;
-
-/**
- * What the reader is typing, and the settled term the feed asks the server for. The term is kept in
- * the page's `?q=`, so a search can be shared and survives a reload; clearing takes effect at once.
- */
-export function useFeedSearch(initial = '') {
- const [query, setQuery] = useState(initial), [term, setTerm] = useState(initial);
- useEffect(() => {
- const timer = setTimeout(() => setTerm(query.trim()), settleMs);
- return () => clearTimeout(timer);
- }, [query]);
- useEffect(() => {
- const url = new URL(window.location.href);
- if (term) url.searchParams.set('q', term);
- else url.searchParams.delete('q');
- if (url.href !== window.location.href) window.history.replaceState(window.history.state, '', url);
- }, [term]);
- const clear = () => { setQuery(''); setTerm(''); };
- return { query, setQuery, term, clear };
-}
diff --git a/website/src/app/hub/components/useFeedView.ts b/website/src/app/hub/components/useFeedView.ts
new file mode 100644
index 000000000..efb5bfd3d
--- /dev/null
+++ b/website/src/app/hub/components/useFeedView.ts
@@ -0,0 +1,23 @@
+'use client';
+import { useEffect, useState } from 'react';
+import { replaceAddressParams, type FeedSort, type FeedView } from '@/lib/community/feed';
+
+const settleMs = 250;
+
+/**
+ * How the reader narrows the feed. `query` is what they are typing; the view carries the settled
+ * search the feed asks the server for. The view is kept in the page's `?q=`, `?category=` and
+ * `?sort=`, so it can be shared and survives a reload; clearing the search takes effect at once.
+ */
+export function useFeedView(initial: FeedView) {
+ const [query, setQuery] = useState(initial.query), [term, setTerm] = useState(initial.query);
+ const [category, setCategory] = useState(initial.category), [sort, setSort] = useState<FeedSort>(initial.sort);
+ useEffect(() => {
+ const timer = setTimeout(() => setTerm(query.trim()), settleMs);
+ return () => clearTimeout(timer);
+ }, [query]);
+ useEffect(() => replaceAddressParams({ q: term, category, sort: sort === 'newest' ? '' : sort }), [term, category, sort]);
+ const clear = () => { setQuery(''); setTerm(''); };
+ const view: FeedView = { query: term, category, sort };
+ return { view, query, setQuery, clear, setCategory, setSort };
+}
diff --git a/website/src/app/hub/components/useHarnessDetail.ts b/website/src/app/hub/components/useHarnessDetail.ts
index 488632fc3..b3480d1a5 100644
--- a/website/src/app/hub/components/useHarnessDetail.ts
+++ b/website/src/app/hub/components/useHarnessDetail.ts
@@ -1,7 +1,9 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { communityRequest, emptySocial, CommunityError } from '@/lib/community/client';
+import { commentTotal } from '@/lib/community/comments';
import type { HarnessComment, OpenHarness, SocialState } from '@/lib/community/types';
+import { useRefreshOnReturn } from './useRefreshOnReturn';
/**
* One harness page's data and the reader's actions on it. Writes run one at a time, and a read that
@@ -15,7 +17,7 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
/**
* A publication never changes: once its files are here, a refresh reads only likes, follows and
* comments. A backend older than `/social` answers 404 there, so the full read tells that apart
- * from an unpublished harness.
+ * from an unpublished harness. The page draws only the output, so the full read asks for that file.
*/
const read = useCallback(async () => {
type Page = { harness?: OpenHarness | null; social: SocialState };
@@ -24,7 +26,7 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
if (!(e instanceof CommunityError && e.status === 404)) throw e;
}
}
- return communityRequest<Page>(`harnesses/${id}`);
+ return communityRequest<Page>(`harnesses/${id}?files=viewer`);
}, [id]);
const load = useCallback(async () => {
if (writing.current) return;
@@ -43,10 +45,10 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
}, [read, initial]);
useEffect(() => {
void load();
- const reload = () => { void load(); };
- window.addEventListener('focus', reload);
- return () => { revision.current++; window.removeEventListener('focus', reload); };
+ return () => { revision.current++; };
}, [load]);
+ const reload = useCallback(() => { void load(); }, [load]);
+ useRefreshOnReturn(reload);
/** Runs one write, reporting whether it succeeded. */
async function mutate(action: () => Promise<void>): Promise<boolean> {
@@ -63,8 +65,9 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
}
const follow = () => mutate(async () => {
+ if (!harness) return;
const next = !social.following;
- await communityRequest(`creators/${harness!.authorId}/follow`, { method: 'PUT', body: { following: next } });
+ await communityRequest(`creators/${harness.authorId}/follow`, { method: 'PUT', body: { following: next } });
setSocial(value => ({ ...value, following: next }));
});
const like = () => mutate(async () => {
@@ -73,12 +76,16 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
});
const removeComment = (comment: HarnessComment) => mutate(async () => {
await communityRequest(`harnesses/${id}/comments/${comment.id}`, { method: 'DELETE' });
- setSocial(value => ({ ...value, comments: value.comments.filter(item => item.id !== comment.id) }));
+ setSocial(value => ({ ...value, comments: value.comments.filter(item => item.id !== comment.id), commentCount: commentTotal(value) - 1 }));
});
/** `clientId` makes a retried post return the same comment rather than a second one. */
const postComment = (body: string, clientId: string, parentId?: string) => mutate(async () => {
const data = await communityRequest<{ comment: HarnessComment }>(`harnesses/${id}/comments`, { method: 'POST', body: { body, clientId, ...(parentId ? { parentId } : {}) } });
- setSocial(value => ({ ...value, comments: [...value.comments.filter(item => item.id !== data.comment.id), data.comment] }));
+ // A retried post answers with the comment it already made: replaced, not counted twice.
+ setSocial(value => {
+ const known = value.comments.some(item => item.id === data.comment.id);
+ return { ...value, comments: [...value.comments.filter(item => item.id !== data.comment.id), data.comment], commentCount: commentTotal(value) + (known ? 0 : 1) };
+ });
});
const unpublish = () => mutate(async () => {
await communityRequest(`harnesses/${id}`, { method: 'DELETE' });
diff --git a/website/src/app/hub/components/useHarnessFiles.ts b/website/src/app/hub/components/useHarnessFiles.ts
new file mode 100644
index 000000000..9e914d284
--- /dev/null
+++ b/website/src/app/hub/components/useHarnessFiles.ts
@@ -0,0 +1,26 @@
+'use client';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { communityRequest, starterSnapshot } from '@/lib/community/client';
+import type { OpenHarness, SourceFile } from '@/lib/community/types';
+
+/**
+ * A harness's source files, read the first time the reader asks for them (`wanted`): a starter's
+ * from this site, a publication's from the Hub. The page itself carries only the output.
+ */
+export function useHarnessFiles(id: string, wanted: boolean) {
+ const [files, setFiles] = useState<SourceFile[] | null>(null), [error, setError] = useState('');
+ const started = useRef(false);
+ const load = useCallback(async () => {
+ setError('');
+ try {
+ const harness = id.startsWith('starter-') ? await starterSnapshot(id) : (await communityRequest<{ harness: OpenHarness | null }>(`harnesses/${id}`)).harness;
+ if (!harness) throw new Error('Harness unavailable.');
+ setFiles(harness.files);
+ } catch { setError('The source files could not be loaded.'); }
+ }, [id]);
+ useEffect(() => {
+ if (!wanted || started.current) return;
+ started.current = true; void load();
+ }, [wanted, load]);
+ return { files, error, load };
+}
diff --git a/website/src/app/hub/components/useRefreshOnReturn.ts b/website/src/app/hub/components/useRefreshOnReturn.ts
new file mode 100644
index 000000000..d90ef6bae
--- /dev/null
+++ b/website/src/app/hub/components/useRefreshOnReturn.ts
@@ -0,0 +1,23 @@
+'use client';
+import { useEffect } from 'react';
+import { sessionHeaders } from '@/lib/community/client';
+
+const minGapMs = 30_000;
+
+/**
+ * Calls `refresh` when the reader comes back to this tab: at once after a sign-in or sign-out
+ * elsewhere, otherwise at most every 30 seconds. Clicking into a page's output and back is not a return.
+ */
+export function useRefreshOnReturn(refresh: () => void) {
+ useEffect(() => {
+ let last = Date.now(), session = sessionHeaders().Authorization;
+ const onVisible = () => {
+ if (document.visibilityState !== 'visible') return;
+ const current = sessionHeaders().Authorization;
+ if (current === session && Date.now() - last < minGapMs) return;
+ last = Date.now(); session = current; refresh();
+ };
+ document.addEventListener('visibilitychange', onVisible);
+ return () => document.removeEventListener('visibilitychange', onVisible);
+ }, [refresh]);
+}
diff --git a/website/src/app/hub/following/page.tsx b/website/src/app/hub/following/page.tsx
index 4e6205ffa..6384891e0 100644
--- a/website/src/app/hub/following/page.tsx
+++ b/website/src/app/hub/following/page.tsx
@@ -1,4 +1,4 @@
-import { searchFromParams } from '@/lib/community/search';
+import { feedViewFromParams, type FeedViewParams } from '@/lib/community/feed';
import Feed from '../components/Feed';
-type Props = { searchParams: Promise<{ q?: string | string[] }> };
-export default async function FollowingPage({ searchParams }: Props) { return <Feed following initialQuery={await searchFromParams(searchParams)} />; }
+type Props = { searchParams: Promise<FeedViewParams> };
+export default async function FollowingPage({ searchParams }: Props) { return <Feed following initialView={await feedViewFromParams(searchParams)} />; }
diff --git a/website/src/app/hub/layout.tsx b/website/src/app/hub/layout.tsx
index c1a711304..16cc71f1d 100644
--- a/website/src/app/hub/layout.tsx
+++ b/website/src/app/hub/layout.tsx
@@ -1,6 +1,7 @@
import type { Metadata, Viewport } from 'next';
import styles from './community.module.css';
-export const metadata: Metadata = { title: { default: 'Harness Hub — Discover, fork, create', template: '%s — Harness Hub' }, description: 'Discover what people make with agents. Like the work, join the conversation, fork your own version, and publish what you make.' };
+/** Absolute addresses for link previews (a harness's cover); the Hub is served from this origin. */
+export const metadata: Metadata = { metadataBase: new URL('https://harness.autonomous.ai'), title: { default: 'Harness Hub — Discover, fork, create', template: '%s — Harness Hub' }, description: 'Discover what people make with agents. Like the work, join the conversation, fork your own version, and publish what you make.' };
export const viewport: Viewport = { themeColor: '#ffffff' };
export default function ExploreLayout({ children }: { children: React.ReactNode }) { return <div className={styles.page}>{children}</div>; }
diff --git a/website/src/app/hub/page.tsx b/website/src/app/hub/page.tsx
index 2178bc9e8..34fd2f48e 100644
--- a/website/src/app/hub/page.tsx
+++ b/website/src/app/hub/page.tsx
@@ -1,4 +1,4 @@
-import { searchFromParams } from '@/lib/community/search';
+import { feedViewFromParams, type FeedViewParams } from '@/lib/community/feed';
import Feed from './components/Feed';
-type Props = { searchParams: Promise<{ q?: string | string[] }> };
-export default async function ExplorePage({ searchParams }: Props) { return <Feed initialQuery={await searchFromParams(searchParams)} />; }
+type Props = { searchParams: Promise<FeedViewParams> };
+export default async function ExplorePage({ searchParams }: Props) { return <Feed initialView={await feedViewFromParams(searchParams)} />; }
diff --git a/website/src/app/hub/yours/page.tsx b/website/src/app/hub/yours/page.tsx
index 975844ddf..947012f0e 100644
--- a/website/src/app/hub/yours/page.tsx
+++ b/website/src/app/hub/yours/page.tsx
@@ -1,4 +1,4 @@
-import { searchFromParams } from '@/lib/community/search';
+import { feedViewFromParams, type FeedViewParams } from '@/lib/community/feed';
import Feed from '../components/Feed';
-type Props = { searchParams: Promise<{ q?: string | string[] }> };
-export default async function YoursPage({ searchParams }: Props) { return <Feed mine initialQuery={await searchFromParams(searchParams)} />; }
+type Props = { searchParams: Promise<FeedViewParams> };
+export default async function YoursPage({ searchParams }: Props) { return <Feed mine initialView={await feedViewFromParams(searchParams)} />; }
diff --git a/website/src/lib/community/client.ts b/website/src/lib/community/client.ts
index 60361149f..40e2afe4b 100644
--- a/website/src/lib/community/client.ts
+++ b/website/src/lib/community/client.ts
@@ -1,4 +1,4 @@
-import type { SocialState } from './types';
+import type { OpenHarness, SocialState } from './types';
import { refreshHubSession } from './session';
/** Read the existing Harness web session; the community does not mint a second identity. */
@@ -37,4 +37,11 @@ export async function communityRequest<T>(path: string, options: { method?: stri
return body.data as T;
}
+/** A starter's whole project, which this site serves itself (the Hub stores only publications). */
+export async function starterSnapshot(id: string): Promise<OpenHarness | null> {
+ const response = await fetch(`/hub/${id}/snapshot`, { cache: 'no-store' });
+ if (!response.ok) return null;
+ return (await response.json() as { harness: OpenHarness }).harness;
+}
+
export const emptySocial: SocialState = { likes: 0, liked: false, following: false, comments: [], signedIn: false, mine: false };
diff --git a/website/src/lib/community/comments.spec.ts b/website/src/lib/community/comments.spec.ts
new file mode 100644
index 000000000..15664c8e5
--- /dev/null
+++ b/website/src/lib/community/comments.spec.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { commentTotal, threadComments } from './comments';
+import type { HarnessComment } from './types';
+
+const comment = (id: string, parentId?: string): HarnessComment => ({ id, parentId, body: id, authorName: 'A', createdAt: '2026-10-09', mine: false });
+
+describe('threadComments', () => {
+ it('draws each reply, and a reply to a reply, under the comment that started the conversation', () => {
+ const ordered = threadComments([comment('a'), comment('b'), comment('a1', 'a'), comment('b1', 'b'), comment('a2', 'a1')]);
+ expect(ordered.map(item => item.id)).toEqual(['a', 'a1', 'a2', 'b', 'b1']);
+ });
+ it('keeps a reply to a missing comment where it was posted, and survives a cycle', () => {
+ expect(threadComments([comment('a'), comment('x1', 'gone'), comment('b')]).map(item => item.id)).toEqual(['a', 'x1', 'b']);
+ expect(threadComments([comment('p', 'q'), comment('q', 'p')])).toHaveLength(2);
+ });
+ it('counts every comment when the backend says how many there are', () => {
+ expect(commentTotal({ comments: [comment('a')], commentCount: 140 })).toBe(140);
+ expect(commentTotal({ comments: [comment('a')] })).toBe(1);
+ });
+});
diff --git a/website/src/lib/community/comments.ts b/website/src/lib/community/comments.ts
new file mode 100644
index 000000000..0fd9487bb
--- /dev/null
+++ b/website/src/lib/community/comments.ts
@@ -0,0 +1,29 @@
+import type { HarnessComment } from './types';
+
+/**
+ * Comments in reading order: each conversation under the comment that started it, oldest first.
+ * A reply whose comment is gone (deleted, or older than the comments read) stays where it was posted.
+ */
+export function threadComments(comments: HarnessComment[]): HarnessComment[] {
+ const byId = new Map(comments.map(comment => [comment.id, comment]));
+ const rootOf = (comment: HarnessComment) => {
+ let current = comment;
+ // Bounded by the list's length, so a malformed cycle cannot loop.
+ for (let depth = 0; depth < comments.length; depth++) {
+ const parent = current.parentId ? byId.get(current.parentId) : undefined;
+ if (!parent) break;
+ current = parent;
+ }
+ return current.id;
+ };
+ const threads = new Map<string, HarnessComment[]>();
+ for (const comment of comments) {
+ const root = rootOf(comment), thread = threads.get(root);
+ if (thread) thread.push(comment);
+ else threads.set(root, [comment]);
+ }
+ return [...threads.values()].flat();
+}
+
+/** How many comments a harness has: the backend's count, or the ones read from an older backend. */
+export const commentTotal = (social: { comments: HarnessComment[]; commentCount?: number }) => social.commentCount ?? social.comments.length;
diff --git a/website/src/lib/community/community.spec.ts b/website/src/lib/community/community.spec.ts
index 206a66cfb..9dbf4464e 100644
--- a/website/src/lib/community/community.spec.ts
+++ b/website/src/lib/community/community.spec.ts
@@ -27,6 +27,11 @@ describe('portable starter projects', () => {
expect(new TextDecoder().decode(zip)).toContain(harness.files[0].content);
}
});
+ it('reads only the output for a harness page, not a starter\'s megabytes of source', async () => {
+ const full = (await getStarter('starter-two-futures'))!, page = (await getStarter('starter-two-futures', { viewerOnly: true }))!;
+ expect(full.files.length).toBeGreaterThan(1);
+ expect(page.files).toEqual([full.files.find(file => file.path === full.viewerPath)]);
+ });
it('rejects path traversal and retains copyright from the fork lineage', async () => {
expect(() => zipFiles([{ path: '../evil', content: 'oops' }])).toThrow('Invalid project path');
const harness = (await getStarter('starter-orbit'))!;
diff --git a/website/src/lib/community/feed.spec.ts b/website/src/lib/community/feed.spec.ts
new file mode 100644
index 000000000..2fa3c4d96
--- /dev/null
+++ b/website/src/lib/community/feed.spec.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+import { feedPath, feedViewFromParams } from './feed';
+
+describe('feed requests', () => {
+ it('leaves defaults out, so an older backend reads the request as before', () => {
+ expect(feedPath({ query: '', category: '', sort: 'newest' })).toBe('harnesses?');
+ expect(feedPath({ mine: true, query: 'orbit', category: 'Games', sort: 'popular' }, 'next')).toBe('harnesses?mine=true&q=orbit&category=Games&sort=popular&cursor=next');
+ expect(feedPath({ forkedFrom: 'starter-orbit' })).toBe('harnesses?forkedFrom=starter-orbit');
+ });
+ it('reads a shared address, dropping what the Hub does not offer', async () => {
+ expect(await feedViewFromParams(Promise.resolve({ q: ` ${'a'.repeat(90)} `, category: 'Games', sort: 'popular' }))).toEqual({ query: 'a'.repeat(80), category: 'Games', sort: 'popular' });
+ expect(await feedViewFromParams(Promise.resolve({ q: ['a', 'b'], category: 'Spam', sort: 'oldest' }))).toEqual({ query: '', category: '', sort: 'newest' });
+ });
+});
diff --git a/website/src/lib/community/feed.ts b/website/src/lib/community/feed.ts
new file mode 100644
index 000000000..5d498254c
--- /dev/null
+++ b/website/src/lib/community/feed.ts
@@ -0,0 +1,50 @@
+import { communityCategories } from './contract';
+
+/** The longest feed search the backend accepts (`q` on GET /api/community/harnesses). */
+export const searchMaxChars = 80;
+
+export const feedSorts = ['newest', 'popular'] as const;
+export type FeedSort = typeof feedSorts[number];
+
+/** How a reader narrows a feed: a search, one category and an order. Kept in the page's address. */
+export type FeedView = { query: string; category: string; sort: FeedSort };
+export const defaultFeedView: FeedView = { query: '', category: '', sort: 'newest' };
+
+/** Which publications one feed lists: a tab's, or one harness's forks, narrowed by a view. */
+export type FeedQuery = Partial<FeedView> & { following?: boolean; mine?: boolean; forkedFrom?: string };
+
+/** One page's request. Defaults are left out, so a backend without a filter reads the request as before. */
+export function feedPath({ following, mine, forkedFrom, query, category, sort }: FeedQuery, after?: string): string {
+ const params = new URLSearchParams();
+ if (following) params.set('following', 'true');
+ if (mine) params.set('mine', 'true');
+ if (forkedFrom) params.set('forkedFrom', forkedFrom);
+ if (query) params.set('q', query);
+ if (category) params.set('category', category);
+ if (sort && sort !== 'newest') params.set('sort', sort);
+ if (after) params.set('cursor', after);
+ return `harnesses?${params}`;
+}
+
+export type FeedViewParams = { q?: string | string[]; category?: string | string[]; sort?: string | string[] };
+const single = (value?: string | string[]) => typeof value === 'string' ? value.trim() : '';
+
+/** The view a page was opened with, from `?q=`, `?category=` and `?sort=`; anything unknown is dropped. */
+export async function feedViewFromParams(searchParams: Promise<FeedViewParams>): Promise<FeedView> {
+ const { q, category, sort } = await searchParams;
+ return {
+ query: single(q).slice(0, searchMaxChars),
+ category: communityCategories.includes(single(category)) ? single(category) : '',
+ sort: feedSorts.find(value => value === single(sort)) ?? 'newest',
+ };
+}
+
+/** Writes these parameters into the address without a navigation; an empty value removes one. */
+export function replaceAddressParams(values: Record<string, string>) {
+ const url = new URL(window.location.href);
+ for (const [key, value] of Object.entries(values)) {
+ if (value) url.searchParams.set(key, value);
+ else url.searchParams.delete(key);
+ }
+ if (url.href !== window.location.href) window.history.replaceState(window.history.state, '', url);
+}
diff --git a/website/src/lib/community/search.ts b/website/src/lib/community/search.ts
deleted file mode 100644
index 7cd880a20..000000000
--- a/website/src/lib/community/search.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/** The longest feed search the backend accepts (`q` on GET /api/community/harnesses). */
-export const searchMaxChars = 80;
-
-/** The search a page was opened with, from its `?q=`. */
-export async function searchFromParams(searchParams: Promise<{ q?: string | string[] }>): Promise<string> {
- const { q } = await searchParams;
- return typeof q === 'string' ? q.trim().slice(0, searchMaxChars) : '';
-}
diff --git a/website/src/lib/community/server.ts b/website/src/lib/community/server.ts
index cafb4923e..55080e8c4 100644
--- a/website/src/lib/community/server.ts
+++ b/website/src/lib/community/server.ts
@@ -10,13 +10,18 @@ export function communityApiOrigin(): string {
return url.origin;
}
-export async function getStarter(id: string): Promise<OpenHarness | null> {
+/** `viewerOnly` reads just the page readers see: a harness page needs no source files, and a starter's run to megabytes. */
+export type HarnessRead = { timeoutMs?: number; viewerOnly?: boolean };
+
+const onlyViewer = (harness: OpenHarness): OpenHarness => ({ ...harness, files: harness.files.filter(file => file.path === harness.viewerPath) });
+
+export async function getStarter(id: string, { viewerOnly = false }: HarnessRead = {}): Promise<OpenHarness | null> {
const summary = starterHarnesses.find(item => item.id === id), slug = starterSlug(id);
if (!summary || !slug) return null;
const viewerPath = summary.recording ? 'preview.html' : 'index.html';
const html = await readFile(path.join(process.cwd(), 'public/open-harnesses', slug, viewerPath), 'utf8');
const files: OpenHarness['files'] = [{ path: viewerPath, content: html }];
- if (summary.harnessId) {
+ if (summary.harnessId && !viewerOnly) {
const names: string[] = JSON.parse(await readFile(path.join(process.cwd(), 'public/open-harnesses', slug, 'source-files.json'), 'utf8'));
for (const name of names) {
const bytes = await readFile(path.join(process.cwd(), 'public/open-harnesses', slug, name));
@@ -27,13 +32,15 @@ export async function getStarter(id: string): Promise<OpenHarness | null> {
return { ...summary, viewerPath, files, conversation: starterConversation(id) };
}
-export async function getPublicHarness(id: string, timeoutMs = 8000): Promise<OpenHarness | null> {
- const starter = await getStarter(id);
+export async function getPublicHarness(id: string, read: HarnessRead = {}): Promise<OpenHarness | null> {
+ const starter = await getStarter(id, read);
if (starter) return starter;
if (!/^[a-f0-9-]{36}$/.test(id)) return null;
- const response = await fetch(`${communityApiOrigin()}/api/community/harnesses/${id}`, { cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) });
+ const query = read.viewerOnly ? '?files=viewer' : '';
+ const response = await fetch(`${communityApiOrigin()}/api/community/harnesses/${id}${query}`, { cache: 'no-store', signal: AbortSignal.timeout(read.timeoutMs ?? 8000) });
if (response.status === 404) return null;
if (!response.ok) throw new Error('Community service unavailable.');
- const body = await response.json();
- return body.data.harness;
+ const harness: OpenHarness | null = (await response.json()).data.harness;
+ // A backend older than `?files=viewer` still sends every file.
+ return harness && read.viewerOnly ? onlyViewer(harness) : harness;
}
diff --git a/website/src/lib/community/types.ts b/website/src/lib/community/types.ts
index 85a71dff9..a9b2d80c7 100644
--- a/website/src/lib/community/types.ts
+++ b/website/src/lib/community/types.ts
@@ -36,7 +36,11 @@ export type SocialState = {
likes: number;
liked: boolean;
following: boolean;
+ /** The latest comments (the backend sends at most 100), oldest first. */
comments: HarnessComment[];
signedIn: boolean;
mine: boolean;
+ /** Every comment, and every public fork. A backend older than these counts leaves them out. */
+ commentCount?: number;
+ forks?: number;
};