π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(remote-agent): reuse desktop session for remote CC instead of operation JWT (#16350)
Arvin Xubf2ac5d2e770
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex c8eb4a0ddfa..df299b0d7f6 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -292,6 +292,20 @@ export default class GatewayConnectionCtr extends ControllerModule {return { reason: 'Remote server URL not configured', status: 'rejected' };}+ // Reuse this device's own logged-in session as the run identity. The+ // access token is a full user OIDC token (7-day TTL, longer than any run),+ // which heteroIngest/heteroFinish now accept (ownership-gated), AND which+ // gives the spawned Claude Code's nested `lh` calls a real login state β+ // unlike the narrow `hetero-operation` token, which only works for the+ // ingest endpoints. We deliberately do NOT pass the refresh token to the+ // CLI: the device stays the single refresher (refresh tokens rotate), and+ // the 7-day access token outlives the run so no mid-run refresh is needed.+ //+ // Fall back to the dispatched `request.jwt` when the device has no access+ // token (e.g. not logged in), preserving the prior behavior gracefully.+ const accessToken = await this.remoteServerConfigCtr.getAccessToken();+ const jwt = accessToken || request.jwt;+// Fire-and-forget: lh hetero exec handles spawn -> adapt ->// BatchIngester -> heteroIngest/heteroFinish -> server -> Gateway -> clients.// Same command as spawnHeteroSandbox() on the server side.@@ -300,7 +314,7 @@ export default class GatewayConnectionCtr extends ControllerModule {args: request.args,cwd: request.cwd,imageList: request.imageList,- jwt: request.jwt,+ jwt,operationId: request.operationId,prompt: request.prompt,resumeSessionId: request.resumeSessionId,diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 1c9ea046827..e49daf19362 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -887,7 +887,9 @@ describe('GatewayConnectionCtr', () => {expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(expect.objectContaining({agentType: 'openclaw',- jwt: 'mock-jwt',+ // Reuses the device's own session token as the run identity, not the+ // dispatched operation jwt.+ jwt: 'mock-access-token',operationId: 'op-xyz',prompt: 'hello',serverUrl: 'https://server.example.com',@@ -896,6 +898,34 @@ describe('GatewayConnectionCtr', () => {);});+ it('reuses the device access token as the run jwt instead of request.jwt', async () => {+ const client = await connectAndOpen();+ client.simulateAgentRunRequest('claude-code', 'op-auth', 'hi', 'dispatched-operation-jwt');+ await vi.advanceTimersByTimeAsync(0);++ expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(+ expect.objectContaining({ jwt: 'mock-access-token' }),+ );+ });++ it('falls back to request.jwt when the device has no access token', async () => {+ const client = await connectAndOpen();+ // Set after connect so the auto-connect getAccessToken call isn't the one+ // that returns null β only the executeAgentRun lookup should see no token.+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);+ client.simulateAgentRunRequest(+ 'claude-code',+ 'op-fallback',+ 'hi',+ 'dispatched-operation-jwt',+ );+ await vi.advanceTimersByTimeAsync(0);++ expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(+ expect.objectContaining({ jwt: 'dispatched-operation-jwt' }),+ );+ });+it('sends rejected ack when remote server URL is not configured', async () => {vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValueOnce('');diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex 6e12bb4042e..cfac3810b99 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -433,4 +433,58 @@ describe('AI Agent Router Integration Tests', () => {expect(assistantMessages[0].parentId).toBe(userMsg.id);});});++ describe('heteroIngest/heteroFinish ownership guard', () => {+ // Build a context that drives heteroOperationAuth to the desired kind:+ // - omit `purpose` β a normal user OIDC token β kind 'user' (ownership-gated)+ // - `purpose: 'hetero-operation'` β the server-minted token β kind 'operation'+ const heteroCtx = (opts: { purpose?: string; sub?: string } = {}) => {+ const sub = opts.sub ?? userId;+ return {+ jwtPayload: { userId: sub },+ oidcAuth: { sub, ...(opts.purpose ? { purpose: opts.purpose } : {}) },+ userId: sub,+ };+ };++ // A schema-valid event so the request passes input validation and reaches+ // the ownership guard (the guard throws before any event is processed).+ const sampleEvent = {+ data: {},+ operationId: 'op-x',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk' as const,+ };++ it('rejects an owner token targeting a topic it does not own', async () => {+ const caller = aiAgentRouter.createCaller(heteroCtx() as any);++ await expect(+ caller.heteroIngest({+ agentType: 'claude-code',+ events: [sampleEvent],+ operationId: 'op-x',+ topicId: 'topic-not-owned',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('rejects an owner token on heteroFinish for a topic it does not own', async () => {+ const caller = aiAgentRouter.createCaller(heteroCtx() as any);++ await expect(+ caller.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-x',+ result: 'success',+ topicId: 'topic-not-owned',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ // The operation-token path (kind 'operation', whose sub may be a workspaceId+ // that never matches topics.userId) is intentionally exempt from this guard;+ // that kind assignment is covered by heteroOperationAuth.test.ts.+ });});diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 3662541321f..312a00003b0 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1213,6 +1213,19 @@ export const aiAgentRouter = router({.from(topics).where(and(eq(topics.id, topicId), eq(topics.userId, ctx.userId))).limit(1);++ // Owner-token callers (a logged-in desktop reusing its own session) must+ // prove they own the target topic β `topicRow` is already filtered by+ // `userId`, so a missing row means the topic isn't theirs. The+ // operation-token path is exempt: its `sub` may be a workspaceId that+ // never matches `topics.userId`, and it's trusted as server-minted.+ if (ctx.heteroAuthKind === 'user' && !topicRow) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Topic not found or not owned by the caller',+ });+ }+const wsId = topicRow?.workspaceId ?? undefined;const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,@@ -1230,6 +1243,9 @@ export const aiAgentRouter = router({});return { ack: true as const };} catch (error: any) {+ // Preserve deliberate auth errors (e.g. the ownership FORBIDDEN) instead+ // of masking them as a generic 500.+ if (error instanceof TRPCError) throw error;log('heteroIngest failed: %s', error?.message);throw new TRPCError({cause: error,@@ -1258,6 +1274,15 @@ export const aiAgentRouter = router({.from(topics).where(and(eq(topics.id, topicId), eq(topics.userId, ctx.userId))).limit(1);++ // See heteroIngest: owner tokens must own the topic; operation tokens are exempt.+ if (ctx.heteroAuthKind === 'user' && !topicRow) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Topic not found or not owned by the caller',+ });+ }+const wsId = topicRow?.workspaceId ?? undefined;const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,@@ -1279,6 +1304,9 @@ export const aiAgentRouter = router({return { ack: true as const };} catch (err: any) {+ // Preserve deliberate auth errors (e.g. the ownership FORBIDDEN) instead+ // of masking them as a generic 500.+ if (err instanceof TRPCError) throw err;log('heteroFinish failed: %s', err?.message);throw new TRPCError({cause: err,diff --git a/packages/trpc/src/lambda/middleware/__tests__/heteroOperationAuth.test.ts b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationAuth.test.tsindex 4f577591287..e1c065c996e 100644--- a/packages/trpc/src/lambda/middleware/__tests__/heteroOperationAuth.test.ts+++ b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationAuth.test.ts@@ -1,4 +1,3 @@-import { TRPCError } from '@trpc/server';import { describe, expect, it } from 'vitest';import { createCallerFactory } from '@/libs/trpc/lambda';@@ -8,45 +7,55 @@ import { heteroOperationAuth } from '../heteroOperationAuth';// Minimal router that exercises heteroOperationAuthconst testRouter = trpc.router({- ping: trpc.procedure.use(heteroOperationAuth).query(({ ctx }) => ctx.userId),+ ping: trpc.procedure+ .use(heteroOperationAuth)+ .query(({ ctx }) => ({ kind: (ctx as any).heteroAuthKind, userId: ctx.userId })),});const createCaller = createCallerFactory(testRouter);describe('heteroOperationAuth middleware', () => {- it('passes through and exposes userId when purpose is hetero-operation', async () => {+ it('accepts a hetero-operation token as kind "operation"', async () => {const caller = createCaller({oidcAuth: { purpose: 'hetero-operation', sub: 'user-abc' },} as any);const result = await caller.ping();- expect(result).toBe('user-abc');+ expect(result).toEqual({ kind: 'operation', userId: 'user-abc' });});- it('rejects when oidcAuth is absent', async () => {- const caller = createCaller({} as any);+ it('accepts a normal user OIDC token (no purpose) as kind "user"', async () => {+ const caller = createCaller({+ oidcAuth: { sub: 'user-abc' },+ } as any);++ const result = await caller.ping();- await expect(caller.ping()).rejects.toMatchObject({- code: 'UNAUTHORIZED',- });+ expect(result).toEqual({ kind: 'user', userId: 'user-abc' });});- it('rejects a cli-sandbox token (wrong purpose)', async () => {+ it('accepts a cli-sandbox token as kind "user"', async () => {const caller = createCaller({oidcAuth: { purpose: 'cli-sandbox', sub: 'user-abc' },} as any);- await expect(caller.ping()).rejects.toMatchObject({- code: 'UNAUTHORIZED',- });+ const result = await caller.ping();++ expect(result).toEqual({ kind: 'user', userId: 'user-abc' });});- it('rejects when purpose is undefined', async () => {+ it('rejects when oidcAuth is absent', async () => {+ const caller = createCaller({} as any);++ await expect(caller.ping()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+ });++ it('rejects when oidcAuth has no sub', async () => {const caller = createCaller({- oidcAuth: { sub: 'user-abc' },+ oidcAuth: { purpose: 'hetero-operation' },} as any);- await expect(caller.ping()).rejects.toThrow(TRPCError);+ await expect(caller.ping()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });});});diff --git a/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts b/packages/trpc/src/lambda/middleware/heteroOperationAuth.tsindex 103d5272eb1..44e8e56a393 100644--- a/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts+++ b/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts@@ -3,23 +3,38 @@ import { TRPCError } from '@trpc/server';import { trpc } from '../init';/**- * Auth middleware for hetero-agent ingest/finish endpoints.- * Accepts ONLY tokens signed with `purpose: 'hetero-operation'` (4h expiry).- * All other tokens β including normal user OIDC tokens β are rejected,- * so this procedure cannot be called from the browser or CLI without the- * dedicated operation JWT issued by execAgent.+ * Auth middleware for hetero-agent ingest/finish endpoints. Accepts two callers:+ *+ * - A `hetero-operation` token (4h expiry) β the narrow, server-minted JWT+ * issued by execAgent for the cloud sandbox / workspace device. Its `sub` may+ * be a userId or, for workspace runs, a workspaceId. Behaves exactly as before.+ * - A normal user OIDC token β a logged-in desktop reusing its own session for a+ * remote run dispatched to it, so the spawned `lh hetero exec` can stream+ * results back without a server round-trip to mint a dedicated token.+ *+ * The owner-token path is safe because heteroIngest / heteroFinish additionally+ * gate every write on `topics.userId === ctx.userId` (see the `heteroAuthKind`+ * ownership check in the handlers), so an owner token can only touch its own+ * running operation β it cannot reach another user's topic.+ *+ * `heteroAuthKind` is forwarded so handlers can apply the strict ownership guard+ * to owner tokens only, while leaving the operation-token path (whose `sub` may+ * be a workspaceId that never matches `topics.userId`) untouched.*/export const heteroOperationAuth = trpc.middleware(async (opts) => {const { ctx, next } = opts;- if (!ctx.oidcAuth || ctx.oidcAuth.purpose !== 'hetero-operation') {+ const sub = ctx.oidcAuth?.sub as string | undefined;+ if (!ctx.oidcAuth || !sub) {throw new TRPCError({code: 'UNAUTHORIZED',- message: 'This endpoint requires a hetero-operation token',+ message: 'This endpoint requires an authenticated token',});}+ const heteroAuthKind = ctx.oidcAuth.purpose === 'hetero-operation' ? 'operation' : 'user';+return next({- ctx: { oidcAuth: ctx.oidcAuth, userId: ctx.oidcAuth.sub as string },+ ctx: { heteroAuthKind, oidcAuth: ctx.oidcAuth, userId: sub },});});