Skip to content

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

2.9 KB
Raw Blame
import type { OpenHarness, SocialState } from './types';
import { gzipJson, gzipType } from './gzip';
import { accessTokenKey, refreshHubSession } from './session';

/** Read the existing Harness web session; the community does not mint a second identity. */
export function sessionHeaders(): Record<string, string> {
  try {
    const token = localStorage.getItem(accessTokenKey);
    const env = localStorage.getItem('harness.web.v1.auth_autonomous_env');
    return { ...(token ? { Authorization: `Bearer ${token}` } : {}), 'x-autonomous-env': env === 'stag' ? 'stag' : 'prod' };
  } catch { return {}; }
}

const unavailable = 'The community is temporarily unavailable. Try again.';

export class CommunityError extends Error {
  constructor(message: string, public status: number) { super(message); }
}

export async function communityRequest<T>(path: string, options: { method?: string; body?: unknown; signal?: AbortSignal } = {}): Promise<T> {
  const headers = sessionHeaders();
  const request: RequestInit = {
    method: options.method || 'GET', signal: options.signal,
    headers: { ...headers, ...(options.body ? { 'Content-Type': gzipType } : {}) },
    ...(options.body ? { body: await gzipJson(options.body) } : {}), cache: 'no-store',
  };
  let response = await fetch(`/api/community/${path}`, request);
  if (response.status === 401 && headers.Authorization && await refreshHubSession(headers.Authorization)) {
    Object.assign(headers, sessionHeaders());
    response = await fetch(`/api/community/${path}`, { ...request, headers: { ...request.headers, ...headers } });
  }
  // An expired workspace sign-in must not hide public projects. Private following
  // views and all writes still require an authenticated request.
  if (response.status === 401 && request.method === 'GET' && headers.Authorization && path.startsWith('harnesses') && !new URLSearchParams(path.split('?')[1]).has('following') && !new URLSearchParams(path.split('?')[1]).has('mine')) {
    delete headers.Authorization;
    response = await fetch(`/api/community/${path}`, { ...request, headers });
  }
  // A proxy's error page is HTML: the reader gets the plain sentence, never a JSON parser's.
  const body: { success?: boolean; data?: T; error?: { message?: string } } | null = await response.json().catch(() => null);
  if (!response.ok || !body?.success) throw new CommunityError(body?.error?.message || unavailable, response.status);
  return body.data as T;
}

/** A starter's whole project, which this site serves itself (the Hub stores only publications). */
export async function starterSnapshot(id: string): Promise<OpenHarness | null> {
  const response = await fetch(`/hub/${id}/snapshot`, { cache: 'no-store' });
  if (!response.ok) return null;
  return (await response.json() as { harness: OpenHarness }).harness;
}

export const emptySocial: SocialState = { likes: 0, liked: false, following: false, comments: [], signedIn: false, mine: false };