Skip to content

The agent that grows with you

fix(plugins): move a plugin socket to the new profile on a profile switch

unsupportedpastelseccb1c3c1354
diff --git a/apps/desktop/src/api/plugins.test.ts b/apps/desktop/src/api/plugins.test.ts
index 7cb0cebb692..3728e118699 100644
--- a/apps/desktop/src/api/plugins.test.ts
+++ b/apps/desktop/src/api/plugins.test.ts
@@ -57,6 +57,7 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {
class FakeSocket {
static all: FakeSocket[] = []
readonly at = Date.now()
+ closed = false
onclose: (() => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onopen: (() => void) | null = null
@@ -64,6 +65,7 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {
FakeSocket.all.push(this)
}
close() {
+ this.closed = true
this.onclose?.()
}
}
@@ -272,6 +274,116 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {
expect(mint).toHaveBeenCalledTimes(11)
})
+ // A grant or descriptor resolved for the profile the user just left, or a socket still bound to
+ // it, would feed that profile's plugin stream into the current view.
+ const urlFor = (profile: null | string) => `ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=${profile}`
+
+ const profileDesktop = () => {
+ const getPluginWsUrl = vi.fn(async ({ profile }: { profile: null | string }): Promise<unknown> => urlFor(profile))
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { getConnection: vi.fn(async () => local), getPluginWsUrl }
+ })
+
+ return getPluginWsUrl
+ }
+
+ const openUrls = () => FakeSocket.all.filter(socket => !socket.closed).map(socket => socket.url)
+
+ it('a profile switch while the grant is being minted dials the new profile, never the old URL', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', FakeSocket)
+ setApiRequestProfile('alpha')
+ const mint = profileDesktop()
+ let resolveAlpha: (url: unknown) => void = () => undefined
+ mint.mockImplementationOnce(() => new Promise(resolve => (resolveAlpha = resolve)))
+
+ const dispose = pluginSocket('kanban', '/events', () => undefined)
+ await vi.advanceTimersByTimeAsync(0)
+ setApiRequestProfile('beta')
+ await vi.advanceTimersByTimeAsync(0)
+ resolveAlpha(urlFor('alpha'))
+ await vi.advanceTimersByTimeAsync(600_000)
+
+ expect(mint).toHaveBeenLastCalledWith(expect.objectContaining({ profile: 'beta' }))
+ expect(FakeSocket.all.map(socket => socket.url)).toEqual([urlFor('beta')])
+ dispose()
+ })
+
+ it('a profile switch while the connection lookup is pending dials the new profile', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', FakeSocket)
+ setApiRequestProfile('alpha')
+ const remote = (profile: string) => ({ authMode: 'token', baseUrl: `http://${profile}.invalid`, token: 'tok' })
+ let resolveAlpha: (connection: unknown) => void = () => undefined
+
+ const getConnection = vi.fn(async (profile: string): Promise<unknown> => remote(profile))
+ getConnection.mockImplementationOnce(() => new Promise(resolve => (resolveAlpha = resolve)))
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { getConnection } })
+
+ const dispose = pluginSocket('kanban', '/events', () => undefined)
+ await vi.advanceTimersByTimeAsync(0)
+ setApiRequestProfile('beta')
+ await vi.advanceTimersByTimeAsync(0)
+ resolveAlpha(remote('alpha'))
+ await vi.advanceTimersByTimeAsync(600_000)
+
+ expect(FakeSocket.all.map(socket => socket.url)).toEqual(['ws://beta.invalid/api/plugins/kanban/events?token=tok'])
+ dispose()
+ })
+
+ it('a profile switch closes the open socket and dials the new profile', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', FakeSocket)
+ setApiRequestProfile('alpha')
+ const mint = profileDesktop()
+ const frames: unknown[] = []
+
+ const dispose = pluginSocket('kanban', '/events', frame => frames.push(frame))
+ await vi.advanceTimersByTimeAsync(0)
+ const alpha = FakeSocket.all[0]
+ alpha.onopen?.()
+
+ setApiRequestProfile('beta')
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(alpha.closed).toBe(true)
+ expect(openUrls()).toEqual([urlFor('beta')])
+ const beta = FakeSocket.all.at(-1)!
+ beta.onopen?.()
+ beta.onmessage?.({ data: '{"profile":"beta"}' })
+ expect(frames).toEqual([{ profile: 'beta' }])
+
+ // The closed alpha socket neither re-dials nor counts as a refusal.
+ await vi.advanceTimersByTimeAsync(600_000)
+ expect(FakeSocket.all).toHaveLength(2)
+ expect(mint).toHaveBeenCalledTimes(2)
+ dispose()
+ })
+
+ it('a quick A to B to A switch ends with exactly one open socket, on A', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', FakeSocket)
+ setApiRequestProfile('alpha')
+ profileDesktop()
+ const frames: unknown[] = []
+
+ const dispose = pluginSocket('kanban', '/events', frame => frames.push(frame))
+ await vi.advanceTimersByTimeAsync(0)
+ FakeSocket.all[0].onopen?.()
+
+ setApiRequestProfile('beta')
+ setApiRequestProfile('alpha')
+ await vi.advanceTimersByTimeAsync(600_000)
+
+ expect(openUrls()).toEqual([urlFor('alpha')])
+ const live = FakeSocket.all.find(socket => !socket.closed)!
+ live.onopen?.()
+ live.onmessage?.({ data: '{"profile":"alpha"}' })
+ expect(frames).toEqual([{ profile: 'alpha' }])
+ dispose()
+ })
+
it('keeps reconnecting a socket that stayed open before it dropped', async () => {
vi.useFakeTimers()
vi.stubGlobal('WebSocket', FakeSocket)
diff --git a/apps/desktop/src/api/plugins.ts b/apps/desktop/src/api/plugins.ts
index 26974398a27..5fba448d990 100644
--- a/apps/desktop/src/api/plugins.ts
+++ b/apps/desktop/src/api/plugins.ts
@@ -131,28 +131,29 @@ const requestScopeKey = () => `${getApiRequestConnection() ?? ''}\n${getApiReque
* restarting, draining or being re-ensured. It stops after
* MAX_REFUSED_PLUGIN_DIALS refusals in a row that do not clear by themselves:
* main refusing the grant mint for a permission reason, or a server that
- * accepts and closes at once. A connection or profile change resets the count
- * and dials again. */
+ * accepts and closes at once. A connection or profile change drops a dial
+ * still resolving for the old scope, closes a socket bound to it, resets the
+ * count and dials for the new scope. */
export function pluginSocket(pluginId: string, path: string, onMessage: (data: unknown) => void): () => void {
const suffix = pluginPathSuffix('pluginSocket', path)
let socket: null | WebSocket = null
let disposed = false
- let stopped = false
let attempt = 0
let refused = 0
let scope = requestScopeKey()
+ // Bumped on every connection or profile change. A lookup, backoff timer or socket started under an
+ // older generation belongs to another scope: its result is dropped and never counts as a refusal.
+ let generation = 0
- const retry = (refusal: boolean) => {
- refused = refusal ? refused + 1 : refused
-
- if (disposed) {
+ const retry = (dial: number, refusal: boolean) => {
+ if (disposed || dial !== generation) {
return
}
- if (refused >= MAX_REFUSED_PLUGIN_DIALS) {
- stopped = true
+ refused = refusal ? refused + 1 : refused
+ if (refused >= MAX_REFUSED_PLUGIN_DIALS) {
return
}
@@ -160,11 +161,18 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: u
// socket reconnect loops — an immediate-retry loop across many
// desktop clients floods the gateway with connection attempts
// during a restart.
- window.setTimeout(() => void connect(), reconnectBackoffDelayMs(attempt, { baseDelayMs: 500, capMs: 30_000 }))
+ window.setTimeout(() => {
+ if (dial === generation) {
+ void connect()
+ }
+ }, reconnectBackoffDelayMs(attempt, { baseDelayMs: 500, capMs: 30_000 }))
attempt += 1
}
const connect = async () => {
+ const dial = generation
+ const stale = () => disposed || dial !== generation
+
// No bridge: stay on the polling fallback.
if (!window.hermesDesktop?.getConnection) {
return
@@ -177,12 +185,12 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: u
} catch {
// The descriptor can't be resolved yet or the lookup timed out (gateway starting, draining,
// or re-ensured after a stale ticket): a connection failure, like a dial that never opened.
- return retry(false)
+ return retry(dial, false)
}
// OAuth cookie auth (WS tickets are single-use, core-managed): stay on the
// polling fallback rather than half-working.
- if (disposed || connection.authMode === 'oauth') {
+ if (stale() || connection.authMode === 'oauth') {
return
}
@@ -192,25 +200,30 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: u
url = await pluginSocketUrl(connection, pluginId, suffix)
} catch {
// The local mint failed or timed out (owner away, re-ensuring): a connection failure.
- return retry(false)
+ return retry(dial, false)
}
- if (disposed || !url) {
+ if (stale() || !url) {
return
}
if (typeof url !== 'string') {
- return retry(true)
+ return retry(dial, true)
}
- socket = new WebSocket(url)
+ const current = new WebSocket(url)
+ socket = current
let openedAt: null | number = null
- socket.onopen = () => {
+ current.onopen = () => {
openedAt = Date.now()
}
- socket.onmessage = event => {
+ current.onmessage = event => {
+ if (stale()) {
+ return
+ }
+
attempt = 0
try {
@@ -220,8 +233,14 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: u
}
}
- socket.onclose = () => {
- socket = null
+ current.onclose = () => {
+ if (socket === current) {
+ socket = null
+ }
+
+ if (stale()) {
+ return
+ }
// Only a socket that stayed up resets the ladder. An accept-then-close server
// (Kanban on an archived board) is up and answering, so it counts as a refusal.
@@ -230,27 +249,28 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: u
refused = 0
}
- retry(openedAt !== null && !isStableOpen(openedAt))
+ retry(dial, openedAt !== null && !isStableOpen(openedAt))
}
}
- // Another connection or profile is another gateway or another consent: a fresh count, and a
- // stopped socket dials again.
+ // Another connection or profile is another gateway or another consent. A socket bound to the
+ // old scope would show that profile's stream in this view: close it, and dial for the new scope
+ // with a fresh count.
const unlisten = $apiRequestScope.listen(() => {
const next = requestScopeKey()
- if (next === scope) {
+ if (next === scope || disposed) {
return
}
scope = next
+ generation += 1
attempt = 0
refused = 0
-
- if (stopped && !disposed) {
- stopped = false
- void connect()
- }
+ const old = socket
+ socket = null
+ old?.close()
+ void connect()
})
void connect()
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 8bdc7c2c0ba..0e947ede515 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -1894,7 +1894,9 @@ When the socket gives up (your polling fallback is then the only feed):
path or profile home), or your backend accepting the socket and closing it at
once. A socket that stays open resets the count.
- **Starts again** when the active connection or profile changes, with a fresh
- count, or when the view remounts.
+ count, or when the view remounts. A profile switch also moves a live socket:
+ Desktop closes the one bound to the old profile, drops a grant still being
+ minted for it, and dials for the new profile.
For gateway-wide data (not your own namespace), use `host.request` (JSON-RPC) and
`host.onEvent` (the gateway event stream) instead.