Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix: console sidebar/titlebar polish, and thread the Mattermost status (CHOO-2173) (#243)
Louis Amaudruz1323f93e357f
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.tsindex db0653cd9..53da2b1eb 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts@@ -50,9 +50,12 @@ function makePty(): {};}+let onOpenForInjection: ReturnType<typeof vi.fn<() => void>>;+describe('scheduleInitialPromptInjection', () => {beforeEach(() => {vi.useFakeTimers();+ onOpenForInjection = vi.fn();});afterEach(() => {@@ -66,6 +69,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});emitData('booting...');@@ -84,6 +88,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});vi.advanceTimersByTime(15_000);@@ -97,6 +102,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: 'line one\nline two',isResuming: false,+ onOpenForInjection,});emitData('ready');@@ -111,6 +117,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('opencode'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});emitData('ready');@@ -125,6 +132,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('grok'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});emitData('ready');@@ -139,6 +147,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('claude'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});emitData('ready');@@ -153,6 +162,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: 'Fix the bug',isResuming: true,+ onOpenForInjection,});emitData('ready');@@ -167,6 +177,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: ' ',isResuming: false,+ onOpenForInjection,});emitData('ready');@@ -181,6 +192,7 @@ describe('scheduleInitialPromptInjection', () => {session: makeSession('hermes'),initialPrompt: 'Fix the bug',isResuming: false,+ onOpenForInjection,});emitData('starting');@@ -189,3 +201,157 @@ describe('scheduleInitialPromptInjection', () => {expect(write).not.toHaveBeenCalled();});});++/**+ * When the pane becomes free for anything else to type into (CHOO-2173).+ *+ * A session auto-started to answer a room message races two writers at the same+ * terminal: its own opening prompt, held back until the TUI is ready, and the+ * room message its connection has already received. Nothing sequenced them, and+ * a message typed into a booting TUI — or onto the end of the unsent opening+ * prompt — reads as a message that never arrived.+ */+describe('the gate on typing into a starting session', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ onOpenForInjection = vi.fn();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('stays shut while the opening prompt is still waiting for the TUI', () => {+ const { pty, emitData } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('hermes'),+ initialPrompt: 'connect to switch room r-1',+ isResuming: false,+ onOpenForInjection,+ });++ emitData('booting...');+ vi.advanceTimersByTime(200);++ expect(onOpenForInjection).not.toHaveBeenCalled();+ });++ it('opens as the opening prompt goes in, and not before', () => {+ const { pty, write, emitData } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('hermes'),+ initialPrompt: 'connect to switch room r-1',+ isResuming: false,+ onOpenForInjection,+ });++ emitData('ready');+ vi.advanceTimersByTime(200);+ expect(write).not.toHaveBeenCalled();+ expect(onOpenForInjection).not.toHaveBeenCalled();++ vi.advanceTimersByTime(800);++ expect(write).toHaveBeenCalled();+ expect(onOpenForInjection).toHaveBeenCalledTimes(1);+ });++ it('still waits for the TUI when the prompt went on the command line', () => {+ // The bug the first attempt at this missed: Claude and Codex take their+ // opening prompt as an argv flag, so there is nothing to type and the gate+ // used to open the instant the pty registered — straight into a booting+ // TUI, which is exactly the case that matters, since those are the+ // providers auto-started sessions actually run.+ const { pty, write, emitData } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('claude'),+ initialPrompt: 'connect to switch room r-1',+ isResuming: false,+ onOpenForInjection,+ });++ expect(onOpenForInjection).not.toHaveBeenCalled();++ emitData('booting...');+ vi.advanceTimersByTime(200);+ expect(onOpenForInjection).not.toHaveBeenCalled();++ vi.advanceTimersByTime(800);++ expect(onOpenForInjection).toHaveBeenCalledTimes(1);+ // Nothing typed — the prompt was already on the command line.+ expect(write).not.toHaveBeenCalled();+ });++ it('waits for the TUI when there is no opening prompt at all', () => {+ const { pty, emitData } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('hermes'),+ initialPrompt: undefined,+ isResuming: false,+ onOpenForInjection,+ });++ expect(onOpenForInjection).not.toHaveBeenCalled();++ emitData('ready');+ vi.advanceTimersByTime(800);++ expect(onOpenForInjection).toHaveBeenCalledTimes(1);+ });++ it('waits for the TUI when resuming, which sends no prompt', () => {+ const { pty, write, emitData } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('hermes'),+ initialPrompt: 'Fix the bug',+ isResuming: true,+ onOpenForInjection,+ });++ emitData('ready');+ vi.advanceTimersByTime(800);++ expect(onOpenForInjection).toHaveBeenCalledTimes(1);+ expect(write).not.toHaveBeenCalled();+ });++ it('opens on the long-stop when the TUI never says anything', () => {+ // A pane that produces no output at all must not strand every room message+ // for the life of the session.+ const { pty } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('claude'),+ initialPrompt: 'connect to switch room r-1',+ isResuming: false,+ onOpenForInjection,+ });++ vi.advanceTimersByTime(15_000);++ expect(onOpenForInjection).toHaveBeenCalledTimes(1);+ });++ it('never opens a pane whose process has gone', () => {+ const { pty, emitData, emitExit } = makePty();+ scheduleInitialPromptInjection({+ pty,+ session: makeSession('claude'),+ initialPrompt: 'connect to switch room r-1',+ isResuming: false,+ onOpenForInjection,+ });++ emitData('starting');+ emitExit();+ vi.advanceTimersByTime(20_000);++ expect(onOpenForInjection).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.tsindex 27a4a1d0c..1a70a27ae 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts@@ -9,64 +9,114 @@ import { buildPromptInjectionPayload } from '@shared/prompt-injection';const QUIET_PERIOD_MS = 800;const MAX_WAIT_MS = 15_000;+/**+ * Wait for a session's TUI to settle, deliver its opening prompt if that prompt+ * is delivered by typing, and then declare the pane free for anything else.+ *+ * Two jobs, because they share one signal. Most providers take their opening+ * prompt on the command line (`argv`) rather than through the keyboard, so+ * there is nothing to type — but a room message still must not be typed into a+ * TUI that is mid-boot, and "the TUI has gone quiet" is the only readiness+ * signal there is. So the wait happens either way and only the injection is+ * conditional.+ */export function scheduleInitialPromptInjection(args: {pty: Pty;session: Session;initialPrompt: string | undefined;isResuming: boolean;+ /**+ * Called once the pane is ready to be typed into and the session's own+ * opening prompt (if it had one to type) is in. Room messages wait on this:+ * delivered any earlier they land in a booting TUI, or in the middle of the+ * prompt being typed. Not called at all if the pty exits first.+ */+ onOpenForInjection: () => void;}): void {- if (args.isResuming) return;- if (!args.initialPrompt?.trim()) return;-const plugin = getPlugin(args.session.providerId);const promptDelivery = plugin.capabilities.prompt;- if (promptDelivery.kind !== 'keystroke') return;-- const submitSequence = promptDelivery.submitSequence ?? '\r';- const submitDelayMs = promptDelivery.submitDelayMs;-- const payload = buildPromptInjectionPayload(args.initialPrompt);+ // Only a keystroke provider has a prompt for us to type. Elsewhere it went+ // on the command line, or there is none, or the session is being resumed and+ // is picking up where it left off.+ const promptToType =+ !args.isResuming && args.initialPrompt?.trim() && promptDelivery.kind === 'keystroke'+ ? args.initialPrompt+ : null;- let injected = false;+ let done = false;let sawAnyOutput = false;let quietTimer: ReturnType<typeof setTimeout> | null = null;- const inject = () => {- if (injected) return;- injected = true;+ const open = (reason: string) => {+ log.info('AgentRuntime: session open for injected prompts', {+ event: 'switch_session_open_for_injection',+ providerId: args.session.providerId,+ sessionId: args.session.id,+ typedOpeningPrompt: promptToType !== null,+ reason,+ });+ args.onOpenForInjection();+ };++ const ready = () => {+ if (done) return;+ done = true;if (quietTimer) clearTimeout(quietTimer);clearTimeout(maxWaitTimer);+ const reason = sawAnyOutput ? 'tui-quiet' : 'max-wait';++ if (promptToType === null) {+ open(reason);+ return;+ }++ const submitSequence =+ promptDelivery.kind === 'keystroke' ? (promptDelivery.submitSequence ?? '\r') : '\r';+ const submitDelayMs =+ promptDelivery.kind === 'keystroke' ? promptDelivery.submitDelayMs : undefined;+ const payload = buildPromptInjectionPayload(promptToType);+try {if (submitDelayMs) {args.pty.write(payload);- setTimeout(() => args.pty.write(submitSequence), submitDelayMs);+ // Opened after the submit, not after the text: in between, the prompt+ // is sitting unsent in the composer and anything else typed would be+ // appended to it and sent as one.+ setTimeout(() => {+ args.pty.write(submitSequence);+ open(reason);+ }, submitDelayMs);return;}args.pty.write(`${payload}${submitSequence}`);+ open(reason);} catch (error) {log.warn('AgentRuntime: failed to inject initial prompt', {providerId: args.session.providerId,sessionId: args.session.id,error: String(error),});+ // The pane is no worse off for a write that failed, and holding the gate+ // shut would strand every room message for the life of the session.+ open('initial-prompt-failed');}};- const maxWaitTimer = setTimeout(inject, MAX_WAIT_MS);+ const maxWaitTimer = setTimeout(ready, MAX_WAIT_MS);args.pty.onData(() => {- if (injected) return;+ if (done) return;sawAnyOutput = true;if (quietTimer) clearTimeout(quietTimer);- quietTimer = setTimeout(inject, QUIET_PERIOD_MS);+ quietTimer = setTimeout(ready, QUIET_PERIOD_MS);});args.pty.onExit(() => {- const promptWasInjected = injected;- injected = true;+ const settled = done;+ done = true;if (quietTimer) clearTimeout(quietTimer);clearTimeout(maxWaitTimer);- if (!promptWasInjected) {+ if (!settled && promptToType !== null) {log.warn('AgentRuntime: PTY exited before initial prompt could be injected', {providerId: args.session.providerId,sessionId: args.session.id,diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex e856a9c1b..1b083826e 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -332,6 +332,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {session,initialPrompt,isResuming: agentSession.isResuming,+ onOpenForInjection: () => ptySessionRegistry.markOpenForInjection(ptySessionId),});// If this session was connected to a Switch room before an app restart,// resume polling that room — the connect_to_room hook only fires on adiff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 63451da3a..7fa57ffa3 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -909,6 +909,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimesession,initialPrompt,isResuming: agentSession.isResuming,+ onOpenForInjection: () => ptySessionRegistry.markOpenForInjection(ptySessionId),});} catch (error) {this.supervisor.failSpawn(spawnToken);diff --git a/console/apps/switch-console-desktop/src/main/core/pty/pty-session-registry.ts b/console/apps/switch-console-desktop/src/main/core/pty/pty-session-registry.tsindex 35ae596c6..0c0149c6f 100644--- a/console/apps/switch-console-desktop/src/main/core/pty/pty-session-registry.ts+++ b/console/apps/switch-console-desktop/src/main/core/pty/pty-session-registry.ts@@ -21,6 +21,7 @@ export class PtySessionRegistry {private metadata: Map<string, PtySessionMetadata> = new Map();private lastSizes: Map<string, { cols: number; rows: number }> = new Map();private pendingFlushes: Map<string, () => void> = new Map();+ private openForInjection: Set<string> = new Set();register(sessionId: string,@@ -36,6 +37,7 @@ export class PtySessionRegistry {this.ringBuffers.delete(sessionId);this.activeConsumers.delete(sessionId);this.metadata.delete(sessionId);+ this.openForInjection.delete(sessionId);if (options?.metadata) this.metadata.set(sessionId, options.metadata);this.ptyMap.set(sessionId, pty);@@ -136,6 +138,7 @@ export class PtySessionRegistry {this.ringBuffers.delete(sessionId);this.activeConsumers.delete(sessionId);this.metadata.delete(sessionId);+ this.openForInjection.delete(sessionId);if (!options.preserveSize) this.lastSizes.delete(sessionId);}@@ -143,6 +146,29 @@ export class PtySessionRegistry {return this.ptyMap.get(sessionId);}+ /**+ * Declare that the session's own opening prompt is in, so anything else may+ * now type into it.+ *+ * A session is launched with a prompt of its own and a TUI that is not ready+ * for it for a second or two, and the runtime holds that prompt back until it+ * is. Meanwhile a room message can arrive — an auto-started session is+ * answering one, and its room connection opens before the terminal exists.+ * Writing it on arrival puts it into a booting TUI, or interleaves it with+ * the opening prompt; both read as the message never arriving.+ *+ * Cleared whenever the pty is registered or torn down, so a respawned session+ * starts closed again.+ */+ markOpenForInjection(sessionId: string): void {+ this.openForInjection.add(sessionId);+ }++ /** Whether {@link markOpenForInjection} has been declared for this session. */+ isOpenForInjection(sessionId: string): boolean {+ return this.openForInjection.has(sessionId);+ }+/*** Atomically snapshot the ring buffer and register a consumer for future* IPC delivery. Returns the current ring buffer without deleting it.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.tsindex 2b3ef8ad1..6faf3ff6f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts@@ -22,9 +22,10 @@ vi.mock('./switch-room-service', () => ({},}));const noteIntendedRoom = vi.fn();+const noteSpawnTrigger = vi.fn();vi.mock('./switch-notification-poller', () => ({switchNotificationPoller: {- noteSpawnTrigger: vi.fn(),+ noteSpawnTrigger: (...args: unknown[]) => noteSpawnTrigger(...args),noteIntendedRoom: (...args: unknown[]) => noteIntendedRoom(...args),},}));@@ -32,6 +33,13 @@ vi.mock('./switch-notification-poller', () => ({vi.mock('@main/core/agents/getAgentById', () => ({getAgentById: (...args: unknown[]) => getAgentById(...args),}));+const fetchRoomDetail = vi.fn();+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ fetchRoomDetail: (...args: unknown[]) => fetchRoomDetail(...args),+}));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: vi.fn(async () => ({ id: 'server-1' })),+}));vi.mock('@main/db/client', () => ({ db: {} }));vi.mock('./auto-session-store', () => ({listAutoSessionAgentIds: vi.fn(async () => []),@@ -53,12 +61,39 @@ function fakeWatcher() {};}+/** An addressed room message, as the watch stream delivers it. */+type Overrides = {+ body?: string;+ sequence?: number;+ messageId?: string;+ threadId?: string;+};++function messageEvent(roomId: string, overrides: Overrides = {}): unknown {+ return {+ type: 'message',+ room_id: roomId,+ sequence: overrides.sequence ?? 7,+ payload: {+ addressed: true,+ body: overrides.body ?? 'hi there',+ sender_name: 'user',+ message_id: overrides.messageId ?? 'msg-1',+ thread_id: overrides.threadId ?? null,+ },+ };+}+// handleNotification is private; reach it directly to test the decision in// isolation from the long-poll loop.-function handle(watcher: ReturnType<typeof fakeWatcher>, roomId: string): void {+function handle(+ watcher: ReturnType<typeof fakeWatcher>,+ roomId: string,+ overrides: Overrides = {}+): void {(- autoSessionWatcher as unknown as { handleNotification: (w: unknown, r: string) => void }- ).handleNotification(watcher, roomId);+ autoSessionWatcher as unknown as { handleNotification: (w: unknown, e: unknown) => void }+ ).handleNotification(watcher, messageEvent(roomId, overrides));}describe('AutoSessionWatcher.handleNotification', () => {@@ -223,3 +258,101 @@ describe('AutoSessionWatcher.handleNotification', () => {expect(noteIntendedRoom).toHaveBeenCalledWith(sessionId, 'room-x', null);});});++/**+ * The message a session was started for travels in its opening prompt+ * (CHOO-2173).+ *+ * It used to be left to the session's room connection to type in once the+ * session was up. But that connection opens before the terminal exists, which+ * is exactly when this message arrives — so it waited, and the agent connected,+ * found nothing addressed to it and greeted the room instead of answering.+ * There is nothing to wait for if it goes in with the launch.+ */+describe('the message that started the session', () => {+ beforeEach(() => {+ createSession.mockReset();+ getConnections.mockReset();+ getConnections.mockReturnValue([]);+ getAgentById.mockReset();+ getAgentById.mockResolvedValue({ id: 'local-1', autoApprove: false, serverId: 'server-1' });+ createSession.mockResolvedValue({ success: true, data: { session: { id: 'new' } } });+ noteSpawnTrigger.mockReset();+ fetchRoomDetail.mockReset();+ fetchRoomDetail.mockResolvedValue({ id: 'room-x', name: 'Charlie' });+ });++ async function openingPrompt(overrides: Overrides = {}): Promise<string> {+ const watcher = fakeWatcher();+ handle(watcher, 'room-x', overrides);+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ return (createSession.mock.calls[0][0] as { initialPrompt: string }).initialPrompt;+ }++ it('titles the session after the room, not its id', async () => {+ // "Switch room 5ee6fedc-b701-4372-beb7-baa36464c3d0" names nothing anyone+ // recognises, and it is how the session is listed from the moment it+ // appears.+ const watcher = fakeWatcher();+ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));++ expect((createSession.mock.calls[0][0] as { title: string }).title).toBe(+ 'Session for room Charlie'+ );+ });++ it('falls back to the id when the room will not say its name', async () => {+ // A name lookup that fails is not a reason to abandon the spawn.+ fetchRoomDetail.mockRejectedValueOnce(new Error('gateway down'));+ const watcher = fakeWatcher();+ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));++ expect((createSession.mock.calls[0][0] as { title: string }).title).toBe(+ 'Session for room room-x'+ );+ });++ it('rides along with the instruction to join the room', async () => {+ const prompt = await openingPrompt({ body: 'what is the build status?' });++ expect(prompt).toContain('connect to switch room room-x');+ expect(prompt).toContain('what is the build status?');+ });++ it('carries who said it and its id, so the agent can reply to it', async () => {+ const prompt = await openingPrompt({ messageId: 'msg-42' });++ expect(prompt).toContain('user');+ expect(prompt).toContain('msg-42');+ });++ it('is not also replayed onto the session, which would answer it twice', async () => {+ await openingPrompt({ sequence: 7 });++ // Start *at* the trigger, so the stream resumes after it rather than+ // handing it over a second time.+ expect(noteSpawnTrigger).toHaveBeenCalledWith('switch-agent-1', 7, true, expect.anything());+ });++ it('hands over where the message sits, so the turn can be reported against it', async () => {+ // Without this the session's first turn is the one turn nothing reports:+ // the message is in the opening prompt, so no injection opens the turn.+ await openingPrompt({ sequence: 7, messageId: 'msg-42', threadId: 'thread-1' });++ expect(noteSpawnTrigger).toHaveBeenCalledWith('switch-agent-1', 7, true, {+ threadId: 'thread-1',+ anchorId: 'msg-42',+ });+ });++ it('reports a root-level message as having no thread', async () => {+ await openingPrompt({ sequence: 7, messageId: 'msg-42' });++ expect(noteSpawnTrigger).toHaveBeenCalledWith('switch-agent-1', 7, true, {+ threadId: null,+ anchorId: 'msg-42',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.tsindex 7e0b1af36..8e3cbb331 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto';import path from 'node:path';-import { SwitchEventStream } from '@sandboxaq/switch-agent-runtime';+import { type AgentBridgeEvent, SwitchEventStream } from '@sandboxaq/switch-agent-runtime';import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import {@@ -9,6 +9,8 @@ import {} from '@main/core/agents/switch-settings-paths';import { getLocationById } from '@main/core/locations/store';import { sessionService } from '@main/core/sessions/session-service';+import { fetchRoomDetail } from '@main/core/switch-servers/gateway-client';+import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import {listAutoSessionAgentIds,@@ -21,9 +23,23 @@ import {readSwitchAgentCredentialsFromSettings,type SwitchAgentCredentials,} from './switch-credentials';-import { switchNotificationPoller } from './switch-notification-poller';+import { formatEventForInjection } from './switch-event-format';+import { type SpawnTurn, switchNotificationPoller } from './switch-notification-poller';import { switchRoomService } from './switch-room-service';+/**+ * Where in the conversation the message that caused this spawn sits, so the+ * session can report working against it the moment it reaches the room.+ *+ * Only a message can start a turn — a command or a join has nobody waiting on+ * an answer, so there is no turn to open and this is null for them.+ */+function spawnTurnOf(event: AgentBridgeEvent): SpawnTurn | null {+ if (event.type !== 'message') return null;+ const msg = event.payload as { thread_id?: string | null; message_id?: string | null };+ return { threadId: msg.thread_id ?? null, anchorId: msg.message_id ?? null };+}+const SPAWN_MAX_ATTEMPTS = 3;const SPAWN_RETRY_DELAY_MS = 2000;// How long a room stays "spawn in flight" before the guard is cleared.@@ -75,6 +91,33 @@ async function getAgentLocalDir(localAgentId: string): Promise<string | null> {return location.dir;}+/**+ * The room's name, for the title of the session being started in it.+ *+ * The spawn is driven by an event that carries only the room's id, so the name+ * has to be asked for. It is worth one call: the id names nothing a person+ * recognises, and this title is how the session is listed from the moment it+ * appears. A failure here is not a reason to abandon the spawn — the caller+ * falls back to the id and says so in the log.+ */+async function roomNameFor(localAgentId: string, roomId: string): Promise<string | null> {+ try {+ const agent = await getAgentById(localAgentId);+ if (!agent?.serverId) return null;+ const server = await getServer(agent.serverId);+ if (!server) return null;+ const detail = await fetchRoomDetail(server, roomId);+ return detail.name || null;+ } catch (error) {+ log.warn('AutoSessionWatcher: could not read the room name; titling by id', {+ localAgentId,+ roomId,+ error: String(error),+ });+ return null;+ }+}+/** Post a message to a room on the agent's behalf (used for the spawn-failure* notice). Best-effort; throws on non-OK so the caller can log. */async function postRoomMessage(@@ -349,7 +392,7 @@ class AutoSessionWatcher {// offline.spawnCapable: true,onEvent: (event) => {- if (event.room_id) this.handleNotification(watcher, event.room_id, event.sequence);+ if (event.room_id) this.handleNotification(watcher, event);},onGap: (info) => {// A gap here means we may have missed a request to start a session.@@ -389,7 +432,9 @@ class AutoSessionWatcher {* between deciding to spawn and the spawned session claiming the room, which* the server cannot know about.*/- private handleNotification(watcher: AgentWatcher, roomId: string, sequence?: number): void {+ private handleNotification(watcher: AgentWatcher, event: AgentBridgeEvent): void {+ const roomId = event.room_id as string;+ const sequence = event.sequence;if (watcher.inFlight.has(roomId)) {log.info('AutoSessionWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',@@ -425,12 +470,26 @@ class AutoSessionWatcher {return;}+ // The message the session is being started for, written the way it would+ // have read had it been injected — so the agent sees the same line either+ // way. Handed to the session as part of its opening prompt rather than+ // typed in afterwards: the session has no terminal for the first seconds+ // of its life, which is exactly when this message arrives.+ const triggerLine = formatEventForInjection(event, null);+// Tell the poller where the session it is about to open should start// reading. We have already consumed this event — that is how we know to// spawn — so a session starting at head would come up having missed the- // very message it exists to answer.+ // very message it exists to answer. When the message is going in the+ // opening prompt the session starts *after* it instead, or it would arrive+ // twice and be answered twice.if (sequence !== undefined) {- switchNotificationPoller.noteSpawnTrigger(watcher.creds.agentId, sequence);+ switchNotificationPoller.noteSpawnTrigger(+ watcher.creds.agentId,+ sequence,+ triggerLine !== null,+ spawnTurnOf(event)+ );}// The two halves of the hand-off are logged at both ends, so a session that// comes up without its triggering message can be diagnosed from the log@@ -443,13 +502,19 @@ class AutoSessionWatcher {agentId: watcher.creds.agentId,roomId,triggerSequence: sequence ?? null,- sessionWillStartFrom: sequence === undefined ? 'head' : Math.max(sequence - 1, 0),+ triggerInOpeningPrompt: triggerLine !== null,+ sessionWillStartFrom:+ sequence === undefined+ ? 'head'+ : triggerLine !== null+ ? sequence+ : Math.max(sequence - 1, 0),});const timer = setTimeout(() => watcher.inFlight.delete(roomId), INFLIGHT_TTL_MS);watcher.inFlight.set(roomId, timer);- void this.spawnForRoom(watcher, roomId).catch((error) => {+ void this.spawnForRoom(watcher, roomId, triggerLine).catch((error) => {log.warn('AutoSessionWatcher: spawn failed', {localAgentId: watcher.localAgentId,roomId,@@ -458,12 +523,18 @@ class AutoSessionWatcher {});}- private async spawnForRoom(watcher: AgentWatcher, roomId: string): Promise<void> {+ private async spawnForRoom(+ watcher: AgentWatcher,+ roomId: string,+ triggerLine: string | null+ ): Promise<void> {// Bypass permissions only if this agent is configured to. Auto-started// local sessions run with no operator watching, but the default is off —// the per-agent setting (location settings) is the source of truth.const agent = await getAgentById(watcher.localAgentId);const autoApprove = agent?.autoApprove ?? false;+ const roomName = await roomNameFor(watcher.localAgentId, roomId);+ const title = `Session for room ${roomName ?? roomId}`;let lastError: string | null = null;for (let attempt = 1; attempt <= SPAWN_MAX_ATTEMPTS; attempt += 1) {if (watcher.abort.signal.aborted) return;@@ -479,11 +550,17 @@ class AutoSessionWatcher {id: sessionId,agentId: watcher.localAgentId,agentName: watcher.agentName,- title: `Switch room ${roomId}`,- // Bootstrap: tell the fresh session to join the room. Once it calls- // connect_to_room, the connect hook starts the per-room poller, which- // injects the message waiting in the room's event queue.- initialPrompt: `connect to switch room ${roomId}`,+ title,+ // Bootstrap: join the room, then answer the message that started this+ // session. Both in the opening prompt because the session has no+ // terminal to be typed into for the first seconds of its life —+ // which is precisely when that message arrives. Waiting for one and+ // typing it in afterwards is what left the agent connecting, finding+ // nothing addressed to it, and greeting the room instead.+ initialPrompt:+ triggerLine === null+ ? `connect to switch room ${roomId}`+ : `connect to switch room ${roomId}\n\nThen respond to this, which is what you were started for:\n${triggerLine}`,autoApprove,});if (result.success) {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.test.tsindex 347401019..7558c8a8a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.test.ts@@ -3,12 +3,15 @@ import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { PtyInjectionSink } from './injection-sink';vi.mock('@main/core/pty/pty-session-registry', () => ({- ptySessionRegistry: { get: vi.fn() },+ ptySessionRegistry: { get: vi.fn(), isOpenForInjection: vi.fn() },}));describe('PtyInjectionSink', () => {beforeEach(() => {vi.mocked(ptySessionRegistry.get).mockReset();+ // Open unless a test says otherwise — the gate is the subject of its own+ // block below, not of the lookup ones.+ vi.mocked(ptySessionRegistry.isOpenForInjection).mockReset().mockReturnValue(true);});it('acquires the live PTY for its key', () => {@@ -26,4 +29,41 @@ describe('PtyInjectionSink', () => {const sink = new PtyInjectionSink('location-1:session-1');expect(sink.acquire()).toBeNull();});++ /**+ * A live pty is not the same as one ready to be typed into (CHOO-2173).+ *+ * A session auto-started to answer a room message has that message in hand+ * before its terminal exists, and for a second or two afterwards the terminal+ * is booting and then receiving the session's own opening prompt. Typing into+ * either moment loses the message — swallowed by a TUI that is not listening,+ * or tacked onto the end of the opening prompt and sent as one.+ */+ describe('the readiness gate', () => {+ it('holds the message back while the session is still starting', () => {+ const pty = { write: vi.fn() };+ vi.mocked(ptySessionRegistry.get).mockReturnValue(pty as never);+ vi.mocked(ptySessionRegistry.isOpenForInjection).mockReturnValue(false);++ const sink = new PtyInjectionSink('location-1:session-1');+ expect(sink.acquire()).toBeNull();+ });++ it('asks about its own session, not some other pane', () => {+ vi.mocked(ptySessionRegistry.get).mockReturnValue({ write: vi.fn() } as never);++ new PtyInjectionSink('location-1:session-1').acquire();++ expect(ptySessionRegistry.isOpenForInjection).toHaveBeenCalledWith('location-1:session-1');+ });++ it('lets the message through once the session is open', () => {+ const pty = { write: vi.fn() };+ vi.mocked(ptySessionRegistry.get).mockReturnValue(pty as never);+ vi.mocked(ptySessionRegistry.isOpenForInjection).mockReturnValue(true);++ const sink = new PtyInjectionSink('location-1:session-1');+ expect(sink.acquire()).toBe(pty);+ });+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.tsindex 312e79da5..c4ea8d0fd 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/injection-sink.ts@@ -24,6 +24,12 @@ export class PtyInjectionSink implements InjectionSink {constructor(private readonly ptyKey: string) {}acquire(): InjectionTarget | null {+ // A live pty is not the same as one ready to be typed into. A session+ // launched to answer a room message spends its first seconds booting its+ // TUI and then receiving its own opening prompt; the runtime says when+ // that is done. Writing before it means the message is swallowed by a TUI+ // that is not listening, or tacked onto the opening prompt.+ if (!ptySessionRegistry.isOpenForInjection(this.ptyKey)) return null;return ptySessionRegistry.get(this.ptyKey) ?? null;}}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.tsindex eb51aad31..3e5e4652a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts@@ -156,7 +156,8 @@ describe('RoomConnection', () => {function connect(sink: { acquire: () => InjectionTarget | null },events: AgentBridgeEvent[],- isHumanTyping: () => boolean = () => false+ isHumanTyping: () => boolean = () => false,+ spawnTurn: { threadId: string | null; anchorId: string | null } | null = null) {const fetchMock = makeFetch(events);vi.stubGlobal('fetch', fetchMock);@@ -172,12 +173,88 @@ describe('RoomConnection', () => {deeplinkScheme: 'switchdash',isHumanTyping,mediaDir,+ spawnTurn,log: silentLog,});conn.start();return { conn, fetchMock };}+ /**+ * The turn a spawned session was started for (CHOO-2173).+ *+ * Addressing an agent with no session gets "Starting a session to handle+ * this" — and then, until now, nothing. The message that caused the spawn+ * travels in the session's opening prompt, because it arrives before there is+ * a terminal to type into, so no injection ever opens the turn. That made the+ * first turn the one turn that reported no state at all: no working, and on+ * Mattermost no indicator and no typing.+ */+ describe('the turn a session was spawned to answer', () => {+ const idleSink = { acquire: () => null };++ it('reports working on reaching the room, with nobody having injected anything', async () => {+ const { conn, fetchMock } = connect(idleSink, [], () => false, {+ threadId: null,+ anchorId: 'msg-42',+ });+ await flush();+ conn.stop();++ expect(runtimeStates(fetchMock)[0]).toBe('working');+ });++ it('reports against the message that is waiting, not the room root', async () => {+ // So the indicator and Mattermost's typing land where the asking happened.+ const { conn, fetchMock } = connect(idleSink, [], () => false, {+ threadId: 'thread-9',+ anchorId: 'msg-42',+ });+ await flush();+ conn.stop();++ expect(workingAnchors(fetchMock)[0]).toBe('msg-42');+ });++ it('still goes idle when the agent finishes', async () => {+ // The turn has to close, or the indicator spins for the session's life.+ const { conn, fetchMock } = connect(idleSink, [], () => false, {+ threadId: null,+ anchorId: 'msg-42',+ });+ await flush();+ conn.onAgentStatusChange('completed');+ await flush();+ conn.stop();++ expect(runtimeStates(fetchMock)).toContain('idle');+ });++ it('opens the turn once, not again on every reconnect', async () => {+ const { conn, fetchMock } = connect(idleSink, [], () => false, {+ threadId: null,+ anchorId: 'msg-42',+ });+ await flush();+ conn.onAgentStatusChange('completed');+ await flush();+ // A second arrival in the same room must not re-raise a turn that is done.+ (conn as unknown as { adoptRoom: (rooms: string[]) => void }).adoptRoom(['room-2']);+ await flush();+ conn.stop();++ expect(runtimeStates(fetchMock).filter((s) => s === 'working')).toHaveLength(1);+ });++ it('a session nobody is waiting on reports idle, as before', async () => {+ const { conn, fetchMock } = connect(idleSink, []);+ await flush();+ conn.stop();++ expect(runtimeStates(fetchMock)).not.toContain('working');+ });+ });+it('injects an addressed message then submits, and surfaces a working turn', async () => {const target: InjectionTarget = { write: vi.fn() };const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);@@ -317,6 +394,52 @@ describe('RoomConnection', () => {conn.stop();});+ it('delivers the message once the session has a terminal to type into', async () => {+ // The bug this guards (CHOO-2173): a session auto-started to answer a room+ // message opens this connection before its terminal exists, so the very+ // message it was started for arrives with nowhere to go. The dialog and+ // operator-typing gates both come back on a timer; this one did not, and+ // waited on an unrelated event that on a fresh session never came — so the+ // agent booted, said hello, and never saw what it was asked.+ vi.useFakeTimers();+ try {+ const target: InjectionTarget = { write: vi.fn() };+ let live = false;+ const { conn } = connect({ acquire: () => (live ? target : null) }, [messageEvent(true)]);++ await vi.advanceTimersByTimeAsync(1);+ expect(target.write).not.toHaveBeenCalled();++ live = true;+ // NO_TARGET_RETRY_MS.+ await vi.advanceTimersByTimeAsync(500);++ expect(vi.mocked(target.write).mock.calls.map((c) => c[0])[0]).toContain('<<');+ conn.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it('stops looking for a terminal once the connection is stopped', async () => {+ vi.useFakeTimers();+ try {+ const target: InjectionTarget = { write: vi.fn() };+ let live = false;+ const { conn } = connect({ acquire: () => (live ? target : null) }, [messageEvent(true)]);++ await vi.advanceTimersByTimeAsync(1);+ conn.stop();++ live = true;+ await vi.advanceTimersByTimeAsync(5_000);++ expect(target.write).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it('defers injection while the operator is typing into the pane', async () => {const target: InjectionTarget = { write: vi.fn() };const { conn } = connect({ acquire: () => target }, [messageEvent(true)], () => true);diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.tsindex d0fb748c3..e747ac920 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts@@ -31,6 +31,12 @@ const BUSY_FALLBACK_MS = 60_000;// is typing into the pane. Short enough that delivery resumes promptly once// they pause.const HUMAN_GATE_RETRY_MS = 500;+// How long to wait before looking again for a target to type into. A session+// auto-started to answer a room message opens its room connection before its+// terminal exists, so the very message it was started for arrives with nowhere+// to go; without a retry of its own it waits for an unrelated event that on a+// fresh session may never come.+const NO_TARGET_RETRY_MS = 500;// Gap between steps of a multi-step control command (e.g. reset's `/clear` then// the reconnect prompt), so a TUI settles one before the next is typed.const CONTROL_STEP_GAP_MS = 600;@@ -128,6 +134,13 @@ export interface RoomConnectionLogger {error(message: string, meta?: Record<string, unknown>): void;}+/** Where the message that caused a spawn sits, so the session can report+ * against it rather than at the room root. */+export interface SpawnTurn {+ threadId: string | null;+ anchorId: string | null;+}+export interface RoomConnectionDeps {creds: SwitchCredentials;/**@@ -152,6 +165,18 @@ export interface RoomConnectionDeps {* session exists to handle.*/startCursor?: number;+ /**+ * The message this session was started to answer, when it was started by one.+ *+ * A session normally opens its turn when an addressed message is injected+ * into it. A spawned one never gets that injection — the message travels in+ * its opening prompt, because it arrives before there is a terminal to type+ * into — so without this its first turn is the one turn that reports+ * nothing: no working state, and on Mattermost no indicator and no typing.+ * Holding the message's own position here lets the turn be opened when the+ * session reaches the room instead, against the message that is waiting.+ */+ spawnTurn?: SpawnTurn | null;/** The Switch Console session id of the session this connection drives, so* the deeplink can resolve to the exact session on any client (the shared* session id is the same across clients; the local room mapping is not). */@@ -254,6 +279,7 @@ export class RoomConnection {private activityTicker: ReturnType<typeof setInterval> | null = null;private busyFallback: ReturnType<typeof setTimeout> | null = null;private humanGateTimer: ReturnType<typeof setTimeout> | null = null;+ private noTargetTimer: ReturnType<typeof setTimeout> | null = null;/** The push transport: one SSE stream plus one heartbeat, replacing the* long-poll and the three renew loops. */private stream: SwitchEventStream | null = null;@@ -263,6 +289,9 @@ export class RoomConnection {* socket. */private readonly connectionId: string;private readonly startCursor: number | undefined;+ /** Cleared once opened, so the turn is opened once and not on every+ * reconnect or room change for the life of the session. */+ private spawnTurn: SpawnTurn | null;/** Notified whenever the server tells us which room this session is in. */private readonly onRoomChanged: ((roomId: string | null) => void) | null;/**@@ -299,6 +328,7 @@ export class RoomConnection {this.mediaDir = deps.mediaDir;this.connectionId = deps.connectionId;this.startCursor = deps.startCursor;+ this.spawnTurn = deps.spawnTurn ?? null;this.onRoomChanged = deps.onRoomChanged ?? null;this.log = deps.log;}@@ -334,7 +364,38 @@ export class RoomConnection {// session's `(Open in Switch Console)` link is available in the new room's// !status immediately on connect/switch — not only once the agent next// works. idle surfaces nothing on the bridge, so this posts no message.- if (this.roomId) void this.postRuntimeState('idle', null).catch(() => {});+ if (this.roomId && !this.openSpawnTurn()) {+ void this.postRuntimeState('idle', null).catch(() => {});+ }+ }++ /**+ * Report the turn a spawned session was started for, once it is in the room.+ *+ * Answers "is anything happening?" for the one turn that could not answer it:+ * the message is already inside the session's opening prompt, so it is being+ * worked on, but nothing had said so. Reported against the message itself, so+ * the indicator and Mattermost's typing land where the asking happened rather+ * than at the room root.+ *+ * Returns whether it opened one, so the caller can fall back to reporting+ * idle — a session that owes nobody an answer should not look busy.+ */+ private openSpawnTurn(): boolean {+ const turn = this.spawnTurn;+ if (turn === null) return false;+ this.spawnTurn = null;+ this.roomTurnActive = true;+ this.currentThreadId = turn.threadId;+ this.currentAnchorId = turn.anchorId;+ this.log.info('RoomConnection: reporting the turn this session was started for', {+ event: 'switch_spawn_turn_opened',+ roomId: this.roomId,+ threadId: turn.threadId,+ anchorId: turn.anchorId,+ });+ this.setRuntimeState('working');+ return true;}/**@@ -397,7 +458,9 @@ export class RoomConnection {roomId: next,});this.onRoomChanged?.(next);- if (next) void this.postRuntimeState('idle', null).catch(() => {});+ if (next && !this.openSpawnTurn()) {+ void this.postRuntimeState('idle', null).catch(() => {});+ }}/** Stop the loops and clear any lingering runtime-state surface. */@@ -417,6 +480,7 @@ export class RoomConnection {this.abort.abort();if (this.busyFallback) clearTimeout(this.busyFallback);if (this.humanGateTimer) clearTimeout(this.humanGateTimer);+ if (this.noTargetTimer) clearTimeout(this.noTargetTimer);this.stopActivityTicker();}@@ -666,6 +730,17 @@ export class RoomConnection {private enqueue(injection: QueuedInjection): void {if (this.stopped) return;this.queue.push(injection);+ // Together with `switch_message_injected` below, these two say whether a+ // message that reached the session ever made it into the pane — the+ // question every "the agent ignored me" report comes down to.+ this.log.info('RoomConnection: room message queued for the session', {+ event: 'switch_message_queued',+ roomId: this.roomId,+ sessionId: this.sessionId,+ messageId: injection.messageId,+ addressed: injection.addressed,+ queued: this.queue.length,+ });this.tryFlush();}@@ -838,12 +913,23 @@ export class RoomConnection {const target = this.sink.acquire();if (!target) {- // Target not live yet (or already gone); leave the message queued and- // retry on the next status change or poll event.- this.log.warn('RoomConnection: injection deferred — no live target for session', {- roomId: this.roomId,- queued: this.queue.length,- });+ // Not ready to be typed into — the terminal is still starting, or the+ // session's own opening prompt has not gone in yet. Keep the message and+ // come back for it: an auto-started session receives the message it was+ // started for before it has a terminal at all, and nothing else is+ // guaranteed to drive the queue afterwards.+ if (!this.noTargetTimer) {+ this.log.warn('RoomConnection: injection deferred — no live target for session', {+ event: 'switch_message_deferred',+ roomId: this.roomId,+ sessionId: this.sessionId,+ queued: this.queue.length,+ });+ this.noTargetTimer = setTimeout(() => {+ this.noTargetTimer = null;+ this.tryFlush();+ }, NO_TARGET_RETRY_MS);+ }return;}@@ -855,8 +941,11 @@ export class RoomConnection {// delivered. Writing both in one chunk makes TUIs (Claude) treat the// trailing Enter as part of the pasted input, leaving the text unsent.target.write(payload);- this.log.debug('RoomConnection: injected message into target', {+ this.log.info('RoomConnection: injected message into target', {+ event: 'switch_message_injected',roomId: this.roomId,+ sessionId: this.sessionId,+ messageId: item.messageId,addressed: item.addressed,queued: this.queue.length,});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.tsindex dbbe9d4b9..82462efcd 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts@@ -12,7 +12,9 @@ import type { AgentStatus, NotificationType } from '@shared/core/providers/agentimport { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import { PtyInjectionSink } from './injection-sink';import { PluginPromptInjector } from './plugin-prompt-injector';-import { RoomConnection } from './room-connection';+import { RoomConnection, type SpawnTurn } from './room-connection';++export type { SpawnTurn };import { sessionConnectionId } from './session-connection-id';import { resolveSessionControl } from './session-control';import {@@ -39,6 +41,8 @@ class SwitchNotificationPoller {private readonly connections = new Map<string, RoomConnection>();/** Agent id → buffer position the next session for it should start from. */private readonly pendingStart = new Map<string, number>();+ /** The turn a spawned session owes an answer to, keyed like `pendingStart`. */+ private readonly pendingTurn = new Map<string, SpawnTurn>();/** Session id → the room it is being started for, before it exists. */private readonly pendingRoom = new Map<string, { roomId: string; roomName: string | null }>();@@ -97,10 +101,23 @@ class SwitchNotificationPoller {* the room it claims, so the cost of overlap is small and the cost of a gap* is the bug this fixes.*/- noteSpawnTrigger(agentId: string, sequence: number): void {- const start = Math.max(sequence - 1, 0);+ noteSpawnTrigger(+ agentId: string,+ sequence: number,+ deliveredInOpeningPrompt: boolean,+ turn: SpawnTurn | null+ ): void {+ // The trigger is replayed to the session unless it has already been handed+ // to it in its opening prompt — in which case start *after* it, or the+ // session receives the same message twice and answers it twice.+ const start = deliveredInOpeningPrompt ? sequence : Math.max(sequence - 1, 0);const pending = this.pendingStart.get(agentId);this.pendingStart.set(agentId, pending === undefined ? start : Math.min(pending, start));+ // Only meaningful when the message went in the opening prompt: that is the+ // case with no injection to open the turn, which is why the turn has to be+ // opened on arrival instead. A replayed trigger opens its own turn when it+ // is injected, as any other message does.+ if (turn !== null && deliveredInOpeningPrompt) this.pendingTurn.set(agentId, turn);}/**@@ -227,6 +244,8 @@ class SwitchNotificationPoller {// later session must not rewind to a message this one already handled.const startCursor = this.pendingStart.get(creds.agentId);this.pendingStart.delete(creds.agentId);+ const spawnTurn = this.pendingTurn.get(creds.agentId) ?? null;+ this.pendingTurn.delete(creds.agentId);// The other end of the watcher's hand-off. If a spawned session comes up// without the message that triggered it, these two lines say whether the// cursor was handed over and honoured, or whether the session opened at@@ -238,6 +257,7 @@ class SwitchNotificationPoller {connectionId,startFrom: startCursor ?? 'head',roomId: roomId ?? '(await the server)',+ owesTurn: spawnTurn !== null,});const connection = new RoomConnection({creds,@@ -245,6 +265,7 @@ class SwitchNotificationPoller {roomName,connectionId,startCursor,+ spawnTurn,sessionId: ctx.sessionId,sink: new PtyInjectionSink(ptySessionId),injector: new PluginPromptInjector(ctx.providerId),diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex e8ee337d5..e064a1e49 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -215,11 +215,14 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocrunHostReady &&submitState === 'idle';- const finishWith = (locationId: string) => {+ /** `agentName` is what picks the agent out of the location — a location can+ * hold several, so navigating on `locationId` alone opens the directory+ * rather than the agent that was just created. */+ const finishWith = (agent: { locationId: string; name: string }) => {setCloseGuard(false);setSubmitState('idle');onClose();- navigate('location', { locationId });+ navigate('location', { locationId: agent.locationId, agentName: agent.name });};const reportProvisionError = (result: ProvisionAgentResult) => {@@ -296,8 +299,8 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocpolicy: form.addressingPolicy,});}- void agentsStore.load();- finishWith(result.agent.locationId);+ await agentsStore.load();+ finishWith(result.agent);} catch (error) {log.error(error);setCloseGuard(false);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 82615d0c6..5af84bb89 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -1,7 +1,7 @@import { useQuery } from '@tanstack/react-query';import { CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useId, useState } from 'react';+import { useEffect, useId, useRef, useState } from 'react';import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';import { AddressingPolicyControl } from '@renderer/features/switch-servers/addressing-policy-control';import type { OptionItem } from '@renderer/features/switch-servers/addressing-policy-editor';@@ -11,9 +11,10 @@ import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';-import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Field, FieldGroup, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Switch } from '@renderer/lib/ui/switch';+import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';import type { ConfigureAgentFormState } from './modes';/**@@ -98,6 +99,23 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({.filter((bridge) => !identities.some((identity) => identity.bridgeId === bridge.id)).map((bridge) => bridge.displayName);+ // The same condition the control draws its warning from, so the section opens+ // exactly when there is a warning inside it and never on a hunch of its own.+ const ownerUnreachable =+ policyNamesOwner(form.addressingPolicy) && unlinkedApps !== null && unlinkedApps.length > 0;++ // Folded is right until the defaults are wrong. The owner-only default admits+ // nobody in an app with no account linked, and a warning nothing on screen+ // hints at is a warning nobody reads — so the section opens itself the first+ // time that is true. Once only: closing it again is an answer, not an+ // oversight, and the queries behind `unlinkedApps` settle after mount.+ const openedForWarning = useRef(false);+ useEffect(() => {+ if (!ownerUnreachable || openedForWarning.current) return;+ openedForWarning.current = true;+ setSettingsOpen(true);+ }, [ownerUnreachable]);+if (servers.length === 0) {return (<div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">@@ -173,15 +191,18 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({</Field><Field>- <FieldLabel>+ {/* FieldTitle rather than FieldLabel: this is a settings row like+ the two toggles above it, and the label styling set it lighter+ and greyer than them for no reason the reader can see. */}+ <FieldTitle><span className="flex items-center gap-1.5">- Who can send instructions+ Who can talk to your agent<InfoTooltiplabel="More info about addressing"- content="Sending instructions means an @mention, a targeted message, or a delegated task. A new agent answers only you; grant other agents to let them delegate to it. You can change this later from the agent's settings."+ content="Talking to an agent means an @mention, a targeted message, or a delegated task. A new agent answers only you; grant other agents to let them delegate to it. You can change this later from the agent's settings."/></span>- </FieldLabel>+ </FieldTitle><AddressingPolicyControlvalue={form.addressingPolicy}onChange={form.setAddressingPolicy}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsxindex 392ba69b5..a142a9bb4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx@@ -5,13 +5,12 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import {asMounted,getLocationStore,- locationDisplayName,locationViewKind,} from '@renderer/features/locations/stores/location-selectors';import { ServerStatusPill } from '@renderer/features/switch-servers/server-presentation';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { OpenInMenu } from '@renderer/lib/components/titlebar/open-in-menu';import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';@@ -19,6 +18,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -31,24 +31,23 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltiimport type { Agent } from '@shared/core/agents/agents';/**- * The agent this page is about. Falls back to the location's own name while the- * agent list is still loading, or when the route carries no agent name.+ * The agent this page is about. Shows a neutral placeholder while the agent+ * list is still loading, or where the route names no agent and the location+ * holds more than one to choose between.*/-const AgentCrumb = observer(function AgentCrumb({- locationId,- agent,-}: {- locationId: string;- agent: Agent | null;-}) {- const label = agent?.name ?? locationDisplayName(getLocationStore(locationId)) ?? 'Agent';+const AgentCrumb = observer(function AgentCrumb({ agent }: { agent: Agent | null }) {+ const label = agent?.name ?? 'Agent';+ const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);return (<TitlebarBreadcrumbcrumbs={[{key: 'agent',- icon: agent?.providerId ? (- <AgentIcon id={agent.providerId} size={14} className="shrink-0" />+ // The agent's own picture, as everywhere else it is listed — the+ // provider logo that used to sit here says what it runs on, which is+ // not what a crumb naming one agent is for.+ icon: agent ? (+ <AgentAvatar name={label} iconUrl={iconUrl} size={16} className="bg-transparent" />) : (<Bot className="size-3.5 shrink-0" />),@@ -103,7 +102,7 @@ const AgentActionsMenu = observer(function AgentActionsMenu({const confirmDeleteAgent = useConfirmDeleteAgent();const { toastPromise } = useToast();- const label = agent?.name ?? locationDisplayName(getLocationStore(locationId)) ?? 'this agent';+ const label = agent?.name ?? 'this agent';const gatewayUrl =agent?.serverId && agent.switchAgentId? switchRoomsStore.gatewayAgentUrl(agent.serverId, agent.switchAgentId)@@ -183,7 +182,7 @@ export const LocationTitlebar = observer(function LocationTitlebar() {return (<Titlebar- leftSlot={<AgentCrumb locationId={locationId} agent={agent} />}+ leftSlot={<AgentCrumb agent={agent} />}rightSlot={<div className="mr-1 flex items-center gap-1.5">{mounted &&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 6c5f23fd3..58024a795 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,10 +1,6 @@import { useQueryClient } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import {- getLocationStore,- locationDisplayName,-} from '@renderer/features/locations/stores/location-selectors';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';import { useToast } from '@renderer/lib/hooks/use-toast';@@ -33,7 +29,10 @@ export const AgentPageHeader = observer(function AgentPageHeader() {const showAddToRoom = useShowModal('addAgentToRoomModal');const agent = agentsStore.agentAtLocation(locationId, agentName);- const title = agent?.name ?? agentName ?? locationDisplayName(getLocationStore(locationId)) ?? '';+ // Never the location's name: a directory is not an agent, and standing its+ // basename in here also seeds the generated avatar from it, so the page+ // presents a whole identity that belongs to no agent.+ const title = agent?.name ?? agentName ?? 'Agent';const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;const serverId = agent?.serverId ?? null;diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxindex 024a099db..e80e56300 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -150,10 +150,10 @@ function AddressingPolicyRow({onChange={change}inlineLabel={<span className="flex items-center gap-1.5 text-sm leading-snug font-medium">- Who can send instructions+ Who can talk to your agent<InfoTooltiplabel="More info about addressing"- content="Sending instructions means an @mention, a targeted message, or a delegated task. Only you, anyone in the agent's rooms, or whoever a rule admits."+ content="Talking to an agent means an @mention, a targeted message, or a delegated task. Only you, anyone in the agent's rooms, or whoever a rule admits."/></span>}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.tsindex 7b14f5f30..1fb86772d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts@@ -70,3 +70,54 @@ describe('AgentsStore server scoping', () => {expect(agentsStore.locationHasAgentsOnServer('orphan', 'server-1')).toBe(false);});});++/**+ * Which agent an agent page is about (CHOO-2173).+ *+ * The route identifies one by location *and* name. Creating an agent used to+ * navigate with the location alone, and with nothing to resolve, every surface+ * on the page fell back to the directory's name — so a new agent opened under+ * the folder's name and an avatar generated from it.+ */+describe('resolving the agent a location route is about', () => {+ afterEach(() => {+ agentsStore.byLocation.clear();+ agentsStore.optimisticServerByLocation.clear();+ });++ it('picks the named agent out of a shared directory', () => {+ agentsStore.byLocation.set('dir', [+ agent('dir', 'server-1', 'charlie'),+ agent('dir', 'server-1', 'delta'),+ ]);++ expect(agentsStore.agentAtLocation('dir', 'charlie')?.name).toBe('charlie');+ expect(agentsStore.agentAtLocation('dir', 'delta')?.name).toBe('delta');+ });++ it('resolves an unnamed route when the directory holds exactly one agent', () => {+ // Nothing to choose between, so there is nothing to get wrong.+ agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);++ expect(agentsStore.agentAtLocation('dir', undefined)?.name).toBe('charlie');+ });++ it('refuses to guess between several agents', () => {+ agentsStore.byLocation.set('dir', [+ agent('dir', 'server-1', 'charlie'),+ agent('dir', 'server-1', 'delta'),+ ]);++ expect(agentsStore.agentAtLocation('dir', undefined)).toBeNull();+ });++ it('is null for a name that is not there, rather than the first agent', () => {+ agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);++ expect(agentsStore.agentAtLocation('dir', 'nobody')).toBeNull();+ });++ it('is null for a directory with no agents at all', () => {+ expect(agentsStore.agentAtLocation('empty', undefined)).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.tsindex 8de883b1e..8c42ef35f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts@@ -69,13 +69,15 @@ export class AgentsStore {* The agent an agent page is routed to — its location plus its name, the pair* every caller of the `location` view navigates with.*- * Returns null rather than guessing when the route carries no name: a location- * can hold several agents, and picking one of them would put another agent's+ * A route carrying no name is answered only where there is nothing to guess+ * between: a location holding exactly one agent resolves to it. Beyond that,+ * null rather than a guess — picking one of several would put another agent's* provider and identity above someone's session list.*/agentAtLocation(locationId: string, agentName: string | undefined): Agent | null {- if (agentName === undefined) return null;- return (this.byLocation.get(locationId) ?? []).find((a) => a.name === agentName) ?? null;+ const agents = this.byLocation.get(locationId) ?? [];+ if (agentName === undefined) return agents.length === 1 ? agents[0]! : null;+ return agents.find((a) => a.name === agentName) ?? null;}/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsxindex 8792e701d..c01cea24d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx@@ -2,10 +2,6 @@ import { Bot, DoorOpen, MessageSquare, Pin } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import {- getLocationStore,- locationDisplayName,-} from '@renderer/features/locations/stores/location-selectors';import { useSessionViewContext } from '@renderer/features/sessions/session-view-context';import {getRegisteredSessionData,@@ -59,7 +55,7 @@ export const SessionTitlebar = observer(function SessionTitlebar() {) : (<Bot className="size-3.5 shrink-0" />),- label: agentName ?? locationDisplayName(getLocationStore(locationId)) ?? 'Agent',+ label: agentName ?? agent?.name ?? 'Agent',maxWidthClassName: 'max-w-40',onClick: () => navigate('location', { locationId, agentName }),},diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsxindex a6780bf04..36f1f3e08 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx@@ -8,7 +8,6 @@ import { AGENTS_CONTAINER, makeDndId, SortableBranch, SortableList } from './sidimport {groupByRoom,isRoomNameKnown,- isRoomViewActive,openRoomInMessagingApp,openRoomView,RoomRow,@@ -67,7 +66,12 @@ const AgentSessions = observer(function AgentSessions({bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}onSelect={() => openRoomView(roomKey)}- isActive={isRoomViewActive(roomKey)}+ // Deliberately never active. A room is a heading under every+ // agent with a session in it, so an open room is several rows+ // here and nothing says which one you came from — highlighting on+ // the room id alone lit all of them at once. The agent rows under+ // a room have the same problem and answer it the same way: with+ // no way to tell the copies apart, none of them lights up.onOpenChannel={switchRoomsStore.roomChannelUrl(roomKey)? () => openRoomInMessagingApp(roomKey)diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsxindex b7e5c43d9..76fab8ccd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx@@ -178,31 +178,39 @@ function RoomHeading({ room }: { room: RemoteRoomDetail }) {);}-/** What the field is doing, once the user has stopped typing in it. */+/** What the section is doing, once the user has stopped typing in it. */type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; message: string };/**- * Description and instructions, saved when the field is left.+ * Description and instructions, written when Save is pressed.*- * There is no Save button, so the saving has to be visible: a field says when it- * is writing, when it has written, and — in the field's own words rather than a- * toast that has already gone — when the server refused. Silence would leave a- * typed value looking stored when it is not.+ * They used to commit when a field lost focus, which meant the moment they were+ * stored was the moment you looked away — and leaving the tab was the only+ * thing that reliably did it. Editing and storing are now separate acts, and+ * the button says which state the section is in: changed and unsaved, writing,+ * written, or refused in the server's own words.+ *+ * One request carries both fields, so the pair is stored together or not at all.*/function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {const queryClient = useQueryClient();- const [description, setDescription] = useState(room.description);- const [instructions, setInstructions] = useState(room.instructions ?? '');- const [descriptionSave, setDescriptionSave] = useState<SaveState>({ phase: 'idle' });- const [instructionsSave, setInstructionsSave] = useState<SaveState>({ phase: 'idle' });-- async function save(- changes: { description: string } | { instructions: string },- setState: (state: SaveState) => void- ) {+ const savedDescription = room.description;+ const savedInstructions = room.instructions ?? '';+ const [description, setDescription] = useState(savedDescription);+ const [instructions, setInstructions] = useState(savedInstructions);+ const [state, setState] = useState<SaveState>({ phase: 'idle' });++ const dirty = description !== savedDescription || instructions !== savedInstructions;++ async function save() {setState({ phase: 'saving' });try {- const updated = await rpc.switchServers.updateRoom({ serverId, roomId: room.id, ...changes });+ const updated = await rpc.switchServers.updateRoom({+ serverId,+ roomId: room.id,+ description,+ instructions,+ });queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);setState({ phase: 'saved' });} catch (cause) {@@ -217,7 +225,6 @@ function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoom<Fieldlabel="Description"hint="Helps other people and agents understand what this room is for."- state={descriptionSave}><InputclassName="h-9"@@ -225,60 +232,68 @@ function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomvalue={description}onChange={(e) => {setDescription(e.target.value);- setDescriptionSave({ phase: 'idle' });- }}- onBlur={() => {- if (description === room.description) return;- void save({ description }, setDescriptionSave);+ setState({ phase: 'idle' });}}/></Field>- <Field- label="Instructions"- hint="Sent to every agent as it joins the room."- state={instructionsSave}- >+ <Field label="Instructions" hint="Sent to every agent as it joins the room."><Textarearows={4}placeholder="Optional guidance shown to agents when they enter the room"value={instructions}onChange={(e) => {setInstructions(e.target.value);- setInstructionsSave({ phase: 'idle' });- }}- onBlur={() => {- if (instructions === (room.instructions ?? '')) return;- void save({ instructions }, setInstructionsSave);+ setState({ phase: 'idle' });}}/></Field>++ {/* The status sits beside the button rather than under a field: one+ request covers both, so there is one answer to report. */}+ <div className="flex items-center justify-end gap-3">+ <SaveStatus state={state} dirty={dirty} />+ <Button+ type="button"+ size="sm"+ disabled={!dirty || state.phase === 'saving'}+ onClick={() => void save()}+ >+ {state.phase === 'saving' ? 'Saving…' : 'Save'}+ </Button>+ </div></section>);}+/** Says where the edits stand, so an unsaved change is never silent. */+function SaveStatus({ state, dirty }: { state: SaveState; dirty: boolean }) {+ if (state.phase === 'failed') {+ return <span className="text-destructive text-xs">Not saved — {state.message}</span>;+ }+ if (state.phase === 'saved' && !dirty) {+ return <span className="text-xs text-foreground-muted">Saved.</span>;+ }+ if (dirty) {+ return <span className="text-xs text-foreground-muted">Unsaved changes.</span>;+ }+ return null;+}+function Field({label,hint,- state,children,}: {label: string;hint: string;- state: SaveState;children: React.ReactNode;}) {return (<div className="flex flex-col gap-1.5"><span className="text-sm text-foreground-muted">{label}</span>{children}- {state.phase === 'failed' ? (- <span className="text-destructive text-xs">Not saved — {state.message}</span>- ) : (- <span className="text-xs text-foreground-muted">- {state.phase === 'saving' ? 'Saving…' : state.phase === 'saved' ? 'Saved.' : hint}- </span>- )}+ <span className="text-xs text-foreground-muted">{hint}</span></div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxindex 8899cb9da..a523fa703 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -38,7 +38,11 @@ type ConnectMessagingAppModalArgs = {* says whether there is any point offering the link-your-account step: on a* platform without a directory, a connection nobody has used yet knows nobody,* so the search would be a form that cannot be filled in. */-type ConnectedApp = { bridgeId: string; directorySearchSupported: boolean };+type ConnectedApp = {+ bridgeId: string;+ displayName: string;+ directorySearchSupported: boolean;+};type Props = BaseModalProps<ConnectedApp> & ConnectMessagingAppModalArgs;@@ -127,6 +131,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod}onSuccess({bridgeId: result.bridge.id,+ displayName: result.bridge.displayName,directorySearchSupported: selectedType.directorySearchSupported,});} catch (cause) {@@ -276,7 +281,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod<span className="text-sm font-medium">Allow creating channels from Switch</span><span className="text-xs text-foreground-muted">{channelCreationSupported- ? 'Lets a new room create its channel here directly. Turn off to only ever adopt channels made in the app.'+ ? `Allows Switch users and agents to create channels in ${bridgePlatformLabel(selectedType.key)} from Switch. Turn it off to only ever use channels made in the app.`: `${bridgePlatformLabel(selectedType.key)} has no way to create channels from Switch, so this connection can only be used with channels made in the app.`}</span></span>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex 1c816ad22..4d5cad1c7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -15,6 +15,7 @@ import { observer } from 'mobx-react-lite';import { useEffect, useMemo, useState } from 'react';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { openExternalUrl } from '@renderer/lib/open-external';@@ -36,6 +37,7 @@ import { BundledChatSignIn } from './BundledChatSignIn';import { orderBridges } from './messaging-apps-order';import {hasUnlinkedMessagingApp,+ identityLinkOrderingNote,shouldOfferIdentityLinkOnConnect,unrecognisedMessagingApps,unrecognisedMessagingAppsMessage,@@ -83,6 +85,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({className?: string;}) {const queryClient = useQueryClient();+ const { toast } = useToast();const showConnectMessagingApp = useShowModal('connectMessagingAppModal');const showClaimIdentity = useShowModal('claimIdentityModal');const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');@@ -201,7 +204,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onClick={() =>showConnectMessagingApp({serverId,- onSuccess: ({ bridgeId, directorySearchSupported }) => {+ onSuccess: ({ bridgeId, displayName, directorySearchSupported }) => {// Refresh the bridge list everywhere it is consumed — this// card and the room-creation picker share the query key.void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });@@ -217,9 +220,16 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({// second ago. The search would be guaranteed empty, which// teaches the user that they are not in their own workspace.// Linking waits for the server page, by which time someone- // has messaged the app and there is a name to pick.+ // has messaged the app and there is a name to pick. Say that,+ // rather than closing on nothing and leaving the step looking+ // forgotten.if (shouldOfferIdentityLinkOnConnect({ directorySearchSupported })) {showClaimIdentity({ serverId, bridgeId });+ return;+ }+ const note = identityLinkOrderingNote({ displayName, directorySearchSupported });+ if (note !== null) {+ toast({ title: 'Link your account later', description: note });}},})@@ -369,6 +379,16 @@ export function MessagingAppRow({}};+ // What it costs not to be linked, and — where the app has no directory to+ // search — how to become linkable at all. The second half is not obvious and+ // is the reason nothing offered to link on the way in.+ const orderingNote = identityLinkOrderingNote({+ displayName: bridge.displayName,+ directorySearchSupported: bridge.directorySearchSupported,+ });+ const noAccountHelp =+ orderingNote === null ? NO_ACCOUNT_EXPLANATION : `${NO_ACCOUNT_EXPLANATION} ${orderingNote}`;+// Why the switch cannot be moved, when it cannot. Said in a tooltip rather// than left to a greyed control, because "off" and "this platform cannot do// it at all" are different claims and look identical otherwise.@@ -411,14 +431,14 @@ export function MessagingAppRow({render={<spantabIndex={0}- aria-label={NO_ACCOUNT_EXPLANATION}+ aria-label={noAccountHelp}className="inline-flex text-foreground-muted"><Info className="size-3" /></span>}/>- <TooltipContent className="max-w-xs">{NO_ACCOUNT_EXPLANATION}</TooltipContent>+ <TooltipContent className="max-w-xs">{noAccountHelp}</TooltipContent></Tooltip></span>) : (diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsxindex 5b18b94fb..ac18c91d5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx@@ -29,9 +29,9 @@ const MODE_LABELS: Record<AddressingMode, string> = {const MODE_HINTS: Record<AddressingMode, string> = {ownerAndAgents:'You, and any agent you own — so one of your agents can hand this one work. Nobody else.',- owner: 'Only you, in person. Agents cannot send it instructions, including your own.',- anyone: 'Anyone in this agent’s rooms can send it instructions.',- custom: 'Rules say exactly who can send instructions, and in which rooms.',+ owner: 'Only you, in person. Agents cannot talk to it, including your own.',+ anyone: 'Anyone in this agent’s rooms can talk to it.',+ custom: 'Rules say exactly who can talk to it, and in which rooms.',};/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsxindex dd6599f4e..bfd2be4a7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx@@ -202,7 +202,7 @@ function DirectoryResults({<p className="text-xs text-foreground-muted">{hasDirectory? `Type at least ${MIN_QUERY_LENGTH} characters to search the workspace directory.`- : `Type at least ${MIN_QUERY_LENGTH} characters to search the people Switch has seen on ${platform}. It has no directory to search — someone appears here once they have sent a message.`}+ : `Type at least ${MIN_QUERY_LENGTH} characters to search the people Switch has seen on ${platform}. It has no directory to search — you appear here once you have sent a message in a chat the bot is in.`}</p>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.tsindex f9d895418..7e3aa9a9f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';import {hasUnlinkedMessagingApp,+ identityLinkOrderingNote,shouldOfferIdentityLinkOnConnect,unrecognisedMessagingApps,unrecognisedMessagingAppsMessage,@@ -156,3 +157,35 @@ describe('offering the link step after connecting an app', () => {expect(shouldOfferIdentityLinkOnConnect({ directorySearchSupported: false })).toBe(false);});});++describe('what is said instead, where the link step is withheld', () => {+ // Withholding the picker is right; withholding the reason left the user+ // waiting for a prompt that never came (CHOO-2173).+ it('says nothing where the directory can be searched', () => {+ expect(+ identityLinkOrderingNote({ displayName: 'Acme Slack', directorySearchSupported: true })+ ).toBeNull();+ });++ it('gives the ordering where it cannot, naming the app', () => {+ const note = identityLinkOrderingNote({+ displayName: 'Telegram louis',+ directorySearchSupported: false,+ });++ expect(note).toContain('Telegram louis');+ // Be seen first, link second — the part that cannot be guessed.+ expect(note).toContain('send a message');+ expect(note).toContain('link your account');+ });++ it('never contradicts the decision not to offer the step', () => {+ // The two must agree: an app that is offered the picker is not also told+ // to come back later, and one that is withheld is always told why.+ for (const directorySearchSupported of [true, false]) {+ const offered = shouldOfferIdentityLinkOnConnect({ directorySearchSupported });+ const note = identityLinkOrderingNote({ displayName: 'X', directorySearchSupported });+ expect(offered).toBe(note === null);+ }+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.tsindex ef7133039..722e2f41e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts@@ -78,3 +78,23 @@ export function shouldOfferIdentityLinkOnConnect(app: {}): boolean {return app.directorySearchSupported;}++/**+ * What to say instead, on an app whose directory cannot be searched+ * (CHOO-2173).+ *+ * Withholding the picker is right, but on its own it reads as the step having+ * been skipped or forgotten — the user is left waiting for a prompt that is+ * never coming, and nothing says linking is still owed. This is the ordering+ * they cannot infer: be seen first, link second.+ *+ * Null where the directory can be searched, because there the ordinary flow+ * asks at the moment it is offering to act.+ */+export function identityLinkOrderingNote(app: {+ displayName: string;+ directorySearchSupported: boolean;+}): string | null {+ if (app.directorySearchSupported) return null;+ return `${app.displayName} has no directory of users to search, so Switch does not know you there yet. Add the bot to a chat and send a message in it — you can then link your account from this app’s menu, once you are someone Switch has seen.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsxnew file mode 100644index 000000000..8b46dc958--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx@@ -0,0 +1,149 @@+/**+ * When the add-agent dialog's Settings section opens itself (CHOO-2173).+ *+ * The section is folded because its defaults are usually right. They are not+ * right when the owner-only default meets a messaging app with no account+ * linked: the agent then answers nobody there, and the control says so — inside+ * the fold, where the person creating the agent never sees it. So the fold+ * opens itself for exactly that case and no other.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// The panel's siblings reach the renderer IPC bridge at import time, which only+// exists inside Electron. Hoisted so it is in place before those modules are+// evaluated.+const remote = vi.hoisted(() => ({+ bridges: [] as { id: string; displayName: string }[],+ identities: [] as { bridgeId: string }[],+}));++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: vi.fn() },+ rpc: {+ switchServers: {+ listRemoteRooms: () => Promise.resolve([]),+ listRemoteRoomGroups: () => Promise.resolve([]),+ listRemoteExternalUsers: () => Promise.resolve([]),+ listRemoteAgents: () => Promise.resolve([]),+ listRemoteBridges: () => Promise.resolve(remote.bridges),+ listMyIdentities: () => Promise.resolve(remote.identities),+ },+ },+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ servers: [{ id: 'srv-1', name: 'Test' }],+ init: () => Promise.resolve(),+ },+}));++import { AgentSettingsSection } from '@renderer/features/locations/components/add-agent-modal/configure-agent-panel';+import { useConfigureAgentForm } from '@renderer/features/locations/components/add-agent-modal/modes';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ remote.bridges = [];+ remote.identities = [];+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++function Panel() {+ const form = useConfigureAgentForm();+ return (+ <AgentSettingsSection+ form={form}+ serverId="srv-1"+ onAddServer={() => {}}+ onOpenMessagingApps={() => {}}+ />+ );+}++/** Renders the panel and lets the four server queries settle. */+async function renderPanel(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Panel />+ </QueryClientProvider>+ )+ );+ // The warning depends on two queries resolving, and the fold opens in an+ // effect off their result — so flush until the tree stops settling.+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());+ return container;+}++function settingsRow(el: HTMLElement): HTMLElement {+ const found = [...el.querySelectorAll<HTMLElement>('button[aria-expanded]')].find((b) =>+ b.textContent?.includes('Settings')+ );+ expect(found, 'no Settings disclosure row').toBeDefined();+ return found!;+}++describe('the add-agent Settings fold', () => {+ it('opens itself when the owner-only default reaches nobody', async () => {+ remote.bridges = [{ id: 'b-slack', displayName: 'Slack' }];+ remote.identities = [];++ const el = await renderPanel();++ expect(settingsRow(el).getAttribute('aria-expanded')).toBe('true');+ expect(el.textContent).toContain('you have not linked a messaging account');+ });++ it('stays folded when every app has an account linked', async () => {+ remote.bridges = [{ id: 'b-slack', displayName: 'Slack' }];+ remote.identities = [{ bridgeId: 'b-slack' }];++ const el = await renderPanel();++ expect(settingsRow(el).getAttribute('aria-expanded')).toBe('false');+ });++ it('stays folded when the server has no messaging apps at all', async () => {+ // Nothing to link an account on is not a misconfiguration, so there is no+ // warning to surface and no reason to unfold.+ remote.bridges = [];++ const el = await renderPanel();++ expect(settingsRow(el).getAttribute('aria-expanded')).toBe('false');+ });++ it('lets the reader fold it away again', async () => {+ // The fold opens once, as a way of showing the warning. Closing it is an+ // answer, so it must not spring back on the next render.+ remote.bridges = [{ id: 'b-slack', displayName: 'Slack' }];++ const el = await renderPanel();+ await act(async () => settingsRow(el).click());++ expect(settingsRow(el).getAttribute('aria-expanded')).toBe('false');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsxindex 370785b00..6414614bb 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx@@ -14,7 +14,7 @@ vi.hoisted(() => {});/**- * "Who can send instructions", as the person setting it sees it (CHOO-2137).+ * "Who can talk to your agent", as the person setting it sees it (CHOO-2137).** The chooser and the rule editor answer the same question at two levels of* detail, and the thing that goes wrong is the seam between them: the owner anddiff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsxindex 6f50dbe64..72b279cb7 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx@@ -3,7 +3,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it } from 'vitest';/**- * What "Who can send instructions" starts on for a brand-new agent (CHOO-2137).+ * What "Who can talk to your agent" starts on for a brand-new agent (CHOO-2137).** This is the ticket's whole point — an agent created in Switch Console answers* only its owner unless someone says otherwise — and it lives in one line ofdiff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsxnew file mode 100644index 000000000..4cbc59f23--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx@@ -0,0 +1,189 @@+/**+ * Saving a room's description and instructions (CHOO-2173).+ *+ * They used to be written when a field lost focus, so the moment they were+ * stored was the moment you looked away — and in practice leaving the+ * configuration tab was the only thing that reliably did it, which is a strange+ * way to be told your edit counted. These pin the replacement: nothing is+ * written until Save is pressed, the button says whether there is anything to+ * write, and both fields travel in one request.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const updateRoom = vi.hoisted(() => vi.fn());+const getRoomDetail = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: vi.fn() },+ rpc: {+ switchServers: {+ updateRoom,+ getRoomDetail,+ listRemoteAgents: vi.fn(() => Promise.resolve([])),+ },+ agents: { getAgents: vi.fn(() => Promise.resolve([])) },+ },+}));++vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({+ switchRoomsStore: {+ roomServerId: () => 'srv-1',+ canDeleteRoom: () => false,+ },+}));++import { RoomConfigurationPanel } from '@renderer/features/switch-rooms/room-configuration-panel';++const ROOM = {+ id: 'room-1',+ name: 'charlie',+ description: 'The original description',+ instructions: 'The original instructions',+ bridgeType: null,+ bridgeDisplayName: null,+ externalChannelUrl: null,+ agentIds: [],+ connectedUserNames: [],+};++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ updateRoom.mockReset();+ updateRoom.mockImplementation((params: Record<string, unknown>) =>+ Promise.resolve({ ...ROOM, ...params })+ );+ getRoomDetail.mockReset();+ getRoomDetail.mockResolvedValue(ROOM);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function renderPanel(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <RoomConfigurationPanel roomId="room-1" />+ </QueryClientProvider>+ )+ );+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());+ return container;+}++function saveButton(el: HTMLElement): HTMLButtonElement {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ /^Save/.test(b.textContent?.trim() ?? '')+ );+ expect(found, 'no Save button').toBeDefined();+ return found!;+}++/** Type into a controlled input/textarea the way React will notice. */+async function type(field: HTMLInputElement | HTMLTextAreaElement, value: string) {+ const proto =+ field instanceof HTMLTextAreaElement+ ? HTMLTextAreaElement.prototype+ : HTMLInputElement.prototype;+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;+ await act(async () => {+ setter.call(field, value);+ field.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++function description(el: HTMLElement): HTMLInputElement {+ return el.querySelector<HTMLInputElement>('input[placeholder="What this room is for"]')!;+}++function instructions(el: HTMLElement): HTMLTextAreaElement {+ return el.querySelector<HTMLTextAreaElement>('textarea')!;+}++describe('a room’s description and instructions', () => {+ it('offers nothing to save until something is edited', async () => {+ const el = await renderPanel();++ expect(saveButton(el).disabled).toBe(true);+ });++ it('does not write anything just because a field was left', async () => {+ // The old behaviour, and the whole point of the change.+ const el = await renderPanel();+ const field = description(el);+ await type(field, 'Edited but not saved');+ await act(async () => field.dispatchEvent(new FocusEvent('blur', { bubbles: true })));++ expect(updateRoom).not.toHaveBeenCalled();+ });++ it('says there are unsaved changes rather than leaving it ambiguous', async () => {+ const el = await renderPanel();+ await type(description(el), 'Edited but not saved');++ expect(el.textContent).toContain('Unsaved changes');+ expect(saveButton(el).disabled).toBe(false);+ });++ it('writes both fields in one request when Save is pressed', async () => {+ // One request, so the pair is stored together or not at all — and the+ // untouched field is sent as it stands rather than being left out.+ const el = await renderPanel();+ await type(instructions(el), 'Be brief');++ await act(async () => saveButton(el).click());++ expect(updateRoom).toHaveBeenCalledTimes(1);+ expect(updateRoom).toHaveBeenCalledWith({+ serverId: 'srv-1',+ roomId: 'room-1',+ description: 'The original description',+ instructions: 'Be brief',+ });+ });++ it('settles back to nothing-to-save once it has written', async () => {+ const el = await renderPanel();+ await type(description(el), 'A new description');++ await act(async () => saveButton(el).click());+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());++ expect(el.textContent).toContain('Saved.');+ expect(saveButton(el).disabled).toBe(true);+ });++ it('says so in the server’s own words when the write is refused', async () => {+ updateRoom.mockRejectedValueOnce(new Error('room is archived'));+ const el = await renderPanel();+ await type(description(el), 'A new description');++ await act(async () => saveButton(el).click());+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());++ expect(el.textContent).toContain('room is archived');+ // Still offered, because the edit is still there and still unwritten.+ expect(saveButton(el).disabled).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.tsindex 0354f8ffc..653317ebe 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts@@ -28,7 +28,7 @@ export function policyNamesOwner(policy: AddressingPolicy | null): boolean {}/**- * What the "Who can send instructions" chooser offers.+ * What the "Who can talk to your agent" chooser offers.** Three answers people actually want, each backed by one policy shape, and* `custom` — the rule editor — for everything else.diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex 200cd30a2..6ccd07223 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex 159b6be1f..fe34e2a96 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differdiff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 071cf89f0..b29d75e09 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -82,7 +82,7 @@ from switch_core.db.stores.agent_runtime_state_store import (from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.deeplinks import switchdash_to_gateway+from switch_core.deeplinks import deeplink_for_platformfrom switch_core.events import (LlmCallReport as MatrixLlmCallReport,)@@ -1262,25 +1262,37 @@ class ProtocolService:transient routing — reported on every refresh, and only a change movesanything.- The `switchdash://` deeplink is rewritten to a gateway HTTP redirect when- `GATEWAY_PUBLIC_URL` is configured, so the "Open in Switch Console" link is- clickable on platforms that only linkify http(s) (Discord). The rewritten- link is what gets persisted and emitted, so both the bridged status- message and the `!status` command surface a clickable link. When unset,- the raw `switchdash://` deeplink is left untouched (today's behavior).+ The `switchdash://` deeplink is rewritten to a gateway HTTP redirect for+ platforms that linkify only http(s) (Discord, Telegram), so the "Open in+ Switch Console" link is clickable there. It takes both a configured+ `GATEWAY_PUBLIC_URL` and a room whose bridge needs the hop: the redirect+ lands in the same place the deeplink already points, so handing it to a+ platform that renders the scheme — Mattermost, Slack — sends the reader+ through the browser for nothing. A room on no bridge keeps the raw link+ for the same reason. When `GATEWAY_PUBLIC_URL` is unset the raw deeplink+ is left untouched whatever the platform.++ The result is what gets persisted and emitted, so the bridged status+ message and the `!status` command surface the same link."""- if deeplink_url is not None and self.config.gateway_public_url:- deeplink_url = (- switchdash_to_gateway(deeplink_url, self.config.gateway_public_url)- or deeplink_url- )-room = await self.require_room_member(agent_id, room_id)async with self.session_factory() as session:agent = await self.agent_store.get(session, agent_id)if agent is None:raise ValueError(f"Agent not found: {agent_id}")room_row = await self.room_store.get(session, room.id)+ bridge_type: str | None = None+ if room_row is not None and room_row.bridge_id is not None:+ bridge = await self.bridge_store.get(session, room_row.bridge_id)+ bridge_type = bridge.type if bridge is not None else None+ deeplink_url = deeplink_for_platform(+ deeplink_url,+ self.config.gateway_public_url,+ # A room on no bridge has no platform to accommodate, so it+ # keeps the link Switch Console built.+ bridge_type is None+ or self.collab_lifecycle.renders_custom_url_schemes(bridge_type),+ )await self.agent_runtime_state_store.upsert(session,agent_id,diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 8f680b1c6..909ea34ca 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -78,6 +78,22 @@ class CollaborationAdapter(ABC):#: instead of each bridge discovering it in its own way.renders_custom_url_schemes: ClassVar[bool] = True+ #: Whether a runtime-state report with no thread of its own should anchor+ #: to the message the agent is working on.+ #:+ #: A report only carries a `thread_id` when the agent was addressed inside+ #: an existing thread. Addressed at the conversation root it carries none,+ #: while the agent's reply still opens a thread on the triggering message —+ #: so the status and the answer to it end up in two different places.+ #: Where this is True the anchor the agent reports (the last message it was+ #: actually handed) stands in, putting the status in the thread the reply+ #: will land in.+ #:+ #: Off by default: on a platform that renders a thread as a side panel+ #: rather than inline, moving the status out of the channel hides it, and+ #: that trade is the platform's to make.+ runtime_state_follows_anchor: ClassVar[bool] = False+def __init__(self) -> None:self._on_message: Callable[[InboundMessage], Awaitable[None]] | None = Noneself._on_command: Callable[[InboundCommand], Awaitable[None]] | None = None@@ -284,6 +300,7 @@ class CollaborationAdapter(ABC):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Serialise against any other runtime-indicator work for this agent,then apply the state. Adapters override ``_apply_runtime_state``."""@@ -296,6 +313,7 @@ class CollaborationAdapter(ABC):thread_root_id=thread_root_id,deeplink_url=deeplink_url,detail=detail,+ trigger_thread_root_id=trigger_thread_root_id,)async def reposition_runtime_state(@@ -317,6 +335,7 @@ class CollaborationAdapter(ABC):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Surface a Switch Console-managed agent's runtime state on the channel.@@ -325,8 +344,17 @@ class CollaborationAdapter(ABC):show a persistent status message they remove (Slack) or edit to aterminal marker (Mattermost, whose delete leaves a tombstone).- ``thread_root_id``, when set, is the external thread the triggering- message belonged to; the state surfaces in that thread.+ ``thread_root_id``, when set, is the external thread the state belongs+ in; the state surfaces there.++ ``trigger_thread_root_id`` is where the triggering message itself sits,+ and is None when it came from the channel root. The two differ on an+ adapter that pins a status to a thread the conversation is not in yet+ (see ``runtime_state_follows_anchor``): the status belongs in the+ thread, but a typing indicator belongs where the person who is waiting+ for it is looking. Defaulted because only an adapter that draws the+ distinction reads it, and its callers should not have to restate a+ value the other adapters ignore.``deeplink_url``, when set, is an https link (served by the gateway) thatopens the agent's session in the Switch Console desktop app; adapters thatdiff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 6ee788d7e..7c1231dd7 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -1449,6 +1449,11 @@ class BridgeCore:message was in a thread, the state surfaces in that same thread: theevent's `thread_id` (a Matrix event id) is resolved to the externalthread root via the same map outbound replies use.++ Addressed at the conversation root there is no `thread_id`, and on an+ adapter that asks for it the reported anchor — the last message the+ agent was handed — stands in, so the status joins the thread the reply+ opens on that message instead of sitting at the channel root beside it."""channel_id = self._find_channel(matrix_room_id=room.room_id)if channel_id is None:@@ -1458,18 +1463,30 @@ class BridgeCore:)return- thread_root_ref: str | None = None+ # Where the triggering message itself sits — None when it came from the+ # channel root. This is what a typing indicator follows.+ trigger_thread_ref: str | None = Noneif event.thread_id is not None:- thread_root_ref = await self._external_post_for_matrix_event(+ trigger_thread_ref = await self._external_post_for_matrix_event(event.thread_id)- if thread_root_ref is None:- logger.debug(- "[BRIDGE-OUT] no external post mapped for runtime-state thread "- "%s; surfacing at channel root in %s",- event.thread_id,- channel_id,- )++ # Where a persistent status belongs, which on an adapter that asks for+ # it is the thread the reply will open on the message being worked on.+ anchor_ref = event.thread_id+ if anchor_ref is None and self._adapter.runtime_state_follows_anchor:+ anchor_ref = event.anchor_event_id++ thread_root_ref: str | None = trigger_thread_ref+ if anchor_ref is not None and anchor_ref != event.thread_id:+ thread_root_ref = await self._external_post_for_matrix_event(anchor_ref)+ if anchor_ref is not None and thread_root_ref is None:+ logger.debug(+ "[BRIDGE-OUT] no external post mapped for runtime-state thread "+ "%s; surfacing at channel root in %s",+ anchor_ref,+ channel_id,+ )await self._adapter.apply_runtime_state(channel_id,@@ -1479,6 +1496,7 @@ class BridgeCore:thread_root_id=thread_root_ref,deeplink_url=event.deeplink_url,detail=event.detail,+ trigger_thread_root_id=trigger_thread_ref,)await self._follow_reported_anchor(channel_id,diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 84a5967e4..bf2e46581 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -576,6 +576,7 @@ class DiscordAdapter(CollaborationAdapter):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Render runtime state as persistent, truly-deletable status messages.diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 3e5769e8d..84b083959 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -131,6 +131,24 @@ class CollaborationBridgeLifecycleService:return Truereturn adapter_cls.supports_directory_search+ def renders_custom_url_schemes(self, bridge_type: str) -> bool:+ """Whether this platform makes a `switchdash://` link clickable.++ Decides whether the "Open in Switch Console" deeplink is rewritten to+ the gateway's https redirect. The redirect exists for platforms that+ linkify only http(s) — a hop through the browser that lands in the same+ place, but a hop. A platform that renders the scheme should be handed+ the real link.++ Read from the adapter class for the same reason as+ `supports_channel_creation`. An unknown type is reported as rendering+ it, matching the base class default.+ """+ adapter_cls = self._adapter_registry.get(bridge_type)+ if adapter_cls is None:+ return True+ return adapter_cls.renders_custom_url_schemes+def get_config_schema(self, bridge_type: str) -> dict[str, object]:config_cls = self._config_registry.get(bridge_type)if config_cls is None:diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex aff48ed49..8df4d7c5f 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -11,7 +11,7 @@ import uuidfrom collections import OrderedDictfrom collections.abc import Awaitable, Callablefrom dataclasses import replace-from typing import Any+from typing import Any, ClassVarimport httpximport requests as sync_requests@@ -64,6 +64,11 @@ class MattermostConnectionConfig(BridgeConnectionConfig):class MattermostAdapter(CollaborationAdapter):+ #: Mattermost renders a thread inline under its root as well as in the+ #: side panel, so anchoring the status to the message being worked on keeps+ #: it beside the answer instead of stranding it at the channel root.+ runtime_state_follows_anchor: ClassVar[bool] = True+def __init__(self, *, config: MattermostConnectionConfig) -> None:super().__init__()self._config = config@@ -420,7 +425,18 @@ class MattermostAdapter(CollaborationAdapter):logger.debug("Mattermost set typing: %s", is_typing)if not is_typing:return+ await self._post_typing(channel_id, sender_name, None)++ async def _post_typing(+ self, channel_id: str, sender_name: str, thread_root_id: str | None+ ) -> None:+ """Tell Mattermost the agent's bot is typing, in a thread when given one.+ Mattermost expires the indicator on its own after a few seconds, so+ this is a one-shot nudge rather than something to switch off. Without+ `parent_id` it only ever shows at the channel root, which is the wrong+ place when the agent is answering inside a thread.+ """bot_info = self._agent_bots.get(sender_name)if not bot_info:logger.warning("No bot info found for sender name %s", sender_name)@@ -432,13 +448,17 @@ class MattermostAdapter(CollaborationAdapter):logger.warning("No bot driver found for sender name %s", sender_name)return+ body: dict[str, str] = {"channel_id": channel_id}+ if thread_root_id is not None:+ body["parent_id"] = thread_root_id+try:await loop.run_in_executor(None,bot_driver.client.make_request,"post",f"/users/{bot_info['user_id']}/typing",- {"channel_id": channel_id},+ body,)except Exception as e:logger.debug("Failed to send MM typing for %s: %s", sender_name, e)@@ -455,6 +475,7 @@ class MattermostAdapter(CollaborationAdapter):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Surface runtime state as a posted message that is **never deleted**.@@ -495,6 +516,17 @@ class MattermostAdapter(CollaborationAdapter):thread_root_id=thread_root_id,started_at=time.monotonic(),)+ # Where the message came from, not where the status went. The+ # status is pinned to the thread the answer will land in, but+ # typing is for whoever is waiting — and someone who wrote at+ # the channel root is watching the root, not a thread they have+ # not opened.+ #+ # Only as the turn opens. Mattermost expires a typing indicator+ # after a few seconds, and the posted message is what carries+ # the state from there on — repeating it on every activity+ # refresh would say "typing" for as long as the agent runs.+ await self._post_typing(channel_id, agent_name, trigger_thread_root_id)elif state == "awaiting-input":ref = await self._ping_operator(channel_id, agent_name, mention_handle, thread_root_id, deeplink_urldiff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex fcb57c8a0..cf0e8f4de 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -467,6 +467,7 @@ class SlackAdapter(CollaborationAdapter):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Render runtime state as persistent, truly-deletable status messages.diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 6a7bea1fb..726f4ba45 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -548,6 +548,7 @@ class TeamsAdapter(CollaborationAdapter):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Persistent status messages, mirroring Slack.diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex b919829ad..bb902f8f2 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -867,6 +867,7 @@ class TelegramAdapter(CollaborationAdapter):thread_root_id: str | None,deeplink_url: str | None = None,detail: str | None = None,+ trigger_thread_root_id: str | None = None,) -> None:"""Render runtime state as persistent, deletable status messages.diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex 5a0f8918d..232bda3f5 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -103,6 +103,12 @@ class _PendingAttachmentGroup:total: intparts: dict[int, AttachmentRef] = field(default_factory=dict)body: str = ""+ # Whether any part of the group addressed this agent. Addressing is read off+ # the message text, and the text rides on part 0 alone — every other part's+ # body is its bare filename. Answering from whichever part completes the+ # group would therefore say "not addressed" for any group not finishing on+ # part 0, which is every group a bridge sends in order.+ addressed: bool = False# The index-0 event, kept so a group that has to be flushed incomplete is# still anchored on its canonical first part (message_id / timestamp /# sender) rather than on whichever part happened to arrive last.@@ -373,7 +379,13 @@ class AgentClient(ClientBase[ClientConfig]):body,format="markdown",mentions=[event.sender],- thread_root_id=reply_thread_root,+ # Answer where the question was asked: `thread_id`, not the+ # reply root. They differ for a message at the conversation+ # root, where the reply root is the message itself — which+ # opens a thread off it, so a one-line "starting a session"+ # buries itself somewhere nobody is looking, away from the+ # answer that follows it.+ thread_root_id=thread_id,extra_content={AUTO_REPLY_FLAG: True},)@@ -466,12 +478,13 @@ class AgentClient(ClientBase[ClientConfig]):group_id, _PendingAttachmentGroup(total=total))pending.parts[index] = attachment+ pending.addressed = pending.addressed or is_addressedif index == 0:pending.body = event.bodypending.first_event = eventif len(pending.parts) < total:self._schedule_attachment_group_flush(- group_id, room, event, meta, is_addressed, sender_name, thread_id+ group_id, room, event, meta, sender_name, thread_id)return@@ -483,7 +496,7 @@ class AgentClient(ClientBase[ClientConfig]):room,pending.first_event or event,meta,- is_addressed,+ pending.addressed,sender_name,thread_id,[pending.parts[i] for i in sorted(pending.parts)],@@ -496,7 +509,6 @@ class AgentClient(ClientBase[ClientConfig]):room: MatrixRoom,event: RoomMessageMedia,meta: RoomMeta,- is_addressed: bool,sender_name: str,thread_id: str | None,) -> None:@@ -517,7 +529,7 @@ class AgentClient(ClientBase[ClientConfig]):ATTACHMENT_GROUP_TIMEOUT_SECONDS,lambda: asyncio.create_task(self._flush_incomplete_attachment_group(- group_id, room, event, meta, is_addressed, sender_name, thread_id+ group_id, room, event, meta, sender_name, thread_id)),)@@ -533,7 +545,6 @@ class AgentClient(ClientBase[ClientConfig]):room: MatrixRoom,event: RoomMessageMedia,meta: RoomMeta,- is_addressed: bool,sender_name: str,thread_id: str | None,) -> None:@@ -562,7 +573,7 @@ class AgentClient(ClientBase[ClientConfig]):room,anchor,meta,- is_addressed,+ pending.addressed,sender_name,thread_id,[pending.parts[i] for i in sorted(pending.parts)],diff --git a/core/switch_core/deeplinks.py b/core/switch_core/deeplinks.pyindex 4aa10d34d..98259a76b 100644--- a/core/switch_core/deeplinks.py+++ b/core/switch_core/deeplinks.py@@ -36,6 +36,29 @@ def switchdash_to_gateway(deeplink_url: str, gateway_public_url: str) -> str | Nreturn f"{base}{DEEPLINK_REDIRECT_PATH}{query}"+def deeplink_for_platform(+ deeplink_url: str | None,+ gateway_public_url: str | None,+ platform_renders_custom_schemes: bool,+) -> str | None:+ """Which form of the deeplink to post on a given platform.++ The redirect lands where the deeplink already points, so it buys nothing+ except a trip through the browser. It is worth that only where the raw+ scheme would not be a link at all. Three things have to be true to rewrite:+ there is a deeplink, the gateway has a public URL to redirect from, and the+ platform will not render the scheme itself.++ Returns the link to post — unchanged when any of those does not hold, and+ unchanged too if it is not a session deeplink this can rewrite.+ """+ if deeplink_url is None or not gateway_public_url:+ return deeplink_url+ if platform_renders_custom_schemes:+ return deeplink_url+ return switchdash_to_gateway(deeplink_url, gateway_public_url) or deeplink_url++def gateway_query_to_switchdash(query: str) -> str:"""Reconstruct the `switchdash://session?…` deeplink the redirect targets.diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.pynew file mode 100644index 000000000..39974487f--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py@@ -0,0 +1,161 @@+"""Where a runtime status surfaces when the agent was addressed at the root.++A runtime-state report only carries a `thread_id` when the agent was addressed+inside an existing thread. Message the agent at channel level and it carries+none — yet the agent's reply still opens a thread on the triggering message. The+status and the answer to it then sit in two different places, which is what the+reader actually notices: a "working on it…" line stranded in the channel while+the reply is somewhere behind a "1 reply" link.++The report does say which message the agent is working on — the anchor — so on+an adapter that asks for it that stands in for the missing thread. These pin+down that it is used only where it was asked for, and never over a real thread.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.events import AgentRuntimeStateEvent+++class _FakeAdapter:+ def __init__(self, *, follows_anchor: bool) -> None:+ self.runtime_state_follows_anchor = follows_anchor+ self.applied: list[str | None] = []+ self.trigger_threads: list[str | None] = []++ def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:+ return []++ async def apply_runtime_state(+ self,+ channel_id: str,+ agent_name: str,+ state: str,+ *,+ mention_handle: str | None,+ thread_root_id: str | None,+ deeplink_url: str | None,+ detail: str | None,+ trigger_thread_root_id: str | None = None,+ ) -> None:+ self.applied.append(thread_root_id)+ self.trigger_threads.append(trigger_thread_root_id)++ async def reposition_runtime_state(+ self, channel_id: str, agent_name: str, thread_root_id: str | None+ ) -> None:+ return None+++def _bridge(*, follows_anchor: bool, posts: dict[str, str]) -> Any:+ """A BridgeCore stand-in wired to the real runtime-state handler.++ `posts` is the message map: Matrix event id -> external post id.+ """+ adapter = _FakeAdapter(follows_anchor=follows_anchor)++ async def external_post_for_matrix_event(event_id: str) -> str | None:+ return posts.get(event_id)++ ns = SimpleNamespace(+ _adapter=adapter,+ _indicator_move_timers={},+ _indicator_move_targets={},+ _reported_anchors={},+ _find_channel=lambda **kwargs: "chan-1",+ _external_post_for_matrix_event=external_post_for_matrix_event,+ adapter_spy=adapter,+ )+ for name in (+ "handle_agent_runtime_state",+ "_follow_reported_anchor",+ "_schedule_indicator_move",+ "_run_indicator_move",+ ):+ setattr(ns, name, getattr(BridgeCore, name).__get__(ns))+ return ns+++def _report(+ bridge: Any, *, thread_id: str | None, anchor_event_id: str | None+) -> str | None:+ """Deliver one "working" report and return where the status was put."""+ event = AgentRuntimeStateEvent(+ agent_id="agent-1",+ agent_name="worker",+ room_id="!room:switch.local",+ state="working",+ thread_id=thread_id,+ anchor_event_id=anchor_event_id,+ )+ room = SimpleNamespace(room_id="!room:switch.local")+ asyncio.run(bridge.handle_agent_runtime_state(room, event))+ return bridge.adapter_spy.applied[-1]+++def test_the_status_joins_the_thread_the_reply_will_open() -> None:+ # Addressed at the channel root: no thread of its own, but the anchor names+ # the message being worked on, and that is where the reply goes.+ bridge = _bridge(follows_anchor=True, posts={"$trigger": "post-trigger"})++ assert _report(bridge, thread_id=None, anchor_event_id="$trigger") == "post-trigger"+++def test_a_real_thread_still_wins_over_the_anchor() -> None:+ # Addressed inside a thread, having since been handed a newer message. The+ # thread the turn belongs to is the one it was started in.+ bridge = _bridge(+ follows_anchor=True,+ posts={"$thread": "post-thread", "$newer": "post-newer"},+ )++ assert _report(bridge, thread_id="$thread", anchor_event_id="$newer") == (+ "post-thread"+ )+++def test_an_adapter_that_did_not_ask_keeps_the_status_at_the_root() -> None:+ # Slack renders a thread in a side panel, so moving the status into one+ # hides it. Only an adapter that opts in gets the fallback.+ bridge = _bridge(follows_anchor=False, posts={"$trigger": "post-trigger"})++ assert _report(bridge, thread_id=None, anchor_event_id="$trigger") is None+++def test_an_unmapped_anchor_falls_back_to_the_root() -> None:+ # The triggering post was never relayed through this bridge, so there is no+ # post to hang the thread on. Root beats guessing.+ bridge = _bridge(follows_anchor=True, posts={})++ assert _report(bridge, thread_id=None, anchor_event_id="$unknown") is None+++def test_a_report_with_neither_stays_at_the_root() -> None:+ bridge = _bridge(follows_anchor=True, posts={"$trigger": "post-trigger"})++ assert _report(bridge, thread_id=None, anchor_event_id=None) is None+++def test_the_trigger_keeps_its_own_place_even_as_the_status_moves() -> None:+ # The two are reported separately: the status goes into the thread the+ # answer will open, the trigger says where the person waiting is looking.+ # Addressed at channel level, that is the root — so no thread.+ bridge = _bridge(follows_anchor=True, posts={"$trigger": "post-trigger"})++ _report(bridge, thread_id=None, anchor_event_id="$trigger")++ assert bridge.adapter_spy.applied == ["post-trigger"]+ assert bridge.adapter_spy.trigger_threads == [None]+++def test_a_threaded_trigger_reports_its_thread() -> None:+ bridge = _bridge(follows_anchor=True, posts={"$thread": "post-thread"})++ _report(bridge, thread_id="$thread", anchor_event_id="$thread")++ assert bridge.adapter_spy.trigger_threads == ["post-thread"]diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.pyindex f85bf2393..1472db4e6 100644--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py@@ -55,6 +55,7 @@ class _Recorder:self.deletes: list[str] = []self.patches: list[tuple[str, str]] = []self.sends: list[tuple[str, str, str, str | None]] = []+ self.typing: list[tuple[str, str, str | None]] = []self._next_id = iter(f"post-{n}" for n in range(2, 20))def install(self, adapter: MattermostAdapter) -> None:@@ -73,9 +74,15 @@ class _Recorder:self.sends.append((channel_id, sender_name, content, thread_root_id))return next(self._next_id)+ async def post_typing(+ channel_id: str, sender_name: str, thread_root_id: str | None+ ) -> None:+ self.typing.append((channel_id, sender_name, thread_root_id))+adapter.delete_message = delete_message # type: ignore[method-assign]adapter._patch_post_as = patch_post_as # type: ignore[method-assign]adapter.send_message = send_message # type: ignore[method-assign]+ adapter._post_typing = post_typing # type: ignore[method-assign]def _seed_indicator(@@ -217,6 +224,89 @@ def test_idle_without_an_indicator_does_nothing() -> None:assert recorder.deletes == []+def test_the_turn_opens_with_a_typing_nudge_where_the_message_came_from() -> None:+ # Addressed inside a thread: the reader is watching that thread, so the+ # nudge goes there. Without a parent Mattermost shows it at the root.+ adapter = _adapter()+ recorder = _Recorder()+ recorder.install(adapter)++ _run(+ adapter.apply_runtime_state(+ "chan-1",+ "worker",+ "working",+ mention_handle=None,+ thread_root_id="root-9",+ trigger_thread_root_id="root-9",+ )+ )++ assert recorder.typing == [("chan-1", "worker", "root-9")]+++def test_typing_stays_at_the_root_when_that_is_where_the_message_was() -> None:+ # The status is pinned into the thread the answer will open, but whoever+ # wrote at channel level is watching the channel — a typing indicator+ # inside a thread they have not opened is one they never see.+ adapter = _adapter()+ recorder = _Recorder()+ recorder.install(adapter)++ _run(+ adapter.apply_runtime_state(+ "chan-1",+ "worker",+ "working",+ mention_handle=None,+ thread_root_id="post-trigger",+ trigger_thread_root_id=None,+ )+ )++ assert recorder.sends[0][3] == "post-trigger"+ assert recorder.typing == [("chan-1", "worker", None)]+++def test_typing_is_not_repeated_on_every_activity_refresh() -> None:+ # Mattermost expires the indicator after a few seconds, so replaying it+ # would claim the agent is typing for as long as the turn runs. The posted+ # status carries the state from there on.+ adapter = _adapter()+ recorder = _Recorder()+ recorder.install(adapter)++ async def turn() -> None:+ for detail in (None, "Ran tool Edit", "Running tests"):+ await adapter.apply_runtime_state(+ "chan-1",+ "worker",+ "working",+ mention_handle=None,+ thread_root_id=None,+ detail=detail,+ )++ _run(turn())++ assert len(recorder.typing) == 1+++def test_a_retired_turn_does_not_nudge() -> None:+ adapter = _adapter()+ recorder = _Recorder()+ recorder.install(adapter)+ _seed_indicator(adapter)++ _run(+ adapter.apply_runtime_state(+ "chan-1", "worker", "idle", mention_handle=None, thread_root_id=None+ )+ )++ assert recorder.typing == []++def test_elapsed_is_written_the_way_it_is_read() -> None:assert _format_elapsed(0.4) == "0s"assert _format_elapsed(8.9) == "8s"diff --git a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py b/core/tests/switch_core/clients/test_agent_client_attachment_groups.pyindex 85c4010ae..9ba4570b9 100644--- a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py+++ b/core/tests/switch_core/clients/test_agent_client_attachment_groups.py@@ -58,8 +58,12 @@ def _fake_client() -> SimpleNamespace:async def _resolve_room_meta(_matrix_room_id: str) -> RoomMeta:return meta- async def _compute_addressed(_event: Any, _meta: RoomMeta) -> bool:- return True+ async def _compute_addressed(event: Any, _meta: RoomMeta) -> bool:+ # Mirrors production, where addressing is read off the message text.+ # Standing in a constant `True` here is what let the coalescing bug+ # through: every part looked addressed, including the caption-less ones+ # that in reality address nobody.+ return f"@{ns.agent.name}" in getattr(event, "body", "")async def _gate_addressed(_room: Any, _event: Any, _meta: Any, _root: Any, is_addressed: bool@@ -293,3 +297,113 @@ async def test_group_timeout_bounds_the_group_not_the_gap_between_parts() -> Nonassert "incomplete attachment group: 3 of 4" in payload.bodyassert client._attachment_groups == {}assert client._attachment_group_timers == {}+++class TestAddressingSurvivesCoalescing:+ """Two screenshots in one Slack message reached nobody (CHOO-2173).++ Matrix has no multi-attachment event, so one such message is split: the+ text and its `@mention` ride on part 0 and every later part is a bare+ file. Addressing was read from whichever part completed the group — a+ filename — so the reassembled message claimed to address nobody and each+ consumer, correctly, ignored it.+ """++ async def test_a_mention_on_part_zero_addresses_the_whole_group(self) -> None:+ client = _fake_client()+ for index, name in [(0, "one.png"), (1, "two.png")]:+ await AgentClient.on_media(+ client,+ _room(),+ _media_event(+ body="@agent-a look at these" if index == 0 else name,+ filename=name if index == 0 else None,+ event_id=f"$part-{index}",+ group={"id": "grp-addr", "index": index, "total": 2},+ ),+ )++ assert len(client.queue.events) == 1+ payload = client.queue.events[0].payload+ assert payload.addressed is True+ # The text travels with the images rather than being left on the part+ # it arrived on.+ assert payload.body == "@agent-a look at these"+ assert [a.filename for a in payload.attachments] == ["one.png", "two.png"]++ async def test_it_holds_when_the_captioned_part_arrives_last(self) -> None:+ client = _fake_client()+ for index, name in [(1, "two.png"), (0, "one.png")]:+ await AgentClient.on_media(+ client,+ _room(),+ _media_event(+ body="@agent-a look at these" if index == 0 else name,+ filename=name if index == 0 else None,+ event_id=f"$part-{index}",+ group={"id": "grp-addr-rev", "index": index, "total": 2},+ ),+ )++ assert client.queue.events[0].payload.addressed is True++ async def test_a_group_that_mentions_nobody_stays_unaddressed(self) -> None:+ # The fix must carry addressing across the group, not assert it.+ client = _fake_client()+ for index, name in [(0, "one.png"), (1, "two.png")]:+ await AgentClient.on_media(+ client,+ _room(),+ _media_event(+ body="just some pictures" if index == 0 else name,+ filename=name if index == 0 else None,+ event_id=f"$part-{index}",+ group={"id": "grp-unaddr", "index": index, "total": 2},+ ),+ )++ assert client.queue.events[0].payload.addressed is False++ async def test_an_incomplete_group_is_still_addressed(self) -> None:+ # A batch that never completes is delivered by the safety net, and+ # losing a file is no reason to also lose who it was for.+ original = ac.ATTACHMENT_GROUP_TIMEOUT_SECONDS+ ac.ATTACHMENT_GROUP_TIMEOUT_SECONDS = 0.01+ try:+ client = _fake_client()+ await AgentClient.on_media(+ client,+ _room(),+ _media_event(+ body="@agent-a two of three",+ filename="one.png",+ event_id="$part-0",+ group={"id": "grp-addr-partial", "index": 0, "total": 3},+ ),+ )+ await AgentClient.on_media(+ client,+ _room(),+ _media_event(+ body="two.png",+ event_id="$part-1",+ group={"id": "grp-addr-partial", "index": 1, "total": 3},+ ),+ )+ await asyncio.sleep(0.15)+ finally:+ ac.ATTACHMENT_GROUP_TIMEOUT_SECONDS = original++ assert len(client.queue.events) == 1+ payload = client.queue.events[0].payload+ assert payload.addressed is True+ assert "@agent-a two of three" in payload.body++ async def test_a_single_attachment_is_unaffected(self) -> None:+ # One screenshot always worked; it takes no group and no buffering.+ client = _fake_client()+ await AgentClient.on_media(+ client, _room(), _media_event(body="@agent-a one picture")+ )++ assert client.queue.events[0].payload.addressed is Truediff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.pyindex b694ffa91..246fd035d 100644--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py@@ -161,16 +161,41 @@ async def test_no_session_reply_tags_distinct_asker_and_operator() -> None:assert "@operator" in body-async def test_no_session_reply_threads_under_root_level_mention() -> None:- # CHOO-586: a root-level mention (no existing thread) must still get a- # threaded reply — the reply starts a NEW thread rooted at the triggering- # message itself, rather than posting at the channel root. PR #115 only- # handled the already-in-a-thread case; this is the remaining edge case.- send_message = _Recorder()- room = SimpleNamespace(room_id="!matrix:server")- await AgentClient.on_message(_fake_self(send_message), room, _event(thread_id=None))-- assert len(send_message.calls) == 1- # Falls back to the triggering event's own id, starting a thread under it.- assert send_message.calls[0]["thread_root_id"] == "$trigger"+class TestUnavailableReplyGoesWhereItWasAsked:+ """Where "Starting a session to handle this" lands (CHOO-2173).++ It used to reply onto the triggering message, which for a message at the+ conversation root means opening a thread off it. So asking at the root got+ a one-line notice tucked into a new thread, away from where the asker was+ looking and away from the answer that follows.++ This reverses CHOO-586, which made the root case start a thread on purpose.+ The reply is now placed the same way the typing indicator already is: in the+ thread when asked in a thread, at the root when asked at the root.+ """++ @pytest.mark.asyncio+ async def test_asked_at_the_root_it_answers_at_the_root(self) -> None:+ send_message = _Recorder()+ room = SimpleNamespace(room_id="!matrix:server")++ await AgentClient.on_message(+ _fake_self(send_message), room, _event(thread_id=None)+ )++ assert len(send_message.calls) == 1+ # Not "$trigger": that would open a thread on the asker's message.+ assert send_message.calls[0]["thread_root_id"] is None++ @pytest.mark.asyncio+ async def test_asked_in_a_thread_it_stays_in_that_thread(self) -> None:+ # The other half of the rule — replying at the root here would strand+ # the notice away from the conversation it belongs to.+ send_message = _Recorder()+ room = SimpleNamespace(room_id="!matrix:server")++ await AgentClient.on_message(+ _fake_self(send_message), room, _event(thread_id="$thread-root")+ )++ assert send_message.calls[0]["thread_root_id"] == "$thread-root"diff --git a/core/tests/switch_core/test_deeplinks.py b/core/tests/switch_core/test_deeplinks.pyindex 9721da038..dfed30833 100644--- a/core/tests/switch_core/test_deeplinks.py+++ b/core/tests/switch_core/test_deeplinks.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom switch_core.deeplinks import (DEEPLINK_REDIRECT_PATH,+ deeplink_for_platform,gateway_query_to_switchdash,switchdash_to_gateway,)@@ -9,6 +10,38 @@ from switch_core.deeplinks import (_DEEPLINK = "switchdash://session?server=https%3A%2F%2Fs&agent=a&room=r&session=x"+class TestDeeplinkForPlatform:+ """Which form of the link a platform is given (CHOO-2173).++ The gateway redirect exists for platforms that will not linkify a custom+ scheme — Discord, Telegram. It was being handed to every platform on any+ deployment that configured a gateway URL, which every managed stack does,+ so Mattermost was sending readers through the browser to reach a link its+ own client would have opened.+ """++ def test_a_platform_that_renders_the_scheme_gets_the_real_link(self) -> None:+ assert deeplink_for_platform(_DEEPLINK, "https://gw.example", True) == _DEEPLINK++ def test_a_platform_that_does_not_gets_the_redirect(self) -> None:+ assert deeplink_for_platform(_DEEPLINK, "https://gw.example", False) == (+ "https://gw.example/deeplink/session"+ "?server=https%3A%2F%2Fs&agent=a&room=r&session=x"+ )++ def test_without_a_gateway_url_there_is_nothing_to_rewrite_to(self) -> None:+ assert deeplink_for_platform(_DEEPLINK, None, False) == _DEEPLINK++ def test_no_deeplink_stays_no_deeplink(self) -> None:+ assert deeplink_for_platform(None, "https://gw.example", False) is None++ def test_a_link_that_is_not_a_session_deeplink_is_left_alone(self) -> None:+ assert (+ deeplink_for_platform("https://elsewhere/x", "https://gw.example", False)+ == "https://elsewhere/x"+ )++class TestSwitchdashToGateway:def test_rewrites_session_deeplink_to_gateway_redirect(self) -> None:result = switchdash_to_gateway(_DEEPLINK, "https://gw.example")diff --git a/docs/bridges/TELEGRAM_SETUP.md b/docs/bridges/TELEGRAM_SETUP.mdindex 563a272cf..75f9d5834 100644--- a/docs/bridges/TELEGRAM_SETUP.md+++ b/docs/bridges/TELEGRAM_SETUP.md@@ -121,6 +121,29 @@ bot lands.A bot cannot be added to a chat by Switch, and it cannot add anyone else: peoplejoin from a Telegram client or an invite link.+## 5. Link your own Telegram account — after you have been seen, not before++Switch has to know which Telegram account is you, or an agent set to answer only+its owner will read your messages as a stranger's. On Slack or Mattermost you do+this straight after connecting, by searching the workspace directory. **Telegram+has no directory a bot may search**, so there is nothing to search until you+have spoken. Switch Console therefore does not offer the step on the way in, and+that is deliberate rather than an omission.++The order is:++1. Connect the Telegram app to your Switch server.+2. Add the bot to a chat — the group or channel from sections 2 to 4.+3. **Send a message in that chat.** This is the step that makes you someone+ Switch has seen; nothing before it puts you in reach.+4. In Switch Console, open the server's **Messaging apps**, choose **Link my+ account…** on the Telegram row, and pick yourself.++Only people who have posted in a chat the bot can see are listed, so a member+who has never spoken cannot be linked yet. In a chat still under privacy mode+(see below) only messages that tag the bot reach Switch at all, so tag it in+that first message.+## Mention-only chats, and how to repair oneA chat where privacy mode is still in force still works, in a reduced way