mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Fix remote session delete, unknown commit responses, restart errors and lost autosave clears
This commit is contained in:
1 parent
51fb4fd12f
commit
fc00273645
11 files changed
+233
-82
No files matched your search
@@ -278,6 +278,11 @@ export function createRepoGitRoutes(
|
||||
}
|
||||
|
||||
const diff = await git.getCommitDiff(id, hash, filePath, database)
|
||||
|
||||
if (!diff) {
|
||||
return c.json({ error: 'Commit not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(diff)
|
||||
}))
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getErrorMessage } from '../../utils/error-utils'
|
||||
import { getRepoById, getRepoByDirectory, updateRepoBranch, listRepos } from '../../db/queries'
|
||||
import { updateScheduleJobsBranch } from '../../db/schedules'
|
||||
import { isSSHUrl, getBranchNameError } from '@opencode-manager/shared/utils'
|
||||
import { GitOperationError, isNoUpstreamError, parseGitError } from '../../utils/git-errors'
|
||||
import { GitOperationError, isNoUpstreamError, isUnknownRevisionError, parseGitError } from '../../utils/git-errors'
|
||||
import { listGitWorktrees, resolveMainCheckoutPath } from '../repo'
|
||||
import { MAX_COMMIT_PROMPT_DIFF_CHARS, type CommitMessageContext } from './commit-message-prompt'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
@@ -595,12 +595,15 @@ export class GitService {
|
||||
files
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (isUnknownRevisionError(error)) {
|
||||
return null
|
||||
}
|
||||
logger.error(`Failed to get commit details for repo ${repoId}:`, error)
|
||||
throw new Error(`Failed to get commit details: ${getErrorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async getCommitDiff(repoId: number, hash: string, filePath: string, database: Database): Promise<FileDiffResponse> {
|
||||
async getCommitDiff(repoId: number, hash: string, filePath: string, database: Database): Promise<FileDiffResponse | null> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
@@ -618,6 +621,9 @@ export class GitService {
|
||||
const status = this.detectDiffStatus(diff)
|
||||
return this.parseDiffOutput(diff, status, filePath)
|
||||
} catch (error: unknown) {
|
||||
if (isUnknownRevisionError(error)) {
|
||||
return null
|
||||
}
|
||||
logger.error(`Failed to get commit diff for repo ${repoId}:`, error)
|
||||
throw new Error(`Failed to get commit diff: ${getErrorMessage(error)}`)
|
||||
}
|
||||
|
||||
@@ -33,22 +33,28 @@ export interface OpenCodeManagerProcess {
|
||||
getLastStartupError: () => string | null
|
||||
}
|
||||
|
||||
function restartFailureError(manager: OpenCodeManagerProcess): Error {
|
||||
const startupError = manager.getLastStartupError()
|
||||
return new Error(startupError ?? 'OpenCode server restart did not complete successfully')
|
||||
interface RestartOutcome {
|
||||
healthy: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
function restartFailureError(manager: OpenCodeManagerProcess, supervisorError: string | null): Error {
|
||||
const reason = supervisorError ?? manager.getLastStartupError()
|
||||
return new Error(reason ?? 'OpenCode server restart did not complete successfully')
|
||||
}
|
||||
|
||||
async function restartServer(
|
||||
supervisor: OpenCodeRestartTarget | undefined,
|
||||
reason: OpenCodeOperationReason,
|
||||
manager: OpenCodeManagerProcess,
|
||||
): Promise<boolean> {
|
||||
): Promise<RestartOutcome> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart(reason)).healthy
|
||||
const status = await supervisor.restart(reason)
|
||||
return { healthy: status.healthy, error: status.lastError }
|
||||
}
|
||||
manager.clearStartupError()
|
||||
await manager.restart()
|
||||
return manager.checkHealth()
|
||||
return { healthy: await manager.checkHealth(), error: null }
|
||||
}
|
||||
|
||||
export async function restartOpenCode(
|
||||
@@ -56,9 +62,9 @@ export async function restartOpenCode(
|
||||
reason: OpenCodeOperationReason = 'settings_restart',
|
||||
manager: OpenCodeManagerProcess = opencodeServerManager,
|
||||
): Promise<void> {
|
||||
const healthy = await restartServer(supervisor, reason, manager)
|
||||
if (!healthy) {
|
||||
throw restartFailureError(manager)
|
||||
const outcome = await restartServer(supervisor, reason, manager)
|
||||
if (!outcome.healthy) {
|
||||
throw restartFailureError(manager, outcome.error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,16 @@ export function isNoUpstreamError(error: Error): boolean {
|
||||
return patterns.some(pattern => pattern.test(error.message))
|
||||
}
|
||||
|
||||
export function isUnknownRevisionError(cause: unknown): boolean {
|
||||
const patterns = [
|
||||
/fatal: bad object/i,
|
||||
/unknown revision/i,
|
||||
/bad revision/i,
|
||||
]
|
||||
const message = getErrorMessage(cause)
|
||||
return patterns.some(pattern => pattern.test(message))
|
||||
}
|
||||
|
||||
export class GitOperationError extends Error {
|
||||
constructor(
|
||||
readonly code: GitErrorCode,
|
||||
|
||||
@@ -374,12 +374,21 @@ describe('repo git routes', () => {
|
||||
expect(diff.diff).toContain('+hello')
|
||||
})
|
||||
|
||||
it('fails when the commit does not exist', async () => {
|
||||
const response = await app.request(`/${repo.id}/git/commit/${'0'.repeat(40)}`)
|
||||
const body = await readJson(response, ErrorSchema)
|
||||
it.each([
|
||||
{ label: 'a full-length hash', hash: '0'.repeat(40) },
|
||||
{ label: 'a short hash', hash: 'deadbeef' },
|
||||
])('returns 404 for $label that does not exist', async ({ hash }) => {
|
||||
const detailsResponse = await app.request(`/${repo.id}/git/commit/${hash}`)
|
||||
const detailsBody = await readJson(detailsResponse, ErrorSchema)
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body.error).not.toBe('')
|
||||
expect(detailsResponse.status).toBe(404)
|
||||
expect(detailsBody.error).toBe('Commit not found')
|
||||
|
||||
const diffResponse = await app.request(`/${repo.id}/git/commit/${hash}/diff?path=notes.txt`)
|
||||
const diffBody = await readJson(diffResponse, ErrorSchema)
|
||||
|
||||
expect(diffResponse.status).toBe(404)
|
||||
expect(diffBody.error).toBe('Commit not found')
|
||||
})
|
||||
|
||||
it('returns 400 when the commit diff has no path', async () => {
|
||||
|
||||
@@ -570,10 +570,13 @@ describe('GitService', () => {
|
||||
await expect(service.getCommitDetails(4242, 'HEAD', db)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws for an unknown hash', async () => {
|
||||
it.each([
|
||||
{ label: 'a short hash', hash: 'does-not-exist' },
|
||||
{ label: 'a full-length hash', hash: '0'.repeat(40) },
|
||||
])('returns null for $label that does not exist', async ({ hash }) => {
|
||||
const repo = initRepo()
|
||||
|
||||
await expect(service.getCommitDetails(repo.id, 'does-not-exist', db)).rejects.toThrow('Failed to get commit details')
|
||||
expect(await service.getCommitDetails(repo.id, hash, db)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -588,12 +591,12 @@ describe('GitService', () => {
|
||||
|
||||
const diff = await service.getCommitDiff(repo.id, hash, 'file.ts', db)
|
||||
|
||||
expect(diff.path).toBe('file.ts')
|
||||
expect(diff.status).toBe('modified')
|
||||
expect(diff.diff).toContain('+new line')
|
||||
expect(diff.additions).toBe(1)
|
||||
expect(diff.deletions).toBe(1)
|
||||
expect(diff.isBinary).toBe(false)
|
||||
expect(diff?.path).toBe('file.ts')
|
||||
expect(diff?.status).toBe('modified')
|
||||
expect(diff?.diff).toContain('+new line')
|
||||
expect(diff?.additions).toBe(1)
|
||||
expect(diff?.deletions).toBe(1)
|
||||
expect(diff?.isBinary).toBe(false)
|
||||
})
|
||||
|
||||
it('reports a binary file', async () => {
|
||||
@@ -608,8 +611,8 @@ describe('GitService', () => {
|
||||
|
||||
const diff = await service.getCommitDiff(repo.id, hash, 'image.bin', db)
|
||||
|
||||
expect(diff.isBinary).toBe(true)
|
||||
expect(diff.diff).toContain('Binary files')
|
||||
expect(diff?.isBinary).toBe(true)
|
||||
expect(diff?.diff).toContain('Binary files')
|
||||
})
|
||||
|
||||
it('counts the deleted lines of a file removed in the commit', async () => {
|
||||
@@ -622,19 +625,22 @@ describe('GitService', () => {
|
||||
|
||||
const diff = await service.getCommitDiff(repo.id, hash, 'removed.txt', db)
|
||||
|
||||
expect(diff.status).toBe('deleted')
|
||||
expect(diff.deletions).toBe(3)
|
||||
expect(diff.additions).toBe(0)
|
||||
expect(diff?.status).toBe('deleted')
|
||||
expect(diff?.deletions).toBe(3)
|
||||
expect(diff?.additions).toBe(0)
|
||||
})
|
||||
|
||||
it('throws for an unknown repository', async () => {
|
||||
await expect(service.getCommitDiff(4242, 'HEAD', 'file.ts', db)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws for an unknown hash', async () => {
|
||||
it.each([
|
||||
{ label: 'a short hash', hash: 'does-not-exist' },
|
||||
{ label: 'a full-length hash', hash: '0'.repeat(40) },
|
||||
])('returns null for $label that does not exist', async ({ hash }) => {
|
||||
const repo = initRepo()
|
||||
|
||||
await expect(service.getCommitDiff(repo.id, 'does-not-exist', 'file.ts', db)).rejects.toThrow('Failed to get commit diff')
|
||||
expect(await service.getCommitDiff(repo.id, hash, 'file.ts', db)).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type OpenCodeRestartTarget,
|
||||
} from '../../src/services/opencode-restart'
|
||||
|
||||
function lifecycleStatus(healthy: boolean): OpenCodeLifecycleStatus {
|
||||
function lifecycleStatus(healthy: boolean, lastError: string | null = healthy ? null : 'OpenCode server failed to become healthy'): OpenCodeLifecycleStatus {
|
||||
return {
|
||||
state: healthy ? 'healthy' : 'failed',
|
||||
healthy,
|
||||
@@ -24,7 +24,7 @@ function lifecycleStatus(healthy: boolean): OpenCodeLifecycleStatus {
|
||||
version: '2.0.15',
|
||||
minVersion: '2.0.15',
|
||||
versionSupported: true,
|
||||
lastError: healthy ? null : 'OpenCode server failed to become healthy',
|
||||
lastError,
|
||||
activeRecoveryAction: null,
|
||||
attemptedRecoveryActions: [],
|
||||
nextRecoveryAction: null,
|
||||
@@ -34,8 +34,8 @@ function lifecycleStatus(healthy: boolean): OpenCodeLifecycleStatus {
|
||||
}
|
||||
}
|
||||
|
||||
function createSupervisor(healthy: boolean): OpenCodeRestartTarget {
|
||||
return { restart: vi.fn<OpenCodeRestartTarget['restart']>(async () => lifecycleStatus(healthy)) }
|
||||
function createSupervisor(healthy: boolean, lastError: string | null = healthy ? null : 'OpenCode server failed to become healthy'): OpenCodeRestartTarget {
|
||||
return { restart: vi.fn<OpenCodeRestartTarget['restart']>(async () => lifecycleStatus(healthy, lastError)) }
|
||||
}
|
||||
|
||||
function createManager(): OpenCodeManagerProcess {
|
||||
@@ -85,16 +85,31 @@ describe('restartOpenCode', () => {
|
||||
expect(supervisor.restart).toHaveBeenCalledWith('settings_restart')
|
||||
})
|
||||
|
||||
it('throws with the startup failure reason when the supervisor restart is unhealthy', async () => {
|
||||
it('throws with the supervisor failure reason when the supervisor restart is unhealthy', async () => {
|
||||
const supervisor = createSupervisor(false, 'supervisor-specific failure')
|
||||
|
||||
await expect(restartOpenCode(supervisor, 'settings_restart', createManager()))
|
||||
.rejects.toThrow('supervisor-specific failure')
|
||||
})
|
||||
|
||||
it('falls back to the startup failure reason when the supervisor reports no error', async () => {
|
||||
const manager = createManager()
|
||||
vi.mocked(manager.getLastStartupError).mockReturnValue('OpenCode server failed to become healthy')
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false), 'settings_restart', manager))
|
||||
await expect(restartOpenCode(createSupervisor(false, null), 'settings_restart', manager))
|
||||
.rejects.toThrow('OpenCode server failed to become healthy')
|
||||
})
|
||||
|
||||
it('uses a generic failure message when no startup error is recorded', async () => {
|
||||
await expect(restartOpenCode(createSupervisor(false), 'settings_restart', createManager())).rejects.toThrow(
|
||||
it('prefers the supervisor failure over the manager startup error', async () => {
|
||||
const manager = createManager()
|
||||
vi.mocked(manager.getLastStartupError).mockReturnValue('startup error from the manager')
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false, 'supervisor-specific failure'), 'settings_restart', manager))
|
||||
.rejects.toThrow('supervisor-specific failure')
|
||||
})
|
||||
|
||||
it('uses a generic failure message when neither the supervisor nor the manager reports an error', async () => {
|
||||
await expect(restartOpenCode(createSupervisor(false, null), 'settings_restart', createManager())).rejects.toThrow(
|
||||
'OpenCode server restart did not complete successfully',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1002,7 +1002,6 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
expect(row).toHaveTextContent('Kitchen')
|
||||
expect(screen.queryByRole('button', { name: 'Session actions' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(row)
|
||||
|
||||
@@ -1027,23 +1026,64 @@ describe('SessionPickerDialog', () => {
|
||||
expect(server.deletedSessionIDs()).toEqual([])
|
||||
})
|
||||
|
||||
it('does not arm Ctrl+D for a remote active work row despite the delete hint', async () => {
|
||||
it('deletes a remote active work row through the owning server on a second Ctrl+D', async () => {
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [remoteSession],
|
||||
})
|
||||
renderPicker(server, { remote })
|
||||
const { fetchFake, onDeleteActiveSession } = renderPicker(server, {
|
||||
remote,
|
||||
activeSessionID: 'ses_remote',
|
||||
})
|
||||
openActiveTab()
|
||||
|
||||
const remoteDeletePath = '/api/opencode/servers/srv_kitchen/api/session/ses_remote'
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
expect(row).toHaveAttribute('aria-selected', 'true')
|
||||
expect(screen.getByText(/Ctrl\+D delete/)).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
|
||||
|
||||
await waitFor(() => expect(screen.queryByText(/Press Ctrl\+D/)).not.toBeInTheDocument())
|
||||
expect(server.deletedSessionIDs()).toEqual([])
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('option', { name: /Press Ctrl\+D again/ })).toBeInTheDocument(),
|
||||
)
|
||||
expect(fetchFake.findRequests('DELETE', remoteDeletePath)).toHaveLength(0)
|
||||
|
||||
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
|
||||
|
||||
await waitFor(() => expect(fetchFake.findRequests('DELETE', remoteDeletePath)).toHaveLength(1))
|
||||
expect(fetchFake.findRequests('DELETE', '/api/opencode/api/session/ses_remote')).toHaveLength(0)
|
||||
await waitFor(() => expect(onDeleteActiveSession).toHaveBeenCalled())
|
||||
await waitFor(() => expect(server.deletedSessionIDs()).toEqual(['ses_remote']))
|
||||
await waitFor(() => expect(screen.queryByText(/Press Ctrl\+D again/)).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('offers Delete but not Pin in a remote active work row menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [remoteSession],
|
||||
})
|
||||
const { fetchFake } = renderPicker(server, { remote })
|
||||
openActiveTab()
|
||||
|
||||
await screen.findByRole('option', { name: /Remote session/ })
|
||||
await user.click(screen.getByRole('button', { name: 'Session actions' }))
|
||||
|
||||
expect(await screen.findByRole('menuitem', { name: 'Delete' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('menuitem', { name: 'Pin' })).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Delete' }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Delete Session' })
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Delete' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
fetchFake.findRequests('DELETE', '/api/opencode/servers/srv_kitchen/api/session/ses_remote'),
|
||||
).toHaveLength(1),
|
||||
)
|
||||
})
|
||||
|
||||
it('deletes a local active work row through the local server', async () => {
|
||||
@@ -1057,9 +1097,10 @@ describe('SessionPickerDialog', () => {
|
||||
const { fetchFake } = renderPicker(server, { remote })
|
||||
openActiveTab()
|
||||
|
||||
await screen.findByRole('option', { name: /Local task/ })
|
||||
const localRow = await screen.findByRole('option', { name: /Local task/ })
|
||||
const rowContainer = localRow.parentElement ?? localRow
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Session actions' }))
|
||||
await user.click(within(rowContainer).getByRole('button', { name: 'Session actions' }))
|
||||
await user.click(await screen.findByText('Delete'))
|
||||
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Delete Session' })
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { z } from 'zod'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { format, startOfDay } from 'date-fns'
|
||||
import { ChevronsUpDown, MoreHorizontal, Pin, PinOff, Plus } from 'lucide-react'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
|
||||
import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation'
|
||||
import { deleteSession as deleteSessionOnServer } from '@/api/opencode'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -30,6 +31,8 @@ import { partitionSessions } from '@/components/session/session-partition'
|
||||
import { buildRepoByDirectory, isRepoReady } from '@/components/navigation/sidebar-session-tree'
|
||||
import { useDeleteSession } from '@/hooks/useOpenCode'
|
||||
import { useActiveWork, useActivityWindowMinutes } from '@/hooks/useActiveWork'
|
||||
import { activeWorkSessionsQueryKey } from '@/lib/queryInvalidation'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useSessionSearch } from '@/hooks/useSessionSearch'
|
||||
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
|
||||
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
|
||||
@@ -205,7 +208,7 @@ interface SessionPickerRowItemProps {
|
||||
onOpen: (row: SessionPickerRow) => void
|
||||
onHover: (index: number) => void
|
||||
onTogglePin: (row: SessionPickerRow) => void
|
||||
onRequestDelete: (session: Session) => void
|
||||
onRequestDelete: (row: SessionPickerRow) => void
|
||||
registerRef: (key: string, node: HTMLDivElement | null) => void
|
||||
}
|
||||
|
||||
@@ -287,7 +290,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center pr-1">
|
||||
{row.serverId || !showActions ? null : <DropdownMenu>
|
||||
{showActions ? <DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -303,13 +306,15 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
|
||||
<DropdownMenuItem onClick={() => onTogglePin(row)}>
|
||||
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
|
||||
{isPinned ? 'Unpin' : 'Pin'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
|
||||
{row.serverId ? null : (
|
||||
<DropdownMenuItem onClick={() => onTogglePin(row)}>
|
||||
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
|
||||
{isPinned ? 'Unpin' : 'Pin'}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => onRequestDelete(row)}>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</DropdownMenu> : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -330,7 +335,7 @@ interface SessionPickerRowActions {
|
||||
openRow: (row: SessionPickerRow | undefined) => void
|
||||
deleteRow: (row: SessionPickerRow | undefined) => void
|
||||
handleTogglePin: (row: SessionPickerRow) => void
|
||||
handleRequestDelete: (session: Session) => void
|
||||
handleRequestDelete: (row: SessionPickerRow) => void
|
||||
deleteDialogProps: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
@@ -351,7 +356,9 @@ function useSessionPickerRowActions({
|
||||
const togglePin = useToggleSessionPin()
|
||||
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
|
||||
const deleteSession = useDeleteSession(directories)
|
||||
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
const [rowToDelete, setRowToDelete] = useState<SessionPickerRow | null>(null)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
|
||||
|
||||
const clearPendingDelete = useCallback(() => {
|
||||
@@ -371,23 +378,37 @@ function useSessionPickerRowActions({
|
||||
)
|
||||
|
||||
const performDelete = useCallback(
|
||||
(session: Session) => {
|
||||
if (session.id === activeSessionID) onDeleteActiveSession()
|
||||
return deleteSession
|
||||
.mutateAsync({ id: session.id, directory: session.location.directory })
|
||||
.catch(() => undefined)
|
||||
async (row: SessionPickerRow) => {
|
||||
if (row.session.id === activeSessionID) onDeleteActiveSession()
|
||||
const serverId = row.serverId
|
||||
if (!serverId) {
|
||||
await deleteSession
|
||||
.mutateAsync({ id: row.session.id, directory: row.session.location.directory })
|
||||
.catch(() => undefined)
|
||||
return
|
||||
}
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
await deleteSessionOnServer(row.session.id, serverId)
|
||||
showToast.success('Session deleted')
|
||||
} catch {
|
||||
showToast.error('Failed to delete sessions')
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
void queryClient.invalidateQueries({ queryKey: activeWorkSessionsQueryKey(serverId) })
|
||||
}
|
||||
},
|
||||
[deleteSession, activeSessionID, onDeleteActiveSession],
|
||||
[deleteSession, activeSessionID, onDeleteActiveSession, queryClient],
|
||||
)
|
||||
|
||||
const deleteRow = useCallback(
|
||||
(row: SessionPickerRow | undefined) => {
|
||||
if (!row || row.serverId) return
|
||||
if (!row) return
|
||||
if (pendingDeleteKey !== row.key) {
|
||||
setPendingDeleteKey(row.key)
|
||||
return
|
||||
}
|
||||
void performDelete(row.session).finally(() => {
|
||||
void performDelete(row).finally(() => {
|
||||
setPendingDeleteKey(null)
|
||||
})
|
||||
},
|
||||
@@ -406,30 +427,30 @@ function useSessionPickerRowActions({
|
||||
[togglePin, pinnedKeys],
|
||||
)
|
||||
|
||||
const handleRequestDelete = useCallback((session: Session) => {
|
||||
setSessionToDelete(session)
|
||||
const handleRequestDelete = useCallback((row: SessionPickerRow) => {
|
||||
setRowToDelete(row)
|
||||
}, [])
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (!sessionToDelete) return
|
||||
void performDelete(sessionToDelete).finally(() => {
|
||||
setSessionToDelete(null)
|
||||
if (!rowToDelete) return
|
||||
void performDelete(rowToDelete).finally(() => {
|
||||
setRowToDelete(null)
|
||||
})
|
||||
}, [sessionToDelete, performDelete])
|
||||
}, [rowToDelete, performDelete])
|
||||
|
||||
const deleteDialogProps = useMemo(
|
||||
() => ({
|
||||
open: sessionToDelete !== null,
|
||||
open: rowToDelete !== null,
|
||||
onOpenChange: (nextOpen: boolean) => {
|
||||
if (!nextOpen) setSessionToDelete(null)
|
||||
if (!nextOpen) setRowToDelete(null)
|
||||
},
|
||||
onConfirm: () => {
|
||||
void confirmDelete()
|
||||
},
|
||||
onCancel: () => setSessionToDelete(null),
|
||||
isDeleting: deleteSession.isPending,
|
||||
onCancel: () => setRowToDelete(null),
|
||||
isDeleting: deleteSession.isPending || isDeleting,
|
||||
}),
|
||||
[sessionToDelete, confirmDelete, deleteSession.isPending],
|
||||
[rowToDelete, confirmDelete, deleteSession.isPending, isDeleting],
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -462,7 +483,7 @@ interface SessionPickerListProps {
|
||||
onOpenRow: (row: SessionPickerRow) => void
|
||||
onHoverRow: (index: number) => void
|
||||
onTogglePin: (row: SessionPickerRow) => void
|
||||
onRequestDelete: (session: Session) => void
|
||||
onRequestDelete: (row: SessionPickerRow) => void
|
||||
registerRef: (key: string, node: HTMLDivElement | null) => void
|
||||
listRef?: React.RefObject<HTMLDivElement | null>
|
||||
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void
|
||||
|
||||
@@ -35,6 +35,27 @@ describe('useAutosavedSetting', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('commits a clear that returns to the stale debounced value inside the delay', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const save = vi.fn()
|
||||
const { result, rerender } = renderTrimmedSetting(undefined, save)
|
||||
|
||||
rerender({ value: 'x' })
|
||||
expect(result.current.draft).toBe('x')
|
||||
|
||||
act(() => result.current.setDraft(''))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800)
|
||||
})
|
||||
|
||||
expect(save).toHaveBeenCalledTimes(1)
|
||||
expect(save).toHaveBeenCalledWith('', 'x')
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('skips an unchanged value and resyncs from the stored value', () => {
|
||||
const save = vi.fn()
|
||||
const { result, rerender } = renderTrimmedSetting('a', save)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
import { useDebouncedValue } from './useDebouncedValue'
|
||||
|
||||
export const AUTOSAVE_DELAY_MS = 800
|
||||
|
||||
@@ -44,9 +43,14 @@ export function useAutosavedSetting<TStored, TDraft, TCommitted>({
|
||||
|
||||
const [draft, setDraft] = useState<TDraft>(() => toDraft(stored))
|
||||
const committed = useRef<TCommitted>(toCommitted(draft, undefined))
|
||||
const pendingCommit = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const nextDraft = handlers.current.toDraft(stored)
|
||||
if (pendingCommit.current !== null) {
|
||||
clearTimeout(pendingCommit.current)
|
||||
pendingCommit.current = null
|
||||
}
|
||||
setDraft(nextDraft)
|
||||
committed.current = handlers.current.toCommitted(nextDraft, committed.current)
|
||||
}, [stored])
|
||||
@@ -60,11 +64,18 @@ export function useAutosavedSetting<TStored, TDraft, TCommitted>({
|
||||
persist(next, previous)
|
||||
}, [])
|
||||
|
||||
const debouncedDraft = useDebouncedValue(draft, delayMs)
|
||||
|
||||
useEffect(() => {
|
||||
commitDraft(debouncedDraft)
|
||||
}, [commitDraft, debouncedDraft])
|
||||
pendingCommit.current = setTimeout(() => {
|
||||
pendingCommit.current = null
|
||||
commitDraft(draft)
|
||||
}, delayMs)
|
||||
return () => {
|
||||
if (pendingCommit.current !== null) {
|
||||
clearTimeout(pendingCommit.current)
|
||||
pendingCommit.current = null
|
||||
}
|
||||
}
|
||||
}, [commitDraft, delayMs, draft])
|
||||
|
||||
const commit = useCallback(() => {
|
||||
commitDraft(draft)
|
||||
|
||||
Reference in new issue
Block a user