Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): give local agents' lh the desktop sign-in, and name `lh login` when it is missing (#22114)

Arvin Xu60732620b15d
diff --git a/apps/cli/src/api/http.test.ts b/apps/cli/src/api/http.test.ts
index d38f01020e7..f9ecb1c0885 100644
--- a/apps/cli/src/api/http.test.ts
+++ b/apps/cli/src/api/http.test.ts
@@ -23,9 +23,13 @@ describe('api/http auth helpers', () => {
vi.clearAllMocks();
delete process.env.LOBEHUB_JWT;
delete process.env.LOBEHUB_WORKSPACE_ID;
+ // Outside an agent run, so a missing login keeps the plain "log in first" wording.
+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');
});
afterEach(() => {
+ vi.unstubAllEnvs();
if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;
else process.env.LOBEHUB_JWT = originalJwt;
diff --git a/apps/cli/src/api/operationTokenFallback.test.ts b/apps/cli/src/api/operationTokenFallback.test.ts
index a61504e4b15..b36c9cd1c99 100644
--- a/apps/cli/src/api/operationTokenFallback.test.ts
+++ b/apps/cli/src/api/operationTokenFallback.test.ts
@@ -116,6 +116,19 @@ describe('operation token fallback', () => {
expect(userScopedRoute).toHaveBeenCalledTimes(1);
});
+ /** The run did carry a token, so "the run passed no sign-in" would misstate the cause. */
+ it('keeps the operation-token wording inside an agent run with no machine login', async () => {
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_1');
+ vi.mocked(getValidToken).mockResolvedValue({ status: 'no-login' });
+
+ await expect(query(userScopedRoute)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining('no stored login of the same account'),
+ );
+ expect(log.warn).not.toHaveBeenCalledWith(expect.stringContaining('passed no LobeHub sign-in'));
+ vi.unstubAllEnvs();
+ });
+
it.each([
{ detail: 'HTTP 502', status: 'unavailable' },
{ detail: 'invalid_client', status: 'refused' },
diff --git a/apps/cli/src/api/operationTokenFallback.ts b/apps/cli/src/api/operationTokenFallback.ts
index a9098aeaed4..8f7c43ff993 100644
--- a/apps/cli/src/api/operationTokenFallback.ts
+++ b/apps/cli/src/api/operationTokenFallback.ts
@@ -64,7 +64,8 @@ export const storedLoginFor = async (
if (owner && subjectOf(stored) === owner) return { token: stored };
}
- const report = describeTokenLookup(result);
+ // This run did pass a credential, so the agent-run "no sign-in" report would misstate the cause.
+ const report = result.status === 'no-login' ? undefined : describeTokenLookup(result);
return {
warning: report
? `${report.detail} ${report.fix}`
diff --git a/apps/cli/src/auth/refresh.test.ts b/apps/cli/src/auth/refresh.test.ts
index c1503d8c3e9..c59b58a6110 100644
--- a/apps/cli/src/auth/refresh.test.ts
+++ b/apps/cli/src/auth/refresh.test.ts
@@ -321,7 +321,26 @@ describe('describeTokenLookup', () => {
expect(report?.fix).toContain('signing in again will not change the answer');
});
- it('leaves the caller its own wording when there is nothing to diagnose', () => {
- expect(describeTokenLookup({ status: 'no-login' })).toBeUndefined();
+ describe('no login', () => {
+ beforeEach(() => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');
+ });
+ afterEach(() => vi.unstubAllEnvs());
+
+ it('leaves the caller its own wording when there is nothing to diagnose', () => {
+ expect(describeTokenLookup({ status: 'no-login' })).toBeUndefined();
+ });
+
+ /** An agent told only "run lh login" guessed at restarts and workspace ids instead. */
+ it('explains a missing login inside an agent run and hands the login to the user', () => {
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_1');
+
+ const report = describeTokenLookup({ status: 'no-login' });
+
+ expect(report?.detail).toContain('agent conversation');
+ expect(report?.fix).toContain("Ask the user to run 'lh login'");
+ expect(report?.fix).toContain('Do not run it yourself');
+ });
});
});
diff --git a/apps/cli/src/auth/refresh.ts b/apps/cli/src/auth/refresh.ts
index baf9eed9736..b502bfec8ba 100644
--- a/apps/cli/src/auth/refresh.ts
+++ b/apps/cli/src/auth/refresh.ts
@@ -108,12 +108,37 @@ export interface TokenLookupReport {
fix: string;
}
+/**
+ * Whether this process runs inside a LobeHub agent run: the app stamps the run's ids into the
+ * environment of every agent it launches, and every shell that agent opens inherits them.
+ */
+export const isInsideAgentRun = (env: NodeJS.ProcessEnv = process.env): boolean =>
+ !!(env.LOBEHUB_TOPIC_ID || env.LOBEHUB_OPERATION_ID);
+
+/**
+ * The missing-login report for a command run by an agent inside LobeHub.
+ *
+ * Read by the agent, not by a person at a terminal, and a bare "run `lh login`" there got turned
+ * into guesses β€” restart the app, set a workspace id β€” because nothing said why a conversation the
+ * user is signed in to has no credential. Spell out the cause and hand the login to the user:
+ * `lh login` rewrites this machine's CLI credentials and registers the device, which is not the
+ * agent's call to make.
+ */
+export const agentRunMissingLoginReport = (): TokenLookupReport => ({
+ detail:
+ 'This command runs inside a LobeHub agent conversation, but the run passed no LobeHub sign-in to the CLI and this machine has no CLI login of its own.',
+ fix: `Ask the user to run '${CLI_PRIMARY_BIN} login' in a terminal on this machine and approve it in the browser, then retry. Do not run it yourself; restarting LobeHub does not fix this. Updating LobeHub Desktop lets local agents use the app's own sign-in.`,
+});
+
/**
* How to explain a lookup that produced no token, or `undefined` when there is nothing to
* diagnose and the caller's own "log in first" message fits.
*/
export function describeTokenLookup(lookup: TokenLookup): TokenLookupReport | undefined {
switch (lookup.status) {
+ case 'no-login': {
+ return isInsideAgentRun() ? agentRunMissingLoginReport() : undefined;
+ }
case 'spent': {
return {
detail: `The stored login is no longer valid (${lookup.detail}).`,
diff --git a/apps/cli/src/commands/connect.integration.test.ts b/apps/cli/src/commands/connect.integration.test.ts
index d1b237e40da..922eba75d66 100644
--- a/apps/cli/src/commands/connect.integration.test.ts
+++ b/apps/cli/src/commands/connect.integration.test.ts
@@ -53,6 +53,9 @@ async function runCli(
LOBEHUB_CLI_API_KEY: '',
LOBEHUB_CLI_HOME: '.lobehub',
LOBEHUB_JWT: '',
+ // Not an agent run, whatever shell runs the suite.
+ LOBEHUB_OPERATION_ID: '',
+ LOBEHUB_TOPIC_ID: '',
...extraEnv,
},
timeout: 10_000,
diff --git a/apps/cli/src/doctor/checks/credentials.test.ts b/apps/cli/src/doctor/checks/credentials.test.ts
index 84a6f0dd183..4dcc4a46188 100644
--- a/apps/cli/src/doctor/checks/credentials.test.ts
+++ b/apps/cli/src/doctor/checks/credentials.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { runCheck } from '../testUtils';
import { credentialChecks } from './credentials';
@@ -22,13 +22,32 @@ describe('credentials.source', () => {
source.value = { kind: 'stored', origin: 'stored login', token: 'abcd1234', tokenType: 'jwt' };
});
- it('fails when nothing is available to authenticate with', async () => {
- source.value = { kind: 'stored', origin: 'stored login', tokenType: 'jwt' };
+ describe('with no credential', () => {
+ beforeEach(() => {
+ source.value = { kind: 'stored', origin: 'stored login', tokenType: 'jwt' };
+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');
+ });
+ afterEach(() => vi.unstubAllEnvs());
- const outcome = await runCheck(credentialChecks, 'credentials.source');
+ it('fails when nothing is available to authenticate with', async () => {
+ const outcome = await runCheck(credentialChecks, 'credentials.source');
- expect(outcome.status).toBe('fail');
- expect(outcome.fix).toContain('login');
+ expect(outcome.status).toBe('fail');
+ expect(outcome.detail).toContain('No credential anywhere');
+ expect(outcome.fix).toContain('login');
+ });
+
+ /** The agent that hit this pointed the user at a desktop restart instead of a login. */
+ it('tells an agent run why it has no credential and that the user must log in', async () => {
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_1');
+
+ const outcome = await runCheck(credentialChecks, 'credentials.source');
+
+ expect(outcome.status).toBe('fail');
+ expect(outcome.detail).toContain('agent conversation');
+ expect(outcome.fix).toContain("Ask the user to run 'lh login'");
+ });
});
it('warns that an inherited LOBEHUB_JWT outranks the stored login', async () => {
diff --git a/apps/cli/src/doctor/checks/credentials.ts b/apps/cli/src/doctor/checks/credentials.ts
index ae6ccafae5a..0e9f7f2a650 100644
--- a/apps/cli/src/doctor/checks/credentials.ts
+++ b/apps/cli/src/doctor/checks/credentials.ts
@@ -1,3 +1,4 @@
+import { agentRunMissingLoginReport, isInsideAgentRun } from '../../auth/refresh';
import { maskSecret, pickAuthSource } from '../../auth/source';
import { CLI_API_KEY_ENV } from '../../constants/auth';
import { CLI_PRIMARY_BIN } from '../../constants/identity';
@@ -24,13 +25,16 @@ const credentialSource: DoctorCheck = {
tokenType: source.tokenType,
};
- if (!source.token)
+ if (!source.token) {
+ if (isInsideAgentRun()) return { ...agentRunMissingLoginReport(), evidence, status: 'fail' };
+
return {
detail: 'No credential anywhere: no login on disk, no API key in the environment.',
evidence,
fix: `Run '${CLI_PRIMARY_BIN} login', or set ${CLI_API_KEY_ENV}.`,
status: 'fail',
};
+ }
if (source.kind === 'env-jwt')
return {
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 4bd2100e845..12efb78cff2 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -111,7 +111,7 @@ import semver from 'semver';
import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
import type { App } from '@/core/App';
import { detectHeterogeneousCliCommand } from '@/modules/binaries';
-import { resolveCliScript, withEmbeddedCliEnv } from '@/modules/cliEmbedding';
+import { prepareAppSignInEnv, resolveCliScript, withEmbeddedCliEnv } from '@/modules/cliEmbedding';
import { getHeterogeneousAgentDriver, withCodexContextArgs } from '@/modules/heterogeneousAgent';
import {
consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
@@ -1475,6 +1475,13 @@ export default class HeterogeneousAgentCtr {
});
}
+ // `lh` in the run acts as the user signed in to this app, like built-in agents' `lh`.
+ const appSignInEnv = await prepareAppSignInEnv({
+ appStoragePath: this.app.appStoragePath,
+ auth: this.remoteServerAuth,
+ });
+ const sessionEnv = hostedProviderBinding?.env ?? params.env;
+
const { model, resumeSessionId } = resolveHostedBindingSession({
...params,
agentType,
@@ -1485,10 +1492,14 @@ export default class HeterogeneousAgentCtr {
this.sessions.set(sessionId, {
agentSessionId: resumeSessionId,
agentType,
- args: withCodexContextArgs(agentType, params.env, hostedProviderBinding?.args ?? params.args),
+ args: withCodexContextArgs(
+ agentType,
+ params.env || appSignInEnv ? { ...appSignInEnv, ...params.env } : undefined,
+ hostedProviderBinding?.args ?? params.args,
+ ),
command: params.command,
cwd: params.cwd,
- env: hostedProviderBinding?.env ?? params.env,
+ env: sessionEnv || appSignInEnv ? { ...appSignInEnv, ...sessionEnv } : undefined,
hostedProviderBinding,
serverDefaultApiConfig:
params.providerBinding?.kind === 'server-default'
diff --git a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
index 317368c5565..5260b851d6b 100644
--- a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
+++ b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
@@ -5,6 +5,7 @@ import type { DataSyncConfig, DesktopBootstrapIdentity } from '@lobechat/electro
import { safeStorage, session as electronSession } from 'electron';
import { OFFICIAL_CLOUD_SERVER } from '@/const/env';
+import { refreshAppSignIn, withdrawAppSignIn } from '@/modules/cliEmbedding/appSignInFile';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
@@ -259,7 +260,7 @@ export default class RemoteServerConfigCtr extends ControllerModule {
lastRefreshAt: this.lastRefreshAt,
refreshToken: this.encryptedRefreshToken,
});
- this.syncGatewayAccessToken(accessToken);
+ this.pushRefreshedAccessToken(accessToken);
return;
}
@@ -282,11 +283,13 @@ export default class RemoteServerConfigCtr extends ControllerModule {
refreshToken: this.encryptedRefreshToken,
});
- this.syncGatewayAccessToken(accessToken);
+ this.pushRefreshedAccessToken(accessToken);
}
/**
- * Hand a freshly stored access token to the live device-gateway socket.
+ * Hand a freshly stored access token to everything that holds a copy of it:
+ * the live device-gateway socket, and the sign-in file `lh` reads inside
+ * local agent runs (which would otherwise keep the expired token).
*
* The gateway client caches the token it was constructed with and replays it
* on every backoff / heartbeat reconnect, while the token itself is rotated
@@ -295,8 +298,9 @@ export default class RemoteServerConfigCtr extends ControllerModule {
* β€” the socket dropped, the client replayed the stale token, and `auth_failed`
* left the device offline.
*/
- private syncGatewayAccessToken(accessToken: string) {
+ private pushRefreshedAccessToken(accessToken: string) {
this.app.getService(GatewayConnectionService)?.updatePersonalToken(accessToken);
+ void refreshAppSignIn(accessToken);
}
/**
@@ -378,6 +382,8 @@ export default class RemoteServerConfigCtr extends ControllerModule {
// Also clear from persistent storage
logger.debug(`Deleting tokens from store key: ${this.encryptedTokensKey}`);
this.app.storeManager.delete(this.encryptedTokensKey);
+ // Signed out: agent runs must not keep acting as the previous user.
+ await withdrawAppSignIn();
// Disconnect gateway when tokens are cleared (logout / token refresh failure)
const gatewaySrv = this.app.getService(GatewayConnectionService);
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 91a9f8f975d..9cead45f87b 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -2824,6 +2824,35 @@ describe('HeterogeneousAgentCtr', () => {
return { cliArgs, command, ctr, options, sessionId, writes };
};
+ /**
+ * `lh` in a local Codex run had only the run's ids, fell back to the machine's own `lh login`
+ * that most users never made, and failed with "No credential anywhere".
+ */
+ it("hands lh the app's sign-in as a file, never the token in argv", async () => {
+ const { proc } = createFakeProc();
+ nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ getController: () => ({
+ getAccessToken: async () => 'app-access-token',
+ getRemoteServerUrl: async () => 'https://app.lobehub.com/',
+ }),
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({ agentType: 'codex', command: 'codex' });
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hi', sessionId });
+
+ const { args, options } = spawnCalls[0];
+ const filePath = path.join(appStoragePath, 'cli-auth', 'jwt');
+ expect(options.env).toMatchObject({
+ LOBEHUB_JWT_FILE: filePath,
+ LOBEHUB_SERVER: 'https://app.lobehub.com',
+ });
+ expect(args).toContain(`shell_environment_policy.set.LOBEHUB_JWT_FILE="${filePath}"`);
+ expect(args.join(' ')).not.toContain('app-access-token');
+ expect(await readFile(filePath, 'utf8')).toBe('app-access-token');
+ });
+
it.each(['codex', 'opencode'] as const)('runs %s via relay', async (agentType) => {
const { proc } = createFakeProc();
nextFakeProc = proc;
diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
index 2db5e695973..3b65d364423 100644
--- a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
@@ -5,11 +5,17 @@ import type { App } from '@/core/App';
import RemoteServerConfigCtr from '../RemoteServerConfigCtr';
-const { ipcMainHandleMock, mockFetch } = vi.hoisted(() => ({
+const { appSignInMock, ipcMainHandleMock, mockFetch } = vi.hoisted(() => ({
+ appSignInMock: {
+ refreshAppSignIn: vi.fn(async () => {}),
+ withdrawAppSignIn: vi.fn(async () => {}),
+ },
ipcMainHandleMock: vi.fn(),
mockFetch: vi.fn(),
}));
+vi.mock('@/modules/cliEmbedding/appSignInFile', () => appSignInMock);
+
vi.mock('@/utils/net-fetch', () => ({
netFetch: mockFetch,
}));
@@ -450,6 +456,15 @@ describe('RemoteServerConfigCtr', () => {
expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalled();
});
+
+ /** Local agent runs read the app's sign-in from a file that must follow it. */
+ it("keeps local agent runs' sign-in file in step with the tokens", async () => {
+ await controller.saveTokens('renewed-access', 'refresh', 3600);
+ expect(appSignInMock.refreshAppSignIn).toHaveBeenCalledWith('renewed-access');
+
+ await controller.clearTokens();
+ expect(appSignInMock.withdrawAppSignIn).toHaveBeenCalled();
+ });
});
describe('getTokenExpiresAt', () => {
diff --git a/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.test.ts b/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.test.ts
new file mode 100644
index 00000000000..7010b312105
--- /dev/null
+++ b/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.test.ts
@@ -0,0 +1,94 @@
+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ prepareAppSignInEnv,
+ refreshAppSignIn,
+ resetAppSignInForTest,
+ withdrawAppSignIn,
+} from './appSignInFile';
+
+const signedIn = (
+ accessToken: string | null,
+ serverUrl: string | null = 'https://app.lobehub.com/',
+) => ({
+ getAccessToken: async () => accessToken,
+ getServerUrl: async () => serverUrl,
+});
+
+describe('app sign-in file', () => {
+ let appStoragePath: string;
+
+ beforeEach(async () => {
+ appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-sign-in-'));
+ });
+
+ afterEach(async () => {
+ resetAppSignInForTest();
+ await rm(appStoragePath, { force: true, recursive: true });
+ });
+
+ it('writes the token to a private file and returns only its path', async () => {
+ const env = await prepareAppSignInEnv({ appStoragePath, auth: signedIn('app-token') });
+
+ const filePath = path.join(appStoragePath, 'cli-auth', 'jwt');
+ expect(env).toEqual({ LOBEHUB_JWT_FILE: filePath, LOBEHUB_SERVER: 'https://app.lobehub.com' });
+ expect(await readFile(filePath, 'utf8')).toBe('app-token');
+ if (process.platform !== 'win32') {
+ expect((await stat(filePath)).mode & 0o777).toBe(0o600);
+ expect((await stat(path.dirname(filePath))).mode & 0o777).toBe(0o700);
+ }
+ });
+
+ it.each([
+ ['no token', signedIn(null)],
+ ['no server', signedIn('app-token', null)],
+ ])('hands nothing over when the app has %s', async (_, auth) => {
+ await expect(prepareAppSignInEnv({ appStoragePath, auth })).resolves.toBeUndefined();
+ });
+
+ /** A run outlives the access token, so `lh` has to see each renewal. */
+ it('follows refreshes and is removed on sign-out until the next sign-in', async () => {
+ await prepareAppSignInEnv({ appStoragePath, auth: signedIn('first') });
+ const filePath = path.join(appStoragePath, 'cli-auth', 'jwt');
+
+ await refreshAppSignIn('renewed');
+ expect(await readFile(filePath, 'utf8')).toBe('renewed');
+
+ await withdrawAppSignIn();
+ await expect(stat(filePath)).rejects.toThrow();
+
+ await refreshAppSignIn('signed-in-again');
+ expect(await readFile(filePath, 'utf8')).toBe('signed-in-again');
+ });
+
+ it('writes nothing on refresh before any run asked for the file', async () => {
+ await refreshAppSignIn('token');
+
+ await expect(stat(path.join(appStoragePath, 'cli-auth', 'jwt'))).rejects.toThrow();
+ });
+
+ /** Local sessions can start together; one writer must not eat the others' temp file. */
+ it('lets concurrent first runs publish without losing the sign-in', async () => {
+ const envs = await Promise.all(
+ [1, 2, 3].map((i) => prepareAppSignInEnv({ appStoragePath, auth: signedIn(`token-${i}`) })),
+ );
+
+ expect(envs.every(Boolean)).toBe(true);
+ const filePath = path.join(appStoragePath, 'cli-auth', 'jwt');
+ expect(['token-1', 'token-2', 'token-3']).toContain(await readFile(filePath, 'utf8'));
+ });
+
+ /** Sign-out must win over a renewal that was already on its way. */
+ it('does not leave the credential behind when sign-out overlaps a refresh', async () => {
+ await prepareAppSignInEnv({ appStoragePath, auth: signedIn('first') });
+ const filePath = path.join(appStoragePath, 'cli-auth', 'jwt');
+
+ await Promise.all([refreshAppSignIn('renewed'), withdrawAppSignIn()]);
+
+ await expect(stat(filePath)).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.ts b/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.ts
new file mode 100644
index 00000000000..dff5fad7389
--- /dev/null
+++ b/apps/desktop/src/main/modules/cliEmbedding/appSignInFile.ts
@@ -0,0 +1,142 @@
+import { rmSync } from 'node:fs';
+import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+/**
+ * The app's sign-in, handed to the `lh` that local external agents run.
+ *
+ * A Claude Code / Codex run launched from this app used to give its shell only
+ * the run's ids, so `lh` inside it fell back to the machine's own `lh login` β€”
+ * a separate login most users never made β€” and failed with "no credential" in
+ * a conversation they were plainly signed in to. Built-in agents never hit
+ * this: their `lh` commands get the app's token from `CliCtr.buildCliEnv`.
+ *
+ * The token goes into a file and only its path into the run's env
+ * (`LOBEHUB_JWT_FILE`, which the CLI reads ahead of every other source):
+ * Codex passes shell env through `-c` argv, readable by any local user via
+ * `ps`, and a run outlives the access token, so the value has to be rewritten
+ * in place when the app refreshes it. One file serves every run β€” the app has
+ * one sign-in β€” and it exists only while a run has asked for it and the app is
+ * signed in: written on the first local run, rewritten on each refresh,
+ * removed on sign-out and on exit.
+ */
+export const APP_SIGN_IN_FILE_ENV = 'LOBEHUB_JWT_FILE';
+
+export const getAppSignInFilePath = (appStoragePath: string): string =>
+ path.join(appStoragePath, 'cli-auth', 'jwt');
+
+/** The file a run asked for, so a refresh or sign-out knows what to touch. */
+let publishedPath: string | undefined;
+
+/**
+ * File work runs one task at a time, in call order. Concurrent local sessions
+ * publish together, and a sign-out can overlap a token refresh: without this,
+ * a refresh that started earlier could rename its replacement into place after
+ * the sign-out removed the file, leaving a usable credential behind a logout.
+ */
+let pendingWrite: Promise<unknown> = Promise.resolve();
+
+const serially = <T>(task: () => Promise<T>): Promise<T> => {
+ const run = pendingWrite.then(task, task);
+ pendingWrite = run.then(
+ () => {},
+ () => {},
+ );
+ return run;
+};
+
+/** Distinguishes the temporary files of concurrent writes in this process. */
+let tempFileCounter = 0;
+
+const writeAtomically = async (filePath: string, token: string) => {
+ const dir = path.dirname(filePath);
+ await mkdir(dir, { mode: 0o700, recursive: true });
+ // `mkdir` applies the mode only to a directory it creates.
+ await chmod(dir, 0o700);
+ // A pid alone is not unique: two sessions can publish in the same process,
+ // and one writer would then rename or remove the other's temporary file.
+ tempFileCounter += 1;
+ const tmpPath = `${filePath}.${process.pid}.${tempFileCounter}.tmp`;
+ try {
+ await writeFile(tmpPath, token, { encoding: 'utf8', mode: 0o600 });
+ await rename(tmpPath, filePath);
+ } catch (error) {
+ await rm(tmpPath, { force: true }).catch(() => {});
+ throw error;
+ }
+};
+
+/** Write the token for runs to read, and remember the file for later refreshes. */
+export const publishAppSignIn = async (filePath: string, token: string): Promise<void> => {
+ if (publishedPath !== filePath) {
+ publishedPath = filePath;
+ process.once('exit', () => {
+ try {
+ rmSync(filePath, { force: true });
+ } catch {
+ // best-effort
+ }
+ });
+ }
+
+ await serially(() => writeAtomically(filePath, token));
+};
+
+/**
+ * Hand a refreshed token to running agents. No-op until a run has asked for the
+ * file; never throws, a failed write only leaves the previous token in place.
+ */
+export const refreshAppSignIn = async (token: string): Promise<void> => {
+ if (!publishedPath) return;
+ // Captured here, so a concurrent first run pointing at another file cannot
+ // redirect a renewal that was already on its way.
+ const filePath = publishedPath;
+ await serially(() => writeAtomically(filePath, token)).catch(() => {});
+};
+
+/**
+ * Remove the token on sign-out. The path stays remembered, so signing in again
+ * rewrites it for runs that were started before.
+ */
+export const withdrawAppSignIn = async (): Promise<void> => {
+ if (!publishedPath) return;
+ const filePath = publishedPath;
+ // Queued behind any renewal that was requested first, so a refresh requested
+ // before the sign-out cannot land after it.
+ await serially(() => rm(filePath, { force: true })).catch(() => {});
+};
+
+/**
+ * Env that lets `lh` inside a local agent run act as the user signed in to the
+ * app. `undefined` when the app is not signed in to a server, or when the file
+ * cannot be written β€” the run then goes on as before, on the machine's own
+ * `lh login`.
+ */
+export const prepareAppSignInEnv = async ({
+ appStoragePath,
+ auth,
+}: {
+ appStoragePath: string;
+ auth: {
+ getAccessToken: () => Promise<string | null>;
+ getServerUrl: () => Promise<string | null>;
+ };
+}): Promise<Record<string, string> | undefined> => {
+ try {
+ // Sequential for the reason given in `createLambdaFileStorePort`.
+ const serverUrl = await auth.getServerUrl();
+ const accessToken = await auth.getAccessToken();
+ if (!serverUrl || !accessToken) return undefined;
+
+ const filePath = getAppSignInFilePath(appStoragePath);
+ await publishAppSignIn(filePath, accessToken);
+ return { [APP_SIGN_IN_FILE_ENV]: filePath, LOBEHUB_SERVER: serverUrl.replace(/\/$/, '') };
+ } catch {
+ return undefined;
+ }
+};
+
+/** Test-only: forget the published file. */
+export const resetAppSignInForTest = () => {
+ publishedPath = undefined;
+};
diff --git a/apps/desktop/src/main/modules/cliEmbedding/index.ts b/apps/desktop/src/main/modules/cliEmbedding/index.ts
index a943259fb4f..7601f9bfb39 100644
--- a/apps/desktop/src/main/modules/cliEmbedding/index.ts
+++ b/apps/desktop/src/main/modules/cliEmbedding/index.ts
@@ -1,2 +1,3 @@
+export { prepareAppSignInEnv } from './appSignInFile';
export { getEmbeddedCliPath, LOBEHUB_CLI_ENV, withEmbeddedCliEnv } from './embeddedCliEnv';
export { generateCliWrapper, getCliWrapperDir, resolveCliScript } from './generateCliWrapper';
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
index e218dacc485..6fa53f0d497 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
@@ -2,9 +2,11 @@ import path from 'node:path';
import {
buildCodexLobeHubContextArgs,
+ buildCodexShellEnvSetArgs,
CODEX_DEFAULT_EXECUTION_ARGS,
CODEX_EXECUTION_MODE_FLAGS,
CODEX_REQUIRED_ARGS,
+ LOBEHUB_JWT_FILE_ENV,
} from '@lobechat/heterogeneous-agents/spawn';
import type {
CodexReasoningEffort,
@@ -237,11 +239,11 @@ const buildServerDefaultModelCatalog = (
/**
* Prefix a Codex session's args with `shell_environment_policy.set.*`
* overrides for the LobeHub run context in its env (agent/operation/topic/
- * workspace ids) plus the bundled `lh` path, so `lh` inside Codex's shell sees
- * them even when the user's config sets `inherit = "core"`. Both the
- * `codex exec` plan and the app-server thread config
- * (`buildCodexAppServerThreadParams`) read these args. Other agent types are
- * returned unchanged.
+ * workspace ids), the bundled `lh` path and the app's sign-in file, so `lh`
+ * inside Codex's shell sees them even when the user's config sets
+ * `inherit = "core"`. Both the `codex exec` plan and the app-server thread
+ * config (`buildCodexAppServerThreadParams`) read these args. Other agent types
+ * are returned unchanged.
*/
export const withCodexContextArgs = (
agentType: string,
@@ -251,6 +253,10 @@ export const withCodexContextArgs = (
agentType === 'codex' && env
? [
...buildCodexLobeHubContextArgs({ [LOBEHUB_CLI_ENV]: getEmbeddedCliPath(), ...env }),
+ // Only the path: the token itself would be readable in argv.
+ ...(env[LOBEHUB_JWT_FILE_ENV]
+ ? buildCodexShellEnvSetArgs(LOBEHUB_JWT_FILE_ENV, env[LOBEHUB_JWT_FILE_ENV])
+ : []),
...args,
]
: args;
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index fe6255ff86a..75cadf0f503 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -44,7 +44,9 @@ import type { AgentTextBlock } from './types';
* every transport:
*
* - **Credentials.** The cloud sandbox is handed a user-scoped JWT, and a
- * desktop client-mode run inherits the machine's own `lh login`. The
+ * desktop client-mode run is handed the app's own sign-in as
+ * `LOBEHUB_JWT_FILE` (older desktops left it to the machine's `lh login`,
+ * which `lh` now names as the fix when it is missing). The
* device-dispatch paths (desktop gateway, `lh connect`) put the run's narrow
* `hetero-operation` token in `LOBEHUB_JWT`, which `oidcAuth` refuses on every
* user-scoped endpoint. `lh topic view` reads through an operation route