test: remove low-value renderer adapter and projection checks

This commit is contained in:
OrcaWin
2026-11-12 00:32:42 -08:00
parent 68d2314615
commit 53a562719d
9 changed files with 17 additions and 812 deletions
File diff suppressed because one or more lines are too long
@@ -4869,7 +4869,6 @@
"src/renderer/src/components/plugins/page/PluginCommandReplacementRow.test.tsx": 1926,
"src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx": 3367,
"src/renderer/src/components/plugins/page/PluginSettingsSection.test.tsx": 572,
"src/renderer/src/components/plugins/presentation/plugin-install-source.test.ts": 214,
"src/renderer/src/components/plugins/state/use-plugin-contribution-source.test.tsx": 1935,
"src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx": 518,
"src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx": 480,
@@ -5154,7 +5153,6 @@
"src/renderer/src/components/skills/SkillsPage.test.tsx": 3822,
"src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 207,
"src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333,
"src/renderer/src/components/stats/usage-overview-model.test.ts": 364,
"src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx": 2317,
"src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785,
"src/renderer/src/components/status-bar/UpdateStatusSegment.test.tsx": 2484,
@@ -5168,7 +5166,6 @@
"src/renderer/src/components/status-bar/resource-session-kill-confirmation.test.ts": 53,
"src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 290,
"src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 251,
"src/renderer/src/components/status-bar/usage-pool-label.test.ts": 170,
"src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx": 462,
"src/renderer/src/components/status-bar/use-resource-memory-snapshot.test.tsx": 321,
"src/renderer/src/components/status-bar/use-resource-pty-actions.test.tsx": 879,
@@ -5233,7 +5230,6 @@
"src/renderer/src/components/task-page/task-page-cache-selectors.test.ts": 108,
"src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1953,
"src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 63,
"src/renderer/src/components/task-page/use-task-page-source-display.test.tsx": 5228,
"src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303,
"src/renderer/src/components/terminal-pane/account-restart/detached/account-restart-queue-progress.test.ts": 1988,
"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-attention-dispatch.test.ts": 301,
@@ -69,33 +69,6 @@ it('leaves producer-owned messages and blocks untouched', () => {
expect(prose.blocks).toHaveLength(1)
})
// Parent streaming must retain the unchanged subagent map to avoid reordering it every frame.
it("keeps the subagent rows when only the conversation changes, and replaces them when a subagent's do", () => {
const projectList = createNativeChatMessageListProjection()
const child = (id: string, timestamp: number, text: string): NativeChatMessage => ({
...message(id, timestamp, [{ type: 'text', text }]),
agentId: 'task-1'
})
const tail = message('tail', 3, [{ type: 'text', text: 'Answer' }])
const rows = [child('child-1', 1, 'Reading'), child('child-2', 2, 'Found it'), tail]
const initial = projectList(rows)
const streamed = projectList([
...rows.slice(0, 2),
{ ...tail, blocks: [{ type: 'text', text: 'Answer grows' }] }
])
expect(streamed.conversation).not.toBe(initial.conversation)
expect(streamed.subagentRows).toBe(initial.subagentRows)
const childSpoke = projectList([...rows, child('child-3', 4, 'Done')])
expect(childSpoke.subagentRows).not.toBe(initial.subagentRows)
expect(childSpoke.subagentRows.get('task-1')?.map((row) => row.message.id)).toEqual([
'child-1',
'child-2',
'child-3'
])
})
it('preserves folded tools when an answer changes and another answer arrives', () => {
const project = createNativeChatMessageListProjection()
const prompt = message('prompt', 0, [{ type: 'text', text: 'Inspect' }], 'user')
@@ -177,116 +150,6 @@ it('rebuilds when a tool append folds into the streaming assistant', () => {
])
})
it('preserves row content and child attribution through reordering, admission and retention', () => {
const project = createNativeChatMessageListProjection()
const parent = {
...message('prompt', 1, [{ type: 'text', text: 'Inspect' }], 'user'),
journalPosition: { sequence: 1, index: 0 }
}
const tail = {
...message('answer', 2, [{ type: 'text', text: 'Found' }]),
journalPosition: { sequence: 2, index: 0 }
}
const child = {
...message('child', 3, [{ type: 'text', text: 'Child answer' }]),
agentId: 'child-a',
journalPosition: { sequence: 3, index: 0 }
}
const pending: NativeChatMessage = {
...message('pending', 4, [{ type: 'text', text: 'Next' }], 'user'),
pendingSend: 'active'
}
const inputs: NativeChatMessage[][] = [
[parent, tail],
[tail, parent],
[parent, tail, pending],
[
parent,
tail,
{ ...pending, pendingSend: undefined, journalPosition: { sequence: 4, index: 0 } }
],
[parent, tail, child],
[tail, child],
[tail, { ...child, journalPosition: { sequence: 5, index: 0 } }],
[tail, { ...tail, id: 'second', journalPosition: { sequence: 6, index: 0 } }],
[tail, tail],
[tail]
]
const promptOutput = {
id: 'prompt',
role: 'user',
blocks: [{ type: 'text', text: 'Inspect' }],
pendingSend: undefined
}
const answerOutput = {
id: 'answer',
role: 'assistant',
blocks: [{ type: 'text', text: 'Found' }],
pendingSend: undefined
}
const pendingOutput = {
id: 'pending',
role: 'user',
blocks: [{ type: 'text', text: 'Next' }],
pendingSend: 'active'
}
const admittedOutput = {
id: 'pending',
role: 'user',
blocks: [{ type: 'text', text: 'Next' }],
pendingSend: undefined
}
const secondOutput = {
id: 'second',
role: 'assistant',
blocks: [{ type: 'text', text: 'Found' }],
pendingSend: undefined
}
const expected = [
{ conversation: [promptOutput, answerOutput], childTurn: null },
{ conversation: [promptOutput, answerOutput], childTurn: null },
{ conversation: [promptOutput, answerOutput, pendingOutput], childTurn: null },
{ conversation: [promptOutput, answerOutput, admittedOutput], childTurn: null },
{ conversation: [promptOutput, answerOutput], childTurn: 'prompt' },
{ conversation: [answerOutput], childTurn: undefined },
{ conversation: [answerOutput], childTurn: undefined },
{ conversation: [answerOutput, secondOutput], childTurn: null },
{ conversation: [answerOutput, answerOutput], childTurn: null },
{ conversation: [answerOutput], childTurn: null }
]
for (const [index, rows] of inputs.entries()) {
const result = project(rows)
const output = expected[index]!
expect(
result.conversation.map(({ id, role, blocks, pendingSend }) => ({
id,
role,
blocks,
pendingSend
}))
).toEqual(output.conversation)
if (output.childTurn === null) {
expect([...result.subagentRows]).toEqual([])
} else {
expect([...result.subagentRows.keys()]).toEqual(['child-a'])
expect(result.subagentRows.get('child-a')).toMatchObject([
{
turnKey: output.childTurn,
message: {
id: 'child',
role: 'assistant',
blocks: [{ type: 'text', text: 'Child answer' }]
}
}
])
}
}
const eligible = { ...tail, blocks: [{ type: 'text' as const, text: 'Eligible revision' }] }
expect(project([eligible]).conversation.map(({ id, blocks }) => ({ id, blocks }))).toEqual([
{ id: 'answer', blocks: [{ type: 'text', text: 'Eligible revision' }] }
])
})
it('revises the correct duplicate occurrence, including aliases settled to the same row', () => {
const project = createNativeChatMessageListProjection()
const tail = message('answer', 1, [{ type: 'text', text: 'Found' }])
@@ -1,42 +0,0 @@
import { describe, expect, it } from 'vitest'
import { parsePluginInstallSource } from './plugin-install-source'
describe('parsePluginInstallSource', () => {
it('leaves the version to main when the git input names none', () => {
expect(parsePluginInstallSource('git', 'kolebayev/orca-md-layout')).toEqual({
ok: true,
source: { kind: 'git', url: 'https://github.com/kolebayev/orca-md-layout', ref: '' }
})
expect(
parsePluginInstallSource(
'git',
'https://github.com/kolebayev/orca-md-layout/releases/tag/v0.1.0'
)
).toEqual({
ok: true,
source: { kind: 'git', url: 'https://github.com/kolebayev/orca-md-layout', ref: 'v0.1.0' }
})
})
it('accepts HTTPS and SSH git URLs with an explicit ref', () => {
expect(parsePluginInstallSource('git', 'git@example.test:acme/plugin.git#main')).toEqual({
ok: true,
source: { kind: 'git', url: 'git@example.test:acme/plugin.git', ref: 'main' }
})
})
it('names why a git URL is refused', () => {
expect(parsePluginInstallSource('git', 'ext::sh -c touch% /tmp/pwned#main')).toEqual({
ok: false,
reason: 'invalid-git-url'
})
expect(parsePluginInstallSource('git', 'https://user@example.test/acme/plugin.git')).toEqual({
ok: false,
reason: 'git-url-credentials'
})
expect(parsePluginInstallSource('local-path', ' ')).toEqual({
ok: false,
reason: 'missing-local-path'
})
})
})
@@ -1,10 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { SshTarget } from '../../../../../../shared/ssh-types'
import {
applySshTargetSelectionClick,
groupSshTargetsBySource,
sshTargetDisplayOrder
} from './ssh-target-list-model'
import { applySshTargetSelectionClick, sshTargetDisplayOrder } from './ssh-target-list-model'
const host = (id: string, extra: Partial<SshTarget> = {}): SshTarget => ({
id,
@@ -16,53 +12,9 @@ const host = (id: string, extra: Partial<SshTarget> = {}): SshTarget => ({
...extra
})
describe('groupSshTargetsBySource', () => {
it('groups a legacy target without a source by the config-sync rule', () => {
const groups = groupSshTargetsBySource([
// The old import shape: alias kept as label/configHost, host is the resolved HostName.
host('legacy-import', {
source: undefined,
label: 'box',
configHost: 'box',
host: '10.0.0.5'
}),
// A legacy manual target lacks `source` too, but doesn't match that shape.
host('legacy-manual', { source: undefined, label: 'My box', host: 'box.example.test' }),
host('mine', { source: 'manual' }),
host('synced', { source: 'ssh-config' })
])
expect(groups.map((group) => [group.id, group.targets.map((t) => t.id)])).toEqual([
['ssh-config', ['legacy-import', 'synced']],
['manual', ['legacy-manual', 'mine']]
])
})
})
describe('applySshTargetSelectionClick', () => {
const orderedIds = ['a', 'b', 'c', 'd']
it('selects the visible range between the anchor and the Shift-clicked row', () => {
const next = applySshTargetSelectionClick({
selected: new Set(['d']),
orderedIds,
anchorId: 'd',
clickedId: 'b',
shiftKey: true
})
expect([...next].sort()).toEqual(['b', 'c', 'd'])
})
it('clears the range when the Shift-clicked row was selected', () => {
const next = applySshTargetSelectionClick({
selected: new Set(['a', 'b', 'c']),
orderedIds,
anchorId: 'a',
clickedId: 'c',
shiftKey: true
})
expect([...next]).toEqual([])
})
it('falls back to one row when the anchor is filtered out', () => {
const next = applySshTargetSelectionClick({
selected: new Set(),
@@ -1,50 +0,0 @@
import { describe, expect, it } from 'vitest'
import type {
CodexUsageDailyPoint,
CodexUsageScanState
} from '../../../../shared/codex-usage-types'
import { buildUsageOverview } from './usage-overview-model'
function enabledCodexScanState(): CodexUsageScanState {
return {
enabled: true,
isScanning: false,
lastScanStartedAt: 300,
lastScanCompletedAt: 400,
lastScanError: null,
hasAnyCodexData: true
}
}
describe('usage overview model', () => {
it('aggregates very large daily histories without spreading every day into Math.max', () => {
const codexDaily: CodexUsageDailyPoint[] = Array.from({ length: 130_000 }, (_, index) => {
const date = new Date(Date.UTC(2026, 0, 1 + index))
return {
day: date.toISOString().slice(0, 10),
inputTokens: index + 1,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
totalTokens: index + 1
}
})
const overview = buildUsageOverview({
claude: { scanState: null, summary: null, daily: [] },
codex: {
scanState: enabledCodexScanState(),
summary: null,
daily: codexDaily
},
opencode: { scanState: null, summary: null, daily: [] },
muse: { scanState: null, summary: null, daily: [] }
})
expect(overview.daily).toHaveLength(130_000)
expect(overview.bestDay?.totalTokens).toBe(130_000)
expect(overview.daily.at(-1)?.intensity).toBe(4)
})
})
@@ -1,87 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { ProviderRateLimits, RateLimitBucket } from '../../../../shared/rate-limit-types'
import { formatPoolShortLabel, formatStatusBarSectionLabel } from './usage-pool-label'
import { getTightestUsageSection } from './UsageRosterPanel'
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, values: Record<string, string> = {}) =>
Object.entries(values).reduce(
(text, [key, value]) => text.replace(`{{${key}}}`, value),
fallback
)
}))
vi.mock('@/components/agent/icons/AgentIcon', () => ({
AgentIcon: () => null
}))
vi.mock('@/hooks/useResetCountdownClock', () => ({ useResetCountdownClock: () => 0 }))
vi.mock('@/components/ui/dropdown-menu', () => ({ DropdownMenuItem: () => null }))
vi.mock('@/components/settings/form-controls/SettingsFormControls', () => ({
SettingsSegmentedControl: () => null
}))
const FIVE_HOURS = 300
const WEEK = 10_080
function pool(
group: string | undefined,
windowMinutes: number,
overrides: Partial<RateLimitBucket> = {}
): RateLimitBucket {
const windowName = windowMinutes === FIVE_HOURS ? '5h Limit Remaining' : 'Weekly Limit Remaining'
return {
name: group ? `${group} · ${windowName}` : 'Pro',
...(group ? { group, windowName } : {}),
usedPercent: 0,
windowMinutes,
resetsAt: null,
resetDescription: null,
...overrides
}
}
describe('pool labels', () => {
it('keeps full group names when two groups shorten to the same text', () => {
const buckets = [pool('Gemini Models', WEEK), pool('Gemini models', WEEK)]
expect(buckets.map((b) => formatPoolShortLabel(b, buckets))).toEqual([
'Gemini Models wk',
'Gemini models wk'
])
})
it('does not shorten another group to a name retained after a collision', () => {
const buckets = [
pool('Gemini Models', WEEK),
pool('Gemini models', WEEK),
pool('Gemini Models Models', WEEK)
]
expect(buckets.map((bucket) => formatPoolShortLabel(bucket, buckets))).toEqual([
'Gemini Models wk',
'Gemini models wk',
'Gemini Models Models wk'
])
})
})
describe('formatStatusBarSectionLabel', () => {
it('labels a tie with the pool, not the derived weekly section', () => {
const buckets = [
pool('Gemini Models', FIVE_HOURS, { usedPercent: 30 }),
pool('Gemini Models', WEEK, { usedPercent: 50 }),
pool('Claude and GPT models', WEEK, { usedPercent: 10 })
]
const p: ProviderRateLimits = {
provider: 'antigravity',
session: null,
// Derived from the pools, so it ties with the Gemini weekly pool.
weekly: { usedPercent: 50, windowMinutes: WEEK, resetsAt: null, resetDescription: null },
buckets,
updatedAt: 0,
error: null,
status: 'ok'
}
const tightest = getTightestUsageSection(p)
expect(tightest?.window).toBe(buckets[1])
expect(formatStatusBarSectionLabel(p, tightest!)).toBe('Gemini wk')
})
})
@@ -1,291 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture'
import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types'
import type { Repo } from '../../../../shared/repo-types'
import type { GitHubWorkItem } from '../../../../shared/github/work-item-types'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache'
import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture'
import {
Q1,
upstream,
fork,
sources,
repo,
view,
Harness,
installSourceDisplayTestLifecycle
} from './use-task-page-source-display.test-fixture'
vi.mock('@/components/github/PRFilterDropdowns', () => ({ default: () => null }))
// The list's own states are under test; mounted-rows shows the row titles.
vi.mock('./github/Rows', () => ({ TaskPageGitHubRows: () => null }))
installSourceDisplayTestLifecycle()
describe('mounted Tasks source lifetime', () => {
const flush = async () => {
for (let i = 0; i < 16; i++) {
await Promise.resolve()
}
}
function item(owner: string): GitHubWorkItem {
return {
id: 'issue:1',
repoId: repo.id,
type: 'issue',
number: 1,
title: owner,
state: 'open',
url: `https://github.com/${owner}/project/issues/1`,
labels: [],
author: null,
updatedAt: '2026-11-01T00:00:00Z'
}
}
const answer = (owner: GitHubOwnerRepo) => ({
items: [item(owner.owner)],
sources: sources(owner)
})
// One selected repo on Upstream, its first list answered and the resume step done.
async function mountUpstream(list = false, repos = [repo]) {
useAppStore.setState({
repos,
settings: createGlobalSettingsFixture({ defaultRepoSelection: [repo.id] }),
taskPageData: { taskSource: 'github' }
})
let mounted!: ReturnType<typeof render>
await act(async () => {
mounted = render(<Harness runRequests list={list} />)
})
await act(async () => {
view.setTaskResumeApplied(true)
await flush()
})
return mounted
}
it('keeps the mounted picker across a held save/list and ends an inverted A→B→A with its own rows and count', async () => {
const list = vi.mocked(window.api.gh.listWorkItems).mockResolvedValue(answer(upstream))
const count = vi.mocked(window.api.gh.countWorkItems).mockResolvedValue(180)
await mountUpstream()
expect(screen.getByTestId('mounted-rows')).toHaveTextContent(upstream.owner)
const knownA = screen.getByTestId('mounted-count').textContent
expect(knownA).not.toBe('unknown')
const picker = screen.getByRole('group', { name: 'Issue source' })
const save = Promise.withResolvers<Repo>()
vi.mocked(window.api.repos.update).mockReturnValueOnce(save.promise)
const b = Promise.withResolvers<Awaited<ReturnType<typeof window.api.gh.listWorkItems>>>()
list.mockReturnValue(b.promise)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Origin' }))
await flush()
})
expect(screen.getByRole('group', { name: 'Issue source' })).toBe(picker)
expect(screen.getByRole('button', { name: 'Origin' })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByTestId('mounted-rows')).toBeEmptyDOMElement()
expect(screen.getByTestId('mounted-count')).toHaveTextContent('unknown')
await act(async () => {
save.resolve({ ...repo, issueSourcePreference: 'origin' })
await flush()
})
const a = Promise.withResolvers<Awaited<ReturnType<typeof window.api.gh.listWorkItems>>>()
const nextCount = Promise.withResolvers<number>()
list.mockReturnValue(a.promise)
count.mockReturnValue(nextCount.promise)
vi.mocked(window.api.repos.update).mockImplementation(async ({ updates }) => ({
...repo,
issueSourcePreference: updates.issueSourcePreference
}))
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Upstream' }))
await flush()
})
expect(screen.getByRole('group', { name: 'Issue source' })).toBe(picker)
expect(screen.getByTestId('mounted-count')).toHaveTextContent(knownA!)
await act(async () => {
a.resolve(answer(upstream))
nextCount.resolve(72)
await flush()
})
const currentCount = screen.getByTestId('mounted-count').textContent
await act(async () => {
b.resolve(answer(fork))
await flush()
})
expect(screen.getByTestId('mounted-rows')).toHaveTextContent(upstream.owner)
expect(screen.getByTestId('mounted-count')).toHaveTextContent(currentCount!)
expect(view.tasksLoading).toBe(false)
expect(view.tasksRefreshing).toBe(false)
// A selected source's known total remains visible while its next answer is held.
const refresh = Promise.withResolvers<number>()
count.mockReturnValue(refresh.promise)
await act(async () => {
view.setTaskRefreshNonce((n) => n + 1)
await flush()
})
expect(screen.getByTestId('mounted-count')).toHaveTextContent(currentCount!)
await act(async () => {
refresh.resolve(108)
await flush()
})
expect(screen.getByTestId('mounted-count').textContent).not.toBe(currentCount)
})
it('ends loading at once when a held save loses its last selected owner, and Refresh keeps it ended', async () => {
const list = vi.mocked(window.api.gh.listWorkItems).mockResolvedValue(answer(upstream))
// A folder project keeps Tasks open after the only GitHub-eligible repo is removed.
const folder: Repo = {
...repo,
id: 'folder',
path: '/folder',
kind: 'folder',
upstream: undefined
}
const { container } = await mountUpstream(true, [repo, folder])
const save = Promise.withResolvers<Repo>()
vi.mocked(window.api.repos.update).mockReturnValueOnce(save.promise)
const origin = Promise.withResolvers<Awaited<ReturnType<typeof window.api.gh.listWorkItems>>>()
list.mockReturnValue(origin.promise)
const skeletons = () => container.querySelector('.animate-pulse') !== null
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Origin' }))
await flush()
})
expect(skeletons()).toBe(true)
expect(screen.queryByText('No matching GitHub work')).toBeNull()
const ended = () => {
expect(view.selectedRepos).toEqual([])
expect(useAppStore.getState().githubSourceCollections.saving(repo)).toBe(false)
expect(skeletons()).toBe(false)
expect(screen.getByTestId('mounted-pending')).toHaveTextContent('false')
expect(screen.getByTestId('mounted-rows')).toBeEmptyDOMElement()
}
await act(async () => {
useAppStore.setState({ repos: [folder] })
await flush()
})
ended()
await act(async () => {
save.resolve({ ...repo, issueSourcePreference: 'origin' })
origin.resolve(answer(fork))
await flush()
})
await act(async () => {
view.setTaskRefreshNonce((n) => n + 1)
await flush()
})
ended()
})
it.each(['upstream', 'origin'] as const)(
"settles repeated legacy-host deliveries with explicit source preferences and shows each kind's reported source and count",
async (preference) => {
clearRuntimeCompatibilityCacheForTests()
// A paired host up to v1.4.60: issues follow the saved preference, PRs resolve origin, no originCandidate.
const legacy = {
issues: preference === 'upstream' ? upstream : fork,
prs: fork,
upstreamCandidate: upstream
}
const QP = 'is:pr is:open'
const totals: Record<string, number> = { [Q1]: 120, [QP]: 300 }
const held: { method: string; query: string; resolve: (response: unknown) => void }[] = []
const call = vi.fn(({ method, params }: { method: string; params?: { query?: string } }) => {
if (method === 'status.get') {
return Promise.resolve(createCompatibleRuntimeStatusResponse())
}
const { promise, resolve } = Promise.withResolvers<unknown>()
// Row decorations such as PR checks are outside the list/count cycle under test.
if (method === 'github.listWorkItems' || method === 'github.countWorkItems') {
held.push({ method, query: params?.query ?? '', resolve })
}
return promise
})
Object.assign(window.api, { runtimeEnvironments: { call } })
const recovery = vi.fn(async () => {})
const hosted: Repo = {
...repo,
path: '/server/project',
executionHostId: 'runtime:env-1',
issueSourcePreference: preference
}
useAppStore.setState({
repos: [hosted],
settings: createGlobalSettingsFixture({ defaultRepoSelection: [hosted.id] }),
taskPageData: { taskSource: 'github' },
fetchReposForAllHosts: recovery
})
const { container } = render(<Harness runRequests list />)
await act(async () => {
view.setAppliedTaskSearch(Q1)
view.setTaskResumeApplied(true)
await flush()
})
const collections = useAppStore.getState().githubSourceCollections
const lifetime = () => [
collections.context(hosted),
useAppStore.getState().workItemsInvalidationNonce
]
const before = lifetime()
// Answers exactly the one list and count this action owes; an unsolicited next request stays held and fails.
const deliver = async (query: string) => {
expect(held.map((entry) => entry.method).sort()).toEqual([
'github.countWorkItems',
'github.listWorkItems'
])
expect(held.every((entry) => entry.query === query)).toBe(true)
const kind = query === QP ? 'pr' : 'issue'
const source = kind === 'pr' ? legacy.prs : legacy.issues
for (const entry of held.splice(0)) {
const result =
entry.method === 'github.countWorkItems'
? totals[query]
: {
items: [{ ...item(`${source.owner} ${kind}`), id: `${kind}:1`, type: kind }],
sources: legacy
}
entry.resolve({
id: entry.method,
ok: true,
result,
_meta: { runtimeId: 'remote-runtime' }
})
}
await act(flush)
await act(flush)
expect(held).toEqual([])
expect(recovery).not.toHaveBeenCalled()
expect(lifetime()).toEqual(before)
const slug = `${source.owner}/${source.repo}`
expect(screen.getByTestId('mounted-rows')).toHaveTextContent(`${source.owner} ${kind}`)
expect(screen.getByTestId('mounted-count')).toHaveTextContent(
String(Math.ceil(totals[query] / view.githubPerRepoPageLimit))
)
expect(container.querySelector('.animate-pulse')).toBeNull()
expect(screen.getByTestId('mounted-pending')).toHaveTextContent('false')
expect(view.tasksLoading || view.tasksRefreshing || view.tasksFiltering).toBe(false)
expect(view.taskSourceContextSummary.title).toContain(`Source: ${slug}`)
expect(view.selectedGitHubRepoExternalLink?.label).toBe(slug)
expect(screen.queryByRole('group', { name: 'Issue source' })).toBeNull()
}
await deliver(Q1)
await act(async () => {
view.setAppliedTaskSearch(QP)
await flush()
})
// The issue total never stands in for the PR query's.
expect(screen.getByTestId('mounted-count')).toHaveTextContent('unknown')
await deliver(QP)
// Two explicit Refreshes with identical answers: one list/count cycle each, then quiet.
for (let press = 0; press < 2; press++) {
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Refresh GitHub work' }))
await flush()
})
await deliver(QP)
}
}
)
})
@@ -1,144 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import type { WorkItemsCacheSources } from '@/store/github/cache/cache-model'
import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture'
import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types'
import type { Repo } from '../../../../shared/repo-types'
import { getTaskPageRepoSourceContext } from '../../lib/work-items/task-repo-source-context'
import {
Q1,
Q2,
upstream,
fork,
sources,
repo,
sshTwin,
listAnswers,
setIssueSourcePreference,
view,
Harness,
installSourceDisplayTestLifecycle
} from './use-task-page-source-display.test-fixture'
vi.mock('@/components/github/PRFilterDropdowns', () => ({ default: () => null }))
installSourceDisplayTestLifecycle()
function mount(repos: Repo[], query = Q1) {
useAppStore.setState({
repos,
settings: createGlobalSettingsFixture({
defaultRepoSelection: [...new Set(repos.map((r) => r.id))]
}),
taskPageData: { taskSource: 'github' }
})
const mounted = render(<Harness />)
applyQuery(query)
return mounted
}
function applyQuery(query: string) {
act(() => view.setAppliedTaskSearch(query))
}
async function fetchList(row: Repo, query: string, answer?: WorkItemsCacheSources) {
if (answer) {
listAnswers.set(`${row.path}\0${query}`, answer)
}
await act(async () => {
await useAppStore
.getState()
.fetchWorkItems(row.id, row.path, view.githubPerRepoPageLimit, query, {
force: true,
sourceContext: getTaskPageRepoSourceContext(row, 'github')
})
.catch(() => [])
})
}
function sourceRowCount() {
return screen.queryAllByRole('group', { name: 'Issue source' }).length
}
// Summary, single-repo link and Filters source row must make the same claim.
function expectSurfaces(
source: (GitHubOwnerRepo & { host?: string }) | null,
knownCandidates = false
) {
const { taskSourceContextSummary: summary, selectedGitHubRepoExternalLink: link } = view
if (!source) {
expect(summary.label).toMatch(/Selected project$/)
expect(summary.title).not.toMatch(/Source:/)
expect(link).toBeNull()
expect(sourceRowCount()).toBe(knownCandidates ? 1 : 0)
return
}
const slug = `${source.owner}/${source.repo}`
expect(summary.label).toMatch(new RegExp(`${slug}$`))
expect(summary.title).toContain(`Source: ${slug}`)
expect(link).toEqual({ url: `https://${source.host ?? 'github.com'}/${slug}`, label: slug })
expect(sourceRowCount()).toBe(1)
}
describe('Tasks source display', () => {
it('carries the last shown entry across a query change, live, until a current entry or eviction', async () => {
mount([repo])
await fetchList(repo, Q1, sources(fork))
expectSurfaces(fork)
applyQuery(Q2)
expectSurfaces(fork)
// Notices and Retry still read only the current query's entry.
expect(view.perRepoSourceState[0].sources).toBeNull()
expect(view.unresolvedSourceRepos).toEqual([])
// The shown entry is read live: an unchanged refresh keeps it, a changed one is followed.
await fetchList(repo, Q1)
expectSurfaces(fork)
await fetchList(repo, Q1, sources(upstream))
expectSurfaces(upstream)
// A changed served mapping retires old claims across queries; raw choices stay mounted.
await fetchList(repo, 'is:issue is:closed', sources(fork))
expectSurfaces(null, true)
await fetchList(repo, Q2, sources(fork))
expectSurfaces(fork)
fireEvent.click(screen.getByRole('button', { name: 'Origin' }))
expect(setIssueSourcePreference).toHaveBeenCalledWith('repo', '/repo', 'origin', 'local')
// An owned preference change detaches rows while known choices stay mounted.
applyQuery('is:issue is:closed sort:updated')
expectSurfaces(fork)
await act(() =>
useAppStore.getState().setIssueSourcePreference('repo', '/repo', 'upstream', 'local')
)
expectSurfaces(null, true)
await fetchList(repo, 'is:issue is:closed sort:updated', sources(upstream))
expectSurfaces(upstream)
})
it('keeps each host copy and selected row on its own history', async () => {
mount([repo, sshTwin])
await fetchList(repo, Q1, sources(fork))
applyQuery(Q2)
expect(view.githubSourceDisplayState.map((state) => state.sources?.issues ?? null)).toEqual([
fork,
null
])
expect(sourceRowCount()).toBe(1)
fireEvent.click(screen.getByRole('button', { name: 'Origin' }))
expect(setIssueSourcePreference).toHaveBeenCalledWith('repo', '/repo', 'origin', 'local')
// A row that leaves the selection forgets its history.
act(() => view.setRepoSelection(new Set()))
act(() => view.setRepoSelection(new Set(['repo'])))
expect(view.githubSourceDisplayState.map((state) => state.sources?.issues ?? null)).toEqual([
null,
null
])
expect(sourceRowCount()).toBe(1)
})
})