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
fix(console): end a turn the host said failed, even when the feed lost its last update
raullopez-sandbox161e4aed9ba2
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.tsindex 48543491e..b63109d6f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts@@ -70,6 +70,39 @@ export function bindTurns(return bound;}+/**+ * The turns a host notice in the room says ended, though the activity feed+ * still has them going: the feed lost the turn's last update (the machine was+ * reconnecting), and nothing would otherwise ever end it. Each failed or+ * stopped notice from the agent ends its latest turn still going that started+ * at a message before it.+ */+export function settleTurnsByNotices(+ turns: readonly TurnActivity[],+ messages: readonly ChatMessage[],+ agentId: string,+ roomId: string+): TurnActivity[] {+ const going = (turn: TurnActivity) => turn.status === 'running' || turn.status === 'queued';+ if (!turns.some(going)) return [...turns];+ const bound = bindTurns(turns, roomId);+ const settled = new Map<TurnActivity, TurnStatus>();+ messages.forEach((message, at) => {+ const notice = message.sender.agentId === agentId ? turnEndNotice(message) : null;+ if (!notice || notice.outcome === 'completed') return;+ const turn = messages+ .slice(0, at)+ .map((each) => bound.get(each.messageId))+ .findLast((each) => each !== undefined && going(each) && !settled.has(each));+ if (turn) settled.set(turn, notice.outcome === 'failed' ? 'error' : 'interrupted');+ });+ if (settled.size === 0) return [...turns];+ return turns.map((turn) => {+ const status = settled.get(turn);+ return status ? { ...turn, status } : turn;+ });+}+/*** Where one agent's turns show, by the message each shows under, in message* order. A turn shows under the message that started it, unless that messagediff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.tsindex 6251e95b3..f40e70679 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts@@ -11,6 +11,7 @@ import {} from '@shared/core/chats/chatEvents';import { roomHealthChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';import { AgentActivities } from './chat-activity-store';+import { chatsStore } from './chats';/** How long to gather room changes before re-reading: a template makes several at once. */const ROOM_REFRESH_DELAY_MS = 500;@@ -24,6 +25,7 @@ export const agentActivities = new AgentActivities(watchPlacements: (serverId, onChange) =>events.on(roomHealthChangedChannel, onChange, serverId),roomActivity: (serverId, roomId) => rpc.chats.roomActivity(serverId, roomId),+ roomMessages: (serverId, roomId) => chatsStore.timelines.peek(serverId, roomId)?.messages ?? [],control: (input) => rpc.chats.control(input),answerApproval: (input) => rpc.chats.answerApproval(input),},diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.tsindex a9aa45674..20cb66b3e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts@@ -9,9 +9,15 @@ import type {RoomActivity,} from '@shared/core/chats/activity';import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';-import type { ChatStreamState } from '@shared/core/chats/chats';+import type { ChatMessage, ChatStreamState } from '@shared/core/chats/chats';import type { ReasoningList, ReasoningTurn, ToolDetail } from '@shared/core/sessions/reasoning';-import { bindTurns, groupTurns, itemKey, type TurnActivity } from '../activity-join';+import {+ bindTurns,+ groupTurns,+ itemKey,+ settleTurnsByNotices,+ type TurnActivity,+} from '../activity-join';import { chatFailure, serverTooOld } from './chat-errors';/**@@ -37,6 +43,8 @@ export type ActivityApi = {/** Call `onChange` whenever the server's local or SSH placements change. */watchPlacements: (serverId: string, onChange: () => void) => () => void;roomActivity: (serverId: string, roomId: string) => Promise<RoomActivity>;+ /** The room's messages loaded here, oldest first: a host's notice that a turn ended is among them. */+ roomMessages: (serverId: string, roomId: string) => readonly ChatMessage[];control: (input: {serverId: string;roomId: string;@@ -155,7 +163,12 @@ export class AgentActivity {}get allTurns(): TurnActivity[] {- return groupTurns(this.items.values(), this.approvals.values());+ return settleTurnsByNotices(+ groupTurns(this.items.values(), this.approvals.values()),+ this.api.roomMessages(this.serverId, this.roomId),+ this.agentId,+ this.roomId+ );}/** Turns joined to the room messages that started them. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.tsindex cbcb14cd8..eb09925cb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts@@ -1,4 +1,4 @@-import { makeAutoObservable, runInAction } from 'mobx';+import { makeAutoObservable, observable, runInAction } from 'mobx';import {type ChatMentionSpan,type ChatMessage,@@ -359,7 +359,8 @@ export class ChatTimeline {* them.*/export class ChatTimelines {- private readonly timelines = new Map<string, ChatTimeline>();+ /** Observable, so what reads a room's messages through {@link peek} follows a timeline opened later. */+ private readonly timelines = observable.map<string, ChatTimeline>({}, { deep: false });constructor(private readonly api: (serverId: string) => TimelineApi) {}@@ -367,8 +368,9 @@ export class ChatTimelines {const key = `${serverId}\u0000${roomId}`;let timeline = this.timelines.get(key);if (!timeline) {- timeline = new ChatTimeline(roomId, this.api(serverId));- this.timelines.set(key, timeline);+ const created = new ChatTimeline(roomId, this.api(serverId));+ runInAction(() => this.timelines.set(key, created));+ timeline = created;}return timeline;}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.tsindex 26d3e6b50..92994d76c 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts@@ -391,7 +391,7 @@ function memoryStorage() {};}-function fakeApi(snapshots: RoomActivity[]) {+function fakeApi(snapshots: RoomActivity[], messages: ChatMessage[] = []) {const reads: string[] = [];const controls: unknown[] = [];const api: ActivityApi = {@@ -406,6 +406,7 @@ function fakeApi(snapshots: RoomActivity[]) {reads.push(roomId);return snapshots.shift() ?? { items: [], approvals: [] };},+ roomMessages: () => messages,control: async (input) => {controls.push(input);return 'cmd-1';@@ -436,6 +437,47 @@ describe('AgentActivities', () => {activities.release(b);});+ it('ends a turn the host said failed, though the feed still has it running, after a reopen too', async () => {+ const said = (messageId: string, agentId: string | null, body = messageId) =>+ ({+ messageId,+ body,+ sender: { kind: agentId ? 'agent' : 'human', agentId, clientId: agentId ?? 'me' },+ }) as unknown as ChatMessage;+ const failed =+ 'I finished without replying. The turn failed: {"type":"error","status":400,"error":"model_not_found"}';+ const messages = [said('m-t1', null), said('n1', 'agent-a', failed)];+ // The feed lost the turn's last update: every read still has it running.+ const running = { items: [row('t1', 'turn')], approvals: [] };+ const { api } = fakeApi([running, running], messages);+ const activities = new AgentActivities(api, memoryStorage());++ let activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ expect(activity.working).toBe(false);+ expect(activity.runningTurn).toBeNull();+ expect(activity.turns().get('m-t1')?.status).toBe('error');+ // The notice folds into the ended turn, which shows the provider's reason.+ expect(foldTurnEndNotices(messages, 'agent-a', activity.turns())).toEqual(+ new Map([['n1', 't1']])+ );++ activities.release(activity);+ activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ expect(activity.working).toBe(false);+ activities.release(activity);+ });++ it('keeps a turn running when no notice says it ended', async () => {+ const { api } = fakeApi([{ items: [row('t1', 'turn')], approvals: [] }]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ expect(activity.working).toBe(true);+ activities.release(activity);+ });+it('merges live rows with the snapshot by revision, dropping stale ones', async () => {const snapshotTool = row('t1', 'tool', { revision: 5, title: 'from snapshot' });const { api } = fakeApi([{ items: [row('t1', 'turn'), snapshotTool], approvals: [] }]);