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(agent-runtime): stop gap notifications from waking an agent (CHOO-1906) (#105)
Louis Amaudruz3fcd8d5fce13
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.jsonindex 36328000c..a65787ae2 100644--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json@@ -1,5 +1,5 @@{"name": "switch-connector",- "version": "0.7.2",+ "version": "0.7.3","description": "Connect Claude Code to a Switch platform instance as a participating agent"}diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex eec2afcbc..06caa80ab 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -174,9 +174,12 @@ notifications automatically — the channel process holds a push connectionto Switch and a plugin hook points it at your room, so you don't need tocall any extra tool. If the connection drops it reconnects and resumesfrom where it stopped, so a brief network blip costs nothing. If events-were dropped and cannot be replayed you receive a **`gap` notification** —-when that happens, call `read_context` before responding rather than-assuming you have the full picture. **Only messages addressed to you,+were dropped and cannot be replayed, the notification you receive next+carries a **gap warning** — a line saying earlier events were dropped, plus+a `gap` entry in its meta. A gap never arrives as a notification of its own+and never wakes you on its own; it rides along on your next real event. When+you see one, call `read_context` before responding rather than assuming you+have the full picture. **Only messages addressed to you,room-join events you are configured to receive, and task events aredelivered as notifications** — unaddressed room chatter (other agentstalking to each other, broadcast updates, the user discussing thingsdiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.tsindex eeb7fbce7..6f69a131c 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts@@ -646,64 +646,126 @@ describe('RoomConnection', () => {conn.stop();});- it('tells the agent to re-read context when the server reports a gap', async () => {- // A gap must never be silent: the session would otherwise carry on- // believing its history is complete.- const encoder = new TextEncoder();- const fetchMock = vi.fn(async (url: string) => {- const u = String(url);- if (u.includes('/events')) {+ /**+ * A gap is reported by the server on routine reconnects — an aged-out cursor,+ * a restarted process. It used to be injected the moment it arrived, which+ * woke the session and spent a turn to say "you might have missed something+ * you might not care about". These pin the replacement: still never silent,+ * but carried on the next event the session was going to receive anyway.+ */+ describe('gap handling', () => {+ /** Serves a `gap` frame, then `events`, on one stream left open. */+ function sseBodyAfterGap(events: AgentBridgeEvent[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ return new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ 'event: connection_state\n' ++ `data: ${JSON.stringify({ connection_id: 'c1', rooms: ['room-1'], cursor: 0 })}\n\n`+ )+ );+ controller.enqueue(+ encoder.encode(+ 'event: gap\n' ++ `data: ${JSON.stringify({+ from_sequence: 7,+ resumed_at: 7,+ reason: 'the server restarted since your last connection',+ })}\n\n`+ )+ );+ events.forEach((event, i) => {+ controller.enqueue(+ encoder.encode(+ `id: ${i + 1}\nevent: ${event.type}\n` ++ `data: ${JSON.stringify({ ...event, sequence: i + 1 })}\n\n`+ )+ );+ });+ },+ });+ }++ function connectAfterGap(events: AgentBridgeEvent[]) {+ let served = false;+ const fetchMock = vi.fn(async (url: string) => {+ const u = String(url);+ if (u.includes('/events')) {+ if (!served) {+ served = true;+ return {+ ok: true,+ status: 200,+ body: sseBodyAfterGap(events),+ text: async (): Promise<string> => '',+ };+ }+ return new Promise(() => {});+ }return {ok: true,status: 200,+ json: async () => ({}),text: async (): Promise<string> => '',- body: new ReadableStream<Uint8Array>({- start(controller) {- controller.enqueue(- encoder.encode(- 'event: gap\n' +- `data: ${JSON.stringify({- from_sequence: 7,- resumed_at: 7,- reason: 'the server restarted since your last connection',- })}\n\n`- )- );- },- }),};- }- return {- ok: true,- status: 200,- json: async () => ({}),- text: async (): Promise<string> => '',- };+ });+ vi.stubGlobal('fetch', fetchMock);+ const target: InjectionTarget = { write: vi.fn() };+ const conn = new RoomConnection({+ creds,+ roomId: 'room-1',+ roomName: 'Room One',+ connectionId: 'conn-1',+ sessionId: 'session-1',+ sink: { acquire: () => target },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ log: silentLog,+ });+ conn.start();+ return { conn, target };+ }++ function writes(target: InjectionTarget): string[] {+ return (target.write as ReturnType<typeof vi.fn>).mock.calls.map((c) => String(c[0]));+ }++ it('does not wake the session for a gap on its own', async () => {+ const { conn, target } = connectAfterGap([]);+ await flush(8);++ expect(writes(target)).toEqual([]);+ // Silent to the session, but not silent: it is on the record.+ expect(silentLog.warn).toHaveBeenCalledWith(+ expect.stringContaining('gap'),+ expect.objectContaining({ fromSequence: 7 })+ );+ conn.stop();});- vi.stubGlobal('fetch', fetchMock);- const target: InjectionTarget = { write: vi.fn() };- const conn = new RoomConnection({- creds,- roomId: 'room-1',- roomName: 'Room One',- connectionId: 'conn-1',- sessionId: 'session-1',- sink: { acquire: () => target },- injector,- control,- deeplinkScheme: 'switchdash',- isHumanTyping: () => false,- mediaDir,- log: silentLog,++ it('carries the gap warning on the next event it surfaces', async () => {+ const { conn, target } = connectAfterGap([messageEvent(true)]);+ await flush(8);++ const injected = writes(target).find((w) => w.includes('addressed you'));+ expect(injected).toBeDefined();+ expect(injected).toContain('dropped and cannot be replayed');+ expect(injected).toContain('read_context');+ conn.stop();});- conn.start();- await flush(8);- const written = (target.write as ReturnType<typeof vi.fn>).mock.calls.map((c) => String(c[0]));- const notice = written.find((w) => w.includes('read_context'));- expect(notice).toBeDefined();- expect(notice).toContain('missed');- conn.stop();+ it('carries the warning once, not on every subsequent event', async () => {+ const { conn, target } = connectAfterGap([messageEvent(true), messageEvent(true)]);+ await flush(12);++ const warned = writes(target).filter((w) => w.includes('dropped and cannot be replayed'));+ expect(warned).toHaveLength(1);+ conn.stop();+ });});/**diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.tsindex aa238e3cd..7a535c2a1 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts@@ -261,6 +261,16 @@ export class RoomConnection {private reportedRoom: string | null = null;/** Unaddressed room messages filtered out since the last event we surfaced. */private missed = 0;+ /**+ * Reason from the most recent gap, held until the next event we surface.+ *+ * Not injected on its own: a gap is a maybe — the agent cannot tell whether+ * anything it cared about was dropped — and interrupting a session to report+ * a maybe costs a turn every time the stream hiccups. Carried on the next+ * real event instead, which is still before any reply stale context could+ * skew.+ */+ private pendingGapReason: string | null = null;constructor(deps: RoomConnectionDeps) {this.creds = deps.creds;@@ -530,30 +540,36 @@ export class RoomConnection {annotated = `${annotated}\n${annotation}`;}}- const body =+ let body =this.missed > 0? `${annotated}\n(${this.missed} unread room message${this.missed === 1 ? '' : 's'} since your last read_context — call read_context to catch up.)`: annotated;this.missed = 0;+ if (this.pendingGapReason !== null) {+ body = `${body}\n(Some earlier room events were dropped and cannot be replayed: ${this.pendingGapReason} — call read_context before responding.)`;+ this.pendingGapReason = null;+ }this.enqueue({ text: body, addressed, threadId });}/**- * Tell the agent it has a hole in its history.+ * Record that the history has a hole, without waking the session for it.** The server reports a gap when it cannot serve our cursor — events aged out- * of the buffer, or the server restarted and the numbering reset. Staying- * quiet here would leave the session believing the stream was complete, which- * is the failure mode this transport exists to make impossible.+ * of the buffer, or the server restarted and the numbering reset. The session+ * must still learn about it: leaving it believing the stream was complete is+ * the failure mode this transport exists to make impossible. But it learns on+ * the next event we surface, not by being interrupted now — a gap fires on+ * routine reconnects, and each interruption is a whole turn spent on a+ * condition whose only remedy the agent can apply just as well later.*/private handleGap(info: { fromSequence: number; reason: string }): void {- this.enqueue({- text:- `[Switch] Some room events were missed and cannot be replayed (${info.reason}). ` +- 'Call read_context to catch up before responding.',- addressed: true,- threadId: null,+ this.log.warn('RoomConnection: gap — deferring the warning to the next surfaced event', {+ roomId: this.roomId,+ fromSequence: info.fromSequence,+ reason: info.reason,});+ this.pendingGapReason = info.reason;}/**diff --git a/dash/packages/switch-agent-runtime/src/bin.gap.test.ts b/dash/packages/switch-agent-runtime/src/bin.gap.test.tsnew file mode 100644index 000000000..31a0118ee--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/bin.gap.test.ts@@ -0,0 +1,51 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * A gap must reach the agent without waking it.+ *+ * `bin.ts` is the process entry point: importing it opens a connection and+ * starts an MCP server on stdio, so the branch below cannot be exercised+ * in-process. These read the source instead — the same approach as+ * `bin.shebang.test.ts`, and enough to catch the regression that actually+ * threatens this: someone restoring the `emitNotification` call to the gap+ * branch, which is what made every stream hiccup cost the agent a turn.+ */+const SOURCE = readFileSync(join(import.meta.dirname, 'bin.ts'), 'utf8');++/** The body of the `case 'gap':` arm, up to its `return`. */+function gapBranch(): string {+ const start = SOURCE.indexOf("case 'gap':");+ expect(start).toBeGreaterThan(-1);+ const end = SOURCE.indexOf('return;', start);+ expect(end).toBeGreaterThan(start);+ return SOURCE.slice(start, end);+}++describe('gap handling in the connector channel', () => {+ it('does not notify the agent from the gap branch', () => {+ expect(gapBranch()).not.toContain('emitNotification');+ });++ it('records the gap for later rather than dropping it', () => {+ expect(gapBranch()).toContain('pendingGapReason =');+ });++ it('still logs the gap', () => {+ expect(gapBranch()).toContain('process.stderr.write');+ });++ it('drains the deferred gap onto an outgoing notification', () => {+ const emit = SOURCE.slice(SOURCE.indexOf('async function emitNotification'));+ // Read and cleared in the one place every notification passes through, so+ // the warning rides out on a turn the agent was already being given.+ expect(emit).toContain('pendingGapReason !== null');+ expect(emit).toContain('pendingGapReason = null');+ });++ it('clears a deferred gap when the agent reads context', () => {+ const hook = SOURCE.slice(SOURCE.indexOf("url.pathname === '/read-context'"));+ expect(hook.slice(0, hook.indexOf('}'))).toContain('pendingGapReason = null');+ });+});diff --git a/dash/packages/switch-agent-runtime/src/bin.ts b/dash/packages/switch-agent-runtime/src/bin.tsindex a3286fc58..5f33c845c 100644--- a/dash/packages/switch-agent-runtime/src/bin.ts+++ b/dash/packages/switch-agent-runtime/src/bin.ts@@ -229,6 +229,17 @@ let streamHasRoom = false;// by the /read-context hook) and when polling switches rooms.let missedSinceRead = 0;+// Reason from the most recent `gap` frame, held until it can ride out on a+// notification the agent was going to receive anyway.+//+// A gap says events were dropped and cannot be replayed. That must never be+// silent, but it does not warrant a wake of its own: the only available+// response is to re-read context, and the agent cannot know whether anything+// it cared about was in the hole. Waking for it spends a turn on a maybe.+// Deferring costs nothing — the warning still arrives before the agent's next+// reply, which is the point at which stale context would actually mislead it.+let pendingGapReason: string | null = null;+// -- MCP server --------------------------------------------------------------const mcp = new Server(@@ -250,7 +261,7 @@ const mcp = new Server('','Delivery is automatic: when you call connect_to_room on the switch MCP server, a PostToolUse hook pushes the room id to this channel over a localhost port. The channel claims that room on its connection and events are pushed to you as they happen. No separate tool call is needed.','',- 'If you receive a `gap` event, some room events were dropped and cannot be replayed — call read_context before responding rather than assuming you have the full picture.',+ 'If a notification carries a gap warning (a `gap` entry in its meta, and a line saying earlier events were dropped), some room events could not be replayed — call read_context before responding rather than assuming you have the full picture. A gap never arrives as a notification of its own; it is attached to the next event you receive.','','When you receive a message event:','1. Call read_context with the since parameter set to a timestamp a few minutes before the event timestamp to get recent conversation context without re-reading the full history.',@@ -740,20 +751,13 @@ async function handleFrame(frame: SseFrame): Promise<void> {return;case 'gap':- // Never silent: tell the agent it has a hole in its history rather than- // letting it carry on as though the stream were complete.+ // Never silent, but never a wake either: logged here and held for the+ // next notification, rather than spending a turn to say "you may have+ // missed something you may not care about".process.stderr.write(`switch: GAP — missed events before sequence ${frame.data.from_sequence}\n`);- await emitNotification(- 'Some room events were missed and cannot be replayed. Call read_context ' +- 'to catch up before responding.',- {- room_id: pollingRoomId ?? '',- event_type: 'gap',- from_sequence: String(frame.data.from_sequence ?? ''),- }- );+ pendingGapReason = String(frame.data.reason ?? 'events were dropped and cannot be replayed');return;case 'evicted':@@ -1026,8 +1030,11 @@ async function handleHookRequest(req: Request): Promise<Response> {if (url.pathname === '/read-context') {// The agent called read_context, so it has caught up on room history —- // clear the missed-message backlog we've been tallying.+ // clear the missed-message backlog we've been tallying, and any deferred+ // gap warning: re-reading context is exactly the recovery that warning+ // would have asked for, so repeating it later would be noise.missedSinceRead = 0;+ pendingGapReason = null;return new Response('ok');}@@ -1299,11 +1306,20 @@ async function emitNotification(content: string, meta: Record<string, string>) {// non-zero, annotate the one-line body so the agent sees it without having// to inspect meta, and knows to widen read_context's `since` to catch up.const missed = missedSinceRead;- const enriched = { ...meta, missed_count: String(missed) };- const body =+ const enriched: Record<string, string> = { ...meta, missed_count: String(missed) };+ let body =missed > 0? `${content}\n⚠️ ${missed} unread room message${missed === 1 ? '' : 's'} since your last read_context — call read_context (widen \`since\`) to catch up on what you missed.`: content;++ // Deliver any deferred gap on the way past. This is the turn the agent was+ // already being woken for, so the warning is free here, and it lands before+ // the reply it would otherwise have skewed.+ if (pendingGapReason !== null) {+ enriched.gap = pendingGapReason;+ body = `${body}\n⚠️ Some earlier room events were dropped and cannot be replayed (${pendingGapReason}) — call read_context before responding.`;+ pendingGapReason = null;+ }await mcp.notification({method: 'notifications/claude/channel',diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.mdindex 778723cdc..40aca9288 100644--- a/docs/api/AGENT_PROTOCOL.md+++ b/docs/api/AGENT_PROTOCOL.md@@ -210,6 +210,15 @@ events and must re-read room context. The same applies when a client asks tostart from a sequence number older than the buffer retains: that is an**error**, not a fast-forward to head.+Never silent is not the same as immediate. A gap is reported to the *client*+the moment it is detected, but a client must not wake its agent for one on its+own: the only available response is to re-read context, and the agent cannot+know whether anything it cared about was dropped, so an interrupt per hiccup+buys a turn spent on a maybe. Clients hold the reason and attach it to the next+event they surface — still ahead of any reply that stale context could skew,+at no cost of its own. A gap that is never followed by a surfaced event is one+the agent had no turn to misuse anyway; it stays in the client's log.+### 4.3 ConfirmationTwo mechanisms, both free:@@ -427,7 +436,7 @@ New, carried on the same stream:|---|---|---|| `connection_state` | `connection_id`, `scope`, `filter`, `rooms`, `cursor`, `protocol` | first event on every stream || `subscription_changed` | `rooms`, `reason` | scope changed — including a room going dark because another connection claimed it |-| `gap` | `from_sequence`, `reason` | events were dropped; re-read context |+| `gap` | `from_sequence`, `reason` | events were dropped; re-read context. Carried to the agent on the next surfaced event, not as a wake of its own (§4.2) || `evicted` | `reason` | this connection lost its slot or was taken over; it must stop acting |`gap` and `evicted` exist so that degradation is always visible. A client that@@ -699,7 +708,7 @@ Fail loud, never fake. Concretely:| situation | behaviour ||---|---|| resume from a cursor older than the buffer | error: missed events, re-read context |-| buffer overflow | drop oldest, flag gap, `gap` event on next connection |+| buffer overflow | drop oldest, flag gap, `gap` event on next connection; client attaches it to the next event it surfaces || heartbeat with no stream attached | reject: reopen the stream || call with unknown/dead `connection_id` | reject: reconnect and resume || `connection_id` belonging to another agent | reject |