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
15 changes: 15 additions & 0 deletions cmd/bootagent-desktop/core_e2e.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
Expand Down Expand Up @@ -104,6 +105,20 @@ func (r *e2eRunner) Run(_ context.Context, argv []string, _ map[string]string, _
return result, nil
}

// RunPrivateInput plays an Agent given a task on stdin. The first task is the
// only caller that sets a working directory, and what it checks afterwards is
// that a page exists there.
func (r *e2eRunner) RunPrivateInput(ctx context.Context, argv []string, _ map[string]string, _ time.Duration, _ string) (process.Result, error) {
result := process.Result{Args: append([]string(nil), argv...), ExitCode: 0}
if directory := process.WorkingDirectory(ctx); directory != "" {
if err := os.WriteFile(filepath.Join(directory, "index.html"), []byte("<!doctype html><title>BootAgent e2e</title>"), 0o600); err != nil {
return result, err
}
result.Stdout = "Created index.html\n"
}
return result, nil
}

type e2eProviderDoer struct{}

func (e2eProviderDoer) Do(request *http.Request) (*http.Response, error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export type {
DesktopAgentProfileResult,
DesktopAgentStatus,
DetectedConfig,
FirstTaskAgent,
FirstTaskRequest,
FirstTaskResult,
InstallRuntimeResult,
InstalledMultimodal,
MCPAgentApplyResult,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,29 @@ export interface DetectedConfig {
"unreadable": string | null;
}

export interface FirstTaskAgent {
"id": string;
"name": string;
}

export interface FirstTaskRequest {
"agent_id": string;
"locale": string;
}

/**
* FirstTaskResult describes a run that started. OK is false when the Agent
* failed or wrote nothing, and Directory is empty then: an empty directory is
* removed rather than reported.
*/
export interface FirstTaskResult {
"agent_id": string;
"ok": boolean;
"directory": string;
"files": string[] | null;
"log": string;
}

/**
* InstallRuntimeResult reports what the bootstrap did. PathUpdated is separate
* from Installed because an already-downloaded runtime may still need its
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ export function ActivateWithConversion(request: $models.AgentConversionRequest):
return $Call.ByID(3840302198, request);
}

/**
* FirstTaskAgents lists the installed Agents RunFirstTask can drive unattended.
*/
export function FirstTaskAgents(): $CancellablePromise<app$0.FirstTaskAgent[] | null> {
return $Call.ByID(1312481620);
}

export function Install(request: $models.InstallRequest): $CancellablePromise<$models.InstallResponse> {
return $Call.ByID(1289781782, request);
}
Expand All @@ -46,6 +53,15 @@ export function PreviewUninstall(request: $models.UpdateRequest): $CancellablePr
return $Call.ByID(224864709, request);
}

/**
* RunFirstTask has an Agent write a small page in a temporary directory of its
* own. It is a billed request to the Agent's model, so the UI calls it only from
* a button the user pressed.
*/
export function RunFirstTask(request: app$0.FirstTaskRequest): $CancellablePromise<app$0.FirstTaskResult> {
return $Call.ByID(1393373323, request);
}

export function Uninstall(request: $models.UpdateRequest): $CancellablePromise<app$0.AgentUninstallResult> {
return $Call.ByID(67868259, request);
}
Expand Down
10 changes: 10 additions & 0 deletions frontend/e2e/wails.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ test("onboarding installs one Agent end to end and writes its Profile", async ({
await page.getByRole("button", { name: "开始安装" }).click();

await expect(page.getByRole("heading", { name: "安装完成" })).toBeVisible({ timeout: 60_000 });

// The Agent just installed is offered one small task. The test build's runner
// plays the Agent, so what this covers is the path from the button to the
// page it names: the binding, the temporary directory and the file listing.
await expect(page.getByRole("heading", { name: "跑一个小任务试试" })).toBeVisible();
await page.getByRole("button", { name: "开始", exact: true }).click();
await expect(page.getByRole("status").filter({ hasText: "Codex 写好了" })).toBeVisible();
await expect(page.getByRole("list", { name: "生成的文件" })).toHaveText("index.html");
await expect(page.locator(".first-task-output code")).toContainText("bootagent-first-task-");

await page.getByRole("button", { name: "进入总览" }).click();

await expect(page.getByRole("heading", { name: "环境总览" })).toBeVisible();
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/backend/wails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ export const wailsApi = {
call(() => AgentService.ActivateWithConversion({ agent_id: agentId, profile_id: profileId })) as CancellableRequest<import("../types/api").AgentConversionResponse>,
launchAgent: (agentId: string, workingDirectory = ""): Promise<LaunchAgentResponse> =>
call(() => AgentService.Launch({ agent_id: agentId, working_directory: workingDirectory })) as Promise<LaunchAgentResponse>,
firstTaskAgents: (): Promise<import("../types/api").FirstTaskAgent[]> =>
call(() => AgentService.FirstTaskAgents()).then((agents) => agents ?? []),
runFirstTask: (agentId: string, locale: string): CancellableRequest<import("../types/api").FirstTaskResult> =>
call(() => AgentService.RunFirstTask({ agent_id: agentId, locale })) as CancellableRequest<import("../types/api").FirstTaskResult>,
migrateConversations: (): Promise<import("../types/api").ConversationMigrationResult> =>
call(() => AgentService.MigrateConversations()) as Promise<import("../types/api").ConversationMigrationResult>,
uninstallAgent: (agentId: string, allowCrossEnvironment = false, installationId = "", installationIds: string[] = [], removeUserData = false): CancellableRequest<AgentUninstallResult> =>
Expand Down
99 changes: 99 additions & 0 deletions frontend/src/components/FirstTaskSection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";

import { api } from "../backend/api";
import { BootAgentApiError } from "../backend/errors";
import type { FirstTaskResult } from "../types/api";
import { FirstTaskSection } from "./FirstTaskSection";

const DIRECTORY = "/tmp/bootagent-first-task-123";

function result(overrides: Partial<FirstTaskResult> = {}): FirstTaskResult {
return { agent_id: "codex", ok: true, directory: DIRECTORY, files: ["index.html"], log: "Created index.html", ...overrides };
}

async function renderSection(agentId = "codex") {
vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]);
const page = render(<MemoryRouter><FirstTaskSection agentId={agentId} /></MemoryRouter>);
await waitFor(() => expect(api.firstTaskAgents).toHaveBeenCalled());
return page;
}

describe("FirstTaskSection", () => {
afterEach(() => vi.restoreAllMocks());

it("is absent for an Agent that cannot run unattended", async () => {
const run = vi.spyOn(api, "runFirstTask");
const { container } = await renderSection("opencode");

expect(container.innerHTML).toBe("");
expect(run).not.toHaveBeenCalled();
});

// The run is a billed request to the user's own Provider. It has to be said
// before the button, and nothing may be sent until the button is pressed.
it("says the run is billed and waits to be asked", async () => {
const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result());
await renderSection();

const start = await screen.findByRole("button", { name: "开始" });
expect(screen.getByText(/真实的模型调用,由模型服务按它的价格计费/)).toBeTruthy();
expect(screen.getByText(/只会写入这个目录/)).toBeTruthy();
expect(run).not.toHaveBeenCalled();

fireEvent.click(start);
expect(run).toHaveBeenCalledTimes(1);
expect(run).toHaveBeenCalledWith("codex", "zh-CN");
});

it("shows where the page is and what was written", async () => {
vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ files: ["assets/style.css", "index.html"] }));
await renderSection();
fireEvent.click(await screen.findByRole("button", { name: "开始" }));

expect((await screen.findByRole("status")).textContent).toContain("Codex 写好了");
expect(screen.getByText(DIRECTORY)).toBeTruthy();
expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["assets/style.css", "index.html"]);
// The record is there, behind a disclosure rather than poured onto the page.
expect(screen.queryByText("Created index.html")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: /查看运行记录/ }));
expect(screen.getByText("Created index.html")).toBeTruthy();
});

