Blog · · 10 min read
Build a multi-user AI agent session without corrupting the run

A multi-user AI agent can fail even when every participant belongs in the workspace. Two people send conflicting instructions. A private note leaks into shared context. Someone approves an action after another person changed its parameters. An old response arrives after the team has moved on. The agent then acts on a conversation that no longer has one clear meaning.
Fix this below the chat interface. Give each participant a product identity, give each command a run revision, separate private and shared context, and serialize state-changing decisions through one control plane. The result is a collaborative agent session that several people can steer without turning concurrent messages into ambiguous authority.
Why a multi-user AI agent needs a control plane
Most chat implementations assume one user, one conversation, and one stream of intent. A team workspace breaks all three assumptions.
The session has several principals. Each principal may have different rights to observe, contribute, interrupt, approve, or hand work to somebody else. Their messages can arrive while the model is reasoning, while a tool is running, or while an approval is pending. Some context belongs to the team, some belongs to one participant, and some should never enter model context at all.
Tenant isolation prevents one customer from reading another customer's data, but it does not settle access inside a shared run. Several authorized people in the same tenant still create four questions for every event:
- Who sent it?
- Which revision of the run did they see?
- What are they allowed to do now?
- How does their event affect work already in progress?
Microsoft's guidance for multiplexing several users through a hosted agent session makes the identity requirement explicit. The middle tier identifies the user on every request, isolates each user's response chain, and authorizes visible history and caller-owned resources. A collaborative session needs the same discipline, plus rules for the content intentionally shared among participants.
Direct implementation reports show what happens without those rules. Pikiloom issue #3 describes a shared bot where histories mixed and one user's session changes affected everyone. Kordi issue #164 describes stale parallel responses, duplicated work, unclear ordering, and no defined behavior for queueing, cancelling, interrupting, or superseding a running response. These are author reports, not incidence measurements, but they expose reproducible failure classes.
Define the shared-run data model
Do not make a channel ID or conversation ID the sole security and concurrency boundary. Model the run, participants, messages, commands, and actions separately.
type ParticipantRole = "observer" | "contributor" | "approver" | "owner";
type CommandKind = "append" | "interrupt" | "supersede" | "approve" | "reject";
type SharedRunCommand = {
commandId: string;
tenantId: string;
runId: string;
principalId: string;
roleAtSubmission: ParticipantRole;
expectedRunRevision: number;
kind: CommandKind;
messageId?: string;
actionVersion?: number;
submittedAt: string;
idempotencyKey: string;
};
type SharedRun = {
runId: string;
tenantId: string;
revision: number;
status: "idle" | "running" | "waiting" | "stopping" | "complete" | "failed";
activeStepId?: string;
pendingActionId?: string;
pendingActionVersion?: number;
};
principalId records who acted. expectedRunRevision records what state that person saw. actionVersion prevents an approval for one proposal from authorizing a later edited proposal. idempotencyKey prevents a client reconnect or repeated button click from applying the same command twice.
Keep messages as immutable records. Corrections should add events rather than rewrite history in place. A message can be marked retracted for future context assembly, but the audit record should retain who retracted it, when, and which later revision excluded it.
Use one append-only event sequence as the source for every participant's timeline. Streams may deliver events late or reconnect from a cursor, but the UI sorts and reconciles them by the server-assigned sequence. A model token stream is presentation data. It is not the authoritative state transition.
Separate private, participant, and shared context
A shared chat window does not imply that every stored fact is shared. Give context an explicit visibility scope:
private: visible only to the originating principal;participant: visible to a named set of principals;shared: visible to current run participants with the required role;system: visible only to the product runtime;publishable: approved for wider workspace reuse.
The MindStudio team-memory guidance separates private, team, and public memory and recommends enforcing access at the database layer. Permit's shared-memory analysis reaches the same practical conclusion: scope and authorization must be evaluated at runtime, including revocation, rather than copied into a prompt and assumed to remain true.
Apply that rule twice. First, authorize retrieval before a record enters context. Second, recheck authority before the agent uses retrieved content to perform an action. A role can change between planning and dispatch.
PostgreSQL row security policies provide a database enforcement point for participant-specific and shared rows. With row security enabled, access is controlled by policies and defaults to deny when no applicable policy exists. Application checks still matter, but database enforcement keeps a missed filter from becoming a cross-participant disclosure.
Never place a participant's private draft into shared model context and then ask the model not to reveal it. The disclosure already happened at context assembly. Promote private material to shared context through an explicit product action that records the source principal, target scope, and current revision.
Give each participant scoped session rights
Workspace membership is too coarse. Define rights against the shared run:
observe: read authorized events and current state;contribute: append non-command context or a queued request;interrupt: request that interruptible reasoning stop;supersede: replace queued intent before side-effect dispatch;approve: authorize an exact pending action version;reject: close an exact pending action without execution;handoff: transfer run ownership or response duty;manage_participants: add, remove, or change roles.
Check the current relationship and context when each right is exercised. OpenFGA conditions document how authorization can depend on contextual facts in addition to relationships. For a shared run, relevant facts include tenant, run status, current revision, participant role, action risk, and approval deadline.
Do not trust roleAtSubmission as the authorization decision. It is audit evidence. The command handler reloads current membership and policy, evaluates the requested right, and records the policy version and decision. If a contributor was removed while a message sat in a queue, the later handler must reject it or send it to review instead of applying stale authority.
Read and action rights should differ. An observer may see that an action is pending but cannot approve it. A contributor may suggest new parameters but cannot interrupt a running tool. An approver may approve a financial action without gaining access to another participant's private notes.
Serialize commands against a run revision
Several users can type concurrently. The product needs a deterministic rule for commands that change run state.
Process state-changing commands through one logical run partition. That can be a transactional row update, a per-run queue, or an actor, but it must compare expectedRunRevision with the current revision before accepting a command.
Use these decision rules:
- Accept
appendduringidleand start a new step at the next revision. - Queue ordinary contributions during a non-interruptible tool call.
- Accept
interruptonly when the active step declares an interrupt boundary. - Accept
supersedeonly before a side-effect commit, then invalidate the old planned-action version. - Accept
approveorrejectonly for the current pending action ID and version. - Return
conflictwith the current snapshot when a command was based on a stale revision. - Return the prior result when an idempotency key was already consumed.
Do not silently merge conflicting instructions. "Refund the order" and "do not refund yet" are both valid sentences from authorized users, but they do not form a safe combined intent. Move the run to a typed conflict state and name the principals and revisions involved. The product owner can decide whether the owner, a quorum, or a designated approver resolves that conflict.
Define queue, interrupt, and supersede semantics
A new message received during a run needs one of three outcomes.
Queue means the current step continues and the message becomes input for a later step. Use it while an external operation cannot safely stop or when the message is additive.
Interrupt means request cancellation at a declared boundary. The runtime records the command, marks the step as stopping, propagates cancellation, and waits for an acknowledgement. A UI stop button must not claim success before the worker and relevant tool path acknowledge the stop.
Supersede means invalidate uncommitted intent and start from a newer run revision. It is valid before a tool dispatch or after a compensable draft operation. It is not permission to pretend a committed payment, message, or deletion never happened.
Choose the behavior from run state and tool metadata, not from message tone. A message that says "stop" is still an untrusted natural-language input until the product resolves it to an authorized command. Conversely, a dedicated interrupt control should not depend on the model recognizing the phrase.
When interruption is impossible, tell the participant what is still running, what can no longer be prevented, and which follow-up action will reconcile the result. That preserves control without fabricating reversibility.
Bind approvals to people, actions, and versions
Group chat reactions are not durable approvals. An approval record must identify the principal, pending action, action version, policy version, expiry, and decision.
Microsoft's AG-UI human-in-the-loop documentation shows the underlying interrupt and same-session resume flow. A production shared session must add product identity and eligibility checks. The participant clicking approve must currently hold the required right, and the request must still describe the exact action the system will dispatch.
If any material field changes, increment the action version and void prior approvals. Material fields include target account, amount, recipient, scope, effective time, and tool parameters. Do not carry an approval forward because the new proposal looks similar.
After approval, consume the grant transactionally with dispatch. A repeated client event should return the existing action receipt. It must not execute the tool again.
Render one authoritative participant view
Every client should derive visible state from the same ordered event log and current snapshot. It can optimistically show a submitted message, but it must reconcile the message with the server-assigned command result.
Display attribution on commands, corrections, interrupts, approvals, and handoffs. Show queued messages separately from accepted run input. Mark stale or rejected commands with the current revision that displaced them. For pending actions, show both the proposer and eligible approvers.
Do not equate the latest token with the latest truth. A stale model stream may finish after an interrupt or superseding revision. The client can retain that output as diagnostic history, but it must not present it as the current answer or attach its proposed actions to the new revision.
Test the collaboration contract
Build deterministic tests around races, not only single-user happy paths:
- Two contributors submit incompatible commands at the same revision.
- A participant loses access after retrieval but before tool dispatch.
- An approver accepts version 3 after another user creates version 4.
- A client repeats an interrupt after reconnecting.
- A non-interruptible tool commits while a supersede request arrives.
- A private note is promoted, retracted, and excluded from later context.
- A stale model stream finishes after the run advances.
- A removed participant attempts to read replayed events from an old cursor.
- Two clients apply the same idempotency key.
- A queued contribution becomes unauthorized before consumption.
For each test, verify database state, ordered events, policy decisions, action receipts, and every participant's rendered snapshot. Also run negative tests that search model inputs, traces, caches, and stream payloads for private context belonging to another principal.
Track conflict rate, stale-command rejection, interrupt acknowledgement time, unauthorized retrieval attempts, invalid approval versions, duplicated idempotency keys, and client reconciliation failures. These metrics diagnose the control plane. They are not substitutes for checking the final product state.
Ship the shared session in bounded stages
Start with shared observation. Several users can watch one run, but only one owner can contribute. Next allow queued contributions with attribution. Add interrupts only after workers acknowledge them reliably. Add supersession only for steps with a clear pre-commit boundary. Add multi-user approvals last, once action versioning and eligibility checks are enforced.
Release only when every event has a principal and sequence, commands name their expected revision, context records carry an enforced visibility scope, actions use current authorization, approvals bind to one action version, and all clients reconcile to the same final snapshot.
Before enabling a multi-user AI agent for customer work, implement the run-revision check and the three-way queue, interrupt, or supersede decision. Then execute the ten race tests against real persistence and safe tool fixtures.