Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

58.0 KB
Raw Blame
import { AIProviderName, apId, Permission, RoleType } from '@activepieces/core-utils'
import { Agent, AgentIcon, AgentPieceProps, AgentRunSource, AgentToolType, AgentVisibility, AI_PIECE_NAME, ColorName, DefaultProjectRole, FlowActionType, FlowStatus, FlowTriggerType, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
import { SelectQueryBuilder } from 'typeorm'
import { agentConversationService } from '../../../../src/app/ee/agent/agent-conversation-service'
import { db } from '../../../helpers/db'
import { createMockFlow, createMockFlowVersion, createMockFolder, createMockProject, createMockProjectRole, mockAndSaveAIProvider } from '../../../helpers/mocks'
import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'

let app: FastifyInstance

const agentBody = (projectId: string, overrides: Record<string, unknown> = {}) => ({
    projectId,
    displayName: 'Marketing agent',
    icon: AgentIcon.SPARKLES,
    color: ColorName.PURPLE,
    draft: {
        instructions: 'Draft launch posts.',
        provider: null,
        modelName: null,
        maxSteps: 5,
        tools: [],
        structuredOutput: [],
    },
    ...overrides,
})

async function context(): Promise<TestContext> {
    return createTestContext(app, { plan: { agentsEnabled: true } })
}

async function createAgent(ctx: TestContext, overrides: Record<string, unknown> = {}) {
    const response = await ctx.post('/v1/agents', agentBody(ctx.project.id, overrides))
    expect(response.statusCode).toBe(StatusCodes.CREATED)
    return response.json()
}

async function publishFlowRunningAgent({ projectId, externalId, displayName, publish = true }: { projectId: string, externalId: string, displayName: string, publish?: boolean }): Promise<string> {
    const flow = createMockFlow({ projectId, status: FlowStatus.ENABLED })
    await db.save('flow', flow)
    const version = createMockFlowVersion({
        flowId: flow.id,
        displayName,
        state: FlowVersionState.LOCKED,
        agentIds: [externalId],
    })
    await db.save('flow_version', version)
    if (publish) {
        await db.update('flow', flow.id, { publishedVersionId: version.id })
    }
    return flow.id
}

beforeAll(async () => {
    app = await setupTestEnvironment()
})

afterAll(async () => {
    await teardownTestEnvironment()
})

describe('agent crud', () => {
    it('fills in the platform model when the request names none', async () => {
        const ctx = await context()
        await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })

        const agent = await createAgent(ctx)

        expect(agent.draft.modelName).toBe('anthropic/claude-sonnet-4.6')
        expect(agent.draft.provider).toBe(AIProviderName.OPENROUTER)
    })

    it('fills in the default tier id, not the model behind it, when the platform runs on Activepieces credits', async () => {
        process.env.AP_OPENROUTER_PROVISION_KEY = 'test-provision-key'
        try {
            const ctx = await context()
            await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES, enabledForChat: true })

            const agent = await createAgent(ctx)

            expect(agent.draft.modelName).toBe('smart')
            expect(agent.draft.provider).toBe(AIProviderName.ACTIVEPIECES)
        }
        finally {
            delete process.env.AP_OPENROUTER_PROVISION_KEY
        }
    })

    it('fills in the default tier on a fresh platform whose Activepieces credits row was never listed', async () => {
        process.env.AP_OPENROUTER_PROVISION_KEY = 'test-provision-key'
        try {
            const ctx = await context()

            const agent = await createAgent(ctx)

            expect(agent.draft.modelName).toBe('smart')
            expect(agent.draft.provider).toBe(AIProviderName.ACTIVEPIECES)
        }
        finally {
            delete process.env.AP_OPENROUTER_PROVISION_KEY
        }
    })

    it('keeps a model the request did name, even where a default was available', async () => {
        const ctx = await context()
        await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })

        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, provider: AIProviderName.OPENROUTER, modelName: 'anthropic/claude-haiku-4.5' } })

        expect(agent.draft.modelName).toBe('anthropic/claude-haiku-4.5')
    })

    it('pins the default model to the chat key, so a key added later does not take the agent over', async () => {
        const ctx = await context()
        const chatKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })

        const agent = await createAgent(ctx)
        await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, displayName: 'Second key' })
        const reread = await ctx.get(`/v1/agents/${agent.id}`, { projectId: ctx.project.id })

        expect(agent.draft.providerConfigId).toBe(chatKey.id)
        expect(reread.json().draft.providerConfigId).toBe(chatKey.id)
    })

    it('picks a default model the pinned chat key allows', async () => {
        const ctx = await context()
        await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, enabledForChat: true, modelScope: 'selected', modelIds: ['gpt-4.1-mini'] })

        const agent = await createAgent(ctx)

        expect(agent.draft.modelName).toBe('gpt-4.1-mini')
    })

    it('pins a saved model that names no key to the key a run would use today', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })

        const response = await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agent.draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: null } })

        expect(response.statusCode).toBe(StatusCodes.OK)
        expect(response.json().draft.providerConfigId).toBe(key.id)
    })

    it('leaves the model empty where the platform has no chat provider', async () => {
        const ctx = await context()

        const agent = await createAgent(ctx)

        expect(agent.draft.modelName).toBeNull()
    })

    it('creates an agent owned by the caller, in draft, unpublished', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        expect(agent.ownerId).toBe(ctx.user.id)
        expect(agent.projectId).toBe(ctx.project.id)
        expect(agent.visibility).toBe(AgentVisibility.PROJECT)
        expect(agent.published).toBeNull()
        expect(agent.draft.instructions).toBe('Draft launch posts.')
    })

    it('updates only the fields the request names', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        const response = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed' })

        expect(response.statusCode).toBe(StatusCodes.OK)
        expect(response.json().displayName).toBe('Renamed')
        expect(response.json().draft.instructions).toBe('Draft launch posts.')
    })

    it('deletes an agent', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)
        expect((await ctx.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NOT_FOUND)
    })

    it('tells you which published flows use an agent before you try to delete it', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const flowId = await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly digest' })

        const withUsage = (await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })).json()
        const withoutUsage = (await ctx.get(`/v1/agents/${agent.id}`)).json()

        expect(withUsage.publishedFlowsUsingAgent).toStrictEqual({ total: 1, names: ['Nightly digest'], flows: [{ id: flowId, displayName: 'Nightly digest' }] })
        expect(withoutUsage.publishedFlowsUsingAgent).toBeUndefined()
    })

    it('reports no usage for an agent no published flow runs', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        const response = await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })

        expect(response.json().publishedFlowsUsingAgent).toStrictEqual({ total: 0, names: [], flows: [] })
    })

    it('refuses an editor who did not create the agent, because deleting takes other people\'s conversations with it', async () => {
        const owner = await context()
        const editor = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(owner)

        expect((await editor.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await owner.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.OK)
    })

    it('takes the conversations held with the agent, whoever held them', async () => {
        const owner = await context()
        const editor = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(owner)
        const conversations = [owner, editor].map((ctx) => ({
            id: apId(),
            platformId: owner.platform.id,
            projectId: owner.project.id,
            userId: ctx.user.id,
            agentId: agent.id,
            source: AgentRunSource.AGENT,
            messages: [],
            uiMessages: [],
        }))
        await db.save('agent_conversation', conversations)

        expect((await owner.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)
        for (const conversation of conversations) {
            expect(await db.findOneBy('agent_conversation', { id: conversation.id })).toBeNull()
        }
    })

    it('refuses to delete an agent a published flow still runs, and names the flow', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly digest' })

        const response = await ctx.delete(`/v1/agents/${agent.id}`)

        expect(response.statusCode).toBe(StatusCodes.CONFLICT)
        expect(JSON.stringify(response.json())).toContain('Nightly digest')
        expect((await ctx.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.OK)
    })

    it('locks the agent row FOR UPDATE when deleting, so a publish holding it FOR SHARE cannot slip a reference past the guard', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const setLock = vi.spyOn(SelectQueryBuilder.prototype, 'setLock')

        expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)

        expect(setLock.mock.calls.map(([mode]) => mode)).toContain('pessimistic_write')
        setLock.mockRestore()
    })

    it('locks the agent row FOR SHARE when a flow that uses it is published, so a delete waits for the publish', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await db.update('agent', agent.id, { published: agent.draft })
        const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED })
        await db.save('flow', flow)
        const version = createMockFlowVersion({ flowId: flow.id, updatedBy: ctx.user.id, state: FlowVersionState.DRAFT, agentIds: [agent.externalId], trigger: triggerRunningAgent(agent.externalId) })
        await db.save('flow_version', version)
        const setLock = vi.spyOn(SelectQueryBuilder.prototype, 'setLock')

        const published = await ctx.post(`/v1/flows/${flow.id}`, { type: 'LOCK_AND_PUBLISH', request: { status: FlowStatus.DISABLED } })

        expect(published.statusCode).toBe(StatusCodes.OK)
        expect(setLock.mock.calls.map(([mode]) => mode)).toContain('pessimistic_read')
        const publishedVersion = await db.findOneByOrFail('flow_version', { id: version.id }) as { agentIds: string[] }
        expect(publishedVersion.agentIds).toStrictEqual([agent.externalId])
        setLock.mockRestore()
    })

    it('names three flows and stops counting, so the refusal cannot grow without bound', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const externalId = agent.externalId
        for (const name of ['Flow A', 'Flow B', 'Flow C', 'Flow D', 'Flow E']) {
            await publishFlowRunningAgent({ projectId: ctx.project.id, externalId, displayName: name })
        }

        const message = JSON.stringify((await ctx.delete(`/v1/agents/${agent.id}`)).json())

        expect(message).toContain('5 published flows (Flow A, Flow B, Flow C, and 2 more)')
        expect(message).not.toContain('Flow D')
    })

    it('lists every flow that uses an agent for the delete dialog, so each one can be opened from it', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        for (const name of ['Flow A', 'Flow B', 'Flow C', 'Flow D', 'Flow E']) {
            await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: name })
        }

        const usage = (await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })).json().publishedFlowsUsingAgent

        expect(usage.total).toBe(5)
        expect(usage.flows.map((flow: { displayName: string }) => flow.displayName)).toStrictEqual(['Flow A', 'Flow B', 'Flow C', 'Flow D', 'Flow E'])
    })

    it('counts the flows instead of naming them for a caller who cannot read flows', async () => {
        const owner = await context()
        const role = createMockProjectRole({
            platformId: owner.platform.id,
            name: `agent-writer-${apId()}`,
            type: RoleType.CUSTOM,
            permissions: [Permission.READ_AGENT, Permission.WRITE_AGENT],
        })
        await db.save('project_role', role)
        const writer = await createMemberContext(app, owner, { projectRole: role.name })
        const agent = await createAgent(writer)
        await publishFlowRunningAgent({ projectId: owner.project.id, externalId: agent.externalId, displayName: 'Payroll run' })

        const response = await writer.delete(`/v1/agents/${agent.id}`)

        expect(response.statusCode).toBe(StatusCodes.CONFLICT)
        expect(JSON.stringify(response.json())).not.toContain('Payroll run')
        expect(JSON.stringify(response.json())).toContain('running in 1 published flow.')
    })

    it('deletes an agent whose only reference is an unpublished draft version', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Draft only', publish: false })

        expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)
    })

    it('ignores a published flow in another project, which cannot be running this agent', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const other = await context()
        await publishFlowRunningAgent({ projectId: other.project.id, externalId: agent.externalId, displayName: 'Someone elses flow' })

        expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)
    })
})

