Skip to content

The agent that grows with you

fix(desktop): write pre-save gateway sign-in sessions to the connection's own jar

Together67d39cc75d51
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index be83bd6e1cd..dd2a34558d3 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -17,6 +17,7 @@ import {
buildAgentRoster,
connectionDialFieldsChanged,
connectionIdForLabel,
+ connectionIdForPendingLogin,
labelKey,
labelSlug,
LOCAL_CONNECTION_ID,
@@ -647,6 +648,62 @@ test('connectionIdForLabel suffixes on collision and never mints "local"', () =>
assert.equal(connectionIdForLabel('Local', []), 'local-2')
})
+// A registry-editor sign-in can run before the draft is saved: the id settled
+// here names the cookie partition the login writes, so it MUST equal the id
+// normalizeConnectionInput mints when the draft is saved.
+test('connectionIdForPendingLogin: an explicit draft id wins (trimmed)', () => {
+ const registry = emptyRegistry()
+
+ assert.equal(connectionIdForPendingLogin({ connectionId: 'homelab', registry }), 'homelab')
+ assert.equal(connectionIdForPendingLogin({ connectionId: ' homelab ', registry }), 'homelab')
+})
+
+test('connectionIdForPendingLogin: mints the save-time id for an unpersisted draft', () => {
+ let registry = emptyRegistry()
+ const entry = normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)
+ registry = upsertConnection(registry, entry)
+
+ // Label-derived and collision-suffixed exactly like normalizeConnectionInput.
+ assert.equal(connectionIdForPendingLogin({ label: 'Mac mini', registry }), 'mac-mini')
+ assert.equal(connectionIdForPendingLogin({ label: 'Homelab', registry }), 'homelab-2')
+
+ // The save must land on the same id the login used.
+ const saved = normalizeConnectionInput(
+ {
+ kind: 'remote',
+ id: connectionIdForPendingLogin({ label: 'Mac mini', registry }),
+ label: 'Mac mini',
+ url: 'http://10.0.0.6:9119'
+ },
+ registry
+ )
+
+ assert.equal(saved.id, 'mac-mini')
+})
+
+test('connectionIdForPendingLogin: an unnamed draft still gets a stable unique id', () => {
+ let registry = emptyRegistry()
+ registry = upsertConnection(registry, {
+ id: 'connection',
+ kind: 'remote',
+ label: 'Taken',
+ url: 'http://10.0.0.7:9119',
+ authMode: 'oauth'
+ })
+
+ // labelSlug('') is 'connection'; the collision suffixes just like a label.
+ assert.equal(connectionIdForPendingLogin({ label: '', registry }), 'connection-2')
+ assert.equal(connectionIdForPendingLogin({ registry }), 'connection-2')
+})
+
+test('connectionIdForPendingLogin: blank or non-string ids fall back to minting', () => {
+ const registry = emptyRegistry()
+
+ for (const junk of ['', ' ', 42, null, undefined]) {
+ assert.equal(connectionIdForPendingLogin({ connectionId: junk, label: 'Homelab', registry }), 'homelab')
+ }
+})
+
test('uniqueLabel counts up (never "X 2 2") and clamps long candidates', () => {
assert.equal(uniqueLabel('Homelab', []), 'Homelab')
assert.equal(uniqueLabel('Homelab', ['Homelab']), 'Homelab 2')
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index c161cc265e1..3e51f96a1ee 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -884,6 +884,34 @@ export function connectionIdForLabel(label: string, taken: Iterable<string>): st
}
}
+/**
+ * Settle the connection id a pre-save OAuth login must write its session for.
+ * The registry editor can open the sign-in window BEFORE the draft is saved,
+ * and the login window's cookie partition is derived from this id
+ * (oauth-partition.ts) — so it must equal the id the eventual save uses. An
+ * explicit draft id wins; otherwise mint from the label exactly like
+ * normalizeConnectionInput will (labelSlug maps an empty label to
+ * 'connection', so even an unnamed draft gets a stable, unique id). The
+ * editor's save path never promotes a fresh entry to primary, so a pending
+ * draft always ends up on its own partition.
+ */
+export function connectionIdForPendingLogin(opts: {
+ connectionId?: unknown
+ label?: unknown
+ registry: ConnectionRegistry
+}): string {
+ if (typeof opts.connectionId === 'string' && opts.connectionId.trim()) {
+ return opts.connectionId.trim()
+ }
+
+ const label = typeof opts.label === 'string' ? opts.label : ''
+
+ return connectionIdForLabel(
+ label,
+ opts.registry.connections.map(c => c.id)
+ )
+}
+
// ── Validation ──────────────────────────────────────────────────────────────
export interface ConnectionInput {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 7e4ffe5ca16..f75faaf0b94 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -167,6 +167,7 @@ import {
backendScopePrefix,
buildAgentRoster,
connectionDialFieldsChanged,
+ connectionIdForPendingLogin,
mergeConnectionInput,
migrateV1ToRegistry,
normalizeConnectionInput,
@@ -7248,9 +7249,10 @@ function getOauthSession() {
// shared partition; see oauth-partition.ts for the full rules.
const oauthSessionsByPartition = new Map()
-function resolveOauthPartitionForUrl(url) {
+function resolveOauthPartitionForUrl(url, { connectionId = '' } = {}) {
try {
return resolveOauthPartition(url, {
+ connectionId,
registry: readDesktopConnectionsRegistry(),
v1RemoteUrl: readDesktopConnectionConfig()?.remote?.url
})
@@ -7260,8 +7262,8 @@ function resolveOauthPartitionForUrl(url) {
}
}
-function getOauthSessionForUrl(url) {
- const partition = resolveOauthPartitionForUrl(url)
+function getOauthSessionForUrl(url, { connectionId = '' } = {}) {
+ const partition = resolveOauthPartitionForUrl(url, { connectionId })
if (partition === OAUTH_SESSION_PARTITION) {
return getOauthSession()
@@ -7336,8 +7338,8 @@ function warmOauthCookieStore(url?) {
// connection-config.ts (cookiesHaveSession / cookiesHaveLiveSession). See
// that module for details.
-async function hasOauthSessionCookie(baseUrl) {
- const sess = getOauthSessionForUrl(baseUrl)
+async function hasOauthSessionCookie(baseUrl, { connectionId = '' } = {}) {
+ const sess = getOauthSessionForUrl(baseUrl, { connectionId })
if (!sess) {
return false
@@ -7459,7 +7461,7 @@ async function clearOauthSession(baseUrl) {
// ``/auth/login`` → portal ``/oauth/authorize`` (auto-approves org members)
// → ``/auth/callback``, which sets the gateway cookie with NO interactive
// prompt. This is the per-agent cloud cascade (decisions.md Q5).
-function openOauthLoginWindow(baseUrl, { silent = false, background = false } = {}) {
+function openOauthLoginWindow(baseUrl, { silent = false, background = false, connectionId = '' } = {}) {
return new Promise((resolve, reject) => {
if (!app.isReady()) {
reject(new Error('Desktop is not ready to start an OAuth login.'))
@@ -7467,7 +7469,7 @@ function openOauthLoginWindow(baseUrl, { silent = false, background = false } =
return
}
- const sess = getOauthSessionForUrl(baseUrl)
+ const sess = getOauthSessionForUrl(baseUrl, { connectionId })
if (!sess) {
reject(new Error('OAuth session partition is unavailable.'))
@@ -7520,7 +7522,7 @@ function openOauthLoginWindow(baseUrl, { silent = false, background = false } =
return
}
- if (await hasOauthSessionCookie(baseUrl)) {
+ if (await hasOauthSessionCookie(baseUrl, { connectionId })) {
finish(null)
}
}
@@ -16290,7 +16292,7 @@ async function fetchJsonForBackend(
}
ipcMain.handle('hermes:connection-config:probe', async (_event, rawUrl) => probeRemoteAuthMode(rawUrl))
-ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) => {
+ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl, rawOpts) => {
// Capability-gated login (RFC 8252). Probe the gateway's public /api/status
// for supported auth_flows and /api/auth/providers for provider capabilities:
// - all providers support password → always use the embedded login window
@@ -16306,6 +16308,25 @@ ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) =>
// Order login attempts without interrupting rotation of the existing session.
const authIsCurrent: () => boolean = nativeAccessTokenCoordinator.beginLogin(baseUrl)
+ // A registry-editor sign-in can run BEFORE the draft connection is saved:
+ // settle the id the save will reuse (returned so the renderer pins it into
+ // the draft) so the login window writes its session cookies into the
+ // per-connection jar the saved connection will actually read — not the
+ // legacy shared jar an unmatched URL would fall back to, where the session
+ // is both unreadable by the new connection and able to evict a same-host
+ // primary's cookie (#92183 isolation hole). '' → URL-matched behavior.
+ let loginConnectionId = ''
+
+ try {
+ loginConnectionId = connectionIdForPendingLogin({
+ connectionId: rawOpts?.connectionId,
+ label: rawOpts?.label,
+ registry: readDesktopConnectionsRegistry()
+ })
+ } catch {
+ loginConnectionId = ''
+ }
+
let statusBody: any = null
try {
@@ -16357,18 +16378,23 @@ ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) =>
// startHermes() re-dials instead of replaying the stale rejection.
remoteReauthFailure = null
- return { ok: true, baseUrl, connected: true }
+ return { ok: true, baseUrl, connected: true, connectionId: loginConnectionId || undefined }
} catch (error) {
rememberLog(`[native-oauth] native login failed (${error instanceof Error ? error.message : String(error)})`)
- return { ok: false, error: error instanceof Error ? error.message : String(error), connected: false }
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ connected: false,
+ connectionId: loginConnectionId || undefined
+ }
}
}
// Legacy embedded-webview cookie flow.
- await openOauthLoginWindow(baseUrl)
+ await openOauthLoginWindow(baseUrl, { connectionId: loginConnectionId })
- const connected = await hasOauthSessionCookie(baseUrl)
+ const connected = await hasOauthSessionCookie(baseUrl, { connectionId: loginConnectionId })
// Only a CONFIRMED sign-in releases the latch. A cancelled/closed login
// window must leave it set, or the overlay's "Sign in" button starts
@@ -16383,7 +16409,7 @@ ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) =>
remoteReauthFailure = null
}
- return { ok: true, baseUrl, connected }
+ return { ok: true, baseUrl, connected, connectionId: loginConnectionId || undefined }
})
ipcMain.handle('hermes:connection-config:oauth-logout', async (_event, rawUrl) => {
const baseUrl = normalizeRemoteBaseUrl(rawUrl)
diff --git a/apps/desktop/electron/oauth-partition.test.ts b/apps/desktop/electron/oauth-partition.test.ts
index 6afb388c98f..0776c91c635 100644
--- a/apps/desktop/electron/oauth-partition.test.ts
+++ b/apps/desktop/electron/oauth-partition.test.ts
@@ -160,3 +160,93 @@ describe('resolveOauthPartition (#92183 per-connection cookie jars)', () => {
expect(got).toContain('alpha')
})
})
+
+// The registry editor can sign a draft in BEFORE it is saved. The login window
+// must then write to the jar the saved entry will read — an unsaved draft has
+// no on-disk entry to URL-match, so identity (connectionId) decides instead.
+describe('resolveOauthPartition with connectionId (pre-save sign-in identity)', () => {
+ it('sends a pending (unsaved) draft sign-in to its own jar, not the legacy shared one', () => {
+ const reg = registry('local', [{ id: 'local', kind: 'local' }])
+
+ const got = resolveOauthPartition('https://macmini.lan:9119', { registry: reg, connectionId: 'macmini' })
+
+ expect(got).not.toBe(LEGACY_OAUTH_PARTITION)
+ expect(got).toContain('conn:macmini')
+ // Deterministic across calls — the saved entry must read the jar the login wrote.
+ expect(resolveOauthPartition('https://macmini.lan:9119', { registry: reg, connectionId: 'macmini' })).toBe(got)
+ })
+
+ it('keeps a pending same-host sign-in out of an existing gateway’s jar (no #92183 eviction)', () => {
+ const reg = registry('local', [{ id: 'local', kind: 'local' }, remote('conn-a', 'https://10.27.27.7:9119')])
+
+ const pending = resolveOauthPartition('https://10.27.27.7:9220', { registry: reg, connectionId: 'conn-b' })
+ const existing = resolveOauthPartition('https://10.27.27.7:9119', { registry: reg })
+
+ expect(pending).not.toBe(LEGACY_OAUTH_PARTITION)
+ expect(pending).not.toBe(existing)
+ expect(existing).toContain('conn-a')
+ expect(pending).toContain('conn-b')
+ })
+
+ it('resolves an existing entry by identity even when the URL was edited but not yet saved', () => {
+ const reg = registry('local', [{ id: 'local', kind: 'local' }, remote('conn-a', 'https://old.example.com')])
+
+ const got = resolveOauthPartition('https://new.example.com', { registry: reg, connectionId: 'conn-a' })
+
+ expect(got).toContain('conn-a')
+ expect(got).not.toBe(LEGACY_OAUTH_PARTITION)
+ })
+
+ it('keeps the primary, the local entry, cloud, and token-auth identities on the legacy jar', () => {
+ const reg = registry('conn-a', [
+ { id: 'local', kind: 'local' },
+ remote('conn-a', 'https://gw-a.example.com'),
+ remote('tok-1', 'https://gw-t.example.com', { authMode: 'token' }),
+ { id: 'cloud-1', kind: 'cloud', url: 'https://agent.nousresearch.com', authMode: 'oauth' }
+ ])
+
+ expect(resolveOauthPartition('https://gw-a.example.com', { registry: reg, connectionId: 'conn-a' })).toBe(
+ LEGACY_OAUTH_PARTITION
+ )
+ expect(resolveOauthPartition('https://gw-a.example.com', { registry: reg, connectionId: 'local' })).toBe(
+ LEGACY_OAUTH_PARTITION
+ )
+ expect(resolveOauthPartition('https://gw-t.example.com', { registry: reg, connectionId: 'tok-1' })).toBe(
+ LEGACY_OAUTH_PARTITION
+ )
+ expect(resolveOauthPartition('https://agent.nousresearch.com', { registry: reg, connectionId: 'cloud-1' })).toBe(
+ LEGACY_OAUTH_PARTITION
+ )
+ })
+
+ it('keeps a v1-migrated entry on the legacy jar even when named by id', () => {
+ const reg = registry('local', [{ id: 'local', kind: 'local' }, remote('mig-1', 'https://gw-a.example.com')])
+
+ expect(
+ resolveOauthPartition('https://gw-a.example.com', {
+ registry: reg,
+ connectionId: 'mig-1',
+ v1RemoteUrl: 'https://gw-a.example.com'
+ })
+ ).toBe(LEGACY_OAUTH_PARTITION)
+ })
+
+ it('ignores blank or non-string connectionIds and falls back to URL matching', () => {
+ const reg = registry('local', [remote('conn-a', 'https://gw-a.example.com')])
+
+ for (const junk of ['', ' ', 42, null, undefined]) {
+ expect(resolveOauthPartition('https://gw-a.example.com', { registry: reg, connectionId: junk })).toContain(
+ 'conn-a'
+ )
+ }
+ })
+
+ it('sanitizes hostile pending ids into partition-safe names', () => {
+ const reg = registry('local', [{ id: 'local', kind: 'local' }])
+
+ const got = resolveOauthPartition('https://gw.example.com', { registry: reg, connectionId: 'we ird/id:€' })
+
+ expect(got.startsWith('persist:')).toBe(true)
+ expect(got).not.toMatch(/[\s/€]/)
+ })
+})
diff --git a/apps/desktop/electron/oauth-partition.ts b/apps/desktop/electron/oauth-partition.ts
index 746df0ec2ad..4b865d00bd5 100644
--- a/apps/desktop/electron/oauth-partition.ts
+++ b/apps/desktop/electron/oauth-partition.ts
@@ -29,6 +29,13 @@
* cascade deliberately shares one jar with the Nous Portal session.
* - Token-auth remotes, portal URLs, and anything unmatched or malformed
* fall back to the legacy partition (cookie-free flows are unaffected).
+ * - Login flows may name the connection explicitly (`connectionId`): the
+ * registry editor can sign a draft in BEFORE it is persisted, and the
+ * login window must write to the jar the saved entry will read from.
+ * Identity then decides — a known entry follows the rules above; an
+ * unknown id is a pending non-primary oauth remote (the editor's save
+ * path never promotes a fresh entry to primary) and gets its own
+ * partition up front.
*
* Kept free of `electron` imports so it unit-tests in the electron vitest
* project; main.ts owns session.fromPartition() and injects nothing here.
@@ -62,6 +69,12 @@ export interface ResolveOauthPartitionOptions {
registry?: PartitionRegistrySnapshot | null
/** v1 single-connection remote URL (connection.json `remote.url`), when set. */
v1RemoteUrl?: unknown
+ /**
+ * Connection id for login flows that run before the draft is persisted.
+ * When set, identity decides the jar (module header); URL matching below
+ * is skipped entirely.
+ */
+ connectionId?: unknown
}
/**
@@ -103,6 +116,15 @@ function sanitizePartitionComponent(id: string): string {
return encodeURIComponent(id).replace(/%/g, '_')
}
+/** Read one property off an untrusted registry entry (parsed JSON) without a cast. */
+function entryField(entry: unknown, key: string): unknown {
+ if (!entry || typeof entry !== 'object' || !(key in entry)) {
+ return undefined
+ }
+
+ return Object.getOwnPropertyDescriptor(entry, key)?.value
+}
+
/**
* Decide the Electron session partition a cookie-authenticated request against
* `requestUrl` must ride. See the module header for the rules.
@@ -123,6 +145,35 @@ export function resolveOauthPartition(requestUrl: unknown, opts: ResolveOauthPar
const primaryId = typeof registry.primary === 'string' ? registry.primary : ''
const v1Norm = normalizeForMatch(opts.v1RemoteUrl)
+ // Identity-keyed resolution for pre-save logins. A pending draft has no
+ // persisted entry to URL-match against; without this branch its sign-in
+ // would fall through to the legacy shared jar — where the session is both
+ // unreadable by the saved connection AND able to evict a same-host primary's
+ // cookie (the #92183 leak the per-connection jars exist to stop).
+ const wantedId = typeof opts.connectionId === 'string' ? opts.connectionId.trim() : ''
+
+ if (wantedId) {
+ const own = (registry.connections as unknown[]).find(c => entryField(c, 'id') === wantedId)
+
+ if (!own) {
+ return `${CONNECTION_PARTITION_PREFIX}${sanitizePartitionComponent(wantedId)}`
+ }
+
+ const ownBaseNorm = normalizeForMatch(entryField(own, 'url'))
+
+ if (
+ wantedId !== primaryId &&
+ entryField(own, 'kind') === 'remote' &&
+ entryField(own, 'authMode') === 'oauth' &&
+ ownBaseNorm &&
+ !(v1Norm && ownBaseNorm === v1Norm)
+ ) {
+ return `${CONNECTION_PARTITION_PREFIX}${sanitizePartitionComponent(wantedId)}`
+ }
+
+ return LEGACY_OAUTH_PARTITION
+ }
+
let best: { baseNorm: string; id: string } | null = null
for (const entry of registry.connections) {
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index c3e48f41ccd..24aa0a19e06 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -305,7 +305,12 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
sshConfigHosts: () => ipcRenderer.invoke('hermes:ssh-config:hosts'),
sshResolveHost: host => ipcRenderer.invoke('hermes:ssh-config:resolve', host),
probeConnectionConfig: remoteUrl => ipcRenderer.invoke('hermes:connection-config:probe', remoteUrl),
- oauthLoginConnectionConfig: remoteUrl => ipcRenderer.invoke('hermes:connection-config:oauth-login', remoteUrl),
+ // `options` lets a registry-editor draft sign in BEFORE it is saved: the
+ // main process settles the draft's connection id up front so the login
+ // window writes into the per-connection cookie jar the saved entry will
+ // read (not the legacy shared jar an unsaved URL would fall back to).
+ oauthLoginConnectionConfig: (remoteUrl, options) =>
+ ipcRenderer.invoke('hermes:connection-config:oauth-login', remoteUrl, options),
oauthLogoutConnectionConfig: remoteUrl => ipcRenderer.invoke('hermes:connection-config:oauth-logout', remoteUrl),
// Hermes Cloud: one portal login powers discovery + silent per-agent sign-in
// (cloud-auto-discovery Phase 3).
diff --git a/apps/desktop/src/app/settings/connections-registry.test.tsx b/apps/desktop/src/app/settings/connections-registry.test.tsx
index 3e9233eb56d..ee1595dd49f 100644
--- a/apps/desktop/src/app/settings/connections-registry.test.tsx
+++ b/apps/desktop/src/app/settings/connections-registry.test.tsx
@@ -133,7 +133,12 @@ describe('ConnectionsRegistrySection', () => {
fireEvent.change(url, { target: { value: 'https://a.example' } })
fireEvent.click(screen.getByRole('button', { name: /^(OAuth|Sign in)$/ }))
fireEvent.click(await screen.findByRole('button', { name: /Sign in with/ }))
- await waitFor(() => expect(oauthLoginConnectionConfig).toHaveBeenCalledWith('https://a.example'))
+ await waitFor(() =>
+ expect(oauthLoginConnectionConfig).toHaveBeenCalledWith('https://a.example', {
+ connectionId: null,
+ label: 'New gateway'
+ })
+ )
fireEvent.change(url, { target: { value: 'https://b.example' } })
await act(async (): Promise<void> => pendingLogin.resolve({ connected: true }))
expect(screen.queryByText('Signed in')).toBeNull()
diff --git a/apps/desktop/src/app/settings/connections-registry.tsx b/apps/desktop/src/app/settings/connections-registry.tsx
index d29d0c71d05..85fa526a8f6 100644
--- a/apps/desktop/src/app/settings/connections-registry.tsx
+++ b/apps/desktop/src/app/settings/connections-registry.tsx
@@ -240,7 +240,15 @@ export function ConnectionsRegistrySection() {
const remote = useRemoteSetup({
host: 'registry',
enabled: editor?.kind === 'remote' || editor?.kind === 'cloud',
- onNotice: notify
+ onNotice: notify,
+ // The registry draft can sign in BEFORE it is saved: the login carries
+ // the draft's identity so the main process settles the id the save will
+ // reuse and writes the session into that connection's own cookie jar.
+ // Pin the settled id into the draft so Save reuses it.
+ oauthLoginIdentity: () => ({ connectionId: editor?.id ?? null, label: editor?.label ?? '' }),
+ onOAuthLoginSettled: settledId => {
+ setEditor(prev => (prev && !prev.id ? { ...prev, id: settledId } : prev))
+ }
})
const bridge = window.hermesDesktop?.connections
diff --git a/apps/desktop/src/components/remote-setup/use-remote-oauth.ts b/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
index 0c924b79cc0..5721c266577 100644
--- a/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
+++ b/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
@@ -16,6 +16,16 @@ interface RemoteOAuthOptions {
invalidateTest: () => void
reportError: (err: unknown, title?: string, kind?: 'error' | 'warning') => void
notify: (notice: NotificationInput) => void
+ /**
+ * Registry-draft identity for a sign-in that runs BEFORE the draft is
+ * saved. The main process derives the login window's cookie partition from
+ * the settled connection id; without it an unsaved draft's session lands in
+ * the legacy shared jar the saved connection never reads. Absent on the
+ * first-run/settings hosts, which have no draft identity.
+ */
+ oauthLoginIdentity?: () => { connectionId: null | string; label: string } | undefined
+ /** Reports the settled id a pre-save sign-in wrote the session for. */
+ onOAuthLoginSettled?: (connectionId: string) => void
}
export interface RemoteOAuth {
@@ -41,7 +51,9 @@ export function useRemoteOAuth(options: RemoteOAuthOptions): RemoteOAuth {
setOAuthConnected,
invalidateTest,
reportError,
- notify
+ notify,
+ oauthLoginIdentity,
+ onOAuthLoginSettled
} = options
const [signingIn, setSigningIn] = useState<boolean>(false)
@@ -74,12 +86,23 @@ export function useRemoteOAuth(options: RemoteOAuthOptions): RemoteOAuth {
return
}
- const result = await window.hermesDesktop.oauthLoginConnectionConfig(url)
+ // Absent identity (first-run/settings hosts) keeps the legacy single-arg
+ // call; the registry host always supplies one for its draft.
+ const identity = oauthLoginIdentity?.()
+ const result = identity
+ ? await window.hermesDesktop.oauthLoginConnectionConfig(url, identity)
+ : await window.hermesDesktop.oauthLoginConnectionConfig(url)
if (!current()) {
return
}
+ // A pre-save sign-in settles the id the later save will reuse; the
+ // registry host pins it into the draft so both agree on the jar.
+ if (result.connectionId) {
+ onOAuthLoginSettled?.(result.connectionId)
+ }
+
setOAuthConnected(Boolean(result.connected))
if (result.connected) {
diff --git a/apps/desktop/src/components/remote-setup/use-remote-setup.ts b/apps/desktop/src/components/remote-setup/use-remote-setup.ts
index de587da31cd..ad3e128aad7 100644
--- a/apps/desktop/src/components/remote-setup/use-remote-setup.ts
+++ b/apps/desktop/src/components/remote-setup/use-remote-setup.ts
@@ -27,6 +27,13 @@ export interface RemoteSetupOptions {
host: RemoteSetupHost
enabled?: boolean
beforeOAuthLogin?: (payload: DesktopConnectionConfigInput) => Promise<void>
+ /**
+ * Registry-draft identity for a sign-in that runs before the draft is
+ * saved; see useRemoteOAuth. Only the registry host supplies it.
+ */
+ oauthLoginIdentity?: () => { connectionId: null | string; label: string }
+ /** Reports the settled connection id a pre-save sign-in wrote the session for. */
+ onOAuthLoginSettled?: (connectionId: string) => void
onNotice?: (notice: NotificationInput) => void
}
@@ -138,6 +145,11 @@ export function useRemoteSetup(options: RemoteSetupOptions): RemoteSetup {
targetSeq,
beforeOAuthLogin: (value: DesktopConnectionConfigInput): Promise<void> | undefined =>
callbacks.current.beforeOAuthLogin?.(value),
+ oauthLoginIdentity: (): { connectionId: null | string; label: string } | undefined =>
+ callbacks.current.oauthLoginIdentity?.(),
+ onOAuthLoginSettled: (connectionId: string): void => {
+ callbacks.current.onOAuthLoginSettled?.(connectionId)
+ },
setOAuthConnected: (oauthConnected: boolean): void => setCredentials(value => ({ ...value, oauthConnected })),
invalidateTest: connectionTest.invalidateTest,
reportError: connectionTest.reportError,
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 91a292e026a..377d48da6e8 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -243,7 +243,10 @@ declare global {
sshConfigHosts: () => Promise<DesktopSshHostsResult>
sshResolveHost: (host: string) => Promise<DesktopSshResolveResult>
probeConnectionConfig: (remoteUrl: string) => Promise<DesktopConnectionProbeResult>
- oauthLoginConnectionConfig: (remoteUrl: string) => Promise<DesktopOauthLoginResult>
+ oauthLoginConnectionConfig: (
+ remoteUrl: string,
+ options?: DesktopOauthLoginOptions
+ ) => Promise<DesktopOauthLoginResult>
oauthLogoutConnectionConfig: (remoteUrl: string) => Promise<DesktopOauthLogoutResult>
// Hermes Cloud: one portal login powers discovery + silent per-agent
// sign-in (cloud-auto-discovery Phase 3).
@@ -1239,11 +1242,28 @@ export interface ExternalOpenFailedPayload {
message?: string
}
+export interface DesktopOauthLoginOptions {
+ /**
+ * Registry-draft identity for a sign-in that runs before the draft is
+ * saved. The main process derives the login window's cookie partition from
+ * the settled connection id; without it an unsaved draft's session lands in
+ * the legacy shared jar the saved connection never reads.
+ */
+ connectionId?: null | string
+ /** Draft label — used to mint the id when `connectionId` is absent. */
+ label?: string
+}
+
export interface DesktopOauthLoginResult {
ok: boolean
baseUrl: string
connected: boolean
error?: string
+ /**
+ * The connection id the session was written for. A pre-save sign-in should
+ * pin this into the draft so the later save reuses the same id (and jar).
+ */
+ connectionId?: string
}
export interface DesktopOauthLogoutResult {