Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

26.5 KB
Raw Blame
import type {
  SkillDetailResponse,
  SkillReferenceResponse,
  SkillVersionResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { detectPlatform } from '@tanstack/react-hotkeys'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, within } from '@testing-library/react'
import { StrictMode } from 'react'
import { afterEach, vi } from 'vite-plus/test'
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import { SkillDetailPage } from '../detail/page'

export const primaryModifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }

const mocks = vi.hoisted(() => ({
  request:
    vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),
  deleteSkillMutationFn: vi.fn(),
  copyToClipboard: vi.fn(),
  downloadBlob: vi.fn(),
  duplicateSkillMutationFn: vi.fn(),
  fetchSkillArchiveBlob: vi.fn(),
  fetchSkillFileBlob: vi.fn(),
  checkDraftFilesMutationFn: vi.fn(),
  publishSkillMutationFn: vi.fn(),
  publishSkillMutationOptions: vi.fn(),
  routerPush: vi.fn(),
  routeSkillId: 'skill-1',
  saveDraftFileMutationFn: vi.fn(),
  sendSkillAssistMessage: vi.fn(),
  modelParameterRulesFetch: vi.fn<typeof fetch>(),
  textGenerationModelListGet: vi.fn(),
  defaultTextGenerationModel: undefined as
    | { provider: { provider: string }; model: string }
    | undefined,
  skillDetail: undefined as SkillDetailResponse | undefined,
  skillDetailGetFn: vi.fn(),
  skillDetailQueryOptions: vi.fn((_options: unknown) => ({})),
  skillTags: [] as { count: number; tag: string }[],
  skillMetadataMutationFn: vi.fn(),
  skillReferencesQueryOptions: vi.fn((_options: unknown) => ({})),
  skillTagsQueryOptions: vi.fn((_options: unknown) => ({})),
  skillVersionsQueryOptions: vi.fn((_options: unknown) => ({})),
  skillVersionDetailQueryOptions: vi.fn((_options: unknown) => ({})),
  textGenerationModelList: [] as {
    provider: string
    status: string
    models: { model: string; status: string }[]
  }[],
  toastError: vi.fn(),
  toastInfo: vi.fn(),
  toastSuccess: vi.fn(),
  uploadSkillFile: vi.fn(),
  versionPatchMutationFn: vi.fn(),
}))

vi.mock('@/app/notifications', () => ({
  toast: {
    error: mocks.toastError,
    info: mocks.toastInfo,
    success: mocks.toastSuccess,
  },
}))

vi.mock('copy-to-clipboard', () => ({
  default: mocks.copyToClipboard,
}))

vi.mock('@/app/components/base/markdown', () => ({
  Markdown: ({
    content,
    customComponents,
  }: {
    content: string
    customComponents?: {
      a?: (props: { children: string; href: string }) => ReactNode
    }
  }) => {
    const reference = content.match(/\[([^\]]+)\]\(<([^>\n]+)>\)/)
    if (reference && customComponents?.a) {
      return <div>{customComponents.a({ children: reference[1]!, href: reference[2]! })}</div>
    }

    return <div>{content}</div>
  },
}))

vi.mock('@/app/components/main-nav/components/account-section', () => ({
  default: ({ compact = false }: { compact?: boolean }) => (
    <button type="button" aria-label={compact ? 'compact-account-section' : 'account-section'}>
      Current account
    </button>
  ),
}))

vi.mock('@/app/components/main-nav/components/help-menu', () => ({
  default: () => (
    <button type="button" aria-label="help-menu">
      Help
    </button>
  ),
}))

vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
  useLanguage: () => 'en_US',
  useDefaultModel: () => ({
    data: mocks.defaultTextGenerationModel,
  }),
  useTextGenerationCurrentProviderAndModelAndModelList: (selectedModel?: DefaultModel) => {
    const currentProvider = mocks.textGenerationModelList.find(
      (provider) => provider.provider === selectedModel?.provider,
    )
    return {
      currentProvider,
      currentModel: currentProvider?.models.find((model) => model.model === selectedModel?.model),
      activeTextGenerationModelList: mocks.textGenerationModelList.filter(
        (provider) => provider.status === 'active',
      ),
    }
  },
}))

vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({
  ModelSelector: () => <button type="button">model-settings</button>,
  SplitModelSelector: () => <button type="button">model-settings</button>,
}))

vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
  default: ({ onChange, value }: { onChange?: (value: string) => void; value: string }) => (
    <textarea
      aria-label="code-editor"
      value={value}
      onChange={(event) => onChange?.(event.target.value)}
    />
  ),
}))

vi.mock('@/hooks/use-document-title', () => ({
  default: vi.fn(),
}))

vi.mock('@/hooks/use-format-time-from-now', () => ({
  useFormatTimeFromNow: () => ({
    formatTimeFromNow: () => 'just now',
  }),
}))

vi.mock('@/hooks/use-timestamp', () => ({
  default: () => ({
    formatTime: () => '2026-07-21 12:00',
  }),
}))

vi.mock('@/features/tag-management/components/tag-management-modal', () => ({
  TagManagementModal: ({ show }: { show: boolean }) =>
    show ? <div role="dialog">common.tag.manageTags</div> : null,
}))

vi.mock('@/next/link', () => ({
  default: ({ children, href, ...props }: { children: ReactNode; href: string }) => (
    <a href={href} {...props}>
      {children}
    </a>
  ),
}))

vi.mock('@/service/base', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@/service/base')>()),
  request: mocks.request,
}))

vi.mock('@/next/navigation', () => ({
  useParams: () => ({ skillId: mocks.routeSkillId }),
  useRouter: () => ({
    push: mocks.routerPush,
  }),
}))

vi.mock('@/utils/download', () => ({
  downloadBlob: mocks.downloadBlob,
}))

vi.mock('@/service/console', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/service/console')>()
  const { withConsoleQueryOverrides, withConsoleResponses } =
    await import('@/test/console/service-responses')
  const modelQuery = withConsoleResponses(actual.consoleQuery, {
    'workspaces.current.models.modelTypes.byModelType.get': () =>
      mocks.textGenerationModelListGet(),
  })
  const query = withConsoleQueryOverrides(actual.consoleQuery, {
    'workspaces.current.skills.tags.get': { queryOptions: mocks.skillTagsQueryOptions },
    'workspaces.current.skills.bySkillId.get': { queryOptions: mocks.skillDetailQueryOptions },
    'workspaces.current.skills.bySkillId.references.get': {
      queryOptions: mocks.skillReferencesQueryOptions,
    },
    'workspaces.current.skills.bySkillId.versions.get': {
      queryOptions: mocks.skillVersionsQueryOptions,
    },
    'workspaces.current.skills.bySkillId.versions.byVersionId.get': {
      queryOptions: mocks.skillVersionDetailQueryOptions,
    },
  })

  return {
    consoleClient: {
      workspaces: {
        current: {
          skills: {
            bySkillId: {
              get: mocks.skillDetailGetFn,
            },
          },
        },
      },
    },
    consoleQuery: {
      workspaces: {
        current: {
          models: modelQuery.workspaces.current.models,
          modelProviders: actual.consoleQuery.workspaces.current.modelProviders,
          agents: {
            byAgentId: {
              skills: {
                get: {
                  key: actual.consoleQuery.workspaces.current.agents.byAgentId.skills.get.key,
                },
              },
            },
          },
          skills: {
            get: {
              key: actual.consoleQuery.workspaces.current.skills.get.key,
            },
            tags: {
              get: {
                key: actual.consoleQuery.workspaces.current.skills.tags.get.key,
                queryOptions: query.workspaces.current.skills.tags.get.queryOptions,
              },
            },
            bySkillId: {
              delete: {
                mutationOptions: () => ({ mutationFn: mocks.deleteSkillMutationFn }),
              },
              duplicate: {
                post: {
                  mutationOptions: () => ({ mutationFn: mocks.duplicateSkillMutationFn }),
                },
              },
              get: {
                key: actual.consoleQuery.workspaces.current.skills.bySkillId.get.key,
                queryOptions: query.workspaces.current.skills.bySkillId.get.queryOptions,
              },
              patch: {
                mutationOptions: () => ({ mutationFn: mocks.skillMetadataMutationFn }),
              },
              publish: {
                post: {
                  mutationOptions: (options?: unknown) => {
                    mocks.publishSkillMutationOptions(options)
                    return { mutationFn: mocks.publishSkillMutationFn }
                  },
                },
              },
              references: {
                get: {
                  queryOptions:
                    query.workspaces.current.skills.bySkillId.references.get.queryOptions,
                },
              },
              restore: actual.consoleQuery.workspaces.current.skills.bySkillId.restore,
              files: {
                check: {
                  post: {
                    mutationOptions: () => ({ mutationFn: mocks.checkDraftFilesMutationFn }),
                  },
                },
                patch: {
                  mutationOptions: () => ({ mutationFn: mocks.saveDraftFileMutationFn }),
                },
              },
              versions: {
                get: {
                  key: actual.consoleQuery.workspaces.current.skills.bySkillId.versions.get.key,
                  queryOptions: query.workspaces.current.skills.bySkillId.versions.get.queryOptions,
                },
                byVersionId: {
                  get: {
                    queryOptions:
                      query.workspaces.current.skills.bySkillId.versions.byVersionId.get
                        .queryOptions,
                  },
                  patch: {
                    mutationOptions: () => ({ mutationFn: mocks.versionPatchMutationFn }),
                  },
                  delete:
                    actual.consoleQuery.workspaces.current.skills.bySkillId.versions.byVersionId
                      .delete,
                },
              },
            },
          },
        },
      },
    },
  }
})