describe('agent publish', () => {
    it('copies the draft to published, so a flow step has something to run', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        const response = await ctx.post(`/v1/agents/${agent.id}/publish`)

        expect(response.statusCode).toBe(StatusCodes.OK)
        expect(response.json().published).toStrictEqual(response.json().draft)
    })

    it('carries the published copy along when the draft is saved', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Rewritten.' } })

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.draft.instructions).toBe('Rewritten.')
        expect(after.published.instructions).toBe('Rewritten.')
    })

    it('publishes on the first save, so a flow can run an agent nobody published by hand', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        expect(agent.published).toBeNull()

        await ctx.post(`/v1/agents/${agent.id}`, { description: 'Now with a description.' })

        expect((await ctx.get(`/v1/agents/${agent.id}`)).json().published).not.toBeNull()
    })

    it('stages the draft without going live, so a change can be tested first', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await ctx.post(`/v1/agents/${agent.id}`, { description: 'Live now.' })
        const live = (await ctx.get(`/v1/agents/${agent.id}`)).json().published

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Only for the test run.' }, goLive: false })

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.draft.instructions).toBe('Only for the test run.')
        expect(after.published).toStrictEqual(live)
    })

    it.each([['explicitly true', true], ['absent', undefined]])(
        'publishes when goLive is %s, so every existing caller keeps working',
        async (_label, goLive) => {
            const ctx = await context()
            const agent = await createAgent(ctx)

            await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Should be live.' }, ...(goLive === undefined ? {} : { goLive }) })

            expect((await ctx.get(`/v1/agents/${agent.id}`)).json().published.instructions).toBe('Should be live.')
        })

    it('keeps published pinned to the same copy across repeated staging', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await ctx.post(`/v1/agents/${agent.id}`, { description: 'Live copy.' })
        const live = (await ctx.get(`/v1/agents/${agent.id}`)).json().published

        for (const attempt of ['first', 'second', 'third']) {
            await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: `Staged ${attempt}.` }, goLive: false })
        }

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.draft.instructions).toBe('Staged third.')
        expect(after.published).toStrictEqual(live)
    })

    it('stages against an agent nobody published yet without inventing a published copy', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        expect(agent.published).toBeNull()

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Only a draft.' }, goLive: false })

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.draft.instructions).toBe('Only a draft.')
        expect(after.published).toBeNull()
    })

    it('publishes the staged draft when the explicit publish route is used afterwards', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Staged for review.' }, goLive: false })
        await ctx.post(`/v1/agents/${agent.id}/publish`)

        expect((await ctx.get(`/v1/agents/${agent.id}`)).json().published.instructions).toBe('Staged for review.')
    })

    it('goes live on the next save, so staging is not a trap', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Staged.' }, goLive: false })
        await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Ready' })

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.published.instructions).toBe('Staged.')
    })

    it('publishes nothing while the instructions are empty, because there is nothing runnable to pin', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, instructions: '' } })

        await ctx.post(`/v1/agents/${agent.id}`, { description: 'Still empty.' })

        expect((await ctx.get(`/v1/agents/${agent.id}`)).json().published).toBeNull()
    })

    it.each([['spaces', '   '], ['tabs', '\t\t'], ['newlines', '\n\n'], ['empty', '']])(
        'refuses to publish an agent whose instructions are only %s',
        async (_kind, instructions) => {
            const ctx = await context()
            const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, instructions } })

            expect((await ctx.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.CONFLICT)
            expect((await ctx.get(`/v1/agents/${agent.id}`)).json().published).toBeNull()
        })

    it('keeps a rich config byte-for-byte through the copy', async () => {
        const ctx = await context()
        const draft = {
            instructions: 'Check the brand guide first.',
            provider: null,
            modelName: 'claude-sonnet-4-6',
            maxSteps: 7,
            tools: [],
            structuredOutput: [{ displayName: 'summary', type: 'text' }],
        }
        const agent = await createAgent(ctx, { draft })

        const published = (await ctx.post(`/v1/agents/${agent.id}/publish`)).json().published
        expect(published).toStrictEqual(draft)
    })

    it('republishes the newer draft, and is a no-op when nothing changed', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const first = (await ctx.post(`/v1/agents/${agent.id}/publish`)).json()
        const again = (await ctx.post(`/v1/agents/${agent.id}/publish`)).json()
        expect(again.published).toStrictEqual(first.published)

        await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agentBody(ctx.project.id).draft, instructions: 'Second version.' } })
        const third = (await ctx.post(`/v1/agents/${agent.id}/publish`)).json()
        expect(third.published.instructions).toBe('Second version.')
    })

    it('keeps the published config when the agent is edited afterwards', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await ctx.post(`/v1/agents/${agent.id}/publish`)

        await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed' })

        const after = (await ctx.get(`/v1/agents/${agent.id}`)).json()
        expect(after.displayName).toBe('Renamed')
        expect(after.published).not.toBeNull()
    })

    it('publishes a piece tool with its predefined input intact', async () => {
        const ctx = await context()
        const draft = {
            instructions: 'File the ticket.',
            provider: null,
            modelName: null,
            maxSteps: 3,
            tools: [{
                type: 'PIECE',
                toolName: 'create_issue',
                pieceMetadata: {
                    pieceName: '@activepieces/piece-github',
                    pieceVersion: '0.1.0',
                    actionName: 'create_issue',
                    predefinedInput: { fields: { title: { mode: 'choose-yourself', value: 'Bug' } } },
                },
            }],
            structuredOutput: [],
        }
        const agent = await createAgent(ctx, { draft })

        expect((await ctx.post(`/v1/agents/${agent.id}/publish`)).json().published).toStrictEqual(draft)
    })

    it('refuses instructions that are only a non-breaking space', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, instructions: '\u00a0' } })

        expect((await ctx.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.CONFLICT)
    })

    it('refuses to publish a restricted agent the caller cannot see', async () => {
        const owner = await context()
        const member = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(owner, { visibility: AgentVisibility.RESTRICTED })

        expect((await member.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.NOT_FOUND)
        expect((await owner.get(`/v1/agents/${agent.id}`)).json().published).toBeNull()
    })

    it('refuses a viewer, and an agent in another project', async () => {
        const owner = await context()
        const viewer = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.VIEWER })
        const stranger = await context()
        const agent = await createAgent(owner)

        expect((await viewer.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await stranger.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await owner.get(`/v1/agents/${agent.id}`)).json().published).toBeNull()
    })
})

