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
Start a fresh conversation when a room message reaches a lost one (#612)
Louis Amaudruz395a3b61ca1b
diff --git a/console/packages/agent-providers/src/host/room-prompt.ts b/console/packages/agent-providers/src/host/room-prompt.tsindex f3fcb1123..6bcb9b9c2 100644--- a/console/packages/agent-providers/src/host/room-prompt.ts+++ b/console/packages/agent-providers/src/host/room-prompt.ts@@ -51,6 +51,15 @@ export function roomCommandId(agentId: string, roomId: string, messageId: stringreturn uuidFrom(`switch-room:${agentId}:${roomId}:${messageId}`);}+/** The fresh start a room message triggers on a conversation that cannot continue: once per message. */+export function roomFreshStartCommandId(+ agentId: string,+ roomId: string,+ messageId: string+): string {+ return uuidFrom(`switch-room-fresh-start:${agentId}:${roomId}:${messageId}`);+}+const MIME_ALIASES: Record<string, string> = {'image/jpg': 'image/jpeg','text/x-markdown': 'text/markdown',diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex d81318bc3..c42b7f4a2 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -443,7 +443,16 @@ export class HostedSession {type: 'notice',level: 'info',code: 'ROOM_BACKLOG_DELIVERED',- message: `${count} room message(s) received while the conversation needed an explicit reset are now being delivered to the fresh conversation.`,+ message: `${count} room message(s) received while the conversation could not continue are now being delivered to the fresh conversation.`,+ });+ }++ startingFreshForRoom(): Promise<void> {+ return this.publish({+ type: 'notice',+ level: 'warning',+ code: 'FRESH_START_FOR_ROOM',+ message: `A room message arrived while the conversation could not continue (${this.decisionCode}). Starting a fresh conversation to answer it; earlier messages stay in the transcript.`,});}diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex d5d9654e8..96766ecdb 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -5,7 +5,11 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import type { Command, Session } from '@switch-console/shared/session-v1';import { afterEach, expect, it, vi } from 'vitest';-import type { ProviderAdapter, TurnAttachment } from '../adapter';+import {+ ProviderConversationUnavailableError,+ type ProviderAdapter,+ type TurnAttachment,+} from '../adapter';import type { ProviderRuntimeEvent } from '../events';import { stubSwitchFetch } from '../testing/agent-sessions-server';import { connectParent } from './session-channel';@@ -77,6 +81,7 @@ function fakeParent() {}type Harness = {+ base: string;root: string;adapter: ProviderAdapter;emit: (event: Record<string, unknown>) => void;@@ -104,11 +109,15 @@ async function start(startUnknown?: boolean;startRefused?: boolean;unavailable?: boolean;+ /** Run in the directory an earlier host ran in, as a restart would. */+ base?: string;+ /** The provider has lost the conversation this host would resume. */+ conversationLost?: boolean;} = {}): Promise<Harness> {const parent = fakeParent();- const base = await mkdtemp(join(tmpdir(), 'shared-host-test-'));- roots.push(base);+ const base = opts.base ?? (await mkdtemp(join(tmpdir(), 'shared-host-test-')));+ if (!opts.base) roots.push(base);const root = join(base, 'session');const owedText =opts.owedStartText ?? (opts.owedStart ? JSON.stringify({ startSource: opts.owedStart }) : null);@@ -194,6 +203,14 @@ async function start(};},};+ if (opts.conversationLost)+ vi.mocked(adapter.startSession).mockRejectedValueOnce(+ new ProviderConversationUnavailableError(+ 'claude',+ 'session',+ 'Saved conversation unavailable'+ )+ );const media = new Map<string, Uint8Array>();const switchCore = stubSwitchFetch(vi.fn(async (url: string) => {@@ -254,6 +271,7 @@ async function start(timeout: 5000,});return {+ base,root,adapter,emit,@@ -776,6 +794,52 @@ it('tells the session to rejoin its room once a reset asked for there has applie}}, 20000);+it('starts a fresh conversation for a room message the lost one could not take, and runs it', async () => {+ const first = await start({ rooms: true, resettable: true });+ await first.parent.ask({ type: 'room', handoff: roomMessage(1, 'first') });+ await vi.waitFor(() => expect(first.turns).toHaveLength(1), { timeout: 3000 });+ first.emit({+ type: 'turn.completed',+ turnId: first.turns[0]!.turnId,+ outcome: 'completed',+ usage: [],+ });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(await first.stop()).toBeNull();+ // Its process would have exited; this one is still alive and would be fenced.+ await rm(join(first.root, 'shared-owner.lock'));++ const host = await start({+ rooms: true,+ resettable: true,+ base: first.base,+ conversationLost: true,+ });+ try {+ expect(host.adapter.startSession).toHaveBeenCalledOnce();+ expect(+ await host.parent.ask({ type: 'room', handoff: roomMessage(2, 'second') })+ ).toMatchObject({ ok: true });+ await vi.waitFor(() => expect(host.turns).toHaveLength(1), { timeout: 5000 });+ expect(host.turns[0]!.text).toContain('second');+ const starts = vi.mocked(host.adapter.startSession).mock.calls;+ expect(starts).toHaveLength(2);+ expect(starts[0]![0].resume).toEqual({ nativeSessionId: 'native' });+ expect(starts[1]![0].resume).toBeUndefined();+ const notices = (await readFile(join(host.root, 'events.jsonl'), 'utf8'))+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line).body)+ .filter((body) => body.type === 'notice')+ .map((body) => body.code);+ expect(notices).toEqual(+ expect.arrayContaining(['FRESH_START_FOR_ROOM', 'CONTEXT_RESET', 'ROOM_BACKLOG_DELIVERED'])+ );+ } finally {+ expect(await host.stop()).toBeNull();+ }+}, 20000);+const startReports = (host: Harness) =>host.switchCore.calls.filter((c) => c.path.endsWith('/started'));const owed = (host: Harness) =>diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 6cfdfe676..18b3ac1f9 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -13,6 +13,7 @@ import { SharedRoomInbox, type roomConnectionSchema } from './room-inbox';import {planAttachments,roomCommand,+ roomFreshStartCommandId,roomMessageSchema,type RoomAttachmentSource,} from './room-prompt';@@ -549,6 +550,40 @@ export async function runSharedHost(}};+ /**+ * A room message reached a conversation that cannot continue as it was —+ * its provider lost it, or a reset was cut off. Nobody in the room can+ * press "Start a fresh conversation" for it, so the session does: the+ * message would otherwise wait unseen for someone at the Console. The+ * transcript keeps everything said before.+ */+ const startFreshFor = async (event: { roomId: string; messageId: string }): Promise<void> => {+ await host!.startingFreshForRoom();+ const outcome = await run(+ {+ contractVersion: 1,+ commandId: roomFreshStartCommandId(agentId, event.roomId, event.messageId),+ sessionId: options.session.sessionId,+ epoch: host!.snapshot().session.epoch,+ origin: {+ surface: 'switch-web',+ actorId: agentId,+ roomId: null,+ threadId: null,+ messageId: null,+ },+ body: { type: 'session.reset' },+ },+ null+ );+ if (typeof outcome === 'string')+ throw new Error(`Could not start a fresh conversation for a room message: ${outcome}`);+ if (outcome.status === 'rejected' || outcome.status === 'unknown')+ throw new Error(+ `Could not start a fresh conversation for a room message: ${outcome.message ?? outcome.code ?? outcome.status}`+ );+ };+identify(host.snapshot().session);// A parent that started this host talks to it over IPC: commands and room// messages come down the pipe, and every recorded event goes up it.@@ -666,8 +701,11 @@ export async function runSharedHost(throw new Error('HOST_FAULTED: Provider execution failed. Inspect the transcript before recovery.');- if (host.resetDecisionPending) heldForDecision = true;- else if (heldForDecision) {+ if (host.resetDecisionPending) {+ heldForDecision = true;+ const first = rooms?.pending()[0];+ if (first) await startFreshFor(first);+ } else if (heldForDecision) {heldForDecision = false;const held = rooms?.pending().length ?? 0;if (held) await host.roomBacklogDelivered(held);