Skip to content
  1. Home
  2. workspace
Checking…
Demo view — sanitized data only. Sign in over HTTPS to create projects and manage the workspace.

AI Engineering Workspace

Partial

Chat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.

Project files

read-only

app/src/components/ai-chat.tsx

1"use client";
2import { useCallback, useEffect, useRef, useState } from "react";
3import { Send, Pause, Play, Square, RotateCw, Plus } from "lucide-react";
4
5type Ses = { id: string; title: string; provider: string; model: string; status: string; budget_usd: number; spent_usd: number };
6type Msg = { id: number; role: string; content: string };
7type Run = { id: string; status: string; attempts: number; max_attempts: number; error: string | null; partial?: string; tokens_in: number; tokens_out: number; cost_usd: number } | null;
8let OCM: string[] = [];
9const MODELS: Record<string, string[]> = { anthropic: ["claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-5-5"], openai: ["gpt-4o", "gpt-4o-mini"], mock: ["mock-1"] };
10
11export function AiChat({ configured, mock, signedIn, secure, ocModels = [], defaultEngine = "", projectId = "", projects = [] }: { projects?: { id: string; name: string; engine?: string }[]; configured: string[]; mock: boolean; signedIn: boolean; secure: boolean; ocModels?: string[]; defaultEngine?: string; projectId?: string }) {
12 const [sessions, setSessions] = useState<Ses[]>([]); const [sid, setSid] = useState(""); const [msgs, setMsgs] = useState<Msg[]>([]); const [run, setRun] = useState<Run>(null);
13 const [text, setText] = useState(""); const [err, setErr] = useState(""); const [conn, setConn] = useState("idle"); const [busy, setBusy] = useState(false);
14 OCM = ocModels; MODELS.opencode = ocModels.length ? ocModels : ["opencode/big-pickle"]; const providers = [...configured, ...(ocModels.length ? ["opencode"] : []), ...(mock ? ["mock"] : [])]; const first = providers.includes(defaultEngine) ? defaultEngine : providers[0] ?? "anthropic"; const [prov, setProv] = useState(first); const [model, setModel] = useState(MODELS[first][0]); const [budget, setBudget] = useState("0.5"); const [proj, setProj] = useState(projectId);
15 const es = useRef<EventSource | null>(null); const end = useRef<HTMLDivElement>(null);
16
17 const api = useCallback(async (url: string, init?: RequestInit) => {
18 const r = await fetch(url, { ...init, headers: { "content-type": "application/json" } }); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); return j;
19 }, []);
20 const loadList = useCallback(async () => { try { const l = await api("/api/ai/sessions"); setSessions(l); if (!sid && l[0]) setSid(l[0].id); } catch (e) { setErr((e as Error).message); } }, [api, sid]);
21 const loadSes = useCallback(async (id: string) => { try { const j = await api(`/api/ai/sessions/${id}`); setMsgs(j.messages); setSessions(s => s.map(x => x.id === id ? j.session : x)); setRun(r => r && r.id === j.runs[0]?.id ? r : j.runs[0] ?? null); } catch (e) { setErr((e as Error).message); } }, [api]);
22 useEffect(() => { if (signedIn && secure) void loadList(); }, [signedIn, secure, loadList]);
23 useEffect(() => {
24 if (!sid || !signedIn) return; void loadSes(sid); let closed = false;
25 const open = () => { if (closed) return; const e = new EventSource(`/api/ai/sessions/${sid}/stream`); es.current = e; setConn("live");
26 e.onmessage = ev => { const d = JSON.parse(ev.data); setRun(d.run); setConn("live"); void loadSes(sid); };
27 e.onerror = () => { setConn("reconnecting"); e.close(); setTimeout(open, 1500); }; }; // durable state lives in Postgres; reconnect just re-reads it
28 open(); return () => { closed = true; es.current?.close(); };
29 }, [sid, signedIn, loadSes]);
30 useEffect(() => { end.current?.scrollIntoView({ block: "nearest" }); }, [msgs.length, run?.partial]);
31
32 const create = async () => { setErr(""); try { const j = await api("/api/ai/sessions", { method: "POST", body: JSON.stringify({ provider: prov, model, budget_usd: Number(budget), title: `${prov} session`, project_id: proj || undefined }) }); await loadList(); setSid(j.id); } catch (e) { setErr((e as Error).message); } };
33 const send = async () => { if (!text.trim() || !sid) return; setBusy(true); setErr(""); try { await api(`/api/ai/sessions/${sid}/messages`, { method: "POST", body: JSON.stringify({ content: text }) }); setText(""); await loadSes(sid); } catch (e) { setErr((e as Error).message); } setBusy(false); };
34 const ctl = async (action: string) => { setErr(""); try { await api(`/api/ai/sessions/${sid}/control`, { method: "POST", body: JSON.stringify({ action }) }); } catch (e) { setErr((e as Error).message); } };
35 const ses = sessions.find(s => s.id === sid); const active = run && ["queued", "running", "paused"].includes(run.status);
36
37 if (!secure) return <div className="p-4 text-sm text-muted">AI sessions require an HTTPS sign-in. Plain HTTP is read-only by design.</div>;
38 if (!signedIn) return <div className="p-4 text-sm text-muted">Sign in to start AI sessions.</div>;
39 return <div className="flex min-h-[22rem] flex-col" data-testid="ai-chat">
40 <div className="flex flex-wrap items-center gap-2 border-b border-line p-3 text-sm">
41 <select className="input !w-auto min-w-0 flex-1" aria-label="Session" value={sid} onChange={e => setSid(e.target.value)}><option value="">{sessions.length ? "Select session…" : "No sessions yet"}</option>{sessions.map(s => <option key={s.id} value={s.id}>{s.title} · {s.model}</option>)}</select>
42 <span className="text-xs text-muted" aria-live="polite">{conn}</span></div>
43 {providers.length === 0 && <div className="m-3 rounded-lg bg-[var(--warn-bg)] p-3 text-sm text-[var(--warn)]">Awaiting credentials: add an Anthropic or OpenAI API key under Integrations. No live model has been called.</div>}
44 <details className="border-b border-line p-3 text-sm" open={!sid}><summary className="cursor-pointer text-muted"><Plus size={13} className="mr-1 inline" />New session</summary>
45 <div className="mt-2 grid gap-2 sm:grid-cols-5"><select className="input" aria-label="Provider" value={prov} onChange={e => { setProv(e.target.value); setModel(MODELS[e.target.value][0]); }}>{["anthropic", "openai", "opencode", ...(mock ? ["mock"] : [])].map(p => <option key={p} value={p}>{p === "mock" ? "mock (test double)" : p}{p === "opencode" ? (ocModels.length ? " (free models)" : " — not installed") : p !== "mock" && !configured.includes(p) ? " — no key" : ""}</option>)}</select>
46 <select className="input" aria-label="Model" value={model} onChange={e => setModel(e.target.value)}>{MODELS[prov].map(m => <option key={m}>{m}</option>)}</select>
47 <select className="input" aria-label="Project (optional)" value={proj} onChange={e => { setProj(e.target.value); const pe = projects.find(x => x.id === e.target.value)?.engine; if (pe && providers.includes(pe)) { setProv(pe); setModel(MODELS[pe][0]); } }}><option value="">No project</option>{projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}</select>
48 <input className="input" aria-label="Budget USD" inputMode="decimal" value={budget} onChange={e => setBudget(e.target.value)} placeholder="Budget $" />
49 <button className="btn btn-primary" onClick={create}>Create</button></div></details>
50 <div className="flex-1 space-y-3 overflow-auto p-4 text-sm" style={{ maxHeight: "28rem" }} aria-live="polite">
51 {msgs.map(m => <div key={m.id} className={`max-w-[92%] whitespace-pre-wrap rounded-lg p-3 ${m.role === "user" ? "ml-auto bg-accentsoft text-accent" : "bg-surface2"}`}><div className="mb-1 text-xs font-medium opacity-70">{m.role}</div>{m.content}</div>)}
52 {run && active && <div className="max-w-[92%] whitespace-pre-wrap rounded-lg bg-surface2 p-3"><div className="mb-1 text-xs font-medium opacity-70">assistant · {run.status} · attempt {run.attempts}/{run.max_attempts}</div>{run.partial || "…"}</div>}
53 {run?.status === "failed" && <div className="rounded-lg bg-[var(--err-bg)] p-3 text-[var(--err)]">Run failed: {run.error}</div>}
54 <div ref={end} /></div>
55 {err && <div role="alert" className="mx-3 mb-2 rounded bg-[var(--err-bg)] px-3 py-2 text-sm text-[var(--err)]">{err}</div>}
56 <div className="border-t border-line p-3"><div className="flex gap-2"><textarea className="input min-h-10 flex-1" aria-label="Prompt input" rows={2} value={text} disabled={!sid || !!active} onChange={e => setText(e.target.value)} placeholder={sid ? "Message the agent (chat only — no tools or shell)" : "Create or select a session first"} onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void send(); }} />
57 <button className="btn btn-primary btn-sm self-end" aria-label="Send" disabled={!sid || !!active || busy || !text.trim()} onClick={send}><Send size={14} /></button></div>
58 <div className="mt-2 flex flex-wrap items-center gap-1.5"><button className="btn btn-sm" disabled={run?.status !== "running" && run?.status !== "queued"} onClick={() => ctl("pause")}><Pause size={13} />Pause</button>
59 <button className="btn btn-sm" disabled={run?.status !== "paused"} onClick={() => ctl("resume")}><Play size={13} />Resume</button>
60 <button className="btn btn-sm" disabled={!active && run?.status !== "failed"} onClick={() => ctl("cancel")}><Square size={13} />Cancel</button>
61 <button className="btn btn-sm" disabled={run?.status !== "failed"} onClick={() => ctl("retry")}><RotateCw size={13} />Retry</button>
62 {ses && <span className="ml-auto text-xs text-muted">${Number(ses.spent_usd).toFixed(4)} / ${Number(ses.budget_usd)} · {ses.provider === "mock" ? "test double" : "estimate"}</span>}</div></div></div>;
63}
64

Conversation

Partial
Sign in to start AI sessions.

Task checklist

  • Application shell deployed
  • Persistent projects
  • Agent runtime
  • Sandboxed terminal

Execution activity

No agent sessions. Git HEAD 1c27633 on master.

Approval requests

None pending.