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.

fix(hub): Popular ranks the starter projects by likes too (#1240)

Jacob Pham23573d1e1e1f
diff --git a/backend/src/lib/communityAccess.ts b/backend/src/lib/communityAccess.ts
index dcb010abc..f3ae7aae7 100644
--- a/backend/src/lib/communityAccess.ts
+++ b/backend/src/lib/communityAccess.ts
@@ -3,9 +3,17 @@ export function isPublicCommunityRead(method: string, url: string): boolean {
return method === 'GET' && /^\/api\/community\/harnesses(?:\/[a-z0-9-]{1,80}(?:\/(?:social|cover))?)?$/.test(url.split('?')[0])
}
+/**
+ * The website's own examples, in the order the Hub draws them (website `starters.ts`, which
+ * `contract.spec.ts` checks): a popular feed ranks them among publications, and keeps this order
+ * among equals.
+ */
export const communityStarters = new Set([
+ 'starter-ribbon-lamp', 'starter-signal-study', 'starter-alpine-drift', 'starter-two-futures', 'starter-molecular-shapes', 'starter-lantern-room', 'starter-portable-light',
+ 'starter-harness-keynote',
'starter-pocket-film', 'starter-moonlight', 'starter-sales-story', 'starter-pleat',
'starter-sunday', 'starter-orbit', 'starter-blue-hour', 'starter-field-notes', 'starter-make-space',
- 'starter-harness-keynote',
- 'starter-ribbon-lamp', 'starter-signal-study', 'starter-alpine-drift', 'starter-two-futures', 'starter-molecular-shapes', 'starter-lantern-room', 'starter-portable-light',
])
+
+/** Who the starters are by, on the website's cards and to a follower. */
+export const communityStarterAuthor = 'harness'
diff --git a/backend/src/lib/communityFeed.ts b/backend/src/lib/communityFeed.ts
index 9be096453..f4f3d7038 100644
--- a/backend/src/lib/communityFeed.ts
+++ b/backend/src/lib/communityFeed.ts
@@ -8,7 +8,6 @@ const feedSelect = { id: true, title: true, description: true, category: true, e
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. */
@@ -20,29 +19,45 @@ function newestPage(where: FeedWhere, cursor?: string) {
}
/**
- * 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.
+ * One page most liked first, newest first among equals, after the last id read. [starters] — the
+ * website's examples, which are not stored here — are ranked alongside, after publications with as
+ * many likes, so the page's order names them too. A page whose last entry 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)
+async function popularPage(where: FeedWhere, autonomousEnv: string, starters: readonly string[], cursor?: string) {
+ const published = (await prisma.communityHarness.findMany({ where, select: { id: true }, orderBy: newest })).map(row => row.id)
+ const ids = [...published, ...starters]
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))
+ // Array sort is stable, so equals keep the 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) ?? [])
+ if (cursor && !start) return { rows: [], order: [] }
+ const order = ranked.slice(start, start + feedPageSize + 1)
+ const rows = await prisma.communityHarness.findMany({ where: { id: { in: order } }, select: feedSelect })
+ return { rows, order }
}
-/** 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 }
+/**
+ * A feed page in the reader's order, and the cursor for the next one (null on the last). A popular
+ * page also returns `order`: its publications' and [starters]' ids as the reader should see them.
+ */
+export async function feedPage(where: FeedWhere, autonomousEnv: string, sort: FeedSort, starters: readonly string[], cursor?: string) {
+ if (sort === 'newest') {
+ const rows = await newestPage(where, cursor)
+ const page = rows.slice(0, feedPageSize)
+ return { page, nextCursor: rows.length > feedPageSize ? page[page.length - 1].id : null }
+ }
+ const { rows, order } = await popularPage(where, autonomousEnv, starters, cursor)
+ const shown = order.slice(0, feedPageSize)
+ const byId = new Map(rows.map(row => [row.id, row]))
+ return {
+ page: shown.flatMap(id => byId.get(id) ?? []),
+ order: shown,
+ nextCursor: order.length > feedPageSize ? shown[shown.length - 1] : null,
+ }
}
/** Likes, comments and public forks of each harness, and which of them the reader likes. */
diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.ts
index 48282aa48..5e8df7dac 100644
--- a/backend/src/routes/community.test.ts
+++ b/backend/src/routes/community.test.ts
@@ -55,7 +55,7 @@ vi.mock('../lib/prisma.js', () => ({ prisma: db }))
import { communityRoutes, publicationSchema } from './community.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
import { errorHandler } from '../middlewares/errorHandler.js'
-import { isPublicCommunityRead } from '../lib/communityAccess.js'
+import { communityStarters, isPublicCommunityRead } from '../lib/communityAccess.js'
const sample = { title: 'A little idea', description: 'An editable project', category: 'Apps', engine: 'Codex', files: [{ path: 'index.html', content: '<h1>A little idea</h1>' }], viewerPath: 'index.html', conversation: [{ role: 'user', text: 'Make a little idea.' }], confirmed: true, license: 'MIT' }
const starter = 'starter-pocket-film'
@@ -278,6 +278,38 @@ describe('persistent social actions', () => {
await call('DELETE', `harnesses/${liked}`, 'alice')
expect((await call('GET', `harnesses?sort=popular&cursor=${liked}`)).json().data.harnesses).toEqual([])
})
+ it('ranks the starters among publications in a popular feed, and names them in its order', async () => {
+ const quiet = await publish('alice', { ...sample, title: 'Quiet' })
+ const liked = await publish('alice', { ...sample, title: 'Liked' })
+ await call('PUT', `harnesses/${liked}/like`, 'bob', { liked: true })
+ for (const token of ['alice', 'bob']) await call('PUT', 'harnesses/starter-blue-hour/like', token, { liked: true })
+ const popular = (await call('GET', 'harnesses?sort=popular')).json().data
+ // Most liked first; publications before starters with as many likes; starters in the Hub's order.
+ const rest = [...communityStarters].filter(id => id !== 'starter-blue-hour')
+ expect(popular.order).toEqual(['starter-blue-hour', liked, quiet, ...rest])
+ expect(popular.harnesses.map((row: Row) => row.id)).toEqual([liked, quiet])
+ expect(popular.stats['starter-blue-hour']).toMatchObject({ likes: 2 })
+ // The newest feed keeps the starters to the website, as before.
+ expect((await call('GET', 'harnesses')).json().data).not.toHaveProperty('order')
+ })
+ it('ranks starters only where the Hub shows them', async () => {
+ const id = await publish('alice')
+ const order = async (query: string, token?: string) => (await call('GET', `harnesses?sort=popular&${query}`, token)).json().data.order
+ expect(await order('mine=true', 'alice')).toEqual([id])
+ expect(await order(`forkedFrom=${id}`)).toEqual([])
+ expect(await order('following=true', 'bob')).toEqual([])
+ await call('PUT', 'creators/harness/follow', 'bob', { following: true })
+ expect(await order('following=true', 'bob')).toEqual([...communityStarters])
+ })
+ it('pages a popular feed past a starter, and only a popular one', async () => {
+ for (let i = 0; i < 20; 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.order).toHaveLength(30); expect(first.harnesses).toHaveLength(20)
+ expect(first.nextCursor).toBe(first.order[29])
+ const second = (await call('GET', `harnesses?sort=popular&cursor=${first.nextCursor}`)).json().data
+ expect(second.order).toEqual([...communityStarters].slice(10)); expect(second.nextCursor).toBeNull()
+ expect((await call('GET', `harnesses?cursor=${first.nextCursor}`)).statusCode).toBe(400)
+ })
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
diff --git a/backend/src/routes/community.ts b/backend/src/routes/community.ts
index 5dc641f97..d96cc6356 100644
--- a/backend/src/routes/community.ts
+++ b/backend/src/routes/community.ts
@@ -2,7 +2,7 @@ import type { FastifyInstance, FastifyRequest } from 'fastify'
import { z } from 'zod'
import { prisma } from '../lib/prisma.js'
import { parseAutonomousEnvironment } from '../lib/autonomousEnvironment.js'
-import { communityStarters } from '../lib/communityAccess.js'
+import { communityStarterAuthor, 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'
@@ -107,7 +107,7 @@ async function socialState(post: Publication, autonomousEnv: string, userId: str
}
async function publication(id: string, autonomousEnv: string) {
- if (communityStarters.has(id)) return { id, authorId: 'harness', authorName: 'Harness', credits: [] }
+ if (communityStarters.has(id)) return { id, authorId: communityStarterAuthor, authorName: 'Harness', credits: [] }
return prisma.communityHarness.findFirst({ where: { id, autonomousEnv, deletedAt: null } })
}
@@ -115,10 +115,11 @@ 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(),
+ cursor: z.string().uuid().or(z.enum([...communityStarters] as [string, ...string[]])).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()
+ }).strict().refine(query => query.sort === 'popular' || !communityStarters.has(query.cursor ?? ''), 'Only a popular feed pages past a starter.')
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)
@@ -129,7 +130,12 @@ export async function communityRoutes(app: FastifyInstance): Promise<void> {
...(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)
+ // Starters are the website's: it matches their search and category, so a popular page ranks all of
+ // them there is a place for — none among your own or a harness's forks, and in Following only
+ // when the reader follows Harness.
+ const followed = new Set(follows.map(row => row.authorId))
+ const starters = mine === 'true' || forkedFrom || (following === 'true' && !followed.has(communityStarterAuthor)) ? [] : [...communityStarters]
+ const { page, order, nextCursor } = await feedPage(where, autonomousEnv, sort, starters, cursor)
const ids = [...page.map(row => row.id), ...communityStarters]
const [stats, covered] = await Promise.all([
feedStats(ids, autonomousEnv, req.user?.sub),
@@ -137,7 +143,7 @@ export async function communityRoutes(app: FastifyInstance): Promise<void> {
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))
- 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) })
+ sendSuccess(reply, { harnesses: page.map(row => withCoverPath({ ...row, cover: withCover.has(row.id) ? 'set' : null })), ...(order ? { order } : {}), stats, signedIn: !!req.user, nextCursor, following: [...followed] })
})
// `files=viewer` sends only the output page: a harness page draws nothing else.
diff --git a/website/src/app/hub/components/Feed.tsx b/website/src/app/hub/components/Feed.tsx
index b6557e0ab..0642bb6f3 100644
--- a/website/src/app/hub/components/Feed.tsx
+++ b/website/src/app/hub/components/Feed.tsx
@@ -1,6 +1,6 @@
'use client';
import Link from 'next/link';
-import { defaultFeedView, type FeedView } from '@/lib/community/feed';
+import { defaultFeedView, inFeedOrder, type FeedView } from '@/lib/community/feed';
import { starterHarnesses } from '@/lib/community/starters';
import type { HarnessSummary } from '@/lib/community/types';
import { FeedCard, FeedSkeleton } from './FeedCard';
@@ -26,12 +26,16 @@ type Props = { following?: boolean; mine?: boolean; initialView?: FeedView };
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 { posts, order, 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 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))];
+ // A popular feed's server ranks the starters among publications by likes, so they are drawn where it
+ // put them; otherwise (or from an older backend) they follow the publications as above.
+ const visible = order
+ ? inFeedOrder(order, [...posts, ...starterHarnesses.filter(item => matches(item, view))])
+ : [...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>}
diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsx
index 05572c321..370b1b72d 100644
--- a/website/src/app/hub/components/community.spec.tsx
+++ b/website/src/app/hub/components/community.spec.tsx
@@ -165,6 +165,16 @@ describe('community navigation', () => {
await waitFor(() => expect(request).toHaveBeenLastCalledWith('harnesses?'));
expect(window.location.search).toBe('');
});
+ it('draws a popular feed in the order the server gave, the liked starters among the publications', async () => {
+ request.mockResolvedValue({ harnesses: [{ ...sample, id: 'post', title: 'Published' }], order: ['starter-blue-hour', 'post', 'starter-orbit'], nextCursor: null, following: [], stats: {} });
+ window.history.replaceState(null, '', '/hub?sort=popular');
+ render(<Feed initialView={{ query: '', category: '', sort: 'popular' }} />);
+ await screen.findByRole('link', { name: 'Open Published' });
+ // Only what the server ranked, where it ranked it: no starter is appended after the publications.
+ expect(screen.getAllByRole('link', { name: /^Open / }).map(link => link.getAttribute('href')))
+ .toEqual(['/hub/starter-blue-hour', '/hub/post', '/hub/starter-orbit']);
+ window.history.replaceState(null, '', '/');
+ });
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 />);
diff --git a/website/src/app/hub/components/useFeed.ts b/website/src/app/hub/components/useFeed.ts
index 15dbb097e..4448a4f95 100644
--- a/website/src/app/hub/components/useFeed.ts
+++ b/website/src/app/hub/components/useFeed.ts
@@ -6,7 +6,8 @@ import type { HarnessSummary } from '@/lib/community/types';
/** `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 };
+/** `order` comes with a popular feed from a backend that ranks the starters too; an older one leaves it out. */
+type FeedResult = { harnesses: HarnessSummary[]; order?: string[]; nextCursor: string | null; following: string[]; stats?: Record<string, Stats>; signedIn?: boolean };
/**
* One feed's pages, their likes, comments and forks, and the reader's likes. Pages load as `more`
@@ -18,6 +19,7 @@ export function useFeed({ following, mine, forkedFrom, query, category, sort }:
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), [settled, setSettled] = useState(false);
+ const [order, setOrder] = useState<string[] | null>(null);
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);
@@ -30,6 +32,7 @@ export function useFeed({ following, mine, forkedFrom, query, category, sort }:
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 || {});
+ setOrder(previous => !result.order ? null : after && previous ? [...previous, ...result.order.filter(id => !previous.includes(id))] : result.order);
setCursor(result.nextCursor); setFollows(result.following); setSignedIn(!!result.signedIn);
} catch (e) {
if (requestId !== generation.current) return;
@@ -65,5 +68,5 @@ export function useFeed({ following, mine, forkedFrom, query, category, sort }:
else setLikeError(e instanceof Error ? e.message : 'Could not save your like. Try again.');
} finally { pending(id, false); }
}
- return { posts, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like };
+ return { posts, order, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like };
}
diff --git a/website/src/lib/community/contract.spec.ts b/website/src/lib/community/contract.spec.ts
index 2cf986551..7395fb375 100644
--- a/website/src/lib/community/contract.spec.ts
+++ b/website/src/lib/community/contract.spec.ts
@@ -14,7 +14,8 @@ describe('the Hub contract', () => {
});
it('lists the same starters the backend serves', async () => {
const { communityStarters } = await import('../../../../backend/src/lib/communityAccess');
- expect(new Set(starterHarnesses.map(item => item.id))).toEqual(communityStarters);
+ // In order: a popular feed keeps the backend's order among starters with as many likes.
+ expect(starterHarnesses.map(item => item.id)).toEqual([...communityStarters]);
});
it('names a missing harness source', () => {
expect(missingMarker('autonomous/blender', ['index.html'])).toBe('scenes/hello.py');
diff --git a/website/src/lib/community/feed.spec.ts b/website/src/lib/community/feed.spec.ts
index 2fa3c4d96..1914cfa32 100644
--- a/website/src/lib/community/feed.spec.ts
+++ b/website/src/lib/community/feed.spec.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { feedPath, feedViewFromParams } from './feed';
+import { feedPath, feedViewFromParams, inFeedOrder } from './feed';
+import type { HarnessSummary } from './types';
describe('feed requests', () => {
it('leaves defaults out, so an older backend reads the request as before', () => {
@@ -11,4 +12,9 @@ describe('feed requests', () => {
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' });
});
+ it('draws a ranked feed in the order the server gave, skipping what is not on offer here', () => {
+ const card = (id: string) => ({ id }) as HarnessSummary;
+ expect(inFeedOrder(['starter-a', 'post', 'starter-gone', 'starter-b'], [card('post'), card('starter-b'), card('starter-a')]).map(item => item.id))
+ .toEqual(['starter-a', 'post', 'starter-b']);
+ });
});
diff --git a/website/src/lib/community/feed.ts b/website/src/lib/community/feed.ts
index 5d498254c..7ff0a70c2 100644
--- a/website/src/lib/community/feed.ts
+++ b/website/src/lib/community/feed.ts
@@ -1,4 +1,5 @@
import { communityCategories } from './contract';
+import type { HarnessSummary } from './types';
/** The longest feed search the backend accepts (`q` on GET /api/community/harnesses). */
export const searchMaxChars = 80;
@@ -26,6 +27,15 @@ export function feedPath({ following, mine, forkedFrom, query, category, sort }:
return `harnesses?${params}`;
}
+/**
+ * A ranked feed's cards in the server's order: its publications and the website's starters, which a
+ * popular feed ranks among them. Ids with no card here — a starter outside the view — are skipped.
+ */
+export function inFeedOrder(order: readonly string[], items: readonly HarnessSummary[]): HarnessSummary[] {
+ const byId = new Map(items.map(item => [item.id, item]));
+ return order.flatMap(id => byId.get(id) ?? []);
+}
+
export type FeedViewParams = { q?: string | string[]; category?: string | string[]; sort?: string | string[] };
const single = (value?: string | string[]) => typeof value === 'string' ? value.trim() : '';