Skip to content
Open
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
16 changes: 16 additions & 0 deletions chatbot/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import ArtifactPanel from "./ArtifactPanel";
import { useWorkspaceChanges } from "./useWorkspaceChanges";
import { localId } from "./local-id.js";
import RunAlerts from "./RunAlerts";
import WorkspaceOpening from "./WorkspaceOpening";
import { runProblems, useConversationRuns } from "./runs.js";
import { reconcileOperation, visibleSidebarArtifact } from "./platform.js";
import { isGeneratedArtifact, shouldRevealArtifactPanel } from "./artifact-autoreveal.js";
Expand Down Expand Up @@ -402,6 +403,10 @@ export default function App() {
// conversations bind the temporary workspace opened by Main Bot.
const workspaceRunId =
chat.session?.workspaceRunId || chat.session?.runId || "";
const followWorkspaceProgress = useCallback(() => {
if (follow.current && scroll.current)
scroll.current.scrollTop = scroll.current.scrollHeight;
}, []);
const workspaceChanges = useWorkspaceChanges(workspaceRunId, {
active: panel && panelView === "changes",
});
Expand Down Expand Up @@ -1751,6 +1756,17 @@ export default function App() {
}} />
{!chat.local && !chat.busy && chat.generation?.failure && !messages.some((m) => m.generationId === chat.generation.id && m.failure) ? <GenerationDiagnostics sessionId={chat.session?.id} generationId={chat.generation.id} failure={chat.generation.failure} onCLIInstall={chat.adoptCLIInstall} readOnly={chat.readOnly} /> : null}
{!chat.local && !chat.readOnly && !chat.busy && chat.generation?.id && chat.generation.status === "cancelled" && !chat.generation.failure && !messages.some((m) => m.generationId === chat.generation.id) ? <GenerationDiagnostics sessionId={chat.session?.id} generationId={chat.generation.id} compact /> : null}
<WorkspaceOpening
sessionId={chat.session?.id}
runId={workspaceRunId}
busy={chat.busy}
readOnly={chat.readOnly}
onProgress={followWorkspaceProgress}
onRetry={(runId) => {
setText(`重试打开当前工作区 ${runId},沿用当前运行环境并保留已有文件。`);
document.querySelector('textarea[aria-label="消息"]')?.focus();
}}
/>
<RunAlerts
runs={conversationRuns}
user={chat.user}
Expand Down
121 changes: 121 additions & 0 deletions chatbot/src/WorkspaceOpening.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import React, { useEffect, useLayoutEffect, useState } from "react";
import { api, formatElapsed, sessionPath } from "./api";
import "./run-alerts.css";
import "./workspace-opening.css";

