Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(workspace): edit run workspaces while agents run (#211)
crispinhu2703c3ab662b8c
diff --git a/chatbot/src/ArtifactPanel.jsx b/chatbot/src/ArtifactPanel.jsxindex 536d0cb9..70d3ec3a 100644--- a/chatbot/src/ArtifactPanel.jsx+++ b/chatbot/src/ArtifactPanel.jsx@@ -6,6 +6,7 @@ import { DraftCard } from "./SidePanel";import SopRunPanel, { runStatus } from "./SopRunPanel";import ChangesPanel from "./ChangesPanel";import AgentBrowser from "./AgentBrowser";+import WorkspaceIDE from "./WorkspaceIDE";import { SubagentSession, subagentName, subagentStatus } from "./SubagentSession";import { collectSubagents, resumeMissed } from "./activity";import { IconButton } from "./ui";@@ -199,7 +200,8 @@ export default function ArtifactPanel({const [nodeId, setNodeId] = useState(selected?.nodeId || null);const [search, setSearch] = useState("");const browsing = view === "browser";- const listView = view !== "changes" && !browsing;+ const coding = view === "ide";+ const listView = view !== "changes" && !browsing && !coding;const live = !!chat?.busy;const subagents = collectSubagents(chat?.session?.messages || [],@@ -250,7 +252,8 @@ export default function ArtifactPanel({onClose,nodeId ||(selectedAgent ? `subagent-${selectedAgent.key}` : null) ||- (browsing && workspaceRunId ? "agent-browser" : null),+ (browsing && workspaceRunId ? "agent-browser" : null) ||+ (coding && workspaceRunId ? "workspace-ide" : null),open,);useEffect(@@ -425,7 +428,7 @@ export default function ArtifactPanel({id="conversation-artifacts"role={layout.compact ? "dialog" : "complementary"}aria-modal={layout.compact && open ? "true" : undefined}- aria-label={view === "changes" ? "会话改动" : browsing ? "Agent 浏览器" : "会话产物"}+ aria-label={view === "changes" ? "会话改动" : browsing ? "Agent 浏览器" : coding ? "工作区 IDE" : "会话产物"}aria-hidden={!open || undefined}inert={!open}data-compact={layout.compact || undefined}@@ -478,6 +481,22 @@ export default function ArtifactPanel({<HarnessIcon name="stage-browser" size={14} /><span>浏览器</span></button>+ <button+ type="button"+ role="tab"+ aria-selected={coding}+ className={coding ? "is-active" : ""}+ onClick={() => onViewChange("ide")}+ disabled={!workspaceRunId}+ title={+ workspaceRunId+ ? "在 VS Code 里浏览、编辑本次会话的工作区"+ : "本次会话还没有工作区"+ }+ >+ <HarnessIcon name="stage-ide" size={14} />+ <span>IDE</span>+ </button></div><div className="artifact-panel-actions">{layout.compact ? (@@ -570,6 +589,22 @@ export default function ArtifactPanel({<ChangesPanel changes={workspaceChanges} /></div>) : null}+ {coding ? (+ <div className="artifact-panel-content workspace-ide-content">+ {workspaceRunId && open ? (+ <WorkspaceIDE+ key={workspaceRunId}+ runId={workspaceRunId}+ onMaximize={layout.compact ? undefined : layout.toggleCovered}+ />+ ) : (+ <div className="agent-browser-empty" role="status">+ <HarnessIcon name="stage-ide" size={28} />+ <p>本次会话还没有工作区。让助手打开工作区后,可以在这里用 VS Code 浏览和编辑它的代码。</p>+ </div>+ )}+ </div>+ ) : null}{browsing ? (<div className="artifact-panel-content agent-browser-content">{workspaceRunId && open ? (diff --git a/chatbot/src/WorkspaceIDE.jsx b/chatbot/src/WorkspaceIDE.jsxnew file mode 100644index 00000000..88c12aa8--- /dev/null+++ b/chatbot/src/WorkspaceIDE.jsx@@ -0,0 +1,47 @@+import React, { useEffect } from "react";+import "./workspace-ide.css";++// The same vscode-web workbench the SOP run record embeds (web/vscode.html),+// pointed at the conversation's workspace run. It only knows the run ID, so a+// conversation workspace and a borrowed SOP workspace open the same way.+export function workspaceIDEURL(runId, { embed = false } = {}) {+ const params = new URLSearchParams({ run: runId });+ if (embed) params.set("embed", "1");+ return `/vscode.html?${params.toString()}`;+}++export function openWorkspaceIDEWindow(runId) {+ const name = "agentflow-vscode-" + String(runId || "").replace(/[^A-Za-z0-9_-]/g, "");+ const win = window.open(workspaceIDEURL(runId), name, "popup=yes,width=1440,height=900");+ try {+ win?.focus();+ } catch {+ /* cross-window focus can be refused */+ }+ return !!win;+}++export default function WorkspaceIDE({ runId, onMaximize = () => {} }) {+ useEffect(() => {+ if (!runId) return undefined;+ const onMessage = (event) => {+ if (event.origin !== window.location.origin) return;+ const data = event.data;+ if (data?.type !== "agentflow-vscode" || data.runId !== runId) return;+ if (data.action === "popout") openWorkspaceIDEWindow(runId);+ if (data.action === "maximize") onMaximize();+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, [runId, onMaximize]);+ return (+ <div className="workspace-ide">+ <iframe+ className="workspace-ide-frame"+ aria-label="VS Code"+ src={workspaceIDEURL(runId, { embed: true })}+ allow="clipboard-read; clipboard-write"+ />+ </div>+ );+}diff --git a/chatbot/src/workspace-ide.css b/chatbot/src/workspace-ide.cssnew file mode 100644index 00000000..d7df4b75--- /dev/null+++ b/chatbot/src/workspace-ide.css@@ -0,0 +1,20 @@+/* Workspace IDE in the conversation side panel ("IDE" tab). */+.chat-shell .artifact-panel .workspace-ide-content {+ display: flex;+ flex-direction: column;+ overflow: hidden;+ padding: 0;+}+.workspace-ide {+ display: flex;+ flex: 1;+ min-width: 0;+ min-height: 0;+}+.workspace-ide-frame {+ flex: 1;+ width: 100%;+ min-height: 0;+ border: 0;+ background: var(--surface, #fff);+}diff --git a/chatbot/tests/workspace-ide.test.jsx b/chatbot/tests/workspace-ide.test.jsxnew file mode 100644index 00000000..301dde40--- /dev/null+++ b/chatbot/tests/workspace-ide.test.jsx@@ -0,0 +1,57 @@+import React from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, test, vi } from "vitest";+import ArtifactPanel from "../src/ArtifactPanel.jsx";+import WorkspaceIDE, { workspaceIDEURL } from "../src/WorkspaceIDE.jsx";++afterEach(() => vi.unstubAllGlobals());++describe("side panel IDE tab", () => {+ const chat = { session: { id: "s1", projectId: "p1" }, projectId: "p1", projects: [] };+ const panel = (props) => (+ <div className="chat-shell">+ <header className="conversation-header" />+ <main className="conversation-main" />+ <ArtifactPanel artifacts={[]} runs={[]} selected={null} setSelected={vi.fn()} chat={chat} onClose={vi.fn()} open {...props} />+ </div>+ );++ test("needs a conversation workspace", () => {+ render(panel({ view: "artifacts" }));+ expect(screen.getByRole("tab", { name: /IDE/ })).toBeDisabled();+ });++ test("embeds the workspace in VS Code and follows workspace switches", () => {+ const onViewChange = vi.fn();+ const { rerender } = render(panel({ view: "artifacts", workspaceRunId: "run-9", onViewChange }));+ fireEvent.click(screen.getByRole("tab", { name: /IDE/ }));+ expect(onViewChange).toHaveBeenCalledWith("ide");+ rerender(panel({ view: "ide", workspaceRunId: "run-9", onViewChange }));+ expect(screen.getByRole("complementary", { name: "工作区 IDE" })).toBeInTheDocument();+ const frame = screen.getByLabelText("VS Code");+ expect(frame).toHaveAttribute("src", "/vscode.html?run=run-9&embed=1");+ // A title would show a hover tip over the whole editor.+ expect(frame).not.toHaveAttribute("title");+ rerender(panel({ view: "ide", workspaceRunId: "run-10", onViewChange }));+ expect(screen.getByLabelText("VS Code")).toHaveAttribute("src", "/vscode.html?run=run-10&embed=1");+ });+});++describe("WorkspaceIDE", () => {+ const post = (data, origin = window.location.origin) =>+ window.dispatchEvent(new MessageEvent("message", { data, origin }));++ test("handles popout and maximize only for its own run", () => {+ const open = vi.fn(() => ({ focus() {} }));+ vi.stubGlobal("open", open);+ const onMaximize = vi.fn();+ render(<WorkspaceIDE runId="run-9" onMaximize={onMaximize} />);+ post({ type: "agentflow-vscode", runId: "other", action: "popout" });+ post({ type: "agentflow-vscode", runId: "run-9", action: "popout" }, "https://evil.example");+ expect(open).not.toHaveBeenCalled();+ post({ type: "agentflow-vscode", runId: "run-9", action: "popout" });+ expect(open).toHaveBeenCalledWith(workspaceIDEURL("run-9"), "agentflow-vscode-run-9", expect.any(String));+ post({ type: "agentflow-vscode", runId: "run-9", action: "maximize" });+ expect(onMaximize).toHaveBeenCalledTimes(1);+ });+});diff --git a/chatbot/vite.config.js b/chatbot/vite.config.jsindex 6b5702dd..3e8e6e27 100644--- a/chatbot/vite.config.js+++ b/chatbot/vite.config.js@@ -10,6 +10,12 @@ export default defineConfig({proxy: {"/api": api,"/mcp": api,+ // Workspace IDE tab embeds the platform's vscode-web workbench.+ "/vscode.html": api,+ "/vscode.js": api,+ "/vscode.css": api,+ "/vscode-web": api,+ "/extensions": api,},},});diff --git a/e2e/api/68-workspace-edit.test.mjs b/e2e/api/68-workspace-edit.test.mjsindex 9d6f72ce..40307758 100644--- a/e2e/api/68-workspace-edit.test.mjs+++ b/e2e/api/68-workspace-edit.test.mjs@@ -1,9 +1,10 @@-// Human editing of a run workspace: a repository-bound run stops at an-// approval gate, a user stops the SOP ("takeover" pauses agents), edits files-// with compare-and-swap hashes, inspects the diff and hands the workspace-// back; the run then resumes and finishes with the edit, without pushing.-// Editing is not exclusive to one person: any non-viewer member may edit a-// stopped workspace, and the content hash is what prevents lost updates.+// Human editing of a run workspace: a repository-bound run waits at an+// approval gate while a user edits files with compare-and-swap hashes, like an+// AI IDE — editing never pauses the SOP ("takeover" is a no-op kept for older+// clients). The user inspects the diff and hands the workspace back; the run+// then continues and finishes with the edit, without pushing. Editing is not+// exclusive to one person: any non-viewer member may edit, and the content+// hash is what prevents lost updates.import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { api, get, post, cleanup, ensureProject, tokenOwner, waitRun, tokenBSkip, asB, withProjectMember } from '../lib/api.mjs';@@ -36,13 +37,8 @@ test('setup: a repository-bound run waits at the gate with a written file', { skassert.equal(String((await file('edit.txt')).content).trim(), 'one');});-test('a running SOP workspace cannot be written', { skip: repoSkip }, async () => {- const current = await file('edit.txt');- await write('edit.txt', 'two\n', current.sha256, { expect: 409 });- assert.equal(String((await file('edit.txt')).content).trim(), 'one');-});-test('viewers can neither stop the SOP nor write', { skip: repoSkip || tokenBSkip }, async () => {+test('viewers cannot write', { skip: repoSkip || tokenBSkip }, async () => {const userB = await tokenOwner(cfg.tokenB);const restore = await withProjectMember(userB.id, 'viewer');await api('POST', ws('/takeover'), {}, asB({ expect: 403 }));@@ -53,12 +49,12 @@ test('viewers can neither stop the SOP nor write', { skip: repoSkip || tokenBSkiassert.ok(!(await get(`/api/runs/${runId}`)).pauseRequested, 'a refused takeover must not pause the run');});-test('takeover pauses the run, edits use compare-and-swap, unsafe paths are refused', { skip: repoSkip, timeout: 120_000 }, async () => {+test('editing never pauses the run, edits use compare-and-swap, unsafe paths are refused', { skip: repoSkip, timeout: 120_000 }, async () => {const me = await tokenOwner();+ assert.equal((await get(ws())).readOnly, false, 'a live SOP workspace must open editable');const lease = await post(ws('/takeover'), {});assert.equal(lease.editorId, me.id);- assert.ok(Date.parse(lease.expiresAt) > Date.now());- assert.equal((await get(`/api/runs/${runId}`)).pauseRequested, true, 'taking over must pause agents');+ assert.equal((await get(`/api/runs/${runId}`)).pauseRequested, false, 'editing must not pause agents');const current = await file('edit.txt');assert.match(current.sha256, /^[0-9a-f]{64}$/);@@ -80,7 +76,7 @@ test('takeover pauses the run, edits use compare-and-swap, unsafe paths are refuassert.equal(String((await file('added.txt')).content).trim(), 'new');});-test('another member may edit the stopped workspace; the hash prevents lost updates', { skip: repoSkip || tokenBSkip }, async () => {+test('another member may edit the workspace; the hash prevents lost updates', { skip: repoSkip || tokenBSkip }, async () => {const userB = await tokenOwner(cfg.tokenB);const restore = await withProjectMember(userB.id, 'member');const mine = await file('edit.txt');@@ -128,11 +124,10 @@ test('per-file diff of a file a node created shows an empty original', { skip: rtest('release hands back; resume cannot skip the human gate, approval continues with the edit, nothing pushed', { skip: repoSkip, timeout: 300_000 }, async () => {await post(ws('/release'), {});- // Pausing at an approval gate is not a checkpoint: resume must not approve it.+ // Resume must not skip the human gate.await api('POST', `/api/runs/${runId}/resume`, {}, { expect: 400 });assert.equal((await get(`/api/runs/${runId}`)).nodes.hold.status, 'waiting_approval');await post(`/api/runs/${runId}/approve`, { nodeId: 'hold' });- assert.ok(!(await get(`/api/runs/${runId}`)).pauseRequested, 'approving must clear the pause');// The check node fails unless it reads all the human edits.const done = await waitRun(runId, r => r.status === 'succeeded', { label: 'run succeeded after the human edit' });assert.equal(done.nodes.check.status, 'succeeded');diff --git a/internal/domain/run.go b/internal/domain/run.goindex 5214e420..2a9ddce9 100644--- a/internal/domain/run.go+++ b/internal/domain/run.go@@ -61,6 +61,29 @@ const ConversationWorkspaceWorkflowID = "conversation-workspace"// IsWorkspace distinguishes an on-demand chat workspace from a scheduled SOP.func (r Run) IsWorkspace() bool { return r.Kind == RunKindWorkspace }+// LiveWorkspace reports a chat workspace that is open for edits. It has no SOP+// graph to pause, so Main Bot and people in the IDE edit it side by side and+// rely on expectedSha256 to catch conflicting writes.+func (r Run) LiveWorkspace() bool {+ return r.IsWorkspace() && !r.CancelRequested && r.WorkspaceCleanedAt.IsZero() && (r.Status == "running" || r.Status == "waiting")+}++// HumanEditable reports whether people may edit the workspace in the IDE. Like+// an AI IDE they edit at any time, also while SOP agents run: nothing pauses,+// expectedSha256 catches conflicting writes and agents re-read what changed.+func (r Run) HumanEditable() bool {+ if !r.WorkspaceCleanedAt.IsZero() {+ return false+ }+ switch r.Status {+ case "succeeded", "failed", "cancelled":+ return true+ case "running", "waiting":+ return !r.CancelRequested+ }+ return false+}+// HistoricalGroup is a record of the retired role groups. It has no SOP graph// that could be resumed or retried.func (r Run) HistoricalGroup() bool {diff --git a/internal/domain/run_test.go b/internal/domain/run_test.gonew file mode 100644index 00000000..51dd1054--- /dev/null+++ b/internal/domain/run_test.go@@ -0,0 +1,26 @@+package domain++import (+ "testing"+ "time"+)++func TestRunHumanEditable(t *testing.T) {+ cases := []struct {+ run Run+ want bool+ }{+ {Run{Status: "running"}, true},+ {Run{Status: "waiting"}, true},+ {Run{Status: "succeeded"}, true},+ {Run{Status: "cancelled", CancelRequested: true}, true},+ {Run{Status: "running", CancelRequested: true}, false},+ {Run{Status: "queued"}, false},+ {Run{Status: "running", WorkspaceCleanedAt: time.Now()}, false},+ }+ for _, c := range cases {+ if got := c.run.HumanEditable(); got != c.want {+ t.Errorf("HumanEditable(%+v) = %v want %v", c.run, got, c.want)+ }+ }+}diff --git a/internal/domain/runner_workspace.go b/internal/domain/runner_workspace.goindex 199844a7..eefcac50 100644--- a/internal/domain/runner_workspace.go+++ b/internal/domain/runner_workspace.go@@ -36,7 +36,10 @@ const (// runner's outbound control socket. Responses are transient and are never// persisted in runner_tasks or the run record.type RunnerWorkspaceRequest struct {- RunKind string `json:"runKind,omitempty"`+ RunKind string `json:"runKind,omitempty"`+ // ConcurrentEdit marks a person editing from the IDE: the runner writes and+ // opens terminals beside running tasks instead of waiting for their fence.+ ConcurrentEdit bool `json:"concurrentEdit,omitempty"`CheckpointTransfer *WorkspaceCheckpointTransfer `json:"checkpointTransfer,omitempty"`// Only the control plane may allow a clean checkout to be refreshed, before// any non-preparation node has run. Later nodes keep their frozen baseline.diff --git a/internal/engine/execution_cleanup_cases_test.go b/internal/engine/execution_cleanup_cases_test.goindex 2e0fb2a0..6c0e0aa9 100644--- a/internal/engine/execution_cleanup_cases_test.go+++ b/internal/engine/execution_cleanup_cases_test.go@@ -257,7 +257,7 @@ func TestWorkspacePreparationDirectValidationAndRemoteStates(t *testing.T) {if _, err := e.TrustedWorkspaceRequest("missing", domain.RunnerWorkspaceRequest{}); err == nil {t.Fatal("missing trusted request succeeded")}- if _, err := e.HandlePreparedWorkspaceTerminal(context.Background(), "missing", &runtime.TerminalPool{}, "scope", domain.WorkspaceTerminalRequest{Operation: "open"}, 0); err == nil {+ if _, err := e.HandlePreparedWorkspaceTerminal(context.Background(), domain.Run{ID: "missing"}, &runtime.TerminalPool{}, "scope", domain.WorkspaceTerminalRequest{Operation: "open"}, 0); err == nil {t.Fatal("unprepared terminal opened")}if state, err := e.PrepareNodeWorkspace(context.Background(), domain.Run{}, &runEnvironment{}); err != nil || state.Status != "ready" {diff --git a/internal/engine/workspace_artifacts.go b/internal/engine/workspace_artifacts.goindex c91f079b..dfeef49f 100644--- a/internal/engine/workspace_artifacts.go+++ b/internal/engine/workspace_artifacts.go@@ -106,6 +106,12 @@ func (e *Engine) restoreWorkspaceFiles(ctx context.Context, run domain.Run, filereturn nil, err}if result.Error != "" {+ // An open IDE terminal or a snapshot holds the fence. Refilling only+ // adds missing archived files, so it waits for the next use instead+ // of failing the save or terminal input that asked for it.+ if runnerWorkspaceBusy(result) {+ return nil, nil+ }return nil, fmt.Errorf("补回归档产物失败(执行机器需支持 restore_artifacts):%s", result.Error)}var report struct {diff --git a/internal/engine/workspace_busy_test.go b/internal/engine/workspace_busy_test.goindex bb58e563..fdc84acf 100644--- a/internal/engine/workspace_busy_test.go+++ b/internal/engine/workspace_busy_test.go@@ -10,6 +10,7 @@ import ("agentflow/internal/domain""agentflow/internal/repo"+ "agentflow/internal/runtime")func busyPreparationRun(t *testing.T, e *Engine, st *repo.Store, id string) domain.Run {@@ -101,3 +102,40 @@ func TestRunnerWorkspaceBusyClassification(t *testing.T) {}}}++// An IDE terminal holds the runner fence after the SOP finished. Refilling+// archived files must not fail the save or terminal input that triggered it.+func TestArchivedRefillWaitsWhileRunnerIsBusy(t *testing.T) {+ e, st := cvEEngine(t)+ run := busyPreparationRun(t, e, st, "refill-busy-run")+ files := []domain.WorkspaceArtifactFile{{Path: "hello.md", Content: "hi", SHA256: runtime.WorkspaceContentSHA("hi")}}+ e.WorkspaceCheckpointTransport = func(_ context.Context, _ domain.Run, request domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error) {+ if request.Operation != domain.RunnerWorkspaceOperationArtifacts {+ t.Fatalf("unexpected operation %s", request.Operation)+ }+ return domain.RunnerWorkspaceResponse{Status: 409, Code: domain.WorkspaceErrorBusy, Error: "workspace is still in use"}, nil+ }+ if restored, err := e.restoreWorkspaceFiles(context.Background(), run, files); err != nil || len(restored) != 0 {+ t.Fatalf("busy refill must be skipped: %v %v", restored, err)+ }+ e.WorkspaceCheckpointTransport = func(context.Context, domain.Run, domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error) {+ return domain.RunnerWorkspaceResponse{Status: 409, Error: "restore failed: disk full"}, nil+ }+ if _, err := e.restoreWorkspaceFiles(context.Background(), run, files); err == nil {+ t.Fatal("a real refill failure must still surface")+ }+}++// The readiness shortcut reads node states. A run without them (a bare locked+// row) would look like it has nothing to prepare.+func TestPreparationPlanNeedsNodeStates(t *testing.T) {+ run := domain.Run{WorkflowSnapshot: domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ID: "setup", Type: "script", Script: "make deps", RunOnWorkspaceRebuild: true}}}}+ run.Nodes = map[string]*domain.NodeRun{"setup": {NodeID: "setup", Status: "succeeded"}}+ if runtime.WorkspacePreparationTrivial(workspacePreparationPlan(run)) {+ t.Fatal("a succeeded preparation step must keep the readiness check")+ }+ run.Nodes = nil+ if !runtime.WorkspacePreparationTrivial(workspacePreparationPlan(run)) {+ t.Fatal("expected a run without node states to look trivial; callers must pass RunState")+ }+}diff --git a/internal/engine/workspace_checkpoint_transport.go b/internal/engine/workspace_checkpoint_transport.goindex 92f6287b..c2938802 100644--- a/internal/engine/workspace_checkpoint_transport.go+++ b/internal/engine/workspace_checkpoint_transport.go@@ -218,7 +218,7 @@ func (e *Engine) HandleWorkspaceCheckpoint(w http.ResponseWriter, r *http.Requesresult.Payload = json.RawMessage(`{"ok":true}`)break}- value, err := e.HandlePreparedWorkspaceTerminal(r.Context(), run.ID, &e.workspaceTerminals, scope, *request.Terminal, request.TerminalOwner)+ value, err := e.HandlePreparedWorkspaceTerminal(r.Context(), run, &e.workspaceTerminals, scope, *request.Terminal, request.TerminalOwner)result.Payload, _ = json.Marshal(value)if err != nil {result.Error = err.Error()diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.goindex d23bfd44..519a1ff2 100644--- a/internal/engine/workspace_preparation.go+++ b/internal/engine/workspace_preparation.go@@ -283,9 +283,13 @@ func (e *Engine) EnsureWorkspaceReady(ctx context.Context, id string) (runtime.Wif hasRunningNode(run) || env.activeExecutions.Load() > 0 || e.workspaceTerminals.HasRunScope(id) || e.WorkspaceActive != nil && e.WorkspaceActive(run) {state := runtime.ReadWorkspacePreparationStatus(env.Workspace(), env.ID())epoch, err := runtime.ReadSandboxEnvironmentIdentity(ctx, env.sandbox)- if run.IsWorkspace() && err == nil && runtime.WorkspacePreparationReusable(state, workspacePreparationPlan(run), run.RepositoryContexts(), epoch) {+ // The environment agents already run in serves the IDE terminal too.+ if err == nil && runtime.WorkspacePreparationReusable(state, workspacePreparationPlan(run), run.RepositoryContexts(), epoch) {return state, nil}+ if state.Status != "preparing" && runtime.WorkspacePreparationTrivial(workspacePreparationPlan(run)) {+ return runtime.WorkspacePreparationStatus{Status: "ready", Steps: []runtime.WorkspacePreparationStep{}}, nil+ }return runtime.WorkspacePreparationStatus{Status: "unprepared", Error: "成员或终端正在使用工作区,请结束当前操作后重新准备", Steps: []runtime.WorkspacePreparationStep{}}, fmt.Errorf("成员或终端正在使用工作区,请结束当前操作后重新准备")}return e.prepareLocalEnvironment(ctx, run, env)@@ -333,10 +337,18 @@ func (e *Engine) HandleWorkspaceTerminal(ctx context.Context, id string, pool *rreturn runtime.TerminalResult{}, err}}- return e.HandlePreparedWorkspaceTerminal(ctx, id, pool, scope, req, actorID)+ run, _ := e.repo.RunState(id)+ run.ID = id+ return e.HandlePreparedWorkspaceTerminal(ctx, run, pool, scope, req, actorID)}-func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, id string, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest, actorID int64) (runtime.TerminalResult, error) {+// HandlePreparedWorkspaceTerminal takes the run from its caller, which may+// hold the run row locked: reading it again here would wait on that lock.+// The run must carry its node states (RunState, not a bare locked row):+// without them every succeeded preparation step looks pending and the+// readiness check would be skipped as if there were nothing to prepare.+func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, run domain.Run, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest, actorID int64) (runtime.TerminalResult, error) {+ id := run.IDif req.Operation != "open" {return pool.HandleSandbox(ctx, nil, scope, req, nil)}@@ -349,7 +361,8 @@ func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, id string,state := runtime.ReadWorkspacePreparationStatus(env.Workspace(), env.ID())epoch, err := runtime.ReadSandboxEnvironmentIdentity(ctx, env.sandbox)- if err != nil || state.Status != "ready" || state.Environment != epoch {+ trivial := len(run.WorkflowSnapshot.Nodes) > 0 && runtime.WorkspacePreparationTrivial(workspacePreparationPlan(run))+ if !trivial && (err != nil || state.Status != "ready" || state.Environment != epoch) {return runtime.TerminalResult{}, fmt.Errorf("工作区执行环境已变化,请重新准备后打开终端")}sshKeys := env.credentialSnapshot().GitSSHKeysdiff --git a/internal/engine/workspace_preparation_test.go b/internal/engine/workspace_preparation_test.goindex ab42ff74..0ae7e9f2 100644--- a/internal/engine/workspace_preparation_test.go+++ b/internal/engine/workspace_preparation_test.go@@ -272,3 +272,77 @@ func TestWorkspacePreparationTrustedRequestCarriesWorkspaceKind(t *testing.T) {t.Fatal("group mode lost during filtered plan projection", request)}}++// While agents or a terminal hold the workspace, an IDE request reuses the+// environment they already run in, reports a trivial plan as ready, and only+// refuses when real preparation would have to run underneath them.+func TestEnsureWorkspaceReadyWhileWorkspaceBusy(t *testing.T) {+ t.Parallel()+ t.Run("reuses prepared environment", func(t *testing.T) {+ e, id := checkpointFixture(t)+ completedPreparationRun(t, e, id)+ if state, err := e.EnsureWorkspaceReady(context.Background(), id); err != nil || state.Status != "ready" {+ t.Fatal(state, err)+ }+ e.WorkspaceActive = func(domain.Run) bool { return true }+ state, err := e.EnsureWorkspaceReady(context.Background(), id)+ if err != nil || state.Status != "ready" {+ t.Fatalf("busy prepared workspace = %+v, %v", state, err)+ }+ raw, _ := os.ReadFile(filepath.Join(e.RunWorkspace(id), ".agentflow", "env-count"))+ if string(raw) != "run\n" {+ t.Fatalf("busy workspace replayed preparation: %q", raw)+ }+ })+ t.Run("trivial plan is ready", func(t *testing.T) {+ e, id := checkpointFixture(t)+ run := completedPreparationRun(t, e, id)+ for i := range run.WorkflowSnapshot.Nodes {+ run.WorkflowSnapshot.Nodes[i].RunOnWorkspaceRebuild = false+ }+ if err := e.repo.PutRun(run); err != nil {+ t.Fatal(err)+ }+ e.WorkspaceActive = func(domain.Run) bool { return true }+ state, err := e.EnsureWorkspaceReady(context.Background(), id)+ if err != nil || state.Status != "ready" || len(state.Steps) != 0 {+ t.Fatalf("busy trivial workspace = %+v, %v", state, err)+ }+ if _, err := os.Stat(filepath.Join(e.RunWorkspace(id), ".agentflow", "env-count")); !os.IsNotExist(err) {+ t.Fatal("trivial plan ran a script")+ }+ })+ t.Run("unprepared plan is refused", func(t *testing.T) {+ e, id := checkpointFixture(t)+ completedPreparationRun(t, e, id)+ e.WorkspaceActive = func(domain.Run) bool { return true }+ state, err := e.EnsureWorkspaceReady(context.Background(), id)+ if err == nil || state.Status != "unprepared" || !strings.Contains(err.Error(), "成员或终端正在使用工作区") {+ t.Fatalf("busy unprepared workspace = %+v, %v", state, err)+ }+ })+}++// A run with nothing to replay never writes a ready preparation status; the+// IDE terminal must still open in the environment agents are using.+func TestWorkspaceTerminalOpensForTrivialPlanWhileBusy(t *testing.T) {+ t.Parallel()+ e, id := checkpointFixture(t)+ run := completedPreparationRun(t, e, id)+ for i := range run.WorkflowSnapshot.Nodes {+ run.WorkflowSnapshot.Nodes[i].RunOnWorkspaceRebuild = false+ }+ if err := e.repo.PutRun(run); err != nil {+ t.Fatal(err)+ }+ e.WorkspaceActive = func(domain.Run) bool { return true }+ var pool runtime.TerminalPool+ opened, err := e.HandleWorkspaceTerminal(context.Background(), id, &pool, "trivial:1", domain.WorkspaceTerminalRequest{Operation: "open"}, 0)+ if err != nil || opened.ID == "" {+ t.Fatalf("trivial busy terminal = %+v, %v", opened, err)+ }+ defer pool.CloseScope("trivial:1")+ if state := runtime.ReadWorkspacePreparationStatus(e.RunWorkspace(id), ""); state.Status == "ready" {+ t.Fatalf("precondition: trivial plan wrote a ready status %+v", state)+ }+}diff --git a/internal/httpapi/run_workspace.go b/internal/httpapi/run_workspace.goindex 46075d6b..357b432b 100644--- a/internal/httpapi/run_workspace.go+++ b/internal/httpapi/run_workspace.go@@ -638,7 +638,7 @@ func collectWorkspaceChanges(ctx context.Context, root string, run domain.Run) (if _, err := os.Stat(filepath.Join(repository.path, ".git")); err != nil {continue}- out, err := exec.CommandContext(ctx, "git", "-C", repository.path, "status", "--porcelain=v1", "-z", "--untracked-files=all").Output()+ out, err := exec.CommandContext(ctx, "git", "--no-optional-locks", "-C", repository.path, "status", "--porcelain=v1", "-z", "--untracked-files=all").Output()if err != nil {return changes, "Git 状态读取失败"}@@ -684,7 +684,9 @@ func readWorkspaceDiff(ctx context.Context, root string, run domain.Run, raw str}rel = strings.TrimPrefix(raw, prefix)}- args := []string{"-C", repository.path, "diff", "--no-ext-diff", "--no-color", "HEAD", "--"}+ // Browsing must never take .git/index.lock: a concurrent preparation+ // or commit would otherwise fail with "index.lock: File exists".+ args := []string{"--no-optional-locks", "-C", repository.path, "diff", "--no-ext-diff", "--no-color", "HEAD", "--"}if rel != "" {args = append(args, filepath.FromSlash(rel))}diff --git a/internal/httpapi/run_workspace_edit.go b/internal/httpapi/run_workspace_edit.goindex a9105e76..6c0e66a7 100644--- a/internal/httpapi/run_workspace_edit.go+++ b/internal/httpapi/run_workspace_edit.go@@ -59,20 +59,8 @@ func (h *runsHandlers) workspaceTakeover(c *gin.Context) {if !ok {return}- // Enabling edit implicitly pauses agents; callers no longer need a separate pause click.- if run.Status == "running" || (run.Status == "waiting" && !run.PauseRequested) {- if err := h.engine.Pause(run.ID); err != nil {- c.JSON(409, gin.H{"error": err.Error()})- return- }- run, _ = h.repo.RunState(run.ID)- }- tasks, err := h.repo.ActiveRunnerTasksForRun(run.ID)- if err != nil || len(tasks) > 0 {- c.JSON(409, gin.H{"error": "正在停止执行,请稍后重试启用编辑"})- return- }- if err = h.repo.AcquireWorkspaceEditor(run.ID, user); err != nil {+ // Kept for older clients. People edit at any time, so this pauses nothing.+ if err := h.repo.AcquireWorkspaceEditor(run.ID, user); err != nil {c.JSON(409, gin.H{"error": err.Error()})return}@@ -112,7 +100,7 @@ func (h *runsHandlers) workspaceWrite(c *gin.Context) {}ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)defer cancel()- response, err := h.runnerControls.requestWorkspace(ctx, runnerID, domain.RunnerWorkspaceRequest{RunID: runnerWorkspaceRunID(locked), RunStatus: locked.Status, WorkspaceLayout: run.ExecutionContext.RunnerWorkspaceLayout, RunKind: mainBotWorkspaceMode(c, locked), Operation: domain.RunnerWorkspaceOperationWrite, Path: req.Path, Content: req.Content, ExpectedSHA256: req.ExpectedSHA, TerminalOwner: user})+ response, err := h.runnerControls.requestWorkspace(ctx, runnerID, domain.RunnerWorkspaceRequest{RunID: runnerWorkspaceRunID(locked), RunStatus: locked.Status, WorkspaceLayout: run.ExecutionContext.RunnerWorkspaceLayout, RunKind: mainBotWorkspaceMode(c, locked), ConcurrentEdit: humanWorkspaceEdit(c, locked), Operation: domain.RunnerWorkspaceOperationWrite, Path: req.Path, Content: req.Content, ExpectedSHA256: req.ExpectedSHA, TerminalOwner: user})if err != nil {return fmt.Errorf("执行端写入失败:%w", err)}@@ -162,7 +150,10 @@ func (h *runsHandlers) workspaceWritable(c *gin.Context, run domain.Run) bool {allowed = true}}- return allowed && ((run.Status == "waiting" && run.PauseRequested && !run.CancelRequested) || run.Status == "succeeded" || run.Status == "failed" || run.Status == "cancelled")+ if mainBotWorkspaceRun(c.Request.Context()) == run.ID {+ return run.LiveWorkspace() || (run.Status == "waiting" && run.PauseRequested && !run.CancelRequested) || domain.TerminalRunStatus(run.Status)+ }+ return allowed && run.HumanEditable()}func (h *runsHandlers) workspaceTerminal(c *gin.Context) {@@ -194,6 +185,7 @@ func (h *runsHandlers) workspaceTerminal(c *gin.Context) {trustedRequest.RunStatus = locked.StatustrustedRequest.WorkspaceLayout = locked.ExecutionContext.RunnerWorkspaceLayouttrustedRequest.RunKind = mainBotWorkspaceMode(c, locked)+ trustedRequest.ConcurrentEdit = humanWorkspaceEdit(c, locked)if runnerID != "" {if h.runnerControls == nil {return fmt.Errorf("执行端未连接")@@ -227,7 +219,7 @@ func (h *runsHandlers) workspaceTerminal(c *gin.Context) {result = json.RawMessage(response.Payload)return nil}- r, err := h.engine.HandlePreparedWorkspaceTerminal(c.Request.Context(), run.ID, &h.terminals, fmt.Sprintf("%s:%d", run.ID, user), req, user)+ r, err := h.engine.HandlePreparedWorkspaceTerminal(c.Request.Context(), run, &h.terminals, fmt.Sprintf("%s:%d", run.ID, user), req, user)result = rreturn err})@@ -298,6 +290,16 @@ func (h *runsHandlers) withWorkspaceWriter(c *gin.Context, runID string, user in}return h.repo.WithWorkspaceEditor(runID, user, fn)}++// humanWorkspaceEdit marks IDE requests on runs that may still have agents+// running, which the runner serves beside those tasks (sharing their gate)+// instead of waiting for their fence. Finished runs keep the exclusive fence.+func humanWorkspaceEdit(c *gin.Context, run domain.Run) bool {+ return mainBotWorkspaceRun(c.Request.Context()) != run.ID && run.HumanEditable() && !domain.TerminalRunStatus(run.Status)+}++// mainBotWorkspaceMode tells the runner to apply the live-workspace rule to+// Main Bot (no SOP fence on its conversation workspace).func mainBotWorkspaceMode(c *gin.Context, run domain.Run) string {if mainBotWorkspaceRun(c.Request.Context()) == run.ID {return run.Kinddiff --git a/internal/httpapi/workspace_cases_test.go b/internal/httpapi/workspace_cases_test.goindex bfffb35f..390bec73 100644--- a/internal/httpapi/workspace_cases_test.go+++ b/internal/httpapi/workspace_cases_test.go@@ -3,6 +3,8 @@ package httpapiimport ("bytes""context"+ "crypto/sha256"+ "encoding/hex""encoding/json""fmt""net/http"@@ -372,8 +374,9 @@ func TestWorkspaceMoreEditAuthorizationAndErrors(t *testing.T) {rec := httptest.NewRecorder()c, _ := gin.CreateTestContext(rec)c.Request = authedRequest(t, httptest.NewRequest(http.MethodGet, "/", nil), f.user)+ // People edit at any time, also while agents run.got := h.workspaceWritable(c, probe)- want := status != "running"+ want := trueif got != want {t.Errorf("workspaceWritable(%s) = %v want %v", status, got, want)}@@ -462,3 +465,71 @@ func TestWorkspaceDeletedFileCancelledSearchAndTimeout(t *testing.T) {t.Fatalf("large search = %#v truncated=%v err=%v", results, truncated, err)}}++// The chat side panel embeds the same IDE on a conversation workspace. Enabling+// edit there must not pause it: Main Bot keeps working beside the person.+func TestConversationWorkspaceIDEEditsWithoutPausing(t *testing.T) {+ f := cvBNewHTTPFixture(t)+ run := domain.Run{ID: "cvb-chat-ws", Kind: domain.RunKindWorkspace, WorkflowID: domain.ConversationWorkspaceWorkflowID, Status: "waiting", ExecutionContext: domain.TelemetryContext{ProjectID: "platform"}, Nodes: map[string]*domain.NodeRun{}}+ if err := f.s.PutRun(run); err != nil {+ t.Fatal(err)+ }+ cvBWrite(t, filepath.Join(f.e.RunWorkspace(run.ID), "note.txt"), []byte("old"))++ rec := cvBRequest(t, f, http.MethodGet, "/api/runs/"+run.ID+"/workspace", nil, true)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"readOnly":false`) {+ t.Fatalf("workspace info = %d: %s", rec.Code, rec.Body.String())+ }+ if rec := cvBRequest(t, f, http.MethodPost, "/api/runs/"+run.ID+"/workspace/takeover", nil, true); rec.Code != http.StatusOK {+ t.Fatalf("takeover = %d: %s", rec.Code, rec.Body.String())+ }+ if got, _ := f.s.RunState(run.ID); got.PauseRequested || got.Status != "waiting" {+ t.Fatalf("takeover paused the conversation workspace: status=%s pause=%v", got.Status, got.PauseRequested)+ }+ sum := sha256.Sum256([]byte("old"))+ body := map[string]any{"path": "note.txt", "content": "new", "expectedSha256": hex.EncodeToString(sum[:])}+ if rec := cvBRequest(t, f, http.MethodPut, "/api/runs/"+run.ID+"/workspace/file", body, true); rec.Code != http.StatusOK {+ t.Fatalf("write = %d: %s", rec.Code, rec.Body.String())+ }++ cancelled := run+ cancelled.ID, cancelled.CancelRequested = "cvb-chat-ws-cancel", true+ if err := f.s.PutRun(cancelled); err != nil {+ t.Fatal(err)+ }+ if rec := cvBRequest(t, f, http.MethodPut, "/api/runs/"+cancelled.ID+"/workspace/file", body, true); rec.Code == http.StatusOK {+ t.Fatalf("cancelling workspace accepted a write: %s", rec.Body.String())+ }+}++// Like an AI IDE, people edit a running SOP's workspace without pausing it.+func TestRunningSOPWorkspaceEditableWithoutPausing(t *testing.T) {+ f := cvBNewHTTPFixture(t)+ run := domain.Run{ID: "cvb-sop-live", Status: "running", ExecutionContext: domain.TelemetryContext{ProjectID: "platform"}, Nodes: map[string]*domain.NodeRun{"build": {Status: "running"}}}+ if err := f.s.PutRun(run); err != nil {+ t.Fatal(err)+ }+ cvBWrite(t, filepath.Join(f.e.RunWorkspace(run.ID), "note.txt"), []byte("old"))+ if rec := cvBRequest(t, f, http.MethodGet, "/api/runs/"+run.ID+"/workspace", nil, true); !strings.Contains(rec.Body.String(), `"readOnly":false`) {+ t.Fatalf("workspace info = %d: %s", rec.Code, rec.Body.String())+ }+ sum := sha256.Sum256([]byte("old"))+ body := map[string]any{"path": "note.txt", "content": "new", "expectedSha256": hex.EncodeToString(sum[:])}+ if rec := cvBRequest(t, f, http.MethodPut, "/api/runs/"+run.ID+"/workspace/file", body, true); rec.Code != http.StatusOK {+ t.Fatalf("write = %d: %s", rec.Code, rec.Body.String())+ }+ if rec := cvBRequest(t, f, http.MethodPut, "/api/runs/"+run.ID+"/workspace/file", body, true); rec.Code != http.StatusConflict {+ t.Fatalf("stale write = %d: %s", rec.Code, rec.Body.String())+ }+ if got, _ := f.s.RunState(run.ID); got.PauseRequested || got.Status != "running" {+ t.Fatalf("editing paused the SOP: status=%s pause=%v", got.Status, got.PauseRequested)+ }+ queued := run+ queued.ID, queued.Status, queued.Nodes = "cvb-sop-queued", "queued", map[string]*domain.NodeRun{}+ if err := f.s.PutRun(queued); err != nil {+ t.Fatal(err)+ }+ if rec := cvBRequest(t, f, http.MethodPost, "/api/runs/"+queued.ID+"/workspace/takeover", nil, true); rec.Code != http.StatusConflict {+ t.Fatalf("queued takeover = %d: %s", rec.Code, rec.Body.String())+ }+}diff --git a/internal/repo/run_workspace_edit.go b/internal/repo/run_workspace_edit.goindex 043543d9..9a065ed7 100644--- a/internal/repo/run_workspace_edit.go+++ b/internal/repo/run_workspace_edit.go@@ -14,9 +14,9 @@ func workspacePaused(row runRow) bool {return ((row.Status == "waiting" && row.PauseRequested && !row.CancelRequested) || row.Status == "succeeded" || row.Status == "failed" || row.Status == "cancelled") && row.WorkspaceCleaned == nil}-// AcquireWorkspaceEditor pauses-compatible marker for callers that still hit-// /workspace/takeover. It no longer grants an exclusive lease — any project-// writer may edit once the run is stopped.+// AcquireWorkspaceEditor is a compatibility marker for callers that still hit+// /workspace/takeover. It no longer grants an exclusive lease or pauses+// anything — any project writer may edit while the run is HumanEditable.func (r *RunsRepo) AcquireWorkspaceEditor(runID string, userID int64) error {if userID <= 0 {return fmt.Errorf("请先登录")@@ -26,15 +26,9 @@ func (r *RunsRepo) AcquireWorkspaceEditor(runID string, userID int64) error {if err != nil {return err}- if !workspacePaused(row) {- return fmt.Errorf("请先停止执行后再启用编辑")- }- var count int64- if err = tx.Model(&runNodeRow{}).Where("run_id = ? AND status = ?", runID, "running").Count(&count).Error; err != nil {- return err- }- if count > 0 {- return fmt.Errorf("节点仍在停止,请稍后启用编辑")+ // People edit beside running agents, so running nodes do not block this.+ if !runFromRow(row).HumanEditable() {+ return fmt.Errorf("工作区已清理或正在取消,无法编辑")}// Clear any stale lease columns so resume paths stay clean.return tx.Model(&runRow{}).Where("id = ?", runID).Updates(map[string]any{@@ -43,14 +37,14 @@ func (r *RunsRepo) AcquireWorkspaceEditor(runID string, userID int64) error {})}-// WithWorkspaceEditor runs fn while the run is stopped for human editing.-// Exclusive editor identity is no longer required; agents re-read before write.+// WithWorkspaceEditor runs fn for a person editing in the IDE, at any time the+// workspace is HumanEditable. Agents re-read before write; the hash guards saves.func (r *RunsRepo) WithWorkspaceEditor(runID string, userID int64, fn func(domain.Run) error) error {return r.withWorkspaceWriter(runID, userID, false, fn)}-// Main Bot may edit its idle conversation workspace. SOP-// execution still requires a stopped run, just like the IDE.+// WithMainBotWorkspace lets Main Bot edit a live conversation workspace as is;+// a borrowed SOP workspace must be stopped first (workbench_workspace_sop).func (r *RunsRepo) WithMainBotWorkspace(runID string, userID int64, fn func(domain.Run) error) error {return r.withWorkspaceWriter(runID, userID, true, fn)}@@ -64,8 +58,11 @@ func (r *RunsRepo) withWorkspaceWriter(runID string, userID int64, mainBot bool,return err}run := runFromRow(row)- workspaceWrite := mainBot && run.IsWorkspace() && !run.CancelRequested && row.WorkspaceCleaned == nil && (run.Status == "running" || run.Status == "waiting")- if !workspacePaused(row) && !workspaceWrite {+ allowed := run.HumanEditable()+ if mainBot {+ allowed = workspacePaused(row) || run.LiveWorkspace()+ }+ if !allowed {return fmt.Errorf("请先停止 SOP 执行后再编辑工作区")}return fn(run)diff --git a/internal/repo/run_workspace_edit_test.go b/internal/repo/run_workspace_edit_test.goindex 74645973..1886ef2a 100644--- a/internal/repo/run_workspace_edit_test.go+++ b/internal/repo/run_workspace_edit_test.go@@ -7,7 +7,7 @@ import ("time")-func TestWorkspaceEditorRequiresPausedRun(t *testing.T) {+func TestWorkspaceEditorEditsWithoutPausing(t *testing.T) {st, err := OpenTest()if err != nil {t.Fatal(err)@@ -36,11 +36,16 @@ func TestWorkspaceEditorRequiresPausedRun(t *testing.T) {if err = st.PutRun(loaded); err != nil {t.Fatal(err)}- if err = st.AcquireWorkspaceEditor(run.ID, 10); err == nil {- t.Fatal("running run acquired edit")+ // Like an AI IDE, people edit beside running agents.+ if err = st.AcquireWorkspaceEditor(run.ID, 10); err != nil {+ t.Fatalf("running run refused edit: %v", err)+ }+ if err = st.WithWorkspaceEditor(run.ID, 10, func(domain.Run) error { return nil }); err != nil {+ t.Fatalf("running run refused write: %v", err)}- if err = st.WithWorkspaceEditor(run.ID, 10, func(domain.Run) error { return nil }); err == nil {- t.Fatal("running run allowed write")+ // Main Bot still needs a borrowed SOP stopped first.+ if err = st.WithMainBotWorkspace(run.ID, 10, func(domain.Run) error { return nil }); err == nil {+ t.Fatal("Main Bot wrote into a running SOP")}}diff --git a/internal/runner/workspace.go b/internal/runner/workspace.goindex 4942f5e7..14c7f868 100644--- a/internal/runner/workspace.go+++ b/internal/runner/workspace.go@@ -167,9 +167,21 @@ func (d *Daemon) readRunnerWorkspace(ctx context.Context, request domain.RunnerWreturn runnerWorkspacePayload(d.runnerWorkspacePreparationStatus(ctx, root, request))}- workspaceWrite := request.RunKind == domain.RunKindWorkspace && (request.RunStatus == "running" || request.RunStatus == "waiting")+ liveWorkspace := request.RunKind == domain.RunKindWorkspace && (request.RunStatus == "running" || request.RunStatus == "waiting")+ // A person editing from the IDE only shares the workspace with running+ // agent tasks (gate readers). Preparation, restore and checkpoints hold the+ // gate exclusively and must still exclude the edit.+ concurrentEdit := request.ConcurrentEdit && !liveWorkspace+ workspaceWrite := liveWorkspace || concurrentEditswitch request.Operation {case domain.RunnerWorkspaceOperationArtifacts:+ if concurrentEdit {+ gate := d.requestGate(request)+ if !gate.TryRLock() {+ return workspaceBusyResponse("workspace is still in use")+ }+ defer gate.RUnlock()+ }if !workspaceWrite {gate := d.requestGate(request)if !gate.TryLock() {@@ -220,7 +232,15 @@ func (d *Daemon) readRunnerWorkspace(ctx context.Context, request domain.RunnerWcase domain.RunnerWorkspaceOperationWrite:// The same human may save files while their terminal holds the fence.scope := fmt.Sprintf("%s:%d", request.RunID, request.TerminalOwner)- if !workspaceWrite && (request.TerminalOwner <= 0 || !d.workspaceTerminals.HasScope(scope)) {+ ownTerminal := request.TerminalOwner > 0 && d.workspaceTerminals.HasScope(scope)+ if concurrentEdit && !ownTerminal {+ gate := d.requestGate(request)+ if !gate.TryRLock() {+ return workspaceBusyResponse("workspace is being prepared, restored or saved")+ }+ defer gate.RUnlock()+ }+ if !workspaceWrite && !ownTerminal {gate := d.requestGate(request)if !gate.TryLock() {return workspaceBusyResponse("execution is still stopping")@@ -641,7 +661,7 @@ func runnerCollectWorkspaceChanges(ctx context.Context, root string, repositorieif _, err := os.Stat(filepath.Join(repository.path, ".git")); err != nil {continue}- out, err := exec.CommandContext(ctx, "git", "-C", repository.path, "status", "--porcelain=v1", "-z", "--untracked-files=all").Output()+ out, err := exec.CommandContext(ctx, "git", "--no-optional-locks", "-C", repository.path, "status", "--porcelain=v1", "-z", "--untracked-files=all").Output()if err != nil {return changes, "Git 状态读取失败"}@@ -687,7 +707,9 @@ func runnerReadWorkspaceDiff(ctx context.Context, root string, repositories []do}rel = strings.TrimPrefix(raw, prefix)}- args := []string{"-C", repository.path, "diff", "--no-ext-diff", "--no-color", "HEAD", "--"}+ // Browsing must never take .git/index.lock: a concurrent preparation+ // or commit would otherwise fail with "index.lock: File exists".+ args := []string{"--no-optional-locks", "-C", repository.path, "diff", "--no-ext-diff", "--no-color", "HEAD", "--"}if rel != "" {args = append(args, filepath.FromSlash(rel))}diff --git a/internal/runner/workspace_preparation.go b/internal/runner/workspace_preparation.goindex 4ab568c6..71993d86 100644--- a/internal/runner/workspace_preparation.go+++ b/internal/runner/workspace_preparation.go@@ -211,6 +211,9 @@ func (d *Daemon) runnerWorkspacePreparationStatus(ctx context.Context, root stristate.Error = "上次工作区准备已中断,请重新准备"}if state.Status != "ready" {+ if state.Status != "preparing" && request.Workflow != nil && runtime.WorkspacePreparationTrivial(*request.Workflow) {+ return runtime.WorkspacePreparationStatus{Status: "ready", Steps: []runtime.WorkspacePreparationStep{}}+ }return state}epoch, err := runtime.ReadSandboxEnvironmentIdentity(ctx, sb)@@ -236,7 +239,7 @@ func (d *Daemon) openBusyGroupTerminal(ctx context.Context, root, scope string,release := onceRelease(releaseSandbox, gate.RUnlock)state := runtime.ReadWorkspacePreparationStatus(root, sb.ID())epoch, err := runtime.ReadSandboxEnvironmentIdentity(ctx, sb)- if err != nil || !runtime.WorkspacePreparationReusable(state, *request.Workflow, request.Repositories, epoch) {+ if !runtime.WorkspacePreparationTrivial(*request.Workflow) && (err != nil || !runtime.WorkspacePreparationReusable(state, *request.Workflow, request.Repositories, epoch)) {release()return runtime.TerminalResult{}, fmt.Errorf("workspace environment changed; wait until active execution finishes before preparing")}diff --git a/internal/runner/workspace_preparation_test.go b/internal/runner/workspace_preparation_test.goindex a922dd63..2a38f018 100644--- a/internal/runner/workspace_preparation_test.go+++ b/internal/runner/workspace_preparation_test.go@@ -558,3 +558,93 @@ func TestConversationWorkspaceMaterializesOnConnectedRunner(t *testing.T) {t.Fatal("second open moved the checkout")}}++// A SOP without preparation steps never stamps readiness: its nodes skip+// preparation. While a node runs, the IDE still joins that live environment.+func TestRunnerIDEJoinsRunningSOPWithoutPreparationSteps(t *testing.T) {+ d, request, root := runnerPreparationFixture(t)+ defer d.closeAllRunSandboxes(context.Background())+ request.RunStatus = "running"+ request.Workflow = &domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ID: "agent", Type: "agent"}}}+ task := domain.RunnerTask{ID: "running-node", RunID: request.RunID, Workspace: "runs/prepared/workspace", Provider: "codebuddy", Sandbox: request.Sandbox}+ _, release, err := d.acquireTaskSandbox(context.Background(), task)+ if err != nil {+ t.Fatal(err)+ }+ defer release()+ gate := d.workspaceGate(request.RunID)+ gate.RLock()+ defer gate.RUnlock()++ request.Operation = domain.RunnerWorkspaceOperationPrepare+ result := d.readRunnerWorkspace(context.Background(), request)+ var state runtime.WorkspacePreparationStatus+ if err := json.Unmarshal(result.Payload, &state); result.Status != 200 || err != nil || state.Status != "ready" {+ t.Fatalf("prepare beside running node: %+v %v", result, err)+ }+ request.Operation = domain.RunnerWorkspaceOperationWrite+ request.ConcurrentEdit = true+ request.Path, request.Content, request.ExpectedSHA256 = "ide.txt", "edited while running\n", "missing"+ if result := d.readRunnerWorkspace(context.Background(), request); result.Status != 200 {+ t.Fatalf("write beside running node: %+v", result)+ }+ if raw, err := os.ReadFile(filepath.Join(root, "ide.txt")); err != nil || string(raw) != "edited while running\n" {+ t.Fatalf("write landed: %q %v", raw, err)+ }+ request.Operation = domain.RunnerWorkspaceOperationTerminal+ request.TerminalOwner = 7+ request.Terminal = &domain.WorkspaceTerminalRequest{Operation: "open", ExpiresAt: time.Now().Add(time.Minute)}+ opened := d.readRunnerWorkspace(context.Background(), request)+ if opened.Status != 200 {+ t.Fatalf("terminal beside running node: %+v", opened)+ }+ d.workspaceTerminals.CloseScope("prepared:7")+}++// IDE edits share the workspace with running agents (gate readers) but stay+// excluded from preparation, restore and checkpoints (the exclusive holder).+func TestRunnerConcurrentEditSharesOnlyTheAgentFence(t *testing.T) {+ d, request, root := runnerPreparationFixture(t)+ defer d.closeAllRunSandboxes(context.Background())+ request.RunStatus = "running"+ request.ConcurrentEdit = true+ gate := d.workspaceGate(request.RunID)+ write := func(content string) domain.RunnerWorkspaceResponse {+ request.Operation = domain.RunnerWorkspaceOperationWrite+ request.Path, request.Content, request.ExpectedSHA256 = "ide.txt", content, "missing"+ return d.readRunnerWorkspace(context.Background(), request)+ }+ artifacts := func() domain.RunnerWorkspaceResponse {+ request.Operation = domain.RunnerWorkspaceOperationArtifacts+ return d.readRunnerWorkspace(context.Background(), request)+ }++ gate.Lock()+ if result := write("during preparation\n"); result.Status != 409 || result.Code != domain.WorkspaceErrorBusy {+ t.Fatalf("write during an exclusive hold: %+v", result)+ }+ if result := artifacts(); result.Status != 409 || result.Code != domain.WorkspaceErrorBusy {+ t.Fatalf("artifacts during an exclusive hold: %+v", result)+ }+ if _, err := os.Stat(filepath.Join(root, "ide.txt")); !os.IsNotExist(err) {+ t.Fatalf("write landed during an exclusive hold: %v", err)+ }+ gate.Unlock()++ gate.RLock()+ if result := write("beside a running agent\n"); result.Status != 200 {+ t.Fatalf("write beside a running agent: %+v", result)+ }+ if result := artifacts(); result.Status != 200 {+ t.Fatalf("artifacts beside a running agent: %+v", result)+ }+ gate.RUnlock()+ if raw, err := os.ReadFile(filepath.Join(root, "ide.txt")); err != nil || string(raw) != "beside a running agent\n" {+ t.Fatalf("write landed: %q %v", raw, err)+ }+ // The edit released its read hold: an exclusive holder can take the gate.+ if !gate.TryLock() {+ t.Fatal("concurrent edit leaked its gate hold")+ }+ gate.Unlock()+}diff --git a/internal/runtime/edges_cases_test.go b/internal/runtime/edges_cases_test.goindex fe2ba422..bd1d34b9 100644--- a/internal/runtime/edges_cases_test.go+++ b/internal/runtime/edges_cases_test.go@@ -113,3 +113,12 @@ func TestSandboxIsolationEnvironmentConcreteTypes(t *testing.T) {t.Fatalf("long safe id length=%d", len(got))}}++func TestWorkspacePreparationTrivial(t *testing.T) {+ if !WorkspacePreparationTrivial(domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ID: "agent", Type: "agent"}}}) {+ t.Fatal("workflow without preparation steps must be trivial")+ }+ if WorkspacePreparationTrivial(domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ID: "setup", Type: "script", RunOnWorkspaceRebuild: true}}}) {+ t.Fatal("workflow with a preparation step is not trivial")+ }+}diff --git a/internal/runtime/git_isolation.go b/internal/runtime/git_isolation.goindex a63e4592..7c1dd552 100644--- a/internal/runtime/git_isolation.go+++ b/internal/runtime/git_isolation.go@@ -158,6 +158,25 @@ func updateProjectAgentGitIndex(ctx context.Context, workspace, driver, mode strreturn fmt.Errorf("git update-index %s: %w: %s (resolve index lock: %v)", mode, err, strings.TrimSpace(string(output)), lockErr)}inUse, confirmed, inspectErr := gitIndexLockInUse(ctx, lockPath)+ // A live holder is usually a short git command (a reader refreshing the+ // index, an agent's commit). Wait for it briefly instead of failing the+ // whole preparation on the first collision.+ for deadline := time.Now().Add(gitIndexLockWait); inspectErr == nil && confirmed && inUse && time.Now().Before(deadline); {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(gitIndexLockPoll):+ }+ if _, statErr := os.Stat(lockPath); os.IsNotExist(statErr) {+ if output, err = run(); err == nil {+ return nil+ }+ if !isGitIndexLockConflict(output) {+ return fmt.Errorf("git update-index %s: %w: %s", mode, err, strings.TrimSpace(string(output)))+ }+ }+ inUse, confirmed, inspectErr = gitIndexLockInUse(ctx, lockPath)+ }if inspectErr != nil || !confirmed {return fmt.Errorf("git update-index %s: %w: %s (cannot safely inspect index lock: %v)", mode, err, strings.TrimSpace(string(output)), inspectErr)}@@ -174,6 +193,13 @@ func updateProjectAgentGitIndex(ctx context.Context, workspace, driver, mode strreturn nil}+// How long a preparation waits for another live git process to release+// .git/index.lock before giving up; variables so tests can shorten them.+var (+ gitIndexLockWait = 15 * time.Second+ gitIndexLockPoll = 200 * time.Millisecond+)+func isGitIndexLockConflict(output []byte) bool {message := strings.ToLower(string(output))return strings.Contains(message, "index.lock") && strings.Contains(message, "file exists")diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.goindex 11e9c5dc..203866bb 100644--- a/internal/runtime/runtime_test.go+++ b/internal/runtime/runtime_test.go@@ -3,6 +3,7 @@ package runtimeimport ("context""encoding/base64"+ "errors""fmt""net/http""net/http/httptest"@@ -1108,6 +1109,9 @@ func TestRestoreProjectAgentGitIndexKeepsLiveIndexLock(t *testing.T) {}defer lock.Close()defer os.Remove(lockPath)+ wait, poll := gitIndexLockWait, gitIndexLockPoll+ gitIndexLockWait, gitIndexLockPoll = 300*time.Millisecond, 20*time.Millisecond+ defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()err = RestoreProjectAgentGitIndex(context.Background(), workspace, "docker")if err == nil || !strings.Contains(err.Error(), "held by a live process") {t.Fatalf("restore error = %v, want live-process protection", err)@@ -2440,3 +2444,70 @@ func TestMCPStartupWaitReachesCodeBuddyProcess(t *testing.T) {}}}++// A short-lived git reader holding .git/index.lock (an IDE status refresh, an+// agent's commit) must not fail workspace preparation: it waits for release.+func TestProjectAgentGitIndexWaitsForBriefLiveLock(t *testing.T) {+ workspace := t.TempDir()+ testRuntimeGit(t, workspace, "init", "-b", "main")+ testRuntimeGit(t, workspace, "config", "user.email", "[email protected]")+ testRuntimeGit(t, workspace, "config", "user.name", "AgentFlow Test")+ if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("instructions\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ testRuntimeGit(t, workspace, "add", "AGENTS.md")+ testRuntimeGit(t, workspace, "commit", "-m", "baseline")+ wait, poll := gitIndexLockWait, gitIndexLockPoll+ gitIndexLockWait, gitIndexLockPoll = 5*time.Second, 20*time.Millisecond+ defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()+ lockPath := filepath.Join(workspace, ".git", "index.lock")+ lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)+ if err != nil {+ t.Fatal(err)+ }+ go func() {+ time.Sleep(300 * time.Millisecond)+ lock.Close()+ os.Remove(lockPath)+ }()+ if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {+ t.Fatalf("brief live lock failed preparation: %v", err)+ }+}++// Cancelling the preparation (pause, run cancel) stops waiting on a live+// .git/index.lock instead of holding the caller for the whole wait window.+func TestProjectAgentGitIndexLockWaitStopsOnCancel(t *testing.T) {+ workspace := t.TempDir()+ testRuntimeGit(t, workspace, "init", "-b", "main")+ testRuntimeGit(t, workspace, "config", "user.email", "[email protected]")+ testRuntimeGit(t, workspace, "config", "user.name", "AgentFlow Test")+ if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("instructions\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ testRuntimeGit(t, workspace, "add", "AGENTS.md")+ testRuntimeGit(t, workspace, "commit", "-m", "baseline")+ wait, poll := gitIndexLockWait, gitIndexLockPoll+ gitIndexLockWait, gitIndexLockPoll = time.Minute, 20*time.Millisecond+ defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()+ lockPath := filepath.Join(workspace, ".git", "index.lock")+ lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)+ if err != nil {+ t.Fatal(err)+ }+ defer os.Remove(lockPath)+ defer lock.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)+ defer cancel()+ started := time.Now()+ err = ProtectProjectAgentGitIndex(ctx, workspace, "docker")+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("cancelled wait error = %v, want context deadline", err)+ }+ if elapsed := time.Since(started); elapsed > 10*time.Second {+ t.Fatalf("cancelled wait took %s", elapsed)+ }+ if _, statErr := os.Stat(lockPath); statErr != nil {+ t.Fatalf("live index lock was removed: %v", statErr)+ }+}diff --git a/internal/runtime/workspace_preparation.go b/internal/runtime/workspace_preparation.goindex c6ac3d61..6b8f10c7 100644--- a/internal/runtime/workspace_preparation.go+++ b/internal/runtime/workspace_preparation.go@@ -439,6 +439,14 @@ func RecordWorkspacePreparation(ctx context.Context, sb Sandbox, wf domain.Workfreturn state, nil}+// WorkspacePreparationTrivial reports a recipe with nothing to prepare. A live+// environment serves it as is, even if no run ever stamped it ready: SOP+// nodes skip preparation entirely when their workflow has no such steps.+func WorkspacePreparationTrivial(wf domain.WorkflowDefinition) bool {+ nodes, err := preparationNodes(WorkspacePreparationWorkflow(wf))+ return err == nil && len(nodes) == 0+}+func WorkspacePreparationReusable(state WorkspacePreparationStatus, wf domain.WorkflowDefinition, repositories []domain.RepositoryContext, epoch string) bool {wf = WorkspacePreparationWorkflow(wf)if state.Status != "ready" || state.Environment != epoch {diff --git a/web/app/runs.js b/web/app/runs.jsindex 4be62f1b..9b6895e3 100644--- a/web/app/runs.js+++ b/web/app/runs.js@@ -656,7 +656,7 @@ function workspacePaneHTML(run){if(ws.error)return `<div class="workspace-unavailable"><span>!</span><b>工作区加载失败</b><p>${escapeHTML(ws.error)}</p><button class="button ghost small" data-workspace-refresh>重试</button></div>`;if(!ws.info?.available)return workspaceUnavailableHTML(ws.info?.reason);const maximized=!!ws.maximized;- return `<section class="run-workspace vscode-embed${maximized?' maximized':''}"><iframe data-vscode-frame data-run-id="${escapeHTML(run.id)}" title="VS Code" src="${escapeHTML(vscodeWorkbenchURL(run.id,{embed:true}))}" allow="clipboard-read; clipboard-write"></iframe></section>`;+ return `<section class="run-workspace vscode-embed${maximized?' maximized':''}"><iframe data-vscode-frame data-run-id="${escapeHTML(run.id)}" aria-label="VS Code" src="${escapeHTML(vscodeWorkbenchURL(run.id,{embed:true}))}" allow="clipboard-read; clipboard-write"></iframe></section>`;}function runPreviewDeclared(run){return !!(run?.workflowSnapshot?.preview&&run.workflowSnapshot.preview.enabled);diff --git a/web/vscode.css b/web/vscode.cssindex 94a5afc5..ee5c555b 100644--- a/web/vscode.css+++ b/web/vscode.css@@ -7,6 +7,14 @@ body.embed{background:#1e1e1e}.vscode-spinner{width:16px;height:16px;border:2px solid #3c3c3c;border-top-color:#007acc;border-radius:50%;animation:vscodeSpin .8s linear infinite}@keyframes vscodeSpin{to{transform:rotate(360deg)}}-body{display:flex;flex-direction:column}#workbench{flex:1;min-height:0;height:auto}.vscode-toolbar{height:38px;flex:none;display:flex;align-items:center;gap:8px;padding:0 14px;background:#252526;border-bottom:1px solid #373737;color:#cccccc;font:12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.vscode-toolbar>span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vscode-toolbar button{border:1px solid #444;border-radius:5px;background:#333;color:#ddd;padding:5px 10px;font:inherit;cursor:pointer}.vscode-toolbar button:last-child{background:#0e639c;border-color:#0e639c;color:white}.vscode-toolbar button:disabled{opacity:.45;cursor:default}.vscode-toolbar button:hover:not(:disabled){filter:brightness(1.15)}+body{display:flex;flex-direction:column}#workbench{flex:1;min-height:0;height:auto}.vscode-toolbar{height:35px;flex:none;display:flex;align-items:center;gap:8px;padding:0 6px 0 12px;background:#181818;border-bottom:1px solid #2b2b2b;color:#9d9d9d;font:12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;user-select:none}+.vscode-toolbar-status{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.vscode-toolbar-actions{display:flex;align-items:center;gap:2px;flex:none}+.vscode-action{display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 6px;border:0;border-radius:5px;background:transparent;color:#cccccc;font:inherit;cursor:pointer}+.vscode-action svg{flex:none}+.vscode-action:hover:not(:disabled){background:rgba(90,93,94,.31)}+.vscode-action:active:not(:disabled){background:rgba(99,102,103,.31)}+.vscode-action:focus-visible{outline:1px solid #0078d4;outline-offset:-1px}+.vscode-action:disabled{opacity:.4;cursor:default}.vscode-environment{display:flex;align-items:center;gap:14px;flex:none;padding:10px 14px;background:#362624;border-bottom:1px solid #573b37;color:#ddd;font:12px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.vscode-environment[hidden]{display:none}.vscode-environment>div{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}.vscode-environment b{font-weight:600}.vscode-environment span{color:#c9afaa;overflow-wrap:anywhere}.vscode-environment button{border:1px solid #80615b;border-radius:5px;background:#49332f;color:#fff;padding:5px 10px;font:inherit;flex:none;cursor:pointer}.vscode-environment button:disabled{opacity:.5;cursor:default}diff --git a/web/vscode.js b/web/vscode.jsindex 1ea13f28..44de6d74 100644--- a/web/vscode.js+++ b/web/vscode.js@@ -5,13 +5,29 @@const host = document.getElementById('workbench') || document.body;if (embedded) document.body.classList.add('embed');const toolbar=document.createElement('header');toolbar.className='vscode-toolbar';- const status=document.createElement('span'),edit=document.createElement('button'),terminal=document.createElement('button');- status.textContent='任务 IDE';edit.textContent='启用编辑';terminal.textContent='+ 终端';terminal.disabled=true;toolbar.append(status,edit,terminal);host.before(toolbar);+ // Like an AI IDE, the workspace is editable whenever the server allows it,+ // also while SOP agents run; there is no separate "enable edit" step.+ // The toolbar reads as VS Code chrome (Dark Modern title bar, ghost action+ // buttons). Codicon glyphs only exist after the workbench boots, so the+ // icons are inline SVGs drawn in the same 16px style.+ const svg=d=>`<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`;+ const ICONS={+ terminal:svg('<rect x="1.5" y="2.5" width="13" height="11" rx="1.5"/><path d="M4.5 6l2 2-2 2M8 10.5h3.5"/>'),+ popout:svg('<path d="M9 2.5h4.5V7M13.5 2.5L7.5 8.5M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>')+ };+ function toolbarAction(icon,label,title){const b=document.createElement('button');b.type='button';b.className='vscode-action';b.title=title;b.setAttribute('aria-label',title);b.innerHTML=ICONS[icon]+'<span>'+label+'</span>';return b}+ const status=document.createElement('span');status.className='vscode-toolbar-status';status.textContent='任务 IDE';status.setAttribute('aria-live','polite');+ const actions=document.createElement('div');actions.className='vscode-toolbar-actions';+ const terminal=toolbarAction('terminal','终端','新建终端');terminal.disabled=true;actions.append(terminal);+ // Opening the IDE in its own window used to hide behind the status bar+ // corner; embedded views now offer it right in the toolbar.+ if(embedded){const popout=toolbarAction('popout','新窗口打开','在新窗口打开 VS Code');popout.onclick=()=>postParent('popout');actions.append(popout)}+ toolbar.append(status,actions);host.before(toolbar);const environment=document.createElement('section');environment.className='vscode-environment';environment.setAttribute('aria-live','polite');environment.hidden=true;toolbar.after(environment);let environmentState=null,preparingEnvironment=false,environmentPoll=0,environmentEpoch=0,environmentRetry=0;function paintEnvironment(info){environmentState=info;environment.hidden=info.status!=='failed';environment.replaceChildren();- terminal.disabled=!editing||preparingEnvironment||info.status==='preparing'||info.status==='busy';+ paintToolbar();if(environment.hidden)return;const copy=document.createElement('div'),heading=document.createElement('b'),detail=document.createElement('span');heading.textContent='工作区准备失败';detail.textContent=info.error||'请重试,现有文件仍可浏览';copy.append(heading,detail);environment.append(copy);const retry=document.createElement('button');retry.type='button';retry.textContent='重试';retry.disabled=!editing||preparingEnvironment;retry.onclick=prepareEnvironment;environment.append(retry);@@ -26,9 +42,20 @@environmentPoll=setInterval(()=>refreshEnvironment().catch(()=>{}),1500);try{const result=await action('preparation');environmentEpoch++;paintEnvironment(result)}catch(err){environmentEpoch++;if(err.code==='workspace_busy'){paintEnvironment({status:'busy'});environmentRetry=setTimeout(()=>prepareEnvironment(),Math.min(5000,Math.max(1000,Number(err.retryAfterMs)||2000)))}else{paintEnvironment({status:'failed',error:err.message})}}finally{preparingEnvironment=false;clearInterval(environmentPoll);if(environmentState)paintEnvironment(environmentState)}}- let currentInfo={},editing=false;+ let currentInfo=null,editing=false;async function action(name,body={}){const res=await fetch('/api/runs/'+encodeURIComponent(runId)+'/workspace/'+name,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await res.json().catch(()=>({}));if(!res.ok){const err=new Error(data.error||'操作失败');err.code=data.code;err.retryAfterMs=data.retryAfterMs;throw err}return data}- function paintEditing(info){currentInfo=info;editing=info.readOnly===false;status.textContent=editing?'任务 IDE · 可编辑':'任务 IDE · 只读';status.textContent+=' · 空闲 1 小时后回收';if(info.checkpointWarning)status.textContent+=' · '+info.checkpointWarning;edit.textContent=editing?'刷新':'启用编辑';terminal.disabled=!editing;}+ function paintToolbar() {+ const busy = environmentState?.status === 'busy';+ const preparing = preparingEnvironment || environmentState?.status === 'preparing';+ terminal.disabled = !editing || !window.agentflowIDEWorkbench || busy || preparing;+ const details = [editing ? '任务 IDE · 可编辑' : '任务 IDE · 只读'];+ if (editing && busy) details.push('等待工作区空闲…');+ else if (editing && preparing) details.push('正在准备终端环境…');+ details.push('空闲 1 小时后回收');+ if (currentInfo.checkpointWarning) details.push(currentInfo.checkpointWarning);+ const summary = details.join(' · ');+ if (status.textContent !== summary) status.textContent = summary;+ }async function releaseEdit(keepalive=false){if(!editing)return;const opts={method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:'{}'};@@ -36,19 +63,6 @@try{await fetch('/api/runs/'+encodeURIComponent(runId)+'/workspace/release',opts)}catch(_){/* page is closing */}editing=false;}- edit.onclick=async()=>{edit.disabled=true;try{- if(editing){location.reload();return}- // takeover pauses agents server-side; retry while the runner drains- let lastErr;- for(let i=0;i<40;i++){- try{await action('takeover');location.reload();return}catch(err){- lastErr=err;- if(!/停止|稍后|仍有任务/.test(String(err.message||err)))throw err;- await new Promise(resolve=>setTimeout(resolve,300));- }- }- throw lastErr||new Error('角色仍在停止,请稍后重试');- }catch(err){status.textContent=err.message;edit.disabled=false}};terminal.onclick=()=>window.agentflowIDEWorkbench?.commands.executeCommand('agentflow.newTerminal');window.addEventListener('pagehide',()=>{clearInterval(environmentPoll);clearTimeout(environmentRetry);releaseEdit(true)});@@ -134,9 +148,15 @@return;}await action('use').catch(()=>{});- workspaceReadOnly = info.readOnly !== false;paintEditing(info);- refreshEnvironment().then(()=>{if(!workspaceReadOnly)prepareEnvironment()}).catch(err=>paintEnvironment({status:'failed',error:err.message}));- // No edit lease to renew; writable once the run is paused.+ currentInfo = info;+ workspaceReadOnly = info.readOnly !== false;+ editing = !workspaceReadOnly;+ paintToolbar();+ // Opening a shell revalidates the environment on the server.+ refreshEnvironment().then(state => {+ if (state.status !== 'ready') return prepareEnvironment();+ }).catch(err => paintEnvironment({ status: 'failed', error: err.message }));+ // No edit lease to renew; writable whenever the server says so.workspaceChanges = Array.isArray(info.changes) ? info.changes : [];const names = new Set();for (const name of info.repositories || []) {@@ -191,7 +211,7 @@});const extensionUri = URI.parse(`${location.origin}/extensions/agentflow-workspace`);host.replaceChildren();- window.agentflowIDEWorkbench=workbench;workbench.create(host, {+ workbench.create(host, {additionalBuiltinExtensions: [extensionUri],folderUri,workspaceProvider: {@@ -231,7 +251,7 @@},windowIndicator: {label: `$(remote) SOP ${runId.slice(-12)}`,- tooltip: workspaceReadOnly ? '任务工作区 · 只读,点击启用编辑' : '任务工作区 · 可读写及交互式终端',+ tooltip: workspaceReadOnly ? '任务工作区 · 只读' : '任务工作区 · 可读写及交互式终端',command: embedded ? 'agentflow.popout' : undefined},commands: [@@ -252,6 +272,8 @@}]});+ window.agentflowIDEWorkbench = workbench;+ paintToolbar();}, err => {showError('VS Code 启动失败', err?.message || String(err));});diff --git a/web/workspace_preparation_test.go b/web/workspace_preparation_test.goindex d488cd72..22dcdde5 100644--- a/web/workspace_preparation_test.go+++ b/web/workspace_preparation_test.go@@ -43,3 +43,94 @@ eval(source.slice(source.indexOf(' async function refreshEnvironment('),source.t.Fatalf("workspace preparation UI: %v\n%s", err, output)}}++func TestIDEStartupReusesPreparedEnvironment(t *testing.T) {+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("node not installed")+ }+ script := `+const assert = require('node:assert/strict');+const { createDOM } = require('./hui_fake_dom.js');++async function openIDE({ status, readOnly = false, preparation }) {+ const dom = createDOM();+ const { document, window } = dom;+ const host = dom.html('<div id="workbench"></div>');+ host.before = node => document.body.insertBefore(node, host);+ const appendChild = document.head.appendChild.bind(document.head);+ document.head.appendChild = node => {+ appendChild(node);+ if (node.tagName === 'SCRIPT') queueMicrotask(() => node.onload());+ return node;+ };++ const preparationMethods = [];+ const commands = [];+ let startWorkbench;+ window.URLSearchParams = URLSearchParams;+ window.location = new URL('https://ide.test/vscode.html?run=test&embed=1');+ window.require = (_modules, start) => {+ startWorkbench = () => start({+ create() {},+ commands: { executeCommand: command => commands.push(command) }+ }, { URI: { from: value => value, parse: value => value } });+ };+ window.require.config = () => {};+ window.setInterval = () => 1;+ window.clearInterval = () => {};+ window.fetch = async (url, { method = 'GET' } = {}) => {+ const response = body => ({ ok: true, json: async () => body });+ switch (url) {+ case '/api/runs/test/workspace':+ return response({ available: true, readOnly });+ case '/api/runs/test/workspace/use':+ return response({});+ case '/api/runs/test/workspace/preparation':+ preparationMethods.push(method);+ return response(method === 'GET' ? { status } : await preparation);+ default:+ throw new Error('Unexpected request ' + method + ' ' + url);+ }+ };+ dom.load('vscode.js');+ await dom.settle();+ assert.equal(typeof startWorkbench, 'function', 'the workbench should load in parallel with preparation');+ return {+ terminal: document.querySelector('button[aria-label="新建终端"]'),+ status: document.querySelector('.vscode-toolbar-status'),+ preparationMethods, commands, startWorkbench, settle: dom.settle+ };+}++(async () => {+ const warm = await openIDE({ status: 'ready' });+ assert.deepEqual(warm.preparationMethods, ['GET'], 'a ready environment needs no preparation POST');+ assert.equal(warm.terminal.disabled, true, 'the terminal command needs the workbench');+ warm.startWorkbench();+ assert.equal(warm.terminal.disabled, false);+ warm.terminal.onclick();+ assert.deepEqual(warm.commands, ['agentflow.newTerminal']);++ let finishPreparation;+ const preparation = new Promise(resolve => { finishPreparation = resolve; });+ const cold = await openIDE({ status: 'unprepared', preparation });+ assert.deepEqual(cold.preparationMethods, ['GET', 'POST']);+ cold.startWorkbench();+ assert.equal(cold.terminal.disabled, true);+ assert.match(cold.status.textContent, /正在准备终端环境/);+ finishPreparation({ status: 'ready' });+ await cold.settle();+ assert.equal(cold.terminal.disabled, false);+ assert.doesNotMatch(cold.status.textContent, /正在准备终端环境/);++ const viewer = await openIDE({ status: 'unprepared', readOnly: true });+ viewer.startWorkbench();+ assert.deepEqual(viewer.preparationMethods, ['GET']);+ assert.equal(viewer.terminal.disabled, true);+})().catch(error => { console.error(error); process.exitCode = 1; });+`+ if output, err := exec.Command(node, "-e", script).CombinedOutput(); err != nil {+ t.Fatalf("IDE startup: %v\n%s", err, output)+ }+}