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): drag the window from the agent page top bar (CHOO-3119) (#878)
raullopez-sandbox12955dfda0cf
diff --git a/console/apps/switch-console-desktop/src/main/app/window.ts b/console/apps/switch-console-desktop/src/main/app/window.tsindex dd1d023ab..4af22cb58 100644--- a/console/apps/switch-console-desktop/src/main/app/window.ts+++ b/console/apps/switch-console-desktop/src/main/app/window.ts@@ -1,5 +1,5 @@import { join } from 'node:path';-import { app, BrowserWindow } from 'electron';+import { app, BrowserWindow, dialog } from 'electron';import appIcon from '@/assets/images/switch-console/icon-dock.png?asset';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';@@ -87,6 +87,20 @@ export function createMainWindow(): BrowserWindow {}});+ // The renderer refuses an unload while a screen has unsaved changes; the+ // person decides here, since a page cannot show its own dialog during unload.+ mainWindow.webContents.on('will-prevent-unload', (event) => {+ const choice = dialog.showMessageBoxSync(mainWindow!, {+ type: 'question',+ message: 'You have unsaved changes',+ detail: 'If you leave now, your unsaved changes will be lost.',+ buttons: ['Stay', 'Discard and leave'],+ defaultId: 0,+ cancelId: 0,+ });+ if (choice === 1) event.preventDefault();+ });+// Cleanup reference on closemainWindow.on('closed', () => {mainWindow = null;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 e8c66781c..6878a7d9f 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@@ -4,7 +4,7 @@ import { getAgents } from '@main/core/agents/getAgents';import { agentPlacements } from '@main/core/sdk-host/connection-health';import { localWatcherControl } from '@main/core/sdk-host/local-host';import { withSidecar } from '@main/core/sdk-host/sidecar-control';-import { fetchMe } from '@main/core/switch-servers/gateway-client';+import { deleteRoom, fetchMe } from '@main/core/switch-servers/gateway-client';import { withServerWorkspaceSession } from '@main/core/workspaces/workspace-session';import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';@@ -34,6 +34,7 @@ import {import { generateChatTitle } from './chat-title';import {answerChatApproval,+ archiveChat,createChat,fetchChatMedia,fetchChatMessages,@@ -42,7 +43,6 @@ import {renameChat,sendChatControl,sendChatMessage,- setChatHidden,uploadChatAttachment,warmChatAgent,} from './gateway';@@ -85,19 +85,23 @@ const activityDeps: ActivityDeps = {};/**- * Asks the host of the person's agent to start the session a message to the- * room would start, ahead of the message: a local or SSH host directly, any- * other through core, which tells the agent's controller. A failure is- * logged, never thrown, so it cannot get in the way of sending.+ * Asks the agent's host to start the session a message to the room would+ * start, ahead of the message: a local or SSH host directly, any other+ * through core, which tells the agent's controller — unless `throughCore` is+ * false because core already did when it created the chat. A failure is+ * logged, never thrown, so it cannot get in the way of the chat.*/-async function warmChat(params: { serverId: string; agentId: string; roomId: string }) {+async function warmChat(+ params: { serverId: string; agentId: string; roomId: string },+ throughCore: boolean+) {const { serverId, agentId, roomId } = params;try {const local = (await activityDeps.localAgents(serverId)).find((agent) => agent.switchAgentId === agentId);if (!local) {- await onServer(serverId, (server) => warmChatAgent(server, roomId, agentId));+ if (throughCore) await onServer(serverId, (server) => warmChatAgent(server, roomId, agentId));return;}await (local.ssh@@ -141,13 +145,21 @@ export const chatsController = createRPCController({},list: (serverId: string): Promise<ChatSummary[]> => onServer(serverId, listChats),/** `greeting`: what the chat's one agent, the caller's own, says as it joins, in place of its usual line. */- create: (params: {+ create: async (params: {serverId: string;agentIds: string[];name: string | null;requestId: string;greeting: string | null;- }): Promise<ChatSummary> => onServer(params.serverId, (server) => createChat(server, params)),+ }): Promise<ChatSummary> => {+ const chat = await onServer(params.serverId, (server) => createChat(server, params));+ if (params.agentIds.length === 1)+ void warmChat(+ { serverId: params.serverId, agentId: params.agentIds[0], roomId: chat.roomId },+ false+ );+ return chat;+ },messages: (params: {serverId: string;roomId: string;@@ -189,10 +201,10 @@ export const chatsController = createRPCController({);return { mimeType: media.mimeType, data: Buffer.from(media.bytes).toString('base64') };},- hide: (serverId: string, roomId: string): Promise<void> =>- onServer(serverId, (server) => setChatHidden(server, roomId, true)),- unhide: (serverId: string, roomId: string): Promise<void> =>- onServer(serverId, (server) => setChatHidden(server, roomId, false)),+ archive: (serverId: string, roomId: string): Promise<void> =>+ onServer(serverId, (server) => archiveChat(server, roomId)),+ delete: (serverId: string, roomId: string): Promise<void> =>+ onServer(serverId, (server) => deleteRoom(server, roomId)),rename: (serverId: string, roomId: string, name: string): Promise<void> =>onServer(serverId, (server) => renameChat(server, roomId, name)),/** A short chat name from its first message, from the user's local Claude CLI. */@@ -206,10 +218,9 @@ export const chatsController = createRPCController({agentId: string;roomId: string;}): Promise<ChatActivityTarget> => resolveChatActivity(activityDeps, params),- /** Start the agent's session for the chat while its user types, if the agent is theirs. */+ /** Start the agent's session for an existing chat reopened empty; creating a chat starts it already. */warm: (params: { serverId: string; agentId: string; roomId: string }): Promise<void> =>- warmChat(params),-+ warmChat(params, true),/** The room's turn steps and approval requests; changes follow on the activity channels. */roomActivity: (serverId: string, roomId: string): Promise<RoomActivity> =>onServer(serverId, (server) => fetchRoomActivity(server, roomId)),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 002304d7c..31284dc40 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@@ -222,12 +222,8 @@ export async function fetchChatMedia(};}-export async function setChatHidden(- server: SwitchServer,- roomId: string,- hidden: boolean-): Promise<void> {- await call(server, `${room(roomId)}/hidden`, { method: hidden ? 'PUT' : 'DELETE' });+export async function archiveChat(server: SwitchServer, roomId: string): Promise<void> {+ await call(server, `${room(roomId)}/archive`, { method: 'POST' });}/** Rename uses the room route: a chat's name is its room's name. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/agent-conversations.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/agent-conversations.tsindex 2d29c5bde..1e019f7d8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/agent-conversations.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/agent-conversations.ts@@ -5,15 +5,18 @@ import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers/*** An agent's conversations, in two lists that never share a room: its 1-1* chats made in Console (see `isConsoleDirectChat`), newest first, and every other room it is in, by name — a messaging-app DM and a- * chat with several agents included, whether or not its membership lists it.+ * chat with several agents included, whether or not its membership lists it. Excludes rooms the person lost access to.*/export function agentConversations(agentChats: readonly ChatSummary[],- agentRooms: readonly RemoteAgentRoom[]+ agentRooms: readonly RemoteAgentRoom[],+ removed: ReadonlySet<string>): { direct: ChatSummary[]; rooms: Pick<RemoteAgentRoom, 'roomId' | 'roomName'>[] } {const direct = agentChats.filter(isConsoleDirectChatSummary);const directIds = new Set(direct.map((chat) => chat.roomId));- const listed = agentRooms.filter((room) => !room.archived && !directIds.has(room.roomId));+ const listed = agentRooms.filter(+ (room) => !room.archived && !directIds.has(room.roomId) && !removed.has(room.roomId)+ );const listedIds = new Set(agentRooms.map((room) => room.roomId));const unlisted = agentChats.filter((chat) => !directIds.has(chat.roomId) && !listedIds.has(chat.roomId))@@ -21,3 +24,24 @@ export function agentConversations(const rooms = [...listed, ...unlisted].sort((a, b) => a.roomName.localeCompare(b.roomName));return { direct, rooms };}++/**+ * Agents by their newest 1-1 Console chat message, newest first. Agents with+ * no such chat, and ties, keep the order they came in. No chats (flag off or+ * not loaded) leaves the order as it is.+ */+export function byLatestDirectChat<T extends { agentId: string }>(+ agents: readonly T[],+ chats: Iterable<ChatSummary> | null+): T[] {+ if (chats === null) return [...agents];+ const latest = new Map<string, string>();+ for (const chat of chats) {+ if (!chat.lastMessage || !isConsoleDirectChatSummary(chat)) continue;+ const id = chat.agents[0].id;+ if ((latest.get(id) ?? '') < chat.lastMessage.sentAt) latest.set(id, chat.lastMessage.sentAt);+ }+ return [...agents].sort((a, b) =>+ (latest.get(b.agentId) ?? '').localeCompare(latest.get(a.agentId) ?? '')+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-removal.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-removal.tsnew file mode 100644index 000000000..a3e30168b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-removal.ts@@ -0,0 +1,17 @@+/** Where the person goes once a chat is deleted or archived: nowhere unless it was the one open. */+export type ChatRemovalNavigation = {+ /** The chat view shows the removed chat: leave it. */+ leaveChatView: boolean;+ /** The agent page points at the removed chat: drop it, so the page opens another or starts one. */+ clearAgentChat: boolean;+};++export function chatRemovalNavigation(+ roomId: string,+ nav: { currentViewId: string; chatRoomId?: string; agentRoomId?: string }+): ChatRemovalNavigation {+ return {+ leaveChatView: nav.currentViewId === 'chat' && nav.chatRoomId === roomId,+ clearAgentChat: nav.agentRoomId === roomId,+ };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsxindex 0831c41a5..a52cdbcdd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx@@ -1,12 +1,12 @@-import { EyeOff, Pencil } from 'lucide-react';+import { Archive, Pencil, Trash2 } from 'lucide-react';import { Fragment, type ReactNode } from 'react';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';-import { rpc } from '@renderer/lib/ipc';import { showModal } from '@renderer/lib/modal/modal-provider';import { appState } from '@renderer/lib/stores/app-state';import { DropdownMenuItem, DropdownMenuSeparator } from '@renderer/lib/ui/dropdown-menu';import type { ChatSummary } from '@shared/core/chats/chats';+import { chatRemovalNavigation } from '../chat-removal';import { chatsStore } from '../stores/chats';export type ChatAction = {@@ -25,43 +25,62 @@ async function attempt(run: () => Promise<void>, failure: string): Promise<void>}}-/** Leave the chat view if it shows this room, and close it on an agent's Chats tab. */+/** Leave the chat view if it shows this room, and close it on an agent's page. */function leaveIfOpen(roomId: string): void {const navigation = appState.navigation;- if (navigation.currentViewId === 'chat' && navigation.viewParamsStore.chat?.roomId === roomId)- navigation.navigate('home');- if (navigation.viewParamsStore.managedAgent?.roomId === roomId)- navigation.updateViewParams('managedAgent', { roomId: undefined });+ const { leaveChatView, clearAgentChat } = chatRemovalNavigation(roomId, {+ currentViewId: navigation.currentViewId,+ chatRoomId: navigation.viewParamsStore.chat?.roomId,+ agentRoomId: navigation.viewParamsStore.managedAgent?.roomId,+ });+ if (leaveChatView) navigation.navigate('home');+ if (clearAgentChat) navigation.updateViewParams('managedAgent', { roomId: undefined });}/**- * What can be done to a chat from its row or its header. Rename changes the- * room for everyone, so it is offered only to its managers; removing it from- * the list is the person's own and comes back with the next message.+ * What can be done to a chat from its row or its header. Each acts on the room+ * for everyone in it, so each is offered only to its managers: the room's owner+ * or a workspace admin, the same rule the server applies.*/export function chatActions(serverId: string, chat: ChatSummary): ChatAction[] {- const actions: ChatAction[] = [];- if (chat.canManage)- actions.push({+ if (!chat.canManage) return [];+ const { roomId } = chat;+ return [+ {key: 'rename',label: 'Rename',icon: <Pencil className="size-4" />,+ run: () => showModal('renameChatModal', { serverId, roomId, currentName: chat.name }),+ },+ {+ key: 'archive',+ label: 'Archive',+ icon: <Archive className="size-4" />,run: () =>- showModal('renameChatModal', { serverId, roomId: chat.roomId, currentName: chat.name }),- });- actions.push({- key: 'hide',- label: 'Remove from my list',- icon: <EyeOff className="size-4" />,- separatorBefore: true,- run: () =>- void attempt(async () => {- await rpc.chats.hide(serverId, chat.roomId);- chatsStore.hide(chat.roomId);- leaveIfOpen(chat.roomId);- }, 'Could not remove the chat from your list.'),- });- return actions;+ void attempt(async () => {+ await chatsStore.archive(serverId, roomId);+ leaveIfOpen(roomId);+ }, 'Could not archive the chat.'),+ },+ {+ key: 'delete',+ label: 'Delete chat…',+ icon: <Trash2 className="size-4" />,+ separatorBefore: true,+ run: () =>+ showModal('confirmActionModal', {+ title: 'Delete this chat?',+ description:+ "This deletes the chat and its messages for everyone, including the agent. This can't be undone.",+ confirmLabel: 'Delete chat',+ onSuccess: () =>+ void attempt(async () => {+ await chatsStore.delete(serverId, roomId);+ leaveIfOpen(roomId);+ }, 'Could not delete the chat.'),+ }),+ },+ ];}/** A chat's actions as dropdown menu items. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsxindex 50babbf61..f9f4df6b2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx@@ -1,6 +1,7 @@import { observer } from 'mobx-react-lite';-import { type ReactNode, useState } from 'react';+import { type ComponentProps, type ReactNode, useState } from 'react';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+import { cn } from '@renderer/utils/utils';import type { ChatActivityItem, ChatApproval } from '@shared/core/chats/activity';import { reasoningLabel } from '@shared/core/sessions/reasoning';import { isThinking, toolState, type TurnActivity, turnTools } from '../activity-join';@@ -116,6 +117,60 @@ export function turnEndLabel(label: string, reason: string | null): ReactNode {);}+/**+ * One row of an agent's block in the timeline. The first row of the block+ * carries the avatar and the agent's name; the rows after it keep the indent.+ */+export function AgentRow({+ agent,+ serverId,+ head,+ trailing,+ className,+ children,+ ...props+}: ComponentProps<'div'> & {+ agent: { name: string; iconUrl: string | null };+ serverId: string;+ head: boolean;+ trailing?: ReactNode;+}) {+ return (+ <div className={cn('flex gap-3', className)} {...props}>+ {head ? (+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={28} />+ ) : (+ <span className="w-7 shrink-0" aria-hidden />+ )}+ <div className="flex min-w-0 flex-1 flex-col">+ {head && (+ <span className="mb-1 text-xs leading-4 font-semibold text-foreground-muted">+ {agent.name}+ </span>+ )}+ {children}+ </div>+ {trailing}+ </div>+ );+}++/** Whether a turn has anything to show in its work log. */+export function turnShown(activity: AgentActivity, turn: TurnActivity): boolean {+ const running = turn.status === 'queued' || turn.status === 'running';+ const reasoning = activity.reasoning.get(turn.turnId) ?? null;+ const { work, switchActions } = turnTools(turn);+ return (+ reasoningLabel(reasoning, running && reasoning !== null) !== null ||+ work.length > 0 ||+ switchActions.length > 0 ||+ isThinking(turn) ||+ turn.status === 'interrupted' ||+ turn.status === 'error' ||+ turn.requests.length > 0+ );+}+/*** What the agent did for one room message, from Switch's activity feed: its* reasoning (local and SSH hosts only, read from the host), each tool it ran,@@ -127,15 +182,20 @@ export const ChatActivityBlock = observer(function ChatActivityBlock({activity,turn,agent,+ head,endReason,serverId,+ className,}: {activity: AgentActivity;turn: TurnActivity;agent: { name: string; iconUrl: string | null };+ /** Whether this turn starts the agent's block, so shows its avatar and name. */+ head: boolean;/** Why the turn ended, from the host's notice in the room; null when it posted none. */endReason: string | null;serverId: string;+ className?: string;}) {const running = turn.status === 'queued' || turn.status === 'running';const reasoning = activity.reasoning.get(turn.turnId) ?? null;@@ -144,56 +204,52 @@ export const ChatActivityBlock = observer(function ChatActivityBlock({const thinking = isThinking(turn) && !label;const ended = turn.status === 'interrupted' || turn.status === 'error';const requests = turn.requests;- if (!label && !work.length && !switchActions.length && !thinking && !ended && !requests.length)- return null;+ if (!turnShown(activity, turn)) return null;return (- <div className="flex gap-3" data-turn-id={turn.turnId}>- <AgentAvatar- name={agent.name}- iconUrl={agent.iconUrl}- serverId={serverId}- size={28}- className="mt-0.5"- />- <div className="flex min-w-0 flex-1 flex-col pt-0.5">- {label && (- <Reasoning- label={label.label}- shimmer={running && !reasoning?.completedAt}- text={reasoning?.text ?? ''}- />- )}- {!running && work.length >= GROUP_AT ? (- <ToolGroup items={work} turn={turn} activity={activity} />- ) : (- <ToolRows items={work} turn={turn} activity={activity} />- )}- {switchActions.length > 0 && (- <SwitchActions items={switchActions} turn={turn} activity={activity} />- )}- {thinking && (+ <AgentRow+ agent={agent}+ serverId={serverId}+ head={head}+ data-turn-id={turn.turnId}+ className={className}+ >+ {label && (+ <Reasoning+ label={label.label}+ shimmer={running && !reasoning?.completedAt}+ text={reasoning?.text ?? ''}+ />+ )}+ {!running && work.length >= GROUP_AT ? (+ <ToolGroup items={work} turn={turn} activity={activity} />+ ) : (+ <ToolRows items={work} turn={turn} activity={activity} />+ )}+ {switchActions.length > 0 && (+ <SwitchActions items={switchActions} turn={turn} activity={activity} />+ )}+ {thinking && (+ <WorkLogRow+ icon={<ThinkingIcon />}+ label={turn.status === 'queued' ? 'Queued…' : 'Thinking…'}+ active+ />+ )}+ {ended && (+ <div role="status"><WorkLogRow- icon={<ThinkingIcon />}- label={turn.status === 'queued' ? 'Queued…' : 'Thinking…'}- active+ icon={<FailedIcon />}+ label={turnEndLabel(+ turn.status === 'interrupted' ? 'Stopped' : 'The turn ended with an error',+ endReason+ )}+ title={endReason ?? undefined}+ tone="failed"/>- )}- {ended && (- <div role="status">- <WorkLogRow- icon={<FailedIcon />}- label={turnEndLabel(- turn.status === 'interrupted' ? 'Stopped' : 'The turn ended with an error',- endReason- )}- title={endReason ?? undefined}- tone="failed"- />- </div>- )}- {requests.length > 0 && <ChatRequests activity={activity} requests={requests} />}- </div>- </div>+ </div>+ )}+ {requests.length > 0 && <ChatRequests activity={activity} requests={requests} />}+ </AgentRow>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsxindex 456786483..ff92ede33 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx@@ -3,16 +3,14 @@ import { observer } from 'mobx-react-lite';import { useEffect, useRef, useState } from 'react';import { reportBuddyMessage } from '@renderer/features/switch-buddy/buddy-telemetry';import { isEditableTarget } from '@renderer/lib/hooks/use-arrow-key-navigation';-import { rpc } from '@renderer/lib/ipc';import { modalStore } from '@renderer/lib/modal/modal-store';import { Button } from '@renderer/lib/ui/button';import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@renderer/lib/ui/popover';import { type ChatAgent, type ChatMessage, chatAgentLabel } from '@shared/core/chats/chats';import { snippetOf } from '../chat-threads';-import { agentChatsFlag } from '../stores/agent-chats-flag';+import { isInterruptAck } from '../stop-rows';import type { AgentActivity, ControlRequest } from '../stores/chat-activity-store';import type { ChatFile, ChatTimeline } from '../stores/chat-timeline-store';-import { createChatWarmer } from '../stores/chat-warmer';import { chatTitler } from '../stores/chats';import {PromptInput,@@ -34,12 +32,6 @@ function chatFile(file: File): ChatFile {return { name: file.name, type: file.type, size: file.size, read: () => toBase64(file) };}-/** Starts the agent's session while its user types, so the first message does not wait for it. */-const warmChat = createChatWarmer(- (serverId, agentId, roomId) => rpc.chats.warm({ serverId, agentId, roomId }),- Date.now-);-/** Drafts by chat, so a draft outlives navigating away. */const drafts = new Map<string, string>();@@ -83,6 +75,14 @@ const ControlStatus = observer(function ControlStatus({: undefined;const failed = control.state === 'failed';const unknown = control.state === 'unknown';+ // The turn's "Stopped" row says a Stop worked; only its failures show here.+ if (+ control.command === 'interrupt' &&+ !failed &&+ !unknown &&+ (!reply || isInterruptAck(reply))+ )+ return null;return (<divkey={control.requestId}@@ -292,8 +292,6 @@ export const ChatComposer = observer(function ChatComposer({value={draft}disabled={disabled !== null}onChange={(event) => {- if (!draft && event.target.value && agent && agents.length === 1)- if (agentChatsFlag(serverId)) void warmChat(serverId, agent.id, timeline.roomId);setDraft(event.target.value);}}/>diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsxindex c6283eea0..89166f6a5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx@@ -37,6 +37,7 @@ export const ChatRow = observer(function ChatRow({}) {const [menuOpen, setMenuOpen] = useState(false);const busy = chatBusy(serverId, chat);+ const actions = chatActions(serverId, chat);return (<SidebarMenuRow className="group/row justify-between" isActive={isActive} onClick={onOpen}><div className="flex h-6 min-w-0 flex-1 items-center gap-1">@@ -57,20 +58,22 @@ export const ChatRow = observer(function ChatRow({) : null}</span>)}- <DropdownMenu onOpenChange={setMenuOpen}>- <DropdownMenuTrigger- className={`${menuOpen ? 'flex' : 'hidden group-hover/row:flex'} size-6 items-center justify-center rounded-md text-foreground-tertiary-muted hover:bg-background-tertiary-2`}- aria-label={`Actions for ${chat.name}`}- onMouseDown={(event) => event.preventDefault()}- onPointerDown={(event) => event.stopPropagation()}- onClick={(event) => event.stopPropagation()}- >- <MoreHorizontal className="size-3.5" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <ChatActionItems actions={chatActions(serverId, chat)} />- </DropdownMenuContent>- </DropdownMenu>+ {actions.length > 0 && (+ <DropdownMenu onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger+ className={`${menuOpen ? 'flex' : 'hidden group-hover/row:flex'} size-6 items-center justify-center rounded-md text-foreground-tertiary-muted hover:bg-background-tertiary-2`}+ aria-label={`Actions for ${chat.name}`}+ onMouseDown={(event) => event.preventDefault()}+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => event.stopPropagation()}+ >+ <MoreHorizontal className="size-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <ChatActionItems actions={actions} />+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div></SidebarMenuRow>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsxindex 88b5e6812..223f292c7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx@@ -2,9 +2,9 @@ import { format, isToday, isYesterday } from 'date-fns';import { CornerUpLeft, Loader2, RotateCw, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { Fragment, type ReactNode } from 'react';-import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { Button } from '@renderer/lib/ui/button';+import { cn } from '@renderer/utils/utils';import { agentInitials } from '@shared/core/agents/agent-avatar';import type { ChatAgent, ChatMessage } from '@shared/core/chats/chats';import {@@ -15,12 +15,19 @@ import {} from '@shared/core/chats/chats';import { foldTurnEndNotices, placeTurns, type TurnActivity } from '../activity-join';import { messageAnchorId, threadChip } from '../chat-threads';+import { hiddenStopRows } from '../stop-rows';import type { AgentActivity } from '../stores/chat-activity-store';import type { ChatTimeline, PendingSend } from '../stores/chat-timeline-store';import { chatsStore } from '../stores/chats';import { ChatMarkdown } from '../ui/chat-markdown';import { FailedIcon, WorkLogRow } from '../ui/work-log';-import { ChatActivityBlock, ChatRequests, turnEndLabel } from './chat-activity-block';+import {+ AgentRow,+ ChatActivityBlock,+ ChatRequests,+ turnEndLabel,+ turnShown,+} from './chat-activity-block';import { ChatAttachments } from './chat-attachments';/** Messages more than this far apart start a new dated group. */@@ -33,9 +40,9 @@ function dayLabel(date: Date): string {return format(date, 'd MMM yyyy, HH:mm');}-function Separator({ children }: { children: ReactNode }) {+function Separator({ children, className }: { children: ReactNode; className?: string }) {return (- <div className="flex items-center gap-3 text-xs text-foreground-passive">+ <div className={cn('flex items-center gap-3 text-xs text-foreground-passive', className)}><span className="h-px flex-1 bg-border" />{children}<span className="h-px flex-1 bg-border" />@@ -153,6 +160,7 @@ export const ChatTimelineView = observer(function ChatTimelineView({]));const liveNotices = liveSessionStartingNotices(timeline.messages, turnAgents);+ const stopRows = hiddenStopRows(timeline.messages);// Open requests whose turn shows under no loaded message still need an answer.const shownRequests = new Set([...blocksByAnchor.values()].flatMap((blocks) =>@@ -160,10 +168,25 @@ export const ChatTimelineView = observer(function ChatTimelineView({));let previous: Date | null = null;+ /** The agent whose block the last row belongs to; its next row shows no avatar or name. */+ let blockAgent: string | null = null;+ const startsBlock = (agentId: string | null) => {+ const head = agentId === null || agentId !== blockAgent;+ blockAgent = agentId;+ return head;+ };+ let isFirstElement = true;+ const spacing = (isNewBlock: boolean = true): string => {+ if (isFirstElement) {+ isFirstElement = false;+ return '';+ }+ return isNewBlock ? 'mt-5' : 'mt-1.5';+ };return (- <div className="flex flex-col gap-5">+ <div className="flex flex-col">{timeline.hasMore && (- <div className="flex justify-center">+ <div className={cn('flex justify-center', spacing())}><Buttonsize="sm"variant="ghost"@@ -177,71 +200,78 @@ export const ChatTimelineView = observer(function ChatTimelineView({{timeline.messages.map((message) => {const notice = isSessionStartingNotice(message);if (notice && !liveNotices.has(message.messageId)) return null;- if (foldedNotices.has(message.messageId)) return null;+ if (foldedNotices.has(message.messageId) || stopRows.has(message.messageId)) return null;const ended = turnEndNotice(message);const sentAt = new Date(message.sentAt);- const separator =- previous === null || sentAt.getTime() - previous.getTime() > GROUP_GAP_MS ? (- <Separator>{dayLabel(sentAt)}</Separator>- ) : null;+ // The conversation's first message gets no separator above it; a later group does.+ const newGroup =+ previous === null+ ? timeline.hasMore+ : sentAt.getTime() - previous.getTime() > GROUP_GAP_MS;+ const separator = newGroup ? (+ <Separator className={spacing()}>{dayLabel(sentAt)}</Separator>+ ) : null;previous = sentAt;+ if (separator) blockAgent = null;const chip = threadChip(message, find);const turns = turnsByMessage.get(message.messageId) ?? [];const agent = agentOf(message.sender.agentId);const mine = message.sender.userId !== null && message.sender.userId === myUserId;+ const agentLabel = {+ name: agent ? chatAgentLabel(agent) : message.sender.name,+ iconUrl: agent?.iconUrl ?? null,+ };+ const agentRow = notice || ended !== null || message.sender.kind === 'agent';+ const head = startsBlock(agentRow ? message.sender.agentId : null);return (<Fragment key={message.messageId}>{separator}{notice ? (- <div id={messageAnchorId(message.messageId)} className="flex gap-3" role="status">- <AgentAvatar- name={agent ? chatAgentLabel(agent) : message.sender.name}- iconUrl={agent?.iconUrl ?? null}- serverId={serverId}- size={28}- className="mt-0.5"+ <AgentRow+ id={messageAnchorId(message.messageId)}+ className={spacing(head)}+ agent={agentLabel}+ serverId={serverId}+ head={head}+ role="status"+ >+ <WorkLogRow+ icon={<Loader2 aria-hidden className="size-3.5 animate-spin" />}+ label={+ agents.length > 1+ ? `${message.sender.name} is starting a session…`+ : 'Starting a session…'+ }+ active/>- <div className="flex min-w-0 flex-1 flex-col pt-0.5">- <WorkLogRow- icon={<Loader2 aria-hidden className="size-3.5 animate-spin" />}- label={- agents.length > 1- ? `${message.sender.name} is starting a session…`- : 'Starting a session…'- }- active- />- </div>- </div>+ </AgentRow>) : ended ? (- <div id={messageAnchorId(message.messageId)} className="flex gap-3" role="status">- <AgentAvatar- name={agent ? chatAgentLabel(agent) : message.sender.name}- iconUrl={agent?.iconUrl ?? null}- serverId={serverId}- size={28}- className="mt-0.5"+ <AgentRow+ id={messageAnchorId(message.messageId)}+ className={spacing(head)}+ agent={agentLabel}+ serverId={serverId}+ head={head}+ role="status"+ >+ <WorkLogRow+ icon={<FailedIcon />}+ label={turnEndLabel(+ ended.outcome === 'interrupted'+ ? 'Stopped'+ : ended.outcome === 'failed'+ ? 'The turn ended with an error'+ : 'Finished without replying',+ ended.reason+ )}+ title={ended.reason ?? undefined}+ tone={ended.outcome === 'completed' ? 'passive' : 'failed'}/>- <div className="flex min-w-0 flex-1 flex-col pt-0.5">- <WorkLogRow- icon={<FailedIcon />}- label={turnEndLabel(- ended.outcome === 'interrupted'- ? 'Stopped'- : ended.outcome === 'failed'- ? 'The turn ended with an error'- : 'Finished without replying',- ended.reason- )}- title={ended.reason ?? undefined}- tone={ended.outcome === 'completed' ? 'passive' : 'failed'}- />- </div>- </div>+ </AgentRow>) : message.sender.kind === 'human' && mine ? (<divid={messageAnchorId(message.messageId)}- className="group/row flex flex-col items-end gap-1"+ className={cn('group/row flex flex-col items-end gap-1', spacing())}>{chip && <ThreadChipButton chip={chip} />}<div className="flex max-w-[85%] items-start gap-1">@@ -261,7 +291,10 @@ export const ChatTimelineView = observer(function ChatTimelineView({</span></div>) : message.sender.kind === 'human' ? (- <div id={messageAnchorId(message.messageId)} className="group/row flex gap-3">+ <div+ id={messageAnchorId(message.messageId)}+ className={cn('group/row flex gap-3', spacing())}+ ><PersonAvatar name={message.sender.name} /><div className="flex max-w-[85%] min-w-0 flex-col items-start gap-1">{chip && <ThreadChipButton chip={chip} />}@@ -288,21 +321,16 @@ export const ChatTimelineView = observer(function ChatTimelineView({<ReplyButton onReply={() => onReply(message)} /></div>) : message.sender.kind === 'agent' ? (- <div id={messageAnchorId(message.messageId)} className="group/row flex gap-3">- <AgentAvatar- name={agent ? chatAgentLabel(agent) : message.sender.name}- iconUrl={agent?.iconUrl ?? null}- serverId={serverId}- size={28}- className="mt-0.5"- />- <div className="flex min-w-0 flex-1 flex-col gap-1">+ <AgentRow+ id={messageAnchorId(message.messageId)}+ className={cn('group/row', spacing(head))}+ agent={agentLabel}+ serverId={serverId}+ head={head}+ trailing={<ReplyButton onReply={() => onReply(message)} />}+ >+ <div className="flex flex-col gap-1">{chip && <ThreadChipButton chip={chip} />}- {agents.length > 1 && (- <span className="text-xs font-medium text-foreground-muted">- {message.sender.name}- </span>- )}<div className="text-sm leading-relaxed"><ChatMarkdown>{message.body}</ChatMarkdown></div>@@ -312,18 +340,18 @@ export const ChatTimelineView = observer(function ChatTimelineView({attachments={message.attachments}/></div>- <ReplyButton onReply={() => onReply(message)} />- </div>+ </AgentRow>) : (<pid={messageAnchorId(message.messageId)}- className="text-center text-xs text-foreground-muted"+ className={cn('text-center text-xs text-foreground-muted', spacing())}>{message.body}</p>)}{(blocksByAnchor.get(message.messageId) ?? []).map(({ activity, turn }) => {const turnAgent = agentOf(activity.agentId);+ const head = turnShown(activity, turn) && startsBlock(activity.agentId);return (<ChatActivityBlockserverId={serverId}@@ -331,10 +359,12 @@ export const ChatTimelineView = observer(function ChatTimelineView({activity={activity}turn={turn}endReason={endReasons.get(`${activity.agentId}:${turn.turnId}`) ?? null}+ head={head}agent={{name: turnAgent ? chatAgentLabel(turnAgent) : activity.agentId,iconUrl: turnAgent?.iconUrl ?? null,}}+ className={spacing(head)}/>);})}@@ -347,23 +377,30 @@ export const ChatTimelineView = observer(function ChatTimelineView({);if (!requests.length) return null;const agent = agentOf(activity.agentId);+ const head = startsBlock(activity.agentId);return (- <div key={`requests:${activity.agentId}`} className="flex gap-3">- <AgentAvatar- name={agent ? chatAgentLabel(agent) : activity.agentId}- iconUrl={agent?.iconUrl ?? null}- serverId={serverId}- size={28}- className="mt-0.5"- />- <div className="flex min-w-0 flex-1 flex-col pt-0.5">- <ChatRequests activity={activity} requests={requests} />- </div>- </div>+ <AgentRow+ key={`requests:${activity.agentId}`}+ agent={{+ name: agent ? chatAgentLabel(agent) : activity.agentId,+ iconUrl: agent?.iconUrl ?? null,+ }}+ serverId={serverId}+ head={head}+ className={spacing(head)}+ >+ <ChatRequests activity={activity} requests={requests} />+ </AgentRow>);})}{timeline.pending.map((send) => (- <PendingBubble key={send.requestId} timeline={timeline} send={send} find={find} />+ <PendingBubble+ key={send.requestId}+ timeline={timeline}+ send={send}+ find={find}+ className={spacing()}+ />))}</div>);@@ -373,16 +410,21 @@ const PendingBubble = observer(function PendingBubble({timeline,send,find,+ className,}: {timeline: ChatTimeline;send: PendingSend;find: (messageId: string) => ChatMessage | undefined;+ className?: string;}) {const chip = send.threadRootId? threadChip({ threadRootId: send.threadRootId, messageId: send.requestId }, find): null;return (- <div className="flex flex-col items-end gap-1" aria-busy={send.state === 'sending'}>+ <div+ className={cn('flex flex-col items-end gap-1', className)}+ aria-busy={send.state === 'sending'}+ >{chip && <ThreadChipButton chip={chip} />}<div className="max-w-[85%] rounded-2xl bg-background-1 px-4 py-2.5 text-sm leading-relaxed break-words whitespace-pre-wrap opacity-70">{send.body}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-redirect.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-redirect.tsxindex 8fe6ec9d9..29b8aedd0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-redirect.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-redirect.tsx@@ -1,6 +1,5 @@import { observer } from 'mobx-react-lite';import { useEffect } from 'react';-import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';@@ -36,10 +35,8 @@ export const ConsoleChatRedirect = observer(function ConsoleChatRedirect({entry.viewId === 'room' &&(entry.params as { roomId?: string }).roomId === roomId);- if (route.viewId === 'managedAgent') {- agentTabStore.setTab(agent.id, 'chats');- appState.navigation.navigate('managedAgent', route.params);- } else appState.navigation.navigate('chat', route.params);+ if (route.viewId === 'managedAgent') appState.navigation.navigate('managedAgent', route.params);+ else appState.navigation.navigate('chat', route.params);}, [enabled, serverId, roomId, agent, isManaged, managed.isLoading]);return null;diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-route.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-route.tsindex abb6942b1..d02d5275c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-route.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-route.ts@@ -8,8 +8,8 @@ export type ConsoleChatRoute =| { viewId: 'chat'; params: { serverId: string; roomId: string; agentId: string } };/**- * Where a 1-1 Console chat opens: on its agent's Chats tab when the agent is a- * managed agent, which is the only agent page with that tab, else on its own.+ * Where a 1-1 Console chat opens: on its agent's page when the agent is a+ * managed agent, which is the only agent page with chats, else on its own.*/export function consoleChatRoute(serverId: string,diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.tsindex 1c0d34afe..9e267d8f7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts@@ -1,5 +1,6 @@import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';+import { log } from '@renderer/utils/logger';import { focusComposerWhenOpened } from './components/chat-composer';import { chatsStore, chatTitler } from './stores/chats';import { DirectChatStarter } from './stores/direct-chat-starter';@@ -25,6 +26,12 @@ export const directChats = new DirectChatStarter({opened: (chat) => {focusComposerWhenOpened(chat.roomId);},+ warm: (serverId, agentId, roomId) =>+ void rpc.chats+ .warm({ serverId, agentId, roomId })+ .catch((error: unknown) =>+ log.warn('Could not ask for the agent’s session in a reused chat', { roomId, error })+ ),failed: (message) =>toast({ title: 'Could not start the chat', description: message, variant: 'destructive' }),findEmpty: (agentId) => emptyChatFinder.find(agentId),diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stop-rows.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stop-rows.tsnew file mode 100644index 000000000..fe0919a9a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stop-rows.ts@@ -0,0 +1,36 @@+import type { ChatMessage } from '@shared/core/chats/chats';++/**+ * A Stop is posted as `!interrupt @agent` and the agent acknowledges it in a+ * thread rooted at the command. The turn's own "Stopped" row already says it+ * stopped, so the command and that acknowledgement are not shown. Any other+ * answer (it could not be stopped) is shown with its command.+ */++/** The agent's in-room answer to an interrupt it carried out (core's `_INTERRUPT.ack`). */+export const INTERRUPT_ACK_MESSAGE = 'Interrupted my current turn.';++type Row = Pick<ChatMessage, 'messageId' | 'threadRootId' | 'body' | 'sender'>;++export function isInterruptAck(message: Pick<ChatMessage, 'body' | 'sender'>): boolean {+ return message.sender.kind !== 'human' && message.body.startsWith(INTERRUPT_ACK_MESSAGE);+}++function isInterruptCommand(message: Row): boolean {+ return message.sender.kind === 'human' && /^!interrupt(\s|$)/.test(message.body.trim());+}++/** Ids of the Stop commands and their acknowledgements to leave out of the transcript. */+export function hiddenStopRows(messages: readonly Row[]): Set<string> {+ const hidden = new Set<string>();+ for (const command of messages) {+ if (!isInterruptCommand(command)) continue;+ const answers = messages.filter(+ (each) => each.threadRootId === command.messageId && each.sender.kind !== 'human'+ );+ if (!answers.every(isInterruptAck)) continue;+ hidden.add(command.messageId);+ for (const answer of answers) hidden.add(answer.messageId);+ }+ return hidden;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.test.tsdeleted file mode 100644index 6b9114436..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import { createChatWarmer, WARM_INTERVAL_MS } from './chat-warmer';--vi.mock('@renderer/utils/logger', () => ({ log: { warn: vi.fn() } }));--describe('createChatWarmer', () => {- it('asks once per chat per interval, and not while an ask is under way', async () => {- let clock = 0;- let finish!: () => void;- const warm = vi.fn(- () =>- new Promise<void>((resolve) => {- finish = resolve;- })- );- const warmChat = createChatWarmer(warm, () => clock);-- const first = warmChat('s', 'a', 'room');- void warmChat('s', 'a', 'room');- clock = WARM_INTERVAL_MS + 1;- void warmChat('s', 'a', 'room');- expect(warm).toHaveBeenCalledTimes(1);- finish();- await first;-- clock = WARM_INTERVAL_MS - 1;- await warmChat('s', 'a', 'room');- expect(warm).toHaveBeenCalledTimes(1);- void warmChat('s', 'a', 'other-room');- expect(warm).toHaveBeenCalledTimes(2);- finish();-- clock = WARM_INTERVAL_MS;- void warmChat('s', 'a', 'room');- expect(warm).toHaveBeenCalledTimes(3);- finish();- });-- it('swallows a failed ask and asks again after the interval', async () => {- let clock = 0;- const warm = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined);- const warmChat = createChatWarmer(warm, () => clock);- await warmChat('s', 'a', 'room');- await warmChat('s', 'a', 'room');- expect(warm).toHaveBeenCalledTimes(1);- clock = WARM_INTERVAL_MS;- await warmChat('s', 'a', 'room');- expect(warm).toHaveBeenCalledTimes(2);- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.tsdeleted file mode 100644index 07598517f..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.ts+++ /dev/null@@ -1,29 +0,0 @@-import { log } from '@renderer/utils/logger';--/** How long after warming a chat its agent's session is not asked for again. */-export const WARM_INTERVAL_MS = 3 * 60_000;--type Warm = (serverId: string, agentId: string, roomId: string) => Promise<void>;--/**- * Asks for a chat's session at most once per `WARM_INTERVAL_MS`, and not- * while an ask is still under way.- */-export function createChatWarmer(warm: Warm, now: () => number): Warm {- const last = new Map<string, number>();- const asking = new Set<string>();- return async (serverId, agentId, roomId) => {- const key = JSON.stringify([serverId, agentId, roomId]);- const at = last.get(key);- if (asking.has(key) || (at !== undefined && now() - at < WARM_INTERVAL_MS)) return;- last.set(key, now());- asking.add(key);- try {- await warm(serverId, agentId, roomId);- } catch (error) {- log.warn('Could not ask for the agent’s session while typing', { roomId, error });- } finally {- asking.delete(key);- }- };-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.tsindex 4455e7797..8f5d8b1ae 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts@@ -1,4 +1,5 @@import { makeAutoObservable, reaction, runInAction } from 'mobx';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { failureText } from '@renderer/lib/errors/describe-failure';import {chatMessageChannel,@@ -32,6 +33,8 @@ export type ChatsApi = {list: (serverId: string) => Promise<ChatSummary[]>;identity: (serverId: string) => Promise<{ userId: string; tenantId: string | null }>;timeline: (serverId: string) => TimelineApi;+ archive: (serverId: string, roomId: string) => Promise<void>;+ delete: (serverId: string, roomId: string) => Promise<void>;};export type ChatsEvents = {@@ -151,9 +154,18 @@ export class ChatsStore {if (serverId === this.serverId) this.upsert(chat);}- /** Hidden by the person: off the list until a newer message brings it back. */- hide(roomId: string): void {- this.chats.delete(roomId);+ /** Archived for everyone in it; throws, leaving the chat listed, if the server refuses. */+ async archive(serverId: string, roomId: string): Promise<void> {+ await this.api.archive(serverId, roomId);+ this.remove(roomId, 'access');+ await switchRoomsStore.refreshRoomState();+ }++ /** Deleted with its messages for everyone; throws, leaving the chat listed, if the server refuses. */+ async delete(serverId: string, roomId: string): Promise<void> {+ await this.api.delete(serverId, roomId);+ this.remove(roomId, 'access');+ await switchRoomsStore.refreshRoomState();}message(serverId: string, message: ChatMessage): void {diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.tsindex b856a247b..862decd19 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts@@ -27,6 +27,8 @@ export const chatsStore = new ChatsStore(send: (roomId, input) => rpc.chats.send({ serverId, roomId, ...input }),newId: () => crypto.randomUUID(),}),+ archive: (serverId, roomId) => rpc.chats.archive(serverId, roomId),+ delete: (serverId, roomId) => rpc.chats.delete(serverId, roomId),},chatsEventsFrom(events));diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.tsindex 0ab599347..4b9670c88 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts@@ -11,6 +11,8 @@ export type DirectChatStarterDeps = {}) => Promise<ChatSummary>;created: (serverId: string, chat: ChatSummary) => void;opened: (chat: ChatSummary) => void;+ /** Ask for the agent's session in a reused chat; creating one asks already. */+ warm: (serverId: string, agentId: string, roomId: string) => void;failed: (message: string) => void;findEmpty: (agentId: string) => ChatSummary | null;newId: () => string;@@ -18,7 +20,8 @@ export type DirectChatStarterDeps = {/*** Starts an unnamed direct chat with one agent. Reuses an existing empty chat- * (one where the user has sent no messages) if one exists. A second start for+ * (one where the user has sent no messages) if one exists, asking again for+ * its agent's session, which may have stopped since. A second start for* the same agent while one is in flight is ignored. After a failure that may* have landed, the next start reuses its request id, so it resumes that chat* rather than making another.@@ -33,6 +36,7 @@ export class DirectChatStarter {const existing = this.deps.findEmpty(agentId);if (existing) {this.deps.opened(existing);+ this.deps.warm(serverId, agentId, existing.roomId);return existing;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.tsindex fa5ba4638..2dfeaaa87 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts@@ -239,6 +239,27 @@ describe('EmptyChatFinder', () => {expect(finder.find('agent-1')).toBe(chat);});+ it('returns chat named "New chat" with an agent greeting', () => {+ const chat = makeChat({+ roomId: 'room-1',+ name: 'New chat',+ agents: [{ id: 'agent-1', name: 'Agent', displayName: null, iconUrl: null, provider: null }],+ lastMessage: {+ seq: 1,+ sentAt: '2024-01-01T00:00:00Z',+ preview: 'Hello',+ senderName: 'Agent',+ },+ });+ const finder = new EmptyChatFinder({+ chatsOfAgent: () => [chat],+ userId: () => 'user-1',+ timeline: () => undefined,+ });++ expect(finder.find('agent-1')).toBe(chat);+ });+it('returns chat with default name using displayName and agent greeting', () => {const chat = makeChat({roomId: 'room-1',diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.tsindex 10fd1ee05..6d97eaf9a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.ts@@ -36,18 +36,18 @@ export class EmptyChatFinder {if (chat.lastMessage === null) return true;- const defaultName = this.defaultChatName(chat);const lastMessageFromAgent = chat.agents.some((agent) =>chat.lastMessage?.senderName === agent.name ||chat.lastMessage?.senderName === agent.displayName);- return chat.name === defaultName && lastMessageFromAgent;+ return this.hasDefaultName(chat) && lastMessageFromAgent;}- private defaultChatName(chat: ChatSummary): string {+ /** "New chat" now; "Chat with <agents>" for chats made before that default. */+ private hasDefaultName(chat: ChatSummary): boolean {const agentNames = chat.agents.map((agent) => agent.displayName || agent.name).join(', ');- return `Chat with ${agentNames}`;+ return chat.name === 'New chat' || chat.name === `Chat with ${agentNames}`;}}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/prompt-input.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/prompt-input.tsxindex 97951aa1f..440351a60 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/prompt-input.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/prompt-input.tsx@@ -145,9 +145,10 @@ export function PromptInputButton({export type PromptInputStatus = 'idle' | 'sending' | 'running';/**- * Send while idle, a spinner while a send is in flight, and Stop while the agent- * is running. A Stop that cannot be honoured stays visible but disabled, with- * the reason on hover — it is kept focusable so the tooltip can still be read.+ * Send while idle, a spinner while a send is in flight, and a Stop icon in the+ * same round button while the agent is running. A Stop that cannot be honoured+ * stays visible but disabled, with the reason on hover — it is kept focusable so+ * the tooltip can still be read.*/export function PromptInputSubmit({status,@@ -162,28 +163,29 @@ export function PromptInputSubmit({disabled?: boolean;className?: string;}) {+ const shape =+ 'rounded-xl border-none bg-(--composer-send-bg) text-(--composer-send-fg) hover:bg-(--composer-send-bg-hover) hover:text-(--composer-send-fg) active:bg-(--composer-send-bg-active) disabled:opacity-50';if (status === 'running') {const reason = stopDisabledReason ?? null;- const stop = (- <Button- type="button"- variant="outline"- size="sm"- className={cn('gap-1.5', className)}- disabled={reason !== null || disabled || !onStop}- focusableWhenDisabled- title={reason ?? undefined}- onClick={onStop}- >- <SquareIcon className="size-3 fill-current" />- Stop- </Button>- );- if (reason === null) return stop;return (<Tooltip>- <TooltipTrigger render={stop} />- <TooltipContent>{reason}</TooltipContent>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className={cn(shape, className)}+ disabled={reason !== null || disabled || !onStop}+ focusableWhenDisabled+ aria-label="Stop reply"+ onClick={onStop}+ >+ <SquareIcon className="size-3 fill-current" />+ </Button>+ }+ />+ <TooltipContent>{reason ?? 'Stop'}</TooltipContent></Tooltip>);}@@ -194,10 +196,7 @@ export function PromptInputSubmit({type="submit"variant="ghost"size="icon-sm"- className={cn(- 'rounded-xl border-none bg-(--composer-send-bg) text-(--composer-send-fg) hover:bg-(--composer-send-bg-hover) active:bg-(--composer-send-bg-active) disabled:opacity-50',- className- )}+ className={cn(shape, className)}disabled={sending || disabled}aria-label={sending ? 'Sending' : 'Send'}title={sending ? 'Sending' : 'Send'}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.tsindex 37e7bed18..82f468022 100644--- a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.ts@@ -1,6 +1,5 @@import { describe, expect, it, vi } from 'vitest';import { LocalAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';-import { AgentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';import type { Agent } from '@shared/core/agents/agents';import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';@@ -79,37 +78,35 @@ describe("a Used by chip's link", () => {});});-describe("opening an agent's Connections tab", () => {- const stores = () => ({ local: new LocalAgentTabStore(), managed: new AgentTabStore() });-+describe("opening an agent's Connections", () => {it('selects the tab on a local agent, then opens its page', () => {- const tabs = stores();+ const tabs = new LocalAgentTabStore();const navigate = vi.fn();openAgentConnections(agentLinkFor('switch-local', [LOCAL], null) as Parameters<typeof openAgentConnections>[0],navigate as unknown as NavigateFnTyped,tabs);- expect(tabs.local.tabFor('local-1')).toBe('connections');+ expect(tabs.tabFor('local-1')).toBe('connections');expect(navigate).toHaveBeenCalledWith('location', {locationId: 'location-1',agentName: 'm1-cc',});});- it('selects the tab on a managed agent, then opens its page', () => {- const tabs = stores();+ it("opens a managed agent's page on its Connections section", () => {+ const tabs = new LocalAgentTabStore();const navigate = vi.fn();openAgentConnections(agentLinkFor('switch-managed', [], [MANAGED]) as Parameters<typeof openAgentConnections>[0],navigate as unknown as NavigateFnTyped,tabs);- expect(tabs.managed.tabFor('switch-managed')).toBe('connections');expect(navigate).toHaveBeenCalledWith('managedAgent', {serverId: 'server',agentId: 'switch-managed',name: 'M3',+ section: 'connections',});});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.tsindex eddc7e585..af50a11a9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.ts@@ -1,12 +1,11 @@import type { LocalAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';-import type { AgentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import { managedAgentLabel } from '@renderer/features/managed-agents/managed-agent-state';import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';import type { Agent } from '@shared/core/agents/agents';import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';/**- * Where an agent named on a connector's profile leads: its Connections tab,+ * Where an agent named on a connector's profile leads: its Connections,* on the page this Console shows it on, or nowhere for an agent that lives in* another Console.*/@@ -48,17 +47,21 @@ export function agentLinkFor(return { kind: 'elsewhere', title: ELSEWHERE_TITLE };}-/** Opens a linked agent's page on its Connections tab. */+/** Opens a linked agent's page on its Connections. */export function openAgentConnections(link: Exclude<AgentLink, { kind: 'elsewhere' }>,navigate: NavigateFnTyped,- tabs: { local: LocalAgentTabStore; managed: AgentTabStore }+ localTabs: LocalAgentTabStore): void {if (link.kind === 'local') {- tabs.local.setTab(link.agentId, 'connections');+ localTabs.setTab(link.agentId, 'connections');navigate('location', { locationId: link.locationId, agentName: link.agentName });return;}- tabs.managed.setTab(link.agentId, 'connections');- navigate('managedAgent', { serverId: link.serverId, agentId: link.agentId, name: link.name });+ navigate('managedAgent', {+ serverId: link.serverId,+ agentId: link.agentId,+ name: link.name,+ section: 'connections',+ });}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsxindex fadd2636b..06c41e1a1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsx@@ -3,7 +3,6 @@ import { observer } from 'mobx-react-lite';import { useEffect, useState } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { localAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';-import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { agentProviderLabelFor } from '@renderer/lib/components/agent-picker';@@ -53,7 +52,7 @@ import {* heading with the count, a card per agent, and an "Add agent" that opens a* search of the person's other agents under the cards. Adding one turns the* service on for it there and then; the cross on a card turns it off again.- * A card opens the agent's Connections tab; an agent from another Console has+ * A card opens the agent's Connections; an agent from another Console has* no page here, so its card is plain.*/export const ConnectorAgentsSection = observer(function ConnectorAgentsSection({@@ -190,13 +189,8 @@ export const ConnectorAgentsSection = observer(function ConnectorAgentsSection({) : (<buttontype="button"- title={`Open ${agent.name}'s Connections tab`}- onClick={() =>- openAgentConnections(link, navigate, {- local: localAgentTabStore,- managed: agentTabStore,- })- }+ title={`Open ${agent.name}'s Connections`}+ onClick={() => openAgentConnections(link, navigate, localAgentTabStore)}className="focus-visible:ring-ring flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-sm text-left focus-visible:ring-2 focus-visible:outline-none">{/* Stretched over the card, so the whole card opens the agent while@@ -243,12 +237,12 @@ export const ConnectorAgentsSection = observer(function ConnectorAgentsSection({)}{!offersAddAgent(connection) && (<p className="text-xs text-foreground-muted">- Turn it on for an agent from the agent's Connections tab.+ Turn it on for an agent from the agent's Connections.</p>)}{connection.slug === 'github' && usedBy.length > 0 && (<p className="text-xs text-foreground-muted">- Each agent has its own repositories and access, changed on its Connections tab.+ Each agent has its own repositories and access, changed from its Connections.</p>)}</section>@@ -261,7 +255,7 @@ export const ConnectorAgentsSection = observer(function ConnectorAgentsSection({* addresses it would have it act as the person. For GitHub, the repositories* and access every added agent gets are chosen above the search, and no* agent can be added until some are; each agent's own choice is on its- * Connections tab.+ * Connections.*/const AddAgentPanel = observer(function AddAgentPanel({serverId,diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsxindex dfd1f6007..db15294ac 100644--- a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsx@@ -35,7 +35,7 @@ export function GitHubAddAgentChoice({</p>) : (<p className="flex-1 text-sm text-foreground-muted">- Agents you add get {summary}. Each can be changed later on its Connections tab.+ Agents you add get {summary}. Each can be changed later from its Connections.</p>)}<Buttondiff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.tsindex 62182b583..189504d88 100644--- a/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.ts@@ -10,7 +10,7 @@ export const OPEN_AGENT_NOTE = 'Others can address it; it would act as you.';* Whether the person adds agents to `entry` from its page: a service a grant* simply switches on, and GitHub, whose grant names repositories chosen above* the agents. A minted service other than GitHub is granted from the agent's- * Connections tab.+ * Connections.*/export function offersAddAgent(entry: ConnectionCatalogEntry): boolean {return entry.pass_through || entry.slug === 'github';@@ -36,10 +36,10 @@ export function addableAgents(agents: ConnectionAgent[], filter: string): Connec/** What the section says when the person has no agents in the workspace. */export function noAgentsText(serviceName: string): string {- return `You have no agents in this workspace yet. Once you add one, turn ${serviceName} on for it from the agent's Connections tab.`;+ return `You have no agents in this workspace yet. Once you add one, turn ${serviceName} on for it from the agent's Connections.`;}/** What stands in for the agents on a server that cannot list them. */export function agentsUnlistedText(serviceName: string): string {- return `This server can't list your agents here. Turn ${serviceName} on for an agent from the agent's Connections tab.`;+ return `This server can't list your agents here. Turn ${serviceName} on for an agent from the agent's Connections.`;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.tsindex 079dec86f..fd5963ccc 100644--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts@@ -3,7 +3,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const navigate = vi.hoisted(() => vi.fn());const showModal = vi.hoisted(() => vi.fn());const toastError = vi.hoisted(() => vi.fn());-const setTab = vi.hoisted(() => vi.fn());const list = vi.hoisted(() => vi.fn());const servers = vi.hoisted(() => ({activeServerId: 'srv-1' as string | null,@@ -27,9 +26,6 @@ const navigation = vi.hoisted(() => ({vi.mock('@renderer/lib/stores/app-state', () => ({ appState: { navigation } }));vi.mock('@renderer/lib/modal/modal-provider', () => ({ showModal }));vi.mock('@renderer/lib/ipc', () => ({ rpc: { managedAgents: { list } } }));-vi.mock('@renderer/features/managed-agents/agent-tab-store', () => ({- agentTabStore: { setTab },-}));vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({switchServersStore: servers,}));@@ -61,14 +57,24 @@ describe('openConsoleLink', () => {expect(showModal).toHaveBeenCalledWith('invitePeopleModal', { workspaceId: 'ws-1' });});- it('opens an agent on the tab it names', async () => {+ it('opens an agent on the section its tab names', async () => {list.mockResolvedValueOnce([{ agentId: 'a-1', name: 'switch-buddy-ada' }]);await openConsoleLink('switchdash://open/agent/a-1?tab=settings');- expect(setTab).toHaveBeenCalledWith('a-1', 'settings');expect(navigate).toHaveBeenCalledWith('managedAgent', {serverId: 'srv-1',agentId: 'a-1',name: 'switch-buddy-ada',+ section: 'settings',+ });+ });++ it('opens an agent on its chat for the Chats tab', async () => {+ list.mockResolvedValueOnce([{ agentId: 'a-1', name: 'reviewer' }]);+ await openConsoleLink('switchdash://open/agent/a-1?tab=chats');+ expect(navigate).toHaveBeenCalledWith('managedAgent', {+ serverId: 'srv-1',+ agentId: 'a-1',+ name: 'reviewer',});});@@ -84,12 +90,12 @@ describe('openConsoleLink', () => {{ agentId: 'a-1', name: 'reviewer' },{ agentId: 'b-1', name: 'switch-buddy-ada' },]);- await openConsoleLink('switchdash://open/buddy?tab=settings');- expect(setTab).toHaveBeenCalledWith('b-1', 'settings');+ await openConsoleLink('switchdash://open/buddy?tab=connections');expect(navigate).toHaveBeenCalledWith('managedAgent', {serverId: 'srv-1',agentId: 'b-1',name: 'switch-buddy-ada',+ section: 'connections',});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.tsindex 5c2173b0b..b9ba38fb6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts@@ -1,5 +1,5 @@import { toast } from 'sonner';-import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';+import { isAgentSection } from '@renderer/features/managed-agents/agent-sections';import type { SettingsPageTab } from '@renderer/features/settings/components/SettingsPage';import { isBuddy } from '@renderer/features/switch-buddy/buddy-identity';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';@@ -127,7 +127,7 @@ async function openOnServer(serverId: string, link: ConsoleLink): Promise<void>}/**- * switch-buddy's page: its agent page once it exists, on the tab the link+ * switch-buddy's page: its agent page once it exists, on the section the link's tab* names, else the page that sets it up, where there are no tabs yet.*/async function openBuddy(serverId: string, tab: string | null): Promise<void> {@@ -137,11 +137,11 @@ async function openBuddy(serverId: string, tab: string | null): Promise<void> {appState.navigation.navigate('switchBuddy', { serverId });return;}- agentTabStore.setTab(buddy.agentId, tab === 'settings' || tab === 'connections' ? tab : 'chats');appState.navigation.navigate('managedAgent', {serverId,agentId: buddy.agentId,name: buddy.name,+ ...(isAgentSection(tab) ? { section: tab } : {}),});}@@ -155,7 +155,10 @@ async function openAgent(serverId: string, agentId: string, tab: string | null):});return;}- if (tab === 'chats' || tab === 'connections' || tab === 'settings')- agentTabStore.setTab(agentId, tab);- appState.navigation.navigate('managedAgent', { serverId, agentId, name: agent.name });+ appState.navigation.navigate('managedAgent', {+ serverId,+ agentId,+ name: agent.name,+ ...(isAgentSection(tab) ? { section: tab } : {}),+ });}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex f96c76a5b..ef244d33d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -20,7 +20,7 @@ import { useParams } from '@renderer/lib/layout/navigation-provider';** It used to be three tabs down a side nav, which asked the reader to know* which of them held what before they could look at anything. The page is short- * enough to scroll instead. The one exception is Connections, a tab of its+ * enough to scroll instead. The one exception is Connections, a page of its* own as on a managed agent's page, for an agent registered on a server with* service connections on.*/@@ -47,6 +47,7 @@ export const ActiveLocation = observer(function ActiveLocation() {return (<AgentEditsProvider><div className="flex min-h-0 w-full flex-1 flex-col">+ <AgentSaveBar /><div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto"><div className="mx-auto flex w-full max-w-[900px] flex-col gap-10 px-8 pb-20"><AgentPageHeader />@@ -55,9 +56,6 @@ export const ActiveLocation = observer(function ActiveLocation() {<SessionList /></div></div>- {/* Outside the scroll area: an edit made at the top of the page should- not need scrolling to the bottom before it can be saved. */}- <AgentSaveBar /></div></AgentEditsProvider>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsxindex 33f57c3ba..e079bd4ea 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx@@ -2,7 +2,6 @@ import { useQueryClient } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { directChats } from '@renderer/features/chats/start-direct-chat';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';@@ -58,7 +57,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {const queryClient = useQueryClient();const { toast } = useToast();const switchAgentId = agent?.switchAgentId ?? null;- // The Chats tab is on a managed agent's page only.+ // A managed agent's page is where its chats are.const managedAgents = useManagedAgents(agent?.serverId ?? null);const chatsEnabled = useFeatureFlags(agent?.serverId).agent_chats;const chatsTab =@@ -129,7 +128,6 @@ export const AgentPageHeader = observer(function AgentPageHeader() {const serverId = agent.serverId as string;const switchAgentId = agent.switchAgentId as string;if (chatsTab) {- agentTabStore.setTab(switchAgentId, 'chats');navigate('managedAgent', { serverId, agentId: switchAgentId, name: title });return;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsxindex 19950db8d..44c57f0e4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsx@@ -12,9 +12,8 @@ import { useAgentEdits } from './agent-edits';* The agent page's pending changes, and what to do about them (CHOO-2228).** Shown only when something is actually unsaved, so the page is not permanently- * wearing a bar it has no use for. It sits outside the scrolling content rather- * than at the end of it: an edit made at the top of a long page would otherwise- * be saveable only by scrolling to the bottom to find out it could be.+ * wearing a bar it has no use for. It sits above the scrolling content, so it+ * stays in view wherever on the page the edit was made.*/export function AgentSaveBar() {const { dirty, saving, saveAll, revertAll } = useAgentEdits();@@ -35,11 +34,11 @@ export function AgentSaveBar() {if (!dirty) return null;return (- <div className="flex shrink-0 items-center justify-between gap-4 border-t border-border bg-background px-8 py-4">- <span className="text-sm text-foreground-muted">Unsaved changes</span>+ <div className="flex shrink-0 items-center justify-between gap-4 border-b border-border-warning bg-background-warning px-8 py-2">+ <span className="text-sm font-medium text-foreground-warning">Unsaved changes</span><div className="flex items-center gap-2"><Button type="button" size="sm" variant="outline" disabled={saving} onClick={revertAll}>- Revert+ Discard</Button><Buttonref={saveRef}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsxindex e8e457211..82ce3b4f1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx@@ -1,21 +1,58 @@-import { ChevronDown, ChevronRight, Plus } from 'lucide-react';+import { ChevronDown, ChevronRight, Plug, Plus, Settings } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { type ReactNode, useEffect, useState } from 'react';+import { type ReactNode, useEffect, useRef, useState } from 'react';import { agentConversations } from '@renderer/features/chats/agent-conversations';import { ChatPanel } from '@renderer/features/chats/components/chat-panel';import { ChatRow } from '@renderer/features/chats/components/chat-row';import { directChats } from '@renderer/features/chats/start-direct-chat';import { chatsStore } from '@renderer/features/chats/stores/chats';import { RoomListRow } from '@renderer/features/sidebar/main-section';-import { SidebarItemMiniButton } from '@renderer/features/sidebar/sidebar-primitives';+import {+ SidebarItemMiniButton,+ SidebarMenuAction,+ SidebarMenuRow,+} from '@renderer/features/sidebar/sidebar-primitives';import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { useParams } from '@renderer/lib/layout/navigation-provider';import { showModal } from '@renderer/lib/modal/modal-provider';import { Button } from '@renderer/lib/ui/button';import { EmptyState } from '@renderer/lib/ui/empty-state';import type { ChatSummary } from '@shared/core/chats/chats';-import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { isCloudMachine, type ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { AgentConnectionsTab, useAgentServiceGrants } from './agent-connections-tab';+import { type AgentSection, agentSections, shownAgentSection } from './agent-sections';+import { shouldAutoStartChat } from './auto-start-chat';+import { ManagedAgentPage } from './managed-agent-page';+import { managedAgentLabel } from './managed-agent-state';++const NAV_ITEMS = [+ { section: 'connections', label: 'Connections', icon: Plug },+ { section: 'settings', label: 'Agent settings', icon: Settings },+] as const satisfies readonly { section: AgentSection; label: string; icon: typeof Settings }[];++export const agentSectionLabel = (section: AgentSection): string =>+ NAV_ITEMS.find((item) => item.section === section)!.label;++/**+ * The sections the agent's page offers, and the one showing: `chosen` from+ * the view's params when it is offered, else none, and a chat shows.+ */+export function useAgentSection(+ serverId: string,+ agent: ManagedAgentView | null,+ chosen: AgentSection | undefined+) {+ const flags = useFeatureFlags(serverId);+ const grants = useAgentServiceGrants(+ flags.service_connections,+ agent?.workspaceId ?? null,+ agent?.agentId ?? ''+ );+ const sections = agentSections(flags.service_connections, grants.data);+ return { sections, section: shownAgentSection(chosen, sections) };+}function Section({title,@@ -32,7 +69,7 @@ function Section({const Chevron = open ? ChevronDown : ChevronRight;return (<section aria-label={title} className="flex flex-col gap-[2px] pb-3">- <div className="flex items-center justify-between px-1 pb-1">+ <div className="flex items-center justify-between pr-1 pb-1"><buttontype="button"aria-expanded={open}@@ -59,10 +96,10 @@ function conversationsOf({ serverId, workspaceId, agentId }: ManagedAgentView) {// The chats store follows the window's server; another server's chats are not in it.const agentChats = chatsStore.serverId === serverId ? chatsStore.chatsOfAgent(agentId) : [];const agentRooms = switchRoomsStore.roomsFor(workspaceId, agentId);- return { agentRooms, ...agentConversations(agentChats, agentRooms ?? []) };+ return { agentRooms, ...agentConversations(agentChats, agentRooms ?? [], chatsStore.removed) };}-/** The direct chat open on an agent's Chats tab: the one in the params, else its newest. */+/** The direct chat open on an agent's page: the one in the params, else its newest. */export function openAgentChat(agent: ManagedAgentView,roomId: string | undefined@@ -72,9 +109,10 @@ export function openAgentChat(}/**- * An agent's chats: its direct chats, beside the one open, and the rooms it is- * in, which open in the room view. The open chat is kept in the view's params;- * with none chosen it is the newest direct chat.+ * An agent's page: its navigation (the agent's settings, its direct chats and+ * the rooms it is in, which open in the room view) beside what is selected.+ * The selection is kept in the view's params; with none chosen it is the+ * newest direct chat, and an agent with none gets one started once per visit.*/export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagedAgentView }) {const { params, setParams } = useParams('managedAgent');@@ -85,16 +123,54 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Managconst { agentRooms, direct, rooms } = conversationsOf(agent);const roomsError = switchRoomsStore.errorFor(workspaceId, agentId);+ const { sections, section } = useAgentSection(serverId, agent, params.section);const roomId = openAgentChat(agent, params.roomId)?.roomId ?? null;- const open = (id: string) => setParams({ roomId: id });+ const open = (id: string) => setParams({ roomId: id, section: undefined });const newChat = async () => {const chat = await directChats.start(serverId, agentId);if (chat) open(chat.roomId);};+ const ownServer = chatsStore.serverId === serverId;+ const listing = ownServer && chatsStore.userId === null && !chatsStore.listError;+ const autoStartTried = useRef(false);+ const [autoStarting, setAutoStarting] = useState(false);+ const autoStart = shouldAutoStartChat({+ listed: ownServer && chatsStore.userId !== null,+ listFailed: chatsStore.listError !== null,+ hasDirectChats: direct.length > 0,+ selected: Boolean(params.roomId) || section !== null,+ tried: autoStartTried.current,+ });+ useEffect(() => {+ if (!autoStart) return;+ autoStartTried.current = true;+ setAutoStarting(true);+ void newChat().finally(() => setAutoStarting(false));+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- runs when the decision turns true, not when newChat is redefined+ }, [autoStart]);+return (<div className="flex h-full min-h-0"><div className="flex w-[300px] shrink-0 flex-col overflow-y-auto border-r border-border p-2">+ <nav aria-label="Agent" className="flex flex-col gap-[2px] pb-3">+ {NAV_ITEMS.filter((item) => sections.includes(item.section)).map((item) => (+ <SidebarMenuRow+ key={item.section}+ isActive={section === item.section}+ onClick={() => setParams({ section: item.section })}+ >+ <div className="flex h-6 min-w-0 flex-1 items-center gap-1">+ <span className="flex size-6 shrink-0 items-center justify-center">+ <item.icon className="size-4 text-foreground-muted" />+ </span>+ <SidebarMenuAction className="overflow-hidden">+ <span className="min-w-0 truncate">{item.label}</span>+ </SidebarMenuAction>+ </div>+ </SidebarMenuRow>+ ))}+ </nav><Section title="Direct chats" addLabel="New chat" onAdd={() => void newChat()}>{chatsStore.listError && <Note>{chatsStore.listError}</Note>}{direct.map((chat) => (@@ -102,7 +178,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Managkey={chat.roomId}serverId={serverId}chat={chat}- isActive={chat.roomId === roomId}+ isActive={!section && chat.roomId === roomId}onOpen={() => open(chat.roomId)}/>))}@@ -131,8 +207,17 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag{agentRooms && rooms.length === 0 && <Note>Not in any room yet.</Note>}</Section></div>- <div className="relative min-w-0 flex-1">- {roomId ? (+ <div className="relative flex min-w-0 flex-1 flex-col">+ {section === 'settings' ? (+ <ManagedAgentPage agent={agent} serviceGrants={!sections.includes('connections')} />+ ) : section === 'connections' ? (+ <AgentConnectionsTab+ workspaceId={workspaceId}+ agentId={agentId}+ agentName={managedAgentLabel(agent)}+ cloud={agent.machine !== null && isCloudMachine(agent.machine)}+ />+ ) : roomId ? (<><ChatPanel key={`${serverId}:${roomId}`} serverId={serverId} roomId={roomId} /><div@@ -140,7 +225,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagclassName="pointer-events-none absolute inset-x-0 top-0 z-10 h-6 bg-linear-to-b from-background to-transparent"/></>- ) : (+ ) : listing || autoStart || autoStarting ? null : (<EmptyStatelabel="No chat open"description="Start a chat with this agent."diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.test.tsnew file mode 100644index 000000000..5253cc146--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';+import { agentSections, isAgentSection, shownAgentSection } from './agent-sections';++const GRANTS: ServiceGrants = { grants: [], addressing_open: false };++describe("a managed agent's sections", () => {+ it('offers Connections above Agent settings for an agent whose grants are yours', () => {+ expect(agentSections(true, GRANTS)).toEqual(['connections', 'settings']);+ });++ it('offers Connections while the grants load, since the page lists only your agents', () => {+ expect(agentSections(true, undefined)).toEqual(['connections', 'settings']);+ });++ it("hides Connections for an agent you don't own: the server answers its grants with null", () => {+ expect(agentSections(true, null)).toEqual(['settings']);+ });++ it('hides Connections when the server has service connections off', () => {+ expect(agentSections(false, GRANTS)).toEqual(['settings']);+ });++ it('shows the chosen section, or the chat when Connections was chosen and is no longer offered', () => {+ expect(shownAgentSection('connections', agentSections(true, GRANTS))).toBe('connections');+ expect(shownAgentSection('connections', agentSections(true, null))).toBeNull();+ expect(shownAgentSection('settings', agentSections(false, GRANTS))).toBe('settings');+ expect(shownAgentSection(undefined, agentSections(true, GRANTS))).toBeNull();+ });++ it('accepts only the known sections from a link or saved params', () => {+ expect(isAgentSection('connections')).toBe(true);+ expect(isAgentSection('settings')).toBe(true);+ expect(isAgentSection('chats')).toBe(false);+ expect(isAgentSection(undefined)).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.tsnew file mode 100644index 000000000..16fe5e08c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-sections.ts@@ -0,0 +1,32 @@+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';++/** What an agent's page shows in place of a chat, picked from its navigation. */+export type AgentSection = 'connections' | 'settings';++const AGENT_SECTIONS: readonly AgentSection[] = ['connections', 'settings'];++export function isAgentSection(value: unknown): value is AgentSection {+ return AGENT_SECTIONS.includes(value as AgentSection);+}++/**+ * The sections a managed agent's page offers. Connections needs the server's+ * `service_connections` flag, and goes once the server answers the agent's+ * grants with null: they are not the caller's, so there is nothing to show.+ * While the grants load it is offered, since this page lists only the+ * caller's own agents.+ */+export function agentSections(+ serviceConnections: boolean,+ grants: ServiceGrants | null | undefined+): readonly AgentSection[] {+ return serviceConnections && grants !== null ? ['connections', 'settings'] : ['settings'];+}++/** The section to show: the one chosen, or none (a chat) when it is not offered. */+export function shownAgentSection(+ chosen: AgentSection | undefined,+ sections: readonly AgentSection[]+): AgentSection | null {+ return chosen !== undefined && sections.includes(chosen) ? chosen : null;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.tsdeleted file mode 100644index 12b986382..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts+++ /dev/null@@ -1,28 +0,0 @@-import { makeAutoObservable } from 'mobx';--export type AgentTab = 'chats' | 'connections' | 'settings';--/**- * Which tab the open agent is showing, as the room page's tab is kept: one- * selection, remembered against the agent id, so opening a different agent- * starts on its chats again.- */-export class AgentTabStore {- private agentId: string | null = null;- private tab: AgentTab = 'chats';-- constructor() {- makeAutoObservable(this, {}, { autoBind: true });- }-- tabFor(agentId: string): AgentTab {- return this.agentId === agentId ? this.tab : 'chats';- }-- setTab(agentId: string, tab: AgentTab): void {- this.agentId = agentId;- this.tab = tab;- }-}--export const agentTabStore = new AgentTabStore();diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.tsdeleted file mode 100644index ee7044096..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { describe, expect, it } from 'vitest';-import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';-import { AgentTabStore } from './agent-tab-store';-import { agentTabs, shownAgentTab } from './agent-tabs';--const GRANTS: ServiceGrants = { grants: [], addressing_open: false };--const values = (tabs: ReturnType<typeof agentTabs>) => tabs.map((tab) => tab.value);--describe('the agent tab store', () => {- it('keeps Connections for the agent it was chosen on, and starts another agent on Chats', () => {- const store = new AgentTabStore();- store.setTab('agent-1', 'connections');- expect(store.tabFor('agent-1')).toBe('connections');- expect(store.tabFor('agent-2')).toBe('chats');- });-});--describe("a managed agent's tabs", () => {- it('offers Connections between Chats and Settings for an agent whose grants are yours', () => {- expect(values(agentTabs(true, GRANTS))).toEqual(['chats', 'connections', 'settings']);- });-- it('offers Connections while the grants load, since the page lists only your agents', () => {- expect(values(agentTabs(true, undefined))).toEqual(['chats', 'connections', 'settings']);- });-- it("hides Connections for an agent you don't own: the server answers its grants with null", () => {- expect(values(agentTabs(true, null))).toEqual(['chats', 'settings']);- });-- it('hides Connections when the server has service connections off', () => {- expect(values(agentTabs(false, GRANTS))).toEqual(['chats', 'settings']);- });-- it('shows the chosen tab, or Chats when Connections was chosen and is no longer offered', () => {- expect(shownAgentTab('connections', agentTabs(true, GRANTS))).toBe('connections');- expect(shownAgentTab('connections', agentTabs(true, null))).toBe('chats');- expect(shownAgentTab('settings', agentTabs(false, GRANTS))).toBe('settings');- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.tsdeleted file mode 100644index 02811d191..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.ts+++ /dev/null@@ -1,27 +0,0 @@-import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';-import type { AgentTab } from './agent-tab-store';--export type AgentTabOption = { value: AgentTab; label: string };--const CHATS: AgentTabOption = { value: 'chats', label: 'Chats' };-const CONNECTIONS: AgentTabOption = { value: 'connections', label: 'Connections' };-const SETTINGS: AgentTabOption = { value: 'settings', label: 'Settings' };--/**- * The tabs a managed agent's page offers. Connections needs the server's- * `service_connections` flag, and goes once the server answers the agent's- * grants with null: they are not the caller's, so there is nothing to show.- * While the grants load it is offered, since this page lists only the- * caller's own agents.- */-export function agentTabs(- serviceConnections: boolean,- grants: ServiceGrants | null | undefined-): readonly AgentTabOption[] {- return serviceConnections && grants !== null ? [CHATS, CONNECTIONS, SETTINGS] : [CHATS, SETTINGS];-}--/** The tab to show: the one chosen, or Chats when the chosen one is not offered. */-export function shownAgentTab(chosen: AgentTab, tabs: readonly AgentTabOption[]): AgentTab {- return tabs.some((tab) => tab.value === chosen) ? chosen : 'chats';-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.test.tsnew file mode 100644index 000000000..ccbb339e8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';+import { shouldAutoStartChat } from './auto-start-chat';++const READY = {+ listed: true,+ listFailed: false,+ hasDirectChats: false,+ selected: false,+ tried: false,+};++describe('shouldAutoStartChat', () => {+ it('starts a chat for a listed agent with no direct chats and nothing selected', () => {+ expect(shouldAutoStartChat(READY)).toBe(true);+ });++ it.each([+ ['chats are still loading', { listed: false }],+ ['the chat list failed', { listFailed: true }],+ ['the agent has a direct chat', { hasDirectChats: true }],+ ['something is selected', { selected: true }],+ ['a start was already tried', { tried: true }],+ ])('does not start when %s', (_, change) => {+ expect(shouldAutoStartChat({ ...READY, ...change })).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.tsnew file mode 100644index 000000000..b36ef43bb--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/auto-start-chat.ts@@ -0,0 +1,17 @@+export type AutoStartChatInput = {+ /** The chats store holds this agent's server and has listed its chats. */+ listed: boolean;+ listFailed: boolean;+ hasDirectChats: boolean;+ /** A chat or the settings is selected in the page's params. */+ selected: boolean;+ /** A start was already tried for this agent on this page visit. */+ tried: boolean;+};++/** Whether an agent's page starts a direct chat by itself: once, and only when it has none. */+export function shouldAutoStartChat(input: AutoStartChatInput): boolean {+ return (+ input.listed && !input.listFailed && !input.hasDirectChats && !input.selected && !input.tried+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsxindex cefb482c9..e41526e4a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx@@ -1,5 +1,7 @@import { Cloud, CloudOff, Server, ServerOff } from 'lucide-react';import { observer } from 'mobx-react-lite';+import { byLatestDirectChat } from '@renderer/features/chats/agent-conversations';+import { chatsStore } from '@renderer/features/chats/stores/chats';import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -34,9 +36,14 @@ export const ManagedAgentList = observer(function ManagedAgentList() {</div>);if (!agents.data?.length) return null;+ // The chats store follows one server, and only while agent_chats is on there.+ const chats =+ chatsStore.serverId === serverId && chatsStore.userId !== null+ ? chatsStore.chats.values()+ : null;return (<div className="flex flex-col gap-[2px]" aria-label="Managed agents">- {disconnectedLast(agents.data).map((agent) => (+ {disconnectedLast(byLatestDirectChat(agents.data, chats)).map((agent) => (<ManagedAgentRow key={agent.agentId} agent={agent} />))}</div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsxindex 80c70e57c..4dacf0ba9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx@@ -1,6 +1,6 @@import { useQuery, useQueryClient } from '@tanstack/react-query';import { Plus } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { LocalDirectorySelector } from '@renderer/features/locations/components/add-agent-modal/local-directory-selector';import type {FormState,@@ -10,6 +10,7 @@ import type { ModelCatalogueResult } from '@renderer/features/locations/componenimport {AgentEditsProvider,useAgentEdit,+ useAgentEdits,} from '@renderer/features/locations/components/main-panel/agent-edits';import { AgentInstructionsField } from '@renderer/features/locations/components/main-panel/agent-instructions-section';import { AgentHeaderLayout } from '@renderer/features/locations/components/main-panel/agent-page-header';@@ -26,8 +27,11 @@ import { ServiceGrantsRow } from '@renderer/features/locations/components/settinimport { SettingRow } from '@renderer/features/locations/components/settings-view/sections/setting-row';import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';import { failureText } from '@renderer/lib/errors/describe-failure';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { rpc } from '@renderer/lib/ipc';+import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { appState } from '@renderer/lib/stores/app-state';import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';@@ -55,6 +59,7 @@ import {} from './managed-agent-changes';import { managedAgentLabel } from './managed-agent-state';import { ManagedMachinePill } from './managed-machine-card';+import { useManagedAgentActions } from './use-managed-agent-actions';import {MANAGED_AGENTS_KEY,useAdvancedConfigSchema,@@ -76,7 +81,7 @@ const NO_EDITS: Edits = { values: {}, form: {} };* it runs on, how it behaves, and its sessions. Every edit on it is one set of* pending changes for the page's save bar; the server checks the definition* against the agent's machine and refuses it whole. `serviceGrants` shows its- * Service access, which a page with a Connections tab shows there instead.+ * Service access, which a page offering Connections shows there instead.*/export function ManagedAgentPage({agent,@@ -113,6 +118,8 @@ function ManagedAgentPageContent({const edit = editOf(agent, schema, saved, draft);const [error, setError] = useState<string | null>(null);const [instructionsExpanded, setInstructionsExpanded] = useState(false);+ const chatsOn = useFeatureFlags(agent.serverId).agent_chats;+ const { busy, remove } = useManagedAgentActions(agent);const setValue = <K extends keyof Edits['values']>(key: K, value: Draft[K]) =>setEdits((current) => ({ ...current, values: { ...current.values, [key]: value } }));@@ -171,6 +178,7 @@ function ManagedAgentPageContent({};useAgentEdit({ id: 'managed-agent', order: 0, dirty: !editIsEmpty(edit), save, revert });+ useConfirmLeave(agent);const catalogue = useHostCatalogue(agent, machines);const title = draft.displayName.trim() || agent.name;@@ -178,6 +186,15 @@ function ManagedAgentPageContent({return (<div className="flex min-h-0 w-full flex-1 flex-col">+ <AgentSaveBar />+ {error && (+ <p+ role="alert"+ className="shrink-0 border-b border-border px-8 py-3 text-sm text-foreground-destructive"+ >+ {error}+ </p>+ )}<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto"><div className="mx-auto flex w-full max-w-[900px] flex-col gap-10 px-8 pb-20"><AgentHeaderLayout@@ -223,9 +240,11 @@ function ManagedAgentPageContent({}actions={<>- <WithReason reason={SESSIONS_START_WHEN_ADDRESSED}>- <Button disabled>New Session</Button>- </WithReason>+ {!chatsOn && (+ <WithReason reason={SESSIONS_START_WHEN_ADDRESSED}>+ <Button disabled>New Session</Button>+ </WithReason>+ )}<Buttonvariant="outline"onClick={() =>@@ -383,21 +402,70 @@ function ManagedAgentPageContent({Sessions of agents on a machine are not listed here yet.</p></section>+ {chatsOn && (+ <section className="flex flex-col gap-6">+ <SectionLabel>Danger zone</SectionLabel>+ <SettingRow+ title="Delete agent"+ info={null}+ description="Its machine stops it and it is deleted from Switch, for every room it is in."+ control={+ <Button variant="destructive" disabled={busy} onClick={remove}>+ Delete agent…+ </Button>+ }+ />+ </section>+ )}</div></div>- {error && (- <p- role="alert"- className="shrink-0 border-t border-border px-8 pt-3 text-sm text-foreground-destructive"- >- {error}- </p>- )}- <AgentSaveBar /></div>);}+/**+ * While the page has unsaved changes, leaving it — another screen, another+ * agent, a chat beside it, or closing the window — asks first.+ */+function useConfirmLeave(agent: ManagedAgentView) {+ const { dirty, revertAll } = useAgentEdits();+ const confirm = useShowModal('confirmActionModal');+ const { section } = useParams('managedAgent').params;+ const { serverId, agentId } = agent;+ useEffect(() => {+ if (!dirty) return;+ appState.navigation.setLeaveGuard((viewId, params) => {+ const target = (params ?? {}) as { serverId?: string; agentId?: string; section?: string };+ if (+ viewId === 'managedAgent' &&+ target.serverId === serverId &&+ target.agentId === agentId &&+ target.section === section+ )+ return Promise.resolve(true);+ return new Promise((resolve) =>+ confirm({+ title: 'You have unsaved changes',+ description: "If you leave now, your changes to this agent's settings will be lost.",+ cancelLabel: 'Stay',+ confirmLabel: 'Discard and leave',+ onSuccess: () => {+ revertAll();+ resolve(true);+ },+ onClose: () => resolve(false),+ })+ );+ });+ const refuseUnload = (event: BeforeUnloadEvent) => event.preventDefault();+ window.addEventListener('beforeunload', refuseUnload);+ return () => {+ appState.navigation.setLeaveGuard(null);+ window.removeEventListener('beforeunload', refuseUnload);+ };+ }, [dirty, revertAll, confirm, serverId, agentId, section]);+}+/*** The models the agent's machine offers, asked of it the way a Console agent's* host is asked — when this Console can reach that machine, and the agent has adiff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsxindex 30d7f19e6..f5699e19e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx@@ -1,7 +1,6 @@-import { useQueryClient } from '@tanstack/react-query';-import { MoreVertical, Play, Square, Trash2 } from 'lucide-react';+import { MoreVertical, Power, PowerOff, Trash2 } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { type ReactNode, useState } from 'react';+import type { ReactNode } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';import { ChatHeaderControls } from '@renderer/features/chats/components/chat-header';import { useAgentActivities } from '@renderer/features/chats/components/chat-panel';@@ -14,12 +13,9 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-serimport { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';-import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';-import { toast } from '@renderer/lib/hooks/use-toast';+import { failureText } from '@renderer/lib/errors/describe-failure';import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';-import { rpc } from '@renderer/lib/ipc';-import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';-import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { useParams } from '@renderer/lib/layout/navigation-provider';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -28,78 +24,56 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';-import { isCloudMachine, type ManagedAgentView } from '@shared/core/managed-agents/managed-agents';-import { AgentChats, openAgentChat } from './agent-chats';-import { AgentConnectionsTab, useAgentServiceGrants } from './agent-connections-tab';-import { agentTabStore } from './agent-tab-store';-import { agentTabs, shownAgentTab } from './agent-tabs';+import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { AgentChats, agentSectionLabel, openAgentChat, useAgentSection } from './agent-chats';+import { type AgentSection, isAgentSection } from './agent-sections';import { ManagedAgentPage } from './managed-agent-page';import { managedAgentLabel } from './managed-agent-state';-import { TabbedAgentTitlebar } from './tabbed-agent-titlebar';-import { MANAGED_AGENTS_KEY, useManagedAgents } from './use-managed-agents';+import { useManagedAgentActions } from './use-managed-agent-actions';+import { useManagedAgents } from './use-managed-agents';type ManagedAgentParams = {serverId: string;agentId: string;name: string;- /** The chat open on the Chats tab. */+ /** The chat open on the agent's page. */roomId?: string;+ /** Shown instead of a chat when set. */+ section?: AgentSection;};-/** The tabs the agent's page offers, and which of them is showing. */-function useAgentTab(serverId: string, agentId: string, agent: ManagedAgentView | null) {- const flags = useFeatureFlags(serverId);- const grants = useAgentServiceGrants(- flags.service_connections,- agent?.workspaceId ?? null,- agentId- );- const tabs = agentTabs(flags.service_connections, grants.data);- return {- tabbed: flags.agent_chats,- tabs,- tab: shownAgentTab(agentTabStore.tabFor(agentId), tabs),- };-}-const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {const { params } = useParams('managedAgent');const agents = useManagedAgents(params.serverId);const agent = agents.data?.find((listed) => listed.agentId === params.agentId) ?? null;const server = switchServersStore.servers.find((s) => s.id === params.serverId) ?? null;const label = agent ? managedAgentLabel(agent) : params.name;- const { tabbed, tabs, tab } = useAgentTab(params.serverId, params.agentId, agent);- const chat = tabbed && agent && tab === 'chats' ? openAgentChat(agent, params.roomId) : null;+ const chatsOn = useFeatureFlags(params.serverId).agent_chats;+ const { section } = useAgentSection(params.serverId, agent, params.section);+ const chat = chatsOn && agent && !section ? openAgentChat(agent, params.roomId) : null;const activities = useAgentActivities(params.serverId, chat ?? undefined);- const breadcrumb = (- <TitlebarBreadcrumb- crumbs={[- {- key: 'agent',- // Nothing until the agent is read: a stand-in drawn from its name- // would be replaced by its own picture a moment later.- icon: agent ? (- <AgentAvatar- name={label}- iconUrl={agent.iconUrl}- serverId={params.serverId}- size={16}- className="bg-transparent"- />- ) : (- <span className="inline-block size-4 shrink-0" aria-hidden />- ),- label,- maxWidthClassName: 'max-w-40',- },- ]}- />- );+ const crumb = {+ key: 'agent',+ // Nothing until the agent is read: a stand-in drawn from its name+ // would be replaced by its own picture a moment later.+ icon: agent ? (+ <AgentAvatar+ name={label}+ iconUrl={agent.iconUrl}+ serverId={params.serverId}+ size={16}+ className="bg-transparent"+ />+ ) : (+ <span className="inline-block size-4 shrink-0" aria-hidden />+ ),+ label,+ };const pill = server && <ServerStatusPill server={server} />;- if (!tabbed)+ if (!chatsOn)return (<Titlebar- leftSlot={breadcrumb}+ leftSlot={<TitlebarBreadcrumb crumbs={[crumb]} />}rightSlot={<div className="mr-1 flex items-center gap-1.5">{pill}@@ -109,15 +83,17 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {/>);return (- <TabbedAgentTitlebar- breadcrumb={breadcrumb}- tab={tab}- tabs={tabs}- onTab={(next) => agentTabStore.setTab(params.agentId, next)}+ <Titlebar+ className="border-b border-border pr-[7px]"+ leftClassName="w-[300px] shrink-0 self-stretch border-r border-border [-webkit-app-region:drag]"+ leftSlot={<TitlebarBreadcrumb crumbs={[{ ...crumb, maxWidthClassName: 'max-w-none' }]} />}+ rightClassName="min-w-0 flex-1 justify-between gap-3 pl-4 [-webkit-app-region:drag]"rightSlot={<>- <span className="truncate text-sm font-medium">{chat?.name}</span>- <div className="mr-1 flex shrink-0 items-center gap-1.5">+ <span className="truncate text-sm font-medium">+ {section ? agentSectionLabel(section) : chat?.name}+ </span>+ <div className="flex shrink-0 items-center gap-1.5 [-webkit-app-region:no-drag]">{server &&serverState(server) !== 'connected' &&serverState(server) !== 'running-local' &&@@ -161,68 +137,31 @@ function ManagedAgentActionsMenu({ agent }: { agent: ManagedAgentView }) {}function ManagedAgentActionItems({ agent }: { agent: ManagedAgentView }) {- const label = managedAgentLabel(agent);- const queryClient = useQueryClient();- const { navigate } = useNavigate();- const confirm = useShowModal('confirmActionModal');- const [busy, setBusy] = useState(false);-- const act = async (fallback: string, run: () => Promise<void>) => {- setBusy(true);- try {- await run();- await queryClient.invalidateQueries({ queryKey: [MANAGED_AGENTS_KEY] });- } catch (failure) {- const { headline, detail } = describeFailure(failure, fallback);- toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });- } finally {- setBusy(false);- }- };- const setDesiredState = (desiredState: 'running' | 'stopped') =>- act(- desiredState === 'running'- ? `${label} could not be started.`- : `${label} could not be stopped.`,- () =>- rpc.managedAgents.setDesiredState({- serverId: agent.serverId,- agentId: agent.agentId,- desiredState,- })- );- const remove = () =>- confirm({- title: `Delete ${label}?`,- description: `Its machine stops it and it is deleted from Switch, for every room it is in.`,- confirmLabel: 'Delete',- onSuccess: () =>- void act(`${label} could not be deleted.`, async () => {- await rpc.managedAgents.remove({ serverId: agent.serverId, agentId: agent.agentId });- // Its name is free again: the New agent form checks names against this list.- await queryClient.invalidateQueries({ queryKey: ['workspace-agents'] });- navigate('serverAgents', { serverId: agent.serverId });- }),- });+ const { busy, setDesiredState, remove } = useManagedAgentActions(agent);+ const chatsOn = useFeatureFlags(agent.serverId).agent_chats;return (<>{agent.desiredState === 'running' ? (<DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('stopped')}>- <Square className="size-4" />- Stop+ <PowerOff className="size-4" />+ Turn off agent</DropdownMenuItem>) : (<DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('running')}>- <Play className="size-4" />- Start+ <Power className="size-4" />+ Turn on agent</DropdownMenuItem>)}- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" disabled={busy} onClick={remove}>- <Trash2 className="size-4" />- Delete agent…- </DropdownMenuItem>+ {!chatsOn && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" disabled={busy} onClick={remove}>+ <Trash2 className="size-4" />+ Delete agent…+ </DropdownMenuItem>+ </>+ )}</>);}@@ -231,7 +170,7 @@ const ManagedAgentPanel = observer(function ManagedAgentPanel() {const { params } = useParams('managedAgent');const agents = useManagedAgents(params.serverId);const agent = agents.data?.find((listed) => listed.agentId === params.agentId);- const { tabbed, tab } = useAgentTab(params.serverId, params.agentId, agent ?? null);+ const chatsOn = useFeatureFlags(params.serverId).agent_chats;if (agents.error)return (<ServerPage width={900} title={params.name} description="">@@ -262,19 +201,8 @@ const ManagedAgentPanel = observer(function ManagedAgentPanel() {</p></ServerPage>);- if (!tabbed) return <ManagedAgentPage key={agent.agentId} agent={agent} serviceGrants />;- if (tab === 'chats') return <AgentChats key={agent.agentId} agent={agent} />;- if (tab === 'connections')- return (- <AgentConnectionsTab- key={agent.agentId}- workspaceId={agent.workspaceId}- agentId={agent.agentId}- agentName={managedAgentLabel(agent)}- cloud={agent.machine !== null && isCloudMachine(agent.machine)}- />- );- return <ManagedAgentPage key={agent.agentId} agent={agent} serviceGrants={false} />;+ if (!chatsOn) return <ManagedAgentPage key={agent.agentId} agent={agent} serviceGrants />;+ return <AgentChats key={agent.agentId} agent={agent} />;});export const managedAgentView = {@@ -287,7 +215,8 @@ export const managedAgentView = {typeof value.serverId !== 'string' ||typeof value.agentId !== 'string' ||typeof value.name !== 'string' ||- (value.roomId !== undefined && typeof value.roomId !== 'string')+ (value.roomId !== undefined && typeof value.roomId !== 'string') ||+ (value.section !== undefined && !isAgentSection(value.section)))return { ok: false, redirect: 'home', discardParams: true };return { ok: true };diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsxdeleted file mode 100644index 7658d3edb..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsx+++ /dev/null@@ -1,50 +0,0 @@-import type { ReactNode } from 'react';-import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';-import { SegmentedControl } from '@renderer/lib/ui/segmented-control';-import { cn } from '@renderer/utils/utils';-import type { AgentTab } from './agent-tab-store';-import type { AgentTabOption } from './agent-tabs';--/**- * A tabbed agent's titlebar: its crumb and tabs on the left, `rightSlot` on- * the right. On Chats the left side is as wide as the chat list below it, so- * the two line up; on the other tabs it takes the width it needs. Either way- * the tabs keep their width and a long name is what gives way.- */-export function TabbedAgentTitlebar({- breadcrumb,- tab,- tabs,- onTab,- rightSlot,-}: {- breadcrumb: ReactNode;- tab: AgentTab;- tabs: readonly AgentTabOption[];- onTab: (tab: AgentTab) => void;- rightSlot: ReactNode;-}) {- return (- <Titlebar- className="border-b border-border"- leftClassName={cn(- 'min-w-0 self-stretch',- tab === 'chats' && 'w-[300px] shrink-0 border-r border-border'- )}- leftSlot={- <div className="flex min-w-0 items-center gap-3">- <div className="min-w-0 truncate">{breadcrumb}</div>- <SegmentedControl- className="shrink-0"- value={tab}- onChange={onTab}- options={tabs}- ariaLabel="Agent view"- />- </div>- }- rightClassName="min-w-0 flex-1 justify-between gap-3 pl-4"- rightSlot={rightSlot}- />- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agent-actions.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agent-actions.tsnew file mode 100644index 000000000..503c9b58e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agent-actions.ts@@ -0,0 +1,59 @@+import { useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { managedAgentLabel } from './managed-agent-state';+import { MANAGED_AGENTS_KEY } from './use-managed-agents';++/** Starting, stopping and deleting a managed agent, each confirmed or reported as a toast. */+export function useManagedAgentActions(agent: ManagedAgentView) {+ const label = managedAgentLabel(agent);+ const queryClient = useQueryClient();+ const { navigate } = useNavigate();+ const confirm = useShowModal('confirmActionModal');+ const [busy, setBusy] = useState(false);++ const act = async (fallback: string, run: () => Promise<void>) => {+ setBusy(true);+ try {+ await run();+ await queryClient.invalidateQueries({ queryKey: [MANAGED_AGENTS_KEY] });+ } catch (failure) {+ const { headline, detail } = describeFailure(failure, fallback);+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });+ } finally {+ setBusy(false);+ }+ };+ const setDesiredState = (desiredState: 'running' | 'stopped') =>+ act(+ desiredState === 'running'+ ? `${label} could not be started.`+ : `${label} could not be stopped.`,+ () =>+ rpc.managedAgents.setDesiredState({+ serverId: agent.serverId,+ agentId: agent.agentId,+ desiredState,+ })+ );+ const remove = () =>+ confirm({+ title: `Delete ${label}?`,+ description: `Its machine stops it and it is deleted from Switch, for every room it is in.`,+ confirmLabel: 'Delete',+ onSuccess: () =>+ void act(`${label} could not be deleted.`, async () => {+ await rpc.managedAgents.remove({ serverId: agent.serverId, agentId: agent.agentId });+ // Its name is free again: the New agent form checks names against this list.+ await queryClient.invalidateQueries({ queryKey: ['workspace-agents'] });+ navigate('serverAgents', { serverId: agent.serverId });+ }),+ });++ return { busy, setDesiredState, remove };+}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 bf39a0a34..06d732e13 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@@ -1,6 +1,5 @@import { focusComposerWhenOpened } from '@renderer/features/chats/components/chat-composer';import { chatsStore, chatTitler } from '@renderer/features/chats/stores/chats';-import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -45,7 +44,7 @@ async function buddyChat(}/**- * Opens the person's buddy on its Chats tab, in its chat. When the chat cannot+ * Opens the person's buddy's page, in its chat. When the chat cannot* be had the agent's page still opens, and a toast says why.*/export async function openBuddyChat(@@ -63,7 +62,6 @@ export async function openBuddyChat(variant: 'destructive',});}- agentTabStore.setTab(agent.agentId, 'chats');appState.navigation.navigate('managedAgent', {serverId,agentId: agent.agentId,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsxindex c5ea21e1c..dbe99e5cc 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx@@ -71,7 +71,7 @@ export function ConnectionsGrid({<DialogContentArea className="space-y-4 pt-0"><p className="text-sm text-foreground-muted">Connect the services your agents can work with. Each agent uses a service only once you- grant it, from the agent's Connections tab.+ grant it, from the agent's Connections.</p><SearchInputaria-label="Search connections"diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/confirm-action-dialog.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/confirm-action-dialog.tsxindex cf1b3c923..3c75410bb 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/confirm-action-dialog.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/confirm-action-dialog.tsx@@ -13,6 +13,7 @@ export type ConfirmActionDialogArgs = {title: string;description: ReactNode;confirmLabel?: string;+ cancelLabel?: string;variant?: 'destructive' | 'default';};@@ -22,6 +23,7 @@ export function ConfirmActionDialog({title,description,confirmLabel = 'Confirm',+ cancelLabel = 'Cancel',variant = 'destructive',onSuccess,onClose,@@ -36,7 +38,7 @@ export function ConfirmActionDialog({</DialogContentArea><DialogFooter><Button variant="outline" onClick={onClose}>- Cancel+ {cancelLabel}</Button><ConfirmButton variant={variant} onClick={() => onSuccess()}>{confirmLabel}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsxindex ccf252259..2d4b02bac 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx@@ -78,7 +78,8 @@ export function WorkspaceLayout({the two, in place of a divider. Flush to the sidebar on the left,8px away on the other three sides. The hairline is a spread shadowrather than a border so it lands on a half pixel and does not take- a whole one out of the panel.+ a whole one out of the panel; the 1px left gutter keeps the clip from+ eating it on the flush side.With the sidebar collapsed there is no sidebar to be flush against,so the card insets on the left too — and on macOS it starts below@@ -87,12 +88,12 @@ export function WorkspaceLayout({own corner under the close button. */}<divclassName={cn(- 'relative h-full w-full overflow-hidden pr-2 pb-2',- isLeftOpen ? 'pt-2' : 'pl-2',+ 'relative h-full w-full overflow-hidden pr-2 pb-2 [-webkit-app-region:drag]',+ isLeftOpen ? 'pt-2 pl-px' : 'pl-2',!isLeftOpen && (isMac ? 'pt-9' : 'pt-2'))}>- <div className="relative flex h-full w-full flex-col overflow-hidden rounded-[var(--panel-radius)] shadow-[0_0_0_0.5px_var(--hair)]">+ <div className="relative flex h-full w-full flex-col overflow-hidden rounded-[var(--panel-radius)] shadow-[0_0_0_0.5px_var(--hair)] [-webkit-app-region:no-drag]">{banner}<div className={cn('relative min-h-0 w-full flex-1', contentClassName)}>{mainContent}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-history-store.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-history-store.tsindex 4840c6f02..76669c67a 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-history-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-history-store.ts@@ -1,5 +1,6 @@import { makeAutoObservable } from 'mobx';import type { ViewId, WrapParams } from '@renderer/app/view-registry';+import { appState } from './app-state';const MAX_STACK_SIZE = 50;@@ -77,22 +78,27 @@ export class NavigationHistoryStore {}back(apply: (entry: HistoryEntry) => void): void {- if (!this.canGoBack) return;- this.index--;- this.navigating = true;- try {- apply(this.entries[this.index]!);- } finally {- this.navigating = false;- }+ if (this.canGoBack) this._step(this.index - 1, apply);}forward(apply: (entry: HistoryEntry) => void): void {- if (!this.canGoForward) return;- this.index++;+ if (this.canGoForward) this._step(this.index + 1, apply);+ }++ private _step(index: number, apply: (entry: HistoryEntry) => void): void {+ const entry = this.entries[index]!;+ if (entry.kind === 'view')+ appState.navigation.whenLeaveAllowed(entry.viewId, entry.params, () =>+ this._moveTo(index, apply)+ );+ else this._moveTo(index, apply);+ }++ private _moveTo(index: number, apply: (entry: HistoryEntry) => void): void {+ this.index = index;this.navigating = true;try {- apply(this.entries[this.index]!);+ apply(this.entries[index]!);} finally {this.navigating = false;}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.test.tsindex 05360f3e9..82608f938 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.test.ts@@ -77,3 +77,48 @@ describe('NavigationStore.restoreSnapshot', () => {expect(store.currentViewId).toBe('home');});});++describe('NavigationStore leave guard', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('navigates at once when no guard is set', () => {+ const store = buildStore();+ store.navigate('location', { locationId: 'p1' });+ expect(store.currentViewId).toBe('location');+ });++ it('holds a navigation until the guard lets it through', async () => {+ const store = buildStore();+ let answer!: (ok: boolean) => void;+ const guard = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));+ store.setLeaveGuard(guard);+ store.navigate('location', { locationId: 'p1' });+ expect(guard).toHaveBeenCalledWith('location', { locationId: 'p1' });+ expect(store.currentViewId).toBe('home');+ answer(true);+ await vi.waitFor(() => expect(store.currentViewId).toBe('location'));+ });++ it('stays when the guard refuses', async () => {+ const store = buildStore();+ store.setLeaveGuard(() => Promise.resolve(false));+ store.navigate('location', { locationId: 'p1' });+ await Promise.resolve();+ await Promise.resolve();+ expect(store.currentViewId).toBe('home');+ });++ it("guards a change to the current view's params, and not to another view's", async () => {+ const store = buildStore();+ store.navigate('location', { locationId: 'p1' });+ store.setLeaveGuard(() => Promise.resolve(false));+ store.updateViewParams('location', { locationId: 'p2' });+ store.updateViewParams('session', { sessionId: 's1' } as never);+ await Promise.resolve();+ await Promise.resolve();+ expect(store.viewParamsStore.location).toEqual({ locationId: 'p1' });+ expect(store.viewParamsStore.session).toEqual({ sessionId: 's1' });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.tsindex b3e4a018a..b357ede92 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/navigation-store.ts@@ -9,6 +9,9 @@ import type { Snapshottable } from './snapshottable';type ViewParamsStore = Partial<{ [K in ViewId]: WrapParams<K> }>;+/** Asked before a navigation while it is set: resolves whether to go on. */+export type LeaveGuard = (viewId: ViewId, params: unknown) => Promise<boolean>;+export class NavigationStore implements Snapshottable<NavigationSnapshot> {currentViewId: ViewId = 'home';viewParamsStore: ViewParamsStore = {};@@ -17,6 +20,7 @@ export class NavigationStore implements Snapshottable<NavigationSnapshot> {private readonly _guards = new Map<ViewId, (params: unknown) => GuardResult>();private readonly _registeredViewIds = new Set<ViewId>();+ private _leaveGuard: LeaveGuard | null = null;constructor() {makeAutoObservable(this);@@ -34,6 +38,20 @@ export class NavigationStore implements Snapshottable<NavigationSnapshot> {this._guards.set(viewId, guard);}+ /** A screen with work that would be lost sets this, and clears it when there is none. */+ setLeaveGuard(guard: LeaveGuard | null): void {+ this._leaveGuard = guard;+ }++ /** Runs `go` now, or once the leave guard lets the navigation through. */+ whenLeaveAllowed(viewId: ViewId, params: unknown, go: () => void): void {+ const guard = this._leaveGuard;+ if (!guard) return go();+ void guard(viewId, params).then((ok) => {+ if (ok) go();+ });+ }+private _runGuard(viewId: ViewId, params: unknown): GuardResult {return this._guards.get(viewId)?.(params) ?? { ok: true };}@@ -54,6 +72,12 @@ export class NavigationStore implements Snapshottable<NavigationSnapshot> {}navigate<T extends ViewId>(viewId: T, params?: WrapParams<T>): void {+ this.whenLeaveAllowed(viewId, params ?? this.viewParamsStore[viewId], () =>+ this._navigate(viewId, params)+ );+ }++ private _navigate<T extends ViewId>(viewId: T, params?: WrapParams<T>): void {const historyParams = params ?? this.viewParamsStore[viewId] ?? ({} as WrapParams<T>);appState.history.push({ kind: 'view', viewId, params: historyParams });this._applyNavigation(viewId, params);@@ -91,7 +115,14 @@ export class NavigationStore implements Snapshottable<NavigationSnapshot> {): void {const current = (this.viewParamsStore[viewId] ?? {}) as WrapParams<TId>;const next = typeof update === 'function' ? update(current) : { ...current, ...update };- this.viewParamsStore = { ...this.viewParamsStore, [viewId]: next };+ // Only the current screen's params change what is on screen.+ if (viewId === this.currentViewId)+ this.whenLeaveAllowed(viewId, next, () => this._setViewParams(viewId, next));+ else this._setViewParams(viewId, next);+ }++ private _setViewParams<TId extends ViewId>(viewId: TId, params: WrapParams<TId>): void {+ this.viewParamsStore = { ...this.viewParamsStore, [viewId]: params };}get snapshot(): NavigationSnapshot {diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsxnew file mode 100644index 000000000..aee7940d4--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx@@ -0,0 +1,164 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';++const flags = vi.hoisted(() => ({ agent_chats: true, service_connections: true }));+const grants = vi.hoisted(() => ({ data: undefined as ServiceGrants | null | undefined }));++/** Stands in for the app's navigation: the agent column picks a section by setting params. */+const navigation = vi.hoisted(() => {+ let params: Record<string, string | undefined> = {};+ const listeners = new Set<() => void>();+ const set = (next: Record<string, string | undefined>) => {+ params = next;+ for (const listener of listeners) listener();+ };+ return {+ params: () => params,+ setParams: (update: Record<string, string | undefined>) => set({ ...params, ...update }),+ reset: (next: Record<string, string | undefined>) => set(next),+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+});++vi.mock('@renderer/lib/layout/navigation-provider', async (importOriginal) => {+ const { useSyncExternalStore } = await import('react');+ return {+ ...(await importOriginal<object>()),+ useParams: () => ({+ params: useSyncExternalStore(navigation.subscribe, navigation.params),+ setParams: navigation.setParams,+ }),+ };+});+vi.mock('@renderer/lib/hooks/useFeatureFlags', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useFeatureFlags: () => flags,+}));+vi.mock('@renderer/lib/ipc', () => ({ events: { on: () => () => {} }, rpc: {} }));+vi.mock('@renderer/lib/modal/modal-provider', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ showModal: vi.fn(),+}));+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({+ switchRoomsStore: {+ fetchAgentRooms: async () => {},+ roomsFor: () => [],+ errorFor: () => null,+ },+}));+vi.mock('@renderer/features/managed-agents/agent-connections-tab', () => ({+ useAgentServiceGrants: () => grants,+ AgentConnectionsTab: (props: { agentId: string; agentName: string }) => (+ <div data-testid="connections">+ Connections for {props.agentName} ({props.agentId})+ </div>+ ),+}));+vi.mock('@renderer/features/managed-agents/managed-agent-page', () => ({+ ManagedAgentPage: (props: { serviceGrants: boolean }) => (+ <div data-testid="settings">+ Settings, service access {props.serviceGrants ? 'shown' : 'not shown'}+ </div>+ ),+}));+vi.mock('@renderer/features/chats/components/chat-panel', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ ChatPanel: () => null,+}));++import '@renderer/index.css';+import { AgentChats } from '@renderer/features/managed-agents/agent-chats';++const AGENT: ManagedAgentView = {+ serverId: 'server-1',+ workspaceId: 'workspace-1',+ agentId: 'agent-1',+ name: 'pm-agent',+ displayName: null,+ iconUrl: null,+ description: '',+ machine: null,+ desiredState: 'running',+ revision: 1,+ definition: {+ provider: 'claude',+ model: null,+ advancedConfig: {},+ instructions: '',+ autoApprove: false,+ directory: null,+ isolation: 'shared',+ },+ status: null,+};++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ flags.service_connections = true;+ grants.data = { grants: [], addressing_open: false };+ navigation.reset({ serverId: 'server-1', agentId: 'agent-1', name: 'pm-agent' });+ container = document.createElement('div');+ container.style.width = '1100px';+ container.style.height = '700px';+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++/** The agent column's rows above the chats, by their labels. */+const navRows = () =>+ [...container.querySelectorAll<HTMLElement>('nav[aria-label="Agent"] > div')].map((row) => ({+ label: row.textContent?.trim() ?? '',+ row,+ }));+const navLabels = () => navRows().map(({ label }) => label);+const navItem = (label: string) => navRows().find((entry) => entry.label === label)!.row;++it("puts Connections in the agent's column, above Agent settings, and opens it there", async () => {+ await act(async () => root.render(<AgentChats agent={AGENT} />));+ expect(navLabels()).toEqual(['Connections', 'Agent settings']);++ await act(async () => navItem('Connections').click());+ expect(navigation.params().section).toBe('connections');+ expect(container.querySelector('[data-testid="connections"]')?.textContent).toBe(+ 'Connections for pm-agent (agent-1)'+ );++ await act(async () => navItem('Agent settings').click());+ expect(container.querySelector('[data-testid="settings"]')?.textContent).toBe(+ 'Settings, service access not shown'+ );+});++it("leaves Connections out for an agent whose grants aren't yours, keeping service access in settings", async () => {+ grants.data = null;+ navigation.reset({ ...navigation.params(), section: 'connections' });+ await act(async () => root.render(<AgentChats agent={AGENT} />));+ expect(navLabels()).toEqual(['Agent settings']);+ expect(container.querySelector('[data-testid="connections"]')).toBeNull();++ await act(async () => navItem('Agent settings').click());+ expect(container.querySelector('[data-testid="settings"]')?.textContent).toBe(+ 'Settings, service access shown'+ );+});++it('leaves Connections out when the server has service connections off', async () => {+ flags.service_connections = false;+ await act(async () => root.render(<AgentChats agent={AGENT} />));+ expect(navLabels()).toEqual(['Agent settings']);+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsxindex 0e067d160..3a43623fc 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx@@ -5,7 +5,7 @@* the page rather than inside advanced configuration — and they are saved from* a bar shared with the other editors on the page, not a button of their own.* These pin what that bar owes the reader: it appears only when something is- * genuinely unsaved, nothing is written until Save, and Revert puts back what+ * genuinely unsaved, nothing is written until Save, and Discard puts back what* was stored rather than clearing the field.*/import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -142,7 +142,7 @@ describe('an agent’s instructions', () => {const el = await renderPage();await type(field(el), 'Answer in Portuguese.');- await act(async () => button(el, /^Revert/)!.click());+ await act(async () => button(el, /^Discard/)!.click());expect(field(el).value).toBe(STORED);expect(updateInstructions).not.toHaveBeenCalled();diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsxindex 652e09326..f0a15bbfd 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx@@ -64,15 +64,14 @@ vi.mock(),}));+vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({+ useFeatureFlags: () => ({ agent_chats: false, service_connections: false }),+}));vi.mock('@renderer/lib/components/agent-icon-picker', () => ({ AgentIconPicker: () => null }));vi.mock('@renderer/lib/modal/modal-provider', () => ({ useShowModal: () => vi.fn() }));import '@renderer/index.css';-import { agentTabs } from '@renderer/features/managed-agents/agent-tabs';import { ManagedAgentPage } from '@renderer/features/managed-agents/managed-agent-page';-import { TabbedAgentTitlebar } from '@renderer/features/managed-agents/tabbed-agent-titlebar';-import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';-import { WorkspaceLayoutContextProvider } from '@renderer/lib/layout/layout-provider';const AGENT: ManagedAgentView = {serverId: 'server-1',@@ -300,41 +299,3 @@ it('gives an agent on the Switch cloud machine the cloud agent’s service acces));});--it('keeps Chats, Connections and Settings in view beside a long name, on every tab', async () => {- const tabs = agentTabs(true, undefined);- expect(tabs.map((tab) => tab.label)).toEqual(['Chats', 'Connections', 'Settings']);- for (const shown of tabs) {- const host = document.createElement('div');- host.style.width = '900px';- document.body.appendChild(host);- const titleRoot = createRoot(host);- await act(async () =>- titleRoot.render(- <WorkspaceLayoutContextProvider>- <TabbedAgentTitlebar- breadcrumb={- <TitlebarBreadcrumb crumbs={[{ key: 'agent', label: 'm3-managed-reviewer' }]} />- }- tab={shown.value}- tabs={tabs}- onTab={() => {}}- rightSlot={null}- />- </WorkspaceLayoutContextProvider>- )- );- const control = host.querySelector<HTMLElement>('[aria-label="Agent view"]')!;- const side = control.parentElement!.parentElement!.getBoundingClientRect();- for (const { label } of tabs) {- const item = control.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;- const box = item.getBoundingClientRect();- expect(box.width, `${label} on ${shown.label}`).toBeGreaterThan(0);- expect(item.scrollWidth, `${label} on ${shown.label}`).toBeLessThanOrEqual(item.clientWidth);- expect(box.right, `${label} on ${shown.label}`).toBeLessThanOrEqual(side.right + 0.5);- }- expect(host.textContent).toContain('m3-managed-reviewer');- act(() => titleRoot.unmount());- host.remove();- }-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.tsindex b12ac98e0..85cbe2578 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from 'vitest';-import { agentConversations } from '@renderer/features/chats/agent-conversations';+import {+ agentConversations,+ byLatestDirectChat,+} from '@renderer/features/chats/agent-conversations';import type { ChatSummary } from '@shared/core/chats/chats';import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';@@ -39,7 +42,8 @@ describe('agentConversations', () => {const channel = summary({ roomId: 'team', channelType: 'channel_private' });const split = agentConversations([direct, slackDm, channel],- [room('team', 'team'), room('dm', 'dm'), room('slack-dm', 'Dana'), room('old', 'old', true)]+ [room('team', 'team'), room('dm', 'dm'), room('slack-dm', 'Dana'), room('old', 'old', true)],+ new Set());expect(split.direct.map((chat) => chat.roomId)).toEqual(['dm']);expect(split.rooms.map((each) => each.roomId)).toEqual(['slack-dm', 'team']);@@ -47,7 +51,7 @@ describe('agentConversations', () => {it('puts a direct room with two agents under Rooms', () => {const shared = summary({ roomId: 'pair', agents: [agent('a', 'alpha'), agent('b', 'beta')] });- const split = agentConversations([shared], []);+ const split = agentConversations([shared], [], new Set());expect(split.direct).toEqual([]);expect(split.rooms).toEqual([{ roomId: 'pair', roomName: 'Chat with helper' }]);});@@ -59,11 +63,61 @@ describe('agentConversations', () => {channelType: 'channel_private',agents: [agent('a', 'alpha'), agent('b', 'beta')],});- const split = agentConversations([group], [room('team', 'team')]);+ const split = agentConversations([group], [room('team', 'team')], new Set());expect(split.direct).toEqual([]);expect(split.rooms).toEqual([{ roomId: 'team', roomName: 'team', archived: false, status: 'live', roomRole: null },{ roomId: 'group', roomName: 'Try me' },]);});++ it('excludes stale membership entries for removed rooms', () => {+ const split = agentConversations(+ [],+ [room('removed', 'Removed Room'), room('live', 'Live Room')],+ new Set(['removed'])+ );+ expect(split.rooms.map((each) => each.roomId)).toEqual(['live']);+ });+});++describe('byLatestDirectChat', () => {+ const agents = ['alpha', 'beta', 'gamma', 'delta'].map((agentId) => ({ agentId }));+ const chat = (roomId: string, agentId: string, sentAt: string | null) =>+ summary({+ roomId,+ agents: [agent(agentId, agentId)],+ lastMessage: sentAt ? { seq: 1, sentAt, preview: '', senderName: 'x' } : null,+ });+ const ids = (list: { agentId: string }[]) => list.map((each) => each.agentId);++ it('puts the newest chat first and agents with no chat after, in their order', () => {+ const chats = [+ chat('g1', 'gamma', '2026-01-01T00:00:00Z'),+ chat('g2', 'gamma', '2026-01-03T00:00:00Z'),+ chat('d1', 'delta', '2026-01-02T00:00:00Z'),+ chat('b1', 'beta', null),+ ];+ expect(ids(byLatestDirectChat(agents, chats))).toEqual(['gamma', 'delta', 'alpha', 'beta']);+ });++ it('ignores chats that are not 1-1 Console chats', () => {+ const pair = summary({+ roomId: 'pair',+ agents: [agent('delta', 'delta'), agent('beta', 'beta')],+ lastMessage: { seq: 1, sentAt: '2026-01-05T00:00:00Z', preview: '', senderName: 'x' },+ });+ const slack = { ...chat('s', 'gamma', '2026-01-05T00:00:00Z'), bridgeType: 'slack' };+ expect(ids(byLatestDirectChat(agents, [pair, slack]))).toEqual(ids(agents));+ });++ it('keeps the given order on a tie', () => {+ const at = '2026-01-01T00:00:00Z';+ const chats = [chat('d', 'delta', at), chat('b', 'beta', at)];+ expect(ids(byLatestDirectChat(agents, chats))).toEqual(['beta', 'delta', 'alpha', 'gamma']);+ });++ it('leaves the order unchanged with no chats', () => {+ expect(ids(byLatestDirectChat(agents, null))).toEqual(ids(agents));+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-console-route.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-console-route.test.tsindex b1e305eac..8c82b284b 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-console-route.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-console-route.test.ts@@ -4,7 +4,7 @@ import { consoleChatRoute } from '@renderer/features/chats/console-chat-route';const helper = { id: 'agent-1', name: 'helper', displayName: 'Helper' };describe('consoleChatRoute', () => {- it("opens a managed agent's chat on its Chats tab", () => {+ it("opens a managed agent's chat on its agent page", () => {expect(consoleChatRoute('s', 'r', helper, true)).toEqual({viewId: 'managedAgent',params: { serverId: 's', agentId: 'agent-1', name: 'Helper', roomId: 'r' },diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-removal.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-removal.test.tsnew file mode 100644index 000000000..640840133--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-removal.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';+import { chatRemovalNavigation } from '@renderer/features/chats/chat-removal';++const stay = { leaveChatView: false, clearAgentChat: false };++describe('chatRemovalNavigation', () => {+ it('leaves the chat view only when it shows the removed chat', () => {+ expect(chatRemovalNavigation('!a', { currentViewId: 'chat', chatRoomId: '!a' })).toEqual({+ leaveChatView: true,+ clearAgentChat: false,+ });+ expect(chatRemovalNavigation('!b', { currentViewId: 'chat', chatRoomId: '!a' })).toEqual(stay);+ });++ it('drops the agent page chat only when it is the removed one', () => {+ expect(+ chatRemovalNavigation('!a', { currentViewId: 'managedAgent', agentRoomId: '!a' })+ ).toEqual({ leaveChatView: false, clearAgentChat: true });+ expect(+ chatRemovalNavigation('!b', { currentViewId: 'managedAgent', agentRoomId: '!a' })+ ).toEqual(stay);+ });++ it('stays put on an agent page showing its newest chat by default', () => {+ expect(chatRemovalNavigation('!b', { currentViewId: 'managedAgent' })).toEqual(stay);+ });++ it('does not navigate from a chat view left in the background', () => {+ expect(chatRemovalNavigation('!a', { currentViewId: 'home', chatRoomId: '!a' })).toEqual(stay);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-stop-rows.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-stop-rows.test.tsnew file mode 100644index 000000000..d467164c9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-stop-rows.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { hiddenStopRows } from '@renderer/features/chats/stop-rows';+import type { ChatMessage } from '@shared/core/chats/chats';++const human = { kind: 'human' } as ChatMessage['sender'];+const agent = { kind: 'agent' } as ChatMessage['sender'];+const row = (+ messageId: string,+ body: string,+ sender = human,+ threadRootId: string | null = null+) => ({+ messageId,+ body,+ sender,+ threadRootId,+});++describe('hiddenStopRows', () => {+ it('hides a Stop command and its acknowledgement', () => {+ const messages = [+ row('$ask', 'fix the build'),+ row('$stop', '!interrupt @coder'),+ row('$ack', 'Interrupted my current turn. ([Open in Switch Console](x))', agent, '$stop'),+ row('$next', 'try again'),+ ];+ expect(hiddenStopRows(messages)).toEqual(new Set(['$stop', '$ack']));+ });++ it('hides a Stop still waiting for its answer', () => {+ expect(hiddenStopRows([row('$stop', '!interrupt @coder')])).toEqual(new Set(['$stop']));+ });++ it('shows a Stop the agent could not carry out, with its answer', () => {+ const messages = [+ row('$stop', '!interrupt @coder'),+ row('$no', "I can't be interrupted — this isn't supported for me.", agent, '$stop'),+ ];+ expect(hiddenStopRows(messages).size).toBe(0);+ });++ it('leaves other commands and messages alone', () => {+ const messages = [+ row('$reset', '!reset @coder'),+ row('$ack', 'Resetting my session.', agent, '$reset'),+ row('$talk', '!interrupting cow'),+ row('$quote', 'Interrupted my current turn.'),+ ];+ expect(hiddenStopRows(messages).size).toBe(0);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.tsindex 4b4cd8437..e62a079a4 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts@@ -7,6 +7,12 @@ import {} from '@renderer/features/chats/stores/chats-store';import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({+ switchRoomsStore: {+ refreshRoomState: vi.fn(async () => {}),+ },+}));+function summary(roomId: string, seq: number): ChatSummary {return {roomId,@@ -63,6 +69,8 @@ function setup(list: vi.fn(list),identity,timeline: () => timeline as TimelineApi,+ archive: vi.fn(async () => {}),+ delete: vi.fn(async () => {}),};const store = new ChatsStore(api, events);return {@@ -95,10 +103,9 @@ describe('ChatsStore', () => {});it('brings a hidden chat back when a message arrives in it', async () => {- let chats = [summary('r1', 1), summary('r2', 1)];+ let chats = [summary('r1', 1)];const { store, api, emit } = setup(async () => chats);await store.connect('s1');- store.hide('r2');expect(store.chat('r2')).toBeUndefined();chats = [summary('r1', 1), summary('r2', 2)];@@ -107,6 +114,26 @@ describe('ChatsStore', () => {expect(api.list).toHaveBeenCalledTimes(2);});+ it.each(['archive', 'delete'] as const)(+ 'drops a chat once the server agrees to %s it',+ async (op) => {+ const { store, api } = setup(async () => [summary('r1', 1), summary('r2', 1)]);+ await store.connect('s1');+ await store[op]('s1', 'r2');+ expect(api[op]).toHaveBeenCalledWith('s1', 'r2');+ expect(store.chat('r2')).toBeUndefined();+ expect(store.chat('r1')).toBeDefined();+ }+ );++ it.each(['archive', 'delete'] as const)('keeps a chat the server refuses to %s', async (op) => {+ const { store, api } = setup(async () => [summary('r1', 1)]);+ await store.connect('s1');+ vi.mocked(api[op]).mockRejectedValueOnce(new Error('Not authorized'));+ await expect(store[op]('s1', 'r1')).rejects.toThrow('Not authorized');+ expect(store.chat('r1')).toBeDefined();+ });+it('does not relist for a room the person lost', async () => {const { store, api, emit } = setup(async () => [summary('r1', 1)]);await store.connect('s1');diff --git a/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.tsindex 218771fd0..9c36cee12 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts@@ -425,15 +425,15 @@ describe('the agents on a connector page', () => {expect(OPEN_AGENT_NOTE).toBe('Others can address it; it would act as you.');});- it("sends the person to the agent's Connections tab where the server cannot list agents", () => {+ it("sends the person to the agent's Connections where the server cannot list agents", () => {expect(agentsUnlistedText('Example')).toBe(- "This server can't list your agents here. Turn Example on for an agent from the agent's Connections tab."+ "This server can't list your agents here. Turn Example on for an agent from the agent's Connections.");});it('says so when the person has no agents yet', () => {expect(noAgentsText('Example')).toBe(- "You have no agents in this workspace yet. Once you add one, turn Example on for it from the agent's Connections tab."+ "You have no agents in this workspace yet. Once you add one, turn Example on for it from the agent's Connections.");});});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.tsindex ca59c1fbb..3ed82ce3f 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts@@ -13,6 +13,7 @@ function setup(create: vi.fn(create),created: vi.fn(),opened: vi.fn(),+ warm: vi.fn(),failed: vi.fn(),findEmpty: vi.fn(findEmpty),newId: () => `req-${++id}`,@@ -32,6 +33,7 @@ describe('DirectChatStarter', () => {greeting: null,});expect(deps.created).toHaveBeenCalledWith('s1', chat);+ expect(deps.warm).not.toHaveBeenCalled();});it('ignores a second start for the same agent while one is in flight', async () => {@@ -65,6 +67,7 @@ describe('DirectChatStarter', () => {await expect(starter.start('s1', 'a1')).resolves.toBe(existing);expect(deps.findEmpty).toHaveBeenCalledWith('a1');expect(deps.opened).toHaveBeenCalledWith(existing);+ expect(deps.warm).toHaveBeenCalledWith('s1', 'a1', 'r2');expect(deps.create).not.toHaveBeenCalled();});diff --git a/console/packages/agent-controller/src/controller.test.ts b/console/packages/agent-controller/src/controller.test.tsindex b8a5bc6dc..a18ce1e88 100644--- a/console/packages/agent-controller/src/controller.test.ts+++ b/console/packages/agent-controller/src/controller.test.ts@@ -505,7 +505,7 @@ describe('runController', () => {expect(await running).toBe('stopped');});- it('warms the agent host for a room when Switch says someone is typing, and only warns when it cannot', async () => {+ it('warms the agent host for a room when Switch asks, and only warns when it cannot', async () => {const warnings: string[] = [];core.setAssignment({ revision: 1, agents: [agent(1)] });running = runController(diff --git a/console/packages/agent-controller/src/controller.ts b/console/packages/agent-controller/src/controller.tsindex e20a870c4..3be3d89c5 100644--- a/console/packages/agent-controller/src/controller.ts+++ b/console/packages/agent-controller/src/controller.ts@@ -630,7 +630,7 @@ export async function runController(});};- /** A hint from someone typing to the agent: a failure costs only the head start. */+ /** A hint that a chat with the agent was created or reopened: a failure costs only the head start. */const warmAgent = async (agentId: string, roomId: string): Promise<void> => {try {await runtime.warm(agentId, roomId);diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.tsindex 1befa5118..c80041b2d 100644--- a/console/packages/agent-providers/src/host/agent-host.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -53,8 +53,8 @@ const assignmentSchema = z.strictObject({});/**- * A session started for a room before any message reached it (Console warming- * a chat while its user types). It has no sequence: nothing was delivered.+ * A session started for a room before any message reached it (a chat just+ * created or reopened). It has no sequence: nothing was delivered.*/const warmedSchema = z.strictObject({warmed: z.literal(true),diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.tsindex c22dfe24e..c03dcc15c 100644--- a/console/packages/agent-providers/src/host/watcher-tools.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.ts@@ -390,8 +390,8 @@ export class WatcherControl {/*** Start the session a message to this room would start, or confirm the one- * placed there, without a message: Console warming a chat while its user- * types. Resolves to that session, or null when the agent may not start one.+ * placed there, without a message: a chat just created or reopened.+ * Resolves to that session, or null when the agent may not start one.* Refused when no watcher is running.*/warm(roomId: string): Promise<string | null> {diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 8c751de20..e35000a59 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -299,6 +299,9 @@ class AgentCore:# Told (tenant_id, room_id) for each room a deleted agent was in, after it# is gone, so whatever follows rooms' agents can catch up at once._room_agents_listener: Callable[[str, str], Awaitable[None]] | None = None+ # Told (tenant_id, agent_id) after an agent's icon or display name changes,+ # so whatever shows them can refresh.+ _agent_profile_listener: Callable[[str, str], Awaitable[None]] | None = Nonedef __init__(self,@@ -765,6 +768,9 @@ class AgentCore:await self.api_key_store.create(session, new_api_key_record)old_api_key_id = existing.api_key_id+ profile_changed = (icon_url is not None and icon_url != existing.icon_url) or (+ display_name is not None and display_name != existing.display_name+ )# An omitted icon keeps whatever the agent already has: re-registration# rotates credentials and rebuilds the profile, and callers that know# nothing about icons must not wipe one the owner chose.@@ -817,6 +823,8 @@ class AgentCore:await session.commit()self.api_key_cache.invalidate_agent(existing.id)+ if profile_changed:+ await self._agent_profile_changed(existing.id)return existing.iddef set_agent_removal_listener(@@ -829,6 +837,15 @@ class AgentCore:) -> None:self._room_agents_listener = listener+ def set_agent_profile_listener(+ self, listener: Callable[[str, str], Awaitable[None]]+ ) -> None:+ self._agent_profile_listener = listener++ async def _agent_profile_changed(self, agent_id: str) -> None:+ if self._agent_profile_listener is not None:+ await self._agent_profile_listener(require_tenant_id(), agent_id)+async def _create_bridge_identities(self, tenant_id: str, agent_name: str, description: str) -> None:@@ -3847,11 +3864,17 @@ class AgentCore:target = await self.agent_store.get(session, target_agent_id)if target is None:raise ValueError(f"Agent not found: {target_agent_id}")+ profile_changed = any(+ key in update.columns and update.columns[key] != getattr(target, key)+ for key in ("icon_url", "display_name")+ )if update.columns:await self.agent_store.update(session, target_agent_id, **update.columns)await session.commit()+ if profile_changed:+ await self._agent_profile_changed(target_agent_id)refreshed = await self.agent_store.get(session, target_agent_id)assert refreshed is not Nonediff --git a/core/switch_core/bridges/agent/protocol/controller_stream.py b/core/switch_core/bridges/agent/protocol/controller_stream.pyindex 1b37a7c33..2e9581975 100644--- a/core/switch_core/bridges/agent/protocol/controller_stream.py+++ b/core/switch_core/bridges/agent/protocol/controller_stream.py@@ -21,8 +21,9 @@ of its agents' watchers exactly the stream it would have had from Switch:- `agent.session_command {agent_id, room_id, command}`: an in-room command(`!reset`, `!compact`, `!interrupt`, a Stop press) for the session working in`room_id`, which the controller routes. `command` is today's frame.-- `agent.warm {agent_id, room_id}`: someone is typing to the agent in- `room_id`; start the session a message there would start. A hint only.+- `agent.warm {agent_id, room_id}`: a chat with the agent was just created+ or reopened as `room_id`; start the session a message there would start. A+ hint only.- `agent.approval_outcome {agent_id, outcome}`.- `agent.rooms {agent_id, rooms}`: its room membership changed.- `agent.detached {agent_id, reason}`: `unassigned` or `deleted`.diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex d4fba2b46..6511e8c88 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -529,6 +529,28 @@ class ChatService:tenant_id, sorted(user_id for user_id in members if user_id is not None))+ async def agent_changed(self, tenant_id: str, agent_id: str) -> None:+ """Wake the streams of everyone in a chat with this agent, so they+ re-send its summaries. Does nothing with `agent_chats` off."""+ if not self.agent_chats_enabled:+ return+ async with tenant_session(self.session_factory, tenant_id) as session:+ members = (+ await session.execute(+ select(Client.user_id)+ .distinct()+ .join(ClientRoom, ClientRoom.client_id == Client.id)+ .join(room_agents, room_agents.c.room_id == ClientRoom.room_id)+ .where(+ room_agents.c.agent_id == agent_id,+ Client.type == MEMBER_CLIENT_TYPE,+ Client.user_id.is_not(None),+ )+ )+ ).scalars()+ user_ids = sorted(user_id for user_id in members if user_id is not None)+ self._memberships_changed(tenant_id, user_ids)+async def _make_lasting(self, tenant_id: str, user_id: str, room_id: str) -> None:async with tenant_session(self.session_factory, tenant_id) as session:await session.execute(@@ -983,11 +1005,7 @@ class ChatService:try:created = await self._room_service.create_room(RoomCreateConfig(- name=name- or "Chat with "- + ", ".join(- agent.display_name or agent.name for agent in agents- ),+ name=name or "New chat",description="Switch Console chat with "+ ", ".join(agent.name for agent in agents),agent_ids=[agent.id for agent in agents],@@ -1030,6 +1048,8 @@ class ChatService:)await session.commit()self._memberships_changed(tenant_id, [user.id])+ if len(agents) == 1:+ self._start_session(agents[0].id, room.id)return roomasync def stage_upload(@@ -1341,22 +1361,23 @@ class ChatService:)agent = await self._agent_store.get(session, agent_id)assert agent is not None- if agent.owner_id != user.id:- raise ChatError(- 403, "NOT_AGENT_OWNER", "Only the agent's owner can warm it."- )decision = await self._addressing.permitted(session, agent=agent, room_id=room.id, sender=client.transport_user_id)if not decision.allowed:raise ChatError(403, "AGENT_NOT_ALLOWED", decision.refusal)+ self._start_session(agent_id, room.id)++ def _start_session(self, agent_id: str, room_id: str) -> None:+ """A hint to a controller-hosted agent: nothing waits for it. An agent+ no controller hosts is started by the Console that runs it."""if not self._connections.controllers.is_bound(agent_id):return- if not self._connections.relay_warm(agent_id, room.id):+ if not self._connections.relay_warm(agent_id, room_id):logger.warning(- "Could not warm agent %s for room %s: its controller is not connected or it is stopped",+ "Could not start agent %s's session for room %s: its controller is not connected or it is stopped",agent_id,- room.id,+ room_id,)async def _posted(diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex 9446dea6a..9d3ce016e 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -27,12 +27,14 @@ from switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,)+from switch_core.chats.service import ChatServicefrom switch_core.config import SwitchConfig-from switch_core.db.models import User+from switch_core.db.models import User, require_tenant_idfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import get_current_user, get_tenant_is_admin+from switch_core.gateway.chats import get_chat_servicefrom switch_core.gateway.dependencies import (get_agent_store,get_config,@@ -417,6 +419,7 @@ async def update_agent_icon(user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],config: Annotated[SwitchConfig, Depends(get_config)],+ chat_service: Annotated[ChatService, Depends(get_chat_service)],) -> AgentSummary:"""Set, change, or clear an agent's icon (CHOO-2171).@@ -459,6 +462,7 @@ async def update_agent_icon(await agent_store.update(session, agent_id, icon_url=icon_url)await session.commit()await session.refresh(agent)+ await chat_service.agent_changed(require_tenant_id(), agent_id)logger.info("%s agent %s icon by user %s",@@ -479,6 +483,7 @@ async def update_agent_display_name(agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+ chat_service: Annotated[ChatService, Depends(get_chat_service)],) -> AgentSummary:"""Set, change, or clear an agent's human display name.@@ -513,6 +518,7 @@ async def update_agent_display_name(await agent_store.update(session, agent_id, display_name=display_name)await session.commit()await session.refresh(agent)+ await chat_service.agent_changed(require_tenant_id(), agent_id)logger.info("%s agent %s display name by user %s",diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.pyindex ab212ed74..83dca8980 100644--- a/core/switch_core/gateway/chats.py+++ b/core/switch_core/gateway/chats.py@@ -16,7 +16,7 @@ import loggingimport timefrom collections.abc import AsyncIteratorfrom datetime import datetime-from typing import Annotated+from typing import Annotated, Anyfrom fastapi import (APIRouter,@@ -526,6 +526,8 @@ class _ChatStream:self.after = afterself.cursors: dict[str, int] = {}self.announced: set[str] = set()+ self.sent: dict[str, dict[str, Any]] = {}+ self.resummarize = Falseself.dirty: set[str] = set()self.wake = asyncio.Event()@@ -534,6 +536,7 @@ class _ChatStream:self.wake.set()def on_memberships(self) -> None:+ self.resummarize = Trueself.wake.set()def close(self) -> None:@@ -544,6 +547,7 @@ class _ChatStream:def _untrack(self, room_id: str, reason: RemovalReason) -> bytes:self.service.listener.unsubscribe(room_id, self.on_room)self.cursors.pop(room_id, None)+ self.sent.pop(room_id, None)return _removed(room_id, reason)async def refresh(@@ -556,6 +560,7 @@ class _ChatStream:"""frames: list[bytes] = []service = self.service+ resummarize, self.resummarize = self.resummarize, Falseif read is None:await service.sync_owned_rooms(self.tenant_id, self.user.id)async with tenant_session(service.session_factory, self.tenant_id) as session:@@ -588,6 +593,7 @@ class _ChatStream:]:frames.append(_removed(room_id, "unlisted"))self.announced.discard(room_id)+ self.sent.pop(room_id, None)for room_id, room in readable.items():if room_id in self.cursors:continue@@ -596,28 +602,29 @@ class _ChatStream:if room_id in listed:self.announced.add(room_id)elif room_id in listed:- summary = await _summary(- service, session, self.tenant_id, self.user, room- )- frames.append(_frame("chat", summary.model_dump(by_alias=True)))+ frames.extend(await self._announce(session, room))self.cursors[room_id] = await service.head_seq(session, room_id)self.announced.add(room_id)else:self.cursors[room_id] = await service.head_seq(session, room_id)service.listener.subscribe(room_id, self.on_room)for room_id, room in listed.items():- if room_id in self.announced:- continue- summary = await _summary(- service, session, self.tenant_id, self.user, room- )- frames.append(_frame("chat", summary.model_dump(by_alias=True)))- self.announced.add(room_id)+ if room_id not in self.announced or resummarize:+ frames.extend(await self._announce(session, room))+ self.announced.add(room_id)for room_id in list(self.cursors) if read is None else read:if room_id in readable:frames.extend(await self._read(session, readable[room_id]))return frames, True+ async def _announce(self, session: AsyncSession, room: Room) -> list[bytes]:+ summary = await _summary(self.service, session, self.tenant_id, self.user, room)+ dump = summary.model_dump(by_alias=True)+ if self.sent.get(room.id) == dump:+ return []+ self.sent[room.id] = dump+ return [_frame("chat", dump)]+async def _read(self, session: AsyncSession, room: Room) -> list[bytes]:frames: list[bytes] = []while True:diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 3fa8ee4e5..fdab837e4 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -1118,6 +1118,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:ChatSignals(service=chat_service, bus=signal_bus)room_service.on_room_agents_changed(chat_service.sync_room)protocol.set_room_agents_listener(room_service.room_agents_changed)+ protocol.set_agent_profile_listener(chat_service.agent_changed)# ── Connector app credentials ─────────────────────────────────────────────# Each connector's app, from configuration or a row the operator saved,diff --git a/core/tests/switch_core/gateway/test_agent_display_name_route.py b/core/tests/switch_core/gateway/test_agent_display_name_route.pyindex 474159bcc..34ff96762 100644--- a/core/tests/switch_core/gateway/test_agent_display_name_route.py+++ b/core/tests/switch_core/gateway/test_agent_display_name_route.py@@ -7,6 +7,10 @@ refused at write time, and clearing is expressible and lands as NULL.from __future__ import annotations+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock+import pytestfrom fastapi import HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -25,6 +29,7 @@ _AGENT_STORE = AgentStore()_NAME = "Switch Dev"_OTHER_NAME = "Switch Reviewer"+_CHATS: Any = SimpleNamespace(agent_changed=AsyncMock())class TestUpdateAgentDisplayName:@@ -42,6 +47,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert summary.display_name == _NAME@@ -65,6 +71,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert summary.display_name == _NAME@@ -85,6 +92,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert summary.display_name == _OTHER_NAME@@ -108,6 +116,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert summary.display_name is None@@ -131,6 +140,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,other,await is_admin(session, other),+ _CHATS,)assert exc.value.status_code == 403@@ -153,6 +163,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,admin,await is_admin(session, admin),+ _CHATS,)assert summary.display_name == _NAME@@ -171,6 +182,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert exc.value.status_code == 404@@ -201,6 +213,7 @@ class TestUpdateAgentDisplayName:_AGENT_STORE,owner,await is_admin(session, owner),+ _CHATS,)assert exc.value.status_code == 400diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.pyindex 9671a1654..9d773d143 100644--- a/core/tests/switch_core/gateway/test_agent_icon_route.py+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py@@ -10,6 +10,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any+from unittest.mock import AsyncMockimport pytestfrom fastapi import HTTPException@@ -32,6 +33,7 @@ _OTHER_ICON = "https://cdn.example.com/9.x/shapes/png?seed=switch-worker"_AVATARS_ON: Any = SimpleNamespace(third_party_avatars_enabled=True)_AVATARS_OFF: Any = SimpleNamespace(third_party_avatars_enabled=False)+_CHATS: Any = SimpleNamespace(agent_changed=AsyncMock())class TestUpdateAgentIcon:@@ -50,6 +52,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert summary.icon_url == _ICON@@ -77,6 +80,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert summary.icon_url == generated_icon_url("a1")@@ -101,6 +105,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert summary.icon_url == _OTHER_ICON@@ -124,6 +129,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert summary.icon_url is None@@ -148,6 +154,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert summary.icon_url is None@@ -169,6 +176,7 @@ class TestUpdateAgentIcon:other,await is_admin(session, other),_AVATARS_ON,+ _CHATS,)assert exc.value.status_code == 403@@ -192,6 +200,7 @@ class TestUpdateAgentIcon:admin,await is_admin(session, admin),_AVATARS_ON,+ _CHATS,)assert summary.icon_url == _ICON@@ -211,6 +220,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert exc.value.status_code == 404@@ -246,6 +256,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)assert exc.value.status_code == 400@@ -271,6 +282,7 @@ class TestUpdateAgentIcon:owner,await is_admin(session, owner),_AVATARS_ON,+ _CHATS,)stored = await _AGENT_STORE.get(session, agent.id)@@ -298,6 +310,7 @@ class TestWithThirdPartyAvatarsOff:owner,await is_admin(session, owner),_AVATARS_OFF,+ _CHATS,)assert refused.value.status_code == 400@@ -321,6 +334,7 @@ class TestWithThirdPartyAvatarsOff:owner,await is_admin(session, owner),_AVATARS_OFF,+ _CHATS,)assert summary.icon_url == _ICONdiff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.pyindex c3a559394..fc0745638 100644--- a/core/tests/switch_core/gateway/test_chats_routes.py+++ b/core/tests/switch_core/gateway/test_chats_routes.py@@ -290,7 +290,7 @@ async def test_several_agents_make_a_private_channel_with_all_of_them(assert chat["channelType"] == "channel_private"assert chat["bridgeType"] is Noneassert sorted(a["id"] for a in chat["agents"]) == sorted([helper.id, other.id])- assert chat["name"] == "Chat with helper, other"+ assert chat["name"] == "New chat"async with chats.factory() as session:clients = set(await RoomStore().get_client_ids(session, chat["roomId"]))@@ -1054,6 +1054,32 @@ async def test_the_periodic_recheck_recovers_a_missed_notification(await events.stream.aclose() # type: ignore[attr-defined]+async def test_a_changed_agent_resends_the_chats_it_is_in(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200++ events = _stream(chats, chats.bob, {}, recheck=60.0)+ assert (await events.next())[0] == "chat"+ assert (await events.next())[0] == "ready"++ async with chats.factory() as session:+ await AgentStore().update(+ session,+ agent.id,+ icon_url="https://example.com/new.png",+ display_name="Helper",+ )+ await session.commit()+ await chats.service.agent_changed(TENANT, agent.id)++ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id+ assert summary["agents"][0]["iconUrl"] == "https://example.com/new.png"+ assert summary["agents"][0]["displayName"] == "Helper"+ await events.stream.aclose() # type: ignore[attr-defined]++def _stream_on(process: _Process, user: User) -> _Events:"""A stream held by `process` that re-reads on its own only after an hour,so whatever it says before then, something woke it to say."""diff --git a/core/tests/switch_core/gateway/test_chats_warm.py b/core/tests/switch_core/gateway/test_chats_warm.pyindex 383ee3c6b..64a07ac92 100644--- a/core/tests/switch_core/gateway/test_chats_warm.py+++ b/core/tests/switch_core/gateway/test_chats_warm.py@@ -1,12 +1,15 @@-"""`POST /chats/{room_id}/warm`: Switch Console asks the controller of the-user's own agent to start its session while the user types."""+"""Starting an agent's session for a chat before its first message: creating a+direct chat asks the agent's controller once, and `POST /chats/{room_id}/warm`+asks again for a chat Switch Console reuses."""from __future__ import annotationsimport asyncio+import loggingfrom collections.abc import Callableimport httpx+import pytestfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.controller_presence import (@@ -63,15 +66,77 @@ async def _eventually(check: Callable[[], bool]) -> None:await asyncio.sleep(0.02)+async def test_creating_a_direct_chat_starts_the_agents_session_once(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ controller = _on_controller(chats.connections, agent)++ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert await chats.new_chat(chats.alice, agent, "c1") == room_id++ await _eventually(lambda: controller.warms == {(agent.id, room_id)})+++async def test_creating_a_chat_with_several_agents_starts_no_session(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ _on_controller(chats.connections, helper)+ _on_controller(chats.connections, other)++ response = await chats.client.post(+ "/chats",+ json={"agentIds": [helper.id, other.id], "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )++ assert response.status_code == 200, response.text+++async def test_creating_a_chat_warns_when_the_controller_is_offline(+ chats: _Harness, caplog: pytest.LogCaptureFixture+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ controller = _on_controller(chats.connections, agent)+ chats.connections.controllers.detach_stream(controller, controller.stream_token)++ with caplog.at_level(logging.WARNING):+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ assert controller.warms == set()+ assert any(+ record.levelno == logging.WARNING and room_id in record.getMessage()+ for record in caplog.records+ )+++async def test_creating_a_chat_with_an_agent_no_controller_hosts_starts_nothing(+ chats: _Harness, caplog: pytest.LogCaptureFixture+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)++ with caplog.at_level(logging.WARNING, logger="switch_core.chats.service"):+ await chats.new_chat(chats.alice, agent, "c1")++ assert not [+ r+ for r in caplog.records+ if r.name == "switch_core.chats.service" and r.levelno >= logging.WARNING+ ]++async def test_a_warm_reaches_the_agents_controller(chats: _Harness) -> None:agent = await chats.agent("helper", owner=chats.alice)controller = _on_controller(chats.connections, agent)room_id = await chats.new_chat(chats.alice, agent, "c1")+ controller.warms.clear()response = await _warm(chats, chats.alice, room_id, agent)assert response.status_code == 202, response.text- assert controller.warms == {(agent.id, room_id)}+ await _eventually(lambda: controller.warms == {(agent.id, room_id)})async def test_a_warm_is_accepted_when_no_controller_takes_it(@@ -89,22 +154,18 @@ async def test_a_warm_is_accepted_when_no_controller_takes_it(assert controller.warms == set()-async def test_a_warm_refuses_non_members_others_agents_and_absent_agents(+async def test_a_warm_refuses_non_members_and_absent_agents(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)controller = _on_controller(chats.connections, agent)room_id = await chats.new_chat(chats.alice, agent, "c1")+ controller.warms.clear()outsider = await _warm(chats, chats.bob, room_id, agent)assert outsider.status_code == 403assert _code(outsider) == "NOT_A_MEMBER"- assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200- not_owner = await _warm(chats, chats.bob, room_id, agent)- assert not_owner.status_code == 403- assert _code(not_owner) == "NOT_AGENT_OWNER"-elsewhere = await chats.agent("elsewhere", owner=chats.alice)absent = await _warm(chats, chats.alice, room_id, elsewhere)assert absent.status_code == 422@@ -113,23 +174,27 @@ async def test_a_warm_refuses_non_members_others_agents_and_absent_agents(assert controller.warms == set()-async def test_a_warm_refuses_an_owner_the_agents_policy_refuses(+async def test_a_warm_follows_the_agents_policy_not_its_owner(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)controller = _on_controller(chats.connections, agent)room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ controller.warms.clear()++ member = await _warm(chats, chats.bob, room_id, agent)async with chats.factory() as session:row = await session.get(Agent, agent.id)assert row is not Nonerow.addressing_policy = {"rules": [{"users": [], "agents": []}]}await session.commit()-refused = await _warm(chats, chats.alice, room_id, agent)+ assert member.status_code == 202, member.textassert refused.status_code == 403assert _code(refused) == "AGENT_NOT_ALLOWED"- assert controller.warms == set()+ await _eventually(lambda: controller.warms == {(agent.id, room_id)})async def test_a_warm_reaches_a_controller_another_process_holds(