diff --git a/cmd/bootagent-desktop/core_e2e.go b/cmd/bootagent-desktop/core_e2e.go
index 74e7ba18..3f0254d0 100644
--- a/cmd/bootagent-desktop/core_e2e.go
+++ b/cmd/bootagent-desktop/core_e2e.go
@@ -6,6 +6,7 @@ import (
"context"
"io"
"net/http"
+ "os"
"path/filepath"
"strings"
"sync"
@@ -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("
BootAgent e2e "), 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) {
diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts
index f1594f45..ac238d73 100644
--- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts
+++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts
@@ -16,6 +16,9 @@ export type {
DesktopAgentProfileResult,
DesktopAgentStatus,
DetectedConfig,
+ FirstTaskAgent,
+ FirstTaskRequest,
+ FirstTaskResult,
InstallRuntimeResult,
InstalledMultimodal,
MCPAgentApplyResult,
diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts
index 56d071e3..219b6ceb 100644
--- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts
+++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts
@@ -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
diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts
index 06dc21ad..1a751f15 100644
--- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts
+++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts
@@ -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 {
+ return $Call.ByID(1312481620);
+}
+
export function Install(request: $models.InstallRequest): $CancellablePromise<$models.InstallResponse> {
return $Call.ByID(1289781782, request);
}
@@ -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 {
+ return $Call.ByID(1393373323, request);
+}
+
export function Uninstall(request: $models.UpdateRequest): $CancellablePromise {
return $Call.ByID(67868259, request);
}
diff --git a/frontend/e2e/wails.spec.ts b/frontend/e2e/wails.spec.ts
index 2995bd52..93c32aff 100644
--- a/frontend/e2e/wails.spec.ts
+++ b/frontend/e2e/wails.spec.ts
@@ -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();
diff --git a/frontend/src/backend/wails.ts b/frontend/src/backend/wails.ts
index 428a8539..ec2f5820 100644
--- a/frontend/src/backend/wails.ts
+++ b/frontend/src/backend/wails.ts
@@ -237,6 +237,10 @@ export const wailsApi = {
call(() => AgentService.ActivateWithConversion({ agent_id: agentId, profile_id: profileId })) as CancellableRequest,
launchAgent: (agentId: string, workingDirectory = ""): Promise =>
call(() => AgentService.Launch({ agent_id: agentId, working_directory: workingDirectory })) as Promise,
+ firstTaskAgents: (): Promise =>
+ call(() => AgentService.FirstTaskAgents()).then((agents) => agents ?? []),
+ runFirstTask: (agentId: string, locale: string): CancellableRequest =>
+ call(() => AgentService.RunFirstTask({ agent_id: agentId, locale })) as CancellableRequest,
migrateConversations: (): Promise =>
call(() => AgentService.MigrateConversations()) as Promise,
uninstallAgent: (agentId: string, allowCrossEnvironment = false, installationId = "", installationIds: string[] = [], removeUserData = false): CancellableRequest =>
diff --git a/frontend/src/components/FirstTaskSection.test.tsx b/frontend/src/components/FirstTaskSection.test.tsx
new file mode 100644
index 00000000..876ad213
--- /dev/null
+++ b/frontend/src/components/FirstTaskSection.test.tsx
@@ -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 {
+ 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( );
+ 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();
+ });
+});
diff --git a/frontend/src/components/FirstTaskSection.tsx b/frontend/src/components/FirstTaskSection.tsx
new file mode 100644
index 00000000..0fd185f2
--- /dev/null
+++ b/frontend/src/components/FirstTaskSection.tsx
@@ -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(null);
+ const [failure, setFailure] = useState("");
+ const [copied, setCopied] = useState(false);
+ const request = useRef | 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 (
+
+ {t("跑一个小任务试试")}
+ {t("让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费", { agent: agentName })}
+ {result?.ok ? (
+
+ {t("{agent} 写好了,文件在下面这个目录", { agent: agentName })}
+
+ ) : null}
+ {problem ? {problem}
: null}
+ {result?.directory ? (
+
+
{result.directory}
+
void copyToClipboard(result.directory).then(setCopied)}>
+
+ {copied ? t("已复制") : t("复制路径")}
+
+
+ {files.map((file) => {file} )}
+
+
+ ) : null}
+
+ {running ? (
+ <>
+
+
+ {t("正在运行,通常需要一两分钟")}
+
+
void request.current?.cancel?.()}>{t("取消")}
+ >
+ ) : !finished ? (
+
void run()}>
+
+ {t("开始")}
+
+ ) : problem ? (
+ <>
+
void run()}>
+
+ {t("重试")}
+
+
navigate("/providers")}>
+
+ {t("检查模型服务")}
+
+ >
+ ) : null}
+
+ {result?.log ? : null}
+
+ );
+}
diff --git a/frontend/src/components/LogDisclosure.tsx b/frontend/src/components/LogDisclosure.tsx
index 26422610..7cf6fb3c 100644
--- a/frontend/src/components/LogDisclosure.tsx
+++ b/frontend/src/components/LogDisclosure.tsx
@@ -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(() => {
@@ -14,7 +14,7 @@ export function LogDisclosure({ log, open: openByParent = false, showEmpty = fal
setOpen((value) => !value)} aria-expanded={open}>
- {t("查看安装日志")}
+ {label ?? t("查看安装日志")}
{open ? {log} : null}
diff --git a/frontend/src/components/SelectField.test.tsx b/frontend/src/components/SelectField.test.tsx
index f999b31e..55f698a0 100644
--- a/frontend/src/components/SelectField.test.tsx
+++ b/frontend/src/components/SelectField.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it } from "vitest";
@@ -102,6 +102,35 @@ describe("SelectField", () => {
expect(screen.queryByRole("listbox")).toBeNull();
});
+ describe("scrolling while the list is open", () => {
+ /** jsdom lays nothing out, so the trigger's position is whatever this says. */
+ function placeTriggerAt(top: number) {
+ trigger().getBoundingClientRect = () => ({ top, bottom: top + 36, left: 0, right: 200, width: 200, height: 36, x: 0, y: top, toJSON: () => ({}) });
+ }
+
+ // The list is positioned from the trigger, so a scroll that moves the
+ // trigger leaves it in the wrong place.
+ it("closes when the scroll moved the trigger", async () => {
+ render( );
+ placeTriggerAt(100);
+ await userEvent.click(trigger());
+ placeTriggerAt(40);
+ fireEvent.scroll(document.body);
+ expect(screen.queryByRole("listbox")).toBeNull();
+ });
+
+ // Opening the list makes the browser scroll its container to show it. That
+ // scroll arrives after the list has been placed, and closing on it shut the
+ // list the moment it opened on a page that was scrolled down.
+ it("stays open when the scroll left the trigger where it was", async () => {
+ render( );
+ placeTriggerAt(100);
+ await userEvent.click(trigger());
+ fireEvent.scroll(document.body);
+ expect(screen.getByRole("listbox")).toBeTruthy();
+ });
+ });
+
it("jumps to an option by typing its first letters", async () => {
render( );
trigger().focus();
diff --git a/frontend/src/components/SelectField.tsx b/frontend/src/components/SelectField.tsx
index 270cb8f6..268c05fd 100644
--- a/frontend/src/components/SelectField.tsx
+++ b/frontend/src/components/SelectField.tsx
@@ -50,6 +50,7 @@ export function SelectField({ value, options, onChange, label, id, className = "
const [dropUp, setDropUp] = useState(false);
const triggerRef = useRef(null);
const listRef = useRef(null);
+ const openedAt = useRef({ top: 0, left: 0 });
const typeahead = useRef({ query: "", at: 0 });
const selectedIndex = options.findIndex((option) => option.value === value);
@@ -76,6 +77,7 @@ export function SelectField({ value, options, onChange, label, id, className = "
const list = listRef.current;
if (!trigger || !list) return;
const box = trigger.getBoundingClientRect();
+ openedAt.current = { top: box.top, left: box.left };
// The margin covers the 5px CSS offset plus room for the shadow, and gives
// the sidebar pickers -- which sit near the bottom edge -- a reason to flip
// before the list is merely technically on screen with nothing to spare.
@@ -95,15 +97,22 @@ export function SelectField({ value, options, onChange, label, id, className = "
const target = event.target as Node;
if (!triggerRef.current?.contains(target) && !listRef.current?.contains(target)) close(false);
};
- // Any scroll or resize invalidates the measured position above.
- const onReflow = () => close(false);
+ // A resize invalidates the measured position above. A scroll only does if it
+ // moved the trigger: scroll events are delivered a frame late, so one from
+ // just before the list opened arrives after it, with the trigger already
+ // where it was measured.
+ const onResize = () => close(false);
+ const onScroll = () => {
+ const box = triggerRef.current?.getBoundingClientRect();
+ if (!box || box.top !== openedAt.current.top || box.left !== openedAt.current.left) close(false);
+ };
document.addEventListener("pointerdown", onPointerDown);
- window.addEventListener("resize", onReflow);
- window.addEventListener("scroll", onReflow, true);
+ window.addEventListener("resize", onResize);
+ window.addEventListener("scroll", onScroll, true);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
- window.removeEventListener("resize", onReflow);
- window.removeEventListener("scroll", onReflow, true);
+ window.removeEventListener("resize", onResize);
+ window.removeEventListener("scroll", onScroll, true);
};
}, [open]);
diff --git a/frontend/src/i18n.tsx b/frontend/src/i18n.tsx
index 0eed7405..856619f5 100644
--- a/frontend/src/i18n.tsx
+++ b/frontend/src/i18n.tsx
@@ -1089,6 +1089,19 @@ const english = {
"在 Agent 的配置页选择配置模版时会自动开启": "Turns on by itself when you choose a profile on an Agent's page",
"开启后这些 Agent 才能使用": "These Agents work once it is on",
"更换": "Change",
+ "跑一个小任务试试": "Try one small task",
+ // Says who bills and stops there, like the key explainer: no amount, no "small".
+ "让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费": "{agent} writes an introduction page in a temporary directory and writes nowhere else. This is a real model call, billed by the provider at its prices",
+ "开始": "Start",
+ "正在运行,通常需要一两分钟": "Running, usually a minute or two",
+ "{agent} 写好了,文件在下面这个目录": "{agent} is done. The files are in the directory below",
+ "{agent} 没有正常结束,下面的文件可能不完整": "{agent} did not finish cleanly, so the files below may be incomplete",
+ "{agent} 没有写出任何文件": "{agent} did not write any file",
+ "小任务没能运行": "The task could not run",
+ "复制路径": "Copy path",
+ "生成的文件": "Files written",
+ "检查模型服务": "Check the provider",
+ "查看运行记录": "View the run record",
"本机环境": "This computer",
"系统": "System",
"已安装的 Agent": "Agents installed",
diff --git a/frontend/src/pages/InstallTaskPage.test.tsx b/frontend/src/pages/InstallTaskPage.test.tsx
index 966ec8bd..bea73be8 100644
--- a/frontend/src/pages/InstallTaskPage.test.tsx
+++ b/frontend/src/pages/InstallTaskPage.test.tsx
@@ -4,6 +4,7 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
// No I18nProvider, so translate() returns the Chinese keys unchanged.
+import { api } from "../backend/api";
import { InstallTaskPage } from "./InstallTaskPage";
const mockUseTaskCenter = vi.hoisted(() => vi.fn(() => ({ tasks: [], cancelTask: vi.fn(), dismissTask: vi.fn(), progress: {}, running: {} })));
@@ -69,3 +70,40 @@ describe("InstallTaskPage update route", () => {
expect(screen.getByRole("region", { name: "任务时间线" })).toBeTruthy();
});
});
+
+// An install ends on this page, so it is where the first task has to be offered.
+describe("InstallTaskPage first task", () => {
+ function renderTask(kind: "install" | "update", state: "success" | "failure") {
+ mockUseTaskCenter.mockReturnValue({
+ tasks: [{
+ id: `${kind}:codex`, kind, target: "codex", title: "安装 Codex", route: `/tasks/${kind}/codex`,
+ progressTarget: "", state, message: "", startedAt: 1, events: [],
+ }],
+ cancelTask: vi.fn(), dismissTask: vi.fn(), progress: {}, running: {},
+ } as never);
+ render(
+
+ } />
+ ,
+ );
+ }
+
+ it("is offered once an Agent has installed", async () => {
+ const agents = vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]);
+ renderTask("install", "success");
+
+ expect(await screen.findByRole("heading", { name: "跑一个小任务试试" })).toBeTruthy();
+ agents.mockRestore();
+ });
+
+ // An update leaves an Agent the user already knows, and a failed install
+ // leaves nothing to run. Neither asks the backend at all.
+ it("is not offered after an update or a failed install", () => {
+ const agents = vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]);
+ renderTask("update", "success");
+ renderTask("install", "failure");
+
+ expect(agents).not.toHaveBeenCalled();
+ agents.mockRestore();
+ });
+});
diff --git a/frontend/src/pages/InstallTaskPage.tsx b/frontend/src/pages/InstallTaskPage.tsx
index 65c1003b..a61e170c 100644
--- a/frontend/src/pages/InstallTaskPage.tsx
+++ b/frontend/src/pages/InstallTaskPage.tsx
@@ -1,6 +1,7 @@
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { DownloadProgress } from "../components/DownloadProgress";
+import { FirstTaskSection } from "../components/FirstTaskSection";
import { LogDisclosure } from "../components/LogDisclosure";
import { PageScaffold } from "../components/PageScaffold";
import { useI18n } from "../i18n";
@@ -80,6 +81,10 @@ export function InstallTaskPage() {
) : null}
{task.log ? : null}
+ {/* This is the page an install ends on, so it is where the new Agent is
+ first offered something to do. The section hides itself for an Agent
+ that cannot run unattended, which covers every desktop app. */}
+ {kind === "install" && task.state === "success" ? : null}
{task.state !== "running" && task.action ? (
{ void task.action?.run(); }}>
{task.action.label}
diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css
index c1be7bc5..a5233f4f 100644
--- a/frontend/src/styles/app.css
+++ b/frontend/src/styles/app.css
@@ -1419,6 +1419,44 @@
color: var(--text-tertiary);
}
+.first-task-section {
+ width: 100%;
+ margin-top: 22px;
+ display: grid;
+ gap: 10px;
+}
+
+.first-task-section h2 { margin: 0; font-size: 13px; font-weight: 650; }
+.first-task-section > p { margin: 0; color: var(--text-secondary); font-size: 12px; line-height: 1.55; }
+.first-task-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+.first-task-actions:empty { display: none; }
+
+.first-task-output {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 8px 12px;
+}
+
+/* A path has no spaces to wrap at, and it is the one thing here the user has
+ to be able to read in full. */
+.first-task-output code {
+ padding: 9px 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-control);
+ background: var(--surface-subtle);
+ font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ overflow-wrap: anywhere;
+}
+
+.first-task-output ul {
+ grid-column: 1 / -1;
+ margin: 0;
+ padding-left: 18px;
+ color: var(--text-secondary);
+ font: 11px/1.6 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+}
+
.loading-block {
min-height: 80px;
display: flex;
diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts
index ad4429b4..82967fd8 100644
--- a/frontend/src/types/api.ts
+++ b/frontend/src/types/api.ts
@@ -78,6 +78,8 @@ export type LaunchAgentResponse = BindingModels.LaunchResponse;
export type AgentUninstallResult = AppModels.AgentUninstallResult;
export type AgentUpdateResult = AppModels.AgentUpdateResult;
export type ConversationMigrationResult = AppModels.ConversationMigrationResult;
+export type FirstTaskAgent = AppModels.FirstTaskAgent;
+export type FirstTaskResult = AppModels.FirstTaskResult;
export type TaskHistoryRecord = AppModels.TaskHistoryRecord;
export type MarketplaceRecommendationAgent = AppModels.MarketplaceRecommendationAgent;
export type MarketplaceKnowledgeItem = AppModels.MarketplaceKnowledgeItem;
diff --git a/internal/app/first_task.go b/internal/app/first_task.go
new file mode 100644
index 00000000..877130f3
--- /dev/null
+++ b/internal/app/first_task.go
@@ -0,0 +1,232 @@
+package app
+
+import (
+ "context"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/MaimoryLab/BootAgent/internal/catalog"
+ oneerrors "github.com/MaimoryLab/BootAgent/internal/errors"
+ "github.com/MaimoryLab/BootAgent/internal/install"
+ "github.com/MaimoryLab/BootAgent/internal/process"
+)
+
+const (
+ // A model writing one page usually finishes inside two minutes; the budget
+ // leaves room for a slow Provider without letting a stuck run sit forever.
+ firstTaskTimeout = 5 * time.Minute
+ firstTaskLogMax = 8000
+ firstTaskFilesMax = 20
+ firstTaskDirPrefix = "bootagent-first-task-"
+)
+
+type FirstTaskAgent struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+type FirstTaskRequest struct {
+ AgentID string `json:"agent_id"`
+ Locale string `json:"locale"`
+}
+
+// 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.
+type FirstTaskResult struct {
+ AgentID string `json:"agent_id"`
+ OK bool `json:"ok"`
+ Directory string `json:"directory"`
+ Files []string `json:"files"`
+ Log string `json:"log"`
+}
+
+// firstTaskAdapter is how one Agent runs unattended with writes confined to a
+// directory. The prompt arrives on stdin, never on argv.
+type firstTaskAdapter struct {
+ ID string
+ Command string
+ Argv func(directory string) []string
+}
+
+var firstTaskAdapters = []firstTaskAdapter{
+ {
+ ID: "codex", Command: "codex",
+ Argv: func(directory string) []string {
+ return []string{
+ "codex", "exec", "--sandbox", "workspace-write",
+ // workspace-write has no network by default, but a user's own
+ // config.toml can turn it on. The override wins over that file.
+ "-c", "sandbox_workspace_write.network_access=false",
+ "--skip-git-repo-check", "--ephemeral", "--ignore-rules", "--color", "never",
+ "-C", directory, "-",
+ }
+ },
+ },
+ {
+ ID: "claude-code", Command: "claude",
+ // No working-directory flag exists, so the directory is where the
+ // process starts. Write is the only tool: without Bash there is no way
+ // to run a command or reach the network, and acceptEdits approves edits
+ // under the working directory only.
+ Argv: func(string) []string {
+ return []string{
+ "claude", "-p", "--safe-mode", "--tools", "Write", "--permission-mode", "acceptEdits",
+ "--no-session-persistence", "--output-format", "text",
+ }
+ },
+ },
+}
+
+func firstTaskAdapterFor(id string) (firstTaskAdapter, bool) {
+ for _, adapter := range firstTaskAdapters {
+ if adapter.ID == id {
+ return adapter, true
+ }
+ }
+ return firstTaskAdapter{}, false
+}
+
+// FirstTaskAgents lists the installed Agents RunFirstTask can drive.
+func (u *UseCases) FirstTaskAgents(ctx context.Context) ([]FirstTaskAgent, error) {
+ if u == nil || u.runner == nil {
+ return nil, oneerrors.New(oneerrors.InternalError, "First task is not configured", oneerrors.WithStatus(501))
+ }
+ if err := contextError(ctx, "First task request was cancelled"); err != nil {
+ return nil, err
+ }
+ manifest, err := catalog.LoadEmbedded()
+ if err != nil {
+ return nil, err
+ }
+ runtime := u.installRuntime(nil)
+ agents := make([]FirstTaskAgent, 0, len(firstTaskAdapters))
+ for _, adapter := range firstTaskAdapters {
+ if _, ok := runtime.Runner.LookPath(adapter.Command); !ok {
+ continue
+ }
+ if entry, ok := manifest.Agents[adapter.ID]; ok {
+ agents = append(agents, FirstTaskAgent{ID: adapter.ID, Name: entry.Name})
+ }
+ }
+ return agents, nil
+}
+
+// RunFirstTask has an installed Agent write a small page in a directory of its
+// own, using whatever model the Agent is already configured for. It sends real
+// requests to that model, so it must only ever run from an explicit user action.
+func (u *UseCases) RunFirstTask(ctx context.Context, request FirstTaskRequest) (FirstTaskResult, error) {
+ if u == nil || u.runner == nil {
+ return FirstTaskResult{}, oneerrors.New(oneerrors.InternalError, "First task is not configured", oneerrors.WithStatus(501))
+ }
+ if err := contextError(ctx, "First task request was cancelled"); err != nil {
+ return FirstTaskResult{}, err
+ }
+ adapter, ok := firstTaskAdapterFor(strings.TrimSpace(request.AgentID))
+ if !ok {
+ return FirstTaskResult{}, oneerrors.New(oneerrors.InvalidRequest, "This Agent cannot run the first task")
+ }
+ runtime := u.installRuntime(nil)
+ executable, present := runtime.Runner.LookPath(adapter.Command)
+ if !present || executable == "" {
+ return FirstTaskResult{}, oneerrors.New(oneerrors.PrerequisiteMissing, "The selected Agent is not installed")
+ }
+ directory, err := os.MkdirTemp("", firstTaskDirPrefix)
+ if err != nil {
+ return FirstTaskResult{}, oneerrors.New(oneerrors.InternalError, "Could not create a directory for the first task", oneerrors.WithCause(err))
+ }
+ argv := adapter.Argv(directory)
+ // The path that made the Agent count as installed, for the reason
+ // RecommendMarketplace gives: a bare name can resolve differently in the child.
+ argv[0] = executable
+ // The Agent may print nothing while the model works, so files appearing in
+ // the directory count as progress too.
+ runContext := process.WithActivityPaths(process.WithWorkingDirectory(ctx, directory), directory)
+ run, runErr := process.RunPrivateInput(runContext, runtime.Runner, argv, runtime.Env, firstTaskTimeout, firstTaskPrompt(request.Locale))
+ if ctx.Err() != nil {
+ _ = os.RemoveAll(directory)
+ return FirstTaskResult{}, contextError(ctx, "First task request was cancelled")
+ }
+ output := strings.TrimSpace(run.Stderr + "\n" + run.Stdout)
+ if runErr != nil {
+ output = strings.TrimSpace(output + "\n" + runErr.Error())
+ }
+ result := FirstTaskResult{
+ AgentID: adapter.ID,
+ Files: firstTaskFiles(directory),
+ Log: tailRunes(install.Redact(output, u.firstTaskSecrets(runtime.Env)), firstTaskLogMax),
+ }
+ if len(result.Files) == 0 {
+ _ = os.RemoveAll(directory)
+ return result, nil
+ }
+ // Kept on purpose: the page is what the user came for. It lives under the
+ // system temporary directory, which the OS clears on its own schedule.
+ result.Directory = directory
+ result.OK = runErr == nil && run.ExitCode == 0
+ return result, nil
+}
+
+func firstTaskPrompt(locale string) string {
+ if strings.HasPrefix(strings.ToLower(strings.TrimSpace(locale)), "en") {
+ return "Create one file named index.html in the current directory: a self-contained page, with its HTML and CSS in that one file, " +
+ "that introduces what you can help with as an AI coding assistant. Create only that file. " +
+ "Do not run any command, do not access the network, and do not read or change anything outside the current directory. " +
+ "When you are done, say in one sentence what you did.\n"
+ }
+ return "在当前目录创建一个名为 index.html 的文件:一个自包含的页面(HTML 和 CSS 都写在这一个文件里),用中文介绍你作为 AI 编程助手能帮用户做哪些事。" +
+ "只创建这一个文件。不要运行任何命令,不要访问网络,不要读取或修改当前目录以外的任何内容。" +
+ "完成后用一句话说明你做了什么。\n"
+}
+
+// firstTaskFiles lists the regular files under directory, relative and with
+// forward slashes. Links are skipped: one could point outside the directory.
+func firstTaskFiles(directory string) []string {
+ files := []string{}
+ _ = filepath.WalkDir(directory, func(path string, entry fs.DirEntry, err error) error {
+ if err != nil || !entry.Type().IsRegular() {
+ return nil
+ }
+ if relative, relErr := filepath.Rel(directory, path); relErr == nil {
+ files = append(files, filepath.ToSlash(relative))
+ }
+ return nil
+ })
+ sort.Strings(files)
+ if len(files) > firstTaskFilesMax {
+ files = files[:firstTaskFilesMax]
+ }
+ return files
+}
+
+// firstTaskSecrets collects every key the Agent's output could repeat: the saved
+// Provider keys, the local compatibility-mode key, and key-like variables.
+func (u *UseCases) firstTaskSecrets(environment map[string]string) []string {
+ secrets := []string{u.conversionAPIKey()}
+ if providers, err := u.providers.Public(); err == nil {
+ for id := range providers {
+ if entry, getErr := u.providers.Get(id); getErr == nil {
+ secrets = append(secrets, entry.APIKey)
+ }
+ }
+ }
+ for name, value := range environment {
+ upper := strings.ToUpper(name)
+ if strings.Contains(upper, "KEY") || strings.Contains(upper, "TOKEN") || strings.Contains(upper, "SECRET") || strings.Contains(upper, "PASSWORD") {
+ secrets = append(secrets, value)
+ }
+ }
+ return secrets
+}
+
+func tailRunes(value string, limit int) string {
+ runes := []rune(value)
+ if len(runes) <= limit {
+ return value
+ }
+ return string(runes[len(runes)-limit:])
+}
diff --git a/internal/app/first_task_test.go b/internal/app/first_task_test.go
new file mode 100644
index 00000000..368bf767
--- /dev/null
+++ b/internal/app/first_task_test.go
@@ -0,0 +1,228 @@
+package app
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ oneerrors "github.com/MaimoryLab/BootAgent/internal/errors"
+ "github.com/MaimoryLab/BootAgent/internal/platform"
+ "github.com/MaimoryLab/BootAgent/internal/process"
+)
+
+// firstTaskRunner stands in for the Agent. `act` plays its part: it receives the
+// directory the command was started in and returns what the command printed.
+type firstTaskRunner struct {
+ available map[string]bool
+ act func(directory string) (process.Result, error)
+ argv []string
+ input string
+ directory string
+ timeout time.Duration
+}
+
+func (r *firstTaskRunner) LookPath(command string) (string, bool) {
+ return "/bin/" + command, r.available[command]
+}
+
+func (r *firstTaskRunner) Run(context.Context, []string, map[string]string, time.Duration) (process.Result, error) {
+ return process.Result{}, errors.New("the task prompt must not travel on argv")
+}
+
+func (r *firstTaskRunner) RunPrivateInput(ctx context.Context, argv []string, _ map[string]string, timeout time.Duration, input string) (process.Result, error) {
+ r.argv = append([]string(nil), argv...)
+ r.input = input
+ r.timeout = timeout
+ r.directory = process.WorkingDirectory(ctx)
+ if r.act == nil {
+ return process.Result{}, nil
+ }
+ return r.act(r.directory)
+}
+
+func firstTaskCore(t *testing.T, runner *firstTaskRunner) *UseCases {
+ t.Helper()
+ return NewUseCases(StatusOptions{
+ Home: t.TempDir(),
+ Platform: platform.For("linux", "amd64"),
+ Runner: runner,
+ Environment: map[string]string{"PATH": "/usr/bin"},
+ })
+}
+
+func writesPage(directory string) (process.Result, error) {
+ if err := os.WriteFile(filepath.Join(directory, "index.html"), []byte(""), 0o600); err != nil {
+ return process.Result{}, err
+ }
+ return process.Result{ExitCode: 0, Stdout: "Created index.html"}, nil
+}
+
+// removeLater cleans up a directory a successful run deliberately keeps.
+func removeLater(t *testing.T, directory string) {
+ t.Helper()
+ t.Cleanup(func() { _ = os.RemoveAll(directory) })
+}
+
+func TestFirstTaskAgentsListsOnlyInstalledAgentsThatCanRunUnattended(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"codex": true, "claude": true, "opencode": true, "dsh": true}}
+ agents, err := firstTaskCore(t, runner).FirstTaskAgents(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(agents) != 2 || agents[0].ID != "codex" || agents[1].ID != "claude-code" {
+ t.Fatalf("agents = %#v", agents)
+ }
+ runner.available = map[string]bool{"claude": true}
+ agents, err = firstTaskCore(t, runner).FirstTaskAgents(context.Background())
+ if err != nil || len(agents) != 1 || agents[0].ID != "claude-code" {
+ t.Fatalf("agents = %#v, err=%v", agents, err)
+ }
+}
+
+func TestRunFirstTaskConfinesCodexToItsOwnTemporaryDirectory(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"codex": true}, act: writesPage}
+ result, err := firstTaskCore(t, runner).RunFirstTask(context.Background(), FirstTaskRequest{AgentID: "codex", Locale: "zh-CN"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ removeLater(t, result.Directory)
+ if !result.OK || !slices.Equal(result.Files, []string{"index.html"}) {
+ t.Fatalf("result = %#v", result)
+ }
+ if filepath.Dir(result.Directory) != filepath.Clean(os.TempDir()) || !strings.HasPrefix(filepath.Base(result.Directory), "bootagent-first-task-") {
+ t.Fatalf("task ran in %q, want a fresh directory under %q", result.Directory, os.TempDir())
+ }
+ if runner.directory != result.Directory {
+ t.Fatalf("command started in %q, want %q", runner.directory, result.Directory)
+ }
+ argv := strings.Join(runner.argv, " ")
+ for _, want := range []string{
+ "/bin/codex exec",
+ "--sandbox workspace-write",
+ // A user's own config.toml can turn network access on for this sandbox.
+ "-c sandbox_workspace_write.network_access=false",
+ "-C " + result.Directory,
+ } {
+ if !strings.Contains(argv, want) {
+ t.Fatalf("argv %q is missing %q", argv, want)
+ }
+ }
+ if strings.Contains(argv, "danger") || runner.argv[len(runner.argv)-1] != "-" {
+ t.Fatalf("argv = %q", argv)
+ }
+ if !strings.Contains(runner.input, "index.html") || strings.Contains(argv, "index.html") {
+ t.Fatalf("the prompt belongs on stdin: input=%q argv=%q", runner.input, argv)
+ }
+ if runner.timeout <= 0 || runner.timeout > 10*time.Minute {
+ t.Fatalf("timeout = %s", runner.timeout)
+ }
+}
+
+// Claude Code has no flag for where to work, and without Bash it has no way to
+// run a command or reach the network.
+func TestRunFirstTaskGivesClaudeCodeOnlyTheWriteTool(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"claude": true}, act: writesPage}
+ result, err := firstTaskCore(t, runner).RunFirstTask(context.Background(), FirstTaskRequest{AgentID: "claude-code", Locale: "en"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ removeLater(t, result.Directory)
+ if !result.OK || runner.directory != result.Directory {
+ t.Fatalf("result = %#v, started in %q", result, runner.directory)
+ }
+ argv := strings.Join(runner.argv, " ")
+ for _, want := range []string{"/bin/claude -p", "--tools Write", "--permission-mode acceptEdits", "--no-session-persistence"} {
+ if !strings.Contains(argv, want) {
+ t.Fatalf("argv %q is missing %q", argv, want)
+ }
+ }
+ if strings.Contains(argv, "Bash") || strings.Contains(argv, "bypassPermissions") {
+ t.Fatalf("argv = %q", argv)
+ }
+ if !strings.Contains(runner.input, "index.html") || strings.ContainsAny(runner.input, "的页") {
+ t.Fatalf("English prompt expected, got %q", runner.input)
+ }
+}
+
+func TestRunFirstTaskReportsAFailedRunWithoutLeakingTheKey(t *testing.T) {
+ const key = "sk-first-task-secret-0123456789"
+ var worked string
+ runner := &firstTaskRunner{available: map[string]bool{"codex": true}, act: func(directory string) (process.Result, error) {
+ worked = directory
+ return process.Result{ExitCode: 1, Stderr: "401 Unauthorized: invalid api key " + key}, nil
+ }}
+ core := firstTaskCore(t, runner)
+ if err := core.providers.SaveKey(context.Background(), "ppio", key); err != nil {
+ t.Fatal(err)
+ }
+ result, err := core.RunFirstTask(context.Background(), FirstTaskRequest{AgentID: "codex"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.OK || result.Directory != "" || len(result.Files) != 0 {
+ t.Fatalf("result = %#v", result)
+ }
+ if strings.Contains(result.Log, key) || !strings.Contains(result.Log, "401 Unauthorized") {
+ t.Fatalf("log = %q", result.Log)
+ }
+ // Nothing was produced, so there is nothing to keep.
+ if _, statErr := os.Stat(worked); !os.IsNotExist(statErr) {
+ t.Fatalf("empty task directory %q was left behind: %v", worked, statErr)
+ }
+}
+
+func TestRunFirstTaskDoesNotCallAnEmptyRunASuccess(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"codex": true}, act: func(string) (process.Result, error) {
+ return process.Result{ExitCode: 0, Stdout: "Done."}, nil
+ }}
+ result, err := firstTaskCore(t, runner).RunFirstTask(context.Background(), FirstTaskRequest{AgentID: "codex"})
+ if err != nil || result.OK || result.Directory != "" {
+ t.Fatalf("result = %#v, err=%v", result, err)
+ }
+}
+
+func TestRunFirstTaskListsWhatTheAgentWrote(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"codex": true}, act: func(directory string) (process.Result, error) {
+ if err := os.MkdirAll(filepath.Join(directory, "assets"), 0o700); err != nil {
+ return process.Result{}, err
+ }
+ for _, name := range []string{"index.html", filepath.Join("assets", "style.css")} {
+ if err := os.WriteFile(filepath.Join(directory, name), []byte("x"), 0o600); err != nil {
+ return process.Result{}, err
+ }
+ }
+ return process.Result{ExitCode: 0}, nil
+ }}
+ result, err := firstTaskCore(t, runner).RunFirstTask(context.Background(), FirstTaskRequest{AgentID: "codex"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ removeLater(t, result.Directory)
+ if !slices.Equal(result.Files, []string{"assets/style.css", "index.html"}) {
+ t.Fatalf("files = %#v", result.Files)
+ }
+}
+
+func TestRunFirstTaskRejectsAgentsItCannotDrive(t *testing.T) {
+ runner := &firstTaskRunner{available: map[string]bool{"opencode": true}}
+ core := firstTaskCore(t, runner)
+ for agent, want := range map[string]string{
+ "opencode": oneerrors.InvalidRequest,
+ "": oneerrors.InvalidRequest,
+ "codex": oneerrors.PrerequisiteMissing,
+ } {
+ _, err := core.RunFirstTask(context.Background(), FirstTaskRequest{AgentID: agent})
+ var failure *oneerrors.BootAgentError
+ if !errors.As(err, &failure) || failure.Code != want {
+ t.Fatalf("RunFirstTask(%q) = %v, want %s", agent, err, want)
+ }
+ }
+ if runner.argv != nil {
+ t.Fatalf("a rejected request still ran %q", runner.argv)
+ }
+}
diff --git a/internal/binding/services.go b/internal/binding/services.go
index 1bf273ba..6e9d8275 100644
--- a/internal/binding/services.go
+++ b/internal/binding/services.go
@@ -612,6 +612,30 @@ func (s *AgentService) Launch(ctx context.Context, request LaunchRequest) (Launc
return LaunchResponse{OK: true, Agent: result.Agent, Command: result.Command, Terminal: result.Terminal}, nil
}
+// FirstTaskAgents lists the installed Agents RunFirstTask can drive unattended.
+func (s *AgentService) FirstTaskAgents(ctx context.Context) ([]app.FirstTaskAgent, error) {
+ if err := contextError(ctx); err != nil {
+ return nil, err
+ }
+ if s == nil || s.core == nil {
+ return nil, notReady("First task is not configured")
+ }
+ return s.core.FirstTaskAgents(ctx)
+}
+
+// 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.
+func (s *AgentService) RunFirstTask(ctx context.Context, request app.FirstTaskRequest) (app.FirstTaskResult, error) {
+ if err := contextError(ctx); err != nil {
+ return app.FirstTaskResult{}, err
+ }
+ if s == nil || s.core == nil {
+ return app.FirstTaskResult{}, notReady("First task is not configured")
+ }
+ return s.core.RunFirstTask(ctx, request)
+}
+
type ProfileService struct {
core *app.UseCases
}
diff --git a/internal/binding/services_test.go b/internal/binding/services_test.go
index 60728a61..baddd785 100644
--- a/internal/binding/services_test.go
+++ b/internal/binding/services_test.go
@@ -50,7 +50,7 @@ func TestServiceMethodAllowlist(t *testing.T) {
}{
{&StatusService{}, []string{"GetStatus"}},
{&ProviderService{}, []string{"DeleteProvider", "GetProvider", "ListModels", "OpenGitHub", "OpenHelp", "OpenRegistration", "Probe", "SaveProvider"}},
- {&AgentService{}, []string{"Activate", "ActivateWithConversion", "Install", "Launch", "MigrateConversations", "PreviewUninstall", "Uninstall", "Update"}},
+ {&AgentService{}, []string{"Activate", "ActivateWithConversion", "FirstTaskAgents", "Install", "Launch", "MigrateConversations", "PreviewUninstall", "RunFirstTask", "Uninstall", "Update"}},
{&ProfileService{}, []string{"CheckModel", "DeleteProfile", "ListProfiles", "SaveProfile"}},
{&RuntimeService{}, []string{"GetSettings", "InstallRuntime", "ListRuntimes", "SaveSettings"}},
{&DesktopAgentService{}, []string{"AssessProfile", "Configure", "ConfigureWithConversion", "GetStatus", "Install", "Open"}},
diff --git a/internal/process/process.go b/internal/process/process.go
index 2f8763ea..f1fe06dd 100644
--- a/internal/process/process.go
+++ b/internal/process/process.go
@@ -518,6 +518,7 @@ func (r OSRunner) runWithOutput(ctx context.Context, argv []string, overrides ma
}
HideWindow(command)
command.Env = mergeEnvironment(r.Env, overrides)
+ command.Dir = WorkingDirectory(ctx)
stdout := &boundedBuffer{limit: MaxOutputBytes}
stderr := &boundedBuffer{limit: MaxOutputBytes}
var streamLock sync.Mutex
diff --git a/internal/process/process_test.go b/internal/process/process_test.go
index 5e32b8d4..43982a50 100644
--- a/internal/process/process_test.go
+++ b/internal/process/process_test.go
@@ -44,6 +44,11 @@ func TestProcessHelper(_ *testing.T) {
os.Stdout.Write(value)
os.Exit(0)
}
+ if os.Getenv("TEST_PROCESS_CWD") == "1" {
+ directory, _ := os.Getwd()
+ os.Stdout.WriteString(directory)
+ os.Exit(0)
+ }
if os.Getenv("TEST_PROCESS_WAIT") == "1" {
if os.Getenv("TEST_PROCESS_READY") == "1" {
os.Stdout.WriteString("ready")
@@ -152,6 +157,34 @@ func TestOSRunnerAcceptsPrivateStdin(t *testing.T) {
}
}
+// A command that writes relative paths has to start where the caller means it
+// to, and not every command has a flag for that.
+func TestOSRunnerStartsInTheContextWorkingDirectory(t *testing.T) {
+ runner := helperRunner(t)
+ // Resolved, because the child reports the real path and a temporary
+ // directory is reached through a symlink on macOS.
+ directory, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ argv := []string{os.Args[0], "-test.run=TestProcessHelper"}
+ overrides := map[string]string{"TEST_PROCESS_CWD": "1"}
+ result, err := runner.Run(WithWorkingDirectory(context.Background(), directory), argv, overrides, helperTimeout)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := filepath.EvalSymlinks(result.Stdout); got != directory {
+ t.Fatalf("command started in %q, want %q", result.Stdout, directory)
+ }
+ inherited, err := runner.Run(context.Background(), argv, overrides, helperTimeout)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if own, _ := os.Getwd(); inherited.Stdout != own {
+ t.Fatalf("command without a working directory started in %q, want %q", inherited.Stdout, own)
+ }
+}
+
func TestOSRunnerStreamsOutputWithoutChangingResult(t *testing.T) {
runner := helperRunner(t)
outputs := make([]Output, 0)
diff --git a/internal/process/workdir.go b/internal/process/workdir.go
new file mode 100644
index 00000000..f5948c11
--- /dev/null
+++ b/internal/process/workdir.go
@@ -0,0 +1,28 @@
+package process
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+)
+
+type workingDirectoryKey struct{}
+
+// WithWorkingDirectory makes a command started under ctx run in directory
+// instead of inheriting this process's own.
+//
+// It travels on the context for the same reason WithActivityPaths does: Runner
+// stays the two-method interface the install tests assert against, and every
+// decorator between the caller and the runner passes it along unchanged.
+func WithWorkingDirectory(ctx context.Context, directory string) context.Context {
+ if directory = strings.TrimSpace(directory); directory == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, workingDirectoryKey{}, filepath.Clean(directory))
+}
+
+// WorkingDirectory reports the directory WithWorkingDirectory set, or "".
+func WorkingDirectory(ctx context.Context) string {
+ directory, _ := ctx.Value(workingDirectoryKey{}).(string)
+ return directory
+}