Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Resume only a recorded Slack hand-off when Welcome opens
raullopez-sandbox9a6af4450fbf
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts b/console/apps/switch-console-desktop/src/main/core/chats/controller.tsindex 959c08360..6975f0a16 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts@@ -171,6 +171,7 @@ export const chatsController = createRPCController({/** Open the chat in this messaging app connection instead of in Switch. */bridgeId?: string | null;kind?: 'group';+ resumeOnly?: boolean;}): Promise<ChatSummary> => {const chat = await onServer(params.serverId, (server) => createChat(server, params));const agentIds = params.agentIds ?? [];diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.tsindex b6ce6fdce..7085f726f 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts@@ -110,6 +110,31 @@ describe('createChat', () => {});});+ it('sends resumeOnly only when true', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ for (const resumeOnly of [true, false]) {+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ chat: row('room-new', 'direct') }), { status: 200 })+ );+ await createChat(server, {+ agentIds: ['agent-1'],+ name: null,+ requestId: 'req-1',+ greeting: null,+ resumeOnly,+ });+ }+ expect(+ vi+ .mocked(gatewayFetch)+ .mock.calls.slice(-2)+ .map(([, , options]) => options?.body)+ ).toEqual([+ { requestId: 'req-1', agentId: 'agent-1', resumeOnly: true },+ { requestId: 'req-1', agentId: 'agent-1' },+ ]);+ });+it('sends bridgeId only when one is given', async () => {const server = { id: 'server-1' } as SwitchServer;vi.mocked(gatewayFetch).mockResolvedValueOnce(diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.tsindex 2c76fa287..c0127da49 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts@@ -132,10 +132,12 @@ export async function createChat(bridgeId?: string | null;/** `group` makes a group even of one agent and nobody else. */kind?: 'group';+ /** Only finish the create already made under `requestId`; none is a `NO_SUCH_OPERATION` 404. */+ resumeOnly?: boolean;}): Promise<ChatSummary> {const agentIds = input.agentIds ?? [];- const body: Record<string, string | string[]> = {+ const body: Record<string, string | string[] | boolean> = {requestId: input.requestId,};if (agentIds.length === 1) body.agentId = agentIds[0];@@ -145,6 +147,7 @@ export async function createChat(if (input.greeting !== null) body.greeting = input.greeting;if (input.bridgeId) body.bridgeId = input.bridgeId;if (input.kind) body.kind = input.kind;+ if (input.resumeOnly) body.resumeOnly = true;return (await json(server, '/chats', chatCreatedSchema, { method: 'POST', body })).chat;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsxindex e04b5705e..2ead86478 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx@@ -1,4 +1,4 @@-import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { useState } from 'react';import { chatsStore } from '@renderer/features/chats/stores/chats';@@ -13,8 +13,13 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';-import { buddySetupStep } from './buddy-setup-step';-import { BUDDY_CHAT_NAME, buddyHandoffRequestId, continueBuddyInSlack } from './open-buddy';+import { type BuddyResume, buddyResumeBridges, buddySetupStep } from './buddy-setup-step';+import {+ BUDDY_CHAT_NAME,+ buddyHandoffRequestId,+ continueBuddyInSlack,+ resumeBuddyInSlack,+} from './open-buddy';/*** The setup cards under the greeting in the buddy's Welcome chat: pick Slack,@@ -56,33 +61,35 @@ const Cards = observer(function Cards({queryKey: ['remote-bridges', workspaceId],queryFn: () => rpc.workspaces.listBridges(workspaceId),});- const chatsQuery = useQuery({- queryKey: ['buddy-handoff-chats', serverId],- queryFn: () => rpc.chats.list(serverId),- });const ids = useMyIdentities(workspaceId);+ const resumeBridges = buddyResumeBridges(bridgesQuery.data ?? null, ids.identities);+ const resumeQueries = useQueries({+ queries: resumeBridges.map((bridge) => ({+ queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)],+ queryFn: () => resumeBuddyInSlack(serverId, agentId, bridge.id),+ retry: false,+ staleTime: Infinity,+ })),+ });+ const resumes: Record<string, BuddyResume> = {};+ resumeBridges.forEach((bridge, index) => {+ const query = resumeQueries[index];+ if (query.isError) resumes[bridge.id] = 'failed';+ else if (query.isSuccess) resumes[bridge.id] = query.data;+ });const step = buddySetupStep({- agentId,bridges: bridgesQuery.data ?? null,identities: ids.identities,- chats: chatsQuery.data ?? null,- failed: bridgesQuery.isError || chatsQuery.isError || ids.error != null,+ resumes,+ failed: bridgesQuery.isError || ids.error != null,});const retry = () => {void bridgesQuery.refetch();- void chatsQuery.refetch();ids.refresh();+ for (const query of resumeQueries) if (query.isError) void query.refetch();};- const confirmBridgeId = step.kind === 'confirm' ? step.bridge.id : null;- const confirmQuery = useQuery({- queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, confirmBridgeId ?? '')],- queryFn: () => continueBuddyInSlack(serverId, { agentId }, confirmBridgeId as string),- enabled: confirmBridgeId !== null,- retry: false,- staleTime: Infinity,- });- const doneRoomId = confirmBridgeId ? (confirmQuery.data?.roomId ?? null) : null;+ const doneRoomId = step.kind === 'done' ? step.chat.roomId : null;const roomQuery = useQuery({queryKey: ['buddy-handoff-room', workspaceId, doneRoomId],queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId, roomId: doneRoomId as string }),@@ -100,9 +107,10 @@ const Cards = observer(function Cards({setCreating(true);setCreateError(null);try {- const chat = await continueBuddyInSlack(serverId, { agentId }, bridge.id);- queryClient.setQueryData(['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)], chat);- await queryClient.invalidateQueries({ queryKey: ['buddy-handoff-chats', serverId] });+ await continueBuddyInSlack(serverId, { agentId }, bridge.id);+ await queryClient.invalidateQueries({+ queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)],+ });} catch (cause) {setCreateError(failureText(cause, 'Switch did not answer.'));} finally {@@ -112,7 +120,7 @@ const Cards = observer(function Cards({const slackIcon = <BridgeIcon bridgeType="slack" className="size-4" />;const pastChoice =- picked || step.kind === 'link' || step.kind === 'create' || step.kind === 'confirm';+ picked || (step.kind !== 'loading' && step.kind !== 'unknown' && step.kind !== 'connect');return (<div className="mt-4 flex flex-col gap-2" data-testid="buddy-setup-cards">@@ -199,33 +207,13 @@ const Cards = observer(function Cards({</Alert>)}- {step.kind === 'confirm' && confirmQuery.isPending && (+ {step.kind === 'resuming' && (<Alert><Spinner size="sm" /><AlertTitle>Finishing setup…</AlertTitle></Alert>)}- {step.kind === 'confirm' && confirmQuery.isError && (- <Alert variant="destructive">- <AlertTitle>Couldn’t finish moving to Slack</AlertTitle>- <AlertDescription>- {failureText(confirmQuery.error, 'Switch did not answer.')}- </AlertDescription>- <AlertAction>- <Button- size="sm"- variant="outline"- disabled={confirmQuery.isFetching}- onClick={() => void confirmQuery.refetch()}- >- {confirmQuery.isFetching && <Spinner size="sm" />}- Try again- </Button>- </AlertAction>- </Alert>- )}-{doneRoomId && (<Alert>{slackIcon}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.tsindex 9b81e1017..02de26fb3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts@@ -4,15 +4,12 @@ import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/simport { buddySetupStep } from './buddy-setup-step';const slack = { id: 'b-1', type: 'slack', status: 'active' } as RemoteBridge;+const slack2 = { id: 'b-2', type: 'slack', status: 'active' } as RemoteBridge;const linked = { bridgeId: 'b-1' } as LinkedIdentity;-const slackChat = {- roomId: 'r-1',- channelType: 'direct',- bridgeType: 'slack',- agents: [{ id: 'a-1' }],-} as ChatSummary;+const linked2 = { bridgeId: 'b-2' } as LinkedIdentity;+const handedOff = { roomId: 'r-2', channelType: 'direct', bridgeType: 'slack' } as ChatSummary;-const base = { agentId: 'a-1', bridges: [], identities: [], chats: [], failed: false };+const base = { bridges: [], identities: [], resumes: {}, failed: false };describe('buddySetupStep', () => {it('waits for the reads, and says unknown when one failed, never not connected', () => {@@ -20,7 +17,7 @@ describe('buddySetupStep', () => {expect(buddySetupStep({ ...base, bridges: null, failed: true })).toEqual({ kind: 'unknown' });});- it('walks connect, link, create', () => {+ it('walks connect, link, resuming, create', () => {expect(buddySetupStep(base)).toEqual({ kind: 'connect' });expect(buddySetupStep({ ...base, bridges: [{ ...slack, status: 'error' }] }).kind).toBe('connect'@@ -30,26 +27,43 @@ describe('buddySetupStep', () => {});expect(buddySetupStep({ ...base, bridges: [slack] })).toEqual({ kind: 'link', bridge: slack });expect(buddySetupStep({ ...base, bridges: [slack], identities: [linked] })).toEqual({- kind: 'create',- bridge: slack,+ kind: 'resuming',});+ expect(+ buddySetupStep({ ...base, bridges: [slack], identities: [linked], resumes: { 'b-1': null } })+ ).toEqual({ kind: 'create', bridge: slack });});- it('confirms, not assumes, a Slack direct chat with the buddy', () => {- expect(buddySetupStep({ ...base, bridges: [slack], chats: [slackChat] })).toEqual({- kind: 'confirm',- bridge: slack,- });- expect(buddySetupStep({ ...base, bridges: [slack], chats: [slackChat], failed: true })).toEqual(- { kind: 'unknown' }- );+ it('offers to create, never assumes, when no hand-off was started, even with a Slack chat made by hand', () => {+ expect(+ buddySetupStep({+ ...base,+ bridges: [slack, slack2],+ identities: [linked, linked2],+ resumes: { 'b-1': null, 'b-2': null },+ })+ ).toEqual({ kind: 'create', bridge: slack });+ });++ it('is done with the room of the hand-off on whichever connection made it', () => {+ expect(+ buddySetupStep({+ ...base,+ bridges: [slack, slack2],+ identities: [linked, linked2],+ resumes: { 'b-1': null, 'b-2': handedOff },+ })+ ).toEqual({ kind: 'done', chat: handedOff });+ });++ it('says unknown when a resume failed', () => {expect(buddySetupStep({...base,bridges: [slack],identities: [linked],- chats: [{ ...slackChat, agents: [] }] as ChatSummary[],- }).kind- ).toBe('create');+ resumes: { 'b-1': 'failed' },+ })+ ).toEqual({ kind: 'unknown' });});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.tsindex 9d9bd0e80..8382cd9ca 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts@@ -6,41 +6,57 @@ export type BuddySetupStep =| { kind: 'unknown' }| { kind: 'connect' }| { kind: 'link'; bridge: RemoteBridge }+ | { kind: 'resuming' }| { kind: 'create'; bridge: RemoteBridge }- | { kind: 'confirm'; bridge: RemoteBridge };+ | { kind: 'done'; chat: ChatSummary };++/** A hand-off resumed on one Slack connection: its chat, null for none started, or failed. */+export type BuddyResume = ChatSummary | null | 'failed';++/** The active Slack connections the person has linked, where a hand-off could have been made. */+export function buddyResumeBridges(+ bridges: RemoteBridge[] | null,+ identities: LinkedIdentity[] | null+): RemoteBridge[] {+ return (bridges ?? []).filter(+ (bridge) =>+ bridge.type === 'slack' &&+ bridge.status === 'active' &&+ identities?.some((identity) => identity.bridgeId === bridge.id)+ );+}/*** Where the person is in moving their buddy to Slack, from live reads. A read* not in yet is `loading`; one that failed is `unknown`, never "not connected".- * A Slack chat with the buddy is `confirm`, not done: the server lists it- * before its hand-off has finished, so the hand-off is resumed to know.+ * Done only when resuming the hand-off on a connection, which never makes one,+ * found its chat: a Slack chat with the buddy made by hand is not a hand-off.+ * `resumes` is by bridge id, a bridge missing still being resumed.*/export function buddySetupStep({- agentId,bridges,identities,- chats,+ resumes,failed,}: {- agentId: string;bridges: RemoteBridge[] | null;identities: LinkedIdentity[] | null;- chats: ChatSummary[] | null;+ resumes: Partial<Record<string, BuddyResume>>;failed: boolean;}): BuddySetupStep {- const handedOff = chats?.find(- (chat) =>- chat.channelType === 'direct' &&- chat.bridgeType === 'slack' &&- chat.agents.some((agent) => agent.id === agentId)- );if (failed) return { kind: 'unknown' };- if (!bridges || !chats) return { kind: 'loading' };+ if (!bridges) return { kind: 'loading' };const slack = bridges.find((bridge) => bridge.type === 'slack' && bridge.status === 'active');if (!slack) return { kind: 'connect' };- if (handedOff) return { kind: 'confirm', bridge: slack };if (!identities) return { kind: 'loading' };- if (!identities.some((identity) => identity.bridgeId === slack.id))- return { kind: 'link', bridge: slack };- return { kind: 'create', bridge: slack };+ const linked = buddyResumeBridges(bridges, identities);+ if (linked.length === 0) return { kind: 'link', bridge: slack };+ const results = linked.map((bridge) => resumes[bridge.id]);+ const chat = results.find(+ (result): result is ChatSummary => typeof result === 'object' && result !== null+ );+ if (chat) return { kind: 'done', chat };+ if (results.includes('failed')) return { kind: 'unknown' };+ if (results.includes(undefined)) return { kind: 'resuming' };+ return { kind: 'create', bridge: linked[0] };}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.tsindex 202eb1324..0893c561b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts@@ -31,8 +31,23 @@ vi.mock('./buddy-welcome-message', () => ({`welcome ${firstName} from ${agentName}`,}));-const { BUDDY_CHAT_NAME, continueBuddyInSlack, openBuddyAfterOnboarding, openBuddyChat } =- await import('./open-buddy');+const {+ BUDDY_CHAT_NAME,+ continueBuddyInSlack,+ openBuddyAfterOnboarding,+ openBuddyChat,+ resumeBuddyInSlack,+} = await import('./open-buddy');+const { RpcError } = await import('@shared/lib/ipc/rpc-error');++function chatApiError(apiCode: string, status: number) {+ return new RpcError({+ __switchConsoleRpcError: true,+ code: 'ChatApiError',+ message: 'refused',+ data: { apiCode, status },+ });+}const buddy = { agentId: 'a-1', name: 'switch-buddy-max' };@@ -191,3 +206,31 @@ describe('continueBuddyInSlack', () => {});});});++describe('resumeBuddyInSlack', () => {+ const handoff = {+ serverId: 'srv-1',+ agentIds: ['a-1'],+ name: null,+ bridgeId: 'b-1',+ requestId: 'buddy-handoff:a-1:b-1',+ greeting: 'opener',+ };++ it('asks only to resume the hand-off, with the same request', async () => {+ const slackChat = chat('r-slack', '', 'a-1', 'direct', 'slack');+ createChat.mockResolvedValue(slackChat);++ await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).resolves.toBe(slackChat);++ expect(createChat).toHaveBeenCalledWith({ ...handoff, resumeOnly: true });+ });++ it('is null when none was started, and throws any other refusal', async () => {+ createChat.mockRejectedValueOnce(chatApiError('NO_SUCH_OPERATION', 404));+ await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).resolves.toBeNull();++ createChat.mockRejectedValueOnce(chatApiError('REQUEST_REUSED', 409));+ await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).rejects.toThrow('refused');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.tsindex 7ec21fa70..adc2d6ac4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts@@ -5,6 +5,7 @@ import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { appState } from '@renderer/lib/stores/app-state';import type { ChatSummary } from '@shared/core/chats/chats';+import { RpcError } from '@shared/lib/ipc/rpc-error';import { firstNameOf } from './buddy-identity';import { buddyIntroStore } from './buddy-intro-store';import { buddyPerson } from './buddy-person';@@ -125,29 +126,60 @@ export function buddyHandoffRequestId(agentId: string, bridgeId: string): string/** The handoffs under way, by request id: one at a time each. */const handingOff = new Map<string, Promise<ChatSummary>>();+function buddyHandoff(serverId: string, agentId: string, bridgeId: string) {+ return {+ serverId,+ agentIds: [agentId],+ name: null,+ bridgeId,+ requestId: buddyHandoffRequestId(agentId, bridgeId),+ greeting: buddySlackOpener(firstNameOf(buddyPerson(serverId).name)),+ };+}+/** Makes the person's private Slack channel with their buddy, the buddy opening it. */export function continueBuddyInSlack(serverId: string,agent: { agentId: string },bridgeId: string): Promise<ChatSummary> {- const requestId = buddyHandoffRequestId(agent.agentId, bridgeId);- const running = handingOff.get(requestId);+ const params = buddyHandoff(serverId, agent.agentId, bridgeId);+ const running = handingOff.get(params.requestId);if (running) return running;const made = rpc.chats- .create({- serverId,- agentIds: [agent.agentId],- name: null,- bridgeId,- requestId,- greeting: buddySlackOpener(firstNameOf(buddyPerson(serverId).name)),- })+ .create(params).then((chat) => {chatsStore.add(serverId, chat);return chat;})- .finally(() => handingOff.delete(requestId));- handingOff.set(requestId, made);+ .finally(() => handingOff.delete(params.requestId));+ handingOff.set(params.requestId, made);return made;}++/**+ * The buddy's Slack channel on this connection when a hand-off was started+ * there, finishing it if it was cut short; null when none was. Never makes one.+ */+export async function resumeBuddyInSlack(+ serverId: string,+ agentId: string,+ bridgeId: string+): Promise<ChatSummary | null> {+ try {+ const chat = await rpc.chats.create({+ ...buddyHandoff(serverId, agentId, bridgeId),+ resumeOnly: true,+ });+ chatsStore.add(serverId, chat);+ return chat;+ } catch (cause) {+ if (+ cause instanceof RpcError &&+ cause.code === 'ChatApiError' &&+ cause.stringField('apiCode') === 'NO_SUCH_OPERATION'+ )+ return null;+ throw cause;+ }+}diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex 5a214b952..366dda558 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -1365,6 +1365,7 @@ class ChatService:greeting: str | None,kind: Literal["group"] | None,bridge_id: str | None,+ resume_only: bool,) -> Room:"""A private room with the agents and members, owned by and joined bythe user.@@ -1385,6 +1386,9 @@ class ChatService:`bridge_id` makes the direct chat a private channel on that bridgebetween the user's own linked account there and the agent.++ `resume_only` only finishes a create this request id already started;+ when it started none, nothing is made and the chat is 404."""member_user_ids = sorted(set(member_user_ids) - {user.id})direct = kind != "group" and len(agent_ids) == 1 and not member_user_ids@@ -1432,6 +1436,12 @@ class ChatService:async with self._lock("create", tenant_id, user.id):async with tenant_session(self.session_factory, tenant_id) as session:operation = await self._operation(session, user.id, request_id)+ if operation is None and resume_only:+ raise ChatError(+ 404,+ "NO_SUCH_OPERATION",+ "No chat was started with this request id, so there is none to resume.",+ )if operation is not None:self._require_same(operation, "create_chat", payload_hash)if operation.state == "done" and operation.room_id is not None:diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.pyindex 57751fb51..496060a58 100644--- a/core/switch_core/gateway/chats.py+++ b/core/switch_core/gateway/chats.py@@ -117,6 +117,9 @@ class CreateChatRequest(CamelModel):# Makes the direct chat a private channel on this collaboration bridge# (Slack), with the caller's own linked account; older clients send none.bridge_id: str | None = None+ # Only finishes the create this request id already started: 404 when it+ # started none; older clients send none.+ resume_only: bool = Falsedef chosen_agents(self) -> list[str]:if (self.agent_id is None) == (self.agent_ids is None):@@ -330,6 +333,7 @@ async def create_chat(greeting=req.greeting,kind=req.kind,bridge_id=req.bridge_id,+ resume_only=req.resume_only,)async with tenant_session(service.session_factory, tenant_id) as session:return ChatEnvelope(diff --git a/core/tests/switch_core/gateway/test_chats_bridged_direct.py b/core/tests/switch_core/gateway/test_chats_bridged_direct.pyindex 19f4a9441..63a0dc995 100644--- a/core/tests/switch_core/gateway/test_chats_bridged_direct.py+++ b/core/tests/switch_core/gateway/test_chats_bridged_direct.py@@ -11,6 +11,7 @@ from typing import Anyimport httpximport pytest+from sqlalchemy import func, selectfrom switch_core.db.models import (Agent,@@ -136,7 +137,11 @@ async def _slack(chats: _Harness, *, link: User | None) -> tuple[str, _FakeCore]async def _create(- chats: _Harness, agents: list[Agent], bridge_id: str, request_id: str = "c1"+ chats: _Harness,+ agents: list[Agent],+ bridge_id: str,+ request_id: str = "c1",+ resume_only: bool = False,) -> httpx.Response:return await chats.client.post("/chats",@@ -144,6 +149,7 @@ async def _create("agentIds": [agent.id for agent in agents],"requestId": request_id,"bridgeId": bridge_id,+ "resumeOnly": resume_only,},headers=chats.as_user(chats.alice),)@@ -251,6 +257,7 @@ async def _create_on(greeting=None,kind=None,bridge_id=bridge_id,+ resume_only=False,)@@ -323,3 +330,62 @@ async def test_a_retry_after_a_failed_bridge_invite_puts_the_bridge_in(assert bridge_invites == [room.transport_room_id]assert core.users_added == [["alice.s"]]assert len(core.dm_calls) == 1+++async def test_resuming_a_create_that_never_started_makes_nothing(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)++ response = await _create(chats, [agent], bridge_id, resume_only=True)++ assert response.status_code == 404+ assert _code(response) == "NO_SUCH_OPERATION"+ assert core.dm_calls == []+ async with chats.factory() as session:+ rooms = await session.scalar(+ select(func.count()).select_from(Room).where(Room.bridge_id == bridge_id)+ )+ assert rooms == 0+ created = await _create(chats, [agent], bridge_id)+ assert created.status_code == 200, created.text+++async def test_resuming_a_finished_create_returns_its_chat(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)++ first = await _create(chats, [agent], bridge_id)+ again = await _create(chats, [agent], bridge_id, resume_only=True)++ assert again.status_code == 200, again.text+ assert again.json()["chat"]["roomId"] == first.json()["chat"]["roomId"]+ assert len(core.dm_calls) == 1+++async def test_resuming_a_create_that_failed_after_saving_finishes_it(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ make_lasting = chats.service._make_lasting+ failures = [RuntimeError("join failed")]++ async def failing_make_lasting(*args: Any) -> None:+ if failures:+ raise failures.pop()+ await make_lasting(*args)++ monkeypatch.setattr(chats.service, "_make_lasting", failing_make_lasting)++ with pytest.raises(RuntimeError, match="join failed"):+ await _create_on(chats, chats.service, agent, bridge_id)+ resumed = await _create(chats, [agent], bridge_id, resume_only=True)+ again = await _create(chats, [agent], bridge_id)++ assert resumed.status_code == 200, resumed.text+ assert again.json()["chat"]["roomId"] == resumed.json()["chat"]["roomId"]+ assert len(core.dm_calls) == 1diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.pyindex c597c323a..79f3c46ce 100644--- a/core/tests/switch_core/gateway/test_chats_groups.py+++ b/core/tests/switch_core/gateway/test_chats_groups.py@@ -935,6 +935,7 @@ async def test_one_create_on_two_processes_makes_one_room(request_id="c1",greeting=None,bridge_id=None,+ resume_only=False,)first, second = await asyncio.gather(create(chats.service), create(other))@@ -1212,6 +1213,7 @@ async def test_one_request_id_with_two_payloads_on_two_processes_is_one_request(request_id="c1",greeting=None,bridge_id=None,+ resume_only=False,)except ChatError as refused:return refused