it("offers a next step when the Agent wrote nothing", async () => {
const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false, directory: "", files: [], log: "401 Unauthorized" }));
await renderSection();
fireEvent.click(await screen.findByRole("button", { name: "开始" }));

expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有写出任何文件");
expect(screen.getByRole("button", { name: "检查模型服务" })).toBeTruthy();
// The reason is in the record, so a failure opens it without being asked.
expect(screen.getByText("401 Unauthorized")).toBeTruthy();

fireEvent.click(screen.getByRole("button", { name: "重试" }));
expect(run).toHaveBeenCalledTimes(2);
});

// Files exist, so they are shown, but the Agent did not finish cleanly and the
// page may be half written. Calling that a success would misreport it.
it("keeps the files of a run that ended badly without calling it done", async () => {
vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false }));
await renderSection();
fireEvent.click(await screen.findByRole("button", { name: "开始" }));

expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有正常结束");
expect(screen.getByText(DIRECTORY)).toBeTruthy();
expect(screen.queryByRole("status")).toBeNull();
});

it("reports a run that could not start", async () => {
vi.spyOn(api, "runFirstTask").mockRejectedValue(new BootAgentApiError("The selected Agent is not installed", "PREREQUISITE_MISSING", false, 400));
await renderSection();
fireEvent.click(await screen.findByRole("button", { name: "开始" }));

expect(await screen.findByRole("alert")).toBeTruthy();
expect(screen.getByRole("button", { name: "重试" })).toBeTruthy();
expect(screen.queryByRole("status")).toBeNull();
});
});
121 changes: 121 additions & 0 deletions frontend/src/components/FirstTaskSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { Copy, ExternalLink, Play, RefreshCw } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";

import { api, failureLine, isCancellationError } from "../backend/api";
import { useI18n } from "../i18n";
import type { FirstTaskResult } from "../types/api";
import { copyToClipboard } from "../utils/clipboard";
import { LogDisclosure } from "./LogDisclosure";

