mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(frontend): order linked server projects by last activity and keep cached lists on refetch errors
This commit is contained in:
1 parent
578a2211ba
commit
36d35cc974
5 files changed
+185
-22
No files matched your search
@@ -37,6 +37,14 @@ export type OpenCodeLocationInfo = Awaited<ReturnType<OpenCodeApi['location']['g
|
||||
|
||||
export type OpenCodeProject = Awaited<ReturnType<OpenCodeApi['project']['list']>>[number]
|
||||
|
||||
/**
|
||||
* The timestamp a project list sorts and labels on: the server's last-activity time, falling back
|
||||
* to the record's update time for a project that has never recorded activity.
|
||||
*/
|
||||
export function projectActivityTimestamp(project: OpenCodeProject): number {
|
||||
return project.time.active || project.time.updated
|
||||
}
|
||||
|
||||
export type VcsInfo = Awaited<ReturnType<OpenCodeApi['vcs']['get']>>['data']
|
||||
|
||||
export type VcsFileStatus = Awaited<ReturnType<OpenCodeApi['vcs']['status']>>['data'][number]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { OpenCodeProject } from '@/api/opencode'
|
||||
@@ -87,14 +87,19 @@ const kitchen = {
|
||||
updatedAt: 2,
|
||||
}
|
||||
|
||||
function createProject(id: string, name: string | undefined, canonical: string): OpenCodeProject {
|
||||
function createProject(
|
||||
id: string,
|
||||
name: string | undefined,
|
||||
canonical: string,
|
||||
time: OpenCodeProject['time'] = { created: 1, updated: 2, active: 0 },
|
||||
): OpenCodeProject {
|
||||
return {
|
||||
id,
|
||||
canonical,
|
||||
name,
|
||||
time: { created: 1, updated: 2 },
|
||||
time,
|
||||
sandboxes: [],
|
||||
} as OpenCodeProject
|
||||
}
|
||||
}
|
||||
|
||||
function createSession(id: string, directory: string, updated = Date.now()): SessionFixture {
|
||||
@@ -117,10 +122,12 @@ function LocationSpy() {
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
function createWrapper(initialEntry: string) {
|
||||
const queryClient = new QueryClient({
|
||||
function createWrapper(
|
||||
initialEntry: string,
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
}),
|
||||
) {
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
@@ -187,6 +194,32 @@ describe('RemoteProjectNavList', () => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('orders projects by recent activity', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
createProject('p_stale', 'Stale', '/projects/stale', {
|
||||
created: now - 10_800_000,
|
||||
updated: now - 300_000,
|
||||
active: now - 10_800_000,
|
||||
}),
|
||||
createProject('p_recent', 'Recent', '/projects/recent', {
|
||||
created: now - 10_800_000,
|
||||
updated: now - 10_800_000,
|
||||
active: now - 300_000,
|
||||
}),
|
||||
])
|
||||
|
||||
const { container } = render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/'),
|
||||
})
|
||||
|
||||
await screen.findByText('Recent')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Recent')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Recent')).toBeLessThan(text.indexOf('Stale'))
|
||||
})
|
||||
|
||||
it('expands the project of the current project route and loads its sessions', async () => {
|
||||
render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha'),
|
||||
@@ -287,6 +320,28 @@ describe('RemoteProjectNavList', () => {
|
||||
expect(await screen.findByText('Could not load projects')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the cached project list when a refetch fails', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
mocks.listProjects.mockResolvedValueOnce([alpha, beta]).mockRejectedValueOnce(new Error('offline'))
|
||||
|
||||
render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/', queryClient),
|
||||
})
|
||||
|
||||
await screen.findByText('Alpha')
|
||||
await act(async () => {
|
||||
await queryClient.refetchQueries()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
expect(screen.getByText('Alpha')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Could not load projects')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports an unreachable server on a failed project load', async () => {
|
||||
mocks.listProjects.mockRejectedValue(new Error('offline'))
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { listProjects, type OpenCodeProject } from '@/api/opencode'
|
||||
import { listProjects, projectActivityTimestamp, type OpenCodeProject } from '@/api/opencode'
|
||||
import type { Session } from '@/api/types'
|
||||
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
|
||||
import { useSessionsAcrossDirectories, sessionQueryOptions } from '@/hooks/useOpenCode'
|
||||
@@ -393,14 +393,20 @@ export function RemoteProjectNavList({
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const projects = useMemo(() => projectsQuery.data ?? [], [projectsQuery.data])
|
||||
const projects = useMemo(
|
||||
() =>
|
||||
[...(projectsQuery.data ?? [])].sort(
|
||||
(a, b) => projectActivityTimestamp(b) - projectActivityTimestamp(a),
|
||||
),
|
||||
[projectsQuery.data],
|
||||
)
|
||||
const trimmedSearch = search.trim()
|
||||
|
||||
if (isServersLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (!server) return <SessionNavStatus>Server not found</SessionNavStatus>
|
||||
if (!server.enabled) return <SessionNavStatus>Server is disabled</SessionNavStatus>
|
||||
if (projectsQuery.isLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (projectsQuery.isError) {
|
||||
if (projectsQuery.isError && projectsQuery.data === undefined) {
|
||||
return (
|
||||
<SessionNavStatus>
|
||||
{statusById[serverId]?.connected === false ? 'Server unreachable' : 'Could not load projects'}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Folder, FolderGit2, FolderPlus, GitBranch, Search, Server } from 'lucide-react'
|
||||
import { listProjects, type OpenCodeProject } from '@/api/opencode'
|
||||
import { listProjects, projectActivityTimestamp, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useProjectActivityState } from '@/hooks/useActiveWork'
|
||||
@@ -27,7 +27,7 @@ function projectName(project: OpenCodeProject): string {
|
||||
function RemoteProjectCard({ project, serverId }: { project: OpenCodeProject; serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const activityState = useProjectActivityState(serverId, project.canonical)
|
||||
const updatedAt = project.time.updated
|
||||
const activeAt = projectActivityTimestamp(project)
|
||||
|
||||
return (
|
||||
<RepoCardShell
|
||||
@@ -45,7 +45,7 @@ function RemoteProjectCard({ project, serverId }: { project: OpenCodeProject; se
|
||||
<span className="truncate">{project.canonical}</span>
|
||||
</span>
|
||||
}
|
||||
activityLabel={updatedAt > 0 ? formatShortRelativeTime(new Date(updatedAt)) : undefined}
|
||||
activityLabel={activeAt > 0 ? formatShortRelativeTime(new Date(activeAt)) : undefined}
|
||||
isInteractive
|
||||
onClick={() => navigate(getServerProjectPath(serverId, project.canonical))}
|
||||
/>
|
||||
@@ -102,7 +102,14 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const projects = useMemo(() => projectsQuery.data ?? [], [projectsQuery.data])
|
||||
const projects = useMemo(
|
||||
() =>
|
||||
[...(projectsQuery.data ?? [])].sort(
|
||||
(a, b) => projectActivityTimestamp(b) - projectActivityTimestamp(a),
|
||||
),
|
||||
[projectsQuery.data],
|
||||
)
|
||||
const showsProjectError = projectsQuery.isError && projectsQuery.data === undefined
|
||||
|
||||
const filteredProjects = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
@@ -138,7 +145,7 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && projectsQuery.isError ? (
|
||||
{server && !isDisabled && showsProjectError ? (
|
||||
<Card className="flex flex-col items-center gap-3 p-6 text-center">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
@@ -155,7 +162,7 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && !projectsQuery.isError ? (
|
||||
{server && !isDisabled && !showsProjectError ? (
|
||||
projectsQuery.isLoading ? (
|
||||
<RemoteProjectListLoading />
|
||||
) : projects.length === 0 ? (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
@@ -15,9 +15,10 @@ const mocks = vi.hoisted(() => ({
|
||||
isMobile: true,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listProjects: mocks.listProjects,
|
||||
}))
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return { ...actual, listProjects: mocks.listProjects }
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useCreateSession: mocks.useCreateSession,
|
||||
@@ -113,9 +114,9 @@ function createQueryClient() {
|
||||
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
}
|
||||
|
||||
function renderProjectList(serverId = 'srv_kitchen') {
|
||||
function renderProjectList(serverId = 'srv_kitchen', queryClient = createQueryClient()) {
|
||||
return render(
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Routes>
|
||||
<Route path="/" element={<RemoteProjectList serverId={serverId} />} />
|
||||
@@ -147,6 +148,66 @@ describe('RemoteProjectList', () => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('orders projects by recent activity and labels rows with that activity time', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
...project,
|
||||
id: 'prj_stale',
|
||||
name: 'Stale',
|
||||
canonical: '/work/stale',
|
||||
time: { created: now - 10_800_000, updated: now - 300_000, active: now - 10_800_000 },
|
||||
},
|
||||
{
|
||||
...project,
|
||||
id: 'prj_recent',
|
||||
name: 'Recent',
|
||||
canonical: '/work/recent',
|
||||
time: { created: now - 10_800_000, updated: now - 10_800_000, active: now - 300_000 },
|
||||
},
|
||||
])
|
||||
|
||||
const { container } = renderProjectList()
|
||||
|
||||
await screen.findByText('Recent')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Recent')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Recent')).toBeLessThan(text.indexOf('5m ago'))
|
||||
expect(text.indexOf('5m ago')).toBeLessThan(text.indexOf('Stale'))
|
||||
expect(text.indexOf('Stale')).toBeLessThan(text.indexOf('3h ago'))
|
||||
})
|
||||
|
||||
it('falls back to the update time when a project has no activity time', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
...project,
|
||||
id: 'prj_older',
|
||||
name: 'Older',
|
||||
canonical: '/work/older',
|
||||
time: { created: now - 10_800_000, updated: now - 10_800_000 },
|
||||
},
|
||||
{
|
||||
...project,
|
||||
id: 'prj_newer',
|
||||
name: 'Newer',
|
||||
canonical: '/work/newer',
|
||||
time: { created: now - 10_800_000, updated: now - 300_000 },
|
||||
},
|
||||
])
|
||||
|
||||
const { container } = renderProjectList()
|
||||
|
||||
await screen.findByText('Newer')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Newer')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Newer')).toBeLessThan(text.indexOf('5m ago'))
|
||||
expect(text.indexOf('5m ago')).toBeLessThan(text.indexOf('Older'))
|
||||
expect(text.indexOf('Older')).toBeLessThan(text.indexOf('3h ago'))
|
||||
})
|
||||
|
||||
it('opens the remote project page when a project card is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderProjectList()
|
||||
@@ -342,6 +403,32 @@ describe('RemoteProjectList', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the load error when no project data is cached', async () => {
|
||||
mocks.listProjects.mockRejectedValue(new Error('offline'))
|
||||
|
||||
renderProjectList()
|
||||
|
||||
expect(await screen.findByText('Could not load projects')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the cached project list when a refetch fails', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
mocks.listProjects.mockResolvedValueOnce([project]).mockRejectedValueOnce(new Error('offline'))
|
||||
|
||||
renderProjectList('srv_kitchen', queryClient)
|
||||
|
||||
await screen.findByText('App')
|
||||
await act(async () => {
|
||||
await queryClient.refetchQueries()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
expect(screen.getByText('App')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Could not load projects')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('scopes the list to the given server rather than the route', async () => {
|
||||
renderProjectList('srv_kitchen')
|
||||
|
||||
|
||||
Reference in new issue
Block a user