This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git
The following commit(s) were added to refs/heads/main by this push:
new de3f021dec fix(agent-service): reject prompts sent while a run is in
flight (#8753)
de3f021dec is described below
commit de3f021deceb3e25529e36441f53f2cf4007b303
Author: Luis Fernando Caro Reyna
<[email protected]>
AuthorDate: Tue Nov 24 21:45:37 2026 +0000
fix(agent-service): reject prompts sent while a run is in flight (#8753)
### What changes were proposed in this PR?
A prompt arriving while an agent run is already in flight could
re-point that run's warehouse mid-execution, and race on shared agent
state.
Before: prompt A starts run (GENERATING) -> prompt B arrives mid-run
-> setDelegateWarehouse() applies B's warehouse unconditionally
-> A's still-running execution tools read the new warehouse
After: prompt A starts run -> prompt B arrives mid-run -> rejected
with a busy error, A's warehouse/state untouched
Root cause, two parts:
1. `server.ts`'s `WsClientPromptCommand` handler called
`agent.setDelegateWarehouse(...)` unconditionally on every prompt,
with no check for whether a run was already in progress.
2. `TexeraAgent.sendMessage` didn't flip `state` to `GENERATING` until
after its first `await` (`refreshWorkflowFromBackend()`). Since two
`message` handler invocations can interleave across that await, a
second prompt could see stale `state` and proceed concurrently,
racing on `head`, `abortController`, and `currentMessageId` as well.
Fix:
**agent-service**
- `sendMessage` now flips `state` (and resets `abortController`)
synchronously before any `await`, and throws if already `GENERATING`.
`refreshWorkflowFromBackend()` runs inside the `try`, so its `finally`
always resets state.
- The WebSocket handler checks `agent.getState()` and rejects a busy
agent with a `WsServerErrorEvent` before it ever calls
`setDelegateWarehouse`, so a rejected prompt's delegate config is left
untouched.
- `stop()` is now a no-op unless the agent is `GENERATING`. Before, an
idle stop set `STOPPING` with nothing to reset it, so the new busy
guard rejected every later prompt.
- Both stop paths report the resulting state instead of assuming a stop
happened: the WebSocket stop handler broadcasts `agent.getState()`,
and `POST /agents/:id/stop` returns `{ status: agent.getState() }`
(`STOPPING` mid-run, `AVAILABLE` when idle) instead of a fixed
`"stopping"`. Nothing in the repo reads that response body.
**frontend**
- The operator-feedback panel (`agent-interaction.component.ts`) only
sends when the selected agent is `AVAILABLE`, matching the chat
panel. `canSend()` disables the Send button mid-run, and
`sendFeedbackToAgent()` checks too, since Ctrl+Enter bypasses the
disabled button. A busy agent gets a warning toast, no success toast,
and the textarea keeps its text.
- New `AgentService.getAgentStateSnapshot()` reads an agent's latest
state synchronously without creating tracking for an unknown id.
`getAgentState()` now wraps it, so the lookup lives in one place.
UI change, operator-feedback panel during an agent run:
<img width="1644" height="610" alt="image"
src="https://github.com/user-attachments/assets/3206edf7-a9f1-49e8-81bc-522bf7d41b6c"
/>
<img width="1644" height="610" alt="image"
src="https://github.com/user-attachments/assets/2164743a-5fbb-4433-b189-7f0d63e3e9c9"
/>
Before: Send is enabled mid-run. Sending shows "Message sent to agent
successfully", clears the input, and the feedback lands as a second
prompt while the first run is still thinking. After: Send is disabled
mid-run. Ctrl+Enter shows only "Agent is busy. Please wait for the
current run to finish.", nothing is sent, and the text is kept.
### Any related issues, documentation, discussions?
Closes #8711
### How was this PR tested?
Regression tests, each verified red without its fix and green with it:
- `agent-service/src/agent/texera-agent.spec.ts`: gates a mock LLM call
open, asserts a concurrent `sendMessage()` call throws "busy" instead
of interleaving. With no sleep before the second call, it also fails
if the refresh await moves back above the state flip.
- `agent-service/src/agent/texera-agent.spec.ts`: an idle `stop()` is a
no-op, a `stop()` while generating still moves to `STOPPING`, and
`sendMessage` succeeds after an idle stop.
- `agent-service/src/server.ws.spec.ts`: the busy scenario over the real
WebSocket protocol; also pins an initial `warehouseId` and asserts a
busy-rejected prompt carrying a different `warehouseId` never reaches
`setDelegateWarehouse`. An idle WS stop reports `AVAILABLE`.
- `agent-service/src/server.spec.ts`: `POST /agents/:id/stop` returns
`STOPPING` mid-run and `AVAILABLE` when idle.
- `agent-interaction.component.spec.ts`: Send is disabled and
Ctrl+Enter is rejected while the agent is busy, with the input kept.
Run with:
cd agent-service && bun run format:check && bun run typecheck && bun
test
348 tests pass (0 fail).
cd frontend && yarn format:ci && yarn lint && yarn test --watch=false
254 test files, 7295 tests pass (1 skipped, 0 fail).
Additionally verified manually against the real running stack (real
signed JWT, real WebSocket, and an actual LLM API key generating a real
response) rather than a stubbed model: sent two prompts back-to-back
with different `warehouseId`s, confirmed the second is rejected with
"Agent is busy processing another message" while the first's run — and
its `warehouseId` — is unaffected. Also checked that `POST /stop` on an
idle agent followed by a prompt runs normally, and that in the feedback
panel Send is disabled mid-run and Ctrl+Enter shows only the busy
warning with the input kept.
UI click path for the screenshots (Chromium, 1280x800 viewport,
local-dev
stack, qwen/qwen4-max agent): open a workflow with a CSV File Scan
operator, create an agent in the AI Agents panel, click the operator's
chat button to open the feedback popover and select the agent, send a
multi-step prompt in the agent chat, then while it shows "Thinking..."
type feedback in the popover and click Send (before) or press Ctrl+Enter
(after).
### Was this PR authored or co-authored using generative AI tooling?
Generated-by: Claude
---
agent-service/src/agent/texera-agent.spec.ts | 55 ++++++++++++++++++-
agent-service/src/agent/texera-agent.ts | 25 +++++++--
agent-service/src/server.spec.ts | 12 +++-
agent-service/src/server.ts | 15 ++++-
agent-service/src/server.ws.spec.ts | 64 +++++++++++++++++++++-
.../agent-interaction.component.spec.ts | 24 ++++++++
.../agent-interaction.component.ts | 15 ++++-
.../workspace/service/agent/agent.service.spec.ts | 9 +++
.../app/workspace/service/agent/agent.service.ts | 15 ++---
9 files changed, 214 insertions(+), 20 deletions(-)
diff --git a/agent-service/src/agent/texera-agent.spec.ts
b/agent-service/src/agent/texera-agent.spec.ts
index 24a8145982..6d0718c5ce 100644
--- a/agent-service/src/agent/texera-agent.spec.ts
+++ b/agent-service/src/agent/texera-agent.spec.ts
@@ -317,7 +317,15 @@ describe("TexeraAgent", () => {
expect(agent.getAncestorPath()).toEqual([INITIAL_STEP_ID]);
});
- test("stop moves the agent into the stopping state", () => {
+ test("stop on an idle agent is a no-op", () => {
+ agent.stop();
+
+ expect(agent.getState()).toBe(AgentState.AVAILABLE);
+ });
+
+ test("stop moves a generating agent into the stopping state", () => {
+ (agent as any).state = AgentState.GENERATING;
+
agent.stop();
expect(agent.getState()).toBe(AgentState.STOPPING);
@@ -1156,6 +1164,51 @@ describe("sendMessage", () => {
expect(observed).toEqual([AgentState.GENERATING]);
expect(agent.getState()).toBe(AgentState.AVAILABLE);
});
+
+ test("a second sendMessage while one is in flight is rejected, not
interleaved (#8711)", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>(r => (release = r));
+ const model = new MockLanguageModelV4({
+ doGenerate: async () => {
+ await gate;
+ return {
+ content: [{ type: "text", text: "x" }],
+ finishReason: finish("stop"),
+ usage: usage(1, 1),
+ warnings: [],
+ } as any;
+ },
+ });
+ const agent = makeAgentWith(model);
+ const first = agent.sendMessage("first");
+
+ expect(agent.getState()).toBe(AgentState.GENERATING);
+ await expect(agent.sendMessage("second")).rejects.toThrow("busy");
+
+ release();
+ await first;
+ expect(agent.getState()).toBe(AgentState.AVAILABLE);
+ });
+
+ test("a stop while idle does not wedge the next sendMessage", async () => {
+ const model = new MockLanguageModelV4({
+ doGenerate: async () =>
+ ({
+ content: [{ type: "text", text: "x" }],
+ finishReason: finish("stop"),
+ usage: usage(1, 1),
+ warnings: [],
+ }) as any,
+ });
+ const agent = makeAgentWith(model);
+
+ agent.stop();
+ expect(agent.getState()).toBe(AgentState.AVAILABLE);
+
+ const res = await agent.sendMessage("after idle stop");
+ expect(res.error).toBeUndefined();
+ expect(agent.getState()).toBe(AgentState.AVAILABLE);
+ });
});
/**
diff --git a/agent-service/src/agent/texera-agent.ts
b/agent-service/src/agent/texera-agent.ts
index e752c54312..126ba33c8a 100644
--- a/agent-service/src/agent/texera-agent.ts
+++ b/agent-service/src/agent/texera-agent.ts
@@ -516,6 +516,16 @@ export class TexeraAgent {
}
async sendMessage(userMessage: string, messageSource?: "chat" | "feedback"):
Promise<AgentMessageResult> {
+ // State flips synchronously, before the first await below, so a second
+ // prompt arriving while this one is mid-flight (e.g. during
+ // refreshWorkflowFromBackend) sees GENERATING and is rejected instead of
+ // interleaving with this run's head/abortController/currentMessageId
(#8711).
+ if (this.state !== AgentStateEnum.AVAILABLE) {
+ throw new Error("Agent is busy processing another message");
+ }
+ this.state = AgentStateEnum.GENERATING;
+ this.abortController = new AbortController();
+
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.
@@ -536,15 +546,13 @@ export class TexeraAgent {
this.head = step.id;
};
- await this.refreshWorkflowFromBackend();
-
- this.abortController = new AbortController();
-
- this.state = AgentStateEnum.GENERATING;
-
this.currentMessageId = messageId;
try {
+ // Inside the try so the finally below always resets state, even if the
+ // refresh ever starts throwing.
+ await this.refreshWorkflowFromBackend();
+
let beforeStepContent = this.workflowState.getWorkflowContent();
const estimatedInputTokens = Math.ceil(userMessage.length / 4);
@@ -780,6 +788,11 @@ export class TexeraAgent {
}
stop(): void {
+ // Only a run in flight can be stopped. An idle agent has no finally to
+ // reset STOPPING, so setting it here would wedge sendMessage's busy guard.
+ if (this.state !== AgentStateEnum.GENERATING) {
+ return;
+ }
this.state = AgentStateEnum.STOPPING;
if (this.abortController) {
this.abortController.abort();
diff --git a/agent-service/src/server.spec.ts b/agent-service/src/server.spec.ts
index 2b42f5dc7e..84e979e289 100644
--- a/agent-service/src/server.spec.ts
+++ b/agent-service/src/server.spec.ts
@@ -208,11 +208,19 @@ describe(`DELETE ${API}/agents/:id`, () => {
});
describe("Agent control routes", () => {
- test("POST /:id/stop returns stopping", async () => {
+ test("POST /:id/stop mid-run returns STOPPING", async () => {
const created = await readJson<{ id: string }>(await createAgent());
+ (_getAgentForTests(created.id)! as any).state = "GENERATING";
const res = await postJson(`${API}/agents/${created.id}/stop`, {});
expect(res.status).toBe(200);
- expect(await readJson<unknown>(res)).toEqual({ status: "stopping" });
+ expect(await readJson<unknown>(res)).toEqual({ status: "STOPPING" });
+ });
+
+ test("POST /:id/stop on an idle agent returns AVAILABLE", async () => {
+ const created = await readJson<{ id: string }>(await createAgent());
+ const res = await postJson(`${API}/agents/${created.id}/stop`, {});
+ expect(res.status).toBe(200);
+ expect(await readJson<unknown>(res)).toEqual({ status: "AVAILABLE" });
});
test("POST /:id/clear resets history", async () => {
diff --git a/agent-service/src/server.ts b/agent-service/src/server.ts
index 02981e02ad..f3775e8895 100644
--- a/agent-service/src/server.ts
+++ b/agent-service/src/server.ts
@@ -303,7 +303,8 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
.post("/:id/stop", ({ params: { id } }) => {
const agent = getAgent(id);
agent.stop();
- return { status: "stopping" };
+ // Report the resulting state: STOPPING mid-run, unchanged when idle.
+ return { status: agent.getState() };
})
.post("/:id/clear", ({ params: { id } }) => {
@@ -473,7 +474,8 @@ export function buildApp() {
switch (msg.type) {
case "WsClientStopCommand":
agent.stop();
- broadcastToAgentClients(agentId, new
WsServerStatusEvent(AgentState.STOPPING));
+ // Broadcast the resulting state: STOPPING mid-run, unchanged when
idle.
+ broadcastToAgentClients(agentId, new
WsServerStatusEvent(agent.getState()));
return;
case "WsClientPromptCommand": {
@@ -484,6 +486,15 @@ export function buildApp() {
wsLog.info({ agentId, preview: msg.content.substring(0, 50) },
"received command");
+ // Reject a prompt that arrives while a run is already in flight
+ // instead of re-pointing that run's warehouse mid-execution
(#8711).
+ // Checked before setDelegateWarehouse so a busy agent's delegate
+ // config is left untouched.
+ if (agent.getState() !== AgentState.AVAILABLE) {
+ sendEventToClient(ws, new WsServerErrorEvent("Agent is busy
processing another message"));
+ return;
+ }
+
// The prompt carries the workspace's current warehouse pick, so a
run
// uses what the user has selected now rather than whatever was
// selected when the agent was created. An absent field IS the
diff --git a/agent-service/src/server.ws.spec.ts
b/agent-service/src/server.ws.spec.ts
index cbb1ffb8eb..cf372bcf03 100644
--- a/agent-service/src/server.ws.spec.ts
+++ b/agent-service/src/server.ws.spec.ts
@@ -26,6 +26,7 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test }
from "bun:test";
import { buildApp, _resetAgentStoreForTests, _getAgentForTests } from
"./server";
import { env } from "./config/env";
+import { AgentState } from "./types/agent";
const API = env.API_PREFIX;
@@ -169,8 +170,9 @@ describe(`WS ${API}/agents/:id/react`, () => {
expect(err.error).toBe("Agent not found");
});
- test("a stop command broadcasts a STOPPING status frame", async () => {
+ test("a stop command mid-run broadcasts a STOPPING status frame", async ()
=> {
const id = await createAgent();
+ (_getAgentForTests(id)! as any).state = "GENERATING";
const { ws, messages } = connect(id);
await waitOpen(ws);
await messages.waitFor(m => m.type === "WsServerSnapshotEvent");
@@ -181,6 +183,19 @@ describe(`WS ${API}/agents/:id/react`, () => {
expect(status.state).toBe("STOPPING");
});
+ test("a stop command on an idle agent leaves it AVAILABLE for the next
prompt", async () => {
+ const id = await createAgent();
+ const { ws, messages } = connect(id);
+ await waitOpen(ws);
+ await messages.waitFor(m => m.type === "WsServerSnapshotEvent");
+
+ ws.send(JSON.stringify({ type: "WsClientStopCommand" }));
+
+ const status = await messages.waitFor(m => m.type ===
"WsServerStatusEvent");
+ expect(status.state).toBe("AVAILABLE");
+ expect(_getAgentForTests(id)!.getState()).toBe(AgentState.AVAILABLE);
+ });
+
test("a prompt with empty content yields an error frame", async () => {
const id = await createAgent();
const { ws, messages } = connect(id);
@@ -299,6 +314,53 @@ describe(`WS ${API}/agents/:id/react`, () => {
expect(resting.state).toBe("AVAILABLE");
});
+ test("a prompt sent while a run is in flight is rejected, not interleaved
(#8711)", async () => {
+ const id = await createAgent();
+ const agent = _getAgentForTests(id)! as any;
+
+ // Pin an initial warehouse so we can assert the busy-rejected prompt below
+ // never reaches setDelegateWarehouse and re-points it mid-run (#8711).
+ agent.setDelegateConfig({ userToken: "t", workflowId: 1, warehouseId: 7 });
+
+ let release!: () => void;
+ const gate = new Promise<void>(r => (release = r));
+ let callCount = 0;
+ agent.sendMessage = async function (this: any) {
+ callCount++;
+ this.state = "GENERATING";
+ await gate;
+ this.state = "AVAILABLE";
+ return {
+ response: "done",
+ messages: [],
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
+ stopped: false,
+ };
+ };
+ agent.getReActSteps = () => [];
+
+ const { ws, messages } = connect(id);
+ await waitOpen(ws);
+ await messages.waitFor(m => m.type === "WsServerSnapshotEvent");
+
+ ws.send(JSON.stringify({ type: "WsClientPromptCommand", content: "first",
warehouseId: 7 }));
+ await messages.waitFor(m => m.type === "WsServerStatusEvent" && m.state
=== "GENERATING");
+ expect(agent.getDelegateConfig()?.warehouseId).toBe(7);
+
+ // Second prompt, mid-run, picks a *different* warehouse. It must be
+ // rejected before setDelegateWarehouse runs, so the in-flight run keeps
+ // writing to warehouse 7, not 99.
+ ws.send(JSON.stringify({ type: "WsClientPromptCommand", content: "second",
warehouseId: 99 }));
+ const err = await messages.waitFor(m => m.type === "WsServerErrorEvent");
+ expect(err.error).toBe("Agent is busy processing another message");
+ expect(callCount).toBe(1);
+ expect(agent.getDelegateConfig()?.warehouseId).toBe(7);
+
+ release();
+ await messages.waitFor(m => m.type === "WsServerStatusEvent" && m.state
=== "AVAILABLE");
+ expect(agent.getDelegateConfig()?.warehouseId).toBe(7);
+ });
+
test("a message for an agent that no longer exists yields an error frame",
async () => {
const id = await createAgent();
const { ws, messages } = connect(id);
diff --git
a/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.spec.ts
b/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.spec.ts
index 193afc2dab..a216269927 100644
---
a/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.spec.ts
+++
b/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.spec.ts
@@ -24,6 +24,7 @@ import { HttpClientTestingModule } from
"@angular/common/http/testing";
import { Observable, Subject, of } from "rxjs";
import { AgentInteractionComponent } from "./agent-interaction.component";
import { AgentInfo, AgentService, IndexedTuple, Tuple } from
"../../../service/agent/agent.service";
+import { AgentState } from "../../../service/agent/agent-types";
import { WorkflowActionService } from
"../../../service/workflow-graph/model/workflow-action.service";
import { NotificationService } from
"../../../../common/service/notification/notification.service";
import { commonTestProviders } from "../../../../common/testing/test-utils";
@@ -42,6 +43,7 @@ describe("AgentInteractionComponent", () => {
getAllAgents: ReturnType<typeof vi.fn>;
getActivelyConnectedAgentIds: ReturnType<typeof vi.fn>;
isAgentActivelyConnected: ReturnType<typeof vi.fn>;
+ getAgentStateSnapshot: ReturnType<typeof vi.fn>;
sendMessage: ReturnType<typeof vi.fn>;
};
let workflowActionService: { getTexeraGraph: ReturnType<typeof vi.fn> };
@@ -65,6 +67,7 @@ describe("AgentInteractionComponent", () => {
getAllAgents: vi.fn().mockReturnValue(of([])),
getActivelyConnectedAgentIds: vi.fn().mockReturnValue([]),
isAgentActivelyConnected: vi.fn().mockReturnValue(false),
+ getAgentStateSnapshot: vi.fn().mockReturnValue(AgentState.AVAILABLE),
sendMessage: vi.fn(),
};
workflowActionService = {
@@ -201,6 +204,18 @@ describe("AgentInteractionComponent", () => {
component.feedbackMessage = "hi";
expect(component.canSend()).toBe(true);
});
+
+ it("is false while the selected agent is not AVAILABLE", () => {
+ createComponent();
+ component.selectedAgentId = "a1";
+ component.feedbackMessage = "hi";
+
+ for (const state of [AgentState.GENERATING, AgentState.STOPPING,
AgentState.UNAVAILABLE]) {
+ agentService.getAgentStateSnapshot.mockReturnValue(state);
+ expect(component.canSend()).toBe(false);
+ }
+ expect(agentService.getAgentStateSnapshot).toHaveBeenCalledWith("a1");
+ });
});
describe("sendFeedbackToAgent", () => {
@@ -238,6 +253,15 @@ describe("AgentInteractionComponent", () => {
expect(agentService.sendMessage).not.toHaveBeenCalled();
});
+ it("warns, does not send, and keeps the input when the agent is mid-run",
() => {
+
agentService.getAgentStateSnapshot.mockReturnValue(AgentState.GENERATING);
+ component.sendFeedbackToAgent();
+ expect(notification.warning).toHaveBeenCalledWith("Agent is busy. Please
wait for the current run to finish.");
+ expect(notification.success).not.toHaveBeenCalled();
+ expect(agentService.sendMessage).not.toHaveBeenCalled();
+ expect(component.feedbackMessage).toBe("hello");
+ });
+
it("sends the feedback with operator context, notifies, and clears the
input", () => {
component.sendFeedbackToAgent();
expect(agentService.sendMessage).toHaveBeenCalledWith(
diff --git
a/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.ts
b/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.ts
index eb4d433c8b..957edd0b38 100644
---
a/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.ts
+++
b/frontend/src/app/workspace/component/agent/agent-interaction/agent-interaction.component.ts
@@ -21,6 +21,7 @@ import { ChangeDetectorRef, Component, Input, OnChanges,
OnInit, SimpleChanges }
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
import { AgentService } from "../../../service/agent/agent.service";
+import { AgentState } from "../../../service/agent/agent-types";
import { WorkflowActionService } from
"../../../service/workflow-graph/model/workflow-action.service";
import { NotificationService } from
"../../../../common/service/notification/notification.service";
import { NgIf, NgFor } from "@angular/common";
@@ -162,6 +163,13 @@ export class AgentInteractionComponent implements OnInit,
OnChanges {
return;
}
+ // The agent service rejects a prompt while a run is in flight; check first
+ // so the user's text is kept instead of cleared under a false success
toast.
+ if (!this.isSelectedAgentAvailable()) {
+ this.notificationService.warning("Agent is busy. Please wait for the
current run to finish.");
+ return;
+ }
+
const agentId = this.selectedAgentId;
const operatorName = this.operatorDisplayName || this.getOperatorName() ||
"this operator";
const contextMessage = `Regarding operator "${operatorName}" (ID:
${this.operatorId}): ${this.feedbackMessage.trim()}`;
@@ -181,8 +189,13 @@ export class AgentInteractionComponent implements OnInit,
OnChanges {
}
}
+ public isSelectedAgentAvailable(): boolean {
+ if (!this.selectedAgentId) return false;
+ return this.agentService.getAgentStateSnapshot(this.selectedAgentId) ===
AgentState.AVAILABLE;
+ }
+
public canSend(): boolean {
- return !!this.selectedAgentId && !!this.feedbackMessage.trim();
+ return !!this.selectedAgentId && !!this.feedbackMessage.trim() &&
this.isSelectedAgentAvailable();
}
public isVisualization(): boolean {
diff --git a/frontend/src/app/workspace/service/agent/agent.service.spec.ts
b/frontend/src/app/workspace/service/agent/agent.service.spec.ts
index c11bcd97cc..e9aa92ec14 100644
--- a/frontend/src/app/workspace/service/agent/agent.service.spec.ts
+++ b/frontend/src/app/workspace/service/agent/agent.service.spec.ts
@@ -1266,6 +1266,15 @@ describe("AgentService", () => {
expect(unknown).toBe(AgentState.UNAVAILABLE);
});
+ it("getAgentStateSnapshot returns the tracked value synchronously, or
UNAVAILABLE without creating tracking", () => {
+ service.getAgentStateObservable("agent-1").subscribe();
+ (service as
any).agentStateTracking.get("agent-1").stateSubject.next(AgentState.GENERATING);
+
expect(service.getAgentStateSnapshot("agent-1")).toBe(AgentState.GENERATING);
+
+
expect(service.getAgentStateSnapshot("ghost")).toBe(AgentState.UNAVAILABLE);
+ expect((service as any).agentStateTracking.has("ghost")).toBe(false);
+ });
+
it("isAgentConnected is false for an unavailable/unknown agent and true
otherwise", () => {
let unknown: boolean | undefined;
service.isAgentConnected("ghost").subscribe(v => (unknown = v));
diff --git a/frontend/src/app/workspace/service/agent/agent.service.ts
b/frontend/src/app/workspace/service/agent/agent.service.ts
index 4692d7beb7..e452895af8 100644
--- a/frontend/src/app/workspace/service/agent/agent.service.ts
+++ b/frontend/src/app/workspace/service/agent/agent.service.ts
@@ -959,13 +959,14 @@ export class AgentService {
* Get the current state of an agent.
*/
public getAgentState(agentId: string): Observable<AgentState> {
- return defer(() => {
- const tracking = this.agentStateTracking.get(agentId);
- if (tracking) {
- return of(tracking.stateSubject.getValue());
- }
- return of(AgentState.UNAVAILABLE);
- });
+ return defer(() => of(this.getAgentStateSnapshot(agentId)));
+ }
+
+ /**
+ * Get the latest known state of an agent synchronously, without creating
tracking.
+ */
+ public getAgentStateSnapshot(agentId: string): AgentState {
+ return this.agentStateTracking.get(agentId)?.stateSubject.getValue() ??
AgentState.UNAVAILABLE;
}
/**