The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): support Privy and NAS portal sessions in Cloud sign-in
Robin Fernandes07a05437b339
diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.ymlindex 62e3a21e698..89da9e8c60f 100644--- a/.github/workflows/js-tests.yml+++ b/.github/workflows/js-tests.yml@@ -26,9 +26,16 @@ jobs:# The desktop SSH watchdog tests run their probe through a real zsh# login shell (#111949). The ubuntu image ships no zsh and the tests# skip without it, so install it here or those legs never run on CI.- - name: Install zsh+ #+ # The desktop portal-session live test drives real Electron windows+ # (electron/portal-session-live.test.ts) and skips without a display,+ # so give the runner a virtual one the same way the Playwright lane does.+ - name: Install zsh and a virtual display for Electronif: runner.os == 'Linux'- run: sudo apt-get install -y zsh+ run: |+ sudo apt-get install -y zsh xvfb \+ libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \+ xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64- name: grab npm 12run: |diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.tsindex abae4e81a68..76fc83f5b1e 100644--- a/apps/desktop/electron/connection-config.test.ts+++ b/apps/desktop/electron/connection-config.test.ts@@ -23,8 +23,6 @@ import {buildGatewayWsUrlWithTicket,connectionScopeKey,cookiesHaveLiveSession,- cookiesHavePrivyAccessToken,- cookiesHavePrivySession,cookiesHaveSession,gatewayTicketFailure,gatewayWsUrlIpcResult,@@ -1100,71 +1098,6 @@ test('cookiesHaveLiveSession is false for unrelated cookies and non-arrays', ()assert.equal(cookiesHaveLiveSession([]), false)})-// --- cookiesHavePrivySession (Nous portal / Privy auth, NOT gateway cookies) -----test('cookiesHavePrivySession detects the privy-token access cookie', () => {- assert.equal(cookiesHavePrivySession([{ name: 'privy-token', value: 'jwt' }]), true)-})--test('cookiesHavePrivySession detects __Host-/__Secure- prefixes and the legacy privy-session name', () => {- assert.equal(cookiesHavePrivySession([{ name: '__Host-privy-token', value: 'x' }]), true)- assert.equal(cookiesHavePrivySession([{ name: '__Secure-privy-token', value: 'x' }]), true)- assert.equal(cookiesHavePrivySession([{ name: 'privy-session', value: 'x' }]), true)-})--test('cookiesHavePrivySession is false for an empty value', () => {- assert.equal(cookiesHavePrivySession([{ name: 'privy-token', value: '' }]), false)-})--test('cookiesHavePrivySession does NOT treat hermes gateway cookies as a portal session', () => {- // The whole point of Q7: a gateway session cookie is NOT a portal sign-in.- assert.equal(cookiesHavePrivySession([{ name: 'hermes_session_at', value: 'x' }]), false)- assert.equal(cookiesHavePrivySession([{ name: '__Host-hermes_session_rt', value: 'x' }]), false)-})--test('cookiesHavePrivySession is false for unrelated cookies and non-arrays', () => {- assert.equal(cookiesHavePrivySession([{ name: 'other', value: 'x' }]), false)- assert.equal(cookiesHavePrivySession(null), false)- assert.equal(cookiesHavePrivySession(undefined), false)- assert.equal(cookiesHavePrivySession([]), false)-})--test('cookiesHavePrivySession treats refresh-token material as a (renewable) session', () => {- // #73495: after a restart the ~1h `privy-token` is often gone while the- // 30-day renewal cookies survive. That jar is still SIGNED IN (renewable),- // so the session check must accept it — the access check below is what- // distinguishes "can discovery succeed right now".- assert.equal(cookiesHavePrivySession([{ name: 'privy-refresh-token', value: 'x' }]), true)-})--// --- cookiesHavePrivyAccessToken (short-lived access state for /api/agents) -----test('cookiesHavePrivyAccessToken detects privy-token and its secured prefixes', () => {- assert.equal(cookiesHavePrivyAccessToken([{ name: 'privy-token', value: 'jwt' }]), true)- assert.equal(cookiesHavePrivyAccessToken([{ name: '__Host-privy-token', value: 'x' }]), true)- assert.equal(cookiesHavePrivyAccessToken([{ name: '__Secure-privy-token', value: 'x' }]), true)-})--test('cookiesHavePrivyAccessToken rejects renewal-only jars (the #73495 cold-start state)', () => {- // Session/refresh material present, access token absent: signed in but- // discovery would 401 → the silent-renewal path must trigger, not re-login.- const renewalOnly = [- { name: 'privy-session', value: 'x' },- { name: 'privy-refresh-token', value: 'x' }- ]-- assert.equal(cookiesHavePrivySession(renewalOnly), true)- assert.equal(cookiesHavePrivyAccessToken(renewalOnly), false)-})--test('cookiesHavePrivyAccessToken is false for empty values, gateway cookies, and non-arrays', () => {- assert.equal(cookiesHavePrivyAccessToken([{ name: 'privy-token', value: '' }]), false)- assert.equal(cookiesHavePrivyAccessToken([{ name: 'hermes_session_at', value: 'x' }]), false)- assert.equal(cookiesHavePrivyAccessToken(null), false)- assert.equal(cookiesHavePrivyAccessToken(undefined), false)- assert.equal(cookiesHavePrivyAccessToken([]), false)-})-// --- tokenPreview ---test('tokenPreview returns null for empty', () => {diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.tsindex 3e620d1be6d..735694264b2 100644--- a/apps/desktop/electron/connection-config.ts+++ b/apps/desktop/electron/connection-config.ts@@ -39,28 +39,6 @@ import { readStatusCode } from './api-transport'const AT_COOKIE_VARIANTS = ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at']const RT_COOKIE_VARIANTS = ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt']-// The Nous portal (NAS) does NOT use Hermes gateway session cookies — it is a-// Privy-authed Next.js app. NAS `auth()` (src/server/auth/session.ts) reads the-// `privy-token` access-token cookie (with `privy-id-token` alongside), which is-// also exactly what the `/api/agents` cookie-auth path validates. So portal-// sign-in / discovery liveness must look for the Privy cookie, NOT the gateway-// cookies above. `privy-token` is the access token (the required signal);-// variants cover the secured-prefix forms and the older `privy-session` name.-const PRIVY_SESSION_COOKIE_VARIANTS = [- '__Host-privy-token',- '__Secure-privy-token',- 'privy-token',- 'privy-session',- 'privy-refresh-token'-]--// The short-lived Privy ACCESS token only — the credential `/api/agents`-// actually validates. `privy-session` / `privy-refresh-token` are long-lived-// renewal material: their presence means the session is RENEWABLE (signed in,-// no interactive login needed), but discovery still 401s until a fresh-// `privy-token` is minted. Distinguishing the two is what lets a cold start-// silently renew instead of demanding a re-login (#73495).-const PRIVY_ACCESS_COOKIE_VARIANTS = ['__Host-privy-token', '__Secure-privy-token', 'privy-token']// Keep this aligned with hermes_cli.profiles.validate_profile_name(). `default`// is the built-in root alias; these names cannot be created as profiles.const RESERVED_REMOTE_PROFILES = new Set(['hermes', 'test', 'tmp', 'root', 'sudo'])@@ -1025,38 +1003,6 @@ function cookiesHaveLiveSession(cookies) {return cookies.some(c => c && c.value && (AT_COOKIE_VARIANTS.includes(c.name) || RT_COOKIE_VARIANTS.includes(c.name)))}-/**- * True if the cookie jar holds a live Nous PORTAL (Privy) session — a non-empty- * `privy-token` (access-token) cookie, or a variant. This is the portal- * analogue of `cookiesHaveLiveSession`: the portal authenticates via Privy, not- * the Hermes gateway session cookies, so cloud sign-in / discovery liveness- * must check THIS, not the gateway helpers. (NAS `auth()` and the `/api/agents`- * cookie path both key off `privy-token`.)- */-function cookiesHavePrivySession(cookies) {- if (!Array.isArray(cookies)) {- return false- }-- return cookies.some(c => c && c.value && PRIVY_SESSION_COOKIE_VARIANTS.includes(c.name))-}--/**- * True only when the short-lived Privy ACCESS token (`privy-token`) is present- * — the exact cookie `/api/agents` validates. A jar can satisfy- * `cookiesHavePrivySession` (renewable session: `privy-session` /- * `privy-refresh-token`) while failing this check; that gap is the cold-start- * "Signed in" + "No agents found" contradiction, and the signal that a silent- * renewal (not an interactive re-login) is the right recovery (#73495).- */-function cookiesHavePrivyAccessToken(cookies) {- if (!Array.isArray(cookies)) {- return false- }-- return cookies.some(c => c && c.value && PRIVY_ACCESS_COOKIE_VARIANTS.includes(c.name))-}-export {apiRequestRegistryConnectionId,AT_COOKIE_VARIANTS,@@ -1065,8 +1011,6 @@ export {buildGatewayWsUrlWithTicket,connectionScopeKey,cookiesHaveLiveSession,- cookiesHavePrivyAccessToken,- cookiesHavePrivySession,cookiesHaveSession,gatewayTicketFailure,gatewayWsUrlIpcResult,@@ -1081,8 +1025,6 @@ export {pathForRegistryBackendRequest,pathWithGlobalRemoteProfile,pathWithProfileScope,- PRIVY_ACCESS_COOKIE_VARIANTS,- PRIVY_SESSION_COOKIE_VARIANTS,profileHasRemoteConnection,profileRemoteOverride,profileSshOverride,diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 34e64b31f89..95b241b29d5 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -8447,10 +8447,8 @@ async function discoverCloudAgents(org?: string) {throw err}- // Renewable session present but the short-lived access token `/api/agents`- // validates is gone (typical after a restart — `privy-token` is ~1h,- // `privy-session`/`privy-refresh-token` last ~30 days). Renew silently up- // front instead of letting the request 401 into a re-login demand (#73495).+ // Access cookies expire before refresh credentials. Let the portal renew+ // whichever session this browser currently holds before discovery.if (!(await hasPortalAccessToken())) {await renewPortalAccessSilently()}@@ -8474,7 +8472,7 @@ async function discoverCloudAgents(org?: string) {// interactive re-login while a 30-day refresh session sits unused. Only a// rejected/failed renewal (or a second 401 on genuinely fresh access)// falls through to needsCloudLogin.- if (error && error.statusCode === 401 && (await renewPortalAccessSilently())) {+ if (error && error.statusCode === 401 && (await renewPortalAccessSilently({ force: true }))) {try {body = (await fetchAgents()) as any} catch (retryError) {diff --git a/apps/desktop/electron/portal-cookies.test.ts b/apps/desktop/electron/portal-cookies.test.tsnew file mode 100644index 00000000000..ed6934e9187--- /dev/null+++ b/apps/desktop/electron/portal-cookies.test.ts@@ -0,0 +1,41 @@+import assert from 'node:assert/strict'++import { test } from 'vitest'++import { cookiesHavePortalAccessToken, cookiesHavePortalSession } from './portal-cookies'++// Contract: NAS accepts either credential family during the auth migration, so+// the Desktop must read both, and must tell renewable-only jars (signed in,+// discovery would 401) apart from jars that can pass /api/agents right now.+test('either portal credential family signs in, and refresh-only material is a session without access', () => {+ for (const [access, refresh] of [+ ['privy-token', 'privy-refresh-token'],+ ['nas-session', 'nas-refresh']+ ]) {+ const accessJar = [{ name: access, value: 'jwt' }]+ const refreshJar = [{ name: refresh, value: 'jwt' }]++ assert.equal(cookiesHavePortalSession(accessJar), true)+ assert.equal(cookiesHavePortalAccessToken(accessJar), true)+ assert.equal(cookiesHavePortalSession(refreshJar), true)+ assert.equal(cookiesHavePortalAccessToken(refreshJar), false)+ }+})++// Contract: the jar also holds Hermes GATEWAY session cookies, NAS provider+// routing hints and logout identifiers. None of those authenticate the portal.+test('gateway cookies, routing hints, empty values and non-arrays are never a portal credential', () => {+ const noise = [+ { name: 'hermes_session_at', value: 'x' },+ { name: '__Host-hermes_session_rt', value: 'x' },+ { name: 'next-auth-provider', value: 'workos' },+ { name: 'workos-session-id', value: 'logout-only' },+ { name: 'privy-token', value: '' },+ { name: 'nas-session', value: '' }+ ]++ for (const jar of [noise, [], null, undefined]) {+ assert.equal(cookiesHavePortalSession(jar), false)+ assert.equal(cookiesHavePortalAccessToken(jar), false)+ }+})diff --git a/apps/desktop/electron/portal-cookies.ts b/apps/desktop/electron/portal-cookies.tsnew file mode 100644index 00000000000..fb9201bd515--- /dev/null+++ b/apps/desktop/electron/portal-cookies.ts@@ -0,0 +1,24 @@+interface PortalCookie {+ name: string+ value: string+}++// NAS accepts either credential during migration. Provider-routing hints and+// WorkOS logout identifiers are not credentials; gateway cookies are unrelated.+const ACCESS_COOKIES = ['nas-session', '__Host-privy-token', '__Secure-privy-token', 'privy-token']+const REFRESH_COOKIES = ['nas-refresh', 'privy-session', 'privy-refresh-token']++export function portalAccessCookies(cookies: PortalCookie[]): PortalCookie[] {+ return cookies.filter(cookie => cookie?.value && ACCESS_COOKIES.includes(cookie.name))+}++export function cookiesHavePortalAccessToken(cookies: unknown): boolean {+ return Array.isArray(cookies) && portalAccessCookies(cookies).length > 0+}++export function cookiesHavePortalSession(cookies: unknown): boolean {+ return (+ cookiesHavePortalAccessToken(cookies) ||+ (Array.isArray(cookies) && cookies.some(cookie => cookie?.value && REFRESH_COOKIES.includes(cookie.name)))+ )+}diff --git a/apps/desktop/electron/portal-session-live-fixture/main.ts b/apps/desktop/electron/portal-session-live-fixture/main.tsnew file mode 100644index 00000000000..a84899565ba--- /dev/null+++ b/apps/desktop/electron/portal-session-live-fixture/main.ts@@ -0,0 +1,169 @@+import assert from 'node:assert/strict'+import { createServer } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'++import { app, BrowserWindow, session } from 'electron'++import { createPortalSession } from '../portal-session'++// Real Chromium cookies, HTTP redirects and renderer requests. All credentials+// are synthetic and the portal is loopback-only; no existing Electron jar is used.+app.setPath('userData', join(process.argv[2], 'user-data'))+app.on('window-all-closed', () => {})++async function run() {+ await app.whenReady()+ const jar = session.fromPartition('persist:portal-test')+ let provider: 'privy' | 'nas' = 'privy'+ let mode: 'login' | 'renew' | 'reject' = 'login'+ let version = 0+ let refreshes = 0++ let completeRequested = () => {}++ let releaseLogin = () => {}+ let loginGate = Promise.resolve()+ const accessName = () => (provider === 'nas' ? 'nas-session' : 'privy-token')+ const refreshName = () => (provider === 'nas' ? 'nas-refresh' : 'privy-refresh-token')+ const cookie = (name: string, value: string) => `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=3600`++ const accessCookies = () => [+ cookie(accessName(), `access-${++version}`),+ cookie(refreshName(), `refresh-${version}`),+ `${provider === 'nas' ? 'privy-token' : 'nas-session'}=; Path=/; Max-Age=0`,+ `${provider === 'nas' ? 'privy-refresh-token' : 'nas-refresh'}=; Path=/; Max-Age=0`+ ]++ const server = createServer(async (req, res) => {+ if (req.url === '/api/agents') {+ res.statusCode = req.headers.cookie?.includes(`${accessName()}=access-${version}`) ? 200 : 401+ res.end(JSON.stringify({ agents: [] }))++ return+ }++ if (req.url === '/complete') {+ completeRequested()+ await loginGate+ res.setHeader('Set-Cookie', accessCookies())+ res.end('ok')++ return+ }++ if (req.url === '/refresh') {+ refreshes+++ res.setHeader('Set-Cookie', accessCookies())+ res.writeHead(302, { Location: '/ready' }).end()++ return+ }++ if (req.url === '/' && mode === 'renew') {+ res.writeHead(302, { Location: '/refresh' }).end()++ return+ }++ res.setHeader('Content-Type', 'text/html')++ if (req.url === '/' && mode === 'login') {+ res.setHeader('Set-Cookie', cookie(refreshName(), 'pending'))+ res.end('<!doctype html><script>fetch("/complete")</script>')+ } else {+ res.end('<!doctype html><p>Portal</p>')+ }+ })++ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`++ const portal = createPortalSession({+ isReady: () => app.isReady(),+ getOauthSession: () => jar,+ resolvePortalBaseUrl: () => base,+ warmOauthCookieStore: () => jar.cookies.flushStore(),+ createWindow: options => new BrowserWindow({ ...options, show: false }),+ rememberLog: message => console.log(message)+ })++ try {+ // Real interactive completion must wait past refresh-only state, for both+ // providers, and NAS login must survive removal of all Privy cookies.+ for (const next of ['privy', 'nas'] as const) {+ provider = next+ mode = 'login'+ await jar.clearStorageData()+ loginGate = new Promise(resolve => {+ releaseLogin = resolve+ })++ const requested = new Promise<void>(resolve => {+ completeRequested = resolve+ })++ let completed = false++ const login = portal.openPortalLoginWindow().then(() => {+ completed = true+ })++ await requested+ assert.equal(await portal.hasLivePortalSession(), true)+ assert.equal(await portal.hasPortalAccessToken(), false)+ assert.equal(completed, false)+ releaseLogin()+ await login+ assert.equal(await portal.hasPortalAccessToken(), true)+ assert.equal((await jar.fetch(`${base}/api/agents`)).status, 200)++ // Expired access + durable refresh, including concurrent discovery/cascade.+ await jar.cookies.remove(base, accessName())+ mode = 'renew'+ const before = refreshes+ const first = portal.renewPortalAccessSilently()+ const second = portal.renewPortalAccessSilently()+ assert.equal(first, second)+ assert.equal(await first, true)+ assert.equal(refreshes, before + 1)+ assert.equal((await jar.fetch(`${base}/api/agents`)).status, 200)+ }++ // Dual-mint, followed by both provider transitions, with no cached identity.+ await jar.cookies.set({ url: base, name: 'privy-token', value: 'old-privy' })+ assert.equal(await portal.hasPortalAccessToken(), true)++ for (const next of ['privy', 'nas', 'privy'] as const) {+ provider = next+ mode = 'renew'+ assert.equal(await portal.renewPortalAccessSilently({ force: true }), true)+ assert.equal((await jar.fetch(`${base}/api/agents`)).status, 200)+ }++ // A server-rejected cookie must not short-circuit renewal as successful.+ mode = 'reject'+ await jar.cookies.set({ url: base, name: accessName(), value: 'rejected', httpOnly: true })+ assert.equal((await jar.fetch(`${base}/api/agents`)).status, 401)+ assert.equal(await portal.renewPortalAccessSilently({ force: true }), false)+ assert.equal(BrowserWindow.getAllWindows().length, 0)++ await jar.clearStorageData()+ await jar.cookies.set({ url: base, name: 'next-auth-provider', value: 'workos' })+ assert.equal(await portal.hasLivePortalSession(), false)+ assert.equal(await portal.renewPortalAccessSilently(), false)+ console.log('PORTAL_SESSION_LIVE_OK')+ } finally {+ for (const window of BrowserWindow.getAllWindows()) {window.destroy()}+ server.closeAllConnections()+ await new Promise<void>(resolve => server.close(() => resolve()))+ }+}++void run().then(+ () => app.exit(0),+ error => {+ console.error(error)+ app.exit(1)+ }+)diff --git a/apps/desktop/electron/portal-session-live.test.ts b/apps/desktop/electron/portal-session-live.test.tsnew file mode 100644index 00000000000..5e3c413f869--- /dev/null+++ b/apps/desktop/electron/portal-session-live.test.ts@@ -0,0 +1,62 @@+import { execFile } from 'node:child_process'+import { existsSync } from 'node:fs'+import { mkdtemp, rm } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { promisify } from 'node:util'++import { build } from 'esbuild'+import { expect, test } from 'vitest'++// Chromium needs a display. macOS and Windows always have one; a headless Linux+// runner gets a virtual one through xvfb-run when it is installed (the js-tests+// CI image installs it for this file). Resolved once so the skip is explicit:+// `null` means the test cannot run here, otherwise the command prefix to use.+const displayPrefix = (() => {+ if (process.platform !== 'linux' || process.env.DISPLAY || process.env.WAYLAND_DISPLAY) {+ return []+ }++ const xvfbRun = (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, 'xvfb-run')).find(existsSync)++ return xvfbRun ? [xvfbRun, '-a'] : null+})()++test.skipIf(displayPrefix === null)(+ 'real portal windows handle both providers, transitions and expired/rejected access',+ async () => {+ const root = await mkdtemp(join(tmpdir(), 'hermes-portal-session-'))++ try {+ const bundle = join(root, 'main.cjs')+ await build({+ entryPoints: [fileURLToPath(new URL('./portal-session-live-fixture/main.ts', import.meta.url))],+ outfile: bundle,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ external: ['electron']+ })+ const env: NodeJS.ProcessEnv = {}++ for (const name of ['PATH', 'SystemRoot', 'WINDIR', 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) {+ if (process.env[name]) {env[name] = process.env[name]}+ }++ const electron: string = createRequire(import.meta.url)('electron')+ const [command, ...args] = [...(displayPrefix ?? []), electron, bundle, root]++ const { stdout } = await promisify(execFile)(command, args, {+ env: { ...env, HERMES_HOME: join(root, '.hermes'), XDG_CONFIG_HOME: join(root, 'config') },+ timeout: 45_000+ })++ expect(stdout).toContain('PORTAL_SESSION_LIVE_OK')+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ },+ 60_000+)diff --git a/apps/desktop/electron/portal-session.ts b/apps/desktop/electron/portal-session.tsindex 7195b22226f..ba331b3cf44 100644--- a/apps/desktop/electron/portal-session.ts+++ b/apps/desktop/electron/portal-session.ts@@ -1,6 +1,6 @@import type { BrowserWindow, BrowserWindowConstructorOptions, Session } from 'electron'-import { cookiesHavePrivyAccessToken, cookiesHavePrivySession } from './connection-config'+import { cookiesHavePortalAccessToken, cookiesHavePortalSession, portalAccessCookies } from './portal-cookies'import { installWindowRendererLifecycle } from './window-renderer-lifecycle'interface PortalSessionDependencies {@@ -22,45 +22,37 @@ export function createPortalSession({createWindow,rememberLog}: PortalSessionDependencies) {- // Whether the OAuth partition currently holds a live Nous portal session — the- // credential that powers both discovery and the silent cascade. The portal- // authenticates via PRIVY, not the Hermes gateway session cookies, so this- // checks for the `privy-token` cookie on the portal host (NOT- // hasLiveOauthSession, which looks for hermes_session_at/rt that the portal- // never sets). See connection-config.ts cookiesHavePrivySession.- //- // Mirrors hasLiveOauthSession's cold-start guard (#73495): a `persist:`- // partition's cookie store hydrates lazily, so the FIRST read on a fresh boot- // can come back empty even for a signed-in user. The renderer checks Cloud- // status exactly once on entering cloud mode, so a single false-negative here- // used to clear the discovered agent list and demand a re-login that a plain- // retry would have avoided. Warm the store and re-read with a short backoff- // before trusting a negative.- async function hasLivePortalSession() {+ // One reader for every portal-cookie question so the failure rungs cannot+ // drift between callers: URL-scoped first, host-scoped when Chromium rejects+ // the URL form, empty when the jar is unreadable.+ async function readPortalCookies() {const sess = getOauthSession()if (!sess) {- return false+ return []}const portalBaseUrl = resolvePortalBaseUrl()- const parsed = new URL(portalBaseUrl)- const readPortal = async () => {+ try {+ return await sess.cookies.get({ url: portalBaseUrl })+ } catch {try {- const cookies = await sess.cookies.get({ url: portalBaseUrl })-- return cookiesHavePrivySession(cookies)+ return await sess.cookies.get({ domain: new URL(portalBaseUrl).hostname })} catch {- try {- const cookies = await sess.cookies.get({ domain: parsed.hostname })-- return cookiesHavePrivySession(cookies)- } catch {- return false- }+ return []}}+ }++ // A persisted Chromium jar hydrates lazily; warm and retry before reporting+ // signed-out on a cold start. Both access and refresh credentials count here.+ async function hasLivePortalSession() {+ if (!getOauthSession()) {+ return false+ }++ const readPortal = async () => cookiesHavePortalSession(await readPortalCookies())if (await readPortal()) {return true@@ -79,51 +71,20 @@ export function createPortalSession({return readPortal()}- // Whether the jar holds the short-lived Privy ACCESS token — the exact cookie- // `/api/agents` validates. hasLivePortalSession() answers "signed in at all?"- // (renewal material counts); this answers "can discovery succeed right now?".- async function hasPortalAccessToken() {- const sess = getOauthSession()-- if (!sess) {- return false- }-- const portalBaseUrl = resolvePortalBaseUrl()- const parsed = new URL(portalBaseUrl)-- try {- const cookies = await sess.cookies.get({ url: portalBaseUrl })-- return cookiesHavePrivyAccessToken(cookies)- } catch {- try {- const cookies = await sess.cookies.get({ domain: parsed.hostname })+ async function readAccessCookies() {+ return portalAccessCookies(await readPortalCookies())+ }- return cookiesHavePrivyAccessToken(cookies)- } catch {- return false- }- }+ async function hasPortalAccessToken() {+ return cookiesHavePortalAccessToken(await readAccessCookies())}- // Bounded silent renewal of the short-lived Privy access token (#73495).- //- // After a Desktop restart the long-lived `privy-session` / `privy-refresh-token`- // cookies routinely survive while the ~1h `privy-token` access cookie has- // expired. Discovery then 401s and the only offered recovery used to be a full- // interactive re-login — even though the persisted refresh material can mint a- // fresh access token with no user action: loading any portal page runs the- // Privy client, which rotates a new `privy-token` from the refresh session.- //- // This drives exactly that, headlessly: a hidden window on the portal root in- // the OAuth partition, polled until the access cookie lands, torn down on a- // bounded timeout. Never shown — if renewal can't complete silently the caller- // falls back to the interactive needsCloudLogin path. The in-flight promise is- // shared so concurrent discovery + cascade calls ride one renewal.+ // Loading the portal lets NAS choose its own refresher: Privy client renewal,+ // or the NAS server-side refresh redirect. Never pin a provider in Desktop.+ // Share a single renewal so concurrent calls cannot race rotating refresh tokens.let portalAccessRenewal: Promise<boolean> | null = null- function renewPortalAccessSilently() {+ function renewPortalAccessSilently({ force = false } = {}) {if (portalAccessRenewal) {return portalAccessRenewal}@@ -145,7 +106,9 @@ export function createPortalSession({return false}- if (await hasPortalAccessToken()) {+ const previousAccess = await readAccessCookies()++ if (!force && previousAccess.length > 0) {return true}@@ -153,9 +116,9 @@ export function createPortalSession({return await new Promise<boolean>(resolve => {let settled = false- let win = null- let pollTimer = null- let deadlineTimer = null+ let win: BrowserWindow | null = null+ let pollTimer: ReturnType<typeof setInterval> | null = null+ let deadlineTimer: ReturnType<typeof setTimeout> | null = nullconst finish = (ok: boolean) => {if (settled) {@@ -189,7 +152,12 @@ export function createPortalSession({return}- if (await hasPortalAccessToken()) {+ const access = await readAccessCookies()++ // A rejected token still in Chromium's jar is not a successful renewal.+ if (+ access.some(cookie => !previousAccess.some(old => old.name === cookie.name && old.value === cookie.value))+ ) {finish(true)}}@@ -260,8 +228,8 @@ export function createPortalSession({}let settled = false- let win = null- let pollTimer = null+ let win: BrowserWindow | null = null+ let pollTimer: ReturnType<typeof setInterval> | null = nullconst finish = err => {if (settled) {@@ -294,8 +262,9 @@ export function createPortalSession({return}- // A live portal (Privy) session cookie means sign-in completed.- if (await hasLivePortalSession()) {+ // Refresh material alone must not close the window before the portal+ // can replace it with usable access, regardless of the login provider.+ if (await hasPortalAccessToken()) {finish(null)}}@@ -336,8 +305,7 @@ export function createPortalSession({}})- // Land on the portal root; any authenticated portal page sets the session- // cookie. We only care that the partition cookie jar is populated.+ // The portal owns provider selection, provisioning and refresh redirects.win.loadURL(portalBaseUrl).catch(error => {finish(error instanceof Error ? error : new Error(String(error)))})diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 5bb900e3053..406af856db0 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -1161,9 +1161,8 @@ export interface DesktopOauthLogoutResult {export interface DesktopCloudStatus {// The portal base URL the desktop talks to (default or env-overridden).portalBaseUrl: string- // Whether the OAuth partition holds a live Nous portal (Privy) session — the- // portal authenticates via Privy, so this reflects the privy-token cookie, NOT- // the hermes gateway session cookies. See cookiesHavePrivySession.+ // Whether the OAuth partition holds portal access or renewal credentials+ // (Privy or NAS). Discovery validates them with the portal.signedIn: boolean}