# How to Enable Cancellation and Steering for OpenMAIC Agent Sessions

> Learn to enable cancellation and steering for OpenMAIC agent sessions. Call cancelWorkbenchSession or send steer messages for mid-run instructions.

- Repository: [MAIC/OpenMAIC](https://github.com/THU-MAIC/OpenMAIC)
- Tags: how-to-guide
- Published: 2026-09-08

---

**You can enable cancellation by calling `cancelWorkbenchSession(sessionId)` from [`lib/workbench/session-store.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/workbench/session-store.ts), and enable steering by sending user messages with `delivery: 'steer'` to inject mid-run instructions into active agent sessions.**

OpenMAIC provides built-in runtime controls for managing agent session lifecycles through two primary mechanisms: **cancellation** (aborting in-flight operations) and **steering** (injecting guidance into running sessions). These capabilities are implemented directly in the THU-MAIC/OpenMAIC backend runtime and exposed through the client-side workbench API.

## Canceling OpenMAIC Agent Sessions

### The Cancellation API Implementation

In [`lib/workbench/session-store.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/workbench/session-store.ts), the `cancelWorkbenchSession(sessionId)` function handles session termination. This utility sends a request to the server endpoint to abort the current run, marking the session as *cancelled* and stopping any in-flight tool calls. The UI components (such as the "Cancel" button) invoke this helper to terminate active sessions immediately.

When invoked, the function contacts the API endpoint implemented in the server layer, which propagates the cancellation signal to the runtime. All pending tool calls receive abort signals, and the session state updates to reflect the cancelled status.

### Practical Cancellation Implementation

To implement cancellation in your client code:

```typescript
import { cancelWorkbenchSession } from '@/lib/workbench/session-store';

async function onCancelClick(sessionId: string) {
  try {
    await cancelWorkbenchSession(sessionId);
    console.log('Session cancelled successfully');
  } catch (error) {
    console.error('Failed to cancel session:', error);
  }
}

```

The `cancelWorkbenchSession` function manages the network request and state synchronization, ensuring the UI immediately reflects the cancelled state while the backend terminates any active model inference or tool execution.

## Steering Live OpenMAIC Agent Sessions

### The Steering Mechanism

Steering allows you to inject messages into actively running sessions. When a live session receives a user message with `delivery: 'steer'`, the runtime queues it as a steer operation. The runner in [`lib/server/agent-runtime/runner.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/runner.ts) detects this delivery type and injects the message into the ongoing model request, guaranteeing the agent responds after the current step finishes.

If the session is idle when the steering message arrives, the system treats it as a normal queued message (`delivery: 'queued'`). This dual-mode behavior ensures steering works transparently regardless of session state.

### Terminal Barrier Protection

The system prevents steering once a session reaches terminal status. In [`lib/agent/runtime/build-agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/agent/runtime/build-agent.ts), the `agent.steer` method is wrapped with a terminal barrier guard that blocks steering operations when the session status is `succeeded`, `failed`, or `cancelled`. This safety mechanism prevents state corruption and ensures steering only occurs during active runs.

### Implementing Session Steering

To steer an active session, construct a message payload with the steering delivery type:

```typescript
async function steerSession(sessionId: string, instruction: string) {
  const payload = {
    text: instruction,
    delivery: 'steer',  // Forces mid-run injection
  };

  const response = await fetch(`/api/agent/sessions/${sessionId}/messages`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(`Steering failed: ${response.statusText}`);
  }
  
  console.log('Steer message queued for injection');
}

```

Behind the scenes, the runner checks the *terminalBarrierActive* flag and queues the message for injection after the current step completes. The wrapped `agent.steer` method respects this barrier, enabling safe mid-run course correction without disrupting the agent's execution flow.

## Key Source Files and Architecture

Understanding the file structure helps when customizing or debugging these features:

- **[`lib/workbench/session-store.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/workbench/session-store.ts)** – Implements `cancelWorkbenchSession` and processes incoming user messages, distinguishing between `delivery: 'steer'` and `delivery: 'queued'` modes.
- **[`lib/server/agent-runtime/runner.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/runner.ts)** – Core runtime that injects steered messages into ongoing runs and processes cancellation signals from the client.
- **[`lib/agent/runtime/build-agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/agent/runtime/build-agent.ts)** – Wraps `agent.steer` with terminal barrier guards to prevent steering completed or cancelled sessions.
- **[`lib/i18n/workbench.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/i18n/workbench.ts)** – Provides UI localization strings for steering status, including the "steerQueued" message indicating the agent will respond after finishing the current step.
- **[`tests/workbench/session-cancel-client.test.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/tests/workbench/session-cancel-client.test.ts)** – Test suite demonstrating client-side cancellation handling and state transitions.
- **[`tests/lib/agent/runtime/build-agent-runtime.test.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/tests/lib/agent/runtime/build-agent-runtime.test.ts)** – Test suite verifying steering behavior and terminal barrier enforcement.

## Summary

- **Cancellation** requires importing `cancelWorkbenchSession` from [`lib/workbench/session-store.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/workbench/session-store.ts) and passing the target session ID to abort in-flight operations immediately.
- **Steering** requires sending POST requests to the messages endpoint with `delivery: 'steer'` in the payload to inject instructions into running sessions.
- The **terminal barrier** in [`build-agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/build-agent.ts) automatically prevents steering attempts against completed, failed, or cancelled sessions.
- Both features are fully integrated into the OpenMAIC workbench API and require no additional server configuration to enable.

## Frequently Asked Questions

### What is the difference between steering and regular messaging in OpenMAIC?

Regular messages with `delivery: 'queued'` wait for the current run to complete before the agent processes them. Steering messages with `delivery: 'steer'` are injected directly into the ongoing model request, allowing the agent to respond to new instructions after completing its current step. According to the OpenMAIC source code, the runner in [`lib/server/agent-runtime/runner.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/runner.ts) handles this injection automatically based on the delivery type.

### Can I cancel a session that has already completed?

No, cancellation only works on actively running sessions. The `cancelWorkbenchSession` function sends a signal to the runtime, but if the session has already reached a terminal state (`succeeded`, `failed`, or `cancelled`), the operation has no effect. The terminal barrier protection in [`lib/agent/runtime/build-agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/agent/runtime/build-agent.ts) enforces similar restrictions on steering attempts against completed sessions.

### How does the terminal barrier protect session integrity?

The terminal barrier is a runtime guard implemented in [`lib/agent/runtime/build-agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/agent/runtime/build-agent.ts) that wraps the `agent.steer` method. It checks the session status before allowing steering operations and blocks any attempts to steer sessions that have finished. This prevents race conditions where steering messages might arrive after a session completes, ensuring state consistency between the client and server.

### What happens to steered messages if the network connection fails?

If the network request to `/api/agent/sessions/{id}/messages` fails, the steering message never reaches the runtime and the agent continues its current operation uninterrupted. The client should implement retry logic or error handling around the fetch call, as the OpenMAIC workbench API returns standard HTTP error codes when message delivery fails.