Skip to content

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

✨ feat(goal): copy a goal between personal and workspace scopes (#21665)

Rdmclin29e9477a8d420
diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.ts
index 888db1e62da..7a2bdb0f4df 100644
--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts
@@ -33,6 +33,7 @@ function expected(): Array<
['bindSubscription', 'mutation', 13],
['bindTopic', 'mutation', 13],
['close', 'mutation', 13],
+ ['copyGoalToWorkspace', 'mutation', 13],
['create', 'mutation', 13],
['createConversationGoal', 'mutation', 8],
['decide', 'mutation', 13],
diff --git a/apps/server/src/routers/lambda/goal/index.ts b/apps/server/src/routers/lambda/goal/index.ts
index 8b03d11ee14..e846c003103 100644
--- a/apps/server/src/routers/lambda/goal/index.ts
+++ b/apps/server/src/routers/lambda/goal/index.ts
@@ -7,6 +7,7 @@ import { lifecycleRouter } from './lifecycle';
import { planningRouter } from './planning';
import { readRouter } from './reads';
import { subscriptionRouter } from './subscriptions';
+import { transferRouter } from './transfer';
export const goalRouter = mergeRouters(
lifecycleRouter,
@@ -15,6 +16,7 @@ export const goalRouter = mergeRouters(
configurationRouter,
readRouter,
subscriptionRouter,
+ transferRouter,
router({
...goalGraphEditProcedures,
}),
diff --git a/apps/server/src/routers/lambda/goal/transfer.test.ts b/apps/server/src/routers/lambda/goal/transfer.test.ts
new file mode 100644
index 00000000000..36e1aafa28a
--- /dev/null
+++ b/apps/server/src/routers/lambda/goal/transfer.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };
+});
+
+vi.mock('@/server/services/goal', () => ({ GoalService: vi.fn() }));
+vi.mock('@/server/services/goal/subscriptions', () => ({ GoalSubscriptionService: vi.fn() }));
+vi.mock('@/database/models/goal', () => ({ GoalModel: vi.fn() }));
+
+const mockHasPermission = vi.fn();
+vi.mock('@/server/services/workspacePermission', () => ({
+ hasWorkspaceScopedPermission: (...args: unknown[]) => mockHasPermission(...args),
+}));
+
+const mockStorageCheck = vi.fn();
+vi.mock('@/business/server/lambda-routers/file', () => ({
+ businessFileTransferStorageCheck: (...args: unknown[]) => mockStorageCheck(...args),
+}));
+
+const mockCopy = vi.fn();
+const mockFixtureResources = vi.fn();
+const copyScopes: Array<string | undefined> = [];
+vi.mock('@/server/services/goal/copy', () => ({
+ GoalCopyService: vi.fn(function (_db: unknown, _userId: string, workspaceId?: string) {
+ copyScopes.push(workspaceId);
+ return { copyToWorkspace: mockCopy, fixtureResources: mockFixtureResources };
+ }),
+}));
+
+const { transferRouter } = await import('./transfer');
+
+describe('goal transferRouter.copyGoalToWorkspace', () => {
+ const caller = (workspaceId: string | null) =>
+ transferRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId } as any);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ copyScopes.length = 0;
+ mockCopy.mockResolvedValue({ goalId: 'goal_copy' });
+ mockFixtureResources.mockResolvedValue({ documentIds: [], files: [] });
+ });
+
+ const checkedActions = () => mockHasPermission.mock.calls.map(([params]) => params.action);
+
+ it('copies from the current scope once the target workspace grants write access', async () => {
+ mockHasPermission.mockResolvedValue(true);
+
+ const result = await caller('ws-source').copyGoalToWorkspace({
+ id: 'goal_1',
+ targetWorkspaceId: 'ws-target',
+ });
+
+ expect(mockHasPermission).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'AGENT_UPDATE',
+ userId: 'user-1',
+ workspaceId: 'ws-target',
+ }),
+ );
+ expect(copyScopes).toEqual(['ws-source']);
+ expect(mockCopy).toHaveBeenCalledWith('goal_1', 'ws-target');
+ expect(result).toEqual({ goalId: 'goal_copy' });
+ });
+
+ it('refuses a target workspace the caller cannot write to', async () => {
+ mockHasPermission.mockResolvedValue(false);
+
+ await expect(
+ caller(null).copyGoalToWorkspace({ id: 'goal_1', targetWorkspaceId: 'ws-target' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockCopy).not.toHaveBeenCalled();
+ });
+
+ it('also needs document and file rights on the target when fixtures are copied', async () => {
+ mockHasPermission.mockResolvedValue(true);
+ mockFixtureResources.mockResolvedValue({
+ documentIds: ['docs_1'],
+ files: [
+ { id: 'file_1', size: 300 },
+ { id: 'file_2', size: 200 },
+ ],
+ });
+
+ await caller('ws-source').copyGoalToWorkspace({ id: 'goal_1', targetWorkspaceId: 'ws-target' });
+
+ expect(checkedActions()).toEqual(['AGENT_UPDATE', 'DOCUMENT_CREATE', 'FILE_UPLOAD']);
+ expect(mockStorageCheck).toHaveBeenCalledWith({
+ additionalSize: 500,
+ targetUserId: 'user-1',
+ targetWorkspaceId: 'ws-target',
+ });
+ expect(mockCopy).toHaveBeenCalledWith('goal_1', 'ws-target');
+ });
+
+ it('refuses fixture files when the target role cannot upload files', async () => {
+ mockHasPermission.mockImplementation(async ({ action }) => action !== 'FILE_UPLOAD');
+ mockFixtureResources.mockResolvedValue({ documentIds: [], files: [{ id: 'file_1', size: 1 }] });
+
+ await expect(
+ caller('ws-source').copyGoalToWorkspace({ id: 'goal_1', targetWorkspaceId: 'ws-target' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockStorageCheck).not.toHaveBeenCalled();
+ expect(mockCopy).not.toHaveBeenCalled();
+ });
+
+ it('stops before writing when fixture files exceed the target storage', async () => {
+ mockFixtureResources.mockResolvedValue({ documentIds: [], files: [{ id: 'file_1', size: 9 }] });
+ mockStorageCheck.mockRejectedValue(new TRPCError({ code: 'FORBIDDEN', message: 'quota' }));
+
+ await expect(
+ caller('ws-source').copyGoalToWorkspace({ id: 'goal_1', targetWorkspaceId: null }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockStorageCheck).toHaveBeenCalledWith(
+ expect.objectContaining({ additionalSize: 9, targetWorkspaceId: null }),
+ );
+ expect(mockCopy).not.toHaveBeenCalled();
+ });
+
+ it('copies into personal without a workspace permission check', async () => {
+ await caller('ws-source').copyGoalToWorkspace({ id: 'goal_1', targetWorkspaceId: null });
+
+ expect(mockHasPermission).not.toHaveBeenCalled();
+ expect(mockCopy).toHaveBeenCalledWith('goal_1', null);
+ });
+});
diff --git a/apps/server/src/routers/lambda/goal/transfer.ts b/apps/server/src/routers/lambda/goal/transfer.ts
new file mode 100644
index 00000000000..72866add6fc
--- /dev/null
+++ b/apps/server/src/routers/lambda/goal/transfer.ts
@@ -0,0 +1,67 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { businessFileTransferStorageCheck } from '@/business/server/lambda-routers/file';
+import { router } from '@/libs/trpc/lambda';
+import { GoalCopyService } from '@/server/services/goal/copy';
+import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
+import { TransferErrorCode } from '@/types/transferError';
+
+import { goalWriteProcedure, mapGoalError } from '../goalProcedures';
+
+export const transferRouter = router({
+ /**
+ * Copy a goal's definition into personal or another workspace. Moving is
+ * intentionally not offered, for the same reason tasks only copy: a goal
+ * drags its graph Tasks and their history with it. Permissions match
+ * `copyTaskToWorkspace`: `agent:update` in the source scope and
+ * `AGENT_UPDATE` on the target workspace; personal needs no target check.
+ * Fixture documents and files are copied too, so they need the same target
+ * permissions and storage headroom as copying them directly.
+ */
+ copyGoalToWorkspace: goalWriteProcedure
+ .input(z.object({ id: z.string(), targetWorkspaceId: z.string().nullable() }))
+ .mutation(async ({ ctx, input }) => {
+ const { targetWorkspaceId } = input;
+ const service = new GoalCopyService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+
+ try {
+ const fixtures = await service.fixtureResources(input.id);
+
+ if (targetWorkspaceId) {
+ const actions = [
+ 'AGENT_UPDATE' as const,
+ ...(fixtures.documentIds.length > 0 ? (['DOCUMENT_CREATE'] as const) : []),
+ ...(fixtures.files.length > 0 ? (['FILE_UPLOAD'] as const) : []),
+ ];
+ for (const action of actions) {
+ const canWriteTarget = await hasWorkspaceScopedPermission({
+ action,
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: targetWorkspaceId,
+ });
+ if (!canWriteTarget) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },
+ code: 'FORBIDDEN',
+ message: 'No write access to target workspace',
+ });
+ }
+ }
+ }
+
+ if (fixtures.files.length > 0) {
+ await businessFileTransferStorageCheck({
+ additionalSize: fixtures.files.reduce((total, file) => total + file.size, 0),
+ targetUserId: ctx.userId,
+ targetWorkspaceId,
+ });
+ }
+
+ return await service.copyToWorkspace(input.id, targetWorkspaceId);
+ } catch (error) {
+ mapGoalError(error, 'copy');
+ }
+ }),
+});
diff --git a/apps/server/src/services/goal/copy.test.ts b/apps/server/src/services/goal/copy.test.ts
new file mode 100644
index 00000000000..00b4b5e9719
--- /dev/null
+++ b/apps/server/src/services/goal/copy.test.ts
@@ -0,0 +1,233 @@
+// @vitest-environment node
+import { and, eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { DocumentModel } from '@/database/models/document';
+import { GoalModel } from '@/database/models/goal';
+import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
+import { files, globalFiles, goalNodes, goals, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { GoalCopyService } from './copy';
+import { GoalService } from './GoalService';
+import { registerGoalServiceTestCleanup } from './testUtils';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'goal-copy-test-user';
+const workspaceId = 'goal-copy-test-ws';
+
+registerGoalServiceTestCleanup(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: userId, slug: 'goal-copy-team' })
+ .onConflictDoNothing();
+});
+
+const problemNode = async (goalId: string) =>
+ (
+ await serverDB
+ .select()
+ .from(goalNodes)
+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.kind, 'problem')))
+ )[0];
+
+describe('GoalCopyService.copyToWorkspace', () => {
+ it('copies a personal goal definition into a workspace as a fresh, agent-less draft', async () => {
+ const source = await new GoalService(serverDB, userId).create({
+ config: {
+ recovery: { maxAttemptsPerTask: 2 },
+ schedule: { deadline: '2000-01-01T00:00:00.000Z' },
+ supervision: { enabled: true, maxIncidents: 3 },
+ },
+ maxRounds: 5,
+ maxTotalCost: 12.5,
+ problemDescription: 'Ship the onboarding flow',
+ requirement: 'Users can finish onboarding',
+ tasks: ['Draft the copy'],
+ title: 'Onboarding',
+ });
+ // Scope-bound fields a copy must not carry: they name the source's agent and run state.
+ await serverDB
+ .update(goals)
+ .set({
+ config: {
+ ...source.goal.config,
+ model: 'gpt-x',
+ pausedBy: 'pattern_break',
+ provider: 'openai',
+ taskAgentId: 'agt_source_only',
+ },
+ status: 'running',
+ })
+ .where(eq(goals.id, source.goal.id));
+
+ const { goalId } = await new GoalCopyService(serverDB, userId).copyToWorkspace(
+ source.goal.id,
+ workspaceId,
+ );
+
+ expect(goalId).not.toBe(source.goal.id);
+ // The copy lands in the workspace, not in personal scope.
+ expect(await new GoalModel(serverDB, userId).findById(goalId)).toBeUndefined();
+ const copy = (await new GoalModel(serverDB, userId, workspaceId).findById(goalId))!;
+ expect(copy).toMatchObject({
+ agentId: null,
+ maxRounds: 5,
+ maxTotalCost: 12.5,
+ projectId: null,
+ requirement: 'Users can finish onboarding',
+ status: 'draft',
+ title: 'Onboarding',
+ workspaceId,
+ });
+ expect(copy.config).toEqual({
+ recovery: { maxAttemptsPerTask: 2 },
+ supervision: { enabled: true, maxIncidents: 3 },
+ });
+
+ // A fresh graph: the problem statement only, none of the source's Tasks.
+ const nodes = await serverDB.select().from(goalNodes).where(eq(goalNodes.goalId, goalId));
+ expect(nodes.map((node) => node.kind)).toEqual(['problem']);
+ expect((await problemNode(goalId))?.description).toBe('Ship the onboarding flow');
+
+ // The source is untouched.
+ const original = (await new GoalModel(serverDB, userId).findById(source.goal.id))!;
+ expect(original.status).toBe('running');
+ expect(original.config?.taskAgentId).toBe('agt_source_only');
+ });
+
+ it('clones acceptance criteria and their instructions into the target scope', async () => {
+ const source = await new GoalService(serverDB, userId, workspaceId).create({
+ config: { acceptance: { metrics: [{ key: 'signups', target: 100 }] } },
+ criteria: [{ instruction: 'Open the page and sign up', title: 'Sign-up works' }],
+ title: 'Grow sign-ups',
+ });
+ const sourceCriterionIds = source.goal.config!.acceptance!.criteriaIds!;
+
+ const { goalId } = await new GoalCopyService(serverDB, userId, workspaceId).copyToWorkspace(
+ source.goal.id,
+ null,
+ );
+
+ const copy = (await new GoalModel(serverDB, userId).findById(goalId))!;
+ expect(copy.workspaceId).toBeNull();
+ expect(copy.config?.acceptance?.metrics).toEqual([{ key: 'signups', target: 100 }]);
+ const copiedIds = copy.config!.acceptance!.criteriaIds!;
+ expect(copiedIds).toHaveLength(1);
+ expect(copiedIds[0]).not.toBe(sourceCriterionIds[0]);
+
+ const [criterion] = await new VerifyCriterionModel(serverDB, userId).findByIds(copiedIds);
+ expect(criterion).toMatchObject({ title: 'Sign-up works', workspaceId: null });
+ const document = await new DocumentModel(serverDB, userId).findById(criterion.documentId!);
+ expect(document?.content).toBe('Open the page and sign up');
+ // The source criterion still belongs to the workspace goal.
+ expect(
+ await new VerifyCriterionModel(serverDB, userId, workspaceId).findByIds(sourceCriterionIds),
+ ).toHaveLength(1);
+ });
+
+ it('re-points fixture resources at copies in the target scope', async () => {
+ const source = await new GoalService(serverDB, userId, workspaceId).create({
+ criteria: [{ instruction: 'Upload the sample and compare', title: 'Import works' }],
+ title: 'Import data',
+ });
+ const [criterionId] = source.goal.config!.acceptance!.criteriaIds!;
+ const sourceDocument = await new DocumentModel(serverDB, userId, workspaceId).create({
+ content: 'name,email',
+ fileType: 'text/csv',
+ source: 'fixture.csv',
+ sourceType: 'api',
+ title: 'fixture.csv',
+ totalCharCount: 10,
+ totalLineCount: 1,
+ });
+ await serverDB
+ .insert(globalFiles)
+ .values({
+ creator: userId,
+ fileType: 'image/png',
+ hashId: 'goal-copy-fixture-hash',
+ size: 1,
+ url: 'k-fx',
+ })
+ .onConflictDoNothing();
+ await serverDB.insert(files).values({
+ fileHash: 'goal-copy-fixture-hash',
+ fileType: 'image/png',
+ id: 'goal-copy-fixture-file',
+ name: 'sample.png',
+ size: 1,
+ url: 'k-fx',
+ userId,
+ workspaceId,
+ });
+ await new VerifyCriterionModel(serverDB, userId, workspaceId).update(criterionId, {
+ definition: {
+ fixtures: [
+ { id: 'csv', name: 'CSV', resource: { id: sourceDocument.id, type: 'document' } },
+ { id: 'png', name: 'PNG', resource: { id: 'goal-copy-fixture-file', type: 'file' } },
+ { id: 'gone', name: 'Gone', resource: { id: 'docs_missing', type: 'document' } },
+ { data: { rows: 3 }, id: 'inline', name: 'Inline' },
+ ],
+ },
+ });
+
+ const service = new GoalCopyService(serverDB, userId, workspaceId);
+ // The preflight lists only resources the copy will duplicate.
+ expect(await service.fixtureResources(source.goal.id)).toEqual({
+ documentIds: [sourceDocument.id],
+ files: [{ id: 'goal-copy-fixture-file', size: 1 }],
+ });
+
+ const { goalId } = await service.copyToWorkspace(source.goal.id, null);
+
+ const copy = (await new GoalModel(serverDB, userId).findById(goalId))!;
+ const [criterion] = await new VerifyCriterionModel(serverDB, userId).findByIds(
+ copy.config!.acceptance!.criteriaIds!,
+ );
+ const [csv, png, gone, inline] = criterion.definition!.fixtures!;
+ expect(csv.resource!.id).not.toBe(sourceDocument.id);
+ expect((await new DocumentModel(serverDB, userId).findById(csv.resource!.id))?.content).toBe(
+ 'name,email',
+ );
+ expect(png.resource!.id).not.toBe('goal-copy-fixture-file');
+ const copiedFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, png.resource!.id),
+ });
+ expect(copiedFile).toMatchObject({ fileHash: 'goal-copy-fixture-hash', workspaceId: null });
+ // An unreadable resource is dropped instead of pointing into the source scope.
+ expect(gone.resource).toBeUndefined();
+ expect(inline).toEqual({ data: { rows: 3 }, id: 'inline', name: 'Inline' });
+
+ // The copied fixtures resolve in the copy's scope, as verification will.
+ const [materialized] = await new VerifyCriterionModel(serverDB, userId).materialize(
+ [
+ {
+ id: 'check_1',
+ index: 0,
+ onFail: criterion.onFail,
+ required: criterion.required,
+ sourceCriterionId: criterion.id,
+ title: criterion.title,
+ verifierConfig: criterion.verifierConfig ?? {},
+ verifierType: criterion.verifierType,
+ },
+ ],
+ 'ctx_goal_copy',
+ );
+ expect(materialized.resourceSnapshot?.fixtures.map((f) => f.fixtureId)).toEqual(['csv', 'png']);
+ });
+
+ it('refuses a goal outside the caller scope', async () => {
+ const source = await new GoalService(serverDB, userId, workspaceId).create({
+ title: 'Workspace only',
+ });
+
+ await expect(
+ new GoalCopyService(serverDB, userId).copyToWorkspace(source.goal.id, workspaceId),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+});
diff --git a/apps/server/src/services/goal/copy.ts b/apps/server/src/services/goal/copy.ts
new file mode 100644
index 00000000000..d18c417b6f3
--- /dev/null
+++ b/apps/server/src/services/goal/copy.ts
@@ -0,0 +1,239 @@
+import type { GoalConfig, GoalCreateConfig, VerifyCheckDefinition } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { and, asc, eq } from 'drizzle-orm';
+
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import { GoalModel } from '@/database/models/goal';
+import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
+import { goalNodes } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { TransferErrorCode } from '@/types/transferError';
+
+import { GoalService } from './GoalService';
+
+/**
+ * The part of a goal's config that is policy the owner chose and still means
+ * the same thing in another scope. Everything else is either runtime state
+ * (manager/supervisor/rollout receipts, planning leases, pause owners, change
+ * requests, reports) or names something in the source scope: the task agent,
+ * the planning model pair (dropped with the agent it overrides, as `setAgent`
+ * does), and the main-Agent policy, which `create` rejects without a goal agent.
+ */
+const copyableConfig = (config: GoalConfig | null, now: Date): GoalCreateConfig | undefined => {
+ if (!config) return undefined;
+ const { exploration, maxConcurrentTasks, recovery, rollout, schedule, supervision } = config;
+ const deadline = schedule?.deadline;
+ return {
+ // Criteria ids are re-pointed at the copied rows by the caller; numeric
+ // clauses only name series keys, which the copy samples afresh.
+ ...(config.acceptance?.metrics?.length
+ ? { acceptance: { metrics: config.acceptance.metrics } }
+ : {}),
+ ...(exploration ? { exploration } : {}),
+ ...(maxConcurrentTasks === undefined ? {} : { maxConcurrentTasks }),
+ ...(recovery ? { recovery } : {}),
+ ...(rollout ? { rollout } : {}),
+ // A deadline that already passed would pause the copy the moment it starts.
+ ...(deadline && new Date(deadline) > now ? { schedule: { deadline } } : {}),
+ ...(supervision?.maxIncidents === undefined
+ ? {}
+ : { supervision: { enabled: true, maxIncidents: supervision.maxIncidents } }),
+ };
+};
+
+/**
+ * Copy a goal into another scope (personal or a workspace).
+ *
+ * Like task copy, this clones the goal *definition* only: title, requirement,
+ * problem statement, budget, planning policy and acceptance criteria. The
+ * copy is a fresh `draft` with its own problem node — no graph progress,
+ * Tasks, events, traces, subscriptions or metric observations follow it, and
+ * it has no agent or project, since those name rows in the source scope. The
+ * owner picks an agent in the target and starts it from the goal page.
+ */
+export class GoalCopyService {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ /**
+ * The readable fixture resources a copy will duplicate in the target scope,
+ * so the caller can check target permissions and storage before writing.
+ */
+ fixtureResources = async (
+ goalId: string,
+ ): Promise<{ documentIds: string[]; files: { id: string; size: number }[] }> => {
+ const source = await this.findSource(goalId);
+ const criteria = await new VerifyCriterionModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findByIds(source.config?.acceptance?.criteriaIds ?? []);
+ const documentIds = new Set<string>();
+ const fileIds = new Set<string>();
+ for (const criterion of criteria)
+ for (const { resource } of criterion.definition?.fixtures ?? [])
+ if (resource) (resource.type === 'document' ? documentIds : fileIds).add(resource.id);
+
+ const sourceDocuments = new DocumentModel(this.db, this.userId, this.workspaceId);
+ const sourceFiles = new FileModel(this.db, this.userId, this.workspaceId);
+ const readableDocumentIds: string[] = [];
+ for (const id of documentIds)
+ if (await sourceDocuments.findById(id)) readableDocumentIds.push(id);
+ const files: { id: string; size: number }[] = [];
+ for (const id of fileIds) {
+ const file = await sourceFiles.findById(id);
+ if (file) files.push({ id, size: file.size });
+ }
+ return { documentIds: readableDocumentIds, files };
+ };
+
+ copyToWorkspace = async (
+ goalId: string,
+ targetWorkspaceId: string | null,
+ ): Promise<{ goalId: string }> => {
+ const source = await this.findSource(goalId);
+
+ const [problem] = await this.db
+ .select({ description: goalNodes.description })
+ .from(goalNodes)
+ .where(and(eq(goalNodes.goalId, source.id), eq(goalNodes.kind, 'problem')))
+ .orderBy(asc(goalNodes.createdAt))
+ .limit(1);
+
+ const targetScope = targetWorkspaceId ?? undefined;
+
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const criteriaIds = await this.copyCriteria(
+ db,
+ source.config?.acceptance?.criteriaIds ?? [],
+ targetScope,
+ );
+ const config = copyableConfig(source.config, new Date());
+ const graph = await new GoalService(db, this.userId, targetScope).create({
+ config: criteriaIds.length
+ ? { ...config, acceptance: { ...config?.acceptance, criteriaIds } }
+ : config,
+ draft: true,
+ maxRounds: source.maxRounds ?? undefined,
+ maxTotalCost: source.maxTotalCost ?? undefined,
+ problemDescription: problem?.description ?? undefined,
+ requirement: source.requirement ?? undefined,
+ title: source.title,
+ });
+ return { goalId: graph.goal.id };
+ });
+ };
+
+ private findSource = async (goalId: string) => {
+ const source = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);
+ if (!source)
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.ResourceNotFound } },
+ code: 'NOT_FOUND',
+ message: 'Goal not found',
+ });
+ return source;
+ };
+
+ /**
+ * Clone the goal's acceptance criteria into the target scope, instruction
+ * documents and fixture resources included: criteria, documents and files are
+ * scoped rows, and verification resolves them in the copy's scope, so the
+ * copy cannot keep pointing at the source's. Returned ids keep the source
+ * order; a criterion the caller can no longer read is skipped.
+ */
+ private copyCriteria = async (
+ db: LobeChatDatabase,
+ ids: string[],
+ targetWorkspaceId: string | undefined,
+ ): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ const sourceCriteria = new VerifyCriterionModel(db, this.userId, this.workspaceId);
+ const sourceDocuments = new DocumentModel(db, this.userId, this.workspaceId);
+ const sourceFiles = new FileModel(db, this.userId, this.workspaceId);
+ const targetCriteria = new VerifyCriterionModel(db, this.userId, targetWorkspaceId);
+ const targetDocuments = new DocumentModel(db, this.userId, targetWorkspaceId);
+
+ // Source resource id → its copy, so a resource shared by several criteria is copied once.
+ const copiedDocuments = new Map<string, string | undefined>();
+ const copiedFiles = new Map<string, string | undefined>();
+
+ const copyDocument = async (id: string): Promise<string | undefined> => {
+ if (copiedDocuments.has(id)) return copiedDocuments.get(id);
+ const document = await sourceDocuments.findById(id);
+ const copy = document
+ ? await targetDocuments.create({
+ content: document.content,
+ fileType: document.fileType,
+ source: document.source,
+ sourceType: document.sourceType,
+ title: document.title,
+ totalCharCount: document.totalCharCount,
+ totalLineCount: document.totalLineCount,
+ })
+ : undefined;
+ copiedDocuments.set(id, copy?.id);
+ return copy?.id;
+ };
+
+ // The row is copied; the blob is shared through its file hash.
+ const copyFile = async (id: string): Promise<string | undefined> => {
+ if (copiedFiles.has(id)) return copiedFiles.get(id);
+ const copy = (await sourceFiles.findById(id))
+ ? await sourceFiles.copyToWorkspace(id, targetWorkspaceId ?? null, this.userId)
+ : undefined;
+ copiedFiles.set(id, copy?.fileId);
+ return copy?.fileId;
+ };
+
+ const copyDefinition = async (
+ definition: VerifyCheckDefinition | null,
+ ): Promise<VerifyCheckDefinition | null> => {
+ if (!definition?.fixtures?.length) return definition;
+ const fixtures = [];
+ for (const fixture of definition.fixtures) {
+ const { resource } = fixture;
+ if (!resource) {
+ fixtures.push(fixture);
+ continue;
+ }
+ const id =
+ resource.type === 'document'
+ ? await copyDocument(resource.id)
+ : await copyFile(resource.id);
+ // A resource the caller can no longer read is dropped from the fixture
+ // rather than left pointing into the source scope.
+ fixtures.push(
+ id ? { ...fixture, resource: { ...resource, id } } : { ...fixture, resource: undefined },
+ );
+ }
+ return { ...definition, fixtures };
+ };
+
+ const rows = new Map((await sourceCriteria.findByIds(ids)).map((row) => [row.id, row]));
+ const copied: string[] = [];
+ for (const id of ids) {
+ const row = rows.get(id);
+ if (!row) continue;
+ const documentId = row.documentId ? await copyDocument(row.documentId) : undefined;
+ const criterion = await targetCriteria.create({
+ definition: await copyDefinition(row.definition),
+ description: row.description,
+ documentId: documentId ?? null,
+ onFail: row.onFail,
+ required: row.required,
+ tags: row.tags,
+ title: row.title,
+ verifierConfig: row.verifierConfig,
+ verifierType: row.verifierType,
+ });
+ copied.push(criterion.id);
+ }
+ return copied;
+ };
+}
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index caf22de3af9..b96a47e7a39 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "العمل المشار إليه غير متاح",
"goalList.acceptanceProgress": "{{passed}}/{{total}} تم اجتيازها",
"goalList.agentRuns": "{{count}} تشغيلات",
+ "goalList.contextMenu.copyConfirm": "نسخ",
+ "goalList.contextMenu.copyDescription": "ينسخ الهدف وميزانيته ومعايير القبول كمسودة جديدة. لا يتم نسخ التقدم والمهام والوكيل؛ اختر وكيلاً هناك وابدأ.",
+ "goalList.contextMenu.copyFailed": "فشل في نسخ الهدف",
+ "goalList.contextMenu.copySuccess": "تم نسخ الهدف",
+ "goalList.contextMenu.copyTitle": "نسخ الهدف",
"goalList.empty": "لا توجد أهداف حتى الآن",
"goalList.findings": "{{count}} نتائج",
"goalList.loadError": "تعذر تحميل الأهداف.",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 785875735b0..51423aa3456 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Реферираната работа не е налична",
"goalList.acceptanceProgress": "{{passed}}/{{total}} преминати",
"goalList.agentRuns": "{{count}} изпълнения",
+ "goalList.contextMenu.copyConfirm": "Копирай",
+ "goalList.contextMenu.copyDescription": "Копира целта, бюджета и критериите за приемане като нова чернова. Напредъкът, задачите и агентът не се копират; изберете агент там и започнете.",
+ "goalList.contextMenu.copyFailed": "Неуспешно копиране на целта",
+ "goalList.contextMenu.copySuccess": "Целта е копирана",
+ "goalList.contextMenu.copyTitle": "Копирай целта",
"goalList.empty": "Все още няма цели",
"goalList.findings": "{{count}} находки",
"goalList.loadError": "Неуспешно зареждане на целите.",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 65baa2f87ce..acb486260ba 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Referenzierte Arbeit ist nicht verfügbar",
"goalList.acceptanceProgress": "{{passed}}/{{total}} bestanden",
"goalList.agentRuns": "{{count}} Ausführungen",
+ "goalList.contextMenu.copyConfirm": "Kopieren",
+ "goalList.contextMenu.copyDescription": "Kopiert das Ziel, sein Budget und die Akzeptanzkriterien als neuen Entwurf. Fortschritt, Aufgaben und der Agent werden nicht kopiert; wählen Sie dort einen Agenten aus und starten Sie ihn.",
+ "goalList.contextMenu.copyFailed": "Ziel konnte nicht kopiert werden",
+ "goalList.contextMenu.copySuccess": "Ziel kopiert",
+ "goalList.contextMenu.copyTitle": "Ziel kopieren",
"goalList.empty": "Noch keine Ziele",
"goalList.findings": "{{count}} Ergebnisse",
"goalList.loadError": "Ziele konnten nicht geladen werden.",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 5b640c0b953..094f3ba60a1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Referenced work is unavailable",
"goalList.acceptanceProgress": "{{passed}}/{{total}} passed",
"goalList.agentRuns": "{{count}} runs",
+ "goalList.contextMenu.copyConfirm": "Copy",
+ "goalList.contextMenu.copyDescription": "Copies the goal, its budget and acceptance criteria as a new draft. Progress, tasks and the agent are not copied; pick an agent there and start it.",
+ "goalList.contextMenu.copyFailed": "Failed to copy goal",
+ "goalList.contextMenu.copySuccess": "Goal copied",
+ "goalList.contextMenu.copyTitle": "Copy goal",
"goalList.empty": "No goals yet",
"goalList.findings": "{{count}} findings",
"goalList.loadError": "Could not load goals",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 7445e7f2163..6ce6986a690 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "El trabajo referenciado no está disponible",
"goalList.acceptanceProgress": "{{passed}}/{{total}} aprobados",
"goalList.agentRuns": "{{count}} ejecuciones",
+ "goalList.contextMenu.copyConfirm": "Copiar",
+ "goalList.contextMenu.copyDescription": "Copia el objetivo, su presupuesto y criterios de aceptación como un nuevo borrador. El progreso, las tareas y el agente no se copian; selecciona un agente allí y comienza.",
+ "goalList.contextMenu.copyFailed": "Error al copiar el objetivo",
+ "goalList.contextMenu.copySuccess": "Objetivo copiado",
+ "goalList.contextMenu.copyTitle": "Copiar objetivo",
"goalList.empty": "Aún no hay objetivos",
"goalList.findings": "{{count}} hallazgos",
"goalList.loadError": "No se pudieron cargar los objetivos.",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 221986296a4..db4d7eb9cc3 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "کار ارجاع شده در دسترس نیست",
"goalList.acceptanceProgress": "{{passed}}/{{total}} پذیرفته شده",
"goalList.agentRuns": "{{count}} اجرا",
+ "goalList.contextMenu.copyConfirm": "کپی",
+ "goalList.contextMenu.copyDescription": "هدف، بودجه و معیارهای پذیرش را به‌عنوان یک پیش‌نویس جدید کپی می‌کند. پیشرفت، وظایف و عامل کپی نمی‌شوند؛ یک عامل را در آنجا انتخاب کنید و شروع کنید.",
+ "goalList.contextMenu.copyFailed": "کپی کردن هدف ناموفق بود",
+ "goalList.contextMenu.copySuccess": "هدف کپی شد",
+ "goalList.contextMenu.copyTitle": "کپی هدف",
"goalList.empty": "هنوز هدفی وجود ندارد",
"goalList.findings": "{{count}} یافته",
"goalList.loadError": "بارگذاری اهداف امکان‌پذیر نیست.",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 9f51cb0c8ed..bbff43f6c29 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Travail référencé indisponible",
"goalList.acceptanceProgress": "{{passed}}/{{total}} validés",
"goalList.agentRuns": "{{count}} exécutions",
+ "goalList.contextMenu.copyConfirm": "Copier",
+ "goalList.contextMenu.copyDescription": "Copie l'objectif, son budget et les critères d'acceptation en tant que nouveau brouillon. Les progrès, les tâches et l'agent ne sont pas copiés ; choisissez un agent là-bas et commencez.",
+ "goalList.contextMenu.copyFailed": "Échec de la copie de l'objectif",
+ "goalList.contextMenu.copySuccess": "Objectif copié",
+ "goalList.contextMenu.copyTitle": "Copier l'objectif",
"goalList.empty": "Aucun objectif pour le moment",
"goalList.findings": "{{count}} résultats",
"goalList.loadError": "Impossible de charger les objectifs.",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 21215af07db..e26ee5af68d 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Lavoro referenziato non disponibile",
"goalList.acceptanceProgress": "{{passed}}/{{total}} superati",
"goalList.agentRuns": "{{count}} esecuzioni",
+ "goalList.contextMenu.copyConfirm": "Copia",
+ "goalList.contextMenu.copyDescription": "Copia l'obiettivo, il budget e i criteri di accettazione come una nuova bozza. I progressi, le attività e l'agente non vengono copiati; seleziona un agente lì e avvialo.",
+ "goalList.contextMenu.copyFailed": "Copia dell'obiettivo non riuscita",
+ "goalList.contextMenu.copySuccess": "Obiettivo copiato",
+ "goalList.contextMenu.copyTitle": "Copia obiettivo",
"goalList.empty": "Ancora nessun obiettivo",
"goalList.findings": "{{count}} risultati",
"goalList.loadError": "Impossibile caricare gli obiettivi.",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 3b95824af16..b45280c51e4 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "参照された作業は利用できません",
"goalList.acceptanceProgress": "{{passed}}/{{total}} 合格",
"goalList.agentRuns": "{{count}} 実行",
+ "goalList.contextMenu.copyConfirm": "コピー",
+ "goalList.contextMenu.copyDescription": "目標、その予算、受け入れ基準を新しいドラフトとしてコピーします。進捗、タスク、エージェントはコピーされません。そこでエージェントを選択して開始してください。",
+ "goalList.contextMenu.copyFailed": "目標のコピーに失敗しました",
+ "goalList.contextMenu.copySuccess": "目標がコピーされました",
+ "goalList.contextMenu.copyTitle": "目標をコピー",
"goalList.empty": "まだ目標がありません",
"goalList.findings": "{{count}} 件の発見",
"goalList.loadError": "目標を読み込めませんでした。",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index 619ed97b824..8f87f20eb07 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "참조된 작업을 사용할 수 없음",
"goalList.acceptanceProgress": "{{passed}}/{{total}} 통과",
"goalList.agentRuns": "{{count}} 실행",
+ "goalList.contextMenu.copyConfirm": "복사",
+ "goalList.contextMenu.copyDescription": "목표, 예산 및 수락 기준을 새 초안으로 복사합니다. 진행 상황, 작업 및 에이전트는 복사되지 않습니다. 거기에서 에이전트를 선택하고 시작하세요.",
+ "goalList.contextMenu.copyFailed": "목표 복사 실패",
+ "goalList.contextMenu.copySuccess": "목표 복사 완료",
+ "goalList.contextMenu.copyTitle": "목표 복사",
"goalList.empty": "아직 목표가 없습니다",
"goalList.findings": "{{count}} 발견",
"goalList.loadError": "목표를 로드할 수 없습니다.",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 6f9801d8980..5fef35896c4 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Verwezen werk is niet beschikbaar",
"goalList.acceptanceProgress": "{{passed}}/{{total}} geslaagd",
"goalList.agentRuns": "{{count}} uitvoeringen",
+ "goalList.contextMenu.copyConfirm": "Kopiëren",
+ "goalList.contextMenu.copyDescription": "Kopieert het doel, het budget en de acceptatiecriteria als een nieuw concept. Voortgang, taken en de agent worden niet gekopieerd; kies daar een agent en start het.",
+ "goalList.contextMenu.copyFailed": "Doel kopiëren mislukt",
+ "goalList.contextMenu.copySuccess": "Doel gekopieerd",
+ "goalList.contextMenu.copyTitle": "Doel kopiëren",
"goalList.empty": "Nog geen doelen",
"goalList.findings": "{{count}} bevindingen",
"goalList.loadError": "Kon doelen niet laden.",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 95985768a10..693e6a4a51e 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Odwołana praca jest niedostępna",
"goalList.acceptanceProgress": "{{passed}}/{{total}} zaliczone",
"goalList.agentRuns": "{{count}} uruchomień",
+ "goalList.contextMenu.copyConfirm": "Kopiuj",
+ "goalList.contextMenu.copyDescription": "Kopiuje cel, jego budżet i kryteria akceptacji jako nowy szkic. Postęp, zadania i agent nie są kopiowane; wybierz agenta tam i rozpocznij.",
+ "goalList.contextMenu.copyFailed": "Nie udało się skopiować celu",
+ "goalList.contextMenu.copySuccess": "Cel skopiowany",
+ "goalList.contextMenu.copyTitle": "Kopiuj cel",
"goalList.empty": "Brak celów",
"goalList.findings": "{{count}} ustaleń",
"goalList.loadError": "Nie udało się załadować celów.",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index a561af14424..15a02e299cf 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Trabalho referenciado está indisponível",
"goalList.acceptanceProgress": "{{passed}}/{{total}} aprovados",
"goalList.agentRuns": "{{count}} execuções",
+ "goalList.contextMenu.copyConfirm": "Copiar",
+ "goalList.contextMenu.copyDescription": "Copia o objetivo, seu orçamento e os critérios de aceitação como um novo rascunho. Progresso, tarefas e o agente não são copiados; escolha um agente lá e inicie.",
+ "goalList.contextMenu.copyFailed": "Falha ao copiar o objetivo",
+ "goalList.contextMenu.copySuccess": "Objetivo copiado",
+ "goalList.contextMenu.copyTitle": "Copiar objetivo",
"goalList.empty": "Ainda não há objetivos",
"goalList.findings": "{{count}} descobertas",
"goalList.loadError": "Não foi possível carregar os objetivos.",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 3c4a099e390..ab38d0a3f8f 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Ссылаемая работа недоступна",
"goalList.acceptanceProgress": "{{passed}}/{{total}} пройдено",
"goalList.agentRuns": "{{count}} запусков",
+ "goalList.contextMenu.copyConfirm": "Копировать",
+ "goalList.contextMenu.copyDescription": "Копирует цель, её бюджет и критерии приёма как новый черновик. Прогресс, задачи и агент не копируются; выберите агента там и начните.",
+ "goalList.contextMenu.copyFailed": "Не удалось скопировать цель",
+ "goalList.contextMenu.copySuccess": "Цель скопирована",
+ "goalList.contextMenu.copyTitle": "Копировать цель",
"goalList.empty": "Цели пока отсутствуют",
"goalList.findings": "{{count}} находок",
"goalList.loadError": "Не удалось загрузить цели.",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index 46f00f4a0ed..e480fc6c3fd 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Referans verilen çalışma mevcut değil",
"goalList.acceptanceProgress": "{{passed}}/{{total}} geçti",
"goalList.agentRuns": "{{count}} çalışma",
+ "goalList.contextMenu.copyConfirm": "Kopyala",
+ "goalList.contextMenu.copyDescription": "Hedefi, bütçesini ve kabul kriterlerini yeni bir taslak olarak kopyalar. İlerleme, görevler ve ajan kopyalanmaz; orada bir ajan seçin ve başlatın.",
+ "goalList.contextMenu.copyFailed": "Hedef kopyalanamadı",
+ "goalList.contextMenu.copySuccess": "Hedef kopyalandı",
+ "goalList.contextMenu.copyTitle": "Hedefi kopyala",
"goalList.empty": "Henüz hedef yok",
"goalList.findings": "{{count}} bulgu",
"goalList.loadError": "Hedefler yüklenemedi.",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 2c82a22afe3..8bb6e2cee08 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "Công việc được tham chiếu không khả dụng",
"goalList.acceptanceProgress": "{{passed}}/{{total}} đã vượt qua",
"goalList.agentRuns": "{{count}} lần chạy",
+ "goalList.contextMenu.copyConfirm": "Sao chép",
+ "goalList.contextMenu.copyDescription": "Sao chép mục tiêu, ngân sách và tiêu chí chấp nhận như một bản nháp mới. Tiến độ, nhiệm vụ và agent không được sao chép; chọn một agent ở đó và bắt đầu.",
+ "goalList.contextMenu.copyFailed": "Không thể sao chép mục tiêu",
+ "goalList.contextMenu.copySuccess": "Mục tiêu đã được sao chép",
+ "goalList.contextMenu.copyTitle": "Sao chép mục tiêu",
"goalList.empty": "Chưa có mục tiêu",
"goalList.findings": "{{count}} phát hiện",
"goalList.loadError": "Không thể tải mục tiêu.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 224ca8731cf..4c437d92b70 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "引用的产物当前不可访问",
"goalList.acceptanceProgress": "已通过 {{passed}}/{{total}}",
"goalList.agentRuns": "{{count}} 次运行",
+ "goalList.contextMenu.copyConfirm": "复制",
+ "goalList.contextMenu.copyDescription": "将目标及其预算和验收标准复制为一个新的草稿。进度、任务和智能体不会复制,请在目标位置选择智能体后再启动。",
+ "goalList.contextMenu.copyFailed": "复制目标失败",
+ "goalList.contextMenu.copySuccess": "目标已复制",
+ "goalList.contextMenu.copyTitle": "复制目标",
"goalList.empty": "暂无目标",
"goalList.findings": "{{count}} 条结论",
"goalList.loadError": "无法加载目标",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index ae754b9fd77..9f9d4d090a2 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -710,6 +710,11 @@
"goalExperiment.unavailableInput": "引用的工作不可用",
"goalList.acceptanceProgress": "{{passed}}/{{total}} 已通過",
"goalList.agentRuns": "{{count}} 次執行",
+ "goalList.contextMenu.copyConfirm": "複製",
+ "goalList.contextMenu.copyDescription": "將目標、預算和接受標準複製為新的草稿。進度、任務和代理人不會被複製;請在那裡選擇代理人並開始。",
+ "goalList.contextMenu.copyFailed": "目標複製失敗",
+ "goalList.contextMenu.copySuccess": "目標已複製",
+ "goalList.contextMenu.copyTitle": "複製目標",
"goalList.empty": "尚無目標",
"goalList.findings": "{{count}} 項發現",
"goalList.loadError": "無法載入目標。",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 49fe02082d8..b96253ca2fb 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2329,6 +2329,12 @@ export default {
'goalEmpty.title': 'Chase goals without limits',
'goalList.acceptanceProgress': '{{passed}}/{{total}} passed',
'goalList.agentRuns': '{{count}} runs',
+ 'goalList.contextMenu.copyConfirm': 'Copy',
+ 'goalList.contextMenu.copyDescription':
+ 'Copies the goal, its budget and acceptance criteria as a new draft. Progress, tasks and the agent are not copied; pick an agent there and start it.',
+ 'goalList.contextMenu.copyFailed': 'Failed to copy goal',
+ 'goalList.contextMenu.copySuccess': 'Goal copied',
+ 'goalList.contextMenu.copyTitle': 'Copy goal',
'goalList.empty': 'No goals yet',
'goalList.taskProgress': '{{done}}/{{total}} tasks done',
'goalList.findings': '{{count}} findings',
diff --git a/src/business/client/hooks/useGoalTransferMenuItem.ts b/src/business/client/hooks/useGoalTransferMenuItem.ts
new file mode 100644
index 00000000000..76f7878ffdc
--- /dev/null
+++ b/src/business/client/hooks/useGoalTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import type { ItemType } from '@lobehub/ui';
+
+export const useGoalTransferMenuItem = (_goalId?: string): ItemType[] | null => null;
diff --git a/src/features/AgentGoals/useGoalMenuItems.test.ts b/src/features/AgentGoals/useGoalMenuItems.test.ts
index a9c7ef73f51..b4d00502d07 100644
--- a/src/features/AgentGoals/useGoalMenuItems.test.ts
+++ b/src/features/AgentGoals/useGoalMenuItems.test.ts
@@ -15,6 +15,11 @@ const mocks = vi.hoisted(() => ({
resumeGoal: vi.fn(),
startGoal: vi.fn(),
},
+ transferItems: null as DropdownItem[] | null,
+}));
+
+vi.mock('@/business/client/hooks/useGoalTransferMenuItem', () => ({
+ useGoalTransferMenuItem: () => mocks.transferItems,
}));
vi.mock('@/store/goal', () => ({
@@ -41,6 +46,7 @@ const pickStatus = (items: DropdownItem[], next: string) => {
describe('useGoalItemMenu', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.transferItems = null;
mocks.store.pauseGoal.mockResolvedValue(undefined);
mocks.store.resumeGoal.mockResolvedValue(undefined);
});
@@ -79,4 +85,14 @@ describe('useGoalItemMenu', () => {
// A host-supplied onDeleted replaces the redirect to the goal list.
expect(mocks.deleteOptions?.onDeleted).toBeTypeOf('function');
});
+
+ it('places the cross-workspace copy entry above the delete group', () => {
+ mocks.transferItems = [{ key: 'copy-goal', label: 'Copy to…' }];
+ const { result } = renderHook(() =>
+ useGoalItemMenu({ agentId: 'agt_1', goal, routeAgentId: 'agt_1' }),
+ );
+
+ const keys = result.current.map((item) => (item && 'key' in item ? item.key : item?.type));
+ expect(keys.slice(-4)).toEqual(['copyLink', 'copy-goal', 'divider', 'delete']);
+ });
});
diff --git a/src/features/AgentGoals/useGoalMenuItems.tsx b/src/features/AgentGoals/useGoalMenuItems.tsx
index da98f7ec114..d4d71148628 100644
--- a/src/features/AgentGoals/useGoalMenuItems.tsx
+++ b/src/features/AgentGoals/useGoalMenuItems.tsx
@@ -3,6 +3,7 @@ import { CircleDashedIcon, CopyIcon, LinkIcon, TrashIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useGoalTransferMenuItem } from '@/business/client/hooks/useGoalTransferMenuItem';
import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
import { renderMenuCheck } from '@/features/AgentTasks/features/menuExtra';
import { usePermission } from '@/hooks/usePermission';
@@ -52,6 +53,7 @@ export const useGoalMenuItems = ({
const resumeGoal = useGoalStore((s) => s.resumeGoal);
const startGoal = useGoalStore((s) => s.startGoal);
const closeGoal = useGoalStore((s) => s.closeGoal);
+ const transferItems = useGoalTransferMenuItem(goalId) as DropdownItem[] | null;
const current = toManualStatus(status);
@@ -118,6 +120,7 @@ export const useGoalMenuItems = ({
toast.success(t('taskList.contextMenu.copyLinkSuccess'));
},
},
+ ...(transferItems ?? []),
{ type: 'divider' },
{
danger: true,
@@ -128,7 +131,18 @@ export const useGoalMenuItems = ({
onClick: confirmDelete,
},
],
- [canClose, canEditTask, changeStatus, confirmDelete, current, goalId, shareUrl, status, t],
+ [
+ canClose,
+ canEditTask,
+ changeStatus,
+ confirmDelete,
+ current,
+ goalId,
+ shareUrl,
+ status,
+ t,
+ transferItems,
+ ],
);
};
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 748333b0a34..21be33c25e6 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -111,6 +111,13 @@ class GoalService {
observation: { key: string; observedAt?: Date; title?: string; unit?: string; value: number },
) => lambdaClient.goal.recordObservation.mutate({ id, ...observation });
+ /**
+ * Copy the goal's definition into personal (`null`) or a workspace as a new
+ * draft; its graph progress and Tasks stay behind.
+ */
+ copyGoalToWorkspace = async (id: string, targetWorkspaceId: string | null) =>
+ lambdaClient.goal.copyGoalToWorkspace.mutate({ id, targetWorkspaceId });
+
/** Delete a goal and its graph. The dispatched Work Tasks are left in place. */
delete = async (id: string) => lambdaClient.goal.delete.mutate({ id });