/**
* Offers one small, real task to an Agent that has just been installed: it
* writes a page in a temporary directory of its own. Rendered only for Agents
* the backend can drive unattended, so it is absent rather than disabled for
* the rest.
*
* Nothing is sent until the button is pressed: the run is a billed request.
*/
export function FirstTaskSection({ agentId }: { agentId: string }) {
const { t, locale } = useI18n();
const navigate = useNavigate();
// Empty until the backend confirms it can drive this Agent, and then its name.
const [agentName, setAgentName] = useState("");
const [running, setRunning] = useState(false);
const [result, setResult] = useState<FirstTaskResult | null>(null);
const [failure, setFailure] = useState("");
const [copied, setCopied] = useState(false);
const request = useRef<ReturnType<typeof api.runFirstTask> | null>(null);

useEffect(() => {
let active = true;
void api.firstTaskAgents()
.then((agents) => { if (active) setAgentName(agents.find((agent) => agent.id === agentId)?.name ?? ""); })
.catch(() => {});
return () => { active = false; };
}, [agentId]);
// Leaving the page ends the run: nobody would see its result, and it would
// keep spending on the user's account.
useEffect(() => () => { void request.current?.cancel?.(); }, []);

if (!agentName) return null;

const run = async () => {
setRunning(true);
setResult(null);
setFailure("");
setCopied(false);
const pending = api.runFirstTask(agentId, locale);
request.current = pending;
try {
setResult(await pending);
} catch (error) {
if (!isCancellationError(error)) setFailure(failureLine(error, t("小任务没能运行"), t));
} finally {
request.current = null;
setRunning(false);
}
};

const files = result?.files ?? [];
const problem = failure
|| (result && !result.ok
? files.length
? t("{agent} 没有正常结束,下面的文件可能不完整", { agent: agentName })
: t("{agent} 没有写出任何文件", { agent: agentName })
: "");
const finished = Boolean(result || failure);

return (
<section className="first-task-section">
<h2>{t("跑一个小任务试试")}</h2>
<p>{t("让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费", { agent: agentName })}</p>
{result?.ok ? (
<div className="notice notice-success" role="status">
<span>{t("{agent} 写好了,文件在下面这个目录", { agent: agentName })}</span>
</div>
) : null}
{problem ? <div className="notice notice-error" role="alert"><span>{problem}</span></div> : null}
{result?.directory ? (
<div className="first-task-output">
<code>{result.directory}</code>
<button className="button button-secondary" type="button" onClick={() => void copyToClipboard(result.directory).then(setCopied)}>
<Copy size={15} aria-hidden="true" />
{copied ? t("已复制") : t("复制路径")}
</button>
<ul aria-label={t("生成的文件")}>
{files.map((file) => <li key={file}>{file}</li>)}
</ul>
</div>
) : null}
<div className="first-task-actions">
{running ? (
<>
<button className="button button-primary" type="button" disabled>
<RefreshCw size={15} className="spin" aria-hidden="true" />
{t("正在运行,通常需要一两分钟")}
</button>
<button className="button button-secondary" type="button" onClick={() => void request.current?.cancel?.()}>{t("取消")}</button>
</>
) : !finished ? (
<button className="button button-primary" type="button" onClick={() => void run()}>
<Play size={15} aria-hidden="true" />
{t("开始")}
</button>
) : problem ? (
<>
<button className="button button-primary" type="button" onClick={() => void run()}>
<RefreshCw size={15} aria-hidden="true" />
{t("重试")}
</button>
<button className="button button-secondary" type="button" onClick={() => navigate("/providers")}>
<ExternalLink size={15} aria-hidden="true" />
{t("检查模型服务")}
</button>
</>
) : null}
</div>
{result?.log ? <LogDisclosure log={result.log} open={!result.ok} label={t("查看运行记录")} /> : null}
</section>
);
}
4 changes: 2 additions & 2 deletions frontend/src/components/LogDisclosure.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect, useState } from "react";

import { useI18n } from "../i18n";

export function LogDisclosure({ log, open: openByParent = false, showEmpty = false }: { log: string; open?: boolean; showEmpty?: boolean }) {
export function LogDisclosure({ log, open: openByParent = false, showEmpty = false, label }: { log: string; open?: boolean; showEmpty?: boolean; label?: string }) {
const { t } = useI18n();
const [open, setOpen] = useState(openByParent);
useEffect(() => {
Expand All @@ -14,7 +14,7 @@ export function LogDisclosure({ log, open: openByParent = false, showEmpty = fal
<section className={`log-disclosure${open ? " is-open" : ""}`}>
<button type="button" onClick={() => setOpen((value) => !value)} aria-expanded={open}>
<TerminalSquare size={17} />
{t("查看安装日志")}
{label ?? t("查看安装日志")}
<ChevronDown size={17} />
</button>
{open ? <pre>{log}</pre> : null}
Expand Down
Loading
Loading