vi.mock('../permissions', () => ({
  useSkillPermissions: () => ({ canDelete: true, canEdit: true, canPublish: true }),
}))

vi.mock('../client', () => ({
  fetchSkillArchiveBlob: mocks.fetchSkillArchiveBlob,
  fetchSkillFileBlob: mocks.fetchSkillFileBlob,
  sendSkillAssistMessage: mocks.sendSkillAssistMessage,
  uploadSkillFile: mocks.uploadSkillFile,
}))

export function createSkillDetail(
  overrides: Partial<SkillDetailResponse> = {},
): SkillDetailResponse {
  return {
    id: 'skill-1',
    name: 'github-actions-failure-debugging',
    display_name: 'Untitled skill',
    icon: '📄',
    description: 'Guide for debugging failing GitHub Actions workflows.',
    tags: [],
    name_manually_edited: true,
    visibility: 'workspace',
    latest_published_version_id: 'version-1',
    latest_published_version_number: 1,
    latest_published_at: 1784638400,
    reference_count: 0,
    created_by: 'user-1',
    created_by_name: 'Fate',
    updated_by: 'user-1',
    updated_by_name: 'Fate',
    created_at: 1784631405,
    updated_at: 1784638487,
    files: [
      {
        id: 'file-1',
        path: 'SKILL.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content:
          '---\nname: github-actions-failure-debugging\ndescription: Guide for debugging failing GitHub Actions workflows.\nmetadata:\n  display-name: Untitled skill\n---\n# GitHub Actions Failure Debugging\n',
        tool_file_id: null,
        size: 180,
        hash: 'hash-1',
      },
    ],
    ...overrides,
  }
}

export function createDefaultSkillDraftDetail(overrides: Partial<SkillDetailResponse> = {}) {
  return createSkillDetail({
    name: 'untitled-skill-74d8b044',
    display_name: 'Untitled skill',
    description: 'Describe what this Skill does and when an Agent should use it.',
    latest_published_version_id: null,
    files: [
      {
        id: 'file-1',
        path: 'SKILL.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content:
          '---\nname: untitled-skill-74d8b044\ndescription: Describe what this Skill does and when an Agent should use it.\nmetadata:\n  display-name: Untitled skill\n---\n# Untitled skill\n\nDescribe what this Skill does, when an Agent should use it, and any step-by-step instructions it must follow.\n',
        tool_file_id: null,
        size: 248,
        hash: 'hash-1',
      },
    ],
    ...overrides,
  })
}

export function createFileTabSkillDetail() {
  return createSkillDetail({
    files: [
      ...createSkillDetail().files!,
      {
        id: 'file-readme',
        path: 'README.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content: '# README',
        tool_file_id: null,
        size: 8,
        hash: 'hash-readme',
      },
      {
        id: 'file-prompt',
        path: 'prompt.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content: '# Prompt',
        tool_file_id: null,
        size: 8,
        hash: 'hash-prompt',
      },
      {
        id: 'file-notes',
        path: 'notes.txt',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/plain',
        content: 'Notes',
        tool_file_id: null,
        size: 5,
        hash: 'hash-notes',
      },
    ],
  })
}