describe('agent governance', () => {
    it('keeps a project admin able to see an agent an editor restricted', async () => {
        const owner = await context()
        const editor = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(editor)

        await editor.post(`/v1/agents/${agent.id}`, { visibility: AgentVisibility.RESTRICTED })

        expect((await owner.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.OK)
    })

    it('refuses to let a non-owner hide an agent from the rest of the project', async () => {
        const owner = await context()
        const editor = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const mine = await createAgent(owner)

        const response = await editor.post(`/v1/agents/${mine.id}`, { visibility: AgentVisibility.RESTRICTED })

        expect(response.statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await owner.get(`/v1/agents/${mine.id}`)).json().visibility).toBe(AgentVisibility.PROJECT)
    })

    it('lets an editor still rename an agent, so the gate is on sharing only', async () => {
        const owner = await context()
        const editor = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(owner)

        expect((await editor.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed' })).statusCode).toBe(StatusCodes.OK)
    })

    it('takes a published agent offline without destroying it', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        await ctx.post(`/v1/agents/${agent.id}/publish`)

        const response = await ctx.post(`/v1/agents/${agent.id}/unpublish`)

        expect(response.statusCode).toBe(StatusCodes.OK)
        expect(response.json().published).toBeNull()
        expect(response.json().draft.instructions).toBe('Draft launch posts.')
    })

    it('never returns a stored mcp credential to a reader', async () => {
        const ctx = await context()
        const draft = {
            instructions: 'Use the server.',
            tools: [{
                type: 'MCP',
                toolName: 'remote',
                serverUrl: 'https://mcp.example.com',
                protocol: 'streamable-http',
                auth: { type: 'api_key', apiKey: 'sk-live-SECRET', apiKeyHeader: 'x-api-key' },
            }],
        }
        const agent = await createAgent(ctx, { draft })

        expect((await ctx.get(`/v1/agents/${agent.id}`)).body).not.toContain('sk-live-SECRET')
        expect((await ctx.post(`/v1/agents/${agent.id}/publish`)).body).not.toContain('sk-live-SECRET')
        expect((await ctx.get('/v1/agents')).body).not.toContain('sk-live-SECRET')
    })

    it('keeps the stored credential usable after an unrelated edit', async () => {
        const ctx = await context()
        const draft = {
            instructions: 'Use the server.',
            tools: [{
                type: 'MCP',
                toolName: 'remote',
                serverUrl: 'https://mcp.example.com',
                protocol: 'streamable-http',
                auth: { type: 'api_key', apiKey: 'sk-live-SECRET', apiKeyHeader: 'x-api-key' },
            }],
        }
        const agent = await createAgent(ctx, { draft })

        await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed' })

        const stored = await db.findOneByOrFail<{ draft: { tools: { auth: { apiKey?: string } }[] } }>('agent', { id: agent.id })
        expect(stored.draft.tools[0].auth.apiKey).toBe('sk-live-SECRET')
    })

    it('refuses a config larger than an agent is allowed to be', async () => {
        const ctx = await context()
        const fields = Object.fromEntries(Array.from({ length: 4000 }, (_, index) => [`f${index}`, { mode: 'choose-yourself', value: 'x'.repeat(100) }]))
        const draft = {
            instructions: 'Big.',
            tools: [{
                type: 'PIECE',
                toolName: 'big',
                pieceMetadata: { pieceName: 'p', pieceVersion: '1.0.0', actionName: 'a', predefinedInput: { fields } },
            }],
        }

        expect((await ctx.post('/v1/agents', agentBody(ctx.project.id, { draft }))).statusCode).toBe(StatusCodes.BAD_REQUEST)
    })
})

describe('agent project isolation', () => {
    it.each([
        ['read', (ctx: TestContext, id: string) => ctx.get(`/v1/agents/${id}`)],
        ['update', (ctx: TestContext, id: string) => ctx.post(`/v1/agents/${id}`, { displayName: 'Hijacked' })],
        ['delete', (ctx: TestContext, id: string) => ctx.delete(`/v1/agents/${id}`)],
    ])('refuses to %s an agent belonging to another project, and leaves it untouched', async (_action, attempt) => {
        const owner = await context()
        const stranger = await context()
        const agent = await createAgent(owner)

        expect((await attempt(stranger, agent.id)).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await owner.get(`/v1/agents/${agent.id}`)).json().displayName).toBe('Marketing agent')
    })

    it('refuses to create an agent in a project the caller is not a member of', async () => {
        const owner = await context()
        const stranger = await context()

        expect((await stranger.post('/v1/agents', agentBody(owner.project.id))).statusCode).toBe(StatusCodes.FORBIDDEN)
    })

    it('lists enough for a card without shipping the config', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, tools: [] } })

        const listed = (await ctx.get('/v1/agents')).json().data.find((row: { id: string }) => row.id === agent.id)

        expect(listed.toolCount).toBe(0)
        expect(listed.toolPieceNames).toStrictEqual([])
        expect(listed.toolTypes).toStrictEqual([])
        expect(listed.draft).toBeUndefined()
        expect(listed.published).toBeUndefined()
    })

    it('never lists another project\'s agents', async () => {
        const owner = await context()
        const stranger = await context()
        await createAgent(owner)
        const own = await createAgent(stranger)

        const listed = (await stranger.get('/v1/agents')).json().data
        expect(listed.map((row: { id: string }) => row.id)).toStrictEqual([own.id])
    })
})

