Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(agents): take off-boarded agents out of every conversation (#357)

Streliziaaf4054b24b48
diff --git a/docs/api-contract.json b/docs/api-contract.json
index 0e87a2d..e5f1368 100644
--- a/docs/api-contract.json
+++ b/docs/api-contract.json
@@ -22,6 +22,7 @@
"participants.avatar",
"computers.status",
"participants.added",
+ "participants.roster_changed",
"message.reactions",
"group.pulled",
"conversation.updated",
diff --git a/server/src/__integration__/agent-offboard-conversations.test.ts b/server/src/__integration__/agent-offboard-conversations.test.ts
new file mode 100644
index 0000000..2d1228f
--- /dev/null
+++ b/server/src/__integration__/agent-offboard-conversations.test.ts
@@ -0,0 +1,196 @@
+/**
+ * Off-boarding an agent must also take it out of every conversation.
+ *
+ * Membership lives in its own normalized table, not on the participant row, so
+ * a participant update alone leaves every group roster untouched.
+ */
+import { test, before, beforeEach, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer, type Server } from 'node:http'
+import {
+ buildApiTestApp, ensureSchemaOnce, resetAllTables, seedUserMembership, teardownAll,
+} from './_helpers.js'
+import { pool } from '../db/pool.js'
+
+const OWNER = 'human-offboard-owner'
+const AGENT = 'agent-offboard-target'
+const PEER = 'agent-offboard-peer'
+const COMPANY = 'c-offboard-conv'
+
+let server: Server
+let baseUrl = ''
+
+before(async () => {
+ await ensureSchemaOnce()
+ const app = await buildApiTestApp(OWNER)
+ await new Promise<void>((resolve) => {
+ server = createServer(app).listen(0, () => {
+ const addr = server.address()
+ if (addr && typeof addr === 'object') baseUrl = `http://127.0.0.1:${addr.port}`
+ resolve()
+ })
+ })
+})
+
+beforeEach(async () => {
+ await resetAllTables()
+})
+
+after(async () => {
+ await teardownAll(server)
+})
+
+async function seed(): Promise<{ groupId: string; dmId: string }> {
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, 'Offboard Co', 'offboard-co', $2)`,
+ [COMPANY, OWNER],
+ )
+ await seedUserMembership(OWNER, COMPANY, { displayName: 'Owner' })
+ for (const [id, name] of [[AGENT, 'Target'], [PEER, 'Peer']] as const) {
+ await pool.query(
+ `INSERT INTO participants (id, company_id, kind, name, role, initial, avatar_bg, status)
+ VALUES ($1, $2, 'agent', $3, 'tester', $4, '#abcdef', 'avail')`,
+ [id, COMPANY, name, name.slice(0, 1)],
+ )
+ }
+ const groupId = 'conv-offboard-group'
+ const dmId = 'conv-offboard-dm'
+ await pool.query(
+ `INSERT INTO conversations (id, kind, title, members, company_id)
+ VALUES ($1, 'group', 'Squad', $2::jsonb, $3)`,
+ [groupId, JSON.stringify([OWNER, AGENT, PEER]), COMPANY],
+ )
+ await pool.query(
+ `INSERT INTO conversations (id, kind, title, members, company_id)
+ VALUES ($1, 'direct', 'Target', $2::jsonb, $3)`,
+ [dmId, JSON.stringify([OWNER, AGENT]), COMPANY],
+ )
+ return { groupId, dmId }
+}
+
+async function membersOf(conversationId: string): Promise<string[]> {
+ const { rows } = await pool.query<{ participant_id: string }>(
+ `SELECT participant_id FROM conversation_members WHERE conversation_id = $1 ORDER BY ordinal`,
+ [conversationId],
+ )
+ return rows.map((row) => row.participant_id)
+}
+
+async function offboard(): Promise<Response> {
+ return await fetch(`${baseUrl}/api/agents/${AGENT}`, {
+ method: 'DELETE',
+ headers: { 'x-company-id': COMPANY },
+ })
+}
+
+test('[integration] off-board removes the agent from every group conversation', async () => {
+ const { groupId } = await seed()
+ assert.deepEqual(await membersOf(groupId), [OWNER, AGENT, PEER])
+
+ const res = await offboard()
+ assert.equal(res.status, 200, await res.text())
+
+ assert.deepEqual(await membersOf(groupId), [OWNER, PEER], 'off-boarded agent stayed in the group roster')
+})
+
+test('[integration] off-board keeps the direct-chat row so a rehire resumes it', async () => {
+ const { dmId } = await seed()
+
+ const res = await offboard()
+ assert.equal(res.status, 200, await res.text())
+
+ // The human workspace-removal path deliberately preserves direct memberships
+ // (server/src/api/router.ts, `AND c.kind <> 'direct'`) so a returning member
+ // lands back in the same thread. Off-board follows the same rule.
+ assert.deepEqual(await membersOf(dmId), [OWNER, AGENT], 'direct membership must survive for a rehire')
+})
+
+test('[integration] off-board leaves the participant row and its history intact', async () => {
+ const { groupId } = await seed()
+
+ const res = await offboard()
+ assert.equal(res.status, 200, await res.text())
+
+ const { rows } = await pool.query<{ departed_at: Date | null; status: string }>(
+ `SELECT departed_at, status FROM participants WHERE id = $1 AND company_id = $2`,
+ [AGENT, COMPANY],
+ )
+ assert.ok(rows[0]?.departed_at, 'participant row must survive as a departed row')
+ assert.equal(rows[0]?.status, 'resting')
+
+ const { rows: convo } = await pool.query<{ members: string[] }>(
+ `SELECT members FROM conversations WHERE id = $1`,
+ [groupId],
+ )
+ assert.deepEqual(convo[0]?.members, [OWNER, PEER], 'jsonb projection drifted from conversation_members')
+})
+
+test('[integration] off-boarded agent no longer appears in group member counts', async () => {
+ const { groupId } = await seed()
+
+ const res = await offboard()
+ assert.equal(res.status, 200, await res.text())
+
+ const listRes = await fetch(`${baseUrl}/api/conversations`, { headers: { 'x-company-id': COMPANY } })
+ assert.equal(listRes.status, 200)
+ const rows = await listRes.json() as Array<{ id: string; members: string[] }>
+ const group = rows.find((row) => row.id === groupId)
+ assert.deepEqual(group?.members, [OWNER, PEER], 'sidebar still counts the off-boarded agent')
+})
+
+test('[integration] the direct chat leaves the sidebar while the agent is off-boarded', async () => {
+ const { dmId } = await seed()
+
+ const res = await offboard()
+ assert.equal(res.status, 200, await res.text())
+
+ const listRes = await fetch(`${baseUrl}/api/conversations`, { headers: { 'x-company-id': COMPANY } })
+ assert.equal(listRes.status, 200)
+ const rows = await listRes.json() as Array<{ id: string }>
+ assert.equal(
+ rows.some((row) => row.id === dmId), false,
+ 'a DM whose other member was off-boarded must not sit in the sidebar as a dead row',
+ )
+})
+
+test('[integration] rehiring brings the same direct chat back', async () => {
+ const { dmId } = await seed()
+ await offboard()
+
+ const res = await fetch(`${baseUrl}/api/agents/${AGENT}/rehire`, {
+ method: 'POST',
+ headers: { 'x-company-id': COMPANY },
+ })
+ assert.equal(res.status, 200, await res.text())
+
+ const listRes = await fetch(`${baseUrl}/api/conversations`, { headers: { 'x-company-id': COMPANY } })
+ const rows = await listRes.json() as Array<{ id: string }>
+ assert.equal(
+ rows.some((row) => row.id === dmId), true,
+ 'the preserved direct membership should put the same thread back in the sidebar',
+ )
+})
+
+test('[integration] off-board and rehire both announce the roster change', async () => {
+ await seed()
+
+ await offboard()
+ const { rows: departed } = await pool.query<{ payload: { type: string; kind: string } }>(
+ `SELECT payload FROM realtime_outbox WHERE payload->>'type' = 'participants.roster_changed'`,
+ )
+ assert.deepEqual(departed.map((row) => row.payload.kind), ['departed'],
+ 'nothing told connected clients the roster changed')
+
+ const res = await fetch(`${baseUrl}/api/agents/${AGENT}/rehire`, {
+ method: 'POST',
+ headers: { 'x-company-id': COMPANY },
+ })
+ assert.equal(res.status, 200, await res.text())
+
+ const { rows: after } = await pool.query<{ payload: { kind: string } }>(
+ `SELECT payload FROM realtime_outbox
+ WHERE payload->>'type' = 'participants.roster_changed' ORDER BY created_at`,
+ )
+ assert.deepEqual(after.map((row) => row.payload.kind), ['departed', 'rehired'],
+ 'a rehire that does not announce itself leaves the sidebar hiding the restored thread')
+})
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 6d21f11..f6a34f0 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -3180,8 +3180,6 @@ api.put('/agents/:id', async (req, res) => {
* /agents/:id/rehire to bring them back.
*/
api.delete('/agents/:id', async (req, res) => {
- // Off-boarding an agent silences it for the whole workspace and removes
- // it from every conversation's wake roster — destructive, owner/admin only.
const { companyId: tenant } = await requireCompanyRole(req)
const id = req.params.id
const { rows: existing } = await pool.query<{ kind: string; departed_at: string | null }>(
@@ -3190,14 +3188,69 @@ api.delete('/agents/:id', async (req, res) => {
if (!existing[0]) { res.status(404).json({ error: 'not found' }); return }
if (existing[0].kind !== 'agent') { res.status(400).json({ error: 'cannot off-board non-agent participant' }); return }
if (existing[0].departed_at) { res.status(409).json({ error: 'already off-boarded' }); return }
- await pool.query(
- `UPDATE participants
- SET departed_at = NOW(),
- status = 'resting',
- status_updated_at = NOW()
- WHERE id = $1 AND company_id = $2`,
- [id, tenant],
- )
+
+ // Membership rows are the single source of truth for a room's roster, so a
+ // participant update alone leaves the agent seated in every group.
+ await withOutboxTransaction(async (client) => {
+ // Same lock order every membership mutation uses: the participant row
+ // first, then the conversations. A concurrent invite/leave either lands
+ // before this transaction (and is undone by the bulk delete below) or
+ // after it (and is rejected by the departed_at predicate), never halfway.
+ const locked = await client.query(
+ `SELECT id FROM participants
+ WHERE id = $1 AND company_id = $2 AND kind = 'agent' AND departed_at IS NULL
+ FOR UPDATE`,
+ [id, tenant],
+ )
+ if (!locked.rowCount) throw new HttpError(409, 'agent is no longer active')
+
+ // Direct chats keep their membership so a rehire resumes the same thread,
+ // the rule the human workspace-removal path follows. GET /conversations
+ // hides them from the other side while the agent is departed.
+ const { rows: conversations } = await client.query<{ id: string }>(
+ `SELECT c.id
+ FROM conversations c
+ JOIN conversation_members cm
+ ON cm.conversation_id = c.id AND cm.company_id = c.company_id
+ WHERE c.company_id = $1
+ AND cm.participant_id = $2
+ AND c.kind <> 'direct'
+ ORDER BY c.id
+ FOR UPDATE OF c`,
+ [tenant, id],
+ )
+ const conversationIds = conversations.map((row) => row.id)
+ if (conversationIds.length > 0) {
+ await client.query(
+ `DELETE FROM conversation_members
+ WHERE company_id = $1 AND participant_id = $2
+ AND conversation_id = ANY($3::text[])`,
+ [tenant, id, conversationIds],
+ )
+ await client.query(
+ `SELECT refresh_conversation_members_projection(cid)
+ FROM unnest($1::text[]) affected(cid)`,
+ [conversationIds],
+ )
+ }
+
+ await client.query(
+ `UPDATE participants
+ SET departed_at = NOW(),
+ status = 'resting',
+ status_updated_at = NOW()
+ WHERE id = $1 AND company_id = $2`,
+ [id, tenant],
+ )
+
+ await enqueueBroadcast(client, CH_STATUS, {
+ type: 'participants.roster_changed',
+ kind: 'departed',
+ companyId: tenant,
+ participantId: id,
+ })
+ })
+
const { invalidatePersonaCache } = await import('../agents/personas.js')
invalidatePersonaCache(id)
// Reclaim the agent's chrome-profile PVC. Off-board is the agent's
@@ -3372,14 +3425,23 @@ api.post('/agents/:id/rehire', async (req, res) => {
if (existing[0].kind !== 'agent') { res.status(400).json({ error: 'cannot rehire non-agent participant' }); return }
if (!existing[0].departed_at) { res.status(409).json({ error: 'agent is not off-boarded' }); return }
await assertCompanyAgentLimit(tenant)
- await pool.query(
- `UPDATE participants
- SET departed_at = NULL,
- status = 'avail',
- status_updated_at = NOW()
- WHERE id = $1 AND company_id = $2`,
- [id, tenant],
- )
+ await withOutboxTransaction(async (client) => {
+ await client.query(
+ `UPDATE participants
+ SET departed_at = NULL,
+ status = 'avail',
+ status_updated_at = NOW()
+ WHERE id = $1 AND company_id = $2`,
+ [id, tenant],
+ )
+ // Off-board hid the shared direct chats from the other side rather than
+ // deleting them, so the roster refetch this triggers puts those threads
+ // back. Without the frame the sidebar would keep hiding them until the
+ // next manual reload.
+ await enqueueBroadcast(client, CH_STATUS, {
+ type: 'participants.roster_changed', kind: 'rehired', companyId: tenant, participantId: id,
+ })
+ })
const { invalidatePersonaCache } = await import('../agents/personas.js')
invalidatePersonaCache(id)
res.json({ ok: true })
@@ -3486,6 +3548,24 @@ api.get('/conversations', async (req, res) => {
AND cm.company_id = c.company_id
AND cm.participant_id = $1
)
+ -- An off-boarded agent keeps its direct-chat membership so a rehire
+ -- finds the same thread again (same rule the human workspace-removal
+ -- path follows). The chat itself must still leave the sidebar for the
+ -- person who stayed: a two-person room with one departed member is a
+ -- dead row that only draws a grey portrait.
+ AND (
+ c.kind <> 'direct'
+ OR NOT EXISTS (
+ SELECT 1 FROM conversation_members peer
+ JOIN participants peer_participant
+ ON peer_participant.id = peer.participant_id
+ AND peer_participant.company_id = peer.company_id
+ WHERE peer.conversation_id = c.id
+ AND peer.company_id = c.company_id
+ AND peer.participant_id <> $1
+ AND peer_participant.departed_at IS NOT NULL
+ )
+ )
ORDER BY c.pinned DESC, c.updated_at DESC
LIMIT ${CONVERSATION_LIST_LIMIT}`,
[me, tenant],
diff --git a/server/src/redis.ts b/server/src/redis.ts
index 31971bc..9bda8e6 100644
--- a/server/src/redis.ts
+++ b/server/src/redis.ts
@@ -205,6 +205,17 @@ export interface ComputerStatusEvent extends TenantTagged {
status: 'online' | 'offline' | 'busy'
}
+/** Fired when an agent is off-boarded or rehired. Both change which rosters
+ * the agent belongs to, which is not a one-row patch on the client: neither
+ * the group memberships nor the sidebar's direct-chat visibility can be
+ * derived from the participant row. Clients refetch the roster and the
+ * conversation list instead. */
+export interface ParticipantRosterChangedEvent extends TenantTagged {
+ type: 'participants.roster_changed'
+ kind: 'departed' | 'rehired'
+ participantId: string
+}
+
/** Fired when an agent's avatar gets (re-)generated. Clients patch their
* local participants store so the new portrait appears without waiting
* for the periodic refresh tick. */
@@ -426,7 +437,7 @@ export interface PollUpdatedEvent extends TenantTagged {
}
export type BroadcastEvent = MessageNewEvent | MessageDeltaEvent | TypingEvent
- | StatusEvent | AvatarEvent | ParticipantAddedEvent | ReactionsEvent
+ | StatusEvent | AvatarEvent | ParticipantAddedEvent | ParticipantRosterChangedEvent | ReactionsEvent
| GroupPulledEvent | ConversationUpdatedEvent | ConveneEvent
| BoardEvent | DocIndexEvent | DocUpdateEvent | DocAwarenessEvent | DocMentionEvent | CalendarReminderEvent
| CalendarEventChangedEvent
diff --git a/src/api/client.ts b/src/api/client.ts
index 3e6ac2e..8640db8 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -1560,6 +1560,7 @@ export type WsEvent =
initial: string; avatarBg: string; avatarUrl: string | null;
status: Status; statusUpdatedAt: string | null;
} }
+ | { type: 'participants.roster_changed'; companyId: string; kind: 'departed' | 'rehired'; participantId: string }
| { type: 'message.reactions'; conversationId: string; messageId: string; reactions: Array<{ emoji: string; count: number; mine?: boolean; users?: string[] }> }
| { type: 'group.pulled'; conversationId: string; pulledById: string }
| { type: 'conversation.updated'; conversationId: string; patch: { topic?: string | null; title?: string } }
diff --git a/src/stores/conversations.ts b/src/stores/conversations.ts
index 4b87807..cb24610 100644
--- a/src/stores/conversations.ts
+++ b/src/stores/conversations.ts
@@ -173,6 +173,22 @@ function fromApi(c: ApiConversation): Conversation {
}
}
+/**
+ * Drop a selection whose row just left the sidebar.
+ *
+ * A conversation can disappear without the viewer acting: the other side of a
+ * direct chat was off-boarded, or the viewer was removed by someone else.
+ * Without this, the chat pane keeps rendering a thread for a room the user can
+ * no longer see, and ChatPane's own `if (!c) return null` only blanks pieces
+ * of it. Matches the 404 path in stores/messages.
+ */
+function dropSelectionIfGone(conversations: Conversation[]): void {
+ const active = useApp.getState().selectedConversationId
+ if (!active) return
+ if (conversations.some((c) => c.id === active)) return
+ useApp.getState().selectConversation(null)
+}
+
function refreshActiveMessagesIfSidebarMoved(conversations: Conversation[]): void {
const active = useApp.getState().selectedConversationId
if (!active) return
@@ -214,6 +230,7 @@ export const useConversations = create<ConversationsState>((set, get) => ({
await commitIfContextCurrent(() => api.getConversations(), (list) => {
const conversations = list.map(fromApi)
set({ list: conversations, loaded: true })
+ dropSelectionIfGone(conversations)
refreshActiveMessagesIfSidebarMoved(conversations)
})
} catch (err) {
@@ -225,6 +242,7 @@ export const useConversations = create<ConversationsState>((set, get) => ({
await commitIfContextCurrent(() => api.getConversations(), (list) => {
const conversations = list.map(fromApi)
set({ list: conversations })
+ dropSelectionIfGone(conversations)
refreshActiveMessagesIfSidebarMoved(conversations)
})
} catch (err) {
@@ -329,6 +347,12 @@ export function bootConversations() {
return next
}),
}))
+ return
+ }
+ if (e.type === 'participants.roster_changed') {
+ // Off-board and rehire change rosters and direct-chat visibility, not
+ // any single row, so refetch.
+ void useConversations.getState().reload()
}
})
}
diff --git a/src/stores/participants.ts b/src/stores/participants.ts
index daf2663..7365f51 100644
--- a/src/stores/participants.ts
+++ b/src/stores/participants.ts
@@ -197,6 +197,13 @@ export function bootParticipants() {
},
},
}))
+ } else if (e.type === 'participants.roster_changed') {
+ // Off-board and rehire only flip departedAt on the existing row, so
+ // refetch for every list that filters on it (Agents view, assignee and
+ // mention pickers). The conversation list is reconciled separately in
+ // stores/conversations.
+ if (!isForActiveWorkspace(e.companyId, useAuth.getState().activeCompanyId)) return
+ void useParticipants.getState().refresh()
}
})
// Quiet background refresh — picks up regenerated avatars and any