export function createReferencePickerSkillDetail() {
  return createSkillDetail({
    files: [
      ...createSkillDetail().files!,
      {
        id: 'file-readme',
        path: 'README.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content: '# README',
        tool_file_id: null,
        size: 8,
        hash: 'hash-readme',
      },
      {
        id: 'file-guide',
        path: 'docs/guide.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content: '# Guide',
        tool_file_id: null,
        size: 7,
        hash: 'hash-guide',
      },
      {
        id: 'file-reference',
        path: 'docs/reference.md',
        kind: 'file',
        storage: 'text',
        mime_type: 'text/markdown',
        content: '# Reference',
        tool_file_id: null,
        size: 11,
        hash: 'hash-reference',
      },
    ],
  })
}

export function createSkillVersion(
  overrides: Partial<SkillVersionResponse> = {},
): SkillVersionResponse {
  return {
    id: 'version-1',
    skill_id: 'skill-1',
    version_number: 1,
    version_name: 'Initial version',
    publish_note: 'Original instructions',
    hash_code: 'hash-code-1',
    archive_size: 180,
    published_by: 'user-1',
    published_by_name: 'Fate',
    created_at: 1784638400,
    is_latest: false,
    ...overrides,
  }
}

export function createAgentReference(
  overrides: Partial<SkillReferenceResponse> = {},
): SkillReferenceResponse {
  return {
    agent_id: 'agent-1',
    agent_icon: '🤖',
    agent_icon_background: '#EFF6FF',
    agent_icon_type: 'emoji',
    app_id: 'app-1',
    display_name: 'Support Agent',
    name: 'support-agent',
    type: 'agent',
    ...overrides,
  }
}

export function renderSkillDetailPage({
  queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  }),
  searchParams = '',
  strict = false,
}: {
  queryClient?: QueryClient
  searchParams?: string
  strict?: boolean
} = {}) {
  const { wrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })

  return {
    ...render(
      <QueryClientProvider client={queryClient}>
        {strict ? (
          <StrictMode>
            <SkillDetailPage skillId="skill-1" />
          </StrictMode>
        ) : (
          <SkillDetailPage skillId="skill-1" />
        )}
      </QueryClientProvider>,
      { wrapper },
    ),
    onUrlUpdate,
    queryClient,
  }
}

export function getBuilderAttachmentInput(container: HTMLElement) {
  const inputs = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="file"]'))
  return inputs.at(-1) ?? null
}

export function getSourceEditor() {
  return screen.getByRole<HTMLTextAreaElement>('textbox', {
    name: 'skill.skillManagement.detail.markdownSourceMode',
  })
}

export function getLiveMarkdownEditor() {
  const liveEditor = screen
    .getAllByRole('textbox')
    .find(
      (editor): editor is HTMLDivElement =>
        editor instanceof HTMLDivElement && editor.isContentEditable,
    )

  if (!liveEditor) throw new Error('live markdown editor not found')

  return liveEditor
}

export function placeCaretAtEnd(element: HTMLElement) {
  const selection = element.ownerDocument.getSelection()
  const range = element.ownerDocument.createRange()
  range.selectNodeContents(element)
  range.collapse(false)
  selection?.removeAllRanges()
  selection?.addRange(range)
}

export function getFileTreeItem(path: string) {
  const fileButton = document.querySelector(`[title="${path}"]`)
  const treeItem = fileButton?.closest('[data-skill-file-tree-item]')
  if (!(treeItem instanceof HTMLElement)) throw new Error(`file tree item not found: ${path}`)

  return treeItem
}

export function getReferencePicker() {
  const picker = document.querySelector<HTMLElement>('div.fixed.z-50')
  if (!picker) throw new Error('reference picker not found')

  return picker
}

export function getReferencePickerButton(name: string | RegExp) {
  return within(getReferencePicker()).getByRole('button', { name })
}

export function preserveDraftFilesOnSave() {
  mocks.saveDraftFileMutationFn.mockImplementation(
    async (input: { body: { content?: string; operation: string; path: string } }) => {
      const currentDetail = mocks.skillDetail ?? createSkillDetail()
      const nextFiles =
        currentDetail.files?.map((file) =>
          file.path === input.body.path
            ? {
                ...file,
                content: input.body.content ?? file.content,
                hash: `${file.hash ?? 'hash'}-saved`,
              }
            : file,
        ) ?? []
      mocks.skillDetail = {
        ...currentDetail,
        files: nextFiles,
        updated_at: 1784638490,
      }

      return mocks.skillDetail
    },
  )
}