describe('agent sharing rules', () => {
    it('refuses to share with someone who is not in the project', async () => {
        const owner = await context()
        const outsider = await context()

        const response = await owner.post('/v1/agents', agentBody(owner.project.id, {
            visibility: AgentVisibility.RESTRICTED,
            sharedWithUserIds: [outsider.user.id],
        }))

        expect(response.statusCode).toBe(StatusCodes.CONFLICT)
    })

    it('drops the share list when the agent goes back to project-wide', async () => {
        const owner = await context()
        const member = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(owner, {
            visibility: AgentVisibility.RESTRICTED,
            sharedWithUserIds: [member.user.id],
        })

        const response = await owner.post(`/v1/agents/${agent.id}`, { visibility: AgentVisibility.PROJECT })

        expect(response.json().sharedWithUserIds).toStrictEqual([])
    })
})

describe('agent list across projects', () => {
    it('narrows to one project on request, and never widens to a project the caller cannot read', async () => {
        const owner = await context()
        const stranger = await context()
        const agent = await createAgent(owner)

        const narrowed = (await owner.get('/v1/agents', { projectId: owner.project.id })).json().data
        expect(narrowed.map((row: { id: string }) => row.id)).toStrictEqual([agent.id])

        const foreign = (await owner.get('/v1/agents', { projectId: stranger.project.id })).json().data
        expect(foreign).toStrictEqual([])
    })

    it('searches by name and by description, and leaves the rest out', async () => {
        const ctx = await context()
        const inbox = await createAgent(ctx, { displayName: 'Inbox triage' })
        const pricing = await createAgent(ctx, { displayName: 'Rival watch', description: 'Reads competitor pricing pages.' })
        await createAgent(ctx, { displayName: 'Meeting notes', description: 'Turns notes into follow-ups.' })

        const byName = (await ctx.get('/v1/agents', { search: 'inbox' })).json().data
        expect(byName.map((row: { id: string }) => row.id)).toStrictEqual([inbox.id])

        const byDescription = (await ctx.get('/v1/agents', { search: 'competitor' })).json().data
        expect(byDescription.map((row: { id: string }) => row.id)).toStrictEqual([pricing.id])

        const noMatch = (await ctx.get('/v1/agents', { search: 'nothing here' })).json().data
        expect(noMatch).toStrictEqual([])
    })

    it('lists the agents whose draft or published tools use one of the given connections', async () => {
        const ctx = await context()
        const pieceTool = (auth: string) => ({
            type: 'PIECE',
            toolName: 'create_issue',
            pieceMetadata: {
                pieceName: '@activepieces/piece-github',
                pieceVersion: '0.1.0',
                actionName: 'create_issue',
                predefinedInput: { auth, fields: {} },
            },
        })
        const usesInDraft = await createAgent(ctx, { displayName: 'Draft user', draft: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('{{connections[\'conn-a\']}}')] } })
        const usesInPublished = await createAgent(ctx, { displayName: 'Published user' })
        await db.update('agent', usesInPublished.id, { published: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('conn-b')] } })
        await createAgent(ctx, { displayName: 'Other connection', draft: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('conn-c')] } })

        const listed = (await ctx.get('/v1/agents', { connectionExternalIds: ['conn-a', 'conn-b'] })).json().data
        expect(listed.map((row: { id: string }) => row.id).sort()).toStrictEqual([usesInDraft.id, usesInPublished.id].sort())
    })

    it('sorts by name when asked, rather than by when it was touched', async () => {
        const ctx = await context()
        const apple = await createAgent(ctx, { displayName: 'Apple duty' })
        const zebra = await createAgent(ctx, { displayName: 'Zebra duty' })

        const byName = (await ctx.get('/v1/agents', { sort: 'name' })).json().data
        expect(byName.map((row: { id: string }) => row.id)).toStrictEqual([apple.id, zebra.id])

        // The newest first, which is the opposite order, so the two cannot both pass by accident.
        const byUpdated = (await ctx.get('/v1/agents', { sort: 'updated' })).json().data
        expect(byUpdated.map((row: { id: string }) => row.id)).toStrictEqual([zebra.id, apple.id])
    })

    it('walks every page with a cursor, so nothing is out of reach', async () => {
        const ctx = await context()
        const created = []
        for (const name of ['One', 'Two', 'Three']) {
            created.push((await createAgent(ctx, { displayName: `Page ${name}` })).id)
        }

        const seen: string[] = []
        let cursor: string | undefined = undefined
        for (let page = 0; page < 5; page++) {
            const body = (await ctx.get('/v1/agents', { limit: '1', ...(cursor === undefined ? {} : { cursor }) })).json()
            seen.push(...body.data.map((row: { id: string }) => row.id))
            if (!body.next) break
            cursor = body.next
        }

        expect(seen.sort()).toStrictEqual([...created].sort())
    })

    it('refuses a page size that would disable pagination', async () => {
        const ctx = await context()

        expect((await ctx.get('/v1/agents', { limit: '-1' })).statusCode).toBe(StatusCodes.BAD_REQUEST)
        expect((await ctx.get('/v1/agents', { limit: '1000000' })).statusCode).toBe(StatusCodes.BAD_REQUEST)
    })
})

