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(cli): renew the operation token during long hetero exec runs (#19549)

Arvin Xuc0c0ac0b276a
diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.ts
index dd828c89f94..541006f21e4 100644
--- a/apps/cli/src/api/client.test.ts
+++ b/apps/cli/src/api/client.test.ts
@@ -17,7 +17,10 @@ vi.mock('../settings', () => ({
resolveServerUrl: () => 'https://app.lobehub.com',
}));
-const headersOfLastLink = () => (mockHttpLink.mock.calls.at(-1)![0] as any).headers;
+const headersOfLastLink = () => {
+ const { headers } = mockHttpLink.mock.calls.at(-1)![0] as any;
+ return typeof headers === 'function' ? headers() : headers;
+};
describe('api/client workspace scoping', () => {
const originalJwt = process.env.LOBEHUB_JWT;
@@ -38,6 +41,21 @@ describe('api/client workspace scoping', () => {
else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;
});
+ /**
+ * Regression: the env JWT was copied into the link once, when the client was
+ * built. `lh hetero exec` holds its client for the whole run, so a renewed
+ * operation token never reached it and every request after the original
+ * token's four hours was rejected.
+ */
+ it('sends a renewed LOBEHUB_JWT on requests from an existing client', async () => {
+ const { getTrpcClient } = await import('./client');
+ await getTrpcClient();
+ expect(headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'env-jwt' });
+
+ process.env.LOBEHUB_JWT = 'renewed-jwt';
+ expect(headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'renewed-jwt' });
+ });
+
// The tools router is workspace aware like lambda; without the header every
// `lh search` ran against personal scope and billed the personal budget.
it('scopes the tools client to the run workspace', async () => {
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.ts
index f3dbcbef7c7..768266dea29 100644
--- a/apps/cli/src/api/client.ts
+++ b/apps/cli/src/api/client.ts
@@ -19,14 +19,19 @@ const PERSONAL_KEY = '__personal__';
const _clients = new Map<string, TrpcClient>();
const _toolsClients = new Map<string, ToolsTrpcClient>();
-async function getAuthAndServer(): Promise<{ headers: Record<string, string>; serverUrl: string }> {
+async function getAuthAndServer(): Promise<{
+ headers: () => Record<string, string>;
+ serverUrl: string;
+}> {
// LOBEHUB_JWT + LOBEHUB_SERVER env vars (used by server-side sandbox execution)
const envJwt = process.env.LOBEHUB_JWT;
if (envJwt) {
const serverUrl = resolveServerUrl();
return {
- headers: { 'Oidc-Auth': envJwt },
+ // Read per request: `hetero exec` renews its operation token in place, and
+ // its clients live for the whole run.
+ headers: () => ({ 'Oidc-Auth': process.env.LOBEHUB_JWT || envJwt }),
serverUrl,
};
}
@@ -36,7 +41,7 @@ async function getAuthAndServer(): Promise<{ headers: Record<string, string>; se
const serverUrl = resolveServerUrl();
return {
- headers: { 'X-API-Key': envApiKey },
+ headers: () => ({ 'X-API-Key': envApiKey }),
serverUrl,
};
}
@@ -50,9 +55,10 @@ async function getAuthAndServer(): Promise<{ headers: Record<string, string>; se
}
const serverUrl = resolveServerUrl();
+ const { accessToken } = result.credentials;
return {
- headers: { 'Oidc-Auth': result.credentials.accessToken },
+ headers: () => ({ 'Oidc-Auth': accessToken }),
serverUrl,
};
}
@@ -67,7 +73,7 @@ export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {
const client = createTRPCClient<LambdaRouter>({
links: [
httpLink({
- headers: withWorkspaceHeader(headers, wsId),
+ headers: () => withWorkspaceHeader(headers(), wsId),
transformer: superjson,
url: `${serverUrl}/trpc/lambda`,
}),
@@ -125,7 +131,7 @@ export async function getToolsTrpcClient(workspaceId?: string): Promise<ToolsTrp
const client = createTRPCClient<ToolsRouter>({
links: [
httpLink({
- headers: withWorkspaceHeader(headers, wsId),
+ headers: () => withWorkspaceHeader(headers(), wsId),
transformer: superjson,
url: `${serverUrl}/trpc/tools`,
}),
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 26f6df67471..d4ac7244ded 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -37,6 +37,11 @@ vi.mock('../api/client', () => ({
getTrpcClient: mockGetTrpcClient,
}));
+const { mockRenewalStop } = vi.hoisted(() => ({ mockRenewalStop: vi.fn() }));
+vi.mock('../utils/OperationTokenRenewal', () => ({
+ createOperationTokenRenewal: () => ({ active: true, stop: mockRenewalStop }),
+}));
+
/**
* Build a Promise resolving to a fake `SpawnAgentHandle`. `spawnAgent` itself
* is async, so test mocks return the handle wrapped β€” same iterable contract,
@@ -1753,6 +1758,56 @@ describe('hetero exec command', () => {
]);
});
+ /**
+ * Regression: renewal was stopped before the final drain, so a token expiring
+ * while the drain or the finish receipt sat in retries rejected both β€” the
+ * very loss renewal exists to prevent.
+ */
+ it('keeps the operation token renewing until the finish receipt is sent', async () => {
+ const callOrder: string[] = [];
+ mockRenewalStop.mockReset();
+ mockRenewalStop.mockImplementation(() => callOrder.push('renewal:stop'));
+ mockHeteroIngestMutate.mockImplementation(async () => {
+ callOrder.push('ingest');
+ return { ack: true };
+ });
+ mockHeteroFinishMutate.mockImplementation(async () => {
+ callOrder.push('finish');
+ return { ack: true };
+ });
+ mockSpawnAgent.mockReturnValue(
+ createFakeHandle({
+ events: [
+ {
+ data: { reason: 'success' },
+ operationId: 'op-renew',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'agent_runtime_end',
+ },
+ ],
+ exitCode: 0,
+ }),
+ );
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-renew',
+ '--render',
+ 'none',
+ ]);
+
+ expect(callOrder).toEqual(['ingest', 'finish', 'renewal:stop']);
+ });
+
it('finishes with result "error" when a terminal error event is pushed despite a clean exit', async () => {
// CC relays an API/rate-limit error as an in-stream `error` event but still
// exits 0. The finish result must NOT be derived from the exit code alone,
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index fd5cadc61f9..0b426eaf836 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -35,6 +35,7 @@ import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';
import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';
import { log } from '../utils/logger';
import { createOperationHeartbeat } from '../utils/OperationHeartbeat';
+import { createOperationTokenRenewal } from '../utils/OperationTokenRenewal';
import { createLocalTraceStore } from '../utils/traceStore';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
@@ -485,6 +486,18 @@ const exec = async (options: ExecOptions): Promise<void> => {
})
: undefined;
+ // The heartbeat only renews the lease while the token under it is valid. The
+ // server signs that token for four hours; a longer run renews it in place, or
+ // every ingest after that point is rejected and the operation is reclaimed.
+ const operationTokenRenewal =
+ serverIngester && operationId
+ ? createOperationTokenRenewal({
+ operationId,
+ renew: async (id) =>
+ (await getTrpcClient()).aiAgent.refreshHeteroOperationToken.mutate({ operationId: id }),
+ })
+ : undefined;
+
// ─── AskUserQuestion MCP β€” remote Human-in-the-loop ────────────────────────
//
// Mount the same `lobe_cc` MCP server the desktop app uses, but resolve the
@@ -1033,6 +1046,9 @@ const exec = async (options: ExecOptions): Promise<void> => {
log.error('Failed to send heteroFinish:', err instanceof Error ? err.message : String(err));
}
}
+ // Only now: the drain and the finish receipt above both authenticate with the
+ // operation token, and either can sit in retries long enough for it to expire.
+ operationTokenRenewal?.stop();
// Tear down the AskUserQuestion MCP: stop polling, cancel any in-flight
// pending (β†’ CC's tool returns cleanly), close the server, drop the temp
diff --git a/apps/cli/src/utils/OperationTokenRenewal.test.ts b/apps/cli/src/utils/OperationTokenRenewal.test.ts
new file mode 100644
index 00000000000..671dec55858
--- /dev/null
+++ b/apps/cli/src/utils/OperationTokenRenewal.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createOperationTokenRenewal } from './OperationTokenRenewal';
+
+vi.mock('./logger', () => ({ log: { warn: vi.fn() } }));
+
+const HOUR = 60 * 60 * 1000;
+const NOW = new Date('2026-09-14T00:00:00.000Z').getTime();
+
+const token = (payload: Record<string, unknown>) =>
+ ['e30', Buffer.from(JSON.stringify(payload)).toString('base64url'), 'sig'].join('.');
+const operationToken = (expiresAt: number) =>
+ token({ exp: Math.floor(expiresAt / 1000), purpose: 'hetero-operation' });
+
+const originalJwt = process.env.LOBEHUB_JWT;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;
+ else process.env.LOBEHUB_JWT = originalJwt;
+});
+
+/**
+ * Regression: a Goal Task ran past the four hours its operation token was
+ * signed for. From then on every ingest β€” heartbeats included β€” was rejected
+ * with "exp claim timestamp check failed", so the run's output and its
+ * completion never reached the server while the agent kept working.
+ */
+describe('createOperationTokenRenewal', () => {
+ it('swaps in a renewed token before the current one expires, then keeps renewing', async () => {
+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);
+ const renewed = [operationToken(NOW + 7 * HOUR), operationToken(NOW + 10 * HOUR)];
+ const renew = vi
+ .fn()
+ .mockResolvedValueOnce({ jwt: renewed[0] })
+ .mockResolvedValueOnce({ jwt: renewed[1] });
+
+ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });
+ expect(renewal.active).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(3 * HOUR - 1);
+ expect(renew).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(renew).toHaveBeenCalledWith('op-1');
+ expect(process.env.LOBEHUB_JWT).toBe(renewed[0]);
+
+ await vi.advanceTimersByTimeAsync(3 * HOUR);
+ expect(renew).toHaveBeenCalledTimes(2);
+ expect(process.env.LOBEHUB_JWT).toBe(renewed[1]);
+
+ renewal.stop();
+ });
+
+ it('retries a transient failure instead of letting the token lapse', async () => {
+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);
+ const next = operationToken(NOW + 8 * HOUR);
+ const renew = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('fetch failed'))
+ .mockResolvedValueOnce({ jwt: next });
+
+ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });
+ await vi.advanceTimersByTimeAsync(3 * HOUR);
+ expect(renew).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(60 * 1000);
+ expect(renew).toHaveBeenCalledTimes(2);
+ expect(process.env.LOBEHUB_JWT).toBe(next);
+
+ renewal.stop();
+ });
+
+ it('stops once the server says the operation can no longer be renewed', async () => {
+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);
+ const renew = vi.fn().mockRejectedValue({ data: { code: 'CONFLICT' }, message: 'ended' });
+
+ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });
+ await vi.advanceTimersByTimeAsync(3 * HOUR);
+ await vi.advanceTimersByTimeAsync(2 * HOUR);
+
+ expect(renew).toHaveBeenCalledTimes(1);
+ renewal.stop();
+ });
+
+ it('does not poll a server that has no renewal endpoint', async () => {
+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);
+ const renew = vi.fn().mockRejectedValue({ data: { code: 'NOT_FOUND' }, message: 'No procedure' });
+
+ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });
+ await vi.advanceTimersByTimeAsync(3 * HOUR);
+ await vi.advanceTimersByTimeAsync(2 * HOUR);
+
+ expect(renew).toHaveBeenCalledTimes(1);
+ renewal.stop();
+ });
+
+ it('leaves a desktop session token to its own refresh flow', async () => {
+ process.env.LOBEHUB_JWT = token({ exp: Math.floor((NOW + HOUR) / 1000), sub: 'user-1' });
+ const renew = vi.fn();
+
+ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });
+ await vi.advanceTimersByTimeAsync(10 * HOUR);
+
+ expect(renewal.active).toBe(false);
+ expect(renew).not.toHaveBeenCalled();
+ });
+
+ it('never renews after the run has stopped it', async () => {
+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);
+ const renew = vi.fn();
+
+ createOperationTokenRenewal({ operationId: 'op-1', renew }).stop();
+ await vi.advanceTimersByTimeAsync(10 * HOUR);
+
+ expect(renew).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/cli/src/utils/OperationTokenRenewal.ts b/apps/cli/src/utils/OperationTokenRenewal.ts
new file mode 100644
index 00000000000..35c3938c1e5
--- /dev/null
+++ b/apps/cli/src/utils/OperationTokenRenewal.ts
@@ -0,0 +1,92 @@
+import { log } from './logger';
+
+/** Renew this long before expiry, so a slow or failed attempt still has room to retry. */
+const RENEW_BEFORE_EXPIRY_MS = 60 * 60 * 1000;
+const RETRY_DELAY_MS = 60 * 1000;
+const MIN_DELAY_MS = 30 * 1000;
+
+/**
+ * The server will never renew after these: the token is gone, out of scope, the
+ * run ended, or the server predates the renewal endpoint.
+ */
+const TERMINAL_CODES = new Set(['CONFLICT', 'FORBIDDEN', 'NOT_FOUND', 'UNAUTHORIZED']);
+
+interface OperationTokenRenewalOptions {
+ operationId: string;
+ renew: (operationId: string) => Promise<{ jwt: string }>;
+}
+
+/** Expiry of a server-minted operation token; undefined for any other credential. */
+const readOperationTokenExpiry = (jwt: string): number | undefined => {
+ try {
+ const payload = JSON.parse(Buffer.from(jwt.split('.')[1] ?? '', 'base64url').toString('utf8'));
+ return payload?.purpose === 'hetero-operation' && typeof payload.exp === 'number'
+ ? payload.exp * 1000
+ : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Keep the operation token of a long `hetero exec` run valid.
+ *
+ * The server signs it for four hours, and a Goal Task can run far longer. Once
+ * it expires every ingest is rejected β€” heartbeats included β€” so the lease stops
+ * renewing and the server reclaims the operation as abandoned while the agent is
+ * still working. Renewing writes the new token back to `LOBEHUB_JWT`, which the
+ * tRPC clients read on every request.
+ *
+ * Only a `hetero-operation` token is renewed. A desktop run authenticates with
+ * its own session token, which has its own refresh flow.
+ */
+export const createOperationTokenRenewal = ({
+ operationId,
+ renew,
+}: OperationTokenRenewalOptions) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let stopped = false;
+
+ const schedule = (delayMs: number) => {
+ if (stopped) return;
+ timer = setTimeout(() => void attempt(), Math.max(delayMs, MIN_DELAY_MS));
+ timer.unref?.();
+ };
+
+ const scheduleFromCurrentToken = () => {
+ const jwt = process.env.LOBEHUB_JWT;
+ const expiresAt = jwt ? readOperationTokenExpiry(jwt) : undefined;
+ if (expiresAt === undefined) return false;
+ schedule(expiresAt - RENEW_BEFORE_EXPIRY_MS - Date.now());
+ return true;
+ };
+
+ const attempt = async () => {
+ try {
+ const { jwt } = await renew(operationId);
+ if (stopped) return;
+ process.env.LOBEHUB_JWT = jwt;
+ scheduleFromCurrentToken();
+ } catch (error) {
+ const code = (error as { data?: { code?: string } } | null)?.data?.code;
+ const message = error instanceof Error ? error.message : String(error);
+ if (code && TERMINAL_CODES.has(code)) {
+ log.warn(`Operation token can no longer be renewed (${code}): ${message}`);
+ return;
+ }
+ log.warn(`Could not renew the operation token, retrying: ${message}`);
+ schedule(RETRY_DELAY_MS);
+ }
+ };
+
+ const active = scheduleFromCurrentToken();
+
+ return {
+ /** Whether this run holds a token that gets renewed at all. */
+ active,
+ stop: () => {
+ stopped = true;
+ clearTimeout(timer);
+ },
+ };
+};