Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: buildathon countdown and tracks

Samrat Talukdar15fb16149c00
diff --git a/apps/app/src/app/lib/buildathon.ts b/apps/app/src/app/lib/buildathon.ts
new file mode 100644
index 00000000..e9a81d51
--- /dev/null
+++ b/apps/app/src/app/lib/buildathon.ts
@@ -0,0 +1,384 @@
+// Buildathon, renderer side. The Electron main process reads
+// GET /me/buildathon (apps/desktop/electron/buildathon.mjs) and answers null
+// for anyone not enrolled, offline or on any error; everything here then
+// renders nothing. Nothing in this file is awaited on the way to the first
+// screen.
+
+import { create } from "zustand";
+
+import type {
+ OmniRushBuildathonEvent,
+ OmniRushBuildathonSession,
+ OmniRushBuildathonStatus,
+ OmniRushBuildathonTagResult,
+ OmniRushBuildathonTrack,
+} from "@omnirush/types/desktop-ipc";
+
+export type BuildathonStatus = OmniRushBuildathonStatus;
+export type BuildathonEvent = OmniRushBuildathonEvent;
+export type BuildathonSession = OmniRushBuildathonSession;
+export type BuildathonTrack = OmniRushBuildathonTrack;
+
+export const BUILDATHON_REFRESH_MS = 10 * 60_000;
+export const ONLY_TOOL_RULE = "OmniRush must be the only generative AI tool you use.";
+export const BUILDATHON_TRACKS_STORAGE_KEY = "omnirush.buildathon.tracks.v1";
+export const BUILDATHON_TAGGED_STORAGE_KEY = "omnirush.buildathon.tagged.v1";
+export const BUILDATHON_REMINDERS_STORAGE_KEY = "omnirush.buildathon.reminders.v1";
+const MAX_TAGGED_REMEMBERED = 500;
+const HOUR_MS = 3_600_000;
+
+// --- Countdown --------------------------------------------------------------
+
+export type BuildathonCountdown =
+ | { kind: "upcoming"; remainingMs: number; urgent: false }
+ | { kind: "open"; remainingMs: number; urgent: boolean }
+ | { kind: "closed"; remainingMs: 0; urgent: false };
+
+const pad = (value: number) => String(value).padStart(2, "0");
+
+/** "5d 03h", "4h 07m", "42m 09s" (never negative). */
+export function formatRemaining(ms: number): string {
+ const total = Math.max(0, Math.floor(ms / 1000));
+ const days = Math.floor(total / 86_400);
+ const hours = Math.floor((total % 86_400) / 3_600);
+ const minutes = Math.floor((total % 3_600) / 60);
+ const seconds = total % 60;
+ if (days > 0) return `${days}d ${pad(hours)}h`;
+ if (hours > 0) return `${hours}h ${pad(minutes)}m`;
+ return `${minutes}m ${pad(seconds)}s`;
+}
+
+/** Milliseconds to add to the local clock to read the server's (0 without a server time). */
+export function clockOffsetMs(serverTime: string | null | undefined, receivedAtMs: number): number {
+ const server = serverTime ? Date.parse(serverTime) : Number.NaN;
+ return Number.isFinite(server) ? server - receivedAtMs : 0;
+}
+
+/** Where the event stands at `nowMs` (server clock). */
+export function buildathonCountdown(event: BuildathonEvent, nowMs: number): BuildathonCountdown {
+ const deadline = Date.parse(event.deadlineAt);
+ if (event.phase === "judging" || event.phase === "results" || event.phase === "closed" || !(deadline > nowMs)) {
+ return { kind: "closed", remainingMs: 0, urgent: false };
+ }
+ const starts = event.startsAt ? Date.parse(event.startsAt) : Number.NaN;
+ if (Number.isFinite(starts) && starts > nowMs) {
+ return { kind: "upcoming", remainingMs: starts - nowMs, urgent: false };
+ }
+ const remainingMs = deadline - nowMs;
+ return { kind: "open", remainingMs, urgent: remainingMs < HOUR_MS };
+}
+
+/** The chip's words: "Buildathon · 5d 03h left". */
+export function buildathonChipText(countdown: BuildathonCountdown): string {
+ if (countdown.kind === "closed") return "Buildathon · Submissions closed";
+ if (countdown.kind === "upcoming") return `Buildathon · starts in ${formatRemaining(countdown.remainingMs)}`;
+ return `Buildathon · ${formatRemaining(countdown.remainingMs)} left`;
+}
+
+/** "20 Oct, 23:59 IST", plus the local time when the machine is not on IST. */
+export function formatEventTime(iso: string | null | undefined, locale?: string): string {
+ if (!iso) return "";
+ const date = new Date(iso);
+ if (!Number.isFinite(date.getTime())) return "";
+ const options: Intl.DateTimeFormatOptions = { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" };
+ const ist = new Intl.DateTimeFormat(locale ?? "en-GB", { ...options, timeZone: "Asia/Kolkata" }).format(date);
+ let localZone = "";
+ try {
+ localZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? "";
+ } catch {
+ localZone = "";
+ }
+ if (localZone === "Asia/Kolkata" || localZone === "Asia/Calcutta") return `${ist} IST`;
+ const local = new Intl.DateTimeFormat(locale ?? "en-GB", { ...options, timeZoneName: "short" }).format(date);
+ return `${ist} IST · ${local} your time`;
+}
+
+export function compactTokens(value: number): string {
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value % 1_000_000 === 0 ? 0 : 1)}M`;
+ if (value >= 1_000) return `${Math.round(value / 1_000)}k`;
+ return String(Math.max(0, Math.floor(value)));
+}
+
+/** The event's rules with the only-tool rule first (the server's wording when it has one). */
+export function rulesWithToolRuleFirst(rules: string[]): string[] {
+ const index = rules.findIndex((rule) => /only generative/i.test(rule));
+ if (index < 0) return [ONLY_TOOL_RULE, ...rules];
+ return [rules[index]!, ...rules.filter((_, at) => at !== index)];
+}
+
+// --- Reminders: each once --------------------------------------------------
+
+export function reminderKey(eventId: string, beforeSeconds: number): string {
+ return `${eventId}:${beforeSeconds}`;
+}
+
+/**
+ * The reminder due now, once: the tightest one whose window has opened.
+ * Every wider one is marked too, so opening the app with 10 minutes left
+ * shows only the 15-minute text.
+ */
+export function reminderToShow(
+ event: BuildathonEvent,
+ countdown: BuildathonCountdown,
+ shown: ReadonlySet<string>,
+): { text: string; keys: string[] } | null {
+ if (countdown.kind !== "open") return null;
+ const remainingSeconds = countdown.remainingMs / 1000;
+ const due = event.reminders.filter((reminder) => remainingSeconds <= reminder.beforeSeconds);
+ if (!due.length) return null;
+ const keys = due.map((reminder) => reminderKey(event.id, reminder.beforeSeconds));
+ const tightest = due.reduce((best, reminder) => (reminder.beforeSeconds < best.beforeSeconds ? reminder : best));
+ if (shown.has(reminderKey(event.id, tightest.beforeSeconds))) return null;
+ return { text: tightest.text, keys };
+}
+
+// --- Local storage ---------------------------------------------------------
+
+type KeyValueStore = Pick<Storage, "getItem" | "setItem">;
+
+function defaultStorage(): KeyValueStore | null {
+ try {
+ return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
+ } catch {
+ return null;
+ }
+}
+
+function readJson<T>(key: string, fallback: T, storage: KeyValueStore | null): T {
+ try {
+ const raw = storage?.getItem(key);
+ if (!raw) return fallback;
+ const parsed = JSON.parse(raw) as unknown;
+ return parsed && typeof parsed === "object" ? (parsed as T) : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+function writeJson(key: string, value: unknown, storage: KeyValueStore | null): void {
+ try {
+ storage?.setItem(key, JSON.stringify(value));
+ } catch {
+ // Full or blocked storage: the worst case is asking or tagging once more.
+ }
+}
+
+/** The key a project folder is stored under: trimmed, without trailing separators. */
+export function projectKey(path: string | null | undefined): string | null {
+ const trimmed = (path ?? "").trim().replace(/[\\/]+$/, "");
+ return trimmed || null;
+}
+
+export function readProjectTracks(storage: KeyValueStore | null = defaultStorage()): Record<string, string> {
+ const value = readJson<Record<string, unknown>>(BUILDATHON_TRACKS_STORAGE_KEY, {}, storage);
+ const tracks: Record<string, string> = {};
+ for (const [path, track] of Object.entries(value)) {
+ if (typeof track === "string" && track) tracks[path] = track;
+ }
+ return tracks;
+}
+
+export function readProjectTrack(path: string | null | undefined, storage: KeyValueStore | null = defaultStorage()): string | null {
+ const key = projectKey(path);
+ return key ? readProjectTracks(storage)[key] ?? null : null;
+}
+
+/** Saves (or, with null, clears) a folder's track. */
+export function writeProjectTrack(path: string | null | undefined, track: string | null, storage: KeyValueStore | null = defaultStorage()): void {
+ const key = projectKey(path);
+ if (!key) return;
+ const tracks = readProjectTracks(storage);
+ if (track) tracks[key] = track;
+ else delete tracks[key];
+ writeJson(BUILDATHON_TRACKS_STORAGE_KEY, tracks, storage);
+}
+
+export function readTaggedSessions(storage: KeyValueStore | null = defaultStorage()): Record<string, string> {
+ return readJson<Record<string, string>>(BUILDATHON_TAGGED_STORAGE_KEY, {}, storage);
+}
+
+export function rememberTaggedSession(sessionId: string, track: string, storage: KeyValueStore | null = defaultStorage()): void {
+ const tagged = readTaggedSessions(storage);
+ delete tagged[sessionId];
+ tagged[sessionId] = track;
+ const ids = Object.keys(tagged);
+ for (const id of ids.slice(0, Math.max(0, ids.length - MAX_TAGGED_REMEMBERED))) delete tagged[id];
+ writeJson(BUILDATHON_TAGGED_STORAGE_KEY, tagged, storage);
+}
+
+export function readShownReminders(storage: KeyValueStore | null = defaultStorage()): Set<string> {
+ const value = readJson<unknown>(BUILDATHON_REMINDERS_STORAGE_KEY, [], storage);
+ return new Set(Array.isArray(value) ? value.filter((key): key is string => typeof key === "string") : []);
+}
+
+export function rememberShownReminders(keys: string[], storage: KeyValueStore | null = defaultStorage()): void {
+ const shown = readShownReminders(storage);
+ for (const key of keys) shown.add(key);
+ writeJson(BUILDATHON_REMINDERS_STORAGE_KEY, [...shown].slice(-50), storage);
+}
+
+// --- Which sessions to tag ---------------------------------------------------
+
+export type BuildathonProject = {
+ id: string;
+ path: string;
+ name: string;
+ local: boolean;
+ sessions: Array<{ id: string; created: number | null; parentId: string | null }>;
+};
+
+/**
+ * Root sessions of a project with a track, started inside the event, whose
+ * track the server has not been told yet (or was told a different one).
+ */
+export function sessionsToTag(
+ projects: BuildathonProject[],
+ event: BuildathonEvent,
+ tracks: Record<string, string>,
+ tagged: Record<string, string>,
+ limit = 20,
+): Array<{ sessionId: string; track: string; project: string | null }> {
+ const starts = event.startsAt ? Date.parse(event.startsAt) : Number.NEGATIVE_INFINITY;
+ const deadline = Date.parse(event.deadlineAt);
+ const known = new Set(event.tracks.map((track) => track.id));
+ const out: Array<{ sessionId: string; track: string; project: string | null }> = [];
+ for (const project of projects) {
+ if (!project.local) continue;
+ const key = projectKey(project.path);
+ const track = key ? tracks[key] : undefined;
+ if (!track || !known.has(track)) continue;
+ for (const session of project.sessions) {
+ if (session.parentId || tagged[session.id] === track) continue;
+ const created = session.created ?? Number.NaN;
+ if (!Number.isFinite(created) || created < starts || created > deadline) continue;
+ out.push({ sessionId: session.id, track, project: key!.split(/[\\/]/).pop() || null });
+ if (out.length >= limit) return out;
+ }
+ }
+ return out;
+}
+
+// --- Store -------------------------------------------------------------------
+
+type BuildathonStore = {
+ status: BuildathonStatus | null;
+ /** Server clock minus local clock, from the latest answer. */
+ offsetMs: number;
+ panelOpen: boolean;
+ projects: BuildathonProject[];
+ /** Projects created in this run, waiting for the one-time track question. */
+ newProjects: Array<{ path: string; name: string }>;
+ /** Bumped on every track change so pickers re-read storage. */
+ tracksVersion: number;
+ setStatus: (status: BuildathonStatus | null, receivedAtMs?: number) => void;
+ openPanel: () => void;
+ closePanel: () => void;
+ setProjects: (projects: BuildathonProject[]) => void;
+ noteNewProject: (project: { path: string; name: string }) => void;
+ dropNewProject: (path: string) => void;
+ bumpTracks: () => void;
+};
+
+export const useBuildathonStore = create<BuildathonStore>((set) => ({
+ status: null,
+ offsetMs: 0,
+ panelOpen: false,
+ projects: [],
+ newProjects: [],
+ tracksVersion: 0,
+ setStatus: (status, receivedAtMs = Date.now()) =>
+ set((state) => ({
+ status,
+ offsetMs: status ? clockOffsetMs(status.serverTime, receivedAtMs) : 0,
+ panelOpen: status ? state.panelOpen : false,
+ })),
+ openPanel: () => set({ panelOpen: true }),
+ closePanel: () => set({ panelOpen: false }),
+ setProjects: (projects) => set({ projects }),
+ noteNewProject: (project) =>
+ set((state) => {
+ const key = projectKey(project.path);
+ if (!key || state.newProjects.some((entry) => projectKey(entry.path) === key)) return state;
+ return { newProjects: [...state.newProjects, { path: key, name: project.name }] };
+ }),
+ dropNewProject: (path) =>
+ set((state) => ({ newProjects: state.newProjects.filter((entry) => entry.path !== projectKey(path)) })),
+ bumpTracks: () => set((state) => ({ tracksVersion: state.tracksVersion + 1 })),
+}));
+
+/** A project folder was just created (desktop); the event layer may ask for its track once. */
+export function noteNewBuildathonProject(path: string | null | undefined, name?: string | null): void {
+ const key = projectKey(path);
+ if (!key) return;
+ useBuildathonStore.getState().noteNewProject({ path: key, name: name?.trim() || key.split(/[\\/]/).pop() || key });
+}
+
+let refreshing: Promise<void> | null = null;
+
+/** One read of the event; any failure hides everything. Never throws. */
+export function refreshBuildathon(read: () => Promise<BuildathonStatus | null>): Promise<void> {
+ if (refreshing) return refreshing;
+ refreshing = (async () => {
+ try {
+ const status = await read();
+ useBuildathonStore.getState().setStatus(status?.enrolled === true ? status : null);
+ } catch {
+ useBuildathonStore.getState().setStatus(null);
+ } finally {
+ refreshing = null;
+ }
+ })();
+ return refreshing;
+}
+
+/** Saves a folder's track and tells the server about its event sessions on the next pass. */
+export function setProjectTrack(path: string | null | undefined, track: string | null): void {
+ writeProjectTrack(path, track);
+ useBuildathonStore.getState().bumpTracks();
+}
+
+/**
+ * Tells the server the track of every session that needs it, one at a time
+ * and fire-and-forget: a refusal is final, a failure is tried on a later pass.
+ */
+export async function tagSessions(
+ pending: Array<{ sessionId: string; track: string; project?: string | null }>,
+ tag: (input: { sessionId: string; track: string; project?: string | null }) => Promise<OmniRushBuildathonTagResult>,
+): Promise<void> {
+ for (const entry of pending) {
+ let result: OmniRushBuildathonTagResult = "retry";
+ try {
+ result = await tag(entry);
+ } catch {
+ result = "retry";
+ }
+ if (result !== "retry") rememberTaggedSession(entry.sessionId, entry.track);
+ }
+}
+
+export function sessionStatusLabel(status: BuildathonSession["status"]): string {
+ if (status === "good") return "Counts";
+ if (status === "incomplete") return "Incomplete";
+ return "Pending";
+}
+
+
+type SessionGroupLike = {
+ workspace: { id: string; path: string; name?: string | null; displayName?: string | null; workspaceType?: string | null };
+ sessions: Array<{ id: string; parentID?: string | null; time?: { created?: number | null } | null }>;
+};
+
+/** The sidebar's groups as the layer needs them (local folders, root sessions, start times). */
+export function buildathonProjects(groups: SessionGroupLike[]): BuildathonProject[] {
+ return groups.map((group) => ({
+ id: group.workspace.id,
+ path: group.workspace.path,
+ name: group.workspace.displayName?.trim() || group.workspace.name?.trim() || group.workspace.path,
+ local: group.workspace.workspaceType === "local",
+ sessions: group.sessions.map((session) => ({
+ id: session.id,
+ created: typeof session.time?.created === "number" ? session.time.created : null,
+ parentId: session.parentID ?? null,
+ })),
+ }));
+}
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index 4f4f3b84..fd0072d9 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -786,6 +786,10 @@ const {
keepAwakeSet,
omnirushSessionStatus,
omnirushQualitySpin,
+ omnirushBuildathon,
+ omnirushBuildathonSessions,
+ omnirushBuildathonLink,
+ omnirushBuildathonTagSession,
omnirushAccountConnect,
omnirushAccountSignOut,
omnirushServerRestart,
@@ -852,6 +856,10 @@ export {
keepAwakeSet,
omnirushSessionStatus,
omnirushQualitySpin,
+ omnirushBuildathon,
+ omnirushBuildathonSessions,
+ omnirushBuildathonLink,
+ omnirushBuildathonTagSession,
omnirushAccountConnect,
omnirushAccountSignOut,
omnirushServerRestart,
diff --git a/apps/app/src/react-app/domains/buildathon/buildathon.tsx b/apps/app/src/react-app/domains/buildathon/buildathon.tsx
new file mode 100644
index 00000000..f1474d82
--- /dev/null
+++ b/apps/app/src/react-app/domains/buildathon/buildathon.tsx
@@ -0,0 +1,447 @@
+/** @jsxImportSource react */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { Copy, ExternalLink, Trophy, X } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { toast } from "@/components/ui/sonner";
+import { cn } from "@/lib/utils";
+
+import {
+ desktopNotificationShow,
+ omnirushBuildathon,
+ omnirushBuildathonLink,
+ omnirushBuildathonSessions,
+ omnirushBuildathonTagSession,
+ openDesktopUrl,
+} from "../../../app/lib/desktop";
+import {
+ BUILDATHON_REFRESH_MS,
+ buildathonChipText,
+ buildathonCountdown,
+ compactTokens,
+ formatEventTime,
+ formatRemaining,
+ readProjectTrack,
+ readProjectTracks,
+ readShownReminders,
+ readTaggedSessions,
+ refreshBuildathon,
+ reminderToShow,
+ rememberShownReminders,
+ rulesWithToolRuleFirst,
+ sessionStatusLabel,
+ sessionsToTag,
+ setProjectTrack,
+ tagSessions,
+ useBuildathonStore,
+ type BuildathonCountdown,
+ type BuildathonSession,
+ type BuildathonStatus,
+ type BuildathonTrack,
+} from "../../../app/lib/buildathon";
+
+const readStatus = () => omnirushBuildathon();
+
+/** The server clock, re-read every `intervalMs`. */
+function useServerNow(intervalMs: number): number {
+ const offsetMs = useBuildathonStore((store) => store.offsetMs);
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
+ return () => window.clearInterval(timer);
+ }, [intervalMs]);
+ return now + offsetMs;
+}
+
+function useCountdown(status: BuildathonStatus | null): BuildathonCountdown | null {
+ const now = useServerNow(1_000);
+ return status ? buildathonCountdown(status.event, now) : null;
+}
+
+/** Header chip: "Buildathon · 5d 03h left", red in the last hour. Nothing unless enrolled. */
+export function BuildathonChip() {
+ const status = useBuildathonStore((store) => store.status);
+ const countdown = useCountdown(status);
+ if (!status || !countdown) return null;
+ return (
+ <button
+ type="button"
+ onClick={() => useBuildathonStore.getState().openPanel()}
+ className={cn(
+ "inline-flex h-6 shrink-0 items-center gap-1.5 rounded-lg border px-2 text-[11.5px] font-medium tabular-nums transition-colors mac:titlebar-no-drag",
+ countdown.urgent
+ ? "border-red-500/50 bg-red-500/10 text-red-600 hover:bg-red-500/15 dark:text-red-400"
+ : countdown.kind === "closed"
+ ? "border-border bg-muted/40 text-muted-foreground hover:bg-muted"
+ : "border-[#b9f45a]/50 bg-[#b9f45a]/10 text-foreground hover:bg-[#b9f45a]/20",
+ )}
+ title={`${status.event.name}: deadline ${formatEventTime(status.event.deadlineAt)}`}
+ data-testid="buildathon-chip"
+ data-urgent={countdown.urgent ? "true" : undefined}
+ >
+ <Trophy className="size-3.5" />
+ <span>{buildathonChipText(countdown)}</span>
+ </button>
+ );
+}
+
+function trackOptions(status: BuildathonStatus): BuildathonTrack[] {
+ return status.event.tracks;
+}
+
+/** A plain select of the event's tracks; "" is no track. */
+function TrackSelect(props: { tracks: BuildathonTrack[]; value: string | null; onChange: (track: string | null) => void; testId?: string }) {
+ return (
+ <select
+ value={props.value ?? ""}
+ onChange={(event) => props.onChange(event.target.value || null)}
+ className="h-8 w-full rounded-lg border border-dls-border bg-dls-surface px-2 text-[12px] text-dls-text"
+ data-testid={props.testId}
+ aria-label="Buildathon track"
+ >
+ <option value="">Not part of the buildathon</option>
+ {props.tracks.map((track) => (
+ <option key={track.id} value={track.id}>{track.label}</option>
+ ))}
+ </select>
+ );
+}
+
+/** Project settings: the folder's track. Nothing unless enrolled. */
+export function BuildathonTrackCard(props: { projectPath: string | null | undefined; projectName?: string | null }) {
+ const status = useBuildathonStore((store) => store.status);
+ const tracksVersion = useBuildathonStore((store) => store.tracksVersion);
+ const track = useMemo(() => readProjectTrack(props.projectPath), [props.projectPath, tracksVersion]);
+ if (!status || !props.projectPath) return null;
+ return (
+ <div className="space-y-3">
+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">Buildathon</div>
+ <div className="flex items-center gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4" data-testid="buildathon-track-card">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">
+ <Trophy size={17} className="text-dls-secondary" />
+ </div>
+ <div className="min-w-0 flex-1 space-y-2">
+ <div>
+ <div className="text-[13px] font-medium text-dls-text">Track for {props.projectName || "this project"}</div>
+ <div className="text-[11px] text-dls-secondary">
+ Chats you start in this project during {status.event.name} are filed under this track.
+ </div>
+ </div>
+ <TrackSelect
+ tracks={trackOptions(status)}
+ value={track}
+ onChange={(next) => setProjectTrack(props.projectPath, next)}
+ testId="buildathon-track-select"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function NewProjectPrompt(props: { status: BuildathonStatus; project: { path: string; name: string }; onDone: () => void }) {
+ const [track, setTrack] = useState<string | null>(null);
+ return (
+ <div
+ className="fixed bottom-4 right-4 z-40 w-80 space-y-3 rounded-2xl border border-border bg-popover p-4 text-sm text-popover-foreground shadow-xl"
+ role="dialog"
+ aria-label="Buildathon track for this project"
+ data-testid="buildathon-new-project-prompt"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div>
+ <div className="flex items-center gap-1.5 font-medium"><Trophy className="size-3.5" /> Building for the buildathon?</div>
+ <div className="mt-0.5 text-xs text-muted-foreground">Pick a track for “{props.project.name}”. You can change it later in Settings.</div>
+ </div>
+ <Button variant="ghost" size="icon-xs" aria-label="Not now" onClick={props.onDone}><X /></Button>
+ </div>
+ <TrackSelect tracks={trackOptions(props.status)} value={track} onChange={setTrack} testId="buildathon-prompt-select" />
+ <div className="flex justify-end gap-2">
+ <Button variant="ghost" size="xs" onClick={props.onDone}>Not now</Button>
+ <Button
+ size="xs"
+ disabled={!track}
+ onClick={() => {
+ setProjectTrack(props.project.path, track);
+ props.onDone();
+ }}
+ >
+ Save track
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+async function copyText(value: string) {
+ try {
+ await navigator.clipboard.writeText(value);
+ toast.success("Copied");
+ } catch {
+ toast.error("Could not copy", { description: <span className="select-all font-mono">{value}</span>, duration: Infinity });
+ }
+}
+
+const SESSION_TONE: Record<BuildathonSession["status"], string> = {
+ good: "bg-[#b9f45a]/20 text-foreground",
+ pending: "bg-muted text-muted-foreground",
+ incomplete: "bg-amber-500/15 text-amber-700 dark:text-amber-400",
+};
+
+function SessionsList(props: { sessions: BuildathonSession[] | null | undefined; tracks: BuildathonTrack[] }) {
+ if (props.sessions === undefined) return <div className="text-xs text-muted-foreground">Loading…</div>;
+ if (props.sessions === null) return <div className="text-xs text-muted-foreground">Your sessions could not be loaded right now.</div>;
+ if (!props.sessions.length) return <div className="text-xs text-muted-foreground">No sessions yet. Chats you start during the event show up here.</div>;
+ const label = (id: string | null) => props.tracks.find((track) => track.id === id)?.label ?? null;
+ return (
+ <ul className="flex flex-col gap-1.5" data-testid="buildathon-sessions">
+ {props.sessions.map((session) => (
+ <li key={session.sessionId} className="rounded-lg border border-border px-3 py-2">
+ <div className="flex items-center justify-between gap-2 text-xs">
+ <span className="truncate font-medium">{session.title ?? session.project ?? session.sessionId}</span>
+ <span className={cn("shrink-0 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium", SESSION_TONE[session.status])}>
+ {sessionStatusLabel(session.status)}
+ </span>
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-muted-foreground">
+ {[session.project, label(session.track), session.tokens ? `${compactTokens(session.tokens)} tokens` : null].filter(Boolean).join(" · ")}
+ </div>
+ {session.reasons.length ? (
+ <ul className="mt-1 list-disc ps-4 text-[11px] text-muted-foreground">
+ {session.reasons.map((reason) => <li key={reason}>{reason}</li>)}
+ </ul>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function LinkCodeForm() {
+ const [code, setCode] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
+ const submit = async () => {
+ setBusy(true);
+ setMessage(null);
+ try {
+ const result = await omnirushBuildathonLink({ code });
+ if (result.ok) {
+ useBuildathonStore.getState().setStatus(result.status);
+ setCode("");
+ setMessage({ ok: true, text: "Code linked." });
+ } else {
+ setMessage({ ok: false, text: result.error });
+ }
+ } catch {
+ setMessage({ ok: false, text: "The code could not be checked. Try again in a moment." });
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <div className="space-y-1.5" data-testid="buildathon-link">
+ <div className="text-xs text-muted-foreground">Registered with a different email? Enter the code from your registration email.</div>
+ <form
+ className="flex gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (code.trim() && !busy) void submit();
+ }}
+ >
+ <input
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ placeholder="FB-XXXX-XX"
+ className="h-8 min-w-0 flex-1 rounded-lg border border-border bg-background px-2 font-mono text-xs uppercase"
+ aria-label="Link code"
+ data-testid="buildathon-link-input"
+ />
+ <Button type="submit" size="sm" variant="outline" disabled={busy || !code.trim()}>{busy ? "Linking…" : "Link"}</Button>
+ </form>
+ {message ? <div className={cn("text-xs", message.ok ? "text-foreground" : "text-red-600 dark:text-red-400")}>{message.text}</div> : null}
+ </div>
+ );
+}
+
+function Section(props: { title: string; children: React.ReactNode; testId?: string }) {
+ return (
+ <section className="space-y-2" data-testid={props.testId}>
+ <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">{props.title}</div>
+ {props.children}
+ </section>
+ );
+}
+
+/** "My Buildathon": countdown, tokens, rules, sessions, submission, link code. */
+export function BuildathonPanel(props: { status: BuildathonStatus; onClose: () => void }) {
+ const { event, participant, submission } = props.status;
+ const countdown = useCountdown(props.status)!;
+ const [sessions, setSessions] = useState<BuildathonSession[] | null | undefined>(undefined);
+
+ useEffect(() => {
+ let live = true;
+ void omnirushBuildathonSessions().catch(() => null).then((list) => {
+ if (live) setSessions(list ?? null);
+ });
+ return () => {
+ live = false;
+ };
+ }, []);
+
+ const granted = participant?.tokensGranted ?? 0;
+ const left = participant?.tokensLeft ?? 0;
+ const percent = granted > 0 ? Math.min(100, Math.max(0, (left / granted) * 100)) : 0;
+ const rules = rulesWithToolRuleFirst(event.rules);
+ const submitUrl = event.submitUrl;
+ const trackLabel = event.tracks.find((track) => track.id === submission?.track)?.label ?? submission?.track ?? null;
+
+ return (
+ <Dialog open onOpenChange={(open) => { if (!open) props.onClose(); }}>
+ <DialogContent className="gap-5 lg:max-w-lg" data-testid="buildathon-panel">
+ <div>
+ <DialogTitle className="flex items-center gap-2 text-base"><Trophy className="size-4" /> My Buildathon</DialogTitle>
+ <DialogDescription className="text-xs">{event.name}</DialogDescription>
+ </div>
+
+ <div className="grid max-h-[65vh] gap-5 overflow-y-auto pe-1">
+ <div className="grid grid-cols-2 gap-2">
+ <div className={cn("rounded-xl border p-3", countdown.urgent ? "border-red-500/50 bg-red-500/5" : "border-border")} data-testid="buildathon-countdown">
+ <div className="text-[11px] text-muted-foreground">
+ {countdown.kind === "closed" ? "Submissions" : countdown.kind === "upcoming" ? "Starts in" : "Time left"}
+ </div>
+ <div className={cn("text-lg font-semibold tabular-nums", countdown.urgent && "text-red-600 dark:text-red-400")}>
+ {countdown.kind === "closed" ? "Closed" : formatRemaining(countdown.remainingMs)}
+ </div>
+ <div className="text-[10.5px] text-muted-foreground">Deadline {formatEventTime(event.deadlineAt)}</div>
+ </div>
+ <div className="rounded-xl border border-border p-3" data-testid="buildathon-tokens">
+ <div className="text-[11px] text-muted-foreground">Event tokens left</div>
+ <div className="text-lg font-semibold tabular-nums">
+ {compactTokens(left)} <span className="text-xs font-normal text-muted-foreground">of {compactTokens(granted)}</span>
+ </div>
+ <div className="mt-1 h-1 overflow-hidden rounded-full bg-muted" aria-hidden="true">
+ <div className="h-full rounded-full bg-[#b9f45a]" style={{ width: `${percent}%` }} />
+ </div>
+ </div>
+ </div>
+
+ <Section title="Submission" testId="buildathon-submission">
+ {submission ? (
+ <div className="space-y-1.5 rounded-lg border border-border px-3 py-2 text-xs">
+ <div className="flex items-center justify-between gap-2">
+ <span className="truncate font-medium">{submission.title ?? "Your project"}</span>
+ <span className="shrink-0 text-muted-foreground">{submission.locked ? "Final" : "Submitted"}</span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">ID</span>
+ <code className="select-all rounded bg-muted px-1.5 py-0.5 font-mono" data-testid="buildathon-submission-id">{submission.submissionId}</code>
+ <Button variant="ghost" size="icon-xs" aria-label="Copy submission ID" onClick={() => void copyText(submission.submissionId)}><Copy /></Button>
+ </div>
+ {trackLabel ? <div className="text-muted-foreground">Track: {trackLabel}</div> : null}
+ {submission.checks.length ? (
+ <ul className="space-y-0.5">
+ {submission.checks.map((check) => (
+ <li key={check.id} className={check.ok ? "text-muted-foreground" : "text-amber-700 dark:text-amber-400"}>
+ {check.ok ? "✓" : "!"} {check.text || check.id}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ ) : (
+ <div className="text-xs text-muted-foreground">
+ {countdown.kind === "closed" ? "No submission was made." : "Not submitted yet. You need a public GitHub repo, README, demo video, live URL, a track and the sessions you built it in."}
+ </div>
+ )}
+ {submitUrl && countdown.kind !== "closed" && !submission?.locked ? (
+ <Button size="sm" onClick={() => void openDesktopUrl(submitUrl).catch(() => undefined)} data-testid="buildathon-submit">
+ {submission ? "Update submission" : "Submit"} <ExternalLink className="size-3.5" />
+ </Button>
+ ) : null}
+ </Section>
+
+ <Section title="Rules" testId="buildathon-rules">
+ <ul className="space-y-1 text-xs">
+ {rules.map((rule, index) => (
+ <li key={rule} className={cn("rounded-lg px-2.5 py-1.5", index === 0 ? "border border-[#b9f45a]/60 bg-[#b9f45a]/10 font-medium" : "text-muted-foreground")}>
+ {rule}
+ </li>
+ ))}
+ </ul>
+ {event.pageUrl ? (
+ <button type="button" className="inline-flex items-center gap-1 text-xs text-primary hover:underline" onClick={() => void openDesktopUrl(event.pageUrl!).catch(() => undefined)}>
+ Event page <ExternalLink className="size-3" />
+ </button>
+ ) : null}
+ </Section>
+
+ <Section title={`Your sessions${participant ? ` · ${participant.sessionsGood} of ${participant.sessionsTagged} count` : ""}`}>
+ <SessionsList sessions={sessions} tracks={event.tracks} />
+ </Section>
+
+ <Section title="Link code">
+ <LinkCodeForm />
+ </Section>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/**
+ * The event over the app (desktop): reads the event at start and every 10
+ * minutes without holding anything up, shows each server reminder once,
+ * files sessions under their project's track, asks once for a new project's
+ * track, and hosts the panel. Renders nothing unless enrolled.
+ */
+export function BuildathonLayer() {
+ const status = useBuildathonStore((store) => store.status);
+ const panelOpen = useBuildathonStore((store) => store.panelOpen);
+ const projects = useBuildathonStore((store) => store.projects);
+ const newProjects = useBuildathonStore((store) => store.newProjects);
+ const tracksVersion = useBuildathonStore((store) => store.tracksVersion);
+ const now = useServerNow(15_000);
+
+ useEffect(() => {
+ // Deferred so the first screen never waits on it.
+ const first = window.setTimeout(() => void refreshBuildathon(readStatus), 1_500);
+ const timer = window.setInterval(() => void refreshBuildathon(readStatus), BUILDATHON_REFRESH_MS);
+ return () => {
+ window.clearTimeout(first);
+ window.clearInterval(timer);
+ };
+ }, []);
+
+ // Reminders: the server's texts, each once.
+ useEffect(() => {
+ if (!status) return;
+ const due = reminderToShow(status.event, buildathonCountdown(status.event, now), readShownReminders());
+ if (!due) return;
+ rememberShownReminders(due.keys);
+ toast.info(status.event.name, { description: due.text, duration: 15_000 });
+ void desktopNotificationShow({ title: status.event.name, body: due.text }).catch(() => undefined);
+ }, [status, now]);
+
+ // Tell the server each event session's track (fire-and-forget).
+ useEffect(() => {
+ if (!status) return;
+ const pending = sessionsToTag(projects, status.event, readProjectTracks(), readTaggedSessions());
+ if (!pending.length) return;
+ void tagSessions(pending, (input) => omnirushBuildathonTagSession(input));
+ }, [status, projects, tracksVersion]);
+
+ const closePrompt = useCallback((path: string) => useBuildathonStore.getState().dropNewProject(path), []);
+ const prompt = status && status.event && buildathonCountdown(status.event, now).kind !== "closed"
+ ? newProjects.find((project) => !readProjectTrack(project.path)) ?? null
+ : null;
+
+ if (!status) return null;
+ return (
+ <>
+ {prompt ? <NewProjectPrompt key={prompt.path} status={status} project={prompt} onDone={() => closePrompt(prompt.path)} /> : null}
+ {panelOpen ? <BuildathonPanel status={status} onClose={() => useBuildathonStore.getState().closePanel()} /> : null}
+ </>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsx
index af5b427f..4a5124fd 100644
--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx
+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx
@@ -3,6 +3,7 @@ import type { CSSProperties } from "react";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { usePanelRef } from "react-resizable-panels";
import { DesktopUpdateButton } from "../../settings/state/desktop-updater-provider";
+import { BuildathonChip } from "../../buildathon/buildathon";
import { ArrowLeft, Cloud, FileText, Globe, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";
import { resolveExtensionIconSrc } from "@/react-app/design-system/extension-icon-src";
@@ -1578,6 +1579,7 @@ export function SessionPage(props: SessionPageProps) {
</div>
<div className="flex shrink-0 items-center gap-1.5 text-gray-10 mac:titlebar-no-drag">
+ <BuildathonChip />
<DesktopUpdateButton />
{!props.primarySlot && findButtonSessionId && !hasMainContentTakeover ? (
<Tooltip>
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index 403ceb20..71ccd484 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -44,6 +44,7 @@ import { isDesktopRuntime } from "../../../../app/lib/runtime-env";
import { refreshAccountStatus, setQualitySessionId, useAccountStatusStore, useQualityUiStore, type AccountQuality } from "../../../../app/lib/quality";
import { goodSessionWording } from "../../../../app/lib/good-session";
import { ProgressRing, QualityTierBadge, SpinCounts, spinRowTitle } from "../../quality/quality-parts";
+import { buildathonProjects, useBuildathonStore } from "../../../../app/lib/buildathon";
import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";
import { NotificationBell } from "../../../shell/notification-center";
import { useUiStateStore } from "../../../shell/ui-state-store";
@@ -1155,6 +1156,11 @@ export function AppSidebar(props: AppSidebarProps) {
setQualitySessionId(props.selectedSessionId ?? null);
}, [props.selectedSessionId]);
+ // The buildathon layer files event sessions under their project's track.
+ React.useEffect(() => {
+ useBuildathonStore.getState().setProjects(buildathonProjects(props.workspaceSessionGroups));
+ }, [props.workspaceSessionGroups]);
+
// Green unread dots: agent finished while the user was on another session.
React.useEffect(() => {
const statuses = props.sessionStatusById ?? {};
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index 32b22431..f9c05cd3 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -40,6 +40,7 @@ import { DiagnosticsSection } from "./diagnostics-section";
import { BEST_PRACTICES_HELP, useBestPractices, type BestPracticesClient } from "../best-practices";
import { useLinuxSandbox, type LinuxSandboxClient } from "../linux-sandbox";
import { LinuxSandboxCard } from "../linux-sandbox-card";
+import { BuildathonTrackCard } from "../../buildathon/buildathon";
export type GeneralSettingsViewProps = {
onNavigateTab: (tab: SettingsTab) => void;
@@ -53,6 +54,8 @@ export type GeneralSettingsViewProps = {
/** The Linux sandbox card (per project); hidden without a client or a selected workspace. */
linuxSandboxClient?: LinuxSandboxClient | null;
sandboxWorkspaceId?: string | null;
+ /** The selected local project, for its buildathon track (shown to enrolled accounts only). */
+ buildathonProject?: { path: string; name: string } | null;
/** Builds the sanitized diagnostics bundle with the route's context. */
buildDiagnosticsBundle?: () => Promise<string>;
};
@@ -454,6 +457,10 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
/>
) : null}
+ {props.buildathonProject ? (
+ <BuildathonTrackCard projectPath={props.buildathonProject.path} projectName={props.buildathonProject.name} />
+ ) : null}
+
{linuxSandboxClient && props.sandboxWorkspaceId ? (
<LinuxSandboxCard
box={linuxSandbox.box}
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index 00941973..d5b41989 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -49,6 +49,7 @@ import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-update
import { SyncRestartGate } from "./sync-restart-banner";
import { UpdateGate } from "./update-gate";
import { QualityRewards } from "../domains/quality/quality-notice";
+import { BuildathonLayer } from "../domains/buildathon/buildathon";
import { TurnRunningSync } from "../domains/quality/good-session";
import { SettingsRoute } from "./settings-route";
import { ShellConfigProvider } from "./shell-config";
@@ -517,6 +518,7 @@ export function AppRoot() {
<LoadingOverlay />
<CloudWorkspaceOverlay />
{isDesktopRuntime() ? <QualityRewards /> : null}
+ {isDesktopRuntime() ? <BuildathonLayer /> : null}
{isDesktopRuntime() ? <TurnRunningSync /> : null}
</CloudWorkspaceStatusProvider>
</OmniRushWebAccessGate>
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 09018c07..f4d6d623 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -14,6 +14,7 @@ import { closeWorkspaceTerminals } from "../domains/session/terminal/terminal-ru
import type { ProviderListResponse } from "@opencode-ai/sdk/v2/client";
import { captureAnalyticsEvent, markTaskRunStart } from "@/app/lib/analytics";
+import { noteNewBuildathonProject } from "@/app/lib/buildathon";
import { trackSessionActive, trackTaskStarted } from "@/app/lib/den-telemetry";
import { buildDiagnosticsBundleJson } from "@/app/lib/diagnostics-bundle";
import { downloadTextAsFile } from "@/app/lib/download";
@@ -3161,6 +3162,7 @@ export function SessionRoute() {
});
}
captureAnalyticsEvent("workspace_created", { workspace_type: "local" });
+ noteNewBuildathonProject(workspacePath, targetWorkspace?.displayName ?? targetWorkspace?.name ?? null);
if (session?.id) {
captureAnalyticsEvent("task_created", { source: "workspace_created", workspace_type: "local" });
if (firstTaskPrompt || firstTaskAttachments.length) {
diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsx
index bcfd1cb9..36f25a0e 100644
--- a/apps/app/src/react-app/shell/settings-route.tsx
+++ b/apps/app/src/react-app/shell/settings-route.tsx
@@ -2288,6 +2288,9 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
runtimeWorkspaceId={runtimeWorkspaceId}
linuxSandboxClient={omnirushClient}
sandboxWorkspaceId={selectedWorkspaceId || runtimeWorkspaceId}
+ buildathonProject={selectedWorkspace?.workspaceType === "local" && selectedWorkspace.path
+ ? { path: selectedWorkspace.path, name: selectedWorkspace.displayName?.trim() || selectedWorkspace.name || selectedWorkspace.path }
+ : null}
buildDiagnosticsBundle={() => buildDiagnosticsBundleJson({
developerMode,
omnirushServerStatus: routeOmniRushStatus,
diff --git a/apps/app/src/react-app/shell/welcome-route.tsx b/apps/app/src/react-app/shell/welcome-route.tsx
index c898f00a..dcc200c6 100644
--- a/apps/app/src/react-app/shell/welcome-route.tsx
+++ b/apps/app/src/react-app/shell/welcome-route.tsx
@@ -27,6 +27,7 @@ import { useDenControlPlaneConfigured } from "../domains/cloud/use-den-control-p
import { JoinOrganizationDialog } from "../domains/cloud/join-organization-dialog";
import { resolveOmniRushConnection } from "./omnirush-connection";
import { captureAnalyticsEvent } from "../../app/lib/analytics";
+import { noteNewBuildathonProject } from "../../app/lib/buildathon";
import { buildOmniRushWorkspaceBaseUrl, createOmniRushServerClient } from "../../app/lib/omnirush-server";
import { buildDenAuthUrl, DEFAULT_DEN_BASE_URL, readDenSettings } from "../../app/lib/den";
import { markDesktopSignInInitiated } from "../../app/lib/den-sign-in-intent";
@@ -239,6 +240,7 @@ export function WelcomeRoute() {
}
if (targetWorkspaceId) {
writeActiveWorkspaceId(targetWorkspaceId);
+ noteNewBuildathonProject(targetWorkspace?.path?.trim() || folder, targetWorkspace?.displayName ?? targetWorkspace?.name ?? null);
if (projectLabel) {
writeWorkspaceProjectDimension(targetWorkspaceId, {
label: projectLabel,
diff --git a/apps/app/tests/buildathon.test.ts b/apps/app/tests/buildathon.test.ts
new file mode 100644
index 00000000..7058c913
--- /dev/null
+++ b/apps/app/tests/buildathon.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ buildathonChipText,
+ buildathonCountdown,
+ buildathonProjects,
+ clockOffsetMs,
+ formatEventTime,
+ formatRemaining,
+ projectKey,
+ readProjectTrack,
+ readShownReminders,
+ readTaggedSessions,
+ refreshBuildathon,
+ rememberShownReminders,
+ rememberTaggedSession,
+ reminderToShow,
+ rulesWithToolRuleFirst,
+ sessionsToTag,
+ useBuildathonStore,
+ writeProjectTrack,
+ type BuildathonEvent,
+ type BuildathonStatus,
+} from "../src/app/lib/buildathon";
+
+function memoryStorage(initial: Record<string, string> = {}) {
+ const data = new Map(Object.entries(initial));
+ return {
+ getItem: (key: string) => data.get(key) ?? null,
+ setItem: (key: string, value: string) => void data.set(key, value),
+ };
+}
+
+const EVENT: BuildathonEvent = {
+ id: "frontier-2026",
+ name: "OmniRush Frontier Buildathon 2026",
+ startsAt: "2026-10-13T18:30:00Z",
+ registrationEndsAt: "2026-10-19T18:29:59Z",
+ deadlineAt: "2026-10-20T18:29:59Z",
+ resultsAt: "2026-10-25T06:30:00Z",
+ phase: "building",
+ pageUrl: "https://unstop.com/p/x",
+ submitUrl: "https://omnirush.ai/console/buildathon",
+ rules: ["Individual only.", "OmniRush must be the only generative AI tool you use."],
+ tracks: [{ id: "agents", label: "Agents & Automation" }, { id: "devtools", label: "Developer Tools & Open Source" }],
+ reminders: [
+ { beforeSeconds: 86_400, text: "24 hours left" },
+ { beforeSeconds: 3_600, text: "1 hour left" },
+ { beforeSeconds: 900, text: "15 minutes left" },
+ ],
+};
+const DEADLINE = Date.parse(EVENT.deadlineAt);
+const HOUR = 3_600_000;
+
+describe("countdown", () => {
+ test("formats days, hours, minutes", () => {
+ expect(formatRemaining(5 * 24 * HOUR + 3 * HOUR + 20 * 60_000)).toBe("5d 03h");
+ expect(formatRemaining(4 * HOUR + 7 * 60_000)).toBe("4h 07m");
+ expect(formatRemaining(42 * 60_000 + 9_000)).toBe("42m 09s");
+ expect(formatRemaining(-5)).toBe("0m 00s");
+ });
+
+ test("open, red under an hour, closed after the deadline or once judging", () => {
+ const open = buildathonCountdown(EVENT, DEADLINE - (5 * 24 + 3) * HOUR);
+ expect(open.kind).toBe("open");
+ expect(open.urgent).toBe(false);
+ expect(buildathonChipText(open)).toBe("Buildathon · 5d 03h left");
+
+ const last = buildathonCountdown(EVENT, DEADLINE - 30 * 60_000);
+ expect(last.urgent).toBe(true);
+ expect(buildathonChipText(last)).toBe("Buildathon · 30m 00s left");
+
+ const closed = buildathonCountdown(EVENT, DEADLINE + 1);
+ expect(closed.kind).toBe("closed");
+ expect(buildathonChipText(closed)).toBe("Buildathon · Submissions closed");
+ expect(buildathonCountdown({ ...EVENT, phase: "judging" }, DEADLINE - HOUR * 10).kind).toBe("closed");
+ });
+
+ test("before the start it counts to the start", () => {
+ const upcoming = buildathonCountdown(EVENT, Date.parse(EVENT.startsAt!) - 2 * HOUR);
+ expect(upcoming.kind).toBe("upcoming");
+ expect(buildathonChipText(upcoming)).toBe("Buildathon · starts in 2h 00m");
+ });
+
+ test("the server clock offset", () => {
+ expect(clockOffsetMs("2026-10-15T10:00:10Z", Date.parse("2026-10-15T10:00:00Z"))).toBe(10_000);
+ expect(clockOffsetMs(null, 5)).toBe(0);
+ });
+
+ test("event times are shown in IST", () => {
+ expect(formatEventTime(EVENT.deadlineAt)).toContain("20 Oct, 23:59 IST");
+ expect(formatEventTime(null)).toBe("");
+ });
+});
+
+describe("reminders", () => {
+ test("each once, the tightest due one only", () => {
+ const storage = memoryStorage();
+ const at = (ms: number) => reminderToShow(EVENT, buildathonCountdown(EVENT, DEADLINE - ms), readShownReminders(storage));
+ expect(at(30 * HOUR)).toBeNull();
+ const day = at(20 * HOUR)!;
+ expect(day.text).toBe("24 hours left");
+ rememberShownReminders(day.keys, storage);
+ expect(at(19 * HOUR)).toBeNull();
+ // Opening the app with ten minutes left: only the 15-minute text, and the hour is never shown after.
+ const late = at(10 * 60_000)!;
+ expect(late.text).toBe("15 minutes left");
+ rememberShownReminders(late.keys, storage);
+ expect(at(5 * 60_000)).toBeNull();
+ expect(reminderToShow(EVENT, buildathonCountdown(EVENT, DEADLINE + 1), new Set())).toBeNull();
+ });
+});
+
+describe("project tracks and tagging", () => {
+ test("stored per folder, trailing separators ignored", () => {
+ const storage = memoryStorage();
+ writeProjectTrack("/home/a/app/", "agents", storage);
+ expect(readProjectTrack("/home/a/app", storage)).toBe("agents");
+ expect(readProjectTrack("/home/a/other", storage)).toBeNull();
+ writeProjectTrack("/home/a/app", null, storage);
+ expect(readProjectTrack("/home/a/app", storage)).toBeNull();
+ expect(projectKey(" C:\\work\\x\\ ")).toBe("C:\\work\\x");
+ expect(projectKey("")).toBeNull();
+ });
+
+ test("root sessions inside the event, once per track", () => {
+ const inside = Date.parse("2026-10-15T00:00:00Z");
+ const projects = buildathonProjects([
+ {
+ workspace: { id: "w1", path: "/p/app", name: "app", workspaceType: "local" },
+ sessions: [
+ { id: "ses_a", time: { created: inside } },
+ { id: "ses_child", parentID: "ses_a", time: { created: inside } },
+ { id: "ses_old", time: { created: Date.parse("2026-10-01T00:00:00Z") } },
+ { id: "ses_done", time: { created: inside } },
+ ],
+ },
+ { workspace: { id: "w2", path: "/p/remote", name: "r", workspaceType: "remote" }, sessions: [{ id: "ses_r", time: { created: inside } }] },
+ { workspace: { id: "w3", path: "/p/none", name: "n", workspaceType: "local" }, sessions: [{ id: "ses_n", time: { created: inside } }] },
+ ]);
+ const tracks = { "/p/app": "agents", "/p/remote": "agents" };
+ expect(sessionsToTag(projects, EVENT, tracks, { ses_done: "agents" })).toEqual([{ sessionId: "ses_a", track: "agents", project: "app" }]);
+ // A track change re-files the project's sessions.
+ expect(sessionsToTag(projects, EVENT, { "/p/app": "devtools" }, { ses_done: "agents" }).map((entry) => entry.sessionId)).toEqual(["ses_a", "ses_done"]);
+ // Unknown track ids are never sent.
+ expect(sessionsToTag(projects, EVENT, { "/p/app": "nope" }, {})).toEqual([]);
+ });
+
+ test("remembered tags are capped", () => {
+ const storage = memoryStorage();
+ for (let index = 0; index < 510; index += 1) rememberTaggedSession(`ses_${index}`, "agents", storage);
+ const tagged = readTaggedSessions(storage);
+ expect(Object.keys(tagged).length).toBe(500);
+ expect(tagged.ses_509).toBe("agents");
+ expect(tagged.ses_0).toBeUndefined();
+ });
+});
+
+test("the only-tool rule comes first", () => {
+ expect(rulesWithToolRuleFirst(EVENT.rules)[0]).toContain("only generative AI tool");
+ expect(rulesWithToolRuleFirst([])[0]).toContain("only generative AI tool");
+});
+
+describe("refresh", () => {
+ const status: BuildathonStatus = { enrolled: true, serverTime: null, event: EVENT, participant: null, submission: null };
+
+ test("enrolled shows, anything else hides", async () => {
+ await refreshBuildathon(async () => status);
+ expect(useBuildathonStore.getState().status?.event.id).toBe("frontier-2026");
+ await refreshBuildathon(async () => null);
+ expect(useBuildathonStore.getState().status).toBeNull();
+ await refreshBuildathon(async () => status);
+ await refreshBuildathon(async () => {
+ throw new Error("bridge missing");
+ });
+ expect(useBuildathonStore.getState().status).toBeNull();
+ });
+});
diff --git a/apps/desktop/electron/buildathon.mjs b/apps/desktop/electron/buildathon.mjs
new file mode 100644
index 00000000..28a164ee
--- /dev/null
+++ b/apps/desktop/electron/buildathon.mjs
@@ -0,0 +1,215 @@
+/**
+ * Buildathon: the event block of GET /me/buildathon, the tagged sessions
+ * (GET /me/buildathon/sessions), the submission and the link code.
+ *
+ * Only an `enrolled: true` answer with a usable event is shown; anything
+ * else (false, 404, an error, a malformed body) reads as null and the app
+ * shows nothing.
+ */
+
+export const BUILDATHON_TRACKS = /** @type {const} */ ([
+ { id: "agents", label: "Agents & Automation" },
+ { id: "devtools", label: "Developer Tools & Open Source" },
+ { id: "research", label: "Research, Data & Scientific Computing" },
+ { id: "systems", label: "Systems, Infrastructure & Cybersecurity" },
+ { id: "human-ai", label: "Human × AI" },
+ { id: "open-frontier", label: "Open Frontier" },
+]);
+export const BUILDATHON_PHASES = /** @type {const} */ (["upcoming", "building", "judging", "results", "closed"]);
+const SESSION_STATES = ["good", "pending", "incomplete"];
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushBuildathonStatus} BuildathonStatus */
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushBuildathonEvent} BuildathonEvent */
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushBuildathonParticipant} BuildathonParticipant */
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushBuildathonSubmission} BuildathonSubmission */
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushBuildathonSession} BuildathonSession */
+const TRACK_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
+/** Link codes look like `FB-7KQ2-M9`; anything short and plain is passed on for the server to judge. */
+const LINK_CODE = /^[A-Za-z0-9][A-Za-z0-9-]{2,39}$/;
+
+function text(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+function count(value) {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
+}
+
+function isoTime(value) {
+ const raw = text(value);
+ return raw && Number.isFinite(Date.parse(raw)) ? raw : null;
+}
+
+function httpsUrl(value) {
+ const raw = text(value);
+ if (!raw) return null;
+ try {
+ const url = new URL(raw);
+ return url.protocol === "https:" ? url.toString() : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A track id the server could know; null otherwise. */
+export function buildathonTrackId(value) {
+ const id = text(value)?.toLowerCase() ?? null;
+ return id && TRACK_ID.test(id) ? id : null;
+}
+
+/** A link code as typed (spaces dropped, upper case), or null when it cannot be one. */
+export function buildathonLinkCode(value) {
+ const code = typeof value === "string" ? value.replace(/\s+/g, "").toUpperCase() : "";
+ return LINK_CODE.test(code) ? code : null;
+}
+
+function parseTracks(value) {
+ const tracks = Array.isArray(value)
+ ? value
+ .filter((track) => track && typeof track === "object")
+ .map((track) => ({ id: buildathonTrackId(track.id), label: text(track.label) }))
+ .filter((track) => track.id && track.label)
+ : [];
+ return tracks.length ? tracks.slice(0, 12) : BUILDATHON_TRACKS.map((track) => ({ ...track }));
+}
+
+function parseReminders(value) {
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter((reminder) => reminder && typeof reminder === "object")
+ .map((reminder) => ({ beforeSeconds: count(reminder.before_s), text: text(reminder.text) }))
+ .filter((reminder) => reminder.beforeSeconds > 0 && reminder.text)
+ .sort((left, right) => right.beforeSeconds - left.beforeSeconds)
+ .slice(0, 6);
+}
+
+/** @returns {BuildathonEvent | null} */
+function parseEvent(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const id = text(value.id);
+ const deadlineAt = isoTime(value.deadline_at);
+ if (!id || !deadlineAt) return null;
+ const phase = text(value.phase);
+ return {
+ id,
+ name: text(value.name) ?? "Buildathon",
+ startsAt: isoTime(value.starts_at),
+ registrationEndsAt: isoTime(value.registration_ends_at),
+ deadlineAt,
+ resultsAt: isoTime(value.results_at),
+ phase: BUILDATHON_PHASES.includes(/** @type {any} */ (phase)) ? /** @type {BuildathonEvent["phase"]} */ (phase) : null,
+ pageUrl: httpsUrl(value.page_url),
+ submitUrl: httpsUrl(value.submit_url),
+ rules: Array.isArray(value.rules) ? value.rules.map(text).filter((rule) => rule !== null).slice(0, 20) : [],
+ tracks: parseTracks(value.tracks),
+ reminders: parseReminders(value.reminders),
+ };
+}
+
+/** @returns {BuildathonParticipant | null} */
+function parseParticipant(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const granted = count(value.tokens_granted);
+ const used = count(value.tokens_used);
+ const left = value.tokens_left === undefined || value.tokens_left === null ? Math.max(0, granted - used) : count(value.tokens_left);
+ return {
+ enrolledAt: isoTime(value.enrolled_at),
+ tokensGranted: granted,
+ tokensUsed: used,
+ tokensLeft: left,
+ sessionsTagged: count(value.sessions_tagged),
+ sessionsGood: count(value.sessions_good),
+ };
+}
+
+/**
+ * The submission object (POST/GET /me/buildathon/submission, `submission` of GET /me/buildathon); null when absent.
+ * @returns {BuildathonSubmission | null}
+ */
+export function parseBuildathonSubmission(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const submissionId = text(value.submission_id);
+ if (!submissionId) return null;
+ return {
+ submissionId,
+ submittedAt: isoTime(value.submitted_at),
+ updatedAt: isoTime(value.updated_at),
+ track: buildathonTrackId(value.track),
+ title: text(value.title),
+ repoUrl: httpsUrl(value.repo_url),
+ demoVideoUrl: httpsUrl(value.demo_video_url),
+ liveUrl: httpsUrl(value.live_url),
+ sessionIds: Array.isArray(value.session_ids) ? value.session_ids.map(text).filter((id) => id !== null).slice(0, 200) : [],
+ checks: Array.isArray(value.checks)
+ ? value.checks
+ .filter((check) => check && typeof check === "object" && text(check.id))
+ .map((check) => ({ id: text(check.id), ok: check.ok === true, text: text(check.text) ?? "" }))
+ .slice(0, 20)
+ : [],
+ locked: value.locked === true,
+ };
+}
+
+/**
+ * GET /me/buildathon (or the link answer): null unless the account is
+ * enrolled and the event names a deadline.
+ * @returns {BuildathonStatus | null}
+ */
+export function parseBuildathonStatus(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.enrolled !== true) return null;
+ const event = parseEvent(value.event);
+ if (!event) return null;
+ return {
+ enrolled: true,
+ serverTime: isoTime(value.server_time),
+ event,
+ participant: parseParticipant(value.participant),
+ submission: parseBuildathonSubmission(value.submission),
+ };
+}
+
+/**
+ * GET /me/buildathon/sessions; null on a malformed body.
+ * @returns {BuildathonSession[] | null}
+ */
+export function parseBuildathonSessions(value) {
+ if (!value || typeof value !== "object" || !Array.isArray(value.sessions)) return null;
+ return value.sessions
+ .filter((session) => session && typeof session === "object" && text(session.session_id))
+ .slice(0, 200)
+ .map((session) => ({
+ sessionId: text(session.session_id),
+ title: text(session.title),
+ project: text(session.project),
+ startedAt: isoTime(session.started_at),
+ endedAt: isoTime(session.ended_at),
+ track: buildathonTrackId(session.track),
+ status: SESSION_STATES.includes(session.status) ? session.status : "pending",
+ reasons: Array.isArray(session.reasons) ? session.reasons.map(text).filter((reason) => reason !== null).slice(0, 10) : [],
+ tokens: count(session.tokens),
+ }));
+}
+
+const LINK_ERRORS = {
+ invalid_code: "That code was not found. Check it against your registration email.",
+ code_already_used: "That code was already used.",
+ already_enrolled: "This account is already enrolled.",
+ not_available: "Linking is not available right now.",
+ too_many_attempts: "Too many tries. Wait a few minutes and try again.",
+};
+
+/** A refused link as a sentence: the server's error code mapped, or its own words. */
+export function buildathonLinkError(payload, status) {
+ const message = payload && typeof payload === "object" ? text(payload.error) ?? text(payload.detail) : null;
+ if (message && Object.hasOwn(LINK_ERRORS, message)) return LINK_ERRORS[message];
+ if (status === 429) return LINK_ERRORS.too_many_attempts;
+ if (message && !/^[a-z0-9_]+$/.test(message)) return message;
+ if (status === 400 || status === 404) return LINK_ERRORS.invalid_code;
+ return "The code could not be checked. Try again in a moment.";
+}
+
+/** A folder's last name, as the server takes it (never a full path). */
+export function buildathonProjectName(value) {
+ const name = text(value)?.split(/[\\/]/).filter(Boolean).pop() ?? null;
+ return name && name.length <= 200 ? name : null;
+}
diff --git a/apps/desktop/electron/buildathon.test.mjs b/apps/desktop/electron/buildathon.test.mjs
new file mode 100644
index 00000000..f12c54f6
--- /dev/null
+++ b/apps/desktop/electron/buildathon.test.mjs
@@ -0,0 +1,212 @@
+import assert from "node:assert/strict";
+import { mkdtemp } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ BUILDATHON_TRACKS,
+ buildathonLinkCode,
+ buildathonTrackId,
+ parseBuildathonSessions,
+ parseBuildathonStatus,
+ parseBuildathonSubmission,
+} from "./buildathon.mjs";
+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";
+
+const GATEWAY = "http://localhost:8090/omnirush/v1";
+const SUBMISSION = {
+ submission_id: "OFB-4K7Q9M",
+ submitted_at: "2026-10-18T10:00:00Z",
+ updated_at: "2026-10-18T11:00:00Z",
+ track: "agents",
+ title: "Thing",
+ repo_url: "https://github.com/a/b",
+ demo_video_url: "https://youtu.be/x",
+ live_url: "http://insecure.example",
+ description: "d",
+ session_ids: ["ses_1", 7],
+ checks: [{ id: "repo_public", ok: true, text: "Repo is public" }, { ok: false }],
+ locked: false,
+};
+const ENROLLED = {
+ enrolled: true,
+ server_time: "2026-10-15T10:00:00Z",
+ event: {
+ id: "frontier-2026",
+ name: "OmniRush Frontier Buildathon 2026",
+ starts_at: "2026-10-13T18:30:00Z",
+ registration_ends_at: "2026-10-19T18:29:59Z",
+ deadline_at: "2026-10-20T18:29:59Z",
+ results_at: "2026-10-25T06:30:00Z",
+ phase: "building",
+ page_url: "https://unstop.com/p/x",
+ submit_url: "https://omnirush.ai/console/buildathon",
+ rules: ["OmniRush must be the only generative AI tool you use.", "", "Individual only."],
+ tracks: [{ id: "agents", label: "Agents & Automation" }, { id: "BAD ID", label: "x" }],
+ reminders: [{ before_s: 900, text: "15 min" }, { before_s: 86400, text: "24 h" }, { before_s: 3600, text: "1 h" }, { before_s: 0, text: "no" }],
+ },
+ participant: { enrolled_at: "2026-10-14T00:00:00Z", tokens_granted: 10000000, tokens_used: 1234567, tokens_left: 8765433, sessions_tagged: 12, sessions_good: 7 },
+ submission: null,
+};
+
+function testStorage() {
+ return {
+ isAsyncEncryptionAvailable: async () => true,
+ getSelectedStorageBackend: () => "keychain",
+ encryptStringAsync: async (value) => Buffer.from(value, "utf8"),
+ decryptStringAsync: async (value) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),
+ };
+}
+
+async function signedInStore(fetchImpl) {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-buildathon-"));
+ const store = createDesktopOmniRushAccountStore({
+ filePath: path.join(directory, "account.bin"),
+ loadSafeStorage: () => testStorage(),
+ platform: /** @type {NodeJS.Platform} */ ("linux"),
+ env: { OMNIRUSH_DEV_MODE: "1" },
+ sleep: async () => undefined,
+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },
+ clientVersion: "3.4.9",
+ fetchImpl,
+ });
+ await store.save({ gatewayUrl: GATEWAY, accessToken: "access-1", refreshToken: "refresh-1" });
+ return store;
+}
+
+test("buildathon: anything but an enrolled answer with a deadline is null", () => {
+ assert.equal(parseBuildathonStatus(null), null);
+ assert.equal(parseBuildathonStatus({ enrolled: false }), null);
+ assert.equal(parseBuildathonStatus({ enrolled: "true", event: ENROLLED.event }), null);
+ assert.equal(parseBuildathonStatus({ enrolled: true }), null);
+ assert.equal(parseBuildathonStatus({ enrolled: true, event: { ...ENROLLED.event, deadline_at: "soon" } }), null);
+ assert.equal(parseBuildathonStatus([]), null);
+});
+
+test("buildathon: the enrolled block, cleaned", () => {
+ const status = parseBuildathonStatus(ENROLLED);
+ assert.equal(status.enrolled, true);
+ assert.equal(status.event.id, "frontier-2026");
+ assert.equal(status.event.phase, "building");
+ assert.equal(status.event.deadlineAt, "2026-10-20T18:29:59Z");
+ assert.deepEqual(status.event.rules, ["OmniRush must be the only generative AI tool you use.", "Individual only."]);
+ assert.deepEqual(status.event.tracks, [{ id: "agents", label: "Agents & Automation" }]);
+ assert.deepEqual(status.event.reminders.map((reminder) => reminder.beforeSeconds), [86400, 3600, 900]);
+ assert.equal(status.participant.tokensLeft, 8765433);
+ assert.equal(status.participant.sessionsGood, 7);
+ assert.equal(status.submission, null);
+});
+
+test("buildathon: the six tracks stand in when the server lists none", () => {
+ const status = parseBuildathonStatus({ ...ENROLLED, event: { ...ENROLLED.event, tracks: [], phase: "odd", submit_url: "javascript:alert(1)" } });
+ assert.deepEqual(status.event.tracks.map((track) => track.id), BUILDATHON_TRACKS.map((track) => track.id));
+ assert.equal(status.event.tracks.length, 6);
+ assert.equal(status.event.phase, null);
+ assert.equal(status.event.submitUrl, null);
+});
+
+test("buildathon: tokens left defaults to granted minus used", () => {
+ const status = parseBuildathonStatus({ ...ENROLLED, participant: { tokens_granted: 10000000, tokens_used: 4000000 } });
+ assert.equal(status.participant.tokensLeft, 6000000);
+});
+
+test("buildathon: the submission object", () => {
+ const submission = parseBuildathonSubmission(SUBMISSION);
+ assert.equal(submission.submissionId, "OFB-4K7Q9M");
+ assert.equal(submission.liveUrl, null, "only https links are kept");
+ assert.deepEqual(submission.sessionIds, ["ses_1"]);
+ assert.deepEqual(submission.checks, [{ id: "repo_public", ok: true, text: "Repo is public" }]);
+ assert.equal(parseBuildathonSubmission({}), null);
+ assert.equal(parseBuildathonStatus({ ...ENROLLED, submission: SUBMISSION }).submission.submissionId, "OFB-4K7Q9M");
+});
+
+test("buildathon: tagged sessions", () => {
+ const sessions = parseBuildathonSessions({
+ sessions: [
+ { session_id: "ses_1", title: "API", project: "app", started_at: "2026-10-15T01:00:00Z", track: "agents", status: "good", reasons: [], tokens: 12000 },
+ { session_id: "ses_2", status: "weird", reasons: ["Too short", ""] },
+ { title: "no id" },
+ ],
+ });
+ assert.equal(sessions.length, 2);
+ assert.equal(sessions[0].status, "good");
+ assert.equal(sessions[1].status, "pending");
+ assert.deepEqual(sessions[1].reasons, ["Too short"]);
+ assert.equal(parseBuildathonSessions({}), null);
+});
+
+test("buildathon: track ids and link codes", () => {
+ assert.equal(buildathonTrackId("Human-AI"), "human-ai");
+ assert.equal(buildathonTrackId("../x"), null);
+ assert.equal(buildathonLinkCode(" fb-7kq2-m9 "), "FB-7KQ2-M9");
+ assert.equal(buildathonLinkCode("x"), null);
+ assert.equal(buildathonLinkCode("FB/../.."), null);
+});
+
+test("buildathon store: GET /me/buildathon with the device credential; null for not enrolled, errors, timeouts", async () => {
+ const seen = [];
+ const store = await signedInStore(async (url, init) => {
+ seen.push({ path: new URL(url).pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal instanceof AbortSignal });
+ return Response.json(ENROLLED);
+ });
+ assert.equal((await store.buildathonStatus()).event.id, "frontier-2026");
+ assert.deepEqual(seen, [{ path: "/omnirush/me/buildathon", authorization: "Bearer access-1", signal: true }]);
+
+ for (const fetchImpl of [
+ async () => Response.json({ enrolled: false }),
+ async () => new Response("nope", { status: 404 }),
+ async () => new Response("down", { status: 500 }),
+ async () => new Response("not json", { status: 200 }),
+ async () => { throw new TypeError("fetch failed"); },
+ async () => { throw new DOMException("The operation timed out.", "TimeoutError"); },
+ ]) {
+ const other = await signedInStore(fetchImpl);
+ assert.equal(await other.buildathonStatus(), null);
+ assert.equal(await other.buildathonSessions(), null);
+ }
+});
+
+test("buildathon store: PUT the track of a session; 204 tagged, 404 refused, 5xx retry", async () => {
+ const seen = [];
+ const store = await signedInStore(async (url, init) => {
+ seen.push({ path: new URL(url).pathname, method: init.method, body: init.body });
+ return new Response(null, { status: 204 });
+ });
+ assert.equal(await store.buildathonTagSession({ sessionId: "ses_abc", track: "agents", project: "/home/a/shipwright" }), "tagged");
+ assert.deepEqual(seen, [{ path: "/omnirush/me/sessions/ses_abc/buildathon", method: "PUT", body: JSON.stringify({ track: "agents", project: "shipwright" }) }]);
+ assert.equal(await store.buildathonTagSession({ sessionId: "../me", track: "agents" }), "refused");
+ assert.equal(await store.buildathonTagSession({ sessionId: "ses_abc", track: "" }), "refused");
+ assert.equal(seen.length, 1, "bad input never reaches the server");
+
+ const notParticipant = await signedInStore(async () => Response.json({ detail: "Not Found" }, { status: 404 }));
+ assert.equal(await notParticipant.buildathonTagSession({ sessionId: "ses_abc", track: "agents" }), "refused");
+ const outside = await signedInStore(async () => Response.json({ error: "outside_window" }, { status: 409 }));
+ assert.equal(await outside.buildathonTagSession({ sessionId: "ses_abc", track: "agents" }), "refused");
+ const down = await signedInStore(async () => new Response("down", { status: 503 }));
+ assert.equal(await down.buildathonTagSession({ sessionId: "ses_abc", track: "agents" }), "retry");
+ const offline = await signedInStore(async () => { throw new TypeError("fetch failed"); });
+ assert.equal(await offline.buildathonTagSession({ sessionId: "ses_abc", track: "agents" }), "retry");
+});
+
+test("buildathon store: link code", async () => {
+ const seen = [];
+ const store = await signedInStore(async (url, init) => {
+ seen.push({ path: new URL(url).pathname, method: init.method, body: init.body });
+ return Response.json(ENROLLED);
+ });
+ const linked = await store.buildathonLink({ code: "fb-7kq2-m9" });
+ assert.equal(linked.ok, true);
+ assert.equal(linked.status.event.id, "frontier-2026");
+ assert.deepEqual(seen, [{ path: "/omnirush/me/buildathon/link", method: "POST", body: JSON.stringify({ code: "FB-7KQ2-M9" }) }]);
+ assert.equal((await store.buildathonLink({ code: "" })).ok, false);
+
+ const refused = await signedInStore(async () => Response.json({ error: "code_already_used" }, { status: 400 }));
+ assert.deepEqual(await refused.buildathonLink({ code: "FB-0000-00" }), { ok: false, error: "That code was already used." });
+ const unknown = await signedInStore(async () => Response.json({ error: "some_new_code" }, { status: 400 }));
+ assert.match(/** @type {any} */ (await unknown.buildathonLink({ code: "FB-0000-00" })).error, /not found/);
+ const limited = await signedInStore(async () => Response.json({ error: "too_many_attempts" }, { status: 429 }));
+ assert.match(/** @type {any} */ (await limited.buildathonLink({ code: "FB-0000-00" })).error, /Too many tries/);
+ const offline = await signedInStore(async () => { throw new TypeError("fetch failed"); });
+ assert.equal((await offline.buildathonLink({ code: "FB-0000-00" })).ok, false);
+});
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 44643e9c..15da5f2a 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -2195,6 +2195,22 @@ const desktopCommandHandlers = {
const input = args[0] && typeof args[0] === "object" ? args[0] : {};
return omnirushAccountStore.spinQuality({ idempotencyKey: typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined });
},
+ // Buildathon: shown only to enrolled accounts; every failure is a null
+ // (or a "retry"), never a thrown error, so the app quietly shows nothing.
+ "omnirushBuildathon": async (event) => {
+ return omnirushAccountStore.buildathonStatus();
+ },
+ "omnirushBuildathonSessions": async (event) => {
+ return omnirushAccountStore.buildathonSessions();
+ },
+ "omnirushBuildathonLink": async (event, ...args) => {
+ const input = args[0] && typeof args[0] === "object" ? args[0] : {};
+ return omnirushAccountStore.buildathonLink({ code: input.code });
+ },
+ "omnirushBuildathonTagSession": async (event, ...args) => {
+ const input = args[0] && typeof args[0] === "object" ? args[0] : {};
+ return omnirushAccountStore.buildathonTagSession({ sessionId: input.sessionId, track: input.track, project: input.project });
+ },
"omnirushAccountConnect": async (event, ...args) => {
const input = args[0] ?? {};
const result = await omnirushAccountStore.authorize({
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index 521e67d2..147498e5 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -13,6 +13,7 @@ import {
writePlaintextCredentialFile,
} from "./plaintext-credential-file.mjs";
import { CLIENT_HEADER, guiClientHeaderValue, parseClientUpdate } from "./update-gate.mjs";
+import { buildathonLinkCode, buildathonLinkError, buildathonProjectName, buildathonTrackId, parseBuildathonSessions, parseBuildathonStatus } from "./buildathon.mjs";
import { parseAccountQuality, parseFailLabels, parseQualitySessions, parseSessionStatus, parseSpinHistory, profileSessionId, parseSpinResult, parseWheelSegments, spinIdempotencyKey, spinRefusal } from "./quality.mjs";
const execFileAsync = promisify(execFile);
@@ -47,6 +48,8 @@ const SERVER_ROTATION_GRACE_MS = 120_000;
const REFRESH_TIMEOUT_MS = 20_000;
/** A session's live status: past this the app shows its own checklist (the server contract's 3 s). */
const SESSION_STATUS_TIMEOUT_MS = 3_000;
+/** Buildathon reads never hold anything up: past this the event is simply not shown. */
+const BUILDATHON_TIMEOUT_MS = 10_000;
/**
* A refresh token that may already have been rotated (the answer was lost)
* is sent again only while that attempt, timeout included, ends inside the
@@ -1245,6 +1248,86 @@ export function createDesktopOmniRushAccountStore({
return spin ? { ok: true, spin } : { ok: false, reason: "failed", status: response.status };
}
+ /**
+ * The buildathon block (GET /me/buildathon). Null for anyone not enrolled,
+ * while signed out, offline, slow or on a bad answer: the app then shows
+ * nothing about the event.
+ */
+ async function buildathonStatus() {
+ try {
+ const response = await sendAuthorized("/me/buildathon", { method: "GET", signal: AbortSignal.timeout(BUILDATHON_TIMEOUT_MS) });
+ if (!response?.ok) return null;
+ return parseBuildathonStatus(await response.json());
+ } catch {
+ return null;
+ }
+ }
+
+ /** The event's tagged sessions (GET /me/buildathon/sessions); null when unavailable. */
+ async function buildathonSessions() {
+ try {
+ const response = await sendAuthorized("/me/buildathon/sessions", { method: "GET", signal: AbortSignal.timeout(BUILDATHON_TIMEOUT_MS) });
+ if (!response?.ok) return null;
+ return parseBuildathonSessions(await response.json());
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * Link a registration made under another email (POST /me/buildathon/link).
+ * @param {{ code?: unknown }} [input]
+ * @returns {Promise<import("@omnirush/types/desktop-ipc").OmniRushBuildathonLinkResult>}
+ */
+ async function buildathonLink(input = {}) {
+ const code = buildathonLinkCode(input.code);
+ if (!code) return { ok: false, error: "Enter the code from your registration email." };
+ let response;
+ try {
+ response = await sendAuthorized("/me/buildathon/link", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ code }),
+ signal: AbortSignal.timeout(BUILDATHON_TIMEOUT_MS),
+ });
+ } catch {
+ return { ok: false, error: "The code could not be checked. Try again in a moment." };
+ }
+ if (!response) return { ok: false, error: "Sign in to link a code." };
+ const payload = await response.json().catch(() => null);
+ if (!response.ok) return { ok: false, error: buildathonLinkError(payload, response.status) };
+ const status = parseBuildathonStatus(payload);
+ return status ? { ok: true, status } : { ok: false, error: "That code is not linked to an event you can join." };
+ }
+
+ /**
+ * Name the track of one session (PUT /me/sessions/{id}/buildathon), with
+ * the folder's last name. 204 is done; 400/403/404/409 (unknown track, not
+ * a participant, outside the event) are final as well; anything else may
+ * be tried again later.
+ * @param {{ sessionId?: unknown, track?: unknown, project?: unknown }} [input]
+ * @returns {Promise<"tagged" | "refused" | "retry">}
+ */
+ async function buildathonTagSession(input = {}) {
+ const sessionId = profileSessionId(input.sessionId);
+ const track = buildathonTrackId(input.track);
+ const project = buildathonProjectName(input.project);
+ if (!sessionId || !track) return "refused";
+ try {
+ const response = await sendAuthorized(`/me/sessions/${encodeURIComponent(sessionId)}/buildathon`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(project ? { track, project } : { track }),
+ signal: AbortSignal.timeout(BUILDATHON_TIMEOUT_MS),
+ });
+ if (!response) return "retry";
+ if (response.ok) return "tagged";
+ return [400, 403, 404, 409].includes(response.status) ? "refused" : "retry";
+ } catch {
+ return "retry";
+ }
+ }
+
/**
* Sign out locally and, for a user-initiated sign-out, revoke the device
* session remotely and forget the keychain gateway URL so the next sign-in
@@ -1284,5 +1367,20 @@ export function createDesktopOmniRushAccountStore({
}
}
- return { load, save, refresh, authorize, status, clear, qualityDetails, qualitySpinTotals, spinQuality, sessionStatus };
+ return {
+ load,
+ save,
+ refresh,
+ authorize,
+ status,
+ clear,
+ qualityDetails,
+ qualitySpinTotals,
+ spinQuality,
+ sessionStatus,
+ buildathonStatus,
+ buildathonSessions,
+ buildathonLink,
+ buildathonTagSession,
+ };
}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index e4a87e06..c0ae4b85 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,7 +27,7 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
"test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index 64055758..efa246e3 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -285,6 +285,68 @@ export type OmniRushQualityDetails = {
* Labels, hints and messages are server text, shown as given. Null from the
* desktop: the app falls back to its own checklist.
*/
+/** Buildathon (GET /omnirush/me/buildathon), parsed by the main process; null unless enrolled. */
+export type OmniRushBuildathonTrack = { id: string; label: string };
+export type OmniRushBuildathonPhase = "upcoming" | "building" | "judging" | "results" | "closed";
+export type OmniRushBuildathonEvent = {
+ id: string;
+ name: string;
+ startsAt: string | null;
+ registrationEndsAt: string | null;
+ deadlineAt: string;
+ resultsAt: string | null;
+ phase: OmniRushBuildathonPhase | null;
+ pageUrl: string | null;
+ submitUrl: string | null;
+ rules: string[];
+ tracks: OmniRushBuildathonTrack[];
+ /** Largest first. */
+ reminders: Array<{ beforeSeconds: number; text: string }>;
+};
+export type OmniRushBuildathonParticipant = {
+ enrolledAt: string | null;
+ tokensGranted: number;
+ tokensUsed: number;
+ tokensLeft: number;
+ sessionsTagged: number;
+ sessionsGood: number;
+};
+export type OmniRushBuildathonSubmission = {
+ submissionId: string;
+ submittedAt: string | null;
+ updatedAt: string | null;
+ track: string | null;
+ title: string | null;
+ repoUrl: string | null;
+ demoVideoUrl: string | null;
+ liveUrl: string | null;
+ sessionIds: string[];
+ checks: Array<{ id: string; ok: boolean; text: string }>;
+ locked: boolean;
+};
+export type OmniRushBuildathonStatus = {
+ enrolled: true;
+ serverTime: string | null;
+ event: OmniRushBuildathonEvent;
+ participant: OmniRushBuildathonParticipant | null;
+ submission: OmniRushBuildathonSubmission | null;
+};
+export type OmniRushBuildathonSession = {
+ sessionId: string;
+ title: string | null;
+ project: string | null;
+ startedAt: string | null;
+ endedAt: string | null;
+ track: string | null;
+ status: "good" | "pending" | "incomplete";
+ reasons: string[];
+ tokens: number;
+};
+export type OmniRushBuildathonLinkResult =
+ | { ok: true; status: OmniRushBuildathonStatus }
+ | { ok: false; error: string };
+export type OmniRushBuildathonTagResult = "tagged" | "refused" | "retry";
+
export type OmniRushSessionStatus = {
sessionId: string;
status: "on_track" | "at_risk" | "failing" | "unknown";
@@ -836,6 +898,13 @@ export type DesktopCommandMap = {
args: [input: { idempotencyKey: string }];
result: OmniRushQualitySpinOutcome;
};
+ omnirushBuildathon: { args: []; result: OmniRushBuildathonStatus | null };
+ omnirushBuildathonSessions: { args: []; result: OmniRushBuildathonSession[] | null };
+ omnirushBuildathonLink: { args: [input: { code: string }]; result: OmniRushBuildathonLinkResult };
+ omnirushBuildathonTagSession: {
+ args: [input: { sessionId: string; track: string; project?: string | null }];
+ result: OmniRushBuildathonTagResult;
+ };
omnirushAccountConnect: {
args: [options?: { gatewayUrl?: string; deviceName?: string }];
result: { connected: true; userCode: string };