mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 10:48:20 +01:00
feat(onboarding): cloud-side "start a new project" — GitHub repo + FleetCrown row
Closes the catsitting-startup loop for cloud-only users (no local runtime).
Before this commit, the only "scaffold from idea" path was BootstrapModal
which requires the Fleet Runner daemon to write to ~/dev and shell out to
`gh repo create`. Users without the daemon could only IMPORT existing
projects — they had no way to create a fresh one through the website.
What ships:
1. POST /api/projects/create-with-github
- Auth via session cookie (signed-in user)
- Reads user's GitHub OAuth access_token from the accounts table (saved
automatically on GitHub sign-in)
- Calls api.github.com/user/repos with the user's token to create a real
repo (name, description, visibility, auto-init README)
- Slugs the repo name (lowercase, hyphens); preserves original display
name as the FleetCrown project entity name
- Creates the FleetCrown project row pointing at the new repo URL
- Returns { gitUrl, sshUrl, cloneCmd, cloneHttpsCmd, project }
- Graceful failure modes: 400 if no GitHub linked (with hasGithub:false
and a hint to /control/import → Connect GitHub), 409 on duplicate repo
name, 502 on GitHub API errors with the original status surfaced
2. /control/new-from-scratch page
- Form: name (required), description (optional), visibility (private/public)
- Submit → endpoint above → success view with the clone command in a copy
button (SSH primary, HTTPS in a collapsed details)
- "Create another" loop without leaving the page
3. EmptyStateWelcome's first card becomes adaptive:
- With runtime (onBootstrap defined): button → BootstrapModal as before
- Without runtime: link to /control/new-from-scratch (cloud GitHub flow)
- Always visible — no more hidden Bootstrap
The grid is now always 5 columns on lg (5 onboarding paths total: start fresh,
import GitHub, import ~/dev, add manually, install Fleet Runner). 2-col on md.
End-to-end:
/control empty → click "Start a new project" → form → submit →
GitHub repo created with README → FleetCrown row created →
user copies `git clone git@github.com:you/catsitting-startup.git` →
clone wherever they want → start hacking.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
1f94978179
commit
9d95b3ee42
3 files changed
+464
-6
No files matched your search
@@ -0,0 +1,283 @@
|
||||
"use client";
|
||||
|
||||
// "Start a new project from scratch" without local runtime.
|
||||
// Creates a brand new GitHub repo + FleetCrown project record in one shot.
|
||||
// After, the user can `git clone` it on any machine — no Fleet Runner needed.
|
||||
//
|
||||
// Companion to BootstrapModal which does the full local stack scaffold but
|
||||
// only works when the local daemon is running.
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft, Loader2, GitBranch, Check, Copy } from "lucide-react";
|
||||
import { PageLayout } from "@/components/ui/page-layout";
|
||||
|
||||
type CreateResponse = {
|
||||
ok: boolean;
|
||||
project?: { id: string; name: string };
|
||||
repo?: {
|
||||
name: string;
|
||||
full_name: string;
|
||||
gitUrl: string;
|
||||
sshUrl: string;
|
||||
cloneUrl: string;
|
||||
private: boolean;
|
||||
};
|
||||
cloneCmd?: string;
|
||||
cloneHttpsCmd?: string;
|
||||
error?: string;
|
||||
detail?: string;
|
||||
hasGithub?: boolean;
|
||||
};
|
||||
|
||||
export default function NewFromScratchPage() {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [visibility, setVisibility] = useState<"private" | "public">("private");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [result, setResult] = useState<CreateResponse | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [copied, setCopied] = useState<"ssh" | "https" | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) return;
|
||||
setSubmitting(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await fetch("/api/projects/create-with-github", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
visibility,
|
||||
init_readme: true,
|
||||
}),
|
||||
});
|
||||
const body = (await res.json()) as CreateResponse;
|
||||
if (!res.ok || !body.ok) {
|
||||
const msg = body.error
|
||||
? body.detail
|
||||
? `${body.error} — ${body.detail}`
|
||||
: body.error
|
||||
: `Failed (HTTP ${res.status})`;
|
||||
setError(msg);
|
||||
if (body.hasGithub === false) {
|
||||
// No GitHub linked — surface a path to connect.
|
||||
setError(`${msg} Go to /control/import to connect GitHub first.`);
|
||||
}
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
setResult(body);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Network error");
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copy(text: string, kind: "ssh" | "https") {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(kind);
|
||||
setTimeout(() => setCopied(null), 1500);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// ── Result view ─────────────────────────────────────────────────────────
|
||||
|
||||
if (result?.ok && result.repo && result.project) {
|
||||
return (
|
||||
<PageLayout title="Project created 🎉">
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div>
|
||||
<Link href="/control" className="ui-btn-ghost inline-flex items-center gap-1 text-sm">
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
Back to Control
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="ui-card-shell space-y-5 p-6">
|
||||
<div>
|
||||
<h2 className="ui-page-subtitle">{result.project.name}</h2>
|
||||
<p className="text-sm text-text-muted mt-1">
|
||||
GitHub repo created ({result.repo.private ? "private" : "public"}) and registered in FleetCrown.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium text-text-primary">
|
||||
<GitBranch className="inline h-4 w-4 mr-1 -mt-0.5" />
|
||||
Repo
|
||||
</div>
|
||||
<a
|
||||
href={result.repo.gitUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-accent underline break-all"
|
||||
>
|
||||
{result.repo.gitUrl}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium text-text-primary">Clone to your machine</div>
|
||||
<div className="relative">
|
||||
<pre className="ui-card-shell p-3 pr-10 overflow-x-auto text-xs text-text-secondary">
|
||||
<code>{result.cloneCmd}</code>
|
||||
</pre>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(result.cloneCmd ?? "", "ssh")}
|
||||
className="absolute top-2 right-2 ui-btn-icon"
|
||||
title="Copy SSH clone command"
|
||||
>
|
||||
{copied === "ssh" ? <Check className="h-3.5 w-3.5 text-status-positive" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
<details className="text-xs text-text-tertiary">
|
||||
<summary className="cursor-pointer">HTTPS clone (no SSH key required)</summary>
|
||||
<div className="relative mt-2">
|
||||
<pre className="ui-card-shell p-3 pr-10 overflow-x-auto text-xs text-text-secondary">
|
||||
<code>{result.cloneHttpsCmd}</code>
|
||||
</pre>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(result.cloneHttpsCmd ?? "", "https")}
|
||||
className="absolute top-2 right-2 ui-btn-icon"
|
||||
>
|
||||
{copied === "https" ? <Check className="h-3.5 w-3.5 text-status-positive" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-border-subtle flex justify-end gap-2">
|
||||
<button type="button" onClick={() => router.push("/control")} className="ui-btn-secondary">
|
||||
Open Control
|
||||
</button>
|
||||
<button type="button" onClick={() => { setResult(null); setName(""); setDescription(""); }} className="ui-btn-ghost">
|
||||
Create another
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Form view ───────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<PageLayout title="Start a new project">
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div>
|
||||
<Link href="/control" className="ui-btn-ghost inline-flex items-center gap-1 text-sm">
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
Back to Control
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="ui-card-shell space-y-5 p-6">
|
||||
<div>
|
||||
<h2 className="ui-page-subtitle">Start fresh — GitHub repo + FleetCrown project</h2>
|
||||
<p className="text-sm text-text-muted mt-1">
|
||||
Creates a brand-new GitHub repo (with README) and registers it as a FleetCrown project.
|
||||
No local runtime needed — clone it to your machine when you're ready.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="ui-error p-3 rounded-md text-sm">{error}</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-primary mb-1">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="catsitting-startup"
|
||||
autoFocus
|
||||
required
|
||||
maxLength={80}
|
||||
className="ui-input w-full"
|
||||
/>
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
Used as both the GitHub repo name (lowercase, hyphens) and the FleetCrown project display name.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-primary mb-1">Description (optional)</label>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="A peer-to-peer marketplace for catsitters."
|
||||
maxLength={300}
|
||||
rows={2}
|
||||
className="ui-input w-full resize-y"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm font-medium text-text-primary mb-1">Visibility</div>
|
||||
<div className="flex gap-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer flex-1 ui-card-shell p-3">
|
||||
<input
|
||||
type="radio"
|
||||
name="visibility"
|
||||
value="private"
|
||||
checked={visibility === "private"}
|
||||
onChange={() => setVisibility("private")}
|
||||
/>
|
||||
<div>
|
||||
<div className="text-sm font-medium">Private</div>
|
||||
<div className="text-xs text-text-muted">Only you can see this repo.</div>
|
||||
</div>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer flex-1 ui-card-shell p-3">
|
||||
<input
|
||||
type="radio"
|
||||
name="visibility"
|
||||
value="public"
|
||||
checked={visibility === "public"}
|
||||
onChange={() => setVisibility("public")}
|
||||
/>
|
||||
<div>
|
||||
<div className="text-sm font-medium">Public</div>
|
||||
<div className="text-xs text-text-muted">Anyone can find and read it.</div>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-2 border-t border-border-subtle">
|
||||
<Link href="/control" className="ui-btn-ghost">Cancel</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting || !name.trim()}
|
||||
className="ui-btn-primary inline-flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Creating…
|
||||
</>
|
||||
) : (
|
||||
<>Create repo + project</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Cloud-side "start a new project from scratch" — creates a brand new GitHub
|
||||
// repo AND the matching FleetCrown project record in one round-trip. This is
|
||||
// the catsitting-startup loop closer: the user has an idea but no local
|
||||
// runtime (Fleet Runner not installed), and they can still get a real repo +
|
||||
// FleetCrown row spun up. They clone the repo to their machine afterward.
|
||||
//
|
||||
// Companion to /api/project/bootstrap which does the full local-stack
|
||||
// scaffold (folder + git init + agent launch) but requires the local daemon.
|
||||
//
|
||||
// Auth: session cookie (same as /api/projects). We pull the user's GitHub
|
||||
// OAuth access_token from the accounts table — created automatically when
|
||||
// they signed in with GitHub. Without it, we can't create repos on their
|
||||
// behalf.
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { db } from "@/db";
|
||||
import { accounts } from "@/db/schema";
|
||||
import { createProject } from "@/db/queries/projects";
|
||||
import { SOURCE_FLEETCROWN_UI } from "@/lib/constants";
|
||||
|
||||
const Body = z.object({
|
||||
name: z.string().trim().min(1, "name is required").max(80),
|
||||
description: z.string().trim().max(300).optional(),
|
||||
visibility: z.enum(["private", "public"]).default("private"),
|
||||
/** Initialize with a README.md so the repo isn't empty. */
|
||||
init_readme: z.boolean().default(true),
|
||||
});
|
||||
|
||||
async function getGithubToken(userId: string): Promise<string | null> {
|
||||
const row = await db.query.accounts.findFirst({
|
||||
where: and(eq(accounts.userId, userId), eq(accounts.provider, "github")),
|
||||
columns: { access_token: true },
|
||||
});
|
||||
return row?.access_token ?? null;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const parsed = Body.safeParse(await req.json().catch(() => ({})));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid body", details: parsed.error.flatten() },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const { name, description, visibility, init_readme } = parsed.data;
|
||||
|
||||
const token = await getGithubToken(userId);
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "No GitHub account linked. Sign in with GitHub or use the Connect GitHub button on /control/import.",
|
||||
hasGithub: false,
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Sanitize repo name. GitHub accepts most chars but we slug for predictable URLs.
|
||||
// It also matches what `gh repo create` would produce so existing callers see the same.
|
||||
const repoName = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
|
||||
if (!repoName) {
|
||||
return NextResponse.json({ error: "Name must contain at least one alphanumeric character" }, { status: 400 });
|
||||
}
|
||||
|
||||
const ghRes = await fetch("https://api.github.com/user/repos", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: repoName,
|
||||
description: description ?? `Started from FleetCrown · ${name}`,
|
||||
private: visibility === "private",
|
||||
auto_init: init_readme,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!ghRes.ok) {
|
||||
let detail = "";
|
||||
try {
|
||||
const body = await ghRes.json();
|
||||
detail = body?.errors?.[0]?.message ?? body?.message ?? "";
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
// Most common cases: 422 "name already exists on this account",
|
||||
// 403 token-doesn't-have-repo-scope, 401 expired token.
|
||||
return NextResponse.json(
|
||||
{ error: `GitHub API rejected the create (${ghRes.status})`, detail, status: ghRes.status },
|
||||
{ status: ghRes.status === 422 ? 409 : 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const repo = (await ghRes.json()) as {
|
||||
id: number;
|
||||
name: string;
|
||||
full_name: string;
|
||||
html_url: string;
|
||||
ssh_url: string;
|
||||
clone_url: string;
|
||||
private: boolean;
|
||||
};
|
||||
|
||||
// Now create the FleetCrown project entity. We use the original (un-slugged)
|
||||
// name as the display name; the slugged repo name lives in description.
|
||||
let projectId: string;
|
||||
let projectName: string;
|
||||
try {
|
||||
const project = await createProject(
|
||||
userId,
|
||||
{
|
||||
name,
|
||||
description: `${repo.html_url}${description ? " · " + description : ""}`,
|
||||
},
|
||||
SOURCE_FLEETCROWN_UI,
|
||||
);
|
||||
projectId = project.id;
|
||||
projectName = project.name;
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
// The GitHub repo IS created at this point; we just couldn't add the FC row.
|
||||
// Surface the GitHub URL so the user isn't dead in the water.
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: `Project record could not be created (${msg.includes("duplicate") ? "duplicate name" : "db error"}), but the GitHub repo is live:`,
|
||||
gitUrl: repo.html_url,
|
||||
cloneCmd: `git clone ${repo.ssh_url}`,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
project: { id: projectId, name: projectName },
|
||||
repo: {
|
||||
name: repo.name,
|
||||
full_name: repo.full_name,
|
||||
gitUrl: repo.html_url,
|
||||
sshUrl: repo.ssh_url,
|
||||
cloneUrl: repo.clone_url,
|
||||
private: repo.private,
|
||||
},
|
||||
cloneCmd: `git clone ${repo.ssh_url}`,
|
||||
cloneHttpsCmd: `git clone ${repo.clone_url}`,
|
||||
});
|
||||
}
|
||||
@@ -36,12 +36,13 @@ export function EmptyStateWelcome({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className={`grid gap-3 md:grid-cols-2 ${onBootstrap ? "lg:grid-cols-5" : "lg:grid-cols-4"}`}>
|
||||
{/* TOP CTA when daemon is running: scaffold a brand-new idea end-to-end
|
||||
(AI brief → GitHub repo → local folder → DB row → agent launched).
|
||||
Hidden when runtime is unavailable because /api/project/bootstrap
|
||||
currently requires the local Fleet Runner daemon. */}
|
||||
{onBootstrap && (
|
||||
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-5">
|
||||
{/* TOP CTA: scaffold a brand-new project from an idea. Two modes:
|
||||
- With local runtime: opens BootstrapModal (AI brief → GitHub repo
|
||||
→ local folder → agent launched).
|
||||
- Cloud only: links to /control/new-from-scratch which creates a
|
||||
GitHub repo + FleetCrown row, and tells the user to `git clone`. */}
|
||||
{onBootstrap ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBootstrap}
|
||||
@@ -58,6 +59,23 @@ export function EmptyStateWelcome({
|
||||
Bootstrap →
|
||||
</div>
|
||||
</button>
|
||||
) : (
|
||||
<Link
|
||||
href="/control/new-from-scratch"
|
||||
className="ui-card-shell hover:border-accent transition-colors p-4 flex flex-col gap-2 group"
|
||||
>
|
||||
<Sparkles className="h-5 w-5 text-accent" />
|
||||
<div>
|
||||
<div className="font-medium text-text-primary">Start a new project</div>
|
||||
<div className="text-sm text-text-muted mt-1">
|
||||
Type a name. We create the GitHub repo + project record. You{" "}
|
||||
<code className="px-1 rounded bg-surface-base text-xs">git clone</code> it when you're ready.
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-accent mt-auto pt-2 group-hover:underline">
|
||||
Recommended →
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{/* Primary CTA when daemon offline (and secondary otherwise): import from GitHub. */}
|
||||
|
||||
Reference in new issue
Block a user