test: remove narrow icon, hydration, and composition cases

This commit is contained in:
OrcaWin
2026-11-12 08:33:46 -08:00
parent 895cd026c0
commit 877b4e7e32
4 changed files with 0 additions and 420 deletions
@@ -1,7 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { RepoIcon } from '../../../shared/repo-icon'
import type { Repo } from '../../../shared/repo-types'
import { MAX_REPO_ICON_DATA_URL_BYTES } from '../../../shared/sidebar-list/repo-icon-data-urls-contract'
import { RepoIconDataUrls, repoIconId, type RepoIconPngEncoder } from './repo-icon-data-urls'
import type { RepoIconFetch } from './repo-icon-remote-fetch'
import { pngHeader } from './repo-icon-image-fixture'
@@ -12,14 +11,6 @@ const AVATAR: RepoIcon = {
source: 'github'
}
function upload(bytes: Uint8Array): RepoIcon {
return {
type: 'image',
src: `data:image/png;base64,${Buffer.from(bytes).toString('base64')}`,
source: 'upload'
}
}
function repo(id: string, repoIcon: RepoIcon | null): Repo {
return { id, path: `/r/${id}`, displayName: id, badgeColor: '#000', addedAt: 0, repoIcon }
}
@@ -43,53 +34,7 @@ function setup(
return { icons, fetch, advance: (ms: number) => (now += ms) }
}
const ENCODED = new Uint8Array([1, 2, 3])
const ENCODED_URL = 'data:image/png;base64,AQID'
describe('RepoIconDataUrls with an encoder (desktop)', () => {
it('steps down to 32 px when the 64 px PNG is over the cap', async () => {
const huge = new Uint8Array(MAX_REPO_ICON_DATA_URL_BYTES)
const encoder = vi.fn<RepoIconPngEncoder>((_bytes, edge) => (edge === 64 ? huge : ENCODED))
const { icons } = setup([repo('a', AVATAR)], { encoder })
expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBe(ENCODED_URL)
expect(encoder.mock.calls.map(([, edge]) => edge)).toEqual([64, 32])
})
it('falls back when neither encoding nor passthrough fits the cap', async () => {
const icon = upload(pngHeader(64, 64, MAX_REPO_ICON_DATA_URL_BYTES))
const huge = new Uint8Array(MAX_REPO_ICON_DATA_URL_BYTES)
const encoder = vi.fn<RepoIconPngEncoder>(() => huge)
const { icons } = setup([repo('a', icon)], { encoder })
expect((await icons.read([repoIconId(icon)!])).icons[0].dataUrl).toBeNull()
expect(encoder).toHaveBeenCalledTimes(2)
})
})
describe('RepoIconDataUrls caps', () => {
it('refuses bytes that are not a readable raster image, before decoding', async () => {
const encoder = vi.fn<RepoIconPngEncoder>(() => ENCODED)
const { icons } = setup([repo('a', AVATAR)], {
encoder,
fetch: async () => pngResponse(new Uint8Array([1, 2, 3, 4]))
})
expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBeNull()
expect(encoder).not.toHaveBeenCalled()
})
it('refuses a fetched image over 512 px before decoding', async () => {
const encoder = vi.fn<RepoIconPngEncoder>(() => ENCODED)
const { icons } = setup([repo('a', AVATAR)], {
encoder,
fetch: async () => pngResponse(pngHeader(513, 64))
})
expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBeNull()
expect(encoder).not.toHaveBeenCalled()
})
it('runs at most four fetches at once', async () => {
const releases: (() => void)[] = []
let active = 0
@@ -126,16 +71,6 @@ describe('RepoIconDataUrls caps', () => {
})
describe('RepoIconDataUrls cache', () => {
it('fetches an avatar shared by two repos once, across concurrent and later reads', async () => {
const { icons, fetch } = setup([repo('a', AVATAR), repo('b', { ...AVATAR, label: 'b' })])
const id = repoIconId(AVATAR)!
await Promise.all([icons.read([id, id]), icons.read([id])])
await icons.read([id])
expect(fetch).toHaveBeenCalledTimes(1)
})
it('retries a failed fetch after five minutes, a success only after an hour', async () => {
let fail = true
const { icons, fetch, advance } = setup([repo('a', AVATAR)], {
@@ -156,27 +91,4 @@ describe('RepoIconDataUrls cache', () => {
await icons.read([id])
expect(fetch).toHaveBeenCalledTimes(3)
})
it('evicts the least recently read icons past 1 MiB', async () => {
const avatars = Array.from({ length: 80 }, (_, index): RepoIcon => ({
...AVATAR,
src: `https://github.com/owner${index}.png`
}))
// Each encoded icon is just under the 16 KiB cap, so 80 of them overflow 1 MiB.
const nearCap = new Uint8Array(12 * 1024 - 64)
const { icons, fetch } = setup(
avatars.map((icon, index) => repo(`r${index}`, icon)),
{ encoder: () => nearCap }
)
const ids = avatars.map((icon) => repoIconId(icon)!)
for (let start = 0; start < ids.length; start += 16) {
await icons.read(ids.slice(start, start + 16))
}
expect(fetch).toHaveBeenCalledTimes(80)
await icons.read([ids[79]])
expect(fetch).toHaveBeenCalledTimes(80)
await icons.read([ids[0]])
expect(fetch).toHaveBeenCalledTimes(81)
})
})
@@ -1,110 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
fetchRemoteRepoIcon,
REPO_ICON_FETCH_MAX_BYTES,
type RepoIconFetch
} from './repo-icon-remote-fetch'
import { pngHeader } from './repo-icon-image-fixture'
const AVATAR = 'https://github.com/stablyai.png?size=64'
function image(bytes: Uint8Array, headers: Record<string, string> = {}): Response {
return new Response(Buffer.from(bytes), {
status: 200,
headers: { 'content-type': 'image/png', ...headers }
})
}
function redirect(location: string): Response {
return new Response(null, { status: 302, headers: { location } })
}
describe('fetchRemoteRepoIcon', () => {
it('follows up to three https redirects without cookies', async () => {
const fetch = vi
.fn<RepoIconFetch>()
.mockResolvedValueOnce(redirect('https://avatars.example/a'))
.mockResolvedValueOnce(redirect('/b'))
.mockResolvedValueOnce(redirect('https://avatars.example/c'))
.mockResolvedValueOnce(image(pngHeader(64, 64)))
const fetched = await fetchRemoteRepoIcon(AVATAR, fetch)
expect(fetched?.mimeType).toBe('image/png')
expect(fetch.mock.calls.map(([url]) => url)).toEqual([
AVATAR,
'https://avatars.example/a',
'https://avatars.example/b',
'https://avatars.example/c'
])
expect(fetch.mock.calls[0][1]).toMatchObject({ redirect: 'manual', credentials: 'omit' })
})
it('gives up on a redirect loop after three hops', async () => {
const fetch = vi.fn<RepoIconFetch>(async () => redirect(AVATAR))
expect(await fetchRemoteRepoIcon(AVATAR, fetch)).toBeNull()
expect(fetch).toHaveBeenCalledTimes(4)
})
it('refuses a redirect off https', async () => {
const fetch = vi.fn<RepoIconFetch>(async () => redirect('http://avatars.example/a'))
expect(await fetchRemoteRepoIcon(AVATAR, fetch)).toBeNull()
expect(fetch).toHaveBeenCalledTimes(1)
})
it('refuses a body declared over the cap without reading it', async () => {
const response = image(pngHeader(64, 64), {
'content-length': String(REPO_ICON_FETCH_MAX_BYTES + 1)
})
const cancel = vi.spyOn(response.body!, 'cancel')
expect(await fetchRemoteRepoIcon(AVATAR, async () => response)).toBeNull()
expect(cancel).toHaveBeenCalled()
})
it('stops reading an undeclared body once it passes the cap', async () => {
const chunk = new Uint8Array(16 * 1024)
let pulls = 0
const body = new ReadableStream<Uint8Array>({
pull: (controller) => {
pulls += 1
controller.enqueue(chunk)
}
})
const response = new Response(body, { headers: { 'content-type': 'image/png' } })
expect(await fetchRemoteRepoIcon(AVATAR, async () => response)).toBeNull()
expect(pulls).toBeLessThan(10)
})
it('refuses non-https and credentialed sources', async () => {
const fetch = vi.fn<RepoIconFetch>()
expect(await fetchRemoteRepoIcon('http://github.com/a.png', fetch)).toBeNull()
expect(await fetchRemoteRepoIcon('https://user:pw@github.com/a.png', fetch)).toBeNull()
expect(fetch).not.toHaveBeenCalled()
})
it('times out a server that never answers', async () => {
const fetch: RepoIconFetch = (_url, init) =>
new Promise((_resolve, reject) =>
init.signal?.addEventListener('abort', () => reject(init.signal?.reason))
)
expect(await fetchRemoteRepoIcon(AVATAR, fetch, 20)).toBeNull()
})
it('times out a body that stalls after the headers', async () => {
const fetch: RepoIconFetch = async (_url, init) => {
const body = new ReadableStream<Uint8Array>({
start: (controller) => {
init.signal?.addEventListener('abort', () => controller.error(init.signal?.reason))
}
})
return new Response(body, { headers: { 'content-type': 'image/png' } })
}
expect(await fetchRemoteRepoIcon(AVATAR, fetch, 20)).toBeNull()
})
})
@@ -192,105 +192,9 @@ describe('structured send racing the next IME composition', () => {
await act(async () => pressEnter(input))
expect(structured.send).toHaveBeenLastCalledWith('하', [])
})
it('keeps the composed text when a mid-composition clear lands away from the caret', async () => {
const dispatch = deferred()
const structured = transport({ dispatchCommand: vi.fn(() => dispatch.promise) })
renderComposer(structured)
const input = textarea()
changePrompt(input, 'abcd')
pressEnter(input)
fireEvent.compositionStart(input)
changePrompt(input, 'ab가cd')
await act(async () => {
dispatch.resolve(PASS_THROUGH)
await dispatch.promise
})
fireEvent.compositionEnd(input, { data: '가' })
expect(promptValue(input)).toBe('가')
})
it('keeps the draft when a rejected send races the next composition', async () => {
const dispatch = deferred()
const structured = transport({
dispatchCommand: vi.fn(() => dispatch.promise),
send: vi.fn(() => false)
})
renderComposer(structured)
const input = textarea()
changePrompt(input, '안녕')
pressEnter(input)
fireEvent.compositionStart(input)
changePrompt(input, '안녕하')
await act(async () => {
dispatch.resolve(PASS_THROUGH)
await dispatch.promise
})
fireEvent.compositionEnd(input, { data: '하' })
expect(promptValue(input)).toBe('안녕하')
})
it('keeps the draft when a handled command is rejected', async () => {
const structured = transport({
dispatchCommand: vi.fn(async () => ({ handled: true, accepted: false, error: 'nope' }))
})
renderComposer(structured)
const input = textarea()
changePrompt(input, '/model')
await act(async () => pressEnter(input))
expect(structured.onError).toHaveBeenCalledWith('nope', undefined)
expect(structured.send).not.toHaveBeenCalled()
expect(promptValue(input)).toBe('/model')
})
})
describe('a withdrawn message put back during an IME composition', () => {
// IME skips programmatic draft sync; retain returned text after its outbox entry is removed.
it('shows the text once the composition settles, after what was composed', () => {
renderComposer(transport())
const pane = `tab-${paneCounter}:structured`
const input = textarea()
changePrompt(input, 'abc')
fireEvent.compositionStart(input)
changePrompt(input, 'abc안')
act(() => appendNativeChatDraftCache(pane, 'withdrawn'))
changePrompt(input, 'abc안녕')
fireEvent.compositionEnd(input, { data: '안녕' })
expect(promptValue(input)).toBe('abc안녕\n\nwithdrawn')
expect(readNativeChatDraftCache(pane)).toBe('abc안녕\n\nwithdrawn')
})
it('shows the text once, however much is typed or composed after', () => {
renderComposer(transport())
const pane = `tab-${paneCounter}:structured`
const input = textarea()
changePrompt(input, 'abc')
fireEvent.compositionStart(input)
changePrompt(input, 'abc안')
act(() => appendNativeChatDraftCache(pane, 'withdrawn'))
fireEvent.compositionEnd(input, { data: '안' })
changePrompt(input, 'abc안\n\nwithdrawn!')
fireEvent.compositionStart(input)
changePrompt(input, 'abc안\n\nwithdrawn!가')
fireEvent.compositionEnd(input, { data: '가' })
expect(promptValue(input)).toBe('abc안\n\nwithdrawn!가')
expect(readNativeChatDraftCache(pane)).toBe('abc안\n\nwithdrawn!가')
})
// At settlement clear sent text before appending held returned text.
it('keeps the text when a sent message is also cleared mid-composition', async () => {
const dispatch = deferred()
@@ -1,126 +0,0 @@
import './terminal-hydration-store.test-bootstrap'
import { describe, expect, it, vi } from 'vitest'
import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types'
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
import { createTestStore, seedStore } from '../testing/app-store-test-fixture'
import { makeLayout, makeTab } from './terminal-tab.test-fixture'
import { makeWorktree } from '../slices/worktrees/worktree.test-fixture'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/runtime/sync-runtime-graph/graph-sync-scheduler', () => ({
scheduleRuntimeGraphSync: vi.fn()
}))
vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({
registerEagerPtyBuffer: vi.fn(),
ensurePtyDispatcher: vi.fn()
}))
describe('hydrateWorkspaceSession canonical terminal rows', () => {
it('drops only legacy rows that duplicate canonical PTY ownership', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
const sharedPtyId = 'daemon-session-1'
const recoveryPtyId = 'daemon-session-2'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'stale-tab',
activeWorktreeIdsOnShutdown: [worktreeId],
activeTabIdByWorktree: { [worktreeId]: 'stale-tab' },
tabsByWorktree: {
[worktreeId]: [
makeTab({ id: 'canonical-tab', worktreeId, ptyId: sharedPtyId }),
makeTab({ id: 'stale-tab', worktreeId, ptyId: sharedPtyId }),
makeTab({ id: 'recovery-tab', worktreeId, ptyId: recoveryPtyId })
]
},
terminalLayoutsByTabId: {
'canonical-tab': {
...makeLayout(),
ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId }
},
'stale-tab': {
...makeLayout(),
ptyIdsByLeafId: { 'stale-leaf': sharedPtyId }
},
'recovery-tab': {
...makeLayout(),
ptyIdsByLeafId: { 'recovery-leaf': recoveryPtyId }
}
},
remoteSessionIdsByTabId: {
'canonical-tab': sharedPtyId,
'stale-tab': sharedPtyId,
'recovery-tab': recoveryPtyId
},
unifiedTabs: {
[worktreeId]: [
{
id: 'canonical-unified-tab',
entityId: 'canonical-tab',
groupId: 'group-1',
worktreeId,
contentType: 'terminal',
label: 'Grok',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabGroups: {
[worktreeId]: [
{
id: 'group-1',
worktreeId,
activeTabId: 'canonical-unified-tab',
tabOrder: ['canonical-unified-tab']
}
]
}
}
store.getState().hydrateWorkspaceSession(session)
store.getState().hydrateTabsSession(session)
const reconciliation = store.getState().reconcileWorktreeTabModel(worktreeId)
const state = store.getState()
const persisted = buildWorkspaceSessionPayload(state)
expect(reconciliation.renderableTabCount).toBe(2)
expect(state.unifiedTabsByWorktree[worktreeId]?.map((tab) => tab.entityId)).toEqual([
'canonical-tab',
'recovery-tab'
])
expect(state.tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'recovery-tab'
])
expect(state.terminalLayoutsByTabId['stale-tab']).toBeUndefined()
expect(persisted.tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'recovery-tab'
])
expect(persisted.terminalLayoutsByTabId['stale-tab']).toBeUndefined()
expect(state.pendingReconnectTabByWorktree[worktreeId]).toEqual([
'canonical-tab',
'recovery-tab'
])
expect(state.pendingReconnectPtyIdByTabId).toEqual({
'canonical-tab': sharedPtyId,
'recovery-tab': recoveryPtyId
})
// The canonical row inherited the dropped row's PTY, so focus follows it instead of resetting.
expect(state.activeTabId).toBe('canonical-tab')
expect(state.activeTabIdByWorktree).toEqual({ [worktreeId]: 'canonical-tab' })
})
})