// Read-only polling never materializes or renews the workspace. Resolve the
// binding during a tool call: the chat's full session refresh happens at finish.
export default function WorkspaceOpening({
sessionId,
runId,
busy,
readOnly,
onRetry,
onProgress,
interval = 2000,
}) {
const [current, setCurrent] = useState(null);
const [error, setError] = useState("");
useLayoutEffect(() => {
if (current) onProgress?.();
}, [current, error, onProgress]);
useEffect(() => {
setCurrent(null);
setError("");
if (!sessionId && !runId) return;
const controller = new AbortController();
let timer;
const poll = async () => {
let again = busy;
try {
if (document.hidden) {
again = true;
return;
}
let id = runId;
if (busy && sessionId) {
const session = await api(sessionPath(sessionId), {
signal: controller.signal,
});
id = session?.workspaceRunId || session?.runId;
}
if (!id) return;
const run = await api(`/api/runs/${encodeURIComponent(id)}`, {
signal: controller.signal,
});
if (controller.signal.aborted) return;
const event = (run?.events || []).findLast(
(item) => item.workspaceOpening,
);
setCurrent(
run?.kind === "workspace" && event
? { runId: id, ...event.workspaceOpening }
: null,
);
setError("");
again ||= event?.workspaceOpening?.state === "running";
} catch (e) {
if (!controller.signal.aborted) {
setError("工作区进度暂时无法更新,正在重新连接。");
again = true;
}
} finally {
if (!controller.signal.aborted && again)
timer = setTimeout(poll, interval);
}
};
void poll();
return () => {
controller.abort();
clearTimeout(timer);
};
}, [sessionId, runId, busy, interval]);

if (!current || (current.state === "ready" && !current.warning)) return null;
const failed = current.state === "failed";
const seconds = Math.max(
0,
Math.floor((Date.now() - Date.parse(current.startedAt)) / 1000),
);
return (
<section
className={`run-alert is-settled workspace-opening ${failed ? "" : "is-busy"}`}
aria-label="工作区准备进度"
>
<div role="status" aria-live="polite">
<strong>
{failed
? "工作区准备失败"
: current.state === "ready"
? "工作区环境提示"
: current.message}
</strong>
{current.state === "running" && Number.isFinite(seconds) ? (
<span className="workspace-opening-time">
已用 {formatElapsed(seconds)}
{current.timeoutSeconds
? ` · 本阶段限时 ${formatElapsed(current.timeoutSeconds)}`
: ""}
</span>
) : null}
</div>
{error ? <p role="status">{error}</p> : null}
{current.warning ? <p>{current.warning}</p> : null}
{failed || current.output ? (
<pre className="workspace-opening-output">
{failed ? current.message : current.output}
</pre>
) : null}
{failed ? <p>已保留当前工作区和已有文件,修复原因后可重试。</p> : null}
{failed && !readOnly ? (
<button
className="run-alert-btn primary"
disabled={busy}
onClick={() => onRetry?.(current.runId)}
>
请助手重试当前工作区
</button>
) : null}
</section>
);
}
21 changes: 21 additions & 0 deletions chatbot/src/workspace-opening.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
.workspace-opening {
margin: 4px 0 16px;
}
.workspace-opening-time {
display: block;
color: var(--hui-muted);
font-size: 12px;
}
.workspace-opening p {
margin: 8px 0;
}
.workspace-opening-output {
max-height: 160px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
padding: 8px;
border-radius: 6px;
background: var(--hui-surface);
font-size: 12px;
}
110 changes: 110 additions & 0 deletions chatbot/tests/workspace-opening.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import React from "react";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import WorkspaceOpening from "../src/WorkspaceOpening";

afterEach(() => vi.unstubAllGlobals());
const response = (data) => ({ ok: true, status: 200, json: async () => data });
const run = (state, extra = {}) => ({
kind: "workspace",
events: [
{
workspaceOpening: {
state,
phase: "clone",
message: "正在克隆仓库",
startedAt: new Date().toISOString(),
timeoutSeconds: 600,
...extra,
},
},
],
});

test("finds a new binding while the open tool is still running and updates progress", async () => {
let progress = run("running", { output: "Receiving objects: 20%, 50 KiB/s" });
const fetch = vi.fn(async (path) =>
response(
path.includes("/sessions/") ? { workspaceRunId: "new-run" } : progress,
),
);
vi.stubGlobal("fetch", fetch);
const view = render(<WorkspaceOpening sessionId="chat" busy interval={20} />);
expect(await screen.findByText(/50 KiB\/s/)).toBeInTheDocument();
expect(fetch).toHaveBeenCalledWith("/api/runs/new-run", expect.anything());
expect(screen.getByText(/本阶段限时 10分钟/)).toBeInTheDocument();
progress = run("failed", { message: "clone: context deadline exceeded" });
expect(await screen.findByText("工作区准备失败")).toBeInTheDocument();
expect(screen.getByRole("button")).toBeDisabled();
view.rerender(
<WorkspaceOpening
sessionId="chat"
runId="new-run"
busy={false}
interval={20}
/>,
);
await waitFor(() => expect(screen.getByRole("button")).toBeEnabled());
});

