This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-9593-89a492f97e92609d12c766af8dfa0b906bd8a2da
in repository https://gitbox.apache.org/repos/asf/texera.git

commit a1b5aad0e39ed184ea715cd108ea249fabe864f7
Author: Jiadong Bai <[email protected]>
AuthorDate: Tue Nov 24 06:30:54 2026 +0000

    feat(agent-service): tell users when the step limit is hit (#9593)
    
    ### What changes were proposed in this PR?
    
    A turn that reaches the step limit now ends with a message from the
    agent. Before, the chat went quiet.
    
    > I stopped because I reached the limit of 25 steps for one message, so
    the task may be unfinished. Send another message to continue, or raise
    the limit in the agent's settings.
    
    - **Where:** `sendMessage` in `agent-service/src/agent/texera-agent.ts`
    adds it as a closing agent step, as for a stopped or failed turn. The
    frontend is unchanged.
    - **When:** only if the loop's stop condition ended the turn. The AI SDK
    asks it only when the loop would otherwise go on, so a turn that ends
    for another reason on its last allowed step gets no message.
    - **Next turn:** the model reads it as the last entry of the earlier
    task.
    - **Stop on the last step:** a stop that lands on the last allowed step
    now ends with "Generation stopped by user.", as one on an earlier step
    does. Before, that turn ended with no message.
    
    **A request that needs four operators, with the step limit set to 3 and
    a scripted model.** Before, the agent stops after three and the chat
    ends on "Execute 1 tool":
    
    <img width="1228" height="704" alt="Before: the agent adds three
    operators, then the chat ends on Execute 1 tool with no message"
    
src="https://github.com/user-attachments/assets/30b0ff28-9f79-4e50-8cae-aef48c9afa23";
    />
    
    After, the agent says it stopped at the limit, and "continue" finishes
    the workflow:
    
    <img width="1228" height="704" alt="After: the agent says it stopped at
    the limit of 3 steps, and continue adds the bar chart and finishes"
    
src="https://github.com/user-attachments/assets/f5f4e11a-6f97-43f3-9c0a-c111c4ddee07";
    />
    
    ### Any related issues, documentation, discussions?
    
    Closes #9592
    Part of #9576
    
    ### How was this PR tested?
    
    - `bun test` in `agent-service`, eight new tests. The message appears at
    the limit and names the limit the turn started with. It does not appear
    when the model answers on its last allowed step, a cut-off tool call
    ends the turn, or the user stops it. A stop on the last allowed step
    ends as stopped.
    - Live with Claude Haiku 5.5 and a limit of 2: the chat panel showed the
    message, and "continue" resumed the work.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Fable 5.2)
---
 agent-service/src/agent/texera-agent.spec.ts | 150 ++++++++++++++++++++++++++-
 agent-service/src/agent/texera-agent.ts      |  87 ++++++++++------
 2 files changed, 202 insertions(+), 35 deletions(-)

diff --git a/agent-service/src/agent/texera-agent.spec.ts 
b/agent-service/src/agent/texera-agent.spec.ts
index a1644921cf..24a8145982 100644
--- a/agent-service/src/agent/texera-agent.spec.ts
+++ b/agent-service/src/agent/texera-agent.spec.ts
@@ -729,6 +729,153 @@ describe("sendMessage", () => {
     expect(agent.getWorkflowState().getOperator("op1")).toBeDefined();
   });
 
