Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(console): New chat opens at once and makes its room on the first send

raullopez-sandboxd48462d6b072
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-view.tsx
index 4452673eb..08b1f92f2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-view.tsx
@@ -9,8 +9,10 @@ import { appState } from '@renderer/lib/stores/app-state';
import { ChatHeaderControls, ChatHeaderTitle } from './components/chat-header';
import { ChatPanel, useAgentActivities } from './components/chat-panel';
import { useOpenGroupAsRoom } from './console-chat-redirect';
+import { directChats } from './start-direct-chat';
import { agentChatsFlag } from './stores/agent-chats-flag';
import { chatsStore } from './stores/chats';
+import { UNSAVED_CHAT_PREFIX } from './stores/direct-chat-starter';
type ChatParams = { serverId: string; roomId: string; agentId: string | null };
@@ -94,6 +96,9 @@ export const chatView = {
(value.agentId !== null && value.agentId !== undefined && typeof value.agentId !== 'string')
)
return { ok: false, redirect: 'home', discardParams: true };
+ // An unsaved chat lives only in memory: one restored after a restart is gone.
+ if (value.roomId.startsWith(UNSAVED_CHAT_PREFIX) && !directChats.unsavedChat(value.roomId))
+ return { ok: false, redirect: 'home', discardParams: true };
return { ok: true };
},
} satisfies ViewDefinition<ChatParams>;
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.tsx
index 819415a5a..d419138a7 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
@@ -229,20 +229,23 @@ export const ChatComposer = observer(function ChatComposer({
workspaceId: workspacesStore.idOnServerInScope(serverId),
roomId: timeline.roomId,
});
- const [draft, setDraft] = useState(() => readChatDraft(draftKey)?.text ?? '');
+ // A draft whose send is still in flight here (the chat was reopened, or its room
+ // just made) is that send, not text to offer again.
+ const [initial] = useState(() => {
+ const kept = readChatDraft(draftKey);
+ const inFlight = timeline.pending.some((send) => send.requestId === kept?.pendingRequestId);
+ return { kept: inFlight ? null : kept, sending: inFlight ? kept!.pendingRequestId : null };
+ });
+ const [draft, setDraft] = useState(initial.kept?.text ?? '');
/** The mentions picked from the list, each with who it names, kept with the draft. */
- const [picked, setPicked] = useState<MentionToken[]>(
- () => readChatDraft(draftKey)?.mentions ?? []
- );
+ const [picked, setPicked] = useState<MentionToken[]>(initial.kept?.mentions ?? []);
/** The send that emptied the composer: its text stays kept until the server has taken it. */
- const [sending, setSending] = useState<string | null>(null);
+ const [sending, setSending] = useState<string | null>(initial.sending);
/**
* A send of the restored draft made before a reload, which may have landed:
* read from storage only, and gone once that draft is sent again or edited away.
*/
- const [resend, setResend] = useState<PendingResend | null>(() =>
- pendingOf(readChatDraft(draftKey))
- );
+ const [resend, setResend] = useState<PendingResend | null>(pendingOf(initial.kept));
const sendState =
sending === null
? null
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
index 1be1752b7..53a8db95e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
@@ -78,6 +78,17 @@ export const ChatPanel = observer(function ChatPanel({
}) {
const timeline = chatsStore.timelines.get(serverId, roomId);
const chat = chatsStore.chat(roomId);
+ const unsaved = directChats.unsavedChat(roomId);
+ // An unsaved chat has no summary yet; its agent is known from the agent's other chats, if any.
+ const agents =
+ chat?.agents ??
+ (unsaved
+ ? chatsStore
+ .chatsOfAgent(unsaved.agentId)
+ .flatMap((each) => each.agents)
+ .filter((agent) => agent.id === unsaved.agentId)
+ .slice(0, 1)
+ : []);
const activities = useAgentActivities(serverId, chat);
const people = useChatPeople(serverId, chat);
const [replyTo, setReplyTo] = useState<ChatMessage | null>(null);
@@ -163,7 +174,7 @@ export const ChatPanel = observer(function ChatPanel({
<ChatTimelineView
serverId={serverId}
timeline={timeline}
- agents={chat?.agents ?? []}
+ agents={agents}
people={people.known}
activities={activities}
onReply={setReplyTo}
@@ -188,17 +199,18 @@ export const ChatPanel = observer(function ChatPanel({
<ChatComposer
serverId={serverId}
timeline={timeline}
- agents={chat?.agents ?? []}
+ agents={agents}
// Everyone but the viewer can be mentioned from here.
people={people.members.filter((person) => person.userId !== chatsStore.userId)}
groupName={chat && chat.channelType !== 'direct' ? chat.name : null}
activity={activities[0] ?? null}
replyTo={replyTo}
onClearReply={() => setReplyTo(null)}
- disabled={composerBlocked({
- offline: chatsStore.streamState === 'offline' && !timeline.loaded,
- startingNewChat: directChats.starting,
- })}
+ disabled={
+ chatsStore.streamState === 'offline' && !timeline.loaded
+ ? 'Switch cannot be reached right now.'
+ : null
+ }
/>
</div>
);
@@ -263,20 +275,6 @@ const ReadWhileFollowing = observer(function ReadWhileFollowing({
return null;
});
-/**
- * Why the composer takes nothing now, or null. While a new chat is being
- * made, this one's composer waits: a quick send would land here, in the chat
- * being left, just before the new one opens.
- */
-export function composerBlocked(state: {
- offline: boolean;
- startingNewChat: boolean;
-}): string | null {
- if (state.startingNewChat) return 'Starting a new chat…';
- if (state.offline) return 'Switch cannot be reached right now.';
- return null;
-}
-
/**
* Sending from here jumps to the end and resumes following, wherever the
* reader had scrolled to: what they just sent is what they want to see.
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.tsx
index 746f6123c..81e39b618 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
@@ -8,11 +8,9 @@ import {
DropdownMenuTrigger,
} from '@renderer/lib/ui/dropdown-menu';
import { RelativeTime } from '@renderer/lib/ui/relative-time';
-import { cn } from '@renderer/utils/utils';
import type { ChatSummary } from '@shared/core/chats/chats';
import { agentActivities } from '../stores/activities';
import { chatsStore } from '../stores/chats';
-import { reuseFlash } from '../stores/reuse-flash';
import { ChatActionItems, chatActions } from './chat-actions';
import { UnreadBadge } from './unread-badge';
@@ -40,19 +38,9 @@ export const ChatRow = observer(function ChatRow({
}) {
const [menuOpen, setMenuOpen] = useState(false);
const busy = chatBusy(serverId, chat);
- const reused = reuseFlash.roomId === chat.roomId;
const actions = chatActions(serverId, chat);
return (
- <SidebarMenuRow
- className={cn(
- 'group/row justify-between transition-colors duration-500',
- // New chat reused this empty chat rather than making another: it says so.
- reused && 'bg-[var(--sel-soft)] ring-1 ring-[var(--sel)]'
- )}
- data-reused={reused || undefined}
- isActive={isActive}
- onClick={onOpen}
- >
+ <SidebarMenuRow className="group/row justify-between" isActive={isActive} onClick={onOpen}>
<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">
<MessageSquare className="size-4 text-foreground-muted" />
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.ts
index cb7a7ae68..94322a7d2 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,41 +1,44 @@
-import { toast } from '@renderer/lib/hooks/use-toast';
+import { runInAction } from 'mobx';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
-import { log } from '@renderer/utils/logger';
+import { appState } from '@renderer/lib/stores/app-state';
import { focusComposerWhenOpened } from './components/chat-composer';
+import { chatDraftKey, moveChatDraft } from './stores/chat-drafts';
import { chatsStore, chatTitler } from './stores/chats';
import { DirectChatStarter } from './stores/direct-chat-starter';
-import { EmptyChatFinder } from './stores/empty-chat-finder';
-import { reuseFlash } from './stores/reuse-flash';
-const emptyChatFinder = new EmptyChatFinder({
- chatsOfAgent: (agentId) => chatsStore.chatsOfAgent(agentId),
- userId: () => chatsStore.userId,
- timeline: (roomId) => {
- const timeline = chatsStore.timelines.peek(chatsStore.serverId ?? '', roomId);
- return timeline ? { messages: timeline.messages, loaded: timeline.loaded } : undefined;
- },
-});
-
-/** Starts a direct chat with one agent, named later from its first message. */
+/** Starts a direct chat with one agent, made on its first message and named from it. */
export const directChats = new DirectChatStarter({
create: (input) => rpc.chats.create(input),
- created: (serverId, chat) => {
- chatsStore.add(serverId, chat);
- chatTitler.created(chat, false);
+ opened: (chat, create) => {
+ if (!chatsStore.timelines.peek(chat.serverId, chat.roomId))
+ chatsStore.timelines.unsaved(chat.serverId, chat.roomId, create);
focusComposerWhenOpened(chat.roomId);
},
- opened: (chat) => {
- focusComposerWhenOpened(chat.roomId);
- reuseFlash.flash(chat.roomId);
+ created: ({ serverId, roomId: from }, chat) => {
+ const draftKey = (roomId: string) =>
+ chatDraftKey({
+ serverId,
+ userId: switchServersStore.statusFor(serverId)?.user?.id ?? null,
+ workspaceId: workspacesStore.idOnServerInScope(serverId),
+ roomId,
+ });
+ moveChatDraft(draftKey(from), draftKey(chat.roomId));
+ if (document.activeElement?.closest('[data-chat-panel]')) focusComposerWhenOpened(chat.roomId);
+ runInAction(() => {
+ chatsStore.timelines.rekey(serverId, from, chat.roomId);
+ chatsStore.add(serverId, chat);
+ for (const entry of appState.history.entries)
+ if (entry.kind === 'view' && (entry.params as { roomId?: string }).roomId === from)
+ entry.params = { ...entry.params, roomId: chat.roomId };
+ for (const viewId of ['chat', 'managedAgent'] as const)
+ if (appState.navigation.viewParamsStore[viewId]?.roomId === from)
+ appState.navigation.updateViewParams(viewId, { roomId: chat.roomId });
+ });
+ chatTitler.created(chat, false);
+ const first = chatsStore.timelines.peek(serverId, chat.roomId)?.pending[0];
+ if (first) void chatTitler.sent(serverId, chat.roomId, first.body);
},
- 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),
newId: () => crypto.randomUUID(),
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts
index c92ae8618..7de9470a5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts
@@ -81,3 +81,11 @@ export function writeChatDraft(key: string, draft: ChatDraft): void {
} else if (draft.text === '') localStorage.removeItem(key);
else localStorage.setItem(key, JSON.stringify(draft));
}
+
+/** Move the draft kept under `from` to `to`: an unsaved chat's, to the room it became. */
+export function moveChatDraft(from: string, to: string): void {
+ const draft = readChatDraft(from);
+ if (!draft) return;
+ writeChatDraft(to, draft);
+ writeChatDraft(from, { ...draft, text: '' });
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
index fe98831ac..ffed31d81 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
@@ -116,7 +116,8 @@ export class ChatTimeline {
threadReplyCounts = new Map<string, number>();
constructor(
- readonly roomId: string,
+ /** Changes once, from an unsaved chat's id to its room's when the room is made. */
+ public roomId: string,
private readonly api: TimelineApi
) {
makeAutoObservable<ChatTimeline, 'api'>(this, { api: false, roomId: false });
@@ -424,6 +425,44 @@ export class ChatTimelines {
return timeline;
}
+ /**
+ * The timeline of a chat whose room does not exist yet: nothing to load, and
+ * its first upload or send makes the room through `create` before going to it.
+ */
+ unsaved(serverId: string, roomId: string, create: () => Promise<string>): ChatTimeline {
+ const api = this.api(serverId);
+ const room = (id: string) => (id === roomId ? create() : Promise.resolve(id));
+ const key = `${serverId}\u0000${roomId}`;
+ const timeline = new ChatTimeline(roomId, {
+ ...api,
+ messages: (id, beforeSeq, limit) =>
+ id === roomId
+ ? Promise.resolve({ messages: [], headSeq: 0, hasMore: false })
+ : api.messages(id, beforeSeq, limit),
+ upload: async (id, file) => api.upload(await room(id), file),
+ send: async (id, input) => api.send(await room(id), input),
+ });
+ runInAction(() => {
+ timeline.loaded = true;
+ });
+ this.timelines.set(key, timeline);
+ queueMicrotask(() => runInAction(() => this.opened.add(key)));
+ return timeline;
+ }
+
+ /** The unsaved chat's room was made: its timeline, sends in flight and all, is that room's now. */
+ rekey(serverId: string, from: string, to: string): void {
+ const timeline = this.timelines.get(`${serverId}\u0000${from}`);
+ if (!timeline) return;
+ this.timelines.delete(`${serverId}\u0000${from}`);
+ timeline.roomId = to;
+ this.timelines.set(`${serverId}\u0000${to}`, timeline);
+ runInAction(() => {
+ this.opened.delete(`${serverId}\u0000${from}`);
+ this.opened.add(`${serverId}\u0000${to}`);
+ });
+ }
+
peek(serverId: string, roomId: string): ChatTimeline | undefined {
const key = `${serverId}\u0000${roomId}`;
this.opened.has(key);
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.ts
index d9d968c55..c0861343a 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
@@ -1,6 +1,16 @@
-import { observable, runInAction } from 'mobx';
import type { ChatSummary } from '@shared/core/chats/chats';
-import { chatFailure } from './chat-errors';
+
+/** Prefix of the id a direct chat goes by on screen until its room exists. */
+export const UNSAVED_CHAT_PREFIX = 'unsaved-chat:';
+
+export type UnsavedChat = {
+ serverId: string;
+ agentId: string;
+ /** The id it goes by on screen until its room exists. */
+ roomId: string;
+ /** One per unsaved chat: every attempt to make its room is the same request, so the server makes one room. */
+ requestId: string;
+};
export type DirectChatStarterDeps = {
create: (input: {
@@ -10,71 +20,72 @@ export type DirectChatStarterDeps = {
requestId: string;
greeting: null;
}) => 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;
+ /** The unsaved chat is being opened, new or again; `create` makes its room, on its first send. */
+ opened: (chat: UnsavedChat, create: () => Promise<string>) => void;
+ /** Its room exists: the chat moves from its unsaved id to the room's. */
+ created: (unsaved: UnsavedChat, chat: ChatSummary) => void;
newId: () => string;
};
/**
- * Starts an unnamed direct chat with one agent. Reuses an existing empty chat
- * (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.
+ * Starts an unnamed direct chat with one agent. Nothing is asked of the server
+ * until the first message: the chat opens at once under an unsaved id, and its
+ * room is made as that message is sent. Starting again for the same agent
+ * before then opens the same unsaved chat, with whatever was typed in it.
*/
export class DirectChatStarter {
- private readonly inFlight = observable.set<string>();
- private readonly retryIds = new Map<string, string>();
+ private readonly unsaved = new Map<string, UnsavedChat>();
+ private readonly byRoomId = new Map<string, UnsavedChat>();
+ private readonly creating = new Map<string, Promise<string>>();
constructor(private readonly deps: DirectChatStarterDeps) {}
- /** A new chat is being made: until it opens, a message typed now has no right room to go to. */
- get starting(): boolean {
- return this.inFlight.size > 0;
+ /** The id of the chat to open: the agent's unsaved one, made now if it has none. */
+ start(serverId: string, agentId: string): string {
+ const key = `${serverId}:${agentId}`;
+ let chat = this.unsaved.get(key);
+ if (!chat) {
+ const requestId = this.deps.newId();
+ chat = { serverId, agentId, roomId: `${UNSAVED_CHAT_PREFIX}${requestId}`, requestId };
+ this.unsaved.set(key, chat);
+ this.byRoomId.set(chat.roomId, chat);
+ }
+ const opened = chat;
+ this.deps.opened(opened, () => this.create(opened));
+ return chat.roomId;
}
- async start(serverId: string, agentId: string): Promise<ChatSummary | null> {
- const existing = this.deps.findEmpty(agentId);
- if (existing) {
- this.deps.opened(existing);
- this.deps.warm(serverId, agentId, existing.roomId);
- return existing;
- }
+ /** The unsaved chat shown under `roomId`, while its room does not exist yet. */
+ unsavedChat(roomId: string): UnsavedChat | undefined {
+ return this.byRoomId.get(roomId);
+ }
- const key = `${serverId}:${agentId}`;
- if (this.inFlight.has(key)) return null;
- runInAction(() => this.inFlight.add(key));
- const requestId = this.retryIds.get(key) ?? this.deps.newId();
- try {
- const chat = await this.deps.create({
- serverId,
- agentIds: [agentId],
- name: null,
- requestId,
- greeting: null,
- });
- this.retryIds.delete(key);
- this.deps.created(serverId, chat);
- return chat;
- } catch (caught) {
- const failure = chatFailure(caught);
- if (failure.kind === 'other' && failure.uncertain) {
- this.retryIds.set(key, requestId);
- this.deps.failed(
- `${failure.message} Try again: it resumes the same chat rather than making another.`
+ /** Make the chat's room, once however often asked; a failure lets the next ask try again under the same request id. */
+ private create(chat: UnsavedChat): Promise<string> {
+ let creating = this.creating.get(chat.roomId);
+ if (!creating) {
+ creating = this.deps
+ .create({
+ serverId: chat.serverId,
+ agentIds: [chat.agentId],
+ name: null,
+ requestId: chat.requestId,
+ greeting: null,
+ })
+ .then(
+ (created) => {
+ this.unsaved.delete(`${chat.serverId}:${chat.agentId}`);
+ this.byRoomId.delete(chat.roomId);
+ this.deps.created(chat, created);
+ return created.roomId;
+ },
+ (error: unknown) => {
+ this.creating.delete(chat.roomId);
+ throw error;
+ }
);
- } else {
- this.retryIds.delete(key);
- this.deps.failed(failure.message);
- }
- return null;
- } finally {
- runInAction(() => this.inFlight.delete(key));
+ this.creating.set(chat.roomId, creating);
}
+ return creating;
}
}
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.ts
deleted file mode 100644
index c0f60d7ec..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts
+++ /dev/null
@@ -1,479 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
-import { EmptyChatFinder } from './empty-chat-finder';
-
-const makeChat = (overrides: Partial<ChatSummary> = {}): ChatSummary => ({
- roomId: 'room-1',
- name: 'Chat',
- channelType: 'direct',
- bridgeType: null,
- channelName: null,
- agents: [
- {
- id: 'agent-1',
- name: 'Agent',
- displayName: null,
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- canManage: false,
- ownsAgent: false,
- memberUserIds: [],
- memberCount: 0,
- unreadCount: 0,
- lastMessage: null,
- ...overrides,
-});
-
-const makeMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
- messageId: 'msg-1',
- seq: 1,
- roomId: 'room-1',
- sentAt: '2024-01-01T00:00:00Z',
- sender: {
- clientId: 'client-1',
- name: 'User',
- kind: 'human',
- agentId: null,
- userId: 'user-1',
- },
- source: 'text',
- body: 'Hello',
- format: null,
- threadRootId: null,
- attachments: [],
- clientTxn: null,
- namedAgentIds: [],
- namedUserIds: [],
- mentions: [],
- threadReplyCount: 0,
- threadLastReplySeq: null,
- ...overrides,
-});
-
-describe('EmptyChatFinder', () => {
- it('returns null when userId is null', () => {
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [],
- userId: () => null,
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns null when no chats exist for agent', () => {
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns chat with no messages', () => {
- const chat = makeChat({ roomId: 'room-1', lastMessage: null });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBe(chat);
- });
-
- it('returns null when chat has user message (from summary)', () => {
- const chat = makeChat({
- lastMessage: {
- seq: 1,
- sentAt: '2024-01-01T00:00:00Z',
- preview: 'Hello',
- senderName: 'User',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns chat with only agent messages when timeline is loaded', () => {
- const chat = makeChat({ roomId: 'room-1' });
- const agentMessage = makeMessage({
- sender: {
- clientId: 'client-2',
- name: 'Agent',
- kind: 'agent',
- agentId: 'agent-1',
- userId: null,
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: (roomId) =>
- roomId === 'room-1' ? { messages: [agentMessage], loaded: true } : undefined,
- });
-
- expect(finder.find('agent-1')).toBe(chat);
- });
-
- it('returns null when timeline has user message', () => {
- const chat = makeChat({ roomId: 'room-1' });
- const userMessage = makeMessage({
- sender: {
- clientId: 'client-1',
- name: 'User',
- kind: 'human',
- agentId: null,
- userId: 'user-1',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: (roomId) =>
- roomId === 'room-1' ? { messages: [userMessage], loaded: true } : undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns null when timeline has both agent and user messages', () => {
- const chat = makeChat({ roomId: 'room-1' });
- const agentMessage = makeMessage({
- seq: 1,
- sender: {
- clientId: 'client-2',
- name: 'Agent',
- kind: 'agent',
- agentId: 'agent-1',
- userId: null,
- },
- });
- const userMessage = makeMessage({
- seq: 2,
- sender: {
- clientId: 'client-1',
- name: 'User',
- kind: 'human',
- agentId: null,
- userId: 'user-1',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: (roomId) =>
- roomId === 'room-1' ? { messages: [agentMessage, userMessage], loaded: true } : undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns most recent empty chat', () => {
- const older = makeChat({
- roomId: 'room-1',
- lastMessage: null,
- });
- const newer = makeChat({
- roomId: 'room-2',
- lastMessage: null,
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [newer, older],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBe(newer);
- });
-
- it('prefers timeline over summary when timeline is loaded', () => {
- const chat = makeChat({
- roomId: 'room-1',
- lastMessage: {
- seq: 1,
- sentAt: '2024-01-01T00:00:00Z',
- preview: 'Hello',
- senderName: 'Agent',
- },
- });
- const agentMessage = makeMessage({
- sender: {
- clientId: 'client-2',
- name: 'Agent',
- kind: 'agent',
- agentId: 'agent-1',
- userId: null,
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: (roomId) =>
- roomId === 'room-1' ? { messages: [agentMessage], loaded: true } : undefined,
- });
-
- expect(finder.find('agent-1')).toBe(chat);
- });
-
- it('uses summary when timeline not loaded', () => {
- const chat = makeChat({ roomId: 'room-1', lastMessage: null });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: (roomId) => (roomId === 'room-1' ? { messages: [], loaded: false } : undefined),
- });
-
- expect(finder.find('agent-1')).toBe(chat);
- });
-
- it('returns chat with default name and agent greeting when timeline not loaded', () => {
- const chat = makeChat({
- roomId: 'room-1',
- name: 'Chat with Agent',
- agents: [
- {
- id: 'agent-1',
- name: 'Agent',
- displayName: null,
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- 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 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,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- 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 the earlier "New chat" name and an agent greeting', () => {
- const chat = makeChat({
- roomId: 'room-1',
- name: 'New chat',
- agents: [
- {
- id: 'agent-1',
- name: 'Agent',
- displayName: null,
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- 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',
- name: 'Chat with Ada',
- agents: [
- {
- id: 'agent-1',
- name: 'ada',
- displayName: 'Ada',
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- lastMessage: {
- seq: 1,
- sentAt: '2024-01-01T00:00:00Z',
- preview: 'Hello',
- senderName: 'Ada',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBe(chat);
- });
-
- it('returns null when chat has default name but last message from user', () => {
- const chat = makeChat({
- roomId: 'room-1',
- name: 'Chat with Agent',
- lastMessage: {
- seq: 1,
- sentAt: '2024-01-01T00:00:00Z',
- preview: 'Hello',
- senderName: 'User',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- it('returns null when chat has custom name even with agent greeting', () => {
- const chat = makeChat({
- roomId: 'room-1',
- name: 'My Custom Chat',
- 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')).toBeNull();
- });
-
- it('never reuses a chat with more than one agent, which is a group', () => {
- const chat = makeChat({
- roomId: 'room-1',
- name: 'Chat with Ada, Bob',
- agents: [
- {
- id: 'agent-1',
- name: 'ada',
- displayName: 'Ada',
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- {
- id: 'agent-2',
- name: 'bob',
- displayName: 'Bob',
- iconUrl: null,
- provider: null,
- alias: null,
- ownerName: null,
- ownedByViewer: false,
- },
- ],
- lastMessage: {
- seq: 1,
- sentAt: '2024-01-01T00:00:00Z',
- preview: 'Hello',
- senderName: 'Ada',
- },
- });
- const finder = new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- expect(finder.find('agent-1')).toBeNull();
- });
-
- describe('only the viewer’s own 1:1 with the agent', () => {
- const finder = (chat: ChatSummary) =>
- new EmptyChatFinder({
- chatsOfAgent: () => [chat],
- userId: () => 'user-1',
- timeline: () => undefined,
- });
-
- it('reuses an empty direct chat with just the viewer in it', () => {
- const chat = makeChat({ memberUserIds: ['user-1'], memberCount: 1 });
- expect(finder(chat).find('agent-1')).toBe(chat);
- });
-
- it('never reuses an empty group, even one that was a direct chat', () => {
- const converted = makeChat({
- channelType: 'channel_private',
- memberUserIds: ['user-1', 'user-2'],
- memberCount: 2,
- });
- expect(finder(converted).find('agent-1')).toBeNull();
- const peopleInDirect = makeChat({ memberUserIds: ['user-1', 'user-2'], memberCount: 2 });
- expect(finder(peopleInDirect).find('agent-1')).toBeNull();
- });
-
- it('never reuses a bridged room or another agent’s chat', () => {
- expect(finder(makeChat({ bridgeType: 'slack' })).find('agent-1')).toBeNull();
- expect(finder(makeChat()).find('agent-2')).toBeNull();
- });
- });
-});
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.ts
deleted file mode 100644
index 949414236..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';
-import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
-
-export type LoadedTimeline = {
- messages: ChatMessage[];
- loaded: boolean;
-};
-
-export type EmptyChatFinderDeps = {
- chatsOfAgent: (agentId: string) => ChatSummary[];
- userId: () => string | null;
- timeline: (roomId: string) => LoadedTimeline | undefined;
-};
-
-/**
- * Finds the most recent empty chat for an agent, where "empty" means the
- * current user has sent no messages. Agent greetings don't count as use.
- * Only the viewer's own 1:1 with that agent qualifies: a group, even one that
- * began as a direct chat, or a bridged room would carry a private message to
- * others.
- */
-export class EmptyChatFinder {
- constructor(private readonly deps: EmptyChatFinderDeps) {}
-
- find(agentId: string): ChatSummary | null {
- const userId = this.deps.userId();
- if (!userId) return null;
-
- const chats = this.deps.chatsOfAgent(agentId);
- const empty = chats.filter(
- (chat) => isOwnDirectChat(chat, agentId, userId) && this.isEmpty(chat, userId)
- );
- return empty[0] ?? null;
- }
-
- private isEmpty(chat: ChatSummary, userId: string): boolean {
- const timeline = this.deps.timeline(chat.roomId);
-
- if (timeline?.loaded) {
- return timeline.messages.every((msg) => msg.sender.userId !== userId);
- }
-
- if (chat.lastMessage === null) return true;
-
- const lastMessageFromAgent = chat.agents.some(
- (agent) =>
- chat.lastMessage?.senderName === agent.name ||
- chat.lastMessage?.senderName === agent.displayName
- );
-
- return this.hasDefaultName(chat) && lastMessageFromAgent;
- }
-
- /** "New Chat" now; "New chat" and "Chat with <agents>" for chats made before. */
- private hasDefaultName(chat: ChatSummary): boolean {
- const agentNames = chat.agents.map((agent) => agent.displayName || agent.name).join(', ');
- return (
- chat.name === 'New Chat' ||
- chat.name === 'New chat' ||
- chat.name === `Chat with ${agentNames}`
- );
- }
-}
-
-/**
- * A Switch Console 1:1 between the viewer and this one agent: direct, unbridged,
- * that agent alone, and nobody else in it (where the server says who is).
- */
-export function isOwnDirectChat(chat: ChatSummary, agentId: string, userId: string): boolean {
- return (
- isConsoleDirectChatSummary(chat) &&
- chat.agents[0]?.id === agentId &&
- chat.memberUserIds.every((member) => member === userId)
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.test.ts
deleted file mode 100644
index 460693053..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { REUSE_FLASH_MS, ReuseFlash } from './reuse-flash';
-
-afterEach(() => vi.useRealTimers());
-
-describe('ReuseFlash', () => {
- it('marks the reused chat for a moment, the latest one only', () => {
- vi.useFakeTimers();
- const flash = new ReuseFlash();
- flash.flash('r1');
- expect(flash.roomId).toBe('r1');
- vi.advanceTimersByTime(REUSE_FLASH_MS / 2);
- flash.flash('r2');
- vi.advanceTimersByTime(REUSE_FLASH_MS / 2);
- expect(flash.roomId).toBe('r2');
- vi.advanceTimersByTime(REUSE_FLASH_MS);
- expect(flash.roomId).toBeNull();
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.ts
deleted file mode 100644
index a2b82a036..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/reuse-flash.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { makeAutoObservable } from 'mobx';
-
-/** How long a chat New chat reused stands out, so the click visibly did something. */
-export const REUSE_FLASH_MS = 1_500;
-
-/**
- * The chat New chat just reused instead of making another: the same empty chat
- * is shown again, often the one already open, and without a sign the click
- * looks like it did nothing.
- */
-export class ReuseFlash {
- roomId: string | null = null;
- private timer: ReturnType<typeof setTimeout> | null = null;
-
- constructor() {
- makeAutoObservable<ReuseFlash, 'timer'>(this, { timer: false });
- }
-
- flash(roomId: string): void {
- this.roomId = roomId;
- if (this.timer) clearTimeout(this.timer);
- this.timer = setTimeout(() => this.clear(roomId), REUSE_FLASH_MS);
- }
-
- private clear(roomId: string): void {
- if (this.roomId === roomId) this.roomId = null;
- this.timer = null;
- }
-}
-
-export const reuseFlash = new ReuseFlash();
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.tsx
index 338045a86..5e66f931f 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
@@ -167,16 +167,15 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
)}
{newChat && (
<Button
- onClick={async () => {
+ onClick={() => {
const serverId = agent.serverId as string;
const switchAgentId = agent.switchAgentId as string;
if (chatsTab) {
navigate('managedAgent', { serverId, agentId: switchAgentId, name: title });
return;
}
- const chat = await directChats.start(serverId, switchAgentId);
- if (chat)
- navigate('chat', { serverId, roomId: chat.roomId, agentId: switchAgentId });
+ const roomId = directChats.start(serverId, switchAgentId);
+ navigate('chat', { serverId, roomId, agentId: switchAgentId });
}}
>
New chat
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.tsx
index ca3a0a079..fbd30ff3d 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
@@ -160,19 +160,19 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
const { sections, section } = useAgentSection(serverId, agent, params.section);
const thisComputer = useRunsOnThisComputer(agent);
const shownRoom = openAgentRoom(agent, params.room, section);
- const roomId = shownRoom ? null : (openAgentChat(agent, params.roomId)?.roomId ?? null);
+ const roomId = shownRoom
+ ? null
+ : params.roomId && directChats.unsavedChat(params.roomId)
+ ? params.roomId
+ : (openAgentChat(agent, params.roomId)?.roomId ?? null);
const open = (id: string) => setParams({ roomId: id, section: undefined, room: undefined });
// The chat open here that becomes a group follows into its room, rather than another chat taking its place.
useOpenGroupAsRoom(shownRoom || section ? null : (params.roomId ?? null), 'managedAgent');
- const newChat = async () => {
- const chat = await directChats.start(serverId, agentId);
- if (chat) open(chat.roomId);
- };
+ const newChat = () => open(directChats.start(serverId, agentId));
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,
@@ -183,8 +183,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
useEffect(() => {
if (!autoStart) return;
autoStartTried.current = true;
- setAutoStarting(true);
- void newChat().finally(() => setAutoStarting(false));
+ newChat();
// oxlint-disable-next-line react-hooks/exhaustive-deps -- runs when the decision turns true, not when newChat is redefined
}, [autoStart]);
@@ -200,12 +199,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
selected={section}
onSelect={(chosen) => setParams({ section: chosen })}
/>
- <Section
- title="Direct chats"
- addLabel="New chat"
- onAdd={() => void newChat()}
- addChoices={null}
- >
+ <Section title="Direct chats" addLabel="New chat" onAdd={newChat} addChoices={null}>
{ownServer && chatsStore.listError && (
<div
role="alert"
@@ -288,11 +282,11 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
className="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 : (
+ ) : listing || autoStart ? null : (
<EmptyState
label="No chat open"
description="Start a chat with this agent."
- action={<Button onClick={() => void newChat()}>Start a chat</Button>}
+ action={<Button onClick={newChat}>Start a chat</Button>}
/>
)}
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
index 35a603129..bd8406159 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
@@ -10,7 +10,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
// Geometry is the subject, so the real utility classes must be present.
import '@renderer/index.css';
import { ChatComposer } from '@renderer/features/chats/components/chat-composer';
-import { composerBlocked } from '@renderer/features/chats/components/chat-panel';
import {
ChatTimeline,
type TimelineApi,
@@ -197,44 +196,3 @@ describe('ChatComposer on a server without group chats', () => {
}
});
});
-
-describe('ChatComposer while a new chat is being made', () => {
- it('sends nothing to the chat being left, and keeps the draft', async () => {
- const send = vi.fn();
- const timeline = new ChatTimeline('room-old', {} as TimelineApi);
- timeline.send = send;
- const composer = (disabled: string | null) => (
- <QueryClientProvider client={new QueryClient()}>
- <ChatComposer
- serverId="s"
- timeline={timeline}
- agents={[agent]}
- people={[]}
- groupName={null}
- activity={null}
- replyTo={null}
- onClearReply={() => {}}
- disabled={disabled}
- />
- </QueryClientProvider>
- );
- const textarea = await render(composer(null));
- await act(async () => {
- textarea.focus();
- document.execCommand('insertText', false, 'for the old chat?');
- });
- // The new chat is being made: the composer waits.
- await act(async () =>
- root!.render(composer(composerBlocked({ offline: false, startingNewChat: true })))
- );
- const waiting = container!.querySelector('textarea')!;
- expect(waiting.disabled).toBe(true);
- expect(waiting.placeholder).toBe('Starting a new chat…');
- await act(async () => {
- waiting.form?.requestSubmit();
- });
- expect(send).not.toHaveBeenCalled();
- // The draft is the old chat's still, not sent anywhere.
- expect(waiting.value).toBe('for the old chat?');
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx
index 08286fa41..b41f00edf 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx
@@ -20,7 +20,11 @@ vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
}));
import { ChatComposer } from '@renderer/features/chats/components/chat-composer';
-import { chatDraftKey, readChatDraft } from '@renderer/features/chats/stores/chat-drafts';
+import {
+ chatDraftKey,
+ moveChatDraft,
+ readChatDraft,
+} from '@renderer/features/chats/stores/chat-drafts';
import {
ChatTimeline,
type TimelineApi,
@@ -177,6 +181,30 @@ describe('chat drafts', () => {
textarea = await mount(new ChatTimeline('room-1', api(vi.fn())));
expect(textarea.value).toBe('do not lose me');
});
+ it('move with an unsaved chat to its room, a send in flight showing as sent rather than as text again', async () => {
+ let finish: () => void = () => {};
+ const send = vi.fn(() => new Promise<[]>((resolve) => (finish = () => resolve([]))));
+ const timeline = new ChatTimeline('unsaved-chat:1', api(send));
+ let textarea = await mount(timeline);
+ await type(textarea, 'first message');
+ await pressEnter(textarea);
+ expect(textarea.value).toBe('');
+
+ // Its room is made while the send is in flight: the chat reopens under the room's id.
+ moveChatDraft(key('user-a', 'ws-1', 'unsaved-chat:1'), key('user-a', 'ws-1', 'r1'));
+ timeline.roomId = 'r1';
+ await unmount();
+ textarea = await mount(timeline);
+ expect(textarea.value).toBe('');
+ expect(readChatDraft(key('user-a', 'ws-1', 'r1'))?.pendingRequestId).toBe(
+ timeline.pending[0]?.requestId
+ );
+ expect(readChatDraft(key('user-a', 'ws-1', 'unsaved-chat:1'))).toBeNull();
+
+ await act(async () => finish());
+ expect(readChatDraft(key('user-a', 'ws-1', 'r1'))).toBeNull();
+ });
+
it('shows the other room’s draft, or none, in the same composer, and never carries one over', async () => {
localStorage.setItem(
key('user-a', 'ws-1', 'room-a'),
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-row-reused.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-row-reused.test.tsx
deleted file mode 100644
index 88a0153b3..000000000
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-row-reused.test.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-/** A chat New chat reused stands out in the list for a moment, so the click visibly did something. */
-import { act } from 'react';
-import { createRoot } from 'react-dom/client';
-import { expect, it, vi } from 'vitest';
-import { ChatRow } from '@renderer/features/chats/components/chat-row';
-import { REUSE_FLASH_MS, reuseFlash } from '@renderer/features/chats/stores/reuse-flash';
-import type { ChatSummary } from '@shared/core/chats/chats';
-
-const chat = {
- roomId: 'r1',
- name: 'New Chat',
- channelType: 'direct',
- bridgeType: null,
- channelName: null,
- agents: [],
- canManage: true,
- ownsAgent: true,
- memberUserIds: [],
- memberCount: 1,
- unreadCount: 0,
- lastMessage: null,
-} as unknown as ChatSummary;
-
-it('highlights the reused chat, then lets it go', async () => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- const container = document.createElement('div');
- document.body.appendChild(container);
- const root = createRoot(container);
- await act(async () =>
- root.render(<ChatRow serverId="s" chat={chat} isActive onOpen={() => {}} />)
- );
- const row = () => container.querySelector('[data-reused]');
- expect(row()).toBeNull();
-
- await act(async () => reuseFlash.flash('r1'));
- expect(row()).not.toBeNull();
- await act(async () => vi.advanceTimersByTime(REUSE_FLASH_MS + 10));
- expect(row()).toBeNull();
-
- vi.useRealTimers();
- await act(async () => root.unmount());
- container.remove();
-});
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.ts
index ae4fe0ead..78878eb09 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
@@ -1,111 +1,159 @@
-import { autorun, configure } from 'mobx';
import { describe, expect, it, vi } from 'vitest';
+import {
+ ChatTimelines,
+ type TimelineApi,
+} from '@renderer/features/chats/stores/chat-timeline-store';
import { DirectChatStarter } from '@renderer/features/chats/stores/direct-chat-starter';
-import type { ChatSummary } from '@shared/core/chats/chats';
+import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
const chat = { roomId: 'r1', channelType: 'direct' } as ChatSummary;
-function setup(
- create: () => Promise<ChatSummary>,
- findEmpty: () => ChatSummary | null = () => null
-) {
+/** The starter wired to real timelines, as the app wires it, over fake RPCs. */
+function setup() {
let id = 0;
- const deps = {
- create: vi.fn(create),
- created: vi.fn(),
- opened: vi.fn(),
- warm: vi.fn(),
- failed: vi.fn(),
- findEmpty: vi.fn(findEmpty),
+ const api = {
+ messages: vi.fn(async () => ({ messages: [], headSeq: 0, hasMore: false })),
+ threadMessages: vi.fn(),
+ upload: vi.fn(),
+ send: vi.fn(
+ async (roomId: string, input: { requestId: string; body: string }) =>
+ [
+ {
+ roomId,
+ seq: 1,
+ messageId: 'm1',
+ body: input.body,
+ clientTxn: `${input.requestId}:0`,
+ },
+ ] as unknown as ChatMessage[]
+ ),
+ newId: () => `id-${++id}`,
+ } satisfies Partial<TimelineApi>;
+ const timelines = new ChatTimelines(() => api as unknown as TimelineApi);
+ const create = vi.fn(async (_input: { requestId: string }): Promise<ChatSummary> => chat);
+ const created = vi.fn((unsaved: { serverId: string; roomId: string }, made: ChatSummary) =>
+ timelines.rekey(unsaved.serverId, unsaved.roomId, made.roomId)
+ );
+ const starter = new DirectChatStarter({
+ create,
+ opened: (unsaved: { serverId: string; roomId: string }, make: () => Promise<string>) => {
+ if (!timelines.peek(unsaved.serverId, unsaved.roomId))
+ timelines.unsaved(unsaved.serverId, unsaved.roomId, make);
+ },
+ created,
newId: () => `req-${++id}`,
- };
- return { deps, starter: new DirectChatStarter(deps) };
+ });
+ return { api, timelines, create, created, starter };
}
+const message = (body: string) => ({
+ body,
+ threadRootId: null,
+ mentionAgentIds: [],
+ mentionUserIds: [],
+ mentionSpans: [],
+ files: [],
+ requestId: null,
+});
+
describe('DirectChatStarter', () => {
- it('creates an unnamed direct chat with the one agent and reports it', async () => {
- const { deps, starter } = setup(async () => chat);
- await expect(starter.start('s1', 'a1')).resolves.toBe(chat);
- expect(deps.create).toHaveBeenCalledWith({
- serverId: 's1',
- agentIds: ['a1'],
- name: null,
- requestId: 'req-1',
- greeting: null,
- });
- expect(deps.created).toHaveBeenCalledWith('s1', chat);
- expect(deps.warm).not.toHaveBeenCalled();
+ it('opens a chat at once, asking the server for nothing until the first send', async () => {
+ const { api, timelines, create, starter } = setup();
+ const roomId = starter.start('s1', 'a1');
+ const timeline = timelines.get('s1', roomId);
+ expect(timeline.loaded).toBe(true);
+ await timeline.load();
+ expect(create).not.toHaveBeenCalled();
+ expect(api.messages).not.toHaveBeenCalled();
+ expect(timeline.messages).toEqual([]);
});
- it('changes whether a chat is starting in actions, as strict mode asks, while a view watches it', async () => {
- configure({ enforceActions: 'observed' });
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const { starter } = setup(async () => chat);
- const seen: boolean[] = [];
- const stop = autorun(() => seen.push(starter.starting));
- await starter.start('s1', 'a1');
- stop();
- expect(seen).toEqual([false, true, false]);
- expect(warn.mock.calls.some((call) => String(call[0]).includes('[MobX]'))).toBe(false);
- warn.mockRestore();
+ it('opens the same unsaved chat on every New chat before its first send, never another', () => {
+ const { create, starter } = setup();
+ const first = starter.start('s1', 'a1');
+ expect(starter.start('s1', 'a1')).toBe(first);
+ expect(starter.start('s1', 'a2')).not.toBe(first);
+ expect(create).not.toHaveBeenCalled();
});
- it('ignores a second start for the same agent while one is in flight', async () => {
- let finish: (value: ChatSummary) => void = () => {};
- const { deps, starter } = setup(() => new Promise((resolve) => (finish = resolve)));
- const first = starter.start('s1', 'a1');
- await expect(starter.start('s1', 'a1')).resolves.toBeNull();
- finish(chat);
- await expect(first).resolves.toBe(chat);
- expect(deps.create).toHaveBeenCalledOnce();
+ it('never reuses an existing chat, whatever it holds', () => {
+ const { starter } = setup();
+ expect(starter.start('s1', 'a1')).not.toBe(chat.roomId);
});
- it('reports a failure and reuses the request id after an uncertain one', async () => {
- const { deps, starter } = setup(async () => {
- throw new Error('offline');
+ it('makes the room on the first send, then sends to it alone, under the same timeline', async () => {
+ const { api, timelines, create, created, starter } = setup();
+ const roomId = starter.start('s1', 'a1');
+ const timeline = timelines.get('s1', roomId);
+ timeline.send(message('hello'));
+ expect(timeline.pending.map((send) => send.state)).toEqual(['sending']);
+ await vi.waitFor(() => expect(timeline.messages).toHaveLength(1));
+ expect(create).toHaveBeenCalledWith({
+ serverId: 's1',
+ agentIds: ['a1'],
+ name: null,
+ requestId: expect.stringMatching(/^req-/),
+ greeting: null,
});
- await expect(starter.start('s1', 'a1')).resolves.toBeNull();
- expect(deps.failed).toHaveBeenCalledWith(expect.stringContaining('Try again'));
- expect(deps.created).not.toHaveBeenCalled();
- deps.create.mockResolvedValueOnce(chat);
- await starter.start('s1', 'a1');
- expect(deps.create).toHaveBeenLastCalledWith(expect.objectContaining({ requestId: 'req-1' }));
+ expect(created).toHaveBeenCalledOnce();
+ expect(api.send).toHaveBeenCalledOnce();
+ expect(api.send.mock.calls[0]![0]).toBe('r1');
+ expect(timeline.roomId).toBe('r1');
+ expect(timelines.get('s1', 'r1')).toBe(timeline);
+ expect(timeline.pending).toEqual([]);
+ expect(starter.unsavedChat(roomId)).toBeUndefined();
+ // The next New chat is a new chat.
+ expect(starter.start('s1', 'a1')).not.toBe(roomId);
});
- it('reuses an existing empty chat', async () => {
- const existing = { roomId: 'r2', channelType: 'direct' } as ChatSummary;
- const { deps, starter } = setup(
- async () => chat,
- () => existing
- );
- 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();
+ it('makes one room for two sends made while it is being made', async () => {
+ const { api, timelines, create, starter } = setup();
+ const timeline = timelines.get('s1', starter.start('s1', 'a1'));
+ timeline.send(message('one'));
+ timeline.send(message('two'));
+ await vi.waitFor(() => expect(api.send).toHaveBeenCalledTimes(2));
+ expect(create).toHaveBeenCalledOnce();
+ expect(api.send.mock.calls.map((call) => call[0])).toEqual(['r1', 'r1']);
});
- it('creates a new chat when no empty chat exists', async () => {
- const { deps, starter } = setup(
- async () => chat,
- () => null
- );
- await expect(starter.start('s1', 'a1')).resolves.toBe(chat);
- expect(deps.findEmpty).toHaveBeenCalledWith('a1');
- expect(deps.create).toHaveBeenCalled();
- expect(deps.opened).not.toHaveBeenCalled();
+ it('keeps a message whose room could not be made, with its error, and retries under the same request id', async () => {
+ const { api, timelines, create, starter } = setup();
+ create.mockRejectedValueOnce(new Error('Switch cannot be reached right now.'));
+ const roomId = starter.start('s1', 'a1');
+ const timeline = timelines.get('s1', roomId);
+ const requestId = timeline.send(message('hello'));
+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));
+ expect(timeline.pending[0]).toMatchObject({ body: 'hello', requestId });
+ expect(timeline.pending[0]?.error).toContain('Switch cannot be reached');
+ expect(api.send).not.toHaveBeenCalled();
+ // Still the same unsaved chat: a New chat now opens it again rather than another.
+ expect(starter.start('s1', 'a1')).toBe(roomId);
+
+ timeline.retry(requestId);
+ await vi.waitFor(() => expect(timeline.messages).toHaveLength(1));
+ expect(create).toHaveBeenCalledTimes(2);
+ expect(create.mock.calls[1]![0].requestId).toBe(create.mock.calls[0]![0].requestId);
+ expect(api.send).toHaveBeenCalledWith('r1', expect.objectContaining({ requestId }));
});
-});
-describe('DirectChatStarter while a chat is being made', () => {
- it('says it is starting until the create answers, so other composers wait', async () => {
- let finish: (value: ChatSummary) => void = () => {};
- const { starter } = setup(() => new Promise((resolve) => (finish = resolve)));
- expect(starter.starting).toBe(false);
- const started = starter.start('s1', 'a1');
- expect(starter.starting).toBe(true);
- finish(chat);
- await started;
- expect(starter.starting).toBe(false);
+ it('retries a first send that failed after its room was made into that room, under its own request id', async () => {
+ const { api, timelines, create, starter } = setup();
+ const send = api.send.getMockImplementation()!;
+ api.send.mockRejectedValueOnce(new Error('The message was not sent.'));
+ const timeline = timelines.get('s1', starter.start('s1', 'a1'));
+ const requestId = timeline.send(message('hello'));
+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));
+ expect(timeline.pending[0]?.body).toBe('hello');
+ expect(timeline.roomId).toBe('r1');
+
+ api.send.mockImplementationOnce(send);
+ timeline.retry(requestId);
+ await vi.waitFor(() => expect(timeline.messages).toHaveLength(1));
+ expect(create).toHaveBeenCalledOnce();
+ expect(api.send.mock.calls.map((call) => [call[0], call[1].requestId])).toEqual([
+ ['r1', requestId],
+ ['r1', requestId],
+ ]);
+ expect(requestId).not.toBe(create.mock.calls[0]![0].requestId);
});
});