test("offers retry for the same run and hides recovered errors", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
response(
run("failed", { message: "docker build: apt mirror unreachable" }),
),
),
);
const retry = vi.fn();
const view = render(<WorkspaceOpening runId="r1" onRetry={retry} />);
fireEvent.click(
await screen.findByRole("button", { name: /重试当前工作区/ }),
);
expect(retry).toHaveBeenCalledWith("r1");
vi.stubGlobal(
"fetch",
vi.fn(async () => response(run("ready"))),
);
view.rerender(<WorkspaceOpening runId="r1" busy onRetry={retry} />);
await waitFor(() =>
expect(screen.queryByLabelText("工作区准备进度")).not.toBeInTheDocument(),
);
});

test("keeps frozen Dockerfile warning visible after readiness", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
response(
run("ready", {
warning: "项目 Dockerfile 已更新;当前工作区仍使用创建时的版本。",
}),
),
),
);
render(<WorkspaceOpening runId="r1" readOnly />);
expect(await screen.findByText(/项目 Dockerfile 已更新/)).toBeInTheDocument();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
});

test("changing conversations ignores a late response from the old workspace", async () => {
let resolveOld;
vi.stubGlobal(
"fetch",
vi.fn((path) =>
path.endsWith("old")
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(response(run("ready"))),
),
);
const view = render(<WorkspaceOpening runId="old" />);
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
view.rerender(<WorkspaceOpening runId="new" />);
resolveOld(response(run("failed", { message: "old failure" })));
await waitFor(() =>
expect(screen.queryByText("old failure")).not.toBeInTheDocument(),
);
});
74 changes: 73 additions & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Access to the Docker socket is equivalent to root on the host. Two safeguards fo

### Slow networks: clone and image build limits

Cloning a repository and building a custom sandbox image report progress while they work, and their errors keep the last lines of git or Docker output. On the platform host the progress is recorded on the run. On an execution machine it is written to the runner's log, and only the final error reaches the platform. A step that prints nothing for its stall window is treated as hung and stopped. A step that keeps printing may be slow but is stopped only by a total limit. All settings take Go durations such as `90s` or `20m`; `0` turns a limit off. Each host reads its own environment, so set the clone limits on execution machines too.
Cloning a repository and building a custom sandbox image report progress while they work, and their errors keep a bounded tail of git or Docker output (at most 20 lines / 16 KiB). On the platform host the progress is recorded on the run. Execution-machine clones also write progress to the runner's log. Workspace-opening requests forward live output to the platform and chat through the same command observer; upgrade both platform and runner for this protocol. Progress is emitted on the first line, at most every 10 seconds thereafter, and with the final output when the command exits. A step that prints nothing for its stall window is treated as hung and stopped. A step that keeps printing may be slow but is stopped only by a total limit. All settings below take Go durations such as `90s` or `20m`; `0` turns that command limit off. Each host reads its own environment, so set the clone limits on execution machines too.

| Setting | Default | Applies to |
|---|---|---|
Expand Down Expand Up @@ -135,6 +135,78 @@ A platform administrator can share one CodeBuddy API Key under **Platform admini

Configure provider credentials in the platform UI, not the host's global CLI configuration. Credentials are bound to the responsible actor by the upstream runtime. The home composer and SOP roles each choose a built-in CLI independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. Requirement clarification and notifications continue to use CodeBuddy. A scheduled assistant task can select any supported CLI and runs as an ordinary chat turn; Codex and Claude Code still need that account's own credential. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials.

## Slow workspace opening and restricted networks

Opening a chat workspace reports sandbox/image preparation and initialization
in the chat. New conversation workspaces start empty: the agent manages Git
through its native CLI after opening. Legacy workspaces with platform-managed
repositories also report cloning and branch checkout, including Git's reported
bytes and speed. The same bounded, redacted preparation output is retained in the
run events and logs; preparation failures also appear in `runs_get.problems`,
including workspaces with no SOP nodes. The run stays `waiting` because it is an
idle workspace, while its latest `workspace.opening.*` event records readiness
or failure separately.

Configure these Go-duration values on the process that executes the work (the
local API/worker or the connected runner), then restart that process:

| Variable | Default | Scope |
| --- | --- | --- |
| `AGENTFLOW_WORKSPACE_BUILD_TIMEOUT` | `15m` | Sandbox acquisition, including image build |
| `AGENTFLOW_WORKSPACE_CLONE_TIMEOUT` | `10m` | Each platform-managed workspace clone, including reference-cache fallback |
| `AGENTFLOW_WORKSPACE_BRANCH_TIMEOUT` | `2m` | Each platform-managed workspace repository's branch preparation |
| `AGENTFLOW_WORKSPACE_PREPARE_TIMEOUT` | `5m` | Runner workspace initialization scripts |

These phase deadlines apply in addition to the command limits above: the first
deadline or stall window reached stops the command. Setting a command limit to
`0` does not disable the opening phase deadline. For example, to allow a runner's
platform-managed workspace clone up to 20 minutes, set both `AGENTFLOW_WORKSPACE_CLONE_TIMEOUT=20m` and
`AGENTFLOW_GIT_CLONE_TIMEOUT=20m` on that runner. Ordinary task checkouts retain
the configurable `AGENTFLOW_GIT_CLONE_TIMEOUT` limit (10 minutes by default).
These Git limits do not apply to commands the agent runs through its native CLI.
Invalid or nonpositive workspace phase values use the default. Canceling the opening request also
cancels its runner request and active Git/build command. Upgrade both platform
and runner to receive live runner progress and cancellation; older runners
still return their final result and retain their previous preparation timeout.

A failed open of the conversation's own workspace retains its binding and
existing files. Retry with
`workbench_workspace_open` and no arguments to reuse the current environment
and run. Choosing another sandbox profile switches environments instead.
Passing `workspaceRunId` can attach an existing same-project SOP workspace on
the same execution machine. If that first attachment fails, the conversation
returns to its previous binding (or no binding if it had none). An SOP already
bound to the conversation stays bound after a failed retry. Its files and SOP
lifecycle remain intact.

For platform-managed checkouts, Git cannot resume an interrupted pack download:
an empty incomplete clone is retried, but local files, refs and indexes are
preserved. For local execution, an administrator-configured repository `localPath` alongside
`cloneUrl` supplies the existing `--reference --dissociate` cache. It must be
readable on the execution host. Docker reuses completed image layers. This does
not introduce a shared cache across users' credentials.

For restricted networks:

- Configure `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY`, or Git's `http.proxy`,
for the service account performing the clone. A proxy on the host loopback
address is not automatically reachable from a container or remote runner.
- Configure registry access/proxies on the Docker daemon separately. Package
downloads inside a Dockerfile use that build's network and package sources;
the platform's Git proxy does not configure `apt`, npm or pip for it.
- In the project Dockerfile, use your organization's approved apt mirror and
package indexes. For Debian images, update the appropriate `URIs` in
`/etc/apt/sources.list.d/debian.sources` (or entries in `/etc/apt/sources.list`
on older images) before `apt-get update`. Keep signature verification enabled.
Prebuild a reusable base image when dependencies are large.

An existing workspace freezes its Dockerfile content and additional files.
Opening it after the project Dockerfile changes shows a warning; retrying does
not replace that environment. Save or push work first, then start a new
conversation with the updated sandbox profile to use its new Dockerfile or
mirror configuration. Reopening the same environment in the existing
conversation reuses its frozen workspace.

## Observability schema

After the base tables have been created, run `bash scripts/install-schema-extensions.sh` for the Compose database. It installs absent `run_telemetry.adapter` and `run_logs.level` columns and their indexes from upstream migration `001_run_obs_generated_columns.sql`, then replays the `INSERT IGNORE` starter catalog. Both steps can be repeated without touching existing rows. The installer runs it before printing the address, and `./start.sh pull` runs it again after recreating containers, so an older data volume upgraded to a newer image picks up the columns the new code reads. Application startup does not run data migrations.
Expand Down
Loading
Loading