Events

Use onEvent to react when a method returns or a run stops, fails or loses its connection.

The scope's onEvent callback receives a TandemEvent, the scope's context and the session. TandemEvent is sealed, so a switch can cover every event:

void showOrderMessages(
  BuildContext context,
  TandemEvent event,
  TandemSession session,
) {
  final message = switch (event) {
    AgentCall(tool: OrderCubitTool.placeOrder, :final result) =>
      'Placed order $result.',
    RunFailed() || ConnectionLost() => 'The agent did not answer. Try again.',
    AgentCall() || RunStopped() => null,
  };
  if (message case final text?) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
  }
}

AgentCall is emitted after a listed method returns. It includes the tool, arguments, result and caller. The tool is a value of the enum tandem_generator writes next to the mixin, such as OrderCubitTool.placeOrder, so a renamed method breaks the match at compile time. The caller is Caller.inAppAgent, Caller.codingAgent, or Caller.view for a press or field in a drawn view. A refused call or a method that throws emits no AgentCall.

RunStopped is emitted when the user stops a run or the backend cancels it. The chat adds a stopped notice or marks the last agent message stopped.

RunFailed and ConnectionLost also add a ChatNotice to session.items. Errors go to FlutterError.reportError; their internal messages are not shown in the chat. RunFailed.code is an optional RunErrorCode, which you can match with a pattern such as RunFailed(code: .unsupportedOutcome).

Approval requests go through approvals:, not onEvent.

Start over

When the conversation history exceeds the model's context window, call session.startOver() to clear Tandem's local history and agent state. The next message starts a new AG-UI thread if Tandem supplied the ID. With an app-supplied ID, the backend may keep its history. A separate conversation needs a new TandemThread with a new backend ID. Existing chat items remain, and the chat adds a startedOver notice. Waiting approval requests are cancelled.

startOver() does nothing while a run or an approved method is active. See Keep the conversation for thread ownership.