Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"bundle:sim:sourcemap": "deno run -A scripts/bundle_simulator_ui.ts --sourcemap=external",
"bundle:sim:web": "deno run -A scripts/bundle_simulator_ui.ts --platform=browser",
"bundle:sim:web:sourcemap": "deno run -A scripts/bundle_simulator_ui.ts --platform=browser --sourcemap=external",
"serve:bot": "mkdir -p /tmp/gambit-bot-root && GAMBIT_BOT_ROOT=/tmp/gambit-bot-root deno run -A src/cli.ts serve src/decks/gambit-bot/PROMPT.md --bundle --port 8000",
"serve:bot:sandbox": "deno run -A scripts/serve_bot_sandbox.ts",
"build_npm": "deno run -A scripts/build_npm.ts"
},
"lint": {
Expand Down
4 changes: 4 additions & 0 deletions docs/external/reference/cli/commands/serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ flags = [
+++

Starts the debug UI server (default at `http://localhost:8000/`).

If no deck path is provided, Gambit creates a new workspace scaffold (root
`PROMPT.md`, `INTENT.md`, plus default scenario/grader decks) and opens the
simulator UI in workspace onboarding mode.
91 changes: 91 additions & 0 deletions scripts/serve_bot_sandbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/env -S deno run -A

import { copy, ensureDir } from "@std/fs";
import * as path from "@std/path";

const DEFAULT_NUX_DEMO_DECK_RELATIVE =
"src/decks/demo/nux_from_scratch/root.deck.md";

function resolveSourceDeckPath(opts: {
repoRoot: string;
gambitPackageRoot: string;
}): string {
const override = Deno.env.get("GAMBIT_NUX_DEMO_DECK_PATH")?.trim();
const fallback = path.resolve(
opts.gambitPackageRoot,
DEFAULT_NUX_DEMO_DECK_RELATIVE,
);
if (!override) {
return fallback;
}
return path.isAbsolute(override)
? override
: path.resolve(opts.repoRoot, override);
}

async function prepareSandboxDeck(opts: {
sourceDeckPath: string;
sandboxRoot: string;
}): Promise<string> {
const sourceDeckPath = path.resolve(opts.sourceDeckPath);
const sourceDir = path.dirname(sourceDeckPath);
const sourceInfo = await Deno.stat(sourceDeckPath);
if (!sourceInfo.isFile) {
throw new Error(`Demo deck path is not a file: ${sourceDeckPath}`);
}

await Deno.remove(opts.sandboxRoot, { recursive: true }).catch(() => {});
await ensureDir(opts.sandboxRoot);
await copy(sourceDir, opts.sandboxRoot, { overwrite: true });

const relativeDeckPath = path.relative(sourceDir, sourceDeckPath);
const sandboxDeckPath = path.join(opts.sandboxRoot, relativeDeckPath);
await Deno.stat(sandboxDeckPath);
return sandboxDeckPath;
}

async function main(): Promise<void> {
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
const repoRoot = path.resolve(moduleDir, "..", "..", "..");
const gambitPackageRoot = path.resolve(repoRoot, "packages", "gambit");
const sandboxRoot = Deno.env.get("GAMBIT_SANDBOX_ROOT")?.trim() ||
"/tmp/gambit-bot-sandbox";
const port = Deno.env.get("GAMBIT_SANDBOX_PORT")?.trim() || "8000";

const sourceDeckPath = resolveSourceDeckPath({
repoRoot,
gambitPackageRoot,
});
const sandboxDeckPath = await prepareSandboxDeck({
sourceDeckPath,
sandboxRoot,
});
Deno.env.set("GAMBIT_SIMULATOR_BUILD_BOT_ROOT", sandboxRoot);

const cmd = new Deno.Command("deno", {
args: [
"run",
"-A",
"src/cli.ts",
"serve",
sandboxDeckPath,
"--bundle",
"--port",
port,
],
cwd: gambitPackageRoot,
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
});

const child = cmd.spawn();
const status = await child.status;
if (!status.success) {
Deno.exit(status.code ?? 1);
}
}

if (import.meta.main) {
await main();
}
30 changes: 28 additions & 2 deletions simulator-ui/demo/gambit-build-tab-demo-timeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { DemoTimelineStep } from "./gambit-ui-demo-timeline.ts";

export function buildTabDemoTimeline(opts: {
userPrompts: Array<string>;
scenarioLabels?: Array<string>;
}): DemoTimelineStep[] {
const beatOpenBuild: DemoTimelineStep[] = [
{ type: "wait-for", selector: '[data-testid="nav-build"]' },
Expand Down Expand Up @@ -113,11 +114,36 @@ export function buildTabDemoTimeline(opts: {
{ type: "screenshot", label: "04-build-recent-changes" },
];

const beatCheckTabs: DemoTimelineStep[] = [
const beatCheckTabs: DemoTimelineStep[] = [];
beatCheckTabs.push(
{ type: "click", selector: '[data-testid="nav-test"]' },
{ type: "wait-for", selector: '[data-testid="testbot-run"]' },
{ type: "wait", ms: 400 },
{ type: "screenshot", label: "04-test-tab" },
);
const scenarioLabels = (opts.scenarioLabels ?? []).filter((label) =>
label.trim().length > 0
);
if (scenarioLabels.length > 0) {
scenarioLabels.forEach((label, index) => {
beatCheckTabs.push(
{ type: "click", selector: ".gds-listbox-trigger" },
{ type: "wait-for", selector: ".gds-listbox-popover" },
{ type: "click", text: label },
{ type: "wait", ms: 200 },
{ type: "click", selector: '[data-testid="testbot-run"]' },
{
type: "wait-for",
selector: '[data-testid="testbot-status"]',
text: "Completed",
timeoutMs: 180_000,
},
{ type: "wait", ms: 200 },
{ type: "screenshot", label: `04-test-run-${index + 1}` },
);
});
}
beatCheckTabs.push(
{ type: "click", selector: '[data-testid="nav-grade"]' },
{ type: "wait-for", text: "Run a grader" },
{ type: "wait", ms: 400 },
Expand All @@ -126,7 +152,7 @@ export function buildTabDemoTimeline(opts: {
{ type: "wait-for", selector: '[data-testid="build-chat-input"]' },
{ type: "wait", ms: 400 },
{ type: "screenshot", label: "06-build-tab-return" },
];
);

return [
...beatOpenBuild,
Expand Down
120 changes: 82 additions & 38 deletions simulator-ui/src/BuildChatContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,13 @@ type BuildChatContextValue = {
const BuildChatContext = createContext<BuildChatContextValue | null>(null);

export function BuildChatProvider(
props: { children: React.ReactNode },
props: {
children: React.ReactNode;
workspaceId?: string | null;
onWorkspaceChange?: (workspaceId: string) => void;
},
) {
const { children } = props;
const { children, workspaceId, onWorkspaceChange } = props;
const [run, setRun] = useState<BuildRun>({
id: "",
status: "idle",
Expand All @@ -92,8 +96,10 @@ export function BuildChatProvider(
{ runId: string; turn: number; text: string } | null
>(null);

const refreshStatus = useCallback(async (opts?: { runId?: string }) => {
const query = opts?.runId ? `?runId=${encodeURIComponent(opts.runId)}` : "";
const refreshStatus = useCallback(async (opts?: { workspaceId?: string }) => {
const query = opts?.workspaceId
? `?workspaceId=${encodeURIComponent(opts.workspaceId)}`
: "";
const res = await fetch(`/api/build/status${query}`);
const data = await res.json().catch(() => ({})) as { run?: BuildRun };
if (data.run) {
Expand All @@ -107,11 +113,31 @@ export function BuildChatProvider(
runIdRef.current = data.run.id;
}
}
}, []);
}, [onWorkspaceChange]);

useEffect(() => {
if (workspaceId) {
runIdRef.current = workspaceId;
refreshStatus({ workspaceId }).catch(() => {});
return;
}
refreshStatus().catch(() => {});
}, [refreshStatus]);
}, [refreshStatus, workspaceId]);

useEffect(() => {
if (!workspaceId) return;
if (runIdRef.current === workspaceId) return;
runIdRef.current = workspaceId;
setRun((prev) => ({
...prev,
id: workspaceId,
}));
setChatError(null);
setStreamingAssistant(null);
setOptimisticUser(null);
setToolCallsOpen({});
refreshStatus({ workspaceId }).catch(() => {});
}, [refreshStatus, workspaceId]);

useEffect(() => {
const streamId = BUILD_STREAM_ID;
Expand Down Expand Up @@ -182,60 +208,75 @@ export function BuildChatProvider(
[run.traces],
);

const ensureRunId = useCallback(() => {
const ensureWorkspaceId = useCallback(async () => {
if (workspaceId) return workspaceId;
if (runIdRef.current) return runIdRef.current;
const next = `build-ui-${crypto.randomUUID()}`;
runIdRef.current = next;
setRun((prev) => ({ ...prev, id: next }));
return next;
}, []);
try {
const res = await fetch("/api/workspace/new", {
method: "POST",
});
const data = await res.json().catch(() => ({})) as {
workspaceId?: string;
};
if (res.ok && typeof data.workspaceId === "string") {
const nextWorkspaceId = data.workspaceId;
runIdRef.current = nextWorkspaceId;
setRun((prev) => ({ ...prev, id: nextWorkspaceId }));
onWorkspaceChange?.(nextWorkspaceId);
return nextWorkspaceId;
}
} catch {
// ignore
}
const fallback = `workspace-${crypto.randomUUID()}`;
runIdRef.current = fallback;
setRun((prev) => ({ ...prev, id: fallback }));
return fallback;
}, [onWorkspaceChange, workspaceId]);

const resetChat = useCallback(async () => {
const runId = runIdRef.current;
if (!runId) {
const res = await fetch("/api/workspace/new", { method: "POST" }).catch(
() => null,
);
const data = res
? await res.json().catch(() => ({})) as { workspaceId?: string }
: {};
if (res && res.ok && typeof data.workspaceId === "string") {
runIdRef.current = data.workspaceId;
setRun({
id: data.workspaceId,
status: "idle",
messages: [],
traces: [],
toolInserts: [],
});
onWorkspaceChange?.(data.workspaceId);
} else {
runIdRef.current = "";
setRun({
id: "",
status: "idle",
messages: [],
traces: [],
toolInserts: [],
});
setChatDraft("");
setChatError(null);
setStreamingAssistant(null);
setOptimisticUser(null);
setToolCallsOpen({});
return;
}
await fetch("/api/build/reset", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ runId }),
}).catch(() => {});
runIdRef.current = "";
setRun({
id: "",
status: "idle",
messages: [],
traces: [],
toolInserts: [],
});
setChatDraft("");
setChatError(null);
setStreamingAssistant(null);
setOptimisticUser(null);
setToolCallsOpen({});
}, []);
}, [onWorkspaceChange]);

const sendMessage = useCallback(async (message: string) => {
const runId = ensureRunId();
const runId = await ensureWorkspaceId();
setChatSending(true);
setChatError(null);
try {
const res = await fetch("/api/build/message", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ runId, message }),
body: JSON.stringify({ workspaceId: runId, message }),
});
const data = await res.json().catch(() => ({})) as {
run?: BuildRun;
Expand All @@ -260,7 +301,7 @@ export function BuildChatProvider(
} finally {
setChatSending(false);
}
}, [ensureRunId]);
}, [ensureWorkspaceId]);

const loadChat = useCallback(async (runId: string) => {
setChatSending(true);
Expand All @@ -269,7 +310,7 @@ export function BuildChatProvider(
const res = await fetch("/api/build/load", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ runId }),
body: JSON.stringify({ workspaceId: runId }),
});
const data = await res.json().catch(() => ({})) as {
run?: BuildRun;
Expand All @@ -290,6 +331,9 @@ export function BuildChatProvider(
if (typeof data.run.id === "string" && data.run.id) {
runIdRef.current = data.run.id;
}
if (typeof data.run.id === "string" && data.run.id) {
onWorkspaceChange?.(data.run.id);
}
setChatDraft("");
setOptimisticUser(null);
setStreamingAssistant(null);
Expand Down
Loading