π€― 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(task): let an explicit run device outrank the task's bound device (#21967)
Lobehub Coder678999175b7d
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 68f0a2c77f6..94d9b5ef3e3 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -2,7 +2,7 @@ import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills'import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';import { BriefIdentifier } from '@lobechat/builtin-tool-brief';import { INBOX_SESSION_ID } from '@lobechat/const';-import type { ExecAgentResult, TaskItem, TaskRunTrigger } from '@lobechat/types';+import type { ChatTopicMetadata, ExecAgentResult, TaskItem, TaskRunTrigger } from '@lobechat/types';import { getHeterogeneousTaskModelProvider, readTaskExecutionConfig } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -22,6 +22,7 @@ import { readTaskSkillIds } from '@/server/services/userSkill';import { buildTaskPrompt } from './buildTaskPrompt';import {+ isSameTopicExecution,resolveRunDeviceId,resolveTaskRunExecution,resolveTopicExecutionPatch,@@ -29,6 +30,15 @@ import {const log = debug('task-runner');+/** Concurrent writers are rare; a few re-reads settle them or fail the kickoff. */+const SYNC_TOPIC_EXECUTION_ATTEMPTS = 3;++/** A continued topic moved for one run only, and how to move it back. */+interface TopicRetarget {+ previous: ChatTopicMetadata;+ written: ChatTopicMetadata;+}+export interface RunTaskParams {/** Extra builtin tools this run mounts beside the Task skill, e.g. the Goal report tool. */additionalPluginIds?: string[];@@ -92,18 +102,53 @@ export class TaskRunnerService {* the previous machine's directory β failing the kickoff (and letting the* caller's error path restore the task's resting state) is better than* running somewhere the user did not pin.+ *+ * Returns the write and the topic's previous execution axes when a device+ * named for this run only took part in it: that retarget is not the task's+ * standing selection, so the caller restores it if the run never starts.+ * The write only lands while the topic still matches the snapshot it was+ * computed from, so `previous` is exactly what it replaced; a concurrent+ * change is re-read and the patch recomputed against it.*/private async syncTopicExecution(topicId: string,taskConfig: Record<string, unknown>,runDeviceId: string | undefined,- ): Promise<void> {- const topic = await this.topicModel.findById(topicId);- const patch = resolveTopicExecutionPatch(topic?.metadata, taskConfig, runDeviceId);- if (!patch) return;+ requestedDeviceId: string | undefined,+ ): Promise<TopicRetarget | undefined> {+ for (let attempt = 0; attempt < SYNC_TOPIC_EXECUTION_ATTEMPTS; attempt++) {+ const topic = await this.topicModel.findById(topicId);+ if (!topic) return;++ const patch = resolveTopicExecutionPatch(+ topic.metadata,+ taskConfig,+ runDeviceId,+ requestedDeviceId,+ );+ if (!patch) return;- await this.topicModel.updateMetadata(topicId, patch);- log('runTask: synced topic %s execution metadata', topicId);+ const updated = await this.topicModel.updateMetadata(topicId, patch, {+ onlyIf: (current) => isSameTopicExecution(current, topic.metadata),+ });+ if (updated.length === 0) continue;++ log('runTask: synced topic %s execution metadata', topicId);++ if (!requestedDeviceId) return;+ return {+ // `undefined` clears an axis on restore, same as in the patch itself.+ previous: {+ boundDeviceId: topic.metadata?.boundDeviceId,+ repos: topic.metadata?.repos,+ workingDirectory: topic.metadata?.workingDirectory,+ workingDirectoryConfig: topic.metadata?.workingDirectoryConfig,+ },+ written: patch,+ };+ }++ throw new Error(`Topic ${topicId} execution kept changing while this run was starting`);}async runTask(params: RunTaskParams): Promise<RunTaskResult> {@@ -136,6 +181,10 @@ export class TaskRunnerService {// otherwise an early failure (e.g. CONFLICT thrown because a concurrent// run is in flight) would clobber the in-flight run's status to 'paused'.let weSetRunning = false;+ // A continued topic retargeted for this run only, and what to put back if+ // the run is not accepted β see `syncTopicExecution`.+ let topicRetarget: TopicRetarget | undefined;+ let runAccepted = false;try {if (!task.assigneeAgentId) {@@ -295,16 +344,21 @@ export class TaskRunnerService {// the run keeps inheriting the assignee agent's target and cwd.const taskExecution = readTaskExecutionConfig(taskConfig);// The device the run will actually use. It differs from the task's pin- // when the author FIXED the agent's target, and that difference decides- // whether the directory may travel: see `resolveTaskRunExecution`.- const runDeviceId = taskExecution- ? resolveRunDeviceId(- taskExecution,- await this.agentModel.getAgentAgencyConfig(agentRef),- this.workspaceId,- )- : undefined;- const runExecution = resolveTaskRunExecution(taskExecution, runDeviceId);+ // when the caller names another device for this run (`--device`), or when+ // the author FIXED the agent's target, and that difference decides+ // whether the directory may travel: see `resolveTaskRunExecution`. A+ // requested device goes through the policy even when the task pins+ // nothing β a fixed target replaces it all the same.+ const runDeviceId =+ taskExecution || deviceId+ ? resolveRunDeviceId(+ taskExecution,+ await this.agentModel.getAgentAgencyConfig(agentRef),+ this.workspaceId,+ deviceId,+ )+ : undefined;+ const runExecution = resolveTaskRunExecution(taskExecution, runDeviceId, deviceId);// A continued topic keeps its own metadata (`turnSetup` stamps// `initialTopicMetadata` only for a topic it creates) and those stored@@ -312,7 +366,12 @@ export class TaskRunnerService {// be ignored, and the previous machine's kept. Stamp the task's selection// onto the topic first; see `resolveTopicExecutionPatch`.if (continueTopicId) {- await this.syncTopicExecution(continueTopicId, taskConfig, runDeviceId);+ topicRetarget = await this.syncTopicExecution(+ continueTopicId,+ taskConfig,+ runDeviceId,+ deviceId,+ );}log('runTask: %s (continue=%s)', taskIdentifier, continueTopicId);@@ -321,7 +380,6 @@ export class TaskRunnerService {...(onOperationCreated ? { onOperationCreated } : {}),...(isSlug ? { slug: agentRef } : { agentId: agentRef }),additionalPluginIds: pluginIds,- ...(deviceId && { deviceId }),...(typeof taskConfig.model === 'string' && { model: taskConfig.model }),...(typeof taskConfig.provider === 'string' && { provider: taskConfig.provider }),hooks: createTaskRunHooks({@@ -339,10 +397,10 @@ export class TaskRunnerService {title: extraPrompt ? extraPrompt.slice(0, 100) : task.name || task.identifier,trigger: TopicTrigger.RunTask,userInterventionConfig: { approvalMode: 'headless' },- // The task's own pin, when it has one. `deviceId` forces device routing- // unless the agent's selection policy is `fixed` (author-controlled- // targets stay authoritative β same rule the chat picker follows), and- // the directory rides into the topic this run creates.+ // The caller's device for this run, else the task's own pin. `deviceId`+ // forces device routing unless the agent's selection policy is `fixed`+ // (author-controlled targets stay authoritative β same rule the chat+ // picker follows), and the directory rides into the topic this run creates....(runExecution?.deviceId ? { deviceId: runExecution.deviceId } : {}),...(continueTopicId || runExecution?.initialTopicMetadata? {@@ -386,6 +444,9 @@ export class TaskRunnerService {}throw new Error(result.error || result.message || 'Agent run failed to start');}+ // The operation may now be live on the requested device: bookkeeping that+ // fails below must not move its topic back to the previous machine.+ runAccepted = true;if (result.topicId) {const topicId = result.topicId;@@ -427,6 +488,9 @@ export class TaskRunnerService {});// Same confirmation gate as TaskService.interruptTaskOperation.const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;+ // Nothing is left running on the requested device, so its retarget+ // goes back like any other kickoff that did not start.+ if (stopped) runAccepted = false;throw new TRPCError({code: stopped? recorded === 'deleted'@@ -448,6 +512,22 @@ export class TaskRunnerService {taskIdentifier: task.identifier,};} catch (error) {+ // The run never started on the requested device, so its retarget must+ // not outlive it: a later plain continuation would otherwise be routed+ // there while the task still pins its own machine.+ if (continueTopicId && topicRetarget && !runAccepted) {+ const { previous, written } = topicRetarget;+ try {+ // Only while the topic still carries this run's own write: a device or+ // directory someone set since then is newer than our snapshot.+ await this.topicModel.updateMetadata(continueTopicId, previous, {+ onlyIf: (current) => isSameTopicExecution(current, written),+ });+ } catch (restoreError) {+ log('runTask: failed to restore topic %s execution: %O', continueTopicId, restoreError);+ }+ }+if (weSetRunning) {try {const failedTask = await this.taskModel.findById(taskId);diff --git a/apps/server/src/services/taskRunner/resolveRunExecution.test.ts b/apps/server/src/services/taskRunner/resolveRunExecution.test.tsindex e855f062944..cac059f7f05 100644--- a/apps/server/src/services/taskRunner/resolveRunExecution.test.ts+++ b/apps/server/src/services/taskRunner/resolveRunExecution.test.ts@@ -314,3 +314,106 @@ describe('resolveRunDeviceId', () => {expect(resolveRunDeviceId({ boundDeviceId: 'device-a' }, fixedDevice)).toBe('device-a');});});++// The scheduler dispatches `lh task run <id> --device <id>` by machine load; a+// device the caller names for one run must beat the task's own pin, except+// where the workspace author fixed the agent's target.+describe('explicit run device', () => {+ const pinnedToA: TaskExecutionConfig = {+ boundDeviceId: 'device-a',+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ };+ const memberSelected: LobeAgentAgencyConfig = { executionTarget: 'device' };+ const fixedAgentDevice: LobeAgentAgencyConfig = {+ boundDeviceId: 'device-c',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ };++ it('runs on the requested device instead of the task pin', () => {+ expect(resolveRunDeviceId(pinnedToA, memberSelected, 'ws-1', 'device-b')).toBe('device-b');+ });++ it('keeps the task pin when no device is requested', () => {+ expect(resolveRunDeviceId(pinnedToA, memberSelected, 'ws-1', undefined)).toBe('device-a');+ });++ it("keeps the agent's fixed target over a requested device", () => {+ expect(resolveRunDeviceId(pinnedToA, fixedAgentDevice, 'ws-1', 'device-b')).toBe('device-c');+ });++ it("sends the requested device without the pinned machine's directory", () => {+ const runDeviceId = resolveRunDeviceId(pinnedToA, memberSelected, 'ws-1', 'device-b');++ expect(resolveTaskRunExecution(pinnedToA, runDeviceId, 'device-b')).toEqual({+ deviceId: 'device-b',+ });+ });++ it('keeps the repo fallback when the requested device drops the pinned directory', () => {+ const execution = { ...pinnedToA, repos: ['lobehub/lobehub'] };++ expect(resolveTaskRunExecution(execution, 'device-b', 'device-b')).toEqual({+ deviceId: 'device-b',+ initialTopicMetadata: {+ repos: ['lobehub/lobehub'],+ workingDirectory: 'lobehub/lobehub',+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },+ },+ });+ });++ it('forwards the requested device for a task that pins nothing', () => {+ const runDeviceId = resolveRunDeviceId(undefined, memberSelected, 'ws-1', 'device-b');++ expect(resolveTaskRunExecution(undefined, runDeviceId, 'device-b')).toEqual({+ deviceId: 'device-b',+ });+ });++ it('drops a requested device the fixed target replaces for a task that pins nothing', () => {+ const runDeviceId = resolveRunDeviceId(undefined, fixedAgentDevice, 'ws-1', 'device-b');++ expect(runDeviceId).toBe('device-c');+ expect(resolveTaskRunExecution(undefined, runDeviceId, 'device-b')).toBeUndefined();+ });++ it('ignores a requested device the fixed agent target replaces', () => {+ const runDeviceId = resolveRunDeviceId(pinnedToA, fixedAgentDevice, 'ws-1', 'device-b');++ // Same as before a caller could name a device: the pin rides as `deviceId`+ // (turnSetup drops it for device-c), and A's directory stays behind.+ expect(resolveTaskRunExecution(pinnedToA, runDeviceId, 'device-b')).toEqual({+ deviceId: 'device-a',+ });+ expect(+ resolveTopicExecutionPatch(+ { boundDeviceId: 'device-a' },+ { execution: pinnedToA },+ runDeviceId,+ 'device-b',+ ),+ ).toBeUndefined();+ });++ it('moves a continued topic to the requested device without the pinned directory', () => {+ expect(+ resolveTopicExecutionPatch(+ {+ boundDeviceId: 'device-a',+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ },+ { execution: pinnedToA },+ 'device-b',+ 'device-b',+ ),+ ).toEqual({+ boundDeviceId: 'device-b',+ repos: undefined,+ workingDirectory: undefined,+ workingDirectoryConfig: undefined,+ });+ });+});diff --git a/apps/server/src/services/taskRunner/resolveRunExecution.ts b/apps/server/src/services/taskRunner/resolveRunExecution.tsindex 541c12cec9e..0f74dcc789f 100644--- a/apps/server/src/services/taskRunner/resolveRunExecution.ts+++ b/apps/server/src/services/taskRunner/resolveRunExecution.ts@@ -42,12 +42,14 @@ export const resolveRunDeviceId = (execution: TaskExecutionConfig | undefined,agencyConfig: LobeAgentAgencyConfig | null | undefined,workspaceId?: string,+ /** A device the caller named for this run only (`lh task run --device`). */+ requestedDeviceId?: string,): string | undefined => {const isFixedSelection =!!workspaceId && agencyConfig?.executionTargetSelectionPolicy === 'fixed';- // A member-selected target is exactly the task-level pin, so nothing replaces it.- if (!isFixedSelection) return execution?.boundDeviceId;+ // A member-selected target follows the run's request first, then the task pin.+ if (!isFixedSelection) return requestedDeviceId ?? execution?.boundDeviceId;// Only a `device` fixed target names a machine; a fixed sandbox names none.return agencyConfig?.executionTarget === 'device' ? agencyConfig.boundDeviceId : undefined;@@ -70,8 +72,21 @@ export const resolveTaskRunExecution = (* would silently drop the directory of every pinned task.*/runDeviceId: string | undefined,+ /**+ * A device the caller named for this run only. When the run honors it+ * (`runDeviceId` names it) it outranks the task's pin as the run's+ * `deviceId`; the pin's directory then stays behind unless the two name the+ * same machine (pass the same request to `resolveRunDeviceId`).+ */+ requestedDeviceId?: string,): TaskRunExecution | undefined => {- if (!execution) return undefined;+ // A request the run will not honor (a fixed agent target replaced it) must not+ // stand in for the pin: it would be persisted on a continued topic as the+ // run's machine while the run goes elsewhere.+ const honoredDeviceId =+ requestedDeviceId && requestedDeviceId === runDeviceId ? requestedDeviceId : undefined;++ if (!execution) return honoredDeviceId ? { deviceId: honoredDeviceId } : undefined;const { boundDeviceId, repos, workingDirectory, workingDirectoryConfig } = execution;@@ -103,8 +118,12 @@ export const resolveTaskRunExecution = (: {}),};+ // An unhonored request falls back to exactly what the run sent before the+ // caller could name a device: the task's own pin.+ const deviceId = honoredDeviceId ?? boundDeviceId;+const runExecution: TaskRunExecution = {- ...(boundDeviceId ? { deviceId: boundDeviceId } : {}),+ ...(deviceId ? { deviceId } : {}),...(Object.keys(initialTopicMetadata).length > 0 ? { initialTopicMetadata } : {}),};@@ -120,6 +139,12 @@ const topicExecutionOf = (metadata?: ChatTopicMetadata | null): string =>workingDirectoryConfig: metadata?.workingDirectoryConfig ?? null,});+/** Whether two topic metadata snapshots agree on every execution axis. */+export const isSameTopicExecution = (+ a: ChatTopicMetadata | null | undefined,+ b: ChatTopicMetadata | null | undefined,+): boolean => topicExecutionOf(a) === topicExecutionOf(b);+/*** The execution metadata a CONTINUED topic has to carry before this run.*@@ -157,21 +182,24 @@ export const resolveTopicExecutionPatch = (taskConfig: null | Record<string, unknown> | undefined,/** The device this run will use β see {@link resolveTaskRunExecution}. */runDeviceId: string | undefined,+ /** A device the caller named for this run only; it outranks the task's pin. */+ requestedDeviceId?: string,): ChatTopicMetadata | undefined => {const stored = taskConfig?.execution;if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return undefined;const execution = readTaskExecutionConfig(taskConfig);- const initial = resolveTaskRunExecution(execution, runDeviceId)?.initialTopicMetadata;+ const run = resolveTaskRunExecution(execution, runDeviceId, requestedDeviceId);+ const initial = run?.initialTopicMetadata;const next: ChatTopicMetadata = {// `undefined` clears the axis: `TopicModel.updateMetadata` shallow-merges, so// the key is dropped rather than kept at its previous value.- boundDeviceId: execution?.boundDeviceId,+ boundDeviceId: run?.deviceId,repos: initial?.repos,workingDirectory: initial?.workingDirectory,workingDirectoryConfig: initial?.workingDirectoryConfig,};- return topicExecutionOf(topicMetadata) === topicExecutionOf(next) ? undefined : next;+ return isSameTopicExecution(topicMetadata, next) ? undefined : next;};diff --git a/apps/server/src/services/taskRunner/runTask.explicitDevice.test.ts b/apps/server/src/services/taskRunner/runTask.explicitDevice.test.tsnew file mode 100644index 00000000000..23bcc5e13dd--- /dev/null+++ b/apps/server/src/services/taskRunner/runTask.explicitDevice.test.ts@@ -0,0 +1,352 @@+import type { LobeAgentAgencyConfig } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';++import { TaskRunnerService } from './index';++const mocks = vi.hoisted(() => ({+ execAgent: vi.fn(),+ findTopicById: vi.fn(),+ getAgentAgencyConfig: vi.fn(),+ getAgentModelConfig: vi.fn(),+ interruptTask: vi.fn(),+ updateTopicMetadata: vi.fn(),+}));++vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));+vi.mock('@/database/models/taskTopic', () => ({ TaskTopicModel: vi.fn() }));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return { findById: mocks.findTopicById, updateMetadata: mocks.updateTopicMetadata };+ }),+}));+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentAgencyConfig: mocks.getAgentAgencyConfig,+ getAgentModelConfig: mocks.getAgentModelConfig,+ };+ }),+}));+vi.mock('@/database/models/brief', () => ({ BriefModel: vi.fn() }));+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(function () {+ return { execAgent: mocks.execAgent, interruptTask: mocks.interruptTask };+ }),+}));+vi.mock('@/server/services/taskLifecycle', () => ({ TaskLifecycleService: vi.fn() }));+vi.mock('./buildTaskPrompt', () => ({+ buildTaskPrompt: vi.fn().mockResolvedValue({+ acceptanceEnabled: false,+ fileIds: [],+ prompt: 'do it',+ }),+}));++// The scheduler picks a machine by load and dispatches `lh task run --device`;+// a task bound to another machine in its detail page must not silently win.+describe('TaskRunnerService.runTask explicit device', () => {+ const db = {+ transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn(db),+ } as any;++ const pinnedToA = {+ execution: {+ boundDeviceId: 'device-a',+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ },+ model: 'codex',+ provider: 'openai',+ };++ const setupTask = (config: Record<string, unknown>) => {+ const task = {+ assigneeAgentId: 'agt_codex',+ config,+ id: 'task-1',+ identifier: 'T-1',+ status: 'backlog',+ totalTopics: 0,+ };+ const taskModel = {+ findById: vi+ .fn()+ .mockResolvedValueOnce({ ...task })+ .mockResolvedValue({ ...task, status: 'running' }),+ getCheckpointConfig: vi.fn().mockReturnValue({}),+ getReviewConfig: vi.fn().mockReturnValue(undefined),+ incrementTopicCount: vi.fn(),+ lockForUpdate: vi.fn().mockResolvedValue(true),+ update: vi.fn(),+ updateCurrentTopic: vi.fn(),+ updateHeartbeat: vi.fn(),+ updateStatus: vi.fn(),+ updateStatusIfCurrent: vi.fn().mockResolvedValue({ ...task, status: 'running' }),+ updateTaskConfig: vi.fn(),+ };+ vi.mocked(TaskModel).mockImplementation(function () {+ return taskModel as any;+ });+ return taskModel;+ };++ const run = (params: { continueTopicId?: string; deviceId?: string } = {}) =>+ new TaskRunnerService(db, 'user-1', 'ws-1').runTask({ taskId: 'T-1', ...params });++ const execParams = () => mocks.execAgent.mock.calls[0][0];++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(TaskTopicModel).mockImplementation(function () {+ return {+ add: vi.fn(),+ findByTaskId: vi.fn().mockResolvedValue([]),+ updateOperationId: vi.fn(),+ updateStatus: vi.fn(),+ } as any;+ });+ mocks.execAgent.mockResolvedValue({ operationId: 'op-1', success: true, topicId: 'tpc-1' });+ mocks.updateTopicMetadata.mockResolvedValue([{ id: 'tpc-old' }]);+ mocks.getAgentModelConfig.mockResolvedValue({ model: 'codex', provider: 'openai' });+ mocks.getAgentAgencyConfig.mockResolvedValue({+ executionTarget: 'device',+ } satisfies LobeAgentAgencyConfig);+ });++ it("runs on the requested device without the pinned machine's directory", async () => {+ setupTask(pinnedToA);++ await run({ deviceId: 'device-b' });++ expect(execParams().deviceId).toBe('device-b');+ expect(execParams().appContext?.initialTopicMetadata).toBeUndefined();+ });++ it('keeps the task pin and its directory when no device is requested', async () => {+ setupTask(pinnedToA);++ await run();++ expect(execParams().deviceId).toBe('device-a');+ expect(execParams().appContext?.initialTopicMetadata).toEqual({+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ });+ });++ it('forwards the requested device for a task that pins nothing', async () => {+ setupTask({ model: 'codex', provider: 'openai' });++ await run({ deviceId: 'device-b' });++ expect(execParams().deviceId).toBe('device-b');+ });++ it("keeps the agent's fixed target in charge of the directory", async () => {+ setupTask(pinnedToA);+ mocks.getAgentAgencyConfig.mockResolvedValue({+ boundDeviceId: 'device-c',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ } satisfies LobeAgentAgencyConfig);++ await run({ deviceId: 'device-b' });++ // `turnSetup` drops any requested device under a fixed policy and routes to+ // device-c, so neither A's directory nor the request may decide anything here.+ expect(execParams().appContext?.initialTopicMetadata).toBeUndefined();+ });++ it('moves a continued topic to the requested device before dispatching', async () => {+ setupTask(pinnedToA);+ mocks.findTopicById.mockResolvedValue({+ id: 'tpc-old',+ metadata: {+ boundDeviceId: 'device-a',+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ },+ });++ await run({ continueTopicId: 'tpc-old', deviceId: 'device-b' });++ expect(mocks.updateTopicMetadata).toHaveBeenCalledWith(+ 'tpc-old',+ {+ boundDeviceId: 'device-b',+ repos: undefined,+ workingDirectory: undefined,+ workingDirectoryConfig: undefined,+ },+ { onlyIf: expect.any(Function) },+ );+ expect(execParams().deviceId).toBe('device-b');+ });++ describe('when a continued kickoff on the requested device fails', () => {+ const previous = {+ boundDeviceId: 'device-a',+ workingDirectory: '/a/project',+ workingDirectoryConfig: { path: '/a/project' },+ };++ beforeEach(() => {+ setupTask(pinnedToA);+ mocks.findTopicById.mockResolvedValue({ id: 'tpc-old', metadata: previous });+ });++ const expectRestored = () =>+ expect(mocks.updateTopicMetadata).toHaveBeenLastCalledWith(+ 'tpc-old',+ { ...previous, repos: undefined },+ { onlyIf: expect.any(Function) },+ );++ it("restores only while the topic still carries this run's retarget", async () => {+ mocks.execAgent.mockResolvedValue({ error: 'device offline', success: false });++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow();++ const { onlyIf } = mocks.updateTopicMetadata.mock.lastCall![2];+ expect(onlyIf({ boundDeviceId: 'device-b', model: 'codex' })).toBe(true);+ // Someone moved the topic while the kickoff was in flight: theirs is newer.+ expect(onlyIf({ boundDeviceId: 'device-d' })).toBe(false);+ expect(onlyIf({ boundDeviceId: 'device-b', workingDirectory: '/b/other' })).toBe(false);+ });++ it('snapshots what the retarget actually replaced when the topic changes underneath', async () => {+ const concurrent = { ...previous, boundDeviceId: 'device-c' };+ mocks.findTopicById+ .mockResolvedValueOnce({ id: 'tpc-old', metadata: previous })+ .mockResolvedValueOnce({ id: 'tpc-old', metadata: concurrent });+ // The first write is computed from a snapshot that is already stale.+ mocks.updateTopicMetadata.mockResolvedValueOnce([]);+ mocks.execAgent.mockResolvedValue({ error: 'device offline', success: false });++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow();++ const [, staleGuard] = mocks.updateTopicMetadata.mock.calls.map((call) => call[2].onlyIf);+ expect(staleGuard(concurrent)).toBe(true);+ expect(mocks.updateTopicMetadata).toHaveBeenLastCalledWith(+ 'tpc-old',+ { ...concurrent, repos: undefined },+ { onlyIf: expect.any(Function) },+ );+ });++ it('fails the kickoff when the topic keeps changing underneath', async () => {+ mocks.updateTopicMetadata.mockResolvedValue([]);++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'kept changing',+ );++ expect(mocks.execAgent).not.toHaveBeenCalled();+ });++ it('restores the topic when the task is withdrawn and the run is confirmed stopped', async () => {+ const taskModel = setupTask(pinnedToA);+ taskModel.lockForUpdate.mockResolvedValue(false);+ mocks.interruptTask.mockResolvedValue({ success: true });++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'the run was stopped',+ );++ expect(mocks.updateTopicMetadata).toHaveBeenCalledTimes(2);+ expectRestored();+ });++ it('keeps the retarget when stopping the withdrawn run is not confirmed', async () => {+ const taskModel = setupTask(pinnedToA);+ taskModel.lockForUpdate.mockResolvedValue(false);+ mocks.interruptTask.mockResolvedValue({ success: false });++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'could not be confirmed',+ );++ expect(mocks.updateTopicMetadata).toHaveBeenCalledTimes(1);+ });++ it('restores the topic when dispatch is not accepted', async () => {+ mocks.execAgent.mockResolvedValue({ error: 'device offline', success: false });++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'device offline',+ );++ expectRestored();+ });++ it('restores the topic when dispatch throws', async () => {+ mocks.execAgent.mockRejectedValue(new Error('boom'));++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'boom',+ );++ expectRestored();+ });++ it('keeps the retarget when bookkeeping fails after a successful dispatch', async () => {+ const taskModel = setupTask(pinnedToA);+ taskModel.lockForUpdate.mockRejectedValue(new Error('db down'));++ await expect(run({ continueTopicId: 'tpc-old', deviceId: 'device-b' })).rejects.toThrow(+ 'db down',+ );++ // The operation may be live on device-b, so the topic must stay there.+ expect(mocks.updateTopicMetadata).toHaveBeenCalledTimes(1);+ });++ it('keeps the retarget once the run is accepted', async () => {+ await run({ continueTopicId: 'tpc-old', deviceId: 'device-b' });++ expect(mocks.updateTopicMetadata).toHaveBeenCalledTimes(1);+ });+ });++ it('does not move a continued topic to a device the fixed target replaces', async () => {+ setupTask(pinnedToA);+ mocks.getAgentAgencyConfig.mockResolvedValue({+ boundDeviceId: 'device-c',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ } satisfies LobeAgentAgencyConfig);+ mocks.findTopicById.mockResolvedValue({+ id: 'tpc-old',+ metadata: { boundDeviceId: 'device-a' },+ });++ await run({ continueTopicId: 'tpc-old', deviceId: 'device-b' });++ expect(mocks.updateTopicMetadata).not.toHaveBeenCalled();+ expect(execParams().deviceId).toBe('device-a');+ });++ it('does not move a continued topic to a device the fixed target replaces after its selection was cleared', async () => {+ // A cleared selection is still persisted (as `null` axes), so the topic sync+ // runs even though the task pins nothing.+ setupTask({+ execution: { boundDeviceId: null, workingDirectory: null },+ model: 'codex',+ provider: 'openai',+ });+ mocks.getAgentAgencyConfig.mockResolvedValue({+ boundDeviceId: 'device-c',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ } satisfies LobeAgentAgencyConfig);+ mocks.findTopicById.mockResolvedValue({ id: 'tpc-old', metadata: {} });++ await run({ continueTopicId: 'tpc-old', deviceId: 'device-b' });++ expect(mocks.updateTopicMetadata).not.toHaveBeenCalled();+ expect(execParams().deviceId).toBeUndefined();+ });+});diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 4f00881350c..65ef28b1d65 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -91,6 +91,30 @@ describe('TopicModel - Update', () => {expect(result[0].metadata).toEqual({ workingDirectory: '/path/to/dir' });});+ it('should skip the write when onlyIf rejects the current metadata', async () => {+ const topicId = 'metadata-test-only-if';+ await serverDB.insert(topics).values({+ userId,+ id: topicId,+ title: 'Test',+ metadata: { boundDeviceId: 'device-d' },+ });++ const skipped = await topicModel.updateMetadata(+ topicId,+ { boundDeviceId: 'device-a' },+ { onlyIf: (metadata) => metadata?.boundDeviceId === 'device-b' },+ );+ const written = await topicModel.updateMetadata(+ topicId,+ { boundDeviceId: 'device-a' },+ { onlyIf: (metadata) => metadata?.boundDeviceId === 'device-d' },+ );++ expect(skipped).toEqual([]);+ expect(written[0].metadata).toEqual({ boundDeviceId: 'device-a' });+ });+it('should merge metadata with existing metadata', async () => {const topicId = 'metadata-test-2';await serverDB.insert(topics).values({diff --git a/packages/database/src/models/topic/update.ts b/packages/database/src/models/topic/update.tsindex fa179593145..0141debd2e3 100644--- a/packages/database/src/models/topic/update.ts+++ b/packages/database/src/models/topic/update.ts@@ -116,10 +116,20 @@ export const recomputeUsage = async (ctx: TopicModelContext, id: string) =>* Update topic metadata with merge logic* This method merges new metadata with existing metadata instead of replacing it*/+export interface UpdateMetadataOptions {+ /**+ * Checked against the row's current metadata under the row lock; the write is+ * skipped (and `[]` returned) when it fails. Lets a caller undo its own+ * earlier write without clobbering one that landed after it.+ */+ onlyIf?: (metadata: ChatTopicMetadata | null | undefined) => boolean;+}+export const updateMetadata = async (ctx: TopicModelContext,id: string,metadata: TopicMetadataPatch,+ options?: UpdateMetadataOptions,) => {// Merge into the existing metadata under a row lock so concurrent writers// can't lose each other's keys. The old read-then-write was a non-atomic@@ -140,6 +150,7 @@ export const updateMetadata = async (// No row (missing or not owned) β nothing to update, mirror the old no-op.if (!existing) return [];+ if (options?.onlyIf && !options.onlyIf(existing.metadata)) return [];const mergedOnboardingSession =existing.metadata?.onboardingSession && metadata.onboardingSession