Skip to content

A full-featured download manager.

21.3 KB
Raw Blame
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { getInspectorSnapHeights } from '@renderer/components/desktop-kit/inspector-drawer'
import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
import { transport } from '@renderer/lib/transport'
import { DownloadErrorCode } from '@shared/errors'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import type { DownloadTask } from '@shared/types/task'
import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'
import {
  TaskHistoryAccuracy,
  TaskHistoryEventKind,
  type TaskInspectorActivitySnapshot,
} from '@shared/types/task-inspector-activity'
import { makeDownloadTask } from '@test-utils/task'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TaskInspectorDrawer } from './task-inspector-drawer'
import { useDownloadsView } from './view-preferences'

const activityHookState = vi.hoisted(() => ({
  current: null as unknown,
  calls: [] as unknown[][],
}))

vi.mock('@renderer/hooks/use-task-pieces', () => ({
  useTaskPieces: () => ({ pieces: null }),
}))
vi.mock('@renderer/hooks/use-task-speed-history', () => ({
  useTaskSpeedHistory: () => ({ history: [], isLoading: false }),
}))
vi.mock('@renderer/hooks/use-task-inspector-activity', () => ({
  createTaskInspectorActivitySnapshotCache: () => ({ cache: true }),
  useTaskInspectorActivity: (...args: unknown[]) => {
    activityHookState.calls.push(args)
    return activityHookState.current
  },
}))

const BASE_TIME = 1_721_390_398_000

function activitySnapshot(failed = false): TaskInspectorActivitySnapshot {
  const events = [
    {
      eventOrdinal: 1,
      eventKey: 'event-1',
      kind: TaskHistoryEventKind.Added,
      fromStatus: null,
      toStatus: TaskStatus.Queued,
      occurredAt: BASE_TIME,
      accuracy: TaskHistoryAccuracy.Exact,
      errorCode: null,
      errorMessage: null,
      errorDetailKey: null,
      errorDetailParams: null,
    },
    ...(failed
      ? [
          {
            eventOrdinal: 3,
            eventKey: 'event-3',
            kind: TaskHistoryEventKind.Failed,
            fromStatus: TaskStatus.Downloading,
            toStatus: TaskStatus.Error,
            occurredAt: BASE_TIME + 2_000,
            accuracy: TaskHistoryAccuracy.Exact,
            errorCode: DownloadErrorCode.NetworkError,
            errorMessage: 'connection refused',
            errorDetailKey: null,
            errorDetailParams: null,
          },
        ]
      : []),
  ]

  return {
    taskId: 'a',
    revision: 2,
    summary: {
      trackingStartedAt: BASE_TIME,
      coverageGapAt: null,
      revision: 2,
      lastEventOrdinal: events.at(-1)?.eventOrdinal ?? 0,
      activeMs: 0,
      downloadActiveMs: 0,
      estimatedDownloadBytes: '0',
      estimatedUploadBytes: '0',
      peakDownloadBps: 0,
      peakUploadBps: 0,
      rawSampleCount: 0,
      historyDroppedCount: 0,
      historyTruncatedAt: null,
      updatedAt: BASE_TIME + 2_000,
    },
    timeline: {
      events,
      trackingStartedAt: BASE_TIME,
      coverageGapAt: null,
      historyDroppedCount: 0,
      historyTruncatedAt: null,
    },
    lifetime: {
      points: [],
      averageDownloadSpeed: 0,
      peakDownloadSpeed: 0,
      peakUploadSpeed: 0,
      activeMs: 0,
      updatedAt: BASE_TIME + 2_000,
      accuracy: 'estimated',
    },
  }
}