+  /**
+   * A turn the step limit cuts short ends on a tool call, with no answer from 
the model. The agent
+   * then closes the turn itself, with a step that says why it stopped and 
what the user can do.
+   */
+  describe("step limit notice", () => {
+    const notice = (limit: string) =>
+      `I stopped because I reached the limit of ${limit} for one message, so 
the task may be unfinished. ` +
+      "Send another message to continue, or raise the limit in the agent's 
settings.";
+
+    /**
+     * A model that calls a tool on each of its first `toolCalls` calls and 
then answers "done".
+     * `reason` is the finish reason it reports along with a tool call, and 
`onCall` is called at
+     * the start of every call with the call's number.
+     */
+    const toolCallingModel = (
+      toolCalls: number,
+      options: { reason?: "tool-calls" | "stop" | "length"; onCall?: (n: 
number) => void } = {}
+    ) => {
+      let n = 0;
+      return new MockLanguageModelV4({
+        doGenerate: async () => {
+          n++;
+          if (n > 20) throw new Error("runaway");
+          options.onCall?.(n);
+          const callsTool = n <= toolCalls;
+          return {
+            content: callsTool
+              ? [
+                  {
+                    type: "tool-call",
+                    toolCallId: "c" + n,
+                    toolName: "deleteOperator",
+                    input: JSON.stringify({ operatorId: "ghost" }),
+                  },
+                ]
+              : [{ type: "text", text: "done" }],
+            finishReason: finish(callsTool ? (options.reason ?? "tool-calls") 
: "stop"),
+            usage: usage(1, 1),
+            warnings: [],
+          } as any;
+        },
+      });
+    };
+
+    test("closes a turn the limit cut short with a step that says so", async 
() => {
+      const agent = makeAgentWith(toolCallingModel(Infinity));
+      agent.updateSettings({ maxSteps: 3 });
+      // The server streams a step to the chat as it is announced, so what is 
announced is what
+      // the user sees.
+      const announced: ReActStep[] = [];
+      agent.setStepCallback(step => announced.push({ ...step }));
+      const res = await agent.sendMessage("go");
+      const steps = agent.getAllSteps();
+      expect(steps.map(s => [s.role, s.stepId, s.content, s.isBegin, 
s.isEnd])).toEqual([
+        ["user", 0, "go", true, true],
+        ["agent", 1, "", true, false],
+        ["agent", 2, "", false, false],
+        ["agent", 3, "", false, false],
+        ["agent", 4, notice("3 steps"), false, true],
+      ]);
+      expect(steps[4].toolCalls).toBeUndefined();
+      expect(steps[4].parentId).toBe(steps[3].id);
+      expect(steps[4].messageId).toBe(steps[0].messageId);
+      expect(agent.getHead()).toBe(steps[4].id);
+      expect(announced.at(-1)).toEqual(steps[4]);
+      expect(res.stopped).toBe(false);
+      expect(res.error).toBeUndefined();
+      expect(agent.getState()).toBe(AgentState.AVAILABLE);
+    });
+
+    test("adds nothing when the model answers on the last allowed step", async 
() => {
+      const agent = makeAgentWith(toolCallingModel(2));
+      agent.updateSettings({ maxSteps: 3 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => [s.stepId, s.content, 
s.isEnd])).toEqual([
+        [0, "go", true],
+        [1, "", false],
+        [2, "", false],
+        [3, "done", true],
+      ]);
+    });
+
+    test("names the limit the turn started with, in the singular for one 
step", async () => {
+      let agent!: TexeraAgent;
+      // A limit saved while the turn is in flight applies from the next 
message on.
+      const model = toolCallingModel(Infinity, { onCall: () => 
agent.updateSettings({ maxSteps: 7 }) });
+      agent = makeAgentWith(model);
+      agent.updateSettings({ maxSteps: 1 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => s.content)).toEqual(["go", "", 
notice("1 step")]);
+      await agent.sendMessage("go on");
+      expect(agent.getAllSteps().at(-1)?.content).toBe(notice("7 steps"));
+    });
+
+    test("still appears when the provider reports a tool call as a plain 
stop", async () => {
+      // The AI SDK goes on whenever a step's tool calls were executed, 
whatever finish reason the
+      // provider gave, so the limit is what ends this turn too.
+      const agent = makeAgentWith(toolCallingModel(Infinity, { reason: "stop" 
}));
+      agent.updateSettings({ maxSteps: 2 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().at(-1)?.content).toBe(notice("2 steps"));
+    });
+
+    test("adds nothing when a cut-off tool call ends the turn on the last 
allowed step", async () => {
+      // The call was never executed, so the turn would have ended here under 
any limit.
+      const agent = makeAgentWith(toolCallingModel(Infinity, { reason: 
"length" }));
+      agent.updateSettings({ maxSteps: 1 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => [s.stepId, s.content, 
s.isEnd])).toEqual([
+        [0, "go", true],
+        [1, "", true],
+      ]);
+    });
+
+    test.each([
+      ["before the limit", 1, ["go", "", "Generation stopped by user."]],
+      ["on the last allowed step", 2, ["go", "", "", "Generation stopped by 
user."]],
+    ])("ends a turn the user stops %s as stopped, without the notice", async 
(_when, stopAtCall, contents) => {
+      // On the last allowed step the AI SDK returns normally rather than 
throwing, since no further
+      // model call sees the abort. The turn still has to end as stopped.
+      let agent!: TexeraAgent;
+      const model = toolCallingModel(Infinity, {
+        onCall: n => {
+          if (n === stopAtCall) agent.stop();
+        },
+      });
+      agent = makeAgentWith(model);
+      agent.updateSettings({ maxSteps: 2 });
+      const res = await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => s.content)).toEqual(contents);
+      expect(res.stopped).toBe(true);
+      expect(agent.getHead()).toBe(agent.getAllSteps().at(-1)!.id);
+    });
+
+    test("the next turn reads the notice as the last entry of the task it 
closed", async () => {
+      const model = toolCallingModel(Infinity);
+      const agent = makeAgentWith(model);
+      agent.updateSettings({ maxSteps: 2 });
+      await agent.sendMessage("go");
+      await agent.sendMessage("continue");
+      const txt: string = (model as 
any).doGenerateCalls[2].prompt[1].content[0].text;
+      expect(txt).toContain("## Task (completed)");
+      expect(txt).toContain(`### Turn 3\nThought: ${notice("2 steps")}\n\n# 
Ongoing Task`);
+      expect(txt.split(notice("2 steps")).length).toBe(2);
+    });
+  });
+
   test("caps the loop at maxSteps", async () => {
     // The cap is the only thing standing between a looping model and an 
unbounded run.
     let n = 0;
@@ -755,7 +902,8 @@ describe("sendMessage", () => {
     agent.updateSettings({ maxSteps: 2 });
     await agent.sendMessage("go");
     expect(n).toBe(2);
-    expect(agent.getAllSteps().map(s => s.stepId)).toEqual([0, 1, 2]);
+    // The user's message, the two model steps the limit allows, and the 
notice that it was reached.
+    expect(agent.getAllSteps().map(s => s.stepId)).toEqual([0, 1, 2, 3]);
   });
 
   test("second turn chains on and reads turn 1 as completed", async () => {
diff --git a/agent-service/src/agent/texera-agent.ts 
b/agent-service/src/agent/texera-agent.ts
index 555cc2730f..e752c54312 100644
--- a/agent-service/src/agent/texera-agent.ts
+++ b/agent-service/src/agent/texera-agent.ts
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-import { generateText, type ModelMessage, type LanguageModel, stepCountIs } 
from "ai";
+import { generateText, type ModelMessage, type LanguageModel } from "ai";
 import { Subscription } from "rxjs";
 import { debounceTime } from "rxjs/operators";
 import { WorkflowState } from "./workflow-state";
@@ -75,6 +75,18 @@ export interface AgentMessageResult {
 
 type ReActStepCallback = (step: ReActStep) => void;
 
+/**
+ * What the agent says when the step limit ends a turn. Such a turn stops on a 
tool call, with no
+ * closing answer from the model, so without this the chat would only go quiet.
+ */
+function stepLimitNotice(maxSteps: number): string {
+  const limit = maxSteps === 1 ? "1 step" : `${maxSteps} steps`;
+  return (
+    `I stopped because I reached the limit of ${limit} for one message, so the 
task may be unfinished. ` +
+    "Send another message to continue, or raise the limit in the agent's 
settings."
+  );
+}
+
 /**
  * A single Texera agent instance.
  *
@@ -506,6 +518,23 @@ export class TexeraAgent {
   async sendMessage(userMessage: string, messageSource?: "chat" | "feedback"): 
Promise<AgentMessageResult> {
     const messageId = 
`msg-${this.agentId}-${++this.messageCounter}-${Date.now()}`;
     let stepIndex = 0;
+    // Ends the turn with a step that says how it ended: at the step limit, 
stopped, or failed.
+    const addClosingStep = (content: string): void => {
+      stepIndex++;
+      const step: ReActStep = {
+        id: this.generateStepId(),
+        parentId: this.head,
+        messageId,
+        stepId: stepIndex,
+        timestamp: Date.now(),
+        role: "agent",
+        content,
+        isBegin: false,
+        isEnd: true,
+      };
+      this.addStep(step);
+      this.head = step.id;
+    };
 
     await this.refreshWorkflowFromBackend();
 
@@ -542,6 +571,15 @@ export class TexeraAgent {
       this.addStep(userStep);
       this.head = userStepId;
 
+      // The limit for this turn: one saved while the turn is in flight 
applies from the next
+      // message on.
+      const maxSteps = this.settings.maxSteps;
+      // Whether the limit is what ended the turn. The AI SDK asks `stopWhen` 
only after a step
+      // whose tool calls were executed, when the loop would otherwise go on, 
so its answer says
+      // so exactly. The last step's finish reason does not: it is the 
provider's word, and the
+      // SDK goes on after a tool call that a provider reported as a plain 
"stop".
+      let stoppedAtStepLimit = false;
+
       let isFirstStep = true;
       let lastPreparedMessages: ModelMessage[] | undefined;
 
@@ -554,7 +592,10 @@ export class TexeraAgent {
         messages: currentUserMessage,
         tools: this.getEnabledTools(),
         temperature: 0.2,
-        stopWhen: stepCountIs(this.settings.maxSteps),
+        stopWhen: ({ steps }) => {
+          stoppedAtStepLimit = steps.length >= maxSteps;
+          return stoppedAtStepLimit;
+        },
         prepareStep: async ({ stepNumber, messages: currentMessages }) => {
           let compilationResult: WorkflowCompilationResponse | null = null;
           if (this.workflowState.getAllOperators().length > 0) {
@@ -671,6 +712,14 @@ export class TexeraAgent {
         },
       });
 
+      // A stop that lands on the last allowed step lets `generateText` return 
normally, since the
+      // stop condition ends the loop before another model call can see the 
abort. Such a turn ends
+      // like a stop on an earlier step, in the catch below.
+      this.abortController?.signal.throwIfAborted();
+
+      // A turn the limit cut short has no closing answer, so the agent says 
why it stopped.
+      if (stoppedAtStepLimit) addClosingStep(stepLimitNotice(maxSteps));
+
       const msgSteps = this.reActStepsByMessageId.get(messageId);
       if (msgSteps && msgSteps.length > 0) {
         const lastStep = msgSteps[msgSteps.length - 1];
@@ -697,22 +746,7 @@ export class TexeraAgent {
       const isAborted = error?.name === "AbortError" || 
this.abortController?.signal.aborted;
 
       if (isAborted) {
-        stepIndex++;
-        const stoppedStepId = this.generateStepId();
-        const stoppedStep: ReActStep = {
-          id: stoppedStepId,
-          parentId: this.head,
-          messageId,
-          stepId: stepIndex,
-          timestamp: Date.now(),
-          role: "agent",
-          content: "Generation stopped by user.",
-          isBegin: false,
-          isEnd: true,
-        };
-        this.addStep(stoppedStep);
-        this.head = stoppedStepId;
-
+        addClosingStep("Generation stopped by user.");
         return {
           response: "",
           messages: [],
@@ -721,22 +755,7 @@ export class TexeraAgent {
         };
       }
 
-      stepIndex++;
-      const errorStepId = this.generateStepId();
-      const errorStep: ReActStep = {
-        id: errorStepId,
-        parentId: this.head,
-        messageId,
-        stepId: stepIndex,
-        timestamp: Date.now(),
-        role: "agent",
-        content: `Error: ${errorMessage}`,
-        isBegin: false,
-        isEnd: true,
-      };
-      this.addStep(errorStep);
-      this.head = errorStepId;
-
+      addClosingStep(`Error: ${errorMessage}`);
       return {
         response: "",
         messages: [],

Reply via email to