export function getFileTreeButton(path: string) {
  const fileButton = document.querySelector(`[title="${path}"]`)
  if (!(fileButton instanceof HTMLButtonElement)) throw new Error(`file button not found: ${path}`)

  return fileButton
}

export function getFileTreeContextRegion() {
  const region = document.querySelector('[data-skill-file-tree-context-region]')
  if (!(region instanceof HTMLElement)) throw new Error('file tree context region not found')

  return region
}

export function getFileTabButton(path: string) {
  const button = Array.from(
    document.querySelectorAll<HTMLButtonElement>(`button[title="${path}"]`),
  ).find((candidate) => !candidate.closest('[data-skill-file-tree-item]'))
  if (!button) throw new Error(`file tab not found: ${path}`)

  return button
}

export function createDataTransfer(files: File[] = []) {
  const data = new Map<string, string>()
  const types = files.length > 0 ? ['Files'] : []
  const setDragImage = vi.fn()

  return {
    dataTransfer: {
      dropEffect: 'none',
      effectAllowed: 'uninitialized',
      files,
      getData: (type: string) => data.get(type) ?? '',
      setData: (type: string, value: string) => {
        data.set(type, value)
        if (!types.includes(type)) types.push(type)
      },
      setDragImage,
      types,
    } as unknown as DataTransfer,
    setDragImage,
  }
}

export async function openFileTreeActions(user: ReturnType<typeof userEvent.setup>, path: string) {
  const treeItem = getFileTreeItem(path)
  await user.click(within(treeItem).getByRole('button', { name: 'common.operation.more' }))
}

export async function openRootCreateMenu(user: ReturnType<typeof userEvent.setup>) {
  const fileTree = screen.getByRole('region', { name: /skillManagement\.detail\.fileCount/ })

  await user.click(within(fileTree).getByRole('button', { name: 'common.operation.add' }))
}

export async function confirmUploadReview() {
  const uploadButton = await screen.findByRole('button', { name: /uploadFilesButton/ })
  fireEvent.click(uploadButton)
}

export async function openVersionRowActions(
  user: ReturnType<typeof userEvent.setup>,
  versionName: string,
) {
  const versionText = await screen.findByText(versionName)
  const versionRow = versionText.closest('li')
  if (!(versionRow instanceof HTMLElement)) throw new Error(`version row not found: ${versionName}`)
  const buttons = within(versionRow).getAllByRole('button')
  const actionButton = buttons.at(-1)
  if (!actionButton) throw new Error(`version row action not found: ${versionName}`)

  await user.click(actionButton)
}

export function getMocks() {
  return mocks
}