describe('moving an agent to another project', () => {
    const secondProjectOf = async (ctx: TestContext) => {
        const project = createMockProject({
            ownerId: ctx.user.id,
            platformId: ctx.platform.id,
            displayName: 'Second project',
        })
        await db.save('project', project)
        return project
    }

    it('moves the agent, its conversations, and nothing else', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        const conversationId = apId()
        await db.save('agent_conversation', {
            id: conversationId,
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            platformId: ctx.platform.id,
            projectId: ctx.project.id,
            userId: ctx.user.id,
            agentId: agent.id,
            source: AgentRunSource.AGENT,
            messages: [],
            status: 'IDLE',
        })

        const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect(moved.statusCode).toBe(StatusCodes.OK)
        expect(moved.json().projectId).toBe(target.id)
        const inTarget = (await ctx.get('/v1/agents', { projectId: target.id })).json().data
        expect(inTarget.map((row: { id: string }) => row.id)).toStrictEqual([agent.id])
        const inSource = (await ctx.get('/v1/agents', { projectId: ctx.project.id })).json().data
        expect(inSource).toStrictEqual([])
        const row = await db.findOneByOrFail('agent_conversation', { id: conversationId })
        expect((row as { projectId: string }).projectId).toBe(target.id)
    })

    it('re-pins the model to a key the new project can use, so a moved agent keeps running', async () => {
        const ctx = await context()
        const target = await secondProjectOf(ctx)
        const sourceKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Source', projectScope: 'selected', projectIds: [ctx.project.id] })
        const targetKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Target', projectScope: 'selected', projectIds: [target.id] })
        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: sourceKey.id } })

        const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect(moved.statusCode).toBe(StatusCodes.OK)
        expect(moved.json().draft.providerConfigId).toBe(targetKey.id)
    })

    it('keeps the pinned key on a move when the new project can use it too', async () => {
        const ctx = await context()
        const target = await secondProjectOf(ctx)
        const shared = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Shared' })
        await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Other' })
        const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: shared.id } })

        const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect(moved.json().draft.providerConfigId).toBe(shared.id)
    })

    it('refuses a project the caller cannot reach', async () => {
        const ctx = await context()
        const stranger = await context()
        const agent = await createAgent(ctx)

        const response = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: stranger.project.id })

        expect(response.statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await db.findOneByOrFail('agent', { id: agent.id }) as { projectId: string }).projectId).toBe(ctx.project.id)
    })

    it('refuses while a published flow still runs it, and says which', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly sweep' })

        const response = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect(response.statusCode).toBe(StatusCodes.CONFLICT)
        expect(JSON.stringify(response.json())).toContain('Nightly sweep')
        expect((await db.findOneByOrFail('agent', { id: agent.id }) as { projectId: string }).projectId).toBe(ctx.project.id)
    })

    it('says up front what the move would cost', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        const flowId = await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly sweep' })

        const preview = await ctx.get(`/v1/agents/${agent.id}/move-preview`, { projectId: target.id })

        expect(preview.statusCode).toBe(StatusCodes.OK)
        expect(preview.json().blockedByPublishedFlows.total).toBe(1)
        expect(preview.json().blockedByPublishedFlows.flows).toStrictEqual([{ id: flowId, displayName: 'Nightly sweep' }])
        expect(preview.json().mayCreateAgentsThere).toBe(true)
        expect(preview.json().toolsThatStopWorking).toStrictEqual([])
        expect(preview.json().membersLosingAccess).toBe(0)
    })

    it('leaves the project alone when the agent is edited after moving', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        expect((await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })).statusCode).toBe(StatusCodes.OK)
        const before = await db.findOneByOrFail('agent', { id: agent.id }) as { updated: string }

        const renamed = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed after the move' })

        expect(renamed.statusCode).toBe(StatusCodes.OK)
        expect(renamed.json().displayName).toBe('Renamed after the move')
        expect(renamed.json().projectId).toBe(target.id)
        const after = await db.findOneByOrFail('agent', { id: agent.id }) as { updated: string, projectId: string }
        expect(after.projectId).toBe(target.id)
        // The sort on the list page reads this, so an update has to keep moving it.
        expect(new Date(after.updated).getTime()).toBeGreaterThanOrEqual(new Date(before.updated).getTime())
    })

    it('still opens a chat with the agent once it has moved', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        expect((await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })).statusCode).toBe(StatusCodes.OK)

        const conversation = await agentConversationService(app.log).createConversation({
            platformId: ctx.platform.id,
            userId: ctx.user.id,
            request: { agentId: agent.id },
        })

        expect(conversation.projectId).toBe(target.id)
    })

    it('refuses to publish a flow that points at an agent from another project', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED })
        await db.save('flow', flow)
        const version = createMockFlowVersion({ flowId: flow.id, updatedBy: ctx.user.id, state: FlowVersionState.DRAFT })
        await db.save('flow_version', { ...version, agentIds: [agent.externalId] })
        expect((await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })).statusCode).toBe(StatusCodes.OK)

        const published = await ctx.post(`/v1/flows/${flow.id}`, {
            type: 'LOCK_AND_PUBLISH',
            request: { status: FlowStatus.DISABLED },
        })

        expect(published.statusCode).toBe(StatusCodes.CONFLICT)
        const row = await db.findOneByOrFail('flow', { id: flow.id }) as { publishedVersionId: string | null }
        expect(row.publishedVersionId).toBeNull()
    })

    it('names every kind of tool that would stop working, not only connections', async () => {
        const ctx = await context()
        const target = await secondProjectOf(ctx)
        const agent = await createAgent(ctx, {
            draft: {
                ...agentBody(ctx.project.id).draft,
                tools: [
                    {
                        type: AgentToolType.FLOW,
                        toolName: 'run_the_intake_flow',
                        externalFlowId: apId(),
                        flowDisplayName: 'Client intake',
                    },
                    {
                        type: AgentToolType.KNOWLEDGE_BASE,
                        toolName: 'search_the_handbook',
                        sourceType: KnowledgeBaseSourceType.FILE,
                        sourceId: apId(),
                        sourceName: 'Handbook.pdf',
                    },
                ],
            },
        })

        const preview = (await ctx.get(`/v1/agents/${agent.id}/move-preview`, { projectId: target.id })).json()

        expect(preview.toolsThatStopWorking).toStrictEqual([
            { kind: 'flow', label: 'Client intake' },
            { kind: 'knowledge', label: 'Handbook.pdf' },
        ])
    })

    it('tells someone who cannot create agents there, and reveals nothing about that project', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const stranger = await context()

        const preview = await ctx.get(`/v1/agents/${agent.id}/move-preview`, { projectId: stranger.project.id })

        expect(preview.statusCode).toBe(StatusCodes.FORBIDDEN)
    })

    it('is not something a member can do to someone else\'s agent', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const target = await secondProjectOf(ctx)
        const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })

        const response = await member.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect([StatusCodes.FORBIDDEN, StatusCodes.NOT_FOUND]).toContain(response.statusCode)
    })
})

