Skip to content

The Unified and Autonomous Development Platform

feat: Max loop count in AI behavior setting to stop infinite loops by malicious prompts (OD-2902)

Robin Shen822835087a3e
diff --git a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
index 5779ead14c..6d24826c77 100644
--- a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
+++ b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
@@ -9164,6 +9164,22 @@ public class DataMigrator {
}
private void migrate235(File dataDir, Stack<Integer> versions) {
+ for (File file : dataDir.listFiles()) {
+ if (file.getName().startsWith("Users.xml")) {
+ var dom = VersionedXmlDoc.fromFile(file);
+ for (Element element : dom.getRootElement().elements()) {
+ var aiSettingElement = element.element("aiSetting");
+ aiSettingElement.addElement("maxLoopCount").setText("3");
+ }
+ dom.writeToFile(file, false);
+ } else if (file.getName().startsWith("Workspaces.xml")) {
+ var dom = VersionedXmlDoc.fromFile(file);
+ for (Element element : dom.getRootElement().elements()) {
+ element.addElement("participatingUserIds");
+ }
+ dom.writeToFile(file, false);
+ }
+ }
}
}
diff --git a/server-core/src/main/java/io/onedev/server/event/project/ProjectEvent.java b/server-core/src/main/java/io/onedev/server/event/project/ProjectEvent.java
index 7d35674133..8f6f89db7d 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/ProjectEvent.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/ProjectEvent.java
@@ -1,7 +1,9 @@
package io.onedev.server.event.project;
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
@@ -22,12 +24,16 @@ import io.onedev.server.util.commenttext.CommentText;
public abstract class ProjectEvent extends Event implements Serializable {
private static final long serialVersionUID = 1L;
+
+ private static final ThreadLocal<List<Long>> participatingUserIdsHolder = new ThreadLocal<>();
private final Long projectId;
private final Long userId;
private final Date date;
+
+ private final List<Long> participatingUserIds;
private transient Optional<CommentText> commentText;
@@ -35,6 +41,21 @@ public abstract class ProjectEvent extends Event implements Serializable {
userId = User.idOf(user);
this.date = date;
projectId = project.getId();
+ var inheritedParticipatingUserIds = participatingUserIdsHolder.get();
+ if (inheritedParticipatingUserIds != null)
+ participatingUserIds = new ArrayList<>(inheritedParticipatingUserIds);
+ else
+ participatingUserIds = new ArrayList<>();
+ if (userId != null)
+ participatingUserIds.add(userId);
+ }
+
+ public static void setContextualParticipatingUserIds(List<Long> participatingUserIds) {
+ participatingUserIdsHolder.set(participatingUserIds);
+ }
+
+ public static void clearContextualParticipatingUserIds() {
+ participatingUserIdsHolder.remove();
}
public Project getProject() {
@@ -49,6 +70,10 @@ public abstract class ProjectEvent extends Event implements Serializable {
public Date getDate() {
return date;
}
+
+ public List<Long> getParticipatingUserIds() {
+ return participatingUserIds;
+ }
public abstract String getActivity();
diff --git a/server-core/src/main/java/io/onedev/server/model/Workspace.java b/server-core/src/main/java/io/onedev/server/model/Workspace.java
index fdba77d128..70c15c0e74 100644
--- a/server-core/src/main/java/io/onedev/server/model/Workspace.java
+++ b/server-core/src/main/java/io/onedev/server/model/Workspace.java
@@ -3,6 +3,7 @@ package io.onedev.server.model;
import static io.onedev.server.search.entity.EntitySort.Direction.ASCENDING;
import static io.onedev.server.search.entity.EntitySort.Direction.DESCENDING;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
@@ -17,6 +18,7 @@ import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
+import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@@ -190,6 +192,10 @@ public class Workspace extends AbstractEntity {
private boolean forTaskAutomation;
+ @JsonIgnore
+ @Lob
+ private ArrayList<Long> participatingUserIds = new ArrayList<>();
+
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn
private Agent agent;
@@ -432,6 +438,14 @@ public class Workspace extends AbstractEntity {
this.forTaskAutomation = forTaskAutomation;
}
+ public ArrayList<Long> getParticipatingUserIds() {
+ return participatingUserIds;
+ }
+
+ public void setParticipatingUserIds(ArrayList<Long> participatingUserIds) {
+ this.participatingUserIds = participatingUserIds;
+ }
+
public WorkspaceReference getReference() {
return new WorkspaceReference(getProject(), getNumber());
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/AiSetting.java b/server-core/src/main/java/io/onedev/server/model/support/AiSetting.java
index 9aec2e90c8..6d1a78c5a9 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/AiSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/AiSetting.java
@@ -2,12 +2,16 @@ package io.onedev.server.model.support;
import java.io.Serializable;
+import javax.validation.constraints.Min;
+
import org.jspecify.annotations.Nullable;
public class AiSetting implements Serializable {
private static final long serialVersionUID = 1L;
+ private static final int DEFAULT_MAX_LOOP_COUNT = 3;
+
private AiModelSetting modelSetting;
private boolean entitleToAll;
@@ -16,6 +20,8 @@ public class AiSetting implements Serializable {
private boolean proactive;
+ private int maxLoopCount = DEFAULT_MAX_LOOP_COUNT;
+
public AiModelSetting getModelSetting() {
return modelSetting;
}
@@ -49,4 +55,13 @@ public class AiSetting implements Serializable {
this.proactive = proactive;
}
+ @Min(value=1, message="At least 1 should be specified")
+ public int getMaxLoopCount() {
+ return maxLoopCount > 0 ? maxLoopCount : DEFAULT_MAX_LOOP_COUNT;
+ }
+
+ public void setMaxLoopCount(int maxLoopCount) {
+ this.maxLoopCount = maxLoopCount;
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
index 82cfcba8e4..567976d278 100644
--- a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
@@ -8,9 +8,11 @@ import static org.unbescape.html.HtmlEscape.escapeHtml5;
import java.io.ObjectStreamException;
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@@ -187,7 +189,7 @@ public class IssueNotificationManager implements Serializable {
public void on(IssueEvent event) {
if (event.isMinor() || !event.isSendNotifications())
return;
-
+
Issue issue = event.getIssue();
User user = event.getUser();
@@ -253,7 +255,7 @@ public class IssueNotificationManager implements Serializable {
replyAddress, senderName, threadingReferences);
}
} else if (isAiEligible(null, issue, member, true) && canCreateWorkspace(member, issue, true)) {
- onFieldSet(member, issue, entry.getKey());
+ onFieldSet(member, issue, entry.getKey(), event.getParticipatingUserIds());
}
}
}
@@ -283,7 +285,7 @@ public class IssueNotificationManager implements Serializable {
replyAddress, senderName, threadingReferences);
}
} else if (isAiEligible(null, issue, assignedUser, true) && canCreateWorkspace(assignedUser, issue, true)) {
- onFieldSet(assignedUser, issue, entry.getKey());
+ onFieldSet(assignedUser, issue, entry.getKey(), event.getParticipatingUserIds());
}
}
}
@@ -318,11 +320,14 @@ public class IssueNotificationManager implements Serializable {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEligible(user, issue, mentionedUser, true)
- && user != null
+ } else if (user != null
+ && (!user.isSystem()
+ || event instanceof IssueOpened issueOpened && issueOpened.getIssue().getOnBehalfOf() != null
+ || event instanceof IssueCommentCreated issueCommentCreated && issueCommentCreated.getComment().getOnBehalfOf() != null)
&& !user.equals(mentionedUser)
+ && isAiEligible(user, issue, mentionedUser, true)
&& canCreateWorkspace(mentionedUser, issue, true)) {
- onAiMentioned(mentionedUser, user, issue);
+ onAiMentioned(mentionedUser, user, issue, event.getParticipatingUserIds());
}
}
}
@@ -348,14 +353,15 @@ public class IssueNotificationManager implements Serializable {
EmailAddress emailAddress = watch.getUser().getPrimaryEmailAddress();
if (emailAddress != null && emailAddress.isVerified())
bccEmailAddresses.add(emailAddress.getValue());
- } else if ((!user.isSystem()
+ } else if (user != null
+ && (!user.isSystem()
|| event instanceof IssueOpened issueOpened && issueOpened.getIssue().getOnBehalfOf() != null
|| event instanceof IssueCommentCreated issueCommentCreated && issueCommentCreated.getComment().getOnBehalfOf() != null)
&& !user.equals(watch.getUser())
&& watch.getUser().getAiSetting().isProactive()
&& isAiEligible(user, issue, watch.getUser(), false)
&& canCreateWorkspace(watch.getUser(), issue, false)) {
- onAiNotified(watch.getUser(), user, issue);
+ onAiNotified(watch.getUser(), user, issue, event.getParticipatingUserIds());
}
}
}
@@ -405,7 +411,7 @@ public class IssueNotificationManager implements Serializable {
return Pair.of(commitId, branch);
}
- private void onAiMentioned(User ai, User user, Issue issue) {
+ private void onAiMentioned(User ai, User user, Issue issue, List<Long> participatingUserIds) {
var branchAndCommitId = getWorkspaceCommitIdAndBranch(issue);
String rolesInfo;
var assignedFields = getAssignedFields(ai, issue);
@@ -420,10 +426,11 @@ public class IssueNotificationManager implements Serializable {
Mention the user in your comment if you expect a response. \
Make sure to submit work afterwards without confirmation.""".
formatted(issue.getNumber(), rolesInfo, user.getName());
- runPrompt(ai, issue, issue.getProject(), branchAndCommitId.getLeft(), branchAndCommitId.getRight(), prompt);
+ runPrompt(ai, issue, issue.getProject(), branchAndCommitId.getLeft(),
+ branchAndCommitId.getRight(), prompt, participatingUserIds);
}
- private void onAiNotified(User ai, User user, Issue issue) {
+ private void onAiNotified(User ai, User user, Issue issue, List<Long> participatingUserIds) {
var branchAndCommitId = getWorkspaceCommitIdAndBranch(issue);
String rolesInfo;
var assignedFields = getAssignedFields(ai, issue);
@@ -438,14 +445,25 @@ public class IssueNotificationManager implements Serializable {
Respond only if you are relevant and a response is necessary. \
Make sure to submit work afterwards without confirmation."""
.formatted(issue.getNumber(), rolesInfo, user.getName());
- runPrompt(ai, issue, issue.getProject(), branchAndCommitId.getLeft(), branchAndCommitId.getRight(), prompt);
+ runPrompt(ai, issue, issue.getProject(), branchAndCommitId.getLeft(),
+ branchAndCommitId.getRight(), prompt, participatingUserIds);
}
private void runPrompt(User ai, Issue issue, Project project,
- ObjectId commitId, @Nullable String branch, String prompt) {
+ ObjectId commitId, @Nullable String branch, String prompt,
+ List<Long> eventParticipatingUserIds) {
+ var participatingUserIds = new ArrayList<>(eventParticipatingUserIds);
+ var awakenCount = participatingUserIds.stream().filter(ai.getId()::equals).count();
+ if (awakenCount >= ai.getAiSetting().getMaxLoopCount()) {
+ var message = "I reached the maximum awaken count of %d in the current event chain"
+ .formatted(ai.getAiSetting().getMaxLoopCount());
+ createComment(ai, issue, message);
+ return;
+ }
try {
var taskFailedCallback = newTaskFailedCallback(ai.getId(), issue.getId());
- workspaceService.runPrompt(ai, project, issue, null, commitId, branch, prompt, taskFailedCallback);
+ workspaceService.runPrompt(ai, project, issue, null, commitId, branch, prompt,
+ participatingUserIds, taskFailedCallback);
} catch (Throwable t) {
var explicitException = ExceptionUtils.find(t, ExplicitException.class);
if (explicitException != null) {
@@ -458,11 +476,8 @@ public class IssueNotificationManager implements Serializable {
}
private void createComment(User ai, Issue issue, String comment) {
- if (SecurityUtils.canAccessIssue(ai.asSubject(), issue)) {
- issueCommentService.create(ai, issue, comment);
- } else {
- issueCommentService.create(userService.getSystem(), issue, "_Commenting on behalf of **%s** as the user does not even have permission to post here._\n\n%s".formatted(ai.getName(), comment));
- }
+ issueCommentService.create(userService.getSystem(), issue,
+ "On behalf of AI user \"%s\": %s".formatted(ai.getDisplayName(), comment));
}
private Set<String> getAssignedFields(User ai, Issue issue) {
@@ -483,21 +498,23 @@ public class IssueNotificationManager implements Serializable {
return assignedFieldNames;
}
- private void onFieldSet(User ai, Issue issue, String field) {
+ private void onFieldSet(User ai, Issue issue, String field, List<Long> participatingUserIds) {
var commitIdAndBranch = getWorkspaceCommitIdAndBranch(issue);
var prompt = """
Work on issue %d as role '%s'. \
Do not switch checkout if your role does not need to write code. \
Make sure to submit work afterwards without confirmation."""
.formatted(issue.getNumber(), field);
- runPrompt(ai, issue, issue.getProject(), commitIdAndBranch.getLeft(), commitIdAndBranch.getRight(), prompt);
+ runPrompt(ai, issue, issue.getProject(), commitIdAndBranch.getLeft(),
+ commitIdAndBranch.getRight(), prompt, participatingUserIds);
}
private TaskFailedCallback newTaskFailedCallback(Long aiId, Long issueId) {
return new TaskFailedCallback() {
- public void onTaskFailed(String workspaceReference) {
- createComment(userService.load(aiId), issueService.load(issueId), "Failed to do the job, please open workspace %s for details".formatted(workspaceReference));
+ public void onTaskFailed(String workspaceReference) {
+ createComment(userService.load(aiId), issueService.load(issueId),
+ "Failed to do the job, please open workspace %s for details".formatted(workspaceReference));
}
};
@@ -593,7 +610,7 @@ public class IssueNotificationManager implements Serializable {
return true;
} else {
if (commentOnError)
- createComment(ai, issue, "%s is not entitled to interact with me".formatted(user.getName()));
+ createComment(ai, issue, "@%s is not entitled to interact with me".formatted(user.getName()));
return false;
}
} else {
diff --git a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
index faa9c3e886..736f205f51 100644
--- a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
@@ -267,7 +267,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
if ((changeData instanceof PullRequestRequestedForChangesData)
&& user.getType() != AI
@@ -280,7 +281,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber(), user.getName());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
} else if (event instanceof PullRequestAssigned) {
assignees.add(((PullRequestAssigned) event).getAssignee());
@@ -346,7 +348,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber(), request.getSubmitter().getName());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(reviewer, request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(reviewer, request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
}
}
@@ -374,12 +377,13 @@ public class PullRequestNotificationManager implements Serializable {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (!(event instanceof PullRequestCodeCommentEvent)
- && isAiEligible(user, request, mentionedUser, true)
+ } else if (!(event instanceof PullRequestCodeCommentEvent)
&& user != null
+ && !user.isSystem()
&& !user.equals(mentionedUser)
+ && isAiEligible(user, request, mentionedUser, true)
&& canCreateWorkspace(mentionedUser, request, true)) {
- onUserMentioned(mentionedUser, user, request);
+ onAiMentioned(mentionedUser, user, request, event.getParticipatingUserIds());
}
}
}
@@ -409,12 +413,13 @@ public class PullRequestNotificationManager implements Serializable {
bccEmailAddresses.add(emailAddress.getValue());
} else if (event.getCommentText() instanceof MarkdownText
&& watch.getUser().getAiSetting().isProactive()
- && isAiEligible(user, request, watch.getUser(), false)
&& user != null
&& !user.isSystem()
&& !user.equals(watch.getUser())
+ && isAiEligible(user, request, watch.getUser(), false)
&& canCreateWorkspace(watch.getUser(), request, false)) {
- onUserCommented(watch.getUser(), user, request);
+ onAiNotified(watch.getUser(), user, request,
+ event.getParticipatingUserIds());
}
}
}
@@ -449,7 +454,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber(), pullRequestBuildEvent.getBuild().getNumber());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
if (event instanceof PullRequestMergePreviewUpdated && request.getMergePreview() != null
&& request.getMergePreview().getMergeCommitHash() == null
@@ -461,7 +467,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(request.getSubmitter(), request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
}
@@ -490,7 +497,8 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber(), request.getSubmitter().getName());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(aiAssignee, request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(aiAssignee, request, commitId, getWorkspaceBranch(request),
+ prompt, event.getParticipatingUserIds());
}
}
}
@@ -523,7 +531,7 @@ public class PullRequestNotificationManager implements Serializable {
return true;
} else {
if (commentOnError)
- createComment(ai, request, "%s is not entitled to interact with me".formatted(user.getName()));
+ createComment(ai, request, "@%s is not entitled to interact with me".formatted(user.getName()));
return false;
}
} else {
@@ -537,7 +545,8 @@ public class PullRequestNotificationManager implements Serializable {
}
}
- private void onUserMentioned(User ai, User commenter, PullRequest request) {
+ private void onAiMentioned(User ai, User commenter, PullRequest request,
+ Collection<Long> participatingUserIds) {
List<String> prompts = new ArrayList<>();
if (request.getSubmitter().equals(ai)) {
prompts.add("Work on pull request %d as submitter to address %s's latest concern."
@@ -558,10 +567,12 @@ public class PullRequestNotificationManager implements Serializable {
var concatenatedPrompts = String.join(" ", prompts);
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(ai, request, commitId, getWorkspaceBranch(request), concatenatedPrompts);
+ runPrompt(ai, request, commitId, getWorkspaceBranch(request),
+ concatenatedPrompts, participatingUserIds);
}
- private void onUserCommented(User ai, User commenter, PullRequest request) {
+ private void onAiNotified(User ai, User commenter, PullRequest request,
+ Collection<Long> participatingUserIds) {
String prompt = """
Work on pull request %d to check whether you are relevant to %s's latest comment. \
Do not switch checkout if the comment does not require you to write code. \
@@ -569,13 +580,23 @@ public class PullRequestNotificationManager implements Serializable {
Make sure to submit work afterwards without confirmation."""
.formatted(request.getNumber(), commenter.getName());
var commitId = request.getLatestUpdate().getHeadCommit().copy();
- runPrompt(ai, request, commitId, getWorkspaceBranch(request), prompt);
+ runPrompt(ai, request, commitId, getWorkspaceBranch(request), prompt, participatingUserIds);
}
- private void runPrompt(User ai, PullRequest request, ObjectId commitId, @Nullable String branch, String prompt) {
+ private void runPrompt(User ai, PullRequest request, ObjectId commitId,
+ @Nullable String branch, String prompt, Collection<Long> eventParticipatingUserIds) {
+ var participatingUserIds = new ArrayList<>(eventParticipatingUserIds);
+ var awakenCount = participatingUserIds.stream().filter(ai.getId()::equals).count();
+ if (awakenCount >= ai.getAiSetting().getMaxLoopCount()) {
+ var message = "I reached the maximum awaken count of %d in the current event chain"
+ .formatted(ai.getAiSetting().getMaxLoopCount());
+ createComment(ai, request, message);
+ return;
+ }
try {
var taskFailedCallback = newTaskFailedCallback(ai.getId(), request.getId());
- workspaceService.runPrompt(ai, request.getProject(), null, request, commitId, branch, prompt, taskFailedCallback);
+ workspaceService.runPrompt(ai, request.getProject(), null, request, commitId, branch, prompt,
+ participatingUserIds, taskFailedCallback);
} catch (Throwable t) {
var explicitException = ExceptionUtils.find(t, ExplicitException.class);
if (explicitException != null) {
@@ -588,11 +609,8 @@ public class PullRequestNotificationManager implements Serializable {
}
private void createComment(User ai, PullRequest request, String comment) {
- if (SecurityUtils.canReadCode(ai.asSubject(), request.getProject())) {
- pullRequestCommentService.create(ai, request, comment);
- } else {
- pullRequestCommentService.create(userService.getSystem(), request, "_Commenting on behalf of **%s** as the user does not even have permission to post here._\n\n%s".formatted(ai.getName(), comment));
- }
+ pullRequestCommentService.create(userService.getSystem(), request,
+ "On behalf of AI user \"%s\": %s".formatted(ai.getDisplayName(), comment));
}
private boolean canCreateWorkspace(User ai, PullRequest request, boolean commentOnError) {
@@ -612,8 +630,9 @@ public class PullRequestNotificationManager implements Serializable {
private TaskFailedCallback newTaskFailedCallback(Long aiId, Long requestId) {
return new TaskFailedCallback() {
- public void onTaskFailed(String workspaceReference) {
- createComment(userService.load(aiId), pullRequestService.load(requestId), "Failed to do the job, please open workspace %s for details".formatted(workspaceReference));
+ public void onTaskFailed(String workspaceReference) {
+ createComment(userService.load(aiId), pullRequestService.load(requestId),
+ "Failed to do the job, please open workspace %s for details".formatted(workspaceReference));
}
};
diff --git a/server-core/src/main/java/io/onedev/server/security/BearerAuthenticationFilter.java b/server-core/src/main/java/io/onedev/server/security/BearerAuthenticationFilter.java
index 5a2898cd1d..4035974dfe 100644
--- a/server-core/src/main/java/io/onedev/server/security/BearerAuthenticationFilter.java
+++ b/server-core/src/main/java/io/onedev/server/security/BearerAuthenticationFilter.java
@@ -1,6 +1,7 @@
package io.onedev.server.security;
import io.onedev.server.cluster.ClusterService;
+import io.onedev.server.event.project.ProjectEvent;
import io.onedev.server.service.AccessTokenService;
import io.onedev.server.service.AgentTokenService;
import io.onedev.server.service.UserService;
@@ -11,8 +12,11 @@ import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
+import java.io.IOException;
+
import javax.inject.Inject;
import javax.inject.Singleton;
+import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@@ -56,6 +60,7 @@ public class BearerAuthenticationFilter extends ExceptionHandleFilter {
if (workspaceContext != null) {
var workspace = workspaceService.load(workspaceContext.getWorkspaceId());
ThreadContext.bind(workspace.getUser().asSubject());
+ ProjectEvent.setContextualParticipatingUserIds(workspace.getParticipatingUserIds());
} else if (agentTokenService.find(bearerToken) == null
&& jobService.getJobContext(bearerToken, false) == null) {
throw new IncorrectCredentialsException("Invalid or expired access token");
@@ -67,4 +72,14 @@ public class BearerAuthenticationFilter extends ExceptionHandleFilter {
return true;
}
+ @Override
+ protected void cleanup(ServletRequest request, ServletResponse response, Exception existing)
+ throws ServletException, IOException {
+ try {
+ super.cleanup(request, response, existing);
+ } finally {
+ ProjectEvent.clearContextualParticipatingUserIds();
+ }
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorEditBean.java b/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorEditBean.java
index 4059cc0a74..b6c261dbb7 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorEditBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorEditBean.java
@@ -2,6 +2,8 @@ package io.onedev.server.web.component.user.aisetting;
import java.io.Serializable;
+import javax.validation.constraints.Min;
+
import org.jspecify.annotations.Nullable;
import io.onedev.server.annotation.Editable;
@@ -16,6 +18,8 @@ public class BehaviorEditBean implements Serializable {
private boolean proactive;
+ private int maxLoopCount;
+
@Editable(order=100, description="""
Optional instructions that define how the AI user should behave""")
@Multiline
@@ -41,4 +45,16 @@ public class BehaviorEditBean implements Serializable {
this.proactive = proactive;
}
+ @Editable(order=300, description="""
+ Maximum number of times this AI user can be awakened in a single event chain. \
+ When the limit is reached, the AI user will not run and a system comment will be posted instead""")
+ @Min(value=1, message="At least 1 should be specified")
+ public int getMaxLoopCount() {
+ return maxLoopCount;
+ }
+
+ public void setMaxLoopCount(int maxLoopCount) {
+ this.maxLoopCount = maxLoopCount;
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorPanel.java
index b0cc264fca..86c1bd63e7 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/aisetting/BehaviorPanel.java
@@ -33,6 +33,7 @@ public class BehaviorPanel extends GenericPanel<User> {
var bean = new BehaviorEditBean();
bean.setSystemPrompt(getUser().getAiSetting().getSystemPrompt());
bean.setProactive(getUser().getAiSetting().isProactive());
+ bean.setMaxLoopCount(getUser().getAiSetting().getMaxLoopCount());
var oldAuditContent = VersionedXmlDoc.fromBean(bean).toXML();
Form<?> form = new Form<Void>("form") {
@@ -43,6 +44,7 @@ public class BehaviorPanel extends GenericPanel<User> {
var newAuditContent = VersionedXmlDoc.fromBean(bean).toXML();
getUser().getAiSetting().setSystemPrompt(bean.getSystemPrompt());
getUser().getAiSetting().setProactive(bean.isProactive());
+ getUser().getAiSetting().setMaxLoopCount(bean.getMaxLoopCount());
userService.update(getUser(), null);
auditService.audit(null, "changed AI behavior settings", oldAuditContent, newAuditContent);
getSession().success(_T("AI behavior settings have been saved"));
diff --git a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
index 06ef1544f7..5da37ab996 100644
--- a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
+++ b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
@@ -1118,7 +1118,8 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
@Transactional
@Override
public void runPrompt(User ai, Project project, @Nullable Issue issue, @Nullable PullRequest request,
- @Nullable ObjectId commitId, @Nullable String branch, String prompt, TaskFailedCallback taskFailedCallback) {
+ @Nullable ObjectId commitId, @Nullable String branch, String prompt,
+ List<Long> participatingUserIds, TaskFailedCallback taskFailedCallback) {
WorkspaceSpec applicableSpec = null;
for (var spec : project.getHierarchyWorkspaceSpecs()) {
if (spec.getTaskAutomation() != null) {
@@ -1131,7 +1132,9 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
}
if (applicableSpec != null) {
final WorkspaceSpec finalApplicableSpec = applicableSpec;
- var workspaceId = create(ai, project, issue, request, commitId, branch, applicableSpec.getName(), true).getId();
+ var createdWorkspace = create(ai, project, issue, request, commitId, branch, applicableSpec.getName(), true);
+ createdWorkspace.setParticipatingUserIds((ArrayList<Long>)participatingUserIds);
+ var workspaceId = createdWorkspace.getId();
transactionService.runAfterCommit(() -> {
executorService.execute(() -> {
diff --git a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
index 853061edb2..9e986ed066 100644
--- a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
+++ b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
@@ -86,6 +86,6 @@ public interface WorkspaceService extends EntityService<Workspace> {
void runPrompt(User ai, Project project, @Nullable Issue issue, @Nullable PullRequest request,
@Nullable ObjectId commitId, @Nullable String branch, String prompt,
- TaskFailedCallback taskFailedCallback);
+ List<Long> participatingUserIds, TaskFailedCallback taskFailedCallback);
}