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
feat(console): chat-first Console backed by Switch rooms (CHOO-3119) (#716)
raullopez-sandboxd9863fdb83a3
diff --git a/.env.example b/.env.exampleindex 800566a1e..807da7979 100644--- a/.env.example+++ b/.env.example@@ -177,6 +177,8 @@ CONTROLLER_TOKEN_SECRET=# service_connections people connect outside services (GitHub# grants, Atlassian, Google Workspace, Datadog)# and grant them to their agents+# agent_chats an agent's chats and rooms on its page in+# Switch ConsoleFEATURE_FLAGS_ENABLED=# ── Server keys ──────────────────────────────────────────────────────────────diff --git a/console/agents/architecture/renderer.md b/console/agents/architecture/renderer.mdindex 43d3add07..7beb97105 100644--- a/console/agents/architecture/renderer.md+++ b/console/agents/architecture/renderer.md@@ -27,6 +27,7 @@ All paths are relative to `apps/switch-console-desktop/`.host setup- `switch-rooms/` — Switch room membership and the inline bridge pane(`room-embed-layer.tsx`)+- `chats/` — direct chats with agents: timeline, composer and agent activity- `switch-servers/` — Switch server connections, including a Switch Console-managed server- `sidebar/` — app sidebar- `settings/` — settings viewdiff --git a/console/apps/switch-console-desktop/components.json b/console/apps/switch-console-desktop/components.jsonindex b0732a2d7..1075259e6 100644--- a/console/apps/switch-console-desktop/components.json+++ b/console/apps/switch-console-desktop/components.json@@ -12,11 +12,11 @@},"iconLibrary": "lucide","aliases": {- "components": "@renderer/components",- "utils": "@renderer/lib/utils",- "ui": "@renderer/components/ui",+ "components": "@renderer/lib/components",+ "utils": "@renderer/utils/utils",+ "ui": "@renderer/lib/ui","lib": "@renderer/lib",- "hooks": "@renderer/hooks"+ "hooks": "@renderer/lib/hooks"},"registries": {"@ai-elements": "https://registry.ai-sdk.dev/{name}.json"diff --git a/console/apps/switch-console-desktop/package.json b/console/apps/switch-console-desktop/package.jsonindex c4fc422df..41f96301b 100644--- a/console/apps/switch-console-desktop/package.json+++ b/console/apps/switch-console-desktop/package.json@@ -141,6 +141,7 @@"remark-math": "^6.0.0","s3mini": "^0.9.4","sonner": "^2.0.7",+ "streamdown": "^2.7.0","tailwind-merge": "^2.6.0","tailwindcss": "^4.2.1","tw-animate-css": "^1.4.0",diff --git a/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.test.tsnew file mode 100644index 000000000..6c16b196d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('@main/lib/logger', () => ({ log: { warn: () => {} } }));++const { ChatActivityStream } = await import('./activity-stream');+const { SERVER_TOO_OLD_FOR_ACTIVITY } = await import('@shared/core/chats/activity');++const item = {+ agentId: 'a',+ sessionId: 's',+ turnId: 't',+ itemId: 'turn',+ kind: 'turn',+ revision: 1,+ status: 'running',+ title: '',+ text: '',+ commandId: null,+ roomId: 'room-1',+ threadId: null,+ messageId: 'm1',+ occurredAt: '2026-01-01T00:00:00Z',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+};++describe('ChatActivityStream', () => {+ it('asks for snapshots on ready and resync, and passes rows that match the contract', async () => {+ const body = [+ 'event: ready\ndata: {}\n\n',+ ': ping\n\n',+ `event: activity\ndata: ${JSON.stringify(item)}\n\n`,+ 'event: activity\ndata: {"roomId":"room-1"}\n\n',+ 'event: resync\ndata: {}\n\n',+ ].join('');+ const seen: string[] = [];+ const stream = new ChatActivityStream({+ open: async () => new Response(body),+ isUnauthorized: () => false,+ backoffMs: () => 60_000,+ setTimer: () => () => {},+ sink: {+ activity: (row) => seen.push(`activity:${row.messageId}`),+ approval: () => seen.push('approval'),+ resync: () => seen.push('resync'),+ state: (state) => seen.push(state),+ },+ });+ stream.start();+ await vi.waitFor(() =>+ expect(seen).toEqual(['live', 'resync', 'activity:m1', 'resync', 'offline'])+ );+ stream.stop();+ });++ it('stops asking a server that has no activity feed until started again', async () => {+ let opened = 0;+ const seen: (string | null)[] = [];+ const stream = new ChatActivityStream({+ open: async () => {+ opened++;+ return new Response('Not Found', { status: 404 });+ },+ isUnauthorized: () => false,+ backoffMs: () => 0,+ setTimer: (fn) => {+ fn();+ return () => {};+ },+ sink: {+ activity: () => {},+ approval: () => {},+ resync: () => {},+ state: (state, detail) => seen.push(`${state}:${detail}`),+ },+ });+ stream.start();+ await vi.waitFor(() => expect(seen).toEqual([`offline:${SERVER_TOO_OLD_FOR_ACTIVITY}`]));+ expect(stream.state).toEqual({ state: 'offline', detail: SERVER_TOO_OLD_FOR_ACTIVITY });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(opened).toBe(1);+ stream.start();+ await vi.waitFor(() => expect(opened).toBe(2));+ stream.stop();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.ts b/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.tsnew file mode 100644index 000000000..e6cdd1114--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/activity-stream.ts@@ -0,0 +1,167 @@+import { log } from '@main/lib/logger';+import {+ type ChatActivityItem,+ chatActivityItemSchema,+ type ChatApproval,+ chatApprovalSchema,+ SERVER_TOO_OLD_FOR_ACTIVITY,+} from '@shared/core/chats/activity';+import type { ChatStreamState } from '@shared/core/chats/chats';+import { sseFrames, STALL_MS } from './chat-stream';++/**+ * The server's activity feed (`GET /chats/activity/events`): turn steps and+ * approval requests of every room the person may read. It has no cursor, so+ * every `ready` (first connect and each reconnect) and every `resync` tells+ * the renderer to reload its rooms' snapshots; rows it already holds are+ * kept or replaced by revision.+ */++export type ChatActivitySink = {+ activity: (item: ChatActivityItem) => void;+ approval: (approval: ChatApproval) => void;+ resync: () => void;+ /** `offline` when the feed drops, with why; `live` once it is back. */+ state: (state: ChatStreamState, detail: string | null) => void;+};++export type ChatActivityStreamDeps = {+ open: (signal: AbortSignal) => Promise<Response>;+ isUnauthorized: (error: unknown) => boolean;+ sink: ChatActivitySink;+ backoffMs: (attempt: number) => number;+ setTimer: (fn: () => void, ms: number) => () => void;+};++export class ChatActivityStream {+ private stopped = false;+ private running = false;+ private abort: AbortController | null = null;+ private cancelTimer: (() => void) | null = null;+ private attempt = 0;+ /** A server without the feed: not asked again until the next `start`. */+ private tooOld = false;+ private current: { state: ChatStreamState; detail: string | null } = {+ state: 'connecting',+ detail: null,+ };++ constructor(private readonly deps: ChatActivityStreamDeps) {}++ get state(): { state: ChatStreamState; detail: string | null } {+ return this.current;+ }++ private setState(state: ChatStreamState, detail: string | null): void {+ this.current = { state, detail };+ this.deps.sink.state(state, detail);+ }++ start(): void {+ this.stopped = false;+ if (this.running) return;+ this.cancelTimer?.();+ this.cancelTimer = null;+ this.attempt = 0;+ this.tooOld = false;+ void this.loop();+ }++ stop(): void {+ this.stopped = true;+ this.cancelTimer?.();+ this.cancelTimer = null;+ this.abort?.abort();+ this.abort = null;+ }++ private async loop(): Promise<void> {+ this.running = true;+ try {+ while (!this.stopped) {+ try {+ await this.connectOnce();+ throw new Error('The server closed the activity feed.');+ } catch (error) {+ if (this.stopped) return;+ const detail = this.tooOld+ ? SERVER_TOO_OLD_FOR_ACTIVITY+ : error instanceof Error+ ? error.message+ : String(error);+ log.warn('Chat activity feed dropped; agent activity may lag until it reconnects', {+ event: 'chat_activity_stream_offline',+ error: detail,+ });+ this.setState('offline', detail);+ if (this.tooOld || this.deps.isUnauthorized(error)) return;+ const wait = this.deps.backoffMs(this.attempt++);+ await new Promise<void>((resolve) => {+ this.cancelTimer = this.deps.setTimer(() => {+ this.cancelTimer = null;+ resolve();+ }, wait);+ });+ }+ }+ } finally {+ this.running = false;+ }+ }++ private async connectOnce(): Promise<void> {+ const abort = new AbortController();+ this.abort = abort;+ const stall = { cancel: (): void => {} };+ const armStall = () => {+ stall.cancel();+ stall.cancel = this.deps.setTimer(() => abort.abort(), STALL_MS);+ };+ try {+ armStall();+ const response = await this.deps.open(abort.signal);+ this.tooOld = response.status === 404;+ if (!response.ok) throw new Error(`The activity feed was refused (${response.status}).`);+ if (!response.body) throw new Error('The activity feed has no body.');+ for await (const frame of sseFrames(+ response.body as unknown as AsyncIterable<Uint8Array>,+ armStall+ )) {+ if (this.stopped) return;+ try {+ this.handle(frame.event, frame.data);+ } catch (error) {+ log.warn('Skipped a chat activity event that does not match the contract', {+ event: 'chat_activity_event_invalid',+ frameEvent: frame.event,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ } finally {+ stall.cancel();+ if (this.abort === abort) this.abort = null;+ }+ }++ private handle(event: string, data: string): void {+ switch (event) {+ case 'ready':+ this.attempt = 0;+ this.setState('live', null);+ this.deps.sink.resync();+ return;+ case 'resync':+ this.deps.sink.resync();+ return;+ case 'activity':+ this.deps.sink.activity(chatActivityItemSchema.parse(JSON.parse(data)));+ return;+ case 'approval':+ this.deps.sink.approval(chatApprovalSchema.parse(JSON.parse(data)));+ return;+ default:+ return;+ }+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/chats/activity.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/activity.test.tsnew file mode 100644index 000000000..a0420d760--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/activity.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { type ActivityDeps, resolveChatActivity } from './activity';++function deps(overrides: Partial<ActivityDeps>): ActivityDeps {+ return {+ localAgents: async () => [],+ placements: async () => ({}),+ ...overrides,+ };+}++describe('resolveChatActivity', () => {+ it('gives two local agents in one room their own sessions', async () => {+ const d = deps({+ localAgents: async () => [+ { id: 'console-a', switchAgentId: 'agent-a', ssh: false },+ { id: 'console-b', switchAgentId: 'agent-b', ssh: true },+ ],+ placements: async (_server, consoleAgentId): Promise<Record<string, string>> =>+ consoleAgentId === 'console-a'+ ? { 'session-a': 'room-1', 'session-a2': 'room-2' }+ : { 'session-b': 'room-1' },+ });+ const a = await resolveChatActivity(d, { serverId: 's', agentId: 'agent-a', roomId: 'room-1' });+ const b = await resolveChatActivity(d, { serverId: 's', agentId: 'agent-b', roomId: 'room-1' });+ expect(a).toMatchObject({+ kind: 'session',+ target: 'local',+ hostAgentKey: 'console-a',+ sessionId: 'session-a',+ });+ expect(b).toMatchObject({+ kind: 'session',+ target: 'ssh',+ hostAgentKey: 'console-b',+ sessionId: 'session-b',+ });+ });++ it('says a local agent has no session in a room it is not placed in', async () => {+ const d = deps({+ localAgents: async () => [{ id: 'console-a', switchAgentId: 'agent-a', ssh: false }],+ placements: async () => ({ 'session-a': 'room-2' }),+ });+ expect(+ await resolveChatActivity(d, { serverId: 's', agentId: 'agent-a', roomId: 'room-1' })+ ).toMatchObject({ kind: 'unavailable', reason: 'not-placed' });+ });++ it('looks up no session for an agent that does not run here', async () => {+ expect(+ await resolveChatActivity(deps({}), { serverId: 's', agentId: 'theirs', roomId: 'room-1' })+ ).toMatchObject({ kind: 'unavailable', reason: 'not-on-this-machine' });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/activity.ts b/console/apps/switch-console-desktop/src/main/core/chats/activity.tsnew file mode 100644index 000000000..8b0576729--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/activity.ts@@ -0,0 +1,52 @@+import {+ ACTIVITY_UNAVAILABLE_TEXT,+ type ChatActivityTarget,+ type ChatActivityUnavailableReason,+} from '@shared/core/chats/activity';++/**+ * Which session of an agent attends a chat, when it runs on this machine or+ * its SSH host: what the chat reads reasoning and full tool input and output+ * from, and restarts. Turns, tools and approvals come from Switch's activity+ * feed for every agent; this lookup adds only what the host alone keeps.+ */++export type LocalChatAgent = { id: string; switchAgentId: string; ssh: boolean };++export type ActivityDeps = {+ /** This Console's agents linked to the server and not moved to a controller. */+ localAgents: (serverId: string) => Promise<LocalChatAgent[]>;+ /** A local agent's placements (session → room), or null while its watcher cannot be asked. */+ placements: (serverId: string, consoleAgentId: string) => Promise<Record<string, string> | null>;+};++const unavailable = (+ reason: ChatActivityUnavailableReason,+ message: string = ACTIVITY_UNAVAILABLE_TEXT[reason]+): ChatActivityTarget => ({ kind: 'unavailable', reason, message });++/** The session placed in `roomId`, from a placements map. */+export function placedSession(placements: Record<string, string>, roomId: string): string | null {+ for (const [sessionId, placedRoom] of Object.entries(placements))+ if (placedRoom === roomId) return sessionId;+ return null;+}++export async function resolveChatActivity(+ deps: ActivityDeps,+ input: { serverId: string; agentId: string; roomId: string }+): Promise<ChatActivityTarget> {+ const { serverId, agentId, roomId } = input;+ const local = (await deps.localAgents(serverId)).find((agent) => agent.switchAgentId === agentId);+ if (!local) return unavailable('not-on-this-machine');+ const placements = await deps.placements(serverId, local.id);+ if (placements === null) return unavailable('watcher-unreachable');+ const sessionId = placedSession(placements, roomId);+ if (sessionId === null) return unavailable('not-placed');+ return {+ kind: 'session',+ target: local.ssh ? 'ssh' : 'local',+ hostAgentKey: local.id,+ sessionId,+ };+}diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.tsnew file mode 100644index 000000000..a2d4c3a00--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts@@ -0,0 +1,206 @@+import { describe, expect, it, vi } from 'vitest';+import type { ChatMessage, ChatStreamState, ChatSummary } from '@shared/core/chats/chats';+import { ChatStream, type ChatStreamDeps, sseFrames } from './chat-stream';++const warn = vi.hoisted(() => vi.fn());+vi.mock('@main/lib/logger', () => ({ log: { warn } }));++function summary(roomId: string, seq: number | null): ChatSummary {+ return {+ roomId,+ name: roomId,+ channelType: 'direct',+ bridgeType: null,+ channelName: null,+ agents: [],+ canManage: true,+ ownsAgent: false,+ lastMessage:+ seq === null ? null : { seq, sentAt: '2026-01-01T00:00:00Z', preview: '', senderName: '' },+ };+}++function message(roomId: string, seq: number): ChatMessage {+ return {+ messageId: `${roomId}-${seq}`,+ seq,+ roomId,+ sentAt: '2026-01-01T00:00:00Z',+ sender: { clientId: 'c', name: 'n', kind: 'agent', agentId: 'a', userId: null },+ source: 'switch',+ body: `m${seq}`,+ format: null,+ threadRootId: null,+ attachments: [],+ clientTxn: null,+ };+}++/** A streaming response the test writes frames into. */+function feed() {+ let controller!: ReadableStreamDefaultController<Uint8Array>;+ const body = new ReadableStream<Uint8Array>({+ start: (c) => {+ controller = c;+ },+ });+ const encoder = new TextEncoder();+ return {+ response: new Response(body, { status: 200 }),+ send: (event: string, data: unknown) =>+ controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)),+ ping: () => controller.enqueue(encoder.encode(': ping\n\n')),+ end: () => controller.close(),+ };+}++function harness(lists: ChatSummary[][], unauthorized = false) {+ const states: { state: ChatStreamState; detail: string | null }[] = [];+ const messages: ChatMessage[] = [];+ const removed: [string, string][] = [];+ const summaries: ChatSummary[] = [];+ const opened: string[] = [];+ const feeds: ReturnType<typeof feed>[] = [];+ const timers: { fn: () => void; ms: number; cancelled: boolean }[] = [];+ let listCall = 0;+ const deps: ChatStreamDeps = {+ listChats: async () => {+ if (unauthorized) throw Object.assign(new Error('Signed out'), { unauthorized: true });+ return lists[Math.min(listCall++, lists.length - 1)]!;+ },+ open: async (after) => {+ opened.push(after);+ const next = feed();+ feeds.push(next);+ return next.response;+ },+ isUnauthorized: (error) => (error as { unauthorized?: boolean }).unauthorized === true,+ backoffMs: (attempt) => 1000 * (attempt + 1),+ setTimer: (fn, ms) => {+ const timer = { fn, ms, cancelled: false };+ timers.push(timer);+ return () => {+ timer.cancelled = true;+ };+ },+ sink: {+ message: (m) => messages.push(m),+ summary: (c) => summaries.push(c),+ removed: (roomId, reason) => removed.push([roomId, reason]),+ state: (state, detail) => states.push({ state, detail }),+ },+ };+ const fireRetry = () => {+ const timer = timers.find((each) => !each.cancelled && each.ms < 60_000);+ if (!timer) throw new Error('No retry is waiting.');+ timer.cancelled = true;+ timer.fn();+ };+ return { deps, states, messages, removed, summaries, opened, feeds, fireRetry };+}++describe('sseFrames', () => {+ it('splits events, skips pings and joins multi-line data', async () => {+ const encoder = new TextEncoder();+ const chunks = [': ping\n\nevent: a\ndata: {"x":', '1}\n\nevent: b\ndata: 1\ndata: 2\n\n'];+ let seen = 0;+ const frames = [];+ for await (const frame of sseFrames(+ (async function* () {+ for (const chunk of chunks) yield encoder.encode(chunk);+ })(),+ () => seen+++ ))+ frames.push(frame);+ expect(frames).toEqual([+ { event: 'a', data: '{"x":1}' },+ { event: 'b', data: '1\n2' },+ ]);+ expect(seen).toBe(2);+ });+});++describe('ChatStream', () => {+ it('reads cursors from the list, and is live only after ready', async () => {+ const h = harness([[summary('room-a', 5), summary('room-b', null)]]);+ const stream = new ChatStream(h.deps);+ stream.start();+ await vi.waitFor(() => expect(h.feeds).toHaveLength(1));+ expect(h.opened[0]).toBe('room-a:5,room-b:0');+ expect(h.summaries.map((chat) => chat.roomId)).toEqual(['room-a', 'room-b']);+ await vi.waitFor(() => expect(stream.state.state).toBe('catching-up'));++ h.feeds[0]!.send('message', message('room-a', 6));+ h.feeds[0]!.ping();+ await vi.waitFor(() => expect(h.messages).toHaveLength(1));+ expect(stream.state.state).toBe('catching-up');++ h.feeds[0]!.send('ready', {});+ await vi.waitFor(() => expect(stream.state.state).toBe('live'));+ expect(h.states.map((each) => each.state)).toEqual(['catching-up', 'live']);+ stream.stop();+ });++ it('reconnects from the cursor it reached and drops what it already delivered', async () => {+ const h = harness([[summary('room-a', 5)], [summary('room-a', 9)]]);+ const stream = new ChatStream(h.deps);+ stream.start();+ await vi.waitFor(() => expect(h.feeds).toHaveLength(1));+ h.feeds[0]!.send('message', message('room-a', 6));+ h.feeds[0]!.send('message', message('room-a', 7));+ h.feeds[0]!.send('ready', {});+ await vi.waitFor(() => expect(stream.state.state).toBe('live'));+ h.feeds[0]!.end();+ await vi.waitFor(() => expect(stream.state.state).toBe('offline'));++ h.fireRetry();+ await vi.waitFor(() => expect(h.feeds).toHaveLength(2));+ // The list now says 9, but the cursor reached stands: nothing between is skipped.+ expect(h.opened[1]).toBe('room-a:7');+ h.feeds[1]!.send('message', message('room-a', 7));+ h.feeds[1]!.send('message', message('room-a', 8));+ h.feeds[1]!.send('ready', {});+ await vi.waitFor(() => expect(stream.state.state).toBe('live'));+ expect(h.messages.map((each) => each.seq)).toEqual([6, 7, 8]);+ expect(stream.cursor('room-a')).toBe(8);+ stream.stop();+ });++ it('forgets a removed room and passes on the removal', async () => {+ const h = harness([[summary('room-a', 1)]]);+ const stream = new ChatStream(h.deps);+ stream.start();+ await vi.waitFor(() => expect(h.feeds).toHaveLength(1));+ h.feeds[0]!.send('chat.removed', { roomId: 'room-a', reason: 'unlisted' });+ await vi.waitFor(() => expect(h.removed).toEqual([['room-a', 'unlisted']]));+ expect(stream.cursor('room-a')).toBeUndefined();+ stream.stop();+ });++ it('skips a malformed event with a warning and stays connected', async () => {+ const h = harness([[summary('room-a', 1)]]);+ const stream = new ChatStream(h.deps);+ stream.start();+ await vi.waitFor(() => expect(h.feeds).toHaveLength(1));+ h.feeds[0]!.send('chat', { ...summary('room-bad', null), channelType: 'unknown' });+ h.feeds[0]!.send('message', message('room-a', 2));+ h.feeds[0]!.send('ready', {});+ await vi.waitFor(() => expect(stream.state.state).toBe('live'));+ expect(h.messages.map((each) => each.seq)).toEqual([2]);+ expect(h.summaries.map((chat) => chat.roomId)).toEqual(['room-a']);+ expect(warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ frameEvent: 'chat', roomId: 'room-bad' })+ );+ stream.stop();+ });++ it('goes offline and stops retrying once signed out', async () => {+ const h = harness([[]], true);+ const stream = new ChatStream(h.deps);+ stream.start();+ await vi.waitFor(() => expect(stream.state.state).toBe('offline'));+ expect(stream.state.detail).toBe('Signed out');+ expect(() => h.fireRetry()).toThrow('No retry is waiting.');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.tsnew file mode 100644index 000000000..fff9a6970--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.ts@@ -0,0 +1,252 @@+import { log } from '@main/lib/logger';+import {+ type ChatMessage,+ chatMessageSchema,+ type ChatRemovalReason,+ chatRemovedSchema,+ type ChatStreamState,+ type ChatSummary,+ chatSummarySchema,+} from '@shared/core/chats/chats';++/**+ * One live feed of a person's chats on one server and tenant.+ *+ * Connecting reads the chat list first and takes each room's newest sequence+ * as its cursor, then opens `GET /chats/events?after=room:seq,…`. The server+ * catches every room up from its cursor and says `ready`; only then is the+ * feed `live`. A dropped feed reconnects with backoff from the cursors it+ * reached, so nothing between is lost and nothing already delivered is+ * delivered again. Pings carry no meaning beyond "the connection is alive":+ * a feed silent for longer than {@link STALL_MS} is treated as dropped.+ */++export const STALL_MS = 60_000;++export type ChatStreamSink = {+ message: (message: ChatMessage) => void;+ summary: (chat: ChatSummary) => void;+ removed: (roomId: string, reason: ChatRemovalReason) => void;+ state: (state: ChatStreamState, detail: string | null) => void;+};++export type ChatStreamDeps = {+ listChats: () => Promise<ChatSummary[]>;+ /** Open the event stream; the response body is read until it ends. */+ open: (after: string, signal: AbortSignal) => Promise<Response>;+ /** Whether a failure means the person is signed out, so retrying cannot help. */+ isUnauthorized: (error: unknown) => boolean;+ sink: ChatStreamSink;+ /** Delay before reconnect attempt `attempt` (0-based). */+ backoffMs: (attempt: number) => number;+ setTimer: (fn: () => void, ms: number) => () => void;+};++export function defaultBackoffMs(attempt: number): number {+ return Math.min(30_000, 1000 * 2 ** attempt);+}++type Frame = { event: string; data: string };++/** Server-sent event frames from a byte stream; `onChunk` fires for every chunk, pings included. */+export async function* sseFrames(+ body: AsyncIterable<Uint8Array>,+ onChunk: () => void+): AsyncGenerator<Frame> {+ const decoder = new TextDecoder();+ let buffered = '';+ for await (const chunk of body) {+ onChunk();+ buffered += decoder.decode(chunk, { stream: true }).replace(/\r\n/g, '\n');+ let at = buffered.indexOf('\n\n');+ while (at !== -1) {+ const block = buffered.slice(0, at);+ buffered = buffered.slice(at + 2);+ let event = 'message';+ const data: string[] = [];+ for (const line of block.split('\n')) {+ if (line.startsWith(':')) continue;+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));+ }+ if (data.length) yield { event, data: data.join('\n') };+ at = buffered.indexOf('\n\n');+ }+ }+}++class StreamClosed extends Error {}++function roomIdOf(data: string): unknown {+ try {+ return (JSON.parse(data) as { roomId?: unknown } | null)?.roomId ?? null;+ } catch {+ return null;+ }+}++export class ChatStream {+ private readonly cursors = new Map<string, number>();+ private stopped = false;+ private running = false;+ private abort: AbortController | null = null;+ private cancelTimer: (() => void) | null = null;+ private attempt = 0;+ private current: { state: ChatStreamState; detail: string | null } = {+ state: 'connecting',+ detail: null,+ };++ constructor(private readonly deps: ChatStreamDeps) {}++ get state(): { state: ChatStreamState; detail: string | null } {+ return this.current;+ }++ /** The sequence each room has been delivered through. */+ cursor(roomId: string): number | undefined {+ return this.cursors.get(roomId);+ }++ /** Start, or reconnect now if the feed is waiting to retry or gave up. */+ start(): void {+ this.stopped = false;+ if (this.running) return;+ this.cancelTimer?.();+ this.cancelTimer = null;+ this.attempt = 0;+ void this.loop();+ }++ /** Drop the connection and reconnect from the cursors reached. */+ resync(): void {+ if (this.stopped) return;+ this.abort?.abort();+ if (!this.running) this.start();+ }++ stop(): void {+ this.stopped = true;+ this.cancelTimer?.();+ this.cancelTimer = null;+ this.abort?.abort();+ this.abort = null;+ }++ private setState(state: ChatStreamState, detail: string | null): void {+ if (this.current.state === state && this.current.detail === detail) return;+ this.current = { state, detail };+ this.deps.sink.state(state, detail);+ }++ private async loop(): Promise<void> {+ this.running = true;+ try {+ while (!this.stopped) {+ try {+ await this.connectOnce();+ throw new Error('The server closed the live feed.');+ } catch (error) {+ if (this.stopped) return;+ const detail = error instanceof Error ? error.message : String(error);+ if (this.deps.isUnauthorized(error)) {+ this.setState('offline', detail);+ return;+ }+ this.setState('offline', detail);+ const wait = this.deps.backoffMs(this.attempt++);+ await new Promise<void>((resolve) => {+ this.cancelTimer = this.deps.setTimer(() => {+ this.cancelTimer = null;+ resolve();+ }, wait);+ });+ }+ }+ } finally {+ this.running = false;+ }+ }++ private afterParam(): string {+ return [...this.cursors].map(([roomId, seq]) => `${roomId}:${seq}`).join(',');+ }++ private async connectOnce(): Promise<void> {+ this.setState('connecting', null);+ const chats = await this.deps.listChats();+ if (this.stopped) return;+ for (const chat of chats) {+ if (!this.cursors.has(chat.roomId)) this.cursors.set(chat.roomId, chat.lastMessage?.seq ?? 0);+ this.deps.sink.summary(chat);+ }+ const abort = new AbortController();+ this.abort = abort;+ const stall = { cancel: (): void => {} };+ const armStall = () => {+ stall.cancel();+ stall.cancel = this.deps.setTimer(() => abort.abort(), STALL_MS);+ };+ try {+ armStall();+ const response = await this.deps.open(this.afterParam(), abort.signal);+ if (!response.ok) throw new Error(`The live feed was refused (${response.status}).`);+ if (!response.body) throw new Error('The live feed has no body.');+ this.setState('catching-up', null);+ for await (const frame of sseFrames(+ response.body as unknown as AsyncIterable<Uint8Array>,+ armStall+ )) {+ if (this.stopped) return;+ try {+ this.handle(frame);+ } catch (error) {+ log.warn('Skipped a live chat event that does not match the contract', {+ event: 'chat_event_invalid',+ frameEvent: frame.event,+ roomId: roomIdOf(frame.data),+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ } catch (error) {+ if (abort.signal.aborted && !this.stopped)+ throw new StreamClosed('The live feed stalled or was restarted.');+ throw error;+ } finally {+ stall.cancel();+ if (this.abort === abort) this.abort = null;+ }+ }++ private handle(frame: Frame): void {+ const data: unknown = JSON.parse(frame.data);+ switch (frame.event) {+ case 'message': {+ const message = chatMessageSchema.parse(data);+ const cursor = this.cursors.get(message.roomId);+ if (cursor !== undefined && message.seq <= cursor) return;+ this.cursors.set(message.roomId, message.seq);+ this.deps.sink.message(message);+ return;+ }+ case 'chat': {+ const chat = chatSummarySchema.parse(data);+ this.deps.sink.summary(chat);+ return;+ }+ case 'chat.removed': {+ const { roomId, reason } = chatRemovedSchema.parse(data);+ this.cursors.delete(roomId);+ this.deps.sink.removed(roomId, reason);+ return;+ }+ case 'ready':+ this.attempt = 0;+ this.setState('live', null);+ return;+ default:+ return;+ }+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.test.tsnew file mode 100644index 000000000..ff8235299--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.test.ts@@ -0,0 +1,82 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ workspace: { id: 'ws-1', tenantId: 'tenant-1' as string | null },+ emitted: [] as { name: string; data: unknown }[],+ opened: [] as { workspaceId: string; signal: AbortSignal }[],+ activityOpened: [] as { workspaceId: string; signal: AbortSignal }[],+}));++vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireWorkspaceForServer: async () => ({ ...state.workspace, serverId: 'server-1' }),+}));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: async (workspaceId: string, fn: (server: unknown) => unknown) =>+ fn({ id: 'server-1', workspaceId }),+}));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ GatewayError: class GatewayError extends Error {},+ gatewayRequest: async (+ server: { workspaceId: string },+ path: string,+ options: { signal: AbortSignal }+ ) => {+ (path === '/chats/activity/events' ? state.activityOpened : state.opened).push({+ workspaceId: server.workspaceId,+ signal: options.signal,+ });+ return new Response(new ReadableStream({ start: () => {} }), { status: 200 });+ },+}));+vi.mock('./gateway', () => ({ listChats: async () => [] }));+vi.mock('@main/lib/events', () => ({+ events: {+ emit: (event: { name: string }, data: unknown) =>+ state.emitted.push({ name: event.name, data }),+ },+}));+vi.mock('@main/lib/logger', () => ({ log: { warn: () => {} } }));++const { connectChatStream, resetChatStream } = await import('./chat-streams');++describe('chat streams', () => {+ beforeEach(() => {+ state.emitted.length = 0;+ state.opened.length = 0;+ state.activityOpened.length = 0;+ state.workspace = { id: 'ws-1', tenantId: 'tenant-1' };+ resetChatStream('server-1');+ state.emitted.length = 0;+ });++ it('keeps one feed for the same tenant', async () => {+ await connectChatStream('server-1');+ await vi.waitFor(() => expect(state.opened).toHaveLength(1));+ await connectChatStream('server-1');+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(state.opened).toHaveLength(1);+ expect(state.emitted.some((each) => each.name === 'chat:reset')).toBe(false);+ });++ it('drops the feed and resets the renderer when the tenant changes', async () => {+ await connectChatStream('server-1');+ await vi.waitFor(() => expect(state.opened).toHaveLength(1));+ state.workspace = { id: 'ws-2', tenantId: 'tenant-2' };+ await connectChatStream('server-1');+ await vi.waitFor(() => expect(state.opened).toHaveLength(2));+ expect(state.opened[0]!.signal.aborted).toBe(true);+ expect(state.opened[1]!.workspaceId).toBe('ws-2');+ await vi.waitFor(() => expect(state.activityOpened).toHaveLength(2));+ expect(state.activityOpened[0]!.signal.aborted).toBe(true);+ expect(state.activityOpened[1]!.workspaceId).toBe('ws-2');+ expect(state.emitted).toContainEqual({ name: 'chat:reset', data: { serverId: 'server-1' } });+ });++ it('resets on sign-out', async () => {+ await connectChatStream('server-1');+ await vi.waitFor(() => expect(state.opened).toHaveLength(1));+ resetChatStream('server-1');+ expect(state.opened[0]!.signal.aborted).toBe(true);+ expect(state.emitted).toContainEqual({ name: 'chat:reset', data: { serverId: 'server-1' } });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.tsnew file mode 100644index 000000000..3fc45fe93--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-streams.ts@@ -0,0 +1,151 @@+import { GatewayError, gatewayRequest } from '@main/core/switch-servers/gateway-client';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';+import { events } from '@main/lib/events';+import { log } from '@main/lib/logger';+import {+ chatActivityChannel,+ chatActivityStateChannel,+ chatActivityResyncChannel,+ chatApprovalChannel,+ chatMessageChannel,+ chatRemovedChannel,+ chatResetChannel,+ chatStreamStateChannel,+ chatSummaryChannel,+} from '@shared/core/chats/chatEvents';+import type { ChatStreamState } from '@shared/core/chats/chats';+import { ChatActivityStream } from './activity-stream';+import { ChatStream, defaultBackoffMs } from './chat-stream';+import { listChats } from './gateway';++/**+ * The chats feed for each server, for the tenant the window is scoped to.+ *+ * One feed per server: the window shows one workspace of a server at a time,+ * and a feed opened for one tenant answers for that tenant only. Connecting+ * under another tenant, or signing out, drops the old feed and tells the+ * renderer to forget everything it held for the server.+ *+ * The request that opens a feed takes the workspace lease only until the+ * server answers; reading the body holds nothing, so a workspace switch is+ * never kept waiting on a feed that does not end.+ */++type Entry = {+ tenantId: string | null;+ workspaceId: string;+ stream: ChatStream;+ activity: ChatActivityStream;+};+const streams = new Map<string, Entry>();++function makeStream(serverId: string, workspaceId: string): ChatStream {+ return new ChatStream({+ listChats: () => withWorkspaceSession(workspaceId, listChats),+ open: (after, signal) =>+ withWorkspaceSession(workspaceId, (server) =>+ gatewayRequest(+ server,+ `/chats/events${after ? `?${new URLSearchParams({ after })}` : ''}`,+ { authenticated: true, signal }+ )+ ),+ isUnauthorized: (error) => error instanceof GatewayError && error.kind === 'unauthorized',+ backoffMs: defaultBackoffMs,+ setTimer,+ sink: {+ message: (message) => events.emit(chatMessageChannel, { serverId, message }),+ summary: (chat) => events.emit(chatSummaryChannel, { serverId, chat }),+ removed: (roomId, reason) => events.emit(chatRemovedChannel, { serverId, roomId, reason }),+ state: (state, detail) => {+ if (state === 'offline')+ log.warn('Chats live feed offline', { event: 'chat_stream_offline', serverId, detail });+ events.emit(chatStreamStateChannel, { serverId, state, detail });+ },+ },+ });+}++const setTimer = (fn: () => void, ms: number) => {+ const timer = setTimeout(fn, ms);+ timer.unref?.();+ return () => clearTimeout(timer);+};++function makeActivityStream(serverId: string, workspaceId: string): ChatActivityStream {+ return new ChatActivityStream({+ open: (signal) =>+ withWorkspaceSession(workspaceId, (server) =>+ gatewayRequest(server, '/chats/activity/events', { authenticated: true, signal })+ ),+ isUnauthorized: (error) => error instanceof GatewayError && error.kind === 'unauthorized',+ backoffMs: defaultBackoffMs,+ setTimer,+ sink: {+ activity: (item) => events.emit(chatActivityChannel, { serverId, item }),+ approval: (approval) => events.emit(chatApprovalChannel, { serverId, approval }),+ resync: () => events.emit(chatActivityResyncChannel, { serverId }),+ state: (state, detail) => events.emit(chatActivityStateChannel, { serverId, state, detail }),+ },+ });+}++/** Drop the server's feed and tell the renderer its chats are stale. */+export function resetChatStream(serverId: string): void {+ const entry = streams.get(serverId);+ if (entry) {+ entry.stream.stop();+ entry.activity.stop();+ streams.delete(serverId);+ }+ events.emit(chatResetChannel, { serverId });+}++type FeedState = { state: ChatStreamState; detail: string | null };++/**+ * Make sure the server's feed runs for the tenant the window is scoped to now,+ * and say where it and the activity feed stand. A feed for another tenant is+ * dropped first.+ */+export async function connectChatStream(+ serverId: string+): Promise<FeedState & { activity: FeedState }> {+ const workspace = await requireWorkspaceForServer(serverId);+ const existing = streams.get(serverId);+ if (+ existing &&+ existing.workspaceId === workspace.id &&+ existing.tenantId === workspace.tenantId+ ) {+ existing.stream.start();+ existing.activity.start();+ return { ...existing.stream.state, activity: existing.activity.state };+ }+ if (existing) resetChatStream(serverId);+ const stream = makeStream(serverId, workspace.id);+ const activity = makeActivityStream(serverId, workspace.id);+ streams.set(serverId, {+ tenantId: workspace.tenantId,+ workspaceId: workspace.id,+ stream,+ activity,+ });+ stream.start();+ activity.start();+ return { ...stream.state, activity: activity.state };+}++/** Stop the feed without forgetting anything, e.g. when no window needs it. */+export function disconnectChatStream(serverId: string): void {+ const entry = streams.get(serverId);+ entry?.stream.stop();+ entry?.activity.stop();+ streams.delete(serverId);+}++/** Reconnect now from the cursors reached. */+export function resyncChatStream(serverId: string): void {+ streams.get(serverId)?.stream.resync();+}diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-title.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-title.test.tsnew file mode 100644index 000000000..a7a16d584--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-title.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';+import { chatTitleFrom } from './chat-title';++describe('chatTitleFrom', () => {+ it('keeps a plain title', () => {+ expect(chatTitleFrom('Nightly build failure on ARM runners\n')).toBe(+ 'Nightly build failure on ARM runners'+ );+ });++ it('strips quotes, a label and closing punctuation', () => {+ expect(chatTitleFrom(' "Fix the login bug." ')).toBe('Fix the login bug');+ expect(chatTitleFrom('Title: «Revisar el despliegue»')).toBe('Revisar el despliegue');+ });++ it('takes the first line only', () => {+ expect(chatTitleFrom('Deploy checklist\nHere is why I chose it')).toBe('Deploy checklist');+ });++ it('caps the length at 60 characters', () => {+ expect(chatTitleFrom('word '.repeat(30))).toHaveLength(59);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-title.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-title.tsnew file mode 100644index 000000000..8385ac9ba--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-title.ts@@ -0,0 +1,51 @@+import { tmpdir } from 'node:os';+import { execProvider } from '@switch-console/agent-providers';++const MAX_TITLE = 60;+const MAX_MESSAGE = 2000;++/** The model's reply as a chat name: one line, unquoted, no closing punctuation, capped. */+export function chatTitleFrom(reply: string): string {+ const line = reply.trim().split('\n')[0] ?? '';+ const title = line+ .replace(/^(title:\s*)/i, '')+ .replace(/^["'`“”‘’«»*]+|["'`“”‘’«»*]+$/g, '')+ .replace(/[.!?:;,。]+$/u, '')+ .trim();+ return title.length > MAX_TITLE ? title.slice(0, MAX_TITLE).trimEnd() : title;+}++/**+ * A short name for a chat from its first message, written by Claude Haiku+ * through the user's own `claude` CLI, so the server needs no model key. No+ * tools, MCP servers, settings or saved session: only the one reply.+ */+export async function generateChatTitle(message: string): Promise<string> {+ // One line: a newline does not survive the cmd.exe quoting a Windows npm install goes through.+ const text = message.replace(/\s+/g, ' ').trim().slice(0, MAX_MESSAGE);+ if (!text) throw new Error('There is no message text to name the chat from.');+ const prompt =+ 'Write a title of at most 6 words for a chat that starts with the message below. ' ++ 'Use the language of the message. Reply with the title only: no quotes, no punctuation at the end. ' ++ `Message: ${text}`;+ const { stdout } = await execProvider(+ 'claude',+ [+ '-p',+ '--model',+ 'haiku',+ '--tools',+ '',+ '--strict-mcp-config',+ '--setting-sources',+ '',+ '--disable-slash-commands',+ '--no-session-persistence',+ prompt,+ ],+ { cwd: tmpdir(), env: process.env, timeout: 60_000 }+ );+ const title = chatTitleFrom(stdout);+ if (!title) throw new Error(`Claude returned no usable title: ${JSON.stringify(stdout)}`);+ return title;+}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.tsnew file mode 100644index 000000000..c762b156e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts@@ -0,0 +1,236 @@+import { listManagedAgentRecords } from '@main/core/agent-migration/managed-agents-store';+import { getAgentLocation } from '@main/core/agents/agent-location';+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 { withServerWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';+import { log } from '@main/lib/logger';+import type {+ ChatActivityTarget,+ ChatApproval,+ ChatApprovalAnswer,+ ChatControlCommand,+ RoomActivity,+} from '@shared/core/chats/activity';+import type {+ ChatMessage,+ ChatMessagesPage,+ ChatSendInput,+ ChatSummary,+ ChatUpload,+ ChatUploadInput,+} from '@shared/core/chats/chats';+import { createRPCController } from '@shared/lib/ipc/rpc';+import { type ActivityDeps, resolveChatActivity } from './activity';+import {+ connectChatStream,+ disconnectChatStream,+ resetChatStream,+ resyncChatStream,+} from './chat-streams';+import { generateChatTitle } from './chat-title';+import {+ answerChatApproval,+ createChat,+ fetchChatMedia,+ fetchChatMessages,+ fetchRoomActivity,+ listChats,+ renameChat,+ sendChatControl,+ sendChatMessage,+ setChatHidden,+ uploadChatAttachment,+ warmChatAgent,+} from './gateway';++const onServer = withServerWorkspaceSession;++/** Short-lived reads repeated by every chat opened. */+const CACHE_MS = 10_000;+const cache = new Map<string, { at: number; value: Promise<unknown> }>();+function cached<T>(key: string, read: () => Promise<T>): Promise<T> {+ const hit = cache.get(key);+ if (hit && Date.now() - hit.at < CACHE_MS) return hit.value as Promise<T>;+ const value = read();+ value.catch(() => {+ if (cache.get(key)?.value === value) cache.delete(key);+ });+ cache.set(key, { at: Date.now(), value });+ return value;+}++function dropServerCaches(serverId: string): void {+ for (const key of [...cache.keys()]) if (key.startsWith(`${serverId}:`)) cache.delete(key);+}++const activityDeps: ActivityDeps = {+ localAgents: async (serverId) => {+ const moved = new Set((await listManagedAgentRecords()).map((record) => record.agentId));+ const linked = (await getAgents()).filter(+ (agent) => agent.serverId === serverId && agent.switchAgentId && !moved.has(agent.id)+ );+ return Promise.all(+ linked.map(async (agent) => ({+ id: agent.id,+ switchAgentId: agent.switchAgentId!,+ ssh: Boolean((await getAgentLocation(agent)).sshHost),+ }))+ );+ },+ placements: (serverId, consoleAgentId) => agentPlacements(serverId, consoleAgentId),+};++/**+ * 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.+ */+async function warmChat(params: { serverId: string; agentId: string; roomId: string }) {+ 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));+ return;+ }+ await (local.ssh+ ? withSidecar(local.id, (client) => client.warm(roomId))+ : localWatcherControl(agentId).warm(roomId));+ } catch (error) {+ log.warn('Could not warm the agent’s session for a chat; its first message starts it', {+ serverId,+ agentId,+ roomId,+ error: String(error),+ });+ }+}++/**+ * The signed-in person's chats on a server: rooms they are a member of, read+ * and written through the gateway's `/chats` routes, kept live by one feed+ * per server and tenant. Sending only ever posts to the room — routing,+ * waking and starting a session belong to the agent's host.+ */+export const chatsController = createRPCController({+ /** Start (or keep) the server's live feed for the window's tenant; returns its state. */+ connect: (serverId: string) => connectChatStream(serverId),+ disconnect: (serverId: string) => {+ disconnectChatStream(serverId);+ },+ resync: (serverId: string) => {+ resyncChatStream(serverId);+ },+ /** Drop everything held for the server, as on sign-out. */+ reset: (serverId: string) => {+ dropServerCaches(serverId);+ resetChatStream(serverId);+ },+ /** Who the person is on the server, and the tenant the chats belong to. */+ identity: async (serverId: string): Promise<{ userId: string; tenantId: string | null }> => {+ const workspace = await requireWorkspaceForServer(serverId);+ const me = await cached(`${serverId}:me`, () => onServer(serverId, fetchMe));+ return { userId: me.id, tenantId: workspace.tenantId };+ },+ list: (serverId: string): Promise<ChatSummary[]> => onServer(serverId, listChats),+ create: (params: {+ serverId: string;+ agentIds: string[];+ name: string | null;+ requestId: string;+ }): Promise<ChatSummary> => onServer(params.serverId, (server) => createChat(server, params)),+ messages: (params: {+ serverId: string;+ roomId: string;+ beforeSeq: number | null;+ limit: number;+ }): Promise<ChatMessagesPage> =>+ onServer(params.serverId, (server) =>+ fetchChatMessages(server, params.roomId, {+ beforeSeq: params.beforeSeq,+ limit: Math.min(200, Math.max(1, params.limit)),+ })+ ),+ send: (input: ChatSendInput): Promise<ChatMessage[]> =>+ onServer(input.serverId, (server) =>+ sendChatMessage(server, input.roomId, {+ requestId: input.requestId,+ body: input.body,+ threadRootId: input.threadRootId,+ uploadIds: input.uploadIds,+ })+ ),+ upload: (input: ChatUploadInput): Promise<ChatUpload> =>+ onServer(input.serverId, (server) =>+ uploadChatAttachment(server, input.roomId, {+ uploadId: input.uploadId,+ name: input.name,+ mimeType: input.mimeType,+ bytes: Buffer.from(input.data, 'base64'),+ })+ ),+ /** A room attachment's bytes, base64, for display. */+ media: async (params: {+ serverId: string;+ roomId: string;+ uri: string;+ }): Promise<{ mimeType: string; data: string }> => {+ const media = await onServer(params.serverId, (server) =>+ fetchChatMedia(server, params.roomId, params.uri)+ );+ 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)),+ 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. */+ title: (message: string): Promise<string> => generateChatTitle(message),+ /**+ * Where the agent's session for the chat runs, as seen from this machine.+ * Changes follow on the room health channel.+ */+ activity: (params: {+ serverId: string;+ 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. */+ warm: (params: { serverId: string; agentId: string; roomId: string }): Promise<void> =>+ warmChat(params),+ /** 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)),+ /** Post Stop, Reset or Compact for an agent; the command id its reply threads under. */+ control: (params: {+ serverId: string;+ roomId: string;+ requestId: string;+ agentId: string;+ command: ChatControlCommand;+ }): Promise<string> =>+ onServer(params.serverId, (server) =>+ sendChatControl(server, params.roomId, {+ requestId: params.requestId,+ agentId: params.agentId,+ command: params.command,+ })+ ),+ answerApproval: (params: {+ serverId: string;+ agentId: string;+ sessionId: string;+ requestId: string;+ answer: ChatApprovalAnswer;+ }): Promise<ChatApproval> =>+ onServer(params.serverId, (server) => answerChatApproval(server, params, params.answer)),+});diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.tsnew file mode 100644index 000000000..5936de62b--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from 'vitest';+import { gatewayFetch } from '@main/core/switch-servers/gateway-client';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { parseChatRows, warmChatAgent } from './gateway';++const warn = vi.hoisted(() => vi.fn());+vi.mock('@main/lib/logger', () => ({ log: { warn } }));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ GatewayError: class extends Error {},+ gatewayFetch: vi.fn(),+}));++function row(roomId: string, channelType: string) {+ return {+ roomId,+ name: roomId,+ channelType,+ bridgeType: null,+ channelName: null,+ agents: [],+ canManage: true,+ ownsAgent: false,+ lastMessage: null,+ };+}++describe('parseChatRows', () => {+ it('accepts every channel type the server sends', () => {+ const types = ['lobby', 'channel_public', 'channel_private', 'group', 'direct'];+ expect(parseChatRows(types.map((type) => row(type, type))).map((c) => c.roomId)).toEqual(types);+ });++ it('skips a row that fails the contract with a warning and keeps the rest', () => {+ const chats = parseChatRows([row('room-a', 'direct'), row('room-bad', 'unknown')]);+ expect(chats.map((chat) => chat.roomId)).toEqual(['room-a']);+ expect(warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ roomId: 'room-bad' })+ );+ });+});++describe('warmChatAgent', () => {+ it('posts the agent to the room’s warm route', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(new Response(null, { status: 202 }));+ await warmChatAgent(server, 'room/a', 'agent-1');+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room%2Fa/warm', {+ authenticated: true,+ method: 'POST',+ body: { agentId: 'agent-1' },+ });+ });+});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.tsnew file mode 100644index 000000000..cc03cc791--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts@@ -0,0 +1,238 @@+import type { z } from 'zod';+import { GatewayError, gatewayFetch } from '@main/core/switch-servers/gateway-client';+import { log } from '@main/lib/logger';+import {+ type ChatApproval,+ type ChatApprovalAnswer,+ chatApprovalSchema,+ chatControlAcceptedSchema,+ type ChatControlCommand,+ type RoomActivity,+ roomActivitySchema,+} from '@shared/core/chats/activity';+import {+ type ChatMessage,+ type ChatMessagesPage,+ chatMessagesPageSchema,+ chatCreatedSchema,+ chatErrorBodySchema,+ chatListSchema,+ chatSentSchema,+ type ChatSummary,+ chatSummarySchema,+ type ChatUpload,+ chatUploadSchema,+} from '@shared/core/chats/chats';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++/**+ * The gateway's `/chats` routes, called as the signed-in person. Every answer+ * is parsed against the contract before it goes anywhere; a refusal the+ * gateway coded is raised as a {@link ChatApiError} so the renderer can tell+ * "not a member" from "request reused" from a network failure.+ */++/** A refusal `/chats` answered with a code, such as `NOT_A_MEMBER` or `REQUEST_REUSED`. */+export class ChatApiError extends Error {+ constructor(+ readonly apiCode: string,+ message: string,+ readonly status: number+ ) {+ super(message);+ this.name = 'ChatApiError';+ }+}++/** The coded refusal inside a failed gateway call, or the call's own error. */+export function chatError(error: unknown): unknown {+ if (!(error instanceof GatewayError) || error.kind !== 'http' || !error.body) return error;+ try {+ const parsed = chatErrorBodySchema.safeParse(JSON.parse(error.body));+ if (parsed.success)+ return new ChatApiError(+ parsed.data.detail.code,+ parsed.data.detail.message,+ error.status ?? 0+ );+ } catch {+ // Not JSON: the gateway's own error stands.+ }+ return error;+}++async function call(+ server: SwitchServer,+ path: string,+ options: { method?: string; body?: unknown; formData?: FormData }+): Promise<Response> {+ try {+ return await gatewayFetch(server, path, { authenticated: true, ...options });+ } catch (error) {+ throw chatError(error);+ }+}++async function json<T>(+ server: SwitchServer,+ path: string,+ schema: z.ZodType<T>,+ options: { method?: string; body?: unknown; formData?: FormData } = {}+): Promise<T> {+ return schema.parse(await (await call(server, path, options)).json());+}++const room = (roomId: string) => `/chats/${encodeURIComponent(roomId)}`;++/** Each row parsed alone: a row that fails the contract is skipped with a warning, not the list. */+export function parseChatRows(rows: unknown[]): ChatSummary[] {+ return rows.flatMap((row) => {+ const parsed = chatSummarySchema.safeParse(row);+ if (parsed.success) return [parsed.data];+ log.warn('Skipped a chat that does not match the contract', {+ event: 'chat_row_invalid',+ roomId: (row as { roomId?: unknown } | null)?.roomId ?? null,+ issues: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`),+ });+ return [];+ });+}++export async function listChats(server: SwitchServer): Promise<ChatSummary[]> {+ return parseChatRows((await json(server, '/chats', chatListSchema)).chats);+}++/**+ * One agent goes as `agentId`, which every server with chats accepts; only a+ * chat with several needs `agentIds`.+ */+export async function createChat(+ server: SwitchServer,+ input: { agentIds: string[]; name: string | null; requestId: string }+): Promise<ChatSummary> {+ const body: Record<string, string | string[]> = {+ ...(input.agentIds.length === 1+ ? { agentId: input.agentIds[0] }+ : { agentIds: input.agentIds }),+ requestId: input.requestId,+ };+ if (input.name) body.name = input.name;+ return (await json(server, '/chats', chatCreatedSchema, { method: 'POST', body })).chat;+}++export async function fetchChatMessages(+ server: SwitchServer,+ roomId: string,+ page: { beforeSeq: number | null; limit: number }+): Promise<ChatMessagesPage> {+ const query = new URLSearchParams({ limit: String(page.limit) });+ if (page.beforeSeq !== null) query.set('beforeSeq', String(page.beforeSeq));+ return json(server, `${room(roomId)}/messages?${query}`, chatMessagesPageSchema);+}++export async function sendChatMessage(+ server: SwitchServer,+ roomId: string,+ input: {+ requestId: string;+ body: string;+ threadRootId: string | null;+ uploadIds: string[];+ }+): Promise<ChatMessage[]> {+ return (+ await json(server, `${room(roomId)}/messages`, chatSentSchema, {+ method: 'POST',+ body: input,+ })+ ).messages;+}++/** The room's turn steps and approval requests, as Switch stores them. */+export async function fetchRoomActivity(+ server: SwitchServer,+ roomId: string+): Promise<RoomActivity> {+ return json(server, `${room(roomId)}/activity`, roomActivitySchema);+}++/**+ * Post Stop, Reset or Compact to the room for an agent. The answer is its+ * command id: the command is posted, not done, and the agent answers it in a+ * thread rooted there.+ */+export async function sendChatControl(+ server: SwitchServer,+ roomId: string,+ input: { requestId: string; agentId: string; command: ChatControlCommand }+): Promise<string> {+ return (+ await json(server, `${room(roomId)}/controls`, chatControlAcceptedSchema, {+ method: 'POST',+ body: input,+ })+ ).commandId;+}++/** Ask core to have the agent's controller start its session for the room; a hint, accepted at once. */+export async function warmChatAgent(server: SwitchServer, roomId: string, agentId: string) {+ await call(server, `${room(roomId)}/warm`, { method: 'POST', body: { agentId } });+}++/** Answer an agent's approval request as the signed-in person. */+export async function answerChatApproval(+ server: SwitchServer,+ request: { agentId: string; sessionId: string; requestId: string },+ answer: ChatApprovalAnswer+): Promise<ChatApproval> {+ const path = [request.agentId, request.sessionId, 'approvals', request.requestId]+ .map(encodeURIComponent)+ .join('/');+ return json(server, `/agent-sessions/${path}/answer`, chatApprovalSchema, {+ method: 'POST',+ body: answer,+ });+}++export async function uploadChatAttachment(+ server: SwitchServer,+ roomId: string,+ file: { uploadId: string; name: string; mimeType: string; bytes: Uint8Array }+): Promise<ChatUpload> {+ const form = new FormData();+ form.set('uploadId', file.uploadId);+ form.set('file', new Blob([new Uint8Array(file.bytes)], { type: file.mimeType }), file.name);+ return json(server, `${room(roomId)}/attachments`, chatUploadSchema, {+ method: 'POST',+ formData: form,+ });+}++export async function fetchChatMedia(+ server: SwitchServer,+ roomId: string,+ uri: string+): Promise<{ mimeType: string; bytes: Uint8Array }> {+ const response = await call(server, `${room(roomId)}/media?${new URLSearchParams({ uri })}`, {});+ return {+ mimeType: response.headers.get('content-type') ?? 'application/octet-stream',+ bytes: new Uint8Array(await response.arrayBuffer()),+ };+}++export async function setChatHidden(+ server: SwitchServer,+ roomId: string,+ hidden: boolean+): Promise<void> {+ await call(server, `${room(roomId)}/hidden`, { method: hidden ? 'PUT' : 'DELETE' });+}++/** Rename uses the room route: a chat's name is its room's name. */+export async function renameChat(+ server: SwitchServer,+ roomId: string,+ name: string+): Promise<void> {+ await call(server, `/rooms/${encodeURIComponent(roomId)}`, { method: 'PATCH', body: { name } });+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health-monitor.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health-monitor.tsindex de450adef..85a151ea8 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health-monitor.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health-monitor.ts@@ -88,6 +88,15 @@ export class ConnectionHealthMonitor {return this.compute(serverId);}+ /**+ * One agent's session placements (session id → room id) as its watcher last+ * reported them, or null while it cannot be asked. Call after+ * {@link snapshot} has attached the agent's server.+ */+ placementsOf(agentId: string): Record<string, string> | null {+ return this.entries.get(agentId)?.source?.health?.placements ?? null;+ }+/** Stops watching every agent. */dispose(): void {for (const agentId of [...this.entries.keys()]) this.detach(agentId);diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health.tsindex 673f23560..9c93ee48d 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/connection-health.ts@@ -52,3 +52,15 @@ const monitor = new ConnectionHealthMonitor({export function connectionHealth(serverId: string) {return monitor.snapshot(serverId);}++/**+ * One linked agent's session placements, session id → room id, from its room+ * watcher; null while the watcher cannot be asked.+ */+export async function agentPlacements(+ serverId: string,+ agentId: string+): Promise<Record<string, string> | null> {+ await monitor.snapshot(serverId);+ return monitor.placementsOf(agentId);+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.tsindex a6df2edc4..c6fd17d27 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts@@ -8,6 +8,7 @@ import { sharedAgentDiagnostics, sharedAgentLogs } from './diagnostics';import { sessionIssue, sessionStartupStatus } from './host-failures';import { transcriptSource } from './host-journal';import { placeSession } from './place-session';+import { listReasoning } from './reasoning';import {reconcileSessionCommand,sessionCommandStatus,@@ -43,4 +44,6 @@ export const sdkHostController = createRPCController({reconcileSessionCommand(agentId, command),sessionCommandStatus: (agentId: string, sessionId: string, commandId: string) =>sessionCommandStatus(agentId, sessionId, commandId),+ reasoningList: (agentId: string, sessionId: string, turnIds: string[] | null) =>+ listReasoning(agentId, sessionId, turnIds),});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.test.tsnew file mode 100644index 000000000..50bc17684--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.test.ts@@ -0,0 +1,78 @@+import { beforeEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ local: { reasoning: vi.fn() },+ sidecar: { reasoning: vi.fn() },+ sidecarControl: vi.fn(),+ sshHost: null as string | null,+ linked: true,+}));+vi.mock('@switch-console/agent-providers', () => ({+ sharedSessionRoot: (id: string) => `/roots/${id}`,+}));+vi.mock('@main/core/agents/getAgentById', () => ({+ getAgentById: async () => (mocks.linked ? { switchAgentId: 'switch-agent' } : null),+}));+vi.mock('@main/core/agents/agent-location', () => ({+ getAgentLocation: async () => ({ sshHost: mocks.sshHost }),+}));+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn() } }));+vi.mock('./local-host', () => ({ localSessionLinks: mocks.local }));+vi.mock('./sidecar-control', () => ({ sidecarControl: mocks.sidecarControl }));++const { listReasoning } = await import('./reasoning');++const list = {+ epoch: 'epoch',+ turns: [+ {+ turnId: 'turn',+ text: 'Look first.',+ startedAt: '2026-10-08T12:00:00.000Z',+ completedAt: '2026-10-08T12:00:04.000Z',+ },+ ],+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.sshHost = null;+ mocks.linked = true;+ mocks.sidecarControl.mockResolvedValue(mocks.sidecar);+});++it('reads a local session’s reasoning from its host', async () => {+ mocks.local.reasoning.mockResolvedValue(list);+ expect(await listReasoning('agent', 'session', ['turn'])).toEqual(list);+ expect(mocks.local.reasoning).toHaveBeenCalledWith('/roots/session', ['turn']);+});++it('reads a remote session’s reasoning through its sidecar', async () => {+ mocks.sshHost = 'host';+ mocks.sidecar.reasoning.mockResolvedValue(list);+ expect(await listReasoning('agent', 'session', null)).toEqual(list);+ expect(mocks.sidecar.reasoning).toHaveBeenCalledWith('session', null);+ expect(mocks.local.reasoning).not.toHaveBeenCalled();+});++it('shows none when the host or sidecar predates reasoning, without raising', async () => {+ // A local host that never answered the request.+ mocks.local.reasoning.mockResolvedValue(null);+ expect(await listReasoning('agent', 'session', null)).toBeNull();+ // An older sidecar reads the ask as a health ask and answers with its health.+ mocks.sshHost = 'host';+ mocks.sidecar.reasoning.mockResolvedValue({ state: 'connected', detail: null, placements: {} });+ expect(await listReasoning('agent', 'session', null)).toBeNull();+ // One that refuses it outright, or cannot be reached.+ mocks.sidecar.reasoning.mockRejectedValue(new Error('The sidecar refused the request.'));+ expect(await listReasoning('agent', 'session', null)).toBeNull();+ mocks.sidecarControl.mockRejectedValue(new Error('The agent’s sidecar is not running.'));+ expect(await listReasoning('agent', 'session', null)).toBeNull();+});++it('asks nothing for an unlinked agent', async () => {+ mocks.linked = false;+ expect(await listReasoning('agent', 'session', null)).toBeNull();+ expect(mocks.local.reasoning).not.toHaveBeenCalled();+ expect(mocks.sidecarControl).not.toHaveBeenCalled();+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.tsnew file mode 100644index 000000000..4f0fdb049--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/reasoning.ts@@ -0,0 +1,47 @@+import { sharedSessionRoot } from '@switch-console/agent-providers';+import { getAgentLocation } from '@main/core/agents/agent-location';+import { getAgentById } from '@main/core/agents/getAgentById';+import { log } from '@main/lib/logger';+import { reasoningListSchema, type ReasoningList } from '@shared/core/sessions/reasoning';+import { localSessionLinks } from './local-host';+import { sidecarControl } from './sidecar-control';++/**+ * The reasoning a session's host still holds for `turnIds` (every buffered+ * turn when null), or null when there is none to show.+ *+ * Only a host on this machine or on the agent's SSH host is asked: reasoning+ * never travels through Switch, so a cloud or controller-run session has+ * none. A host or sidecar that predates reasoning, one that is not running,+ * or one that cannot be reached all read as none — this never raises, and+ * never starts or waits for a host.+ *+ * An SSH sidecar is not asked with the session request `askHost` sends: one+ * that predates reasoning closes the whole control connection on a request+ * type it cannot parse. `ControlClient.reasoning` sends a message such a+ * sidecar reads as a health ask instead, and its health answer fails the+ * parse below.+ */+export async function listReasoning(+ agentId: string,+ sessionId: string,+ turnIds: string[] | null+): Promise<ReasoningList | null> {+ try {+ const agent = await getAgentById(agentId);+ if (!agent?.switchAgentId) return null;+ const answer = (await getAgentLocation(agent)).sshHost+ ? await (await sidecarControl(agentId)).reasoning(sessionId, turnIds)+ : await localSessionLinks.reasoning(sharedSessionRoot(sessionId), turnIds);+ if (answer === null) return null;+ const parsed = reasoningListSchema.safeParse(answer);+ return parsed.success ? parsed.data : null;+ } catch (error) {+ log.warn('Could not read the session reasoning; showing none', {+ agentId,+ sessionId,+ error: String(error),+ });+ return null;+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.tsindex bd501255d..2e07896a8 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -2,6 +2,7 @@ import type { Result } from '@switch-console/shared';import { z } from 'zod';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';import { appService } from '@main/core/app/service';+import { resetChatStream } from '@main/core/chats/chat-streams';import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';import { featureFlagsService } from '@main/core/feature-flags/feature-flags';import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';@@ -541,6 +542,7 @@ export const switchServersController = createRPCController({const server = await getServer(serverId).catch(() => null);await deleteManagedClaudeCredential(serverId);await deleteSessionCookie(serverId);+ resetChatStream(serverId);if (server) trackEvent('server_sign_out', { server_kind: serverKindOf(server) });},diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex c9ec38907..b02e8fe1e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -587,7 +587,26 @@ describe('room creation', () => {expect(slack).toMatchObject({ channelCreationSupported: true, canCreateChannels: false });});- it('always names a bridge and a channel type, never the internal-only escape hatch', async () => {+ it('makes a room with no bridge internal, not one on the default app', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ id: 'room-1',+ name: 'design',+ description: 'd',+ channel_type: 'channel_public',+ agent_count: 0,+ bridge_display_name: null,+ archived: false,+ created_at: '2026-01-01T00:00:00Z',+ }) as never+ );++ await createRoom(SERVER, { name: 'design', description: 'd', bridgeId: null, agentIds: [] });++ expect(bodyOf(fetchMock.mock.calls[0])).toMatchObject({ bridge_id: null, internal_only: true });+ });++ it('names a chosen bridge and a channel type, never the internal-only escape hatch', async () => {fetchMock.mockResolvedValue(jsonResponse({id: 'room-1',diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex 56dac323a..b02ccda8b 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -223,6 +223,8 @@ type FetchOptions = {authenticated: boolean;method?: string;body?: unknown;+ /** A multipart body, sent as is; `fetch` sets its boundary. Excludes `body`. */+ formData?: FormData;};/**@@ -312,7 +314,9 @@ export async function gatewayRequest(return await fetch(gatewayUrl(server, path), {method: options.method ?? 'GET',headers,- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,+ body:+ options.formData ??+ (options.body !== undefined ? JSON.stringify(options.body) : undefined),// We attach the cookie explicitly; don't let the runtime manage a jar.redirect: 'manual',signal: options.signal,@@ -2921,7 +2925,8 @@ export async function createRoom(name: string;description: string;instructions?: string;- bridgeId: string;+ /** Null makes an internal room: no channel, not even on the default app. */+ bridgeId: string | null;agentIds: string[];}): Promise<RemoteRoomSummary> {@@ -2933,6 +2938,7 @@ export async function createRoom(description: params.description,instructions: params.instructions?.trim() ? params.instructions : null,bridge_id: params.bridgeId,+ ...(params.bridgeId === null ? { internal_only: true } : {}),channel_type: 'channel_public',agent_ids: params.agentIds,},diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.tsindex 7a3890347..6eea4cefb 100644--- a/console/apps/switch-console-desktop/src/main/rpc.ts+++ b/console/apps/switch-console-desktop/src/main/rpc.ts@@ -4,6 +4,7 @@ import { agentTemplatesController } from './core/agent-templates/controller';import { agentTypesController } from './core/agent-types/controller';import { agentsController } from './core/agents/controller';import { appController } from './core/app/controller';+import { chatsController } from './core/chats/controller';import { embeddedControllerController } from './core/embedded-controller/controller';import { featureFlagsController } from './core/feature-flags/controller';import { filesController } from './core/fs/controller';@@ -34,6 +35,7 @@ export const rpcRouter = createRPCRouter({agents: agentsController,agentTemplates: agentTemplatesController,app: appController,+ chats: chatsController,appSettings: appSettingsController,update: updateController,resourceMonitor: resourceMonitorController,diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex fa4ea16d4..517922e46 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -1,3 +1,4 @@+import { RenameChatModal } from '@renderer/features/chats/components/chat-modals';import { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';@@ -115,5 +116,6 @@ export const modalRegistry = {dismissOnOutsideClick: false,}),deleteRoomModal: createModal(DeleteRoomModal, { size: 'sm', dismissOnOutsideClick: false }),+ renameChatModal: createModal(RenameChatModal, { size: 'xs', dismissOnOutsideClick: false }),// oxlint-disable-next-line typescript/no-explicit-any} satisfies Record<string, ModalRegistryEntry<any, any>>;diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.tsindex a2be6fcb9..4f7b397ef 100644--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts@@ -1,5 +1,6 @@import type { ComponentType, ReactNode } from 'react';import { homeView } from '@renderer/app/home-view';+import { chatView } from '@renderer/features/chats/chat-view';import { locationView } from '@renderer/features/locations/view';import { managedAgentView } from '@renderer/features/managed-agents/managed-agent-view';import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';@@ -27,6 +28,7 @@ export const views = {home: homeView,location: locationView,session: sessionView,+ chat: chatView,managedAgent: managedAgentView,room: roomView,settings: settingsView,diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.tsnew file mode 100644index 000000000..2e36c1f0a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts@@ -0,0 +1,182 @@+import {+ type ChatActivityItem,+ type ChatApproval,+ TURN_ITEM_ID,+} from '@shared/core/chats/activity';+import { type ChatMessage, isSessionStartingNotice, turnEndNotice } from '@shared/core/chats/chats';+import { SWITCH_TOOL_PREFIX } from './tool-presentation';++/**+ * Joining an agent's turns, as Switch's activity feed stores them, to the+ * room messages that started them. Every row of a turn the agent took from+ * the room carries that message's id, so a turn shows under its message;+ * its other steps (tool activity, the agent's own text) and its approval+ * requests show with it.+ */++export type TurnStatus = 'queued' | 'running' | 'completed' | 'interrupted' | 'error';++export type TurnActivity = {+ sessionId: string;+ turnId: string;+ status: TurnStatus;+ roomId: string | null;+ messageId: string | null;+ /** Tool activity and assistant text, in the order the host recorded them. */+ items: ChatActivityItem[];+ requests: ChatApproval[];+};++/** Where a row is held: one per step, whatever its revision. */+export const itemKey = (item: ChatActivityItem): string =>+ JSON.stringify([item.sessionId, item.turnId, item.itemId]);+export const turnKey = (sessionId: string, turnId: string): string =>+ JSON.stringify([sessionId, turnId]);++/** One agent's rows grouped into turns, oldest first. A turn not reported yet is left out. */+export function groupTurns(+ items: Iterable<ChatActivityItem>,+ approvals: Iterable<ChatApproval>+): TurnActivity[] {+ const byCreation = (a: ChatActivityItem, b: ChatActivityItem) =>+ a.createdAt.localeCompare(b.createdAt) || a.itemId.localeCompare(b.itemId);+ const rows = [...items].sort(byCreation);+ const turns = new Map<string, TurnActivity>();+ for (const row of rows)+ if (row.itemId === TURN_ITEM_ID)+ turns.set(turnKey(row.sessionId, row.turnId), {+ sessionId: row.sessionId,+ turnId: row.turnId,+ status: row.status as TurnStatus,+ roomId: row.roomId,+ messageId: row.messageId,+ items: [],+ requests: [],+ });+ for (const row of rows)+ if (row.itemId !== TURN_ITEM_ID) turns.get(turnKey(row.sessionId, row.turnId))?.items.push(row);+ for (const approval of approvals)+ turns.get(turnKey(approval.sessionId, approval.turnId))?.requests.push(approval);+ return [...turns.values()];+}++/** The turns started by a message of `roomId`, by that message; a later turn for it wins. */+export function bindTurns(+ turns: readonly TurnActivity[],+ roomId: string+): Map<string, TurnActivity> {+ const bound = new Map<string, TurnActivity>();+ for (const turn of turns)+ if (turn.roomId === roomId && turn.messageId) bound.set(turn.messageId, turn);+ return bound;+}++/**+ * Where one agent's turns show, by the message each shows under, in message+ * order. A turn shows under the message that started it, unless that message+ * was sent while the agent's previous turn still ran: the turn then runs after+ * that turn's reply, and shows under it. Shortcut: the reply is taken to be+ * the agent's first message after the previous turn, so a turn that ended+ * without a reply pushes the next turn under its own reply. A turn also shows+ * after the agent's own messages sent before its first step, such as an+ * acknowledgement posted while the session started.+ */+export function placeTurns(+ messages: readonly ChatMessage[],+ agentId: string,+ bound: ReadonlyMap<string, TurnActivity>+): Map<string, TurnActivity[]> {+ const placed = new Map<string, TurnActivity[]>();+ let previous: number | null = null;+ const shown = (each: ChatMessage) =>+ each.sender.kind === 'agent' &&+ each.sender.agentId === agentId &&+ !isSessionStartingNotice(each) &&+ !turnEndNotice(each);+ messages.forEach((message, at) => {+ const turn = bound.get(message.messageId);+ if (!turn) return;+ let anchor = at;+ if (previous !== null) {+ const after = previous;+ const reply = messages.findIndex((each, index) => index > after && shown(each));+ anchor = Math.max(at, reply === -1 ? previous : reply);+ }+ const firstStep = turn.items[0] ? Date.parse(turn.items[0].createdAt) : null;+ for (let next = anchor + 1; firstStep !== null && next < messages.length; next++) {+ const each = messages[next];+ if (bound.has(each.messageId) || Date.parse(each.sentAt) >= firstStep) break;+ if (shown(each)) anchor = next;+ }+ const key = messages[anchor].messageId;+ placed.set(key, [...(placed.get(key) ?? []), turn]);+ previous = turn.status === 'interrupted' || turn.status === 'error' ? null : anchor;+ });+ return placed;+}++/**+ * The host's notices of turns that ended without a reply, each matched to the+ * turn it reports: the agent's latest turn before it that shows the same+ * ending and has no notice yet. A queued turn may have started in between.+ * Only the session's own turns are bound, which keeps the search to it. Maps+ * the notice's message id to the turn id.+ */+export function foldTurnEndNotices(+ messages: readonly ChatMessage[],+ agentId: string,+ bound: ReadonlyMap<string, TurnActivity>+): Map<string, string> {+ const folded = new Map<string, string>();+ const claimed = new Set<string>();+ messages.forEach((message, at) => {+ const notice = message.sender.agentId === agentId ? turnEndNotice(message) : null;+ if (!notice) return;+ const status = { failed: 'error', interrupted: 'interrupted', completed: null }[notice.outcome];+ const turn = messages+ .slice(0, at)+ .map((each) => bound.get(each.messageId))+ .findLast((each) => each?.status === status && !claimed.has(each.turnId));+ if (!turn) return;+ claimed.add(turn.turnId);+ folded.set(message.messageId, turn.turnId);+ });+ return folded;+}++export type ToolState = 'running' | 'done' | 'failed' | 'declined';++/** How a tool item stands, given its turn's status: one left open by a turn that ended failed. */+export function toolState(item: Pick<ChatActivityItem, 'status'>, turn: TurnStatus): ToolState {+ if (item.status === 'completed') return 'done';+ if (item.status === 'failed') return 'failed';+ if (item.status === 'declined') return 'declined';+ return turn === 'interrupted' || turn === 'error' ? 'failed' : 'running';+}++/**+ * The tool calls a turn shows. Assistant text is left out: what the agent+ * means the room to read it posts there, and the room message is the copy+ * shown. Switch's own tools (connecting, reading context, posting) are split+ * off — they are how the agent talks to the room, not work done for it.+ */+export function turnTools(turn: TurnActivity): {+ work: ChatActivityItem[];+ switchActions: ChatActivityItem[];+} {+ const work: ChatActivityItem[] = [];+ const switchActions: ChatActivityItem[] = [];+ for (const item of turn.items) {+ if (item.kind !== 'tool-activity') continue;+ (item.title.startsWith(SWITCH_TOOL_PREFIX) ? switchActions : work).push(item);+ }+ return { work, switchActions };+}++/** Whether the turn is under way with no tool run yet. */+export function isThinking(turn: TurnActivity): boolean {+ return (+ (turn.status === 'queued' || turn.status === 'running') &&+ !turn.items.some((item) => item.kind === 'tool-activity')+ );+}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.tsnew file mode 100644index 000000000..2d29c5bde--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/agent-conversations.ts@@ -0,0 +1,23 @@+import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';+import type { ChatSummary } from '@shared/core/chats/chats';+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.+ */+export function agentConversations(+ agentChats: readonly ChatSummary[],+ agentRooms: readonly RemoteAgentRoom[]+): { 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 listedIds = new Set(agentRooms.map((room) => room.roomId));+ const unlisted = agentChats+ .filter((chat) => !directIds.has(chat.roomId) && !listedIds.has(chat.roomId))+ .map((chat) => ({ roomId: chat.roomId, roomName: chat.name }));+ const rooms = [...listed, ...unlisted].sort((a, b) => a.roomName.localeCompare(b.roomName));+ return { direct, rooms };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-threads.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-threads.tsnew file mode 100644index 000000000..04fb0f436--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-threads.ts@@ -0,0 +1,43 @@+import type { ChatMessage } from '@shared/core/chats/chats';++/**+ * Threads are shown inline: every message in sequence order, and a reply+ * carries a chip naming the message it answers ("↳ reply to …"), which+ * scrolls to it when clicked.+ */++const SNIPPET = 80;++/** A message's text, flattened to one line and cut to a chip's length. */+export function snippetOf(message: Pick<ChatMessage, 'body' | 'attachments'>): string {+ const text = message.body.replace(/\s+/g, ' ').trim();+ if (!text) return message.attachments[0]?.filename ?? 'an attachment';+ return text.length > SNIPPET ? `${text.slice(0, SNIPPET - 1)}…` : text;+}++export type ThreadChip = {+ rootId: string;+ /** The root's text, or null while it is not loaded (older than what is shown). */+ snippet: string | null;+ label: string;+};++export function threadChip(+ message: Pick<ChatMessage, 'threadRootId' | 'messageId'>,+ find: (messageId: string) => ChatMessage | undefined+): ThreadChip | null {+ const rootId = message.threadRootId;+ if (!rootId || rootId === message.messageId) return null;+ const root = find(rootId);+ const snippet = root ? snippetOf(root) : null;+ return {+ rootId,+ snippet,+ label: snippet === null ? '↳ reply to an earlier message' : `↳ reply to ${snippet}`,+ };+}++/** The DOM id a message is rendered under, for scrolling to it. */+export function messageAnchorId(messageId: string): string {+ return `chat-message-${messageId.replace(/[^A-Za-z0-9_-]/g, '_')}`;+}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.tsxnew file mode 100644index 000000000..b389f4ea0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-view.tsx@@ -0,0 +1,97 @@+import { observer } from 'mobx-react-lite';+import { useEffect } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { managedAgentLabel } from '@renderer/features/managed-agents/managed-agent-state';+import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';+import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';+import { useParams } from '@renderer/lib/layout/navigation-provider';+import { appState } from '@renderer/lib/stores/app-state';+import { ChatHeaderControls, ChatHeaderTitle } from './components/chat-header';+import { ChatPanel, useAgentActivities } from './components/chat-panel';+import { agentChatsFlag } from './stores/agent-chats-flag';+import { chatsStore } from './stores/chats';++type ChatParams = { serverId: string; roomId: string; agentId: string | null };++const ChatTitlebar = observer(function ChatTitlebar() {+ const { params } = useParams('chat');+ const chat = chatsStore.chat(params.roomId);+ // Shared with the panel: the registry hands both the same activities.+ const activities = useAgentActivities(params.serverId, chat);+ return (+ <Titlebar+ leftClassName="min-w-0"+ leftSlot={+ <div className="flex min-w-0 items-center pr-2">+ {chat ? (+ <ChatHeaderTitle serverId={params.serverId} chat={chat} />+ ) : (+ <span className="text-sm text-foreground-muted">Chat</span>+ )}+ </div>+ }+ rightSlot={+ chat && (+ <ChatHeaderControls serverId={params.serverId} chat={chat} activities={activities} />+ )+ }+ />+ );+});++/**+ * With agent_chats off the chat view is not offered: a restored or linked chat+ * opens as main shows it, on the managed agent's page, else as a room.+ */+function useLeaveWhenChatsOff(params: ChatParams): boolean | undefined {+ const enabled = agentChatsFlag(params.serverId);+ const managed = useManagedAgents(params.serverId);+ const agent = managed.data?.find((each) => each.agentId === params.agentId);+ useEffect(() => {+ if (enabled !== false || managed.isLoading) return;+ appState.history.prune(+ (entry) =>+ entry.kind === 'view' &&+ entry.viewId === 'chat' &&+ (entry.params as { roomId?: string }).roomId === params.roomId+ );+ if (agent)+ appState.navigation.navigate('managedAgent', {+ serverId: params.serverId,+ agentId: agent.agentId,+ name: managedAgentLabel(agent),+ });+ else appState.navigation.navigate('room', { roomId: params.roomId });+ }, [enabled, managed.isLoading, agent, params.serverId, params.roomId]);+ return enabled;+}++const ChatMainPanel = observer(function ChatMainPanel(): React.JSX.Element | null {+ const { params } = useParams('chat');+ const enabled = useLeaveWhenChatsOff(params);+ if (enabled !== true) return null;+ return (+ <ChatPanel+ key={`${params.serverId}:${params.roomId}`}+ serverId={params.serverId}+ roomId={params.roomId}+ />+ );+});++/** A chat opened on its own: a room the person is a member of, with its agents' activity. */+export const chatView = {+ WrapView: ({ children }: ChatParams & { children: React.ReactNode }) => <>{children}</>,+ TitlebarSlot: ChatTitlebar,+ MainPanel: ChatMainPanel,+ canActivate: (params: unknown): GuardResult => {+ const value = (params ?? {}) as Partial<Record<keyof ChatParams, unknown>>;+ if (+ typeof value.serverId !== 'string' ||+ typeof value.roomId !== 'string' ||+ (value.agentId !== null && value.agentId !== undefined && typeof value.agentId !== 'string')+ )+ 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-actions.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsxnew file mode 100644index 000000000..0831c41a5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx@@ -0,0 +1,78 @@+import { EyeOff, Pencil } 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 { chatsStore } from '../stores/chats';++export type ChatAction = {+ key: string;+ label: string;+ icon: ReactNode;+ separatorBefore?: boolean;+ run: () => void;+};++async function attempt(run: () => Promise<void>, failure: string): Promise<void> {+ try {+ await run();+ } catch (error) {+ toast({ title: failureText(error, failure), variant: 'destructive' });+ }+}++/** Leave the chat view if it shows this room, and close it on an agent's Chats tab. */+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 });+}++/**+ * 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.+ */+export function chatActions(serverId: string, chat: ChatSummary): ChatAction[] {+ const actions: ChatAction[] = [];+ if (chat.canManage)+ actions.push({+ key: 'rename',+ label: 'Rename',+ icon: <Pencil 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;+}++/** A chat's actions as dropdown menu items. */+export function ChatActionItems({ actions }: { actions: ChatAction[] }) {+ return actions.map((action, index) => (+ <Fragment key={action.key}>+ {action.separatorBefore && index > 0 && <DropdownMenuSeparator />}+ <DropdownMenuItem onClick={action.run}>+ {action.icon}+ {action.label}+ </DropdownMenuItem>+ </Fragment>+ ));+}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.tsxnew file mode 100644index 000000000..50babbf61--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx@@ -0,0 +1,219 @@+import { observer } from 'mobx-react-lite';+import { type ReactNode, useState } from 'react';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+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';+import type { AgentActivity } from '../stores/chat-activity-store';+import { presentTool, summarizeTools } from '../tool-presentation';+import { Reasoning } from '../ui/reasoning';+import { FailedIcon, ThinkingIcon, ToolKindIcon, WorkLogDetails, WorkLogRow } from '../ui/work-log';+import { ChatApprovalCard } from './chat-approval-card';+import { ToolRow } from './tool-row';++/** A settled turn with at least this many tool calls folds them behind one summary line. */+const GROUP_AT = 2;++function ToolRows({+ items,+ turn,+ activity,+}: {+ items: ChatActivityItem[];+ turn: TurnActivity;+ activity: AgentActivity;+}) {+ return (+ <>+ {items.map((item) => (+ <ToolRow+ key={item.itemId}+ item={item}+ state={toolState(item, turn.status)}+ detail={activity.toolDetails.get(item.itemId) ?? null}+ />+ ))}+ </>+ );+}++/**+ * A finished turn's tool calls as one line ("Ran 2 commands and read 3+ * files"), opening to the calls themselves. A failure is named on the line so+ * it is not hidden by the fold.+ */+function ToolGroup({+ items,+ turn,+ activity,+}: {+ items: ChatActivityItem[];+ turn: TurnActivity;+ activity: AgentActivity;+}) {+ const [open, setOpen] = useState(false);+ const summary = summarizeTools(+ items.map((item) => presentTool(item, activity.toolDetails.get(item.itemId) ?? null).kind)+ );+ const failed = items.filter((item) => toolState(item, turn.status) === 'failed').length;+ return (+ <WorkLogRow+ icon={<ToolKindIcon kind={summary.kind} />}+ label={summary.label}+ trailing={+ failed > 0 ? (+ <span className="shrink-0 text-xs text-foreground-destructive">{failed} failed</span>+ ) : null+ }+ open={open}+ onToggle={() => setOpen(!open)}+ >+ {open && (+ <div className="ms-3 border-l border-border ps-2">+ <ToolRows items={items} turn={turn} activity={activity} />+ </div>+ )}+ </WorkLogRow>+ );+}++/** Switch's own tools for the turn, folded into a count until asked for. */+function SwitchActions({+ items,+ turn,+ activity,+}: {+ items: ChatActivityItem[];+ turn: TurnActivity;+ activity: AgentActivity;+}) {+ const [open, setOpen] = useState(false);+ return (+ <WorkLogRow+ icon={<ToolKindIcon kind="switch" />}+ label={`${items.length} Switch ${items.length === 1 ? 'action' : 'actions'}`}+ tone="passive"+ open={open}+ onToggle={() => setOpen(!open)}+ >+ {open && (+ <div className="ms-3 border-l border-border ps-2">+ <ToolRows items={items} turn={turn} activity={activity} />+ </div>+ )}+ </WorkLogRow>+ );+}++/** How a turn ended, with the host's reason for it muted after it. */+export function turnEndLabel(label: string, reason: string | null): ReactNode {+ if (!reason) return label;+ return (+ <>+ {label}+ <span className="text-foreground-passive"> — {reason}</span>+ </>+ );+}++/**+ * 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,+ * and the requests it put to people, as a compact work log under the message that started the turn. The+ * text the agent wrote is not shown: its reply arrives as a room message of+ * its own, and that is the copy shown.+ */+export const ChatActivityBlock = observer(function ChatActivityBlock({+ activity,+ turn,+ agent,+ endReason,+ serverId,+}: {+ activity: AgentActivity;+ turn: TurnActivity;+ agent: { name: string; iconUrl: string | null };+ /** Why the turn ended, from the host's notice in the room; null when it posted none. */+ endReason: string | null;+ serverId: string;+}) {+ const running = turn.status === 'queued' || turn.status === 'running';+ const reasoning = activity.reasoning.get(turn.turnId) ?? null;+ const label = reasoningLabel(reasoning, running && reasoning !== null);+ const { work, switchActions } = turnTools(turn);+ 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;+ 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 && (+ <WorkLogRow+ icon={<ThinkingIcon />}+ label={turn.status === 'queued' ? 'Queued…' : 'Thinking…'}+ active+ />+ )}+ {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>+ );+});++/** Requests answered through Switch as the signed-in person. */+export const ChatRequests = observer(function ChatRequests({+ activity,+ requests,+}: {+ activity: AgentActivity;+ requests: ChatApproval[];+}) {+ return (+ <WorkLogDetails>+ {requests.map((request) => (+ <ChatApprovalCard+ key={request.requestId}+ request={request}+ onAnswer={(answer) => activity.answer(request, answer)}+ />+ ))}+ </WorkLogDetails>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-approval-card.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-approval-card.tsxnew file mode 100644index 000000000..14f7626b9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-approval-card.tsx@@ -0,0 +1,160 @@+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { Button } from '@renderer/lib/ui/button';+import { Textarea } from '@renderer/lib/ui/textarea';+import type { ChatApproval, ChatApprovalAnswer } from '@shared/core/chats/activity';++type Answers = NonNullable<ChatApproval['answers']>;++function settledLabel(request: ChatApproval): string {+ if (request.state === 'expired') return 'Expired';+ if (request.state !== 'answered') return 'Request closed';+ const decision = request.options.find((option) => option.id === request.answer)?.decision;+ if (decision === 'decline') return 'Denied';+ if (decision === 'cancel') return 'Closed';+ return decision ? 'Approved' : 'Answered';+}++/**+ * An agent's request as the chat shows it, from Switch's copy: answered+ * through Switch as the signed-in person, so it needs no connection to the+ * agent's session. A settled one folds to a line saying how it ended.+ */+export function ChatApprovalCard({+ request,+ onAnswer,+}: {+ request: ChatApproval;+ onAnswer: (answer: ChatApprovalAnswer) => Promise<void>;+}) {+ const [answers, setAnswers] = useState<Record<string, Answers[number]>>({});+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ if (request.state !== 'open')+ return (+ <details className="mt-2 text-xs text-foreground-muted">+ <summary className="cursor-pointer">+ {settledLabel(request)} · {request.title}+ </summary>+ <p className="mt-2 whitespace-pre-wrap">{request.detail ?? request.title}</p>+ </details>+ );+ const submit = async (answer: ChatApprovalAnswer) => {+ setBusy(true);+ setError(null);+ try {+ await onAnswer(answer);+ } catch (failure) {+ setError(failureText(failure, 'The answer was not taken.'));+ } finally {+ setBusy(false);+ }+ };+ return (+ <section className="rounded-xl border border-border bg-background-1 p-4">+ <h3 className="font-medium">{request.title}</h3>+ {request.kind !== 'questions' ? (+ <>+ {request.detail && (+ <p className="mt-2 text-sm [overflow-wrap:anywhere] whitespace-pre-wrap text-foreground-muted">+ {request.detail}+ </p>+ )}+ <div className="mt-3 flex flex-wrap gap-2">+ {request.options.map((option) => (+ <Button+ key={option.id}+ variant={option.decision === 'accept' ? 'default' : 'outline'}+ size="sm"+ disabled={busy}+ onClick={() => void submit({ answer: option.id })}+ >+ {option.label}+ </Button>+ ))}+ </div>+ </>+ ) : (+ <>+ {request.questions.map((question) => {+ const answer = answers[question.id] ?? {+ questionId: question.id,+ selectedOptionIds: [],+ customText: null,+ };+ const set = (next: Answers[number]) => setAnswers({ ...answers, [question.id]: next });+ return (+ <fieldset key={question.id} disabled={busy} className="mt-4 flex flex-col gap-2">+ <legend className="text-sm font-medium">{question.title || question.prompt}</legend>+ {question.title && <p className="text-sm">{question.prompt}</p>}+ {question.options.map((option) => (+ <label+ key={option.id}+ className="flex cursor-pointer items-start gap-2 rounded-lg border border-border p-3 text-sm"+ >+ <input+ type={question.multiSelect ? 'checkbox' : 'radio'}+ name={question.id}+ checked={answer.selectedOptionIds.includes(option.id)}+ onChange={(event) =>+ set({+ ...answer,+ customText: question.multiSelect ? answer.customText : null,+ selectedOptionIds: question.multiSelect+ ? event.target.checked+ ? [...answer.selectedOptionIds, option.id]+ : answer.selectedOptionIds.filter((id) => id !== option.id)+ : [option.id],+ })+ }+ />+ <span>+ {option.label}+ {option.description && (+ <span className="block text-foreground-muted">{option.description}</span>+ )}+ </span>+ </label>+ ))}+ {question.allowCustomAnswer && (+ <Textarea+ aria-label={`Custom answer: ${question.title || question.prompt}`}+ placeholder="Write your answer…"+ value={answer.customText ?? ''}+ onChange={(event) =>+ set({+ ...answer,+ customText: event.target.value,+ selectedOptionIds: question.multiSelect ? answer.selectedOptionIds : [],+ })+ }+ />+ )}+ </fieldset>+ );+ })}+ <Button+ className="mt-3"+ size="sm"+ disabled={+ busy ||+ request.questions.some(+ (question) =>+ !answers[question.id]?.selectedOptionIds.length &&+ !answers[question.id]?.customText?.trim()+ )+ }+ onClick={() => void submit({ answers: Object.values(answers) })}+ >+ Submit answers+ </Button>+ </>+ )}+ {error && (+ <p role="alert" className="mt-3 text-sm text-foreground-destructive">+ {error}+ </p>+ )}+ </section>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-attachments.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-attachments.tsxnew file mode 100644index 000000000..8da03418b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-attachments.tsx@@ -0,0 +1,165 @@+import { FileIcon, Loader2 } from 'lucide-react';+import { useEffect, useState } 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 { events } from '@renderer/lib/ipc';+import { chatRemovedChannel, chatResetChannel } from '@shared/core/chats/chatEvents';+import type { ChatAttachment } from '@shared/core/chats/chats';++/**+ * A room attachment's bytes, fetched through the chat's media route (which+ * checks membership and that the file belongs to the room) and kept for the+ * session as object URLs — dropped when the person loses the room or the+ * server's chats are reset.+ */+const media = new Map<string, Promise<string>>();+const mediaKey = (serverId: string, roomId: string, uri: string) =>+ JSON.stringify([serverId, roomId, uri]);++function dropMedia(match: (serverId: string, roomId: string) => boolean): void {+ for (const [key, url] of media) {+ const [serverId, roomId] = JSON.parse(key) as [string, string];+ if (!match(serverId, roomId)) continue;+ media.delete(key);+ void url.then((value) => URL.revokeObjectURL(value)).catch(() => {});+ }+}+events.on(chatRemovedChannel, ({ serverId, roomId, reason }) => {+ if (reason === 'access') dropMedia((s, r) => s === serverId && r === roomId);+});+events.on(chatResetChannel, ({ serverId }) => dropMedia((s) => s === serverId));++function mediaUrl(serverId: string, roomId: string, uri: string): Promise<string> {+ const key = mediaKey(serverId, roomId, uri);+ let url = media.get(key);+ if (!url) {+ url = rpc.chats.media({ serverId, roomId, uri }).then(({ mimeType, data }) => {+ const bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));+ return URL.createObjectURL(new Blob([bytes], { type: mimeType }));+ });+ url.catch(() => media.delete(key));+ media.set(key, url);+ }+ return url;+}++function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++function ChatImage({+ serverId,+ roomId,+ attachment,+}: {+ serverId: string;+ roomId: string;+ attachment: ChatAttachment;+}) {+ const [url, setUrl] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ let cancelled = false;+ mediaUrl(serverId, roomId, attachment.uri)+ .then((value) => !cancelled && setUrl(value))+ .catch(+ (caught: unknown) =>+ !cancelled && setError(failureText(caught, 'Could not load the image.'))+ );+ return () => {+ cancelled = true;+ };+ }, [serverId, roomId, attachment.uri]);+ if (error) return <p className="text-xs text-foreground-destructive">{error}</p>;+ if (!url)+ return (+ <span className="flex size-24 items-center justify-center rounded-lg bg-background-1">+ <Loader2 className="size-4 animate-spin text-foreground-muted" />+ </span>+ );+ return (+ <img+ src={url}+ alt={attachment.filename}+ className="max-h-72 max-w-full rounded-lg border border-border object-contain"+ />+ );+}++function ChatFileChip({+ serverId,+ roomId,+ attachment,+}: {+ serverId: string;+ roomId: string;+ attachment: ChatAttachment;+}) {+ const [busy, setBusy] = useState(false);+ const download = async () => {+ setBusy(true);+ try {+ const url = await mediaUrl(serverId, roomId, attachment.uri);+ const link = document.createElement('a');+ link.href = url;+ link.download = attachment.filename;+ link.click();+ } catch (caught) {+ toast({ title: failureText(caught, 'Could not download the file.'), variant: 'destructive' });+ } finally {+ setBusy(false);+ }+ };+ return (+ <button+ type="button"+ onClick={() => void download()}+ className="flex max-w-xs items-center gap-2 rounded-lg border border-border bg-background-1 px-3 py-2 text-left text-xs hover:bg-background-2"+ title={`Download ${attachment.filename}`}+ >+ {busy ? (+ <Loader2 className="size-4 shrink-0 animate-spin" />+ ) : (+ <FileIcon className="size-4 shrink-0 text-foreground-muted" />+ )}+ <span className="min-w-0 truncate">{attachment.filename}</span>+ <span className="shrink-0 text-foreground-muted">{formatSize(attachment.size)}</span>+ </button>+ );+}++export function ChatAttachments({+ serverId,+ roomId,+ attachments,+}: {+ serverId: string;+ roomId: string;+ attachments: ChatAttachment[];+}) {+ if (!attachments.length) return null;+ return (+ <div className="flex flex-wrap gap-2">+ {attachments.map((attachment) =>+ attachment.mimetype.startsWith('image/') ? (+ <ChatImage+ key={attachment.uri}+ serverId={serverId}+ roomId={roomId}+ attachment={attachment}+ />+ ) : (+ <ChatFileChip+ key={attachment.uri}+ serverId={serverId}+ roomId={roomId}+ attachment={attachment}+ />+ )+ )}+ </div>+ );+}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.tsxnew file mode 100644index 000000000..1cb2cf1e6--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx@@ -0,0 +1,400 @@+import { ChevronDown, Minimize2, Plus, RotateCcw, RotateCw, X } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useRef, useState } from 'react';+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 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,+ PromptInputAttachments,+ PromptInputButton,+ PromptInputSubmit,+ PromptInputTextarea,+} from '../ui/prompt-input';++async function toBase64(file: File): Promise<string> {+ const bytes = new Uint8Array(await file.arrayBuffer());+ let binary = '';+ for (let at = 0; at < bytes.length; at += 0x8000)+ binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));+ return btoa(binary);+}++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>();++/** Chats just created here, whose composer takes focus when it first shows. */+const focusOnOpen = new Set<string>();+/** Composers on screen by chat; a chat's stream event can open it before its create returns. */+const mountedFocus = new Map<string, () => void>();++export function focusComposerWhenOpened(roomId: string): void {+ const focus = mountedFocus.get(roomId);+ if (focus) focus();+ else focusOnOpen.add(roomId);+}++const CONTROL_LABEL: Record<ControlRequest['command'], string> = {+ interrupt: 'Stop',+ reset: 'Reset',+ compact: 'Compact',+};++/**+ * Where each Stop, Reset or Compact sent from here stands: being posted,+ * posted and waiting for the agent, or the agent's answer, which it threads+ * under the command in the room.+ */+const ControlStatus = observer(function ControlStatus({+ activity,+ timeline,+ who,+}: {+ activity: AgentActivity;+ timeline: ChatTimeline;+ who: string;+}) {+ return (+ <>+ {activity.controls.map((control) => {+ const label = CONTROL_LABEL[control.command];+ const reply = control.commandId+ ? timeline.messages.findLast((message) => message.threadRootId === control.commandId)+ : undefined;+ const failed = control.state === 'failed';+ const unknown = control.state === 'unknown';+ return (+ <div+ key={control.requestId}+ role={failed || unknown ? 'alert' : 'status'}+ className={`mb-2 flex items-start gap-2 text-xs ${failed || unknown ? 'text-foreground-destructive' : 'text-foreground-muted'}`}+ >+ <span className="min-w-0 flex-1">+ {failed+ ? `${label} was not sent: ${control.error}`+ : unknown+ ? `${label} outcome unknown: ${control.error} Retrying sends the same ${label}, never a second one.`+ : control.state === 'sending'+ ? `Sending ${label}…`+ : reply+ ? `${label}: ${snippetOf(reply)}`+ : `${label} requested — waiting for ${who} to answer.`}+ </span>+ {unknown && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => void activity.retryControl(control.requestId)}+ >+ <RotateCw className="size-3" /> Retry+ </Button>+ )}+ {control.state !== 'sending' && !unknown && (+ <button+ type="button"+ aria-label="Dismiss"+ onClick={() => activity.dismissControl(control.requestId)}+ >+ <X className="size-3.5" />+ </button>+ )}+ </div>+ );+ })}+ </>+ );+});++/**+ * The chat's composer. Sending posts the message to the room and nothing+ * else: which session answers, and starting or waking it, is up to the+ * agent's host. Stop, Reset and Compact are posted to the room as commands+ * for the agent, which answers each in the room.+ */+export const ChatComposer = observer(function ChatComposer({+ serverId,+ timeline,+ agents,+ activity,+ replyTo,+ onClearReply,+ disabled,+}: {+ serverId: string;+ timeline: ChatTimeline;+ agents: ChatAgent[];+ activity: AgentActivity | null;+ replyTo: ChatMessage | null;+ onClearReply: () => void;+ disabled: string | null;+}) {+ const draftKey = `${serverId}\u0000${timeline.roomId}`;+ const [draft, setDraft] = useState(() => drafts.get(draftKey) ?? '');+ useEffect(() => {+ drafts.set(draftKey, draft);+ }, [draftKey, draft]);+ const [files, setFiles] = useState<{ id: string; file: File }[]>([]);+ const [confirmReset, setConfirmReset] = useState(false);+ const [contextOpen, setContextOpen] = useState(false);+ const picker = useRef<HTMLInputElement>(null);+ const input = useRef<HTMLTextAreaElement>(null);+ useEffect(() => {+ const roomId = timeline.roomId;+ const focus = () => requestAnimationFrame(() => input.current?.focus());+ if (focusOnOpen.delete(roomId)) focus();+ mountedFocus.set(roomId, focus);+ return () => {+ if (mountedFocus.get(roomId) === focus) mountedFocus.delete(roomId);+ };+ }, [timeline.roomId]);+ // Typing anywhere else in the chat goes to the composer, as in Slack.+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ const textarea = input.current;+ const target = event.target;+ if (!textarea || textarea.disabled || event.defaultPrevented || event.isComposing) return;+ if (event.key.length !== 1 || event.key === ' ') return;+ if (event.ctrlKey || event.metaKey || event.altKey) return;+ if (modalStore.isOpen || isEditableTarget(target) || !textarea.checkVisibility()) return;+ const panel = textarea.closest('[data-chat-panel]');+ if (target !== document.body && !(target instanceof Node && panel?.contains(target))) return;+ if (panel?.closest('[aria-hidden="true"]')) return;+ // Focus moved during keydown: the browser types the key into the textarea.+ textarea.focus();+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);+ };+ document.addEventListener('keydown', onKeyDown);+ return () => document.removeEventListener('keydown', onKeyDown);+ }, []);+ const agent = agents[0] ?? null;+ const stopActivity = activity?.runningTurn ? activity : null;++ const addFiles = (list: File[]) => {+ if (!list.length) return;+ setFiles((current) => [...current, ...list.map((file) => ({ id: crypto.randomUUID(), file }))]);+ input.current?.focus();+ };++ const send = () => {+ const body = draft.trim();+ if (disabled || (!body && !files.length)) return;+ timeline.send({+ body,+ threadRootId: replyTo?.messageId ?? null,+ files: files.map(({ file }) => chatFile(file)),+ });+ void chatTitler.sent(serverId, timeline.roomId, body);+ setDraft('');+ setFiles([]);+ onClearReply();+ };++ const showStop = Boolean(stopActivity) && !draft.trim() && !files.length;+ const stopping = stopActivity?.pendingControl?.command === 'interrupt';+ const status = stopping ? 'sending' : showStop ? 'running' : 'idle';+ // Not blocked while working: a turn whose host died stays running in the feed, and Reset is the way out.+ const contextBlocked = activity?.pendingControl+ ? 'Waiting for the previous command to be sent.'+ : null;++ return (+ <div className="mx-auto w-full max-w-[860px] px-5 pb-1.5">+ {activity && (+ <ControlStatus+ activity={activity}+ timeline={timeline}+ who={agent ? chatAgentLabel(agent) : 'the agent'}+ />+ )}+ {replyTo && (+ <div className="mb-2 flex items-center gap-2 rounded-md border border-border px-3 py-1.5 text-xs text-foreground-muted">+ <span className="min-w-0 flex-1 truncate">+ Replying to {replyTo.sender.name}: {snippetOf(replyTo)}+ </span>+ <button type="button" aria-label="Cancel reply" onClick={onClearReply}>+ <X className="size-3.5" />+ </button>+ </div>+ )}+ <div+ onDragOver={(event) => {+ if (event.dataTransfer.types.includes('Files')) event.preventDefault();+ }}+ onDrop={(event) => {+ if (!event.dataTransfer.files.length) return;+ event.preventDefault();+ addFiles(Array.from(event.dataTransfer.files));+ }}+ onPaste={(event) => {+ if (!event.clipboardData.files.length) return;+ event.preventDefault();+ addFiles(Array.from(event.clipboardData.files));+ }}+ >+ <PromptInput+ onSubmit={send}+ className="rounded-[20px] border-(--composer-border) bg-background-1/50 shadow-(--composer-shadow) duration-200 focus-within:border-(--composer-border-focus)"+ >+ <PromptInputAttachments+ items={files.map(({ id, file }) => ({ id, name: file.name, mediaType: file.type }))}+ onRemove={(id) => setFiles((current) => current.filter((each) => each.id !== id))}+ />+ <div className="flex items-end gap-1 p-2">+ <PromptInputButton+ tooltip="Attach files"+ className="size-8 rounded-full"+ disabled={disabled !== null}+ onClick={() => picker.current?.click()}+ >+ <Plus className="size-4" />+ </PromptInputButton>+ <input+ ref={picker}+ type="file"+ multiple+ className="hidden"+ aria-label="Choose attachments"+ onChange={(event) => {+ addFiles(Array.from(event.target.files ?? []));+ event.target.value = '';+ }}+ />+ <PromptInputTextarea+ ref={input}+ className="min-h-0 px-1 py-1.5"+ aria-label={`Message ${agent ? chatAgentLabel(agent) : 'the agent'}`}+ placeholder={disabled ?? `Message ${agent ? chatAgentLabel(agent) : 'the agent'}...`}+ 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);+ }}+ />+ <PromptInputSubmit+ status={status}+ className="h-8 min-w-8"+ onStop={() => void stopActivity?.control('interrupt')}+ stopDisabledReason={stopActivity?.pendingControl ? 'Sending…' : null}+ disabled={disabled !== null || (!showStop && !draft.trim() && !files.length)}+ />+ </div>+ </PromptInput>+ <div className="mt-1.5 flex min-h-7 items-center justify-end gap-1 px-2">+ {activity && (+ <Popover+ open={contextOpen}+ onOpenChange={(open) => {+ setContextOpen(open);+ setConfirmReset(false);+ }}+ >+ <PopoverTrigger+ render={<Button variant="ghost" size="sm" />}+ className="h-7 gap-1.5 rounded-md px-2 text-xs font-normal text-foreground-muted"+ aria-label="Context actions"+ >+ Context+ <ChevronDown className="size-3" />+ </PopoverTrigger>+ <PopoverContent+ side="top"+ align="end"+ className="w-80 max-w-[calc(100vw-2rem)] gap-2 p-3"+ >+ <PopoverTitle>+ {confirmReset ? 'Start a fresh conversation?' : 'Conversation context'}+ </PopoverTitle>+ {confirmReset ? (+ <>+ <p className="text-xs text-foreground-muted">+ The agent starts with a fresh context. Earlier messages stay in the transcript+ as history.+ </p>+ <div className="flex justify-end gap-2 pt-2">+ <Button size="sm" variant="ghost" onClick={() => setConfirmReset(false)}>+ Cancel+ </Button>+ <Button+ size="sm"+ disabled={contextBlocked !== null}+ onClick={() => {+ setContextOpen(false);+ setConfirmReset(false);+ void activity.control('reset');+ }}+ >+ Start fresh+ </Button>+ </div>+ </>+ ) : (+ <>+ <Button+ variant="ghost"+ disabled={contextBlocked !== null}+ className="h-auto justify-start gap-3 px-2 py-2 text-left"+ onClick={() => {+ setContextOpen(false);+ void activity.control('compact');+ }}+ >+ <Minimize2 className="size-4 shrink-0" />+ <span>+ <span className="block">Compact context</span>+ <span className="block text-xs font-normal text-foreground-muted">+ Free up space in this conversation+ </span>+ </span>+ </Button>+ <Button+ variant="ghost"+ disabled={contextBlocked !== null}+ className="h-auto justify-start gap-3 px-2 py-2 text-left"+ onClick={() => setConfirmReset(true)}+ >+ <RotateCcw className="size-4 shrink-0" />+ <span>+ <span className="block">Reset context...</span>+ <span className="block text-xs font-normal text-foreground-muted">+ Start fresh and keep transcript history+ </span>+ </span>+ </Button>+ {contextBlocked && (+ <p className="text-xs text-foreground-muted">{contextBlocked}</p>+ )}+ <p className="border-t border-border pt-2 text-xs text-foreground-muted">+ Skills and MCP load from the execution host. Restart the host while idle after+ changing their configuration.+ </p>+ </>+ )}+ </PopoverContent>+ </Popover>+ )}+ </div>+ </div>+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-header.tsxnew file mode 100644index 000000000..8ea435afc--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-header.tsx@@ -0,0 +1,127 @@+import { MoreVertical, RotateCw } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import type { ReactNode } from 'react';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@renderer/lib/ui/dropdown-menu';+import { type ChatSummary, chatAgentLabel } from '@shared/core/chats/chats';+import type { AgentActivity } from '../stores/chat-activity-store';+import { chatsStore } from '../stores/chats';+import { ChatActionItems, chatActions } from './chat-actions';++const STREAM_LABEL = {+ connecting: 'Connecting…',+ 'catching-up': 'Catching up…',+ offline: 'Offline',+ live: null,+} as const;++async function restartSession(activity: AgentActivity): Promise<void> {+ const target = activity.target;+ if (target?.kind !== 'session') return;+ await rpc.sessions.restartAgent(target.sessionId);+}++/** Who and where: the chat's agent and its name. */+export function ChatHeaderTitle({ serverId, chat }: { serverId: string; chat: ChatSummary }) {+ const agent = chat.agents[0] ?? null;+ return (+ <div className="flex min-w-0 items-center gap-2 text-sm">+ {agent && (+ <AgentAvatar+ name={chatAgentLabel(agent)}+ iconUrl={agent.iconUrl}+ serverId={serverId}+ size={18}+ />+ )}+ {agent && <span className="truncate text-foreground-muted">{chatAgentLabel(agent)}</span>}+ <span className="text-foreground-passive">/</span>+ <span className="truncate font-medium">{chat.name}</span>+ </div>+ );+}++/**+ * Whether the agent is working, the live feed's state, and the chat's menu —+ * the chat actions the person may take, and the agent's session for those who+ * can reach it, then any `children` after a separator.+ */+export const ChatHeaderControls = observer(function ChatHeaderControls({+ serverId,+ chat,+ activities,+ children,+}: {+ serverId: string;+ chat: ChatSummary;+ activities: AgentActivity[];+ children?: ReactNode;+}) {+ const working = activities.some((activity) => activity.working);+ const stream = STREAM_LABEL[chatsStore.streamState];+ const sessionActivities = activities.filter((activity) => activity.target?.kind === 'session');+ return (+ <div className="flex shrink-0 items-center gap-3 text-sm">+ {working && (+ <span className="flex items-center gap-1.5 text-xs text-foreground-muted">+ <span className="size-1.5 rounded-full bg-amber-400" aria-hidden />+ working+ </span>+ )}+ {stream && (+ <span+ className="flex items-center gap-1 text-xs text-foreground-muted"+ title={chatsStore.streamDetail ?? undefined}+ >+ {stream}+ {chatsStore.streamState === 'offline' && (+ <Button size="sm" variant="ghost" onClick={() => void rpc.chats.connect(serverId)}>+ Reconnect+ </Button>+ )}+ </span>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Button variant="ghost" size="sm" className="size-7 p-0" />}+ aria-label={`Actions for ${chat.name}`}+ >+ <MoreVertical className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <ChatActionItems actions={chatActions(serverId, chat)} />+ {sessionActivities.length > 0 && <DropdownMenuSeparator />}+ {sessionActivities.map((activity) => (+ <DropdownMenuItem+ key={`restart:${activity.agentId}`}+ disabled={activity.working}+ onClick={() =>+ void restartSession(activity).catch((error: unknown) =>+ toast({+ title: failureText(error, 'Could not restart the session.'),+ variant: 'destructive',+ })+ )+ }+ >+ <RotateCw className="size-4" />+ Restart session+ </DropdownMenuItem>+ ))}+ {children && <DropdownMenuSeparator />}+ {children}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-modals.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-modals.tsxnew file mode 100644index 000000000..0d09d6342--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-modals.tsx@@ -0,0 +1,78 @@+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { chatsStore } from '../stores/chats';++/** Rename a chat: its room's name, for everyone in it. */+export function RenameChatModal({+ serverId,+ roomId,+ currentName,+ onSuccess,+ onClose,+}: BaseModalProps<void> & { serverId: string; roomId: string; currentName: string }) {+ const [name, setName] = useState(currentName);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const trimmed = name.trim();+ const valid = trimmed.length > 0 && trimmed !== currentName;+ const rename = async () => {+ if (!valid || busy) return;+ setBusy(true);+ setError(null);+ try {+ await rpc.chats.rename(serverId, roomId, trimmed);+ const chat = chatsStore.chat(roomId);+ if (chat) chatsStore.add(serverId, { ...chat, name: trimmed });+ onSuccess();+ } catch (caught) {+ setError(failureText(caught, 'Could not rename the chat.'));+ setBusy(false);+ }+ };+ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Rename chat</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <FieldGroup>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={name}+ autoFocus+ onChange={(event) => setName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') void rename();+ }}+ />+ <p className="mt-1 text-xs text-foreground-muted">+ The room is renamed for everyone in it.+ </p>+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ </Field>+ </FieldGroup>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <ConfirmButton onClick={() => void rename()} disabled={!valid || busy}>+ {busy ? 'Renaming…' : 'Rename'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+}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.tsxnew file mode 100644index 000000000..bde28a362--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx@@ -0,0 +1,251 @@+import { Lock, UserPlus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useRef, useState } from 'react';+import { Button } from '@renderer/lib/ui/button';+import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';+import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';+import { agentActivities } from '../stores/activities';+import type { AgentActivity } from '../stores/chat-activity-store';+import type { ChatTimeline } from '../stores/chat-timeline-store';+import { chatsStore } from '../stores/chats';+import {+ MessageScroller,+ MessageScrollerButton,+ MessageScrollerContent,+ MessageScrollerViewport,+ useMessageScroller,+} from '../ui/message-scroller';+import { ChatComposer } from './chat-composer';+import { ChatTimelineView } from './chat-timeline';++/** How often the session behind each agent is looked up again while the chat is open. */+const RESOLVE_MS = 15_000;+/** How often a running turn's reasoning is read from a local or SSH host. */+const REASONING_MS = 1500;++/** One activity per agent in the chat, held while the chat is on screen. */+export function useAgentActivities(+ serverId: string,+ chat: ChatSummary | undefined+): AgentActivity[] {+ const tenantId = chatsStore.tenantId;+ const agentIds = (chat?.agents ?? []).map((agent) => agent.id).join('\u0000');+ const roomId = chat?.roomId ?? null;+ const [activities, setActivities] = useState<AgentActivity[]>([]);+ useEffect(() => {+ if (!roomId || !agentIds) {+ setActivities([]);+ return;+ }+ const held = agentIds+ .split('\u0000')+ .map((agentId) => agentActivities.acquire(serverId, tenantId, roomId, agentId));+ setActivities(held);+ const timer = setInterval(() => {+ for (const activity of held) void activity.resolve();+ }, RESOLVE_MS);+ return () => {+ clearInterval(timer);+ for (const activity of held) agentActivities.release(activity);+ };+ }, [serverId, tenantId, roomId, agentIds]);+ return activities;+}++const Notice = ({ icon, title, body }: { icon: React.ReactNode; title: string; body: string }) => (+ <div className="flex h-full flex-col items-center justify-center gap-2 p-8 text-center">+ {icon}+ <p className="text-sm font-medium">{title}</p>+ <p className="max-w-sm text-sm text-foreground-muted">{body}</p>+ </div>+);++/**+ * A chat: the room's messages from Switch, kept live, with each agent's+ * activity from Switch's activity feed joined under the messages that+ * started it, and a composer that posts to the+ * room.+ */+export const ChatPanel = observer(function ChatPanel({+ serverId,+ roomId,+}: {+ serverId: string;+ roomId: string;+}) {+ const timeline = chatsStore.timelines.get(serverId, roomId);+ const chat = chatsStore.chat(roomId);+ const activities = useAgentActivities(serverId, chat);+ const [replyTo, setReplyTo] = useState<ChatMessage | null>(null);+ const lost = timeline.accessLost || chatsStore.removed.has(roomId);++ useEffect(() => {+ if (!timeline.loaded && !lost && !timeline.notMember) void timeline.load();+ }, [timeline, lost, timeline.notMember]);++ // Reasoning lives only on a local or SSH host and is read while a turn runs,+ // and whenever the joined turns change.+ const working = activities.some((activity) => activity.working);+ const turnIdsKey = activities+ .map((activity) => [...activity.turns().values()].map((turn) => turn.turnId).join(','))+ .join('|');+ const activeTurnsKey = activities+ .map((activity) =>+ [...activity.turns().values()]+ .filter((turn) => turn.status === 'running' || turn.status === 'queued')+ .map((turn) => turn.turnId)+ .join(',')+ )+ .join('|');+ // The answer carries tool output too, so a tick reads only the turns still+ // running; every turn is read again whenever the set of running turns changes.+ useEffect(() => {+ const read = (activeOnly: boolean) => {+ for (const activity of activities) {+ const turns = [...activity.turns().values()].filter(+ (turn) => !activeOnly || turn.status === 'running' || turn.status === 'queued'+ );+ void activity.readReasoning(turns.slice(-20));+ }+ };+ read(false);+ if (!working) return;+ const timer = setInterval(() => read(true), REASONING_MS);+ return () => clearInterval(timer);+ }, [activities, working, turnIdsKey, activeTurnsKey]);++ if (lost)+ return (+ <Notice+ icon={<Lock className="size-5 text-foreground-muted" />}+ title="You no longer have access to this chat"+ body="You were removed from it, left it, or lost your role in this workspace. Its messages are no longer shown here."+ />+ );+ if (timeline.notMember)+ return (+ <Notice+ icon={<UserPlus className="size-5 text-foreground-muted" />}+ title="You are not in this chat"+ body="Ask the room owner to invite you. Being able to see a room does not let you read its conversation."+ />+ );++ return (+ <div data-chat-panel className="flex h-full min-h-0 flex-col bg-background text-foreground">+ {timeline.loadError && (+ <div+ role="alert"+ className="flex items-center justify-between gap-3 bg-background-1 px-5 py-2 text-sm"+ >+ <span>{timeline.loadError}</span>+ <Button size="sm" variant="outline" onClick={() => void timeline.load()}>+ Try again+ </Button>+ </div>+ )}+ <MessageScroller className="min-h-0 flex-1">+ <MessageScrollerViewport>+ <MessageScrollerContent className="mx-auto w-full max-w-[860px] gap-0 px-5 py-6">+ {!timeline.loaded && timeline.loading ? (+ <p className="text-sm text-foreground-muted">Loading the conversation…</p>+ ) : (+ <ChatTimelineView+ serverId={serverId}+ timeline={timeline}+ agents={chat?.agents ?? []}+ activities={activities}+ onReply={setReplyTo}+ />+ )}+ {timeline.loaded && timeline.messages.length === 0 && timeline.pending.length === 0 && (+ <p className="mt-10 text-center text-sm text-foreground-muted">+ No messages yet. Say what you need below.+ </p>+ )}+ </MessageScrollerContent>+ </MessageScrollerViewport>+ <div+ aria-hidden+ className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-linear-to-t from-background to-transparent"+ />+ <MessageScrollerButton className="absolute bottom-3 left-1/2 -translate-x-1/2" />+ <FollowOwnSends timeline={timeline} />+ </MessageScroller>+ <ActivityUnavailable serverId={serverId} activities={activities} />+ <ChatComposer+ serverId={serverId}+ timeline={timeline}+ agents={chat?.agents ?? []}+ activity={activities[0] ?? null}+ replyTo={replyTo}+ onClearReply={() => setReplyTo(null)}+ disabled={+ chatsStore.streamState === 'offline' && !timeline.loaded+ ? 'Switch cannot be reached right now.'+ : null+ }+ />+ </div>+ );+});++/**+ * 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.+ */+const FollowOwnSends = observer(function FollowOwnSends({ timeline }: { timeline: ChatTimeline }) {+ const { scrollToEnd } = useMessageScroller();+ const latest = timeline.pending.at(-1)?.requestId ?? null;+ const seen = useRef(latest);+ useEffect(() => {+ if (latest === null || latest === seen.current) return;+ seen.current = latest;+ scrollToEnd();+ }, [latest, scrollToEnd]);+ return null;+});++/**+ * Why an agent's activity may be missing or stale: the live activity feed is+ * down, or a snapshot read or host lookup failed.+ */+const ActivityUnavailable = observer(function ActivityUnavailable({+ serverId,+ activities,+}: {+ serverId: string;+ activities: AgentActivity[];+}) {+ const feedDown = activities.length > 0 && agentActivities.feedDown.has(serverId);+ const tooOld = agentActivities.feedDown.get(serverId) === SERVER_TOO_OLD_FOR_ACTIVITY;+ const notes = activities.flatMap((activity) =>+ [activity.feedError, activity.resolveError].filter((note) => note !== null)+ );+ const unique = [...new Set(notes)].filter(+ (note) => !(feedDown && tooOld && note === SERVER_TOO_OLD_FOR_ACTIVITY)+ );+ return (+ <>+ {feedDown && (+ <p+ role="status"+ title={agentActivities.feedDown.get(serverId) ?? undefined}+ className="mx-auto w-full max-w-[860px] px-5 pb-1 text-xs text-foreground-warning"+ >+ {tooOld+ ? SERVER_TOO_OLD_FOR_ACTIVITY+ : 'Live activity is reconnecting — progress may be stale.'}+ </p>+ )}+ {unique.length > 0 && (+ <p+ role="alert"+ className="mx-auto w-full max-w-[860px] px-5 pb-1 text-xs text-foreground-destructive"+ >+ {unique.join(' ')}+ </p>+ )}+ </>+ );+});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.tsxnew file mode 100644index 000000000..c6283eea0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx@@ -0,0 +1,77 @@+import { Loader2, MessageSquare, MoreHorizontal } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { SidebarMenuAction, SidebarMenuRow } from '@renderer/features/sidebar/sidebar-primitives';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from '@renderer/lib/ui/dropdown-menu';+import { RelativeTime } from '@renderer/lib/ui/relative-time';+import type { ChatSummary } from '@shared/core/chats/chats';+import { agentActivities } from '../stores/activities';+import { chatsStore } from '../stores/chats';+import { ChatActionItems, chatActions } from './chat-actions';++/** Whether something is under way in the chat: a send from here, or an agent working. */+function chatBusy(serverId: string, chat: ChatSummary): boolean {+ const timeline = chatsStore.timelines.peek(serverId, chat.roomId);+ if (timeline?.pending.some((send) => send.state === 'sending')) return true;+ return chat.agents.some(+ (agent) =>+ agentActivities.peek(serverId, chatsStore.tenantId, chat.roomId, agent.id)?.working ?? false+ );+}++/** One chat in a list: its name, when it last moved or that it is busy, and its actions. */+export const ChatRow = observer(function ChatRow({+ serverId,+ chat,+ isActive,+ onOpen,+}: {+ serverId: string;+ chat: ChatSummary;+ isActive: boolean;+ onOpen: () => void;+}) {+ const [menuOpen, setMenuOpen] = useState(false);+ const busy = chatBusy(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">+ <span className="flex size-6 shrink-0 items-center justify-center">+ <MessageSquare className="size-4 text-foreground-muted" />+ </span>+ <SidebarMenuAction aria-label={`Open chat ${chat.name}`} className="overflow-hidden">+ <span className="min-w-0 truncate">{chat.name}</span>+ </SidebarMenuAction>+ </div>+ <div className="ml-2 flex min-w-6 shrink-0 items-center justify-end gap-1">+ {!menuOpen && (+ <span className="flex items-center text-xs text-foreground-passive group-hover/row:hidden">+ {busy ? (+ <Loader2 className="size-3.5 animate-spin" aria-label="Working" />+ ) : chat.lastMessage ? (+ <RelativeTime value={chat.lastMessage.sentAt} compact />+ ) : 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>+ </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.tsxnew file mode 100644index 000000000..88b5e6812--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx@@ -0,0 +1,444 @@+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 { agentInitials } from '@shared/core/agents/agent-avatar';+import type { ChatAgent, ChatMessage } from '@shared/core/chats/chats';+import {+ chatAgentLabel,+ isSessionStartingNotice,+ liveSessionStartingNotices,+ turnEndNotice,+} from '@shared/core/chats/chats';+import { foldTurnEndNotices, placeTurns, type TurnActivity } from '../activity-join';+import { messageAnchorId, threadChip } from '../chat-threads';+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 { ChatAttachments } from './chat-attachments';++/** Messages more than this far apart start a new dated group. */+const GROUP_GAP_MS = 30 * 60 * 1000;++function dayLabel(date: Date): string {+ const time = format(date, 'HH:mm');+ if (isToday(date)) return `Today ${time}`;+ if (isYesterday(date)) return `Yesterday ${time}`;+ return format(date, 'd MMM yyyy, HH:mm');+}++function Separator({ children }: { children: ReactNode }) {+ return (+ <div className="flex items-center gap-3 text-xs text-foreground-passive">+ <span className="h-px flex-1 bg-border" />+ {children}+ <span className="h-px flex-1 bg-border" />+ </div>+ );+}++function isBridged(message: ChatMessage): boolean {+ return message.source !== 'console' && message.source !== 'switch';+}++function sourceLabel(message: ChatMessage): string {+ if (!isBridged(message)) return message.sender.name;+ return `${message.sender.name} · from ${bridgePlatformLabel(message.source)}`;+}++/** Another person's initials disc: people have no picture in Switch. */+function PersonAvatar({ name }: { name: string }) {+ return (+ <span+ className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full bg-[var(--fill-2)] text-[11px] font-medium text-foreground"+ title={name}+ aria-hidden+ >+ {agentInitials(name)}+ </span>+ );+}++function scrollToMessage(messageId: string): void {+ document+ .getElementById(messageAnchorId(messageId))+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });+}++function ThreadChipButton({ chip }: { chip: NonNullable<ReturnType<typeof threadChip>> }) {+ return (+ <button+ type="button"+ onClick={() => scrollToMessage(chip.rootId)}+ disabled={chip.snippet === null}+ className="max-w-full truncate text-left text-xs text-foreground-muted hover:text-foreground disabled:cursor-default"+ >+ {chip.label}+ </button>+ );+}++function ReplyButton({ onReply }: { onReply: () => void }) {+ return (+ <button+ type="button"+ onClick={onReply}+ aria-label="Reply"+ title="Reply in thread"+ className="invisible flex size-6 shrink-0 items-center justify-center rounded-md text-foreground-muted group-hover/row:visible hover:bg-background-1 hover:text-foreground"+ >+ <CornerUpLeft className="size-3.5" />+ </button>+ );+}++type Props = {+ serverId: string;+ timeline: ChatTimeline;+ agents: ChatAgent[];+ activities: AgentActivity[];+ onReply: (message: ChatMessage) => void;+};++/**+ * The chat's messages in sequence order, each agent's activity under the+ * room message that started it, then the sends from here the room has not+ * echoed yet.+ */+export const ChatTimelineView = observer(function ChatTimelineView({+ serverId,+ timeline,+ agents,+ activities,+ onReply,+}: Props) {+ const turnsByMessage = new Map<string, { activity: AgentActivity; turn: TurnActivity }[]>();+ const blocksByAnchor = new Map<string, { activity: AgentActivity; turn: TurnActivity }[]>();+ /** Turn-end notices shown on their turn's status row, by message id → `agentId:turnId`. */+ const foldedNotices = new Map<string, string>();+ const boundTurns = new Map(activities.map((activity) => [activity, activity.turns()]));+ for (const [activity, bound] of boundTurns) {+ for (const [messageId, turn] of bound) {+ const list = turnsByMessage.get(messageId) ?? [];+ list.push({ activity, turn });+ turnsByMessage.set(messageId, list);+ }+ for (const [anchorId, turns] of placeTurns(timeline.messages, activity.agentId, bound))+ blocksByAnchor.set(anchorId, [+ ...(blocksByAnchor.get(anchorId) ?? []),+ ...turns.map((turn) => ({ activity, turn })),+ ]);+ for (const [noticeId, turnId] of foldTurnEndNotices(timeline.messages, activity.agentId, bound))+ foldedNotices.set(noticeId, `${activity.agentId}:${turnId}`);+ }+ const endReasons = new Map(+ timeline.messages.flatMap((message) => {+ const turnKey = foldedNotices.get(message.messageId);+ return turnKey ? [[turnKey, turnEndNotice(message)?.reason ?? null] as const] : [];+ })+ );+ const agentOf = (agentId: string | null) => agents.find((agent) => agent.id === agentId) ?? null;+ const find = (messageId: string) => timeline.byId(messageId);+ const myUserId = chatsStore.userId;+ const turnAgents = new Map(+ [...turnsByMessage].map(([messageId, list]) => [+ messageId,+ new Set(list.map(({ activity }) => activity.agentId)),+ ])+ );+ const liveNotices = liveSessionStartingNotices(timeline.messages, turnAgents);+ // Open requests whose turn shows under no loaded message still need an answer.+ const shownRequests = new Set(+ [...blocksByAnchor.values()].flatMap((blocks) =>+ blocks.flatMap(({ turn }) => turn.requests.map((request) => request.requestId))+ )+ );+ let previous: Date | null = null;+ return (+ <div className="flex flex-col gap-5">+ {timeline.hasMore && (+ <div className="flex justify-center">+ <Button+ size="sm"+ variant="ghost"+ disabled={timeline.loading}+ onClick={() => void timeline.loadOlder()}+ >+ {timeline.loading ? 'Loading…' : 'Load earlier messages'}+ </Button>+ </div>+ )}+ {timeline.messages.map((message) => {+ const notice = isSessionStartingNotice(message);+ if (notice && !liveNotices.has(message.messageId)) return null;+ if (foldedNotices.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;+ previous = sentAt;+ 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;+ 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"+ />+ <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>+ ) : 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"+ />+ <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>+ ) : message.sender.kind === 'human' && mine ? (+ <div+ id={messageAnchorId(message.messageId)}+ className="group/row flex flex-col items-end gap-1"+ >+ {chip && <ThreadChipButton chip={chip} />}+ <div className="flex max-w-[85%] items-start gap-1">+ <ReplyButton onReply={() => onReply(message)} />+ <div className="min-w-0 rounded-2xl bg-background-1 px-4 py-2.5 text-sm leading-relaxed break-words whitespace-pre-wrap">+ {message.body}+ </div>+ </div>+ <ChatAttachments+ serverId={serverId}+ roomId={timeline.roomId}+ attachments={message.attachments}+ />+ <span className="text-xs text-foreground-passive">+ {sourceLabel(message)}+ {turns.some(({ turn }) => turn.status === 'queued') && ' · queued'}+ </span>+ </div>+ ) : message.sender.kind === 'human' ? (+ <div id={messageAnchorId(message.messageId)} className="group/row flex gap-3">+ <PersonAvatar name={message.sender.name} />+ <div className="flex max-w-[85%] min-w-0 flex-col items-start gap-1">+ {chip && <ThreadChipButton chip={chip} />}+ <span className="flex items-center gap-1.5 text-xs">+ <span className="font-medium text-foreground-muted">{message.sender.name}</span>+ {isBridged(message) && (+ <span className="rounded bg-background-1 px-1.5 py-px text-[10px] text-foreground-passive">+ {bridgePlatformLabel(message.source)}+ </span>+ )}+ </span>+ <div className="min-w-0 rounded-2xl bg-background-1 px-4 py-2.5 text-sm leading-relaxed break-words whitespace-pre-wrap">+ {message.body}+ </div>+ <ChatAttachments+ serverId={serverId}+ roomId={timeline.roomId}+ attachments={message.attachments}+ />+ {turns.some(({ turn }) => turn.status === 'queued') && (+ <span className="text-xs text-foreground-passive">queued</span>+ )}+ </div>+ <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">+ {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>+ <ChatAttachments+ serverId={serverId}+ roomId={timeline.roomId}+ attachments={message.attachments}+ />+ </div>+ <ReplyButton onReply={() => onReply(message)} />+ </div>+ ) : (+ <p+ id={messageAnchorId(message.messageId)}+ className="text-center text-xs text-foreground-muted"+ >+ {message.body}+ </p>+ )}+ {(blocksByAnchor.get(message.messageId) ?? []).map(({ activity, turn }) => {+ const turnAgent = agentOf(activity.agentId);+ return (+ <ChatActivityBlock+ serverId={serverId}+ key={`${activity.agentId}:${turn.turnId}`}+ activity={activity}+ turn={turn}+ endReason={endReasons.get(`${activity.agentId}:${turn.turnId}`) ?? null}+ agent={{+ name: turnAgent ? chatAgentLabel(turnAgent) : activity.agentId,+ iconUrl: turnAgent?.iconUrl ?? null,+ }}+ />+ );+ })}+ </Fragment>+ );+ })}+ {activities.map((activity) => {+ const requests = [...activity.approvals.values()].filter(+ (request) => request.state === 'open' && !shownRequests.has(request.requestId)+ );+ if (!requests.length) return null;+ const agent = agentOf(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>+ );+ })}+ {timeline.pending.map((send) => (+ <PendingBubble key={send.requestId} timeline={timeline} send={send} find={find} />+ ))}+ </div>+ );+});++const PendingBubble = observer(function PendingBubble({+ timeline,+ send,+ find,+}: {+ timeline: ChatTimeline;+ send: PendingSend;+ find: (messageId: string) => ChatMessage | undefined;+}) {+ 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'}>+ {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}+ </div>+ {send.files.length > 0 && (+ <ul className="flex flex-col items-end gap-0.5 text-xs">+ {send.files.map((file) => (+ <li+ key={file.id}+ className={+ file.state === 'refused' ? 'text-foreground-destructive' : 'text-foreground-muted'+ }+ >+ {file.file.name}+ {file.state === 'uploading' && ' · uploading…'}+ {file.state === 'refused' && ` · not attached: ${file.error}`}+ </li>+ ))}+ </ul>+ )}+ {send.state === 'sending' ? (+ <span className="flex items-center gap-1 text-xs text-foreground-passive">+ <Loader2 className="size-3 animate-spin" /> Sending…+ </span>+ ) : (+ <div role="alert" className="flex max-w-[85%] flex-col items-end gap-1 text-xs">+ <span className="text-right text-foreground-destructive">+ {send.state === 'conflict'+ ? 'This request id was already used for a different message, so it was not sent. Discard it and send again.'+ : send.uncertain+ ? `Not confirmed: ${send.error ?? 'Switch did not answer.'} Retrying sends the same message, never a second copy.`+ : send.error}+ </span>+ <span className="flex gap-1">+ {send.state === 'failed' && (+ <Button size="sm" variant="ghost" onClick={() => timeline.retry(send.requestId)}>+ <RotateCw className="size-3" /> Retry+ </Button>+ )}+ {send.state === 'failed' &&+ !send.posted &&+ send.files.some((file) => file.state === 'refused') && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => timeline.dropRefusedFiles(send.requestId)}+ >+ Send without them+ </Button>+ )}+ <Button size="sm" variant="ghost" onClick={() => timeline.discard(send.requestId)}>+ <X className="size-3" /> Discard+ </Button>+ </span>+ </div>+ )}+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chats-offline-note.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chats-offline-note.tsxnew file mode 100644index 000000000..e34f95756--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chats-offline-note.tsx@@ -0,0 +1,27 @@+import { observer } from 'mobx-react-lite';+import { serverState } from '@renderer/features/switch-servers/server-presentation';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { chatsStore } from '../stores/chats';++/**+ * Beside a server that reads as connected: its chat feed is not. The server+ * answering does not mean chats are live, and saying only "Connected" while+ * every chat shows Offline would contradict it.+ */+export const ChatsOfflineNote = observer(function ChatsOfflineNote({+ server,+}: {+ server: SwitchServer;+}) {+ const state = serverState(server);+ if (state !== 'connected' && state !== 'running-local') return null;+ if (chatsStore.serverId !== server.id || chatsStore.streamState !== 'offline') return null;+ return (+ <span+ className="shrink-0 text-foreground-warning"+ title={chatsStore.streamDetail ?? 'The live chat feed is not connected.'}+ >+ · Chats offline+ </span>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/tool-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/tool-row.tsxnew file mode 100644index 000000000..af326ec88--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/tool-row.tsx@@ -0,0 +1,161 @@+import { useState } from 'react';+import { cn } from '@renderer/utils/utils';+import type { ChatActivityItem } from '@shared/core/chats/activity';+import type { ToolDetail } from '@shared/core/sessions/reasoning';+import type { ToolState } from '../activity-join';+import {+ presentTool,+ shortPath,+ type ToolDetailView,+ type ToolPresentation,+} from '../tool-presentation';+import { ToolKindIcon, WorkLogDetails, WorkLogNote, WorkLogPre, WorkLogRow } from '../ui/work-log';++function Label({ presentation }: { presentation: ToolPresentation }) {+ const { verb, subject, code, kind } = presentation;+ if (!subject) return <>{verb}</>;+ const shown = kind === 'read' || kind === 'edit' ? shortPath(subject) : subject;+ return (+ <>+ {verb}{' '}+ {code ? (+ <code className="rounded bg-background-2 px-1 py-px font-mono text-xs text-foreground-muted">+ {shown}+ </code>+ ) : (+ <span className="text-foreground-muted">{shown}</span>+ )}+ </>+ );+}++function resultCount(output: string | null): number | null {+ if (!output) return null;+ return output.split('\n').filter((line) => line.trim().length > 0).length;+}++function Details({ view }: { view: ToolDetailView }) {+ switch (view.kind) {+ case 'command':+ return (+ <>+ <WorkLogPre>+ <span className="text-foreground">$ {view.command}</span>+ {view.output ? `\n${view.output}` : ''}+ </WorkLogPre>+ {view.exitCode !== null && view.exitCode !== 0 && (+ <WorkLogNote tone="failed">Exit code {view.exitCode}</WorkLogNote>+ )}+ </>+ );+ case 'read':+ return (+ <>+ {view.path && <WorkLogNote>{view.path}</WorkLogNote>}+ {view.output && <WorkLogPre>{view.output}</WorkLogPre>}+ </>+ );+ case 'diff':+ return (+ <>+ {view.path && <WorkLogNote>{view.path}</WorkLogNote>}+ <WorkLogPre className="px-0">+ {view.lines.map((line, index) => (+ <span+ key={index}+ className={cn(+ 'block px-2.5',+ line.sign === '+' && 'bg-background-success/60 text-foreground-success',+ line.sign === '-' && 'bg-background-error/60 text-foreground-error'+ )}+ >+ {line.sign === ' ' ? ' ' : `${line.sign} `}+ {line.text}+ </span>+ ))}+ </WorkLogPre>+ </>+ );+ case 'search': {+ const count = resultCount(view.output);+ return (+ <>+ <WorkLogNote>+ {view.query ? `Pattern: ${view.query}` : 'Search'}+ {view.scope ? ` in ${view.scope}` : ''}+ {count !== null ? ` · ${count} ${count === 1 ? 'result' : 'results'}` : ''}+ </WorkLogNote>+ {view.output && <WorkLogPre>{view.output}</WorkLogPre>}+ </>+ );+ }+ case 'web':+ return (+ <>+ {view.target && <WorkLogNote>{view.target}</WorkLogNote>}+ {view.output && <WorkLogPre>{view.output}</WorkLogPre>}+ </>+ );+ case 'generic':+ return (+ <>+ {view.input && (+ <>+ <WorkLogNote>Input</WorkLogNote>+ <WorkLogPre>{view.input}</WorkLogPre>+ </>+ )}+ {view.output && (+ <>+ <WorkLogNote>Output</WorkLogNote>+ <WorkLogPre>{view.output}</WorkLogPre>+ </>+ )}+ </>+ );+ }+}++/**+ * One tool call as a work-log line. Running shimmers, failed is tinted red+ * and says so, done carries no mark at all. It opens only when the session+ * host gave it something to show.+ */+export function ToolRow({+ item,+ state,+ detail,+}: {+ item: ChatActivityItem;+ state: ToolState;+ detail: ToolDetail | null;+}) {+ const [open, setOpen] = useState(false);+ const presentation = presentTool(item, detail);+ const { details, truncated } = presentation;+ const failed = state === 'failed';+ return (+ <WorkLogRow+ icon={<ToolKindIcon kind={presentation.kind} />}+ label={<Label presentation={presentation} />}+ title={presentation.subject ?? undefined}+ tone={failed ? 'failed' : state === 'declined' ? 'passive' : 'default'}+ active={state === 'running'}+ trailing={+ failed ? (+ <span className="shrink-0 text-xs text-foreground-destructive">Failed</span>+ ) : state === 'declined' ? (+ <span className="shrink-0 text-xs text-foreground-passive">Declined</span>+ ) : null+ }+ {...(details ? { open, onToggle: () => setOpen(!open) } : {})}+ >+ {details && open && (+ <WorkLogDetails>+ <Details view={details} />+ {truncated && <WorkLogNote>Long values were clipped.</WorkLogNote>}+ </WorkLogDetails>+ )}+ </WorkLogRow>+ );+}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.tsxnew file mode 100644index 000000000..8fe6ec9d9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-redirect.tsx@@ -0,0 +1,46 @@+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';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';+import { appState } from '@renderer/lib/stores/app-state';+import { consoleChatRoute } from './console-chat-route';+import { chatsStore } from './stores/chats';++/**+ * On the room page, with agent_chats on: a 1-1 Console chat is not a room, so+ * it opens in the chat UI instead, whether reached from a deep link, search, a+ * notification or the view restored at start. The room page leaves history so+ * Back does not return to it and redirect again.+ */+export const ConsoleChatRedirect = observer(function ConsoleChatRedirect({+ roomId,+}: {+ roomId: string;+}): null {+ const serverId = switchRoomsStore.roomServerId(roomId) ?? chatsStore.serverId;+ const enabled = useFeatureFlags(serverId).agent_chats;+ const managed = useManagedAgents(serverId);+ const chat = chatsStore.serverId === serverId ? chatsStore.chat(roomId) : undefined;+ const agent = chat && isConsoleDirectChatSummary(chat) ? chat.agents[0] : undefined;+ const isManaged = managed.data?.some((each) => each.agentId === agent?.id) ?? false;++ useEffect(() => {+ if (!enabled || !serverId || !agent || managed.isLoading) return;+ const route = consoleChatRoute(serverId, roomId, agent, isManaged);+ appState.history.prune(+ (entry) =>+ entry.kind === 'view' &&+ 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);+ }, [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.tsnew file mode 100644index 000000000..abb6942b1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/console-chat-route.ts@@ -0,0 +1,26 @@+import { type ChatAgent, chatAgentLabel } from '@shared/core/chats/chats';++export type ConsoleChatRoute =+ | {+ viewId: 'managedAgent';+ params: { serverId: string; agentId: string; name: string; roomId: string };+ }+ | { 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.+ */+export function consoleChatRoute(+ serverId: string,+ roomId: string,+ agent: Pick<ChatAgent, 'id' | 'name' | 'displayName'>,+ managed: boolean+): ConsoleChatRoute {+ if (managed)+ return {+ viewId: 'managedAgent',+ params: { serverId, agentId: agent.id, name: chatAgentLabel(agent), roomId },+ };+ return { viewId: 'chat', params: { serverId, roomId, agentId: agent.id } };+}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.tsnew file mode 100644index 000000000..1c0d34afe--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts@@ -0,0 +1,32 @@+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { focusComposerWhenOpened } from './components/chat-composer';+import { chatsStore, chatTitler } from './stores/chats';+import { DirectChatStarter } from './stores/direct-chat-starter';+import { EmptyChatFinder } from './stores/empty-chat-finder';++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. */+export const directChats = new DirectChatStarter({+ create: (input) => rpc.chats.create(input),+ created: (serverId, chat) => {+ chatsStore.add(serverId, chat);+ chatTitler.created(chat, false);+ focusComposerWhenOpened(chat.roomId);+ },+ opened: (chat) => {+ focusComposerWhenOpened(chat.roomId);+ },+ 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/activities.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.tsnew file mode 100644index 000000000..a6b235993--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts@@ -0,0 +1,39 @@+import { events, rpc } from '@renderer/lib/ipc';+import {+ chatActivityChannel,+ chatActivityResyncChannel,+ chatActivityStateChannel,+ chatApprovalChannel,+ chatRemovedChannel,+ chatResetChannel,+} from '@shared/core/chats/chatEvents';+import { roomHealthChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';+import { AgentActivities } from './chat-activity-store';++/** The app's agent activities, kept in step with the activity feed, placements and access. */+export const agentActivities = new AgentActivities(+ {+ resolve: (serverId, agentId, roomId) => rpc.chats.activity({ serverId, agentId, roomId }),+ reasoning: (hostAgentKey, sessionId, turnIds) =>+ rpc.sdkHost.reasoningList(hostAgentKey, sessionId, turnIds),+ watchPlacements: (serverId, onChange) =>+ events.on(roomHealthChangedChannel, onChange, serverId),+ roomActivity: (serverId, roomId) => rpc.chats.roomActivity(serverId, roomId),+ control: (input) => rpc.chats.control(input),+ answerApproval: (input) => rpc.chats.answerApproval(input),+ },+ sessionStorage+);++events.on(chatActivityChannel, ({ serverId, item }) => agentActivities.applyItem(serverId, item));+events.on(chatApprovalChannel, ({ serverId, approval }) =>+ agentActivities.applyApproval(serverId, approval)+);+events.on(chatActivityResyncChannel, ({ serverId }) => agentActivities.resync(serverId));+events.on(chatActivityStateChannel, ({ serverId, state, detail }) =>+ agentActivities.feedState(serverId, state, detail)+);+events.on(chatRemovedChannel, ({ serverId, roomId, reason }) => {+ if (reason === 'access') agentActivities.drop(serverId, roomId);+});+events.on(chatResetChannel, ({ serverId }) => agentActivities.drop(serverId, null));diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/agent-chats-flag.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/agent-chats-flag.tsnew file mode 100644index 000000000..273bc9c9a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/agent-chats-flag.ts@@ -0,0 +1,39 @@+import { observable, runInAction } from 'mobx';+import { events, rpc } from '@renderer/lib/ipc';+import type { ServerFeatureFlags } from '@shared/core/feature-flags/feature-flags';+import { featureFlagsChangedChannel } from '@shared/events/featureFlagEvents';++const known = observable.map<string, boolean>();+const asked = new Set<string>();++function record(state: ServerFeatureFlags): void {+ if (state.fetchedAt === null) return;+ runInAction(() => known.set(state.serverId, state.flags.agent_chats));+}++events.on(featureFlagsChangedChannel, record);++const RETRY_MS = 15_000;++/** Read the server's flags, now if never read, and again until a read succeeds. */+function ask(serverId: string): void {+ void rpc.featureFlags.current(serverId).then((res) => {+ if (!res?.success) return;+ record(res.data);+ if (res.data.fetchedAt === null && !known.has(serverId))+ setTimeout(() => ask(serverId), RETRY_MS);+ });+}++/**+ * Whether a server turns agent_chats on, observable outside React. Undefined+ * until the server's flags have been read once, which is tried again until it+ * works; a server that does not send the flag is off.+ */+export function agentChatsFlag(serverId: string): boolean | undefined {+ if (!asked.has(serverId)) {+ asked.add(serverId);+ ask(serverId);+ }+ return known.get(serverId);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.tsnew file mode 100644index 000000000..a9aa45674--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts@@ -0,0 +1,532 @@+import { makeAutoObservable, observable, reaction, runInAction } from 'mobx';+import { failureText } from '@renderer/lib/errors/describe-failure';+import type {+ ChatActivityItem,+ ChatActivityTarget,+ ChatApproval,+ ChatApprovalAnswer,+ ChatControlCommand,+ RoomActivity,+} from '@shared/core/chats/activity';+import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';+import type { ChatStreamState } from '@shared/core/chats/chats';+import type { ReasoningList, ReasoningTurn, ToolDetail } from '@shared/core/sessions/reasoning';+import { bindTurns, groupTurns, itemKey, type TurnActivity } from '../activity-join';+import { chatFailure, serverTooOld } from './chat-errors';++/**+ * What one agent is doing in one chat, from Switch's activity feed: the+ * steps of its turns and the requests it put to people, joined to the room+ * messages that started them. Snapshots and live rows are merged by+ * revision, so a row older than the one held is dropped whichever arrives+ * first.+ *+ * Stop, Reset and Compact are posted to the room as commands; the agent+ * answers each in a thread rooted at the command. Reasoning and full tool+ * input and output are read from the agent's session host when it runs on+ * this machine or its SSH host — the only thing the host is asked for.+ */++export type ActivityApi = {+ resolve: (serverId: string, agentId: string, roomId: string) => Promise<ChatActivityTarget>;+ reasoning: (+ hostAgentKey: string,+ sessionId: string,+ turnIds: string[] | null+ ) => Promise<ReasoningList | null>;+ /** Call `onChange` whenever the server's local or SSH placements change. */+ watchPlacements: (serverId: string, onChange: () => void) => () => void;+ roomActivity: (serverId: string, roomId: string) => Promise<RoomActivity>;+ control: (input: {+ serverId: string;+ roomId: string;+ requestId: string;+ agentId: string;+ command: ChatControlCommand;+ }) => Promise<string>;+ answerApproval: (input: {+ serverId: string;+ agentId: string;+ sessionId: string;+ requestId: string;+ answer: ChatApprovalAnswer;+ }) => Promise<ChatApproval>;+};++/**+ * A Stop, Reset or Compact sent from here: `requested` once Switch posted it,+ * not once done. `unknown`: no answer came back, so it may have been posted;+ * it is only ever sent again under the same request id, which Switch answers+ * with the command it already posted.+ */+export type ControlRequest = {+ requestId: string;+ command: ChatControlCommand;+ state: 'sending' | 'requested' | 'failed' | 'unknown';+ /** The room message the command is; the agent's answer threads under it. */+ commandId: string | null;+ error: string | null;+};++const unsettled = (control: ControlRequest) =>+ control.state === 'sending' || control.state === 'unknown';++const approvalKey = (approval: ChatApproval) =>+ JSON.stringify([approval.sessionId, approval.requestId]);++export class AgentActivity {+ target: ChatActivityTarget | null = null;+ resolveError: string | null = null;+ /** Why the room's activity snapshot could not be read; null once it has been. */+ feedError: string | null = null;+ readonly items = observable.map<string, ChatActivityItem>({}, { deep: false });+ readonly approvals = observable.map<string, ChatApproval>({}, { deep: false });+ controls: ControlRequest[] = [];+ reasoning = new Map<string, ReasoningTurn>();+ /** Tool item id → what the call was given and gave back; local and SSH hosts only. */+ toolDetails = new Map<string, ToolDetail>();+ private resolving = false;+ /** Counts rows taken; each held row remembers when, so a snapshot only drops rows older than its request. */+ private taken = 0;+ private readonly takenAt = new Map<string, number>();++ constructor(+ readonly serverId: string,+ readonly tenantId: string | null,+ readonly roomId: string,+ readonly agentId: string,+ private readonly api: ActivityApi+ ) {+ makeAutoObservable<AgentActivity, 'api' | 'resolving' | 'taken' | 'takenAt'>(this, {+ api: false,+ resolving: false,+ taken: false,+ takenAt: false,+ target: observable.ref,+ });+ }++ /** Take a row of this agent in this room, unless one at least as new is held. */+ applyItem(item: ChatActivityItem): void {+ if (item.agentId !== this.agentId || item.roomId !== this.roomId) return;+ const key = itemKey(item);+ const held = this.items.get(key);+ if (held && held.revision >= item.revision) return;+ this.items.set(key, item);+ this.takenAt.set(`i${key}`, ++this.taken);+ }++ /** Take a request of this agent in this room; a settled one is never reopened by an older copy. */+ applyApproval(approval: ChatApproval): void {+ if (approval.agentId !== this.agentId || approval.roomId !== this.roomId) return;+ const key = approvalKey(approval);+ const held = this.approvals.get(key);+ if (held && held.state !== 'open' && approval.state === 'open') return;+ this.approvals.set(key, approval);+ this.takenAt.set(`a${key}`, ++this.taken);+ }++ /** Where the row count stands; take it when a snapshot is requested and pass it to {@link applySnapshot}. */+ get mark(): number {+ return this.taken;+ }++ /**+ * The snapshot is the room's whole activity as of its request: a row held+ * from before `mark` that it lacks has aged out or been pruned, and goes.+ * Rows taken from the live feed since `mark` stay.+ */+ applySnapshot(snapshot: RoomActivity, mark: number): void {+ this.feedError = null;+ const items = new Set(snapshot.items.map(itemKey));+ for (const key of [...this.items.keys()])+ if (!items.has(key) && (this.takenAt.get(`i${key}`) ?? 0) <= mark) {+ this.items.delete(key);+ this.takenAt.delete(`i${key}`);+ }+ const approvals = new Set(snapshot.approvals.map(approvalKey));+ for (const key of [...this.approvals.keys()])+ if (!approvals.has(key) && (this.takenAt.get(`a${key}`) ?? 0) <= mark) {+ this.approvals.delete(key);+ this.takenAt.delete(`a${key}`);+ }+ for (const item of snapshot.items) this.applyItem(item);+ for (const approval of snapshot.approvals) this.applyApproval(approval);+ }++ get allTurns(): TurnActivity[] {+ return groupTurns(this.items.values(), this.approvals.values());+ }++ /** Turns joined to the room messages that started them. */+ get bound(): Map<string, TurnActivity> {+ return bindTurns(this.allTurns, this.roomId);+ }++ turns(): Map<string, TurnActivity> {+ return this.bound;+ }++ /** The turn running now, which Stop interrupts. */+ get runningTurn(): TurnActivity | null {+ return this.allTurns.findLast((turn) => turn.status === 'running') ?? null;+ }++ get working(): boolean {+ return this.allTurns.some((turn) => turn.status === 'running' || turn.status === 'queued');+ }++ /** A Stop, Reset or Compact still being posted. */+ get pendingControl(): ControlRequest | null {+ return this.controls.findLast((control) => control.state === 'sending') ?? null;+ }++ async resolve(): Promise<void> {+ if (this.resolving) return;+ this.resolving = true;+ try {+ const target = await this.api.resolve(this.serverId, this.agentId, this.roomId);+ runInAction(() => {+ this.resolveError = null;+ this.target = target;+ });+ } catch (error) {+ runInAction(() => {+ this.resolveError = failureText(error, "The agent's session could not be looked up.");+ });+ } finally {+ this.resolving = false;+ }+ }++ /**+ * Post a command to the room for this agent. A command of the same kind+ * whose outcome is unknown is sent again under its own request id instead,+ * so a Reset that landed before its answer was lost never runs twice.+ */+ async control(command: ChatControlCommand): Promise<void> {+ const unknown = this.controls.find(+ (control) => control.state === 'unknown' && control.command === command+ );+ if (unknown) return this.post(unknown);+ this.controls.push({+ requestId: crypto.randomUUID(),+ command,+ state: 'sending',+ commandId: null,+ error: null,+ });+ return this.post(this.controls.at(-1)!);+ }++ /** Send a command whose outcome is unknown again, under the same request id. */+ async retryControl(requestId: string): Promise<void> {+ const control = this.controls.find((each) => each.requestId === requestId);+ if (control?.state === 'unknown') await this.post(control);+ }++ /** Settle every command whose outcome is unknown, e.g. once the feed is back. */+ retryUnknownControls(): void {+ for (const control of this.controls) if (control.state === 'unknown') void this.post(control);+ }++ private async post(held: ControlRequest): Promise<void> {+ const command = held.command;+ runInAction(() => {+ held.state = 'sending';+ held.error = null;+ });+ try {+ const commandId = await this.api.control({+ serverId: this.serverId,+ roomId: this.roomId,+ requestId: held.requestId,+ agentId: this.agentId,+ command,+ });+ runInAction(() => {+ held.state = 'requested';+ held.commandId = commandId;+ this.keepLatestSettled(held);+ });+ } catch (error) {+ const failure = chatFailure(error);+ runInAction(() => {+ held.state = failure.uncertain ? 'unknown' : 'failed';+ held.error = serverTooOld(error) ? SERVER_TOO_OLD_FOR_ACTIVITY : failure.message;+ if (held.state === 'failed') this.keepLatestSettled(held);+ });+ }+ }++ /** Only the command settled last shows its outcome; ones still open stay. */+ private keepLatestSettled(held: ControlRequest): void {+ this.controls = this.controls.filter((control) => control === held || unsettled(control));+ }++ /** Forget a settled command; one whose outcome is unknown stays until a retry settles it. */+ dismissControl(requestId: string): void {+ this.controls = this.controls.filter(+ (control) => control.requestId !== requestId || control.state === 'unknown'+ );+ }++ /** Answer a request as the signed-in person; the answered copy replaces the held one. */+ async answer(approval: ChatApproval, answer: ChatApprovalAnswer): Promise<void> {+ const answered = await this.api.answerApproval({+ serverId: this.serverId,+ agentId: approval.agentId,+ sessionId: approval.sessionId,+ requestId: approval.requestId,+ answer,+ });+ runInAction(() => this.applyApproval(answered));+ }++ /** Ask the host for the reasoning and tool details of these turns; local and SSH hosts only. */+ async readReasoning(turns: TurnActivity[]): Promise<void> {+ const target = this.target;+ if (target?.kind !== 'session') return;+ const turnIds = turns+ .filter((turn) => turn.sessionId === target.sessionId)+ .map((turn) => turn.turnId);+ if (!turnIds.length) return;+ const list = await this.api.reasoning(target.hostAgentKey, target.sessionId, turnIds);+ runInAction(() => {+ if (!list) return;+ for (const turn of list.turns) this.reasoning.set(turn.turnId, turn);+ for (const turn of list.tools ?? [])+ for (const tool of turn.tools) this.toolDetails.set(tool.itemId, tool);+ });+ }+}++const CONTROLS_KEY = 'switch-console.chat-controls';++/** Activities by server, room and agent, shared by the views showing them. */+export class AgentActivities {+ /** Observable so a view that only peeks (the chat's title bar) follows the one holding it. */+ private readonly entries = observable.map<string, { activity: AgentActivity; users: number }>(+ {},+ { deep: false }+ );+ /** Unsettled controls of activities no view holds, by entry key. */+ private readonly parked = observable.map<string, ControlRequest[]>({}, { deep: false });+ /** The activity feed's connection for each server, when it is down: why. Absent while live. */+ readonly feedDown = observable.map<string, string | null>({}, { deep: false });+ private readonly watches = new Map<string, () => void>();+ /** Rooms whose snapshot is due, read once per room however many agents asked. */+ private readonly due = new Set<string>();+ /** The newest snapshot read of each room; an older or dropped read's answer is ignored. */+ private readonly latestLoad = new Map<string, number>();+ private loads = 0;++ /**+ * Unsettled controls are kept in `storage` (the window's sessionStorage) so+ * a reload still settles them under their request ids. One still sending+ * when the window went has no answer coming, so it comes back unknown.+ */+ constructor(+ private readonly api: ActivityApi,+ storage: Pick<Storage, 'getItem' | 'setItem'>+ ) {+ const saved = storage.getItem(CONTROLS_KEY);+ for (const [key, controls] of saved ? (JSON.parse(saved) as [string, ControlRequest[]][]) : [])+ this.parked.set(+ key,+ controls.map((control) =>+ control.state === 'sending'+ ? { ...control, state: 'unknown', error: 'The window reloaded before Switch answered.' }+ : control+ )+ );+ reaction(+ () =>+ JSON.stringify(+ [+ ...[...this.entries].map(([key, { activity }]) => [key, activity.controls] as const),+ ...this.parked,+ ].flatMap(([key, controls]) => {+ const open = controls.filter(unsettled);+ return open.length ? [[key, open]] : [];+ })+ ),+ (json) => storage.setItem(CONTROLS_KEY, json)+ );+ }++ private syncWatches(): void {+ const servers = new Set([...this.entries.values()].map(({ activity }) => activity.serverId));+ for (const serverId of servers)+ if (!this.watches.has(serverId))+ this.watches.set(+ serverId,+ this.api.watchPlacements(serverId, () => this.refresh(serverId, null))+ );+ for (const [serverId, off] of this.watches)+ if (!servers.has(serverId)) {+ off();+ this.watches.delete(serverId);+ }+ }++ private inRoom(serverId: string, roomId: string): AgentActivity[] {+ return [...this.entries.values()]+ .map(({ activity }) => activity)+ .filter((activity) => activity.serverId === serverId && activity.roomId === roomId);+ }++ /** Read the room's snapshot soon, once for every agent asking in the same tick. */+ private scheduleLoad(serverId: string, roomId: string): void {+ const key = JSON.stringify([serverId, roomId]);+ if (this.due.has(key)) return;+ this.due.add(key);+ queueMicrotask(() => {+ this.due.delete(key);+ void this.loadRoom(serverId, roomId);+ });+ }++ async loadRoom(serverId: string, roomId: string): Promise<void> {+ const key = JSON.stringify([serverId, roomId]);+ const load = ++this.loads;+ this.latestLoad.set(key, load);+ const current = () => this.latestLoad.get(key) === load;+ const marks = new Map(+ this.inRoom(serverId, roomId).map((activity) => [activity, activity.mark])+ );+ try {+ const snapshot = await this.api.roomActivity(serverId, roomId);+ if (!current()) return;+ runInAction(() => {+ // An activity acquired while the snapshot was read held nothing older than it.+ for (const activity of this.inRoom(serverId, roomId))+ activity.applySnapshot(snapshot, marks.get(activity) ?? 0);+ });+ } catch (error) {+ if (!current()) return;+ const message = serverTooOld(error)+ ? SERVER_TOO_OLD_FOR_ACTIVITY+ : failureText(error, "The agents' activity in this chat could not be read.");+ runInAction(() => {+ for (const activity of this.inRoom(serverId, roomId)) activity.feedError = message;+ });+ }+ }++ /**+ * The feed reconnected or may have missed changes: read every room shown+ * again, and settle the commands whose outcome was lost.+ */+ resync(serverId: string): void {+ const shown = [...this.entries.values()]+ .map(({ activity }) => activity)+ .filter((activity) => activity.serverId === serverId);+ for (const roomId of new Set(shown.map((activity) => activity.roomId)))+ this.scheduleLoad(serverId, roomId);+ for (const activity of shown) activity.retryUnknownControls();+ }++ feedState(serverId: string, state: ChatStreamState, detail: string | null): void {+ runInAction(() => {+ if (state === 'offline') this.feedDown.set(serverId, detail);+ else if (state === 'live') this.feedDown.delete(serverId);+ });+ }++ applyItem(serverId: string, item: ChatActivityItem): void {+ if (!item.roomId) return;+ for (const activity of this.inRoom(serverId, item.roomId)) activity.applyItem(item);+ }++ applyApproval(serverId: string, approval: ChatApproval): void {+ if (!approval.roomId) return;+ for (const activity of this.inRoom(serverId, approval.roomId)) activity.applyApproval(approval);+ }++ acquire(+ serverId: string,+ tenantId: string | null,+ roomId: string,+ agentId: string+ ): AgentActivity {+ const key = JSON.stringify([serverId, tenantId, roomId, agentId]);+ let entry = this.entries.get(key);+ if (!entry) {+ entry = {+ activity: new AgentActivity(serverId, tenantId, roomId, agentId, this.api),+ users: 0,+ };+ const parked = this.parked.get(key)?.filter(unsettled);+ if (parked) entry.activity.controls = parked;+ const created = entry;+ runInAction(() => {+ this.parked.delete(key);+ this.entries.set(key, created);+ });+ this.syncWatches();+ void entry.activity.resolve();+ this.scheduleLoad(serverId, roomId);+ }+ entry.users += 1;+ return entry.activity;+ }++ /** An activity some view already holds, without holding it. */+ peek(+ serverId: string,+ tenantId: string | null,+ roomId: string,+ agentId: string+ ): AgentActivity | null {+ return (+ this.entries.get(JSON.stringify([serverId, tenantId, roomId, agentId]))?.activity ?? null+ );+ }++ release(activity: AgentActivity): void {+ const key = JSON.stringify([+ activity.serverId,+ activity.tenantId,+ activity.roomId,+ activity.agentId,+ ]);+ const entry = this.entries.get(key);+ if (!entry || entry.activity !== activity) return;+ entry.users -= 1;+ if (entry.users > 0) return;+ // A command still sending or of unknown outcome outlives the view, so reopening reuses its request id.+ const open = activity.controls.filter(unsettled);+ runInAction(() => {+ if (open.length > 0) this.parked.set(key, open);+ this.entries.delete(key);+ });+ this.syncWatches();+ }++ /** Look again for where every activity on the server runs (placements changed). */+ refresh(serverId: string, agentId: string | null): void {+ for (const { activity } of this.entries.values())+ if (activity.serverId === serverId && (agentId === null || activity.agentId === agentId))+ void activity.resolve();+ }++ /** Forget everything for a room the person lost, or a whole server on reset. */+ drop(serverId: string, roomId: string | null): void {+ if (roomId === null) runInAction(() => this.feedDown.delete(serverId));+ for (const [key, { activity }] of this.entries)+ if (activity.serverId === serverId && (roomId === null || activity.roomId === roomId))+ runInAction(() => this.entries.delete(key));+ for (const key of this.latestLoad.keys()) {+ const [loadServer, loadRoom] = JSON.parse(key) as [string, string];+ if (loadServer === serverId && (roomId === null || loadRoom === roomId))+ this.latestLoad.delete(key);+ }+ for (const key of [...this.parked.keys()]) {+ const [parkedServer, , parkedRoom] = JSON.parse(key) as [string, string | null, string];+ if (parkedServer === serverId && (roomId === null || parkedRoom === roomId))+ runInAction(() => this.parked.delete(key));+ }+ this.syncWatches();+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-errors.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-errors.tsnew file mode 100644index 000000000..c162a115d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-errors.ts@@ -0,0 +1,60 @@+import { failureText } from '@renderer/lib/errors/describe-failure';+import { RpcError } from '@shared/lib/ipc/rpc-error';++/**+ * What a failed `/chats` call means for the chat: the person lost access, a+ * request id was reused with another payload, the server refused the message+ * on trust grounds, or something else — and whether the outcome is unknown+ * (the request may have been applied), in which case only a retry with the+ * same request id is safe.+ */+export type ChatFailure = {+ kind: 'not-a-member' | 'request-reused' | 'refused' | 'not-a-manager' | 'agent-owner' | 'other';+ message: string;+ /** The server may have applied the request; retrying with the same id is safe. */+ uncertain: boolean;+};++const API_CODES: Record<string, ChatFailure['kind']> = {+ NOT_A_MEMBER: 'not-a-member',+ REQUEST_REUSED: 'request-reused',+ MESSAGE_REFUSED: 'refused',+ NOT_A_MANAGER: 'not-a-manager',+ AGENT_OWNER: 'agent-owner',+};++export function chatFailure(error: unknown): ChatFailure {+ if (error instanceof RpcError) {+ if (error.code === 'ChatApiError') {+ const apiCode = error.stringField('apiCode') ?? '';+ return { kind: API_CODES[apiCode] ?? 'other', message: error.message, uncertain: false };+ }+ if (error.code === 'GatewayError') {+ const kind = error.stringField('kind');+ const status = error.numberField('status');+ // No answer, or a server error: the request may have landed.+ const uncertain = kind === 'network' || (status !== undefined && status >= 500);+ return { kind: 'other', message: failureText(error, 'Switch did not answer.'), uncertain };+ }+ // An answer that did not match the contract arrived after the server acted.+ return {+ kind: 'other',+ message: failureText(error, 'The request failed.'),+ uncertain: error.code === 'ZodError',+ };+ }+ return {+ kind: 'other',+ message: failureText(error, 'The request failed.'),+ uncertain: true,+ };+}++/** An uncoded 404 from an activity route: the server predates live chat activity. */+export function serverTooOld(error: unknown): boolean {+ return (+ error instanceof RpcError &&+ error.code === 'GatewayError' &&+ error.numberField('status') === 404+ );+}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.tsnew file mode 100644index 000000000..8e751c8e2--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts@@ -0,0 +1,337 @@+import { makeAutoObservable, runInAction } from 'mobx';+import {+ type ChatMessage,+ type ChatMessagesPage,+ type ChatUpload,+ requestIdOfClientTxn,+} from '@shared/core/chats/chats';+import { chatFailure } from './chat-errors';++/**+ * One chat's messages as the room holds them, by sequence, and the sends the+ * person made from here that the room has not echoed yet.+ *+ * A send is identified by its request id from the moment it is made: a retry+ * reuses it, so the server applies it at most once however often it is asked,+ * and the echo (`clientTxn` = `{requestId}:{i}`) is what retires it. A send+ * whose outcome is unknown stays visible as such — it is never resent on its+ * own, and never dropped as if it had failed.+ */++export const PAGE_SIZE = 50;++export type ChatFile = {+ name: string;+ type: string;+ size: number;+ /** The bytes, base64. */+ read: () => Promise<string>;+};++export type PendingFile = {+ id: string;+ /** Stable across retries: the upload is idempotent per upload id. */+ uploadId: string;+ file: ChatFile;+ state: 'waiting' | 'uploading' | 'uploaded' | 'refused';+ error: string | null;+};++export type PendingSend = {+ requestId: string;+ body: string;+ threadRootId: string | null;+ files: PendingFile[];+ state: 'sending' | 'failed' | 'conflict';+ error: string | null;+ /** The server may have taken it: only a retry with the same request id is safe. */+ uncertain: boolean;+ /** The message itself was posted at least once (not just its files). */+ posted: boolean;+};++export type SendInput = {+ body: string;+ threadRootId: string | null;+ files: ChatFile[];+};++export type TimelineApi = {+ messages: (roomId: string, beforeSeq: number | null, limit: number) => Promise<ChatMessagesPage>;+ upload: (+ roomId: string,+ file: { uploadId: string; name: string; mimeType: string; data: string }+ ) => Promise<ChatUpload>;+ send: (+ roomId: string,+ input: {+ requestId: string;+ body: string;+ threadRootId: string | null;+ uploadIds: string[];+ }+ ) => Promise<ChatMessage[]>;+ newId: () => string;+};++export class ChatTimeline {+ messages: ChatMessage[] = [];+ pending: PendingSend[] = [];+ hasMore = false;+ loaded = false;+ loading = false;+ loadError: string | null = null;+ /** The person is not a member of the room. */+ notMember = false;+ /** The person was a member and lost access while the chat was known. */+ accessLost = false;++ constructor(+ readonly roomId: string,+ private readonly api: TimelineApi+ ) {+ makeAutoObservable<ChatTimeline, 'api'>(this, { api: false, roomId: false });+ }++ get newestSeq(): number | null {+ return this.messages.at(-1)?.seq ?? null;+ }++ byId(messageId: string): ChatMessage | undefined {+ return this.messages.find((message) => message.messageId === messageId);+ }++ /** Merge a message from the room: by sequence, once, retiring the send it echoes. */+ apply(message: ChatMessage): void {+ if (message.roomId !== this.roomId) return;+ const requestId = requestIdOfClientTxn(message.clientTxn);+ if (requestId) this.pending = this.pending.filter((send) => send.requestId !== requestId);+ if (this.messages.some((each) => each.seq === message.seq)) return;+ const at = this.messages.findIndex((each) => each.seq > message.seq);+ if (at === -1) this.messages.push(message);+ else this.messages.splice(at, 0, message);+ }++ async load(): Promise<void> {+ if (this.loading) return;+ this.loading = true;+ this.loadError = null;+ try {+ const page = await this.api.messages(this.roomId, null, PAGE_SIZE);+ runInAction(() => {+ for (const message of page.messages) this.apply(message);+ if (!this.loaded) this.hasMore = page.hasMore;+ this.loaded = true;+ this.notMember = false;+ });+ } catch (error) {+ const failure = chatFailure(error);+ runInAction(() => {+ if (failure.kind === 'not-a-member') this.notMember = true;+ else this.loadError = failure.message;+ });+ } finally {+ runInAction(() => {+ this.loading = false;+ });+ }+ }++ async loadOlder(): Promise<void> {+ const oldest = this.messages[0]?.seq ?? null;+ if (this.loading || !this.hasMore || oldest === null) return;+ this.loading = true;+ try {+ const page = await this.api.messages(this.roomId, oldest, PAGE_SIZE);+ runInAction(() => {+ for (const message of page.messages) this.apply(message);+ this.hasMore = page.hasMore;+ });+ } catch (error) {+ runInAction(() => {+ this.loadError = chatFailure(error).message;+ });+ } finally {+ runInAction(() => {+ this.loading = false;+ });+ }+ }++ /** Send a message; returns its request id. */+ send(input: SendInput): string {+ const send: PendingSend = {+ requestId: this.api.newId(),+ body: input.body,+ threadRootId: input.threadRootId,+ files: input.files.map((file) => ({+ id: this.api.newId(),+ uploadId: this.api.newId(),+ file,+ state: 'waiting',+ error: null,+ })),+ state: 'sending',+ error: null,+ uncertain: false,+ posted: false,+ };+ this.pending.push(send);+ void this.attempt(send.requestId);+ return send.requestId;+ }++ /** Ask again with the same request id and the same files. */+ retry(requestId: string): void {+ const send = this.find(requestId);+ if (!send || send.state === 'sending') return;+ void this.attempt(requestId);+ }++ /**+ * Drop the files the server refused and send the rest. Only before the+ * message was posted: a posted request id names its payload for good.+ */+ dropRefusedFiles(requestId: string): void {+ const send = this.find(requestId);+ if (!send || send.posted || send.state === 'sending') return;+ send.files = send.files.filter((file) => file.state !== 'refused');+ void this.attempt(requestId);+ }++ discard(requestId: string): void {+ this.pending = this.pending.filter((send) => send.requestId !== requestId);+ }++ /** The person lost access: nothing held for the room is theirs to see any more. */+ revoke(): void {+ this.accessLost = true;+ this.messages = [];+ this.pending = [];+ }++ /** Access came back: read the room again from scratch. */+ restore(): void {+ if (!this.accessLost && !this.notMember) return;+ this.accessLost = false;+ this.notMember = false;+ this.loaded = false;+ this.loadError = null;+ }++ private find(requestId: string): PendingSend | undefined {+ return this.pending.find((send) => send.requestId === requestId);+ }++ private async attempt(requestId: string): Promise<void> {+ const send = this.find(requestId);+ if (!send) return;+ runInAction(() => {+ send.state = 'sending';+ send.error = null;+ });+ await Promise.all(+ send.files+ .filter((file) => file.state !== 'uploaded')+ .map(async (file) => {+ runInAction(() => {+ file.state = 'uploading';+ file.error = null;+ });+ try {+ await this.api.upload(this.roomId, {+ uploadId: file.uploadId,+ name: file.file.name,+ mimeType: file.file.type || 'application/octet-stream',+ data: await file.file.read(),+ });+ runInAction(() => {+ file.state = 'uploaded';+ });+ } catch (error) {+ const failure = chatFailure(error);+ runInAction(() => {+ file.state = 'refused';+ file.error = failure.message;+ });+ if (failure.kind === 'not-a-member') runInAction(() => this.revoke());+ }+ })+ );+ if (!this.find(requestId)) return;+ const refused = send.files.filter((file) => file.state === 'refused');+ if (refused.length) {+ runInAction(() => {+ send.state = 'failed';+ send.error =+ refused.length === 1+ ? `${refused[0]!.file.name} could not be attached: ${refused[0]!.error}`+ : `${refused.length} files could not be attached.`;+ });+ return;+ }+ try {+ runInAction(() => {+ send.posted = true;+ });+ const messages = await this.api.send(this.roomId, {+ requestId,+ body: send.body,+ threadRootId: send.threadRootId,+ uploadIds: send.files.map((file) => file.uploadId),+ });+ runInAction(() => {+ for (const message of messages) this.apply(message);+ this.discard(requestId);+ });+ } catch (error) {+ const failure = chatFailure(error);+ runInAction(() => {+ if (failure.kind === 'not-a-member') {+ this.revoke();+ return;+ }+ send.state = failure.kind === 'request-reused' ? 'conflict' : 'failed';+ send.error = failure.message;+ send.uncertain = failure.uncertain;+ });+ }+ }+}++/**+ * The timelines of every chat opened since the server's feed was last reset,+ * by server and room: they, and the sends in them, outlive the view showing+ * them.+ */+export class ChatTimelines {+ private readonly timelines = new Map<string, ChatTimeline>();++ constructor(private readonly api: (serverId: string) => TimelineApi) {}++ get(serverId: string, roomId: string): ChatTimeline {+ const key = `${serverId}\u0000${roomId}`;+ let timeline = this.timelines.get(key);+ if (!timeline) {+ timeline = new ChatTimeline(roomId, this.api(serverId));+ this.timelines.set(key, timeline);+ }+ return timeline;+ }++ peek(serverId: string, roomId: string): ChatTimeline | undefined {+ return this.timelines.get(`${serverId}\u0000${roomId}`);+ }++ /** Load again each of the server's timelines whose last load failed. */+ reloadFailed(serverId: string): void {+ for (const [key, timeline] of this.timelines)+ if (key.startsWith(`${serverId}\u0000`) && timeline.loadError) void timeline.load();+ }++ /** Forget everything held for a server: signed out, or the tenant changed. */+ dropServer(serverId: string): void {+ for (const key of [...this.timelines.keys()])+ if (key.startsWith(`${serverId}\u0000`)) this.timelines.delete(key);+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-titler.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-titler.tsnew file mode 100644index 000000000..3fc46b94a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-titler.ts@@ -0,0 +1,42 @@+import type { ChatSummary } from '@shared/core/chats/chats';++export type ChatTitlerDeps = {+ title: (message: string) => Promise<string>;+ rename: (serverId: string, roomId: string, name: string) => Promise<void>;+ chat: (roomId: string) => ChatSummary | undefined;+ add: (serverId: string, chat: ChatSummary) => void;+ warn: (message: string, context: Record<string, unknown>) => void;+};++/**+ * Names a direct chat created here without a name from its first message.+ * A failed title leaves the default name, with a warning in the log.+ */+export class ChatTitler {+ // shortcut: held in memory, so a reload before the first message keeps the default name; persist it if that matters.+ private readonly untitled = new Set<string>();++ constructor(private readonly deps: ChatTitlerDeps) {}++ created(chat: ChatSummary, named: boolean): void {+ if (!named && chat.channelType === 'direct') this.untitled.add(chat.roomId);+ }++ async sent(serverId: string, roomId: string, body: string): Promise<void> {+ if (!body.trim() || !this.untitled.delete(roomId)) return;+ const before = this.deps.chat(roomId)?.name;+ try {+ const title = await this.deps.title(body);+ const chat = this.deps.chat(roomId);+ // Renamed by someone while the title was being written: theirs wins.+ if (!chat || chat.name !== before || chat.name === title) return;+ await this.deps.rename(serverId, roomId, title);+ this.deps.add(serverId, { ...chat, name: title });+ } catch (error) {+ this.deps.warn('Could not name the chat from its first message; it keeps its default name.', {+ roomId,+ error: String(error),+ });+ }+ }+}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.tsnew file mode 100644index 000000000..6b9114436--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.test.ts@@ -0,0 +1,50 @@+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.tsnew file mode 100644index 000000000..07598517f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-warmer.ts@@ -0,0 +1,29 @@+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.tsnew file mode 100644index 000000000..4455e7797--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts@@ -0,0 +1,247 @@+import { makeAutoObservable, reaction, runInAction } from 'mobx';+import { failureText } from '@renderer/lib/errors/describe-failure';+import {+ chatMessageChannel,+ chatRemovedChannel,+ chatResetChannel,+ chatStreamStateChannel,+ chatSummaryChannel,+} from '@shared/core/chats/chatEvents';+import type {+ ChatMessage,+ ChatRemovalReason,+ ChatStreamState,+ ChatSummary,+} from '@shared/core/chats/chats';+import { ChatTimelines, type TimelineApi } from './chat-timeline-store';++/**+ * The signed-in person's chats on the server the window is scoped to, kept+ * live by the main process's feed, and the timelines of the chats opened.+ *+ * A reset (sign-out, tenant switch) drops everything held for the server; a+ * removal for lost access drops the room's messages and marks it lost, so an+ * open chat can say so instead of quietly emptying. A room merely unlisted+ * (still a member, e.g. no agents left) only leaves the list: an open chat+ * keeps reading and posting, and catches up if the room is listed again.+ */++export type ChatsApi = {+ connect: (serverId: string) => Promise<{ state: ChatStreamState; detail: string | null }>;+ disconnect: (serverId: string) => Promise<void>;+ list: (serverId: string) => Promise<ChatSummary[]>;+ identity: (serverId: string) => Promise<{ userId: string; tenantId: string | null }>;+ timeline: (serverId: string) => TimelineApi;+};++export type ChatsEvents = {+ onMessage: (cb: (data: { serverId: string; message: ChatMessage }) => void) => () => void;+ onSummary: (cb: (data: { serverId: string; chat: ChatSummary }) => void) => () => void;+ onRemoved: (+ cb: (data: { serverId: string; roomId: string; reason: ChatRemovalReason }) => void+ ) => () => void;+ onState: (+ cb: (data: { serverId: string; state: ChatStreamState; detail: string | null }) => void+ ) => () => void;+ onReset: (cb: (data: { serverId: string }) => void) => () => void;+};++export class ChatsStore {+ serverId: string | null = null;+ userId: string | null = null;+ tenantId: string | null = null;+ chats = new Map<string, ChatSummary>();+ /** Rooms the person lost access to since the feed started. */+ removed = new Set<string>();+ /** Rooms off the list while the person is still a member. */+ unlisted = new Set<string>();+ streamState: ChatStreamState = 'offline';+ streamDetail: string | null = null;+ listError: string | null = null;+ readonly timelines: ChatTimelines;++ constructor(+ private readonly api: ChatsApi,+ events: ChatsEvents+ ) {+ this.timelines = new ChatTimelines(api.timeline);+ makeAutoObservable<ChatsStore, 'api'>(this, { api: false, timelines: false });+ events.onSummary(({ serverId, chat }) => {+ if (serverId === this.serverId) this.upsert(chat);+ });+ events.onMessage(({ serverId, message }) => this.message(serverId, message));+ events.onRemoved(({ serverId, roomId, reason }) => {+ if (serverId === this.serverId) this.remove(roomId, reason);+ });+ events.onState(({ serverId, state, detail }) => {+ if (serverId !== this.serverId) return;+ runInAction(() => {+ this.streamState = state;+ this.streamDetail = detail;+ });+ // A first load that failed while the server was down is not retried by anything else.+ if (state !== 'live') return;+ if (this.userId === null || this.listError) void this.connect(serverId);+ this.timelines.reloadFailed(serverId);+ });+ events.onReset(({ serverId }) => this.reset(serverId));+ }++ /** Follow the server the window is scoped to; `key` changes with the workspace. */+ follow(read: () => { serverId: string | null; key: string | null }): () => void {+ return reaction(read, ({ serverId }) => void this.connect(serverId), {+ fireImmediately: true,+ equals: (a, b) => a.serverId === b.serverId && a.key === b.key,+ });+ }++ async connect(serverId: string | null): Promise<void> {+ if (serverId !== this.serverId) {+ if (this.serverId) void this.api.disconnect(this.serverId);+ runInAction(() => {+ this.serverId = serverId;+ this.chats = new Map();+ this.removed = new Set();+ this.unlisted = new Set();+ this.userId = null;+ this.tenantId = null;+ this.listError = null;+ this.streamState = serverId ? 'connecting' : 'offline';+ this.streamDetail = null;+ });+ }+ if (!serverId) return;+ try {+ const [state, identity, chats] = await Promise.all([+ this.api.connect(serverId),+ this.api.identity(serverId),+ this.api.list(serverId),+ ]);+ if (serverId !== this.serverId) {+ void this.api.disconnect(serverId);+ return;+ }+ runInAction(() => {+ this.streamState = state.state;+ this.streamDetail = state.detail;+ this.userId = identity.userId;+ this.tenantId = identity.tenantId;+ this.listError = null;+ for (const chat of chats) this.upsert(chat);+ });+ } catch (error) {+ if (serverId !== this.serverId) return;+ runInAction(() => {+ this.listError = failureText(error, 'Your chats could not be listed.');+ });+ }+ }++ upsert(chat: ChatSummary): void {+ this.chats.set(chat.roomId, chat);+ this.removed.delete(chat.roomId);+ const timeline = this.serverId ? this.timelines.peek(this.serverId, chat.roomId) : undefined;+ timeline?.restore();+ // The feed did not follow the room while it was off the list.+ if (this.unlisted.delete(chat.roomId) && timeline?.loaded) void timeline.load();+ }++ /** A chat the person made or was let into from here, ahead of the feed. */+ add(serverId: string, chat: ChatSummary): void {+ 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);+ }++ message(serverId: string, message: ChatMessage): void {+ if (serverId !== this.serverId) return;+ this.timelines.peek(serverId, message.roomId)?.apply(message);+ const chat = this.chats.get(message.roomId);+ // The feed follows hidden chats too; a message in one is what brings it back.+ if (!chat && !this.removed.has(message.roomId) && !this.unlisted.has(message.roomId))+ void this.relist(serverId);+ if (chat && (chat.lastMessage === null || chat.lastMessage.seq < message.seq))+ this.chats.set(message.roomId, {+ ...chat,+ lastMessage: {+ seq: message.seq,+ sentAt: message.sentAt,+ preview: message.body.slice(0, 200),+ senderName: message.sender.name,+ },+ });+ }++ private relisting = false;++ private async relist(serverId: string): Promise<void> {+ if (this.relisting) return;+ this.relisting = true;+ try {+ const chats = await this.api.list(serverId);+ if (serverId !== this.serverId) return;+ runInAction(() => {+ for (const chat of chats) if (!this.chats.has(chat.roomId)) this.upsert(chat);+ });+ } catch (error) {+ if (serverId !== this.serverId) return;+ runInAction(() => {+ this.listError = failureText(error, 'Your chats could not be listed.');+ });+ } finally {+ this.relisting = false;+ }+ }++ remove(roomId: string, reason: ChatRemovalReason): void {+ this.chats.delete(roomId);+ if (reason === 'unlisted') {+ this.unlisted.add(roomId);+ return;+ }+ this.unlisted.delete(roomId);+ this.removed.add(roomId);+ if (this.serverId) {+ const timeline = this.timelines.peek(this.serverId, roomId);+ if (timeline) timeline.revoke();+ }+ }++ reset(serverId: string): void {+ this.timelines.dropServer(serverId);+ if (serverId !== this.serverId) return;+ this.chats = new Map();+ this.removed = new Set();+ this.unlisted = new Set();+ this.userId = null;+ this.tenantId = null;+ void this.connect(serverId);+ }++ /** The chats an agent is in, newest activity first. */+ chatsOfAgent(agentId: string): ChatSummary[] {+ return [...this.chats.values()]+ .filter((chat) => chat.agents.some((agent) => agent.id === agentId))+ .sort((a, b) => (b.lastMessage?.sentAt ?? '').localeCompare(a.lastMessage?.sentAt ?? ''));+ }++ chat(roomId: string): ChatSummary | undefined {+ return this.chats.get(roomId);+ }+}++/** The events the store listens to, from the typed renderer event bus. */+export function chatsEventsFrom(bus: {+ on: <T>(event: { name: string; _data?: T }, cb: (data: T) => void) => () => void;+}): ChatsEvents {+ return {+ onMessage: (cb) => bus.on(chatMessageChannel, cb),+ onSummary: (cb) => bus.on(chatSummaryChannel, cb),+ onRemoved: (cb) => bus.on(chatRemovedChannel, cb),+ onState: (cb) => bus.on(chatStreamStateChannel, cb),+ onReset: (cb) => bus.on(chatResetChannel, cb),+ };+}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.tsnew file mode 100644index 000000000..b856a247b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts@@ -0,0 +1,56 @@+import { reaction } from 'mobx';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { events, rpc } from '@renderer/lib/ipc';+import { log } from '@renderer/utils/logger';+import { agentActivities } from './activities';+import { agentChatsFlag } from './agent-chats-flag';+import { ChatTitler } from './chat-titler';+import { ChatsStore, chatsEventsFrom } from './chats-store';++/** The app's chats store, following the workspace the window is scoped to. */+export const chatsStore = new ChatsStore(+ {+ connect: async (serverId) => {+ const state = await rpc.chats.connect(serverId);+ // A feed already down when this renderer (re)connects sends no change to hear.+ agentActivities.feedState(serverId, state.activity.state, state.activity.detail);+ return state;+ },+ disconnect: (serverId) => rpc.chats.disconnect(serverId),+ list: (serverId) => rpc.chats.list(serverId),+ identity: (serverId) => rpc.chats.identity(serverId),+ timeline: (serverId) => ({+ messages: (roomId, beforeSeq, limit) =>+ rpc.chats.messages({ serverId, roomId, beforeSeq, limit }),+ upload: (roomId, file) => rpc.chats.upload({ serverId, roomId, ...file }),+ send: (roomId, input) => rpc.chats.send({ serverId, roomId, ...input }),+ newId: () => crypto.randomUUID(),+ }),+ },+ chatsEventsFrom(events)+);++chatsStore.follow(() => {+ const serverId = workspacesStore.activeServerId;+ const active = workspacesStore.active;+ if (!serverId || agentChatsFlag(serverId) !== true) return { serverId: null, key: null };+ return { serverId, key: active ? `${active.id}:${active.tenantId}` : null };+});++// Server status is otherwise read again only on focus; until it is, the sidebar asks a server it thinks is down for no room names.+reaction(+ () => (chatsStore.streamState === 'live' ? chatsStore.serverId : null),+ (serverId) => {+ if (serverId && !switchServersStore.isConnected(serverId))+ void switchServersStore.refreshStatus(serverId);+ }+);++export const chatTitler = new ChatTitler({+ title: (message) => rpc.chats.title(message),+ rename: (serverId, roomId, name) => rpc.chats.rename(serverId, roomId, name),+ chat: (roomId) => chatsStore.chat(roomId),+ add: (serverId, chat) => chatsStore.add(serverId, chat),+ warn: (message, context) => log.warn(message, context),+});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.tsnew file mode 100644index 000000000..df856cdc4--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts@@ -0,0 +1,63 @@+import type { ChatSummary } from '@shared/core/chats/chats';+import { chatFailure } from './chat-errors';++export type DirectChatStarterDeps = {+ create: (input: {+ serverId: string;+ agentIds: string[];+ name: null;+ requestId: string;+ }) => Promise<ChatSummary>;+ created: (serverId: string, chat: ChatSummary) => void;+ opened: (chat: ChatSummary) => void;+ failed: (message: string) => void;+ findEmpty: (agentId: string) => ChatSummary | null;+ 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. 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.+ */+export class DirectChatStarter {+ private readonly inFlight = new Set<string>();+ private readonly retryIds = new Map<string, string>();++ constructor(private readonly deps: DirectChatStarterDeps) {}++ async start(serverId: string, agentId: string): Promise<ChatSummary | null> {+ const existing = this.deps.findEmpty(agentId);+ if (existing) {+ this.deps.opened(existing);+ return existing;+ }++ const key = `${serverId}:${agentId}`;+ if (this.inFlight.has(key)) return null;+ 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 });+ 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.`+ );+ } else {+ this.retryIds.delete(key);+ this.deps.failed(failure.message);+ }+ return null;+ } finally {+ this.inFlight.delete(key);+ }+ }+}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.tsnew file mode 100644index 000000000..fa5ba4638--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts@@ -0,0 +1,326 @@+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 }],+ canManage: false,+ ownsAgent: false,+ 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,+ ...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 }],+ 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 }],+ 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('handles multi-agent chat default name', () => {+ const chat = makeChat({+ roomId: 'room-1',+ name: 'Chat with Ada, Bob',+ agents: [+ { id: 'agent-1', name: 'ada', displayName: 'Ada', iconUrl: null, provider: null },+ { id: 'agent-2', name: 'bob', displayName: 'Bob', iconUrl: null, provider: null },+ ],+ 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);+ });+});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.tsnew file mode 100644index 000000000..10fd1ee05--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.ts@@ -0,0 +1,53 @@+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.+ */+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) => 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 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;+ }++ private defaultChatName(chat: ChatSummary): string {+ const agentNames = chat.agents.map((agent) => agent.displayName || agent.name).join(', ');+ return `Chat with ${agentNames}`;+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/tool-presentation.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/tool-presentation.tsnew file mode 100644index 000000000..50e72ca84--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/tool-presentation.ts@@ -0,0 +1,366 @@+import type { ToolDetail } from '@shared/core/sessions/reasoning';++/**+ * How a tool call reads in a chat's work log: what kind of thing it did (for+ * its icon), a short human label ("Ran `ls -la`", "Read src/store.ts") and+ * what opening it shows.+ *+ * The activity row carries only a title and text. What the call was given and gave+ * back comes from the session host's tool details when it has them (a local+ * or SSH host that knows them); without them the row is labelled from the+ * title alone and has nothing to open.+ */++export type ToolKind =+ | 'shell'+ | 'read'+ | 'edit'+ | 'search'+ | 'web'+ | 'agent'+ | 'todo'+ | 'switch'+ | 'mcp'+ | 'other';++export type DiffLine = { sign: '+' | '-' | ' '; text: string };++export type ToolDetailView =+ | { kind: 'command'; command: string; output: string | null; exitCode: number | null }+ | { kind: 'read'; path: string | null; output: string | null }+ | { kind: 'diff'; path: string | null; lines: DiffLine[] }+ | { kind: 'search'; query: string | null; scope: string | null; output: string | null }+ | { kind: 'web'; target: string | null; output: string | null }+ | { kind: 'generic'; input: string | null; output: string | null };++export type ToolPresentation = {+ kind: ToolKind;+ /** The verb ("Ran", "Read") and what it acted on, which is set in code when it is code. */+ verb: string;+ subject: string | null;+ code: boolean;+ /** Null when there is nothing to show beyond the label: the row does not open. */+ details: ToolDetailView | null;+ truncated: boolean;+};++const SHELL = new Set(['Bash', 'bash', 'BashOutput', 'KillShell', 'KillBash', 'shell']);+const READ = new Set(['Read', 'read', 'NotebookRead', 'view']);+const EDIT = new Set([+ 'Edit',+ 'MultiEdit',+ 'Write',+ 'NotebookEdit',+ 'edit',+ 'write',+ 'patch',+ 'apply_patch',+ 'multiedit',+]);+const SEARCH = new Set(['Grep', 'Glob', 'LS', 'grep', 'glob', 'list', 'codesearch']);+const WEB = new Set(['WebSearch', 'WebFetch', 'websearch', 'webfetch', 'web_search']);+const AGENT = new Set(['Task', 'Agent', 'task']);+const TODO = new Set(['TodoWrite', 'TodoRead', 'todowrite', 'todoread']);++/** Tool names the Switch MCP server's tools carry, as Claude Code reports them. */+export const SWITCH_TOOL_PREFIX = 'mcp__switch__';++const SWITCH_LABELS: Record<string, string> = {+ connect_to_room: 'Connected to the room',+ read_context: 'Read the room',+ post_message: 'Posted to the room',+ send_targeted_message: 'Sent a message in the room',+ send_attachment: 'Sent an attachment',+ download_attachment: 'Downloaded an attachment',+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function field(input: Record<string, unknown>, ...keys: string[]): string | null {+ for (const key of keys) {+ const value = input[key];+ if (typeof value === 'string' && value.trim().length > 0) return value;+ }+ return null;+}++function kindOf(name: string, type: string | null): ToolKind {+ if (name.startsWith(SWITCH_TOOL_PREFIX)) return 'switch';+ if (SHELL.has(name) || type === 'command_execution') return 'shell';+ if (READ.has(name)) return 'read';+ if (EDIT.has(name) || type === 'file_change') return 'edit';+ if (SEARCH.has(name)) return 'search';+ if (WEB.has(name) || type === 'web_search') return 'web';+ if (AGENT.has(name) || type === 'subagent') return 'agent';+ if (TODO.has(name)) return 'todo';+ if (name.startsWith('mcp__') || type === 'mcp_tool_call') return 'mcp';+ return 'other';+}++/** A tool name as Claude reports an MCP one (`mcp__server__tool`), split for reading. */+function mcpParts(name: string): { server: string; tool: string } | null {+ const match = /^mcp__(.+?)__(.+)$/.exec(name);+ return match ? { server: match[1]!, tool: match[2]! } : null;+}++const humanize = (name: string) => name.replace(/[_-]+/g, ' ').trim();++function lines(text: string): string[] {+ return text.replace(/\n$/, '').split('\n');+}++function editDiff(name: string, input: Record<string, unknown>): DiffLine[] {+ const pairs: { before: string; after: string }[] = [];+ const edits = Array.isArray(input.edits) ? input.edits : null;+ if (edits) {+ for (const edit of edits)+ if (isRecord(edit))+ pairs.push({+ before: field(edit, 'old_string', 'oldString') ?? '',+ after: field(edit, 'new_string', 'newString') ?? '',+ });+ } else if (+ field(input, 'old_string', 'oldString') !== null ||+ field(input, 'new_string', 'newString') !== null+ ) {+ pairs.push({+ before: field(input, 'old_string', 'oldString') ?? '',+ after: field(input, 'new_string', 'newString') ?? '',+ });+ } else if (name === 'Write' || name === 'write' || field(input, 'content') !== null) {+ const content = field(input, 'content', 'new_source');+ if (content) pairs.push({ before: '', after: content });+ }+ return pairs.flatMap(({ before, after }, index) => [+ ...(index > 0 ? [{ sign: ' ' as const, text: '…' }] : []),+ ...(before ? lines(before).map((text) => ({ sign: '-' as const, text })) : []),+ ...(after ? lines(after).map((text) => ({ sign: '+' as const, text })) : []),+ ]);+}++/** A unified diff's lines, coloured by their first character; headers read as context. */+function unifiedDiff(text: string): DiffLine[] {+ return lines(text).map((line) => {+ if (line.startsWith('+') && !line.startsWith('+++')) return { sign: '+', text: line.slice(1) };+ if (line.startsWith('-') && !line.startsWith('---')) return { sign: '-', text: line.slice(1) };+ return { sign: ' ', text: line };+ });+}++function pretty(input: unknown): string | null {+ if (input === null || input === undefined) return null;+ if (typeof input === 'string') return input.trim() ? input : null;+ if (isRecord(input) && Object.keys(input).length === 0) return null;+ return JSON.stringify(input, null, 2);+}++function nonEmpty(text: string | null | undefined): string | null {+ return text && text.trim().length > 0 ? text : null;+}++/** The title's tool name and subject, for a row with no details (`Edit /a.ts`, `Read`). */+function fromTitle(title: string): { name: string; subject: string | null } {+ const match = /^([A-Za-z]+) (\S.*)$/.exec(title);+ if (match && (EDIT.has(match[1]!) || READ.has(match[1]!)))+ return { name: match[1]!, subject: match[2]! };+ return { name: title, subject: null };+}++/** The verb while running and once done, and the whole label when there is no subject. */+type Verbs = { running: string; done: string; bareRunning: string; bareDone: string };+const VERBS: Record<Exclude<ToolKind, 'switch' | 'mcp' | 'other'>, Verbs> = {+ shell: {+ running: 'Running',+ done: 'Ran',+ bareRunning: 'Running a command',+ bareDone: 'Ran a command',+ },+ read: {+ running: 'Reading',+ done: 'Read',+ bareRunning: 'Reading a file',+ bareDone: 'Read a file',+ },+ edit: {+ running: 'Editing',+ done: 'Edited',+ bareRunning: 'Editing a file',+ bareDone: 'Edited a file',+ },+ search: {+ running: 'Searching for',+ done: 'Searched for',+ bareRunning: 'Searching',+ bareDone: 'Searched',+ },+ web: {+ running: 'Searching the web for',+ done: 'Searched the web for',+ bareRunning: 'Searching the web',+ bareDone: 'Searched the web',+ },+ agent: {+ running: 'Running agent:',+ done: 'Ran agent:',+ bareRunning: 'Running an agent',+ bareDone: 'Ran an agent',+ },+ todo: {+ running: 'Updating the to-do list',+ done: 'Updated the to-do list',+ bareRunning: 'Updating the to-do list',+ bareDone: 'Updated the to-do list',+ },+};++/** What a tool row is drawn from: an activity row's status, title and text. */+export type ToolItem = { status: string; title: string; text: string };++export function presentTool(item: ToolItem, detail: ToolDetail | null): ToolPresentation {+ const running = item.status === 'in-progress';+ const titled = fromTitle(item.title);+ const name = detail?.toolName ?? titled.name;+ const kind = kindOf(name, detail?.type ?? null);+ const input = isRecord(detail?.input) ? detail.input : {};+ const output = nonEmpty(detail?.output) ?? nonEmpty(item.text);+ const truncated = detail?.truncated ?? false;+ const base = { kind, truncated };+ const labelled = (verbs: Verbs, subject: string | null, code: boolean) =>+ subject+ ? { verb: running ? verbs.running : verbs.done, subject, code }+ : { verb: running ? verbs.bareRunning : verbs.bareDone, subject: null, code: false };++ switch (kind) {+ case 'shell': {+ const command = field(input, 'command') ?? item.title;+ return {+ ...base,+ ...labelled(VERBS.shell, command, true),+ details: detail+ ? { kind: 'command', command, output, exitCode: detail.exitCode }+ : output+ ? { kind: 'command', command, output, exitCode: null }+ : null,+ };+ }+ case 'read': {+ const path = field(input, 'file_path', 'filePath', 'path', 'notebook_path') ?? titled.subject;+ return {+ ...base,+ ...labelled(VERBS.read, path, false),+ details: output ? { kind: 'read', path, output } : null,+ };+ }+ case 'edit': {+ const path =+ field(input, 'file_path', 'filePath', 'path', 'notebook_path') ??+ titled.subject ??+ (detail?.type === 'file_change' ? item.title : null);+ const diff = editDiff(name, input);+ const lines = diff.length > 0 ? diff : output ? unifiedDiff(output) : [];+ const created = name === 'Write' || name === 'write';+ return {+ ...base,+ ...labelled(+ created ? { ...VERBS.edit, running: 'Writing', done: 'Wrote' } : VERBS.edit,+ path,+ false+ ),+ details: lines.length > 0 ? { kind: 'diff', path, lines } : null,+ };+ }+ case 'search': {+ const query = field(input, 'pattern', 'query', 'path');+ const scope = field(input, 'path', 'glob', 'include');+ return {+ ...base,+ ...labelled(VERBS.search, query, true),+ details:+ query || output+ ? { kind: 'search', query, scope: scope === query ? null : scope, output }+ : null,+ };+ }+ case 'web': {+ const url = field(input, 'url');+ const target = field(input, 'query') ?? url ?? (item.title !== name ? item.title : null);+ return {+ ...base,+ ...labelled(+ url ? { ...VERBS.web, running: 'Fetching', done: 'Fetched' } : VERBS.web,+ target,+ false+ ),+ details: detail && (target || output) ? { kind: 'web', target, output } : null,+ };+ }+ case 'agent':+ case 'todo': {+ const subject =+ kind === 'agent' ? (field(input, 'description') ?? (item.title || null)) : null;+ const shown = pretty(detail?.input);+ return {+ ...base,+ ...labelled(VERBS[kind], subject, false),+ details: shown || output ? { kind: 'generic', input: shown, output } : null,+ };+ }+ case 'switch':+ case 'mcp':+ case 'other': {+ const mcp = mcpParts(name);+ const label =+ kind === 'switch'+ ? (SWITCH_LABELS[mcp?.tool ?? ''] ?? `Switch: ${humanize(mcp?.tool ?? name)}`)+ : mcp+ ? `${humanize(mcp.server)}: ${humanize(mcp.tool)}`+ : item.title || name;+ const shown = pretty(detail?.input);+ return {+ ...base,+ verb: label,+ subject: null,+ code: false,+ details: shown || output ? { kind: 'generic', input: shown, output } : null,+ };+ }+ }+}++/** A path's last few segments, which are the part a reader looks for. */+export function shortPath(path: string): string {+ const parts = path.split('/').filter(Boolean);+ return parts.length > 3 ? `…/${parts.slice(-3).join('/')}` : path;+}++const COUNTED: Record<ToolKind, (count: number) => string> = {+ shell: (n) => `Ran ${n} ${n === 1 ? 'command' : 'commands'}`,+ read: (n) => `Read ${n} ${n === 1 ? 'file' : 'files'}`,+ edit: (n) => `Edited ${n} ${n === 1 ? 'file' : 'files'}`,+ search: (n) => `Searched ${n} ${n === 1 ? 'time' : 'times'}`,+ web: (n) => `Searched the web ${n} ${n === 1 ? 'time' : 'times'}`,+ agent: (n) => `Ran ${n} ${n === 1 ? 'agent' : 'agents'}`,+ todo: (n) => `Updated the to-do list${n === 1 ? '' : ` ${n} times`}`,+ switch: (n) => `Took ${n} Switch ${n === 1 ? 'action' : 'actions'}`,+ mcp: (n) => `Called ${n} ${n === 1 ? 'tool' : 'tools'}`,+ other: (n) => `Used ${n} ${n === 1 ? 'tool' : 'tools'}`,+};++/**+ * One line for a run of tool calls, by kind in the order each first appears:+ * "Ran 2 commands, read 3 files and edited 1 file". The kind is the icon's+ * when every call shares it, and null when they are mixed.+ */+export function summarizeTools(kinds: ToolKind[]): { label: string; kind: ToolKind | null } {+ const counts = new Map<ToolKind, number>();+ for (const kind of kinds) counts.set(kind, (counts.get(kind) ?? 0) + 1);+ const parts = [...counts].map(([kind, count], index) => {+ const text = COUNTED[kind](count);+ return index === 0 ? text : text.charAt(0).toLowerCase() + text.slice(1);+ });+ const label =+ parts.length < 2 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`;+ return { label, kind: counts.size === 1 ? kinds[0]! : null };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/attachment.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/attachment.tsxnew file mode 100644index 000000000..f6a297b6c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/attachment.tsx@@ -0,0 +1,195 @@+import { mergeProps } from '@base-ui/react/merge-props';+import { useRender } from '@base-ui/react/use-render';+import { cva, type VariantProps } from 'class-variance-authority';+import type * as React from 'react';+import { Button } from '@renderer/lib/ui/button';+import { cn } from '@renderer/utils/utils';++export type AttachmentState = 'idle' | 'uploading' | 'processing' | 'error' | 'done';++const attachmentVariants = cva(+ 'group/attachment relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-xl border border-border bg-background-1 text-foreground transition-colors focus-within:border-border-primary has-[>a,>button]:hover:bg-background-2 data-[state=error]:border-border-destructive data-[state=idle]:border-dashed',+ {+ variants: {+ size: {+ default:+ 'gap-2 text-sm has-data-[slot=attachment-content]:px-2.5 has-data-[slot=attachment-content]:py-2 has-data-[slot=attachment-media]:p-2',+ sm: 'gap-2.5 text-xs has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5',+ xs: 'gap-1.5 rounded-lg text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1',+ },+ orientation: {+ horizontal: 'min-w-40 items-center',+ vertical: 'w-24 flex-col has-data-[slot=attachment-content]:w-30',+ },+ },+ }+);++function Attachment({+ className,+ state = 'done',+ size = 'default',+ orientation = 'horizontal',+ ...props+}: React.ComponentProps<'div'> &+ VariantProps<typeof attachmentVariants> & {+ state?: AttachmentState;+ }) {+ return (+ <div+ data-slot="attachment"+ data-state={state}+ data-size={size}+ data-orientation={orientation}+ className={cn(attachmentVariants({ size, orientation }), className)}+ {...props}+ />+ );+}++const attachmentMediaVariants = cva(+ "relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-background-2 text-foreground group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-md group-data-[state=error]/attachment:bg-background-destructive group-data-[state=error]/attachment:text-foreground-destructive [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5",+ {+ variants: {+ variant: {+ icon: '',+ image:+ 'opacity-60 group-data-[state=done]/attachment:opacity-100 group-data-[state=idle]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover',+ },+ },+ defaultVariants: {+ variant: 'icon',+ },+ }+);++function AttachmentMedia({+ className,+ variant = 'icon',+ ...props+}: React.ComponentProps<'div'> & VariantProps<typeof attachmentMediaVariants>) {+ return (+ <div+ data-slot="attachment-media"+ data-variant={variant}+ className={cn(attachmentMediaVariants({ variant }), className)}+ {...props}+ />+ );+}++function AttachmentContent({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="attachment-content"+ className={cn(+ 'max-w-full min-w-0 flex-1 leading-tight group-data-[orientation=vertical]/attachment:px-1',+ className+ )}+ {...props}+ />+ );+}++function AttachmentTitle({ className, ...props }: React.ComponentProps<'span'>) {+ return (+ <span+ data-slot="attachment-title"+ className={cn(+ 'block max-w-full min-w-0 truncate font-medium group-data-[state=processing]/attachment:text-shimmer group-data-[state=uploading]/attachment:text-shimmer',+ className+ )}+ {...props}+ />+ );+}++function AttachmentDescription({ className, ...props }: React.ComponentProps<'span'>) {+ return (+ <span+ data-slot="attachment-description"+ className={cn(+ 'mt-0.5 block max-w-full min-w-0 truncate text-xs text-foreground-muted group-data-[state=error]/attachment:text-foreground-destructive',+ className+ )}+ {...props}+ />+ );+}++function AttachmentActions({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="attachment-actions"+ className={cn(+ 'relative z-20 flex shrink-0 items-center group-data-[orientation=vertical]/attachment:absolute group-data-[orientation=vertical]/attachment:top-3 group-data-[orientation=vertical]/attachment:right-3 group-data-[orientation=vertical]/attachment:gap-1',+ className+ )}+ {...props}+ />+ );+}++function AttachmentAction({+ className,+ variant,+ size = 'icon-xs',+ ...props+}: React.ComponentProps<typeof Button>) {+ return (+ <Button+ data-slot="attachment-action"+ variant={variant ?? 'ghost'}+ size={size}+ className={cn(className)}+ {...props}+ />+ );+}++function AttachmentTrigger({+ className,+ render,+ type,+ ...props+}: useRender.ComponentProps<'button'>) {+ return useRender({+ defaultTagName: 'button',+ props: mergeProps<'button'>(+ {+ type: render ? type : (type ?? 'button'),+ className: cn('absolute inset-0 z-10 outline-none', className),+ },+ props+ ),+ render,+ state: {+ slot: 'attachment-trigger',+ },+ });+}++function AttachmentGroup({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="attachment-group"+ className={cn(+ 'flex min-w-0 snap-x snap-mandatory scroll-px-1 gap-3 overflow-x-auto overscroll-x-contain py-1 [scrollbar-width:none] *:data-[slot=attachment]:flex-none *:data-[slot=attachment]:snap-start',+ className+ )}+ {...props}+ />+ );+}++export {+ Attachment,+ AttachmentGroup,+ AttachmentMedia,+ AttachmentContent,+ AttachmentTitle,+ AttachmentDescription,+ AttachmentActions,+ AttachmentAction,+ AttachmentTrigger,+};diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/chat-markdown.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/chat-markdown.tsxnew file mode 100644index 000000000..c3785a951--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/chat-markdown.tsx@@ -0,0 +1,125 @@+import type * as React from 'react';+import { defaultRehypePlugins, Streamdown, type Components, type ExtraProps } from 'streamdown';+import type { PluggableList } from 'unified';+import { confirmOpenExternalLink } from '@renderer/lib/open-external-link';+import { cn } from '@renderer/utils/utils';+import { CodeBlock } from './code-block';++const HTTP_URL_PATTERN = /^https?:\/\//i;++/**+ * Streamdown's defaults minus `rehype-raw`: chat text is written by agents and+ * other people, so HTML in it is dropped rather than parsed (`skipHtml` below+ * removes the raw nodes; without `rehype-raw` nothing would turn them into+ * elements anyway). Sanitize and harden stay.+ */+const REHYPE_PLUGINS: PluggableList = [defaultRehypePlugins.sanitize, defaultRehypePlugins.harden];++type WithChildren = { children?: React.ReactNode } & ExtraProps;++function ChatLink({ href, children }: React.ComponentProps<'a'> & ExtraProps) {+ const isHttp = typeof href === 'string' && HTTP_URL_PATTERN.test(href);+ return (+ <a+ href={href}+ className="text-foreground underline decoration-foreground-passive underline-offset-2 hover:decoration-foreground"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(event) => {+ // Never let a link navigate the app window; only http(s) links leave the+ // app, and only through the confirm dialog.+ event.preventDefault();+ if (isHttp) confirmOpenExternalLink(href);+ }}+ >+ {children}+ </a>+ );+}++function ChatCode({+ node: _node,+ children,+ className,+ ...props+}: React.ComponentProps<'code'> & ExtraProps) {+ if ('data-block' in props) {+ const language = /language-([\w+-]+)/.exec(className ?? '')?.[1];+ return <CodeBlock code={String(children).replace(/\n$/, '')} language={language} />;+ }+ return (+ <code className="rounded bg-background-2 px-1 py-0.5 font-mono text-[0.92em]">{children}</code>+ );+}++const COMPONENTS: Components = {+ a: ChatLink,+ code: ChatCode,+ p: ({ children }: WithChildren) => <p className="my-2 leading-relaxed">{children}</p>,+ h1: ({ children }: WithChildren) => (+ <h1 className="mt-4 mb-2 text-base font-semibold first:mt-0">{children}</h1>+ ),+ h2: ({ children }: WithChildren) => (+ <h2 className="mt-4 mb-2 text-sm font-semibold first:mt-0">{children}</h2>+ ),+ h3: ({ children }: WithChildren) => (+ <h3 className="mt-3 mb-1 text-sm font-semibold first:mt-0">{children}</h3>+ ),+ h4: ({ children }: WithChildren) => (+ <h4 className="mt-3 mb-1 text-sm font-medium first:mt-0">{children}</h4>+ ),+ h5: ({ children }: WithChildren) => (+ <h5 className="mt-2 mb-1 text-xs font-medium first:mt-0">{children}</h5>+ ),+ h6: ({ children }: WithChildren) => (+ <h6 className="mt-2 mb-1 text-xs font-medium text-foreground-muted first:mt-0">{children}</h6>+ ),+ ul: ({ children }: WithChildren) => (+ <ul className="my-2 ml-5 list-disc space-y-1 marker:text-foreground-passive">{children}</ul>+ ),+ ol: ({ children }: WithChildren) => (+ <ol className="my-2 ml-5 list-decimal space-y-1 marker:text-foreground-passive">{children}</ol>+ ),+ li: ({ children }: WithChildren) => <li className="leading-relaxed">{children}</li>,+ blockquote: ({ children }: WithChildren) => (+ <blockquote className="my-2 border-l-2 border-border pl-3 text-foreground-muted">+ {children}+ </blockquote>+ ),+ table: ({ children }: WithChildren) => (+ <div className="my-2 overflow-x-auto rounded-md border border-border">+ <table className="w-full min-w-max border-collapse text-left text-xs">{children}</table>+ </div>+ ),+ thead: ({ children }: WithChildren) => (+ <thead className="border-b border-border bg-background-2">{children}</thead>+ ),+ th: ({ children }: WithChildren) => (+ <th className="border-r border-border px-2.5 py-1.5 font-semibold last:border-r-0">+ {children}+ </th>+ ),+ td: ({ children }: WithChildren) => (+ <td className="border-t border-r border-border px-2.5 py-1.5 align-top last:border-r-0">+ {children}+ </td>+ ),+ hr: (_props: ExtraProps) => <hr className="my-4 border-border" />,+ strong: ({ children }: WithChildren) => <strong className="font-semibold">{children}</strong>,+};++/** Markdown for chat messages, tolerant of a reply that is still streaming in. */+export function ChatMarkdown({ children, className }: { children: string; className?: string }) {+ return (+ <Streamdown+ className={cn('min-w-0 text-sm text-foreground', className)}+ components={COMPONENTS}+ rehypePlugins={REHYPE_PLUGINS}+ skipHtml+ controls={false}+ linkSafety={{ enabled: false }}+ >+ {children}+ </Streamdown>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/code-block.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/code-block.tsxnew file mode 100644index 000000000..3eb239db1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/code-block.tsx@@ -0,0 +1,93 @@+import { CheckIcon, CopyIcon } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';+import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';+import { toast } from 'sonner';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { useTheme } from '@renderer/lib/hooks/useTheme';+import { Button } from '@renderer/lib/ui/button';+import { cn } from '@renderer/utils/utils';++const COPIED_RESET_MS = 1600;++/**+ * A fenced code block with a copy button. Highlighting reuses the Prism build the+ * markdown renderer already ships rather than a second highlighter.+ */+export function CodeBlock({+ code,+ language,+ className,+}: {+ code: string;+ language?: string;+ className?: string;+}) {+ const { effectiveTheme } = useTheme();+ const isDark = effectiveTheme === 'emdark';++ return (+ <div+ data-slot="code-block"+ className={cn(+ 'group/code-block relative w-full overflow-hidden rounded-md border border-border bg-background-1 text-foreground',+ className+ )}+ >+ <div className="flex h-8 items-center justify-between border-b border-border pr-1 pl-3">+ <span className="font-mono text-tiny text-foreground-passive">{language || 'text'}</span>+ <CodeBlockCopyButton code={code} />+ </div>+ <SyntaxHighlighter+ style={isDark ? oneDark : oneLight}+ language={language || 'text'}+ PreTag="div"+ customStyle={{ margin: 0, background: 'transparent', padding: '0.75rem' }}+ codeTagProps={{ className: 'font-mono text-xs' }}+ >+ {code}+ </SyntaxHighlighter>+ </div>+ );+}++function CodeBlockCopyButton({ code }: { code: string }) {+ const [copied, setCopied] = useState(false);+ const resetRef = useRef<number | null>(null);++ useEffect(+ () => () => {+ if (resetRef.current !== null) window.clearTimeout(resetRef.current);+ },+ []+ );++ const copy = async () => {+ try {+ await navigator.clipboard.writeText(code);+ } catch (error) {+ const { headline, detail } = describeFailure(error, 'Could not copy the code');+ toast.error(headline, { description: detail ?? undefined });+ return;+ }+ setCopied(true);+ if (resetRef.current !== null) window.clearTimeout(resetRef.current);+ resetRef.current = window.setTimeout(() => {+ setCopied(false);+ resetRef.current = null;+ }, COPIED_RESET_MS);+ };++ const Icon = copied ? CheckIcon : CopyIcon;+ return (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={copied ? 'Copied' : 'Copy code'}+ title={copied ? 'Copied' : 'Copy code'}+ onClick={() => void copy()}+ >+ <Icon />+ </Button>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/follow-bottom.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/follow-bottom.tsnew file mode 100644index 000000000..25dfea8e9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/follow-bottom.ts@@ -0,0 +1,38 @@+/** The scroll geometry of a viewport, as read off the element. */+export type ScrollMetrics = {+ scrollTop: number;+ scrollHeight: number;+ clientHeight: number;+};++/**+ * How close to the end still counts as "at the bottom". Not zero: fractional+ * device pixels leave `scrollTop` a hair short of the maximum, and a reader who+ * nudges the wheel by a line has not asked to stop following.+ */+export const FOLLOW_BOTTOM_THRESHOLD_PX = 32;++export function distanceFromBottom({ scrollTop, scrollHeight, clientHeight }: ScrollMetrics) {+ return Math.max(0, scrollHeight - clientHeight - scrollTop);+}++/** Whether the viewport sits at the end, within `threshold`. */+export function isAtBottom(metrics: ScrollMetrics, threshold: number) {+ return distanceFromBottom(metrics) <= threshold;+}++/**+ * Whether to keep following after a scroll event. Reaching the end resumes+ * following; only the reader moving up stops it. Position alone is not enough:+ * scroll events are dispatched a frame late, so the one fired by sticking to the+ * end can arrive after more content has landed and look far from the bottom.+ */+export function keepsFollowing(+ metrics: ScrollMetrics,+ previousScrollTop: number,+ following: boolean,+ threshold: number+) {+ if (isAtBottom(metrics, threshold)) return true;+ return following && metrics.scrollTop >= previousScrollTop;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message-scroller.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message-scroller.tsxnew file mode 100644index 000000000..ca126a995--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message-scroller.tsx@@ -0,0 +1,206 @@+import { ArrowDownIcon } from 'lucide-react';+import * as React from 'react';+import { Button } from '@renderer/lib/ui/button';+import { cn } from '@renderer/utils/utils';+import { FOLLOW_BOTTOM_THRESHOLD_PX, keepsFollowing } from './follow-bottom';++type MessageScrollerContextValue = {+ viewportRef: React.RefObject<HTMLDivElement | null>;+ viewport: HTMLDivElement | null;+ setViewport: (viewport: HTMLDivElement | null) => void;+ followingRef: React.RefObject<boolean>;+ atBottom: boolean;+ setAtBottom: (atBottom: boolean) => void;+ scrollToEnd: (behavior: ScrollBehavior) => void;+};++const MessageScrollerContext = React.createContext<MessageScrollerContextValue | null>(null);++function useMessageScrollerContext(): MessageScrollerContextValue {+ const context = React.useContext(MessageScrollerContext);+ if (!context) throw new Error('MessageScroller parts must be rendered inside <MessageScroller>');+ return context;+}++/**+ * Where the reader is in the transcript, and a way to jump to the end. Following+ * is on while the viewport sits at the bottom: new content then keeps it pinned+ * there. Scrolling up stops following; scrolling back down, or `scrollToEnd`,+ * resumes it.+ */+function useMessageScroller(): { isAtBottom: boolean; scrollToEnd: () => void } {+ const { atBottom, scrollToEnd } = useMessageScrollerContext();+ return { isAtBottom: atBottom, scrollToEnd: () => scrollToEnd('smooth') };+}++function MessageScroller({ className, ...props }: React.ComponentProps<'div'>) {+ const viewportRef = React.useRef<HTMLDivElement | null>(null);+ // The viewport is also held as state because the content's layout effect+ // runs before the enclosing viewport's ref is attached on mount: reading the+ // ref there finds null, and nothing would ever stick to the bottom.+ const [viewport, setViewport] = React.useState<HTMLDivElement | null>(null);+ const followingRef = React.useRef(true);+ const [atBottom, setAtBottom] = React.useState(true);++ const scrollToEnd = React.useCallback((behavior: ScrollBehavior) => {+ const viewport = viewportRef.current;+ if (!viewport) return;+ followingRef.current = true;+ setAtBottom(true);+ viewport.scrollTo({ top: viewport.scrollHeight, behavior });+ }, []);++ const value = React.useMemo(+ () => ({+ viewportRef,+ viewport,+ setViewport,+ followingRef,+ atBottom,+ setAtBottom,+ scrollToEnd,+ }),+ [viewport, atBottom, scrollToEnd]+ );++ return (+ <MessageScrollerContext.Provider value={value}>+ <div+ data-slot="message-scroller"+ data-at-bottom={atBottom}+ className={cn(+ 'group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden',+ className+ )}+ {...props}+ />+ </MessageScrollerContext.Provider>+ );+}++function MessageScrollerViewport({ className, onScroll, ...props }: React.ComponentProps<'div'>) {+ const { viewportRef, setViewport, followingRef, setAtBottom } = useMessageScrollerContext();+ const attach = React.useCallback(+ (node: HTMLDivElement | null) => {+ viewportRef.current = node;+ setViewport(node);+ },+ [viewportRef, setViewport]+ );++ const lastScrollTop = React.useRef(0);++ const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {+ const viewport = event.currentTarget;+ const following = keepsFollowing(+ viewport,+ lastScrollTop.current,+ followingRef.current,+ FOLLOW_BOTTOM_THRESHOLD_PX+ );+ lastScrollTop.current = viewport.scrollTop;+ followingRef.current = following;+ setAtBottom(following);+ onScroll?.(event);+ };++ // No scroll anchoring: when content above the end grows, the browser would+ // shift scrollTop to hold its anchor, and that scroll reads as the reader+ // leaving the bottom, so following stops.+ return (+ <div+ data-slot="message-scroller-viewport"+ className={cn(+ 'size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain [overflow-anchor:none] [scrollbar-gutter:stable]',+ className+ )}+ {...props}+ ref={attach}+ onScroll={handleScroll}+ />+ );+}++function MessageScrollerContent({ className, ...props }: React.ComponentProps<'div'>) {+ const { viewport, followingRef } = useMessageScrollerContext();+ const contentRef = React.useRef<HTMLDivElement | null>(null);++ React.useLayoutEffect(() => {+ const content = contentRef.current;+ if (!viewport || !content) return;++ const stick = () => {+ if (followingRef.current) viewport.scrollTop = viewport.scrollHeight;+ };+ stick();+ // Content growing (a streamed reply) and the viewport shrinking (the composer+ // growing beneath it) both move the end out of view.+ const observer = new ResizeObserver(stick);+ observer.observe(content);+ observer.observe(viewport);+ return () => observer.disconnect();+ }, [viewport, followingRef]);++ return (+ <div+ data-slot="message-scroller-content"+ className={cn('flex h-max min-h-full flex-col gap-8', className)}+ {...props}+ ref={contentRef}+ />+ );+}++function MessageScrollerItem({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-scroller-item"+ className={cn('min-w-0 shrink-0', className)}+ {...props}+ />+ );+}++function MessageScrollerButton({+ className,+ children,+ variant = 'outline',+ size = 'icon-sm',+ ...props+}: Omit<React.ComponentProps<typeof Button>, 'onClick'>) {+ const { atBottom, scrollToEnd } = useMessageScrollerContext();+ const active = !atBottom;++ return (+ <Button+ data-slot="message-scroller-button"+ data-active={active}+ aria-hidden={!active}+ tabIndex={active ? 0 : -1}+ variant={variant}+ size={size}+ className={cn(+ 'absolute bottom-4 left-1/2 -translate-x-1/2 rounded-full bg-background shadow-sm transition-[translate,scale,opacity] duration-200 data-[active=false]:pointer-events-none data-[active=false]:translate-y-full data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 motion-reduce:transition-none',+ className+ )}+ {...props}+ onClick={() => scrollToEnd('smooth')}+ >+ {children ?? (+ <>+ <ArrowDownIcon />+ <span className="sr-only">Scroll to end</span>+ </>+ )}+ </Button>+ );+}++export {+ MessageScroller,+ MessageScrollerViewport,+ MessageScrollerContent,+ MessageScrollerItem,+ MessageScrollerButton,+ useMessageScroller,+};diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message.tsxnew file mode 100644index 000000000..c8f2edfa9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/message.tsx@@ -0,0 +1,84 @@+import type * as React from 'react';+import { cn } from '@renderer/utils/utils';++function MessageGroup({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-group"+ className={cn('flex min-w-0 flex-col gap-2', className)}+ {...props}+ />+ );+}++function Message({+ className,+ align = 'start',+ ...props+}: React.ComponentProps<'div'> & { align?: 'start' | 'end' }) {+ return (+ <div+ data-slot="message"+ data-align={align}+ className={cn(+ 'group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse',+ className+ )}+ {...props}+ />+ );+}++function MessageAvatar({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-avatar"+ className={cn(+ 'flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full bg-background-2 group-has-data-[slot=message-footer]/message:-translate-y-8',+ className+ )}+ {...props}+ />+ );+}++function MessageContent({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-content"+ className={cn(+ 'flex w-full min-w-0 flex-col gap-2.5 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',+ className+ )}+ {...props}+ />+ );+}++function MessageHeader({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-header"+ className={cn(+ 'flex max-w-full min-w-0 items-center px-3 text-xs font-medium text-foreground-muted group-has-data-[variant=ghost]/message:px-0',+ className+ )}+ {...props}+ />+ );+}++function MessageFooter({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="message-footer"+ className={cn(+ 'flex max-w-full min-w-0 items-center px-3 text-xs font-medium text-foreground-muted group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',+ className+ )}+ {...props}+ />+ );+}++export { MessageGroup, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader };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.tsxnew file mode 100644index 000000000..97951aa1f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/prompt-input.tsx@@ -0,0 +1,255 @@+import { ArrowUpIcon, FileIcon, SquareIcon, XIcon } from 'lucide-react';+import {+ useState,+ type ComponentProps,+ type FormEvent,+ type KeyboardEvent,+ type ReactNode,+} from 'react';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import { cn } from '@renderer/utils/utils';+import {+ Attachment,+ AttachmentAction,+ AttachmentActions,+ AttachmentContent,+ AttachmentGroup,+ AttachmentMedia,+ AttachmentTitle,+ type AttachmentState,+} from './attachment';++/**+ * The composer: a bordered box with the text on top and a footer row beneath it+ * (tools on the left, Send/Stop on the right). The text is controlled by the+ * caller; submitting — the Send button or Enter in the textarea — calls+ * `onSubmit` and leaves what to do with the text to it.+ */+export function PromptInput({+ onSubmit,+ children,+ className,+}: {+ onSubmit: () => void;+ children: ReactNode;+ className?: string;+}) {+ const handleSubmit = (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ onSubmit();+ };++ return (+ <form+ data-slot="prompt-input"+ className={cn(+ 'flex w-full min-w-0 flex-col rounded-lg border border-border bg-background-1 transition-colors focus-within:border-border-primary',+ className+ )}+ onSubmit={handleSubmit}+ >+ {children}+ </form>+ );+}++/**+ * Enter submits the form, Shift+Enter inserts a newline, and Enter that commits+ * an IME composition does neither. A disabled submit button blocks Enter too, so+ * the keyboard cannot send what the button would refuse.+ */+export function PromptInputTextarea({+ className,+ onKeyDown,+ onCompositionStart,+ onCompositionEnd,+ ...props+}: ComponentProps<'textarea'>) {+ const [composing, setComposing] = useState(false);++ const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ onKeyDown?.(event);+ if (event.defaultPrevented) return;+ if (event.key !== 'Enter' || event.shiftKey) return;+ if (composing || event.nativeEvent.isComposing) return;+ event.preventDefault();+ const form = event.currentTarget.form;+ const submit = form?.querySelector<HTMLButtonElement>('button[type="submit"]');+ if (submit?.disabled) return;+ form?.requestSubmit();+ };++ return (+ <textarea+ data-slot="prompt-input-textarea"+ rows={1}+ className={cn(+ 'field-sizing-content max-h-60 min-h-14 w-full resize-none bg-transparent px-3 pt-3 pb-1 text-sm text-foreground outline-none placeholder:text-foreground-passive disabled:cursor-not-allowed disabled:opacity-50',+ className+ )}+ onKeyDown={handleKeyDown}+ onCompositionStart={(event) => {+ setComposing(true);+ onCompositionStart?.(event);+ }}+ onCompositionEnd={(event) => {+ setComposing(false);+ onCompositionEnd?.(event);+ }}+ {...props}+ />+ );+}++export function PromptInputFooter({ className, ...props }: ComponentProps<'div'>) {+ return (+ <div+ data-slot="prompt-input-footer"+ className={cn('flex items-center justify-between gap-1 px-2 pb-2', className)}+ {...props}+ />+ );+}++export function PromptInputTools({ className, ...props }: ComponentProps<'div'>) {+ return (+ <div+ data-slot="prompt-input-tools"+ className={cn('flex min-w-0 items-center gap-1', className)}+ {...props}+ />+ );+}++/** A ghost button for the tools row. `tooltip` doubles as its accessible name. */+export function PromptInputButton({+ tooltip,+ variant = 'ghost',+ size = 'icon-sm',+ ...props+}: ComponentProps<typeof Button> & { tooltip?: string }) {+ const button = (+ <Button type="button" variant={variant} size={size} aria-label={tooltip} {...props} />+ );+ if (!tooltip) return button;+ return (+ <Tooltip>+ <TooltipTrigger render={button} />+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ );+}++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.+ */+export function PromptInputSubmit({+ status,+ onStop,+ stopDisabledReason,+ disabled,+ className,+}: {+ status: PromptInputStatus;+ onStop?: () => void;+ stopDisabledReason?: string | null;+ disabled?: boolean;+ className?: string;+}) {+ 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>+ </Tooltip>+ );+ }++ const sending = status === 'sending';+ return (+ <Button+ 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+ )}+ disabled={sending || disabled}+ aria-label={sending ? 'Sending' : 'Send'}+ title={sending ? 'Sending' : 'Send'}+ >+ {sending ? <Spinner size="sm" className="size-3.5" /> : <ArrowUpIcon />}+ </Button>+ );+}++export type PromptInputAttachmentItem = {+ id: string;+ name: string;+ mediaType?: string;+ /** An image preview URL; files without one show a file icon. */+ previewUrl?: string;+ state?: AttachmentState;+};++/** The files queued with the message, each removable. Renders nothing when empty. */+export function PromptInputAttachments({+ items,+ onRemove,+ className,+}: {+ items: PromptInputAttachmentItem[];+ onRemove: (id: string) => void;+ className?: string;+}) {+ if (items.length === 0) return null;+ return (+ <AttachmentGroup data-slot="prompt-input-attachments" className={cn('px-3 pt-3', className)}>+ {items.map((item) => (+ <Attachment key={item.id} size="xs" state={item.state ?? 'done'} className="min-w-0">+ <AttachmentMedia variant={item.previewUrl ? 'image' : 'icon'}>+ {item.previewUrl ? <img src={item.previewUrl} alt="" /> : <FileIcon />}+ </AttachmentMedia>+ <AttachmentContent>+ <AttachmentTitle className="max-w-48" title={item.name}>+ {item.name}+ </AttachmentTitle>+ </AttachmentContent>+ <AttachmentActions>+ <AttachmentAction+ aria-label={`Remove ${item.name}`}+ title={`Remove ${item.name}`}+ onClick={() => onRemove(item.id)}+ >+ <XIcon />+ </AttachmentAction>+ </AttachmentActions>+ </Attachment>+ ))}+ </AttachmentGroup>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/reasoning.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/reasoning.tsxnew file mode 100644index 000000000..32e86bae1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/reasoning.tsx@@ -0,0 +1,38 @@+import { useState } from 'react';+import { ChatMarkdown } from './chat-markdown';+import { ThinkingIcon, WorkLogDetails, WorkLogRow } from './work-log';++/**+ * The model's thinking as one work-log line ("Thought for 4s"). With no text+ * there is nothing to open, so the line is a plain label.+ */+export function Reasoning({+ label,+ shimmer = false,+ text,+}: {+ label: string;+ shimmer?: boolean;+ text: string;+}) {+ const [open, setOpen] = useState(false);+ const openable = text.length > 0;+ return (+ <div data-slot="reasoning">+ <WorkLogRow+ icon={<ThinkingIcon />}+ label={label}+ active={shimmer}+ {...(openable ? { open, onToggle: () => setOpen(!open) } : {})}+ >+ {openable && open && (+ <WorkLogDetails>+ <div className="max-h-96 overflow-auto border-l border-border pl-3 select-text">+ <ChatMarkdown className="text-xs text-foreground-muted">{text}</ChatMarkdown>+ </div>+ </WorkLogDetails>+ )}+ </WorkLogRow>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/shimmer.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/shimmer.tsxnew file mode 100644index 000000000..8caad5de9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/shimmer.tsx@@ -0,0 +1,11 @@+import type { ReactNode } from 'react';+import { cn } from '@renderer/utils/utils';++/**+ * Text with a light sweeping across it, for a label that names work still in+ * progress. CSS only — the `text-shimmer` class in `index.css` carries the+ * gradient, the animation and the reduced-motion opt-out.+ */+export function Shimmer({ children, className }: { children: ReactNode; className?: string }) {+ return <span className={cn('text-shimmer inline-block', className)}>{children}</span>;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/ui/work-log.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/work-log.tsxnew file mode 100644index 000000000..53ef5d7dc--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/ui/work-log.tsx@@ -0,0 +1,163 @@+import {+ Bot,+ Brain,+ ChevronRightIcon,+ CircleAlert,+ FileText,+ Globe,+ Hammer,+ ListTodo,+ MessagesSquare,+ Plug,+ Search,+ SquarePen,+ Terminal,+ Wrench,+} from 'lucide-react';+import type { ReactNode } from 'react';+import { cn } from '@renderer/utils/utils';+import type { ToolKind } from '../tool-presentation';++/**+ * A turn's work as a quiet log: one compact line per step, an icon for what+ * kind of step it was and a muted label, with no cards or status badges. A+ * line that has more to show opens in place; one that has nothing does not+ * pretend to. The layout follows the work log in T3 Code (MIT, T3 Tools Inc.),+ * re-implemented on this app's tokens.+ */++const ICONS: Record<ToolKind, typeof Terminal> = {+ shell: Terminal,+ read: FileText,+ edit: SquarePen,+ search: Search,+ web: Globe,+ agent: Bot,+ todo: ListTodo,+ switch: MessagesSquare,+ mcp: Plug,+ other: Wrench,+};++export function ToolKindIcon({ kind }: { kind: ToolKind | null }) {+ const Icon = kind ? ICONS[kind] : Hammer;+ return <Icon aria-hidden className="size-3.5" />;+}++export const ThinkingIcon = () => <Brain aria-hidden className="size-3.5" />;+export const FailedIcon = () => <CircleAlert aria-hidden className="size-3.5" />;++export function WorkLogRow({+ icon,+ label,+ trailing,+ tone = 'default',+ active = false,+ open,+ onToggle,+ title,+ children,+}: {+ icon: ReactNode;+ label: ReactNode;+ trailing?: ReactNode;+ /** `failed` tints the icon red; `passive` mutes the label further. */+ tone?: 'default' | 'failed' | 'passive';+ /** Work still under way: the label shimmers. */+ active?: boolean;+ /** Present with `onToggle` only: whether the details are showing. */+ open?: boolean;+ onToggle?: () => void;+ title?: string;+ children?: ReactNode;+}) {+ const line = (+ <>+ <span+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center',+ tone === 'failed' ? 'text-foreground-destructive' : 'text-foreground-passive'+ )}+ >+ {icon}+ </span>+ <span+ className={cn('min-w-0 flex-1 truncate', tone === 'passive' && 'text-foreground-passive')}+ >+ {active ? <span className="text-shimmer">{label}</span> : label}+ </span>+ {trailing}+ {onToggle && (+ <ChevronRightIcon+ aria-hidden+ className={cn(+ 'size-3 shrink-0 text-foreground-passive opacity-0 transition-[transform,opacity] group-hover/work-row:opacity-100 group-focus-visible/work-row:opacity-100 motion-reduce:transition-none',+ open && 'rotate-90 opacity-100'+ )}+ />+ )}+ </>+ );+ const lineClass =+ 'flex min-h-6 w-full min-w-0 items-center gap-1.5 rounded-md px-0.5 text-left text-sm leading-relaxed text-foreground-muted';+ return (+ <div data-slot="work-log-row" className="min-w-0">+ {onToggle ? (+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={open}+ title={title}+ className={cn(+ lineClass,+ 'group/work-row cursor-pointer outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/70 focus-visible:ring-inset'+ )}+ >+ {line}+ </button>+ ) : (+ <div className={lineClass} title={title}>+ {line}+ </div>+ )}+ {children}+ </div>+ );+}++/** What an opened line shows, indented under its label. */+export function WorkLogDetails({ children }: { children: ReactNode }) {+ return <div className="ms-6 mt-0.5 mb-1.5 flex min-w-0 flex-col gap-1.5">{children}</div>;+}++export function WorkLogPre({ children, className }: { children: ReactNode; className?: string }) {+ return (+ <pre+ className={cn(+ 'max-h-64 overflow-auto rounded-md border border-border bg-background-1 px-2.5 py-1.5 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap text-foreground-muted select-text',+ className+ )}+ >+ {children}+ </pre>+ );+}++export function WorkLogNote({+ children,+ tone = 'passive',+}: {+ children: ReactNode;+ tone?: 'passive' | 'failed';+}) {+ return (+ <p+ className={cn(+ 'text-xs',+ tone === 'failed' ? 'text-foreground-destructive' : 'text-foreground-passive'+ )}+ >+ {children}+ </p>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsxindex ee6c0ebdf..055e3b51a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx@@ -3,10 +3,12 @@ import { Command } from 'cmdk';import { Activity, DoorOpen, Globe, type LucideIcon, MessageSquare, Server } from 'lucide-react';import { observer, useObserver } from 'mobx-react-lite';import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { agentChatsFlag } from '@renderer/features/chats/stores/agent-chats-flag';import { REMOTE_HOSTS_QUERY_KEY } from '@renderer/features/remote-hosts/views/remote-hosts-view';import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';import { agentExpandKey } from '@renderer/features/sidebar/sidebar-store';import { openRoom } from '@renderer/features/switch-rooms/open-room';+import { isConsoleDirectChat } from '@renderer/features/switch-servers/room-filters';import { serverIcon } from '@renderer/features/switch-servers/server-icon';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';@@ -272,7 +274,13 @@ export function CommandPaletteModal({// span every server, not the active one: you search precisely because you do// not know where a thing is.const roomResults = useObserver(() =>- matchRooms(switchRoomsStore.listedRoomsInAllWorkspaces, debouncedQuery)+ matchRooms(+ switchRoomsStore.listedRoomsInAllWorkspaces.filter((room) => {+ const serverId = switchRoomsStore.roomServerId(room.id);+ return !(serverId && agentChatsFlag(serverId) && isConsoleDirectChat(room));+ }),+ debouncedQuery+ ));const serverResults = useObserver(() => matchServers(switchServersStore.servers, debouncedQuery));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 641ad851d..33f57c3ba 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@@ -1,12 +1,16 @@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';import { describeFailure } from '@renderer/lib/errors/describe-failure';import { useToast } from '@renderer/lib/hooks/use-toast';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { rpc } from '@renderer/lib/ipc';-import { useParams } from '@renderer/lib/layout/navigation-provider';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import {workspaceAgentsQueryKey,@@ -29,6 +33,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {params: { locationId, agentName },} = useParams('location');const showCreateSessionModal = useShowModal('sessionModal');+ const { navigate } = useNavigate();const showAddToRoom = useShowModal('addAgentToRoomModal');const agent = agentsStore.agentAtLocation(locationId, agentName);@@ -53,6 +58,12 @@ 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.+ const managedAgents = useManagedAgents(agent?.serverId ?? null);+ const chatsEnabled = useFeatureFlags(agent?.serverId).agent_chats;+ const chatsTab =+ chatsEnabled && (managedAgents.data ?? []).some((managed) => managed.agentId === switchAgentId);+ const newChat = chatsEnabled && agent?.serverId != null && switchAgentId !== null;/** The icon is stored on the Switch server, not locally, so a change is a* request that can fail. It is reported rather than swallowed: a picture@@ -103,13 +114,33 @@ export const AgentPageHeader = observer(function AgentPageHeader() {description={description}actions={<>- <Button- onClick={() =>- showCreateSessionModal({ locationId, agentName, entryPoint: 'agent_page' })- }- >- New Session- </Button>+ {!newChat && (+ <Button+ onClick={() =>+ showCreateSessionModal({ locationId, agentName, entryPoint: 'agent_page' })+ }+ >+ New Session+ </Button>+ )}+ {newChat && (+ <Button+ onClick={async () => {+ 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;+ }+ const chat = await directChats.start(serverId, switchAgentId);+ if (chat)+ navigate('chat', { serverId, roomId: chat.roomId, agentId: switchAgentId });+ }}+ >+ New chat+ </Button>+ )}{roomable && (<Buttonvariant="outline"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.tsxnew file mode 100644index 000000000..e8e457211--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx@@ -0,0 +1,153 @@+import { ChevronDown, ChevronRight, Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { type ReactNode, useEffect, 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 { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+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';++function Section({+ title,+ addLabel,+ onAdd,+ children,+}: {+ title: string;+ addLabel: string;+ onAdd: () => void;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(true);+ 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">+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ className="flex items-center gap-1 text-xs font-medium text-foreground-muted hover:text-foreground"+ >+ <Chevron className="size-3.5" />+ {title}+ </button>+ <SidebarItemMiniButton aria-label={addLabel} title={addLabel} onClick={onAdd}>+ <Plus className="size-3.5" />+ </SidebarItemMiniButton>+ </div>+ {open && children}+ </section>+ );+}++const Note = ({ children }: { children: ReactNode }) => (+ <p className="px-2 py-1 text-xs text-foreground-muted">{children}</p>+);++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 ?? []) };+}++/** The direct chat open on an agent's Chats tab: the one in the params, else its newest. */+export function openAgentChat(+ agent: ManagedAgentView,+ roomId: string | undefined+): ChatSummary | null {+ const { direct } = conversationsOf(agent);+ return direct.find((chat) => chat.roomId === roomId) ?? direct[0] ?? null;+}++/**+ * 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.+ */+export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagedAgentView }) {+ const { params, setParams } = useParams('managedAgent');+ const { serverId, workspaceId, agentId } = agent;+ useEffect(() => {+ void switchRoomsStore.fetchAgentRooms(workspaceId, agentId);+ }, [workspaceId, agentId]);++ const { agentRooms, direct, rooms } = conversationsOf(agent);+ const roomsError = switchRoomsStore.errorFor(workspaceId, agentId);+ const roomId = openAgentChat(agent, params.roomId)?.roomId ?? null;+ const open = (id: string) => setParams({ roomId: id });+ const newChat = async () => {+ const chat = await directChats.start(serverId, agentId);+ if (chat) open(chat.roomId);+ };++ 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">+ <Section title="Direct chats" addLabel="New chat" onAdd={() => void newChat()}>+ {chatsStore.listError && <Note>{chatsStore.listError}</Note>}+ {direct.map((chat) => (+ <ChatRow+ key={chat.roomId}+ serverId={serverId}+ chat={chat}+ isActive={chat.roomId === roomId}+ onOpen={() => open(chat.roomId)}+ />+ ))}+ {direct.length === 0 && <Note>No direct chats yet.</Note>}+ </Section>+ <Section+ title="Rooms"+ addLabel="Create room"+ onAdd={() => showModal('createRoomModal', { serverId })}+ >+ {roomsError && <Note>{roomsError}</Note>}+ {rooms.map((room) => (+ <RoomListRow+ key={room.roomId}+ room={{+ name: switchRoomsStore.roomNameById(room.roomId) ?? room.roomName,+ bridgeType: switchRoomsStore.roomBridgeTypeById(room.roomId),+ bridgeDisplayName:+ switchRoomsStore.roomSummaryById(room.roomId)?.bridgeDisplayName ?? null,+ }}+ isActive={false}+ onOpen={() => openRoomView(room.roomId)}+ />+ ))}+ {!agentRooms && !roomsError && <Note>Loading…</Note>}+ {agentRooms && rooms.length === 0 && <Note>Not in any room yet.</Note>}+ </Section>+ </div>+ <div className="relative min-w-0 flex-1">+ {roomId ? (+ <>+ <ChatPanel key={`${serverId}:${roomId}`} serverId={serverId} roomId={roomId} />+ <div+ aria-hidden+ className="pointer-events-none absolute inset-x-0 top-0 z-10 h-6 bg-linear-to-b from-background to-transparent"+ />+ </>+ ) : (+ <EmptyState+ label="No chat open"+ description="Start a chat with this agent."+ action={<Button onClick={() => void newChat()}>Start a chat</Button>}+ />+ )}+ </div>+ </div>+ );+});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.tsnew file mode 100644index 000000000..ef293c765--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts@@ -0,0 +1,28 @@+import { makeAutoObservable } from 'mobx';++export type AgentTab = 'chats' | '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/managed-agent-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsxindex 2bb291c48..b2a29e740 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@@ -3,14 +3,20 @@ import { MoreVertical, Play, Square, Trash2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { type ReactNode, useState } 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';import { ServerPage } from '@renderer/features/switch-servers/server-page';-import { ServerStatusPill } from '@renderer/features/switch-servers/server-presentation';+import {+ ServerStatusPill,+ serverState,+} from '@renderer/features/switch-servers/server-presentation';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { 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 { 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';@@ -22,12 +28,27 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import { cn } from '@renderer/utils/utils';import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { AgentChats, openAgentChat } from './agent-chats';+import { type AgentTab, agentTabStore } from './agent-tab-store';import { ManagedAgentPage } from './managed-agent-page';import { managedAgentLabel } from './managed-agent-state';import { MANAGED_AGENTS_KEY, useManagedAgents } from './use-managed-agents';-type ManagedAgentParams = { serverId: string; agentId: string; name: string };+type ManagedAgentParams = {+ serverId: string;+ agentId: string;+ name: string;+ /** The chat open on the Chats tab. */+ roomId?: string;+};++const TABS = [+ { value: 'chats', label: 'Chats' },+ { value: 'settings', label: 'Settings' },+] as const satisfies readonly { value: AgentTab; label: string }[];const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {const { params } = useParams('managedAgent');@@ -35,32 +56,79 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {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 = useFeatureFlags(params.serverId).agent_chats;+ const tab = agentTabStore.tabFor(params.agentId);+ const chat = tabbed && agent && tab === 'chats' ? openAgentChat(agent, params.roomId) : null;+ const activities = useAgentActivities(params.serverId, chat ?? undefined);+ const breadcrumb = (+ <TitlebarBreadcrumb+ crumbs={[+ {+ key: 'agent',+ icon: (+ <AgentAvatar+ name={label}+ iconUrl={agent?.iconUrl ?? null}+ serverId={params.serverId}+ size={16}+ className="bg-transparent"+ />+ ),+ label,+ },+ ]}+ />+ );+ const pill = server && <ServerStatusPill server={server} />;+ if (!tabbed)+ return (+ <Titlebar+ leftSlot={breadcrumb}+ rightSlot={+ <div className="mr-1 flex items-center gap-1.5">+ {pill}+ {agent && <ManagedAgentActionsMenu agent={agent} />}+ </div>+ }+ />+ );return (<Titlebar+ className="border-b border-border"+ leftClassName={cn(+ 'w-[300px] shrink-0 self-stretch',+ tab === 'chats' && 'border-r border-border'+ )}leftSlot={- <TitlebarBreadcrumb- crumbs={[- {- key: 'agent',- icon: (- <AgentAvatar- name={label}- iconUrl={agent?.iconUrl ?? null}- serverId={params.serverId}- size={16}- className="bg-transparent"- />- ),- label,- },- ]}- />+ <div className="flex min-w-0 items-center gap-3">+ {breadcrumb}+ <SegmentedControl+ value={tab}+ onChange={(next) => agentTabStore.setTab(params.agentId, next)}+ options={TABS}+ ariaLabel="Agent view"+ />+ </div>}+ rightClassName="min-w-0 flex-1 justify-between gap-3 pl-4"rightSlot={- <div className="mr-1 flex items-center gap-1.5">- {server && <ServerStatusPill server={server} />}- {agent && <ManagedAgentActionsMenu agent={agent} />}- </div>+ <>+ <span className="truncate text-sm font-medium">{chat?.name}</span>+ <div className="mr-1 flex shrink-0 items-center gap-1.5">+ {server &&+ serverState(server) !== 'connected' &&+ serverState(server) !== 'running-local' &&+ pill}+ {agent &&+ (chat ? (+ <ChatHeaderControls serverId={params.serverId} chat={chat} activities={activities}>+ <ManagedAgentActionItems agent={agent} />+ </ChatHeaderControls>+ ) : (+ <ManagedAgentActionsMenu agent={agent} />+ ))}+ </div>+ </>}/>);@@ -68,6 +136,28 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {/** Starting, stopping and deleting the agent, from the titlebar's menu as a Console agent's actions are. */function ManagedAgentActionsMenu({ agent }: { agent: ManagedAgentView }) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="sm"+ className="size-7 p-0"+ aria-label={`${managedAgentLabel(agent)} actions`}+ >+ <MoreVertical className="size-4" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ <ManagedAgentActionItems agent={agent} />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function ManagedAgentActionItems({ agent }: { agent: ManagedAgentView }) {const label = managedAgentLabel(agent);const queryClient = useQueryClient();const { navigate } = useNavigate();@@ -113,33 +203,24 @@ function ManagedAgentActionsMenu({ agent }: { agent: ManagedAgentView }) {});return (- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button variant="ghost" size="sm" className="size-7 p-0" aria-label={`${label} actions`}>- <MoreVertical className="size-4" />- </Button>- }- />- <DropdownMenuContent align="end">- {agent.desiredState === 'running' ? (- <DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('stopped')}>- <Square className="size-4" />- Stop- </DropdownMenuItem>- ) : (- <DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('running')}>- <Play className="size-4" />- Start- </DropdownMenuItem>- )}- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" disabled={busy} onClick={remove}>- <Trash2 className="size-4" />- Delete agent…+ <>+ {agent.desiredState === 'running' ? (+ <DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('stopped')}>+ <Square className="size-4" />+ Stop</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ ) : (+ <DropdownMenuItem disabled={busy} onClick={() => void setDesiredState('running')}>+ <Play className="size-4" />+ Start+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" disabled={busy} onClick={remove}>+ <Trash2 className="size-4" />+ Delete agent…+ </DropdownMenuItem>+ </>);}@@ -147,6 +228,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 = useFeatureFlags(params.serverId).agent_chats;if (agents.error)return (<ServerPage width={900} title={params.name} description="">@@ -177,6 +259,9 @@ const ManagedAgentPanel = observer(function ManagedAgentPanel() {</p></ServerPage>);+ if (!tabbed) return <ManagedAgentPage key={agent.agentId} agent={agent} />;+ const tab = agentTabStore.tabFor(agent.agentId);+ if (tab === 'chats') return <AgentChats key={agent.agentId} agent={agent} />;return <ManagedAgentPage key={agent.agentId} agent={agent} />;});@@ -189,7 +274,8 @@ export const managedAgentView = {if (typeof value.serverId !== 'string' ||typeof value.agentId !== 'string' ||- typeof value.name !== 'string'+ typeof value.name !== 'string' ||+ (value.roomId !== undefined && typeof value.roomId !== 'string'))return { ok: false, redirect: 'home', discardParams: true };return { ok: true };diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsxindex b555c0b2f..d0f06b11a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx@@ -3,9 +3,10 @@ import { observer } from 'mobx-react-lite';import { useState } from 'react';import { ManagedAgentList } from '@renderer/features/managed-agents/managed-agent-list';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { useListedRoomsInActiveScope } from '@renderer/features/switch-servers/use-listed-rooms';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { SegmentedControl } from '@renderer/lib/ui/segmented-control';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';import { SidebarMenuRow } from './sidebar-primitives';@@ -36,7 +37,8 @@ function storedTab(): MainTab {export const SidebarMainSection = observer(function SidebarMainSection() {const [tab, setTab] = useState<MainTab>(storedTab);const agents = useManagedAgents(switchServersStore.activeServerId);- const rooms = switchRoomsStore.listedRoomsInActiveScope;+ const flags = useFeatureFlags(switchServersStore.activeServerId);+ const rooms = useListedRoomsInActiveScope();const count = tab === 'agents' ? (agents.data?.length ?? 0) : rooms.length;return (@@ -60,7 +62,7 @@ export const SidebarMainSection = observer(function SidebarMainSection() {{agents.data?.length === 0 && (<p className="px-[9px] py-2 text-xs text-foreground-muted">No agents yet.</p>)}- <ChatsTeaser />+ {!flags.agent_chats && <ChatsTeaser />}</>) : (<RoomList rooms={rooms} />@@ -77,26 +79,44 @@ const RoomList = observer(function RoomList({ rooms }: { rooms: RemoteRoomSummarreturn (<div className="flex flex-col gap-[2px]" aria-label="Rooms">{rooms.map((room) => (- <SidebarMenuRow+ <RoomListRowkey={room.id}+ room={room}isActive={isRoomViewActive(room.id)}- title={room.bridgeDisplayName ? `${room.name} · ${room.bridgeDisplayName}` : room.name}- onMouseDown={(event) => event.preventDefault()}- onClick={() => openRoomView(room.id)}- className="h-[30px] py-0 text-[13px]"- >- {hasBridgeIcon(room.bridgeType) ? (- <BridgeIcon bridgeType={room.bridgeType} size={17} className="shrink-0" />- ) : (- <DoorOpen className="size-[17px] shrink-0 text-[var(--fg-icon)]" />- )}- <span className="min-w-0 flex-1 truncate">{room.name}</span>- </SidebarMenuRow>+ onOpen={() => openRoomView(room.id)}+ />))}</div>);});+export function RoomListRow({+ room,+ isActive,+ onOpen,+}: {+ room: Pick<RemoteRoomSummary, 'name' | 'bridgeType' | 'bridgeDisplayName'>;+ isActive: boolean;+ onOpen: () => void;+}) {+ return (+ <SidebarMenuRow+ isActive={isActive}+ title={room.bridgeDisplayName ? `${room.name} · ${room.bridgeDisplayName}` : room.name}+ onMouseDown={(event) => event.preventDefault()}+ onClick={onOpen}+ className="h-[30px] py-0 text-[13px]"+ >+ {hasBridgeIcon(room.bridgeType) ? (+ <BridgeIcon bridgeType={room.bridgeType} size={17} className="shrink-0" />+ ) : (+ <DoorOpen className="size-[17px] shrink-0 text-[var(--fg-icon)]" />+ )}+ <span className="min-w-0 flex-1 truncate">{room.name}</span>+ </SidebarMenuRow>+ );+}+/*** One sentence about what is coming for these agents, under them, closed for* good with its ×.diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsxindex 45ec09fd1..ce17778f8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx@@ -2,8 +2,10 @@ import { observer } from 'mobx-react-lite';import { Fragment } from 'react';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { useListedRoomsInActiveScope } from '@renderer/features/switch-servers/use-listed-rooms';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';import { RoomAgentRow } from './room-agent-row';import { filterRoomGroups, sortRoomGroups } from './room-tree-data';import { SidebarSessionItem } from './session-item';@@ -73,11 +75,8 @@ function membersByRoom(): Map<string, AgentEntry[]> {* Shared with Collapse all, which needs the same set of rows without the tree* being on screen to ask.*/-export function listedRoomKeys(): string[] {- const keys = new Set<string>([- ...switchRoomsStore.listedRoomsInActiveScope.map((room) => room.id),- ...membersByRoom().keys(),- ]);+export function listedRoomKeys(listedRooms: RemoteRoomSummary[]): string[] {+ const keys = new Set<string>([...listedRooms.map((room) => room.id), ...membersByRoom().keys()]);for (const entry of scopedAgents()) {for (const session of agentSessions(entry)) {const roomKey = sessionRoomId(session);@@ -90,6 +89,7 @@ export function listedRoomKeys(): string[] {export const RoomTree = observer(function RoomTree() {const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');const showDeleteRoomModal = useShowModal('deleteRoomModal');+ const listedRooms = useListedRoomsInActiveScope();// Tag every visible session with the agent it belongs to, then group by room.const bySession = new Map<string, AgentEntry>();@@ -102,7 +102,7 @@ export const RoomTree = observer(function RoomTree() {}const members = membersByRoom();- const alwaysShow = listedRoomKeys();+ const alwaysShow = listedRoomKeys(listedRooms);const sorted = sortRoomGroups(filterRoomGroups(diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsxindex fa8e1ae16..2391cb68b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx@@ -9,7 +9,8 @@ import {} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { bridgeFilterValues } from '@renderer/features/switch-servers/switch-rooms-store';+import { useListedRoomsInActiveScope } from '@renderer/features/switch-servers/use-listed-rooms';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';@@ -33,6 +34,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltiimport { cn } from '@renderer/utils/utils';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import { getProvider } from '@shared/core/providers/agent-provider-registry';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';import { type SidebarGrouping, UNBRIDGED_FILTER_VALUE } from '@shared/view-state';import { listedRoomKeys } from './room-tree';import { agentExpandKey, roomViewGroupKey } from './sidebar-store';@@ -54,9 +56,9 @@ const GROUPING_OPTIONS: { value: SidebarGrouping; label: string }[] = [* looked at is named: collapsing the other one would be a change the user never* asked for and would not see until they switched.*/-function topLevelGroupKeys(): string[] {+function topLevelGroupKeys(listedRooms: RemoteRoomSummary[]): string[] {if (sidebarStore.grouping === 'room') {- return listedRoomKeys().map(roomViewGroupKey);+ return listedRoomKeys(listedRooms).map(roomViewGroupKey);}return scopedAgents().map((entry) => agentExpandKey(entry.agent.id));}@@ -97,7 +99,7 @@ function bridgeLabel(value: string): string {* members, under a control that looks like it filters rooms.*/const RoomFilterSections = observer(function RoomFilterSections() {- const bridgeValues = switchRoomsStore.bridgeFilterValuesInActiveScope;+ const bridgeValues = bridgeFilterValues(useListedRoomsInActiveScope());return (<>@@ -219,6 +221,7 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader({const showAddLocationModal = useShowModal('addAgentModal');const showCreateRoomModal = useShowModal('createRoomModal');const showCreateSessionModal = useShowModal('sessionModal');+ const listedRooms = useListedRoomsInActiveScope();const [optionsOpen, setOptionsOpen] = useState(false);// The add actions offer both rather than the one matching the current view.// Which grouping you are looking at says how you want the list arranged, not@@ -332,7 +335,9 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader({</DropdownMenuCheckboxItem></DropdownMenuGroup><DropdownMenuSeparator />- <DropdownMenuItem onClick={() => sidebarStore.collapseAll(topLevelGroupKeys())}>+ <DropdownMenuItem+ onClick={() => sidebarStore.collapseAll(topLevelGroupKeys(listedRooms))}+ ><ChevronsDownUp className="mr-1.5 h-4 w-4" />Collapse all</DropdownMenuItem>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex c22cb4a7f..e174a430d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -9,6 +9,7 @@ import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/swiimport { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { useListedRoomsInActiveScope } from '@renderer/features/switch-servers/use-listed-rooms';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { useNavigate } from '@renderer/lib/layout/navigation-provider';@@ -97,6 +98,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {const managedAgents = useManagedAgents(switchServersStore.activeServerId);const activeServerId = switchServersStore.activeServerId;const managementMode = useAgentManagementMode();+ const listedRooms = useListedRoomsInActiveScope();const managedAgentCount = activeServerId && managedAgents.data ? managedAgents.data.length : 0;const emptyState = sidebarEmptyState({grouping: sidebarStore.grouping,@@ -104,7 +106,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {filteredLocationCount: sidebarStore.filteredLocations.length,activeServerId: switchServersStore.activeServerId,locationCount: sidebarStore.orderedLocations.length,- roomCount: switchRoomsStore.listedRoomsInActiveScope.length,+ roomCount: listedRooms.length,serverListedAgentCount: managedAgentCount,});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsxindex fd91ce3a2..f28c63709 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx@@ -1,6 +1,7 @@import { observer } from 'mobx-react-lite';import { useCallback, useState } from 'react';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { useReadableRoomsInWorkspace } from '@renderer/features/switch-servers/use-listed-rooms';import { PickerCombobox } from '@renderer/lib/components/picker-combobox';import { ChosenRoomTile, RoomPickerRow } from '@renderer/lib/components/room-picker';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -58,8 +59,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({// Every room the server let us see, not only the ones this user created: an// agent's usefulness is mostly in rooms someone else set up, and a picker that// omitted them made those rooms unreachable from here entirely.- const candidates: Candidate[] = switchRoomsStore- .readableRoomsInWorkspace(workspaceId)+ const candidates: Candidate[] = useReadableRoomsInWorkspace(workspaceId).filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id)).map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));const nothingToAdd = candidates.length === 0 && selected.length === 0;diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsxindex 5a205a239..065c85921 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx@@ -1,6 +1,7 @@import { DoorOpen, ExternalLink } from 'lucide-react';import { observer } from 'mobx-react-lite';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { ConsoleChatRedirect } from '@renderer/features/chats/console-chat-redirect';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';@@ -107,10 +108,16 @@ const RoomTitlebar = observer(function RoomTitlebar() {/** Settings when the room is showing them; otherwise nothing, and the* conversation drawn by `RoomEmbedLayer` above shows through. */-const RoomMainPanel = observer(function RoomMainPanel() {+const RoomMainPanel = observer(function RoomMainPanel(): React.JSX.Element {const { params } = useParams('room');- if (roomTabStore.tabFor(params.roomId) !== 'configuration') return null;- return <RoomConfigurationPanel roomId={params.roomId} />;+ return (+ <>+ <ConsoleChatRedirect roomId={params.roomId} />+ {roomTabStore.tabFor(params.roomId) === 'configuration' && (+ <RoomConfigurationPanel roomId={params.roomId} />+ )}+ </>+ );});export const roomView = {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.tsnew file mode 100644index 000000000..22b2a3034--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';+import { isConsoleDirectChat, isConsoleDirectChatSummary } from './room-filters';++const agent = { id: 'a', name: 'a', displayName: null, iconUrl: null, provider: null };++describe('isConsoleDirectChat', () => {+ it('returns true for a direct unbridged room with one agent', () => {+ expect(isConsoleDirectChat({ channelType: 'direct', bridgeType: null, agentCount: 1 })).toBe(+ true+ );+ });++ it('returns false for a direct unbridged room with no agent or several', () => {+ expect(isConsoleDirectChat({ channelType: 'direct', bridgeType: null, agentCount: 0 })).toBe(+ false+ );+ expect(isConsoleDirectChat({ channelType: 'direct', bridgeType: null, agentCount: 2 })).toBe(+ false+ );+ });++ it('returns false for direct bridged rooms', () => {+ expect(isConsoleDirectChat({ channelType: 'direct', bridgeType: 'slack', agentCount: 1 })).toBe(+ false+ );+ });++ it('returns false for non-direct rooms', () => {+ for (const channelType of ['channel_public', 'channel_private', 'group', 'lobby', null])+ expect(isConsoleDirectChat({ channelType, bridgeType: null, agentCount: 1 })).toBe(false);+ });+});++describe('isConsoleDirectChatSummary', () => {+ it('counts the agents of a chat summary', () => {+ expect(+ isConsoleDirectChatSummary({ channelType: 'direct', bridgeType: null, agents: [agent] })+ ).toBe(true);+ expect(+ isConsoleDirectChatSummary({+ channelType: 'direct',+ bridgeType: null,+ agents: [agent, { ...agent, id: 'b' }],+ })+ ).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.tsnew file mode 100644index 000000000..52e651f33--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.ts@@ -0,0 +1,22 @@+import type { ChatSummary } from '@shared/core/chats/chats';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';++/**+ * A 1-1 Console chat: a direct room with exactly one agent and no+ * messaging-app bridge. With agent_chats on, it shows in the chat UI and not+ * as a room.+ * shortcut: room and chat summaries carry no human count, so a 1-1 chat that+ * gained a second person still matches; check members when a summary has them.+ */+export function isConsoleDirectChat(+ room: Pick<RemoteRoomSummary, 'channelType' | 'bridgeType' | 'agentCount'>+): boolean {+ return room.channelType === 'direct' && room.bridgeType === null && room.agentCount === 1;+}++/** {@link isConsoleDirectChat} for a chat summary. */+export function isConsoleDirectChatSummary(+ chat: Pick<ChatSummary, 'channelType' | 'bridgeType' | 'agents'>+): boolean {+ return isConsoleDirectChat({ ...chat, agentCount: chat.agents.length });+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex 066bd5ff7..9e668941b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -22,6 +22,7 @@ import { ServerPage, ServerTableEmpty } from './server-page';import { ServerSectionTitlebar } from './server-section-titlebar';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';+import { useReadableRoomsInWorkspace } from './use-listed-rooms';/** Group key for a room with no messaging app behind it. */const UNBRIDGED = '';@@ -45,7 +46,7 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {}, [serverId]);const workspaceId = workspacesStore.idOnServerInScope(serverId);- const rooms = workspaceId === null ? [] : switchRoomsStore.readableRoomsInWorkspace(workspaceId);+ const rooms = useReadableRoomsInWorkspace(workspaceId);const signedOut = switchRoomsStore.workspacesNotSignedIn.some((w) => w.id === workspaceId);const failed = switchRoomsStore.workspacesThatFailedToLoad.some((w) => w.id === workspaceId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsxindex be2d1a04c..34649b9f6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx@@ -8,7 +8,7 @@ import {} from '@renderer/features/managed-agents/use-managed-agents';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';-import { switchRoomsStore } from './switch-rooms-store';+import { useReadableRoomsInWorkspace } from './use-listed-rooms';/*** How much of this server Switch Console is holding: the agents onboarded@@ -42,6 +42,7 @@ export const ServerStatTiles = observer(function ServerStatTiles({// Counted the way the Your Agents page lists them: this Console's agents,// less the ones the server runs, plus every agent the server runs.const managed = useManagedAgents(serverId);+ const rooms = useReadableRoomsInWorkspace(workspaceId);const agentCount =!agentsStore.loaded || managed.isLoading? null@@ -51,14 +52,7 @@ export const ServerStatTiles = observer(function ServerStatTiles({return (<div className="grid grid-cols-3 gap-3"><StatTile label="Your Agents" value={agentCount} />- <StatTile- label="Your Rooms"- value={- workspaceId === null- ? null- : switchRoomsStore.readableRoomsInWorkspace(workspaceId).length- }- />+ <StatTile label="Your Rooms" value={workspaceId === null ? null : rooms.length} /><StatTile label="Messaging apps" value={bridgesQuery.data?.length ?? null} /></div>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 6c9d7bf04..0bfc380e8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -15,6 +15,25 @@ function key(workspaceId: string, switchAgentId: string): string {return `${workspaceId}:${switchAgentId}`;}+/**+ * The messaging-app values worth offering as a room filter for these rooms:+ * the bridge types actually in use, plus the unbridged sentinel when some room+ * has no messaging app. Offering a platform with no rooms behind it would be a+ * filter that can only ever empty the list.+ */+export function bridgeFilterValues(rooms: readonly RemoteRoomSummary[]): string[] {+ const present = new Set<string>();+ for (const room of rooms) {+ present.add(room.bridgeType ?? UNBRIDGED_FILTER_VALUE);+ }+ // The sentinel sorts last so the real platforms lead the menu.+ return [...present].sort((a, b) => {+ if (a === UNBRIDGED_FILTER_VALUE) return 1;+ if (b === UNBRIDGED_FILTER_VALUE) return -1;+ return a.localeCompare(b);+ });+}+/*** Renderer cache of per-agent room membership, queried live from the gateway* (the server is the source of truth — we do not mirror rooms into SQLite).@@ -190,25 +209,6 @@ export class SwitchRoomsStore {return listed.sort((a, b) => a.name.localeCompare(b.name));}- /**- * The messaging-app values worth offering as a room filter in the active- * workspace: the bridge types actually in use, plus the unbridged sentinel- * when some room has no messaging app. Offering a platform with no rooms- * behind it would be a filter that can only ever empty the list.- */- get bridgeFilterValuesInActiveScope(): string[] {- const present = new Set<string>();- for (const room of this.listedRoomsInActiveScope) {- present.add(room.bridgeType ?? UNBRIDGED_FILTER_VALUE);- }- // The sentinel sorts last so the real platforms lead the menu.- return [...present].sort((a, b) => {- if (a === UNBRIDGED_FILTER_VALUE) return 1;- if (b === UNBRIDGED_FILTER_VALUE) return -1;- return a.localeCompare(b);- });- }-/** Full detail for a room, when its workspace's room list has been loaded. */roomSummaryById(roomId: string): RemoteRoomSummary | null {const workspaceId = this.roomWorkspaceById.get(roomId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-listed-rooms.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-listed-rooms.tsnew file mode 100644index 000000000..ab2f8e340--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-listed-rooms.ts@@ -0,0 +1,39 @@+import { computed } from 'mobx';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';+import { isConsoleDirectChat } from './room-filters';+import { switchRoomsStore } from './switch-rooms-store';+import { switchServersStore } from './switch-servers-store';++function filterConsoleDirectChats(+ rooms: RemoteRoomSummary[],+ hideDirectChats: boolean+): RemoteRoomSummary[] {+ if (!hideDirectChats) return rooms;+ return rooms.filter((room) => !isConsoleDirectChat(room));+}++/**+ * Rooms listed in the sidebar and on the Your Rooms page, filtered by the+ * agent_chats flag: when on, 1-1 Console chats (see `isConsoleDirectChat`)+ * are hidden. Bridged DMs and multi-agent rooms stay visible.+ */+export function useListedRoomsInActiveScope(): RemoteRoomSummary[] {+ const flags = useFeatureFlags(switchServersStore.activeServerId);+ return computed(() =>+ filterConsoleDirectChats(switchRoomsStore.listedRoomsInActiveScope, flags.agent_chats)+ ).get();+}++/**+ * Readable rooms in a workspace, filtered by the agent_chats flag when on.+ */+export function useReadableRoomsInWorkspace(workspaceId: string | null): RemoteRoomSummary[] {+ const flags = useFeatureFlags(workspaceId && workspacesStore.serverIdFor(workspaceId));+ if (workspaceId === null) return [];+ return filterConsoleDirectChats(+ switchRoomsStore.readableRoomsInWorkspace(workspaceId),+ flags.agent_chats+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsxindex 7f8f49ff1..abf5d4cff 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';import { Check, ChevronsUpDown, Plus, Search, Server, UserPlus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useState } from 'react';+import { ChatsOfflineNote } from '@renderer/features/chats/components/chats-offline-note';import {InvitedBadge,invitationSummary,@@ -194,6 +195,7 @@ const ServerMenu = observer(function ServerMenu({ activeServer }: { activeServer) : (<ServerProblemDot server={activeServer} />)}+ <ChatsOfflineNote server={activeServer} /></span></span><ChevronsUpDown className="size-3.5 shrink-0 text-foreground-muted" />@@ -368,6 +370,7 @@ const WorkspaceMenu = observer(function WorkspaceMenu({) : (<ServerProblemDot server={activeServer} />)}+ <ChatsOfflineNote server={activeServer} /></span></span><PendingInvitationCount server={activeServer} />diff --git a/console/apps/switch-console-desktop/src/renderer/index.css b/console/apps/switch-console-desktop/src/renderer/index.cssindex bb6518df5..b05d888a4 100644--- a/console/apps/switch-console-desktop/src/renderer/index.css+++ b/console/apps/switch-console-desktop/src/renderer/index.css@@ -2,6 +2,9 @@@import 'tw-animate-css';@import 'allotment/dist/style.css';+/* Streamdown's built-in renderers carry Tailwind classes from its dist (pnpm hoists it). */+@source '../../../../node_modules/streamdown/dist/*.js';+@custom-variant dark (&:is(.dark *));@custom-variant dark-black (&:is(.dark-black *));@custom-variant emlight (&:is(.emlight *));@@ -430,6 +433,14 @@--menu-surface: #ffffff;--menu-field: #f6f6f5;--menu-shadow: 0 20px 44px rgb(0 0 0 / 0.12);+ --composer-shadow:+ 0 1px 1px rgb(0 0 0 / 0.04), 0 2px 4px rgb(0 0 0 / 0.04), 0 4px 10px rgb(0 0 0 / 0.03);+ --composer-border: var(--border);+ --composer-border-focus: var(--border-1);+ --composer-send-bg: #1b1817;+ --composer-send-fg: var(--foreground-inverse);+ --composer-send-bg-hover: color-mix(in srgb, #1b1817 90%, white);+ --composer-send-bg-active: color-mix(in srgb, #1b1817, black 10%);--menu-faint: rgb(0 0 0 / 0.03);--menu-pill: rgb(0 0 0 / 0.06);--menu-tile: #ebebea;@@ -765,6 +776,13 @@--menu-surface: #262626;--menu-field: #1e1e1e;--menu-shadow: 0 20px 44px rgb(0 0 0 / 0.28);+ --composer-shadow: 0 1px 1px rgb(0 0 0 / 0.2), 0 2px 4px rgb(0 0 0 / 0.18);+ --composer-border: var(--border);+ --composer-border-focus: var(--border-1);+ --composer-send-bg: var(--foreground);+ --composer-send-fg: var(--foreground-inverse);+ --composer-send-bg-hover: color-mix(in srgb, var(--foreground) 92%, black);+ --composer-send-bg-active: color-mix(in srgb, var(--foreground) 85%, black);--menu-faint: rgb(255 255 255 / 0.03);--menu-pill: rgb(255 255 255 / 0.1);--menu-tile: #333333;diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsxindex f7488b5ac..6a67b22e9 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx@@ -10,7 +10,19 @@ import { cn } from '@renderer/utils/utils';const isLinux = detectPlatform() === 'linux';-export function Titlebar({ leftSlot, rightSlot }: { leftSlot?: ReactNode; rightSlot?: ReactNode }) {+export function Titlebar({+ leftSlot,+ rightSlot,+ className,+ leftClassName,+ rightClassName,+}: {+ leftSlot?: ReactNode;+ rightSlot?: ReactNode;+ className?: string;+ leftClassName?: string;+ rightClassName?: string;+}) {const { setCollapsed, isLeftOpen } = useWorkspaceLayoutContext();return (<header@@ -25,13 +37,19 @@ export function Titlebar({ leftSlot, rightSlot }: { leftSlot?: ReactNode; rightS// covers the views that render no titlebar at all.// Linux draws its own controls flush to the right corner (no native// frame); everywhere else keep the normal right padding.- isLinux ? 'pr-0' : 'pr-[18px]'+ isLinux ? 'pr-0' : 'pr-[18px]',+ className)}>- <div className="pointer-events-auto flex min-w-0 flex-1 items-center gap-1">+ <div className="pointer-events-auto flex min-w-0 flex-1 items-center gap-1 self-stretch">{!isLeftOpen && <div className="[-webkit-app-region:no-drag]"></div>}- <div className="flex w-full items-center justify-between">- <div className="flex items-center justify-start [-webkit-app-region:no-drag]">+ <div className="flex w-full items-center justify-between self-stretch">+ <div+ className={cn(+ 'flex items-center justify-start [-webkit-app-region:no-drag]',+ leftClassName+ )}+ >{!isLeftOpen && (<div className="ml-2 flex items-center gap-0.5 [-webkit-app-region:no-drag]"><Tooltip>@@ -55,7 +73,12 @@ export function Titlebar({ leftSlot, rightSlot }: { leftSlot?: ReactNode; rightS)}{leftSlot}</div>- <div className="flex items-center justify-end [-webkit-app-region:no-drag]">+ <div+ className={cn(+ 'flex items-center justify-end [-webkit-app-region:no-drag]',+ rightClassName+ )}+ >{rightSlot}</div></div>diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-arrow-key-navigation.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-arrow-key-navigation.tsindex 610f93431..45cd5ea7b 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-arrow-key-navigation.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-arrow-key-navigation.ts@@ -1,7 +1,7 @@import { useEffect, useRef, useState } from 'react';import { modalStore } from '@renderer/lib/modal/modal-store';-function isEditableTarget(target: EventTarget | null): boolean {+export function isEditableTarget(target: EventTarget | null): boolean {if (!(target instanceof HTMLElement)) return false;return target.closest('input, textarea, select, [contenteditable], [role="textbox"]') !== null;}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsxindex 17eff91cf..45bb7a8d4 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx@@ -35,13 +35,16 @@ vi.mock('@renderer/features/managed-agents/use-managed-agents', async (importOriuseManagedAgents: () => ({ data: managed.data, isLoading: false }),}));+const roomsData = vi.hoisted(() => ({ rooms: [] as unknown[] }));+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({- switchRoomsStore: { workspacesNotSignedIn: [], readableRoomsInWorkspace: () => [] },+ switchRoomsStore: { workspacesNotSignedIn: [], readableRoomsInWorkspace: () => roomsData.rooms },}));vi.mock('@renderer/features/workspaces/workspaces-store', () => ({workspacesStore: {idOnServerInScope: (serverId: string | null) => (serverId === 'server' ? 'workspace' : null),+ serverIdFor: (workspaceId: string) => (workspaceId === 'workspace' ? 'server' : null),},}));@@ -49,6 +52,12 @@ vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({switchServersStore: { servers: [], statusFor: () => null },}));+const featureFlags = vi.hoisted(() => ({ agent_chats: false }));++vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({+ useFeatureFlags: () => featureFlags,+}));+import { ServerStatTiles } from '@renderer/features/switch-servers/server-stat-tiles';let container: HTMLDivElement | null = null;@@ -56,6 +65,8 @@ let root: Root | null = null;beforeEach(() => {managed.data = undefined;+ roomsData.rooms = [];+ featureFlags.agent_chats = false;vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });});@@ -89,6 +100,10 @@ function agentsTile(el: HTMLElement): HTMLElement {return [...el.querySelectorAll('p')].find((p) => p.textContent === 'Your Agents')!.parentElement!;}+function roomsTile(el: HTMLElement): HTMLElement {+ return [...el.querySelectorAll('p')].find((p) => p.textContent === 'Your Rooms')!.parentElement!;+}+it('counts the agents onboarded on the server', async () => {const tile = agentsTile(await render());expect(tile.querySelectorAll('p')[1].textContent).toBe('2');@@ -99,3 +114,13 @@ it('counts the agents the server runs too, once each, as the Your Agents page liconst tile = agentsTile(await render());expect(tile.querySelectorAll('p')[1].textContent).toBe('4');});++it('hides 1-1 chats when agent_chats flag is on', async () => {+ roomsData.rooms = [+ { channelType: 'direct', bridgeType: null, agentCount: 1 },+ { channelType: 'group', bridgeType: null, agentCount: 2 },+ ];+ featureFlags.agent_chats = true;+ const tile = roomsTile(await render());+ expect(tile.querySelectorAll('p')[1].textContent).toBe('1');+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsxindex b4e50a62c..626214fcd 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx@@ -119,6 +119,10 @@ vi.mock('@renderer/features/switch-servers/server-presentation', () => ({serverStatusLabel: (server: SwitchServer) => `${server.name} status`,}));+vi.mock('@renderer/features/chats/components/chats-offline-note', () => ({+ ChatsOfflineNote: () => null,+}));+vi.mock('@renderer/features/switch-servers/server-icon', () => ({serverIcon: () => () => null,}));diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.tsnew file mode 100644index 000000000..4c5b9aa07--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts@@ -0,0 +1,774 @@+import { describe, expect, it, vi } from 'vitest';+import {+ bindTurns,+ foldTurnEndNotices,+ groupTurns,+ isThinking,+ placeTurns,+ toolState,+ type TurnActivity,+ turnTools,+} from '@renderer/features/chats/activity-join';+import {+ type ActivityApi,+ AgentActivities,+} from '@renderer/features/chats/stores/chat-activity-store';+import {+ type ChatActivityItem,+ type ChatApproval,+ type RoomActivity,+ SERVER_TOO_OLD_FOR_ACTIVITY,+} from '@shared/core/chats/activity';+import type { ChatMessage } from '@shared/core/chats/chats';+import { RpcError } from '@shared/lib/ipc/rpc-error';++let clock = 0;+function row(+ turnId: string,+ itemId: string,+ extra: Partial<ChatActivityItem> = {}+): ChatActivityItem {+ const at = new Date(Date.UTC(2026, 0, 1, 0, 0, clock++)).toISOString();+ return {+ agentId: 'agent-a',+ sessionId: 's1',+ turnId,+ itemId,+ kind: itemId === 'turn' ? 'turn' : 'tool-activity',+ revision: 1,+ status: itemId === 'turn' ? 'running' : 'completed',+ title: '',+ text: '',+ commandId: null,+ roomId: 'room-1',+ threadId: null,+ messageId: `m-${turnId}`,+ occurredAt: at,+ createdAt: at,+ updatedAt: at,+ ...extra,+ };+}++function approval(turnId: string, extra: Partial<ChatApproval> = {}): ChatApproval {+ return {+ agentId: 'agent-a',+ sessionId: 's1',+ requestId: `req-${turnId}`,+ turnId,+ kind: 'approval',+ roomId: 'room-1',+ threadId: null,+ title: 'Run tests?',+ detail: null,+ options: [{ id: 'yes', label: 'Yes', decision: 'accept' }],+ questions: [],+ state: 'open',+ expiresAt: null,+ answer: null,+ answers: null,+ answeredBy: null,+ answeredAt: null,+ ...extra,+ };+}++function turnOf(items: ChatActivityItem[], status: TurnActivity['status']): TurnActivity {+ return {+ sessionId: 's1',+ turnId: 't1',+ status,+ roomId: 'room-1',+ messageId: 'm1',+ items,+ requests: [],+ };+}++describe('placeTurns', () => {+ const said = (messageId: string, agentId: string | null): ChatMessage =>+ ({+ messageId,+ body: messageId,+ sender: { kind: agentId ? 'agent' : 'human', agentId, clientId: agentId ?? 'me' },+ }) as unknown as ChatMessage;+ const turn = (turnId: string, status: TurnActivity['status'] = 'completed'): TurnActivity => ({+ sessionId: 's1',+ turnId,+ status,+ roomId: 'room-1',+ messageId: null,+ items: [],+ requests: [],+ });+ const ids = (placed: Map<string, TurnActivity[]>) =>+ Object.fromEntries([...placed].map(([at, turns]) => [at, turns.map((each) => each.turnId)]));++ it('shows a turn under the message that started it', () => {+ const messages = [said('q1', null), said('r1', 'helper'), said('q2', null)];+ const bound = new Map([+ ['q1', turn('t1')],+ ['q2', turn('t2', 'running')],+ ]);+ expect(ids(placeTurns(messages, 'helper', bound))).toEqual({ q1: ['t1'], q2: ['t2'] });+ });++ it('shows a queued turn under the reply to the turn it waited for', () => {+ const bound = new Map([+ ['q1', turn('t1', 'running')],+ ['q2', turn('t2', 'queued')],+ ]);+ expect(ids(placeTurns([said('q1', null), said('q2', null)], 'helper', bound))).toEqual({+ q1: ['t1'],+ q2: ['t2'],+ });+ const replied = [said('q1', null), said('q2', null), said('r1', 'helper')];+ expect(ids(placeTurns(replied, 'helper', bound))).toEqual({ q1: ['t1'], r1: ['t2'] });+ });++ it('chains turns queued one after another under each reply in turn', () => {+ const messages = [+ said('q1', null),+ said('q2', null),+ said('q3', null),+ said('r1', 'helper'),+ said('other', 'reviewer'),+ said('r2', 'helper'),+ ];+ const bound = new Map([+ ['q1', turn('t1')],+ ['q2', turn('t2')],+ ['q3', turn('t3', 'running')],+ ]);+ expect(ids(placeTurns(messages, 'helper', bound))).toEqual({+ q1: ['t1'],+ r1: ['t2'],+ r2: ['t3'],+ });+ });++ it("shows a turn after the agent's messages sent before its first step", () => {+ const at = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();+ const timed = (message: ChatMessage, second: number) =>+ ({ ...message, sentAt: at(second) }) as ChatMessage;+ const messages = [+ timed(said('q1', null), 0),+ timed(said('ack', 'helper'), 1),+ timed(said('r1', 'helper'), 5),+ ];+ const started = {+ ...turn('t1'),+ items: [row('t1', 'tool', { createdAt: at(3) })],+ };+ expect(ids(placeTurns(messages, 'helper', new Map([['q1', started]])))).toEqual({+ ack: ['t1'],+ });+ // Before its first step, or another agent's message, it stays under the question.+ expect(ids(placeTurns(messages, 'helper', new Map([['q1', turn('t1')]])))).toEqual({+ q1: ['t1'],+ });+ expect(ids(placeTurns(messages, 'reviewer', new Map([['q1', started]])))).toEqual({+ q1: ['t1'],+ });+ });++ it('does not wait on a reply from a turn that ended with an error', () => {+ const messages = [said('q1', null), said('q2', null), said('r2', 'helper')];+ const bound = new Map([+ ['q1', turn('t1', 'error')],+ ['q2', turn('t2')],+ ]);+ expect(ids(placeTurns(messages, 'helper', bound))).toEqual({ q1: ['t1'], q2: ['t2'] });+ });+});++describe('foldTurnEndNotices', () => {+ const said = (messageId: string, agentId: string | null, body = messageId): ChatMessage =>+ ({+ messageId,+ body,+ sender: { kind: agentId ? 'agent' : 'human', agentId, clientId: agentId ?? 'me' },+ }) as unknown as ChatMessage;+ const turn = (turnId: string, status: TurnActivity['status']): TurnActivity => ({+ sessionId: 's1',+ turnId,+ status,+ roomId: 'room-1',+ messageId: null,+ items: [],+ requests: [],+ });+ const interrupted = 'I finished without replying. The turn was interrupted: Claude turn ended';++ it("folds a notice into the agent's last turn when that turn shows the same ending", () => {+ const messages = [+ said('q1', null),+ said('q2', null),+ said('r1', 'helper'),+ said('n2', 'helper', interrupted),+ ];+ const bound = new Map([+ ['q1', turn('t1', 'completed')],+ ['q2', turn('t2', 'interrupted')],+ ]);+ expect(foldTurnEndNotices(messages, 'helper', bound)).toEqual(new Map([['n2', 't2']]));+ });++ it('folds the notice of a stopped turn that a queued turn followed', () => {+ const messages = [+ said('what means second', null),+ said('actually', null),+ said('n1', 'helper', 'I finished without replying. The turn was interrupted: error'),+ ];+ const bound = new Map([+ ['what means second', turn('t1', 'interrupted')],+ ['actually', turn('t2', 'running')],+ ]);+ expect(foldTurnEndNotices(messages, 'helper', bound)).toEqual(new Map([['n1', 't1']]));+ });++ it('gives each stopped turn one notice at most', () => {+ const messages = [+ said('q1', null),+ said('n1', 'helper', interrupted),+ said('q2', null),+ said('n2', 'helper', interrupted),+ said('n3', 'helper', interrupted),+ ];+ const bound = new Map([+ ['q1', turn('t1', 'interrupted')],+ ['q2', turn('t2', 'interrupted')],+ ]);+ expect(foldTurnEndNotices(messages, 'helper', bound)).toEqual(+ new Map([+ ['n1', 't1'],+ ['n2', 't2'],+ ])+ );+ });++ it('keeps a notice whose turn shows no such ending, or is not known', () => {+ const messages = [said('q1', null), said('n1', 'helper', interrupted)];+ expect(+ foldTurnEndNotices(messages, 'helper', new Map([['q1', turn('t1', 'running')]]))+ ).toEqual(new Map());+ expect(foldTurnEndNotices(messages, 'helper', new Map())).toEqual(new Map());+ expect(+ foldTurnEndNotices(messages, 'reviewer', new Map([['q1', turn('t1', 'interrupted')]]))+ ).toEqual(new Map());+ });++ it('does not take a notice as the reply a queued turn waits for', () => {+ const messages = [+ said('q1', null),+ said('q2', null),+ said('n1', 'helper', 'I finished without replying.'),+ said('r2', 'helper'),+ ];+ const bound = new Map([+ ['q1', turn('t1', 'completed')],+ ['q2', turn('t2', 'running')],+ ]);+ expect([...placeTurns(messages, 'helper', bound).keys()]).toEqual(['q1', 'r2']);+ });+});++describe('bindTurns', () => {+ it('joins each turn to the room message its rows name, with its steps and requests', () => {+ const turns = groupTurns(+ [+ row('t1', 'turn', { status: 'completed' }),+ row('t1', 'grep', { title: 'grep' }),+ row('t1', 'reply', { kind: 'assistant-message', text: 'done' }),+ row('t2', 'turn'),+ row('t3', 'turn', { roomId: 'room-2' }),+ row('t4', 'turn', { messageId: null, commandId: 'cmd' }),+ row('t5', 'orphan'),+ ],+ [approval('t2')]+ );+ const bound = bindTurns(turns, 'room-1');+ expect([...bound.keys()]).toEqual(['m-t1', 'm-t2']);+ expect(bound.get('m-t1')!.items.map((each) => each.kind)).toEqual([+ 'tool-activity',+ 'assistant-message',+ ]);+ expect(bound.get('m-t2')!.requests.map((each) => each.requestId)).toEqual(['req-t2']);+ expect(isThinking(bound.get('m-t2')!)).toBe(true);+ expect(isThinking(bound.get('m-t1')!)).toBe(false);+ });++ it('keeps a turn thinking while it has written text but run no tool', () => {+ const turn = turnOf(+ [row('t1', 'draft', { kind: 'assistant-message', text: 'draft' })],+ 'running'+ );+ expect(isThinking(turn)).toBe(true);+ expect(isThinking({ ...turn, items: [row('t1', 'tool')] })).toBe(false);+ });++ it("shows tools only, with Switch's own tools set apart", () => {+ const turn = turnOf(+ [+ row('t1', 'a', { title: 'mcp__switch__read_context' }),+ row('t1', 'b', { title: 'ls -la' }),+ row('t1', 'c', { kind: 'assistant-message', text: 'the answer' }),+ row('t1', 'd', { title: 'mcp__switch__post_message' }),+ ],+ 'completed'+ );+ const { work, switchActions } = turnTools(turn);+ expect(work.map((each) => each.title)).toEqual(['ls -la']);+ expect(switchActions.map((each) => each.title)).toEqual([+ 'mcp__switch__read_context',+ 'mcp__switch__post_message',+ ]);+ });++ it('shows an unfinished tool of an interrupted turn as failed', () => {+ const tool = row('t', 'tool', { status: 'in-progress' });+ expect(toolState(tool, 'running')).toBe('running');+ expect(toolState(tool, 'interrupted')).toBe('failed');+ expect(toolState({ ...tool, status: 'completed' }, 'running')).toBe('done');+ });+});++function rpcError(code: string, message: string, data: Record<string, unknown>): RpcError {+ return new RpcError({ code, message, data } as unknown as ConstructorParameters<+ typeof RpcError+ >[0]);+}++function memoryStorage() {+ const held = new Map<string, string>();+ return {+ held,+ getItem: (key: string) => held.get(key) ?? null,+ setItem: (key: string, value: string) => void held.set(key, value),+ };+}++function fakeApi(snapshots: RoomActivity[]) {+ const reads: string[] = [];+ const controls: unknown[] = [];+ const api: ActivityApi = {+ resolve: async () => ({+ kind: 'unavailable',+ reason: 'not-on-this-machine',+ message: 'Activity not available on this machine.',+ }),+ reasoning: async () => null,+ watchPlacements: () => () => {},+ roomActivity: async (_server, roomId) => {+ reads.push(roomId);+ return snapshots.shift() ?? { items: [], approvals: [] };+ },+ control: async (input) => {+ controls.push(input);+ return 'cmd-1';+ },+ answerApproval: async (input) =>+ approval('t1', { requestId: input.requestId, state: 'answered', answer: 'yes' }),+ };+ return { api, reads, controls };+}++describe('AgentActivities', () => {+ it('reads one snapshot for the agents of a room and keeps them apart', async () => {+ const { api, reads } = fakeApi([+ {+ items: [row('ta', 'turn'), row('tb', 'turn', { agentId: 'agent-b', status: 'completed' })],+ approvals: [],+ },+ ]);+ const activities = new AgentActivities(api, memoryStorage());+ const a = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ const b = activities.acquire('server', 'tenant', 'room-1', 'agent-b');+ await vi.waitFor(() => expect(b.turns().size).toBe(1));+ expect(reads).toEqual(['room-1']);+ expect(a.working).toBe(true);+ expect(a.runningTurn?.turnId).toBe('ta');+ expect(b.working).toBe(false);+ activities.release(a);+ activities.release(b);+ });++ it('merges live rows with the snapshot by revision, dropping stale ones', async () => {+ const snapshotTool = row('t1', 'tool', { revision: 5, title: 'from snapshot' });+ const { api } = fakeApi([{ items: [row('t1', 'turn'), snapshotTool], approvals: [] }]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ // A newer row arrives over the feed before the snapshot is read.+ activities.applyItem('server', { ...snapshotTool, revision: 7, title: 'live' });+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ expect(activity.turns().get('m-t1')!.items[0].title).toBe('live');+ activities.applyItem('server', { ...snapshotTool, revision: 7, title: 'replayed' });+ activities.applyItem('server', { ...snapshotTool, revision: 6, title: 'stale' });+ expect(activity.turns().get('m-t1')!.items[0].title).toBe('live');+ activities.applyItem('server', { ...snapshotTool, revision: 8, title: 'newer' });+ expect(activity.turns().get('m-t1')!.items[0].title).toBe('newer');+ activities.applyItem('server', row('t1', 'other-room', { roomId: 'room-2' }));+ expect(activity.turns().get('m-t1')!.items).toHaveLength(1);+ activities.release(activity);+ });++ it('reads every shown room again on resync, and says when a read fails', async () => {+ const { api, reads } = fakeApi([+ { items: [], approvals: [] },+ { items: [row('t1', 'turn', { status: 'completed' })], approvals: [] },+ ]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await vi.waitFor(() => expect(reads).toEqual(['room-1']));+ activities.resync('server');+ activities.resync('other-server');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ expect(reads).toEqual(['room-1', 'room-1']);+ api.roomActivity = async () => {+ throw new Error('Switch did not answer.');+ };+ await activities.loadRoom('server', 'room-1');+ expect(activity.feedError).toContain('Switch did not answer.');+ activities.release(activity);+ });++ it('never reopens an answered request from an older copy', async () => {+ const { api } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await activities.loadRoom('server', 'room-1');+ activities.applyItem('server', row('t1', 'turn'));+ activities.applyApproval('server', approval('t1'));+ await activity.answer(approval('t1'), { answer: 'yes' });+ activities.applyApproval('server', approval('t1'));+ expect(activity.turns().get('m-t1')!.requests[0]).toMatchObject({+ state: 'answered',+ answer: 'yes',+ });+ activities.release(activity);+ });++ it('keeps a settled request settled when a resync snapshot still has it open', async () => {+ const { api } = fakeApi([+ { items: [row('t1', 'turn')], approvals: [] },+ { items: [row('t1', 'turn')], approvals: [approval('t1'), approval('t2')] },+ ]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ activities.applyApproval('server', approval('t1', { state: 'expired' }));+ await activities.loadRoom('server', 'room-1');+ expect(activity.turns().get('m-t1')!.requests[0].state).toBe('expired');+ expect(activity.approvals.size).toBe(2);+ activities.applyApproval('server', approval('t1', { state: 'closed' }));+ expect(activity.turns().get('m-t1')!.requests[0].state).toBe('closed');+ activities.release(activity);+ });++ it('posts Stop to the room and holds its command id as requested', async () => {+ const { api, controls } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await activity.control('interrupt');+ expect(controls).toEqual([+ {+ serverId: 'server',+ roomId: 'room-1',+ requestId: activity.controls[0].requestId,+ agentId: 'agent-a',+ command: 'interrupt',+ },+ ]);+ expect(activity.controls[0]).toMatchObject({ state: 'requested', commandId: 'cmd-1' });+ api.control = async () => {+ throw rpcError('ChatApiError', 'That agent is not in this chat.', {+ apiCode: 'NOT_A_MEMBER',+ });+ };+ await activity.control('reset');+ expect(activity.controls).toHaveLength(1);+ expect(activity.controls[0]).toMatchObject({ command: 'reset', state: 'failed' });+ expect(activity.controls[0].error).toContain('That agent is not in this chat.');+ activities.release(activity);+ });++ it('keeps the request id of a command whose answer was lost until a retry settles it', async () => {+ const { api, controls } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ const sent = () => (controls as { requestId: string }[]).map((input) => input.requestId);+ api.control = async (input) => {+ controls.push(input);+ throw rpcError('GatewayError', 'socket hang up', { kind: 'network' });+ };+ await activity.control('reset');+ expect(activity.controls[0]).toMatchObject({ state: 'unknown' });+ // A second click, the Retry button and a feed reconnect all reuse the request id.+ await activity.control('reset');+ await activity.retryControl(activity.controls[0].requestId);+ activity.dismissControl(activity.controls[0].requestId);+ expect(activity.controls).toHaveLength(1);+ api.control = async (input) => {+ controls.push(input);+ return 'cmd-1';+ };+ activities.resync('server');+ await vi.waitFor(() => expect(activity.controls[0]).toMatchObject({ state: 'requested' }));+ expect(new Set(sent()).size).toBe(1);+ expect(sent()).toHaveLength(4);+ // Settled: the next Reset is a new request.+ await activity.control('reset');+ expect(new Set(sent()).size).toBe(2);+ activities.release(activity);+ });++ it('keeps the request id of a lost command across leaving and reopening the chat', async () => {+ const { api, controls } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const sent = () => (controls as { requestId: string }[]).map((input) => input.requestId);+ api.control = async (input) => {+ controls.push(input);+ throw rpcError('GatewayError', 'socket hang up', { kind: 'network' });+ };+ const first = activities.acquire('server', null, 'room-1', 'agent-a');+ await first.control('reset');+ activities.release(first);+ const reopened = activities.acquire('server', null, 'room-1', 'agent-a');+ expect(reopened.controls[0]).toMatchObject({ state: 'unknown' });+ await reopened.control('reset');+ expect(new Set(sent()).size).toBe(1);+ activities.release(reopened);+ });++ it('keeps the request id of a command still sending when the chat closes', async () => {+ const { api, controls } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const sent = () => (controls as { requestId: string }[]).map((input) => input.requestId);+ let fail!: (error: unknown) => void;+ api.control = (input) => {+ controls.push(input);+ return new Promise((_resolve, reject) => (fail = reject));+ };+ const first = activities.acquire('server', null, 'room-1', 'agent-a');+ const pending = first.control('reset');+ activities.release(first);+ fail(rpcError('GatewayError', 'socket hang up', { kind: 'network' }));+ await pending;+ const reopened = activities.acquire('server', null, 'room-1', 'agent-a');+ expect(reopened.controls[0]).toMatchObject({ state: 'unknown' });+ api.control = async (input) => {+ controls.push(input);+ return 'cmd-1';+ };+ await reopened.control('reset');+ expect(new Set(sent()).size).toBe(1);+ activities.release(reopened);+ });++ it('does not bring back a parked command that settled after the chat closed', async () => {+ const { api } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ let answer!: (commandId: string) => void;+ api.control = () => new Promise((resolve) => (answer = resolve));+ const first = activities.acquire('server', null, 'room-1', 'agent-a');+ const pending = first.control('reset');+ activities.release(first);+ answer('cmd-1');+ await pending;+ const reopened = activities.acquire('server', null, 'room-1', 'agent-a');+ expect(reopened.controls).toHaveLength(0);+ activities.release(reopened);+ });++ it('settles a lost command after a reload, and forgets it on drop', async () => {+ const { api, controls } = fakeApi([]);+ const storage = memoryStorage();+ const sent = () => (controls as { requestId: string }[]).map((input) => input.requestId);+ let fail!: (error: unknown) => void;+ api.control = async (input) => {+ controls.push(input);+ if (input.command === 'compact') return new Promise((_resolve, reject) => (fail = reject));+ throw rpcError('GatewayError', 'socket hang up', { kind: 'network' });+ };+ const before = new AgentActivities(api, storage);+ const first = before.acquire('server', 't', 'room-1', 'agent-a');+ await first.control('reset');+ void first.control('compact');+ await vi.waitFor(() => expect(first.controls).toHaveLength(2));++ // The window reloads: Reset is still unknown and Compact, mid-send, comes back unknown.+ const after = new AgentActivities(api, storage);+ const reopened = after.acquire('server', 't', 'room-1', 'agent-a');+ expect(reopened.controls.map((control) => [control.command, control.state])).toEqual([+ ['reset', 'unknown'],+ ['compact', 'unknown'],+ ]);+ api.control = async (input) => {+ controls.push(input);+ return 'cmd-1';+ };+ await reopened.control('reset');+ expect(new Set(sent()).size).toBe(2);+ expect(storage.held.get('switch-console.chat-controls')).not.toContain('reset');++ after.drop('server', null);+ expect(storage.held.get('switch-console.chat-controls')).toBe('[]');+ fail(rpcError('GatewayError', 'socket hang up', { kind: 'network' }));+ });++ it('shows only the outcome of the command settled last', async () => {+ const { api } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await activity.control('interrupt');+ await activity.control('interrupt');+ expect(activity.controls).toHaveLength(1);+ api.control = async () => {+ throw rpcError('GatewayError', 'socket hang up', { kind: 'network' });+ };+ await activity.control('reset');+ expect(activity.controls.map((control) => control.state)).toEqual(['requested', 'unknown']);+ activities.release(activity);+ });++ it('says plainly when the server predates chat activity', async () => {+ const { api } = fakeApi([]);+ const tooOld = () =>+ rpcError('GatewayError', 'Switch gateway returned 404', {+ kind: 'http',+ status: 404,+ });+ api.roomActivity = async () => {+ throw tooOld();+ };+ api.control = async () => {+ throw tooOld();+ };+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.feedError).toBe(SERVER_TOO_OLD_FOR_ACTIVITY));+ await activity.control('reset');+ expect(activity.controls[0]).toMatchObject({+ state: 'failed',+ error: SERVER_TOO_OLD_FOR_ACTIVITY,+ });+ activities.release(activity);+ });++ it('forgets a lost command when the server or room is dropped', async () => {+ const { api } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ api.control = async () => {+ throw rpcError('GatewayError', 'socket hang up', { kind: 'network' });+ };+ for (const drop of [+ () => activities.drop('server', null),+ () => activities.drop('server', 'room-1'),+ ]) {+ const first = activities.acquire('server', null, 'room-1', 'agent-a');+ await first.control('reset');+ activities.release(first);+ drop();+ const reopened = activities.acquire('server', null, 'room-1', 'agent-a');+ expect(reopened.controls).toHaveLength(0);+ activities.release(reopened);+ }+ });++ it('ignores the answer of a snapshot read that a newer read or a drop superseded', async () => {+ const { api } = fakeApi([]);+ const activities = new AgentActivities(api, memoryStorage());+ const running: RoomActivity = { items: [row('t1', 'turn')], approvals: [] };+ const empty: RoomActivity = { items: [], approvals: [] };+ const first = activities.acquire('server', null, 'room-1', 'agent-a');+ await new Promise((resolve) => setTimeout(resolve, 0));+ const pending: { resolve: (a: RoomActivity) => void; reject: (e: unknown) => void }[] = [];+ api.roomActivity = () => new Promise((resolve, reject) => pending.push({ resolve, reject }));++ // A newer read answers first: the older one's answer and error are both ignored.+ const older = activities.loadRoom('server', 'room-1');+ const failing = activities.loadRoom('server', 'room-1');+ const newer = activities.loadRoom('server', 'room-1');+ pending[2].resolve(empty);+ await newer;+ pending[0].resolve(running);+ pending[1].reject(new Error('late failure'));+ await Promise.all([older, failing]);+ expect(first.working).toBe(false);+ expect(first.feedError).toBeNull();++ // A read from before a drop never reaches the activity acquired after it.+ const beforeDrop = activities.loadRoom('server', 'room-1');+ activities.drop('server', null);+ api.roomActivity = async () => empty;+ const current = activities.acquire('server', null, 'room-1', 'agent-a');+ await new Promise((resolve) => setTimeout(resolve, 0));+ pending[3].resolve(running);+ await beforeDrop;+ expect(current.items.size).toBe(0);+ activities.release(current);+ });++ it('drops rows and settled requests a snapshot no longer has, keeping live ones from during the read', async () => {+ const { api } = fakeApi([+ { items: [row('t1', 'turn')], approvals: [approval('t1', { state: 'answered' })] },+ ]);+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.working).toBe(true));+ expect(activity.approvals.size).toBe(1);+ let release!: (snapshot: RoomActivity) => void;+ api.roomActivity = () => new Promise((resolve) => (release = resolve));+ const load = activities.loadRoom('server', 'room-1');+ // Arrives over the live feed while the snapshot is read; the snapshot predates it.+ activities.applyItem('server', row('t2', 'turn'));+ activities.applyApproval('server', approval('t2'));+ release({ items: [], approvals: [] });+ await load;+ expect(activity.allTurns.map((turn) => turn.turnId)).toEqual(['t2']);+ expect([...activity.approvals.values()].map((each) => each.turnId)).toEqual(['t2']);+ activities.release(activity);+ });++ it('says the activity feed is down until it is live again', () => {+ const activities = new AgentActivities(fakeApi([]).api, memoryStorage());+ activities.feedState('server', 'offline', 'The server closed the activity feed.');+ expect(activities.feedDown.get('server')).toBe('The server closed the activity feed.');+ activities.feedState('server', 'live', null);+ expect(activities.feedDown.has('server')).toBe(false);+ });++ it('reads reasoning and tool details from a local host for its own session only', async () => {+ const tool = {+ itemId: '["t1","tool"]',+ type: 'tool_call',+ toolName: 'Read',+ input: { file_path: '/a.ts' },+ output: 'x',+ truncated: false,+ exitCode: null,+ };+ const asked: string[][] = [];+ const { api } = fakeApi([]);+ api.resolve = async () => ({+ kind: 'session',+ target: 'local',+ hostAgentKey: 'console-a',+ sessionId: 's1',+ });+ api.reasoning = async (_key, _session, turnIds) => {+ asked.push(turnIds ?? []);+ return { epoch: 'e1', turns: [], tools: [{ turnId: 't1', tools: [tool] }] };+ };+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', null, 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.target?.kind).toBe('session'));+ await activity.readReasoning([+ { ...turnOf([], 'completed'), turnId: 't1' },+ { ...turnOf([], 'completed'), turnId: 't0', sessionId: 'older-session' },+ ]);+ expect(asked).toEqual([['t1']]);+ expect(activity.toolDetails.get(tool.itemId)).toEqual(tool);+ activities.release(activity);+ });+});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.tsnew file mode 100644index 000000000..b12ac98e0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';+import { agentConversations } from '@renderer/features/chats/agent-conversations';+import type { ChatSummary } from '@shared/core/chats/chats';+import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';++const agent = (id: string, name: string, displayName: string | null = null) => ({+ id,+ name,+ displayName,+ iconUrl: null,+ provider: null,+});++const summary = (overrides: Partial<ChatSummary>): ChatSummary => ({+ roomId: 'r',+ name: 'Chat with helper',+ channelType: 'direct',+ bridgeType: null,+ channelName: null,+ agents: [],+ canManage: false,+ ownsAgent: false,+ lastMessage: null,+ ...overrides,+});++describe('agentConversations', () => {+ const room = (roomId: string, roomName: string, archived = false): RemoteAgentRoom => ({+ roomId,+ roomName,+ archived,+ status: 'live',+ roomRole: null,+ });++ it('puts unbridged direct chats under Direct chats and every other room under Rooms', () => {+ const direct = summary({ roomId: 'dm', agents: [agent('a', 'alpha')] });+ const slackDm = summary({ roomId: 'slack-dm', bridgeType: 'slack' });+ 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)]+ );+ expect(split.direct.map((chat) => chat.roomId)).toEqual(['dm']);+ expect(split.rooms.map((each) => each.roomId)).toEqual(['slack-dm', 'team']);+ });++ 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], []);+ expect(split.direct).toEqual([]);+ expect(split.rooms).toEqual([{ roomId: 'pair', roomName: 'Chat with helper' }]);+ });++ it('puts a chat with several agents under Rooms when its membership does not list it', () => {+ const group = summary({+ roomId: 'group',+ name: 'Try me',+ channelType: 'channel_private',+ agents: [agent('a', 'alpha'), agent('b', 'beta')],+ });+ const split = agentConversations([group], [room('team', 'team')]);+ expect(split.direct).toEqual([]);+ expect(split.rooms).toEqual([+ { roomId: 'team', roomName: 'team', archived: false, status: 'live', roomRole: null },+ { roomId: 'group', roomName: 'Try me' },+ ]);+ });+});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.tsnew file mode 100644index 000000000..b1e305eac--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-console-route.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';+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", () => {+ expect(consoleChatRoute('s', 'r', helper, true)).toEqual({+ viewId: 'managedAgent',+ params: { serverId: 's', agentId: 'agent-1', name: 'Helper', roomId: 'r' },+ });+ });++ it('opens any other agent’s chat on its own', () => {+ expect(consoleChatRoute('s', 'r', helper, false)).toEqual({+ viewId: 'chat',+ params: { serverId: 's', roomId: 'r', agentId: 'agent-1' },+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-follow-bottom.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-follow-bottom.test.tsnew file mode 100644index 000000000..ba8d50098--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-follow-bottom.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import {+ distanceFromBottom,+ FOLLOW_BOTTOM_THRESHOLD_PX,+ isAtBottom,+ keepsFollowing,+} from '@renderer/features/chats/ui/follow-bottom';++describe('follow-bottom', () => {+ it('measures the distance left to scroll', () => {+ expect(distanceFromBottom({ scrollTop: 0, scrollHeight: 1000, clientHeight: 400 })).toBe(600);+ expect(distanceFromBottom({ scrollTop: 600, scrollHeight: 1000, clientHeight: 400 })).toBe(0);+ });++ it('never reports a negative distance when content is shorter than the viewport', () => {+ expect(distanceFromBottom({ scrollTop: 0, scrollHeight: 200, clientHeight: 400 })).toBe(0);+ });++ it('keeps following within the threshold, including fractional pixels', () => {+ const threshold = FOLLOW_BOTTOM_THRESHOLD_PX;+ expect(isAtBottom({ scrollTop: 599.5, scrollHeight: 1000, clientHeight: 400 }, threshold)).toBe(+ true+ );+ expect(+ isAtBottom({ scrollTop: 600 - threshold, scrollHeight: 1000, clientHeight: 400 }, threshold)+ ).toBe(true);+ });++ it('stops following once the reader scrolls up past the threshold', () => {+ const threshold = FOLLOW_BOTTOM_THRESHOLD_PX;+ expect(+ isAtBottom(+ { scrollTop: 600 - threshold - 1, scrollHeight: 1000, clientHeight: 400 },+ threshold+ )+ ).toBe(false);+ });++ it('stops following when content grows under a reader who is not at the bottom', () => {+ expect(isAtBottom({ scrollTop: 600, scrollHeight: 1400, clientHeight: 400 }, 32)).toBe(false);+ });++ it('keeps following when its own stick is reported after more content landed', () => {+ const late = { scrollTop: 2819, scrollHeight: 3601, clientHeight: 698 };+ expect(keepsFollowing(late, 1151, true, 32)).toBe(true);+ });++ it('stops following only when the reader moves up', () => {+ const above = { scrollTop: 500, scrollHeight: 1400, clientHeight: 400 };+ expect(keepsFollowing(above, 900, true, 32)).toBe(false);+ expect(keepsFollowing(above, 500, false, 32)).toBe(false);+ });++ it('resumes following at the end', () => {+ expect(+ keepsFollowing({ scrollTop: 1000, scrollHeight: 1400, clientHeight: 400 }, 0, false, 32)+ ).toBe(true);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-markdown.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-markdown.test.tsnew file mode 100644index 000000000..f4632193e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-markdown.test.ts@@ -0,0 +1,50 @@+import React from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it, vi } from 'vitest';+import { ChatMarkdown } from '@renderer/features/chats/ui/chat-markdown';++vi.mock('@renderer/lib/hooks/useTheme', () => ({+ useTheme: () => ({ effectiveTheme: 'emlight' }),+}));++vi.mock('@renderer/lib/open-external-link', () => ({+ confirmOpenExternalLink: vi.fn(),+}));++function render(markdown: string): string {+ return renderToStaticMarkup(React.createElement(ChatMarkdown, null, markdown));+}++describe('ChatMarkdown', () => {+ it('renders markdown', () => {+ const html = render('Hello **world**');+ expect(html).toContain('<strong');+ expect(html).toContain('world');+ });++ it('shows raw HTML from the message as text instead of rendering it', () => {+ const html = render('before <img src="x" onerror="alert(1)"> <script>alert(2)</script> after');+ expect(html).not.toContain('<img');+ expect(html).not.toContain('<script');+ expect(html).toContain('<script>');+ });++ it('does not render a block of raw HTML either', () => {+ const html = render(+ 'text\n\n<div onclick="alert(1)"><iframe src="https://example.com"></iframe></div>\n\nmore'+ );+ expect(html).not.toContain('<iframe');+ expect(html).not.toContain('<div onclick');+ });++ it('does not render a javascript: link as a live href', () => {+ const html = render('[click](javascript:alert(1))');+ expect(html).not.toContain('href="javascript:');+ });++ it('renders a fenced block through the chat code block', () => {+ const html = render('```ts\nconst a = 1;\n```');+ expect(html).toContain('data-slot="code-block"');+ expect(html).toContain('ts');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-session-starting.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-session-starting.test.tsnew file mode 100644index 000000000..2225dff0c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-session-starting.test.ts@@ -0,0 +1,121 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import {+ type ChatMessage,+ liveSessionStartingNotices,+ SESSION_STARTING_MESSAGE,+ TURN_FAILED_PHRASE,+ TURN_INTERRUPTED_PHRASE,+ turnEndNotice,+ UNPOSTED_REPLY_MESSAGE,+} from '@shared/core/chats/chats';++function message(messageId: string, clientId: string, body: string): ChatMessage {+ return {+ messageId,+ body,+ sender: { clientId, name: clientId, kind: 'agent', agentId: clientId, userId: null },+ } as unknown as ChatMessage;+}++function ask(messageId: string): ChatMessage {+ return {+ messageId,+ body: 'please help',+ sender: { clientId: 'me', name: 'me', kind: 'human', agentId: null, userId: 'me' },+ } as unknown as ChatMessage;+}++const noTurns = new Map<string, Set<string>>();++describe('session-starting notices', () => {+ it('shows a notice while it is the latest message from its agent', () => {+ const messages = [+ message('$ask', 'helper', 'hi'),+ message('$start', 'helper', SESSION_STARTING_MESSAGE),+ message('$other', 'reviewer', 'unrelated'),+ ];+ expect(liveSessionStartingNotices(messages, noTurns)).toEqual(new Set(['$start']));+ });++ it('hides a notice once its agent posts again', () => {+ const messages = [+ message('$start', 'helper', SESSION_STARTING_MESSAGE),+ message('$reply', 'helper', 'Here is the answer.'),+ ];+ expect(liveSessionStartingNotices(messages, noTurns)).toEqual(new Set());+ });++ it('hides a notice once its agent shows a turn for the message it answers', () => {+ const messages = [ask('$ask'), message('$start', 'helper', SESSION_STARTING_MESSAGE)];+ const turns = new Map([['$ask', new Set(['helper'])]]);+ expect(liveSessionStartingNotices(messages, turns)).toEqual(new Set());+ });++ it('keeps a notice while only another agent or an earlier turn shows activity', () => {+ const messages = [+ ask('$old'),+ message('$reply', 'helper', 'Done.'),+ ask('$ask'),+ message('$start', 'helper', SESSION_STARTING_MESSAGE),+ ];+ const turns = new Map([+ ['$old', new Set(['helper'])],+ ['$ask', new Set(['reviewer'])],+ ]);+ expect(liveSessionStartingNotices(messages, turns)).toEqual(new Set(['$start']));+ });++ it('matches the text the host posts', () => {+ const source = readFileSync(+ join(__dirname, '../../../../../packages/agent-providers/src/host/watcher-tools.ts'),+ 'utf8'+ );+ expect(source).toContain(`SESSION_STARTING_MESSAGE = '${SESSION_STARTING_MESSAGE}'`);+ });+});++describe('turn-end notices', () => {+ it('reads how the turn ended and why', () => {+ const read = (body: string) => turnEndNotice(message('$n', 'helper', body));+ expect(+ read(+ 'I finished without replying. The turn was interrupted: Claude turn ended: error_during_execution'+ )+ ).toEqual({ outcome: 'interrupted', reason: null });+ expect(read('I finished without replying. The turn failed: Not signed in.')).toEqual({+ outcome: 'failed',+ reason: 'Not signed in.',+ });+ expect(read('I finished without replying. The turn failed.')).toEqual({+ outcome: 'failed',+ reason: null,+ });+ expect(read('I finished without replying.')).toEqual({ outcome: 'completed', reason: null });+ });++ it('leaves other messages alone', () => {+ expect(+ turnEndNotice(+ message('$n', 'helper', 'I finished without posting a reply. My last words were:\n\nHi')+ )+ ).toBeNull();+ expect(+ turnEndNotice(message('$n', 'helper', 'I finished without replying. Then more.'))+ ).toBeNull();+ expect(turnEndNotice(ask('$n'))).toBeNull();+ });++ it('matches the text the host posts', () => {+ const source = readFileSync(+ join(__dirname, '../../../../../packages/agent-providers/src/host/session-host.ts'),+ 'utf8'+ );+ expect(source).toContain(`'${UNPOSTED_REPLY_MESSAGE}'`);+ expect(source).toContain(`\`${UNPOSTED_REPLY_MESSAGE} \${failure}\``);+ expect(source).toContain(`\`${TURN_FAILED_PHRASE}\${reason}\``);+ expect(source).toContain(`\`${TURN_INTERRUPTED_PHRASE}\${reason}\``);+ expect(source).toContain("? `: ${cap(detail.trim(), 1000)}` : '.'");+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-threads.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-threads.test.tsnew file mode 100644index 000000000..9aca0124e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-threads.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';+import { messageAnchorId, snippetOf, threadChip } from '@renderer/features/chats/chat-threads';+import type { ChatMessage } from '@shared/core/chats/chats';++const root = {+ messageId: '$root',+ body: 'Can you check why the controller\ncrash-loops after the upgrade?',+ attachments: [],+} as unknown as ChatMessage;++describe('thread chips', () => {+ it('names the message a reply answers', () => {+ const chip = threadChip({ threadRootId: '$root', messageId: '$reply' }, (id) =>+ id === '$root' ? root : undefined+ );+ expect(chip).toEqual({+ rootId: '$root',+ snippet: 'Can you check why the controller crash-loops after the upgrade?',+ label: '↳ reply to Can you check why the controller crash-loops after the upgrade?',+ });+ });++ it('says so when the root is older than what is loaded', () => {+ expect(+ threadChip({ threadRootId: '$gone', messageId: '$reply' }, () => undefined)+ ).toMatchObject({+ snippet: null,+ label: '↳ reply to an earlier message',+ });+ });++ it('shows no chip for a message outside a thread or for the root itself', () => {+ expect(threadChip({ threadRootId: null, messageId: '$m' }, () => root)).toBeNull();+ expect(threadChip({ threadRootId: '$root', messageId: '$root' }, () => root)).toBeNull();+ });++ it('cuts long text and falls back to the file name', () => {+ expect(snippetOf({ body: 'x'.repeat(200), attachments: [] })).toHaveLength(80);+ expect(+ snippetOf({+ body: ' ',+ attachments: [+ { uri: 'u', filename: 'log.txt', mimetype: 'text/plain', size: 1, msgtype: 'm.file' },+ ],+ })+ ).toBe('log.txt');+ expect(messageAnchorId('$a:b')).toBe('chat-message-_a_b');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.tsnew file mode 100644index 000000000..8b36343fe--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts@@ -0,0 +1,197 @@+import { describe, expect, it, vi } from 'vitest';+import {+ ChatTimeline,+ type ChatFile,+ type TimelineApi,+} from '@renderer/features/chats/stores/chat-timeline-store';+import type { ChatMessage } from '@shared/core/chats/chats';+import { RpcError } from '@shared/lib/ipc/rpc-error';++function message(seq: number, extra: Partial<ChatMessage> = {}): ChatMessage {+ return {+ messageId: `m${seq}`,+ seq,+ roomId: 'room-1',+ sentAt: '2026-01-01T00:00:00Z',+ sender: { clientId: 'c', name: 'Ada', kind: 'human', agentId: null, userId: 'u' },+ source: 'console',+ body: `body ${seq}`,+ format: null,+ threadRootId: null,+ attachments: [],+ clientTxn: null,+ ...extra,+ };+}++const apiError = (apiCode: string, message: string) =>+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'ChatApiError',+ message,+ data: { apiCode, status: 409 },+ });+const networkError = () =>+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: 'Could not reach the server',+ data: { kind: 'network' },+ });++function api(overrides: Partial<TimelineApi> = {}) {+ let id = 0;+ const calls = { send: [] as Parameters<TimelineApi['send']>[1][], upload: [] as string[] };+ const value: TimelineApi = {+ messages: async () => ({ messages: [], headSeq: 0, hasMore: false }),+ upload: async (_room, file) => {+ calls.upload.push(file.uploadId);+ return {+ uploadId: file.uploadId,+ uri: 'mxc://x',+ filename: file.name,+ mimetype: file.mimeType,+ size: 1,+ };+ },+ send: async (_room, input) => {+ calls.send.push(input);+ return [message(10, { clientTxn: `${input.requestId}:0` })];+ },+ newId: () => `id-${++id}`,+ ...overrides,+ };+ return { value, calls };+}++const file = (name: string): ChatFile => ({+ name,+ type: 'text/plain',+ size: 1,+ read: async () => 'eA==',+});+const input = (files: ChatFile[] = []) => ({+ body: 'hello',+ threadRootId: null,+ files,+});++describe('ChatTimeline', () => {+ it('orders by sequence and keeps one copy of each message', () => {+ const timeline = new ChatTimeline('room-1', api().value);+ timeline.apply(message(3));+ timeline.apply(message(1));+ timeline.apply(message(2));+ timeline.apply(message(2));+ timeline.apply(message(4, { roomId: 'other' }));+ expect(timeline.messages.map((each) => each.seq)).toEqual([1, 2, 3]);+ });++ it('retires a send when its echo arrives', async () => {+ const { value } = api();+ const timeline = new ChatTimeline('room-1', value);+ const requestId = timeline.send(input());+ expect(timeline.pending[0]).toMatchObject({ requestId, state: 'sending' });+ await vi.waitFor(() => expect(timeline.pending).toHaveLength(0));+ expect(timeline.messages.map((each) => each.clientTxn)).toEqual([`${requestId}:0`]);+ });++ it('reconciles on the feed echo before the send answers', async () => {+ let answer!: (messages: ChatMessage[]) => void;+ const { value } = api({ send: () => new Promise((resolve) => (answer = resolve)) });+ const timeline = new ChatTimeline('room-1', value);+ const requestId = timeline.send(input());+ await vi.waitFor(() => expect(answer).toBeDefined());+ timeline.apply(message(7, { clientTxn: `${requestId}:0` }));+ expect(timeline.pending).toHaveLength(0);+ answer([message(7, { clientTxn: `${requestId}:0` })]);+ await Promise.resolve();+ expect(timeline.messages).toHaveLength(1);+ });++ it('keeps an uncertain send as failed and retries it with the same request id', async () => {+ let fail = true;+ const sent: string[] = [];+ const { value } = api({+ send: async (_room, request) => {+ sent.push(request.requestId);+ if (fail) throw networkError();+ return [message(11, { clientTxn: `${request.requestId}:0` })];+ },+ });+ const timeline = new ChatTimeline('room-1', value);+ const requestId = timeline.send(input());+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));+ expect(timeline.pending[0]).toMatchObject({ uncertain: true, posted: true });+ fail = false;+ timeline.retry(requestId);+ await vi.waitFor(() => expect(timeline.pending).toHaveLength(0));+ expect(sent).toEqual([requestId, requestId]);+ });++ it('marks a reused request id as a conflict', async () => {+ const { value } = api({+ send: async () => {+ throw apiError('REQUEST_REUSED', 'This request id was used for another message.');+ },+ });+ const timeline = new ChatTimeline('room-1', value);+ timeline.send(input());+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('conflict'));+ expect(timeline.pending[0]?.uncertain).toBe(false);+ });++ it('reports each refused file and sends the rest once they are dropped', async () => {+ const { value, calls } = api({+ upload: async (_room, upload) => {+ if (upload.name === 'big.bin') throw apiError('FILE_TOO_LARGE', 'Too large');+ return {+ uploadId: upload.uploadId,+ uri: 'mxc://x',+ filename: upload.name,+ mimetype: 'text/plain',+ size: 1,+ };+ },+ });+ const timeline = new ChatTimeline('room-1', value);+ const requestId = timeline.send(input([file('ok.txt'), file('big.bin')]));+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));+ expect(timeline.pending[0]?.error).toBe('big.bin could not be attached: Too large');+ expect(timeline.pending[0]?.files.map((each) => each.state)).toEqual(['uploaded', 'refused']);+ expect(timeline.pending[0]?.posted).toBe(false);+ expect(calls.send).toHaveLength(0);++ timeline.dropRefusedFiles(requestId);+ await vi.waitFor(() => expect(timeline.pending).toHaveLength(0));+ expect(calls.send).toHaveLength(1);+ expect(calls.send[0]!.requestId).toBe(requestId);+ expect(calls.send[0]!.uploadIds).toHaveLength(1);+ });++ it('drops everything and locks when access is lost', async () => {+ const { value } = api({+ send: async () => {+ throw apiError('NOT_A_MEMBER', 'Not a member');+ },+ });+ const timeline = new ChatTimeline('room-1', value);+ timeline.apply(message(1));+ timeline.send(input());+ await vi.waitFor(() => expect(timeline.accessLost).toBe(true));+ expect(timeline.messages).toHaveLength(0);+ expect(timeline.pending).toHaveLength(0);+ });++ it('says a non-member cannot read the room', async () => {+ const { value } = api({+ messages: async () => {+ throw apiError('NOT_A_MEMBER', 'Not a member');+ },+ });+ const timeline = new ChatTimeline('room-1', value);+ await timeline.load();+ expect(timeline.notMember).toBe(true);+ expect(timeline.loadError).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.tsnew file mode 100644index 000000000..854675816--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from 'vitest';+import { ChatTitler } from '@renderer/features/chats/stores/chat-titler';+import type { ChatSummary } from '@shared/core/chats/chats';++function summary(roomId: string, channelType: ChatSummary['channelType'] = 'direct'): ChatSummary {+ return {+ roomId,+ name: 'Chat with ada',+ channelType,+ bridgeType: null,+ channelName: null,+ agents: [{ id: 'a1', name: 'ada', displayName: null, iconUrl: null, provider: null }],+ canManage: true,+ ownsAgent: false,+ lastMessage: null,+ };+}++function setup(title: () => Promise<string>) {+ const chats = new Map<string, ChatSummary>();+ const deps = {+ title: vi.fn(title),+ rename: vi.fn(async () => {}),+ chat: (roomId: string) => chats.get(roomId),+ add: vi.fn((_serverId: string, chat: ChatSummary) => void chats.set(chat.roomId, chat)),+ warn: vi.fn(),+ };+ return { chats, deps, titler: new ChatTitler(deps) };+}++describe('ChatTitler', () => {+ it('names an unnamed direct chat from its first message, once', async () => {+ const { chats, deps, titler } = setup(async () => 'Arm build failure');+ chats.set('r1', summary('r1'));+ titler.created(summary('r1'), false);+ await titler.sent('s1', 'r1', 'why does the arm build fail?');+ await titler.sent('s1', 'r1', 'second message');+ expect(deps.title).toHaveBeenCalledOnce();+ expect(deps.rename).toHaveBeenCalledWith('s1', 'r1', 'Arm build failure');+ expect(chats.get('r1')?.name).toBe('Arm build failure');+ });++ it('leaves a named chat, a channel and a chat not created here alone', async () => {+ const { chats, deps, titler } = setup(async () => 'Title');+ for (const id of ['named', 'channel', 'elsewhere']) chats.set(id, summary(id));+ titler.created(summary('named'), true);+ titler.created(summary('channel', 'channel_private'), false);+ for (const id of ['named', 'channel', 'elsewhere']) await titler.sent('s1', id, 'hello');+ expect(deps.title).not.toHaveBeenCalled();+ });++ it('waits for a message with text', async () => {+ const { chats, deps, titler } = setup(async () => 'Title');+ chats.set('r1', summary('r1'));+ titler.created(summary('r1'), false);+ await titler.sent('s1', 'r1', ' ');+ await titler.sent('s1', 'r1', 'hello');+ expect(deps.title).toHaveBeenCalledWith('hello');+ });++ it('keeps a name the user gave while the title was written', async () => {+ const { chats, deps, titler } = setup(async () => {+ chats.set('r1', { ...summary('r1'), name: 'Mine' });+ return 'Generated';+ });+ chats.set('r1', summary('r1'));+ titler.created(summary('r1'), false);+ await titler.sent('s1', 'r1', 'hello');+ expect(deps.rename).not.toHaveBeenCalled();+ expect(chats.get('r1')?.name).toBe('Mine');+ });++ it('warns and keeps the default name when the title fails', async () => {+ const { chats, deps, titler } = setup(async () => {+ throw new Error('claude not found');+ });+ chats.set('r1', summary('r1'));+ titler.created(summary('r1'), false);+ await titler.sent('s1', 'r1', 'hello');+ expect(deps.warn).toHaveBeenCalledOnce();+ expect(deps.rename).not.toHaveBeenCalled();+ expect(chats.get('r1')?.name).toBe('Chat with ada');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-tool-presentation.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-tool-presentation.test.tsnew file mode 100644index 000000000..56a804f16--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-tool-presentation.test.ts@@ -0,0 +1,175 @@+import type { Item } from '@switch-console/shared/session-v1';+import { describe, expect, it } from 'vitest';+import { presentTool, shortPath, summarizeTools } from '@renderer/features/chats/tool-presentation';+import type { ToolDetail } from '@shared/core/sessions/reasoning';++function item(title: string, status: Item['status'] = 'completed'): Item {+ return {+ itemId: '["turn","t1"]',+ turnId: 'turn',+ revision: 1,+ kind: 'tool-activity',+ status,+ title,+ text: '',+ attachments: [],+ origin: null,+ };+}++function detail(extra: Partial<ToolDetail>): ToolDetail {+ return {+ itemId: '["turn","t1"]',+ type: 'tool_call',+ toolName: null,+ input: null,+ output: null,+ truncated: false,+ exitCode: null,+ ...extra,+ };+}++describe('presentTool', () => {+ it('shows a command with its output and a failing exit code', () => {+ const shown = presentTool(+ item('ls -la'),+ detail({+ type: 'command_execution',+ toolName: 'Bash',+ input: { command: 'ls -la' },+ output: 'total 0',+ exitCode: 2,+ })+ );+ expect(shown).toMatchObject({ kind: 'shell', verb: 'Ran', subject: 'ls -la', code: true });+ expect(shown.details).toEqual({+ kind: 'command',+ command: 'ls -la',+ output: 'total 0',+ exitCode: 2,+ });+ expect(presentTool(item('ls -la', 'in-progress'), detail({ toolName: 'Bash' })).verb).toBe(+ 'Running'+ );+ });++ it('names the file a read opened and shows what it read', () => {+ const shown = presentTool(+ item('Read'),+ detail({ toolName: 'Read', input: { file_path: '/repo/src/store.ts' }, output: '1\tx' })+ );+ expect(shown).toMatchObject({ kind: 'read', verb: 'Read', subject: '/repo/src/store.ts' });+ expect(shown.details).toEqual({ kind: 'read', path: '/repo/src/store.ts', output: '1\tx' });+ });++ it('shows an edit as a diff of what it replaced, and a write as all added', () => {+ const edit = presentTool(+ item('Edit /a.ts'),+ detail({+ type: 'file_change',+ toolName: 'Edit',+ input: { file_path: '/a.ts', old_string: 'one', new_string: 'two\nthree' },+ })+ );+ expect(edit).toMatchObject({ kind: 'edit', verb: 'Edited', subject: '/a.ts' });+ expect(edit.details).toEqual({+ kind: 'diff',+ path: '/a.ts',+ lines: [+ { sign: '-', text: 'one' },+ { sign: '+', text: 'two' },+ { sign: '+', text: 'three' },+ ],+ });+ const write = presentTool(+ item('Write /b.ts'),+ detail({+ type: 'file_change',+ toolName: 'Write',+ input: { file_path: '/b.ts', content: 'x' },+ })+ );+ expect(write.verb).toBe('Wrote');+ expect(write.details).toMatchObject({ lines: [{ sign: '+', text: 'x' }] });+ });++ it('reads a Codex file change from its unified diff', () => {+ const shown = presentTool(+ item('src/a.ts'),+ detail({ type: 'file_change', input: { changes: [] }, output: '--- a\n+++ b\n-old\n+new' })+ );+ expect(shown.subject).toBe('src/a.ts');+ expect(shown.details).toMatchObject({+ lines: [+ { sign: ' ', text: '--- a' },+ { sign: ' ', text: '+++ b' },+ { sign: '-', text: 'old' },+ { sign: '+', text: 'new' },+ ],+ });+ });++ it('shows what a search looked for and what it found', () => {+ const shown = presentTool(+ item('Grep'),+ detail({ toolName: 'Grep', input: { pattern: 'TODO', path: 'src' }, output: 'a.ts\nb.ts' })+ );+ expect(shown).toMatchObject({ kind: 'search', verb: 'Searched for', subject: 'TODO' });+ expect(shown.details).toEqual({+ kind: 'search',+ query: 'TODO',+ scope: 'src',+ output: 'a.ts\nb.ts',+ });+ });++ it('falls back to the raw input for a tool it does not know', () => {+ const shown = presentTool(+ item('mcp__linear__get_issue'),+ detail({ toolName: 'mcp__linear__get_issue', input: { id: 'X-1' } })+ );+ expect(shown).toMatchObject({ kind: 'mcp', verb: 'linear: get issue' });+ expect(shown.details).toEqual({ kind: 'generic', input: '{\n "id": "X-1"\n}', output: null });+ });++ it('labels from the title alone, and opens to nothing, without details', () => {+ expect(presentTool(item('Edit /a.ts'), null)).toMatchObject({+ kind: 'edit',+ verb: 'Edited',+ subject: '/a.ts',+ details: null,+ });+ expect(presentTool(item('Read'), null)).toMatchObject({+ kind: 'read',+ verb: 'Read a file',+ subject: null,+ details: null,+ });+ expect(presentTool(item('mcp__switch__post_message'), null)).toMatchObject({+ kind: 'switch',+ verb: 'Posted to the room',+ details: null,+ });+ expect(presentTool(item('ToolSearch'), null)).toMatchObject({+ kind: 'other',+ verb: 'ToolSearch',+ details: null,+ });+ });+});++describe('summarizeTools', () => {+ it('counts each kind in the order it first appears', () => {+ expect(summarizeTools(['shell', 'read', 'read', 'edit'])).toEqual({+ label: 'Ran 1 command, read 2 files and edited 1 file',+ kind: null,+ });+ expect(summarizeTools(['read', 'read'])).toEqual({ label: 'Read 2 files', kind: 'read' });+ });+});++it('keeps the end of a long path, which is the part a reader looks for', () => {+ expect(shortPath('/Users/me/repo/src/stores/chat.ts')).toBe('…/src/stores/chat.ts');+ expect(shortPath('src/a.ts')).toBe('src/a.ts');+});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.tsnew file mode 100644index 000000000..4b4cd8437--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts@@ -0,0 +1,225 @@+import { describe, expect, it, vi } from 'vitest';+import type { TimelineApi } from '@renderer/features/chats/stores/chat-timeline-store';+import {+ ChatsStore,+ type ChatsApi,+ type ChatsEvents,+} from '@renderer/features/chats/stores/chats-store';+import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';++function summary(roomId: string, seq: number): ChatSummary {+ return {+ roomId,+ name: roomId,+ channelType: 'direct',+ bridgeType: null,+ channelName: null,+ agents: [{ id: 'a1', name: 'ada', displayName: null, iconUrl: null, provider: null }],+ canManage: true,+ ownsAgent: false,+ lastMessage: { seq, sentAt: '2026-01-01T00:00:00Z', preview: 'hi', senderName: 'Ada' },+ };+}++function message(roomId: string, seq: number): ChatMessage {+ return {+ messageId: `m${seq}`,+ seq,+ roomId,+ sentAt: '2026-01-01T00:00:00Z',+ sender: { clientId: 'c', name: 'Ada', kind: 'human', agentId: null, userId: 'u' },+ source: 'console',+ body: `body ${seq}`,+ format: null,+ threadRootId: null,+ attachments: [],+ clientTxn: null,+ };+}++function setup(+ list: () => Promise<ChatSummary[]>,+ timeline: Partial<TimelineApi> = {},+ identity: ChatsApi['identity'] = async () => ({ userId: 'u', tenantId: 't' })+) {+ let onMessage: Parameters<ChatsEvents['onMessage']>[0] = () => {};+ let onState: Parameters<ChatsEvents['onState']>[0] = () => {};+ const events: ChatsEvents = {+ onMessage: (cb) => {+ onMessage = cb;+ return () => {};+ },+ onSummary: () => () => {},+ onRemoved: () => () => {},+ onState: (cb) => {+ onState = cb;+ return () => {};+ },+ onReset: () => () => {},+ };+ const api: ChatsApi = {+ connect: async () => ({ state: 'live', detail: null }),+ disconnect: vi.fn(async () => {}),+ list: vi.fn(list),+ identity,+ timeline: () => timeline as TimelineApi,+ };+ const store = new ChatsStore(api, events);+ return {+ store,+ api,+ emit: (m: ChatMessage) => onMessage({ serverId: 's1', message: m }),+ live: () => onState({ serverId: 's1', state: 'live', detail: null }),+ };+}++describe('ChatsStore', () => {+ it('stops the feed of the server it no longer follows', async () => {+ const { store, api } = setup(async () => []);+ await store.connect('s1');+ expect(api.disconnect).not.toHaveBeenCalled();+ await store.connect('s2');+ expect(api.disconnect).toHaveBeenCalledWith('s1');+ await store.connect(null);+ expect(api.disconnect).toHaveBeenLastCalledWith('s2');+ expect(api.disconnect).toHaveBeenCalledTimes(2);+ });++ it('stops a feed that came up after the store moved on', async () => {+ const { store, api } = setup(async () => []);+ const pending = store.connect('s1');+ await store.connect(null);+ await pending;+ expect(api.disconnect).toHaveBeenNthCalledWith(1, 's1');+ expect(api.disconnect).toHaveBeenNthCalledWith(2, 's1');+ });++ it('brings a hidden chat back when a message arrives in it', async () => {+ let chats = [summary('r1', 1), summary('r2', 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)];+ emit(message('r2', 2));+ await vi.waitFor(() => expect(store.chat('r2')?.lastMessage?.seq).toBe(2));+ expect(api.list).toHaveBeenCalledTimes(2);+ });++ it('does not relist for a room the person lost', async () => {+ const { store, api, emit } = setup(async () => [summary('r1', 1)]);+ await store.connect('s1');+ store.remove('r1', 'access');+ emit(message('r1', 2));+ await Promise.resolve();+ expect(api.list).toHaveBeenCalledTimes(1);+ expect(store.chat('r1')).toBeUndefined();+ });++ it('lets a chat be read again when access comes back', async () => {+ const { store } = setup(async () => [summary('r1', 1)]);+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ store.remove('r1', 'access');+ expect(timeline.accessLost).toBe(true);+ expect(store.removed.has('r1')).toBe(true);++ store.upsert(summary('r1', 2));+ expect(timeline.accessLost).toBe(false);+ expect(timeline.loaded).toBe(false);+ });++ it('keeps an unlisted chat usable: off the list, not lost', async () => {+ const messages = vi.fn(async () => ({+ messages: [message('r1', 1)],+ headSeq: 1,+ hasMore: false,+ }));+ const { store } = setup(async () => [summary('r1', 1)], { messages });+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ await timeline.load();++ store.remove('r1', 'unlisted');+ expect(store.chat('r1')).toBeUndefined();+ expect(store.removed.has('r1')).toBe(false);+ expect(timeline.accessLost).toBe(false);+ expect(timeline.messages.map((m) => m.seq)).toEqual([1]);+ });++ it('lists an unlisted chat again and catches its open timeline up', async () => {+ let page = [message('r1', 1)];+ const messages = vi.fn(async () => ({ messages: page, headSeq: page.length, hasMore: false }));+ const { store } = setup(async () => [summary('r1', 1)], { messages });+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ await timeline.load();+ store.remove('r1', 'unlisted');++ page = [message('r1', 1), message('r1', 2)];+ store.upsert(summary('r1', 2));+ expect(store.chat('r1')?.lastMessage?.seq).toBe(2);+ await vi.waitFor(() => expect(timeline.messages.map((m) => m.seq)).toEqual([1, 2]));+ expect(timeline.accessLost).toBe(false);+ });++ it('revokes a chat unlisted earlier once access is lost', async () => {+ const { store } = setup(async () => [summary('r1', 1)]);+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ store.remove('r1', 'unlisted');+ store.remove('r1', 'access');+ expect(timeline.accessLost).toBe(true);+ expect(store.removed.has('r1')).toBe(true);+ expect(store.unlisted.has('r1')).toBe(false);+ });++ it('does not relist for unlisted rooms', async () => {+ const { store, api, emit } = setup(async () => [summary('r1', 1)]);+ await store.connect('s1');+ store.remove('r1', 'unlisted');+ emit(message('r1', 2));+ await Promise.resolve();+ expect(api.list).toHaveBeenCalledTimes(1);+ expect(store.chat('r1')).toBeUndefined();+ });++ it('loads who the person is, their chats and a failed timeline once a feed down at start comes up', async () => {+ let up = false;+ const down = () => Promise.reject(new Error('Could not reach the server'));+ const { store, live } = setup(+ async () => (up ? [summary('r1', 1)] : down()),+ {+ messages: async () =>+ up ? { messages: [message('r1', 1)], headSeq: 1, hasMore: false } : down(),+ },+ async () => (up ? { userId: 'u', tenantId: 't' } : down())+ );+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ await timeline.load();+ expect(store.userId).toBeNull();+ expect(store.listError).not.toBeNull();+ expect(timeline.loadError).not.toBeNull();++ up = true;+ live();+ await vi.waitFor(() => expect(store.userId).toBe('u'));+ await vi.waitFor(() => expect(timeline.loaded).toBe(true));+ expect(store.chat('r1')?.name).toBe('r1');+ expect(store.listError).toBeNull();+ expect(timeline.loadError).toBeNull();+ });++ it('reads a chat once the person is let into it after a refused first load', async () => {+ const { store } = setup(async () => []);+ await store.connect('s1');+ const timeline = store.timelines.get('s1', 'r1');+ timeline.notMember = true;++ store.upsert(summary('r1', 1));+ expect(timeline.notMember).toBe(false);+ expect(timeline.loaded).toBe(false);+ });+});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.tsnew file mode 100644index 000000000..cef37c166--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it, vi } from 'vitest';+import { DirectChatStarter } from '@renderer/features/chats/stores/direct-chat-starter';+import type { ChatSummary } from '@shared/core/chats/chats';++const chat = { roomId: 'r1', channelType: 'direct' } as ChatSummary;++function setup(+ create: () => Promise<ChatSummary>,+ findEmpty: () => ChatSummary | null = () => null+) {+ let id = 0;+ const deps = {+ create: vi.fn(create),+ created: vi.fn(),+ opened: vi.fn(),+ failed: vi.fn(),+ findEmpty: vi.fn(findEmpty),+ newId: () => `req-${++id}`,+ };+ return { deps, starter: new DirectChatStarter(deps) };+}++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',+ });+ expect(deps.created).toHaveBeenCalledWith('s1', chat);+ });++ 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('reports a failure and reuses the request id after an uncertain one', async () => {+ const { deps, starter } = setup(async () => {+ throw new Error('offline');+ });+ 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' }));+ });++ 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.create).not.toHaveBeenCalled();+ });++ 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();+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/activity.ts b/console/apps/switch-console-desktop/src/shared/core/chats/activity.tsnew file mode 100644index 000000000..7153583d2--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/chats/activity.ts@@ -0,0 +1,129 @@+import { z } from 'zod';++/**+ * What a chat shows of its agents' work. Turns, tool rows and approval+ * requests come from Switch's activity feed, the same rows the platforms draw+ * their progress messages from. Where an agent's session runs as seen from+ * this machine (a local or SSH host) is looked up only for what the host+ * alone keeps — reasoning and full tool input and output — and for restarting+ * the session.+ */++export type ChatActivityHostTarget = 'local' | 'ssh';++export type ChatActivityUnavailableReason =+ /** Not a local agent here. */+ | 'not-on-this-machine'+ /** The agent's watcher runs, but no session of it is placed in this room. */+ | 'not-placed'+ /** The agent's watcher could not be asked. */+ | 'watcher-unreachable';++export type ChatActivityTarget =+ | {+ kind: 'unavailable';+ reason: ChatActivityUnavailableReason;+ message: string;+ }+ | {+ kind: 'session';+ target: ChatActivityHostTarget;+ /** What the session calls (`rpc.sdkHost.*`) name the agent by. */+ hostAgentKey: string;+ sessionId: string;+ };++export const ACTIVITY_UNAVAILABLE_TEXT: Record<ChatActivityUnavailableReason, string> = {+ 'not-on-this-machine': 'Activity not available on this machine.',+ 'not-placed': 'The agent has no session in this chat yet.',+ 'watcher-unreachable': "The agent's room watcher cannot be reached.",+};++/**+ * One step of an agent's turn as Switch stores it (`GET /chats/{room}/activity`+ * and the activity feed): the turn's own row (`itemId` {@link TURN_ITEM_ID}),+ * a message, a tool call or a notice. `revision` only grows, so a row at or+ * below the one held is stale.+ */+export const TURN_ITEM_ID = 'turn';++export const chatActivityItemSchema = z.object({+ agentId: z.string(),+ sessionId: z.string(),+ turnId: z.string(),+ itemId: z.string(),+ kind: z.enum(['turn', 'user-message', 'assistant-message', 'tool-activity', 'notice']),+ revision: z.number().int(),+ status: z.string(),+ title: z.string(),+ text: z.string(),+ commandId: z.string().nullable(),+ roomId: z.string().nullable(),+ threadId: z.string().nullable(),+ messageId: z.string().nullable(),+ occurredAt: z.string(),+ createdAt: z.string(),+ updatedAt: z.string(),+});+export type ChatActivityItem = z.infer<typeof chatActivityItemSchema>;++/** A request an agent's session put to a person, in any state, so a settled one survives reload. */+export const chatApprovalSchema = z.object({+ agentId: z.string(),+ sessionId: z.string(),+ requestId: z.string(),+ turnId: z.string(),+ kind: z.string(),+ roomId: z.string().nullable(),+ threadId: z.string().nullable(),+ title: z.string(),+ detail: z.string().nullable(),+ options: z.array(z.object({ id: z.string(), label: z.string(), decision: z.string() })),+ questions: z.array(+ z.object({+ id: z.string(),+ title: z.string(),+ prompt: z.string(),+ options: z.array(+ z.object({ id: z.string(), label: z.string(), description: z.string().nullable() })+ ),+ multiSelect: z.boolean(),+ allowCustomAnswer: z.boolean(),+ })+ ),+ state: z.string(),+ expiresAt: z.string().nullable(),+ answer: z.string().nullable(),+ answers: z+ .array(+ z.object({+ questionId: z.string(),+ selectedOptionIds: z.array(z.string()),+ customText: z.string().nullable(),+ })+ )+ .nullable(),+ answeredBy: z.string().nullable(),+ answeredAt: z.string().nullable(),+});+export type ChatApproval = z.infer<typeof chatApprovalSchema>;++export const roomActivitySchema = z.object({+ items: z.array(chatActivityItemSchema),+ approvals: z.array(chatApprovalSchema),+});+export type RoomActivity = z.infer<typeof roomActivitySchema>;++/** An approval's chosen option, or an answer per question. */+export type ChatApprovalAnswer =+ | { answer: string }+ | { answers: NonNullable<ChatApproval['answers']> };++/** A server without the activity routes answers them with an uncoded 404. */+export const SERVER_TOO_OLD_FOR_ACTIVITY =+ 'This Switch server is too old for live chat activity — update the server.';++/** What the chat's Stop, Reset and Compact post to the room for an agent. */+export type ChatControlCommand = 'interrupt' | 'reset' | 'compact';++export const chatControlAcceptedSchema = z.object({ commandId: z.string() });diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/chatEvents.ts b/console/apps/switch-console-desktop/src/shared/core/chats/chatEvents.tsnew file mode 100644index 000000000..7853ebebd--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/chats/chatEvents.ts@@ -0,0 +1,64 @@+import { defineEvent } from '@shared/lib/ipc/events';+import type { ChatActivityItem, ChatApproval } from './activity';+import type { ChatMessage, ChatRemovalReason, ChatStreamState, ChatSummary } from './chats';++/**+ * The chats live feed, pushed by the main process. Every event names the+ * server it came from: one feed runs per server and tenant, and a renderer+ * scoped to another server ignores it.+ */+export const chatMessageChannel = defineEvent<{ serverId: string; message: ChatMessage }>(+ 'chat:message'+);++/** A chat entered the list (new membership, or it qualifies again) or its summary changed. */+export const chatSummaryChannel = defineEvent<{ serverId: string; chat: ChatSummary }>(+ 'chat:summary'+);++/**+ * The room left the person's list. `access`: they lost it (removed, left,+ * lost their tenant role, or it was archived). `unlisted`: still a member, so+ * an open chat keeps reading and posting; it is only off the list.+ */+export const chatRemovedChannel = defineEvent<{+ serverId: string;+ roomId: string;+ reason: ChatRemovalReason;+}>('chat:removed');++export const chatStreamStateChannel = defineEvent<{+ serverId: string;+ state: ChatStreamState;+ /** Why the feed is offline or retrying, when it is. */+ detail: string | null;+}>('chat:stream-state');++/**+ * Everything held for the server's chats is stale: the person signed out or+ * the tenant changed. Drop cursors, messages and media for it.+ */+export const chatResetChannel = defineEvent<{ serverId: string }>('chat:reset');++/** One turn step from the server's activity feed, for a room the person may read. */+export const chatActivityChannel = defineEvent<{ serverId: string; item: ChatActivityItem }>(+ 'chat:activity'+);++/** An approval request, in whatever state it is now. */+export const chatApprovalChannel = defineEvent<{ serverId: string; approval: ChatApproval }>(+ 'chat:approval'+);++/**+ * The activity feed (re)connected or may have missed changes: reload the+ * activity snapshot of every room shown.+ */+export const chatActivityResyncChannel = defineEvent<{ serverId: string }>('chat:activity-resync');++/** The activity feed dropped (`offline`) or is back (`live`); same shape as {@link chatStreamStateChannel}. */+export const chatActivityStateChannel = defineEvent<{+ serverId: string;+ state: ChatStreamState;+ detail: string | null;+}>('chat:activity-state');diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts b/console/apps/switch-console-desktop/src/shared/core/chats/chats.tsnew file mode 100644index 000000000..772a10322--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts@@ -0,0 +1,206 @@+import { z } from 'zod';++/**+ * A chat is a Switch room the signed-in person is a member of and that has at+ * least one agent in it. Everything here is the gateway's `/chats` contract,+ * parsed at the main-process boundary so the renderer only ever sees values+ * that matched it.+ */++export const chatAgentSchema = z.object({+ id: z.string(),+ name: z.string(),+ displayName: z.string().nullable(),+ iconUrl: z.string().nullable(),+ provider: z.string().nullable(),+});+export type ChatAgent = z.infer<typeof chatAgentSchema>;++export const chatSummarySchema = z.object({+ roomId: z.string(),+ name: z.string(),+ channelType: z.enum(['lobby', 'channel_public', 'channel_private', 'group', 'direct']),+ bridgeType: z.string().nullable(),+ channelName: z.string().nullable(),+ agents: z.array(chatAgentSchema),+ canManage: z.boolean(),+ /** The viewer owns one of the agents, which keeps them in the room: they cannot leave it. */+ ownsAgent: z.boolean().default(false),+ lastMessage: z+ .object({+ seq: z.number().int(),+ sentAt: z.string(),+ preview: z.string(),+ senderName: z.string(),+ })+ .nullable(),+});+export type ChatSummary = z.infer<typeof chatSummarySchema>;++export const chatSenderSchema = z.object({+ clientId: z.string(),+ name: z.string(),+ kind: z.enum(['human', 'agent', 'system']),+ agentId: z.string().nullable(),+ userId: z.string().nullable(),+});+export type ChatSender = z.infer<typeof chatSenderSchema>;++export const chatAttachmentSchema = z.object({+ uri: z.string(),+ filename: z.string(),+ mimetype: z.string(),+ size: z.number(),+ msgtype: z.string(),+});+export type ChatAttachment = z.infer<typeof chatAttachmentSchema>;++export const chatMessageSchema = z.object({+ messageId: z.string(),+ seq: z.number().int(),+ roomId: z.string(),+ sentAt: z.string(),+ sender: chatSenderSchema,+ source: z.string(),+ body: z.string(),+ format: z.string().nullable(),+ threadRootId: z.string().nullable(),+ attachments: z.array(chatAttachmentSchema),+ clientTxn: z.string().nullable(),+});+export type ChatMessage = z.infer<typeof chatMessageSchema>;++export const chatListSchema = z.object({ chats: z.array(z.unknown()) });+export const chatCreatedSchema = z.object({ chat: chatSummarySchema });+export const chatMessagesPageSchema = z.object({+ messages: z.array(chatMessageSchema),+ headSeq: z.number().int(),+ hasMore: z.boolean(),+});+export type ChatMessagesPage = z.infer<typeof chatMessagesPageSchema>;+export const chatSentSchema = z.object({ messages: z.array(chatMessageSchema) });+export const chatUploadSchema = z.object({+ uploadId: z.string(),+ uri: z.string(),+ filename: z.string(),+ mimetype: z.string(),+ size: z.number(),+});+export type ChatUpload = z.infer<typeof chatUploadSchema>;+/**+ * `access`: the person lost the room (membership, workspace role, archive).+ * `unlisted`: still a member, but the room no longer qualifies for the list.+ */+export const chatRemovalReasonSchema = z.enum(['access', 'unlisted']);+export type ChatRemovalReason = z.infer<typeof chatRemovalReasonSchema>;+export const chatRemovedSchema = z.object({+ roomId: z.string(),+ reason: chatRemovalReasonSchema,+});++/** The gateway's coded refusal: `{ detail: { code, message } }`. */+export const chatErrorBodySchema = z.object({+ detail: z.object({ code: z.string(), message: z.string() }),+});++/**+ * The live feed's state. `live` is only reached after the server's `ready`,+ * which it sends once every member room has been caught up from its cursor.+ */+export type ChatStreamState = 'connecting' | 'catching-up' | 'live' | 'offline';++export type ChatSendInput = {+ serverId: string;+ roomId: string;+ requestId: string;+ body: string;+ threadRootId: string | null;+ uploadIds: string[];+};++export type ChatUploadInput = {+ serverId: string;+ roomId: string;+ uploadId: string;+ name: string;+ mimeType: string;+ /** The file's bytes, base64. */+ data: string;+};++/** The display name the room and the platforms show for an agent. */+export function chatAgentLabel(agent: Pick<ChatAgent, 'name' | 'displayName'>): string {+ return agent.displayName ?? agent.name;+}++/** The `clientTxn` a Console send's parts carry: `{requestId}:{index}`. */+export function requestIdOfClientTxn(clientTxn: string | null): string | null {+ if (clientTxn === null) return null;+ const at = clientTxn.lastIndexOf(':');+ return at > 0 ? clientTxn.slice(0, at) : null;+}++/** The notice an agent posts to a room while a session starts to answer it. */+export const SESSION_STARTING_MESSAGE = 'Starting a session to handle this — one moment.';++export function isSessionStartingNotice(message: ChatMessage): boolean {+ return message.sender.kind === 'agent' && message.body.trim() === SESSION_STARTING_MESSAGE;+}++/**+ * The session-starting notices still current: each is its agent's latest+ * message, and that agent shows no turn yet for the message it answers or any+ * later one. `turnAgents` maps a message id to the agents with a turn under it.+ */+export function liveSessionStartingNotices(+ messages: readonly ChatMessage[],+ turnAgents: ReadonlyMap<string, ReadonlySet<string>>+): Set<string> {+ const live = new Set<string>();+ const seen = new Set<string>();+ for (let at = messages.length - 1; at >= 0; at--) {+ const message = messages[at];+ if (message.sender.kind !== 'agent' || seen.has(message.sender.clientId)) continue;+ seen.add(message.sender.clientId);+ if (!isSessionStartingNotice(message)) continue;+ let from = at;+ while (from > 0 && messages[from].sender.kind !== 'human') from--;+ const agentId = message.sender.agentId;+ const working = messages+ .slice(from)+ .some((each) => agentId !== null && turnAgents.get(each.messageId)?.has(agentId));+ if (!working) live.add(message.messageId);+ }+ return live;+}++/** What the host posts for a turn that ended without the agent posting, then why it ended. */+export const UNPOSTED_REPLY_MESSAGE = 'I finished without replying.';+export const TURN_FAILED_PHRASE = 'The turn failed';+export const TURN_INTERRUPTED_PHRASE = 'The turn was interrupted';++export type TurnEndNotice = {+ outcome: 'completed' | 'failed' | 'interrupted';+ reason: string | null;+};++/** The host's notice of a turn that ended without a reply, or null for any other message. */+export function turnEndNotice(message: ChatMessage): TurnEndNotice | null {+ const body = message.body.trim();+ if (message.sender.kind !== 'agent' || !body.startsWith(UNPOSTED_REPLY_MESSAGE)) return null;+ const rest = body.slice(UNPOSTED_REPLY_MESSAGE.length).trim();+ if (!rest) return { outcome: 'completed', reason: null };+ for (const [phrase, outcome] of [+ [TURN_FAILED_PHRASE, 'failed'],+ [TURN_INTERRUPTED_PHRASE, 'interrupted'],+ ] as const) {+ if (rest === `${phrase}.`) return { outcome, reason: null };+ // An interrupt is the person's Stop; the provider's raw reason for it says nothing more.+ if (rest.startsWith(`${phrase}: `))+ return {+ outcome,+ reason: outcome === 'interrupted' ? null : rest.slice(phrase.length + 2).trim(),+ };+ }+ return null;+}diff --git a/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.tsindex 4f62b3d4f..7c89eafca 100644--- a/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts+++ b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts@@ -15,6 +15,7 @@ export const CONSOLE_FEATURE_FLAGS = ['hosted_agents','agent_management','service_connections',+ 'agent_chats',] as const;export type FeatureFlagKey = (typeof CONSOLE_FEATURE_FLAGS)[number];diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.test.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.test.tsnew file mode 100644index 000000000..db96e58c0--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.test.ts@@ -0,0 +1,69 @@+import { expect, it } from 'vitest';+import { reasoningLabel, reasoningListSchema, type ReasoningTurn } from './reasoning';++const turn = (startedAt: string | null, completedAt: string | null): ReasoningTurn => ({+ turnId: 'turn',+ text: 'Look first.',+ startedAt,+ completedAt,+});++it('labels reasoning by what is known of its timing', () => {+ expect(reasoningLabel(null, true)).toBeNull();+ expect(reasoningLabel(null, false)).toBeNull();+ expect(reasoningLabel(turn('2026-10-08T12:00:00.000Z', null), true)).toEqual({+ label: 'Thinking…',+ seconds: null,+ });+ expect(reasoningLabel(turn(null, null), true)).toEqual({ label: 'Thinking…', seconds: null });+ expect(+ reasoningLabel(turn('2026-10-08T12:00:00.000Z', '2026-10-08T12:00:04.400Z'), true)+ ).toEqual({ label: 'Thought for 4s', seconds: 4 });+ expect(+ reasoningLabel(turn('2026-10-08T12:00:00.000Z', '2026-10-08T12:00:12.600Z'), false)+ ).toEqual({ label: 'Thought for 13s', seconds: 13 });+ expect(+ reasoningLabel(turn('2026-10-08T12:00:00.000Z', '2026-10-08T12:00:00.100Z'), false)+ ).toEqual({ label: 'Thought for 1s', seconds: 1 });+});++it('says only "Thought" without a real start, and never makes a duration up', () => {+ expect(reasoningLabel(turn(null, '2026-10-08T12:00:04.000Z'), false)).toEqual({+ label: 'Thought',+ seconds: null,+ });+ expect(reasoningLabel(turn(null, '2026-10-08T12:00:04.000Z'), true)).toEqual({+ label: 'Thought',+ seconds: null,+ });+ // The turn ended without the reasoning completing.+ expect(reasoningLabel(turn('2026-10-08T12:00:00.000Z', null), false)).toEqual({+ label: 'Thought',+ seconds: null,+ });+ expect(reasoningLabel(turn('not a time', '2026-10-08T12:00:04.000Z'), false)).toEqual({+ label: 'Thought',+ seconds: null,+ });+});++it('reads a reasoning list and refuses anything else', () => {+ const list = { epoch: 'epoch', turns: [turn(null, null)] };+ expect(reasoningListSchema.parse(list)).toEqual(list);+ expect(reasoningListSchema.safeParse({ state: 'connected' }).success).toBe(false);+});++it('reads tool details when a host sends them, and an older host’s answer without them', () => {+ const tool = {+ itemId: '["turn","t1"]',+ type: 'tool_call',+ toolName: 'Read',+ input: { file_path: '/a.ts' },+ output: '1\tconst a = 1;',+ truncated: false,+ exitCode: null,+ };+ const withTools = { epoch: 'e', turns: [], tools: [{ turnId: 'turn', tools: [tool] }] };+ expect(reasoningListSchema.parse(withTools)).toEqual(withTools);+ expect(reasoningListSchema.parse({ epoch: 'e', turns: [] }).tools).toBeUndefined();+});diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.tsnew file mode 100644index 000000000..1be9df9f1--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/reasoning.ts@@ -0,0 +1,86 @@+import z from 'zod';++/**+ * The model's reasoning for a session's recent turns, as its local or SSH+ * session host holds it in memory. It is never part of the session's event+ * stream or transcript, and a cloud or controller-run session has none.+ *+ * `startedAt` is null when the provider gave no real start signal (Claude+ * reports thinking only once it is done); `completedAt` is null while the+ * reasoning is still running. Both are ISO timestamps.+ */+export type ReasoningTurn = {+ turnId: string;+ text: string;+ startedAt: string | null;+ completedAt: string | null;+};++/**+ * What one tool call was given and gave back, as the session host holds it+ * beside the reasoning (and under the same rules: local and SSH hosts only,+ * never part of the session's event stream). `itemId` is the session-v1 item+ * the call was projected as. `input` is the call's arguments with long strings+ * clipped, or clipped JSON text when the whole was too large; `output` keeps+ * its head and tail. `truncated` says something was clipped.+ */+export type ToolDetail = {+ itemId: string;+ type: string;+ toolName: string | null;+ input: unknown;+ output: string | null;+ truncated: boolean;+ exitCode: number | null;+};++export type ToolDetailTurn = { turnId: string; tools: ToolDetail[] };++/** `tools` is absent from a host that predates tool details. */+export type ReasoningList = { epoch: string; turns: ReasoningTurn[]; tools?: ToolDetailTurn[] };++export const reasoningTurnSchema = z.object({+ turnId: z.string().min(1),+ text: z.string(),+ startedAt: z.string().nullable(),+ completedAt: z.string().nullable(),+});++export const toolDetailSchema = z.object({+ itemId: z.string().min(1),+ type: z.string(),+ toolName: z.string().nullable(),+ input: z.unknown(),+ output: z.string().nullable(),+ truncated: z.boolean(),+ exitCode: z.number().nullable(),+});++export const reasoningListSchema = z.object({+ epoch: z.string().min(1),+ turns: z.array(reasoningTurnSchema),+ tools: z+ .array(z.object({ turnId: z.string().min(1), tools: z.array(toolDetailSchema) }))+ .optional(),+});++/**+ * The row label for a turn's reasoning: "Thinking…" while the turn runs and+ * the reasoning has not completed, "Thought for Ns" only when both ends are+ * known, and plain "Thought" otherwise — never a duration made up from one end.+ */+export function reasoningLabel(+ turn: ReasoningTurn | null,+ running: boolean+): { label: string; seconds: number | null } | null {+ if (!turn) return null;+ if (running && turn.completedAt === null) return { label: 'Thinking…', seconds: null };+ if (turn.startedAt !== null && turn.completedAt !== null) {+ const elapsed = Date.parse(turn.completedAt) - Date.parse(turn.startedAt);+ if (Number.isFinite(elapsed)) {+ const seconds = Math.max(1, Math.round(elapsed / 1000));+ return { label: `Thought for ${seconds}s`, seconds };+ }+ }+ return { label: 'Thought', seconds: null };+}diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex 13aa56825..eb9d00d4c 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -921,9 +921,11 @@ export type CreateRoomParams = {description: string;/** Room-specific system prompt shown to agents on connect. Optional. */instructions?: string;- bridgeId: string;- /** Switch agent ids to add as members. May be empty — a bridged room is- * valid with no agents, and members can be invited later. */+ /** The messaging app to bridge the room to, or null for an internal room+ * that people reach from Switch Console's chats. */+ bridgeId: string | null;+ /** Switch agent ids to add as members. May be empty — a room is valid with+ * no agents, and members can be invited later. */agentIds: string[];};diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.tsindex 29037496f..fc4d6be47 100644--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts@@ -11,6 +11,7 @@ export const VIEW_IDS = ['home','location','session',+ 'chat','managedAgent','room','settings',diff --git a/console/packages/agent-controller/src/control-port.test.ts b/console/packages/agent-controller/src/control-port.test.tsnew file mode 100644index 000000000..5b42bac65--- /dev/null+++ b/console/packages/agent-controller/src/control-port.test.ts@@ -0,0 +1,55 @@+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { createServer, type Server } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createInterface } from 'node:readline';+import { afterEach, beforeEach, expect, it } from 'vitest';+import { warmOverControlPort } from './control-port';++const TOKEN = 'a-control-token-of-enough-length';+let dir: string;+let server: Server;+let received: unknown[];++beforeEach(async () => {+ dir = mkdtempSync(join(tmpdir(), 'control-port-'));+ received = [];+ server = createServer((socket) => {+ createInterface({ input: socket }).on('line', (line) => {+ const message = JSON.parse(line) as { token?: string; id?: number };+ if (message.token === TOKEN) socket.write(`${JSON.stringify({ authenticated: true })}\n`);+ else {+ received.push(message);+ socket.write(`${JSON.stringify({ id: message.id, ok: true, value: 'session-1' })}\n`);+ }+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+});++afterEach(() => {+ server.close();+ rmSync(dir, { recursive: true, force: true });+});++function controlFile(content: unknown): string {+ const path = join(dir, 'control.json');+ writeFileSync(path, JSON.stringify(content));+ return path;+}++it('sends warm for the room over the port its control file names', async () => {+ const { port } = server.address() as { port: number };+ await warmOverControlPort(controlFile({ port, token: TOKEN }), 'room-a');+ expect(received).toEqual([{ id: 0, warm: { roomId: 'room-a' } }]);+});++it('refuses a control file that is a symlink or names more than a port and a token', async () => {+ const { port } = server.address() as { port: number };+ const real = controlFile({ port, token: TOKEN, host: 'elsewhere' });+ await expect(warmOverControlPort(real, 'room-a')).rejects.toThrow();+ const link = join(dir, 'linked.json');+ symlinkSync(controlFile({ port, token: TOKEN }), link);+ await expect(warmOverControlPort(link, 'room-a')).rejects.toThrow('not a regular file');+ expect(received).toEqual([]);+});diff --git a/console/packages/agent-controller/src/control-port.ts b/console/packages/agent-controller/src/control-port.tsnew file mode 100644index 000000000..9100dce69--- /dev/null+++ b/console/packages/agent-controller/src/control-port.ts@@ -0,0 +1,40 @@+import { lstat, readFile } from 'node:fs/promises';+import { connect } from 'node:net';+import { ControlClient } from '@switch-console/agent-providers';+import { z } from 'zod';++const CONTROL_FILE_LIMIT_BYTES = 4096;+const CONNECT_TIMEOUT_MS = 5_000;++const controlFileSchema = z.strictObject({+ port: z.number().int().min(1024).max(65535),+ token: z.string().regex(/^[A-Za-z0-9_-]{16,256}$/),+});++/**+ * Ask an agent host in a process of its own to warm `roomId`, over the+ * loopback control port named in its `control.json`. The file is the agent's,+ * so it is read as untrusted: not through a symlink, small, a port and a token.+ */+export async function warmOverControlPort(controlFile: string, roomId: string): Promise<void> {+ const link = await lstat(controlFile);+ if (!link.isFile()) throw new Error(`${controlFile} is not a regular file.`);+ if (link.size > CONTROL_FILE_LIMIT_BYTES) throw new Error(`${controlFile} is too large.`);+ const { port, token } = controlFileSchema.parse(JSON.parse(await readFile(controlFile, 'utf8')));+ const client = new ControlClient(connect({ host: '127.0.0.1', port }), token);+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ client.ready.then(() => client.warm(roomId)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('The agent host’s control port did not answer in time.')),+ CONNECT_TIMEOUT_MS+ );+ }),+ ]);+ } finally {+ clearTimeout(timer);+ client.close();+ }+}diff --git a/console/packages/agent-controller/src/controller.test.ts b/console/packages/agent-controller/src/controller.test.tsindex 013ded82a..726514cf5 100644--- a/console/packages/agent-controller/src/controller.test.ts+++ b/console/packages/agent-controller/src/controller.test.ts@@ -469,6 +469,28 @@ 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 () => {+ const warnings: string[] = [];+ core.setAssignment({ revision: 1, agents: [agent(1)] });+ running = runController(+ { ...deps(), log: { ...silentLogger, warn: (message) => void warnings.push(message) } },+ stop.signal+ );+ await waitFor(() => runtime.launches('agent-1').length === 1, 'the agent started');+ await waitFor(() => core.streamCount === 1, 'the stream attached');++ runtime.warmFailure = new Error('not running here');+ core.push('agent.warm', { agent_id: 'agent-1', room_id: 'room-a' });+ await waitFor(() => warnings.some((w) => w.includes('warm')), 'the warning');++ runtime.warmFailure = null;+ core.push('agent.warm', { agent_id: 'agent-1', room_id: 'room-a' });+ await waitFor(() => runtime.warms.length === 1, 'the warm');+ expect(runtime.warms).toEqual([{ agentId: 'agent-1', roomId: 'room-a' }]);+ stop.abort();+ expect(await running).toBe('stopped');+ });+it('takes up a login given to the machine on demand, and moves its agent onto it', async () => {runtime.readiness = { status: 'unauthenticated', message: 'Not signed in.', models: [] };core.setAssignment({ revision: 1, agents: [agent(1)] });diff --git a/console/packages/agent-controller/src/controller.ts b/console/packages/agent-controller/src/controller.tsindex fa53c7d1b..216b55edb 100644--- a/console/packages/agent-controller/src/controller.ts+++ b/console/packages/agent-controller/src/controller.ts@@ -615,6 +615,19 @@ export async function runController(});};+ /** A hint from someone typing to the agent: a failure costs only the head start. */+ const warmAgent = async (agentId: string, roomId: string): Promise<void> => {+ try {+ await runtime.warm(agentId, roomId);+ } catch (error) {+ log.warn('Could not warm an agent’s session for a room; its first message starts it', {+ agentId,+ roomId,+ error: errorMessage(error),+ });+ }+ };+const onFrame = async (frame: ControllerFrame): Promise<void> => {switch (frame.type) {case 'connection_state':@@ -637,6 +650,9 @@ export async function runController(case 'agent.session_command':hub.sessionCommand(frame.data);return;+ case 'agent.warm':+ void warmAgent(frame.data.agent_id, frame.data.room_id);+ return;case 'agent.approval_outcome':hub.approvalOutcome(frame.data);return;diff --git a/console/packages/agent-controller/src/runtime.ts b/console/packages/agent-controller/src/runtime.tsindex 22f435599..cd7536e69 100644--- a/console/packages/agent-controller/src/runtime.ts+++ b/console/packages/agent-controller/src/runtime.ts@@ -120,7 +120,7 @@ export interface AgentRunner {* `InProcessRuntime` and a runner for isolated agents); tests substitute a* fake.*/-export interface AgentRuntime extends AgentRunner {+export interface AgentRuntime extends AgentRunner, WarmsRooms {credentialsPath(agentId: string): string;/** The credentials file as written, or null when there is none or it cannot be read. */readCredentials(agentId: string): Promise<RelayCredentials | null>;@@ -146,6 +146,12 @@ export interface AgentRuntime extends AgentRunner {agentStateRoot(agentId: string): string;}+/** An agent host this controller runs, asked to start a room's session early. */+export interface WarmsRooms {+ /** Start the session a message to `roomId` would start; throws when the agent host is not running here. */+ warm(agentId: string, roomId: string): Promise<void>;+}+/*** The environment to probe `login` with: its files written under `dir`, made* afresh, and the variables pointing at them or holding its token.@@ -653,6 +659,19 @@ export class InProcessRuntime implements AgentRuntime {return this.deps.layout.watcherRoot(agentId);}+ /** False when the agent host does not run in this process. */+ async warmHere(agentId: string, roomId: string): Promise<boolean> {+ const host = this.hosts.get(agentId);+ if (!host) return false;+ await host.control.warm(roomId);+ return true;+ }++ async warm(agentId: string, roomId: string): Promise<void> {+ if (!(await this.warmHere(agentId, roomId)))+ throw new Error(`The agent host of agent ${agentId} is not running in this controller.`);+ }+private async writeFlags(root: string, flags: WatchFlags): Promise<void> {await writeAtomic(join(root, WATCH_FLAGS_FILE), JSON.stringify(watchFlagsSchema.parse(flags)));}diff --git a/console/packages/agent-controller/src/runtimes.ts b/console/packages/agent-controller/src/runtimes.tsindex 083cbd8f3..13e52b047 100644--- a/console/packages/agent-controller/src/runtimes.ts+++ b/console/packages/agent-controller/src/runtimes.ts@@ -1,4 +1,10 @@-import type { ProviderReadiness, SharedHostConfig } from '@switch-console/agent-providers';+import { join } from 'node:path';+import {+ CONTROL_FILE,+ type ProviderReadiness,+ type SharedHostConfig,+} from '@switch-console/agent-providers';+import { warmOverControlPort } from './control-port';import type {AgentObservation,AgentRunner,@@ -79,6 +85,12 @@ export class AgentRuntimes implements AgentRuntime {return this.shared.probe(provider, binaryPath, cwd, login);}+ /** In this process when it runs here; otherwise on the control port its own process opens. */+ async warm(agentId: string, roomId: string): Promise<void> {+ if (await this.shared.warmHere(agentId, roomId)) return;+ await warmOverControlPort(join(this.agentStateRoot(agentId), CONTROL_FILE), roomId);+ }+/** The same for both: moving an agent between them keeps its root. */agentStateRoot(agentId: string): string {return this.shared.agentStateRoot(agentId);diff --git a/console/packages/agent-controller/src/schemas.ts b/console/packages/agent-controller/src/schemas.tsindex 47b538f14..6b9bbebcf 100644--- a/console/packages/agent-controller/src/schemas.ts+++ b/console/packages/agent-controller/src/schemas.ts@@ -416,6 +416,9 @@ export const agentSessionCommandFrameSchema = z.object({});export type AgentSessionCommandFrame = z.infer<typeof agentSessionCommandFrameSchema>;+export const agentWarmFrameSchema = z.object({ agent_id: id, room_id: id });+export type AgentWarmFrame = z.infer<typeof agentWarmFrameSchema>;+export const agentApprovalOutcomeFrameSchema = z.object({agent_id: id,outcome: z.looseObject({diff --git a/console/packages/agent-controller/src/stream.ts b/console/packages/agent-controller/src/stream.tsindex 531ce24e7..d833ea92d 100644--- a/console/packages/agent-controller/src/stream.ts+++ b/console/packages/agent-controller/src/stream.ts@@ -26,6 +26,8 @@ import {agentRoomsFrameSchema,type AgentSessionCommandFrame,agentSessionCommandFrameSchema,+ type AgentWarmFrame,+ agentWarmFrameSchema,assignmentChangedSchema,type ConnectionState,connectionStateSchema,@@ -44,6 +46,7 @@ export const STREAM_FRAME_SCHEMAS = {'agent.event': agentEventFrameSchema,'agent.gap': agentGapFrameSchema,'agent.session_command': agentSessionCommandFrameSchema,+ 'agent.warm': agentWarmFrameSchema,'agent.approval_outcome': agentApprovalOutcomeFrameSchema,'agent.attached': agentAttachedFrameSchema,'agent.detached': agentDetachedFrameSchema,@@ -59,6 +62,7 @@ export type ControllerFrame =| { type: 'agent.event'; data: AgentEventFrame }| { type: 'agent.gap'; data: AgentGapFrame }| { type: 'agent.session_command'; data: AgentSessionCommandFrame }+ | { type: 'agent.warm'; data: AgentWarmFrame }| { type: 'agent.approval_outcome'; data: AgentApprovalOutcomeFrame }| { type: 'agent.attached'; data: AgentAttachedFrame }| { type: 'agent.detached'; data: AgentDetachedFrame }diff --git a/console/packages/agent-controller/src/systemd-runtime.ts b/console/packages/agent-controller/src/systemd-runtime.tsindex cfbb3ed42..51997ddd8 100644--- a/console/packages/agent-controller/src/systemd-runtime.ts+++ b/console/packages/agent-controller/src/systemd-runtime.ts@@ -5,6 +5,7 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';import { promisify } from 'node:util';import {AGENT_ENV_VARS,+ CONTROL_FILE,clearTakenOver,type ProviderReadiness,type SharedHostConfig,@@ -15,6 +16,7 @@ import {watcherHealthFileSchema,watchFlagsSchema,} from '@switch-console/agent-providers';+import { warmOverControlPort } from './control-port';import { ReasonedError } from './errors';import type { Logger } from './log';import {@@ -241,6 +243,15 @@ export class SystemdRuntime implements AgentRuntime {});}+ async warm(agentId: string, roomId: string): Promise<void> {+ const slot = this.deps.store.agentUser(agentId);+ if (slot === null) throw new Error(`Agent ${agentId} has no user on this machine.`);+ await warmOverControlPort(+ join(agentRoot(this.deps.config, slot), 'watcher', CONTROL_FILE),+ roomId+ );+ }+agentStateRoot(_agentId: string): string {return join(unitAgentRoot(this.deps.config), 'watcher');}diff --git a/console/packages/agent-controller/src/testing/fake-runtime.ts b/console/packages/agent-controller/src/testing/fake-runtime.tsindex 4a04a043b..0f8811f3e 100644--- a/console/packages/agent-controller/src/testing/fake-runtime.ts+++ b/console/packages/agent-controller/src/testing/fake-runtime.ts@@ -133,6 +133,14 @@ export class FakeRuntime implements AgentRuntime {return `/data/watchers/${agentId}`;}+ readonly warms: { agentId: string; roomId: string }[] = [];+ warmFailure: Error | null = null;++ async warm(agentId: string, roomId: string): Promise<void> {+ if (this.warmFailure) throw this.warmFailure;+ this.warms.push({ agentId, roomId });+ }+async probe(_provider: Provider,_binaryPath: string,diff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex 79a0a80a1..9ab32ce43 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -1,4 +1,4 @@-import type { ModelChoice } from '@switch-console/shared/session-v1';+import type { ModelChoice, SessionContext } from '@switch-console/shared/session-v1';import type {ApprovalDecision,ProviderKind,@@ -145,6 +145,11 @@ export interface ProviderAdapter {canCompact?(sessionId: string): Promise<boolean>;listModels?(sessionId: string): Promise<ModelChoice[]>;setModel?(sessionId: string, model: ModelSelection): Promise<void>;+ /**+ * How full the conversation's context window is now, as the provider+ * measures it; null when it has not said. Absent means it never reports one.+ */+ contextUsage?(sessionId: string): Promise<Omit<SessionContext, 'updatedAt'> | null>;/*** Adds a developer message to the conversation, read by the model before* the next turn with a developer message's weight. Absent means the providerdiff --git a/console/packages/agent-providers/src/claude/claude-adapter.test.ts b/console/packages/agent-providers/src/claude/claude-adapter.test.tsindex 2103e58ea..de4010047 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.test.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.test.ts@@ -1090,6 +1090,16 @@ describe('ClaudeAdapter user input', () => {});});+describe('ClaudeAdapter context usage', () => {+ it("reads the live query's context usage and window", async () => {+ const { adapter } = await startSession();+ await expect(adapter.contextUsage(SESSION)).resolves.toEqual({+ usedTokens: 134000,+ windowTokens: 1000000,+ });+ });+});+describe('ClaudeAdapter model switching', () => {it('clears an explicit effort when the user selects the provider default', async () => {const { sdk, adapter } = await startSession();diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.tsindex f9fa3a5b3..6d11c7303 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts@@ -654,6 +654,11 @@ export class ClaudeAdapter implements ProviderAdapter {});}+ async contextUsage(sessionId: string): Promise<{ usedTokens: number; windowTokens: number }> {+ const usage = await this.requireSession(sessionId).query.getContextUsage({ detail: 'summary' });+ return { usedTokens: usage.totalTokens, windowTokens: usage.maxTokens };+ }+async setModel(sessionId: string, model: ModelSelection): Promise<void> {const session = this.requireSession(sessionId);await this.applyModel(session, model);diff --git a/console/packages/agent-providers/src/claude/fake-sdk.ts b/console/packages/agent-providers/src/claude/fake-sdk.tsindex 44c6c3dbe..f5d739c62 100644--- a/console/packages/agent-providers/src/claude/fake-sdk.ts+++ b/console/packages/agent-providers/src/claude/fake-sdk.ts@@ -67,6 +67,10 @@ export class FakeQuery {return Promise.resolve();}+ getContextUsage(): Promise<{ totalTokens: number; maxTokens: number }> {+ return Promise.resolve({ totalTokens: 134000, maxTokens: 1000000 });+ }+applyFlagSettings(settings: unknown): Promise<void> {this.flagSettingsCalls.push(settings);return Promise.resolve();diff --git a/console/packages/agent-providers/src/codex/codex-adapter.test.ts b/console/packages/agent-providers/src/codex/codex-adapter.test.tsindex 7fcff39db..1b906dd9f 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.test.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.test.ts@@ -303,6 +303,10 @@ describe('CodexAdapter', () => {},],]);+ await expect(adapter.contextUsage('session-1')).resolves.toEqual({+ usedTokens: 164,+ windowTokens: null,+ });});it("counts a resumed thread from its first report, not from the thread's history", async () => {diff --git a/console/packages/agent-providers/src/codex/codex-adapter.ts b/console/packages/agent-providers/src/codex/codex-adapter.tsindex b053c447b..c3d762021 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.ts@@ -120,6 +120,8 @@ interface CodexSessionState {*/usage: CumulativeUsage;unreportedUsage: TokenUsage[];+ /** The last model call's size against the window, cleared when a compaction makes it stale. */+ context?: { usedTokens: number; windowTokens: number | null };}interface ThreadModeConfig {@@ -483,6 +485,12 @@ export class CodexAdapter implements ProviderAdapter {});}+ async contextUsage(+ sessionId: string+ ): Promise<{ usedTokens: number; windowTokens: number | null } | null> {+ return this.requireSession(sessionId).context ?? null;+ }+async compactSession(sessionId: string): Promise<void> {const state = this.requireSession(sessionId);if (state.activeNativeTurnId || state.compaction) throw new Error('SESSION_BUSY');@@ -495,6 +503,7 @@ export class CodexAdapter implements ProviderAdapter {void promise.catch(() => {});const pending = { promise, resolve, reject };state.compaction = pending;+ state.context = undefined;try {await state.client.request('thread/compact/start', { threadId: state.threadId });await pending.promise;@@ -618,6 +627,12 @@ export class CodexAdapter implements ProviderAdapter {const payload = params as CodexThreadTokenUsageUpdatedNotification;if (!this.isOwnThread(state, payload.threadId)) return;const { total, last } = payload.tokenUsage;+ // The compaction call's own report measures the history it replaced.+ if (!state.compaction)+ state.context = {+ usedTokens: last.totalTokens,+ windowTokens: payload.tokenUsage.modelContextWindow,+ };if (!state.usage.started) {state.usage.startFrom(new Map([['', subtractCodexUsage(codexCounts(total), codexCounts(last))]])diff --git a/console/packages/agent-providers/src/host/agent-host.test.ts b/console/packages/agent-providers/src/host/agent-host.test.tsindex 0474a2d29..fd515fe9b 100644--- a/console/packages/agent-providers/src/host/agent-host.test.ts+++ b/console/packages/agent-providers/src/host/agent-host.test.ts@@ -777,6 +777,80 @@ it('routes to the session Console moved the room to, and tells Switch where ever});});+it('warms a room once: starts its session unasked, and the first message goes to it', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-warm-'));+ roots.push(root);+ paths.root = root;+ const config = await spawning(root);+ const hosts = sessionHosts();+ const control = new WatcherControl();++ const abort = new AbortController();+ const run = runAgentHost(+ root,+ config,+ abort.signal,+ hosts.supervision,+ control,+ openSwitchStream+ );+ let warmed: string | null = null;+ try {+ await eventually(() => streams.length === 1);+ warmed = await control.warm('room');+ expect(warmed).not.toBeNull();+ expect(published.at(-1)).toEqual({ [warmed!]: 'room' });+ expect(await control.warm('room')).toBe(warmed);+ await streams[0]!.onEvent!(addressed(1, 'room'));+ await eventually(() => settled(root));+ } finally {+ abort.abort();+ await run;+ }++ expect(+ new Set(+ vi.mocked(ensureSharedProcess).mock.calls.map((call) => call[0].config.session.sessionId)+ )+ ).toEqual(new Set([warmed]));+ expect(hosts.to(join(root, warmed!))).toMatchObject([+ { type: 'room', handoff: { sequence: 1, roomId: 'room', messageId: 'message-1' } },+ ]);+ const journal = await AgentHostAssignments.open(root);+ expect(journal.sessions().map((each) => each.session.sessionId)).toEqual([warmed]);+ expect(journal.cursor).toBe(1);+ await expect(control.warm('room')).rejects.toThrow('not running');+});++it('warms nothing while the agent may not start sessions', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-warm-off-'));+ roots.push(root);+ paths.root = root;+ const config = await spawning(root);+ await stopSpawning(root);+ const hosts = sessionHosts();+ const control = new WatcherControl();++ const abort = new AbortController();+ const run = runAgentHost(+ root,+ config,+ abort.signal,+ hosts.supervision,+ control,+ openSwitchStream+ );+ try {+ await eventually(() => streams.length === 1);+ expect(await control.warm('room')).toBeNull();+ } finally {+ abort.abort();+ await run;+ }+ expect(vi.mocked(ensureSharedProcess)).not.toHaveBeenCalled();+ expect((await AgentHostAssignments.open(root)).sessions()).toEqual([]);+});+it('puts a move Console asked for back when Switch refuses it', async () => {const root = await mkdtemp(join(tmpdir(), 'shared-watch-place-refused-'));roots.push(root);diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.tsindex a527db5d5..1befa5118 100644--- a/console/packages/agent-providers/src/host/agent-host.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -52,6 +52,16 @@ const assignmentSchema = z.strictObject({config: sharedConfigSchema,});+/**+ * 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.+ */+const warmedSchema = z.strictObject({+ warmed: z.literal(true),+ roomId: z.string().min(1),+ config: sharedConfigSchema,+});+/** Marks where the server's sequence numbering restarted. */const restartSchema = z.strictObject({ restarted: z.literal(true), at: z.string().min(1) });@@ -97,9 +107,11 @@ export const assignmentRecordSchema = z.union([handledSchema,parkedSchema,releasedSchema,+ warmedSchema,]);type Assignment = z.infer<typeof assignmentSchema>;+type Assigned = Assignment | z.infer<typeof warmedSchema>;type Held = Handoff & { spawning: boolean };type WatchRecord = z.infer<typeof assignmentRecordSchema>;@@ -125,6 +137,11 @@ function isReset(command: Record<string, unknown>): boolean {}function isAssignment(record: WatchRecord): record is Assignment {+ return 'sequence' in record;+}++/** An assignment or a warmed session: a session this watcher started for a room. */+function isAssigned(record: WatchRecord): record is Assigned {return 'config' in record;}@@ -421,8 +438,8 @@ export class AgentHostAssignments {return records.slice(index + 1);}- private get every(): Assignment[] {- return this.journal.records.filter(isAssignment);+ private get every(): Assigned[] {+ return this.journal.records.filter(isAssigned);}/** Held deliveries this journal has finished with, by room and message. */@@ -590,6 +607,17 @@ export class AgentHostAssignments {return config;}+ /** A new session for a room no message has reached yet. */+ async warm(template: SharedHostConfig, roomId: string): Promise<SharedHostConfig> {+ if (!template.roomConnection?.connectionId)+ throw new Error('A watcher assignment needs the connection its agent is reached over.');+ const sessionId = randomUUID();+ const config = sessionFrom(template, sessionId);+ await mkdir(sharedSessionRoot(sessionId), { recursive: true });+ await this.journal.append({ warmed: true, roomId, config });+ return config;+ }+/** The config this journal assigned a session under, or null if it assigned none. */configOf(sessionId: string): SharedHostConfig | null {return (@@ -1392,6 +1420,32 @@ export async function runAgentHost();return { sessionId, roomId, ...moved };},+ // Queued with the events, so a message arriving meanwhile finds the+ // session this placed rather than starting a second one.+ warm: (roomId) => {+ const run = async (): Promise<string | null> => {+ const placed = placements.sessionIn(roomId);+ if (placed) {+ const owner = await sessionConfig(placed);+ if (owner && !(await stopped(placed))) {+ if (!links.ready(sharedSessionRoot(placed))) await launch(owner);+ return placed;+ }+ }+ if (!spawn) return null;+ const config = await assignments.warm(await currentTemplate(), roomId);+ await placements.place(config.session.sessionId, roomId);+ publishQuietly();+ await launch(config);+ return config.session.sessionId;+ };+ const warmed = pending.then(run);+ pending = warmed.then(+ () => {},+ () => {}+ );+ return warmed;+ },}));// Queued behind the events rather than run beside them: the decision itdiff --git a/console/packages/agent-providers/src/host/control.test.ts b/console/packages/agent-providers/src/host/control.test.tsindex 045ce92e0..d851da12c 100644--- a/console/packages/agent-providers/src/host/control.test.ts+++ b/console/packages/agent-providers/src/host/control.test.ts@@ -4,7 +4,9 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { connect } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { PassThrough } from 'node:stream';import { afterEach, expect, it, vi } from 'vitest';+import { z } from 'zod';import { AttachmentTransfers } from './attachment-transfers';import { CONTROL_FILE, ControlClient, ensureSessions, serveControl } from './control';import type { Supervision } from './launch';@@ -50,10 +52,21 @@ function host() {return child;}+/** Gives `sessionId` a saved configuration naming `agentId`, as its host's launch writes it. */+async function saved(base: string, sessionId: string, agentId: string): Promise<void> {+ await mkdir(join(base, sessionId), { recursive: true });+ await writeFile(+ join(base, sessionId, 'config.json'),+ JSON.stringify({ session: { sessionId, agentId } })+ );+}+async function started() {const base = await mkdtemp(join(tmpdir(), 'control-'));roots.push(base);paths.base = base;+ for (const id of ['session', 'stopped', 'gone', 'elsewhere']) await saved(base, id, 'agent');+ await saved(base, 'theirs', 'other');const links = new SessionLinks();const ensure = vi.fn(async () => ({ created: true }));const stop = new AbortController();@@ -181,6 +194,111 @@ it('answers at once for a session nothing is running', async () => {await serving;});+it('never reads or commands a session of another agent', async () => {+ const { base, links, stop, serving, client, watcher } = await started();+ const sessionRoot = join(base, 'theirs');+ await writeFile(join(sessionRoot, 'running'), 'yes');+ const child = host();+ const sent = vi.spyOn(child, 'send');+ links.attach(sessionRoot, child as unknown as ChildProcess);+ child.emit('message', { kind: 'ready' });+ const placed = vi.fn();+ const forgot = vi.fn();+ const unbind = watcher.bind({ place: placed, forget: forgot, warm: vi.fn() });++ const console = client();+ await console.ready;+ const refused = 'not a session of agent agent';+ for (const id of ['theirs', 'unknown']) {+ await expect(console.request(id, { type: 'snapshot' })).rejects.toThrow(refused);+ if (id === 'theirs')+ await expect(+ console.subscribe(+ id,+ () => {},+ () => {}+ )+ ).rejects.toThrow(refused);+ // No public method sends these two; the port must still refuse them.+ await expect(console['call']({ journal: id })).rejects.toThrow(refused);+ const chunk = {+ transferId: 't1',+ sessionId: id,+ name: 'a.txt',+ mimeType: 'text/plain',+ size: 1,+ sha256: '0'.repeat(64),+ index: 0,+ count: 1,+ chunk: 'YQ==',+ };+ await expect(console['call']({ attachment: chunk })).rejects.toThrow(refused);+ await expect(console.place(id, 'room')).rejects.toThrow(refused);+ if (id === 'theirs') await expect(console.forget(id)).rejects.toThrow(refused);+ await expect(console.reasoning(id, null)).rejects.toThrow(refused);+ }+ expect(sent).not.toHaveBeenCalled();+ expect(placed).not.toHaveBeenCalled();+ expect(forgot).not.toHaveBeenCalledWith('theirs');++ unbind();+ console.close();+ stop.abort();+ await serving;+});++it('forgets a session with no config and waits on one until its config is saved', async () => {+ const { base, links, stop, serving, client, watcher } = await started();+ const forgot = vi.fn();+ const unbind = watcher.bind({ place: vi.fn(), forget: forgot, warm: vi.fn() });+ const console = client();+ await console.ready;++ await console.forget('deleted');+ expect(forgot).toHaveBeenCalledWith('deleted');++ const watch = async (id: string) => {+ const root = join(base, id);+ await mkdir(root, { recursive: true });+ const child = host();+ links.attach(root, child as unknown as ChildProcess);+ const heard: number[] = [];+ const failures: (string | null)[] = [];+ const off = await console.subscribe(+ id,+ (pushed) => heard.push(pushed.sequence),+ (failure) => failures.push(failure)+ );+ return { child, heard, failures, off };+ };++ const mine = await watch('starting');+ expect(mine.failures).toEqual([null]);+ mine.child.emit('message', { kind: 'event', event: event(1) });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(mine.heard).toEqual([]);+ await saved(base, 'starting', 'agent');+ mine.child.emit('message', { kind: 'event', event: event(2) });+ await vi.waitFor(() => expect(mine.heard).toEqual([2]));+ mine.off();++ const foreign = await watch('claimed');+ await saved(base, 'claimed', 'other');+ foreign.child.emit('message', { kind: 'event', event: event(1) });+ await vi.waitFor(() =>+ expect(foreign.failures).toEqual([null, 'Session claimed is not a session of agent agent.'])+ );+ foreign.child.emit('message', { kind: 'event', event: event(2) });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(foreign.heard).toEqual([]);+ await expect(console.place('claimed', 'room')).rejects.toThrow('not a session of agent agent');++ unbind();+ console.close();+ stop.abort();+ await serving;+});+it('refuses a client without the secret', async () => {const { stop, serving, client } = await started();await expect(client('wrong').ready).rejects.toThrow();@@ -200,9 +318,12 @@ it('moves a room to a session through the watcher, and says why when it cannot',displaced: 'other',}));const forgot = vi.fn(async () => {});- const unbind = watcher.bind({ place: placed, forget: forgot });+ const warmed = vi.fn(async (roomId: string) => `session-for-${roomId}`);+ const unbind = watcher.bind({ place: placed, forget: forgot, warm: warmed });await console.forget('gone');expect(forgot).toHaveBeenCalledWith('gone');+ expect(await console.warm('room')).toBe('session-for-room');+ expect(warmed).toHaveBeenCalledWith('room');expect(await console.place('session', 'room')).toEqual({sessionId: 'session',roomId: 'room',@@ -417,3 +538,60 @@ it('starts a session whose start source is newer than this sidecar, as not knownstop.abort();await serving;});++it('answers a reasoning ask from the session host, and from no host with none', async () => {+ const { base, links, stop, serving, client, watcher } = await started();+ const sessionRoot = join(base, 'session');+ const list = { epoch: 'epoch', turns: [] };+ const child = host();+ const asked: unknown[] = [];+ child.send = (message, callback) => {+ callback(null);+ const { id, request } = message as { id: number; request: unknown };+ asked.push(request);+ setImmediate(() => child.emit('message', { kind: 'reply', id, ok: true, value: list }));+ return true;+ };+ links.attach(sessionRoot, child as unknown as ChildProcess);+ child.emit('message', { kind: 'ready' });++ const console = client();+ await console.ready;+ expect(await console.reasoning('session', ['turn'])).toEqual(list);+ expect(asked).toEqual([{ type: 'reasoning', turnIds: ['turn'] }]);+ expect(await console.reasoning('elsewhere', null)).toBeNull();+ expect(await console.request('session', { type: 'reasoning', turnIds: null })).toEqual(list);+ // A plain health ask is still a health ask.+ expect(await console.health()).toEqual(watcher.health());++ console.close();+ stop.abort();+ await serving;+});++it('reads as a health ask to a sidecar that predates reasoning, so its connection stays up', async () => {+ const stream = new PassThrough();+ const toSidecar: string[] = [];+ const duplex = Object.assign(stream, {+ write: (line: string) => {+ toSidecar.push(line);+ const message = JSON.parse(line) as Record<string, unknown>;+ // What an older sidecar parses the line as: its plain health message.+ const old = z.object({ id: z.number().int(), health: z.literal(true) }).safeParse(message);+ if ('token' in message) setImmediate(() => stream.emit('data', '{"authenticated":true}\n'));+ else if (old.success)+ setImmediate(() =>+ stream.emit(+ 'data',+ `${JSON.stringify({ id: old.data.id, ok: true, value: { state: 'connected' } })}\n`+ )+ );+ return true;+ },+ });+ const console = new ControlClient(duplex, 'token');+ await console.ready;+ expect(await console.reasoning('session', null)).toEqual({ state: 'connected' });+ expect(console.isClosed).toBe(false);+ expect(toSidecar).toHaveLength(2);+});diff --git a/console/packages/agent-providers/src/host/control.ts b/console/packages/agent-providers/src/host/control.tsindex c0e20e6e7..f0996929b 100644--- a/console/packages/agent-providers/src/host/control.ts+++ b/console/packages/agent-providers/src/host/control.ts@@ -1,5 +1,5 @@import { randomBytes } from 'node:crypto';-import { rm, writeFile } from 'node:fs/promises';+import { readFile, rm, writeFile } from 'node:fs/promises';import { createServer, type Socket } from 'node:net';import { join } from 'node:path';import type { Duplex } from 'node:stream';@@ -42,10 +42,7 @@ import {export const CONTROL_FILE = 'control.json';-/**- * One message Console sends a sidecar or a watcher, whether over the loopback- * socket or relayed through Switch: the one vocabulary both paths answer.- */+/** One message Console sends a sidecar or a watcher over the loopback socket. */export const controlMessageSchema = z.union([z.object({ sessionId: z.string().min(1), request: sessionRequestSchema }),z.object({ subscribe: z.string().min(1) }),@@ -66,6 +63,22 @@ export const controlMessageSchema = z.union([/** Console's "Reconnect to room": move a room's messages to this session. */z.object({ place: z.object({ sessionId: z.string().min(1), roomId: z.string().min(1) }) }),z.object({ forget: z.string().min(1) }),+ /** Start the session a message to this room would start, before the message is sent. */+ z.object({ warm: z.object({ roomId: z.string().min(1) }) }),+ /**+ * A session's buffered reasoning, from its host. It rides on a `health`+ * message because a sidecar that predates it closes the connection on any+ * message it cannot parse, while it reads this one as `health` — dropping+ * the key it does not know — and answers with its health, which the asker+ * reads as no reasoning. Must stay ahead of the plain `health` below.+ */+ z.object({+ health: z.literal(true),+ reasoning: z.object({+ sessionId: z.string().min(1),+ turnIds: z.array(z.string().min(1)).nullable(),+ }),+ }),/** The room watcher's connection state and placements, as it holds them now. */z.object({ health: z.literal(true) }),/** Start or stop pushing `{health}` to this connection whenever the watcher's changes. */@@ -74,10 +87,6 @@ export const controlMessageSchema = z.union([z.object({ list: z.literal(true) }),/** A session read from its journal, whether or not its host is running. */z.object({ journal: z.string().min(1) }),- /** One page of a paged answer; only the relay pages its answers. */- z.object({- page: z.object({ snapshotId: z.string().min(1), index: z.number().int().nonnegative() }),- }),z.object({ attachment: attachmentChunkSchema }),z.object({ attachmentCancel: z.string().min(1) }),]);@@ -125,7 +134,7 @@ const sentAttachmentsSchema = z.object({});/**- * Answer one control message; a refusal throws. `page` is the relay's.+ * Answer one control message; a refusal throws.* `dispatching` is called just before a session request is sent to its host.*/export async function handleControlMessage(@@ -135,8 +144,17 @@ export async function handleControlMessage(dispatching: () => void): Promise<unknown> {const { links, watcher } = context;+ // The sessions directory is shared by every agent on the machine.+ const named = namedSession(message);+ const owner = named === null ? null : await sessionOwner(named);+ // A session with no config yet may be waited on or forgotten, nothing else.+ const unconfigured = owner === null && ('subscribe' in message || 'forget' in message);+ if (named !== null && !unconfigured && owner !== context.agentId)+ throw notOwnSession(context.agentId, named);if ('request' in message) {const sessionRoot = sharedSessionRoot(message.sessionId);+ if (message.request.type === 'reasoning')+ return links.reasoning(sessionRoot, message.request.turnIds);if (message.request.type === 'command') {const sent = sentAttachmentsSchema.safeParse(message.request.command);if (sent.success)@@ -150,13 +168,20 @@ export async function handleControlMessage(const sessionId = message.subscribe;const sessionRoot = sharedSessionRoot(sessionId);if (!peer.subscriptions.has(sessionId)) {- const offEvents = links.subscribe(sessionRoot, (event) => peer.send({ sessionId, event }));+ const unsubscribe = () => {+ peer.subscriptions.get(sessionId)?.();+ peer.subscriptions.delete(sessionId);+ };+ const send = unconfigured+ ? ownedSender(context.agentId, sessionId, peer.send, unsubscribe)+ : peer.send;+ const offEvents = links.subscribe(sessionRoot, (event) => send({ sessionId, event }));const offFailure = links.onFailure((failed, failure) => {- if (failed === sessionRoot) peer.send({ sessionId, failure });+ if (failed === sessionRoot) send({ sessionId, failure });});// A host that comes up again has put its failure behind it.const offReady = links.onReady((ready) => {- if (ready === sessionRoot) peer.send({ sessionId, failure: null });+ if (ready === sessionRoot) send({ sessionId, failure: null });});peer.subscriptions.set(sessionId, () => {offEvents();@@ -166,7 +191,7 @@ export async function handleControlMessage(}// Answered with the failure already recorded, so a subscriber that// arrives after the host stopped still hears why.- return { failure: links.failure(sessionRoot) };+ return { failure: unconfigured ? null : links.failure(sessionRoot) };}if ('unsubscribe' in message) {peer.subscriptions.get(message.unsubscribe)?.();@@ -175,6 +200,12 @@ export async function handleControlMessage(}if ('place' in message) return watcher.place(message.place.sessionId, message.place.roomId);if ('forget' in message) return watcher.forget(message.forget);+ if ('warm' in message) return watcher.warm(message.warm.roomId);+ if ('reasoning' in message)+ return links.reasoning(+ sharedSessionRoot(message.reasoning.sessionId),+ message.reasoning.turnIds+ );if ('health' in message) return watcher.health();if ('watchHealth' in message) {if (message.watchHealth)@@ -187,8 +218,6 @@ export async function handleControlMessage(}if ('list' in message) return listSessions(context.agentId);if ('journal' in message) return readJournalSnapshot(message.journal);- if ('page' in message)- throw new ControlError('refused_message', 'Pages are served only to relayed answers.');if ('attachment' in message) return context.transfers.receive(message.attachment);if ('attachmentCancel' in message) return context.transfers.cancel(message.attachmentCancel);return context.ensure(message.ensure);@@ -221,6 +250,75 @@ export function ensureSessions(supervision: Supervision): EnsureSession {};}+/** The session a message names, if it names one. */+function namedSession(message: ControlMessage): string | null {+ if ('request' in message) return message.sessionId;+ if ('subscribe' in message) return message.subscribe;+ if ('place' in message) return message.place.sessionId;+ if ('forget' in message) return message.forget;+ if ('journal' in message) return message.journal;+ if ('reasoning' in message) return message.reasoning.sessionId;+ if ('attachment' in message) return message.attachment.sessionId;+ return null;+}++/** The agent a session's saved configuration names, or null while it has none. */+async function sessionOwner(sessionId: string): Promise<unknown> {+ try {+ const text = await readFile(join(sharedSessionRoot(sessionId), 'config.json'), 'utf8');+ const owner = (JSON.parse(text) as { session?: { agentId?: unknown } } | null)?.session+ ?.agentId;+ return owner ?? undefined;+ } catch (error) {+ // A config being written can read as truncated JSON.+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError)+ return null;+ throw error;+ }+}++function notOwnSession(agentId: string, sessionId: string): ControlError {+ return new ControlError(+ 'not_own_session',+ `Session ${sessionId} is not a session of agent ${agentId}.`+ );+}++/**+ * `send` for a subscription made before the session had a config: holds+ * every push until a config names `agentId`, and ends the subscription with+ * a failure once one names another agent. Pushes keep their order.+ */+function ownedSender(+ agentId: string,+ sessionId: string,+ send: (push: ControlPush) => void,+ unsubscribe: () => void+): (push: ControlPush) => void {+ let state: 'unknown' | 'own' | 'foreign' = 'unknown';+ let chain = Promise.resolve();+ return (push) => {+ chain = chain+ .then(async () => {+ if (state === 'unknown') {+ const owner = await sessionOwner(sessionId);+ if (owner === null) return;+ state = owner === agentId ? 'own' : 'foreign';+ if (state === 'foreign') {+ unsubscribe();+ send({ sessionId, failure: notOwnSession(agentId, sessionId).message });+ }+ }+ if (state === 'own') send(push);+ })+ .catch((error: unknown) => {+ state = 'foreign';+ unsubscribe();+ send({ sessionId, failure: `Session ${sessionId} could not be checked: ${String(error)}` });+ });+ };+}+/** How long a request waits for the session's host to be ready. */const REQUEST_WAIT_MS = 30000;@@ -379,7 +477,14 @@ export class ControlClient {stream.on('error', (error: Error) => fail(error));stream.on('close', () => fail(new SidecarConnectionClosedError()));lines(stream, (line) => {- const message = serverMessageSchema.safeParse(JSON.parse(line));+ let json: unknown;+ try {+ json = JSON.parse(line);+ } catch {+ stream.destroy(new Error('The control port sent a line that is not JSON.'));+ return;+ }+ const message = serverMessageSchema.safeParse(json);if (!message.success) return;const data = message.data;if ('authenticated' in data) authenticate();@@ -421,6 +526,14 @@ export class ControlClient {return this.call({ sessionId, request });}+ /**+ * A session's buffered reasoning, or what an older sidecar answers instead+ * (its health): parse the answer, and read anything else as no reasoning.+ */+ reasoning(sessionId: string, turnIds: string[] | null): Promise<unknown> {+ return this.call({ health: true, reasoning: { sessionId, turnIds } });+ }+ensure(input: {config: unknown;resuming: boolean;@@ -440,6 +553,14 @@ export class ControlClient {await this.call({ forget: sessionId });}+ /** Start the session a message to this room would start, through the sidecar's room watcher. */+ async warm(roomId: string): Promise<string | null> {+ return z+ .string()+ .nullable()+ .parse(await this.call({ warm: { roomId } }));+ }+/** The sidecar's room watcher: its connection state and placements. */async health(): Promise<WatcherHealth> {return watcherHealthSchema.parse(await this.call({ health: true }));diff --git a/console/packages/agent-providers/src/host/reasoning-buffer.test.ts b/console/packages/agent-providers/src/host/reasoning-buffer.test.tsnew file mode 100644index 000000000..f8f535c30--- /dev/null+++ b/console/packages/agent-providers/src/host/reasoning-buffer.test.ts@@ -0,0 +1,145 @@+import { expect, it } from 'vitest';+import type { ProviderItem, ProviderRuntimeEvent } from '../events';+import { REASONING_TEXT_LIMIT, REASONING_TURN_LIMIT, ReasoningBuffer } from './reasoning-buffer';++const base = { eventId: 'e', provider: 'codex', sessionId: 'session', createdAt: '' } as const;++function itemEvent(+ type: 'item.started' | 'item.updated' | 'item.completed',+ turnId: string,+ item: Partial<ProviderItem> & { id: string }+): ProviderRuntimeEvent {+ return {+ ...base,+ type,+ turnId,+ item: { type: 'reasoning', status: 'in_progress', title: '', ...item },+ };+}++function delta(turnId: string, itemId: string, text: string): ProviderRuntimeEvent {+ return { ...base, type: 'item.delta', turnId, itemId, delta: text };+}++const at = (seconds: number) => Date.parse('2026-10-08T12:00:00.000Z') + seconds * 1000;+const iso = (seconds: number) => new Date(at(seconds)).toISOString();++it('times a reasoning item from its start to its completion (Codex, OpenCode)', () => {+ const buffer = new ReasoningBuffer();+ buffer.ingest(itemEvent('item.started', 'turn', { id: 'r1' }), 'epoch', at(0));+ buffer.ingest(delta('turn', 'r1', 'Look at '), 'epoch', at(1));+ buffer.ingest(delta('turn', 'r1', 'the file.'), 'epoch', at(2));+ expect(buffer.list('epoch', null)).toEqual({+ epoch: 'epoch',+ turns: [{ turnId: 'turn', text: 'Look at the file.', startedAt: iso(0), completedAt: null }],+ });+ buffer.ingest(+ itemEvent('item.completed', 'turn', {+ id: 'r1',+ status: 'completed',+ text: 'Look at the file.',+ }),+ 'epoch',+ at(4)+ );+ expect(buffer.list('epoch', ['turn']).turns).toEqual([+ { turnId: 'turn', text: 'Look at the file.', startedAt: iso(0), completedAt: iso(4) },+ ]);+});++it('takes the first delta as the start when the item itself carried none', () => {+ const buffer = new ReasoningBuffer();+ buffer.ingest(+ itemEvent('item.started', 'turn', { id: 'r1', status: 'completed', text: '' }),+ 'epoch',+ at(0)+ );+ expect(buffer.list('epoch', null).turns[0]!.startedAt).toBeNull();+ const fresh = new ReasoningBuffer();+ fresh.ingest(itemEvent('item.updated', 'turn', { id: 'r1', text: 'a' }), 'epoch', at(1));+ expect(fresh.list('epoch', null).turns[0]!.startedAt).toBe(iso(1));+});++it('leaves the start unknown for reasoning reported only on completion (Claude)', () => {+ const buffer = new ReasoningBuffer();+ buffer.ingest(+ itemEvent('item.completed', 'turn', { id: 'm#t0', status: 'completed', text: 'Hmm.' }),+ 'epoch',+ at(5)+ );+ expect(buffer.list('epoch', null).turns).toEqual([+ { turnId: 'turn', text: 'Hmm.', startedAt: null, completedAt: iso(5) },+ ]);+});++it('joins a turn’s reasoning items and stays open until each completes', () => {+ const joined = new ReasoningBuffer();+ joined.ingest(itemEvent('item.started', 'turn', { id: 'a', text: 'one' }), 'epoch', at(0));+ joined.ingest(itemEvent('item.started', 'turn', { id: 'b', text: 'two' }), 'epoch', at(2));+ joined.ingest(+ itemEvent('item.completed', 'turn', { id: 'a', status: 'completed' }),+ 'epoch',+ at(3)+ );+ expect(joined.list('epoch', null).turns[0]).toEqual({+ turnId: 'turn',+ text: 'one\n\ntwo',+ startedAt: iso(0),+ completedAt: null,+ });+ joined.ingest(+ itemEvent('item.completed', 'turn', { id: 'b', status: 'completed' }),+ 'epoch',+ at(6)+ );+ expect(joined.list('epoch', null).turns[0]!.completedAt).toBe(iso(6));+});++it('ignores everything but reasoning', () => {+ const buffer = new ReasoningBuffer();+ buffer.ingest(+ itemEvent('item.started', 'turn', { id: 'x', type: 'assistant_message', text: 'hello' }),+ 'epoch',+ at(0)+ );+ buffer.ingest(delta('turn', 'cmd', 'stdout'), 'epoch', at(0));+ buffer.ingest(+ { ...base, type: 'content.delta', turnId: 'turn', itemId: 'x', delta: 'more' },+ 'epoch',+ at(0)+ );+ expect(buffer.list('epoch', null).turns).toEqual([]);+});++it('keeps the most recent turns and the latest text of each, and drops another epoch', () => {+ const buffer = new ReasoningBuffer();+ for (let index = 0; index < REASONING_TURN_LIMIT + 5; index++)+ buffer.ingest(itemEvent('item.started', `turn-${index}`, { id: 'r' }), 'epoch', at(index));+ const turns = buffer.list('epoch', null).turns;+ expect(turns).toHaveLength(REASONING_TURN_LIMIT);+ expect(turns[0]!.turnId).toBe('turn-5');++ buffer.ingest(delta('turn-60', 'r', 'x'), 'epoch', at(0));+ buffer.ingest(+ delta(`turn-${REASONING_TURN_LIMIT + 4}`, 'r', 'a'.repeat(REASONING_TEXT_LIMIT)),+ 'epoch',+ at(0)+ );+ buffer.ingest(delta(`turn-${REASONING_TURN_LIMIT + 4}`, 'r', 'tail'), 'epoch', at(0));+ const last = buffer.list('epoch', [`turn-${REASONING_TURN_LIMIT + 4}`]).turns[0]!;+ expect(last.text).toHaveLength(REASONING_TEXT_LIMIT);+ expect(last.text.endsWith('tail')).toBe(true);++ for (let index = 0; index < 3; index++)+ buffer.ingest(+ itemEvent('item.started', 'many', { id: `r${index}`, text: 'b'.repeat(20000) }),+ 'epoch',+ at(0)+ );+ const many = buffer.list('epoch', ['many']).turns[0]!;+ expect(many.text.length).toBeLessThanOrEqual(REASONING_TEXT_LIMIT);++ expect(buffer.list('other', null)).toEqual({ epoch: 'other', turns: [] });+ buffer.ingest(itemEvent('item.started', 'fresh', { id: 'r' }), 'next', at(0));+ expect(buffer.list('next', null).turns.map((turn) => turn.turnId)).toEqual(['fresh']);+});diff --git a/console/packages/agent-providers/src/host/reasoning-buffer.ts b/console/packages/agent-providers/src/host/reasoning-buffer.tsnew file mode 100644index 000000000..647670a29--- /dev/null+++ b/console/packages/agent-providers/src/host/reasoning-buffer.ts@@ -0,0 +1,165 @@+import { z } from 'zod';+import type { ProviderRuntimeEvent } from '../events';+import { hostToolTurnSchema } from './tool-detail-buffer';++/**+ * The model's reasoning for recent turns, held in memory by the session host+ * and nowhere else.+ *+ * Reasoning is a local side channel: it is never recorded as a session-v1+ * event, never journaled, never in a snapshot or a replay, and never sent to+ * Switch. A Console on the same machine (or over SSH) asks for it with a+ * `reasoning` request and gets what is still buffered; a host restart, a+ * reset (a new epoch) or age drops it.+ *+ * Timing is only what the provider said: `startedAt` comes from a real start+ * signal (the reasoning item starting in progress, or its first delta), and+ * `completedAt` from the item completing. A provider that only reports+ * reasoning once it is done (Claude) leaves `startedAt` null rather than+ * having one made up from the completion.+ */++/** How many turns are kept; the oldest go first. */+export const REASONING_TURN_LIMIT = 50;+/** How much reasoning text one turn keeps, in UTF-16 code units; the latest is kept. */+export const REASONING_TEXT_LIMIT = 32 * 1024;+/** How many reasoning items one turn keeps; the oldest go first. */+const REASONING_ITEM_LIMIT = 256;++export const hostReasoningTurnSchema = z.object({+ turnId: z.string().min(1),+ text: z.string(),+ startedAt: z.string().nullable(),+ completedAt: z.string().nullable(),+});+export type HostReasoningTurn = z.infer<typeof hostReasoningTurnSchema>;++export const hostReasoningListSchema = z.object({+ epoch: z.string().min(1),+ turns: z.array(hostReasoningTurnSchema),+ /**+ * What the turns' tool calls were given and gave back, from the+ * `ToolDetailBuffer`. Rides on the reasoning answer so it reaches Console by+ * the same local-or-SSH path; a host that predates it leaves it out.+ */+ tools: z.array(hostToolTurnSchema).optional(),+});+export type HostReasoningList = z.infer<typeof hostReasoningListSchema>;++type ReasoningItem = { text: string; startedAt: number | null; completedAt: number | null };+type ReasoningTurnEntry = { items: Map<string, ReasoningItem> };++function tail(text: string): string {+ return text.length > REASONING_TEXT_LIMIT ? text.slice(text.length - REASONING_TEXT_LIMIT) : text;+}++export class ReasoningBuffer {+ private epoch: string | null = null;+ /** In insertion order, so the first entry is the oldest turn. */+ private readonly turns = new Map<string, ReasoningTurnEntry>();++ /** Take one provider event, for the session's current epoch. Ignores all but reasoning. */+ ingest(event: ProviderRuntimeEvent, epoch: string, now: number): void {+ if (this.epoch !== epoch) {+ this.turns.clear();+ this.epoch = epoch;+ }+ switch (event.type) {+ case 'item.started':+ case 'item.updated':+ case 'item.completed': {+ if (event.item.type !== 'reasoning') return;+ const item = this.item(event.turnId, event.item.id, true)!;+ if (event.item.text !== undefined && event.item.text.length > 0)+ item.text = tail(event.item.text);+ // An item that first appears already finished carries no start signal.+ if (item.startedAt === null && event.type !== 'item.completed') {+ if (event.item.status === 'in_progress') item.startedAt = now;+ }+ if (event.type === 'item.completed' || event.item.status !== 'in_progress')+ item.completedAt ??= now;+ this.trim(event.turnId);+ return;+ }+ case 'item.delta':+ case 'content.delta': {+ const item = this.item(event.turnId, event.itemId, false);+ if (!item || event.delta.length === 0) return;+ item.text = tail(item.text + event.delta);+ item.startedAt ??= now;+ this.trim(event.turnId);+ return;+ }+ default:+ return;+ }+ }++ /** What is buffered for `turnIds` (every turn when null), oldest first. */+ list(epoch: string, turnIds: string[] | null): HostReasoningList {+ if (this.epoch !== epoch) return { epoch, turns: [] };+ const wanted = turnIds === null ? null : new Set(turnIds);+ const turns: HostReasoningTurn[] = [];+ for (const [turnId, entry] of this.turns) {+ if (wanted && !wanted.has(turnId)) continue;+ const items = [...entry.items.values()];+ const starts = items.flatMap((item) => (item.startedAt === null ? [] : [item.startedAt]));+ const open = items.some((item) => item.completedAt === null);+ const completions = items.flatMap((item) =>+ item.completedAt === null ? [] : [item.completedAt]+ );+ turns.push({+ turnId,+ text: tail(+ items+ .map((item) => item.text)+ .filter((text) => text.length > 0)+ .join('\n\n')+ ),+ startedAt: starts.length > 0 ? new Date(Math.min(...starts)).toISOString() : null,+ completedAt:+ !open && completions.length > 0 ? new Date(Math.max(...completions)).toISOString() : null,+ });+ }+ return { epoch, turns };+ }++ /** Keep a turn within its text and item limits by dropping its oldest reasoning first. */+ private trim(turnId: string): void {+ const entry = this.turns.get(turnId);+ if (!entry) return;+ while (entry.items.size > REASONING_ITEM_LIMIT) {+ const oldest = entry.items.keys().next().value;+ if (oldest === undefined) break;+ entry.items.delete(oldest);+ }+ let excess = -REASONING_TEXT_LIMIT;+ for (const item of entry.items.values()) excess += item.text.length;+ for (const item of entry.items.values()) {+ if (excess <= 0) break;+ const cut = Math.min(excess, item.text.length);+ item.text = item.text.slice(cut);+ excess -= cut;+ }+ }++ private item(turnId: string, itemId: string, create: boolean): ReasoningItem | null {+ let entry = this.turns.get(turnId);+ if (!entry) {+ if (!create) return null;+ entry = { items: new Map() };+ this.turns.set(turnId, entry);+ while (this.turns.size > REASONING_TURN_LIMIT) {+ const oldest = this.turns.keys().next().value;+ if (oldest === undefined) break;+ this.turns.delete(oldest);+ }+ }+ let item = entry.items.get(itemId);+ if (!item && create) {+ item = { text: '', startedAt: null, completedAt: null };+ entry.items.set(itemId, item);+ }+ return item ?? null;+ }+}diff --git a/console/packages/agent-providers/src/host/room-control-followup.ts b/console/packages/agent-providers/src/host/room-control-followup.tsindex 633c57aa8..78909c452 100644--- a/console/packages/agent-providers/src/host/room-control-followup.ts+++ b/console/packages/agent-providers/src/host/room-control-followup.ts@@ -27,3 +27,10 @@ export function roomControlFollowup(input: {export function followupCommandId(commandId: string): string {return `${commandId}:followup`;}++/** What the room is told when the session refused a reset or compaction asked for there. */+export function roomControlRefusal(action: 'reset' | 'compact', reason: string | null): string {+ if (reason?.includes('SESSION_BUSY'))+ return `I can't ${action} my session while I'm working on a turn. Ask again once I've finished, or stop the turn first.`;+ return `I couldn't ${action} my session: ${reason?.replace(/^Error: /, '') || 'the session refused it.'}`;+}diff --git a/console/packages/agent-providers/src/host/session-channel.test.ts b/console/packages/agent-providers/src/host/session-channel.test.tsindex dcde538c6..f6fa4a8db 100644--- a/console/packages/agent-providers/src/host/session-channel.test.ts+++ b/console/packages/agent-providers/src/host/session-channel.test.ts@@ -162,6 +162,7 @@ it('serves requests on the host side once it has handlers', async () => {room: async () => null,snapshot: async () => 'snapshot',approvals: async () => null,+ reasoning: async () => null,});served.ready();served.push(event(3) as never);@@ -416,3 +417,94 @@ it('tells a request waiting on a host that the host stopped, rather than at itsawait expect(waiting).rejects.toThrow('stopped before it was ready');expect(Date.now() - started).toBeLessThan(5000);});++const REASONING = {+ epoch: 'epoch',+ turns: [+ {+ turnId: 'turn',+ text: 'thinking',+ startedAt: '2026-09-24T12:00:00.000Z',+ completedAt: '2026-09-24T12:00:03.000Z',+ },+ ],+};++it('asks a ready host for its reasoning, and asks nothing of a host that is not ready', async () => {+ const links = new SessionLinks();+ expect(await links.reasoning('nowhere', null)).toBeNull();+ const child = fakeChild();+ links.attach('root', child as unknown as ChildProcess);+ expect(await links.reasoning('root', null)).toBeNull();+ expect(child.sent).toEqual([]);+ child.emit('message', { kind: 'ready' });+ const answer = links.reasoning('root', ['turn']);+ await vi.waitFor(() => expect(child.sent).toHaveLength(1));+ const [request] = child.sent as { id: number; request: unknown }[];+ expect(request!.request).toEqual({ type: 'reasoning', turnIds: ['turn'] });+ child.emit('message', { kind: 'reply', id: request!.id, ok: true, value: REASONING });+ expect(await answer).toEqual(REASONING);+});++it('reads an unreadable or refused reasoning answer as none', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const links = new SessionLinks();+ const child = fakeChild();+ links.attach('root', child as unknown as ChildProcess);+ child.emit('message', { kind: 'ready' });+ const unreadable = links.reasoning('root', null);+ await vi.waitFor(() => expect(child.sent).toHaveLength(1));+ child.emit('message', { kind: 'reply', id: (child.sent[0] as { id: number }).id, ok: true });+ expect(await unreadable).toBeNull();+ const refused = links.reasoning('root', null);+ await vi.waitFor(() => expect(child.sent).toHaveLength(2));+ child.emit('message', {+ kind: 'reply',+ id: (child.sent[1] as { id: number }).id,+ ok: false,+ error: 'no',+ });+ expect(await refused).toBeNull();+});++it('stops asking a host that predates reasoning, and asks the next host again', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.useFakeTimers();+ try {+ const links = new SessionLinks();+ // An older host cannot parse the request, so it only warns and never answers.+ const child = fakeChild();+ links.attach('root', child as unknown as ChildProcess);+ child.emit('message', { kind: 'ready' });+ const answer = links.reasoning('root', null);+ await vi.advanceTimersByTimeAsync(5000);+ expect(await answer).toBeNull();+ expect(child.sent).toHaveLength(1);+ expect(await links.reasoning('root', null)).toBeNull();+ expect(child.sent).toHaveLength(1);+ // The link still works for everything else.+ const snapshot = links.request('root', { type: 'snapshot' }, 1000);+ child.emit('message', {+ kind: 'reply',+ id: (child.sent[1] as { id: number }).id,+ ok: true,+ value: 's',+ });+ expect(await snapshot).toBe('s');++ const next = fakeChild();+ links.attach('root', next as unknown as ChildProcess);+ next.emit('message', { kind: 'ready' });+ const again = links.reasoning('root', null);+ await vi.waitFor(() => expect(next.sent).toHaveLength(1));+ next.emit('message', {+ kind: 'reply',+ id: (next.sent[0] as { id: number }).id,+ ok: true,+ value: REASONING,+ });+ expect(await again).toEqual(REASONING);+ } finally {+ vi.useRealTimers();+ }+});diff --git a/console/packages/agent-providers/src/host/session-channel.ts b/console/packages/agent-providers/src/host/session-channel.tsindex 9d20c7bbc..51feb8816 100644--- a/console/packages/agent-providers/src/host/session-channel.ts+++ b/console/packages/agent-providers/src/host/session-channel.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import { serverEventSchema, type ServerEvent } from '@switch-console/shared/session-v1';import { z } from 'zod';import { killProcessTree } from './process-fence';+import { hostReasoningListSchema, type HostReasoningList } from './reasoning-buffer';import { Redactions, tokenForms } from './redaction';import { ServiceCredential } from './service-credential';import { isStopMessage } from './stop-request';@@ -62,6 +63,12 @@ export const sessionRequestSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('snapshot') }),/** Switch has an answer to one of this session's approval requests. */z.object({ type: z.literal('approvals') }),+ /**+ * The reasoning the host still holds for these turns (all of them when+ * null). Read-only, never journaled, and only ever asked over a local or SSH+ * link: a host that predates it cannot parse it and does not answer.+ */+ z.object({ type: z.literal('reasoning'), turnIds: z.array(z.string().min(1)).nullable() }),]);export type SessionRequest = z.infer<typeof sessionRequestSchema>;@@ -202,6 +209,8 @@ function recordedFailure(root: string, code: number): string {return `The session host exited with code ${code}.`;}+const NO_ANSWER = 'The session host did not answer in time.';+type Pending = {resolve: (value: unknown) => void;reject: (error: Error) => void;@@ -223,8 +232,17 @@ type Link = {barriers: Map<number, Pending>;/** How many hosts here have exited, so a waiting request can tell one did. */exits: number;+ /** The running host did not answer a `reasoning` request: it predates them. */+ noReasoning: boolean;};+/**+ * How long a `reasoning` request waits for its answer. A host that predates+ * the request cannot parse it and never answers, so this is how such a host+ * is told apart; the link does not ask it again.+ */+const REASONING_TIMEOUT_MS = 5000;+/*** The parent's end: one link per session state root, re-attached each time* the supervisor starts the host again.@@ -265,6 +283,7 @@ export class SessionLinks {busy: null,barriers: new Map(),exits: 0,+ noReasoning: false,};this.links.set(root, link);}@@ -279,6 +298,7 @@ export class SessionLinks {link.identity = null;link.failure = null;link.busy = null;+ link.noReasoning = false;for (const listener of this.busyListeners) listener(root);child.on('message', (raw) => {const parsed = fromChildSchema.safeParse(raw);@@ -535,7 +555,7 @@ export class SessionLinks {const timer = setTimeout(() => {link.pending.delete(id);- reject(new SessionUnavailableError('The session host did not answer in time.'));+ reject(new SessionUnavailableError(NO_ANSWER));},Math.max(deadline - Date.now(), 5000));@@ -549,6 +569,37 @@ export class SessionLinks {});}+ /**+ * The reasoning the running host at this root still holds, or null when no+ * host is ready there or it predates the request. Never waits for a host to+ * start and never raises: reasoning is a nicety, not something to fail on.+ */+ async reasoning(root: string, turnIds: string[] | null): Promise<HostReasoningList | null> {+ const link = this.links.get(root);+ if (!link?.ready || !link.child || link.noReasoning) return null;+ const child = link.child;+ try {+ const answer = hostReasoningListSchema.safeParse(+ await this.request(root, { type: 'reasoning', turnIds }, REASONING_TIMEOUT_MS)+ );+ if (answer.success) return answer.data;+ console.warn(`The session host at ${root} answered a reasoning request unreadably.`);+ return null;+ } catch (error) {+ if (+ error instanceof SessionUnavailableError &&+ error.message === NO_ANSWER &&+ link.child === child+ ) {+ link.noReasoning = true;+ console.warn(+ `The session host at ${root} did not answer a reasoning request; it predates them, so it is not asked again.`+ );+ }+ return null;+ }+ }+/** The roots with a host process running, ready or not. */live(): string[] {return [...this.links].flatMap(([root, link]) => (link.child ? [root] : []));diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex 435eb78a0..d0e96231e 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -690,6 +690,29 @@ it('waits for native compaction and keeps history without sending a summarizatioexpect(fixture.adapter.interruptTurn).not.toHaveBeenCalled();});+it('publishes context usage when a turn ends and clears it on reset', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-context-test-'));+ roots.push(root);+ const fixture = setup('claude');+ fixture.adapter.contextUsage = vi.fn(async () => ({ usedTokens: 134000, windowTokens: 0 }));+ const host = await HostedSession.start(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(host.snapshot().session.context).toBeUndefined();+ await host.command(message('turn'));+ await waitFor(() => expect(fixture.adapter.sendTurn).toHaveBeenCalledTimes(1));+ fixture.emit({ type: 'turn.completed', turnId: 'turn', outcome: 'completed', usage: [] });+ await waitFor(() =>+ expect(host.snapshot().session.context).toMatchObject({+ usedTokens: 134000,+ windowTokens: null,+ })+ );+ await host.command({ ...message('reset'), body: { type: 'session.reset' } });+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(host.snapshot().session.context).toBeNull();+});+it('stages attachments before dispatch and never executes after shutdown during transfer', async () => {const { adapter, config } = setup('codex');let resolve!: (files: Array<{ path: string; mimeType: string }>) => void;@@ -1469,3 +1492,123 @@ it('caps what a room reply quotes and adds the failure the text does not already);expect(unpostedReply('', 'error', null)).toBe('I finished without replying. The turn failed.');});++/**+ * One turn, as the provider reports it, with or without its reasoning; what+ * the host records and publishes for it, with the per-event noise removed.+ */+async function runTurn(provider: 'codex' | 'claude', withReasoning: boolean) {+ const { host, emit, root } = await start(provider);+ const published: unknown[] = [];+ host.onPublished((event) => published.push(event.body));+ await host.command(message('turn'));+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));+ const secret = 'PRIVATE REASONING TEXT';+ if (withReasoning) {+ if (provider === 'codex') {+ emit({+ type: 'item.started',+ turnId: 'turn',+ item: { id: 'r1', type: 'reasoning', status: 'in_progress', title: 'Reasoning' },+ });+ emit({ type: 'item.delta', turnId: 'turn', itemId: 'r1', delta: secret });+ emit({ type: 'content.delta', turnId: 'turn', itemId: 'r1', delta: ' more' });+ }+ emit({+ type: 'item.completed',+ turnId: 'turn',+ item: {+ id: 'r1',+ type: 'reasoning',+ status: 'completed',+ title: secret,+ text: `${secret} more`,+ },+ });+ }+ emit({+ type: 'item.completed',+ turnId: 'turn',+ item: { id: 'a1', type: 'assistant_message', status: 'completed', title: 'Done', text: 'Done' },+ });+ emit({ type: 'turn.completed', turnId: 'turn', outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));+ await host.barrier();+ const journal = await readFile(join(root, 'events.jsonl'), 'utf8');+ const snapshot = host.snapshot();+ const strip = (value: unknown) =>+ JSON.parse(+ JSON.stringify(value, (key, field) =>+ ['eventId', 'occurredAt', 'revision', 'createdAt', 'updatedAt'].includes(key)+ ? undefined+ : field+ )+ );+ return {+ host,+ secret,+ journal,+ published: strip(published),+ snapshot: strip({ ...snapshot, session: { ...snapshot.session, epoch: null } }),+ };+}++it.each(['codex', 'claude'] as const)(+ 'keeps %s reasoning off the event stream, the journal and the snapshot',+ async (provider) => {+ const withReasoning = await runTurn(provider, true);+ expect(withReasoning.journal).not.toContain(withReasoning.secret);+ expect(JSON.stringify(withReasoning.published)).not.toContain(withReasoning.secret);+ expect(JSON.stringify(withReasoning.snapshot)).not.toContain(withReasoning.secret);+ expect(withReasoning.host.reasoning(['turn']).turns[0]?.text).toBe(+ `${withReasoning.secret} more`+ );+ // What an older client or server sees is exactly what it saw before reasoning was kept.+ const without = await runTurn(provider, false);+ expect(withReasoning.published).toEqual(without.published);+ expect(withReasoning.snapshot).toEqual(without.snapshot);+ expect(without.host.reasoning(null).turns).toEqual([]);+ }+);++it('times reasoning only from a real start: Codex has one, Claude does not', async () => {+ const codex = await runTurn('codex', true);+ const [timed] = codex.host.reasoning(null).turns;+ expect(timed?.startedAt).toEqual(expect.any(String));+ expect(timed?.completedAt).toEqual(expect.any(String));+ expect(codex.host.reasoning(null).epoch).toBe(codex.host.snapshot().session.epoch);+ const claude = await runTurn('claude', true);+ const [untimed] = claude.host.reasoning(['turn', 'other']).turns;+ expect(untimed?.startedAt).toBeNull();+ expect(untimed?.completedAt).toEqual(expect.any(String));+});++it('keeps tool input and output off the event stream, the journal and the snapshot', async () => {+ const { host, emit, root } = await start('claude');+ const published: unknown[] = [];+ host.onPublished((event) => published.push(event.body));+ await host.command(message('turn'));+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));+ const input = { file_path: '/repo/PRIVATE-INPUT.ts' };+ const tool = { id: 't1', type: 'tool_call', title: 'Read', toolName: 'Read', payload: input };+ emit({ type: 'item.started', turnId: 'turn', item: { ...tool, status: 'in_progress' } });+ emit({+ type: 'item.completed',+ turnId: 'turn',+ item: { ...tool, status: 'completed', text: 'PRIVATE OUTPUT' },+ });+ emit({ type: 'turn.completed', turnId: 'turn', outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));+ await host.barrier();+ const journal = await readFile(join(root, 'events.jsonl'), 'utf8');+ for (const text of [journal, JSON.stringify(published), JSON.stringify(host.snapshot())]) {+ expect(text).not.toContain('PRIVATE-INPUT');+ expect(text).not.toContain('PRIVATE OUTPUT');+ }+ expect(host.reasoning(['turn']).tools).toEqual([+ {+ turnId: 'turn',+ tools: [expect.objectContaining({ input, output: 'PRIVATE OUTPUT', toolName: 'Read' })],+ },+ ]);+});diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex 4ec726d11..a50305dfa 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -27,7 +27,9 @@ import { ChatProjector } from '../session-v1/chat-projector';import { ATTACHMENT_MIME_TYPES } from './attachments';import { Journal } from './journal';import { fitModelCatalog } from './model-catalog';+import { ReasoningBuffer, type HostReasoningList } from './reasoning-buffer';import type { Redactions } from './redaction';+import { ToolDetailBuffer } from './tool-detail-buffer';export const hostInboxRecordSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('accepted'), command: commandSchema }),@@ -105,6 +107,10 @@ export class HostedSession {private readonly queue: Command[] = [];private readonly questions = new Map<string, PendingQuestion>();private readonly listeners = new Set<(event: ServerEvent) => void>();+ /** Recent reasoning, in memory only: never published, journaled or replayed. */+ private readonly reasoningBuffer = new ReasoningBuffer();+ /** Recent tool input and output, in memory only, under the same rules as reasoning. */+ private readonly toolDetails = new ToolDetailBuffer();private activeTurn: string | null = null;private serial: Promise<unknown> = Promise.resolve();private eventSerial: Promise<unknown> = Promise.resolve();@@ -178,6 +184,8 @@ export class HostedSession {this.projector = new ChatProjector(config.session, config.redactions ?? null);this.unsubscribe = adapter.subscribe((event) => {if (event.sessionId !== config.session.sessionId) return;+ this.reasoningBuffer.ingest(event, this.config.session.epoch, Date.now());+ this.toolDetails.ingest(event, this.config.session.epoch);// Process cleanup leaves this conversation available for recovery.// An explicit session.stop is handled before shutdown and remains terminal.if (@@ -279,6 +287,7 @@ export class HostedSession {if (config.epochAuthority !== 'server') config.session.epoch = randomUUID();const next = host.replica.snapshot();config.session.models = next.session.models;+ config.session.context = next.session.context;next.session = structuredClone(config.session);host.replica = new SessionReplica(next);}@@ -397,6 +406,28 @@ export class HostedSession {await this.publish({ type: 'notice', level: 'error', code, message });}+ /** Reads how full the context window is and publishes it; unknown when the read fails. */+ private async refreshContext(): Promise<void> {+ if (!this.adapter.contextUsage) return;+ const { sessionId, epoch } = this.config.session;+ let usage: Awaited<ReturnType<NonNullable<ProviderAdapter['contextUsage']>>> = null;+ try {+ usage = await this.adapter.contextUsage(sessionId);+ } catch (error) {+ console.warn(`Could not read context usage for session ${sessionId}: ${String(error)}`);+ }+ if (this.shuttingDown || this.resetting || epoch !== this.config.session.epoch) return;+ this.config.session.context = usage+ ? {+ usedTokens: Math.max(0, Math.round(usage.usedTokens)),+ windowTokens:+ usage.windowTokens && usage.windowTokens > 0 ? Math.round(usage.windowTokens) : null,+ updatedAt: new Date().toISOString(),+ }+ : null;+ await this.publish({ type: 'session.upsert', session: structuredClone(this.config.session) });+ }+private async refreshModels(): Promise<void> {const generation = ++this.modelGeneration;const compact =@@ -505,6 +536,17 @@ export class HostedSession {snapshot(): Snapshot {return this.replica.snapshot();}+ /**+ * The reasoning and tool details still held for `turnIds` (all buffered+ * turns when null), for this epoch.+ */+ reasoning(turnIds: string[] | null): HostReasoningList {+ const epoch = this.config.session.epoch;+ return {+ ...this.reasoningBuffer.list(epoch, turnIds),+ tools: this.toolDetails.list(epoch, turnIds),+ };+ }replay(after: number): { events: ServerEvent[]; throughSequence: number } {return {events: structuredClone(this.events.records.filter((event) => event.sequence > after)),@@ -803,6 +845,7 @@ export class HostedSession {type: 'session.upsert',session: structuredClone(this.config.session),});+ void this.refreshContext().catch((error: unknown) => this.fail(error));} catch (error) {await this.fail(error);throw error;@@ -845,6 +888,7 @@ export class HostedSession {const epoch = this.config.resetEpoch ? await this.config.resetEpoch() : randomUUID();this.config.session.epoch = epoch;this.config.session.status = 'starting';+ this.config.session.context = null;const snapshot = this.snapshot();snapshot.session = structuredClone(this.config.session);this.replica = new SessionReplica(snapshot);@@ -1161,6 +1205,7 @@ export class HostedSession {await this.replyIfUnposted(event.turnId, event.outcome, event.message ?? null);this.activeTurn = null;void this.runNext().catch((error: unknown) => this.fail(error));+ void this.refreshContext().catch((error: unknown) => this.fail(error));}}diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex ddfb7ce7c..a153781fb 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -945,6 +945,50 @@ it('tells the session to rejoin its room once a reset asked for there has applie}}, 20000);+it('tells the room at once when it refuses a compaction asked for there mid-turn', async () => {+ const host = await start({ rooms: true });+ const asks = () =>+ host.parent.sent.filter(+ (message): message is typeof message & { id: number; ask: Record<string, unknown> } =>+ message.kind === 'ask'+ );+ try {+ expect(+ await host.parent.ask({ type: 'room', handoff: roomMessage(1, 'work on it') })+ ).toMatchObject({ ok: true });+ await vi.waitFor(() => expect(host.turns).toHaveLength(1), { timeout: 5000 });+ const compact: Command = {+ ...relayed('current', 'room-compact', { type: 'session.compact' }),+ origin: {+ actorId: '@person:test',+ surface: 'switch-web',+ roomId: 'room',+ threadId: 'thread',+ messageId: 'message-9',+ },+ };+ const answer = await host.parent.ask({+ type: 'command',+ command: compact,+ requesterName: null,+ });+ expect(answer).toMatchObject({ ok: true, value: { status: 'rejected' } });+ await vi.waitFor(() => expect(asks()).toHaveLength(1), { timeout: 5000 });+ expect(asks()[0]!.ask).toEqual({+ type: 'room-reply',+ roomId: 'room',+ threadId: 'thread',+ body: "I can't compact my session while I'm working on a turn. Ask again once I've finished, or stop the turn first.",+ });+ // Asked again (a relay retried), the room is not told twice.+ await host.parent.ask({ type: 'command', command: compact, requesterName: null });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(asks()).toHaveLength(1);+ } finally {+ await host.stop();+ }+}, 20000);+it('keeps running through a reset whose provider reports the old conversation stopped', async () => {const host = await start({ resettable: true, stopReports: true });try {diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 0164ee314..d22de3b74 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -11,7 +11,11 @@ import { cliToolsBase, pinnedBinary } from './cli-binaries';import { HostWaker } from './handoff';import { agentHasOwnUser } from './host-permissions';import { Redactions } from './redaction';-import { followupCommandId, roomControlFollowup } from './room-control-followup';+import {+ followupCommandId,+ roomControlFollowup,+ roomControlRefusal,+} from './room-control-followup';import { SharedRoomInbox, type roomConnectionSchema } from './room-inbox';import {planAttachments,@@ -670,6 +674,9 @@ export async function runSharedHost(const owed = followupFor(command, requesterName);if (owed && !followups().some((record) => record.commandId === command.commandId))await state.journal.append(owed);+ const repeated = host!+ .snapshot()+ .commandStatuses.some((entry) => entry.commandId === command.commandId);try {await host!.command(command);} catch (error) {@@ -679,6 +686,26 @@ export async function runSharedHost(.snapshot().commandStatuses.find((entry) => entry.commandId === command.commandId);if (owed && status?.status === 'applied') await sendFollowup(owed);+ // Switch already told the room the control is under way; a refusal is answered there too.+ if (+ owed &&+ status?.status === 'rejected' &&+ !repeated &&+ parentChannel &&+ options.roomConnection+ )+ void parentChannel+ .ask({+ type: 'room-reply',+ roomId: owed.roomId,+ threadId: owed.threadId,+ body: roomControlRefusal(owed.action, status.message),+ })+ .catch((error: unknown) =>+ console.warn(+ `Could not tell room ${owed.roomId} that its ${owed.action} was refused: ${String(error)}`+ )+ );// A fresh conversation starts with the instructions this host was given.if (command.body.type === 'session.reset' && status?.status === 'applied')await instructionsTold();@@ -792,6 +819,7 @@ export async function runSharedHost(return { accepted: true };},snapshot: async () => host!.snapshot(),+ reasoning: async ({ turnIds }) => host!.reasoning(turnIds),approvals: async () => {active();waker.approvalsWaiting();diff --git a/console/packages/agent-providers/src/host/tool-detail-buffer.test.ts b/console/packages/agent-providers/src/host/tool-detail-buffer.test.tsnew file mode 100644index 000000000..5198a18eb--- /dev/null+++ b/console/packages/agent-providers/src/host/tool-detail-buffer.test.ts@@ -0,0 +1,157 @@+import { expect, it } from 'vitest';+import type { ProviderItem, ProviderRuntimeEvent } from '../events';+import {+ TOOL_ANSWER_LIMIT,+ TOOL_DETAIL_TURN_LIMIT,+ TOOL_INPUT_STRING_LIMIT,+ TOOL_OUTPUT_HEAD,+ TOOL_OUTPUT_TAIL,+ ToolDetailBuffer,+} from './tool-detail-buffer';++const base = { eventId: 'e', provider: 'claude', sessionId: 'session', createdAt: '' } as const;++function itemEvent(+ type: 'item.started' | 'item.updated' | 'item.completed',+ turnId: string,+ item: Partial<ProviderItem> & { id: string }+): ProviderRuntimeEvent {+ return {+ ...base,+ type,+ turnId,+ item: { type: 'tool_call', status: 'in_progress', title: '', ...item },+ };+}++it('keeps a Claude call’s input from its start and its output from its result', () => {+ const buffer = new ToolDetailBuffer();+ buffer.ingest(+ itemEvent('item.started', 'turn', {+ id: 'tu1',+ type: 'command_execution',+ toolName: 'Bash',+ title: 'ls -la',+ payload: { command: 'ls -la' },+ }),+ 'epoch'+ );+ buffer.ingest(+ itemEvent('item.completed', 'turn', {+ id: 'tu1',+ type: 'command_execution',+ status: 'completed',+ toolName: 'Bash',+ title: 'ls -la',+ payload: { command: 'ls -la' },+ text: 'total 0',+ }),+ 'epoch'+ );+ expect(buffer.list('epoch', ['turn'])).toEqual([+ {+ turnId: 'turn',+ tools: [+ {+ itemId: JSON.stringify(['turn', 'tu1']),+ type: 'command_execution',+ toolName: 'Bash',+ input: { command: 'ls -la' },+ output: 'total 0',+ truncated: false,+ exitCode: null,+ },+ ],+ },+ ]);+});++it('streams a command’s output from deltas and takes its exit code (Codex)', () => {+ const buffer = new ToolDetailBuffer();+ const payload = { command: 'make', cwd: '/w', exitCode: null };+ buffer.ingest(+ itemEvent('item.started', 't', { id: 'c', type: 'command_execution', payload }),+ 'epoch'+ );+ buffer.ingest(+ { ...base, type: 'item.delta', turnId: 't', itemId: 'c', delta: 'built\n' },+ 'epoch'+ );+ expect(buffer.list('epoch', null)[0]!.tools[0]!.output).toBe('built\n');+ buffer.ingest(+ itemEvent('item.completed', 't', {+ id: 'c',+ type: 'command_execution',+ status: 'failed',+ payload: { ...payload, exitCode: 2 },+ text: 'built\nerror\n',+ }),+ 'epoch'+ );+ const [tool] = buffer.list('epoch', null)[0]!.tools;+ expect(tool).toMatchObject({ output: 'built\nerror\n', exitCode: 2 });+});++it('unwraps OpenCode’s nested input and ignores reasoning and messages', () => {+ const buffer = new ToolDetailBuffer();+ buffer.ingest(+ itemEvent('item.started', 't', {+ id: 'p',+ toolName: 'read',+ payload: { tool: 'read', input: { filePath: '/a.ts' }, status: 'running' },+ }),+ 'epoch'+ );+ buffer.ingest(itemEvent('item.started', 't', { id: 'r', type: 'reasoning' }), 'epoch');+ buffer.ingest(itemEvent('item.started', 't', { id: 'm', type: 'assistant_message' }), 'epoch');+ const tools = buffer.list('epoch', null)[0]!.tools;+ expect(tools.map((tool) => tool.input)).toEqual([{ filePath: '/a.ts' }]);+});++it('clips long input strings and long output, keeping the output’s head and tail', () => {+ const buffer = new ToolDetailBuffer();+ const content = 'x'.repeat(TOOL_INPUT_STRING_LIMIT + 50);+ const output = `${'h'.repeat(TOOL_OUTPUT_HEAD)}${'m'.repeat(5000)}${'t'.repeat(TOOL_OUTPUT_TAIL)}`;+ buffer.ingest(+ itemEvent('item.completed', 't', {+ id: 'w',+ type: 'file_change',+ payload: { file_path: '/f', content },+ text: output,+ }),+ 'epoch'+ );+ const [tool] = buffer.list('epoch', null)[0]!.tools;+ expect(tool!.truncated).toBe(true);+ expect((tool!.input as { content: string }).content).toHaveLength(TOOL_INPUT_STRING_LIMIT + 1);+ expect(tool!.output).toBe(`${'h'.repeat(TOOL_OUTPUT_HEAD)}\n…\n${'t'.repeat(TOOL_OUTPUT_TAIL)}`);+});++it('drops everything on a new epoch and the oldest turns past its limit', () => {+ const buffer = new ToolDetailBuffer();+ for (let index = 0; index <= TOOL_DETAIL_TURN_LIMIT; index += 1)+ buffer.ingest(itemEvent('item.started', `turn-${index}`, { id: 'x' }), 'epoch');+ const turns = buffer.list('epoch', null);+ expect(turns).toHaveLength(TOOL_DETAIL_TURN_LIMIT);+ expect(turns[0]!.turnId).toBe('turn-1');+ expect(buffer.list('other', null)).toEqual([]);+ buffer.ingest(itemEvent('item.started', 'fresh', { id: 'x' }), 'next');+ expect(buffer.list('next', null).map((turn) => turn.turnId)).toEqual(['fresh']);+});++it('keeps an answer bounded, newest turns first, listing what is left over bare', () => {+ const buffer = new ToolDetailBuffer();+ const big = 'o'.repeat(TOOL_OUTPUT_HEAD + TOOL_OUTPUT_TAIL);+ for (let turn = 0; turn < 3; turn += 1)+ for (let call = 0; call < 60; call += 1)+ buffer.ingest(+ itemEvent('item.completed', `turn-${turn}`, { id: `c${call}`, payload: {}, text: big }),+ 'epoch'+ );+ const turns = buffer.list('epoch', null);+ const size = JSON.stringify(turns).length;+ expect(size).toBeLessThan(TOOL_ANSWER_LIMIT * 1.1);+ expect(turns.at(-1)!.turnId).toBe('turn-2');+ expect(turns.at(-1)!.tools[0]!.output).toBe(big);+ expect(turns.flatMap((turn) => turn.tools).some((tool) => tool.output === null)).toBe(true);+});diff --git a/console/packages/agent-providers/src/host/tool-detail-buffer.ts b/console/packages/agent-providers/src/host/tool-detail-buffer.tsnew file mode 100644index 000000000..ae21647b4--- /dev/null+++ b/console/packages/agent-providers/src/host/tool-detail-buffer.ts@@ -0,0 +1,259 @@+import { z } from 'zod';+import type { ItemType, ProviderRuntimeEvent } from '../events';++/**+ * What each recent tool call was given and what it gave back, held in memory+ * by the session host beside the reasoning buffer and under the same rules.+ *+ * A session-v1 tool item carries only a title: raw tool input and output are+ * not a shared summary, so they are never published, journaled, snapshotted+ * or sent to Switch (whose renderers show an item's text in Slack and the+ * like). A Console on the same machine, or over SSH, reads them here to show+ * what a tool did. Every value is clipped as it is taken, so the buffer and an+ * answer stay bounded however large a file read or a command's output is.+ */++/** How many turns are kept; the oldest go first. */+export const TOOL_DETAIL_TURN_LIMIT = 50;+/** How many tool calls one turn keeps; the oldest go first. */+const TOOL_ITEM_LIMIT = 200;+/** One string inside a tool's input, in UTF-16 code units. */+export const TOOL_INPUT_STRING_LIMIT = 3000;+/** A tool's whole input once serialized; past it the input is kept as clipped text. */+export const TOOL_INPUT_LIMIT = 12 * 1024;+/** A tool's output: its head and its tail are kept, the middle dropped. */+export const TOOL_OUTPUT_HEAD = 6 * 1024;+export const TOOL_OUTPUT_TAIL = 2 * 1024;+/** Roughly how much one answer carries; older turns are left out past it. */+export const TOOL_ANSWER_LIMIT = 1024 * 1024;++const TOOL_TYPES: ReadonlySet<ItemType> = new Set([+ 'command_execution',+ 'file_change',+ 'mcp_tool_call',+ 'tool_call',+ 'web_search',+ 'subagent',+]);++export const hostToolDetailSchema = z.object({+ /** The session-v1 item id the call was projected under. */+ itemId: z.string().min(1),+ type: z.string(),+ toolName: z.string().nullable(),+ /** The call's arguments, with long strings clipped; null when it had none. */+ input: z.unknown(),+ output: z.string().nullable(),+ /** Whether anything above was clipped. */+ truncated: z.boolean(),+ exitCode: z.number().nullable(),+});+export type HostToolDetail = z.infer<typeof hostToolDetailSchema>;++export const hostToolTurnSchema = z.object({+ turnId: z.string().min(1),+ tools: z.array(hostToolDetailSchema),+});+export type HostToolTurn = z.infer<typeof hostToolTurnSchema>;++type ToolEntry = {+ itemId: string;+ type: ItemType;+ toolName: string | null;+ input: unknown;+ inputClipped: boolean;+ head: string;+ tail: string;+ outputClipped: boolean;+ hasOutput: boolean;+ exitCode: number | null;+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/** The arguments in a provider payload: OpenCode nests them under `input`. */+function payloadInput(payload: Record<string, unknown> | undefined): unknown {+ if (!payload) return null;+ if (typeof payload.tool === 'string' && isRecord(payload.input)) return payload.input;+ return payload;+}++function clipValue(value: unknown, depth: number, clipped: { value: boolean }): unknown {+ if (typeof value === 'string') {+ if (value.length <= TOOL_INPUT_STRING_LIMIT) return value;+ clipped.value = true;+ return `${value.slice(0, TOOL_INPUT_STRING_LIMIT)}…`;+ }+ if (value === null || typeof value !== 'object') return value;+ if (depth >= 6) {+ clipped.value = true;+ return '…';+ }+ if (Array.isArray(value)) {+ if (value.length > 100) clipped.value = true;+ return value.slice(0, 100).map((each) => clipValue(each, depth + 1, clipped));+ }+ return Object.fromEntries(+ Object.entries(value).map(([key, each]) => [key, clipValue(each, depth + 1, clipped)])+ );+}++function clipInput(payload: Record<string, unknown> | undefined): {+ input: unknown;+ clipped: boolean;+} {+ const clipped = { value: false };+ const input = clipValue(payloadInput(payload), 0, clipped);+ const text = JSON.stringify(input) ?? '';+ if (text.length <= TOOL_INPUT_LIMIT) return { input, clipped: clipped.value };+ return { input: `${text.slice(0, TOOL_INPUT_LIMIT)}…`, clipped: true };+}++function exitCodeOf(payload: Record<string, unknown> | undefined): number | null {+ const code = payload?.exitCode;+ return typeof code === 'number' && Number.isFinite(code) ? code : null;+}++function setOutput(entry: ToolEntry, text: string): void {+ entry.head = '';+ entry.tail = '';+ entry.outputClipped = false;+ appendOutput(entry, text);+}++function appendOutput(entry: ToolEntry, text: string): void {+ entry.hasOutput = true;+ const room = TOOL_OUTPUT_HEAD - entry.head.length;+ if (room > 0) {+ entry.head += text.slice(0, room);+ text = text.slice(room);+ }+ if (text.length === 0) return;+ const tail = entry.tail + text;+ if (tail.length > TOOL_OUTPUT_TAIL) entry.outputClipped = true;+ entry.tail = tail.slice(-TOOL_OUTPUT_TAIL);+}++function detailOf(entry: ToolEntry): HostToolDetail {+ return {+ itemId: entry.itemId,+ type: entry.type,+ toolName: entry.toolName,+ input: entry.input,+ output: entry.hasOutput+ ? entry.outputClipped+ ? `${entry.head}\n…\n${entry.tail}`+ : entry.head + entry.tail+ : null,+ truncated: entry.inputClipped || entry.outputClipped,+ exitCode: entry.exitCode,+ };+}++function sizeOf(detail: HostToolDetail): number {+ return (JSON.stringify(detail.input) ?? '').length + (detail.output?.length ?? 0) + 200;+}++export class ToolDetailBuffer {+ private epoch: string | null = null;+ /** In insertion order, so the first entry is the oldest turn. */+ private readonly turns = new Map<string, Map<string, ToolEntry>>();++ /** Take one provider event, for the session's current epoch. Ignores all but tool calls. */+ ingest(event: ProviderRuntimeEvent, epoch: string): void {+ if (this.epoch !== epoch) {+ this.turns.clear();+ this.epoch = epoch;+ }+ switch (event.type) {+ case 'item.started':+ case 'item.updated':+ case 'item.completed': {+ const item = event.item;+ if (!TOOL_TYPES.has(item.type)) return;+ const tools = this.turn(event.turnId);+ let entry = tools.get(item.id);+ if (!entry) {+ entry = {+ itemId: JSON.stringify([event.turnId, item.id]),+ type: item.type,+ toolName: null,+ input: null,+ inputClipped: false,+ head: '',+ tail: '',+ outputClipped: false,+ hasOutput: false,+ exitCode: null,+ };+ tools.set(item.id, entry);+ while (tools.size > TOOL_ITEM_LIMIT) {+ const oldest = tools.keys().next().value;+ if (oldest === undefined) break;+ tools.delete(oldest);+ }+ }+ entry.type = item.type;+ if (item.toolName) entry.toolName = item.toolName;+ if (item.payload) {+ const { input, clipped } = clipInput(item.payload);+ entry.input = input;+ entry.inputClipped = clipped;+ entry.exitCode = exitCodeOf(item.payload) ?? entry.exitCode;+ }+ if (item.text !== undefined && item.text.length > 0) setOutput(entry, item.text);+ return;+ }+ case 'item.delta': {+ const entry = this.turns.get(event.turnId)?.get(event.itemId);+ if (entry && event.delta.length > 0) appendOutput(entry, event.delta);+ return;+ }+ default:+ return;+ }+ }++ /**+ * The calls held for `turnIds` (every turn when null), oldest turn first.+ * Turns are taken newest first until the answer reaches its limit, so a+ * request for many large turns leaves the oldest of them out rather than+ * growing without bound.+ */+ list(epoch: string, turnIds: string[] | null): HostToolTurn[] {+ if (this.epoch !== epoch) return [];+ const wanted = turnIds === null ? null : new Set(turnIds);+ const picked: HostToolTurn[] = [];+ let size = 0;+ for (const [turnId, tools] of [...this.turns].reverse()) {+ if (wanted && !wanted.has(turnId)) continue;+ if (size >= TOOL_ANSWER_LIMIT) break;+ const details = [...tools.values()].map((entry) => {+ const detail = detailOf(entry);+ size += sizeOf(detail);+ // Past the limit a call is still listed, so its row can say what it was, but bare.+ return size > TOOL_ANSWER_LIMIT+ ? { ...detail, input: null, output: null, truncated: true }+ : detail;+ });+ picked.push({ turnId, tools: details });+ }+ return picked.reverse();+ }++ private turn(turnId: string): Map<string, ToolEntry> {+ let tools = this.turns.get(turnId);+ if (!tools) {+ tools = new Map();+ this.turns.set(turnId, tools);+ while (this.turns.size > TOOL_DETAIL_TURN_LIMIT) {+ const oldest = this.turns.keys().next().value;+ if (oldest === undefined) break;+ this.turns.delete(oldest);+ }+ }+ return tools;+ }+}diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.tsindex 6dc344348..c22dfe24e 100644--- a/console/packages/agent-providers/src/host/watcher-tools.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.ts@@ -332,6 +332,7 @@ export type WatcherHealth = z.infer<typeof watcherHealthSchema>;export type WatcherHandlers = {place: (sessionId: string, roomId: string) => Promise<PlaceOutcome>;forget: (sessionId: string) => Promise<void>;+ warm: (roomId: string) => Promise<string | null>;};/**@@ -387,6 +388,18 @@ export class WatcherControl {return this.handlers.place(sessionId, roomId);}+ /**+ * 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.+ * Refused when no watcher is running.+ */+ warm(roomId: string): Promise<string | null> {+ if (!this.handlers)+ return Promise.reject(new Error("The agent's room watcher is not running."));+ return this.handlers.warm(roomId);+ }+health(): WatcherHealth {return this.current;}diff --git a/console/packages/shared/src/session-v1/contract.ts b/console/packages/shared/src/session-v1/contract.tsindex 9e0b4aa9b..a73b1698f 100644--- a/console/packages/shared/src/session-v1/contract.ts+++ b/console/packages/shared/src/session-v1/contract.ts@@ -69,6 +69,8 @@ export type Request = {expiresAt: string | null;};export type SessionModel = { id: string; options: Record<string, string> };+/** How full the provider's context window was when last measured; `windowTokens` null when the provider does not say. */+export type SessionContext = { usedTokens: number; windowTokens: number | null; updatedAt: string };export type ModelChoice = {id: string;label: string;@@ -89,6 +91,7 @@ export type Session = {pendingRequestIds: Id[];models?: ModelChoice[];model?: SessionModel | null;+ context?: SessionContext | null;};export type HostBody =| { type: 'session.upsert'; session: Session }diff --git a/console/packages/shared/src/session-v1/validation.ts b/console/packages/shared/src/session-v1/validation.tsindex 352155731..31d09b81d 100644--- a/console/packages/shared/src/session-v1/validation.ts+++ b/console/packages/shared/src/session-v1/validation.ts@@ -118,6 +118,14 @@ export const sessionSchema = z.object({.strictObject({ id, options: z.record(z.string(), z.string()) }).nullable().optional(),+ context: z+ .strictObject({+ usedTokens: z.number().int().nonnegative(),+ windowTokens: z.number().int().positive().nullable(),+ updatedAt: timestamp,+ })+ .nullable()+ .optional(),});const turn = z.strictObject({type: z.literal('turn.upsert'),diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yamlindex 87658aec1..dcef7ff62 100644--- a/console/pnpm-lock.yaml+++ b/console/pnpm-lock.yaml@@ -275,6 +275,9 @@ importers:sonner:specifier: ^2.0.7+ streamdown:+ specifier: ^2.7.0tailwind-merge:specifier: ^2.6.0version: 2.6.1@@ -4281,6 +4284,11 @@ packages:engines: {node: '>= 20'}hasBin: true+ resolution: {integrity: sha512-PamYXWWWg2nboG3oX5Ffzpy3EFZROqZJK9hSlMmUnekp7TxPs5DcT95vwd46m73/exfKCRVMtgXoPMI4FEJL6w==}+ engines: {node: '>= 20'}+ hasBin: true+resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}engines: {node: '>=10'}@@ -4929,6 +4937,9 @@ packages:resolution: {integrity: sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA==}+ resolution: {integrity: sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw==}+resolution: {integrity: sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==}@@ -4953,6 +4964,9 @@ packages:resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}+ resolution: {integrity: sha512-mHiYhhwphs1IgIZmkToKLwJn0U99IjPXuutkA2acrNcG0vlEq2G4TGnd2eT0saIHwh2KjaCpvleHcsd5SAz96A==}+resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}engines: {node: '>=0.10.0'}@@ -5211,6 +5225,12 @@ packages:resolution: {integrity: sha512-OgLYGVFCNa430WOrj9tYZhQge5yg6vd6JsKredveAqEhdLVQkfrpnQIGjx0L9lLqzL4Kq4J8yNTcfQR/MpBwhg==}+ resolution: {integrity: sha512-SHYTCveHpRJfcIC8r+5EANczK21R0iNYo4i7wNaLeLeQjEnaVk4xMFhgV4E/mix69BpFSBui1NOESEXKlZfReA==}+ peerDependencies:+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}engines: {node: '>=8'}@@ -5262,6 +5282,9 @@ packages:resolution: {integrity: sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==}+ resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==}+resolution: {integrity: sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==}@@ -9280,6 +9303,8 @@ snapshots:+ [email protected]: {}+dependencies:escape-string-regexp: 4.0.0@@ -10195,6 +10220,10 @@ snapshots:parse-entities: 2.0.0prismjs: 1.27.0+ dependencies:+ unist-util-visit: 5.1.0+dependencies:'@types/hast': 3.0.4@@ -10259,6 +10288,8 @@ snapshots:mdast-util-to-markdown: 2.1.2unified: 11.0.5+ [email protected]: {}+@@ -10560,6 +10591,28 @@ snapshots:+ dependencies:+ clsx: 2.1.1+ hast-util-to-jsx-runtime: 2.3.6+ html-url-attributes: 3.0.1+ marked: 18.1.0+ react: 19.2.7+ react-dom: 19.2.7([email protected])+ rehype-harden: 1.1.8+ rehype-raw: 7.0.0+ rehype-sanitize: 6.0.0+ remark-gfm: 4.0.1+ remark-parse: 11.0.0+ remark-rehype: 11.1.2+ remend: 1.4.0+ tailwind-merge: 3.7.0+ unified: 11.0.5+ unist-util-visit: 5.1.0+ unist-util-visit-parents: 6.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:emoji-regex: 8.0.0@@ -10615,6 +10668,8 @@ snapshots:+ [email protected]: {}+diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex a3b22cdd1..466b0f0a6 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -87,6 +87,7 @@ from switch_core.db.models import (Tool,User,require_tenant_id,+ room_agents,)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import (@@ -289,6 +290,9 @@ class AgentCore:# The credential broker, set by the process wiring when service# connections are on; None means they are off, and nothing can be granted.service_broker: ServiceBroker | None = None+ # 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 = Nonedef __init__(self,@@ -813,6 +817,11 @@ class AgentCore:) -> None:self._agent_removal_listener = listener+ def set_room_agents_listener(+ self, listener: Callable[[str, str], Awaitable[None]]+ ) -> None:+ self._room_agents_listener = listener+async def _create_bridge_identities(self, tenant_id: str, agent_name: str, description: str) -> None:@@ -1003,6 +1012,18 @@ class AgentCore:"had_parent": agent.parent_agent_id is not None,}removed["room_count"] = await self._room_count_for(resolved_id)+ room_ids: list[str] = []+ if self._room_agents_listener is not None:+ async with self.session_factory() as session:+ room_ids = list(+ (+ await session.execute(+ select(room_agents.c.room_id).where(+ room_agents.c.agent_id == resolved_id+ )+ )+ ).scalars()+ )if self._agent_removal_listener is not None:await self._agent_removal_listener(tenant_id, resolved_id)await self.client_lifecycle.stop(client_id)@@ -1017,6 +1038,9 @@ class AgentCore:await self.client_lifecycle.delete_record(session, client_id)await session.commit()self.api_key_cache.invalidate_agent(resolved_id)+ if self._room_agents_listener is not None:+ for room_id in room_ids:+ await self._room_agents_listener(tenant_id, room_id)emit_safely(self.telemetry, "agent_deleted", removed)diff --git a/core/switch_core/bridges/agent/protocol/controller_presence.py b/core/switch_core/bridges/agent/protocol/controller_presence.pyindex afa4e1fe2..58c5663c9 100644--- a/core/switch_core/bridges/agent/protocol/controller_presence.py+++ b/core/switch_core/bridges/agent/protocol/controller_presence.py@@ -167,6 +167,7 @@ class ControllerConnection:sent_cursors: dict[str, int] = field(default_factory=dict)# Frames owed to the stream, written on its next pass.session_commands: list[tuple[str, dict[str, Any]]] = field(default_factory=list)+ warms: set[tuple[str, str]] = field(default_factory=set)detached: dict[str, str] = field(default_factory=dict)rooms_changed: set[str] = field(default_factory=set)@@ -416,6 +417,20 @@ class ControllerPresence:conn.wake.set()return True+ def relay_warm(self, agent_id: str, room_id: str) -> bool:+ """Ask the agent's controller to start the session a message to+ `room_id` would start. False when its controller is not live or the+ agent is stopped. A warm already owed for the room is not repeated."""+ binding = self._bindings.get(agent_id)+ if binding is None or not binding.running:+ return False+ conn = self._live_connection(binding.controller_id)+ if conn is None:+ return False+ conn.warms.add((agent_id, room_id))+ conn.wake.set()+ return True+def room_joined(self, agent_id: str, room_id: str) -> None:self._rooms_changed(agent_id, room_id, joined=True)@@ -588,6 +603,11 @@ class ControllerPresence:conn.session_commands.clear()return owed+ def take_warms(self, conn: ControllerConnection) -> list[tuple[str, str]]:+ owed = sorted(conn.warms)+ conn.warms.clear()+ return owed+def _close(self, conn: ControllerConnection, closure: Closure) -> None:if self._connections.get(conn.controller_id) is conn:del self._connections[conn.controller_id]diff --git a/core/switch_core/bridges/agent/protocol/controller_stream.py b/core/switch_core/bridges/agent/protocol/controller_stream.pyindex 3aeaced83..11736a9cc 100644--- a/core/switch_core/bridges/agent/protocol/controller_stream.py+++ b/core/switch_core/bridges/agent/protocol/controller_stream.py@@ -21,6 +21,8 @@ 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.approval_outcome {agent_id, outcome}`.- `agent.rooms {agent_id, rooms}`: its room membership changed.- `agent.detached {agent_id, reason}`: `unassigned` or `deleted`.@@ -207,6 +209,11 @@ class _ControllerStream:{"agent_id": agent_id, "room_id": room_id, "command": command},)+ for agent_id, room_id in self._presence.take_warms(conn):+ yield frame(+ "agent.warm", {"agent_id": agent_id, "room_id": room_id}+ )+for raw in await self._owed_outcomes():yield raw@@ -454,7 +461,12 @@ class _ControllerStream:if (conn.closure is not Noneor conn.stream_token != self._token- or bool(conn.detached or conn.rooms_changed or conn.session_commands)+ or bool(+ conn.detached+ or conn.rooms_changed+ or conn.session_commands+ or conn.warms+ )or self._presence.agents_of(conn.controller_id) != set(self._attached)or any(a.outcomes or a.resync for a in self._attached.values())):diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.pyindex 9de0f0b65..dc1249e35 100644--- a/core/switch_core/bridges/collaboration/collaboration_core.py+++ b/core/switch_core/bridges/collaboration/collaboration_core.py@@ -96,6 +96,7 @@ if TYPE_CHECKING:)from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.clients.workspace_consumer import WorkspaceConsumer+ from switch_core.events import CommandEventfrom switch_core.room_service import RoomService@@ -2014,6 +2015,38 @@ class CollaborationCore:with self._counted_outbound("message"):await self._relay_outbound_message(channel_id, event)+ async def handle_outbound_command(self, room: RoomRef, event: CommandEvent) -> None:+ """Post a room command as the text that types it, so the reply threaded+ under the command has a platform post to sit under.++ A command typed on the platform names its human actor as `user_id`, so+ `handle_outbound_message` drops it like any other message from there.+ """+ assert event.message_id is not None and event.thread_id is not None+ threaded = event.thread_id != event.message_id+ await self.handle_outbound_message(+ room,+ TransportMessage(+ room_id=room.room_id,+ event_id=event.message_id,+ sender=event.user_id,+ timestamp=0,+ content=(+ {+ "m.relates_to": {+ "rel_type": "m.thread",+ "event_id": event.thread_id,+ }+ }+ if threaded+ else {}+ ),+ body=f"!{event.command} {event.args}".strip(),+ sender_name=event.user_name,+ thread_root_id=event.thread_id if threaded else None,+ ),+ )+async def _relay_outbound_message(self, channel_id: str, event: TransportMessage) -> None:diff --git a/core/switch_core/chats/__init__.py b/core/switch_core/chats/__init__.pynew file mode 100644index 000000000..fb921619b--- /dev/null+++ b/core/switch_core/chats/__init__.py@@ -0,0 +1,7 @@+"""Chats: a gateway user taking part in Switch rooms as themselves.++A person reaches a room from Switch Console through a `member` client, one per+user per tenant, linked to their gateway user by `clients.user_id`.+"""++MEMBER_CLIENT_TYPE = "member"diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pynew file mode 100644index 000000000..e204924f1--- /dev/null+++ b/core/switch_core/chats/service.py@@ -0,0 +1,1425 @@+"""A gateway user in Switch rooms as themselves: membership, chats and sends.++Membership is the only read authority. A person sees a room when their+`member` client has a `client_rooms` row for it and they still hold a role in+the tenant; a room's visibility and any claimed platform account do not count.+Membership is granted by creating a chat, by a room manager (the room's owner+or a tenant admin) adding a tenant member, or by a manager adding themselves.+With the `agent_chats` feature flag on, it is also granted to a person in each+chat they started that holds an agent they own, for as long as it does:+`sync_owned_rooms` puts them in and takes back what was held only for that.+Other people's chats and rooms set up elsewhere never gain an agent's owner.++Requests a person may retry carry a request id, recorded in `chat_operations`+per user. The same id with the same payload answers what the first attempt+did; with a different payload it is refused.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import re+import uuid+import weakref+from collections.abc import Callable+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Literal++import markdown+from sqlalchemy import (+ ColumnElement,+ and_,+ delete,+ exists,+ false,+ func,+ select,+ update,+)+from sqlalchemy.dialects.postgresql import insert as pg_insert+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.addressing import allows_on_behalf_of, parse_policy+from switch_core.authz import administers_tenant+from switch_core.bridges.agent.protocol.controller_presence import ControllerPresence+from switch_core.chats import MEMBER_CLIENT_TYPE+from switch_core.chats.views import (+ COMMAND_EVENT_TYPE,+ MESSAGE_EVENT_TYPE,+ SHOWN_EVENT_TYPES,+)+from switch_core.clients.mentions import mention_regex, strip_emphasis+from switch_core.db.models import (+ Agent,+ AgentSessionActivityItem,+ ApprovalRequest,+ ChatHidden,+ ChatOperation,+ ChatOwnerGrant,+ Client,+ ClientRoom,+ MediaBlob,+ Message,+ MessageAttachment,+ Room,+ UsageMetric,+ User,+ require_tenant_id,+ room_agents,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.media_store import MediaStore+from switch_core.db.stores.message_store import MessageStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.session_activity_store import (+ AgentSessionActivityStore,+ ApprovalRequestStore,+)+from switch_core.db.stores.usage_store import UsageStore+from switch_core.db.stores.user_store import UserStore+from switch_core.delivery.addressing import AddressingResolver+from switch_core.messages.notify import MessageListener+from switch_core.messages.row import attachments_in, message_row, new_event_id+from switch_core.observability.catalogue import MESSAGES_SENT+from switch_core.observability.metrics import metrics+from switch_core.provisioning import Provisioning+from switch_core.room_service import RoomCreateConfig, RoomService+from switch_core.session_activity.listener import AgentSessionActivityListener+from switch_core.session_activity.maintenance import ACTIVITY_RETENTION+from switch_core.sessions.attachments import normalise_mime_type+from switch_core.tenant_context import tenant_scope+from switch_core.transport.content import media_content, message_content+from switch_core.transport.types import MessageFormat++logger = logging.getLogger(__name__)++# Fixed so the ids derived from it are stable across processes and releases.+_CHATS_NAMESPACE = uuid.UUID("6f1d3c2e-8a4b-4f5e-9c7d-2b1a0e9f8d7c")+++class ChatError(Exception):+ """A refusal the gateway reports as `{"detail": {"code", "message"}}`."""++ def __init__(self, status: int, code: str, message: str) -> None:+ super().__init__(message)+ self.status = status+ self.code = code+ self.message = message+++@dataclass(frozen=True)+class StagedUpload:+ upload_id: str+ uri: str+ filename: str+ mimetype: str+ size: int+++RemovalReason = Literal["access", "unlisted"]+RoomControl = Literal["interrupt", "reset", "compact"]+++def _hash(payload: dict[str, object]) -> str:+ return hashlib.sha256(+ json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()+ ).hexdigest()+++def _upload_key(upload_id: str) -> str:+ # Uploads share the per-user key space with requests; the prefix keeps a+ # client's upload id from ever colliding with one of its request ids.+ return f"upload:{upload_id}"+++class ChatService:+ def __init__(+ self,+ *,+ session_factory: async_sessionmaker[AsyncSession],+ room_service: RoomService,+ provisioning: Provisioning,+ listener: MessageListener,+ activity_listener: AgentSessionActivityListener,+ room_store: RoomStore,+ agent_store: AgentStore,+ user_store: UserStore,+ message_store: MessageStore,+ media_store: MediaStore,+ usage_store: UsageStore,+ id_server_name: str,+ media_max_bytes: int,+ agent_chats_enabled: bool,+ controllers: ControllerPresence,+ ) -> None:+ self.session_factory = session_factory+ self._controllers = controllers+ self.agent_chats_enabled = agent_chats_enabled+ self.listener = listener+ self.activity_listener = activity_listener+ self._activity_store = AgentSessionActivityStore()+ self._approval_store = ApprovalRequestStore()+ self._room_service = room_service+ self._provisioning = provisioning+ self._room_store = room_store+ self._agent_store = agent_store+ self._user_store = user_store+ self._message_store = message_store+ self._media_store = media_store+ self._usage_store = usage_store+ self._id_server_name = id_server_name+ self._media_max_bytes = media_max_bytes+ self._locks: weakref.WeakValueDictionary[tuple[str, ...], asyncio.Lock] = (+ weakref.WeakValueDictionary()+ )+ self._membership_watchers: dict[tuple[str, str], set[Callable[[], None]]] = {}+ self._addressing = AddressingResolver(+ room_store=room_store,+ room_role_store=RoomRoleStore(),+ client_store=ClientStore(),+ agent_store=agent_store,+ external_user_store=ExternalUserStore(),+ # Only role mentions consult liveness; a permission check never does.+ live_connection_ids=set,+ )++ # ── Membership signals ───────────────────────────────────────────────────++ def watch_memberships(+ self, tenant_id: str, user_id: str, callback: Callable[[], None]+ ) -> None:+ """Call `callback` whenever this process changes the user's chats."""+ self._membership_watchers.setdefault((tenant_id, user_id), set()).add(callback)++ def unwatch_memberships(+ self, tenant_id: str, user_id: str, callback: Callable[[], None]+ ) -> None:+ watchers = self._membership_watchers.get((tenant_id, user_id))+ if watchers is None:+ return+ watchers.discard(callback)+ if not watchers:+ del self._membership_watchers[(tenant_id, user_id)]++ def _memberships_changed(self, tenant_id: str, user_ids: list[str]) -> None:+ for user_id in user_ids:+ for callback in list(+ self._membership_watchers.get((tenant_id, user_id), ())+ ):+ callback()++ def _lock(self, *key: str) -> asyncio.Lock:+ lock = self._locks.get(key)+ if lock is None:+ lock = asyncio.Lock()+ self._locks[key] = lock+ return lock++ # ── Identity and access ──────────────────────────────────────────────────++ async def member_client(self, session: AsyncSession, user_id: str) -> Client | None:+ return (+ await session.execute(+ select(Client).where(+ Client.tenant_id == require_tenant_id(),+ Client.user_id == user_id,+ Client.type == MEMBER_CLIENT_TYPE,+ )+ )+ ).scalar_one_or_none()++ async def member_actor(self, tenant_id: str, user: User) -> Client:+ """The user's member client in the tenant, created on first use."""+ async with self._lock("member", tenant_id, user.id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ client = await self.member_client(session, user.id)+ if client is not None:+ return client+ client = Client(+ transport_user_id=f"@switch-member-{user.id}:{self._id_server_name}",+ display_name=user.name,+ type=MEMBER_CLIENT_TYPE,+ user_id=user.id,+ )+ session.add(client)+ await session.commit()+ logger.info("Created member client %s for user %s", client.id, user.id)+ return client++ async def has_tenant_role(+ self, session: AsyncSession, tenant_id: str, user_id: str+ ) -> bool:+ return (+ await self._user_store.tenant_role(session, tenant_id, user_id) is not None+ )++ async def _room(self, session: AsyncSession, tenant_id: str, room_id: str) -> Room:+ room = await self._room_store.get(session, room_id)+ if room is None or room.tenant_id != tenant_id:+ raise ChatError(404, "ROOM_NOT_FOUND", "Room not found.")+ return room++ async def _is_in_room(+ self, session: AsyncSession, client_id: str, room_id: str+ ) -> bool:+ return bool(+ await session.scalar(+ select(+ exists().where(+ ClientRoom.client_id == client_id, ClientRoom.room_id == room_id+ )+ )+ )+ )++ async def require_member(+ self, session: AsyncSession, tenant_id: str, user: User, room_id: str+ ) -> tuple[Room, Client]:+ """The room and the caller's member client, or a refusal.++ Checked on every read and write, and again when a retried request+ resumes, so removal from the room or the tenant takes effect at once.+ """+ room = await self._room(session, tenant_id, room_id)+ refusal = ChatError(403, "NOT_A_MEMBER", "You are not a member of this chat.")+ if not await self.has_tenant_role(session, tenant_id, user.id):+ raise refusal+ client = await self.member_client(session, user.id)+ if client is not None and await self._is_in_room(session, client.id, room.id):+ return room, client+ if room.archived_at is None and await self.joins_as_owner(+ session, user.id, room.id+ ):+ await self.sync_owned_rooms(tenant_id, user.id)+ client = await self.member_client(session, user.id)+ if client is not None and await self._is_in_room(+ session, client.id, room.id+ ):+ return room, client+ raise refusal++ async def can_manage(+ self, session: AsyncSession, tenant_id: str, user: User, room: Room+ ) -> bool:+ if room.owner_id is not None and room.owner_id == user.id:+ return True+ role = await self._user_store.tenant_role(session, tenant_id, user.id)+ return administers_tenant(is_operator=user.role == "admin", tenant_role=role)++ async def _require_manager(+ self, session: AsyncSession, tenant_id: str, user: User, room: Room+ ) -> None:+ if not await self.can_manage(session, tenant_id, user, room):+ raise ChatError(+ 403,+ "NOT_A_MANAGER",+ "Only the room's owner or a workspace admin can do that.",+ )++ # ── Agent owners ─────────────────────────────────────────────────────────++ async def joins_as_owner(+ self, session: AsyncSession, user_id: str, room_id: str+ ) -> bool:+ """True when `sync_owned_rooms` keeps the user in this room."""+ if not self.agent_chats_enabled:+ return False+ return bool(+ await session.scalar(+ select(exists().where(Room.id == room_id, _owner_joins(user_id)))+ )+ )++ async def sync_owned_rooms(self, tenant_id: str, user_id: str) -> None:+ """Put the user in every live chat they started that holds an agent+ they own, and take back each membership held only for that once it no+ longer satisfies that rule. With `agent_chats` off nothing satisfies+ it: no one joins, and every such membership is taken back.++ Such a membership is marked by a `ChatOwnerGrant`; being invited,+ creating the chat or joining as a manager removes the mark, and the+ membership then stays when the agent goes. Cheap when nothing changed:+ two queries.+ """+ kept = _owner_joins(user_id) if self.agent_chats_enabled else false()+ async with self._lock("owned", tenant_id, user_id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ if not await self.has_tenant_role(session, tenant_id, user_id):+ return+ client = await self.member_client(session, user_id)+ joined: ColumnElement[bool] = (+ exists().where(+ ClientRoom.client_id == client.id,+ ClientRoom.room_id == Room.id,+ )+ if client is not None+ else false()+ )+ to_join = list(+ (+ await session.execute(+ select(Room)+ .where(+ Room.tenant_id == tenant_id,+ Room.archived_at.is_(None),+ kept,+ ~joined,+ )+ .order_by(Room.created_at)+ )+ )+ .scalars()+ .all()+ )+ to_drop = list(+ (+ await session.execute(+ select(Room)+ .join(ChatOwnerGrant, ChatOwnerGrant.room_id == Room.id)+ .where(+ ChatOwnerGrant.user_id == user_id,+ # A room with no creator makes `kept` NULL, not false.+ ~func.coalesce(kept, false()),+ )+ )+ )+ .scalars()+ .all()+ )+ if not to_join and not to_drop:+ return+ user = await self._user_store.get(session, user_id)+ assert user is not None+ if to_join:+ # Marked before joining: a join cut short leaves a mark+ # the next pass completes or clears, never a membership+ # that would outlive the agent unmarked.+ await session.execute(+ pg_insert(ChatOwnerGrant)+ .values(+ [+ {+ "tenant_id": tenant_id,+ "user_id": user_id,+ "room_id": room.id,+ }+ for room in to_join+ ]+ )+ .on_conflict_do_nothing(+ index_elements=["tenant_id", "user_id", "room_id"]+ )+ )+ await session.commit()+ if client is None:+ client = await self.member_actor(tenant_id, user)+ for room in to_join:+ await self._join(tenant_id, room, client)+ for room in to_drop:+ with tenant_scope(tenant_id):+ await self._provisioning.kick_user(+ room.transport_room_id, client.transport_user_id+ )+ if to_drop:+ async with tenant_session(self.session_factory, tenant_id) as session:+ await session.execute(+ delete(ChatOwnerGrant).where(+ ChatOwnerGrant.user_id == user_id,+ ChatOwnerGrant.room_id.in_([room.id for room in to_drop]),+ )+ )+ await session.commit()+ logger.info(+ "Agent owner %s: joined %d room(s), left %d",+ user_id,+ len(to_join),+ len(to_drop),+ )+ self._memberships_changed(tenant_id, [user_id])++ async def sync_room(self, tenant_id: str, room_id: str) -> None:+ """`sync_owned_rooms` for everyone a change to this room's agents may+ concern: the owners of its agents and the holders of owner grants.+ The room's other members are told too, as gaining or losing its+ agents can move it into or out of their list. Does nothing with+ `agent_chats` off."""+ if not self.agent_chats_enabled:+ return+ async with tenant_session(self.session_factory, tenant_id) as session:+ owners = set(+ (+ await session.execute(+ select(Agent.owner_id)+ .join(room_agents, room_agents.c.agent_id == Agent.id)+ .where(+ room_agents.c.room_id == room_id,+ Agent.owner_id.is_not(None),+ )+ )+ ).scalars()+ )+ holders = set(+ (+ await session.execute(+ select(ChatOwnerGrant.user_id).where(+ ChatOwnerGrant.room_id == room_id+ )+ )+ ).scalars()+ )+ members = set(+ (+ await session.execute(+ select(Client.user_id)+ .join(ClientRoom, ClientRoom.client_id == Client.id)+ .where(+ ClientRoom.room_id == room_id,+ Client.type == MEMBER_CLIENT_TYPE,+ Client.user_id.is_not(None),+ )+ )+ ).scalars()+ )+ for user_id in sorted(+ user_id for user_id in owners | holders if user_id is not None+ ):+ await self.sync_owned_rooms(tenant_id, user_id)+ self._memberships_changed(+ tenant_id, sorted(user_id for user_id in members if user_id is not None)+ )++ 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(+ delete(ChatOwnerGrant).where(+ ChatOwnerGrant.user_id == user_id, ChatOwnerGrant.room_id == room_id+ )+ )+ await session.commit()++ # ── Listing ──────────────────────────────────────────────────────────────++ async def readable_rooms(self, session: AsyncSession, user_id: str) -> list[Room]:+ """All rooms the caller can read: member of, unarchived, tenant role."""+ client = await self.member_client(session, user_id)+ if client is None:+ return []+ result = await session.execute(+ select(Room)+ .join(ClientRoom, ClientRoom.room_id == Room.id)+ .where(+ ClientRoom.client_id == client.id,+ Room.archived_at.is_(None),+ )+ .order_by(Room.created_at)+ )+ return list(result.scalars().all())++ async def stream_rooms(self, session: AsyncSession, user_id: str) -> list[Room]:+ """The caller's member rooms that are chats: unarchived, with an agent."""+ client = await self.member_client(session, user_id)+ if client is None:+ return []+ result = await session.execute(+ select(Room)+ .join(ClientRoom, ClientRoom.room_id == Room.id)+ .where(+ ClientRoom.client_id == client.id,+ Room.archived_at.is_(None),+ exists().where(room_agents.c.room_id == Room.id),+ )+ .order_by(Room.created_at)+ )+ return list(result.scalars().all())++ async def room_activity(+ self, session: AsyncSession, room_id: str+ ) -> tuple[list[AgentSessionActivityItem], list[ApprovalRequest]]:+ """The room's turn steps and approval requests (every state) within retention."""+ since = datetime.now(UTC) - ACTIVITY_RETENTION+ return (+ await self._activity_store.for_room(session, room_id, since),+ await self._approval_store.for_room(session, room_id, since),+ )++ async def turn_items(+ self, session: AsyncSession, agent_id: str, session_id: str, turn_id: str+ ) -> list[AgentSessionActivityItem]:+ return await self._activity_store.turn(session, agent_id, session_id, turn_id)++ async def approval(+ self, session: AsyncSession, agent_id: str, session_id: str, request_id: str+ ) -> ApprovalRequest | None:+ return await self._approval_store.get(+ session, agent_id, session_id, request_id, for_update=False+ )++ async def removal_reason(+ self, session: AsyncSession, user_id: str, room_id: str+ ) -> RemovalReason:+ """Why a room left `stream_rooms`: the caller lost it ("access") or is+ still a member of a live room that no longer qualifies ("unlisted")."""+ room = await self._room_store.get(session, room_id)+ if room is None or room.archived_at is not None:+ return "access"+ client = await self.member_client(session, user_id)+ if client is None or not await self._is_in_room(session, client.id, room_id):+ return "access"+ return "unlisted"++ async def list_chats(self, session: AsyncSession, user_id: str) -> list[Room]:+ """`stream_rooms` less the ones the caller hid with nothing said since."""+ rooms = await self.stream_rooms(session, user_id)+ hidden = {+ row.room_id: row.hidden_through_seq+ for row in (+ await session.execute(+ select(ChatHidden).where(ChatHidden.user_id == user_id)+ )+ ).scalars()+ }+ shown: list[Room] = []+ for room in rooms:+ through = hidden.get(room.id)+ if (+ through is not None+ and await self._last_message_seq(session, room.id) <= through+ ):+ continue+ shown.append(room)+ return shown++ async def _last_message_seq(self, session: AsyncSession, room_id: str) -> int:+ seq = await session.scalar(+ select(Message.seq)+ .where(+ Message.room_id == room_id, Message.event_type.in_(SHOWN_EVENT_TYPES)+ )+ .order_by(Message.seq.desc())+ .limit(1)+ )+ return seq if seq is not None else 0++ async def page(+ self, session: AsyncSession, room_id: str, before_seq: int | None, limit: int+ ) -> tuple[list[Message], int, bool]:+ """Messages before `before_seq` (newest first, returned oldest first),+ the room's head position, and whether older messages remain."""+ query = select(Message).where(+ Message.room_id == room_id, Message.event_type.in_(SHOWN_EVENT_TYPES)+ )+ if before_seq is not None:+ query = query.where(Message.seq < before_seq)+ rows = list(+ (await session.execute(query.order_by(Message.seq.desc()).limit(limit + 1)))+ .scalars()+ .all()+ )+ has_more = len(rows) > limit+ rows = rows[:limit]+ rows.reverse()+ return rows, await self._message_store.head_seq(session, room_id), has_more++ async def head_seq(self, session: AsyncSession, room_id: str) -> int:+ return await self._message_store.head_seq(session, room_id)++ async def messages_after(+ self, session: AsyncSession, room_id: str, after_seq: int, limit: int+ ) -> list[Message]:+ """Every row after `after_seq`, conversation or not, oldest first."""+ return await self._message_store.list_for_room(+ session, room_id, after_seq=after_seq, limit=limit+ )++ async def members(+ self, session: AsyncSession, room: Room+ ) -> list[tuple[User, bool]]:+ result = await session.execute(+ select(User)+ .join(Client, Client.user_id == User.id)+ .join(ClientRoom, ClientRoom.client_id == Client.id)+ .where(+ ClientRoom.room_id == room.id,+ Client.type == MEMBER_CLIENT_TYPE,+ Client.tenant_id == room.tenant_id,+ )+ .order_by(User.name)+ )+ return [(user, user.id == room.owner_id) for user in result.scalars().all()]++ async def media(self, session: AsyncSession, room: Room, uri: str) -> MediaBlob:+ """The bytes behind `uri`, only when a message in this room carries it."""+ carried = await session.scalar(+ select(+ exists().where(+ MessageAttachment.uri == uri,+ MessageAttachment.message_id == Message.id,+ Message.room_id == room.id,+ )+ )+ )+ blob = await self._media_store.get(session, uri) if carried else None+ if blob is None:+ raise ChatError(404, "MEDIA_NOT_FOUND", "No such file in this chat.")+ return blob++ # ── Joining and leaving ──────────────────────────────────────────────────++ async def _join(self, tenant_id: str, room: Room, client: Client) -> None:+ """Put the member client in the room; already in is success."""+ with tenant_scope(tenant_id):+ await self._provisioning.invite_to_room(+ room.transport_room_id, client.transport_user_id+ )++ async def add_member(+ self, tenant_id: str, actor: User, room_id: str, target_user_id: str+ ) -> Room:+ async with tenant_session(self.session_factory, tenant_id) as session:+ room = await self._room(session, tenant_id, room_id)+ await self._require_manager(session, tenant_id, actor, room)+ target = await self._user_store.get(session, target_user_id)+ if target is None or not await self.has_tenant_role(+ session, tenant_id, target_user_id+ ):+ raise ChatError(+ 422,+ "NOT_A_TENANT_MEMBER",+ "That person is not a member of this workspace.",+ )+ client = await self.member_actor(tenant_id, target)+ await self._join(tenant_id, room, client)+ await self._make_lasting(tenant_id, target_user_id, room.id)+ self._memberships_changed(tenant_id, [target_user_id])+ return room++ async def remove_member(+ self, tenant_id: str, actor: User, room_id: str, target_user_id: str+ ) -> None:+ async with tenant_session(self.session_factory, tenant_id) as session:+ if actor.id == target_user_id:+ room, client = await self.require_member(+ session, tenant_id, actor, room_id+ )+ else:+ room = await self._room(session, tenant_id, room_id)+ await self._require_manager(session, tenant_id, actor, room)+ found = await self.member_client(session, target_user_id)+ if found is None or not await self._is_in_room(+ session, found.id, room.id+ ):+ return+ client = found+ if await self.joins_as_owner(session, target_user_id, room.id):+ raise ChatError(+ 409,+ "AGENT_OWNER",+ (+ "You own an agent in this chat, so you stay in it while "+ "the agent does. You can remove it from your list instead."+ )+ if actor.id == target_user_id+ else (+ "They own an agent in this chat, so they stay in it "+ "while the agent does."+ ),+ )+ with tenant_scope(tenant_id):+ await self._provisioning.kick_user(+ room.transport_room_id, client.transport_user_id+ )+ await self._make_lasting(tenant_id, target_user_id, room.id)+ self._memberships_changed(tenant_id, [target_user_id])++ async def archive(self, tenant_id: str, user: User, room_id: str) -> None:+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, _ = await self.require_member(session, tenant_id, user, room_id)+ await self._require_manager(session, tenant_id, user, room)+ member_ids = [member.id for member, _ in await self.members(session, room)]+ await self._room_service.set_room_archived(room.id, True)+ self._memberships_changed(tenant_id, member_ids)++ async def set_hidden(+ self, tenant_id: str, user: User, room_id: str, hidden: bool+ ) -> None:+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, _ = await self.require_member(session, tenant_id, user, room_id)+ if hidden:+ through = await self._message_store.head_seq(session, room.id)+ await session.execute(+ pg_insert(ChatHidden)+ .values(+ tenant_id=tenant_id,+ user_id=user.id,+ room_id=room.id,+ hidden_through_seq=through,+ )+ .on_conflict_do_update(+ index_elements=["tenant_id", "user_id", "room_id"],+ set_={"hidden_through_seq": through},+ )+ )+ else:+ await session.execute(+ delete(ChatHidden).where(+ ChatHidden.user_id == user.id, ChatHidden.room_id == room.id+ )+ )+ await session.commit()++ # ── Operations ───────────────────────────────────────────────────────────++ async def _operation(+ self, session: AsyncSession, user_id: str, request_id: str+ ) -> ChatOperation | None:+ return await session.get(+ ChatOperation, (require_tenant_id(), user_id, request_id)+ )++ @staticmethod+ def _require_same(operation: ChatOperation, kind: str, payload_hash: str) -> None:+ if operation.kind != kind or operation.payload_hash != payload_hash:+ raise ChatError(+ 409,+ "REQUEST_REUSED",+ "This request id was already used for a different request.",+ )++ async def _claim(+ self,+ session: AsyncSession,+ *,+ tenant_id: str,+ user_id: str,+ request_id: str,+ kind: str,+ payload_hash: str,+ state: str,+ room_id: str | None,+ ) -> bool:+ """Insert the operation row; False when one already holds the key.++ A concurrent attempt with the same key waits here for the first to+ commit or roll back, so at most one of them goes on to act.+ """+ claimed = await session.scalar(+ pg_insert(ChatOperation)+ .values(+ tenant_id=tenant_id,+ user_id=user_id,+ request_id=request_id,+ kind=kind,+ payload_hash=payload_hash,+ state=state,+ room_id=room_id,+ )+ .on_conflict_do_nothing(+ index_elements=["tenant_id", "user_id", "request_id"]+ )+ .returning(ChatOperation.request_id)+ )+ return claimed is not None++ async def _require_may_use_agent(+ self, session: AsyncSession, tenant_id: str, user: User, agent_id: str+ ) -> Agent:+ """The agent, if the user may address it themselves.++ The rule the platform applies when it speaks for a person, asked+ before the room exists: a rule naming particular rooms admits nobody+ into a new one, and no claimed platform account is consulted.+ """+ agent = await self._agent_store.get(session, agent_id)+ if agent is None or agent.tenant_id != tenant_id:+ raise ChatError(404, "AGENT_NOT_FOUND", "Agent not found.")+ if not allows_on_behalf_of(+ parse_policy(agent.addressing_policy),+ room_id="",+ group_id=None,+ user_id=user.id,+ external_user_ids=[],+ owner_user_id=agent.owner_id,+ ):+ raise ChatError(+ 403, "AGENT_NOT_ALLOWED", "You may not start a chat with this agent."+ )+ return agent++ def _operation_id(self, tenant_id: str, user_id: str, request_id: str) -> str:+ return str(uuid.uuid5(_CHATS_NAMESPACE, f"{tenant_id}:{user_id}:{request_id}"))++ async def create_chat(+ self,+ tenant_id: str,+ user: User,+ *,+ agent_ids: list[str],+ name: str | None,+ request_id: str,+ ) -> Room:+ """A private room with the agents, owned by and joined by the user.++ One agent makes a direct room, which addresses it without a mention.+ Several make a private channel, where a message names the agent it is+ for. Every agent must be one the user may address.++ Retrying with the same request id finishes whatever an earlier attempt+ left undone: the room is found by the operation id stamped on it, and+ the agents' and the user's memberships are re-applied.+ """+ if not agent_ids:+ raise ChatError(422, "AGENTS_REQUIRED", "A chat needs at least one agent.")+ payload_hash = _hash(+ {"agentId": agent_ids[0], "name": name}+ if len(agent_ids) == 1+ else {"agentIds": agent_ids, "name": name}+ )+ async with self._lock("create", tenant_id, user.id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ operation = await self._operation(session, user.id, request_id)+ if operation is not None:+ self._require_same(operation, "create_chat", payload_hash)+ if operation.state == "done" and operation.room_id is not None:+ room, _ = await self.require_member(+ session, tenant_id, user, operation.room_id+ )+ return room+ agents = [+ await self._require_may_use_agent(+ session, tenant_id, user, agent_id+ )+ for agent_id in agent_ids+ ]+ if operation is None:+ await self._claim(+ session,+ tenant_id=tenant_id,+ user_id=user.id,+ request_id=request_id,+ kind="create_chat",+ payload_hash=payload_hash,+ state="pending",+ room_id=None,+ )+ await session.commit()+ operation_id = self._operation_id(tenant_id, user.id, request_id)+ found = (+ await session.execute(+ select(Room).where(+ Room.metadata_["chat_operation_id"].astext == operation_id+ )+ )+ ).scalar_one_or_none()+ if found is None:+ 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+ ),+ description="Switch Console chat with "+ + ", ".join(agent.name for agent in agents),+ agent_ids=[agent.id for agent in agents],+ channel_type=(+ "direct" if len(agents) == 1 else "channel_private"+ ),+ internal_only=True,+ created_by=user.id,+ owner_id=user.id,+ read_visibility="private",+ write_visibility="private",+ acting_user_id=user.id,+ created_by_kind="user",+ chat_operation_id=operation_id,+ )+ )+ except ValueError as exc:+ raise ChatError(422, "CHAT_NOT_CREATED", str(exc)) from exc+ room = created.room+ else:+ room = found+ await self._room_service.reconcile_room(room)+ client = await self.member_actor(tenant_id, user)+ await self._join(tenant_id, room, client)+ await self._make_lasting(tenant_id, user.id, room.id)+ async with tenant_session(self.session_factory, tenant_id) as session:+ await session.execute(+ update(ChatOperation)+ .where(+ ChatOperation.tenant_id == tenant_id,+ ChatOperation.user_id == user.id,+ ChatOperation.request_id == request_id,+ )+ .values(state="done", room_id=room.id, result={"roomId": room.id})+ )+ await session.commit()+ self._memberships_changed(tenant_id, [user.id])+ return room++ async def stage_upload(+ self,+ tenant_id: str,+ user: User,+ room_id: str,+ *,+ upload_id: str,+ data: bytes,+ filename: str,+ mimetype: str,+ ) -> StagedUpload:+ """Store a file for a later send, keyed by the caller's upload id."""+ mimetype = normalise_mime_type(mimetype) or "application/octet-stream"+ if not data:+ raise ChatError(422, "ATTACHMENT_REFUSED", f"'{filename}' is empty.")+ if len(data) > self._media_max_bytes:+ raise ChatError(+ 422,+ "ATTACHMENT_REFUSED",+ f"'{filename}' is {len(data)} bytes, over the "+ f"{self._media_max_bytes}-byte limit.",+ )+ key = _upload_key(upload_id)+ payload_hash = _hash(+ {+ "roomId": room_id,+ "filename": filename,+ "mimetype": mimetype,+ "sha256": hashlib.sha256(data).hexdigest(),+ }+ )+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, _ = await self.require_member(session, tenant_id, user, room_id)+ if await self._claim(+ session,+ tenant_id=tenant_id,+ user_id=user.id,+ request_id=key,+ kind="upload",+ payload_hash=payload_hash,+ state="done",+ room_id=room.id,+ ):+ uri = f"switch-media://{uuid.uuid4().hex}"+ await self._media_store.put(+ session,+ MediaBlob(+ uri=uri,+ content_type=mimetype,+ filename=filename,+ size=len(data),+ data=data,+ ),+ )+ staged = StagedUpload(upload_id, uri, filename, mimetype, len(data))+ await session.execute(+ update(ChatOperation)+ .where(+ ChatOperation.tenant_id == tenant_id,+ ChatOperation.user_id == user.id,+ ChatOperation.request_id == key,+ )+ .values(result=_staged_result(staged))+ )+ await session.commit()+ return staged+ operation = await self._operation(session, user.id, key)+ assert operation is not None+ self._require_same(operation, "upload", payload_hash)+ return _staged(upload_id, operation)++ async def send(+ self,+ tenant_id: str,+ user: User,+ room_id: str,+ *,+ request_id: str,+ body: str,+ thread_root_id: str | None,+ upload_ids: list[str],+ mention_agent_id: str | None,+ ) -> tuple[Room, list[Message]]:+ """Post the user's message, every part of it in one transaction.++ Files are staged first (`stage_upload`), so all that is left here is+ writing rows: each part, and the operation marked done, commit+ together or not at all. A retry after a failure before the commit+ posts it once; one after the commit answers the parts already posted.+ """+ payload_hash = _hash(+ {+ "roomId": room_id,+ "body": body,+ "threadRootId": thread_root_id,+ "uploadIds": upload_ids,+ "mentionAgentId": mention_agent_id,+ }+ )+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, client = await self.require_member(session, tenant_id, user, room_id)+ operation = await self._operation(session, user.id, request_id)+ if operation is not None:+ self._require_same(operation, "send", payload_hash)+ return room, await self._posted(session, room, operation)++ if not body.strip() and not upload_ids:+ raise ChatError(422, "EMPTY_MESSAGE", "There is nothing to send.")+ uploads = [+ await self._staged_upload(session, user.id, room.id, upload_id)+ for upload_id in upload_ids+ ]+ root = await self._thread_root(session, room, thread_root_id)+ if mention_agent_id is not None:+ body = await self._with_mention(session, room, mention_agent_id, body)++ if not await self._claim(+ session,+ tenant_id=tenant_id,+ user_id=user.id,+ request_id=request_id,+ kind="send",+ payload_hash=payload_hash,+ state="done",+ room_id=room.id,+ ):+ operation = await self._operation(session, user.id, request_id)+ assert operation is not None+ self._require_same(operation, "send", payload_hash)+ return room, await self._posted(session, room, operation)++ contents = _parts(+ body,+ uploads,+ sender_name=user.name,+ thread_root_id=root,+ group_id=str(+ uuid.uuid5(+ _CHATS_NAMESPACE,+ f"{tenant_id}:{client.id}:{room.id}:{request_id}",+ )+ ),+ )+ posted: list[Message] = []+ for index, content in enumerate(contents):+ message = message_row(+ room_id=room.id,+ event_id=new_event_id(),+ sender_id=client.transport_user_id,+ sender_client_id=client.id,+ sender_name=user.name,+ event_type=MESSAGE_EVENT_TYPE,+ content=content,+ client_txn_id=f"{request_id}:{index}",+ )+ posted.append(+ await self._message_store.create(+ session, message, attachments_in(content)+ )+ )+ await self._usage_store.record(+ session,+ tenant_id=tenant_id,+ metric=UsageMetric.MESSAGES,+ client_id=client.id,+ model="",+ amount=len(posted),+ )+ await session.execute(+ update(ChatOperation)+ .where(+ ChatOperation.tenant_id == tenant_id,+ ChatOperation.user_id == user.id,+ ChatOperation.request_id == request_id,+ )+ .values(result={"messageIds": [m.transport_event_id for m in posted]})+ )+ await session.commit()+ for content in contents:+ metrics().increment(+ MESSAGES_SENT,+ {"kind": "media" if "url" in content else "message", "actor": "human"},+ )+ return room, posted++ async def control(+ self,+ tenant_id: str,+ user: User,+ room_id: str,+ *,+ request_id: str,+ agent_id: str,+ command: RoomControl,+ ) -> str:+ """Post `!<command> @agent` as the user; the command's event id.++ Written as the `com.switch.command` event a platform bridge writes for+ a typed `!interrupt`, so the agents' own command handling, addressing+ gate and in-room acknowledgement apply unchanged. The addressing check+ here only turns a refusal into an answer instead of a room message.+ """+ payload_hash = _hash(+ {"roomId": room_id, "agentId": agent_id, "command": command}+ )+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, client = await self.require_member(session, tenant_id, user, room_id)+ operation = await self._operation(session, user.id, request_id)+ if operation is not None:+ self._require_same(operation, "control", payload_hash)+ return str((operation.result or {})["commandId"])++ if agent_id not in await self._room_store.get_agent_ids(session, room.id):+ raise ChatError(+ 422, "AGENT_NOT_IN_CHAT", "That agent is not in this chat."+ )+ agent = await self._agent_store.get(session, agent_id)+ assert agent is not None+ 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)+ # `!interrupt` stops the agent's running turn wherever it runs; this check can race a turn change.+ if command == "interrupt":+ turn = await self._activity_store.newest_running_turn(session, agent.id)+ if turn is None or turn.room_id != room.id:+ raise ChatError(+ 409,+ "NOTHING_RUNNING_HERE",+ f"{agent.name}'s current turn is not in this chat.",+ )++ if not await self._claim(+ session,+ tenant_id=tenant_id,+ user_id=user.id,+ request_id=request_id,+ kind="control",+ payload_hash=payload_hash,+ state="done",+ room_id=room.id,+ ):+ operation = await self._operation(session, user.id, request_id)+ assert operation is not None+ self._require_same(operation, "control", payload_hash)+ return str((operation.result or {})["commandId"])++ command_id = new_event_id()+ await self._message_store.create(+ session,+ message_row(+ room_id=room.id,+ event_id=command_id,+ sender_id=client.transport_user_id,+ sender_client_id=client.id,+ sender_name=user.name,+ event_type=COMMAND_EVENT_TYPE,+ content={+ "command": command,+ "args": f"@{agent.name}",+ "user_id": client.transport_user_id,+ "user_name": user.name,+ },+ client_txn_id=request_id,+ ),+ [],+ )+ await session.execute(+ update(ChatOperation)+ .where(+ ChatOperation.tenant_id == tenant_id,+ ChatOperation.user_id == user.id,+ ChatOperation.request_id == request_id,+ )+ .values(result={"commandId": command_id})+ )+ await session.commit()+ return command_id++ async def warm(+ self, tenant_id: str, user: User, room_id: str, *, agent_id: str+ ) -> None:+ """Ask the controller of the user's own agent to start its session for+ this chat before the first message. A hint: nothing waits for it, and+ an agent no controller hosts is not warmed."""+ async with tenant_session(self.session_factory, tenant_id) as session:+ room, client = await self.require_member(session, tenant_id, user, room_id)+ if agent_id not in await self._room_store.get_agent_ids(session, room.id):+ raise ChatError(+ 422, "AGENT_NOT_IN_CHAT", "That agent is not in this chat."+ )+ 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)+ if not self._controllers.is_bound(agent_id):+ return+ if not self._controllers.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",+ agent_id,+ room.id,+ )++ async def _posted(+ self, session: AsyncSession, room: Room, operation: ChatOperation+ ) -> list[Message]:+ ids = (operation.result or {}).get("messageIds", [])+ rows = await self._message_store.list_by_transport_event_ids(+ session, room.id, ids+ )+ return sorted(rows, key=lambda m: m.seq)++ async def _staged_upload(+ self, session: AsyncSession, user_id: str, room_id: str, upload_id: str+ ) -> StagedUpload:+ operation = await self._operation(session, user_id, _upload_key(upload_id))+ if (+ operation is None+ or operation.kind != "upload"+ or operation.room_id != room_id+ ):+ raise ChatError(+ 422,+ "UPLOAD_NOT_FOUND",+ f"No file was uploaded to this chat as {upload_id}.",+ )+ return _staged(upload_id, operation)++ async def _thread_root(+ self, session: AsyncSession, room: Room, thread_root_id: str | None+ ) -> str | None:+ """The thread a reply goes in: a mid-thread message names its root."""+ if thread_root_id is None:+ return None+ found = await self._message_store.list_by_transport_event_ids(+ session, room.id, [thread_root_id]+ )+ if not found:+ raise ChatError(+ 422, "THREAD_NOT_FOUND", "The message to reply to is not in this chat."+ )+ return found[0].thread_root_event_id or found[0].transport_event_id++ async def _with_mention(+ self, session: AsyncSession, room: Room, agent_id: str, body: str+ ) -> str:+ if agent_id not in await self._room_store.get_agent_ids(session, room.id):+ raise ChatError(422, "AGENT_NOT_IN_CHAT", "That agent is not in this chat.")+ agent = await self._agent_store.get(session, agent_id)+ assert agent is not None+ if mention_regex(agent.name).search(strip_emphasis(body)) is not None:+ return body+ return f"@{agent.name} {body}" if body else f"@{agent.name}"+++def _owns_agent_in_room(user_id: str) -> ColumnElement[bool]:+ """True for a `Room` row holding an agent `user_id` owns."""+ return exists().where(+ room_agents.c.room_id == Room.id,+ room_agents.c.agent_id == Agent.id,+ Agent.owner_id == user_id,+ )+++def _owner_joins(user_id: str) -> ColumnElement[bool]:+ """True for a `Room` row `sync_owned_rooms` puts `user_id` in: a chat they+ started through the chats API that holds an agent they own."""+ return and_(+ Room.created_by == user_id,+ Room.metadata_.has_key("chat_operation_id"),+ _owns_agent_in_room(user_id),+ )+++def _staged_result(staged: StagedUpload) -> dict[str, object]:+ return {+ "uri": staged.uri,+ "filename": staged.filename,+ "mimetype": staged.mimetype,+ "size": staged.size,+ }+++def _staged(upload_id: str, operation: ChatOperation) -> StagedUpload:+ result = operation.result or {}+ return StagedUpload(+ upload_id=upload_id,+ uri=str(result["uri"]),+ filename=str(result["filename"]),+ mimetype=str(result["mimetype"]),+ size=int(str(result["size"])),+ )+++_PARAGRAPH_TAG = re.compile(r"</?p>")+_HTML_TAG = re.compile(r"<[A-Za-z/!]")+++def _format_of(body: str) -> MessageFormat:+ """Markdown only when rendering it adds more than paragraphs.++ A plain sentence stays plain text, so receivers do not get an HTML body+ that says nothing the text does not.+ """+ rendered = _PARAGRAPH_TAG.sub("", markdown.markdown(body))+ return "markdown" if _HTML_TAG.search(rendered) else "text"+++def _parts(+ body: str,+ uploads: list[StagedUpload],+ *,+ sender_name: str,+ thread_root_id: str | None,+ group_id: str,+) -> list[dict[str, object]]:+ """The events a send is made of.++ Text alone is one message. With files, the text rides as the caption on+ the first and the rest are bare media events; more than one file shares+ a group so receivers can show them as one post.+ """+ if not uploads:+ return [+ message_content(+ body,+ sender_name=sender_name,+ format=_format_of(body),+ thread_root_id=thread_root_id,+ )+ ]+ total = len(uploads)+ return [+ media_content(+ upload.uri,+ upload.filename,+ upload.mimetype,+ upload.size,+ sender_name=sender_name,+ msgtype="m.image" if upload.mimetype.startswith("image/") else "m.file",+ caption=body if index == 0 and body.strip() else None,+ thread_root_id=thread_root_id,+ group=(+ {"id": group_id, "index": index, "total": total} if total > 1 else None+ ),+ )+ for index, upload in enumerate(uploads)+ ]diff --git a/core/switch_core/chats/views.py b/core/switch_core/chats/views.pynew file mode 100644index 000000000..afd6e83f3--- /dev/null+++ b/core/switch_core/chats/views.py@@ -0,0 +1,278 @@+"""What Switch Console is shown of a chat: summaries, messages and members.++Assembled from the database alone, so the HTTP routes and the event stream+describe a room in exactly the same terms.+"""++from __future__ import annotations++from collections.abc import Sequence+from datetime import datetime++from pydantic import BaseModel, ConfigDict+from pydantic.alias_generators import to_camel+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.chats import MEMBER_CLIENT_TYPE+from switch_core.db.models import (+ Agent,+ AgentDefinition,+ Client,+ CollaborationBridge,+ Message,+ Room,+ room_agents,+)+from switch_core.db.stores.message_store import MessageStore++MESSAGE_EVENT_TYPE = "m.room.message"+COMMAND_EVENT_TYPE = "com.switch.command"+# A room command (`!reset @agent`) is shown so its threaded acknowledgement has a visible root.+SHOWN_EVENT_TYPES = (MESSAGE_EVENT_TYPE, COMMAND_EVENT_TYPE)+PREVIEW_CHARS = 140++_MESSAGE_STORE = MessageStore()++_PROVIDER_OF_KNOWN_AGENT_TYPE = {+ "claude-code": "claude",+ "codex": "codex",+ "opencode": "opencode",+ "antigravity": "antigravity",+ "cursor": "cursor",+}+++def _provider(agent: Agent, defined: object) -> str | None:+ """The provider an agent runs on: its managed definition's, else its registration's."""+ if isinstance(defined, str):+ return defined+ metadata = agent.metadata_ if isinstance(agent.metadata_, dict) else {}+ known = metadata.get("known_agent_type")+ return _PROVIDER_OF_KNOWN_AGENT_TYPE.get(known) if isinstance(known, str) else None+++class CamelModel(BaseModel):+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)+++class ChatAgent(CamelModel):+ id: str+ name: str+ display_name: str | None+ icon_url: str | None+ provider: str | None+++class ChatLastMessage(CamelModel):+ seq: int+ sent_at: str+ preview: str+ sender_name: str+++class ChatSummary(CamelModel):+ room_id: str+ name: str+ channel_type: str+ bridge_type: str | None+ channel_name: str | None+ agents: list[ChatAgent]+ can_manage: bool+ # The viewer owns one of the agents, which keeps them in the room.+ owns_agent: bool+ last_message: ChatLastMessage | None+++class ChatSender(CamelModel):+ client_id: str+ name: str+ kind: str+ agent_id: str | None+ user_id: str | None+++class ChatAttachment(CamelModel):+ uri: str+ filename: str+ mimetype: str+ size: int+ msgtype: str+++class ChatMessage(CamelModel):+ message_id: str+ seq: int+ room_id: str+ sent_at: str+ sender: ChatSender+ source: str+ body: str+ format: str | None+ thread_root_id: str | None+ attachments: list[ChatAttachment]+ client_txn: str | None+++class ChatMember(CamelModel):+ user_id: str+ name: str+ is_owner: bool+++def _iso(value: object) -> str:+ return value.isoformat() if isinstance(value, datetime) else str(value)+++async def _bridge(session: AsyncSession, room: Room) -> CollaborationBridge | None:+ if room.bridge_id is None:+ return None+ return await session.get(CollaborationBridge, room.bridge_id)+++async def chat_summary(+ session: AsyncSession, room: Room, *, viewer_id: str, can_manage: bool+) -> ChatSummary:+ agent_rows = (+ await session.execute(+ select(Agent)+ .join(room_agents, room_agents.c.agent_id == Agent.id)+ .where(room_agents.c.room_id == room.id)+ .order_by(Agent.name)+ )+ ).scalars()+ agents = list(agent_rows)+ providers = {+ definition.agent_id: definition.definition.get("provider")+ for definition in (+ await session.execute(+ select(AgentDefinition).where(+ AgentDefinition.agent_id.in_([agent.id for agent in agents])+ )+ )+ ).scalars()+ }+ bridge = await _bridge(session, room)+ channel_name: str | None = None+ if bridge is not None and room.external_channel_id is not None:+ prefix = f"{bridge.display_name}: "+ channel_name = (+ room.name[len(prefix) :] if room.name.startswith(prefix) else room.name+ )+ last = (+ await session.execute(+ select(Message)+ .where(+ Message.room_id == room.id, Message.event_type.in_(SHOWN_EVENT_TYPES)+ )+ .order_by(Message.seq.desc())+ .limit(1)+ )+ ).scalar_one_or_none()+ return ChatSummary(+ room_id=room.id,+ name=room.name,+ channel_type=room.channel_type or "channel_public",+ bridge_type=bridge.type if bridge is not None else None,+ channel_name=channel_name,+ agents=[+ ChatAgent(+ id=agent.id,+ name=agent.name,+ display_name=agent.display_name,+ icon_url=agent.icon_url,+ provider=_provider(agent, providers.get(agent.id)),+ )+ for agent in agents+ ],+ can_manage=can_manage,+ owns_agent=any(agent.owner_id == viewer_id for agent in agents),+ last_message=(+ ChatLastMessage(+ seq=last.seq,+ sent_at=_iso(last.sent_at),+ preview=(last.body or _command_text(last))[:PREVIEW_CHARS],+ sender_name=last.sender_name or "",+ )+ if last is not None+ else None+ ),+ )+++def _command_text(message: Message) -> str:+ if message.event_type != COMMAND_EVENT_TYPE:+ return ""+ command = message.content.get("command")+ args = message.content.get("args")+ return f"!{command} {args}".strip() if args else f"!{command}"+++async def chat_messages(+ session: AsyncSession, room: Room, messages: Sequence[Message]+) -> list[ChatMessage]:+ """`messages` as Switch Console renders them, in the order given.++ Only conversation is shown: a row of any other event type is skipped.+ """+ shown = [m for m in messages if m.event_type in SHOWN_EVENT_TYPES]+ client_ids = {m.sender_client_id for m in shown if m.sender_client_id}+ clients = {+ client.id: client+ for client in (+ await session.execute(select(Client).where(Client.id.in_(client_ids)))+ ).scalars()+ }+ agents = {+ agent.client_id: agent+ for agent in (+ await session.execute(select(Agent).where(Agent.client_id.in_(client_ids)))+ ).scalars()+ }+ bridge = await _bridge(session, room)+ attachments = await _MESSAGE_STORE.attachments_for(session, [m.id for m in shown])+ out: list[ChatMessage] = []+ for message in shown:+ client = clients.get(message.sender_client_id or "")+ agent = agents.get(message.sender_client_id or "")+ if agent is not None:+ kind, source = "agent", "switch"+ elif client is not None and client.type == MEMBER_CLIENT_TYPE:+ kind, source = "human", "console"+ elif client is not None and client.type == "user":+ kind, source = "human", bridge.type if bridge is not None else "switch"+ else:+ kind, source = "system", "switch"+ format_ = message.content.get("format")+ out.append(+ ChatMessage(+ message_id=message.transport_event_id,+ seq=message.seq,+ room_id=room.id,+ sent_at=_iso(message.sent_at),+ sender=ChatSender(+ client_id=message.sender_client_id or "",+ name=message.sender_name+ or (client.display_name if client is not None else ""),+ kind=kind,+ agent_id=agent.id if agent is not None else None,+ user_id=client.user_id if client is not None else None,+ ),+ source=source,+ body=message.body or _command_text(message),+ format=format_ if isinstance(format_, str) else None,+ thread_root_id=message.thread_root_event_id,+ attachments=[+ ChatAttachment(+ uri=attachment.uri,+ filename=attachment.filename or "",+ mimetype=attachment.mimetype or "application/octet-stream",+ size=attachment.size or 0,+ msgtype=message.msgtype or "m.file",+ )+ for attachment in attachments.get(message.id, [])+ ],+ client_txn=message.client_txn_id,+ )+ )+ return outdiff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex d9c23ab24..9de330a73 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -10,6 +10,7 @@ from sqlalchemy.exc import InterfaceError, OperationalErrorfrom sqlalchemy.exc import TimeoutError as PoolTimeoutErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.chats import MEMBER_CLIENT_TYPEfrom switch_core.clients.actor import Actor, AgentActor, ClientConfigfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.consumer import Consumer@@ -229,7 +230,13 @@ class ClientLifecycleService:if record.tenant_id == tenant_id)- records = [r for r in records if r.type not in self.COLLAB_CLIENT_TYPES]+ # A member client's messages are written by the chats routes in the+ # request's own transaction, so it has nothing to run.+ records = [+ r+ for r in records+ if r.type not in self.COLLAB_CLIENT_TYPES and r.type != MEMBER_CLIENT_TYPE+ ]try:agents = await self._agents_by_client_id(records)except Exception:diff --git a/core/switch_core/clients/workspace_consumer.py b/core/switch_core/clients/workspace_consumer.pyindex 394b19b10..b291b3f90 100644--- a/core/switch_core/clients/workspace_consumer.py+++ b/core/switch_core/clients/workspace_consumer.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKINGfrom switch_core.clients.actor import Actor, ClientConfigfrom switch_core.clients.consumer import Consumer+from switch_core.events import CommandEventfrom switch_core.logging_context import log_contextfrom switch_core.transport import InboundMedia, InboundMessage, RoomRef@@ -58,3 +59,9 @@ class WorkspaceConsumer(Consumer[Actor[WorkspaceConsumerConfig]]):bridge="collaboration", platform=self._collaboration_core.bridge_type):await self._collaboration_core.handle_outbound_media(room, event, self)++ async def on_command(self, room: RoomRef, event: CommandEvent) -> None:+ with log_context(+ bridge="collaboration", platform=self._collaboration_core.bridge_type+ ):+ await self._collaboration_core.handle_outbound_command(room, event)diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex a581945b7..cd112de25 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -15,6 +15,7 @@ from pydantic import AliasChoices, Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom switch_core.feature_flags import (+ AGENT_CHATS,AGENT_MANAGEMENT,HOSTED_AGENTS,KNOWN_FEATURE_FLAGS,@@ -1161,6 +1162,10 @@ class SwitchConfig(BaseSettings):def service_connections_enabled(self) -> bool:return self.feature_flags[SERVICE_CONNECTIONS]+ @property+ def agent_chats_enabled(self) -> bool:+ return self.feature_flags[AGENT_CHATS]+@model_validator(mode="after")def _validate_outbound_allowed_private_hosts(self) -> "SwitchConfig":OutboundPolicy.parse(self.outbound_allowed_private_hosts)diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex f83e7fba3..72a49db7c 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -588,6 +588,7 @@ class Client(TenantScoped, Base):"tenant_id", "matrix_user_id", name="uq_clients_tenant_matrix_user_id"),UniqueConstraint("id", "tenant_id", name="uq_clients_id_tenant"),+ UniqueConstraint("tenant_id", "user_id", name="uq_clients_tenant_user_id"),)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)@@ -598,6 +599,14 @@ class Client(TenantScoped, Base):display_name: Mapped[str] = mapped_column(Text, nullable=False)type: Mapped[str] = mapped_column(Text, nullable=False)config: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+ # The gateway user a `member` client speaks for: a person in a room as+ # themselves, through Switch Console, rather than through a platform+ # account. NULL for every other client type.+ user_id: Mapped[str | None] = mapped_column(+ Text,+ ForeignKey("users.id", ondelete="SET NULL", name="fk_clients_user"),+ nullable=True,+ )created_at: Mapped[str] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)@@ -2225,6 +2234,14 @@ class Message(TenantScoped, Base):postgresql_where=text("thread_root_event_id IS NOT NULL"),),UniqueConstraint("id", "tenant_id", name="uq_messages_id_tenant"),+ # A sender's retry of the same part is the same row, never a second one.+ Index(+ "uq_messages_sender_client_txn",+ "sender_client_id",+ "client_txn_id",+ unique=True,+ postgresql_where=text("client_txn_id IS NOT NULL"),+ ),ForeignKeyConstraint(["tenant_id", "room_id"],["rooms.tenant_id", "rooms.id"],@@ -2276,6 +2293,9 @@ class Message(TenantScoped, Base):sent_at: Mapped[str] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)+ # The sender's own idempotency key for this part, `{requestId}:{index}`,+ # set by Switch Console sends. NULL for everything else.+ client_txn_id: Mapped[str | None] = mapped_column(Text, nullable=True)class MessageAttachment(TenantScoped, Base):@@ -2661,6 +2681,118 @@ class MediaBlob(TenantScoped, Base):)+# ── Chats ─────────────────────────────────────────────────────────────────────+++class ChatOperation(TenantScoped, Base):+ """A Switch Console request a person may retry, keyed by their request id.++ The same key with the same payload answers what the first attempt did; the+ same key with a different payload is refused. `pending` is only ever seen+ on a chat creation, which spans several transactions: a send and an upload+ commit their effect and this row together, so they are `done` or absent.+ """++ __tablename__ = "chat_operations"+ __table_args__ = (+ PrimaryKeyConstraint("tenant_id", "user_id", "request_id"),+ ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_operations_room",+ ondelete="CASCADE",+ ),+ CheckConstraint(+ "kind IN ('create_chat', 'send', 'upload', 'control')",+ name="ck_chat_operations_kind",+ ),+ CheckConstraint(+ "state IN ('pending', 'done')", name="ck_chat_operations_state"+ ),+ )++ user_id: Mapped[str] = mapped_column(+ Text,+ ForeignKey("users.id", ondelete="CASCADE", name="fk_chat_operations_user"),+ nullable=False,+ )+ request_id: Mapped[str] = mapped_column(Text, nullable=False)+ kind: Mapped[str] = mapped_column(Text, nullable=False)+ payload_hash: Mapped[str] = mapped_column(Text, nullable=False)+ state: Mapped[str] = mapped_column(Text, nullable=False)+ room_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ result: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )+++class ChatHidden(TenantScoped, Base):+ """A chat one person took off their own list, until something new is said.++ `hidden_through_seq` is the room's position when it was hidden; a message+ after it brings the chat back.+ """++ __tablename__ = "chat_hidden"+ __table_args__ = (+ PrimaryKeyConstraint("tenant_id", "user_id", "room_id"),+ ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_hidden_room",+ ondelete="CASCADE",+ ),+ )++ user_id: Mapped[str] = mapped_column(+ Text,+ ForeignKey("users.id", ondelete="CASCADE", name="fk_chat_hidden_user"),+ nullable=False,+ )+ room_id: Mapped[str] = mapped_column(Text, nullable=False)+ hidden_through_seq: Mapped[int] = mapped_column(BigInteger, nullable=False)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+++class ChatOwnerGrant(TenantScoped, Base):+ """A membership held only because the person owns an agent in the room.++ Present while that is the sole reason: it goes with the membership when+ they no longer own an agent there, and is dropped (making the membership+ lasting) when they are invited, create the chat, or join as a manager.+ """++ __tablename__ = "chat_owner_grants"+ __table_args__ = (+ PrimaryKeyConstraint("tenant_id", "user_id", "room_id"),+ ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_owner_grants_room",+ ondelete="CASCADE",+ ),+ )++ user_id: Mapped[str] = mapped_column(+ Text,+ ForeignKey("users.id", ondelete="CASCADE", name="fk_chat_owner_grants_user"),+ nullable=False,+ )+ room_id: Mapped[str] = mapped_column(Text, nullable=False)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )++# `create_all` builds the schema for tests; the trigger has to come with it or# the delivery tests would exercise a table that announces nothing. Real# databases get the same DDL from a migration.diff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex e55f722d1..c365ac31d 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom datetime import datetimefrom typing import TYPE_CHECKING-from sqlalchemy import delete, func, select, update+from sqlalchemy import delete, func, or_, select, updatefrom sqlalchemy.dialects.postgresql import insertfrom switch_core.db.models import Agent, AgentSessionActivityItem, ApprovalRequest@@ -83,6 +83,22 @@ class ApprovalRequestStore:)return list(result.scalars())+ async def for_room(+ self, session: AsyncSession, room_id: str, since: datetime+ ) -> list[ApprovalRequest]:+ """Open requests in `room_id` plus closed ones changed since `since`; oldest first."""+ result = await session.execute(+ select(ApprovalRequest)+ .where(+ ApprovalRequest.room_id == room_id,+ or_(+ ApprovalRequest.state == "open", ApprovalRequest.updated_at >= since+ ),+ )+ .order_by(ApprovalRequest.created_at)+ )+ return list(result.scalars())+async def expire_due(self, session: AsyncSession, now: datetime) -> list[ApprovalRequest]:@@ -199,6 +215,38 @@ class AgentSessionActivityStore:)return list(result.scalars())+ async def newest_running_turn(+ self, session: AsyncSession, agent_id: str+ ) -> AgentSessionActivityItem | None:+ """The agent's most recently reported running turn row; queued turns wait behind it."""+ result = await session.execute(+ select(AgentSessionActivityItem)+ .where(+ AgentSessionActivityItem.agent_id == agent_id,+ AgentSessionActivityItem.item_id == TURN_ITEM_ID,+ AgentSessionActivityItem.status == "running",+ )+ .order_by(AgentSessionActivityItem.created_at.desc())+ .limit(1)+ )+ return result.scalar_one_or_none()++ async def for_room(+ self, session: AsyncSession, room_id: str, since: datetime+ ) -> list[AgentSessionActivityItem]:+ """Steps placed in `room_id` changed since `since`, in first-reported order."""+ result = await session.execute(+ select(AgentSessionActivityItem)+ .where(+ AgentSessionActivityItem.room_id == room_id,+ AgentSessionActivityItem.updated_at >= since,+ )+ .order_by(+ AgentSessionActivityItem.created_at, AgentSessionActivityItem.item_id+ )+ )+ return list(result.scalars())+async def prune_before(self, session: AsyncSession, cutoff: datetime) -> int:result = await session.execute(delete(AgentSessionActivityItem).where(diff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.pyindex f2bbe9c73..cd442dacf 100644--- a/core/switch_core/delivery/addressing.py+++ b/core/switch_core/delivery/addressing.py@@ -34,6 +34,7 @@ from switch_core.addressing import (can_address,parse_policy,)+from switch_core.chats import MEMBER_CLIENT_TYPEfrom switch_core.clients.admin_messages import (ADMIN_MARKER,PLATFORM_MARKER,@@ -386,9 +387,13 @@ class AddressingResolver:"""Map a sender's mxid to the principal a policy is written about.Every participant is a Switch client, so the mxid resolves to a Client- and from there to an Agent, an ExternalUser, or the admin client- (the platform). None means none of those, which a restricted agent- should not trust.+ and from there to an Agent, an ExternalUser, a gateway user's member+ client, or the admin client (the platform). None means none of those,+ which a restricted agent should not trust.++ A member client is that gateway user speaking in person, so it+ resolves to them directly: `user_ids` is that one user, with no+ platform claims involved.`content` matters only for the admin client: its platform marker mayname the person the message speaks for. The marker is read for no@@ -417,6 +422,8 @@ class AddressingResolver:session, external_user.id)return SenderPrincipal("user", external_user.id, claimants, None)+ if client.type == MEMBER_CLIENT_TYPE and client.user_id is not None:+ return SenderPrincipal("user", client.id, [client.user_id], None)if client.type == "admin":person = platform_on_behalf_of(content or {})if person is not None and person.agent_id is not None:diff --git a/core/switch_core/feature_flags.py b/core/switch_core/feature_flags.pyindex b382b3668..3a4422efc 100644--- a/core/switch_core/feature_flags.py+++ b/core/switch_core/feature_flags.py@@ -43,6 +43,12 @@ AGENT_MANAGEMENT = "agent_management"# connect routes stay.SERVICE_CONNECTIONS = "service_connections"+# Agent chats in Switch Console: an agent's page opens on its chats (its+# direct chats and the rooms it is in) beside the conversation. Core puts an+# agent's owner back in each chat they started that holds the agent; with it+# off, owning an agent gives no room membership.+AGENT_CHATS = "agent_chats"+# Every flag the server recognises.KNOWN_FEATURE_FLAGS: frozenset[str] = frozenset({@@ -51,5 +57,6 @@ KNOWN_FEATURE_FLAGS: frozenset[str] = frozenset(HOSTED_AGENTS,AGENT_MANAGEMENT,SERVICE_CONNECTIONS,+ AGENT_CHATS,})diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 8c95980cf..84b46efcd 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -17,6 +17,7 @@ from switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)from switch_core.bridges.resource.service import ResourceService+from switch_core.chats.service import ChatError, ChatServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.connections.adapters.github import load_github_app@@ -38,6 +39,8 @@ from switch_core.gateway.agent_sessions import router as agent_sessions_routerfrom switch_core.gateway.agents import router as agents_routerfrom switch_core.gateway.api_keys import router as api_keys_routerfrom switch_core.gateway.auth_routes import router as auth_router+from switch_core.gateway.chats import chat_error_response+from switch_core.gateway.chats import router as chats_routerfrom switch_core.gateway.collaborations import router as collaborations_routerfrom switch_core.gateway.connection_catalog import router as connection_catalog_routerfrom switch_core.gateway.connectors import router as connectors_router@@ -101,6 +104,7 @@ def create_gateway_app(protocol: AgentCore,install_service: MessagingInstallService | None,invite_mailer: InviteMailer | None,+ chat_service: ChatService,config: SwitchConfig,) -> FastAPI:init_dependencies(@@ -131,6 +135,7 @@ def create_gateway_app()app = FastAPI(title="Switch Gateway API")+ app.state.chat_service = chat_serviceapp.state.hosted_controller_settings = (HostedControllerSettings.model_validate_json(Path(config.hosted_controller_config_path).read_text()@@ -176,6 +181,7 @@ def create_gateway_app(register_oidc_client(config)app.add_exception_handler(SessionError, session_error_response)+ app.add_exception_handler(ChatError, chat_error_response)app.include_router(agent_sessions_router, prefix="/agent-sessions", tags=["session activity"])@@ -183,6 +189,7 @@ def create_gateway_app(app.include_router(oidc_router, tags=["auth"])app.include_router(tenants_router, tags=["tenants"])app.include_router(rooms_router, prefix="/rooms", tags=["rooms"])+ app.include_router(chats_router, prefix="/chats", tags=["chats"])app.include_router(room_groups_router, prefix="/room-groups", tags=["room-groups"])app.include_router(agents_router, prefix="/agents", tags=["agents"])app.include_router(diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.pynew file mode 100644index 000000000..7d0edf4a4--- /dev/null+++ b/core/switch_core/gateway/chats.py@@ -0,0 +1,792 @@+"""`/chats`: Switch Console's view of the rooms a person is a member of.++Every route except creating a chat requires the caller's membership of the+room (`ChatService.require_member`); adding a member requires managing it.+With `agent_chats` on, owning an agent in a chat one started keeps one a+member of it (`sync_owned_rooms`), so the list, the event stream and the room+routes bring that up to date first.+Refusals are `ChatError`s, answered as `{"detail": {"code", "message"}}`.+"""++from __future__ import annotations++import asyncio+import json+import logging+import time+from collections.abc import AsyncIterator+from datetime import datetime+from typing import Annotated++from fastapi import (+ APIRouter,+ Depends,+ File,+ Form,+ HTTPException,+ Query,+ Request,+ Response,+ UploadFile,+)+from fastapi.responses import JSONResponse, StreamingResponse+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.chats.service import (+ ChatError,+ ChatService,+ RemovalReason,+ RoomControl,+)+from switch_core.chats.views import (+ CamelModel,+ ChatMember,+ ChatMessage,+ ChatSummary,+ chat_messages,+ chat_summary,+)+from switch_core.db.models import (+ AgentSessionActivityItem,+ Room,+ User,+ require_tenant_id,+)+from switch_core.db.session_scope import tenant_session+from switch_core.gateway.agent_sessions import ApprovalRequestView+from switch_core.gateway.auth import get_current_user+from switch_core.session_activity.listener import Change++logger = logging.getLogger(__name__)++router = APIRouter()++PING_SECONDS = 20.0+ACTIVITY_QUEUE_MAX = 256+RECHECK_SECONDS = 30.0+_CATCH_UP_PAGE = 200+# Revisions one activity stream remembers before forgetting them all.+_ACTIVITY_SENT_MAX = 10_000+MAX_PAGE = 200+++def get_chat_service(request: Request) -> ChatService:+ return request.app.state.chat_service # type: ignore[no-any-return]+++async def chat_error_response(_request: Request, exc: Exception) -> JSONResponse:+ assert isinstance(exc, ChatError)+ return JSONResponse(+ status_code=exc.status,+ content={"detail": {"code": exc.code, "message": exc.message}},+ )+++class ChatList(CamelModel):+ chats: list[ChatSummary]+++class ChatEnvelope(CamelModel):+ chat: ChatSummary+++class CreateChatRequest(CamelModel):+ """`agentIds` names the chat's agents; `agentId` is the one-agent form+ earlier clients send. Exactly one of the two is given."""++ agent_id: str | None = None+ agent_ids: list[str] | None = None+ name: str | None = None+ request_id: str++ def chosen_agents(self) -> list[str]:+ if (self.agent_id is None) == (self.agent_ids is None):+ raise ChatError(+ 422,+ "AGENTS_REQUIRED",+ "Name the chat's agents in agentIds, or one in agentId; not both.",+ )+ ids = [self.agent_id] if self.agent_id is not None else self.agent_ids or []+ return list(dict.fromkeys(ids))+++class MessagePage(CamelModel):+ messages: list[ChatMessage]+ head_seq: int+ has_more: bool+++class SendRequest(CamelModel):+ request_id: str+ body: str+ thread_root_id: str | None = None+ upload_ids: list[str] = []+ mention_agent_id: str | None = None+++class ControlRequest(CamelModel):+ request_id: str+ agent_id: str+ command: RoomControl+++class ControlAccepted(CamelModel):+ """The command is posted, not done: the agent answers it in the room,+ in a thread rooted at `commandId`."""++ command_id: str+++class SentMessages(CamelModel):+ messages: list[ChatMessage]+++class StagedUploadResponse(CamelModel):+ upload_id: str+ uri: str+ filename: str+ mimetype: str+ size: int+++class MemberList(CamelModel):+ members: list[ChatMember]+++class AddMemberRequest(CamelModel):+ user_id: str+++class ActivityItemView(CamelModel):+ """One step of a turn; `revision` only grows, so a lower one is stale."""++ agent_id: str+ session_id: str+ turn_id: str+ item_id: str+ kind: str+ revision: int+ status: str+ title: str+ text: str+ command_id: str | None+ room_id: str | None+ thread_id: str | None+ message_id: str | None+ occurred_at: datetime+ created_at: datetime+ updated_at: datetime++ @classmethod+ def of(cls, row: AgentSessionActivityItem) -> ActivityItemView:+ return cls(+ agent_id=row.agent_id,+ session_id=row.session_id,+ turn_id=row.turn_id,+ item_id=row.item_id,+ kind=row.kind,+ revision=row.revision,+ status=row.status,+ title=row.title,+ text=row.text,+ command_id=row.command_id,+ room_id=row.room_id,+ thread_id=row.thread_id,+ message_id=row.message_id,+ occurred_at=row.occurred_at,+ created_at=row.created_at,+ updated_at=row.updated_at,+ )+++class RoomActivity(CamelModel):+ items: list[ActivityItemView]+ approvals: list[ApprovalRequestView]+++Service = Annotated[ChatService, Depends(get_chat_service)]+CurrentUser = Annotated[User, Depends(get_current_user)]+++async def _summary(+ service: ChatService, session: AsyncSession, tenant_id: str, user: User, room: Room+) -> ChatSummary:+ return await chat_summary(+ session,+ room,+ viewer_id=user.id,+ can_manage=await service.can_manage(session, tenant_id, user, room),+ )+++async def _member_list(+ service: ChatService, session: AsyncSession, room: Room+) -> MemberList:+ return MemberList(+ members=[+ ChatMember(user_id=member.id, name=member.name, is_owner=is_owner)+ for member, is_owner in await service.members(session, room)+ ]+ )++[email protected]("", response_model=ChatList)+async def list_chats(user: CurrentUser, service: Service) -> ChatList:+ tenant_id = require_tenant_id()+ await service.sync_owned_rooms(tenant_id, user.id)+ async with tenant_session(service.session_factory, tenant_id) as session:+ if not await service.has_tenant_role(session, tenant_id, user.id):+ return ChatList(chats=[])+ rooms = await service.list_chats(session, user.id)+ return ChatList(+ chats=[+ await _summary(service, session, tenant_id, user, room)+ for room in rooms+ ]+ )++[email protected]("", response_model=ChatEnvelope)+async def create_chat(+ req: CreateChatRequest, user: CurrentUser, service: Service+) -> ChatEnvelope:+ tenant_id = require_tenant_id()+ room = await service.create_chat(+ tenant_id,+ user,+ agent_ids=req.chosen_agents(),+ name=req.name,+ request_id=req.request_id,+ )+ async with tenant_session(service.session_factory, tenant_id) as session:+ return ChatEnvelope(+ chat=await _summary(service, session, tenant_id, user, room)+ )++[email protected]("/events")+async def chat_events_stream(+ user: CurrentUser,+ service: Service,+ after: Annotated[str | None, Query()] = None,+) -> StreamingResponse:+ tenant_id = require_tenant_id()+ return StreamingResponse(+ chat_events(+ service,+ tenant_id,+ user,+ parse_after(after),+ ping_seconds=PING_SECONDS,+ recheck_seconds=RECHECK_SECONDS,+ ),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},+ )++[email protected]("/activity/events")+async def chat_activity_stream(+ user: CurrentUser, service: Service+) -> StreamingResponse:+ tenant_id = require_tenant_id()+ return StreamingResponse(+ chat_activity_events(+ service,+ tenant_id,+ user,+ ping_seconds=PING_SECONDS,+ queue_max=ACTIVITY_QUEUE_MAX,+ ),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},+ )++[email protected]("/{room_id}/activity", response_model=RoomActivity)+async def room_activity(+ room_id: str, user: CurrentUser, service: Service+) -> RoomActivity:+ tenant_id = require_tenant_id()+ async with tenant_session(service.session_factory, tenant_id) as session:+ room, _ = await service.require_member(session, tenant_id, user, room_id)+ items, approvals = await service.room_activity(session, room.id)+ return RoomActivity(+ items=[ActivityItemView.of(row) for row in items],+ approvals=[ApprovalRequestView.of(row) for row in approvals],+ )++[email protected]("/{room_id}/messages", response_model=MessagePage)+async def list_messages(+ room_id: str,+ user: CurrentUser,+ service: Service,+ before_seq: Annotated[int | None, Query(alias="beforeSeq")] = None,+ limit: Annotated[int, Query(ge=1, le=MAX_PAGE)] = 50,+) -> MessagePage:+ tenant_id = require_tenant_id()+ async with tenant_session(service.session_factory, tenant_id) as session:+ room, _ = await service.require_member(session, tenant_id, user, room_id)+ rows, head_seq, has_more = await service.page(+ session, room.id, before_seq, limit+ )+ return MessagePage(+ messages=await chat_messages(session, room, rows),+ head_seq=head_seq,+ has_more=has_more,+ )++[email protected]("/{room_id}/attachments", response_model=StagedUploadResponse)+async def upload_attachment(+ room_id: str,+ user: CurrentUser,+ service: Service,+ file: Annotated[UploadFile, File()],+ upload_id: Annotated[str, Form(alias="uploadId")],+) -> StagedUploadResponse:+ tenant_id = require_tenant_id()+ staged = await service.stage_upload(+ tenant_id,+ user,+ room_id,+ upload_id=upload_id,+ data=await file.read(),+ filename=file.filename or "attachment",+ mimetype=file.content_type or "application/octet-stream",+ )+ return StagedUploadResponse(+ upload_id=staged.upload_id,+ uri=staged.uri,+ filename=staged.filename,+ mimetype=staged.mimetype,+ size=staged.size,+ )++[email protected]("/{room_id}/messages", response_model=SentMessages)+async def send_message(+ room_id: str, req: SendRequest, user: CurrentUser, service: Service+) -> SentMessages:+ tenant_id = require_tenant_id()+ room, posted = await service.send(+ tenant_id,+ user,+ room_id,+ request_id=req.request_id,+ body=req.body,+ thread_root_id=req.thread_root_id,+ upload_ids=req.upload_ids,+ mention_agent_id=req.mention_agent_id,+ )+ async with tenant_session(service.session_factory, tenant_id) as session:+ return SentMessages(messages=await chat_messages(session, room, posted))++[email protected]("/{room_id}/controls", response_model=ControlAccepted, status_code=202)+async def send_control(+ room_id: str, req: ControlRequest, user: CurrentUser, service: Service+) -> ControlAccepted:+ command_id = await service.control(+ require_tenant_id(),+ user,+ room_id,+ request_id=req.request_id,+ agent_id=req.agent_id,+ command=req.command,+ )+ return ControlAccepted(command_id=command_id)+++class WarmRequest(CamelModel):+ agent_id: str++[email protected]("/{room_id}/warm", status_code=202)+async def warm_agent(+ room_id: str, req: WarmRequest, user: CurrentUser, service: Service+) -> Response:+ await service.warm(require_tenant_id(), user, room_id, agent_id=req.agent_id)+ return Response(status_code=202)++[email protected]("/{room_id}/media")+async def get_media(+ room_id: str,+ user: CurrentUser,+ service: Service,+ uri: Annotated[str, Query()],+) -> Response:+ tenant_id = require_tenant_id()+ async with tenant_session(service.session_factory, tenant_id) as session:+ room, _ = await service.require_member(session, tenant_id, user, room_id)+ blob = await service.media(session, room, uri)+ return Response(+ content=blob.data,+ media_type=blob.content_type or "application/octet-stream",+ headers={"Cache-Control": "private, no-store"},+ )++[email protected]("/{room_id}/members", response_model=MemberList)+async def list_members(room_id: str, user: CurrentUser, service: Service) -> MemberList:+ tenant_id = require_tenant_id()+ async with tenant_session(service.session_factory, tenant_id) as session:+ room, _ = await service.require_member(session, tenant_id, user, room_id)+ return await _member_list(service, session, room)++[email protected]("/{room_id}/members", response_model=MemberList)+async def add_member(+ room_id: str, req: AddMemberRequest, user: CurrentUser, service: Service+) -> MemberList:+ """Manager only, and the one route a non-member may call: a manager may+ add themselves to a room they manage."""+ tenant_id = require_tenant_id()+ room = await service.add_member(tenant_id, user, room_id, req.user_id)+ async with tenant_session(service.session_factory, tenant_id) as session:+ return await _member_list(service, session, room)++[email protected]("/{room_id}/members/{member_user_id}", status_code=204)+async def remove_member(+ room_id: str, member_user_id: str, user: CurrentUser, service: Service+) -> Response:+ await service.remove_member(require_tenant_id(), user, room_id, member_user_id)+ return Response(status_code=204)++[email protected]("/{room_id}/hidden", status_code=204)+async def hide_chat(room_id: str, user: CurrentUser, service: Service) -> Response:+ await service.set_hidden(require_tenant_id(), user, room_id, True)+ return Response(status_code=204)++[email protected]("/{room_id}/hidden", status_code=204)+async def unhide_chat(room_id: str, user: CurrentUser, service: Service) -> Response:+ await service.set_hidden(require_tenant_id(), user, room_id, False)+ return Response(status_code=204)++[email protected]("/{room_id}/archive", status_code=204)+async def archive_chat(room_id: str, user: CurrentUser, service: Service) -> Response:+ await service.archive(require_tenant_id(), user, room_id)+ return Response(status_code=204)+++# ── Live updates ─────────────────────────────────────────────────────────────+++def parse_after(raw: str | None) -> dict[str, int]:+ """`roomId:seq,roomId:seq` → `{roomId: seq}`."""+ cursors: dict[str, int] = {}+ for item in (raw or "").split(","):+ if not item:+ continue+ room_id, sep, seq = item.rpartition(":")+ if not sep or not room_id:+ raise HTTPException(422, f"Malformed cursor: {item!r}")+ try:+ cursors[room_id] = int(seq)+ except ValueError as exc:+ raise HTTPException(422, f"Malformed cursor: {item!r}") from exc+ return cursors+++def _frame(event: str, data: object) -> bytes:+ return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()+++def _removed(room_id: str, reason: RemovalReason) -> bytes:+ """`chat.removed`: "access" when the caller lost the room (membership,+ tenant role, archive), "unlisted" when they are still a member but it no+ longer qualifies for the list."""+ return _frame("chat.removed", {"roomId": room_id, "reason": reason})+++class _ChatStream:+ """One caller's live view of their chats.++ Every wake-up re-reads what the caller may see before reading anything+ else, so a removal from a room or from the tenant ends that room's events+ at once. Database sessions are opened per pass and closed before waiting.+ """++ def __init__(+ self, service: ChatService, tenant_id: str, user: User, after: dict[str, int]+ ) -> None:+ self.service = service+ self.tenant_id = tenant_id+ self.user = user+ self.after = after+ self.cursors: dict[str, int] = {}+ self.announced: set[str] = set()+ self.dirty: set[str] = set()+ self.wake = asyncio.Event()++ async def on_room(self, room_id: str) -> None:+ self.dirty.add(room_id)+ self.wake.set()++ def on_memberships(self) -> None:+ self.wake.set()++ def close(self) -> None:+ for room_id in self.cursors:+ self.service.listener.unsubscribe(room_id, self.on_room)+ self.cursors.clear()++ def _untrack(self, room_id: str, reason: RemovalReason) -> bytes:+ self.service.listener.unsubscribe(room_id, self.on_room)+ self.cursors.pop(room_id, None)+ return _removed(room_id, reason)++ async def refresh(+ self, read: set[str] | None, initial: bool+ ) -> tuple[list[bytes], bool]:+ """Frames for what changed, and whether the stream may continue.++ `read` names the rooms to read new messages from; None reads all,+ and first brings the caller's agent-owner memberships up to date.+ """+ frames: list[bytes] = []+ service = self.service+ if 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:+ if not await service.has_tenant_role(session, self.tenant_id, self.user.id):+ frames.extend(+ self._untrack(room_id, "access") for room_id in list(self.cursors)+ )+ frames.extend(+ _removed(room_id, "access") for room_id in self.after if initial+ )+ return frames, False+ readable = {+ room.id: room+ for room in await service.readable_rooms(session, self.user.id)+ }+ listed = {+ room.id: room+ for room in await service.stream_rooms(session, self.user.id)+ }+ for room_id in [r for r in self.cursors if r not in readable]:+ frames.append(self._untrack(room_id, "access"))+ if initial:+ for room_id in self.after:+ if room_id not in readable:+ frames.append(_removed(room_id, "access"))+ elif room_id not in listed:+ frames.append(_removed(room_id, "unlisted"))+ for room_id in [+ r for r in self.announced if r in readable and r not in listed+ ]:+ frames.append(_removed(room_id, "unlisted"))+ self.announced.discard(room_id)+ for room_id, room in readable.items():+ if room_id in self.cursors:+ continue+ if initial and room_id in self.after:+ self.cursors[room_id] = self.after[room_id]+ 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)))+ 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)+ 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 _read(self, session: AsyncSession, room: Room) -> list[bytes]:+ frames: list[bytes] = []+ while True:+ rows = await self.service.messages_after(+ session, room.id, self.cursors[room.id], _CATCH_UP_PAGE+ )+ if not rows:+ return frames+ self.cursors[room.id] = rows[-1].seq+ frames.extend(+ _frame("message", message.model_dump(by_alias=True))+ for message in await chat_messages(session, room, rows)+ )+ if len(rows) < _CATCH_UP_PAGE:+ return frames+++async def chat_events(+ service: ChatService,+ tenant_id: str,+ user: User,+ after: dict[str, int],+ *,+ ping_seconds: float,+ recheck_seconds: float,+) -> AsyncIterator[bytes]:+ """The caller's chat events as SSE frames.++ Catches every member room up from its cursor in `after`, says `ready`,+ then pushes as rooms move. A room the caller joined since is announced as+ `chat` and followed from its head; one that leaves the list is `chat.removed`. A+ re-read every `recheck_seconds` recovers anything a missed notification+ or another process's membership change left behind.+ """+ stream = _ChatStream(service, tenant_id, user, after)+ service.watch_memberships(tenant_id, user.id, stream.on_memberships)+ try:+ frames, alive = await stream.refresh(None, initial=True)+ for frame in frames:+ yield frame+ if not alive:+ return+ yield _frame("ready", {})+ now = time.monotonic()+ next_ping = now + ping_seconds+ next_recheck = now + recheck_seconds+ while True:+ timeout = max(0.0, min(next_ping, next_recheck) - time.monotonic())+ try:+ await asyncio.wait_for(stream.wake.wait(), timeout=timeout)+ except TimeoutError:+ pass+ now = time.monotonic()+ if now >= next_ping:+ next_ping = now + ping_seconds+ yield b": ping\n\n"+ read: set[str] | None+ if now >= next_recheck:+ next_recheck = now + recheck_seconds+ read = None+ elif stream.wake.is_set():+ read = set(stream.dirty)+ else:+ continue+ stream.wake.clear()+ stream.dirty.clear()+ frames, alive = await stream.refresh(read, initial=False)+ for frame in frames:+ yield frame+ if not alive:+ return+ finally:+ service.unwatch_memberships(tenant_id, user.id, stream.on_memberships)+ stream.close()+++async def chat_activity_events(+ service: ChatService,+ tenant_id: str,+ user: User,+ *,+ ping_seconds: float,+ queue_max: int,+) -> AsyncIterator[bytes]:+ """Turn steps and approval requests of the rooms the caller may read, as SSE.++ Says `ready` once subscribed, so a snapshot fetched after it misses+ nothing. Readability is checked on every change, so leaving a room stops+ its frames at once. `resync` means changes may have been missed (the+ listener reconnected, or this connection fell behind): reload snapshots.+ """+ queue: asyncio.Queue[Change | None] = asyncio.Queue(maxsize=queue_max)++ def resync() -> None:+ while not queue.empty():+ queue.get_nowait()+ queue.put_nowait(None)++ async def on_change(change: Change) -> None:+ try:+ queue.put_nowait(change)+ except asyncio.QueueFull:+ resync()++ async def on_resync() -> None:+ resync()++ unsubscribe = service.activity_listener.subscribe(tenant_id, on_change, on_resync)+ # Per-connection, so a turn reread on every change resends only moved steps.+ sent: dict[tuple[str, str, str, str], int] = {}+ try:+ await service.sync_owned_rooms(tenant_id, user.id)+ yield _frame("ready", {})+ while True:+ try:+ change = await asyncio.wait_for(queue.get(), timeout=ping_seconds)+ except TimeoutError:+ async with tenant_session(+ service.session_factory, tenant_id+ ) as session:+ if not await service.has_tenant_role(session, tenant_id, user.id):+ return+ yield b": ping\n\n"+ continue+ if change is None:+ sent.clear()+ yield _frame("resync", {})+ continue+ if len(sent) > _ACTIVITY_SENT_MAX:+ # Forgetting only resends steps the client already holds.+ sent.clear()+ frames = await _activity_frames(service, tenant_id, user, change, sent)+ if frames is None:+ return+ for frame in frames:+ yield frame+ finally:+ unsubscribe()+++async def _activity_frames(+ service: ChatService,+ tenant_id: str,+ user: User,+ change: Change,+ sent: dict[tuple[str, str, str, str], int],+) -> list[bytes] | None:+ """Frames for one change, limited to the rooms the caller may read now;+ None once the caller has no tenant role, which ends the stream."""+ async with tenant_session(service.session_factory, tenant_id) as session:+ if not await service.has_tenant_role(session, tenant_id, user.id):+ return None+ readable = {room.id for room in await service.readable_rooms(session, user.id)}+ if not readable:+ return []+ if change.kind == "activity":+ rows = await service.turn_items(+ session, change.agent_id, change.session_id, change.key+ )+ frames = []+ for row in rows:+ key = (row.agent_id, row.session_id, row.turn_id, row.item_id)+ if row.room_id in readable and sent.get(key, -1) < row.revision:+ sent[key] = row.revision+ view = ActivityItemView.of(row)+ frames.append(+ _frame("activity", view.model_dump(mode="json", by_alias=True))+ )+ return frames+ request = await service.approval(+ session, change.agent_id, change.session_id, change.key+ )+ if request is None or request.room_id not in readable:+ return []+ approval = ApprovalRequestView.of(request)+ return [_frame("approval", approval.model_dump(mode="json", by_alias=True))]diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 34ce0b4cf..5e7b5c7cd 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -90,6 +90,7 @@ from switch_core.bridges.collaboration.webhooks import (create_bridge_webhook_router,)from switch_core.bridges.resource.service import ResourceService+from switch_core.chats.service import ChatServicefrom switch_core.clients.actor import Actor, AgentActor, HumanActor, SystemActorfrom switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.client_factory import ClientFactory@@ -879,6 +880,26 @@ async def run(config: SwitchConfig) -> None:keyring=config.keyring,)+ chat_service = ChatService(+ session_factory=session_factory,+ room_service=room_service,+ provisioning=provisioning,+ listener=message_listener,+ activity_listener=session_activity_listener,+ room_store=room_store,+ agent_store=agent_store,+ user_store=user_store,+ message_store=message_store,+ media_store=media_store,+ usage_store=usage_store,+ id_server_name=config.id_server_name,+ media_max_bytes=config.agent_media_max_bytes,+ agent_chats_enabled=config.agent_chats_enabled,+ controllers=connections.controllers,+ )+ room_service.on_room_agents_changed(chat_service.sync_room)+ protocol.set_room_agents_listener(room_service.room_agents_changed)+# ── Gateway app ───────────────────────────────────────────────────────────gateway_app = create_gateway_app(agent_store=agent_store,@@ -908,6 +929,7 @@ async def run(config: SwitchConfig) -> None:if config.invite_email_enabledelse None),+ chat_service=chat_service,config=config,)diff --git a/core/switch_core/messages/row.py b/core/switch_core/messages/row.pyindex 4252a9d9d..6e287be0b 100644--- a/core/switch_core/messages/row.py+++ b/core/switch_core/messages/row.py@@ -8,7 +8,9 @@ the same event stored twice would be two different rows.from __future__ import annotations-from switch_core.db.models import MessageAttachment+import uuid++from switch_core.db.models import Message, MessageAttachmentdef text_field(value: object) -> str | None:@@ -46,3 +48,46 @@ def attachments_in(content: dict[str, object]) -> list[MessageAttachment]:position=0,)]+++def new_event_id() -> str:+ """A fresh event id.++ Prefixed so that a row's origin is readable at a glance during the window+ where a room holds both these and ids minted by the old bus. The prefix is+ decoration for humans — no code may branch on it.+ """+ return f"sw_{uuid.uuid4().hex}"+++def message_row(+ *,+ room_id: str,+ event_id: str,+ sender_id: str,+ sender_client_id: str,+ sender_name: str,+ event_type: str,+ content: dict[str, object],+ client_txn_id: str | None,+) -> Message:+ """The `messages` row that sending `content` writes.++ Shared by every writer of the table, so a message sent through a transport+ and one a gateway route writes for a person in a single transaction are+ the same row.+ """+ return Message(+ room_id=room_id,+ transport_event_id=event_id,+ sender_id=sender_id,+ sender_client_id=sender_client_id,+ sender_name=sender_name,+ event_type=event_type,+ msgtype=text_field(content.get("msgtype")),+ body=text_field(content.get("body")),+ formatted_body=text_field(content.get("formatted_body")),+ thread_root_event_id=thread_root_of(content),+ content=content,+ client_txn_id=client_txn_id,+ )diff --git a/core/switch_core/migrations/versions/b3c7e1d9f2a5_chat_operation_control_kind.py b/core/switch_core/migrations/versions/b3c7e1d9f2a5_chat_operation_control_kind.pynew file mode 100644index 000000000..d406e2467--- /dev/null+++ b/core/switch_core/migrations/versions/b3c7e1d9f2a5_chat_operation_control_kind.py@@ -0,0 +1,34 @@+"""chat operations: a `control` kind for room commands posted from a chat++Revision ID: b3c7e1d9f2a5+Revises: e2a6c9f1b7d4+Create Date: 2026-10-14 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "b3c7e1d9f2a5"+down_revision: str | Sequence[str] | None = "e2a6c9f1b7d4"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++TABLE = "chat_operations"+CONSTRAINT = "ck_chat_operations_kind"+++def upgrade() -> None:+ op.drop_constraint(CONSTRAINT, TABLE, type_="check")+ op.create_check_constraint(+ CONSTRAINT, TABLE, "kind IN ('create_chat', 'send', 'upload', 'control')"+ )+++def downgrade() -> None:+ op.execute(f"DELETE FROM {TABLE} WHERE kind = 'control'")+ op.drop_constraint(CONSTRAINT, TABLE, type_="check")+ op.create_check_constraint(+ CONSTRAINT, TABLE, "kind IN ('create_chat', 'send', 'upload')"+ )diff --git a/core/switch_core/migrations/versions/d8b4f2a6c1e9_chats.py b/core/switch_core/migrations/versions/d8b4f2a6c1e9_chats.pynew file mode 100644index 000000000..0b3ada3dd--- /dev/null+++ b/core/switch_core/migrations/versions/d8b4f2a6c1e9_chats.py@@ -0,0 +1,157 @@+"""chats: member clients, retryable chat operations, per-person hidden chats++- `clients.user_id`: the gateway user a `member` client speaks for, one per+ user per tenant.+- `messages.client_txn_id`: a Switch Console sender's key for one part of a+ send, unique per sending client, so a retried send cannot post twice.+- `chat_operations`: a person's retryable requests (create a chat, send,+ upload), keyed by their request id.+- `chat_hidden`: chats a person took off their own list.++The row-level-security DDL is a verbatim copy of `switch_core/db/rls_ddl.py`+as it stood when this migration was written, copied rather than imported for+the reason `265ed188ad6f` gives.++Revision ID: d8b4f2a6c1e9+Revises: a7e3c1d9f204+Create Date: 2026-10-08 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "d8b4f2a6c1e9"+down_revision: str | Sequence[str] | None = "a7e3c1d9f204"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"++TABLES = ("chat_operations", "chat_hidden")++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+++def _create_policy(table: str) -> str:+ return (+ f'CREATE POLICY {POLICY_NAME} ON "{table}"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+ )+++def _timestamp(name: str) -> sa.Column:+ return sa.Column(+ name,+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ )+++def upgrade() -> None:+ op.add_column("clients", sa.Column("user_id", sa.Text(), nullable=True))+ op.create_foreign_key(+ "fk_clients_user",+ "clients",+ "users",+ ["user_id"],+ ["id"],+ ondelete="SET NULL",+ )+ op.create_unique_constraint(+ "uq_clients_tenant_user_id", "clients", ["tenant_id", "user_id"]+ )++ op.add_column("messages", sa.Column("client_txn_id", sa.Text(), nullable=True))+ op.create_index(+ "uq_messages_sender_client_txn",+ "messages",+ ["sender_client_id", "client_txn_id"],+ unique=True,+ postgresql_where=sa.text("client_txn_id IS NOT NULL"),+ )++ op.create_table(+ "chat_operations",+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("user_id", sa.Text(), nullable=False),+ sa.Column("request_id", sa.Text(), nullable=False),+ sa.Column("kind", sa.Text(), nullable=False),+ sa.Column("payload_hash", sa.Text(), nullable=False),+ sa.Column("state", sa.Text(), nullable=False),+ sa.Column("room_id", sa.Text(), nullable=True),+ sa.Column("result", postgresql.JSONB(), nullable=True),+ _timestamp("created_at"),+ _timestamp("updated_at"),+ sa.PrimaryKeyConstraint("tenant_id", "user_id", "request_id"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_chat_operations_tenant"+ ),+ sa.ForeignKeyConstraint(+ ["user_id"],+ ["users.id"],+ name="fk_chat_operations_user",+ ondelete="CASCADE",+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_operations_room",+ ondelete="CASCADE",+ ),+ sa.CheckConstraint(+ "kind IN ('create_chat', 'send', 'upload')",+ name="ck_chat_operations_kind",+ ),+ sa.CheckConstraint(+ "state IN ('pending', 'done')", name="ck_chat_operations_state"+ ),+ )++ op.create_table(+ "chat_hidden",+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("user_id", sa.Text(), nullable=False),+ sa.Column("room_id", sa.Text(), nullable=False),+ sa.Column("hidden_through_seq", sa.BigInteger(), nullable=False),+ _timestamp("created_at"),+ sa.PrimaryKeyConstraint("tenant_id", "user_id", "room_id"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_chat_hidden_tenant"+ ),+ sa.ForeignKeyConstraint(+ ["user_id"],+ ["users.id"],+ name="fk_chat_hidden_user",+ ondelete="CASCADE",+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_hidden_room",+ ondelete="CASCADE",+ ),+ )++ for table in TABLES:+ op.execute(f'ALTER TABLE "{table}" ENABLE ROW LEVEL SECURITY')+ op.execute(_create_policy(table))+++def downgrade() -> None:+ for table in reversed(TABLES):+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{table}"')+ op.drop_table("chat_hidden")+ op.drop_table("chat_operations")+ op.drop_index("uq_messages_sender_client_txn", table_name="messages")+ op.drop_column("messages", "client_txn_id")+ op.drop_constraint("uq_clients_tenant_user_id", "clients", type_="unique")+ op.drop_constraint("fk_clients_user", "clients", type_="foreignkey")+ op.drop_column("clients", "user_id")diff --git a/core/switch_core/migrations/versions/e2a6c9f1b7d4_chat_owner_grants.py b/core/switch_core/migrations/versions/e2a6c9f1b7d4_chat_owner_grants.pynew file mode 100644index 000000000..d4446ce1a--- /dev/null+++ b/core/switch_core/migrations/versions/e2a6c9f1b7d4_chat_owner_grants.py@@ -0,0 +1,75 @@+"""chat owner grants: memberships held only through owning an agent in the room++With the `agent_chats` feature flag on, a person is put as a chat member in+each chat they started through the chats API that holds an agent they own.+This table marks the memberships that exist for that reason alone, so they+can be taken back once that no longer holds, or once the flag is off.++The row-level-security DDL is a verbatim copy of `switch_core/db/rls_ddl.py`+as it stood when this migration was written, copied rather than imported for+the reason `265ed188ad6f` gives.++Revision ID: e2a6c9f1b7d4+Revises: d8b4f2a6c1e9+Create Date: 2026-10-09 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "e2a6c9f1b7d4"+down_revision: str | Sequence[str] | None = "d8b4f2a6c1e9"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"+TABLE = "chat_owner_grants"++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+++def upgrade() -> None:+ op.create_table(+ TABLE,+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("user_id", sa.Text(), nullable=False),+ sa.Column("room_id", sa.Text(), nullable=False),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.PrimaryKeyConstraint("tenant_id", "user_id", "room_id"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_chat_owner_grants_tenant"+ ),+ sa.ForeignKeyConstraint(+ ["user_id"],+ ["users.id"],+ name="fk_chat_owner_grants_user",+ ondelete="CASCADE",+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id", "room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_chat_owner_grants_room",+ ondelete="CASCADE",+ ),+ )+ op.execute(f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY')+ op.execute(+ f'CREATE POLICY {POLICY_NAME} ON "{TABLE}"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+ )+++def downgrade() -> None:+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"')+ op.drop_table(TABLE)diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex a0ee2d0d3..7fafe7f3a 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -16,6 +16,7 @@ room Switch has no record of it being in.from __future__ import annotationsimport logging+from collections.abc import Awaitable, Callablefrom typing import TYPE_CHECKING, Any, Literalfrom pydantic import BaseModel@@ -135,6 +136,9 @@ class RoomCreateConfig(BaseModel):created_by_kind: Literal["user", "agent", "system"] = "user"# Provisioned from a room template rather than created directly.from_template: bool = False+ # The Switch Console chat creation this room is for, stamped into the+ # room's metadata in the same insert so a retried creation finds it.+ chat_operation_id: str | None = Noneclass RoomCreateResult(BaseModel):@@ -151,11 +155,12 @@ class RoomCreateResult(BaseModel):class RoomService:- # Class-level default so a caller that builds this without `__init__` —+ # Class-level defaults so a caller that builds this without `__init__` —# several tests assemble a minimal instance directly — still has the- # attribute. Telemetry is genuinely optional here; `emit_safely` treats+ # attributes. Telemetry is genuinely optional here; `emit_safely` treats# None as "report nothing"._telemetry: TelemetryService | None = None+ _room_agents_listeners: tuple[Callable[[str, str], Awaitable[None]], ...] = ()def __init__(self,@@ -185,6 +190,28 @@ class RoomService:# The shared delivery read; told when a room goes.self._room_cache = room_cache+ def on_room_agents_changed(+ self, listener: Callable[[str, str], Awaitable[None]]+ ) -> None:+ """Call `listener(tenant_id, room_id)` after a room's agents change."""+ self._room_agents_listeners = (*self._room_agents_listeners, listener)++ async def room_agents_changed(self, tenant_id: str, room_id: str) -> None:+ """Tell the listeners a room's agents (or their owners) changed.++ The change itself is already committed, so a listener that fails is+ reported rather than raised; listeners re-read on their own schedule.+ """+ for listener in self._room_agents_listeners:+ try:+ await listener(tenant_id, room_id)+ except Exception:+ logger.exception(+ "Room-agents listener failed for room %s; it will catch up "+ "on its next re-read",+ room_id,+ )+async def _resolve_agent_ids(self, config: RoomCreateConfig) -> list[str]:if config.agent_ids is not None:agent_ids = list(config.agent_ids)@@ -599,7 +626,14 @@ class RoomService:read_visibility=config.read_visibility,write_visibility=config.write_visibility,# Nothing else on the row can answer this afterwards.- metadata_={"created_by_kind": config.created_by_kind},+ metadata_={+ "created_by_kind": config.created_by_kind,+ **(+ {"chat_operation_id": config.chat_operation_id}+ if config.chat_operation_id is not None+ else {}+ ),+ },)async with self._session_factory() as session:@@ -735,6 +769,9 @@ class RoomService:len(system_clients),)+ if agent_ids:+ await self.room_agents_changed(room.tenant_id, room.id)+failed_attachments = unreachable_users + await self._attach_after_creation(room.id, config)@@ -924,6 +961,7 @@ class RoomService:)logger.info("Added %d agents to room %s", len(agent_ids), room_id)+ await self.room_agents_changed(room.tenant_id, room.id)emit_safely(self._telemetry,@@ -965,6 +1003,7 @@ class RoomService:)logger.info("Removed %d agents from room %s", len(agent_ids), room_id)+ await self.room_agents_changed(room.tenant_id, room.id)emit_safely(self._telemetry,@@ -1503,6 +1542,14 @@ class RoomService:", ".join(failures),)+ async def reconcile_room(self, room: Room) -> None:+ """Put the room's agent and system clients in it where they are missing.++ For a caller repairing one room whose creation may have stopped after+ the room row committed and before its clients joined.+ """+ await self._reconcile_one_room(room)+async def _reconcile_one_room(self, room: Room) -> None:with tenant_scope(room.tenant_id):async with self._session_factory() as session:diff --git a/core/switch_core/sessions/contract.py b/core/switch_core/sessions/contract.pyindex 9ca6b0375..fd3fc9ea7 100644--- a/core/switch_core/sessions/contract.py+++ b/core/switch_core/sessions/contract.py@@ -198,6 +198,12 @@ class SessionModel(_Model):options: dict[str, str]+class SessionContext(_Model):+ used_tokens: int = Field(ge=0)+ window_tokens: int | None = Field(gt=0)+ updated_at: Timestamp++class ModelChoice(_Model):id: Idlabel: str@@ -219,6 +225,7 @@ class Session(_Model):pending_request_ids: list[Id]models: list[ModelChoice] = Field(default_factory=list)model: SessionModel | None = None+ context: SessionContext | None = None# ── Event bodies ─────────────────────────────────────────────────────────────diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex 2fcfd671a..417e989ff 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -46,7 +46,12 @@ from switch_core.db.models import (from switch_core.db.session_scope import tenant_sessionfrom switch_core.logging_context import log_contextfrom switch_core.messages.recorded_types import EPHEMERAL-from switch_core.messages.row import attachments_in, text_field, thread_root_of+from switch_core.messages.row import (+ attachments_in,+ message_row,+ new_event_id,+ thread_root_of,+)from switch_core.observability.catalogue import (DELIVERY_FAILURES,DELIVERY_LAG,@@ -152,16 +157,6 @@ def _age_ms(sent_at: object) -> float | None:MEMBERSHIP_EVENT_TYPE = "m.room.member"-def new_event_id() -> str:- """A fresh event id.-- Prefixed so that a row's origin is readable at a glance during the window- where a room holds both these and ids minted by the old bus. The prefix is- decoration for humans — no code may branch on it.- """- return f"sw_{uuid.uuid4().hex}"--class PostgresTransport:"""Carries a room's events in the `messages` table.@@ -836,18 +831,15 @@ class PostgresTransport:try:room_id, tenant_id = await self._resolve_room_and_tenant(transport_room_id)async with tenant_session(self._session_factory, tenant_id) as session:- message = Message(+ message = message_row(room_id=room_id,- transport_event_id=result.event_id,+ event_id=result.event_id,sender_id=self.user_id,sender_client_id=self.client_id,sender_name=sender_name,event_type=event_type,- msgtype=text_field(content.get("msgtype")),- body=text_field(content.get("body")),- formatted_body=text_field(content.get("formatted_body")),- thread_root_event_id=thread_root_of(content),content=content,+ client_txn_id=None,)await self._message_store.create(session, message, attachments_in(content)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py b/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.pyindex 023637495..8902214d9 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py@@ -15,7 +15,7 @@ import uuidfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.db.models import Room+from switch_core.db.models import Room, require_tenant_idfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.room_store import RoomStorefrom tests.switch_core.bridges.agent.protocol.registration_harness import (@@ -70,8 +70,19 @@ class TestDeleteAgentInARoom:await RoomStore().add_client(session, client_id, room_id)await session.commit()+ told: list[tuple[str, str, list[str]]] = []++ async def room_agents_changed(tenant_id: str, changed_room_id: str) -> None:+ async with session_factory() as session:+ remaining = await RoomStore().get_agent_ids(session, changed_room_id)+ told.append((tenant_id, changed_room_id, remaining))++ svc.set_room_agents_listener(room_agents_changed)await svc.delete_agent(agent_id=agent_id)+ # Told once the agent is gone, so a listener re-reading the room+ # finds it without the agent.+ assert told == [(require_tenant_id(), room_id, [])]assert lifecycle.stopped == [client_id]async with session_factory() as session:assert await svc.agent_store.get(session, agent_id) is Nonediff --git a/core/tests/switch_core/clients/test_member_addressing.py b/core/tests/switch_core/clients/test_member_addressing.pynew file mode 100644index 000000000..43f76a642--- /dev/null+++ b/core/tests/switch_core/clients/test_member_addressing.py@@ -0,0 +1,109 @@+"""A gateway user's member client is that user in person, to every rule that+asks who a sender is: addressing an agent, commanding it (`!reset`,+`!compact`, `!interrupt` are gated on the same decision, asked with no event+content), and answering its requests from a platform.++Real Postgres, real stores: the resolution is a chain of lookups, and a fake+for each link would test the fakes.+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.addressing import owner_only_policy+from switch_core.chats import MEMBER_CLIENT_TYPE+from switch_core.db.models import Client, Room, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.delivery.addressing import (+ ADDRESSING_DENIED_MESSAGE,+ AddressingResolver,+ SenderPrincipal,+)+from tests.switch_core.gateway.agent_route_harness import add_agent+++def _resolver() -> AddressingResolver:+ return AddressingResolver(+ room_store=RoomStore(),+ room_role_store=RoomRoleStore(),+ client_store=ClientStore(),+ agent_store=AgentStore(),+ external_user_store=ExternalUserStore(),+ live_connection_ids=set,+ )+++async def _member(session: AsyncSession, name: str) -> tuple[User, Client]:+ user = User(name=name, email=f"{name}@example.com", role="user")+ session.add(user)+ await session.flush()+ client = Client(+ transport_user_id=f"@switch-member-{user.id}:test",+ display_name=name,+ type=MEMBER_CLIENT_TYPE,+ user_id=user.id,+ )+ session.add(client)+ await session.flush()+ return user, client+++async def test_a_member_client_resolves_to_its_user_with_no_claims(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ user, client = await _member(session, "alice")+ principal = await _resolver().resolve_sender(session, client.transport_user_id)+ assert principal == SenderPrincipal("user", client.id, [user.id], None)+++async def test_a_member_client_whose_user_is_gone_resolves_to_nobody(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ _, client = await _member(session, "alice")+ client.user_id = None+ await session.flush()+ assert (+ await _resolver().resolve_sender(session, client.transport_user_id) is None+ )+++async def test_an_owner_only_agent_admits_its_owner_and_refuses_another_member(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, owner_client = await _member(session, "alice")+ _, other_client = await _member(session, "bob")+ agent = await add_agent(session, name="private", owner_id=owner.id)+ agent.addressing_policy = owner_only_policy([]).model_dump()+ room = Room(transport_room_id="!r:test", name="r", description="")+ session.add(room)+ await session.flush()+ resolver = _resolver()++ for content in ({"body": "@private hi"}, None):+ # With content: a message. Without: a room command, which the+ # agent gates on exactly this decision.+ allowed = await resolver.permitted(+ session,+ agent=agent,+ room_id=room.id,+ sender=owner_client.transport_user_id,+ content=content,+ )+ assert allowed.allowed is True+ refused = await resolver.permitted(+ session,+ agent=agent,+ room_id=room.id,+ sender=other_client.transport_user_id,+ content=content,+ )+ assert refused.allowed is False+ assert refused.refusal == ADDRESSING_DENIED_MESSAGEdiff --git a/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json b/core/tests/switch_core/fixtures/agent_controllers/stream_frames.jsonindex 842a1f0b9..c8c5f30eb 100644--- a/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json+++ b/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json@@ -87,6 +87,13 @@}}},+ {+ "event": "agent.warm",+ "data": {+ "agent_id": "00000000-0000-4000-8000-0000000000a1",+ "room_id": "00000000-0000-4000-8000-0000000000b1"+ }+ },{"event": "agent.approval_outcome","data": {diff --git a/core/tests/switch_core/gateway/conftest.py b/core/tests/switch_core/gateway/conftest.pynew file mode 100644index 000000000..c5672b7eb--- /dev/null+++ b/core/tests/switch_core/gateway/conftest.py@@ -0,0 +1,294 @@+"""The `/chats` harness: real routes, `ChatService`, `RoomService` and+Postgres provisioning, shared by the chats test modules."""++from __future__ import annotations++from collections.abc import AsyncIterator, Awaitable, Callable+from types import SimpleNamespace+from typing import Any+from unittest.mock import MagicMock++import httpx+import pytest+from fastapi import FastAPI, Request+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.chats.service import ChatError, ChatService+from switch_core.db.models import (+ Agent,+ Client,+ Message,+ User,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.media_store import MediaStore+from switch_core.db.stores.message_store import MessageStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.usage_store import UsageStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway.auth import get_current_user+from switch_core.gateway.chats import (+ chat_error_response,+ router,+)+from switch_core.provisioning.postgres import PostgresProvisioning+from switch_core.room_service import RoomService+from switch_core.session_activity.listener import Change+from switch_core.transport.invites import InviteBus+from tests.switch_core.gateway.agent_route_harness import add_agent++_MESSAGE_STORE = MessageStore()+++class _FakeLifecycle:+ """The running-client registry, for agents that have no consumer here."""++ def __init__(self) -> None:+ self.agents: dict[str, SimpleNamespace] = {}++ def get_by_agent_id(self, agent_id: str) -> SimpleNamespace | None:+ return self.agents.get(agent_id)++ def get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:+ return []+++class _FakeListener:+ """Records subscriptions; a test rings a room by hand, or deliberately not."""++ def __init__(self) -> None:+ self.wakers: dict[str, set[Callable[[str], Awaitable[None]]]] = {}++ def subscribe(self, room_id: str, waker: Callable[[str], Awaitable[None]]) -> None:+ self.wakers.setdefault(room_id, set()).add(waker)++ def unsubscribe(+ self, room_id: str, waker: Callable[[str], Awaitable[None]]+ ) -> None:+ self.wakers.get(room_id, set()).discard(waker)++ async def ring(self, room_id: str) -> None:+ for waker in list(self.wakers.get(room_id, ())):+ await waker(room_id)+++class _FakeActivityListener:+ """The session-activity listener; a test delivers changes by hand."""++ def __init__(self) -> None:+ self.subscribers: list[tuple[Any, Any]] = []++ def subscribe(self, tenant_id: str, on_change: Any, on_resync: Any) -> Any:+ entry = (on_change, on_resync)+ self.subscribers.append(entry)+ return lambda: self.subscribers.remove(entry)++ async def change(self, change: Change) -> None:+ for on_change, _ in list(self.subscribers):+ await on_change(change)++ async def resync(self) -> None:+ for _, on_resync in list(self.subscribers):+ await on_resync()+++class _FakeControllers:+ """The controller presence, as far as warming a chat reads it."""++ def __init__(self) -> None:+ self.bound: set[str] = set()+ self.live = True+ self.warms: list[tuple[str, str]] = []++ def is_bound(self, agent_id: str) -> bool:+ return agent_id in self.bound++ def relay_warm(self, agent_id: str, room_id: str) -> bool:+ if not self.live:+ return False+ self.warms.append((agent_id, room_id))+ return True+++class _Harness(SimpleNamespace):+ client: httpx.AsyncClient+ factory: async_sessionmaker[AsyncSession]+ service: ChatService+ room_service: RoomService+ listener: _FakeListener+ activity: _FakeActivityListener+ lifecycle: _FakeLifecycle+ controllers: _FakeControllers+ alice: User+ bob: User+ carol: User+ admin: User++ def as_user(self, user: User) -> dict[str, str]:+ return {"x-user": user.id}++ async def agent(+ self, name: str, *, owner: User, policy: dict | None = None+ ) -> Agent:+ async with self.factory() as session:+ agent = await add_agent(session, name=name, owner_id=owner.id)+ agent.addressing_policy = policy+ client = await session.get(Client, agent.client_id)+ assert client is not None+ self.lifecycle.agents[agent.id] = SimpleNamespace(+ client_id=client.id, transport_user_id=client.transport_user_id+ )+ await session.commit()+ return agent++ async def create_chat(+ self, user: User, agent: Agent, request_id: str, name: str | None = None+ ) -> httpx.Response:+ return await self.client.post(+ "/chats",+ json={"agentId": agent.id, "name": name, "requestId": request_id},+ headers=self.as_user(user),+ )++ async def new_chat(self, user: User, agent: Agent, request_id: str) -> str:+ response = await self.create_chat(user, agent, request_id)+ assert response.status_code == 200, response.text+ return str(response.json()["chat"]["roomId"])++ async def send(+ self, user: User, room_id: str, request_id: str, body: str, **extra: Any+ ) -> httpx.Response:+ return await self.client.post(+ f"/chats/{room_id}/messages",+ json={"requestId": request_id, "body": body, **extra},+ headers=self.as_user(user),+ )++ async def invite(self, manager: User, room_id: str, user: User) -> httpx.Response:+ return await self.client.post(+ f"/chats/{room_id}/members",+ json={"userId": user.id},+ headers=self.as_user(manager),+ )++ async def upload(+ self, user: User, room_id: str, upload_id: str, data: bytes, name: str+ ) -> httpx.Response:+ return await self.client.post(+ f"/chats/{room_id}/attachments",+ data={"uploadId": upload_id},+ files={"file": (name, data, "image/png")},+ headers=self.as_user(user),+ )++ async def message_rows(self, room_id: str) -> list[Message]:+ async with self.factory() as session:+ rows = await session.execute(+ select(Message)+ .where(+ Message.room_id == room_id, Message.event_type == "m.room.message"+ )+ .order_by(Message.seq)+ )+ return list(rows.scalars().all())+++async def _user(session: AsyncSession, name: str, role: str | None) -> User:+ user = User(name=name, email=f"{name}@example.com", role="user")+ session.add(user)+ await session.flush()+ if role is not None:+ await UserStore().add_membership(+ session,+ tenant_id="00000000-0000-0000-0000-000000000000",+ user_id=user.id,+ role=role,+ )+ return user+++async def chats(+ session_factory: async_sessionmaker[AsyncSession],+) -> AsyncIterator[_Harness]:+ async with session_factory() as session:+ alice = await _user(session, "alice", "member")+ bob = await _user(session, "bob", "member")+ carol = await _user(session, "carol", None)+ admin = await _user(session, "admin", "admin")+ await session.commit()++ room_store = RoomStore()+ lifecycle = _FakeLifecycle()+ provisioning = PostgresProvisioning(+ session_factory=session_factory,+ room_store=room_store,+ client_store=ClientStore(),+ message_store=_MESSAGE_STORE,+ invites=InviteBus(),+ )+ room_service = RoomService(+ provisioning=provisioning,+ room_store=room_store,+ agent_store=AgentStore(),+ client_lifecycle=lifecycle, # type: ignore[arg-type]+ collab_lifecycle=None, # type: ignore[arg-type]+ collab_bridge_store=CollaborationBridgeStore(),+ resource_service=None, # type: ignore[arg-type]+ session_factory=session_factory,+ room_cache=MagicMock(),+ )+ listener = _FakeListener()+ activity = _FakeActivityListener()+ controllers = _FakeControllers()+ service = ChatService(+ session_factory=session_factory,+ room_service=room_service,+ provisioning=provisioning,+ listener=listener, # type: ignore[arg-type]+ activity_listener=activity, # type: ignore[arg-type]+ room_store=room_store,+ agent_store=AgentStore(),+ user_store=UserStore(),+ message_store=_MESSAGE_STORE,+ media_store=MediaStore(),+ usage_store=UsageStore(),+ id_server_name="switch.test",+ media_max_bytes=1024,+ agent_chats_enabled=True,+ controllers=controllers, # type: ignore[arg-type]+ )+ room_service.on_room_agents_changed(service.sync_room)++ app = FastAPI()+ app.state.chat_service = service+ app.add_exception_handler(ChatError, chat_error_response)+ app.include_router(router, prefix="/chats")++ async def user_from_header(request: Request) -> User:+ async with session_factory() as session:+ user = await session.get(User, request.headers["x-user"])+ assert user is not None+ return user++ app.dependency_overrides[get_current_user] = user_from_header+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://switch.test"+ ) as client:+ yield _Harness(+ client=client,+ factory=session_factory,+ service=service,+ room_service=room_service,+ listener=listener,+ activity=activity,+ lifecycle=lifecycle,+ controllers=controllers,+ alice=alice,+ bob=bob,+ carol=carol,+ admin=admin,+ )diff --git a/core/tests/switch_core/gateway/test_app_route_mounting.py b/core/tests/switch_core/gateway/test_app_route_mounting.pyindex 082c5e09c..45fe998f8 100644--- a/core/tests/switch_core/gateway/test_app_route_mounting.py+++ b/core/tests/switch_core/gateway/test_app_route_mounting.py@@ -22,6 +22,7 @@ def _app(**overrides: object) -> object:room_store=MagicMock(),room_group_store=MagicMock(),room_service=MagicMock(),+ chat_service=MagicMock(),bridge_store=MagicMock(),client_lifecycle=MagicMock(),collab_lifecycle=MagicMock(),diff --git a/core/tests/switch_core/gateway/test_chats_bridge_integration.py b/core/tests/switch_core/gateway/test_chats_bridge_integration.pynew file mode 100644index 000000000..cf5fa5487--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_bridge_integration.py@@ -0,0 +1,625 @@+"""Console /chats integration with collaboration bridges.++Tests that console member messages relay outbound through bridges, that+threading works both ways, inbound threaded replies arrive correctly, echo+prevention works, and multi-attachment sends are atomic even when the bridge+adapter fails mid-relay.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest+from sqlalchemy import func, select++from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore+from switch_core.bridges.collaboration.models import InboundMessage+from switch_core.clients.consumer import Consumer+from switch_core.db.models import (+ Client,+ CollaborationBridge,+ Message,+ Room,+)+from switch_core.events import CommandEvent+from switch_core.transport import InboundMessage as TransportMessage+from switch_core.transport import RoomRef+from switch_core.transport.stored import to_inbound+from switch_core.trust.client import NullTrustClient+from tests.switch_core.gateway.conftest import _Harness+++class _FakeCollabAdapter(PlatformAdapter):+ """Minimal fake adapter for testing console → bridge outbound relay."""++ def __init__(self) -> None:+ self.sent: list[dict[str, Any]] = []+ self.next_ref_id = 1+ self._should_raise: Exception | None = None++ async def send_message(+ self,+ channel_id: str,+ sender_name: str,+ content: str,+ thread_root_id: str | None = None,+ room_wide_mention: bool = False,+ ) -> str:+ if self._should_raise:+ raise self._should_raise+ ref_id = f"ext-{self.next_ref_id}"+ self.next_ref_id += 1+ self.sent.append(+ {+ "channel_id": channel_id,+ "sender_name": sender_name,+ "content": content,+ "thread_root_id": thread_root_id,+ "room_wide_mention": room_wide_mention,+ }+ )+ return ref_id++ async def send_attachment(+ self,+ channel_id: str,+ sender_name: str,+ filename: str,+ mimetype: str,+ data: bytes,+ caption: str | None = None,+ thread_root_id: str | None = None,+ ) -> str:+ if self._should_raise:+ raise self._should_raise+ ref_id = f"ext-{self.next_ref_id}"+ self.next_ref_id += 1+ self.sent.append(+ {+ "channel_id": channel_id,+ "sender_name": sender_name,+ "filename": filename,+ "mimetype": mimetype,+ "data": data,+ "caption": caption,+ "thread_root_id": thread_root_id,+ }+ )+ return ref_id++ def translate_outbound(self, content: str) -> str:+ return content++ def _render_outbound(self, content: str) -> str:+ return content++ def translate_inbound(self, content: str) -> str:+ return content++ def render_room_wide_mention(self, content: str) -> str:+ return content++ async def start(self) -> None:+ pass++ async def stop(self) -> None:+ pass++ async def create_channel(self, *args: Any, **kwargs: Any) -> Any:+ return None++ async def add_users_to_channel(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def add_agents_to_channel(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def get_channel_type(self, *args: Any, **kwargs: Any) -> Any:+ return None++ async def get_channel_agent_names(self, *args: Any, **kwargs: Any) -> list[str]:+ return []++ async def create_agent_identity(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def remove_agent_identity(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def send_typing(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def update_message(self, *args: Any, **kwargs: Any) -> None:+ pass++ async def delete_message(self, *args: Any, **kwargs: Any) -> None:+ pass+++async def _bridged_room(+ chats: _Harness, agent: Any+) -> tuple[str, CollaborationBridge, _FakeCollabAdapter]:+ """Create a room with the given agent, attach a fake collaboration bridge, return room_id, bridge, adapter."""+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None++ bridge_client = Client(+ transport_user_id=f"@fake-bridge-bot:{agent.id}:switch.test",+ display_name="Fake Bridge Bot",+ type="bridge",+ )+ session.add(bridge_client)+ await session.flush()++ bridge = CollaborationBridge(+ tenant_id=room.tenant_id,+ type="fake",+ display_name="Fake Bridge",+ connection_config={},+ client_id=bridge_client.id,+ status="active",+ )+ session.add(bridge)+ await session.flush()++ room.bridge_id = bridge.id+ room.external_channel_id = "fake-chan-1"+ await session.commit()++ adapter = _FakeCollabAdapter()+ return room_id, bridge, adapter+++async def _fake_collab_core_full(+ chats: _Harness,+ room_id: str,+ bridge: CollaborationBridge,+ adapter: _FakeCollabAdapter,+) -> CollaborationCore:+ """Wire a CollaborationCore with both outbound and inbound paths for full testing."""++ async def _room_tenant(rid: str) -> str:+ async with chats.factory() as session:+ room = await session.get(Room, rid)+ assert room is not None+ return room.tenant_id++ async def _external_post_for_event(transport_event_id: str) -> str | None:+ async with chats.factory() as session:+ from switch_core.db.models import BridgeMessageMap++ result = await session.execute(+ select(BridgeMessageMap.external_post_id).where(+ BridgeMessageMap.transport_event_id == transport_event_id+ )+ )+ return result.scalar_one_or_none()++ async def _event_for_external_post(external_post_id: str) -> str | None:+ async with chats.factory() as session:+ from switch_core.db.models import BridgeMessageMap++ result = await session.execute(+ select(BridgeMessageMap.transport_event_id).where(+ BridgeMessageMap.external_post_id == external_post_id+ )+ )+ return result.scalar_one_or_none()++ async def _record_message_map(+ external_channel_id: str, transport_event_id: str, external_post_id: str+ ) -> None:+ async with chats.factory() as session:+ from switch_core.db.models import BridgeMessageMap++ map_row = BridgeMessageMap(+ bridge_id=bridge.id,+ external_channel_id=external_channel_id,+ transport_event_id=transport_event_id,+ external_post_id=external_post_id,+ )+ session.add(map_row)+ await session.commit()++ async def _is_registered_agent(name: str) -> bool:+ return False++ # Track created human actors for the test+ human_actors: dict[str, SimpleNamespace] = {}++ async def _ensure_human_in_room(+ external_user_id: str,+ external_username: str,+ room_id: str,+ transport_room_id: str,+ ) -> Any:+ # Return existing or create new fake actor+ if external_user_id in human_actors:+ return human_actors[external_user_id]++ # Create a minimal fake actor that can send messages+ async def send_message(+ transport_room_id_param: str,+ content: str,+ format: str = "markdown", # noqa: A002+ thread_root_id: str | None = None,+ metered: bool = False,+ ) -> str:+ # Use the real provisioning to send the message+ from switch_core.messages.row import message_row, new_event_id+ from switch_core.transport.content import message_content++ async with chats.factory() as session:+ from switch_core.db.stores.message_store import MessageStore+ from switch_core.db.stores.room_store import RoomStore++ # Get the room UUID from the transport_room_id+ room_row = await RoomStore().get_by_transport_room_id(+ session, transport_room_id_param+ )+ if not room_row:+ raise ValueError(f"Room not found: {transport_room_id_param}")++ event_id = new_event_id()+ msg_content = message_content(+ content,+ sender_name=external_username,+ format=format,+ thread_root_id=thread_root_id,+ )+ message = message_row(+ room_id=room_row.id,+ event_id=event_id,+ sender_id=f"@fake-{external_user_id}:switch.test",+ sender_client_id=None,+ sender_name=external_username,+ event_type="m.room.message",+ content=msg_content,+ client_txn_id=None,+ )+ await MessageStore().create(session, message, [])+ await session.commit()+ return event_id++ actor = SimpleNamespace(+ send_message=send_message,+ transport_user_id=f"@fake-{external_user_id}:switch.test",+ )+ human_actors[external_user_id] = actor+ return actor++ async def _handle_text_answer(msg: InboundMessage) -> None:+ pass++ async def _repair_placeholder_username(+ external_user_id: str, external_username: str+ ) -> None:+ pass++ async def _maybe_guide_self_mention(msg: InboundMessage, room_id: str) -> None:+ pass++ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None+ transport_room_id = room.transport_room_id++ ns = SimpleNamespace(+ _bridge_id=bridge.id,+ _bridge_type="fake",+ _adapter=adapter,+ _human_user_ids=set(),+ _workspace_consumer_transport_user_id="@bridge-bot:switch.test",+ _channel_to_room={"fake-chan-1": (room_id, transport_room_id)},+ _channel_locks={},+ _room_tenant=_room_tenant,+ _external_post_for_event=_external_post_for_event,+ _event_for_external_post=_event_for_external_post,+ _record_message_map=_record_message_map,+ _is_registered_agent=_is_registered_agent,+ _ensure_human_in_room=_ensure_human_in_room,+ _handle_text_answer=_handle_text_answer,+ _repair_placeholder_username=_repair_placeholder_username,+ _maybe_guide_self_mention=_maybe_guide_self_mention,+ _max_attachment_bytes=1024 * 1024,+ _trust_client=NullTrustClient(),+ )++ ns._find_channel = lambda room_id=None, transport_room_id=None: (+ "fake-chan-1" if transport_room_id == transport_room_id else None+ )+ ns._outbound_thread_root_ref = CollaborationCore._outbound_thread_root_ref.__get__(+ ns+ )+ ns._relay_outbound_message = CollaborationCore._relay_outbound_message.__get__(ns)+ ns.handle_outbound_message = CollaborationCore.handle_outbound_message.__get__(ns)+ ns._relay_outbound_media = CollaborationCore._relay_outbound_media.__get__(ns)+ ns._counted_outbound = CollaborationCore._counted_outbound.__get__(ns)+ ns._handle_inbound_message = CollaborationCore._handle_inbound_message.__get__(ns)+ ns._download_media = CollaborationCore._download_media.__get__(ns)++ return ns # type: ignore[return-value]+++async def test_console_member_threaded_reply_roundtrip_through_bridge(+ chats: _Harness,+) -> None:+ """Console member messages relay outbound with sender_name (not skipped),+ inbound platform threaded replies arrive with threadRootId, and the+ member's own post echo from the platform is not re-imported."""+ agent = await chats.agent("helper-threaded", owner=chats.alice)+ room_id, bridge, adapter = await _bridged_room(chats, agent)+ core = await _fake_collab_core_full(chats, room_id, bridge, adapter)++ # Send root message from console member+ sent = await chats.send(chats.alice, room_id, "s1", "root message")+ assert sent.status_code == 200, sent.text+ root_msg = sent.json()["messages"][0]+ root_event_id = root_msg["messageId"]++ # Drive outbound relay+ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None+ member = await chats.service.member_client(session, chats.alice.id)+ assert member is not None++ msg_row = await session.execute(+ select(Message).where(Message.transport_event_id == root_event_id)+ )+ msg = msg_row.scalar_one()++ event = TransportMessage(+ room_id=room.transport_room_id,+ event_id=msg.transport_event_id,+ sender=member.transport_user_id,+ timestamp=1700000000000,+ content=msg.content,+ body=msg.body,+ sender_name=msg.sender_name,+ thread_root_id=None,+ )++ await CollaborationCore.handle_outbound_message(+ core, RoomRef(room.transport_room_id), event+ )++ # Verify outbound relay: member's message relayed with sender_name, not skipped+ assert len(adapter.sent) == 1+ assert adapter.sent[0]["sender_name"] == "alice"+ assert adapter.sent[0]["content"] == "root message"+ assert adapter.sent[0]["thread_root_id"] is None++ # Send threaded reply from console member+ reply_sent = await chats.send(+ chats.alice, room_id, "s2", "threaded reply", threadRootId=root_event_id+ )+ assert reply_sent.status_code == 200+ reply_msg = reply_sent.json()["messages"][0]+ assert reply_msg["threadRootId"] == root_event_id++ # Drive outbound relay for the reply+ async with chats.factory() as session:+ reply_row = await session.execute(+ select(Message).where(Message.transport_event_id == reply_msg["messageId"])+ )+ reply_db = reply_row.scalar_one()++ reply_event = TransportMessage(+ room_id=room.transport_room_id,+ event_id=reply_db.transport_event_id,+ sender=member.transport_user_id,+ timestamp=1700000000000,+ content=reply_db.content,+ body=reply_db.body,+ sender_name=reply_db.sender_name,+ thread_root_id=root_event_id,+ )++ await CollaborationCore.handle_outbound_message(+ core, RoomRef(room.transport_room_id), reply_event+ )++ # Verify threaded outbound: thread_root_id mapped to external post+ assert len(adapter.sent) == 2+ assert adapter.sent[1]["sender_name"] == "alice"+ assert adapter.sent[1]["content"] == "threaded reply"+ assert adapter.sent[1]["thread_root_id"] == "ext-1"++ # Test inbound direction: platform user replies in thread to ext-1+ inbound_reply = InboundMessage(+ channel_id="fake-chan-1",+ channel_type="channel_public",+ sender_id="platform-user-123",+ sender_name="bob",+ content="platform threaded reply",+ message_ref="ext-3",+ root_id="ext-1",+ )++ await CollaborationCore._handle_inbound_message(core, inbound_reply)++ # Verify inbound threaded reply arrives with threadRootId+ page = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ messages = page.json()["messages"]+ platform_reply = [m for m in messages if m["body"] == "platform threaded reply"]+ assert len(platform_reply) == 1, "Inbound threaded reply imported"+ assert platform_reply[0]["threadRootId"] == root_event_id, (+ "Thread root mapped from external post to room event"+ )++ # Test echo prevention: console member's own message won't echo inbound+ # because member clients post natively in the room, not through the bridge+ async with chats.factory() as session:+ count_before = await session.scalar(+ select(func.count()).select_from(Message).where(Message.room_id == room_id)+ )++ # Member posts again+ member_post2 = await chats.send(chats.alice, room_id, "s3", "second message")+ assert member_post2.status_code == 200++ async with chats.factory() as session:+ count_after = await session.scalar(+ select(func.count()).select_from(Message).where(Message.room_id == room_id)+ )++ # Exactly one new message (the member's post), no echo imported+ assert count_after == count_before + 1+++async def test_a_console_command_is_posted_and_its_reply_threads_under_it(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id, bridge, adapter = await _bridged_room(chats, agent)+ core = await _fake_collab_core_full(chats, room_id, bridge, adapter)++ response = await chats.client.post(+ f"/chats/{room_id}/controls",+ json={"requestId": "k1", "agentId": agent.id, "command": "reset"},+ headers=chats.as_user(chats.alice),+ )+ assert response.status_code == 202, response.text+ command_id = response.json()["commandId"]++ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None+ row = (+ await session.execute(+ select(Message).where(Message.transport_event_id == command_id)+ )+ ).scalar_one()+ transport_room = RoomRef(room.transport_room_id)++ async def on_command(room_ref: RoomRef, event: CommandEvent) -> None:+ await CollaborationCore.handle_outbound_command(core, room_ref, event)++ consumer = SimpleNamespace(+ _EVENT_DISPATCH=Consumer._EVENT_DISPATCH,+ _should_ignore=lambda _room, _event: False,+ on_command=on_command,+ )+ inbound = to_inbound(row, [], transport_room_id=room.transport_room_id)+ await Consumer._handle_custom_event(consumer, transport_room, inbound) # type: ignore[arg-type]++ [posted] = adapter.sent+ assert (posted["sender_name"], posted["content"]) == ("alice", "!reset @helper")+ assert posted["thread_root_id"] is None++ ack = TransportMessage(+ room_id=room.transport_room_id,+ event_id="$ack",+ sender="@helper:switch.test",+ timestamp=1700000000000,+ content={"m.relates_to": {"rel_type": "m.thread", "event_id": command_id}},+ body="Session reset.",+ sender_name="helper",+ thread_root_id=command_id,+ )+ await CollaborationCore.handle_outbound_message(core, transport_room, ack)+ assert adapter.sent[1]["thread_root_id"] == "ext-1"++ # A command typed on the platform is already there: it is not posted back.+ core._human_user_ids.add("@fake-platform-user:switch.test")+ await CollaborationCore.handle_outbound_command(+ core,+ transport_room,+ CommandEvent(+ command="reset",+ args="@helper",+ user_id="@fake-platform-user:switch.test",+ user_name="bob",+ message_id="$typed",+ thread_id="$typed",+ ),+ )+ assert len(adapter.sent) == 2+++async def test_multi_attachment_send_atomic_despite_bridge_failure(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Multi-attachment message parts commit atomically as one group in the DB.+ Retry with the same requestId returns the stored parts without inserting+ duplicates.++ Note: Full bridge outbound media relay (with group buffering, adapter+ calls, and failure handling) requires _outbound_groups, _outbound_group_timers,+ _schedule_outbound_group_flush, _relay_outbound_group, and other state+ management that is too entangled to properly fake. This test focuses on+ the DB-level atomicity guarantee."""+ agent = await chats.agent("helper-atomic", owner=chats.alice)+ room_id, _bridge, _adapter = await _bridged_room(chats, agent)++ for upload_id in ("u1", "u2", "u3"):+ staged = await chats.upload(+ chats.alice, room_id, upload_id, b"data", f"{upload_id}.png"+ )+ assert staged.status_code == 200, staged.text++ # Send multi-attachment message+ retried = await chats.send(+ chats.alice,+ room_id,+ "s1",+ "three files",+ uploadIds=["u1", "u2", "u3"],+ )+ assert retried.status_code == 200, retried.text+ parts = retried.json()["messages"]+ assert len(parts) == 3+ assert [p["clientTxn"] for p in parts] == ["s1:0", "s1:1", "s1:2"]++ # Verify DB has exactly one complete 3-part group (atomic insert)+ async with chats.factory() as session:+ rows = list(+ (+ await session.execute(+ select(Message)+ .where(+ Message.room_id == room_id,+ Message.client_txn_id.like("s1:%"),+ )+ .order_by(Message.seq)+ )+ ).scalars()+ )+ assert len(rows) == 3, "All 3 parts committed"+ groups = {row.content["com.switch.attachment_group"]["id"] for row in rows}+ assert len(groups) == 1, "Atomic insert created exactly one complete group"++ # Test retry with same requestId: returns stored parts, no duplicates+ again = await chats.send(+ chats.alice,+ room_id,+ "s1",+ "three files",+ uploadIds=["u1", "u2", "u3"],+ )+ assert again.status_code == 200+ assert [p["messageId"] for p in again.json()["messages"]] == [+ p["messageId"] for p in parts+ ], "Retry returned stored parts, no duplicates inserted"++ # Final verification: still exactly 3 parts, one group+ async with chats.factory() as session:+ final_count = await session.scalar(+ select(func.count())+ .select_from(Message)+ .where(Message.room_id == room_id, Message.client_txn_id.like("s1:%"))+ )++ assert final_count == 3, "Retry did not insert duplicate parts"diff --git a/core/tests/switch_core/gateway/test_chats_controls.py b/core/tests/switch_core/gateway/test_chats_controls.pynew file mode 100644index 000000000..e7e0781be--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_controls.py@@ -0,0 +1,184 @@+"""`POST /chats/{room_id}/controls`: Switch Console's Stop, reset and compact,+posted as the same `com.switch.command` event a platform bridge writes."""++from __future__ import annotations++from types import SimpleNamespace++import httpx+from sqlalchemy import select, update++from switch_core.addressing import owner_only_policy+from switch_core.clients.consumer import Consumer+from switch_core.db.models import Agent, AgentSessionActivityItem, Message, User+from switch_core.events import CommandEvent+from switch_core.transport import RoomRef+from switch_core.transport.stored import to_inbound+from tests.switch_core.gateway.conftest import _Harness+from tests.switch_core.gateway.test_chats_routes import _code, _step+++async def _control(+ chats: _Harness,+ user: User,+ room_id: str,+ agent: Agent,+ request_id: str,+ command: str = "reset",+) -> httpx.Response:+ return await chats.client.post(+ f"/chats/{room_id}/controls",+ json={"requestId": request_id, "agentId": agent.id, "command": command},+ headers=chats.as_user(user),+ )+++async def _commands(chats: _Harness, room_id: str) -> list[Message]:+ async with chats.factory() as session:+ rows = await session.execute(+ select(Message).where(+ Message.room_id == room_id,+ Message.event_type == "com.switch.command",+ )+ )+ return list(rows.scalars().all())+++async def test_a_control_refuses_non_members_and_senders_the_agent_refuses(+ chats: _Harness,+) -> None:+ private = await chats.agent(+ "private", owner=chats.alice, policy=owner_only_policy([]).model_dump()+ )+ room_id = await chats.new_chat(chats.alice, private, "c1")++ outsider = await _control(chats, chats.bob, room_id, private, "k1")+ assert outsider.status_code == 403+ assert _code(outsider) == "NOT_A_MEMBER"++ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ refused = await _control(chats, chats.bob, room_id, private, "k1")+ assert refused.status_code == 403+ assert _code(refused) == "AGENT_NOT_ALLOWED"++ elsewhere = await chats.agent("elsewhere", owner=chats.alice)+ absent = await _control(chats, chats.alice, room_id, elsewhere, "k2")+ assert absent.status_code == 422+ assert _code(absent) == "AGENT_NOT_IN_CHAT"++ assert await _commands(chats, room_id) == []+++async def test_a_repeated_control_posts_one_command(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ first = await _control(chats, chats.alice, room_id, agent, "k1")+ again = await _control(chats, chats.alice, room_id, agent, "k1")+ assert first.status_code == again.status_code == 202+ assert first.json() == again.json()+ assert len(await _commands(chats, room_id)) == 1++ reused = await _control(chats, chats.alice, room_id, agent, "k1", "compact")+ assert reused.status_code == 409+ assert _code(reused) == "REQUEST_REUSED"+++async def test_the_posted_control_reaches_command_dispatch(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ response = await _control(chats, chats.alice, room_id, agent, "k1", "compact")+ command_id = response.json()["commandId"]++ [row] = await _commands(chats, room_id)+ async with chats.factory() as session:+ member = await chats.service.member_client(session, chats.alice.id)+ assert member is not None+ assert row.transport_event_id == command_id+ assert row.sender_id == member.transport_user_id++ seen: list[CommandEvent] = []++ async def on_command(_room: RoomRef, event: CommandEvent) -> None:+ seen.append(event)++ consumer = SimpleNamespace(+ _EVENT_DISPATCH=Consumer._EVENT_DISPATCH,+ _should_ignore=lambda _room, _event: False,+ on_command=on_command,+ )+ room = RoomRef(room_id="!room:test")+ inbound = to_inbound(row, [], transport_room_id=room.room_id)+ await Consumer._handle_custom_event(consumer, room, inbound) # type: ignore[arg-type]++ [event] = seen+ assert event.command == "compact"+ assert event.args == "@helper"+ assert event.user_id == member.transport_user_id+ assert event.user_name == "alice"+ assert event.message_id == event.thread_id == command_id+++async def test_a_posted_control_is_shown_in_the_chat(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ response = await _control(chats, chats.alice, room_id, agent, "k1", "reset")+ command_id = response.json()["commandId"]++ page = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ assert page.status_code == 200, page.text+ [shown] = [m for m in page.json()["messages"] if m["messageId"] == command_id]+ assert shown["body"] == "!reset @helper"++ listed = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ [chat] = [c for c in listed.json()["chats"] if c["roomId"] == room_id]+ assert chat["lastMessage"]["preview"] == "!reset @helper"+++async def test_stop_refuses_unless_the_agents_current_turn_is_in_this_chat(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ here = await chats.new_chat(chats.alice, agent, "c1")+ there = await chats.new_chat(chats.alice, agent, "c2")++ idle = await _control(chats, chats.alice, here, agent, "k1", "interrupt")+ assert idle.status_code == 409+ assert _code(idle) == "NOTHING_RUNNING_HERE"++ await _step(chats, agent, here, "t1", "turn", 1)+ await _step(chats, agent, there, "t2", "turn", 1)+ elsewhere = await _control(chats, chats.alice, here, agent, "k2", "interrupt")+ assert elsewhere.status_code == 409+ assert _code(elsewhere) == "NOTHING_RUNNING_HERE"+ assert await _commands(chats, here) == []++ stopped = await _control(chats, chats.alice, there, agent, "k3", "interrupt")+ assert stopped.status_code == 202, stopped.text+ assert len(await _commands(chats, there)) == 1+++async def test_stop_follows_the_running_turn_not_one_queued_behind_it(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ running_room = await chats.new_chat(chats.alice, agent, "c1")+ queued_room = await chats.new_chat(chats.alice, agent, "c2")+ await _step(chats, agent, running_room, "t1", "turn", 1)+ await _step(chats, agent, queued_room, "t2", "turn", 1)+ async with chats.factory() as session:+ await session.execute(+ update(AgentSessionActivityItem)+ .where(AgentSessionActivityItem.turn_id == "t2")+ .values(status="queued")+ )+ await session.commit()++ queued = await _control(chats, chats.alice, queued_room, agent, "k1", "interrupt")+ assert queued.status_code == 409+ assert _code(queued) == "NOTHING_RUNNING_HERE"++ running = await _control(chats, chats.alice, running_room, agent, "k2", "interrupt")+ assert running.status_code == 202, running.textdiff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.pynew file mode 100644index 000000000..2facd7a6e--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_routes.py@@ -0,0 +1,1684 @@+"""`/chats`: membership as the only read authority, retryable creates and+sends, and the live event stream — against real Postgres.++The routes run behind a real `ChatService`, `RoomService` and Postgres+provisioning. Only the running-client registry is faked (no agent consumer+runs here) and the message listener, whose wake-ups the stream tests ring by+hand so a missed notification can be staged.+"""++from __future__ import annotations++import asyncio+import json+import uuid+from collections.abc import AsyncIterator+from datetime import UTC, datetime, timedelta+from typing import Any++import httpx+import pytest+from sqlalchemy import delete, func, select, update++from switch_core.addressing import owner_only_policy+from switch_core.db.models import (+ Agent,+ AgentSessionActivityItem,+ ApprovalRequest,+ ChatOperation,+ ChatOwnerGrant,+ Client,+ ClientRoom,+ CollaborationBridge,+ Message,+ Room,+ TenantMember,+ User,+ room_agents,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.message_store import MessageStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.gateway import chats as chats_module+from switch_core.gateway.chats import (+ chat_activity_events,+ chat_events,+)+from switch_core.session_activity.listener import Change+from tests.switch_core.gateway.conftest import _Harness+++def _code(response: httpx.Response) -> str:+ return str(response.json()["detail"]["code"])+++# ── Access ───────────────────────────────────────────────────────────────────+++async def test_public_room_is_not_readable_without_membership(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ async with chats.factory() as session:+ room = Room(+ transport_room_id="!public:test",+ name="public",+ description="",+ owner_id=chats.alice.id,+ read_visibility="public",+ write_visibility="public",+ )+ session.add(room)+ await session.flush()+ await session.execute(+ room_agents.insert().values(room_id=room.id, agent_id=agent.id)+ )+ await session.commit()++ response = await chats.client.get(+ f"/chats/{room.id}/messages", headers=chats.as_user(chats.bob)+ )+ assert response.status_code == 403+ assert _code(response) == "NOT_A_MEMBER"++ sent = await chats.send(chats.bob, room.id, "r1", "hello")+ assert sent.status_code == 403+ assert await chats.message_rows(room.id) == []++ missing = await chats.client.get(+ "/chats/no-such-room/messages", headers=chats.as_user(chats.bob)+ )+ assert missing.status_code == 404+++async def test_a_member_who_does_not_manage_cannot_join_or_invite(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ self_join = await chats.invite(chats.bob, room_id, chats.bob)+ assert self_join.status_code == 403+ assert _code(self_join) == "NOT_A_MANAGER"++ read = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.bob)+ )+ assert read.status_code == 403+++async def test_a_manager_invites_tenant_members_and_may_join_themselves(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ invited = await chats.invite(chats.alice, room_id, chats.bob)+ assert invited.status_code == 200, invited.text+ assert {m["userId"] for m in invited.json()["members"]} == {+ chats.alice.id,+ chats.bob.id,+ }+ read = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.bob)+ )+ assert read.status_code == 200++ outsider = await chats.invite(chats.alice, room_id, chats.carol)+ assert outsider.status_code == 422+ assert _code(outsider) == "NOT_A_TENANT_MEMBER"++ # A tenant admin manages every room, so may add themselves to this one.+ joined = await chats.invite(chats.admin, room_id, chats.admin)+ assert joined.status_code == 200+ members = await chats.client.get(+ f"/chats/{room_id}/members", headers=chats.as_user(chats.admin)+ )+ assert [m for m in members.json()["members"] if m["isOwner"]] == [+ {"userId": chats.alice.id, "name": "alice", "isOwner": True}+ ]+++async def test_losing_the_tenant_role_revokes_access(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++ async with chats.factory() as session:+ await session.execute(+ delete(TenantMember).where(TenantMember.user_id == chats.bob.id)+ )+ await session.commit()++ read = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.bob)+ )+ assert read.status_code == 403+ listed = await chats.client.get("/chats", headers=chats.as_user(chats.bob))+ assert listed.json() == {"chats": []}+++async def test_removing_a_member_and_leaving(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+ assert (await chats.invite(chats.alice, room_id, chats.admin)).status_code == 200++ refused = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.admin.id}", headers=chats.as_user(chats.bob)+ )+ assert refused.status_code == 403++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ read = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.bob)+ )+ assert read.status_code == 403++ left = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.admin.id}", headers=chats.as_user(chats.admin)+ )+ assert left.status_code == 204+ members = await chats.client.get(+ f"/chats/{room_id}/members", headers=chats.as_user(chats.alice)+ )+ assert [m["userId"] for m in members.json()["members"]] == [chats.alice.id]+++# ── Creating a chat ──────────────────────────────────────────────────────────+++async def test_a_new_chat_is_a_private_direct_room_owned_by_its_creator(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ response = await chats.create_chat(chats.alice, agent, "c1")+ assert response.status_code == 200, response.text+ chat = response.json()["chat"]+ assert chat["channelType"] == "direct"+ assert chat["bridgeType"] is None+ assert chat["canManage"] is True+ assert [a["id"] for a in chat["agents"]] == [agent.id]+ assert chat["lastMessage"] is None++ async with chats.factory() as session:+ room = await session.get(Room, chat["roomId"])+ assert room is not None+ assert room.bridge_id is None+ assert room.read_visibility == "private"+ assert room.write_visibility == "private"+ assert room.owner_id == chats.alice.id+ assert room.created_by == chats.alice.id+ members = set(+ (+ await session.execute(+ select(ClientRoom.client_id).where(ClientRoom.room_id == room.id)+ )+ ).scalars()+ )+ member = await chats.service.member_client(session, chats.alice.id)+ assert member is not None+ assert {member.id, agent.client_id} <= members++ listed = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ assert [c["roomId"] for c in listed.json()["chats"]] == [chat["roomId"]]+++async def test_a_registered_agent_reports_its_provider(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ async with chats.factory() as session:+ row = await session.get(Agent, agent.id)+ assert row is not None+ row.metadata_ = {"known_agent_type": "claude-code"}+ await session.commit()+ other = await chats.agent("plain", owner=chats.alice)++ first = await chats.create_chat(chats.alice, agent, "c1")+ second = await chats.create_chat(chats.alice, other, "c2")+ assert first.json()["chat"]["agents"][0]["provider"] == "claude"+ assert second.json()["chat"]["agents"][0]["provider"] is None+++async def test_an_owner_only_agent_refuses_a_chat_from_anyone_else(+ chats: _Harness,+) -> None:+ agent = await chats.agent(+ "private", owner=chats.alice, policy=owner_only_policy([]).model_dump()+ )+ refused = await chats.create_chat(chats.bob, agent, "c1")+ assert refused.status_code == 403+ assert _code(refused) == "AGENT_NOT_ALLOWED"+ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 0++ allowed = await chats.create_chat(chats.alice, agent, "c1")+ assert allowed.status_code == 200+++async def test_creating_twice_with_one_request_id_creates_one_chat(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ first = await chats.new_chat(chats.alice, agent, "c1")+ second = await chats.new_chat(chats.alice, agent, "c1")+ assert first == second++ reused = await chats.create_chat(chats.alice, other, "c1")+ assert reused.status_code == 409+ assert _code(reused) == "REQUEST_REUSED"+ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 1+++async def test_several_agents_make_a_private_channel_with_all_of_them(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ response = await chats.client.post(+ "/chats",+ json={"agentIds": [helper.id, other.id, helper.id], "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )+ assert response.status_code == 200, response.text+ chat = response.json()["chat"]+ assert chat["channelType"] == "channel_private"+ assert chat["bridgeType"] is None+ assert sorted(a["id"] for a in chat["agents"]) == sorted([helper.id, other.id])+ assert chat["name"] == "Chat with helper, other"++ async with chats.factory() as session:+ clients = set(await RoomStore().get_client_ids(session, chat["roomId"]))+ member = await chats.service.member_client(session, chats.alice.id)+ assert member is not None+ assert {member.id, helper.client_id, other.client_id} <= clients++ sent = await chats.send(+ chats.alice, chat["roomId"], "s1", "your turn", mentionAgentId=other.id+ )+ assert sent.json()["messages"][0]["body"] == "@other your turn"+++async def test_a_chat_with_several_agents_needs_every_one_allowed(+ chats: _Harness,+) -> None:+ open_agent = await chats.agent("helper", owner=chats.alice)+ private = await chats.agent(+ "private", owner=chats.alice, policy=owner_only_policy([]).model_dump()+ )+ refused = await chats.client.post(+ "/chats",+ json={"agentIds": [open_agent.id, private.id], "requestId": "c1"},+ headers=chats.as_user(chats.bob),+ )+ assert refused.status_code == 403+ assert _code(refused) == "AGENT_NOT_ALLOWED"+ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 0+++async def test_the_agents_are_part_of_a_create_request(chats: _Harness) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)++ def create(agent_ids: list[str]) -> Any:+ return chats.client.post(+ "/chats",+ json={"agentIds": agent_ids, "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )++ first = await create([helper.id, other.id])+ assert first.status_code == 200, first.text+ again = await create([helper.id, other.id])+ assert again.json()["chat"]["roomId"] == first.json()["chat"]["roomId"]+ changed = await create([helper.id])+ assert changed.status_code == 409+ assert _code(changed) == "REQUEST_REUSED"+++async def test_a_create_names_its_agents_one_way(chats: _Harness) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ for body in (+ {"requestId": "c1"},+ {"requestId": "c2", "agentIds": []},+ {"requestId": "c3", "agentId": helper.id, "agentIds": [helper.id]},+ ):+ response = await chats.client.post(+ "/chats", json=body, headers=chats.as_user(chats.alice)+ )+ assert response.status_code == 422, body+ assert _code(response) == "AGENTS_REQUIRED"+++async def test_a_create_that_stopped_after_the_room_committed_is_repaired(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)++ async def crash(*_args: object) -> None:+ raise RuntimeError("process died")++ with monkeypatch.context() as patch:+ patch.setattr(chats.room_service, "_invite_clients", crash)+ with pytest.raises(RuntimeError):+ await chats.create_chat(chats.alice, agent, "c1")++ async with chats.factory() as session:+ operation = await session.get(+ ChatOperation,+ ("00000000-0000-0000-0000-000000000000", chats.alice.id, "c1"),+ )+ assert operation is not None and operation.state == "pending"+ rooms = list((await session.execute(select(Room))).scalars())+ assert len(rooms) == 1+ assert await RoomStore().get_client_ids(session, rooms[0].id) == []++ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert room_id == rooms[0].id+ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 1+ clients = set(await RoomStore().get_client_ids(session, room_id))+ assert agent.client_id in clients+ member = await chats.service.member_client(session, chats.alice.id)+ assert member is not None and member.id in clients+++# ── Sending ──────────────────────────────────────────────────────────────────+++async def test_a_sent_message_reads_back_as_the_console_member(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ sent = await chats.send(chats.alice, room_id, "s1", "hello **there**")+ assert sent.status_code == 200, sent.text+ [message] = sent.json()["messages"]+ assert message["source"] == "console"+ assert message["sender"]["kind"] == "human"+ assert message["sender"]["userId"] == chats.alice.id+ assert message["sender"]["name"] == "alice"+ assert message["clientTxn"] == "s1:0"+ assert message["format"] == "org.matrix.custom.html"+ assert message["threadRootId"] is None++ page = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ body = page.json()+ assert [m["messageId"] for m in body["messages"]] == [message["messageId"]]+ assert body["headSeq"] >= message["seq"]+ assert body["hasMore"] is False+++async def test_a_plain_sent_message_carries_no_html(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ sent = await chats.send(chats.alice, room_id, "s1", "just a plain line\nand a < b")+ assert sent.status_code == 200, sent.text+ [message] = sent.json()["messages"]+ assert message["format"] is None+ assert message["body"] == "just a plain line\nand a < b"+++async def test_paging_walks_back_by_seq(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ for i in range(3):+ assert (+ await chats.send(chats.alice, room_id, f"s{i}", f"m{i}")+ ).status_code == 200++ newest = await chats.client.get(+ f"/chats/{room_id}/messages?limit=2", headers=chats.as_user(chats.alice)+ )+ page = newest.json()+ assert [m["body"] for m in page["messages"]] == ["m1", "m2"]+ assert page["hasMore"] is True+ older = await chats.client.get(+ f"/chats/{room_id}/messages?limit=2&beforeSeq={page['messages'][0]['seq']}",+ headers=chats.as_user(chats.alice),+ )+ assert [m["body"] for m in older.json()["messages"]] == ["m0"]+ assert older.json()["hasMore"] is False+++async def test_a_send_that_failed_before_commit_posts_once_on_retry(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ for upload_id in ("u1", "u2", "u3"):+ staged = await chats.upload(+ chats.alice, room_id, upload_id, b"png", f"{upload_id}.png"+ )+ assert staged.status_code == 200, staged.text++ original = MessageStore.create+ calls = 0++ async def fail_on_second(self: MessageStore, *args: Any, **kwargs: Any) -> Message:+ nonlocal calls+ calls += 1+ if calls == 2:+ raise RuntimeError("database went away")+ return await original(self, *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(MessageStore, "create", fail_on_second)+ with pytest.raises(RuntimeError):+ await chats.send(+ chats.alice, room_id, "s1", "three files", uploadIds=["u1", "u2", "u3"]+ )+ assert await chats.message_rows(room_id) == []++ retried = await chats.send(+ chats.alice, room_id, "s1", "three files", uploadIds=["u1", "u2", "u3"]+ )+ assert retried.status_code == 200, retried.text+ parts = retried.json()["messages"]+ assert [p["clientTxn"] for p in parts] == ["s1:0", "s1:1", "s1:2"]+ assert parts[0]["body"] == "three files"+ assert [p["attachments"][0]["filename"] for p in parts] == [+ "u1.png",+ "u2.png",+ "u3.png",+ ]++ again = await chats.send(+ chats.alice, room_id, "s1", "three files", uploadIds=["u1", "u2", "u3"]+ )+ assert [p["messageId"] for p in again.json()["messages"]] == [+ p["messageId"] for p in parts+ ]+ rows = await chats.message_rows(room_id)+ assert len(rows) == 3+ groups = {row.content["com.switch.attachment_group"]["id"] for row in rows}+ assert len(groups) == 1+++async def test_one_request_id_from_two_users_is_two_sends(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++ from_alice = await chats.send(chats.alice, room_id, "same", "from alice")+ from_bob = await chats.send(chats.bob, room_id, "same", "from bob")+ assert from_alice.status_code == 200 and from_bob.status_code == 200+ assert [m.body for m in await chats.message_rows(room_id)] == [+ "from alice",+ "from bob",+ ]+++async def test_reusing_a_request_id_for_another_room_is_refused(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ first = await chats.new_chat(chats.alice, agent, "c1")+ second = await chats.new_chat(chats.alice, agent, "c2")+ assert (await chats.send(chats.alice, first, "s1", "hi")).status_code == 200++ reused = await chats.send(chats.alice, second, "s1", "hi")+ assert reused.status_code == 409+ assert _code(reused) == "REQUEST_REUSED"+ assert await chats.message_rows(second) == []+++async def test_concurrent_duplicate_sends_post_once(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ results = await asyncio.gather(+ *(chats.send(chats.alice, room_id, "s1", "only once") for _ in range(4))+ )+ assert {r.status_code for r in results} == {200}+ assert len({r.json()["messages"][0]["messageId"] for r in results}) == 1+ assert len(await chats.message_rows(room_id)) == 1+++async def test_a_reply_goes_into_the_thread_of_its_root(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ root = (await chats.send(chats.alice, room_id, "s1", "root")).json()["messages"][0]++ reply = await chats.send(+ chats.alice, room_id, "s2", "reply", threadRootId=root["messageId"]+ )+ assert reply.json()["messages"][0]["threadRootId"] == root["messageId"]+ nested = await chats.send(+ chats.alice,+ room_id,+ "s3",+ "reply to reply",+ threadRootId=reply.json()["messages"][0]["messageId"],+ )+ assert nested.json()["messages"][0]["threadRootId"] == root["messageId"]+ [row] = [r for r in await chats.message_rows(room_id) if r.body == "reply to reply"]+ assert row.content["m.relates_to"] == {+ "rel_type": "m.thread",+ "event_id": root["messageId"],+ }++ unknown = await chats.send(chats.alice, room_id, "s4", "x", threadRootId="sw_nope")+ assert unknown.status_code == 422+++async def test_mentioning_an_agent_prefixes_its_name_once(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ plain = await chats.send(+ chats.alice, room_id, "s1", "do it", mentionAgentId=agent.id+ )+ assert plain.json()["messages"][0]["body"] == "@helper do it"+ tagged = await chats.send(+ chats.alice, room_id, "s2", "ask @helper now", mentionAgentId=agent.id+ )+ assert tagged.json()["messages"][0]["body"] == "ask @helper now"+++async def test_uploads_are_idempotent_and_media_is_scoped_to_the_room(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ other_room = await chats.new_chat(chats.alice, agent, "c2")++ staged = await chats.upload(chats.alice, room_id, "u1", b"bytes", "a.png")+ again = await chats.upload(chats.alice, room_id, "u1", b"bytes", "a.png")+ assert staged.json() == again.json()+ conflict = await chats.upload(chats.alice, room_id, "u1", b"other", "a.png")+ assert conflict.status_code == 409+ too_big = await chats.upload(chats.alice, room_id, "u2", b"x" * 2048, "b.png")+ assert too_big.status_code == 422++ uri = staged.json()["uri"]+ unsent = await chats.client.get(+ f"/chats/{room_id}/media",+ params={"uri": uri},+ headers=chats.as_user(chats.alice),+ )+ assert unsent.status_code == 404++ wrong_room = await chats.send(chats.alice, other_room, "s0", "", uploadIds=["u1"])+ assert wrong_room.status_code == 422+ sent = await chats.send(chats.alice, room_id, "s1", "", uploadIds=["u1"])+ [part] = sent.json()["messages"]+ assert part["attachments"] == [+ {+ "uri": uri,+ "filename": "a.png",+ "mimetype": "image/png",+ "size": 5,+ "msgtype": "m.image",+ }+ ]++ media = await chats.client.get(+ f"/chats/{room_id}/media",+ params={"uri": uri},+ headers=chats.as_user(chats.alice),+ )+ assert media.status_code == 200+ assert media.content == b"bytes"+ assert media.headers["content-type"] == "image/png"+ elsewhere = await chats.client.get(+ f"/chats/{other_room}/media",+ params={"uri": uri},+ headers=chats.as_user(chats.alice),+ )+ assert elsewhere.status_code == 404+ stranger = await chats.client.get(+ f"/chats/{room_id}/media", params={"uri": uri}, headers=chats.as_user(chats.bob)+ )+ assert stranger.status_code == 403+++async def test_a_member_removed_after_a_failed_send_cannot_retry_it(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> 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++ async def fail(self: MessageStore, *args: Any, **kwargs: Any) -> Message:+ raise RuntimeError("database went away")++ with monkeypatch.context() as patch:+ patch.setattr(MessageStore, "create", fail)+ with pytest.raises(RuntimeError):+ await chats.send(chats.bob, room_id, "s1", "hi")++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ retried = await chats.send(chats.bob, room_id, "s1", "hi")+ assert retried.status_code == 403+ assert await chats.message_rows(room_id) == []+++# ── Hiding and archiving ─────────────────────────────────────────────────────+++async def test_a_hidden_chat_returns_when_something_new_is_said(+ 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+ assert (await chats.send(chats.alice, room_id, "s1", "before")).status_code == 200++ hidden = await chats.client.put(+ f"/chats/{room_id}/hidden", headers=chats.as_user(chats.alice)+ )+ assert hidden.status_code == 204+ listed = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ assert listed.json()["chats"] == []+ still_bobs = await chats.client.get("/chats", headers=chats.as_user(chats.bob))+ assert len(still_bobs.json()["chats"]) == 1++ assert (await chats.send(chats.bob, room_id, "s2", "news")).status_code == 200+ back = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ [chat] = back.json()["chats"]+ assert chat["lastMessage"]["preview"] == "news"+ assert chat["lastMessage"]["senderName"] == "bob"++ await chats.client.put(+ f"/chats/{room_id}/hidden", headers=chats.as_user(chats.alice)+ )+ shown = await chats.client.delete(+ f"/chats/{room_id}/hidden", headers=chats.as_user(chats.alice)+ )+ assert shown.status_code == 204+ again = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ assert len(again.json()["chats"]) == 1+++async def test_only_a_manager_archives_a_chat(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++ refused = await chats.client.post(+ f"/chats/{room_id}/archive", headers=chats.as_user(chats.bob)+ )+ assert refused.status_code == 403+ assert _code(refused) == "NOT_A_MANAGER"++ archived = await chats.client.post(+ f"/chats/{room_id}/archive", headers=chats.as_user(chats.alice)+ )+ assert archived.status_code == 204+ listed = await chats.client.get("/chats", headers=chats.as_user(chats.alice))+ assert listed.json()["chats"] == []+++# ── Live updates ─────────────────────────────────────────────────────────────+++class _Events:+ """Reads one stream's frames as `(event, data)` pairs, skipping pings."""++ def __init__(self, stream: AsyncIterator[bytes]) -> None:+ self.stream = stream++ async def next(self, timeout: float = 3.0) -> tuple[str, Any]:+ while True:+ frame = (await asyncio.wait_for(anext(self.stream), timeout)).decode()+ if frame.startswith(":"):+ continue+ event_line, data_line = frame.strip().split("\n")+ return event_line.removeprefix("event: "), json.loads(+ data_line.removeprefix("data: ")+ )++ async def until(self, event: str) -> Any:+ while True:+ name, data = await self.next()+ if name == event:+ return data+++def _stream(+ chats: _Harness, user: User, after: dict[str, int], recheck: float+) -> _Events:+ return _Events(+ chat_events(+ chats.service,+ "00000000-0000-0000-0000-000000000000",+ user,+ after,+ ping_seconds=60.0,+ recheck_seconds=recheck,+ )+ )+++async def test_the_stream_catches_up_then_says_ready_then_pushes(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ first = (await chats.send(chats.alice, room_id, "s1", "one")).json()["messages"][0]+ assert (await chats.send(chats.alice, room_id, "s2", "two")).status_code == 200++ second = await _read_back(chats, room_id, "two")++ events = _stream(chats, chats.alice, {room_id: first["seq"]}, recheck=60.0)+ assert await events.next() == ("message", second)+ assert (await events.next())[0] == "ready"++ assert (await chats.send(chats.alice, room_id, "s3", "three")).status_code == 200+ await chats.listener.ring(room_id)+ name, data = await events.next()+ assert name == "message" and data["body"] == "three"+ await events.stream.aclose() # type: ignore[attr-defined]+ assert all(not wakers for wakers in chats.listener.wakers.values())+++async def _read_back(chats: _Harness, room_id: str, body: str) -> dict[str, Any]:+ page = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ [message] = [m for m in page.json()["messages"] if m["body"] == body]+ return message # type: ignore[no-any-return]+++async def test_the_stream_announces_new_chats_and_removals(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ events = _stream(chats, chats.bob, {"gone-room": 3}, recheck=60.0)+ assert await events.next() == (+ "chat.removed",+ {"roomId": "gone-room", "reason": "access"},+ )+ assert (await events.next())[0] == "ready"++ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )++ # Nothing more about the room reaches someone no longer in it.+ assert (await chats.send(chats.alice, room_id, "s1", "secret")).status_code == 200+ await chats.listener.ring(room_id)+ with pytest.raises(TimeoutError):+ await events.next(timeout=0.3)+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_the_stream_ends_when_the_tenant_role_is_gone(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 session.execute(+ delete(TenantMember).where(TenantMember.user_id == chats.bob.id)+ )+ await session.commit()+ await chats.listener.ring(room_id)+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )+ with pytest.raises(StopAsyncIteration):+ await anext(events.stream)+++async def test_an_invited_member_keeps_a_chat_that_loses_its_last_agent(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.bob)+ room_id = await _room(chats, [agent], owner=chats.alice)+ assert room_id not in await _listed(chats, chats.bob)+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200++ events = _stream(chats, chats.bob, {}, recheck=0.2)+ assert (await events.next())[0] == "chat"+ assert (await events.next())[0] == "ready"++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "unlisted"},+ )+ assert await _reads(chats, chats.bob, room_id) == 200+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_unlisted_room_still_delivers_messages_to_invited_member(+ 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"++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "unlisted"},+ )++ assert (+ await chats.send(chats.alice, room_id, "s1", "hello after unlisted")+ ).status_code == 200+ await chats.listener.ring(room_id)+ name, data = await events.next()+ assert name == "message" and data["body"] == "hello after unlisted"+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_unlisted_then_revoked_room_emits_access_removal(+ 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"++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "unlisted"},+ )++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )++ assert (await chats.send(chats.alice, room_id, "s1", "secret")).status_code == 200+ await chats.listener.ring(room_id)+ with pytest.raises(TimeoutError):+ await events.next(timeout=0.3)+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_an_unlisted_chat_is_announced_again_when_an_agent_returns(+ 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"++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "unlisted"},+ )++ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id+ assert room_id in await _listed(chats, chats.bob)+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_the_periodic_recheck_announces_a_chat_that_regains_an_agent(+ 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+ async with chats.factory() as session:+ await session.execute(+ delete(room_agents).where(room_agents.c.room_id == room_id)+ )+ await session.commit()++ events = _stream(chats, chats.bob, {room_id: 0}, recheck=0.2)+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "unlisted"},+ )+ assert (await events.next())[0] == "ready"++ # Written straight to the table, as another process would: no hook runs.+ async with chats.factory() as session:+ await session.execute(+ room_agents.insert().values(room_id=room_id, agent_id=agent.id)+ )+ await session.commit()+ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_an_owner_only_member_loses_access_with_the_last_agent(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.bob)+ room_id = await _left_chat(chats, chats.bob)+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ assert room_id in await _listed(chats, chats.bob)++ events = _stream(chats, chats.bob, {}, recheck=60.0)+ assert (await events.next())[0] == "chat"+ assert (await events.next())[0] == "ready"++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )+ assert await _reads(chats, chats.bob, room_id) == 403+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_archiving_a_chat_removes_it_for_access(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=0.2)+ assert (await events.next())[0] == "chat"+ assert (await events.next())[0] == "ready"++ archived = await chats.client.post(+ f"/chats/{room_id}/archive", headers=chats.as_user(chats.alice)+ )+ assert archived.status_code == 204+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_the_periodic_recheck_recovers_a_missed_notification(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ events = _stream(chats, chats.alice, {room_id: 0}, recheck=0.2)+ assert (await events.next())[0] == "ready"++ # Written without ringing the listener: the notification never arrives.+ assert (+ await chats.send(chats.alice, room_id, "s1", "unannounced")+ ).status_code == 200+ name, data = await events.next()+ assert name == "message" and data["body"] == "unannounced"+ await events.stream.aclose() # type: ignore[attr-defined]+++# ── Agent owners ─────────────────────────────────────────────────────────────++TENANT = "00000000-0000-0000-0000-000000000000"+++async def _room(+ chats: _Harness,+ agents: list[Agent],+ *,+ name: str = "room",+ owner: User | None = None,+ bridge: str | None = None,+ channel_type: str = "channel_public",+ archived: bool = False,+) -> str:+ """A room someone else set up, holding `agents`, with no member clients."""+ async with chats.factory() as session:+ bridge_id: str | None = None+ if bridge is not None:+ bridge_client = Client(+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.test",+ display_name="bridge",+ type="bridge",+ )+ session.add(bridge_client)+ await session.flush()+ row = CollaborationBridge(+ type=bridge,+ display_name="Acme",+ client_id=bridge_client.id,+ status="active",+ )+ session.add(row)+ await session.flush()+ bridge_id = row.id+ room = Room(+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name=f"Acme: {name}" if bridge is not None else name,+ description="",+ owner_id=(owner or chats.bob).id,+ read_visibility="private",+ write_visibility="private",+ bridge_id=bridge_id,+ external_channel_id=f"C{uuid.uuid4().hex[:6]}" if bridge else None,+ channel_type=channel_type,+ archived_at=datetime.now(UTC) if archived else None,+ )+ session.add(room)+ await session.flush()+ for agent in agents:+ await session.execute(+ room_agents.insert().values(room_id=room.id, agent_id=agent.id)+ )+ await session.commit()+ return room.id+++async def _listed(chats: _Harness, user: User) -> dict[str, dict[str, Any]]:+ response = await chats.client.get("/chats", headers=chats.as_user(user))+ assert response.status_code == 200, response.text+ return {chat["roomId"]: chat for chat in response.json()["chats"]}+++async def _reads(chats: _Harness, user: User, room_id: str) -> int:+ response = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(user)+ )+ return response.status_code+++async def _left_chat(chats: _Harness, user: User) -> str:+ """A chat `user` started with someone else's agent, then left."""+ guest = await chats.agent(f"guest-{uuid.uuid4().hex[:8]}", owner=chats.admin)+ room_id = await chats.new_chat(user, guest, uuid.uuid4().hex)+ left = await chats.client.delete(+ f"/chats/{room_id}/members/{user.id}", headers=chats.as_user(user)+ )+ assert left.status_code == 204, left.text+ return room_id+++async def _grants(chats: _Harness) -> int:+ async with chats.factory() as session:+ return int(+ await session.scalar(select(func.count()).select_from(ChatOwnerGrant)) or 0+ )+++async def test_an_agent_owner_is_not_joined_to_bridged_rooms_holding_their_agent(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ channel = await _room(chats, [agent], name="general", bridge="slack")+ dm = await _room(chats, [agent], name="dm", bridge="discord", channel_type="direct")++ assert await _reads(chats, chats.alice, channel) == 403+ assert await _reads(chats, chats.alice, dm) == 403+ assert await _listed(chats, chats.alice) == {}+ await chats.room_service.room_agents_changed(TENANT, channel)+ assert await _listed(chats, chats.alice) == {}+ assert await _grants(chats) == 0+++async def _grant_as_before(chats: _Harness, user: User, room_id: str) -> None:+ """An owner membership made by the earlier, wider rule."""+ client = await chats.service.member_actor(TENANT, user)+ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None+ session.add(ChatOwnerGrant(tenant_id=TENANT, user_id=user.id, room_id=room_id))+ await session.commit()+ await chats.service._join(TENANT, room, client)+++async def _in_room(chats: _Harness, user: User, room_id: str) -> bool:+ async with chats.factory() as session:+ client = await chats.service.member_client(session, user.id)+ assert client is not None+ return await chats.service._is_in_room(session, client.id, room_id)+++async def test_an_owner_grant_on_a_bridged_room_is_taken_back(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ channel = await _room(chats, [agent], name="general", bridge="slack")+ await _grant_as_before(chats, chats.alice, channel)+ assert await _in_room(chats, chats.alice, channel)++ assert await _listed(chats, chats.alice) == {}+ assert not await _in_room(chats, chats.alice, channel)+ assert await _reads(chats, chats.alice, channel) == 403+ assert await _grants(chats) == 0+++async def test_with_agent_chats_off_owner_grants_are_taken_back(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ assert await _grants(chats) == 1++ chats.service.agent_chats_enabled = False+ assert await _listed(chats, chats.alice) == {}+ assert not await _in_room(chats, chats.alice, room_id)+ assert await _grants(chats) == 0+++async def test_an_agent_owner_is_not_joined_to_someone_elses_chat(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.bob, agent, "c1")++ assert room_id not in await _listed(chats, chats.alice)+ assert await _reads(chats, chats.alice, room_id) == 403+ assert await _grants(chats) == 0++ assert (await chats.invite(chats.bob, room_id, chats.alice)).status_code == 200+ assert room_id in await _listed(chats, chats.alice)+ left = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.alice.id}",+ headers=chats.as_user(chats.alice),+ )+ assert left.status_code == 204+++async def test_with_agent_chats_off_owning_an_agent_joins_nothing(+ chats: _Harness,+) -> None:+ chats.service.agent_chats_enabled = False+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])++ assert await _listed(chats, chats.alice) == {}+ assert await _reads(chats, chats.alice, room_id) == 403+ assert await _grants(chats) == 0+++async def test_an_agent_owner_rejoins_a_chat_they_started_when_their_agent_arrives(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ assert await _reads(chats, chats.alice, room_id) == 403++ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ listed = await _listed(chats, chats.alice)+ assert set(listed) == {room_id}+ assert listed[room_id]["ownsAgent"] is True+ assert await _reads(chats, chats.alice, room_id) == 200+ assert await _grants(chats) == 1+++async def test_owning_an_agent_in_an_archived_room_grants_nothing(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _room(chats, [agent], archived=True)++ assert await _listed(chats, chats.alice) == {}+ assert await _reads(chats, chats.alice, room_id) == 403+++async def test_owner_membership_is_granted_once(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ async with chats.factory() as session:+ await session.execute(+ room_agents.insert().values(room_id=room_id, agent_id=agent.id)+ )+ await session.commit()++ for _ in range(3):+ assert set(await _listed(chats, chats.alice)) == {room_id}+ assert await _reads(chats, chats.alice, room_id) == 200++ async with chats.factory() as session:+ client = await chats.service.member_client(session, chats.alice.id)+ assert client is not None+ memberships = await session.scalar(+ select(func.count())+ .select_from(ClientRoom)+ .where(ClientRoom.client_id == client.id)+ )+ arrivals = await session.scalar(+ select(func.count())+ .select_from(Message)+ .where(+ Message.room_id == room_id,+ Message.sender_client_id == client.id,+ Message.event_type == "m.room.member",+ )+ )+ # One arrival from starting the chat, one from the owner rejoin.+ assert (memberships, arrivals, await _grants(chats)) == (1, 2, 1)+++async def test_a_room_that_gains_the_owners_agent_is_announced_at_once(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)++ events = _stream(chats, chats.alice, {}, recheck=60.0)+ assert (await events.next())[0] == "ready"++ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id+ assert await _reads(chats, chats.alice, room_id) == 200++ await chats.room_service.remove_agents_from_room(room_id, [agent.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )+ assert await _reads(chats, chats.alice, room_id) == 403+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_the_periodic_recheck_finds_a_chat_the_agent_joined_elsewhere(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)++ events = _stream(chats, chats.alice, {}, recheck=0.2)+ assert (await events.next())[0] == "ready"++ # Written straight to the table, as another process would: no hook runs.+ async with chats.factory() as session:+ await session.execute(+ room_agents.insert().values(room_id=room_id, agent_id=agent.id)+ )+ await session.commit()+ name, summary = await events.next()+ assert name == "chat" and summary["roomId"] == room_id+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_an_agent_owner_cannot_leave_or_be_removed(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await _listed(chats, chats.alice))[room_id]["ownsAgent"] is True++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.alice.id}",+ headers=chats.as_user(chats.admin),+ )+ assert removed.status_code == 409+ assert _code(removed) == "AGENT_OWNER"+ left = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.alice.id}",+ headers=chats.as_user(chats.alice),+ )+ assert left.status_code == 409+ assert _code(left) == "AGENT_OWNER"+ assert "remove it from your list" in left.json()["detail"]["message"]++ hidden = await chats.client.put(+ f"/chats/{room_id}/hidden", headers=chats.as_user(chats.alice)+ )+ assert hidden.status_code == 204+ assert room_id not in await _listed(chats, chats.alice)+ assert await _reads(chats, chats.alice, room_id) == 200+++async def test_losing_the_last_owned_agent_ends_the_owners_access(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ await chats.room_service.add_agents_to_room(+ room_id, agent_ids=[helper.id, other.id]+ )+ assert room_id in await _listed(chats, chats.alice)++ events = _stream(chats, chats.alice, {}, recheck=60.0)+ assert (await events.next())[0] == "chat"+ assert (await events.next())[0] == "ready"++ # One of two owned agents gone: still a member, and nothing is announced.+ await chats.room_service.remove_agents_from_room(room_id, [helper.id])+ assert await _reads(chats, chats.alice, room_id) == 200++ await chats.room_service.remove_agents_from_room(room_id, [other.id])+ assert await events.next() == (+ "chat.removed",+ {"roomId": room_id, "reason": "access"},+ )+ assert await _reads(chats, chats.alice, room_id) == 403+ assert await _listed(chats, chats.alice) == {}+ assert await _grants(chats) == 0+ await events.stream.aclose() # type: ignore[attr-defined]+++async def test_handing_an_agent_to_someone_else_ends_the_owners_access(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ assert room_id in await _listed(chats, chats.alice)++ async with chats.factory() as session:+ row = await session.get(Agent, agent.id)+ assert row is not None+ row.owner_id = chats.bob.id+ await session.commit()++ assert await _listed(chats, chats.alice) == {}+ assert await _reads(chats, chats.alice, room_id) == 403+ # Not a chat Bob started, so the new owner is not joined either.+ assert await _listed(chats, chats.bob) == {}+ assert await _reads(chats, chats.bob, room_id) == 403+++async def test_a_deleted_agent_takes_its_owners_access_with_it(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])+ assert room_id in await _listed(chats, chats.alice)++ async with chats.factory() as session:+ await AgentStore().delete(session, agent.id)+ await session.commit()+ await chats.room_service.room_agents_changed(TENANT, room_id)++ assert await _reads(chats, chats.alice, room_id) == 403+++async def test_an_owner_who_created_the_chat_keeps_it_when_the_agent_goes(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.bob)+ room_id = await chats.new_chat(chats.alice, helper, "c1")+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[other.id])+ await chats.room_service.remove_agents_from_room(room_id, [helper.id])++ assert await _reads(chats, chats.alice, room_id) == 200+++# ── Turn activity and approval requests ──────────────────────────────────────+++async def _step(+ chats: _Harness, agent: Agent, room_id: str, turn_id: str, item_id: str, rev: int+) -> None:+ async with chats.factory() as session:+ await session.merge(+ AgentSessionActivityItem(+ tenant_id="00000000-0000-0000-0000-000000000000",+ agent_id=agent.id,+ session_id="s1",+ turn_id=turn_id,+ item_id=item_id,+ kind="turn" if item_id == "turn" else "tool-activity",+ revision=rev,+ status="running" if item_id == "turn" else "in-progress",+ title=f"{item_id} r{rev}",+ text="",+ room_id=room_id,+ occurred_at=datetime.now(UTC),+ )+ )+ await session.commit()+++async def _request(+ chats: _Harness, agent: Agent, room_id: str, request_id: str, state: str+) -> None:+ async with chats.factory() as session:+ session.add(+ ApprovalRequest(+ tenant_id="00000000-0000-0000-0000-000000000000",+ agent_id=agent.id,+ session_id="s1",+ request_id=request_id,+ turn_id="t1",+ kind="approval",+ room_id=room_id,+ title="Run it?",+ options=[{"id": "y", "label": "Yes", "decision": "accept"}],+ questions=[],+ state=state,+ answer="y" if state == "answered" else None,+ )+ )+ await session.commit()+++def _turn_change(agent: Agent, turn_id: str) -> Change:+ return Change(+ kind="activity",+ tenant_id="00000000-0000-0000-0000-000000000000",+ agent_id=agent.id,+ session_id="s1",+ key=turn_id,+ row=None,+ )+++def _activity_stream(+ chats: _Harness, user: User, queue_max: int = 64, ping_seconds: float = 60.0+) -> _Events:+ return _Events(+ chat_activity_events(+ chats.service,+ "00000000-0000-0000-0000-000000000000",+ user,+ ping_seconds=ping_seconds,+ queue_max=queue_max,+ )+ )+++async def test_room_activity_is_the_rooms_steps_and_requests_in_every_state(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ mine = await chats.new_chat(chats.alice, agent, "c1")+ other_agent = await chats.agent("other", owner=chats.bob)+ other = await chats.new_chat(chats.bob, other_agent, "c2")+ await _step(chats, agent, mine, "t1", "turn", 1)+ await _step(chats, agent, mine, "t1", "tool-1", 2)+ await _step(chats, other_agent, other, "t9", "turn", 1)+ await _request(chats, agent, mine, "r-open", "open")+ await _request(chats, agent, mine, "r-done", "answered")+ await _request(chats, other_agent, other, "r-other", "open")++ response = await chats.client.get(+ f"/chats/{mine}/activity", headers=chats.as_user(chats.alice)+ )+ assert response.status_code == 200, response.text+ body = response.json()+ assert [(i["turnId"], i["itemId"], i["revision"]) for i in body["items"]] == [+ ("t1", "turn", 1),+ ("t1", "tool-1", 2),+ ]+ assert {(a["requestId"], a["state"]) for a in body["approvals"]} == {+ ("r-open", "open"),+ ("r-done", "answered"),+ }++ refused = await chats.client.get(+ f"/chats/{mine}/activity", headers=chats.as_user(chats.bob)+ )+ assert refused.status_code == 403+++async def test_room_activity_keeps_open_requests_past_retention(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ await _request(chats, agent, room_id, "r-old-open", "open")+ await _request(chats, agent, room_id, "r-old-done", "answered")+ async with chats.factory() as session:+ await session.execute(+ update(ApprovalRequest).values(+ updated_at=datetime.now(UTC) - timedelta(days=8)+ )+ )+ await session.commit()++ response = await chats.client.get(+ f"/chats/{room_id}/activity", headers=chats.as_user(chats.alice)+ )+ assert response.status_code == 200, response.text+ assert [a["requestId"] for a in response.json()["approvals"]] == ["r-old-open"]+++async def test_the_activity_stream_sends_only_readable_rooms_and_moved_steps(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ other_agent = await chats.agent("other", owner=chats.alice)+ hidden = await chats.new_chat(chats.alice, other_agent, "c2")+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200++ events = _activity_stream(chats, chats.bob)+ assert (await events.next())[0] == "ready"++ await _step(chats, agent, room_id, "t1", "turn", 1)+ await chats.activity.change(_turn_change(agent, "t1"))+ name, item = await events.next()+ assert name == "activity" and item["roomId"] == room_id and item["revision"] == 1++ # A reread of the turn resends only the step that moved.+ await _step(chats, agent, room_id, "t1", "tool-1", 1)+ await chats.activity.change(_turn_change(agent, "t1"))+ name, item = await events.next()+ assert (name, item["itemId"]) == ("activity", "tool-1")++ # A room the reader is not in is never sent: the next frame is the request.+ await _step(chats, other_agent, hidden, "t2", "turn", 1)+ await chats.activity.change(_turn_change(other_agent, "t2"))+ await _request(chats, agent, room_id, "r1", "answered")+ await chats.activity.change(+ Change(+ kind="approval.answered",+ tenant_id="00000000-0000-0000-0000-000000000000",+ agent_id=agent.id,+ session_id="s1",+ key="r1",+ row=None,+ )+ )+ name, request = await events.next()+ assert (name, request["requestId"], request["state"]) == (+ "approval",+ "r1",+ "answered",+ )++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ await _step(chats, agent, room_id, "t1", "turn", 2)+ await chats.activity.change(_turn_change(agent, "t1"))+ with pytest.raises(TimeoutError):+ await events.next(timeout=0.3)+ await events.stream.aclose() # type: ignore[attr-defined]+ assert chats.activity.subscribers == []+++async def test_the_activity_stream_says_resync_when_changes_may_be_lost(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ await _step(chats, agent, room_id, "t1", "turn", 1)++ events = _activity_stream(chats, chats.alice, queue_max=2)+ assert (await events.next())[0] == "ready"++ await chats.activity.resync()+ assert await events.next() == ("resync", {})++ # Falling behind drops what was queued and asks for a reload instead.+ for _ in range(3):+ await chats.activity.change(_turn_change(agent, "t1"))+ assert await events.next() == ("resync", {})+ with pytest.raises(TimeoutError):+ await events.next(timeout=0.3)+ await events.stream.aclose() # type: ignore[attr-defined]+++async def _drop_tenant_role(chats: _Harness, user: User) -> None:+ async with chats.factory() as session:+ await session.execute(+ delete(TenantMember).where(TenantMember.user_id == user.id)+ )+ await session.commit()+++async def test_the_activity_stream_ends_when_the_tenant_role_is_gone(+ 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++ on_change = _activity_stream(chats, chats.bob)+ assert (await on_change.next())[0] == "ready"+ on_ping = _activity_stream(chats, chats.bob, ping_seconds=0.05)+ assert (await on_ping.next())[0] == "ready"++ await _drop_tenant_role(chats, chats.bob)+ await _step(chats, agent, room_id, "t1", "turn", 1)+ await chats.activity.change(_turn_change(agent, "t1"))+ with pytest.raises(StopAsyncIteration):+ await on_change.next()+ with pytest.raises(StopAsyncIteration):+ await on_ping.next()+ assert chats.activity.subscribers == []+++async def test_the_activity_stream_forgets_revisions_past_its_cap(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(chats_module, "_ACTIVITY_SENT_MAX", 1)+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ events = _activity_stream(chats, chats.alice)+ assert (await events.next())[0] == "ready"++ await _step(chats, agent, room_id, "t1", "turn", 1)+ await _step(chats, agent, room_id, "t1", "tool-1", 1)+ await chats.activity.change(_turn_change(agent, "t1"))+ assert [(await events.next())[1]["itemId"] for _ in range(2)] == ["turn", "tool-1"]++ # Over the cap, the next reread starts from nothing and resends the turn.+ await chats.activity.change(_turn_change(agent, "t1"))+ assert [(await events.next())[1]["itemId"] for _ in range(2)] == ["turn", "tool-1"]+ await events.stream.aclose() # type: ignore[attr-defined]diff --git a/core/tests/switch_core/gateway/test_chats_warm.py b/core/tests/switch_core/gateway/test_chats_warm.pynew file mode 100644index 000000000..c90c28741--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_warm.py@@ -0,0 +1,89 @@+"""`POST /chats/{room_id}/warm`: Switch Console asks the controller of the+user's own agent to start its session while the user types."""++from __future__ import annotations++import httpx++from switch_core.db.models import Agent, User+from tests.switch_core.gateway.conftest import _Harness+from tests.switch_core.gateway.test_chats_routes import _code+++async def _warm(+ chats: _Harness, user: User, room_id: str, agent: Agent+) -> httpx.Response:+ return await chats.client.post(+ f"/chats/{room_id}/warm",+ json={"agentId": agent.id},+ headers=chats.as_user(user),+ )+++async def test_a_warm_reaches_the_agents_controller(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ chats.controllers.bound.add(agent.id)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ response = await _warm(chats, chats.alice, room_id, agent)++ assert response.status_code == 202, response.text+ assert chats.controllers.warms == [(agent.id, room_id)]+++async def test_a_warm_is_accepted_when_no_controller_takes_it(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ unbound = await _warm(chats, chats.alice, room_id, agent)+ chats.controllers.bound.add(agent.id)+ chats.controllers.live = False+ offline = await _warm(chats, chats.alice, room_id, agent)++ assert unbound.status_code == offline.status_code == 202+ assert chats.controllers.warms == []+++async def test_a_warm_refuses_non_members_others_agents_and_absent_agents(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ chats.controllers.bound.add(agent.id)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ outsider = await _warm(chats, chats.bob, room_id, agent)+ assert outsider.status_code == 403+ assert _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+ assert _code(absent) == "AGENT_NOT_IN_CHAT"++ assert chats.controllers.warms == []+++async def test_a_warm_refuses_an_owner_the_agents_policy_refuses(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ chats.controllers.bound.add(agent.id)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ async with chats.factory() as session:+ row = await session.get(Agent, agent.id)+ assert row is not None+ row.addressing_policy = {"rules": [{"users": [], "agents": []}]}+ await session.commit()++ refused = await _warm(chats, chats.alice, room_id, agent)++ assert refused.status_code == 403+ assert _code(refused) == "AGENT_NOT_ALLOWED"+ assert chats.controllers.warms == []diff --git a/core/tests/switch_core/management/test_contract_fixtures.py b/core/tests/switch_core/management/test_contract_fixtures.pyindex ced812daf..4095c524b 100644--- a/core/tests/switch_core/management/test_contract_fixtures.py+++ b/core/tests/switch_core/management/test_contract_fixtures.py@@ -411,6 +411,9 @@ class TestStreamFrames:)provoked += await take(stream, 1)+ assert presence.relay_warm(agent_id, room_id)+ provoked += await take(stream, 1)+other_room = await add_room(harness.session_factory, agent_id, name="new")presence.room_joined(agent_id, other_room)provoked += await take(stream, 1)diff --git a/core/tests/switch_core/management/test_stream.py b/core/tests/switch_core/management/test_stream.pyindex 753a7301e..0abd54270 100644--- a/core/tests/switch_core/management/test_stream.py+++ b/core/tests/switch_core/management/test_stream.py@@ -379,6 +379,27 @@ class TestLiveChanges:{"agent_id": agent_id, "room_id": room_id, "command": command},)+ async def test_a_warm_reaches_the_stream_once_per_room(+ self, harness: Harness+ ) -> None:+ owner = await add_member(harness.session_factory, "ada")+ async with harness.client() as client:+ controller = await enroll_console(harness, client, owner)+ agent_id = await place_agent(client, controller, name="reviewer")+ room_id = await add_room(harness.session_factory, agent_id)+ opened = await open_connection(client, controller)+ stream = await open_stream(harness, controller, opened)+ await take(stream, 2)++ presence = harness.protocol.connections.controllers+ assert presence.relay_warm(agent_id, room_id)+ assert presence.relay_warm(agent_id, room_id)+ (frame,) = await take(stream, 1)+ assert not presence.relay_warm("not-bound", room_id)+ await stream.aclose()++ assert frame == ("agent.warm", {"agent_id": agent_id, "room_id": room_id})+async def test_the_nudges_are_merged_and_revocation_ends_the_stream(self, harness: Harness) -> None:diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 2d7346f0b..a744625e9 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -389,7 +389,7 @@ switchCore:# ["ecosystem.show_owners"]. Every other flag is off, and no one can change# them while the server runs. An unknown flag stops switch-core at startup.# Known flags: ecosystem.show_owners, agent_management, switch_cloud,- # hosted_agents, service_connections.+ # hosted_agents, service_connections, agent_chats.featureFlags:enabled: []# Invitation e-mails. When enabled, an invitation addressed to an e-mail is