describe('agent folders', () => {
    const folderIn = async (projectId: string) => {
        const folder = createMockFolder({ projectId })
        await db.save('folder', folder)
        return folder
    }

    it('files an agent into a folder, moves it between folders, and back to the root', async () => {
        const ctx = await context()
        const first = await folderIn(ctx.project.id)
        const second = await folderIn(ctx.project.id)

        const agent = await createAgent(ctx, { folderId: first.id })
        expect(agent.folderId).toBe(first.id)

        const moved = await ctx.post(`/v1/agents/${agent.id}`, { folderId: second.id })
        expect(moved.json().folderId).toBe(second.id)

        const renamed = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Still filed' })
        expect(renamed.json().folderId).toBe(second.id)

        const unfiled = await ctx.post(`/v1/agents/${agent.id}`, { folderId: null })
        expect(unfiled.json().folderId).toBeNull()

        const listed = (await ctx.get('/v1/agents', { projectId: ctx.project.id })).json()
        expect(listed.data[0].folderId).toBeNull()
    })

    it('files an unpublished agent without publishing it', async () => {
        const ctx = await context()
        const folder = await folderIn(ctx.project.id)
        const agent = await createAgent(ctx)
        await ctx.post(`/v1/agents/${agent.id}/unpublish`)

        const filed = await ctx.post(`/v1/agents/${agent.id}`, { folderId: folder.id, goLive: false })

        expect(filed.json().folderId).toBe(folder.id)
        expect(filed.json().published).toBeNull()
    })

    it('refuses a folder from another project, on create and on update', async () => {
        const ctx = await context()
        const stranger = await context()
        const foreign = await folderIn(stranger.project.id)
        const agent = await createAgent(ctx)

        expect((await ctx.post('/v1/agents', agentBody(ctx.project.id, { folderId: foreign.id }))).statusCode).toBe(StatusCodes.NOT_FOUND)
        expect((await ctx.post(`/v1/agents/${agent.id}`, { folderId: foreign.id })).statusCode).toBe(StatusCodes.NOT_FOUND)
        expect((await ctx.get(`/v1/agents/${agent.id}`)).json().folderId).toBeNull()
    })

    it('keeps the agent at the root when its folder is deleted', async () => {
        const ctx = await context()
        const folder = await folderIn(ctx.project.id)
        const agent = await createAgent(ctx, { folderId: folder.id })

        expect((await ctx.delete(`/v1/folders/${folder.id}`)).statusCode).toBe(StatusCodes.OK)

        const after = await ctx.get(`/v1/agents/${agent.id}`)
        expect(after.statusCode).toBe(StatusCodes.OK)
        expect(after.json().folderId).toBeNull()
    })

    it('drops the folder when the agent moves to another project, since the folder stays behind', async () => {
        const ctx = await context()
        const folder = await folderIn(ctx.project.id)
        const agent = await createAgent(ctx, { folderId: folder.id })
        const target = createMockProject({ ownerId: ctx.user.id, platformId: ctx.platform.id })
        await db.save('project', target)

        const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })

        expect(moved.statusCode).toBe(StatusCodes.OK)
        expect(moved.json().folderId).toBeNull()
    })
})