function fake(over: Partial<DownloadTask> = {}): DownloadTask {
  return makeDownloadTask({
    id: 'a',
    engineTaskId: 'g',
    name: 'demo',
    progress: 0.5,
    totalBytes: 100,
    downloadedBytes: 50,
    downloadSpeed: 10,
    etaSeconds: 5,
    saveDir: '/',
    uris: [''],
    fileCount: 1,
    filename: 'demo',
    sizeWhenDone: 100,
    diskPath: '/demo',
    finalPath: '/demo',
    finalName: 'demo',
    ...over,
  })
}

function TestHarness({
  selection,
  tasks,
  onDismiss,
}: {
  selection: SelectionStore<DownloadTask>
  tasks: readonly DownloadTask[]
  onDismiss?: () => void
}) {
  const [container, setContainer] = useState<HTMLElement | null>(null)
  return (
    <div ref={setContainer}>
      <TaskInspectorDrawer
        selection={selection}
        tasks={tasks}
        container={container}
        onDismiss={onDismiss}
      />
    </div>
  )
}

describe('TaskInspectorDrawer', () => {
  it.each([
    [900, [220, 450, 675]],
    [600, [220, 300, 450]],
    [500, [220, 220, 375]],
    [400, [220, 220, 300]],
    [300, [225, 225, 225]],
    [240, [176, 176, 176]],
  ] as const)('adapts snap heights to a %ipx container', (height, expected) => {
    expect(getInspectorSnapHeights(height)).toEqual(expected)
  })

  it('skips merged detents when resizing with the keyboard in a short window', async () => {
    const measure = vi
      .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
      .mockReturnValue(new DOMRect(0, 0, 1000, 400))
    try {
      const user = userEvent.setup()
      const selection = createSelectionStore<DownloadTask>((task) => task.id)
      const tasks = [fake()]
      selection.getState().setItems(tasks)
      selection.getState().select('a')
      render(<TestHarness selection={selection} tasks={tasks} />)
      const resize = screen.getByRole('separator', { name: 'Resize Inspector' })
      expect(resize).toHaveAttribute('aria-valuenow', '220')
      expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
      resize.focus()
      await user.keyboard('{ArrowUp}')
      expect(resize).toHaveAttribute('aria-valuenow', '300')
      expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')
      await user.keyboard('{ArrowDown}')
      expect(resize).toHaveAttribute('aria-valuenow', '220')
      await user.keyboard('{ArrowDown}')
      expect(resize).toHaveAttribute('aria-valuenow', '220')
    } finally {
      measure.mockRestore()
    }
  })

  beforeEach(() => {
    useDownloadsView.setState({
      inspectorTab: 'overview',
      inspectorVisible: true,
      inspectorSnap: 'medium',
    })
    activityHookState.calls.length = 0
    activityHookState.current = {
      status: 'ready',
      snapshot: activitySnapshot(),
    }
  })

  it('does not render drawer content when hidden', () => {
    useDownloadsView.setState({ inspectorVisible: false })
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    render(<TestHarness selection={selection} tasks={[fake()]} />)
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('loads file details only in the visible Files tab and stops listening when closed', async () => {
    const originalInvoke = transport.invoke.bind(transport)
    const invoke = vi
      .spyOn(transport, 'invoke')
      .mockImplementation(async (channel, ...args) =>
        channel === Queries.GetTaskFiles ? [] : originalInvoke(channel, ...args)
      )
    const on = vi.spyOn(transport, 'on').mockImplementation(() => {})
    const off = vi.spyOn(transport, 'off').mockImplementation(() => {})
    try {
      const user = userEvent.setup()
      const selection = createSelectionStore<DownloadTask>((task) => task.id)
      const tasks = [fake({ status: TaskStatus.Downloading })]
      selection.getState().setItems(tasks)
      selection.getState().select('a')
      render(<TestHarness selection={selection} tasks={tasks} />)
      const reads = () =>
        invoke.mock.calls.filter(
          ([channel]) => channel === Queries.GetTaskFiles
        ).length
      expect(reads()).toBe(0)
      await user.click(screen.getByRole('tab', { name: 'Files' }))
      await waitFor(() => expect(reads()).toBe(1))
      await user.click(screen.getByRole('tab', { name: 'Overview' }))
      expect(off).toHaveBeenCalledWith(
        Events.TaskFilesUpdated,
        expect.any(Function)
      )
      await user.click(screen.getByRole('tab', { name: 'Files' }))
      await waitFor(() => expect(reads()).toBe(2))
      off.mockClear()
      await user.click(screen.getByRole('button', { name: 'Close' }))
      expect(off).toHaveBeenCalledWith(
        Events.TaskFilesUpdated,
        expect.any(Function)
      )
    } finally {
      invoke.mockRestore()
      on.mockRestore()
      off.mockRestore()
    }
  })

  it('closes a restored inspector with no selection and keeps a subsequent single selection closed', () => {
    const selection = createSelectionStore<DownloadTask>((task) => task.id)
    const tasks = [fake()]
    selection.getState().setItems(tasks)
    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    expect(useDownloadsView.getState().inspectorVisible).toBe(false)
    act(() => selection.getState().select('a'))
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })

  it('closes on empty selection and preserves tab and height for an explicit reopen', async () => {
    const selection = createSelectionStore<DownloadTask>((task) => task.id)
    const tasks = [fake({ id: 'a' }), fake({ id: 'b' })]
    const onDismiss = vi.fn()
    selection.getState().setItems(tasks)
    selection.getState().select('a')
    useDownloadsView.setState({
      inspectorSnap: 'expanded',
      inspectorTab: 'activity',
    })
    render(
      <TestHarness selection={selection} tasks={tasks} onDismiss={onDismiss} />
    )

    act(() => selection.getState().clearSelection())
    await waitFor(() =>
      expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    )
    expect(useDownloadsView.getState().inspectorVisible).toBe(false)
    expect(onDismiss).not.toHaveBeenCalled()

    act(() => selection.getState().select('b'))
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    act(() => useDownloadsView.getState().setInspectorVisible(true))
    expect(screen.getByRole('tab', { name: 'Activity' })).toHaveAttribute(
      'aria-selected',
      'true'
    )
    expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')

    act(() => screen.getByRole('button', { name: 'Close' }).click())
    await waitFor(() =>
      expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    )
    act(() => selection.getState().select('a'))
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    expect(onDismiss).toHaveBeenCalledOnce()
  })

  it.each(['missing', 'removed'] as const)(
    'hides when the selected task becomes %s',
    async (mode) => {
      const selection = createSelectionStore<DownloadTask>((task) => task.id)
      const tasks = [fake()]
      selection.getState().setItems(tasks)
      selection.getState().select('a')
      const view = render(<TestHarness selection={selection} tasks={tasks} />)

      view.rerender(
        <TestHarness
          selection={selection}
          tasks={
            mode === 'missing' ? [] : [fake({ status: TaskStatus.Removed })]
          }
        />
      )
      await waitFor(() =>
        expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
      )
      expect(useDownloadsView.getState().inspectorVisible).toBe(false)
    }
  )

  it('does not move focus away from an input when selection is cleared', async () => {
    const selection = createSelectionStore<DownloadTask>((task) => task.id)
    const tasks = [fake()]
    selection.getState().setItems(tasks)
    selection.getState().select('a')
    render(
      <>
        <input aria-label="Search" />
        <TestHarness selection={selection} tasks={tasks} />
      </>
    )

    const search = screen.getByRole('textbox', { name: 'Search' })
    search.focus()
    act(() => selection.getState().clearSelection())
    await waitFor(() =>
      expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    )
    expect(search).toHaveFocus()
  })

  it('renders single-mode body with Overview tab active when one task selected', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [fake({ id: 'a' })]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(<TestHarness selection={selection} tasks={tasks} />)
    expect(screen.getByRole('tab', { name: /overview/i })).toHaveAttribute(
      'aria-selected',
      'true'
    )
  })

  it('shows Pieces for a direct HTTP task', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [
      fake({ id: 'a', type: TaskType.Http, kind: TaskKind.Direct }),
    ]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')

    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.getByRole('tab', { name: /pieces/i })).toBeInTheDocument()
    expect(screen.queryByRole('tab', { name: /peers/i })).toBeNull()
    expect(screen.queryByRole('tab', { name: /trackers/i })).toBeNull()
  })

  it('does not show Pieces for a multi-instance HTTP media task', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [fake({ id: 'a', type: TaskType.Http, kind: TaskKind.Hls })]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')

    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.queryByRole('tab', { name: /pieces/i })).toBeNull()
  })

  it('reuses one keyed Activity cache across tab remounts', async () => {
    const user = userEvent.setup()
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [fake({ id: 'a' })]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(activityHookState.calls).toHaveLength(0)
    await user.click(screen.getByRole('tab', { name: /activity/i }))
    expect(activityHookState.calls.length).toBeGreaterThan(0)
    const firstCache = activityHookState.calls[0]?.[1]
    const firstMountCallCount = activityHookState.calls.length
    await user.click(screen.getByRole('tab', { name: /overview/i }))
    await user.click(screen.getByRole('tab', { name: /activity/i }))

    expect(activityHookState.calls.length).toBeGreaterThan(firstMountCallCount)
    expect(firstCache).toBeDefined()
    expect(
      activityHookState.calls
        .slice(firstMountCallCount)
        .every((call) => call[1] === firstCache)
    ).toBe(true)
  })

  it('hides folder reveal path for metadata-only tasks', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [
      fake({
        id: 'a',
        type: TaskType.Magnet,
        status: TaskStatus.FetchingMetadata,
        diskPath: '/',
      }),
    ]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.queryByRole('button', { name: '/' })).toBeNull()
  })

  it('shows the final BT destination instead of its internal workspace', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [
      fake({
        id: 'a',
        type: TaskType.Bt,
        kind: TaskKind.Bt,
        diskPath: '/downloads/.motrix/61282448e78c1fc29ac1/p',
        finalPath: '/downloads/sample-data',
      }),
    ]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')

    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.getByText('/downloads/sample-data')).toBeInTheDocument()
    expect(
      screen.queryByText('/downloads/.motrix/61282448e78c1fc29ac1/p')
    ).not.toBeInTheDocument()
  })

  it('displays and copies a native Windows UNC path without changing the task', async () => {
    const platform = vi
      .spyOn(transport, 'platform', 'get')
      .mockReturnValue('win32')
    try {
      const user = userEvent.setup()
      const clipboard = vi.spyOn(navigator.clipboard, 'writeText')
      const selection = createSelectionStore<DownloadTask>((task) => task.id)
      const storedPath = '//nas/share//模型 文件.bin'
      const nativePath = '\\\\nas\\share\\模型 文件.bin'
      const tasks = [fake({ finalPath: storedPath, diskPath: storedPath })]
      selection.getState().setItems(tasks)
      selection.getState().select('a')
      render(<TestHarness selection={selection} tasks={tasks} />)

      expect(screen.getByTitle(nativePath)).toBeInTheDocument()
      expect(screen.queryByTitle(storedPath)).not.toBeInTheDocument()
      await user.click(screen.getByRole('button', { name: 'Copy file path' }))
      expect(clipboard).toHaveBeenCalledExactlyOnceWith(nativePath)
      expect(tasks[0].finalPath).toBe(storedPath)
      clipboard.mockRestore()
    } finally {
      platform.mockRestore()
    }
  })

  it('does not switch inspector content during marquee preview', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [
      fake({ id: 'a', name: 'alpha', diskPath: '/alpha' }),
      fake({ id: 'b', name: 'beta', diskPath: '/beta' }),
      fake({ id: 'c', name: 'gamma', diskPath: '/gamma' }),
    ]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(<TestHarness selection={selection} tasks={tasks} />)

    expect(screen.getByText('alpha')).toBeInTheDocument()

    act(() => {
      selection.getState().marqueeSelect(1, 2)
    })

    expect(screen.getByText('alpha')).toBeInTheDocument()
    expect(screen.queryByText('beta')).not.toBeInTheDocument()

    act(() => {
      selection.getState().marqueeEnd()
    })

    expect(screen.queryByText('alpha')).not.toBeInTheDocument()
    expect(screen.getByText(/total size/i)).toBeInTheDocument()
  })

  it('preserves selection when closed and calls the dismissal callback', () => {
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [fake({ id: 'a' })]
    const onDismiss = vi.fn()
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(
      <TestHarness selection={selection} tasks={tasks} onDismiss={onDismiss} />
    )

    act(() => screen.getByRole('button', { name: 'Close' }).click())

    expect(selection.getState().committedSelectedIds).toEqual(new Set(['a']))
    expect(onDismiss).toHaveBeenCalledOnce()
  })

  it('dismisses directly from Activity while Task history is hidden', async () => {
    const user = userEvent.setup()
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [
      fake({
        id: 'a',
        status: TaskStatus.Error,
        updatedAt: BASE_TIME + 2_000,
        errorCode: DownloadErrorCode.NetworkError,
        errorMessage: 'connection refused',
      }),
    ]
    const onDismiss = vi.fn()
    activityHookState.current = {
      status: 'ready',
      snapshot: activitySnapshot(true),
    }
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(
      <TestHarness selection={selection} tasks={tasks} onDismiss={onDismiss} />
    )

    await user.click(screen.getByRole('tab', { name: /activity/i }))
    expect(
      screen.queryByTestId('task-inspector-activity-timeline')
    ).not.toBeInTheDocument()
    expect(screen.queryByRole('dialog', { name: 'Failed details' })).toBeNull()

    await user.keyboard('{Escape}')
    expect(selection.getState().committedSelectedIds).toEqual(new Set(['a']))
    expect(onDismiss).toHaveBeenCalledOnce()
  })

  it('keeps the chosen snap point when changing tabs', async () => {
    const user = userEvent.setup()
    const selection = createSelectionStore<DownloadTask>((t) => t.id)
    const tasks = [fake({ id: 'a' })]
    selection.getState().setItems([...tasks])
    selection.getState().select('a')
    render(<TestHarness selection={selection} tasks={tasks} />)

    const drawer = screen.getByRole('dialog')
    const height = drawer.style.height

    await user.click(screen.getByRole('tab', { name: /activity/i }))

    expect(drawer.style.height).toBe(height)
    expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
  })

  it.each(['single', 'multiple', 'finalizing'] as const)(
    'resizes from the %s header without consuming button keys',
    async (mode) => {
      const user = userEvent.setup()
      const selection = createSelectionStore<DownloadTask>((task) => task.id)
      const tasks = [
        fake({
          id: 'a',
          status:
            mode === 'finalizing' ? TaskStatus.Finalizing : TaskStatus.Paused,
        }),
        fake({ id: 'b' }),
      ]
      selection.getState().setItems(tasks)
      if (mode === 'multiple') selection.getState().selectAll()
      else selection.getState().select('a')
      render(<TestHarness selection={selection} tasks={tasks} />)

      const resize = screen.getByRole('separator', { name: 'Resize Inspector' })
      const header = resize.closest('[data-slot="drawer-header"]')
      const close = screen.getByRole('button', { name: 'Close' })
      expect(header).toContainElement(close)
      expect(resize).not.toContainElement(close)
      close.focus()
      await user.keyboard('{ArrowUp}')
      expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
      resize.focus()
      await user.keyboard('{Home}')
      expect(useDownloadsView.getState().inspectorSnap).toBe('compact')
      await user.keyboard('{ArrowUp}')
      expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
      await user.keyboard('{End}')
      expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')
    }
  )
})