export function resetDetailPageFixture() {
  vi.useRealTimers()
  vi.resetAllMocks()
  mocks.request.mockImplementation(async (_url, _init, options) => {
    const req = options.request
    const pathname = new URL(req.url).pathname
    // Model parameter rules go through the console client and land on the fetch mock.
    if (pathname.endsWith('/models/parameter-rules')) return mocks.modelParameterRulesFetch(req)
    if (req.method === 'POST' && /\/skills\/[^/]+\/restore$/.test(pathname))
      return Response.json(mocks.skillDetail)
    if (req.method === 'DELETE' && /\/skills\/[^/]+\/versions\/[^/]+$/.test(pathname))
      return Response.json({ result: 'success' })
    throw new Error(`Unexpected request: ${req.method} ${pathname}`)
  })
  mocks.modelParameterRulesFetch.mockImplementation(async (input) => {
    const url = input instanceof Request ? input.url : String(input)
    if (!url.includes('/models/parameter-rules'))
      throw new Error(`Unexpected Skill detail request: ${url}`)
    return Response.json({ data: [] })
  })
  vi.stubGlobal('fetch', mocks.modelParameterRulesFetch)
  mocks.routeSkillId = 'skill-1'
  mocks.defaultTextGenerationModel = {
    provider: {
      provider: 'langgenius/openai/openai',
    },
    model: 'gpt-5.5',
  }
  mocks.textGenerationModelList = [
    {
      provider: 'langgenius/openai/openai',
      status: 'active',
      models: [
        {
          model: 'gpt-5.5',
          status: 'active',
        },
      ],
    },
  ]
  mocks.textGenerationModelListGet.mockImplementation(async () => ({
    data: mocks.textGenerationModelList,
  }))
  mocks.skillDetail = createSkillDetail()
  mocks.skillDetailGetFn.mockImplementation(async () => mocks.skillDetail)

  mocks.skillTags = [
    { count: 3, tag: 'Search' },
    { count: 2, tag: 'Productivity' },
    { count: 1, tag: 'Utilities' },
  ]

  mocks.skillTagsQueryOptions.mockImplementation(() => ({
    queryFn: async () => ({
      data: [],
    }),
  }))
  mocks.skillDetailQueryOptions.mockImplementation(() => ({
    queryFn: async () => mocks.skillDetail,
  }))
  mocks.skillVersionsQueryOptions.mockImplementation(() => ({
    queryFn: async () => ({
      data: [],
    }),
  }))
  mocks.skillVersionDetailQueryOptions.mockImplementation(() => ({
    queryFn: async () => ({
      ...mocks.skillDetail,
      files: [],
    }),
  }))
  mocks.skillReferencesQueryOptions.mockImplementation(() => ({
    queryFn: async () => ({
      data: [],
    }),
  }))
  mocks.skillTagsQueryOptions.mockImplementation(() => ({
    queryFn: async () => ({
      data: mocks.skillTags,
    }),
  }))
  mocks.saveDraftFileMutationFn.mockImplementation(
    async (input: { body: { content?: string; operation: string; path: string } }) => {
      if (input.body.operation !== 'upsert_text') {
        const nextDetail = createSkillDetail({
          updated_at: 1784638490,
        })
        mocks.skillDetail = {
          ...nextDetail,
          files: mocks.skillDetail?.files ?? nextDetail.files,
        }
        return mocks.skillDetail
      }

      const nextDetail = createSkillDetail({
        display_name: input.body.content?.includes('display-name: 333333333')
          ? '333333333'
          : 'Untitled skill',
        updated_at: 1784638490,
      })
      const nextFiles = nextDetail.files ?? []
      nextFiles[0] = {
        ...nextFiles[0]!,
        content: input.body.content ?? '',
      }
      nextDetail.files = nextFiles
      mocks.skillDetail = nextDetail
      return nextDetail
    },
  )
  mocks.skillMetadataMutationFn.mockImplementation(
    async (input: { body: { display_name?: string; tags?: string[] } }) => {
      const nextDetail = createSkillDetail({
        display_name: input.body.display_name ?? 'Untitled skill',
        tags: input.body.tags ?? mocks.skillDetail?.tags ?? [],
        updated_at: 1784638491,
      })
      mocks.skillDetail = {
        ...nextDetail,
        files: mocks.skillDetail?.files ?? nextDetail.files,
      }
      return nextDetail
    },
  )
  mocks.publishSkillMutationFn.mockImplementation(async () => {
    const version = {
      id: 'version-2',
      version_number: 2,
      version_name: '',
      publish_note: '',
      hash_code: 'hash-code',
      archive_size: 180,
      published_by: 'user-1',
      published_by_name: 'Fate',
      created_at: 1784638492,
      is_latest: true,
    }
    mocks.skillDetail = mocks.skillDetail
      ? {
          ...mocks.skillDetail,
          latest_published_at: version.created_at,
          latest_published_version_id: version.id,
          latest_published_version_number: version.version_number,
        }
      : mocks.skillDetail
    return version
  })
  mocks.versionPatchMutationFn.mockResolvedValue({})
  mocks.sendSkillAssistMessage.mockResolvedValue(undefined)
  mocks.checkDraftFilesMutationFn.mockImplementation(
    async (input: {
      body: {
        files?: Array<{
          filename: string
          mime_type?: string | null
          path?: string | null
          size: number
        }>
      }
    }) => ({
      data: Object.fromEntries(
        (input.body.files ?? []).map((file) => [
          file.filename,
          {
            errors: [],
            extension: file.filename.includes('.') ? `.${file.filename.split('.').at(-1)}` : '',
            filename: file.filename,
            mime_type: file.mime_type ?? 'application/octet-stream',
            path: file.path ?? file.filename,
            size: file.size,
          },
        ]),
      ),
    }),
  )
  mocks.uploadSkillFile.mockResolvedValue({
    id: 'tool-file-1',
    name: 'guide.md',
    mime_type: 'text/markdown',
    size: 10,
  })
}

afterEach(() => {
  vi.unstubAllGlobals()
})