describe('agent permissions', () => {
    it('lets a viewer read an agent but never create or change one', async () => {
        const owner = await context()
        const viewer = await createMemberContext(app, owner, { projectRole: DefaultProjectRole.VIEWER })
        const agent = await createAgent(owner)

        expect((await viewer.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.OK)
        expect((await viewer.post('/v1/agents', agentBody(owner.project.id))).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await viewer.post(`/v1/agents/${agent.id}`, { displayName: 'Nope' })).statusCode).toBe(StatusCodes.FORBIDDEN)
        expect((await viewer.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.FORBIDDEN)
    })
})

describe('agent routes coexist with the chat routes already on /v1/agents', () => {
    it('does not swallow the static sibling routes with /:id', async () => {
        const ctx = await createTestContext(app, { plan: { agentsEnabled: true, chatEnabled: true } })

        expect((await ctx.get('/v1/agents/memory')).statusCode).toBe(StatusCodes.OK)
        expect((await ctx.get('/v1/agents/conversations')).statusCode).toBe(StatusCodes.OK)
    })

    it('reports a missing agent as not found rather than routing it elsewhere', async () => {
        const ctx = await context()

        expect((await ctx.get(`/v1/agents/${apId()}`)).statusCode).toBe(StatusCodes.NOT_FOUND)
    })
})

describe('agent feature gate', () => {
    it('refuses every agent route once the platform loses the entitlement', async () => {
        const ctx = await context()
        const agent = await createAgent(ctx)
        const plan = await db.findOneByOrFail<{ id: string }>('platform_plan', { platformId: ctx.platform.id })
        await db.update('platform_plan', plan.id, { agentsEnabled: false })

        expect((await ctx.get('/v1/agents')).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
        expect((await ctx.post('/v1/agents', agentBody(ctx.project.id))).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
        expect((await ctx.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
        expect((await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'x' })).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
        expect((await ctx.post(`/v1/agents/${agent.id}/publish`)).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
        expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
    })
})

function triggerRunningAgent(agentExternalId: string) {
    return {
        type: FlowTriggerType.EMPTY,
        name: 'trigger',
        settings: {},
        valid: false,
        displayName: 'Select Trigger',
        lastUpdatedDate: new Date().toISOString(),
        nextAction: {
            type: FlowActionType.PIECE,
            name: 'step_1',
            displayName: 'Run Agent',
            skip: false,
            valid: true,
            lastUpdatedDate: new Date().toISOString(),
            settings: {
                pieceName: AI_PIECE_NAME,
                pieceVersion: '0.1.0',
                actionName: 'run_agent',
                input: { [AgentPieceProps.AGENT_ID]: agentExternalId },
                propertySettings: {},
            },
        },
    } as const
}

describe('updating an agent while someone else changes it', () => {
    it.each([
        ['unpublishes it', { published: null }, (agent: Agent) => expect(agent.published).toBeNull()],
        ['edits its draft', { draft: { ...agentBody('').draft, instructions: 'Newer draft.' } }, (agent: Agent) => expect(agent.draft.instructions).toBe('Newer draft.')],
        ['revokes a share', { sharedWithUserIds: [] }, (agent: Agent) => expect(agent.sharedWithUserIds).toStrictEqual([])],
    ])('keeps the change when another writer %s just before a rename takes the row lock', async (_label, change, expectKept) => {
        const ctx = await context()
        const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })
        const agent = await createAgent(ctx, { visibility: AgentVisibility.RESTRICTED, sharedWithUserIds: [member.user.id] })
        await ctx.post(`/v1/agents/${agent.id}/publish`)
        expect(agent.sharedWithUserIds).toStrictEqual([member.user.id])
        const getOne = SelectQueryBuilder.prototype.getOne
        const concurrentWrite = vi.spyOn(SelectQueryBuilder.prototype, 'getOne').mockImplementation(async function (this: SelectQueryBuilder<Agent>) {
            if (this.expressionMap.lockMode === 'pessimistic_write') {
                concurrentWrite.mockRestore()
                await db.update('agent', agent.id, change)
            }
            return getOne.call(this)
        })

        const rename = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed', goLive: false })
        concurrentWrite.mockRestore()

        expect(rename.statusCode).toBe(StatusCodes.OK)
        const stored = await db.findOneByOrFail<Agent>('agent', { id: agent.id })
        expect(stored.displayName).toBe('Renamed')
        expectKept(stored)
    })
})

describe('forgetting memories from a list that is out of date', () => {
    async function memoryContext(memories: string[]): Promise<TestContext> {
        const ctx = await createTestContext(app, { plan: { agentsEnabled: true, chatEnabled: true } })
        expect((await ctx.post('/v1/agents/memory', { memories: { next: memories, base: [] } })).statusCode).toBe(StatusCodes.OK)
        return ctx
    }

    it('applies both of two quick forgets made from the same list', async () => {
        const ctx = await memoryContext(['A', 'B', 'C'])

        await ctx.post('/v1/agents/memory', { memories: { next: ['A', 'C'], base: ['A', 'B', 'C'] } })
        await ctx.post('/v1/agents/memory', { memories: { next: ['A', 'B'], base: ['A', 'B', 'C'] } })

        expect((await ctx.get('/v1/agents/memory')).json().memories).toEqual(['A'])
    })

    it('keeps a fact the assistant remembered while the list was open', async () => {
        const ctx = await memoryContext(['A', 'B'])
        await ctx.post('/v1/agents/memory', { memories: { next: ['A', 'B', 'D'], base: ['A', 'B'] } })

        await ctx.post('/v1/agents/memory', { memories: { next: ['A'], base: ['A', 'B'] } })

        expect((await ctx.get('/v1/agents/memory')).json().memories).toEqual(['A', 'D'])
    })
    it('refuses a bare list, so no client can overwrite memories it never saw', async () => {
        const ctx = await memoryContext(['A', 'B'])

        expect((await ctx.post('/v1/agents/memory', { memories: ['A'] })).statusCode).toBe(StatusCodes.BAD_REQUEST)
        expect((await ctx.get('/v1/agents/memory')).json().memories).toEqual(['A', 'B'])
    })
})