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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness Hub: lighter reads, publications that fit, one contract, native results as viewer pictures (#1026)
Jacob Phambdbdafd3154b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e0a5966c3..0b65aff02 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -156,6 +156,7 @@ jobs:/store//docs/images//mobile/pubspec.lock+ /backend/src/lib/communityContract.ts/.gitattributes/.gitignore/.gitmodulesdiff --git a/backend/src/lib/communityAccess.ts b/backend/src/lib/communityAccess.tsindex 4da28db6e..f9d3a5c09 100644--- a/backend/src/lib/communityAccess.ts+++ b/backend/src/lib/communityAccess.ts@@ -1,6 +1,6 @@-/** Only these two GET shapes are public. Mutations and following inventory stay authenticated. */+/** Only the feed and one harness (with its social state or cover) are public. Mutations and following inventory stay authenticated. */export function isPublicCommunityRead(method: string, url: string): boolean {- return method === 'GET' && /^\/api\/community\/harnesses(?:\/[a-z0-9-]{1,80})?$/.test(url.split('?')[0])+ return method === 'GET' && /^\/api\/community\/harnesses(?:\/[a-z0-9-]{1,80}(?:\/(?:social|cover))?)?$/.test(url.split('?')[0])}export const communityStarters = new Set([diff --git a/backend/src/lib/communityContract.ts b/backend/src/lib/communityContract.tsnew file mode 100644index 000000000..29f8f2e64--- /dev/null+++ b/backend/src/lib/communityContract.ts@@ -0,0 +1,36 @@+/**+ * What the Hub accepts from a publication. The website and the desktop keep their own copies+ * (`website/src/lib/community/contract.ts`, `desktop/lib/community/hub_contract.dart`); each has a+ * test that reads this file and fails when they drift, so change all three together.+ */++/** The harnesses the Hub names, and the source file a publication of each must include. */+export const communityHarnessMarkers = {+ 'autonomous/blender': 'scenes/hello.py',+ 'autonomous/marp': 'deck.md',+ 'autonomous/typst': 'main.typ',+ 'autonomous/circuitjs': 'circuit.txt',+ 'autonomous/godogen': 'studio.json',+ 'autonomous/jev-sheets': 'sheet.json',+ 'autonomous/mujoco': 'sim/hello.py',+ 'autonomous/rdkit': 'molecules/hello.py',+ 'autonomous/strudel': 'track.strudel',+} as const++export const communityHarnessIds = Object.keys(communityHarnessMarkers) as [keyof typeof communityHarnessMarkers, ...(keyof typeof communityHarnessMarkers)[]]+export const communityCategories = ['Apps', 'Games', 'Motion', 'Music', 'Design', 'Data', 'Documents', 'Experiments'] as const+export const communityEngines = ['Codex', 'Claude Code', 'OpenCode', 'pi'] as const++export const communityLimits = {+ files: 30,+ /** Characters of one file as sent: a binary file is base64, about a third larger than on disk. */+ fileChars: 3_000_000,+ snapshotBytes: 6_000_000,+ turns: 80,+ turnChars: 12_000,+ coverChars: 350_000,+} as const++/** Names a fork bundle writes for itself, and names Windows cannot hold. */+export const communityReservedName = /^(?:harness\.json|AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|OPEN-HARNESS\.json|README\.md|CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i+export const communityPathPattern = /^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,179}$/diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.tsindex 3ecfaecf4..6b327b7b2 100644--- a/backend/src/routes/community.test.ts+++ b/backend/src/routes/community.test.ts@@ -10,6 +10,7 @@ const db = vi.hoisted(() => {const filter = value as Record<string, unknown>if ('in' in filter) return (filter.in as unknown[]).includes(row[key])if ('gt' in filter) return (row[key] as Date) > (filter.gt as Date)+ if ('isSet' in filter || 'not' in filter) return (!filter.isSet || row[key] !== undefined) && (!('not' in filter) || row[key] !== filter.not)return matches(row, filter)}return row[key] === value@@ -132,6 +133,33 @@ describe('publications and access', () => {expect((await call('GET', 'harnesses', 'forged')).statusCode).toBe(401)expect((await call('GET', 'harnesses', undefined, undefined, 'invalid')).statusCode).toBe(400)})+ it('gives readers a cover address and a social state without the project', async () => {+ const bytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0])+ const id = await publish('alice', { ...sample, cover: `data:image/png;base64,${bytes.toString('base64')}` } as typeof sample)+ const address = `/api/community/harnesses/${id}/cover`+ const bare = await publish('alice')+ const feed = (await call('GET', 'harnesses')).json().data.harnesses+ expect(feed.find((row: { id: string }) => row.id === id).cover).toBe(address)+ expect(feed.find((row: { id: string }) => row.id === bare)).not.toHaveProperty('cover')+ // The feed never reads a cover's bytes, only whether there is one.+ expect(db.communityHarness.findMany.mock.calls.every(([query]) => !query?.select?.cover)).toBe(true)+ expect((await call('GET', `harnesses/${id}`)).json().data.harness.cover).toBe(address)+ // An <img> sends no environment header, so the cover does not depend on it.+ const cover = await call('GET', `harnesses/${id}/cover`, undefined, undefined, 'stag')+ expect(cover.statusCode).toBe(200)+ expect(cover.headers['content-type']).toBe('image/png')+ expect(cover.rawPayload.equals(bytes)).toBe(true)+ const social = (await call('GET', `harnesses/${id}/social`, 'bob')).json().data+ expect(Object.keys(social)).toEqual(['social'])+ expect(social.social).toMatchObject({ likes: 0, signedIn: true, mine: false, comments: [] })+ expect((await call('GET', `harnesses/${starter}/social`)).statusCode).toBe(200)+ expect((await call('GET', `harnesses/${starter}/cover`)).statusCode).toBe(404)+ await call('DELETE', `harnesses/${id}`, 'alice')+ expect((await call('GET', `harnesses/${id}/cover`)).statusCode).toBe(404)+ expect((await call('GET', `harnesses/${id}/social`)).statusCode).toBe(404)+ expect(isPublicCommunityRead('GET', address)).toBe(true)+ expect(isPublicCommunityRead('GET', `/api/community/harnesses/${id}/files`)).toBe(false)+ })it('publishes an explicit snapshot, retains source attribution, and never exposes emails', async () => {const id = await publish('alice', { ...sample, forkedFrom: starter } as typeof sample)const result = (await call('GET', `harnesses/${id}`)).json().datadiff --git a/backend/src/routes/community.ts b/backend/src/routes/community.tsindex d272d28b3..8c957ae51 100644--- a/backend/src/routes/community.ts+++ b/backend/src/routes/community.ts@@ -3,38 +3,47 @@ import { z } from 'zod'import { prisma } from '../lib/prisma.js'import { parseAutonomousEnvironment } from '../lib/autonomousEnvironment.js'import { communityStarters } from '../lib/communityAccess.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'import { ValidationError } from '../errors/index.js'const identifier = z.string().regex(/^[a-z0-9-]{1,80}$/)++/** A stored cover's bytes and type, or null unless its data URL holds the image it claims. */+export function coverImage(value: string): { type: string; bytes: Buffer } | null {+ const match = value.match(/^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/]+={0,2})$/)+ if (!match) return null+ const bytes = Buffer.from(match[2], 'base64')+ const valid = match[1] === 'png' ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))+ : match[1] === 'jpeg' ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255+ : bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'+ return valid ? { type: `image/${match[1]}`, bytes } : null+}++/** Readers get a cover's address, never its bytes: a feed page would otherwise carry every image inline. */+function withCoverPath<T extends { id: string; cover: string | null }>(row: T): Omit<T, 'cover'> & { cover?: string } {+ const { cover, ...rest } = row+ return { ...rest, ...(cover ? { cover: `/api/community/harnesses/${row.id}/cover` } : {}) }+}const params = z.object({ id: identifier })const file = z.object({- path: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,179}$/).refine(path =>- !path.split('/').some(part => !part || part.startsWith('.') ||- /^(?:harness\.json|AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|OPEN-HARNESS\.json|README\.md|CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(part)), 'Use a relative project path, not a reserved bundle file.'),- content: z.string().max(3_000_000),+ path: z.string().regex(communityPathPattern).refine(path =>+ !path.split('/').some(part => !part || part.startsWith('.') || communityReservedName.test(part)), 'Use a relative project path, not a reserved bundle file.'),+ content: z.string().max(communityLimits.fileChars),encoding: z.literal('base64').optional(),}).strict()export const publicationSchema = z.object({title: z.string().trim().min(1).max(100),description: z.string().trim().min(1).max(300),- category: z.enum(['Apps', 'Games', 'Motion', 'Music', 'Design', 'Data', 'Documents', 'Experiments']),- engine: z.enum(['Codex', 'Claude Code', 'OpenCode', 'pi']),- harnessId: z.enum(["autonomous/blender", "autonomous/marp", "autonomous/typst", "autonomous/circuitjs", "autonomous/godogen", "autonomous/jev-sheets", "autonomous/mujoco", "autonomous/rdkit", "autonomous/strudel"]).optional(),- files: z.array(file).min(1).max(30),+ category: z.enum(communityCategories),+ engine: z.enum(communityEngines),+ harnessId: z.enum(communityHarnessIds).optional(),+ files: z.array(file).min(1).max(communityLimits.files),viewerPath: z.string().max(180),- conversation: z.array(z.object({ role: z.enum(['user', 'assistant', 'tool']), text: z.string().min(1).max(12_000) }).strict()).min(1).max(80),- cover: z.string().max(350_000).optional().refine(value => {- if (!value) return true- const match = value.match(/^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/]+={0,2})$/)- if (!match) return false- const bytes = Buffer.from(match[2], 'base64')- return match[1] === 'png' ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))- : match[1] === 'jpeg' ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255- : bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'- }, 'Use a PNG, JPEG, or WebP cover.'),+ conversation: z.array(z.object({ role: z.enum(['user', 'assistant', 'tool']), text: z.string().min(1).max(communityLimits.turnChars) }).strict()).min(1).max(communityLimits.turns),+ cover: z.string().max(communityLimits.coverChars).optional().refine(value => !value || !!coverImage(value), 'Use a PNG, JPEG, or WebP cover.'),forkedFrom: identifier.optional(),clientId: z.string().uuid().optional(),license: z.literal('MIT'),@@ -49,9 +58,9 @@ export const publicationSchema = z.object({ctx.addIssue({ code: 'custom', message: 'Project paths must be unique.' })if (!value.viewerPath.endsWith('.html') || !value.files.some(f => f.path === value.viewerPath && !f.encoding))ctx.addIssue({ code: 'custom', message: 'Choose an included HTML file as the viewer.' })- const marker = value.harnessId ? {"autonomous/blender": "scenes/hello.py", "autonomous/marp": "deck.md", "autonomous/typst": "main.typ", "autonomous/circuitjs": "circuit.txt", "autonomous/godogen": "studio.json", "autonomous/jev-sheets": "sheet.json", "autonomous/mujoco": "sim/hello.py", "autonomous/rdkit": "molecules/hello.py", "autonomous/strudel": "track.strudel"}[value.harnessId] : undefined+ const marker = value.harnessId ? communityHarnessMarkers[value.harnessId] : undefinedif (marker && !value.files.some(file => file.path === marker && !file.encoding)) ctx.addIssue({ code: 'custom', message: 'Include the harness project source.' })- if (Buffer.byteLength(JSON.stringify(value)) > 6_000_000)+ if (Buffer.byteLength(JSON.stringify(value)) > communityLimits.snapshotBytes)ctx.addIssue({ code: 'custom', message: 'Keep the published snapshot under 6 MB.' })})@@ -65,6 +74,22 @@ async function authorName(userId: string): Promise<string> {return user?.name?.trim().slice(0, 80) || 'Harness user'}+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([+ 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,+ ])+ return {+ likes, liked: !!liked, following: !!follow, signedIn: !!userId, mine: post.authorId === userId,+ 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 })),+ }+}+async function publication(id: string, autonomousEnv: string) {if (communityStarters.has(id)) return { id, authorId: 'harness', authorName: 'Harness', credits: [] }return prisma.communityHarness.findFirst({ where: { id, autonomousEnv, deletedAt: null } })@@ -80,38 +105,50 @@ export async function communityRoutes(app: FastifyInstance): Promise<void> {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 } : {}) },- select: { id: true, title: true, description: true, category: true, engine: true, harnessId: true, authorId: true, authorName: true, cover: true, forkedFrom: true, createdAt: true },+ 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 ids = [...rows.slice(0, 30).map(row => row.id), ...communityStarters]- const [likes, comments, liked] = await Promise.all([+ 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 } }) : [],+ // 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: rows.slice(0, 30), 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: rows.length > 30 ? rows[29].id : null, following: follows.map(row => row.authorId) })})app.get<{ Params: z.infer<typeof params> }>('/api/community/harnesses/:id', { preHandler: validateParams(params) }, async (req, reply) => {const autonomousEnv = environment(req), harnessId = req.params.idconst post = await publication(harnessId, autonomousEnv)if (!post) return sendError(reply, 'This harness is unavailable.', 'NOT_FOUND', 404)- const userId = req.user?.sub- const [likes, liked, comments, follow] = 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,- ])sendSuccess(reply, {- harness: communityStarters.has(harnessId) ? null : post,- social: { likes, liked: !!liked, following: !!follow, signedIn: !!userId, mine: post.authorId === userId,- 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 })) },+ // A starter's files are the website's own; only a publication is stored here.+ harness: 'title' in post ? withCoverPath(post) : null,+ social: await socialState(post, autonomousEnv, req.user?.sub),})})+ // What a reader's page refreshes: the publication itself never changes after it is published.+ app.get<{ Params: z.infer<typeof params> }>('/api/community/harnesses/:id/social', { preHandler: validateParams(params) }, async (req, reply) => {+ const autonomousEnv = environment(req)+ const post = await publication(req.params.id, autonomousEnv)+ if (!post) return sendError(reply, 'This harness is unavailable.', 'NOT_FOUND', 404)+ sendSuccess(reply, { social: await socialState(post, autonomousEnv, req.user?.sub) })+ })++ // Read by an <img>, which sends no environment header: a publication id is a UUID, unique across both.+ app.get<{ Params: z.infer<typeof params> }>('/api/community/harnesses/:id/cover', { preHandler: validateParams(params) }, async (req, reply) => {+ const post = await prisma.communityHarness.findFirst({ where: { id: req.params.id, deletedAt: null }, select: { cover: true } })+ const image = post?.cover ? coverImage(post.cover) : null+ if (!image) return sendError(reply, 'This cover is unavailable.', 'NOT_FOUND', 404)+ reply.header('Content-Type', image.type).header('X-Content-Type-Options', 'nosniff').send(image.bytes)+ })+app.post<{ Body: z.infer<typeof publicationSchema> }>('/api/community/harnesses', { bodyLimit: 6_100_000, preHandler: validateBody(publicationSchema) }, async (req, reply) => {const autonomousEnv = environment(req), userId = req.user!.subif (req.body.clientId) {diff --git a/desktop/lib/community/fork_project.dart b/desktop/lib/community/fork_project.dartindex d4fbfc181..c4c712d54 100644--- a/desktop/lib/community/fork_project.dart+++ b/desktop/lib/community/fork_project.dart@@ -6,18 +6,9 @@ import 'package:path/path.dart' as p;import '../core/harness_cli_runner.dart';import '../core/project_folder.dart';import 'fork_link.dart';+import 'hub_contract.dart';-const communityHarnesses = {- 'autonomous/blender',- 'autonomous/marp',- 'autonomous/typst',- 'autonomous/circuitjs',- 'autonomous/godogen',- 'autonomous/jev-sheets',- 'autonomous/mujoco',- 'autonomous/rdkit',- 'autonomous/strudel',-};+final communityHarnesses = hubHarnessMarkers.keys.toSet();const _communityViewers = {'autonomous/web-viewer',@@ -471,16 +462,11 @@ class ForkProjectImporter {}final path = file['path'] as String;final parts = path.split('/');- if (!RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,179}$').hasMatch(path) ||+ if (!hubPathPattern.hasMatch(path) ||parts.any((s) => s.isEmpty || s == '.' || s == '..' || s.startsWith('.'),) ||- parts.any(- (s) => RegExp(- r'^(harness\.json|agents\.md|claude\.md|session\.md|open-harness\.json|license|readme\.md|con|prn|aux|nul|com[1-9]|lpt[1-9])$',- caseSensitive: false,- ).hasMatch(s),- ) ||+ parts.any(hubReservedName.hasMatch) ||!keys.add(path.toLowerCase())) {invalid();}@@ -498,17 +484,7 @@ class ForkProjectImporter {!files.containsKey(data['viewerPath'])) {invalid();}- final marker = {- 'autonomous/blender': 'scenes/hello.py',- 'autonomous/marp': 'deck.md',- 'autonomous/typst': 'main.typ',- 'autonomous/circuitjs': 'circuit.txt',- 'autonomous/godogen': 'studio.json',- 'autonomous/jev-sheets': 'sheet.json',- 'autonomous/mujoco': 'sim/hello.py',- 'autonomous/rdkit': 'molecules/hello.py',- 'autonomous/strudel': 'track.strudel',- }[data['harnessId']];+ final marker = hubHarnessMarkers[data['harnessId']];if (marker != null && !files.containsKey(marker)) invalid();final conversation = data['conversation'];if (conversation is! List ||diff --git a/desktop/lib/community/hub_contract.dart b/desktop/lib/community/hub_contract.dartnew file mode 100644index 000000000..ed6ddfdd8--- /dev/null+++ b/desktop/lib/community/hub_contract.dart@@ -0,0 +1,67 @@+/// What the Hub accepts from a publication, as `backend/src/routes/community.ts` checks it.+///+/// ⚠️ Mirrored, not shared: `test/community_hub_contract_test.dart` reads the backend's source and+/// fails when the two drift, so change both together.+library;++/// The harnesses the Hub names, and the source file a publication of each must include.+const hubHarnessMarkers = <String, String>{+ 'autonomous/blender': 'scenes/hello.py',+ 'autonomous/marp': 'deck.md',+ 'autonomous/typst': 'main.typ',+ 'autonomous/circuitjs': 'circuit.txt',+ 'autonomous/godogen': 'studio.json',+ 'autonomous/jev-sheets': 'sheet.json',+ 'autonomous/mujoco': 'sim/hello.py',+ 'autonomous/rdkit': 'molecules/hello.py',+ 'autonomous/strudel': 'track.strudel',+};++/// A Harness engine id, and the agent the Hub lists it as.+const hubEngines = <String, String>{+ 'codex': 'Codex',+ 'claude': 'Claude Code',+ 'opencode': 'OpenCode',+ 'pi': 'pi',+};++const hubMaxFiles = 30;+const hubMaxTurns = 80;+const hubMaxTurnChars = 12000;++/// Characters as sent. A binary file goes as base64, about a third larger than on disk.+const hubMaxFileChars = 3000000;++/// The project's share of the Hub's 6 MB snapshot, leaving room for the conversation.+const hubMaxProjectChars = 5600000;++/// A cover's data URL, as the Hub stores it.+const hubMaxCoverChars = 350000;++const hubBinaryExtensions = {'.png', '.jpg', '.jpeg', '.webp', '.glb', '.pdf'};+const hubTextExtensions = {+ '.html',+ '.css',+ '.js',+ '.mjs',+ '.ts',+ '.tsx',+ '.jsx',+ '.json',+ '.md',+ '.svg',+ '.py',+ '.typ',+ '.strudel',+ '.txt',+ '.csv',+ '.xml',+ '.sdf',+};++/// Names a fork bundle writes for itself, and names Windows cannot hold.+final hubReservedName = RegExp(+ r'^(?:harness\.json|AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|OPEN-HARNESS\.json|README\.md|CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$',+ caseSensitive: false,+);+final hubPathPattern = RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,179}$');diff --git a/desktop/lib/community/hub_links.dart b/desktop/lib/community/hub_links.dartnew file mode 100644index 000000000..9ba54e3e2--- /dev/null+++ b/desktop/lib/community/hub_links.dart@@ -0,0 +1,16 @@+import 'package:url_launcher/url_launcher.dart';++/// Where a publication is reviewed when the app cannot hand it over.+final hubPublishPage = Uri.parse('https://harness.autonomous.ai/hub/publish');++/// Opens a Hub page, or says where to go when nothing on this computer can.+Future<void> openHubPage(+ Uri url, {+ LaunchMode mode = LaunchMode.platformDefault,+}) async {+ if (!await launchUrl(url, mode: mode)) {+ throw const FormatException(+ 'Could not open the Hub. Open harness.autonomous.ai/hub/publish to continue.',+ );+ }+}diff --git a/desktop/lib/community/publish_conversation.dart b/desktop/lib/community/publish_conversation.dartnew file mode 100644index 000000000..89be2560d--- /dev/null+++ b/desktop/lib/community/publish_conversation.dart@@ -0,0 +1,28 @@+import 'dart:math';++import 'hub_contract.dart';++/// The session tail as Hub turns: each ask and answer, split to the Hub's turn length, keeping the+/// newest turns when there are more than it takes. The end of a session is usually what made the result.+List<Map<String, String>> publicationTurns(Map<String, dynamic>? tail) {+ final turns = <Map<String, String>>[];+ for (final row in (tail?['rows'] as List? ?? const [])) {+ if (row is! Map) continue;+ for (final (key, role) in [('ask', 'user'), ('answer', 'assistant')]) {+ final text = row[key];+ if (text is! String || text.trim().isEmpty) continue;+ for (var start = 0; start < text.length; start += hubMaxTurnChars) {+ turns.add({+ 'role': role,+ 'text': text.substring(+ start,+ min(start + hubMaxTurnChars, text.length),+ ),+ });+ }+ }+ }+ return turns.length > hubMaxTurns+ ? turns.sublist(turns.length - hubMaxTurns)+ : turns;+}diff --git a/desktop/lib/community/publish_files.dart b/desktop/lib/community/publish_files.dartnew file mode 100644index 000000000..3572363bb--- /dev/null+++ b/desktop/lib/community/publish_files.dart@@ -0,0 +1,233 @@+import 'dart:convert';+import 'dart:io';++import 'package:path/path.dart' as p;++import 'hub_contract.dart';++const _skippedFolders = {+ 'node_modules',+ 'build',+ 'dist',+ 'target',+ 'vendor',+ 'coverage',+ '__pycache__',+};+const _maxDepth = 8;+const _maxEntries = 1500;++/// The files a publication carries, and the ones that did not fit.+class ProjectSelection {+ const ProjectSelection({+ required this.files,+ required this.viewerPath,+ required this.leftOut,+ required this.scannedAll,+ this.pictured = false,+ });++ /// `{path, content, encoding?}` rows in path order, as the Hub reads them.+ final List<Map<String, String>> files;+ final String viewerPath;++ /// Portable files left out: over a limit, or not UTF-8 text.+ final List<String> leftOut;++ /// False when the folder was deeper or larger than one publication is ever read.+ final bool scannedAll;++ /// True when the output is the picture of the viewer rather than a page of the project.+ final bool pictured;+}++class _Candidate {+ _Candidate(this.path, File this.file) : page = null;+ _Candidate.page(this.path, String this.page) : file = null;+ final String path;+ final File? file;++ /// A page made for this publication rather than read from the project.+ final String? page;+ bool get binary =>+ hubBinaryExtensions.contains(p.extension(path).toLowerCase());+ int get depth => '/'.allMatches(path).length;++ String? _read;+ bool _wasRead = false;++ /// What the Hub would receive, measured without reading: bytes on disk for text (exact for+ /// UTF-8), base64 length for a binary file.+ Future<int> sentBytes() async {+ if (page != null) return utf8.encode(page!).length;+ final length = await file!.length();+ return binary ? (length + 2) ~/ 3 * 4 : length;+ }++ /// The file as the Hub stores it, read once, or null when text is not UTF-8.+ Future<String?> content() async {+ if (page != null) return page;+ if (_wasRead) return _read;+ _wasRead = true;+ final bytes = await file!.readAsBytes();+ if (binary) return _read = base64Encode(bytes);+ try {+ return _read = utf8.decode(bytes);+ } on FormatException {+ return null;+ }+ }+}++/// The project has no page of its own to show, or only the original's. With a picture of the+/// viewer, publishing can still go ahead; without one, the message says what to ask the agent for.+class NeedsOutput extends FormatException {+ const NeedsOutput(super.message);+}++/// Local project files only. No daemon state, hidden files, credentials files, links, installed+/// dependencies, or native engine session identifiers are exported.+///+/// The output is chosen first and the harness's own source second; the rest are added shallowest+/// first while they fit. A file that does not fit is named, never a reason to publish nothing, and+/// is never read: a size on disk says enough.+///+/// The output is [viewer] (the page a fork was published with), or else `preview.html`, skipping a+/// page still as it is in [original] (the fork's files as they arrived), which shows the original.+/// Any other page is never assumed: an app's `index.html` usually needs files the Hub's sandbox+/// cannot load. Without a page of its own, the output is [picture], a page showing the viewer.+Future<ProjectSelection> selectProjectFiles(+ String folder, {+ String? marker,+ String? viewer,+ Map<String, String> original = const {},+ String? picture,+}) async {+ final root = Directory(await Directory(folder).resolveSymbolicLinks());+ final (candidates, scannedAll) = await _candidates(root);+ final (own, stale) = await _output(candidates, viewer, original);+ final shown =+ own ??+ (picture == null+ ? throw NeedsOutput(+ stale != null+ ? '${stale.path} is still the original\'s and has none of your changes. '+ 'Ask your agent to update it to show the current result, then publish again.'+ : 'The Hub shows what a session made. Ask your agent for a preview.html that runs '+ 'on its own (for a review, a page presenting it), then publish again.',+ )+ : _Candidate.page('preview.html', picture));+ final rest =+ candidates.where((c) => c.path != shown.path && c.path != marker).toList()+ ..sort(+ (a, b) =>+ a.depth != b.depth ? a.depth - b.depth : a.path.compareTo(b.path),+ );+ final ordered = [+ shown,+ ...candidates.where((c) => c.path == marker && c.path != shown.path),+ ...rest,+ ];+ final files = <Map<String, String>>[], leftOut = <String>[];+ var size = 0;+ for (final candidate in ordered) {+ // The snapshot limit is in bytes; one file's is in characters, as the backend counts each.+ final weight = await candidate.sentBytes();+ final room =+ files.length < hubMaxFiles && size + weight <= hubMaxProjectChars;+ final content = room ? await candidate.content() : null;+ if (content == null || content.length > hubMaxFileChars) {+ if (candidate == shown) {+ throw FormatException(+ '${shown.path} is too large to publish. Keep the preview under 3 MB.',+ );+ }+ leftOut.add(candidate.path);+ continue;+ }+ size += weight;+ files.add({+ 'path': candidate.path,+ 'content': content,+ if (candidate.binary) 'encoding': 'base64',+ });+ }+ files.sort((a, b) => a['path']!.compareTo(b['path']!));+ return ProjectSelection(+ files: files,+ viewerPath: shown.path,+ leftOut: leftOut..sort(),+ scannedAll: scannedAll,+ pictured: shown.page != null,+ );+}++/// The page readers see, and the original's page passed over on the way, if any.+Future<(_Candidate?, _Candidate?)> _output(+ List<_Candidate> candidates,+ String? viewer,+ Map<String, String> original,+) async {+ _Candidate? stale;+ for (final name in {?viewer, 'preview.html'}) {+ final page = candidates+ .where((c) => c.path == name && name.endsWith('.html'))+ .firstOrNull;+ if (page == null) continue;+ if (original.containsKey(name) && await page.content() == original[name]) {+ stale ??= page;+ continue;+ }+ return (page, stale);+ }+ return (null, stale);+}++Future<(List<_Candidate>, bool)> _candidates(Directory root) async {+ final found = <_Candidate>[];+ var visited = 0, scannedAll = true;+ Future<void> walk(Directory directory, int depth) async {+ if (depth > _maxDepth) {+ scannedAll = false;+ return;+ }+ await for (final entry in directory.list(followLinks: false)) {+ if (++visited > _maxEntries) {+ scannedAll = false;+ return;+ }+ final name = p.basename(entry.path);+ if (name.startsWith('.') ||+ _skippedFolders.contains(name) ||+ hubReservedName.hasMatch(name) ||+ entry is Link) {+ continue;+ }+ if (entry is Directory) {+ await walk(entry, depth + 1);+ continue;+ }+ if (entry is! File || !await _insideRoot(root, entry)) continue;+ final path = p+ .relative(entry.path, from: root.path)+ .split(p.separator)+ .join('/');+ final extension = p.extension(name).toLowerCase();+ if (!hubPathPattern.hasMatch(path) ||+ (!hubTextExtensions.contains(extension) &&+ !hubBinaryExtensions.contains(extension))) {+ continue;+ }+ found.add(_Candidate(path, entry));+ }+ }++ await walk(root, 0);+ return (found, scannedAll);+}++/// A plain file whose real location is still inside the project.+Future<bool> _insideRoot(Directory root, File file) async =>+ p.isWithin(root.path, await file.resolveSymbolicLinks()) &&+ await FileSystemEntity.type(file.path, followLinks: false) ==+ FileSystemEntityType.file;diff --git a/desktop/lib/community/publish_native.dart b/desktop/lib/community/publish_native.dartindex 76e01d075..237126c03 100644--- a/desktop/lib/community/publish_native.dart+++ b/desktop/lib/community/publish_native.dart@@ -1,9 +1,13 @@import 'package:url_launcher/url_launcher.dart';import '../state/app_state.dart';+import 'hub_links.dart';+import 'publish_files.dart' show NeedsOutput;import 'publish_project.dart';+import 'viewer_picture.dart';-Future<void> publishHarness(+/// Sends a local harness's draft to the Hub and returns what the person should do next there.+Future<String> publishHarness(AppNotifier app,String machineId,String agentId,@@ -13,28 +17,44 @@ Future<void> publishHarness(if (agent == null) {throw const FormatException('This harness is no longer available.');}+ // Only this computer's files can be read from here.+ // TODO: read another machine's project through its CLI, the way readSessionTail reads its session.if (machine?.isLocalMachine != true || agent.project?.cwd == null) {- await launchUrl(- Uri.parse('https://harness.autonomous.ai/hub/publish'),- mode: LaunchMode.externalApplication,- );- return;+ await openHubPage(hubPublishPage, mode: LaunchMode.externalApplication);+ return 'This harness runs on another computer, so its files cannot be sent from here. '+ 'Choose its project folder on the Hub page that opened.';}final tail = agent.sessionId == null? null: await app.readSessionTail(machineId, agent.sessionId!, maxChars: 60000);- final snapshot = await buildPublicationDraft(- folder: agent.project!.cwd,- title: agent.title ?? agent.name,- engine: agent.engine ?? 'codex',- harnessId: agent.dsh,- tail: tail,- );+ Future<Map<String, dynamic>> draft({String? picture}) =>+ buildPublicationDraft(+ folder: agent.project!.cwd,+ title: agent.title ?? agent.name,+ engine: agent.engine ?? 'codex',+ harnessId: agent.dsh,+ tail: tail,+ viewerPicture: picture,+ );+ Map<String, dynamic> snapshot;+ try {+ snapshot = await draft();+ } on NeedsOutput {+ // No page of its own: what the harness shows now is the result, when it can be pictured.+ final picture = agent.viewerUrl == null+ ? null+ : await captureViewer(+ (payload) => app.viewerSurface(machineId, agentId, payload),+ );+ if (picture == null) rethrow;+ snapshot = await draft(picture: picture);+ }final handoff = await PublicationHandoff.start(snapshot);- if (!await launchUrl(handoff.url, mode: LaunchMode.externalApplication)) {+ try {+ await openHubPage(handoff.url, mode: LaunchMode.externalApplication);+ } on FormatException {await handoff.close();- throw const FormatException(- 'Could not open the Hub. Open harness.autonomous.ai/hub/publish to continue.',- );+ rethrow;}+ return 'Review your files and conversation in the Hub, then publish.';}diff --git a/desktop/lib/community/publish_project.dart b/desktop/lib/community/publish_project.dartindex 07281437f..f987a326d 100644--- a/desktop/lib/community/publish_project.dart+++ b/desktop/lib/community/publish_project.dart@@ -5,162 +5,38 @@ import 'dart:math';import 'package:path/path.dart' as p;-import 'fork_project.dart' show communityHarnesses;+import 'hub_contract.dart';+import 'publish_conversation.dart';+import 'publish_files.dart';+import 'viewer_picture.dart';-const _skipped = {- 'node_modules',- 'build',- 'dist',- 'target',- 'vendor',- 'coverage',- '__pycache__',-};-final _reserved = RegExp(- r'^(harness\.json|AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|OPEN-HARNESS\.json|README\.md|CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$',- caseSensitive: false,-);-const _binary = {'.png', '.jpg', '.jpeg', '.webp', '.glb', '.pdf'};-const _text = {- '.html',- '.css',- '.js',- '.mjs',- '.ts',- '.tsx',- '.jsx',- '.json',- '.md',- '.svg',- '.py',- '.typ',- '.strudel',- '.txt',- '.csv',- '.xml',- '.sdf',-};--/// Local project files only. No daemon state, hidden files, credentials, links,-/// installed dependencies, or native engine session identifiers are exported.+/// A Hub draft of the project in [folder]: its portable files, the recent conversation, and notes+/// telling the person what to review or add before publishing. Nothing here publishes.Future<Map<String, dynamic>> buildPublicationDraft({required String folder,required String title,required String engine,String? harnessId,Map<String, dynamic>? tail,+ String? viewerPicture,}) async {- final root = Directory(await Directory(folder).resolveSymbolicLinks());- final files = <Map<String, String>>[];- var size = 0, visited = 0;- Future<void> walk(Directory directory, int depth) async {- if (depth > 8) {- throw const FormatException(- 'This project is too large to publish as one harness. Choose its portable files on the Hub.',- );- }- await for (final entry in directory.list(followLinks: false)) {- if (++visited > 1500) {- throw const FormatException(- 'Choose a smaller project or its portable files on the Hub.',- );- }- final name = p.basename(entry.path);- if (name.startsWith('.') ||- _skipped.contains(name) ||- _reserved.hasMatch(name)) {- continue;- }- if (entry is Link) continue;- if (entry is Directory) {- await walk(entry, depth + 1);- continue;- }- if (entry is! File) continue;- final resolved = await entry.resolveSymbolicLinks();- if (!p.isWithin(root.path, resolved) ||- await FileSystemEntity.type(entry.path, followLinks: false) !=- FileSystemEntityType.file) {- continue;- }- final relative = p- .relative(entry.path, from: root.path)- .split(p.separator)- .join('/');- if (!RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,179}$').hasMatch(relative)) {- continue;- }- final extension = p.extension(name).toLowerCase();- if (!_text.contains(extension) && !_binary.contains(extension)) continue;- final length = await entry.length();- if (length > 3000000 || files.length == 30) {- throw const FormatException(- 'Publish up to 30 files, under 3 MB each. Choose the files on the Hub.',- );- }- final bytes = await entry.readAsBytes();- final binary = _binary.contains(extension);- final content = binary ? base64Encode(bytes) : utf8.decode(bytes);- size += utf8.encode(content).length;- if (content.length > 3000000 || size > 5600000) {- throw const FormatException(- 'Keep this harness under 6 MB. Choose a smaller set of files on the Hub.',- );- }- files.add({- 'path': relative,- 'content': content,- if (binary) 'encoding': 'base64',- });- }- }-- await walk(root, 0);- files.sort((a, b) => a['path']!.compareTo(b['path']!));- final htmlFiles = files- .where((file) => file['path']!.endsWith('.html'))- .toList();- if (htmlFiles.isEmpty) {- throw const FormatException(- 'Ask your agent to create a self-contained preview.html, then publish again.',- );- }- final viewer =- htmlFiles.where((f) => f['path'] == 'preview.html').firstOrNull ??- htmlFiles.where((f) => f['path'] == 'index.html').firstOrNull ??- htmlFiles.first;- Map<String, dynamic> previous = {};- final origin = File(p.join(root.path, 'OPEN-HARNESS.json'));- if (await origin.exists() &&- await origin.length() <= 8100000 &&- await FileSystemEntity.type(origin.path, followLinks: false) ==- FileSystemEntityType.file) {- try {- final decoded = jsonDecode(await origin.readAsString());- if (decoded is Map<String, dynamic>) previous = decoded;- } on FormatException {- /* A fresh project is still publishable. */- }- }- final conversation = <Map<String, String>>[];- for (final row in (tail?['rows'] as List? ?? const [])) {- if (row is! Map) continue;- for (final part in [('ask', 'user'), ('answer', 'assistant')]) {- final text = row[part.$1];- if (text is String && text.trim().isNotEmpty) {- for (- var start = 0;- start < text.length && conversation.length < 80;- start += 12000- ) {- conversation.add({- 'role': part.$2,- 'text': text.substring(start, min(start + 12000, text.length)),- });- }- }- }- }+ final marker = hubHarnessMarkers[harnessId];+ final previous = await _openHarness(folder);+ final selection = await selectProjectFiles(+ folder,+ marker: marker,+ viewer: previous['viewerPath'] is String ? previous['viewerPath'] : null,+ original: _originalFiles(previous),+ picture: viewerPicture == null+ ? null+ : viewerPosterPage(title, viewerPicture),+ );+ final cover = viewerPicture == null+ ? null+ : 'data:image/jpeg;base64,$viewerPicture';+ final conversation = publicationTurns(tail);+ final hasMarker = selection.files.any((file) => file['path'] == marker);+ final agent = hubEngines[engine];return {'version': 1,'title': title.substring(0, min(100, title.length)),@@ -168,31 +44,76 @@ Future<Map<String, dynamic>> buildPublicationDraft({? previous['description']: '','category': previous['category'] is String ? previous['category'] : 'Apps',- 'engine':- {- 'codex': 'Codex',- 'claude': 'Claude Code',- 'opencode': 'OpenCode',- 'pi': 'pi',- }[engine] ??- 'Codex',- if (communityHarnesses.contains(harnessId)) 'harnessId': harnessId,- 'files': files,- 'viewerPath': viewer['path'],+ 'engine': ?agent,+ if (hasMarker) 'harnessId': harnessId,+ 'files': selection.files,+ 'viewerPath': selection.viewerPath,'conversation': conversation.isEmpty? [{'role': 'user', 'text': ''},]: conversation,if (previous['forkedFrom'] is String) 'forkedFrom': previous['forkedFrom'],- 'contextNote': tail?['hasMore'] == true- ? 'Recent conversation included. Review it and add any earlier context you want to publish.'- : conversation.isEmpty- ? 'Add the conversation or a brief describing what you made.'- : 'Review the conversation before publishing.',+ if (selection.pictured && cover != null && cover.length <= hubMaxCoverChars)+ 'cover': cover,+ 'contextNote': [+ _conversationNote(conversation, tail),+ if (selection.pictured) 'The output is a picture of your viewer, taken just now. A fork opens the real thing.',+ if (selection.leftOut.isNotEmpty) _leftOutNote(selection.leftOut),+ if (!selection.scannedAll)+ 'This folder is larger than one harness, so only part of it was read.',+ if (marker != null && !hasMarker)+ 'Without $marker this is published as a general harness, not with its own viewer.',+ if (agent == null)+ 'The Hub does not list $engine yet. Choose the closest agent.',+ ].join(' '),};}+/// A fork's text files as they arrived, to tell its output apart from a new version of it.+Map<String, String> _originalFiles(Map<String, dynamic> previous) => {+ for (final file in (previous['files'] as List? ?? const []).whereType<Map>())+ if (file['path'] is String && file['content'] is String)+ file['path'] as String: file['content'] as String,+};++String _conversationNote(+ List<Map<String, String>> conversation,+ Map<String, dynamic>? tail,+) {+ if (tail?['hasMore'] == true) {+ return 'Recent conversation included. Review it and add any earlier context you want to publish.';+ }+ if (conversation.isEmpty) {+ return 'Add the conversation or a brief describing what you made.';+ }+ return 'Review the conversation before publishing.';+}++String _leftOutNote(List<String> leftOut) {+ final named = leftOut.take(3).join(', ');+ final more = leftOut.length > 3 ? ' and ${leftOut.length - 3} more' : '';+ return 'Left out $named$more: over the Hub\'s limits or not UTF-8 text. '+ 'Choose a project folder here to pick the files yourself.';+}++/// The fork bundle a project came from, for its description, category and attribution.+Future<Map<String, dynamic>> _openHarness(String folder) async {+ final origin = File(p.join(folder, 'OPEN-HARNESS.json'));+ if (!await origin.exists() ||+ await origin.length() > 8100000 ||+ await FileSystemEntity.type(origin.path, followLinks: false) !=+ FileSystemEntityType.file) {+ return const {};+ }+ try {+ final decoded = jsonDecode(await origin.readAsString());+ return decoded is Map<String, dynamic> ? decoded : const {};+ } on FormatException {+ return const {}; // A fresh project is still publishable.+ }+}+/// A short-lived, one-use loopback page sends the draft to the Hub review form./// The Hub keeps it in this browser tab; nothing is published by this handoff.class PublicationHandoff {diff --git a/desktop/lib/community/publish_web.dart b/desktop/lib/community/publish_web.dartindex ac272e2d7..1a0a4b388 100644--- a/desktop/lib/community/publish_web.dart+++ b/desktop/lib/community/publish_web.dart@@ -1,11 +1,12 @@-import 'package:url_launcher/url_launcher.dart';-import '../state/app_state.dart';+import 'hub_links.dart';-Future<void> publishHarness(+/// A browser cannot read a harness's files, so the person chooses them on the Hub.+Future<String> publishHarness(AppNotifier app,String machineId,String agentId,) async {- await launchUrl(Uri.parse('https://harness.autonomous.ai/hub/publish'));+ await openHubPage(hubPublishPage);+ return 'A browser cannot send a harness\'s files. Choose its project folder on the Hub page that opened.';}diff --git a/desktop/lib/community/viewer_picture.dart b/desktop/lib/community/viewer_picture.dartnew file mode 100644index 000000000..ac2b555bb--- /dev/null+++ b/desktop/lib/community/viewer_picture.dart@@ -0,0 +1,66 @@+import 'dart:async';+import 'dart:convert';+import 'dart:math';++/// One `viewer_surface` request to the harness's machine (`AppNotifier.viewerSurface`).+typedef ViewerSurfaceRequest = Future<Map<String, dynamic>> Function(+ Map<String, dynamic> payload,+);++const _width = 1280, _height = 800;++/// Viewers draw after their page loads (pdf.js pages, a WebGL model), so the second frame is kept.+const viewerSettle = Duration(milliseconds: 1500);++/// A JPEG (base64) of the harness's live viewer, as its machine's daemon renders it in headless+/// Chrome, or null when it cannot: no viewer yet, no Chrome on that machine, or no connection.+/// This is how a native result (a Typst PDF, a Blender model) reaches the Hub as a picture.+Future<String?> captureViewer(+ ViewerSurfaceRequest send, {+ Duration settle = viewerSettle,+ Duration timeout = const Duration(seconds: 10),+}) async {+ // A picture is a convenience: a slow machine gives up rather than holding Publish.+ Future<Map<String, dynamic>> request(Map<String, dynamic> payload) =>+ send(payload).timeout(timeout);+ final id =+ 'hub-publish-${Random.secure().nextInt(1 << 32).toRadixString(16)}';+ Map<String, dynamic> frame() => {+ 'surfaceId': id,+ 'op': 'frame',+ 'width': _width,+ 'height': _height,+ 'dark': false,+ 'events': const [],+ };+ try {+ if ((await request(frame()))['error'] != null) return null;+ await Future<void>.delayed(settle);+ final reply = await request(frame());+ final data = reply['data'];+ if (reply['error'] != null ||+ reply['mime'] != 'image/jpeg' ||+ data is! String ||+ data.length > 2 * 1024 * 1024) {+ return null;+ }+ return data;+ } catch (_) {+ return null;+ } finally {+ unawaited(+ request({'surfaceId': id, 'op': 'close'}).then((_) {}, onError: (_) {}),+ );+ }+}++/// A self-contained output page showing [jpeg]: the same shape as a featured starter's poster,+/// but of this version.+String viewerPosterPage(String title, String jpeg) {+ final alt = const HtmlEscape().convert(+ '$title, as its viewer showed it when published',+ );+ return '<!doctype html><html><head><meta charset="utf-8"><title>${const HtmlEscape().convert(title)}</title>'+ '<style>body{margin:0;background:#f7f7f7}img{display:block;width:100%;height:100vh;object-fit:contain}</style>'+ '</head><body><img alt="$alt" src="data:image/jpeg;base64,$jpeg"></body></html>';+}diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dartindex 1b46f5953..fcb0749b3 100644--- a/desktop/lib/sharing/share_harness_dialog.dart+++ b/desktop/lib/sharing/share_harness_dialog.dart@@ -48,7 +48,9 @@ class ShareHarnessDialog extends StatefulWidget {});final String name;final ShareAction manage;- final Future<void> Function()? publish;++ /// Hands the harness to the Hub, returning what the person does next there.+ final Future<String> Function()? publish;@overrideState<ShareHarnessDialog> createState() => _ShareHarnessDialogState();}@@ -798,12 +800,8 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {_error = null;});try {- await widget.publish!();- if (mounted) {- setState(- () => _notice = 'Review your files and conversation in the Hub, then publish.',- );- }+ final next = await widget.publish!();+ if (mounted) setState(() => _notice = next);} catch (error) {if (mounted) {setState(diff --git a/desktop/test/community_hub_contract_test.dart b/desktop/test/community_hub_contract_test.dartnew file mode 100644index 000000000..35a2aa8b1--- /dev/null+++ b/desktop/test/community_hub_contract_test.dart@@ -0,0 +1,66 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/community/hub_contract.dart';++/// `hub_contract.dart` mirrors what the backend accepts. A rule changed there and not here makes+/// Publish to Hub hand the browser drafts the Hub refuses, so this reads the backend's own source.+void main() {+ late String contract;+ setUpAll(() {+ final file = File('../backend/src/lib/communityContract.ts');+ if (!file.existsSync()) {+ throw StateError(+ '${file.path} missing — run from desktop/ in the monorepo',+ );+ }+ contract = file.readAsStringSync();+ });++ String block(String name) {+ final from = contract.indexOf('export const $name');+ if (from < 0) throw StateError('"$name" is gone from communityContract.ts');+ return contract.substring(from, contract.indexOf(RegExp(r'\n\}|\]'), from));+ }++ int limit(String key) {+ final match = RegExp('\\b$key: ([0-9_]+)')+ .firstMatch(block('communityLimits'));+ if (match == null) throw StateError('communityLimits.$key is gone');+ return int.parse(match[1]!.replaceAll('_', ''));+ }++ String pattern(String name) =>+ RegExp('$name = /(.+)/i?\n').firstMatch(contract)![1]!;++ test('the harnesses and their sources are the backend\'s', () {+ final markers = {+ for (final m in RegExp(+ r"'(autonomous/[a-z-]+)': '([^']+)'",+ ).allMatches(block('communityHarnessMarkers')))+ m[1]!: m[2]!,+ };+ expect(markers, isNotEmpty);+ expect(hubHarnessMarkers, markers);+ });++ test('the agents are the backend\'s', () {+ final engines = RegExp(r"'([^']+)'")+ .allMatches(block('communityEngines'))+ .map((m) => m[1]!)+ .toSet();+ expect(hubEngines.values.toSet(), engines);+ });++ test('the limits and names are the backend\'s', () {+ expect(hubMaxFiles, limit('files'));+ expect(hubMaxFileChars, limit('fileChars'));+ expect(hubMaxTurns, limit('turns'));+ expect(hubMaxTurnChars, limit('turnChars'));+ expect(hubMaxCoverChars, limit('coverChars'));+ expect(hubMaxProjectChars, lessThan(limit('snapshotBytes')));+ expect(hubReservedName.pattern, pattern('communityReservedName'));+ expect(hubReservedName.isCaseSensitive, isFalse);+ expect(hubPathPattern.pattern, pattern('communityPathPattern'));+ });+}diff --git a/desktop/test/community_publish_test.dart b/desktop/test/community_publish_test.dartindex e3d112202..28727f2d8 100644--- a/desktop/test/community_publish_test.dart+++ b/desktop/test/community_publish_test.dart@@ -3,6 +3,8 @@ import 'dart:io';import 'package:flutter_test/flutter_test.dart';import 'package:harness/community/hub_return.dart';+import 'package:harness/community/publish_conversation.dart';+import 'package:harness/community/publish_files.dart';import 'package:harness/community/publish_project.dart';void main() {@@ -64,39 +66,222 @@ void main() {});test('never follows source symlinks outside the selected project', () async {final secret = await file('.private/key.json', 'private');- await file('index.html', '<p>Public</p>');+ await file('preview.html', '<p>Public</p>');await Link('${root.path}/leak.json').create(secret.path);final draft = await buildPublicationDraft(folder: root.path,title: 'Safe',engine: 'codex',);- expect((draft['files'] as List).map((f) => f['path']), ['index.html']);+ expect((draft['files'] as List).map((f) => f['path']), ['preview.html']);}, skip: Platform.isWindows);test(- 'refuses a missing viewer and oversized projects without publishing',+ 'asks for a preview.html, never assuming an app page is the output',() async {await file('code.py', 'print(1)');+ await file('index.html', '<script src="app.js"></script>');+ Future<Map<String, dynamic>> build() => buildPublicationDraft(+ folder: root.path,+ title: 'Test',+ engine: 'codex',+ );await expectLater(- buildPublicationDraft(- folder: root.path,- title: 'Test',- engine: 'codex',+ build(),+ throwsA(+ isA<FormatException>().having(+ (e) => e.message,+ 'message',+ contains('preview.html'),+ ),),- throwsFormatException,);- await file('index.html', '<p>Ready</p>');- await file('large.json', 'x' * 3000001);- await expectLater(- buildPublicationDraft(- folder: root.path,- title: 'Test',- engine: 'codex',+ await file('preview.html', 'x' * 3000001);+ await expectLater(build(), throwsFormatException);+ },+ );+ test('a fork keeps the page it was published with', () async {+ await file('index.html', '<h1>Moonlight</h1>');+ await file(+ 'OPEN-HARNESS.json',+ jsonEncode({+ 'forkedFrom': 'starter-moonlight',+ 'viewerPath': 'index.html',+ }),+ );+ final draft = await buildPublicationDraft(+ folder: root.path,+ title: 'My moonlight',+ engine: 'codex',+ );+ expect(draft['viewerPath'], 'index.html');+ expect(draft['forkedFrom'], 'starter-moonlight');+ });+ test('refuses a fork whose output is still the original', () async {+ const poster = '<img src="data:image/png;base64,AA==">';+ await file('preview.html', poster);+ await file('main.typ', '= My changes');+ await file(+ 'OPEN-HARNESS.json',+ jsonEncode({+ 'forkedFrom': 'starter-portable-light',+ 'viewerPath': 'preview.html',+ 'files': [+ {'path': 'preview.html', 'content': poster},+ {'path': 'main.typ', 'content': '= Original'},+ ],+ }),+ );+ Future<Map<String, dynamic>> build() => buildPublicationDraft(+ folder: root.path,+ title: 'Mine',+ engine: 'codex',+ );+ await expectLater(+ build(),+ throwsA(+ isA<NeedsOutput>().having(+ (e) => e.message,+ 'message',+ contains('preview.html is still the original'),),- throwsFormatException,+ ),+ );+ await file('preview.html', '<h1>My page</h1>');+ expect((await build())['viewerPath'], 'preview.html');+ });+ test(+ 'shows a picture of the viewer when the project has no page of its own',+ () async {+ const poster = '<img src="data:image/png;base64,AA==">';+ await file('preview.html', poster);+ await file('main.typ', '= My changes');+ await file(+ 'OPEN-HARNESS.json',+ jsonEncode({+ 'viewerPath': 'preview.html',+ 'files': [+ {'path': 'preview.html', 'content': poster},+ ],+ }),+ );+ final draft = await buildPublicationDraft(+ folder: root.path,+ title: 'Light that travels',+ engine: 'codex',+ harnessId: 'autonomous/typst',+ viewerPicture: 'SNAPSHOT',+ );+ final files = draft['files'] as List;+ final output = files.firstWhere((f) => f['path'] == 'preview.html');+ expect(output['content'], contains('data:image/jpeg;base64,SNAPSHOT'));+ expect(files.where((f) => f['path'] == 'preview.html'), hasLength(1));+ expect(draft['cover'], 'data:image/jpeg;base64,SNAPSHOT');+ expect(draft['harnessId'], 'autonomous/typst');+ expect(draft['contextNote'], contains('a picture of your viewer'));++ await file('preview.html', '<h1>My own page</h1>');+ final own = await buildPublicationDraft(+ folder: root.path,+ title: 'Light that travels',+ engine: 'codex',+ viewerPicture: 'SNAPSHOT',+ );+ expect(+ (own['files'] as List).firstWhere(+ (f) => f['path'] == 'preview.html',+ )['content'],+ '<h1>My own page</h1>',+ );+ expect(own['contextNote'], isNot(contains('a picture of your viewer')));+ },+ );+ test(+ 'passes over an unchanged original page to the new preview.html',+ () async {+ const original = '<h1>Moonlight</h1>';+ await file('index.html', original);+ await file('preview.html', '<h1>My review</h1>');+ await file(+ 'OPEN-HARNESS.json',+ jsonEncode({+ 'viewerPath': 'index.html',+ 'files': [+ {'path': 'index.html', 'content': original},+ ],+ }),+ );+ final draft = await buildPublicationDraft(+ folder: root.path,+ title: 'Mine',+ engine: 'codex',+ viewerPicture: 'SNAPSHOT',);+ expect(draft['viewerPath'], 'preview.html');+ expect(+ (draft['files'] as List).firstWhere(+ (f) => f['path'] == 'preview.html',+ )['content'],+ '<h1>My review</h1>',+ );+ expect(draft, isNot(contains('cover')));},);+ test('leaves out what does not fit and names it, keeping the output and the harness source', () async {+ await file('preview.html', '<p>Ready</p>');+ await file('sim/hello.py', 'print("marker")');+ for (var i = 0; i < 40; i++) {+ await file('src/deep/part$i.ts', 'export const n = $i');+ }+ await file('large.json', 'x' * 3000001);+ await File('${root.path}/latin1.csv')+ .writeAsBytes([0x63, 0x61, 0x66, 0xe9]);+ final draft = await buildPublicationDraft(+ folder: root.path,+ title: 'Robot',+ engine: 'codex',+ harnessId: 'autonomous/mujoco',+ );+ final paths = (draft['files'] as List).map((f) => f['path']).toList();+ expect(paths, hasLength(30));+ expect(paths, containsAll(['preview.html', 'sim/hello.py']));+ expect(paths, isNot(contains('large.json')));+ expect(paths, isNot(contains('latin1.csv')));+ expect(draft['viewerPath'], 'preview.html');+ expect(draft['harnessId'], 'autonomous/mujoco');+ expect(+ draft['contextNote'],+ contains('Left out large.json, latin1.csv, src/deep/'),+ );+ expect(draft['contextNote'], contains('and 11 more'));+ });+ test('publishes without a harness whose source is missing, and asks for an unknown agent', () async {+ await file('preview.html', '<p>Ready</p>');+ final draft = await buildPublicationDraft(+ folder: root.path,+ title: 'Lamp',+ engine: 'grok',+ harnessId: 'autonomous/blender',+ );+ expect(draft, isNot(contains('harnessId')));+ expect(draft, isNot(contains('engine')));+ expect(draft['contextNote'], contains('Without scenes/hello.py'));+ expect(draft['contextNote'], contains('does not list grok'));+ });+ test('keeps the newest turns of a long session', () async {+ final rows = [+ for (var i = 0; i < 50; i++) {'ask': 'ask $i', 'answer': 'answer $i'},+ ];+ final turns = publicationTurns({'rows': rows});+ expect(turns, hasLength(80));+ expect(turns.first, {'role': 'user', 'text': 'ask 10'});+ expect(turns.last, {'role': 'assistant', 'text': 'answer 49'});+ final long = publicationTurns({+ 'rows': [+ {'ask': 'x' * 25000},+ ],+ });+ expect(long.map((turn) => turn['text']!.length), [12000, 12000, 1000]);+ });test('one-use browser handoff posts a draft only to the configured Hub', () async {final draft = {'version': 1,diff --git a/desktop/test/community_viewer_picture_test.dart b/desktop/test/community_viewer_picture_test.dartnew file mode 100644index 000000000..1144d8fee--- /dev/null+++ b/desktop/test/community_viewer_picture_test.dart@@ -0,0 +1,56 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/community/viewer_picture.dart';++void main() {+ test('keeps the second frame, after the viewer has drawn, and closes the surface', () async {+ final calls = <Map<String, dynamic>>[];+ var frames = 0;+ final picture = await captureViewer((payload) async {+ calls.add(payload);+ if (payload['op'] == 'close') return {'closed': true};+ return {'mime': 'image/jpeg', 'data': 'frame${++frames}'};+ }, settle: Duration.zero);+ expect(picture, 'frame2');+ expect(calls.map((c) => c['op']), ['frame', 'frame', 'close']);+ expect(calls.first, containsPair('width', 1280));+ expect(calls.first['surfaceId'], calls.last['surfaceId']);+ });++ test('gives nothing when the viewer cannot be pictured', () async {+ Future<String?> capture(Map<String, dynamic> reply) => captureViewer(+ (payload) async => payload['op'] == 'close' ? {} : reply,+ settle: Duration.zero,+ );+ expect(await capture({'error': 'VIEWER_UNAVAILABLE'}), isNull);+ expect(await capture({'mime': 'image/png', 'data': 'x'}), isNull);+ expect(+ await captureViewer(+ (_) => Future.error(StateError('Reconnect')),+ settle: Duration.zero,+ ),+ isNull,+ );+ });++ test(+ 'a viewer that does not answer is given up on, not waited for',+ () async {+ final never = Completer<Map<String, dynamic>>();+ final picture = await captureViewer(+ (payload) => payload['op'] == 'close' ? Future.value({}) : never.future,+ settle: Duration.zero,+ timeout: const Duration(milliseconds: 20),+ );+ expect(picture, isNull);+ },+ );++ test('a poster page carries the picture and escapes the title', () {+ final page = viewerPosterPage('<Lamp> & "light"', 'AAAA');+ expect(page, contains('src="data:image/jpeg;base64,AAAA"'));+ expect(page, contains('<Lamp> & "light"'));+ expect(page, isNot(contains('<Lamp>')));+ });+}diff --git a/desktop/test/first_task_test.dart b/desktop/test/first_task_test.dartindex 808cfbfdc..82870ce07 100644--- a/desktop/test/first_task_test.dart+++ b/desktop/test/first_task_test.dart@@ -28,6 +28,26 @@ void main() {).allMatches(table!.group(1)!))m.group(1)!: m.group(2) != 'null',};+ // Engines whose launch moved into an engine contract (cli/src/engines/<id>/launch.ts) are+ // spread into the table from there; read them where they are declared.+ if (table.group(1)!.contains("...launchField('firstPromptArgs')")) {+ final launches = RegExp(+ r'export const engineLaunches = \{([^}]*)\}',+ ).firstMatch(File('../cli/src/engines/launches.ts').readAsStringSync());+ expect(+ launches,+ isNotNull,+ reason: 'engineLaunches moved or changed shape',+ );+ for (final id in launches!.group(1)!.split(',').map((s) => s.trim())) {+ if (id.isEmpty) continue;+ final contract = RegExp(r'firstPromptArgs:\s*(null|\[)').firstMatch(+ File('../cli/src/engines/$id/launch.ts').readAsStringSync(),+ );+ expect(contract, isNotNull, reason: '$id has no firstPromptArgs');+ entries.putIfAbsent(id, () => contract!.group(1) != 'null');+ }+ }expect(entries, isNotEmpty);expect({for (final e in entries.entries)diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dartindex bcff2b755..af75016fd 100644--- a/desktop/test/share_harness_test.dart+++ b/desktop/test/share_harness_test.dart@@ -72,6 +72,7 @@ void main() {AppKeymap? keymap,Brightness brightness = Brightness.dark,double scale = 1,+ Future<String> Function()? publish,}) async {tester.view.physicalSize = size;tester.view.devicePixelRatio = 1;@@ -103,6 +104,7 @@ void main() {child: ShareHarnessDialog(name: 'Climate dashboard',manage: manage,+ publish: publish,),),);@@ -843,4 +845,24 @@ void main() {await tester.pumpWidget(const SizedBox());},);+ testWidgets('Publish to Hub says what the Hub needs next', (tester) async {+ await show(+ tester,+ (action, payload) async => {+ 'collaboration': true,+ 'shares': [],+ 'link': {'visibility': 'private'},+ },+ publish: () async =>+ 'Choose its project folder on the Hub page that opened.',+ );+ await tester.tap(find.text('Publish to Hub'));+ await tester.pumpAndSettle();+ expect(+ find.text('Choose its project folder on the Hub page that opened.'),+ findsOneWidget,+ );+ expect(find.textContaining('Review your files'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ });}diff --git a/scripts/record-ci-validation.py b/scripts/record-ci-validation.pyindex b3e6ff70d..f74f16343 100644--- a/scripts/record-ci-validation.py+++ b/scripts/record-ci-validation.py@@ -33,9 +33,11 @@ SCOPES["full"] = CLI_JOBS | TUI_JOBS | SCOPES["backend"] | DESKTOP_JOBS | {"compSOURCE_INPUTS = {"process": (".github/", "scripts/", "desktop/scripts/", ".gitattributes", ".gitignore", ".gitmodules", "Makefile"),# VM tests also read CLI protocol definitions, shared layout fixtures,- # daemon metadata and store catalog/artwork, including docs/images posters.+ # daemon metadata and store catalog/artwork, including docs/images posters,+ # and the Hub's publication rules that desktop/lib/community/hub_contract.dart mirrors."desktop": (".github/", "scripts/", "desktop/", "cli/", "tests/", "daemons/", "store/", "docs/images/",- "mobile/pubspec.lock", ".gitattributes", ".gitignore", ".gitmodules", "Makefile"),+ "mobile/pubspec.lock", "backend/src/lib/communityContract.ts",+ ".gitattributes", ".gitignore", ".gitmodules", "Makefile"),}CHECKOUT_STEP = "Verify declared source checkout"diff --git a/website/README.md b/website/README.mdindex 90c56fda8..afb8c247c 100644--- a/website/README.md+++ b/website/README.md@@ -109,7 +109,10 @@ draft in the browser, then opens `/hub/publish` for review. No access token or ntransferred. Nothing becomes public until the creator reviews the output, source and conversationand clicks Publish. A draft survives the existing sign-in flow; repeated submission uses onepublication ID. Remote projects and older apps can use the project-folder picker or import-`OPEN-HARNESS.json`. The first version requires a self-contained HTML preview, up to 30 files/6 MB;+`OPEN-HARNESS.json`. The output is the project's `preview.html` (or the page a fork arrived with,+once changed). Without one, as for a native result such as a Typst PDF or a Blender model, the+desktop asks the machine's daemon for a picture of the harness's viewer (`viewer_surface`, headless+Chrome) and publishes it as `preview.html` and the cover; a fork still opens the real viewer. The first version requires a self-contained HTML preview, up to 30 files/6 MB;hidden configuration, symlinks and installed dependencies are excluded. Conversation tails may beincomplete and the review form says so. `/explore` links remain compatible with `/hub`.diff --git a/website/src/app/api/community/[...path]/route.spec.ts b/website/src/app/api/community/[...path]/route.spec.tsindex cc2545700..8de10ba2e 100644--- a/website/src/app/api/community/[...path]/route.spec.ts+++ b/website/src/app/api/community/[...path]/route.spec.ts@@ -28,6 +28,22 @@ describe('community API boundary', () => {expect(fetcher.mock.calls[0][1].headers.has('content-type')).toBe(false);expect(fetcher.mock.calls[0][1].body).toBeUndefined();});+ it('serves a cover as a cacheable image, and only an image', async () => {+ const id = '0f8fad5b-d9cb-469f-a165-70867728950e', context = { params: Promise.resolve({ path: ['harnesses', id, 'cover'] }) };+ const request = new Request(`https://harness.example/api/community/harnesses/${id}/cover`, { headers: { authorization: 'Bearer fixture' } });+ const fetcher = vi.fn()+ .mockResolvedValueOnce(new Response(new Uint8Array([137, 80]), { headers: { 'Content-Type': 'image/png' } }))+ .mockResolvedValueOnce(new Response('<svg onload=alert(1)>', { headers: { 'Content-Type': 'image/svg+xml' } }))+ .mockResolvedValueOnce(Response.json({ success: false }, { status: 404 }));+ vi.stubGlobal('fetch', fetcher);+ const image = await GET(request, context);+ expect(image.headers.get('content-type')).toBe('image/png');+ expect(image.headers.get('cache-control')).toBe('public, max-age=86400');+ expect(new Uint8Array(await image.arrayBuffer())).toEqual(new Uint8Array([137, 80]));+ expect(fetcher.mock.calls[0][1].headers).toBeUndefined();+ expect((await GET(request, context)).status).toBe(503);+ expect((await GET(request, context)).status).toBe(404);+ });it('preserves backend permission errors and handles service outages', async () => {const fetcher = vi.fn().mockResolvedValueOnce(Response.json({ success: false, error: { message: 'Sign in.' } }, { status: 401 })).mockRejectedValueOnce(new Error('offline'));vi.stubGlobal('fetch', fetcher);diff --git a/website/src/app/api/community/[...path]/route.ts b/website/src/app/api/community/[...path]/route.tsindex 6e4aa442e..06af96da4 100644--- a/website/src/app/api/community/[...path]/route.ts+++ b/website/src/app/api/community/[...path]/route.ts@@ -1,10 +1,27 @@import { communityApiOrigin } from '@/lib/community/server';type Context = { params: Promise<{ path: string[] }> };-const allowed = /^(?:harnesses(?:\/[a-z0-9-]{1,80}(?:\/like|\/comments(?:\/[a-f0-9-]{36})?)?)?|creators\/[a-z0-9-]{1,80}\/follow)$/;+const allowed = /^(?:harnesses(?:\/[a-z0-9-]{1,80}(?:\/like|\/social|\/comments(?:\/[a-f0-9-]{36})?)?)?|creators\/[a-z0-9-]{1,80}\/follow)$/;+const coverPath = /^harnesses\/[a-f0-9-]{36}\/cover$/;+const coverTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);+const unavailable = () => Response.json({ success: false, error: { message: 'The community is temporarily unavailable. Try again.' } }, { status: 503, headers: { 'Cache-Control': 'no-store' } });++/** A publication never changes once published, so its cover can be cached; an unpublished one goes stale within a day. */+async function cover(path: string): Promise<Response> {+ try {+ const response = await fetch(new URL(`/api/community/${path}`, communityApiOrigin()), { redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(12_000) });+ const type = response.headers.get('content-type') || '';+ if (response.status === 404) return new Response(null, { status: 404, headers: { 'Cache-Control': 'no-store' } });+ if (!response.ok || !coverTypes.has(type)) return unavailable();+ return new Response(await response.arrayBuffer(), { headers: { 'Content-Type': type, 'Cache-Control': 'public, max-age=86400', 'X-Content-Type-Options': 'nosniff' } });+ } catch {+ return unavailable();+ }+}async function forward(request: Request, context: Context): Promise<Response> {const path = (await context.params).path.join('/');+ if (request.method === 'GET' && coverPath.test(path)) return cover(path);const sessionPath = path === 'session' && request.method === 'GET' ? 'me': path === 'session/refresh' && request.method === 'POST' ? 'refresh' : null;if (!sessionPath && !allowed.test(path)) return Response.json({ success: false, error: { message: 'Not found.' } }, { status: 404 });@@ -22,7 +39,7 @@ async function forward(request: Request, context: Context): Promise<Response> {const content = await response.json();return Response.json(content, { status: response.status, headers: { 'Cache-Control': 'no-store' } });} catch {- return Response.json({ success: false, error: { message: 'The community is temporarily unavailable. Try again.' } }, { status: 503, headers: { 'Cache-Control': 'no-store' } });+ return unavailable();}}export const GET = forward;diff --git a/website/src/app/hub/[id]/page.tsx b/website/src/app/hub/[id]/page.tsxindex 279524431..9a6f73edb 100644--- a/website/src/app/hub/[id]/page.tsx+++ b/website/src/app/hub/[id]/page.tsx@@ -1,17 +1,37 @@import type { Metadata } from 'next';+import { cache } from 'react';import { notFound } from 'next/navigation';-import { getStarter } from '@/lib/community/server';-import { starterHarnesses } from '@/lib/community/starters';+import { getPublicHarness } from '@/lib/community/server';+import type { OpenHarness } from '@/lib/community/types';import Detail from '../components/Detail';type Props = { params: Promise<{ id: string }>; searchParams: Promise<{ comments?: string }> };++const validId = (id: string) => /^starter-[a-z-]+$/.test(id) || /^[a-f0-9-]{36}$/.test(id);++/**+ * 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.+ */+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);+});++/** 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) };+}+export async function generateMetadata({ params }: Props): Promise<Metadata> {- const { id } = await params, starter = starterHarnesses.find(item => item.id === id);- return { title: starter?.title || 'Open harness', description: starter?.description };+ const harness = await readHarness((await params).id);+ return { title: harness?.title || 'Open harness', description: harness?.description };}+export default async function HarnessPage({ params, searchParams }: Props) {const { id } = await params;- if (!/^starter-[a-z-]+$/.test(id) && !/^[a-f0-9-]{36}$/.test(id)) notFound();- const initial = await getStarter(id);+ if (!validId(id)) notFound();+ const initial = await readHarness(id);if (id.startsWith('starter-') && !initial) notFound();- return <Detail key={id} id={id} initial={initial} initialComments={(await searchParams).comments !== undefined} />;+ return <Detail key={id} id={id} initial={initial && forViewer(initial)} initialComments={(await searchParams).comments !== undefined} />;}diff --git a/website/src/app/hub/components/Comments.tsx b/website/src/app/hub/components/Comments.tsxnew file mode 100644index 000000000..87fd97d53--- /dev/null+++ b/website/src/app/hub/components/Comments.tsx@@ -0,0 +1,49 @@+'use client';+import { useRef, useState } from 'react';+import type { HarnessComment, SocialState } from '@/lib/community/types';+import { SignIn } from './Header';+import styles from '../community.module.css';++type Props = {+ social: SocialState; ready: boolean; busy: boolean; onRetry: () => void;+ onRemove: (comment: HarnessComment) => void; onPost: (body: string, clientId: string, parentId?: string) => Promise<boolean>;+};++const day = (createdAt: string) => new Date(createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });++function Comment({ comment, busy, canReply, onReply, onRemove }: { comment: HarnessComment; busy: boolean; canReply: boolean; onReply: () => void; onRemove: () => void }) {+ return <article className={`${styles.comment} ${comment.parentId ? styles.reply : ''}`}>+ <div className={styles.commentBy}>+ <span>{comment.authorName}</span>{comment.creator && <em className={styles.creator}>Creator</em>}<small>{day(comment.createdAt)}</small>+ {comment.mine && <button disabled={busy} aria-label={`Delete comment by ${comment.authorName}`} onClick={onRemove}>Delete</button>}+ </div>+ {comment.parentId && <small className={styles.replyContext}>Replying to {comment.parentAuthorName}</small>}+ <p>{comment.body}</p>+ {canReply && <button className={styles.replyButton} onClick={onReply}>Reply</button>}+ </article>;+}++/** The conversation under a harness: the comments, 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.+ const requestId = useRef<string | null>(null);+ const reply = (comment: HarnessComment | null) => { setReplyTo(comment); requestId.current = null; if (comment) document.getElementById('comment')?.focus(); };+ async function submit() {+ if (!draft.trim()) return;+ requestId.current ??= crypto.randomUUID();+ if (!await onPost(draft, requestId.current, replyTo?.id)) return;+ setDraft(''); setReplyTo(null); requestId.current = null;+ }+ 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)} />)}+ {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>}+ <textarea id="comment" required maxLength={2000} value={draft} onChange={event => { setDraft(event.target.value); requestId.current = null; }} placeholder="Ask a question or share an idea…" />+ <button className={styles.primary} disabled={busy || !draft.trim()}>{replyTo ? 'Post reply' : 'Post comment'}</button>+ </form> : <SignIn />}+ </>;+}diff --git a/website/src/app/hub/components/Detail.tsx b/website/src/app/hub/components/Detail.tsxindex 326c178f8..59f36f197 100644--- a/website/src/app/hub/components/Detail.tsx+++ b/website/src/app/hub/components/Detail.tsx@@ -1,73 +1,48 @@'use client';-import { useCallback, useEffect, useRef, useState } from 'react';+import { useState } from 'react';import Link from 'next/link';import { ArrowLeft, GitFork, Heart, MessageCircle, X } from 'lucide-react';-import { communityRequest, emptySocial, CommunityError } from '@/lib/community/client';import { previewDocument } from '@/lib/community/preview';-import type { HarnessComment, OpenHarness, SocialState } from '@/lib/community/types';-import { Header, SignIn } from './Header';-import { HarnessTags } from './HarnessTags';+import type { OpenHarness } from '@/lib/community/types';+import { Comments } from './Comments';import { ForkButton } from './ForkButton';+import { HarnessTags } from './HarnessTags';+import { Header } from './Header';+import { Transcript } from './Transcript';+import { useHarnessDetail } from './useHarnessDetail';import styles from '../community.module.css';-export default function Detail({ id, initial, initialComments = false }: { id: string; initial: OpenHarness | null; initialComments?: boolean }) {- const [harness, setHarness] = useState(initial), [social, setSocial] = useState(emptySocial), [comments, setComments] = useState(initialComments);- const [replyTo, setReplyTo] = useState<HarnessComment | null>(null);- const [draft, setDraft] = useState(''), [error, setError] = useState(''), [busy, setBusy] = useState(false), [ready, setReady] = useState(false), [unavailable, setUnavailable] = useState(false);- const requestId = useRef<string | null>(null), revision = useRef(0), writing = useRef(false);- const load = useCallback(async () => {- if (writing.current) return;- const current = ++revision.current;- try {- const data = await communityRequest<{ harness: OpenHarness | null; social: SocialState }>(`harnesses/${id}`);- if (current !== revision.current) return;- if (data.harness) setHarness(data.harness); setSocial(data.social); setReady(true); setError('');- } catch (e) {- if (current !== revision.current) return;- setReady(false);- if (e instanceof CommunityError && e.status === 404) setUnavailable(true);- else if (!initial) setError('This harness could not be loaded. Please try again.');- }- }, [id, initial]);- useEffect(() => { void load(); const reload = () => { void load(); }; window.addEventListener('focus', reload); return () => { revision.current++; window.removeEventListener('focus', reload); }; }, [load]);- async function mutate(action: () => Promise<void>) {- if (!social.signedIn) { setComments(true); return; }- if (writing.current) return;- writing.current = true; revision.current++;- setBusy(true); setError('');- try { await action(); } catch (e) {- if (e instanceof CommunityError && e.status === 401) { setSocial(value => ({ ...value, signedIn: false })); setComments(true); }- setError(e instanceof CommunityError && e.status === 401 ? 'Your sign-in has expired. Sign in to Harness again to continue.' : e instanceof Error ? e.message : 'Please try again.');- }- finally { writing.current = false; setBusy(false); }- }- if (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}`}>{error || 'Loading harness…'}{error && <button onClick={() => void load()}>Retry</button>}</main></>;+/** 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 { 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(); };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 mutate(async () => { const next = !social.following; await communityRequest(`creators/${harness.authorId}/follow`, { method: 'PUT', body: { following: next } }); setSocial(value => ({ ...value, following: next })); })}>{social.following ? 'Following' : 'Follow'}</button>}+ <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 mutate(async () => { const result = await communityRequest<{ liked: boolean; likes: number }>(`harnesses/${id}/like`, { method: 'PUT', body: { liked: !social.liked } }); setSocial(value => ({ ...value, ...result })); })}><Heart /><span>{ready ? social.likes : 'Like'}</span></button>+ <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>- <div className={styles.split}><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>+ <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 ? <>- {!ready && <p className={styles.notice}>Comments are unavailable right now. <button onClick={() => void load()}>Retry</button></p>}- {ready && !social.comments.length && <p className={styles.notice}>What would you make from here?</p>}- {social.comments.map(comment => <article className={`${styles.comment} ${comment.parentId ? styles.reply : ''}`} key={comment.id}><div className={styles.commentBy}><span>{comment.authorName}</span>{comment.creator && <em className={styles.creator}>Creator</em>}<small>{new Date(comment.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}</small>{comment.mine && <button disabled={busy} aria-label={`Delete comment by ${comment.authorName}`} onClick={() => void mutate(async () => { await communityRequest(`harnesses/${id}/comments/${comment.id}`, { method: 'DELETE' }); setSocial(value => ({ ...value, comments: value.comments.filter(item => item.id !== comment.id) })); })}>Delete</button>}</div>{comment.parentId && <small className={styles.replyContext}>Replying to {comment.parentAuthorName}</small>}<p>{comment.body}</p><button className={styles.replyButton} onClick={() => { setReplyTo(comment); requestId.current = null; document.getElementById('comment')?.focus(); }}>Reply</button></article>)}- {social.signedIn ? <form className={styles.commentForm} onSubmit={event => { event.preventDefault(); if (!draft.trim()) return; requestId.current ??= crypto.randomUUID(); void mutate(async () => { const data = await communityRequest<{ comment: HarnessComment }>(`harnesses/${id}/comments`, { method: 'POST', body: { body: draft, clientId: requestId.current, ...(replyTo ? { parentId: replyTo.id } : {}) } }); setSocial(value => ({ ...value, comments: [...value.comments.filter(item => item.id !== data.comment.id), data.comment] })); setDraft(''); setReplyTo(null); requestId.current = null; }); }}><label htmlFor="comment">{replyTo ? `Reply to ${replyTo.authorName}` : 'Join the conversation'}</label>{replyTo && <button type="button" className={styles.replyButton} onClick={() => { setReplyTo(null); requestId.current = null; }}>Cancel reply</button>}<textarea id="comment" required maxLength={2000} value={draft} onChange={event => { setDraft(event.target.value); requestId.current = null; }} placeholder="Ask a question or share an idea…" /><button className={styles.primary} disabled={busy || !draft.trim()}>{replyTo ? 'Post reply' : 'Post comment'}</button></form> : <SignIn />}- </> : <div className={styles.transcript}>- {harness.example && <p className={styles.contextNote}>{harness.recording ? 'Featured Store project. Watch the recorded run; fork the editable source. This is its published brief, not the original session transcript.' : 'Example conversation. The output and source files are real, editable starter projects.'}</p>}- {harness.conversation.map((turn, index) => turn.role === 'tool' ? <details className={styles.tool} key={index}><summary>Tool output</summary><p>{turn.text}</p></details> : <div className={styles.turn} key={index}><small>{turn.role === 'user' ? harness.authorName : harness.engine}</small><p>{turn.text}</p></div>)}- </div>}- {error && <p className={styles.error} role="alert">{error}</p>}+ {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>- {social.mine && <div className={styles.manage}><button disabled={busy} onClick={() => { if (window.confirm('Remove this harness from the public feed? Existing downloaded forks remain with their owners.')) void mutate(async () => { await communityRequest(`harnesses/${id}`, { method: 'DELETE' }); setUnavailable(true); }); }}>Unpublish this harness</button></div>}+ {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/Feed.tsx b/website/src/app/hub/components/Feed.tsxindex a0f0f0e6f..c4d52909e 100644--- a/website/src/app/hub/components/Feed.tsx+++ b/website/src/app/hub/components/Feed.tsx@@ -1,80 +1,46 @@'use client';-import { useCallback, useEffect, useRef, useState } from 'react';+import { useState } from 'react';import Link from 'next/link';import { Heart, MessageCircle, Search, X } from 'lucide-react';import { starterHarnesses } from '@/lib/community/starters';-import { communityRequest, CommunityError } from '@/lib/community/client';import type { HarnessSummary } from '@/lib/community/types';import { Header, SignIn } from './Header';import { HarnessTags } from './HarnessTags';+import { useFeed, type Stats } from './useFeed';import styles from '../community.module.css';-type Stats = { likes: number; comments: number; liked: boolean };-type FeedResult = { harnesses: HarnessSummary[]; nextCursor: string | null; following: string[]; stats?: Record<string, Stats>; signedIn?: boolean };+/** 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>;+}++const matches = (item: HarnessSummary, query: string) => `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase());+export default function Feed({ following = false, mine = false }: { following?: boolean; mine?: boolean }) {- const [posts, setPosts] = useState<HarnessSummary[]>([]), [follows, setFollows] = useState<string[]>([]);- const [stats, setStats] = useState<Record<string, Stats>>({}), [signedIn, setSignedIn] = useState(false);- const [query, setQuery] = useState(''), [search, setSearch] = useState(false), [cursor, setCursor] = useState<string | null>(null);- const [error, setError] = useState(''), [signedOut, setSignedOut] = useState(false), [busy, setBusy] = useState(false);- 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 (after) params.set('cursor', after);- const result = await communityRequest<FeedResult>(`harnesses?${params}`);- 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 || {});- setCursor(result.nextCursor); setFollows(result.following); setSignedIn(!!result.signedIn);- } catch (e) {- 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]);- useEffect(() => {- void load(); const reload = () => { void load(); };- window.addEventListener('storage', reload); window.addEventListener('harness-session', reload);- return () => { generation.current++; window.removeEventListener('storage', reload); window.removeEventListener('harness-session', reload); };- }, [load]);- useEffect(() => {- if (!cursor || busy || error || !more.current || !('IntersectionObserver' in window)) return;- 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]);- async function like(id: string) {- if (!signedIn) { setSignedOut(true); return; }- if (pendingLikes.current.has(id)) return;- pendingLikes.current.add(id);- 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 } }));- } catch (e) {- if (e instanceof CommunityError && e.status === 401) setSignedOut(true);- else setError(e instanceof Error ? e.message : 'Could not save your like. Try again.');- } finally { pendingLikes.current.delete(id); }- }- const starters = mine ? [] : following ? starterHarnesses.filter(item => follows.includes(item.authorId)) : starterHarnesses;- const visible = [...posts, ...starters].filter(item => `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase()));+ const { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like } = useFeed({ following, mine });+ const [query, setQuery] = useState(''), [search, setSearch] = useState(false);+ // 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));return <><Header following={following} mine={mine} onSearch={() => { setSearch(value => !value); setQuery(''); }} /><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>}{search && <div className={styles.search}><Search size={17} /><input autoFocus type="search" aria-label="Search harnesses" placeholder="Find a harness, creator, or idea" value={query} onChange={event => setQuery(event.target.value)} /><button className={styles.icon} aria-label="Close search" onClick={() => { setSearch(false); setQuery(''); }}><X /></button></div>}{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 => <article key={item.id} 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[item.id]?.liked ? styles.liked : ''} aria-label={`${stats[item.id]?.liked ? 'Unlike' : 'Like'} ${item.title}`} aria-pressed={!!stats[item.id]?.liked} onClick={() => void like(item.id)}><Heart />{stats[item.id]?.likes || 0}</button>- <Link href={`/hub/${item.id}?comments=1`} aria-label={`Comments on ${item.title}`}><MessageCircle />{stats[item.id]?.comments || 0}</Link>- </div>- </article>)}</div>+ <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 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/HarnessTags.tsx b/website/src/app/hub/components/HarnessTags.tsxindex 5200db721..6a1b1107a 100644--- a/website/src/app/hub/components/HarnessTags.tsx+++ b/website/src/app/hub/components/HarnessTags.tsx@@ -1,15 +1,9 @@+import { communityHarnesses } from '@/lib/community/contract';import type { HarnessSummary } from '@/lib/community/types';import styles from '../community.module.css';-const names: Record<string, string> = {- 'autonomous/blender': 'Blender', 'autonomous/marp': 'Marp', 'autonomous/typst': 'Typst',- 'autonomous/circuitjs': 'CircuitJS', 'autonomous/godogen': 'Godogen',- 'autonomous/jev-sheets': 'Jev Sheets', 'autonomous/mujoco': 'MuJoCo',- 'autonomous/rdkit': 'RDKit', 'autonomous/strudel': 'Strudel',-};-export function HarnessTags({ harness }: { harness: Pick<HarnessSummary, 'harnessId' | 'harnessName' | 'engine'> }) {- const name = harness.harnessName || names[harness.harnessId || ''];+ const name = harness.harnessName || communityHarnesses[harness.harnessId || '']?.name;return <span className={styles.tags} aria-label="Harness and agent">{name && <span>{name}</span>}<span>{harness.engine}</span></span>;diff --git a/website/src/app/hub/components/Header.tsx b/website/src/app/hub/components/Header.tsxindex 3bd8c429e..41a06e9fc 100644--- a/website/src/app/hub/components/Header.tsx+++ b/website/src/app/hub/components/Header.tsx@@ -1,14 +1,12 @@'use client';-import { useEffect, useState } from 'react';import Link from 'next/link';import { ArrowUpRight, Search } from 'lucide-react';-import { sessionHeaders } from '@/lib/community/client';import { rememberHubReturn } from '@/lib/community/session';+import { useSignedIn } from './useSignedIn';import styles from '../community.module.css';export function Header({ following = false, mine = false, onSearch }: { following?: boolean; mine?: boolean; onSearch?: () => void }) {- const [signedIn, setSignedIn] = useState(false);- useEffect(() => { const update = () => setSignedIn(!!sessionHeaders().Authorization); update(); window.addEventListener('storage', update); window.addEventListener('harness-session', update); return () => { window.removeEventListener('storage', update); window.removeEventListener('harness-session', update); }; }, []);+ const signedIn = useSignedIn();return <header className={`${styles.wrap} ${styles.bar}`}><Link className={styles.brand} href="/hub">Harness <span className={styles.hubWord}>Hub</span></Link><nav className={styles.nav} aria-label="Harness community">@@ -17,7 +15,7 @@ export function Header({ following = false, mine = false, onSearch }: { followin{signedIn && <Link href="/hub/yours" aria-current={mine ? 'page' : undefined}>Yours</Link>}{onSearch && <button onClick={onSearch} aria-label="Search harnesses"><Search /></button>}<Link href="/hub/publish">Publish</Link>- {!signedIn && <a href="/" onClick={rememberHubReturn}>Sign in</a>}+ {signedIn === false && <a href="/" onClick={rememberHubReturn}>Sign in</a>}<a href="/" className={styles.openApp}>Open Harness <ArrowUpRight /></a></nav></header>;diff --git a/website/src/app/hub/components/Transcript.tsx b/website/src/app/hub/components/Transcript.tsxnew file mode 100644index 000000000..db68a4d4c--- /dev/null+++ b/website/src/app/hub/components/Transcript.tsx@@ -0,0 +1,12 @@+import type { OpenHarness } from '@/lib/community/types';+import styles from '../community.module.css';++/** The published conversation: what was asked, what the agent answered, and folded tool output. */+export function Transcript({ harness }: { harness: OpenHarness }) {+ return <div className={styles.transcript}>+ {harness.example && <p className={styles.contextNote}>{harness.recording ? 'Featured Store project. Watch the recorded run; fork the editable source. This is its published brief, not the original session transcript.' : 'Example conversation. The output and source files are real, editable starter projects.'}</p>}+ {harness.conversation.map((turn, index) => turn.role === 'tool'+ ? <details className={styles.tool} key={index}><summary>Tool output</summary><p>{turn.text}</p></details>+ : <div className={styles.turn} key={index}><small>{turn.role === 'user' ? harness.authorName : harness.engine}</small><p>{turn.text}</p></div>)}+ </div>;+}diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsxindex b1a14b594..3ede2376c 100644--- a/website/src/app/hub/components/community.spec.tsx+++ b/website/src/app/hub/components/community.spec.tsx@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest';import Feed from './Feed';import Detail from './Detail';-import { emptySocial } from '@/lib/community/client';+import { CommunityError, emptySocial } from '@/lib/community/client';import type { OpenHarness } from '@/lib/community/types';const request = vi.hoisted(() => vi.fn());@@ -48,6 +48,38 @@ describe('community navigation', () => {expect(screen.queryByRole('link', { name: 'Open Blue hour' })).not.toBeInTheDocument();await waitFor(() => expect(request).toHaveBeenCalled());});+ it('draws the starters after the last page, so paging never lands above them', async () => {+ request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'first' }], nextCursor: 'next-page', following: [], stats: {}, signedIn: true });+ render(<Feed />);+ await screen.findByRole('button', { name: 'More harnesses' });+ expect(screen.queryByRole('link', { name: 'Open Blue hour' })).not.toBeInTheDocument();+ // A search finds them at once: there is nothing to scroll past.+ fireEvent.click(screen.getByRole('button', { name: 'Search harnesses' }));+ fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'melody' } });+ expect(screen.getByRole('link', { name: 'Open Blue hour' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Close search' }));+ request.mockResolvedValueOnce({ harnesses: [{ ...sample, id: 'second', title: 'Second' }], nextCursor: null, following: [], stats: {}, signedIn: true });+ fireEvent.click(screen.getByRole('button', { name: 'More harnesses' }));+ await screen.findByRole('link', { name: 'Open Blue hour' });+ const links = screen.getAllByRole('link', { name: /^Open / }).map(link => link.getAttribute('href'));+ expect(links.indexOf('/hub/second')).toBeLessThan(links.indexOf('/hub/starter-blue-hour'));+ });+ it('reports a failed like without offering to reload the feed', async () => {+ request.mockResolvedValueOnce({ harnesses: [], nextCursor: null, following: [], stats: {}, signedIn: true });+ render(<Feed />);+ await waitFor(() => expect(request).toHaveBeenCalledTimes(1));+ request.mockRejectedValueOnce(new CommunityError('The community is temporarily unavailable. Try again.', 503));+ fireEvent.click(screen.getByRole('button', { name: 'Like Blue hour' }));+ await screen.findByText('The community is temporarily unavailable. Try again.');+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();+ });+ it('offers Reply only to a signed-in reader', async () => {+ const comment = { id: 'comment-1', body: 'Lovely.', authorName: 'Bob', mine: false, createdAt: '2026-10-06' };+ request.mockResolvedValue({ social: { ...emptySocial, comments: [comment] } });+ render(<Detail id={sample.id} initial={sample} initialComments />);+ await screen.findByText('Lovely.');+ expect(screen.queryByRole('button', { name: 'Reply' })).not.toBeInTheDocument();+ });it('keeps the viewer in place while comments replace the chat and escape user text', async () => {request.mockResolvedValue({ harness: null, social: { ...emptySocial, comments: [{ id: 'c', body: '<img src=x onerror=alert(1)>', authorName: 'Someone', mine: false, createdAt: '2026-10-05' }] } });render(<Detail id={sample.id} initial={sample} />);@@ -63,6 +95,23 @@ describe('community navigation', () => {fireEvent.click(screen.getByRole('button', { name: 'Back to chat log' }));expect(screen.getByText('Make an orbit.')).toBeInTheDocument();});+ it('reads a publication once, then refreshes only its social state', async () => {+ const id = '0f8fad5b-d9cb-469f-a165-70867728950e';+ 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')); });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Like harness' })).toHaveTextContent('3'));+ expect(request).toHaveBeenLastCalledWith(`harnesses/${id}/social`);+ });+ 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(screen.queryByText('This harness is unavailable.')).not.toBeInTheDocument();+ });it('does not pretend a signed-out like succeeded', async () => {request.mockResolvedValue({ harness: null, social: emptySocial });render(<Detail id={sample.id} initial={sample} />);diff --git a/website/src/app/hub/components/useFeed.ts b/website/src/app/hub/components/useFeed.tsnew file mode 100644index 000000000..2d25e5e24--- /dev/null+++ b/website/src/app/hub/components/useFeed.ts@@ -0,0 +1,60 @@+'use client';+import { useCallback, useEffect, useRef, useState } from 'react';+import { communityRequest, CommunityError } from '@/lib/community/client';+import type { HarnessSummary } from '@/lib/community/types';++export type Stats = { likes: number; comments: number; liked: boolean };+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 or sign-out reloads.+ */+export function useFeed({ following, mine }: { following: boolean; mine: boolean }) {+ 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 [error, setError] = useState(''), [likeError, setLikeError] = useState(''), [signedOut, setSignedOut] = useState(false), [busy, setBusy] = useState(false);+ 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 (after) params.set('cursor', after);+ const result = await communityRequest<FeedResult>(`harnesses?${params}`);+ 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 || {});+ setCursor(result.nextCursor); setFollows(result.following); setSignedIn(!!result.signedIn);+ } catch (e) {+ 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]);+ useEffect(() => {+ void load(); const reload = () => { void load(); };+ window.addEventListener('storage', reload); window.addEventListener('harness-session', reload);+ return () => { generation.current++; window.removeEventListener('storage', reload); window.removeEventListener('harness-session', reload); };+ }, [load]);+ useEffect(() => {+ if (!cursor || busy || error || !more.current || !('IntersectionObserver' in window)) return;+ 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]);+ async function like(id: string) {+ if (!signedIn) { setSignedOut(true); return; }+ if (pendingLikes.current.has(id)) return;+ pendingLikes.current.add(id); 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 } }));+ } catch (e) {+ 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); }+ }+ return { posts, follows, stats, cursor, error, likeError, signedOut, busy, more, load, like };+}diff --git a/website/src/app/hub/components/useHarnessDetail.ts b/website/src/app/hub/components/useHarnessDetail.tsnew file mode 100644index 000000000..488632fc3--- /dev/null+++ b/website/src/app/hub/components/useHarnessDetail.ts@@ -0,0 +1,89 @@+'use client';+import { useCallback, useEffect, useRef, useState } from 'react';+import { communityRequest, emptySocial, CommunityError } from '@/lib/community/client';+import type { HarnessComment, OpenHarness, SocialState } from '@/lib/community/types';++/**+ * One harness page's data and the reader's actions on it. Writes run one at a time, and a read that+ * started before a write never lands after it. `onSignIn` is called when an action needs an account.+ */+export function useHarnessDetail(id: string, initial: OpenHarness | null, onSignIn: () => void) {+ const [harness, setHarness] = useState(initial), [social, setSocial] = useState(emptySocial);+ const [error, setError] = useState(''), [busy, setBusy] = useState(false), [ready, setReady] = useState(false), [unavailable, setUnavailable] = useState(false);+ const revision = useRef(0), writing = useRef(false), loaded = useRef(!!initial);++ /**+ * 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.+ */+ const read = useCallback(async () => {+ type Page = { harness?: OpenHarness | null; social: SocialState };+ if (loaded.current) {+ try { return await communityRequest<Page>(`harnesses/${id}/social`); } catch (e) {+ if (!(e instanceof CommunityError && e.status === 404)) throw e;+ }+ }+ return communityRequest<Page>(`harnesses/${id}`);+ }, [id]);+ const load = useCallback(async () => {+ if (writing.current) return;+ const current = ++revision.current;+ try {+ const data = await read();+ if (current !== revision.current) return;+ if (data.harness) { loaded.current = true; setHarness(data.harness); }+ setSocial(data.social); setReady(true); setError('');+ } catch (e) {+ if (current !== revision.current) return;+ setReady(false);+ if (e instanceof CommunityError && e.status === 404) setUnavailable(true);+ else if (!initial) setError('This harness could not be loaded. Please try again.');+ }+ }, [read, initial]);+ useEffect(() => {+ void load();+ const reload = () => { void load(); };+ window.addEventListener('focus', reload);+ return () => { revision.current++; window.removeEventListener('focus', reload); };+ }, [load]);++ /** Runs one write, reporting whether it succeeded. */+ async function mutate(action: () => Promise<void>): Promise<boolean> {+ if (!social.signedIn) { onSignIn(); return false; }+ if (writing.current) return false;+ writing.current = true; revision.current++;+ setBusy(true); setError('');+ try { await action(); return true; } catch (e) {+ const expired = e instanceof CommunityError && e.status === 401;+ if (expired) { setSocial(value => ({ ...value, signedIn: false })); onSignIn(); }+ setError(expired ? 'Your sign-in has expired. Sign in to Harness again to continue.' : e instanceof Error ? e.message : 'Please try again.');+ return false;+ } finally { writing.current = false; setBusy(false); }+ }++ const follow = () => mutate(async () => {+ const next = !social.following;+ await communityRequest(`creators/${harness!.authorId}/follow`, { method: 'PUT', body: { following: next } });+ setSocial(value => ({ ...value, following: next }));+ });+ const like = () => mutate(async () => {+ const result = await communityRequest<{ liked: boolean; likes: number }>(`harnesses/${id}/like`, { method: 'PUT', body: { liked: !social.liked } });+ setSocial(value => ({ ...value, ...result }));+ });+ 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) }));+ });+ /** `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] }));+ });+ const unpublish = () => mutate(async () => {+ await communityRequest(`harnesses/${id}`, { method: 'DELETE' });+ setUnavailable(true);+ });++ return { harness, social, ready, error, busy, unavailable, load, follow, like, removeComment, postComment, unpublish };+}diff --git a/website/src/app/hub/components/useSignedIn.ts b/website/src/app/hub/components/useSignedIn.tsnew file mode 100644index 000000000..3163d659e--- /dev/null+++ b/website/src/app/hub/components/useSignedIn.ts@@ -0,0 +1,16 @@+'use client';+import { useEffect, useState } from 'react';+import { sessionHeaders } from '@/lib/community/client';++/** Whether this browser holds a Harness session: null until it has been read, so nothing flashes. */+export function useSignedIn(): boolean | null {+ const [signedIn, setSignedIn] = useState<boolean | null>(null);+ useEffect(() => {+ const update = () => setSignedIn(!!sessionHeaders().Authorization);+ const events = ['focus', 'storage', 'harness-session'];+ update();+ for (const event of events) window.addEventListener(event, update);+ return () => { for (const event of events) window.removeEventListener(event, update); };+ }, []);+ return signedIn;+}diff --git a/website/src/app/hub/publish/components/ConversationEditor.tsx b/website/src/app/hub/publish/components/ConversationEditor.tsxnew file mode 100644index 000000000..2b71fe25c--- /dev/null+++ b/website/src/app/hub/publish/components/ConversationEditor.tsx@@ -0,0 +1,20 @@+import { communityLimits } from '@/lib/community/contract';+import type { ConversationTurn } from '@/lib/community/types';+import styles from '../../community.module.css';++/** The published conversation, turn by turn, so the person removes what they do not want to share. */+export function ConversationEditor({ turns, onChange }: { turns: ConversationTurn[]; onChange: (turns: ConversationTurn[]) => void }) {+ const edit = (index: number, patch: Partial<ConversationTurn>) => onChange(turns.map((turn, i) => i === index ? { ...turn, ...patch } : turn));+ return <div className={`${styles.field} ${styles.wide}`}>+ <span>Conversation</span>+ <small>Review the published context. Remove private messages, credentials, and tool output you do not want to share.</small>+ {turns.map((turn, index) => <div key={index} className={styles.field}>+ <select aria-label={`Speaker ${index + 1}`} value={turn.role} onChange={event => edit(index, { role: event.target.value as ConversationTurn['role'] })}>+ <option value="user">You</option><option value="assistant">Agent</option><option value="tool">Tool output</option>+ </select>+ <textarea required aria-label={`Message ${index + 1}`} maxLength={communityLimits.turnChars} value={turn.text} onChange={event => edit(index, { text: event.target.value })} />+ <button type="button" disabled={turns.length === 1} onClick={() => onChange(turns.filter((_, i) => i !== index))}>Remove message</button>+ </div>)}+ <button type="button" disabled={turns.length >= communityLimits.turns} onClick={() => onChange([...turns, { role: 'assistant', text: '' }])}>+ Add a message</button>+ </div>;+}diff --git a/website/src/app/hub/publish/components/DetailsFields.tsx b/website/src/app/hub/publish/components/DetailsFields.tsxnew file mode 100644index 000000000..39559d2e7--- /dev/null+++ b/website/src/app/hub/publish/components/DetailsFields.tsx@@ -0,0 +1,17 @@+import { communityCategories, communityEngines, communityHarnesses } from '@/lib/community/contract';+import type { PublishDraft } from '../usePublishDraft';+import styles from '../../community.module.css';++/** How the harness is listed: title, introduction, category, harness and agent. */+export function DetailsFields({ draft, update }: { draft: PublishDraft; update: (patch: Partial<PublishDraft>) => void }) {+ return <>+ <label className={styles.field}>Title<input required maxLength={100} value={draft.title} onChange={event => update({ title: event.target.value })} placeholder="What did you make?" /></label>+ <label className={styles.field}>Description<input required maxLength={300} value={draft.description} onChange={event => update({ description: event.target.value })} placeholder="A short introduction to the work" /></label>+ <label className={styles.field}>Category<select value={draft.category} onChange={event => update({ category: event.target.value })}>{communityCategories.map(c => <option key={c}>{c}</option>)}</select></label>+ <label className={styles.field}>Harness<select value={draft.harnessId || ''} onChange={event => update({ harnessId: event.target.value || undefined })}>+ <option value="">General</option>+ {Object.entries(communityHarnesses).map(([id, { name }]) => <option key={id} value={id}>{name}</option>)}+ </select></label>+ <label className={styles.field}>Agent<select value={draft.engine} onChange={event => update({ engine: event.target.value })}>{communityEngines.map(e => <option key={e}>{e}</option>)}</select></label>+ </>;+}diff --git a/website/src/app/hub/publish/components/FilesReview.tsx b/website/src/app/hub/publish/components/FilesReview.tsxnew file mode 100644index 000000000..8771ebc47--- /dev/null+++ b/website/src/app/hub/publish/components/FilesReview.tsx@@ -0,0 +1,22 @@+import type { SourceFile } from '@/lib/community/types';+import styles from '../../community.module.css';++const kilobytes = (file: SourceFile) => Math.ceil(new TextEncoder().encode(file.content).length / 1024);++/** Every file that will be published, readable before it is, and which page the viewer opens. */+export function FilesReview({ files, viewerPath, onRemove, onViewer }: { files: SourceFile[]; viewerPath: string; onRemove: (path: string) => void; onViewer: (path: string) => void }) {+ if (!files.length) return null;+ const pages = files.filter(file => file.path.endsWith('.html') && !file.encoding);+ return <details className={styles.filesReview}>+ <summary>Review {files.length} source files</summary>+ {files.map(file => <div className={styles.fileRow} key={file.path}>+ <details><summary>{file.path}</summary>{file.encoding ? <p>Binary artifact included in the fork.</p> : <pre className={styles.sourceText}>{file.content}</pre>}</details>+ <small>{kilobytes(file)} KB</small>+ <button type="button" disabled={file.path === viewerPath} onClick={() => onRemove(file.path)}>Remove</button>+ </div>)}+ <label className={styles.field}>Output preview<select value={pages.some(file => file.path === viewerPath) ? viewerPath : ''} onChange={event => onViewer(event.target.value)}>+ <option value="" disabled>Choose the page readers see</option>+ {pages.map(file => <option key={file.path}>{file.path}</option>)}+ </select></label>+ </details>;+}diff --git a/website/src/app/hub/publish/components/ProjectInputs.tsx b/website/src/app/hub/publish/components/ProjectInputs.tsxnew file mode 100644index 000000000..c6520c312--- /dev/null+++ b/website/src/app/hub/publish/components/ProjectInputs.tsx@@ -0,0 +1,19 @@+import styles from '../../community.module.css';++const first = (files: FileList | null, pick: (file: File) => void) => { const file = files?.[0]; if (file) pick(file); };++/** Where a project comes from: its folder, or the fork bundle it started as. */+export function SourceInputs({ onFolder, onBundle }: { onFolder: (files: FileList) => void; onBundle: (file: File) => void }) {+ return <>+ <label className={`${styles.field} ${styles.wide}`}>Project folder<input type="file" multiple ref={element => { element?.setAttribute('webkitdirectory', ''); }} aria-label="Choose project folder" onChange={event => { if (event.target.files) onFolder(event.target.files); }} /><small>Current source and output, up to 30 files and 6 MB. Hidden files and dependencies are excluded.</small></label>+ <label className={`${styles.field} ${styles.wide}`}>Start from your fork<input type="file" accept="application/json,.json" aria-label="Import fork bundle" onChange={event => first(event.target.files, onBundle)} /><small>Optional. Import OPEN-HARNESS.json to keep the original project and attribution.</small></label>+ </>;+}++/** What people see first: the HTML output and an optional cover. */+export function OutputInputs({ onOutput, onCover }: { onOutput: (file: File) => void; onCover: (file: File) => void }) {+ return <>+ <label className={styles.field}>Your output<input type="file" accept="text/html,.html" aria-label="Upload HTML output" onChange={event => first(event.target.files, onOutput)} /><small>Self-contained HTML, up to 3 MB. Styles, scripts, and images should be included in the file; the public viewer cannot call external services.</small></label>+ <label className={styles.field}>Cover image<input type="file" accept="image/png,image/jpeg,image/webp" onChange={event => first(event.target.files, onCover)} /><small>Optional. A 3:2 image, up to 250 KB. The title is used when there is no image.</small></label>+ </>;+}diff --git a/website/src/app/hub/publish/components/PublishChecks.tsx b/website/src/app/hub/publish/components/PublishChecks.tsxnew file mode 100644index 000000000..e68d3792b--- /dev/null+++ b/website/src/app/hub/publish/components/PublishChecks.tsx@@ -0,0 +1,25 @@+import type { SecretFinding } from '@/lib/community/secrets';+import styles from '../../community.module.css';++type Props = {+ noOutput: boolean; unchanged: string | null; outside: string[]; missingMarker: string | null;+ findings: SecretFinding[]; acknowledged: boolean; onAcknowledge: (value: boolean) => void;+};++const listed = (items: string[]) => items.slice(0, 4).join(', ') + (items.length > 4 ? ` and ${items.length - 4} more` : '');++/** What readers would miss, and what stops a publication before the Hub would. */+export function PublishChecks({ noOutput, unchanged, outside, missingMarker, findings, acknowledged, onAcknowledge }: Props) {+ return <>+ {noOutput && <p className={styles.error} role="status">The Hub shows what a session made. Choose the page readers see under Output preview, or upload your output: one page that runs on its own.</p>}+ {unchanged && <p className={styles.error} role="status">{unchanged} is still the original's and has none of your changes. Ask your agent to update it to show the current result, or upload your output.</p>}+ {outside.length > 0 && <p className={styles.notice} role="status">Your output loads {listed(outside)}. The Hub's preview cannot reach other files or the internet, so readers would see it without them. Ask your agent to put them into the page.</p>}+ {missingMarker && <p className={styles.error} role="status">This harness needs {missingMarker} from its project. Choose its project folder, or set Harness to General.</p>}+ {findings.length > 0 && <div className={styles.notice} role="status">+ <strong>This may publish a credential.</strong>+ <ul>{findings.map(finding => <li key={`${finding.where}:${finding.kind}`}>{finding.where} looks like it holds {finding.kind}.</li>)}</ul>+ <p>Remove it from the file or the conversation. Anything published here is public.</p>+ <label className={styles.check}><input type="checkbox" name="secrets" checked={acknowledged} onChange={event => onAcknowledge(event.target.checked)} /><span>I checked these. None of them is a real credential.</span></label>+ </div>}+ </>;+}diff --git a/website/src/app/hub/publish/page.spec.tsx b/website/src/app/hub/publish/page.spec.tsxindex 105663c2e..7aa51875a 100644--- a/website/src/app/hub/publish/page.spec.tsx+++ b/website/src/app/hub/publish/page.spec.tsx@@ -1,6 +1,7 @@import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import PublishPage from './page';+import { readDraft } from '@/lib/community/drafts';vi.mock('@/lib/community/drafts', async importActual => ({ ...await importActual<typeof import('@/lib/community/drafts')>(), readDraft: vi.fn(async () => undefined), saveDraft: vi.fn(async () => {}) }));const mocks = vi.hoisted(() => ({ request: vi.fn(), push: vi.fn(), headers: vi.fn() }));@@ -18,10 +19,16 @@ describe('explicit publication', () => {expect(screen.getByTitle('Publication preview')).toHaveAttribute('sandbox', 'allow-scripts');expect(screen.getByRole('button', { name: 'Publish harness' })).toBeDisabled();expect(mocks.request).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('checkbox'));+ expect(screen.getByText(/index.html is still the original/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Upload HTML output'), { target: { files: [Object.assign(new File(['<h1>My new orbit</h1>'], 'index.html'), { text: async () => '<h1>My new orbit</h1>' })] } });+ await waitFor(() => expect(screen.queryByText(/still the original/)).not.toBeInTheDocument());+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));fireEvent.click(screen.getByRole('button', { name: 'Publish harness' }));await waitFor(() => expect(mocks.push).toHaveBeenCalledWith('/hub/published-fixture'));- expect(mocks.request.mock.calls[0][1].body).toMatchObject({ forkedFrom: 'starter-orbit', confirmed: true, license: 'MIT', files: project.files, conversation: project.conversation });+ expect(mocks.request.mock.calls[0][1].body).toMatchObject({ forkedFrom: 'starter-orbit', confirmed: true, license: 'MIT', files: [{ path: 'index.html', content: '<h1>My new orbit</h1>' }], conversation: project.conversation });+ expect(mocks.request.mock.calls[0][1].body).not.toHaveProperty('originalOutput');});it('keeps a draft after a failed publication and requires sign-in', async () => {mocks.headers.mockReturnValue({}); render(<PublishPage />); await act(async () => {});@@ -33,9 +40,57 @@ describe('explicit publication', () => {fireEvent.change(screen.getByLabelText('Message 1'), { target: { value: 'Make it.' } });fireEvent.change(screen.getByLabelText('Upload HTML output'), { target: { files: [Object.assign(new File(['<h1>Test</h1>'], 'index.html'), { text: async () => '<h1>Test</h1>' })] } });await waitFor(() => expect(screen.getByTitle('Publication preview')).toBeInTheDocument());- fireEvent.click(screen.getByRole('checkbox')); mocks.request.mockRejectedValue(new Error('Service unavailable'));+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ })); mocks.request.mockRejectedValue(new Error('Service unavailable'));fireEvent.click(screen.getByRole('button', { name: 'Publish harness' }));expect(await screen.findByRole('alert')).toHaveTextContent('Service unavailable');expect(screen.getByDisplayValue('Keep this draft')).toBeInTheDocument(); expect(mocks.push).not.toHaveBeenCalled();});+ it('holds back a publication that looks like it carries a credential or lacks its harness source', async () => {+ render(<PublishPage />);+ const bundle = { ...project, harnessId: 'autonomous/blender', files: [...project.files, { path: 'config.json', content: '{ "apiKey": "abcd1234efgh5678" }' }] };+ const file = Object.assign(new File([JSON.stringify(bundle)], 'OPEN-HARNESS.json', { type: 'application/json' }), { text: async () => JSON.stringify(bundle) });+ fireEvent.change(screen.getByLabelText('Import fork bundle'), { target: { files: [file] } });+ await screen.findByText('config.json looks like it holds a password or secret.');+ expect(screen.getByText(/This harness needs scenes\/hello.py/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ fireEvent.click(screen.getByRole('checkbox', { name: /None of them is a real credential/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Harness'), { target: { value: '' } });+ fireEvent.change(screen.getByLabelText('Upload HTML output'), { target: { files: [Object.assign(new File(['<h1>Mine</h1>'], 'index.html'), { text: async () => '<h1>Mine</h1>' })] } });+ await waitFor(() => expect(screen.queryByText(/still the original/)).not.toBeInTheDocument());+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeEnabled();+ });+ it('never assumes an app page is the output, and says what a chosen page cannot load', async () => {+ render(<PublishPage />); await act(async () => {});+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Code review' } });+ fireEvent.change(screen.getByLabelText('Description'), { target: { value: 'What changed and why' } });+ fireEvent.change(screen.getByLabelText('Message 1'), { target: { value: 'Review this.' } });+ const folder = [['index.html', '<script src="app.js"></script>'], ['app.js', 'go()']].map(([path, text]) => Object.assign(new File([text], path), { webkitRelativePath: `project/${path}`, text: async () => text }));+ fireEvent.change(screen.getByLabelText('Choose project folder'), { target: { files: folder } });+ await screen.findByText(/The Hub shows what a session made/);+ expect(screen.queryByTitle('Publication preview')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeDisabled();+ fireEvent.change(screen.getByRole('combobox', { name: /^Output preview/ }), { target: { value: 'index.html' } });+ expect(await screen.findByText(/Your output loads app.js/)).toBeInTheDocument();+ expect(screen.queryByText(/The Hub shows what a session made/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeEnabled();+ });+ it('still knows a fork\'s original output after a reload or a sign-in', async () => {+ vi.mocked(readDraft).mockResolvedValueOnce({ ...project, originalOutput: project.files[0].content } as never);+ render(<PublishPage />);+ expect(await screen.findByText(/index.html is still the original/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox', { name: /I have permission/ }));+ expect(screen.getByRole('button', { name: 'Publish harness' })).toBeDisabled();+ });+ it('refuses a large file by its size, without reading it', async () => {+ render(<PublishPage />); await act(async () => {});+ const read = vi.fn();+ const model = Object.assign(new File([new Uint8Array(2_400_000)], 'model.glb'), { webkitRelativePath: 'project/model.glb', arrayBuffer: read });+ fireEvent.change(screen.getByLabelText('Choose project folder'), { target: { files: [model] } });+ expect(await screen.findByRole('alert')).toHaveTextContent('model.glb is over 3 MB as sent');+ expect(read).not.toHaveBeenCalled();+ });});diff --git a/website/src/app/hub/publish/page.tsx b/website/src/app/hub/publish/page.tsxindex 54c3abd7f..a0128f161 100644--- a/website/src/app/hub/publish/page.tsx+++ b/website/src/app/hub/publish/page.tsx@@ -1,118 +1,89 @@'use client';-import { useEffect, useRef, useState } from 'react';+import { useMemo, useState, type FormEvent } from 'react';import { useRouter } from 'next/navigation';-import { communityRequest, sessionHeaders } from '@/lib/community/client';-import { readDraft, saveDraft, validateDraft, type HubDraft } from '@/lib/community/drafts';+import { communityRequest } from '@/lib/community/client';+import { communityLimits, missingMarker } from '@/lib/community/contract';+import { validateDraft } from '@/lib/community/drafts';import { previewDocument } from '@/lib/community/preview';-import type { ConversationTurn, HarnessSnapshot, SourceFile } from '@/lib/community/types';+import { outsideResources } from '@/lib/community/outputCheck';+import { findSecrets } from '@/lib/community/secrets';import { Header, SignIn } from '../components/Header';+import { useSignedIn } from '../components/useSignedIn';+import { ConversationEditor } from './components/ConversationEditor';+import { DetailsFields } from './components/DetailsFields';+import { FilesReview } from './components/FilesReview';+import { OutputInputs, SourceInputs } from './components/ProjectInputs';+import { PublishChecks } from './components/PublishChecks';+import { originalOutput, readCover, readProjectFolder } from './projectFiles';+import { toSnapshot, usePublishDraft, type PublishDraft } from './usePublishDraft';import styles from '../community.module.css';-const categories = ['Apps', 'Games', 'Motion', 'Music', 'Design', 'Data', 'Documents', 'Experiments'];-const engines = ['Codex', 'Claude Code', 'OpenCode', 'pi'];+const reviewInputs = ['confirmation', 'secrets'];+export default function PublishPage() {- const router = useRouter();- const [title, setTitle] = useState(''), [description, setDescription] = useState(''), [category, setCategory] = useState('Apps'), [engine, setEngine] = useState('Codex');- const [harnessId, setHarnessId] = useState<string | undefined>();- const [files, setFiles] = useState<SourceFile[]>([]), [viewerPath, setViewerPath] = useState('index.html'), [cover, setCover] = useState<string | undefined>();- const [conversation, setConversation] = useState<ConversationTurn[]>([{ role: 'user', text: '' }]), [forkedFrom, setForkedFrom] = useState<string | undefined>();- const draftId = useRef<string | null>(null), publicationId = useRef<string | null>(null), submitting = useRef(false);- const [draftReady, setDraftReady] = useState(false), [contextNote, setContextNote] = useState('');- const [confirmed, setConfirmed] = useState(false), [signedIn, setSignedIn] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState('');- useEffect(() => { const update = () => setSignedIn(!!sessionHeaders().Authorization); update(); window.addEventListener('focus', update); window.addEventListener('storage', update); return () => { window.removeEventListener('focus', update); window.removeEventListener('storage', update); }; }, []);+ const router = useRouter(), signedIn = useSignedIn();+ const { draft, update, applyBundle, saveError, publishOnce } = usePublishDraft();+ const [confirmed, setConfirmed] = useState(false), [checkedSecrets, setCheckedSecrets] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState('');+ const findings = useMemo(() => findSecrets(draft.files, draft.conversation), [draft.files, draft.conversation]);+ // The acknowledgement is for these findings: a new one needs checking again.+ const findingsKey = JSON.stringify(findings), secretsChecked = !findings.length || checkedSecrets === findingsKey;+ const marker = missingMarker(draft.harnessId, draft.files.map(file => file.path));+ const html = draft.files.find(file => file.path === draft.viewerPath && !file.encoding)?.content;+ const outside = useMemo(() => html ? outsideResources(html) : [], [html]);+ const unchanged = html !== undefined && html === draft.originalOutput;+ const ready = !!signedIn && !!html && !unchanged && confirmed && !marker && secretsChecked;- function applyDraft(bundle: HubDraft) {- setTitle(String(bundle.title || '').slice(0, 100)); setDescription(String(bundle.description || '').slice(0, 300));- setCategory(categories.includes(bundle.category || '') ? bundle.category! : 'Apps'); setEngine(engines.includes(bundle.engine || '') ? bundle.engine! : 'Codex');- setHarnessId(bundle.harnessId); setFiles(bundle.files || []); setViewerPath(bundle.viewerPath || 'index.html');- setConversation(bundle.conversation?.length ? bundle.conversation : [{ role: 'user', text: '' }]);- setForkedFrom(bundle.forkedFrom); setCover(bundle.cover); setContextNote(bundle.contextNote || '');- publicationId.current = bundle.clientId || crypto.randomUUID(); setConfirmed(false); setError('');- }- useEffect(() => {- let disposed = false;- const query = new URLSearchParams(window.location.search).get('draft');- const id = query && /^[a-f0-9-]{36}$/.test(query) ? query : crypto.randomUUID();- draftId.current = id; publicationId.current = crypto.randomUUID();- if (!query) window.history.replaceState(null, '', `/hub/publish?draft=${id}`);- void readDraft(id).then(saved => { if (!disposed && saved) applyDraft(saved); }).catch(() => { /* A fresh draft can still be composed. */ }).finally(() => { if (!disposed) setDraftReady(true); });- return () => { disposed = true; };- }, []);- useEffect(() => {- if (!draftReady || !draftId.current || submitting.current) return;- const id = draftId.current;- const timer = setTimeout(() => {- if (submitting.current) return;- void saveDraft(id, { version: 1, title, description, category, engine, harnessId, files, viewerPath, cover, conversation, forkedFrom, contextNote, clientId: publicationId.current || undefined }).catch(() => setError('Your browser could not save this draft. Keep this tab open until you publish.'));- }, 300);- return () => clearTimeout(timer);- }, [draftReady, title, description, category, engine, harnessId, files, viewerPath, cover, conversation, forkedFrom, contextNote]);- async function importBundle(file: File) {- try {- if (file.size > 6_000_000) throw new Error('Keep the project under 6 MB.');- applyDraft(validateDraft(JSON.parse(await file.text())));- } catch (e) { setError(e instanceof Error ? e.message : 'This bundle could not be read.'); }- }- async function importFiles(selected: FileList) {- try {- const entries: SourceFile[] = []; let size = 0;- for (const file of Array.from(selected)) {- const path = file.webkitRelativePath ? file.webkitRelativePath.split('/').slice(1).join('/') : file.name;- if (path.split('/').some(part => part.startsWith('.') || ['node_modules', 'build', 'dist', 'target', 'vendor', '__pycache__'].includes(part))) continue;- if (/^(AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|README\.md|harness\.json)$/i.test(file.name)) continue;- if (file.name === 'OPEN-HARNESS.json') { const original = validateDraft(JSON.parse(await file.text())); setForkedFrom(original.forkedFrom); setHarnessId(original.harnessId); continue; }- if (!/\.(html|css|js|mjs|ts|tsx|jsx|json|md|svg|py|typ|strudel|txt|csv|xml|sdf|png|jpe?g|webp|glb|pdf)$/i.test(path)) continue;- if (entries.length === 30 || file.size > 3_000_000) throw new Error('Choose up to 30 portable files, under 3 MB each.');- const binary = /\.(png|jpe?g|webp|glb|pdf)$/i.test(path);- let content: string;- if (binary) { let raw = ''; for (const byte of new Uint8Array(await file.arrayBuffer())) raw += String.fromCharCode(byte); content = btoa(raw); }- else content = await file.text();- size += new TextEncoder().encode(content).length;- if (content.length > 3_000_000 || size > 5_600_000) throw new Error('Keep the project under 6 MB.');- entries.push({ path, content, ...(binary ? { encoding: 'base64' as const } : {}) });- }- const output = entries.find(f => f.path === viewerPath) || entries.find(f => f.path === 'preview.html') || entries.find(f => f.path.endsWith('.html'));- if (!output) throw new Error('Include a self-contained preview.html or index.html.');- setFiles(entries); setViewerPath(output.path); setConfirmed(false); setError('');- } catch (e) { setError(e instanceof Error ? e.message : 'Could not read the project files.'); }+ /** A changed project has to be reviewed again before it is published. */+ function replaceProject(patch: Partial<PublishDraft>) { update(patch); setConfirmed(false); setError(''); }+ async function attempt(action: () => Promise<void>, fallback: string) {+ try { await action(); } catch (e) { setError(e instanceof Error ? e.message : fallback); }}- async function importOutput(file: File) {- if (file.size > 3_000_000) { setError('Keep the self-contained HTML output under 3 MB.'); return; }- const content = await file.text(); setFiles(previous => [...previous.filter(f => f.path !== viewerPath), { path: viewerPath, content }]); setConfirmed(false); setError('');- }- async function importCover(file: File) {- if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type) || file.size > 250_000) { setError('Choose a PNG, JPEG, or WebP image under 250 KB.'); return; }- const bytes = new Uint8Array(await file.arrayBuffer()); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte);- setCover(`data:${file.type};base64,${btoa(binary)}`); setError('');+ const importBundle = (file: File) => attempt(async () => {+ if (file.size > communityLimits.snapshotBytes) throw new Error('Keep the project under 6 MB.');+ const bundle = validateDraft(JSON.parse(await file.text()));+ applyBundle(bundle); update({ originalOutput: originalOutput(bundle) }); setConfirmed(false); setError('');+ }, 'This bundle could not be read.');+ const importFolder = (files: FileList) => attempt(async () => {+ const folder = await readProjectFolder(Array.from(files), draft.viewerPath);+ const { output, ...origin } = folder.origin || {};+ replaceProject({ files: folder.files, viewerPath: folder.viewerPath, ...origin, ...(folder.origin ? { originalOutput: output } : {}) });+ }, 'Could not read the project files.');+ const importOutput = (file: File) => attempt(async () => {+ if (file.size > communityLimits.fileChars) throw new Error('Keep the self-contained HTML output under 3 MB.');+ const content = await file.text();+ replaceProject({ files: [...draft.files.filter(f => f.path !== draft.viewerPath), { path: draft.viewerPath, content }] });+ }, 'Could not read the output.');+ const importCover = (file: File) => attempt(async () => { update({ cover: await readCover(file) }); setError(''); }, 'Could not read the image.');++ function publish(event: FormEvent) {+ event.preventDefault();+ if (!ready || busy) return;+ setBusy(true); setError('');+ void publishOnce(async clientId => {+ const result = await communityRequest<{ id: string }>('harnesses', { method: 'POST', body: { ...toSnapshot(draft), confirmed, license: 'MIT', clientId } });+ router.push(`/hub/${result.id}`);+ }).catch(e => setError(e instanceof Error ? e.message : 'Publication failed. Your draft is still here.')).finally(() => setBusy(false));}- const html = files.find(f => f.path === viewerPath)?.content;+return <><Header /><main className={`${styles.wrap} ${styles.publish}`}><h1>Give someone a place to begin.</h1><p className={styles.forkIntro}>Publish one session: the working output, its source, and the conversation that got you there. People can inspect it and make their own version.</p>- {!signedIn && <SignIn action="publish your harness" />}- <form onChange={event => { if (!(event.target instanceof HTMLInputElement && event.target.name === 'confirmation')) setConfirmed(false); }} onSubmit={event => { event.preventDefault(); if (!signedIn || submitting.current) return; submitting.current = true; setBusy(true); setError(''); const snapshot: HarnessSnapshot = { title, description, category, engine, ...(harnessId ? { harnessId } : {}), files, viewerPath, conversation, ...(cover ? { cover } : {}), ...(forkedFrom ? { forkedFrom } : {}) }; void communityRequest<{ id: string }>('harnesses', { method: 'POST', body: { ...snapshot, confirmed, license: 'MIT', clientId: publicationId.current || undefined } }).then(async result => { if (draftId.current) await saveDraft(draftId.current, null).catch(() => {}); router.push(`/hub/${result.id}`); }).catch(e => setError(e instanceof Error ? e.message : 'Publication failed. Your draft is still here.')).finally(() => { submitting.current = false; setBusy(false); }); }}>+ {signedIn === false && <SignIn action="publish your harness" />}+ <form onChange={event => { if (!(event.target instanceof HTMLInputElement && reviewInputs.includes(event.target.name))) setConfirmed(false); }} onSubmit={publish}><div className={styles.importActions}><strong>Bring your harness here.</strong><p>In the desktop app, open Share → Publish to Hub. Your current files and conversation arrive here for review.</p><p>You can also choose a project folder below. Include a self-contained HTML preview so everyone can see the result.</p></div><div className={styles.publishForm}>- <label className={`${styles.field} ${styles.wide}`}>Project folder<input type="file" multiple ref={element => { element?.setAttribute('webkitdirectory', ''); }} aria-label="Choose project folder" onChange={event => { if (event.target.files) void importFiles(event.target.files); }} /><small>Current source and output, up to 30 files and 6 MB. Hidden files and dependencies are excluded.</small></label>- <label className={`${styles.field} ${styles.wide}`}>Start from your fork<input type="file" accept="application/json,.json" aria-label="Import fork bundle" onChange={event => { const file = event.target.files?.[0]; if (file) void importBundle(file); }} /><small>Optional. Import OPEN-HARNESS.json to keep the original project and attribution.</small></label>- <label className={styles.field}>Title<input required maxLength={100} value={title} onChange={event => setTitle(event.target.value)} placeholder="What did you make?" /></label>- <label className={styles.field}>Description<input required maxLength={300} value={description} onChange={event => setDescription(event.target.value)} placeholder="A short introduction to the work" /></label>- <label className={styles.field}>Category<select value={category} onChange={event => setCategory(event.target.value)}>{categories.map(c => <option key={c}>{c}</option>)}</select></label>- <label className={styles.field}>Harness<select value={harnessId || ''} onChange={event => setHarnessId(event.target.value || undefined)}><option value="">General</option><option value="autonomous/blender">Blender</option><option value="autonomous/marp">Marp</option><option value="autonomous/typst">Typst</option><option value="autonomous/circuitjs">CircuitJS</option><option value="autonomous/godogen">Godogen</option><option value="autonomous/jev-sheets">Jev Sheets</option><option value="autonomous/mujoco">MuJoCo</option><option value="autonomous/rdkit">RDKit</option><option value="autonomous/strudel">Strudel</option></select></label>- <label className={styles.field}>Agent<select value={engine} onChange={event => setEngine(event.target.value)}>{engines.map(e => <option key={e}>{e}</option>)}</select></label>- <label className={styles.field}>Your output<input type="file" accept="text/html,.html" aria-label="Upload HTML output" onChange={event => { const file = event.target.files?.[0]; if (file) void importOutput(file); }} /><small>Self-contained HTML, up to 3 MB. Styles, scripts, and images should be included in the file; the public viewer cannot call external services.</small></label>- <label className={styles.field}>Cover image<input type="file" accept="image/png,image/jpeg,image/webp" onChange={event => { const file = event.target.files?.[0]; if (file) void importCover(file); }} /><small>Optional. A 3:2 image, up to 250 KB. The title is used when there is no image.</small></label>- <div className={`${styles.field} ${styles.wide}`}><span>Conversation</span><small>Review the published context. Remove private messages, credentials, and tool output you do not want to share.</small>- {conversation.map((turn, index) => <div key={index} className={styles.field}><select aria-label={`Speaker ${index + 1}`} value={turn.role} onChange={event => setConversation(previous => previous.map((item, i) => i === index ? { ...item, role: event.target.value as ConversationTurn['role'] } : item))}><option value="user">You</option><option value="assistant">Agent</option><option value="tool">Tool output</option></select><textarea required aria-label={`Message ${index + 1}`} maxLength={12000} value={turn.text} onChange={event => setConversation(previous => previous.map((item, i) => i === index ? { ...item, text: event.target.value } : item))} /><button type="button" disabled={conversation.length === 1} onClick={() => setConversation(previous => previous.filter((_, i) => i !== index))}>Remove message</button></div>)}- <button type="button" disabled={conversation.length >= 80} onClick={() => setConversation(previous => [...previous, { role: 'assistant', text: '' }])}>+ Add a message</button>- </div>+ <SourceInputs onFolder={files => void importFolder(files)} onBundle={file => void importBundle(file)} />+ <DetailsFields draft={draft} update={update} />+ <OutputInputs onOutput={file => void importOutput(file)} onCover={file => void importCover(file)} />+ <ConversationEditor turns={draft.conversation} onChange={conversation => update({ conversation })} /></div>- {!!files.length && <details className={styles.filesReview}><summary>Review {files.length} source files</summary>{files.map(file => <div className={styles.fileRow} key={file.path}><details><summary>{file.path}</summary>{file.encoding ? <p>Binary artifact included in the fork.</p> : <pre className={styles.sourceText}>{file.content}</pre>}</details><small>{Math.ceil(new TextEncoder().encode(file.content).length / 1024)} KB</small><button type="button" disabled={file.path === viewerPath} onClick={() => { setFiles(previous => previous.filter(item => item.path !== file.path)); setConfirmed(false); }}>Remove</button></div>)}<label className={styles.field}>Output preview<select value={viewerPath} onChange={event => setViewerPath(event.target.value)}>{files.filter(file => file.path.endsWith('.html') && !file.encoding).map(file => <option key={file.path}>{file.path}</option>)}</select></label></details>}- {contextNote && <p className={styles.notice}>{contextNote}</p>}+ <FilesReview files={draft.files} viewerPath={draft.viewerPath} onRemove={path => replaceProject({ files: draft.files.filter(file => file.path !== path) })} onViewer={viewerPath => update({ viewerPath })} />+ {draft.contextNote && <p className={styles.notice}>{draft.contextNote}</p>}{html && <section className={styles.publishPreview}><h2>Review your output</h2><iframe title="Publication preview" sandbox="allow-scripts" referrerPolicy="no-referrer" srcDoc={previewDocument(html)} /></section>}- {forkedFrom && <p className={styles.notice}>The original harness will stay credited on your publication.</p>}+ {draft.forkedFrom && <p className={styles.notice}>The original harness will stay credited on your publication.</p>}+ <PublishChecks noOutput={!!draft.files.length && html === undefined} unchanged={unchanged ? draft.viewerPath : null} outside={outside} missingMarker={marker} findings={findings} acknowledged={secretsChecked} onAcknowledge={value => setCheckedSecrets(value ? findingsKey : '')} /><label className={styles.check}><input required type="checkbox" name="confirmation" checked={confirmed} onChange={event => setConfirmed(event.target.checked)} /><span>I have permission to publish these files and this conversation under the MIT license. I have reviewed them for private information.</span></label>- {error && <p className={styles.error} role="alert">{error}</p>}- <button className={styles.primary} disabled={busy || !signedIn || !html || !confirmed}>{busy ? 'Publishing…' : 'Publish harness'}</button>+ {(error || saveError) && <p className={styles.error} role="alert">{error || saveError}</p>}+ <button className={styles.primary} disabled={busy || !ready}>{busy ? 'Publishing…' : 'Publish harness'}</button></form></main></>;}diff --git a/website/src/app/hub/publish/projectFiles.ts b/website/src/app/hub/publish/projectFiles.tsnew file mode 100644index 000000000..02a045069--- /dev/null+++ b/website/src/app/hub/publish/projectFiles.ts@@ -0,0 +1,61 @@+import { validateDraft, type HubDraft } from '@/lib/community/drafts';+import { communityLimits } from '@/lib/community/contract';+import type { SourceFile } from '@/lib/community/types';++const skippedFolders = ['node_modules', 'build', 'dist', 'target', 'vendor', '__pycache__'];+const bundleFiles = /^(AGENTS\.md|CLAUDE\.md|SESSION\.md|LICENSE|README\.md|harness\.json)$/i;+const portable = /\.(html|css|js|mjs|ts|tsx|jsx|json|md|svg|py|typ|strudel|txt|csv|xml|sdf|png|jpe?g|webp|glb|pdf)$/i;+const binary = /\.(png|jpe?g|webp|glb|pdf)$/i;+const sentNote = 'Images count about a third larger than on disk.';++export type ProjectFolder = { files: SourceFile[]; viewerPath: string; origin?: Pick<HubDraft, 'forkedFrom' | 'harnessId'> & { output?: string } };++/** A fork bundle's output page as it arrived, to tell a new version from the original. */+export const originalOutput = (bundle: HubDraft) => bundle.files?.find(file => file.path === bundle.viewerPath)?.content;++function base64(bytes: Uint8Array): string {+ let raw = '';+ for (let at = 0; at < bytes.length; at += 0x8000) raw += String.fromCharCode(...bytes.subarray(at, at + 0x8000));+ return btoa(raw);+}++/** A file's size as sent, known before reading it: base64 for binary, at least its characters for text. */+const sentSize = (file: File, encoded: boolean) => encoded ? Math.ceil(file.size / 3) * 4 : file.size;++/** A chosen project folder as the Hub stores it: portable files only, measured as they will be sent. */+export async function readProjectFolder(selected: Iterable<File>, preferredViewer: string): Promise<ProjectFolder> {+ const files: SourceFile[] = [];+ let size = 0, origin: ProjectFolder['origin'];+ for (const file of selected) {+ const path = file.webkitRelativePath ? file.webkitRelativePath.split('/').slice(1).join('/') : file.name;+ if (path.split('/').some(part => part.startsWith('.') || skippedFolders.includes(part))) continue;+ if (bundleFiles.test(file.name)) continue;+ if (file.name === 'OPEN-HARNESS.json') {+ const original = validateDraft(JSON.parse(await file.text()));+ origin = { forkedFrom: original.forkedFrom, harnessId: original.harnessId, output: originalOutput(original) };+ continue;+ }+ if (!portable.test(path)) continue;+ if (files.length === communityLimits.files) throw new Error(`Choose up to ${communityLimits.files} portable files.`);+ const encoded = binary.test(path);+ // Refused by size before it is read: a large model or video would otherwise freeze the tab.+ if (encoded && sentSize(file, encoded) > communityLimits.fileChars) throw new Error(`${path} is over 3 MB as sent. ${sentNote}`);+ if (size + sentSize(file, encoded) > communityLimits.projectBytes) throw new Error(`Keep the project under 6 MB as sent. ${sentNote}`);+ const content = encoded ? base64(new Uint8Array(await file.arrayBuffer())) : await file.text();+ if (content.length > communityLimits.fileChars) throw new Error(`${path} is over 3 MB as sent. ${sentNote}`);+ size += new TextEncoder().encode(content).length;+ if (size > communityLimits.projectBytes) throw new Error(`Keep the project under 6 MB as sent. ${sentNote}`);+ files.push({ path, content, ...(encoded ? { encoding: 'base64' as const } : {}) });+ }+ // The page already chosen, or else preview.html. Any other page is offered, never assumed: an app's+ // index.html usually needs files the Hub's sandbox cannot load.+ const viewer = [preferredViewer, 'preview.html'].map(name => files.find(f => f.path === name && f.path.endsWith('.html') && !f.encoding)).find(Boolean);+ if (!files.length) throw new Error('This folder has no portable project files.');+ return { files, viewerPath: viewer?.path ?? preferredViewer, origin };+}++/** A cover as the data URL the Hub stores, or an error naming what it accepts. */+export async function readCover(file: File): Promise<string> {+ if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type) || file.size > 250_000) throw new Error('Choose a PNG, JPEG, or WebP image under 250 KB.');+ return `data:${file.type};base64,${base64(new Uint8Array(await file.arrayBuffer()))}`;+}diff --git a/website/src/app/hub/publish/usePublishDraft.ts b/website/src/app/hub/publish/usePublishDraft.tsnew file mode 100644index 000000000..39c834ab7--- /dev/null+++ b/website/src/app/hub/publish/usePublishDraft.ts@@ -0,0 +1,73 @@+'use client';+import { useCallback, useEffect, useRef, useState } from 'react';+import { readDraft, saveDraft, type HubDraft } from '@/lib/community/drafts';+import { communityCategories, communityEngines } from '@/lib/community/contract';+import type { HarnessSnapshot } from '@/lib/community/types';++/** `originalOutput` is the fork's output as it arrived: kept here to compare against, never published. */+export type PublishDraft = Omit<HarnessSnapshot, 'harnessName' | 'credits'> & { contextNote: string; originalOutput?: string };++const fresh: PublishDraft = { title: '', description: '', category: 'Apps', engine: 'Codex', files: [], viewerPath: 'preview.html', conversation: [{ role: 'user', text: '' }], contextNote: '' };++/** A handed-off or imported bundle, kept within what the form can show and the Hub accepts. */+function fromBundle(bundle: HubDraft): PublishDraft {+ return {+ title: String(bundle.title || '').slice(0, 100), description: String(bundle.description || '').slice(0, 300),+ category: communityCategories.includes(bundle.category || '') ? bundle.category! : 'Apps',+ engine: communityEngines.includes(bundle.engine || '') ? bundle.engine! : 'Codex',+ harnessId: bundle.harnessId, files: bundle.files || [], viewerPath: bundle.viewerPath || 'preview.html',+ conversation: bundle.conversation?.length ? bundle.conversation : fresh.conversation,+ forkedFrom: bundle.forkedFrom, cover: bundle.cover, contextNote: bundle.contextNote || '', originalOutput: bundle.originalOutput,+ };+}++/** What the Hub stores: the draft without the note that was only for the person reviewing it. */+export function toSnapshot(draft: PublishDraft): HarnessSnapshot {+ const { title, description, category, engine, harnessId, files, viewerPath, conversation, cover, forkedFrom } = draft;+ return { title, description, category, engine, ...(harnessId ? { harnessId } : {}), files, viewerPath, conversation, ...(cover ? { cover } : {}), ...(forkedFrom ? { forkedFrom } : {}) };+}++/**+ * The publish form's draft, kept in this browser under `?draft=<id>` so a reload or a sign-in keeps+ * it. `publicationId` makes a retried Publish return the same publication instead of a second one.+ */+export function usePublishDraft() {+ const [draft, setDraft] = useState(fresh), [ready, setReady] = useState(false), [saveError, setSaveError] = useState('');+ const draftId = useRef<string | null>(null), publicationId = useRef<string | null>(null), submitting = useRef(false);+ const update = useCallback((patch: Partial<PublishDraft>) => setDraft(value => ({ ...value, ...patch })), []);+ const applyBundle = useCallback((bundle: HubDraft) => {+ setDraft(fromBundle(bundle));+ publicationId.current = bundle.clientId || crypto.randomUUID();+ }, []);++ useEffect(() => {+ let disposed = false;+ const query = new URLSearchParams(window.location.search).get('draft');+ const id = query && /^[a-f0-9-]{36}$/.test(query) ? query : crypto.randomUUID();+ draftId.current = id; publicationId.current = crypto.randomUUID();+ if (!query) window.history.replaceState(null, '', `/hub/publish?draft=${id}`);+ void readDraft(id).then(saved => { if (!disposed && saved) applyBundle(saved); }).catch(() => { /* A fresh draft can still be composed. */ }).finally(() => { if (!disposed) setReady(true); });+ return () => { disposed = true; };+ }, [applyBundle]);++ useEffect(() => {+ if (!ready || !draftId.current || submitting.current) return;+ const id = draftId.current;+ const timer = setTimeout(() => {+ if (submitting.current) return;+ void saveDraft(id, { version: 1, ...draft, clientId: publicationId.current || undefined }).then(() => setSaveError(''), () => setSaveError('Your browser could not save this draft. Keep this tab open until you publish.'));+ }, 300);+ return () => clearTimeout(timer);+ }, [ready, draft]);++ /** Sends the publication once at a time with this draft's id, then forgets the draft. */+ const publishOnce = useCallback(async (send: (clientId: string | undefined) => Promise<void>) => {+ if (submitting.current) return;+ submitting.current = true;+ try {+ await send(publicationId.current || undefined);+ if (draftId.current) await saveDraft(draftId.current, null).catch(() => {});+ } finally { submitting.current = false; }+ }, []);+ return { draft, update, applyBundle, saveError, publishOnce };+}diff --git a/website/src/lib/community/contract.spec.ts b/website/src/lib/community/contract.spec.tsnew file mode 100644index 000000000..2cf986551--- /dev/null+++ b/website/src/lib/community/contract.spec.ts@@ -0,0 +1,24 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';+import * as backend from '../../../../backend/src/lib/communityContract';+import { communityCategories, communityEngines, communityHarnesses, communityLimits, missingMarker } from './contract';+import { starterHarnesses } from './starters';++describe('the Hub contract', () => {+ it('matches what the backend accepts', () => {+ expect(Object.fromEntries(Object.entries(communityHarnesses).map(([id, { marker }]) => [id, marker]))).toEqual(backend.communityHarnessMarkers);+ expect(communityCategories).toEqual(backend.communityCategories);+ expect(communityEngines).toEqual(backend.communityEngines);+ for (const key of ['files', 'fileChars', 'snapshotBytes', 'turns', 'turnChars'] as const)+ expect(communityLimits[key], key).toBe(backend.communityLimits[key]);+ });+ 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);+ });+ it('names a missing harness source', () => {+ expect(missingMarker('autonomous/blender', ['index.html'])).toBe('scenes/hello.py');+ expect(missingMarker('autonomous/blender', ['index.html', 'scenes/hello.py'])).toBeNull();+ expect(missingMarker(undefined, [])).toBeNull();+ });+});diff --git a/website/src/lib/community/contract.ts b/website/src/lib/community/contract.tsnew file mode 100644index 000000000..08bbc2c4e--- /dev/null+++ b/website/src/lib/community/contract.ts@@ -0,0 +1,38 @@+/**+ * What the Hub accepts from a publication, as `backend/src/lib/communityContract.ts` checks it.+ * ⚠️ A copy, because the website does not ship the backend: `contract.spec.ts` imports that file and+ * fails when the two drift, so change both together (and `desktop/lib/community/hub_contract.dart`).+ */++/** The harnesses the Hub names: how a card labels each, and the source file its publication must include. */+export const communityHarnesses: Record<string, { name: string; marker: string }> = {+ 'autonomous/blender': { name: 'Blender', marker: 'scenes/hello.py' },+ 'autonomous/marp': { name: 'Marp', marker: 'deck.md' },+ 'autonomous/typst': { name: 'Typst', marker: 'main.typ' },+ 'autonomous/circuitjs': { name: 'CircuitJS', marker: 'circuit.txt' },+ 'autonomous/godogen': { name: 'Godogen', marker: 'studio.json' },+ 'autonomous/jev-sheets': { name: 'Jev Sheets', marker: 'sheet.json' },+ 'autonomous/mujoco': { name: 'MuJoCo', marker: 'sim/hello.py' },+ 'autonomous/rdkit': { name: 'RDKit', marker: 'molecules/hello.py' },+ 'autonomous/strudel': { name: 'Strudel', marker: 'track.strudel' },+};++export const communityCategories = ['Apps', 'Games', 'Motion', 'Music', 'Design', 'Data', 'Documents', 'Experiments'];+export const communityEngines = ['Codex', 'Claude Code', 'OpenCode', 'pi'];++export const communityLimits = {+ files: 30,+ /** Characters of one file as sent: a binary file is base64, about a third larger than on disk. */+ fileChars: 3_000_000,+ /** The project's share of the 6 MB snapshot, leaving room for the conversation. */+ projectBytes: 5_600_000,+ snapshotBytes: 6_000_000,+ turns: 80,+ turnChars: 12_000,+};++/** The harness source a publication still needs, or null when it has it (or names no harness). */+export function missingMarker(harnessId: string | undefined, paths: string[]): string | null {+ const marker = harnessId ? communityHarnesses[harnessId]?.marker : undefined;+ return marker && !paths.includes(marker) ? marker : null;+}diff --git a/website/src/lib/community/drafts.ts b/website/src/lib/community/drafts.tsindex ce6f8125e..1d427d0ce 100644--- a/website/src/lib/community/drafts.ts+++ b/website/src/lib/community/drafts.ts@@ -1,15 +1,17 @@+import { communityLimits } from './contract';import type { HarnessSnapshot } from './types';-export type HubDraft = Partial<HarnessSnapshot> & { version?: number; clientId?: string; contextNote?: string };+/** `originalOutput` is kept only by the review page, to tell a fork's new output from the one it arrived with. */+export type HubDraft = Partial<HarnessSnapshot> & { version?: number; clientId?: string; contextNote?: string; originalOutput?: string };export const draftDatabase = 'harness.hub.drafts';export function validateDraft(value: unknown): HubDraft {if (!value || typeof value !== 'object') throw new Error('Choose a Harness project bundle.');const draft = value as HubDraft;- for (const key of ['title', 'description', 'category', 'engine', 'viewerPath', 'cover', 'harnessId', 'forkedFrom', 'clientId', 'contextNote'] as const) {+ for (const key of ['title', 'description', 'category', 'engine', 'viewerPath', 'cover', 'harnessId', 'forkedFrom', 'clientId', 'contextNote', 'originalOutput'] as const) {if (draft[key] !== undefined && typeof draft[key] !== 'string') throw new Error('Invalid draft metadata.');}- if (draft.version !== 1 || !Array.isArray(draft.files) || draft.files.length > 30 || !draft.files.every(file => typeof file.path === 'string' && typeof file.content === 'string' && file.content.length <= 3_000_000 && (!file.encoding || file.encoding === 'base64')) || !Array.isArray(draft.conversation) || draft.conversation.length > 80 || !draft.conversation.every(turn => ['user', 'assistant', 'tool'].includes(turn.role) && typeof turn.text === 'string' && turn.text.length <= 12000)) throw new Error('Choose the OPEN-HARNESS.json from your harness.');+ if (draft.version !== 1 || !Array.isArray(draft.files) || draft.files.length > communityLimits.files || !draft.files.every(file => typeof file.path === 'string' && typeof file.content === 'string' && file.content.length <= communityLimits.fileChars && (!file.encoding || file.encoding === 'base64')) || !Array.isArray(draft.conversation) || draft.conversation.length > communityLimits.turns || !draft.conversation.every(turn => ['user', 'assistant', 'tool'].includes(turn.role) && typeof turn.text === 'string' && turn.text.length <= communityLimits.turnChars)) throw new Error('Choose the OPEN-HARNESS.json from your harness.');if (typeof draft.viewerPath !== 'string' || !draft.files.some(file => file.path === draft.viewerPath && !file.encoding && file.path.endsWith('.html'))) throw new Error('Include a self-contained HTML preview of your output.');return draft;}diff --git a/website/src/lib/community/outputCheck.spec.ts b/website/src/lib/community/outputCheck.spec.tsnew file mode 100644index 000000000..5fa27ab42--- /dev/null+++ b/website/src/lib/community/outputCheck.spec.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';+import { outsideResources } from './outputCheck';++describe('output check', () => {+ it('names what an output page loads from elsewhere', () => {+ const html = `<link rel="stylesheet" href="style.css"><link rel="icon" href="favicon.ico">+ <script type="module" src='./app.js'></script><img src=https://cdn.example/logo.png>+ <style>@import "fonts.css"; body { background: url(bg.png) }</style><a href="other.html">More</a>`;+ expect(outsideResources(html)).toEqual(['./app.js', 'https://cdn.example/logo.png', 'style.css', 'bg.png', 'fonts.css']);+ });+ it('accepts a page that carries everything itself', () => {+ expect(outsideResources('<style>i{background:url("data:image/png;base64,AA==")}</style><img src="data:image/png;base64,AA=="><script>go()</script><a href="#top">Top</a>')).toEqual([]);+ });+});diff --git a/website/src/lib/community/outputCheck.ts b/website/src/lib/community/outputCheck.tsnew file mode 100644index 000000000..5c4de320a--- /dev/null+++ b/website/src/lib/community/outputCheck.ts@@ -0,0 +1,20 @@+/** Addresses the page loads for itself that the Hub's sandbox serves: none, apart from these. */+const inline = /^(?:data:|blob:|#|about:|javascript:)/i;++const attribute = (tag: string, name: string) => tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'))?.slice(1).find(value => value !== undefined)?.trim();++/**+ * Files and addresses an output page loads that the published preview cannot reach: the sandbox+ * serves no other file and blocks the network, so each one is missing for readers.+ */+export function outsideResources(html: string): string[] {+ const found = new Set<string>();+ const add = (value: string | undefined) => { if (value && !inline.test(value)) found.add(value); };+ for (const [tag] of html.matchAll(/<(?:script|img|iframe|source|video|audio|embed|track)\b[^>]*>/gi)) add(attribute(tag, 'src'));+ for (const [tag] of html.matchAll(/<link\b[^>]*>/gi)) {+ if (/\brel\s*=\s*["']?(?:stylesheet|preload|modulepreload)\b/i.test(tag)) add(attribute(tag, 'href'));+ }+ for (const [, value] of html.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/gi)) add(value.trim());+ for (const [, value] of html.matchAll(/@import\s+["']([^"']+)["']/gi)) add(value);+ return [...found];+}diff --git a/website/src/lib/community/secrets.spec.ts b/website/src/lib/community/secrets.spec.tsnew file mode 100644index 000000000..7f7f626d9--- /dev/null+++ b/website/src/lib/community/secrets.spec.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';+import { findSecrets } from './secrets';++describe('secret review', () => {+ it('names where a credential appears in the files and the conversation', () => {+ const findings = findSecrets(+ [+ { path: 'index.html', content: '<h1>Fine</h1>' },+ { path: 'config.json', content: '{ "apiKey": "abcd1234efgh5678" }' },+ { path: 'deploy.md', content: 'AKIAIOSFODNN7EXAMPLE' },+ { path: 'photo.png', content: 'c2stYW50LXNlY3JldA==', encoding: 'base64' },+ ],+ [{ role: 'user', text: 'Use sk-ant-api03-abcdefghijklmnopqrstuvwxyz' }, { role: 'assistant', text: 'Done.' }],+ );+ expect(findings).toEqual([+ { where: 'config.json', kind: 'a password or secret' },+ { where: 'deploy.md', kind: 'an AWS access key' },+ { where: 'Message 1', kind: 'an AI provider key' },+ ]);+ });+ it('leaves ordinary code alone', () => {+ expect(findSecrets([{ path: 'app.js', content: 'const password = input.value; // sk-short' }], [])).toEqual([]);+ });+});diff --git a/website/src/lib/community/secrets.ts b/website/src/lib/community/secrets.tsnew file mode 100644index 000000000..72b84851e--- /dev/null+++ b/website/src/lib/community/secrets.ts@@ -0,0 +1,25 @@+import type { ConversationTurn, SourceFile } from './types';++export type SecretFinding = { where: string; kind: string };++/** Shapes a credential has when someone pastes or prints one. A hint for review, not a guarantee. */+const patterns: { kind: string; pattern: RegExp }[] = [+ { kind: 'a private key', pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },+ { kind: 'an AWS access key', pattern: /\bAKIA[0-9A-Z]{16}\b/ },+ { kind: 'a GitHub token', pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})\b/ },+ { kind: 'an AI provider key', pattern: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/ },+ { kind: 'a Slack token', pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },+ { kind: 'a Google API key', pattern: /\bAIza[0-9A-Za-z_-]{35}\b/ },+ { kind: 'a Stripe key', pattern: /\b[rs]k_live_[0-9A-Za-z]{20,}/ },+ { kind: 'a sign-in token', pattern: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },+ { kind: 'a password or secret', pattern: /\b(?:password|passwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token)\b["']?\s*[:=]\s*["'][^"'\s]{8,}["']/i },+];++/** Where the text files and the conversation look like they hold a credential. */+export function findSecrets(files: SourceFile[], conversation: ConversationTurn[]): SecretFinding[] {+ const places = [+ ...files.filter(file => !file.encoding).map(file => ({ where: file.path, text: file.content })),+ ...conversation.map((turn, index) => ({ where: `Message ${index + 1}`, text: turn.text })),+ ];+ return places.flatMap(({ where, text }) => patterns.filter(({ pattern }) => pattern.test(text)).map(({ kind }) => ({ where, kind })));+}diff --git a/website/src/lib/community/server.ts b/website/src/lib/community/server.tsindex 732d4764d..cafb4923e 100644--- a/website/src/lib/community/server.ts+++ b/website/src/lib/community/server.ts@@ -27,11 +27,11 @@ export async function getStarter(id: string): Promise<OpenHarness | null> {return { ...summary, viewerPath, files, conversation: starterConversation(id) };}-export async function getPublicHarness(id: string): Promise<OpenHarness | null> {+export async function getPublicHarness(id: string, timeoutMs = 8000): Promise<OpenHarness | null> {const starter = await getStarter(id);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(8000) });+ const response = await fetch(`${communityApiOrigin()}/api/community/harnesses/${id}`, { cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) });if (response.status === 404) return null;if (!response.ok) throw new Error('Community service unavailable.');const body = await response.json();diff --git a/work/HUB-REVIEW-2026-10-07.md b/work/HUB-REVIEW-2026-10-07.mdnew file mode 100644index 000000000..d012fbf5e--- /dev/null+++ b/work/HUB-REVIEW-2026-10-07.md@@ -0,0 +1,211 @@+# Harness Hub review · October 7++Scope: the Hub as shipped in `aff63539d` (#890) and unchanged on `origin/main` today: the web+pages (`website/src/app/hub/`, `website/src/lib/community/`), the API (`backend/src/routes/community.ts`,+the four `Community*` Prisma models, the Next proxy in `website/src/app/api/community/`), and the+desktop's **Share ▸ Publish to Hub** (`desktop/lib/community/publish_*.dart`). Forking from the Hub+into the desktop was not reviewed.++This is a source review plus one live read of https://harness.autonomous.ai/hub (signed in). No tests+were run for this report.++## What the live page shows++18 cards, all "Harness · Starter", all tagged Codex, all at 0 likes and 0 comments. No community+posts exist yet. The page is fast (DOM ready ~0.8 s). Card images use `alt=""` on purpose, because the+surrounding link carries `aria-label="Open {title}"`.++## How a publication travels++```+Desktop: Share ▸ Publish to Hub+ └ buildPublicationDraft: walk the agent's project folder + the last 60k chars of its session+ └ PublicationHandoff: one-use loopback page on 127.0.0.1 (random token, 5 min expiry)+ └ the browser auto-POSTs the draft to harness.autonomous.ai/hub/import+ └ Next stores it in IndexedDB, redirects to /hub/publish?draft=…+ └ the person reviews, ticks the MIT confirmation, presses Publish+ └ POST /api/community/harnesses (Next proxy) → Fastify → MongoDB+```++## What is already right++- Nothing publishes itself. A draft stays in the browser until the person presses Publish.+- The loopback handoff is tight: random token, `Host` check, one use, `form-action` limited by CSP,+ 5-minute expiry.+- The API validates with Zod in depth: relative paths, reserved names, cover magic bytes,+ file-vs-directory clashes, an included HTML viewer, idempotent `clientId`, rate limits on publish+ and comment.+- Published HTML runs in a sandbox without `allow-same-origin`, under a CSP with+ `connect-src 'none'`. Comments render as text. `/hub/import` uses a nonce CSP and escapes its payload.+- Likes and follows change only after the server answers.++## Findings++Severity is the reviewer's judgement: **High** breaks a main path or degrades with growth,+**Medium** is wrong in a real case, **Low** is polish.++### High++**H1. The feed carries every cover inline.** `GET /api/community/harnesses` selects `cover`, a data+URL of up to 350 KB (`community.ts:83`). One page of 30 posts can be ~10 MB of JSON, which the Next+proxy buffers whole with `response.json()` under a 12 s timeout. The feed gets slower with every+post that has a cover.+*Fix:* return a cover URL in the feed, and serve the image from its own cacheable route.++**H2. The detail page re-downloads the whole project on every focus.** `GET /harnesses/:id` returns+`files` (up to 6 MB) and the conversation with the social state (`community.ts:109`), and+`Detail.tsx:32` calls it on every window `focus`. Only `social` needs refreshing.+*Fix:* a social-only endpoint for refreshes. Render the harness itself on the server (see M1).++**H3. Publish to Hub fails on most real projects** (`publish_project.dart:96`):+- The 31st eligible file throws instead of being skipped. `.json`, `.md` and `.ts` all count, so an+ ordinary Vite or Next project is over 30 files.+- One file over 3 MB (a large PNG asset, a data CSV) fails the whole publication.+- `dist/` is skipped, so the source `index.html` is picked as the viewer. That file is not+ self-contained and previews blank.++*Fix:* choose the viewer first, then add files by priority until the limits, skipping (and listing)+what does not fit.++**H4. Remote machines cannot publish.** For an agent on another machine, or from the web build,+Publish to Hub opens an empty `/hub/publish` (`publish_native.dart:16`, `publish_web.dart`). The+dialog still says "Review your files and conversation in the Hub", as if a draft had been sent.+*Fix now:* say plainly that this machine's files cannot be read from here. *Later:* read the files+through the machine's CLI, the way `readSessionTail` already reads the session.++### Medium++**M1. Published harness pages have no server render or metadata.** `[id]/page.tsx` only loads+starters on the server. A user's harness renders "Loading harness…" with the title "Open harness"+and no description, so shared links have no preview. `getPublicHarness` in `server.ts` already does+the fetch.++**M2. Infinite scroll inserts posts above the starters** (`Feed.tsx:60`). The list is+`[...posts, ...starters]`. With more than 30 posts, reaching the starters loads the next page above+them and pushes them down.++**M3. A failed like breaks the feed** (`Feed.tsx:56`). It shares the feed's `error` state, so it+shows a Retry button that reloads the feed, and it stops infinite scroll (`Feed.tsx:43`).++**M4. Publishing can leak secrets.** Only dotfiles are skipped. `config.json`, `secrets.ts` or+`credentials.txt` are included, and the conversation can hold a token the agent printed. Nothing+scans for secrets, and the file list on the review page is a collapsed `<details>`.+*Fix:* scan for common secret patterns on the review page, name the files and turns, and require+them to be removed or acknowledged before Publish.++**M5. Long conversations lose their newest turns** (`publish_project.dart:146`). The tail is the end+of the session, but the loop keeps the first 80 turns of it. A session with many short turns drops+its last turns, usually the most relevant.++**M6. Search only filters what is loaded** (`Feed.tsx:60`). Posts on unloaded pages cannot be found.+A short filtered list keeps the load trigger in view, so it pages through everything one request+at a time.++**M7. A missing harness marker fails only at the last step.** The API requires a marker file per+`harnessId`, for example `scenes/hello.py` for Blender (`community.ts:52`). Neither the desktop nor+the web form checks it, so the person fills in everything before seeing "Include the harness project+source."++**M8. The detail comment count stops at 100.** The detail page shows the newest 100 comments+(`community.ts:105`) and counts them. The feed counts all of them, so the two numbers differ past 100.++**M9. Publish size limits are measured after base64.** On the web form (`publish/page.tsx:71`) and+on the desktop, a PNG of ~2.3 MB is refused with "under 6 MB". The real ceiling is ~4.2 MB of raw+data. The API's own limit is also base64, so the copy should say what is actually measured.++### Low++- **L1.** Non-UTF-8 text files (a Latin-1 `.csv`) make the desktop show a raw `FormatException`+ ("Unexpected extension byte").+- **L2.** Engines outside the four the Hub knows (for example Grok) are labelled Codex without a+ word.+- **L3.** Reply is shown to signed-out readers and does nothing (`Detail.tsx:63`).+- **L4.** The header renders "Sign in" first and then switches to "Yours" (`Header.tsx:10`).+- **L5.** `/hub/import` accepts a cross-site POST, so any site can open a prefilled publish draft.+ This is low risk, because the person must still confirm and press Publish, and it is open on+ purpose for the desktop handoff. It should be documented as such.+- **L6.** Rate limits count and then write, so parallel requests can exceed them. Likes and follows+ have no limit.++### Product risk++**P1. No report or moderation.** The feed publishes user-made HTML with no Report button and no way+for an admin to hide a post. A creator can delete comments on their own harness, and that is the+only control.++### Structure++**S1. The publication contract is copied by hand in about five places.** Nothing fails when the+copies drift:++| Rule | Copies |+|---|---|+| The nine harnesses | backend enum and marker map, `HarnessTags.tsx`, the publish `<select>`, desktop `communityHarnesses` |+| Categories, engines | backend enums, publish page |+| Extensions, reserved names, 30 files / 3 MB / 6 MB | backend, publish page, desktop |+| Starter ids | `communityAccess.ts`, `starters.ts` |++*Fix:* one shared contract module per language, plus a test that reads the backend's source the way+`desktop/test/e2ee/encrypted_down_types_test.dart` reads the CLI's.++**S2.** `Detail.tsx` and `publish/page.tsx` keep real logic in one-line inline handlers. The publish+page holds about 13 `useState`s. Split them into hooks (`useFeed`, `useHarnessSocial`,+`usePublishDraft`) and components (`CommentList`, `CommentForm`, `ConversationEditor`,+`FilesReview`).++## Plan++In order. Each step has its own tests.++1. **API payloads:** a cover route (H1) and a social-only endpoint (H2).+2. **Web:** server render and metadata for published harnesses (M1), feed order and like errors+ (M2, M3), size copy (M9), Reply and header polish (L3, L4).+3. **Desktop publish:** viewer-first file choice with skips listed (H3), honest remote and web+ messages (H4), newest turns kept (M5), non-UTF-8 and engine labels (L1, L2).+4. **Secret scan** on the review page (M4), and the marker checked before Publish (M7).+5. **Shared contract** and its drift test (S1), then the component split (S2).++Deferred (needs a product decision): report and moderation (P1), server-side search (M6), comment+pagination (M8), and remote-machine publishing through the CLI (H4, later part).++## Status++Steps 1–5 are done on `fix/hub-review`:++- **H1, H2:** the feed and the harness carry `/api/community/harnesses/:id/cover` instead of the image.+ The website serves it as a PNG, JPEG or WebP, cached for a day, so an unpublished cover can show+ for up to a day. A reader's page refreshes from `/social`.+- **M1, M2, M3, M9, L3, L4:** as planned. Server rendering asks as a production reader, so a+ staging publication still loads in the browser.+- **H3, H4 (now), M5, L1, L2:** the desktop picks the output, then the harness source, then the+ shallowest files that fit, and names the rest on the review page. A missing harness source+ publishes as a general harness, with a note.+- **M4, M7:** the review page lists what looks like a credential and holds Publish until it is+ removed or acknowledged. This runs in the browser only, so the API does not enforce it. A missing+ harness source also holds Publish.+- **S1:** `backend/src/lib/communityContract.ts` is the source. The website (`contract.ts`) and the+ desktop (`hub_contract.dart`) copies are tested against it, starter ids included, and+ `scripts/ci-plan.py` runs both suites when it changes.+- **S2:** `Detail`, `Feed` and the publish page are split into hooks (`useHarnessDetail`, `useFeed`,+ `usePublishDraft`, `useSignedIn`) and small components.++- **The output stays required.** The Hub (#890) publishes what a session made: the output at 70%+ beside its conversation, forking into the same viewer and agent workspace. A code review that made+ nothing to look at was given an app's `index.html` that showed blank and could not be removed.+ Instead of making the output optional (tried, then reverted), the desktop and the folder picker+ now choose only `preview.html`, or the page a fork was published with. Without one, the desktop+ asks for a preview.html that runs on its own (for a review, a page presenting it). The review page+ asks for one too, and names files or addresses an output loads that the sandbox cannot reach.+- **A fork's unchanged output is refused.** A featured starter's `preview.html` is only its poster:+ the real result (a Typst PDF, a Blender model) lives in the harness's own viewer. Republishing a+ fork would have shown the original's picture. Now the desktop and the review page refuse an+ output identical to the one the fork arrived with, and ask for a page showing the current result.+- **A native result reaches the Hub as a picture of its viewer.** When a project has no page of its+ own, or a fork's page is unchanged, the desktop asks the machine's daemon for a frame of the+ harness's viewer (the existing `viewer_surface`, headless Chrome) and publishes it as `preview.html`+ and the cover. Checked on a Typst fork: the current PDF, about 65 KB. Without Chrome on that machine+ it falls back to asking for a page.++Checks: backend typecheck and the full suite (1153 tests), website `tsc`, the full suite (103) and+lint (no new findings), desktop `flutter analyze` and the community, fork and share tests (89), and+the CI planner tests. `next build` was not run locally.