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
8 changes: 8 additions & 0 deletions internal/runtime/conversation_sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ func resolveNativeConversationBinary(provider string) (string, error) {
}
}
}
return hostCLIPath(provider, binary)
}

// hostCLIPath finds an installed CLI on this execution machine: PATH, the
// official installer's ~/.local/bin, the system bin directories, then the
// platform's on-demand install directory. Native conversations and native
// LOOP nodes share it so both run the same executable.
func hostCLIPath(provider, binary string) (string, error) {
path, err := exec.LookPath(binary)
if err == nil {
return path, nil
Expand Down
33 changes: 26 additions & 7 deletions internal/runtime/managed_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,44 @@ func explicitNativeCLIPath(provider string) string {
return ""
}

// Pin host executables for platform-owned workflow runs. Docker sandboxes and
// connected runners resolve the CLI on their own execution machines.
// Pin host executables for workflow runs in native sandboxes. Docker
// sandboxes install the CLI inside their container instead.
func pinNativeExecutorCLI(ctx context.Context, driver, runID string, executor domain.ExecutorDefinition) (string, *managedcli.ClaimLease, error) {
switch driver {
case "local", "seatbelt", "bwrap":
default:
return "", nil, nil
}
root := strings.TrimSpace(os.Getenv("AGENTFLOW_MANAGED_CLI_ROOT"))
kind := strings.TrimSpace(executor.Kind)
if root == "" || !managedcli.Supports(kind) {
return "", nil, nil
}
if binary := strings.TrimSpace(executor.Binary); binary != "" && binary != conversationBinary(kind) {
return "", nil, nil
}
if path := explicitNativeCLIPath(kind); path != "" {
// Claude Code, Codex and CodeBuddy are agent CLIs too: Claude Code is not
// in the platform image and is installed on demand like the others.
hostCLI := managedcli.Supports(kind) || IsAgentCLI(kind)
root := strings.TrimSpace(os.Getenv("AGENTFLOW_MANAGED_CLI_ROOT"))
managed := root != "" && managedcli.Supports(kind)
if path := explicitNativeCLIPath(kind); path != "" && hostCLI {
return path, nil, nil
}
if managed {
binary, lease, err := pinManagedCLI(ctx, root, runID, kind)
if err != nil || binary != "" {
return binary, lease, err
}
}
// A CLI the managed root does not provide may still be installed on this
// machine, for example on demand from a chat. Run the executable a native
// conversation would, instead of a bare name PATH may not resolve.
if hostCLI {
if path, err := hostCLIPath(kind, conversationBinary(kind)); err == nil {
return path, nil, nil
}
}
return "", nil, nil
}

func pinManagedCLI(ctx context.Context, root, runID, kind string) (string, *managedcli.ClaimLease, error) {
lease, err := managedcli.BeginClaim(ctx, root)
if err != nil {
return "", nil, fmt.Errorf("managed CLI usage for %s: %w", kind, err)
Expand Down
97 changes: 97 additions & 0 deletions internal/runtime/managed_cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ func TestExecutorRunnerPinsManagedNativeCLI(t *testing.T) {
}
t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", root)
t.Setenv("AGENTFLOW_PI_BIN", "")
// Keep host installations out of the bare-name expectations below.
t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", "")
t.Setenv("PATH", t.TempDir())
t.Setenv("HOME", t.TempDir())
publish := func(version string) string {
t.Helper()
binary := filepath.Join(root, "providers", "pi", version, "pi")
Expand Down Expand Up @@ -70,6 +74,99 @@ func TestExecutorRunnerPinsManagedNativeCLI(t *testing.T) {
check("local", "run6", "pi", override)
}

// A LOOP node in a native sandbox runs the same agent CLI a native chat
// would, including one installed on demand, instead of a bare name that
// fails with "command not found" when PATH lacks it.
func TestExecutorRunnerFindsHostAgentCLIOutsideManagedRoot(t *testing.T) {
cliDir := t.TempDir()
t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", cliDir)
t.Setenv("AGENTFLOW_PI_BIN", "")
t.Setenv("PATH", t.TempDir())
t.Setenv("HOME", t.TempDir())
runner := NewExecutorRunner()
check := func(driver, binary, want string) {
t.Helper()
sandbox := &capturingSandbox{workspace: t.TempDir(), driver: driver}
executor := domain.ExecutorDefinition{Kind: "pi", Binary: binary}
if _, err := runner.Run(context.Background(), sandbox, "invocation", executor, domain.AgentDefinition{ID: "agent"}, domain.AgentAssetBundle{}, "hello", InvocationOptions{RunID: "run"}, nil); err != nil {
t.Fatal(err)
}
if len(sandbox.argv) == 0 || sandbox.argv[0] != want {
t.Fatalf("%s got %v, want %s", driver, sandbox.argv, want)
}
}
install := func(path string) string {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
return path
}

// Nothing installed: keep the bare name so the error stays unchanged.
t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
check("bwrap", "", "pi")

onDemand := install(filepath.Join(cliDir, "pi", "current", "node_modules", ".bin", "pi"))
for _, driver := range []string{"local", "seatbelt", "bwrap"} {
check(driver, "", onDemand)
check(driver, "pi", onDemand)
}
// A managed root without this CLI falls back the same way.
t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", t.TempDir())
check("bwrap", "", onDemand)
// Docker sandboxes and explicit executables are left alone.
check("docker", "pi", "pi")
check("bwrap", "/custom/bin/pi", "/custom/bin/pi")
// The installer's ~/.local/bin wins over the on-demand directory, as in chat.
home := t.TempDir()
t.Setenv("HOME", home)
local := install(filepath.Join(home, ".local", "bin", "pi"))
check("bwrap", "", local)
}

// Claude Code is not in the platform image either; a chat installs it on
// demand. A native LOOP node must run that installation, not a bare "claude".
func TestExecutorRunnerFindsOnDemandClaudeCode(t *testing.T) {
cliDir := t.TempDir()
t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", cliDir)
t.Setenv("AGENTFLOW_CLAUDE_BIN", "")
t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
t.Setenv("PATH", t.TempDir())
t.Setenv("HOME", t.TempDir())
runner := NewExecutorRunner()
check := func(driver, binary, want string) {
t.Helper()
sandbox := &capturingSandbox{workspace: t.TempDir(), driver: driver}
executor := domain.ExecutorDefinition{Kind: "claude-code", Binary: binary, Args: []string{"-p", "--output-format", "stream-json"}}
if _, err := runner.Run(context.Background(), sandbox, "invocation", executor, domain.AgentDefinition{ID: "agent"}, domain.AgentAssetBundle{}, "hello", InvocationOptions{RunID: "run"}, nil); err != nil {
t.Fatal(err)
}
if len(sandbox.argv) == 0 || sandbox.argv[0] != want {
t.Fatalf("%s got %v, want %s", driver, sandbox.argv, want)
}
}
check("bwrap", "claude", "claude")
onDemand := claudeCodeBinary(cliDir)
if err := os.MkdirAll(filepath.Dir(onDemand), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(onDemand, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
for _, driver := range []string{"local", "seatbelt", "bwrap"} {
check(driver, "claude", onDemand)
}
// A managed root without Claude Code falls back to the same installation.
t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", t.TempDir())
check("bwrap", "claude", onDemand)
check("docker", "claude", "claude")
check("bwrap", "/custom/bin/claude", "/custom/bin/claude")
}

func TestBwrapMountsManagedInstallationUnderPrivateTmp(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("bwrap is available on Linux")
Expand Down
2 changes: 1 addition & 1 deletion web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2121,7 +2121,7 @@ function switchView(name){
if(name==='agents'){api('/api/agents',{silent:true}).then(agents=>{state.data.agents=agents;renderAgents()}).catch(e=>toast(e.message));renderAgents();applyAgentRoute()}
if(name==='settings')renderPersonalSettings();
if(name==='platform')renderPlatformAdminPanel();
if(name==='projects')renderProjectAdmin();
if(name==='projects'){renderProjectAdmin();refreshProjectAdminStats()}
if(name==='projectCredentials')loadProjectCredentialsPage();
if(assetViews.includes(name)){
if(staying&&state.assetType===name){if(state.selectedAsset)closeAssetDetail({force:true});else renderAssets()}
Expand Down
9 changes: 9 additions & 0 deletions web/app/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,15 @@ function renderProjectAdmin(opt={}){
listView.hidden=detail;detailView.hidden=!detail;
if(detail)renderProjectDetail(opt);else renderProjectList();
}
// Card and header counts read the requirement list, which only the requirement
// views load. Fetch it here as well, so opening 项目配置 directly does not show
// 0 requirements until the user has visited 需求列表.
function refreshProjectAdminStats(){
return refreshIssues().then(()=>{
if(activeViewName()!=='projects')return;
if(state.projectAdminDetailId)renderProjectAdminHead();else renderProjectList();
});
}
function resetProjectAdminDetail(){
state.projectAdminDetailId=null;state.projectAdminTab='basic';state.projectDraft=null;state.projectDraftFor='';state.projectDraftBase=null;state.projectIdentCustom=false;state.projectAdminErrors={};
if(typeof closeRepoDrawer==='function')closeRepoDrawer();
Expand Down
37 changes: 37 additions & 0 deletions webtest/tests/project-admin-stats.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadApp, settle } from '../lib/load-app.mjs';

// 项目配置 counts requirements from the requirement list. Opening it first
// must fetch that list instead of showing 0 until 需求列表 has been visited.
async function projectsApp(t) {
const app = await loadApp();
t.after(app.close);
app.router.get('/api/project-join-requests', []);
app.router.get('/api/issues', [
{ id: 'issue-1', projectId: 'project-1', title: 'one', status: 'backlog' },
{ id: 'issue-2', projectId: 'project-1', title: 'two', status: 'backlog' },
{ id: 'issue-3', projectId: 'other', title: 'elsewhere', status: 'backlog' },
]);
app.router.get('/api/tasks', []);
app.router.get('/api/runs', []);
app.evaluate(`state.data.issues=undefined;state.data.projects=[{...state.data.projects[0],id:'project-1',name:'Atlas',workflowId:'flow-1',ownerId:1,members:[]}]`);
return app;
}

test('the project list counts requirements when opened directly', async t => {
const app = await projectsApp(t);
app.evaluate(`resetProjectAdminDetail();switchView('projects')`);
await settle();
assert.ok(app.router.calls.some(c => c.method === 'GET' && c.path === '/api/issues'), 'requirements were fetched');
const stats = app.document.querySelector('[data-project-open="project-1"] .pa-stats').textContent.replace(/\s+/g, ' ').trim();
assert.match(stats, /^2 需求/);
});

test('the project header counts requirements when opened directly', async t => {
const app = await projectsApp(t);
app.evaluate(`state.projectAdminDetailId='project-1';state.projectAdminTab='basic';state.projectDraft=null;switchView('projects')`);
await settle();
const meta = app.document.querySelector('#projectAdminHead .pa-dmeta').textContent.replace(/\s+/g, ' ');
assert.match(meta, /2 个需求/);
});
Loading