π€― 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
π fix(heterogeneous-agent): scope workspace hetero ingest and settle abandoned topics (#18461)
AmAzing-64fcda8fb44e
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 778cc88153a..a6b19a15f61 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -445,7 +445,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// Request handlers (system info / tool calls / device RPCs / agent runs) β// shared with the workspace-share connections opened via `enrollWorkspace`.- bindGatewayClientHandlers(client, handlerContext);+ bindGatewayClientHandlers(client, handlerContext, workspaceId);client.on('connected', () => {updateStatus('connected');@@ -504,7 +504,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {workspaceId: wsId,});- bindGatewayClientHandlers(wsClient, handlerContext);+ bindGatewayClientHandlers(wsClient, handlerContext, wsId);const entry: WorkspaceShareConnection = { cancelRefresh: null, client: wsClient };@@ -814,7 +814,11 @@ interface GatewayHandlerContext {* the `enrollWorkspace` RPC β so a workspace principal exposes exactly the same* tool / RPC / agent-run surface as the personal one.*/-function bindGatewayClientHandlers(client: GatewayClient, ctx: GatewayHandlerContext) {+function bindGatewayClientHandlers(+ client: GatewayClient,+ ctx: GatewayHandlerContext,+ connectionWorkspaceId?: string,+) {const { deps, error, getServerUrl, info, isDaemonChild } = ctx;// Handle system info requests@@ -903,6 +907,7 @@ function bindGatewayClientHandlers(client: GatewayClient, ctx: GatewayHandlerConserverUrl: getServerUrl(),systemContext: request.systemContext,topicId: request.topicId,+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,},{ error, info },);diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex 38da0f98412..f81147d0f9a 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -73,6 +73,7 @@ describe('spawnHeteroAgentRun', () => {LOBEHUB_SERVER: 'https://app.lobehub.com',}),});+ expect(opts.env).not.toHaveProperty('LOBEHUB_WORKSPACE_ID');// stdin is only written after the child actually spawns.expect(child.stdin.write).not.toHaveBeenCalled();@@ -94,6 +95,25 @@ describe('spawnHeteroAgentRun', () => {expect(child.stdin.write).not.toHaveBeenCalled();});+ it('forwards the topic workspace as LOBEHUB_WORKSPACE_ID for ingest', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ workspaceId: 'ws-lobehub',+ });+ child.emit('spawn');+ await ackPromise;++ const [, , opts] = spawnMock.mock.calls[0];+ expect(opts.env).toEqual(+ expect.objectContaining({+ LOBEHUB_WORKSPACE_ID: 'ws-lobehub',+ }),+ );+ });+it('appends --resume when resuming a session', () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 4b5c0bdf6e9..2476e364187 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -22,6 +22,8 @@ export interface SpawnHeteroAgentRunParams {serverUrl: string;systemContext?: string;topicId: string;+ /** Topic/run workspace β forwarded as `LOBEHUB_WORKSPACE_ID` for ingest. */+ workspaceId?: string;}export interface AgentRunAckResult {@@ -69,6 +71,7 @@ export function spawnHeteroAgentRun(serverUrl,systemContext,topicId,+ workspaceId,} = params;const workDir = cwd ?? process.cwd();@@ -120,6 +123,7 @@ export function spawnHeteroAgentRun(...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),LOBEHUB_JWT: jwt,LOBEHUB_SERVER: serverUrl,+ ...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),},stdio: ['pipe', 'inherit', 'inherit'],});diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 4f2ffbae0c5..eedd6b5bed1 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -289,6 +289,7 @@ export default class GatewayConnectionCtr extends ControllerModule {serverUrl,systemContext: request.systemContext,topicId: request.topicId,+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId,});} catch (err) {const reason = err instanceof Error ? err.message : String(err);diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 83008a12e95..1243eb83b1f 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -2447,6 +2447,8 @@ export default class HeterogeneousAgentCtr {serverUrl: string;systemContext?: string;topicId: string;+ /** Topic/run workspace β forwarded as `LOBEHUB_WORKSPACE_ID` for ingest. */+ workspaceId?: string;}): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {const {agentType,@@ -2462,6 +2464,7 @@ export default class HeterogeneousAgentCtr {serverUrl,systemContext,topicId,+ workspaceId,} = params;const workDir = cwd ?? process.cwd();@@ -2514,6 +2517,10 @@ export default class HeterogeneousAgentCtr {LOBEHUB_JWT: jwt,...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),LOBEHUB_SERVER: serverUrl,+ // Same reason `runHeteroTask` injects this for notify: without it the+ // CLI's heteroIngest/heteroFinish fall back to personal scope and the+ // workspace topic 404s (empty assistant, topic stuck `running`).+ ...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),};logger.info('spawnLhHeteroExec: type=%s op=%s topic=%s', agentType, operationId, topicId);diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex e1a0c5c9b19..a5c666d99a3 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -902,6 +902,18 @@ describe('GatewayConnectionCtr', () => {);});+ it('forwards ingestWorkspaceId to spawnLhHeteroExec as workspaceId', async () => {+ const client = await connectAndOpen();+ client.simulateAgentRunRequest('grok-build', 'op-ws', 'hi', 'mock-jwt', {+ ingestWorkspaceId: 'ws-lobehub',+ });+ await vi.advanceTimersByTimeAsync(0);++ expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(+ expect.objectContaining({ workspaceId: 'ws-lobehub' }),+ );+ });+it('sends accepted ack and spawns lh hetero exec', async () => {const client = await connectAndOpen();client.simulateAgentRunRequest('openclaw', 'op-xyz');diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 0a489d171e7..418d257bf89 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -2557,6 +2557,7 @@ describe('HeterogeneousAgentCtr', () => {LOBEHUB_SERVER: 'https://server.example.com',}),);+ expect(spawnCall.options.env).not.toHaveProperty('LOBEHUB_WORKSPACE_ID');expect(proc.stdin.write).not.toHaveBeenCalled();proc.emit('spawn');@@ -2566,6 +2567,23 @@ describe('HeterogeneousAgentCtr', () => {expect(proc.stdin.end).toHaveBeenCalledOnce();});+ it('forwards the topic workspace as LOBEHUB_WORKSPACE_ID for ingest', async () => {+ const proc = createGatewayCliProc();+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec({ ...params, workspaceId: 'ws-lobehub' });+ proc.emit('spawn');+ await expect(ack).resolves.toEqual({ status: 'accepted' });++ expect(spawnCalls[0].options.env).toEqual(+ expect.objectContaining({ LOBEHUB_WORKSPACE_ID: 'ws-lobehub' }),+ );+ });+it('encodes primary and resume fallback contexts for the embedded CLI', async () => {const proc = createGatewayCliProc();nextFakeProc = proc;diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 8a3b0e9692f..dcc2d201d94 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -427,7 +427,7 @@ export default class GatewayConnectionService extends ServiceModule {});client.on('agent_run_request', (request) => {- this.handleAgentRunRequest(client, request);+ this.handleAgentRunRequest(client, request, scope?.workspaceId);});client.on('auth_expired', () => {@@ -722,6 +722,7 @@ export default class GatewayConnectionService extends ServiceModule {private handleAgentRunRequest = async (client: GatewayClient,request: AgentRunRequestMessage,+ connectionWorkspaceId?: string,) => {logger.info(`Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,@@ -737,7 +738,14 @@ export default class GatewayConnectionService extends ServiceModule {return;}- const result = await this.agentRunHandler(request);+ // Topic scope for heteroIngest/heteroFinish. Prefer the explicit ingest+ // field, then a forwarded routing workspaceId, then the connection this+ // request arrived on (workspace enrollments). Older gateways omit both+ // payload fields; the workspace socket is still a reliable fallback.+ const workspaceId = request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId;+ const result = await this.agentRunHandler(+ workspaceId && workspaceId !== request.workspaceId ? { ...request, workspaceId } : request,+ );client.sendAgentRunAck({ operationId: request.operationId, ...result });};diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.tsindex 8a36536fd6e..fa4b001ceff 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts@@ -1,7 +1,9 @@// @vitest-environment nodeimport type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { type LobeChatDatabase } from '@lobechat/database';+import { topics, workspaceMembers, workspaces } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { aiAgentRouter } from '../aiAgent';@@ -50,6 +52,10 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {serverDB = await getTestDB();testDB = serverDB;userId = await createTestUser(serverDB);+ await serverDB.insert(topics).values([+ { id: 'topic-1', title: 'Personal topic 1', userId },+ { id: 'topic-2', title: 'Personal topic 2', userId },+ ]);mockHeteroIngest.mockReset();mockHeteroFinish.mockReset();mockHeteroIngest.mockResolvedValue(undefined);@@ -61,12 +67,20 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {vi.clearAllMocks();});- const createCaller = () =>- aiAgentRouter.createCaller({- jwtPayload: { userId },- oidcAuth: { purpose: 'hetero-operation', sub: userId },- userId,+ const createCaller = (+ params: { authKind?: 'operation' | 'user'; authUserId?: string; workspaceId?: string } = {},+ ) => {+ const authUserId = params.authUserId ?? userId;+ return aiAgentRouter.createCaller({+ jwtPayload: { userId: authUserId },+ oidcAuth: {+ ...(params.authKind === 'user' ? {} : { purpose: 'hetero-operation' }),+ sub: authUserId,+ },+ userId: authUserId,+ workspaceId: params.workspaceId,} as any);+ };describe('heteroIngest', () => {it('delegates the batch to HeterogeneousAgentService and acks', async () => {@@ -151,6 +165,95 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {}),).rejects.toThrow();});++ it("accepts a device user ingesting and finishing another member's workspace topic", async () => {+ const creatorId = await createTestUser(serverDB);+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({+ name: 'Hetero ingest workspace',+ primaryOwnerId: creatorId,+ slug: `hetero-ingest-${creatorId.slice(0, 8)}`,+ })+ .returning();++ try {+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: creatorId, workspaceId: workspace.id },+ { role: 'member', userId, workspaceId: workspace.id },+ ]);+ await serverDB.insert(topics).values({+ id: 'workspace-topic',+ title: 'Created by another member',+ userId: creatorId,+ workspaceId: workspace.id,+ });++ const caller = createCaller({ authKind: 'user' });+ const ingestResult = await caller.heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-workspace',+ topicId: 'workspace-topic',+ });+ const finishResult = await caller.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-workspace',+ result: 'success',+ topicId: 'workspace-topic',+ });++ expect(ingestResult).toEqual({ ack: true });+ expect(finishResult).toEqual({ ack: true });+ expect(mockHeteroIngest).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'workspace-topic' }),+ );+ expect(mockHeteroFinish).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'workspace-topic' }),+ );+ } finally {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspace.id));+ await cleanupTestUser(serverDB, creatorId);+ }+ });++ it('rejects a user who is not a member of the topic workspace', async () => {+ const creatorId = await createTestUser(serverDB);+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({+ name: 'Foreign hetero workspace',+ primaryOwnerId: creatorId,+ slug: `foreign-hetero-${creatorId.slice(0, 8)}`,+ })+ .returning();++ try {+ await serverDB.insert(workspaceMembers).values({+ role: 'owner',+ userId: creatorId,+ workspaceId: workspace.id,+ });+ await serverDB.insert(topics).values({+ id: 'foreign-workspace-topic',+ title: 'Foreign workspace topic',+ userId: creatorId,+ workspaceId: workspace.id,+ });++ await expect(+ createCaller().heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-foreign',+ topicId: 'foreign-workspace-topic',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ } finally {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspace.id));+ await cleanupTestUser(serverDB, creatorId);+ }+ });});describe('heteroFinish', () => {diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 321f029bdec..baf3417dd9c 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -13,7 +13,7 @@ import {} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';-import { and, eq } from 'drizzle-orm';+import { and, eq, isNull } from 'drizzle-orm';import pMap from 'p-map';import { z } from 'zod';@@ -23,7 +23,7 @@ import { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';-import { agentOperations, topics } from '@/database/schemas';+import { agentOperations, topics, workspaceMembers } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -43,6 +43,49 @@ import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent'const log = debug('lobe-server:ai-agent-router');+const resolveHeteroTopicWorkspace = async (params: {+ db: LobeChatDatabase;+ requestedWorkspaceId?: string | null;+ topicId: string;+ userId: string;+}) => {+ const { db, requestedWorkspaceId, topicId, userId } = params;+ const [topic] = await db+ .select({ userId: topics.userId, workspaceId: topics.workspaceId })+ .from(topics)+ .where(eq(topics.id, topicId))+ .limit(1);++ if (!topic || (requestedWorkspaceId != null && requestedWorkspaceId !== topic.workspaceId)) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Topic is outside the caller scope' });+ }++ if (!topic.workspaceId) {+ if (topic.userId !== userId) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Topic is outside the caller scope' });+ }+ return undefined;+ }++ const [membership] = await db+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, topic.workspaceId),+ eq(workspaceMembers.userId, userId),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ .limit(1);++ if (!membership) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Topic is outside the caller scope' });+ }++ return topic.workspaceId;+};+/*** Workspace `use` guard for operation-keyed endpoints: resolve the operation* row to its agent and run the same `use` guard. Operations without an agent@@ -704,9 +747,9 @@ const aiAgentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)// Requires a `hetero-operation` JWT (4h expiry) β normal user tokens are rejected,// so only the sandbox/device that received the JWT from execAgent can call these.//-// Note: workspaceId is not on `ctx` for this procedure (the JWT is server-to-server-// and carries no workspace claim). Handlers must resolve wsId from the row keyed-// by `topicId` and construct `HeterogeneousAgentService` per request.+// The workspace header is optional because older gateways may not forward it.+// Handlers resolve the authoritative scope from `topicId`, then verify the token+// subject owns the personal topic or is an active member of its workspace.const heteroAgentProcedure = heteroAuthedProcedure.use(serverDatabase);const aiAgentWriteProcedure = aiAgentProcedure.use(withScopedPermission('message:create'));@@ -1692,30 +1735,12 @@ export const aiAgentRouter = router({);try {- // Resolve workspaceId from the topic row so persistence writes land in- // the correct workspace scope. heteroAuthedProcedure carries no- // workspace claim, so we must look it up here per request. We bypass- // `TopicModel.findById` because it filters by workspace; here we need a- // workspace-agnostic lookup keyed only by topicId + userId.- const [topicRow] = await ctx.serverDB- .select({ workspaceId: topics.workspaceId })- .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 wsId = await resolveHeteroTopicWorkspace({+ db: ctx.serverDB,+ requestedWorkspaceId: ctx.workspaceId,+ topicId,+ userId: ctx.userId,+ });const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,});@@ -1756,23 +1781,12 @@ export const aiAgentRouter = router({log('heteroFinish: topic=%s op=%s type=%s result=%s', topicId, operationId, agentType, result);try {- // Resolve workspaceId from the topic row (heteroAuthedProcedure has no- // workspace claim) so persistence writes land in the correct scope.- const [topicRow] = await ctx.serverDB- .select({ workspaceId: topics.workspaceId })- .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 wsId = await resolveHeteroTopicWorkspace({+ db: ctx.serverDB,+ requestedWorkspaceId: ctx.workspaceId,+ topicId,+ userId: ctx.userId,+ });const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,});diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex 857c7ff595a..ed8505b14cd 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -164,12 +164,7 @@ export class AbandonOperationService {if (metadata.topicId) {try {const topicModel = new TopicModel(this.db, metadata.userId, metadata.workspaceId);- const topic = await topicModel.findById(metadata.topicId);- const running = topic?.metadata?.runningOperation as- { assistantMessageId?: string; operationId?: string } | undefined;- if (running?.operationId === operationId) {- await topicModel.updateMetadata(metadata.topicId, { runningOperation: null });- }+ await topicModel.settleRunningOperation(metadata.topicId, operationId);} catch (e) {log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);}@@ -327,16 +322,9 @@ export class AbandonOperationService {if (op.topicId) {try {topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined);- const topic = await topicModel.findById(op.topicId);- const running = topic?.metadata?.runningOperation as- { assistantMessageId?: string; operationId?: string } | undefined;-- if (running?.operationId && running.operationId !== operationId) return undefined;-- if (running?.operationId === operationId) {- await topicModel.updateMetadata(op.topicId, { runningOperation: null }).catch(() => {});- if (running.assistantMessageId) return running.assistantMessageId;- }+ const settled = await topicModel.settleRunningOperation(op.topicId, operationId);+ if (settled.status !== 'settled') return undefined;+ if (settled.assistantMessageId) return settled.assistantMessageId;} catch (e) {log('[%s] no-state abandon: topic lookup failed (non-fatal): %O', operationId, e);}diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 3a4addf8272..b4c01772859 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -51,12 +51,12 @@ vi.mock('@/database/models/thread', () => ({ThreadModel: vi.fn().mockImplementation(() => ({ findById: findThreadMock })),}));-const topicFindByIdMock = vi.fn().mockResolvedValue(null);-const topicUpdateMetadataMock = vi.fn().mockResolvedValue(undefined);+const topicSettleRunningOperationMock = vi+ .fn()+ .mockResolvedValue({ assistantMessageId: undefined, status: 'missing' });vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({- findById: topicFindByIdMock,- updateMetadata: topicUpdateMetadataMock,+ settleRunningOperation: topicSettleRunningOperationMock,})),}));@@ -93,8 +93,9 @@ describe('AbandonOperationService', () => {findOperationMock.mockReset().mockResolvedValue(null);recordCompletionMock.mockClear();findThreadMock.mockReset().mockResolvedValue(null);- topicFindByIdMock.mockReset().mockResolvedValue(null);- topicUpdateMetadataMock.mockReset().mockResolvedValue(undefined);+ topicSettleRunningOperationMock+ .mockReset()+ .mockResolvedValue({ assistantMessageId: undefined, status: 'missing' });});it('returns found:false when coordinator has no state', async () => {@@ -131,13 +132,9 @@ describe('AbandonOperationService', () => {workspaceId: 'ws_x',},});- topicFindByIdMock.mockResolvedValue({- metadata: {- runningOperation: {- assistantMessageId: 'msg_assist_1',- operationId: 'op_x',- },- },+ topicSettleRunningOperationMock.mockResolvedValue({+ assistantMessageId: 'msg_assist_1',+ status: 'settled',});const svc = new AbandonOperationService(db, {@@ -162,7 +159,7 @@ describe('AbandonOperationService', () => {toolCalls: 0,}),);- expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_x');expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {content: '',error: expect.objectContaining({@@ -210,15 +207,6 @@ describe('AbandonOperationService', () => {userId: 'user_x',},});- topicFindByIdMock.mockResolvedValue({- metadata: {- runningOperation: {- assistantMessageId: 'msg_new_placeholder',- operationId: 'op_new',- },- },- });-const svc = new AbandonOperationService(db, {coordinator: coord as any,snapshotStore: store as any,@@ -228,7 +216,34 @@ describe('AbandonOperationService', () => {expect(result.abandoned).toBe(true);expect(recordCompletionMock).toHaveBeenCalled();- expect(topicUpdateMetadataMock).not.toHaveBeenCalled();+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_old');+ expect(messageUpdateMock).not.toHaveBeenCalled();+ });++ it('does not settle a running topic when operation ownership is no longer provable', async () => {+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });+ const store = buildStore();+ const db = buildDb({+ assistantRow: { id: 'msg_assist_1' },+ operationRow: {+ agentId: 'agt_x',+ id: 'op_x',+ provider: 'grok-build',+ startedAt: new Date('2026-08-18T08:51:32.466Z'),+ status: 'running',+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: 'ws_x',+ },+ });+ const svc = new AbandonOperationService(db, {+ coordinator: coord as any,+ snapshotStore: store as any,+ });++ await svc.finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_x');expect(messageUpdateMock).not.toHaveBeenCalled();});@@ -246,15 +261,6 @@ describe('AbandonOperationService', () => {{ stepIndex: 1, stepType: 'call_tool' },],});- topicFindByIdMock.mockResolvedValue({- metadata: {- runningOperation: {- assistantMessageId: 'msg_assist_1',- operationId: 'op_x',- },- },- });-const svc = new AbandonOperationService({} as any, {coordinator: coord as any,snapshotStore: store as any,@@ -289,7 +295,7 @@ describe('AbandonOperationService', () => {type: 'AgentRuntimeError',}),});- expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_x');expect(dispatchHooksMock).toHaveBeenCalledWith('op_x',expect.objectContaining({@@ -315,15 +321,6 @@ describe('AbandonOperationService', () => {});const store = buildStore();store.loadPartial.mockResolvedValue(null);- topicFindByIdMock.mockResolvedValue({- metadata: {- runningOperation: {- assistantMessageId: 'msg_assist_1',- operationId: 'op_x',- },- },- });-const svc = new AbandonOperationService({} as any, {coordinator: coord as any,snapshotStore: store as any,@@ -332,7 +329,7 @@ describe('AbandonOperationService', () => {const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');expect(result.found).toBe(true);- expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_x');expect(dispatchHooksMock).not.toHaveBeenCalled();},);diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex edc379fc9d7..5633808e4c2 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -1035,6 +1035,40 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>);});+ it('forwards the topic workspace as ingestWorkspaceId on device hetero dispatch', async () => {+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-a' });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'do the task on my device',+ } as any);++ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ ingestWorkspaceId: 'workspace-a' }),+ );+ });++ it('forwards the topic workspace into the cloud sandbox hetero spawn', async () => {+ heteroAgentConfig.agencyConfig = {+ heterogeneousProvider: { type: 'claude-code' },+ } as any;+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-a' });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'do the task in the cloud sandbox',+ } as any);++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({ workspaceId: 'workspace-a' }),+ );+ });+it('keeps the conversation workspace separate from a personal platform device scope', async () => {heteroAgentConfig.agencyConfig = {executionTarget: 'local',diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex bb492b891e8..80b97842742 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -2759,6 +2759,10 @@ export class AiAgentService {// Route to the workspace pool when this is a workspace device; the// operation JWT stays member-scoped (the run belongs to the member).workspaceId: dispatchWorkspaceId,+ // Topic scope for device-side heteroIngest/heteroFinish. Distinct+ // from the routing workspace above: a workspace topic on a personal+ // device still has to write back under `this.workspaceId`.+ ingestWorkspaceId: this.workspaceId,});if (!result.success) {log('execAgent: hetero device dispatch failed: %s', result.error);@@ -2837,6 +2841,7 @@ export class AiAgentService {args: heteroExecArgs,jwt: sandboxJwt,marketService,+ workspaceId: this.workspaceId,}).catch(async (err) => {// Fire-and-forget: execAgent has already returned `autoStarted`, and// the sandbox never reached the point of calling heteroFinish. Drivediff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 633ea154815..94f124864b2 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1289,6 +1289,8 @@ export class DeviceGateway {topicId: string;userId: string;workspaceId?: string;+ /** Topic/run workspace forwarded to the device for hetero ingest. */+ ingestWorkspaceId?: string;}): Promise<{ error?: string; success: boolean }> {const client = this.getClient();if (!client) return { error: 'GATEWAY_NOT_CONFIGURED', success: false };diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex f62e9afd5c5..1eb4503468b 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -466,6 +466,39 @@ describe('HeterogeneousAgentService', () => {});});+ it('ignores a delayed finish when a newer operation owns the topic', async () => {+ const { manager, published } = createFakeStreamManager();+ const persistenceHandler = createFakePersistenceHandler();+ const topicModel = {+ settleRunningOperation: vi.fn(async () => ({+ activeOperationId: 'op-new',+ status: 'conflict' as const,+ })),+ } as any;+ const completeOperationSpy = vi+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')+ .mockResolvedValue();+ const service = new HeterogeneousAgentService({} as any, 'user-test', {+ persistenceHandler,+ snapshotStore: null,+ streamEventManager: manager,+ topicModel,+ });++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-old',+ result: 'success',+ topicId: 'topic-1',+ });++ expect(topicModel.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-old');+ expect(published).toHaveLength(0);+ expect(completeOperationSpy).not.toHaveBeenCalled();++ completeOperationSpy.mockRestore();+ });+// The unified terminal funnel: heteroFinish must drive the run's lifecycle// hooks through the shared hookDispatcher (the same mechanism the normal LLM// path uses), which is what marks the owning task done/failed and fires any@@ -695,11 +728,12 @@ describe('HeterogeneousAgentService', () => {const topicModel = {// Mirror what execAgent persisted at dispatch: the serialized hooks live// under runningOperation. heteroFinish must read them from here.- findById: vi.fn(async () => ({- id: 'topic-q',- metadata: { runningOperation: { hooks, operationId: 'op-q' } },+ settleRunningOperation: vi.fn(async () => ({+ assistantMessageId: undefined,+ hooks,+ status: 'settled' as const,+ threadId: undefined,})),- updateMetadata: vi.fn(async () => {}),} as any;const { manager } = createFakeStreamManager();const service = new HeterogeneousAgentService({} as any, 'user-test', {@@ -788,13 +822,41 @@ describe('HeterogeneousAgentService', () => {},};- // Shared topic store whose updateMetadata mirrors TopicModel.updateMetadata:- // a non-atomic read-modify-write that shallow-merges the patch over a- // snapshot. `mergeBase` lets a test force the "read a stale snapshot" race.+ // Shared topic store whose updateMetadata mirrors TopicModel.updateMetadata.+ // `mergeBase` lets a test force the historical stale-snapshot race, while+ // settleRunningOperation models the operation-owned terminal CAS.const makeStore = () => {let meta: Record<string, any> = {};const topicModel = {- findById: vi.fn(async () => ({ id: TOPIC, metadata: meta })),+ settleRunningOperation: vi.fn(async (_id: string, operationId: string) => {+ const runningOperation = meta.runningOperation;+ if (!runningOperation) {+ const currentMessage = meta.heteroCurrentMsgId;+ return {+ assistantMessageId:+ currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,+ status: 'missing' as const,+ };+ }+ if (runningOperation.operationId !== operationId) {+ return {+ activeOperationId: runningOperation.operationId,+ status: 'conflict' as const,+ };+ }++ const currentMessage = meta.heteroCurrentMsgId;+ meta = { ...meta, runningOperation: null };+ return {+ assistantMessageId:+ currentMessage?.operationId === operationId+ ? currentMessage.msgId+ : runningOperation.assistantMessageId,+ hooks: runningOperation.hooks,+ status: 'settled' as const,+ threadId: runningOperation.threadId,+ };+ }),updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>, mergeBase?: any) => {meta = { ...(mergeBase ?? meta), ...patch };}),diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsindex 63927975304..34656f40f44 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -61,4 +61,21 @@ describe('spawnHeteroSandbox', () => {expect(command).toContain("'hi'\\''there'");expect(command).not.toContain('"$(touch /tmp/pwned)"');});++ it('injects LOBEHUB_WORKSPACE_ID when the topic belongs to a workspace', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ workspaceId: 'ws-lobehub',+ });++ const command = mockCallTool.mock.calls[0][1].command;+ expect(command).toContain("LOBEHUB_WORKSPACE_ID='ws-lobehub'");+ });});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 1c161063453..e3509b805b2 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -282,22 +282,6 @@ export class HeterogeneousAgentService {topicId,});- // Always emit a terminal `agent_runtime_end` so renderer subscribers shut- // down even if the CLI stream missed it (process killed mid-flight,- // network drop on last batch). Idempotent on the renderer side: the- // gateway event handler latches `terminalState` on first end-event.- await this.streamEventManager.publishStreamEvent(operationId, {- data: {- agentType,- error,- operationId,- reason: result,- sessionId,- },- stepIndex: 0,- type: 'agent_runtime_end',- });-// Drive the run's lifecycle hooks (onComplete / onError) through the same// `hookDispatcher` the normal LLM runtime uses, so the task lifecycle// (onTopicComplete β task done/failed) and any IM bot completion callback@@ -312,35 +296,50 @@ export class HeterogeneousAgentService {// no-op for the task lifecycle anyway β onTopicComplete has no interrupted// branch β and suppresses a spurious bot "stopped" message before the real// result lands.)- if (result === 'cancelled') return;-let serializedHooks: SerializedHook[] | undefined;- let assistantMessageId: string | undefined;+ let assistantMessageId = seedAssistantMessageId;let isolationThreadId: string | undefined;- try {- const topic = await this.topicModel.findById(topicId);- serializedHooks = topic?.metadata?.runningOperation?.hooks as SerializedHook[] | undefined;- isolationThreadId = topic?.metadata?.runningOperation?.threadId ?? undefined;- // Prefer heteroCurrentMsgId β the persistence handler updates this pointer- // on every step boundary, so it refers to the LAST assistant message with- // the complete final content. Fall back to the initial placeholder id- // recorded in runningOperation if the pointer is absent or belongs to a- // different operation (shouldn't happen, but defensive).- const currentMsgRef = topic?.metadata?.heteroCurrentMsgId;- assistantMessageId =- currentMsgRef?.operationId === operationId- ? currentMsgRef.msgId- : topic?.metadata?.runningOperation?.assistantMessageId;- await this.topicModel.updateMetadata(topicId, { runningOperation: null });- // Settle `status: 'running'` for runs with no renderer attached (e.g. a- // cron-dispatched scheduled resume) β otherwise nothing ever moves the- // topic off `running`. Guarded in the model: an attached client's own- // terminal write ('active'/'unread') is never clobbered.- await this.topicModel.settleRunningStatus(topicId);- } catch (err) {- log('heteroFinish: failed to clear runningOperation (non-fatal): %O', err);+ if (result !== 'cancelled') {+ try {+ const settled = await this.topicModel.settleRunningOperation(topicId, operationId);+ if (settled.status === 'conflict') {+ log(+ 'heteroFinish: ignore stale finish topic=%s op=%s; current operation is %s',+ topicId,+ operationId,+ settled.activeOperationId,+ );+ return;+ }++ assistantMessageId = settled.assistantMessageId ?? assistantMessageId;+ if (settled.status === 'settled') {+ serializedHooks = settled.hooks as SerializedHook[] | undefined;+ isolationThreadId = settled.threadId;+ }+ } catch (err) {+ log('heteroFinish: failed to settle runningOperation (non-fatal): %O', err);+ }}+ // Emit a terminal `agent_runtime_end` so renderer subscribers shut down even+ // if the CLI stream missed it (process killed mid-flight, network drop on+ // last batch). A stale finish that conflicts with a newer operation returns+ // above instead of projecting the old terminal state into the active run.+ await this.streamEventManager.publishStreamEvent(operationId, {+ data: {+ agentType,+ error,+ operationId,+ reason: result,+ sessionId,+ },+ stepIndex: 0,+ type: 'agent_runtime_end',+ });++ if (result === 'cancelled') return;+// The owning agentId is authoritatively encoded in the operationId// (op_<ts>_agt_<id>_tpc_<id>_<suffix>, built at dispatch from the resolved// agent), so derive it from there. Reading it back off the final assistantdiff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex 71e537cd5ad..f2fd1369c5a 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -51,6 +51,8 @@ export interface SandboxRunParams {systemContext?: string;topicId: string;userId: string;+ /** Topic/run workspace β injected as `LOBEHUB_WORKSPACE_ID` for ingest. */+ workspaceId?: string;}/**@@ -145,6 +147,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidresumeSessionId,topicId,userId,+ workspaceId,} = params;// For cloud sandbox, default cwd is /workspace β must be explicit so CC stores and@@ -198,6 +201,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void`LOBEHUB_JWT=${shellQuote(jwt)}`,`LOBEHUB_SERVER=${shellQuote(serverUrl)}`,`LOBEHUB_ASSISTANT_MESSAGE_ID=${shellQuote(assistantMessageId)}`,+ ...(workspaceId ? [`LOBEHUB_WORKSPACE_ID=${shellQuote(workspaceId)}`] : []),// Inject GitHub token so CC can authenticate git operations and GitHub API// calls inside the sandbox (e.g. gh CLI, git push, API requests)....(githubToken ? [`GITHUB_TOKEN=${shellQuote(githubToken)}`] : []),diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 16d61baaf16..a27f897c3c2 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -567,6 +567,85 @@ describe('TopicModel', () => {});});+ describe('settleRunningOperation', () => {+ it('atomically clears and settles the matching operation', async () => {+ const hooks = [+ {+ id: 'hook-old',+ type: 'onComplete',+ webhook: { url: '/callback' },+ },+ ];+ const topic = await topicModel.create({+ metadata: {+ heteroCurrentMsgId: { msgId: 'msg-current', operationId: 'op-old' },+ runningOperation: {+ assistantMessageId: 'msg-old',+ hooks,+ operationId: 'op-old',+ threadId: 'thread-old',+ },+ },+ title: 'matching operation',+ });+ await topicModel.update(topic.id, { status: 'running' });++ const settled = await topicModel.settleRunningOperation(topic.id, 'op-old');++ expect(settled).toEqual({+ assistantMessageId: 'msg-current',+ hooks,+ status: 'settled',+ threadId: 'thread-old',+ });+ const row = await topicModel.findById(topic.id);+ expect(row?.metadata?.runningOperation).toBeNull();+ expect(row?.status).toBe('unread');+ });++ it('does not let an old watchdog settle a newer operation', async () => {+ const topic = await topicModel.create({+ metadata: {+ runningOperation: { assistantMessageId: 'msg-new', operationId: 'op-new' },+ },+ title: 'newer operation',+ });+ await topicModel.update(topic.id, { status: 'running' });++ const settled = await topicModel.settleRunningOperation(topic.id, 'op-old');++ expect(settled).toEqual({ activeOperationId: 'op-new', status: 'conflict' });+ const row = await topicModel.findById(topic.id);+ expect(row?.metadata?.runningOperation?.operationId).toBe('op-new');+ expect(row?.status).toBe('running');+ });++ it('does not settle an unmarked client-side run', async () => {+ const topic = await topicModel.create({ title: 'client operation' });+ await topicModel.update(topic.id, { status: 'running' });++ const settled = await topicModel.settleRunningOperation(topic.id, 'op-old');++ expect(settled).toEqual({ assistantMessageId: undefined, status: 'missing' });+ const row = await topicModel.findById(topic.id);+ expect(row?.status).toBe('running');+ });++ it('retains the operation-scoped assistant pointer after another terminal path cleared the marker', async () => {+ const topic = await topicModel.create({+ metadata: {+ heteroCurrentMsgId: { msgId: 'msg-current', operationId: 'op-old' },+ runningOperation: null,+ },+ title: 'already cleared operation',+ });++ const settled = await topicModel.settleRunningOperation(topic.id, 'op-old');++ expect(settled).toEqual({ assistantMessageId: 'msg-current', status: 'missing' });+ });+ });+describe('updateMetadata', () => {it('merges new metadata into existing metadata', async () => {const topic = await topicModel.create({diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 06a2e503213..a7c43f71673 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1297,6 +1297,66 @@ export class TopicModel {.returning({ id: topics.id, status: topics.status });};+ /**+ * Atomically clear and settle the operation that still owns a topic.+ * A row lock keeps a stale terminal callback from clearing a newer operation+ * between the ownership check and update. Missing markers are intentionally+ * not settled because a client-side run can set `status = 'running'` without+ * an operation marker, so there is no proof that the terminal callback owns it.+ *+ * The result distinguishes a missing marker from a conflicting operation:+ * some legitimate hetero callbacks arrive after another terminal path has+ * already cleared their marker, while a callback that observes a newer+ * operation must stop before dispatching lifecycle hooks for the wrong run.+ */+ settleRunningOperation = async (id: string, operationId: string) => {+ return this.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(and(eq(topics.id, id), this.ownership()))+ .for('update');++ const runningOperation = existing?.metadata?.runningOperation;+ if (!runningOperation) {+ const currentMessage = existing?.metadata?.heteroCurrentMsgId;+ return {+ assistantMessageId:+ currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,+ status: 'missing' as const,+ };+ }+ if (runningOperation.operationId !== operationId) {+ return { activeOperationId: runningOperation.operationId, status: 'conflict' as const };+ }++ const metadata = {+ ...existing.metadata,+ runningOperation: null,+ } as ChatTopicMetadata;++ await tx+ .update(topics)+ .set({+ metadata,+ ...(existing.status === 'running' ? { status: 'unread' as const } : {}),+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, id), this.ownership()));++ const currentMessage = existing.metadata?.heteroCurrentMsgId;+ return {+ assistantMessageId:+ currentMessage?.operationId === operationId+ ? currentMessage.msgId+ : runningOperation.assistantMessageId,+ hooks: runningOperation.hooks,+ status: 'settled' as const,+ threadId: runningOperation.threadId ?? undefined,+ };+ });+ };+/*** Move multiple topics (and all their messages) to another agent.*diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 07fd62a5ffe..8cea557c605 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -217,6 +217,13 @@ export class GatewayHttpClient {topicId: string;userId: string;workspaceId?: string;+ /**+ * Topic/run workspace for device-side ingest. Distinct from+ * {@link workspaceId}, which routes the request to a device pool. A+ * workspace topic dispatched to a personal device still needs this so+ * `lh hetero exec` can write back under the topic's scope.+ */+ ingestWorkspaceId?: string;}): Promise<{ success: boolean; error?: string }> {const res = await this.post('/api/device/agent/run', params);if (!res.ok) {diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 6afbe9eb865..8e96813d0e9 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -234,6 +234,12 @@ export interface AgentRunRequestMessage {* `sendPrompt(imageList)` path. Optional β omitted for older servers.*/imageList?: Array<{ id?: string; url: string }>;+ /**+ * Same meaning as {@link workspaceId}. The HTTP dispatch payload uses this+ * name so it is not confused with the device-pool routing `workspaceId`.+ * Naive gateways forward the POST body as-is; devices accept either field.+ */+ ingestWorkspaceId?: string;jwt: string;operationId: string;prompt: string;@@ -254,6 +260,14 @@ export interface AgentRunRequestMessage {systemContext?: string;topicId: string;type: 'agent_run_request';+ /**+ * Workspace that owns the topic. `lh hetero exec` must send this as+ * `X-Workspace-Id` on heteroIngest/heteroFinish; without it the write lands+ * in personal scope and the workspace topic stays `running` with an empty+ * assistant. Optional for older gateways β a workspace-enrolled connection+ * falls back to its own enrollment id.+ */+ workspaceId?: string;}/** Client β Server: acknowledgement for an agent_run_request. */diff --git a/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts b/packages/trpc/src/lambda/middleware/heteroOperationAuth.tsindex 44e8e56a393..c3f2cd307d2 100644--- a/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts+++ b/packages/trpc/src/lambda/middleware/heteroOperationAuth.ts@@ -12,14 +12,10 @@ import { trpc } from '../init';* 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.+ * The handlers resolve the target topic and require this subject to own its+ * personal scope or be an active member of its workspace before writing.+ * `heteroAuthKind` remains available to endpoints that need to distinguish the+ * narrow operation token from a full user session.*/export const heteroOperationAuth = trpc.middleware(async (opts) => {const { ctx, next } = opts;