diff --git a/frontend/jest.project-feedback.config.js b/frontend/jest.project-feedback.config.js new file mode 100644 index 00000000..683e5eb7 --- /dev/null +++ b/frontend/jest.project-feedback.config.js @@ -0,0 +1,19 @@ +// Real React components, with only network/navigation/platform boundaries mocked. +module.exports = { + testEnvironment: 'jsdom', + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + tsconfig: { + jsx: 'react-jsx', + module: 'CommonJS', + moduleResolution: 'node', + }, + isolatedModules: true, + }, + ], + }, + moduleNameMapper: { '^@/(.*)$': '/src/$1' }, + testMatch: ['/src/components/__tests__/project-feedback.test.tsx'], +}; diff --git a/frontend/src/components/__tests__/project-feedback.test.tsx b/frontend/src/components/__tests__/project-feedback.test.tsx new file mode 100644 index 00000000..c864eccb --- /dev/null +++ b/frontend/src/components/__tests__/project-feedback.test.tsx @@ -0,0 +1,569 @@ +import React from 'react'; +import '@testing-library/jest-dom'; +import { + act, + cleanup, + fireEvent, + render, + renderHook, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { useMutation, useQuery } from '@apollo/client'; +import { toast } from 'sonner'; +import { Workbench } from '@/components/root/workbench'; +import { PublicProjects } from '@/components/root/public-projects'; +import ChatTopbar from '@/components/chat/chat-topbar'; +import { SideBarItem } from '@/components/sidebar-item'; +import { ClearHistoryDialog } from '@/components/chat/clear-history-dialog'; +import { useChatList } from '@/hooks/useChatList'; +import { copyText } from '@/lib/copy-text'; +import ResponsiveToolbar from '@/components/chat/code-engine/responsive-toolbar'; + +const mockPush = jest.fn(); +const mockReplace = jest.fn(); +const mockRefetch = jest.fn(); +const mockSetVisibility = jest.fn(); +let mockToolbarWidth = 900; +const mockMutations = new Map(); + +jest.mock('next/navigation', () => ({ + useRouter: () => ({ push: mockPush, replace: mockReplace }), + useSearchParams: () => new URLSearchParams(), +})); +jest.mock('next/image', () => ({ __esModule: true, default: () => null })); +jest.mock('@/hooks/useChatList', () => ({ useChatList: jest.fn() })); +jest.mock('@/providers/AuthProvider', () => ({ + useAuthContext: () => ({ isAuthorized: true, user: { id: 'owner' } }), +})); +jest.mock('@/components/chat/code-engine/project-context', () => ({ + ProjectContext: jest.requireActual('react').createContext({ + forkProject: jest.fn(), + setProjectPublicStatus: (...args: unknown[]) => mockSetVisibility(...args), + }), +})); +jest.mock('@/components/root/prompt-form', () => ({ + PromptForm: jest.requireActual('react').forwardRef(() => null), +})); +jest.mock('@/components/chat/code-engine/deploy-dialog', () => ({ + DeployDialog: () => null, +})); +jest.mock('@/components/chat/code-engine/key-dialog', () => ({ + KeyDialog: () => null, +})); +jest.mock('@/components/chat/code-engine/notes-dialog', () => ({ + NotesDialog: () => null, +})); +jest.mock('@/lib/authenticatedFetch', () => ({ + authenticatedFetch: jest.fn(), +})); +jest.mock('@/app/log/logger', () => ({ logger: { error: jest.fn() } })); +jest.mock('@apollo/client', () => ({ + ...jest.requireActual('@apollo/client'), + useMutation: jest.fn(), + useQuery: jest.fn(), +})); +jest.mock('sonner', () => ({ + toast: { success: jest.fn(), error: jest.fn(), info: jest.fn() }, +})); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +const chat = { + id: 'chat-1', + title: 'My chat', + createdAt: new Date().toISOString(), + project: { id: 'project-1' }, +}; +const list = () => ({ + chats: [chat], + loading: false, + error: undefined, + refetchChats: mockRefetch, +}); +const renderWorkbench = () => + render( + {}} + isLoading={false} + /> + ); +const openMenu = async (label: string) => { + fireEvent.keyDown(screen.getByRole('button', { name: label }), { + key: 'Enter', + code: 'Enter', + }); + await screen.findByRole('menu'); +}; + +beforeEach(() => { + jest.clearAllMocks(); + mockMutations.clear(); + mockToolbarWidth = 900; + mockSetVisibility.mockResolvedValue(undefined); + Object.defineProperty(globalThis, 'ResizeObserver', { + configurable: true, + value: class { + constructor(private callback: (entries: unknown[]) => void) {} + observe() { + this.callback([{ contentRect: { width: mockToolbarWidth } }]); + } + disconnect() {} + }, + }); + mockRefetch.mockResolvedValue({}); + (useChatList as jest.Mock).mockReturnValue(list()); + (useQuery as jest.Mock).mockReturnValue({ + data: { fetchPublicProjects: [] }, + loading: false, + refetch: mockRefetch, + }); + (useMutation as jest.Mock).mockImplementation((document, callbacks = {}) => { + const name = document.definitions[0].name.value; + if (!mockMutations.has(name)) + mockMutations.set(name, jest.fn().mockResolvedValue({ data: {} })); + const mutate = async (args: unknown) => { + try { + const result = await mockMutations.get(name)!(args); + callbacks.onCompleted?.(result.data); + return result; + } catch (error) { + callbacks.onError?.(error); + throw error; + } + }; + return [mutate, { loading: false }]; + }); + Element.prototype.scrollIntoView = jest.fn(); +}); +afterEach(cleanup); + +describe('duplicate and rename', () => { + test('success reports duplication once and opens the returned chat', async () => { + const result = deferred<{ data: { duplicateProject: { id: string } } }>(); + mockMutations.set( + 'DuplicateProject', + jest.fn().mockReturnValue(result.promise) + ); + renderWorkbench(); + await openMenu('Project options'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Duplicate' })); + expect(toast.success).not.toHaveBeenCalled(); + await act(async () => + result.resolve({ data: { duplicateProject: { id: 'copy-chat' } } }) + ); + expect(toast.success).toHaveBeenCalledTimes(1); + expect(toast.success).toHaveBeenCalledWith('Project duplicated'); + expect(mockPush).toHaveBeenCalledWith('/chat?id=copy-chat'); + expect(mockRefetch).toHaveBeenCalled(); + }); + + test.each([ + [ + 'network rejection', + () => Promise.reject(new Error('Network offline')), + 'Could not duplicate this project. Try again.', + ], + [ + 'ownership rejection', + () => Promise.reject(new Error('That project is not yours')), + 'You can only duplicate your own projects.', + ], + [ + 'quota rejection', + () => + Promise.reject( + new Error('You have 5 projects, which is the limit of your plan') + ), + 'You have 5 projects, which is the limit of your plan', + ], + [ + 'missing returned id', + () => Promise.resolve({ data: { duplicateProject: null } }), + 'Could not duplicate this project. Try again.', + ], + ])( + '%s never reports deletion or duplication success', + async (_name, response, message) => { + mockMutations.set( + 'DuplicateProject', + jest.fn().mockImplementation(response) + ); + renderWorkbench(); + await openMenu('Project options'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Duplicate' })); + await waitFor(() => expect(toast.error).toHaveBeenCalledWith(message)); + expect(toast.error).toHaveBeenCalledTimes(1); + expect(toast.success).not.toHaveBeenCalled(); + expect(mockPush).not.toHaveBeenCalled(); + } + ); + + test('rename describes the chat title, not the project name', async () => { + renderWorkbench(); + await openMenu('Project options'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Rename chat' })); + expect( + await screen.findByRole('dialog', { name: 'Rename chat' }) + ).toBeVisible(); + expect(screen.getByLabelText('Chat title')).toHaveValue('My chat'); + expect(screen.getByText(/project name stays the same/)).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(mockMutations.get('UpdateChatTitle')).not.toHaveBeenCalled(); + }); +}); + +describe('project-list query feedback', () => { + test('workbench distinguishes error from empty and retries', () => { + (useChatList as jest.Mock).mockReturnValue({ + ...list(), + chats: [], + error: new Error('offline'), + }); + renderWorkbench(); + expect(screen.getByRole('alert')).toHaveTextContent( + 'Could not load your projects' + ); + expect(screen.queryByText(/Nothing yet/)).not.toBeInTheDocument(); + fireEvent.click( + within(screen.getByRole('alert')).getByRole('button', { + name: 'Try again', + }) + ); + expect(mockRefetch).toHaveBeenCalledTimes(1); + }); + + test('cached workbench projects remain visible with an out-of-date warning', () => { + (useChatList as jest.Mock).mockReturnValue({ + ...list(), + error: new Error('offline'), + }); + renderWorkbench(); + expect(screen.getByText('My chat')).toBeVisible(); + expect(screen.getByRole('alert')).toHaveTextContent('may be out of date'); + }); + + test('public gallery distinguishes error from empty and retries without unhandled rejection', async () => { + mockRefetch.mockRejectedValue(new Error('still offline')); + (useQuery as jest.Mock).mockReturnValue({ + data: undefined, + loading: false, + error: new Error('offline'), + refetch: mockRefetch, + }); + render(); + expect(screen.getByRole('alert')).toHaveTextContent( + 'Could not load public projects' + ); + expect(screen.queryByText('Nothing published yet')).not.toBeInTheDocument(); + await act(async () => + fireEvent.click(screen.getByRole('button', { name: 'Try again' })) + ); + expect(mockRefetch).toHaveBeenCalledTimes(1); + }); + + test('genuinely empty lists retain their empty states', () => { + (useChatList as jest.Mock).mockReturnValue({ ...list(), chats: [] }); + renderWorkbench(); + expect(screen.getByText(/Nothing yet/)).toBeVisible(); + expect(screen.getByText('Nothing published yet')).toBeVisible(); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); +}); + +describe('clear-history confirmation', () => { + test.each(['topbar', 'sidebar'])( + '%s opens a confirmation, and Cancel leaves messages alone', + async (surface) => { + if (surface === 'topbar') render(); + else + render( + {}} + refetchChats={mockRefetch} + /> + ); + await openMenu('Chat options'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Clear history' })); + const dialog = await screen.findByRole('dialog', { + name: 'Clear chat history?', + }); + expect(dialog).toHaveTextContent('project files stay'); + expect(mockMutations.get('ClearChatHistory')).not.toHaveBeenCalled(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(mockMutations.get('ClearChatHistory')).not.toHaveBeenCalled(); + } + ); + + test('Escape dismisses the confirmation without clearing history', async () => { + render(); + await openMenu('Chat options'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Clear history' })); + await screen.findByRole('dialog', { name: 'Clear chat history?' }); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(mockMutations.get('ClearChatHistory')).not.toHaveBeenCalled(); + }); + + test('confirmation locks repeated clicks and reports only server-confirmed success', async () => { + const result = deferred<{ data: { clearChatHistory: boolean } }>(); + const mutate = jest.fn().mockReturnValue(result.promise); + mockMutations.set('ClearChatHistory', mutate); + const onCleared = jest.fn(); + const onOpenChange = jest.fn(); + render( + + ); + const button = screen.getByRole('button', { name: 'Clear history' }); + fireEvent.click(button); + fireEvent.click(button); + expect(mutate).toHaveBeenCalledTimes(1); + expect(button).toBeDisabled(); + expect(onCleared).not.toHaveBeenCalled(); + await act(async () => result.resolve({ data: { clearChatHistory: true } })); + expect(onCleared).toHaveBeenCalledTimes(1); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(toast.success).toHaveBeenCalledWith('Chat history cleared'); + }); + + test.each([false, 'reject'])( + 'failed clear (%s) stays open and allows retry', + async (response) => { + mockMutations.set( + 'ClearChatHistory', + jest + .fn() + .mockImplementation(() => + response === false + ? Promise.resolve({ data: { clearChatHistory: false } }) + : Promise.reject(new Error('offline')) + ) + ); + const onCleared = jest.fn(); + const onOpenChange = jest.fn(); + render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'Clear history' })); + await waitFor(() => + expect(toast.error).toHaveBeenCalledWith( + 'Could not clear chat history. Try again.' + ) + ); + expect( + screen.getByRole('button', { name: 'Clear history' }) + ).toBeEnabled(); + expect(onCleared).not.toHaveBeenCalled(); + expect(onOpenChange).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + } + ); + + test('an old clear response cannot empty a newly selected chat', async () => { + const result = deferred<{ data: { clearChatHistory: boolean } }>(); + mockMutations.set( + 'ClearChatHistory', + jest.fn().mockReturnValue(result.promise) + ); + const onCleared = jest.fn(); + const onOpenChange = jest.fn(); + const view = render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'Clear history' })); + view.rerender( + + ); + await act(async () => result.resolve({ data: { clearChatHistory: true } })); + expect(onCleared).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + }); +}); + +describe('chat-list retry boundary', () => { + const actualUseChatList = jest.requireActual( + '@/hooks/useChatList' + ).useChatList; + + test('query failure retains the last successful projects and retry rejection is handled', async () => { + mockRefetch.mockRejectedValue(new Error('still offline')); + (useQuery as jest.Mock).mockReturnValue({ + data: undefined, + previousData: { getUserChats: [chat] }, + loading: false, + error: new Error('offline'), + refetch: mockRefetch, + }); + const { result } = renderHook(() => actualUseChatList()); + expect(result.current.chats).toEqual([chat]); + expect(result.current.error.message).toBe('offline'); + await expect(result.current.refetchChats()).resolves.toBeUndefined(); + expect(useQuery).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ notifyOnNetworkStatusChange: true }) + ); + }); +}); + +describe('clipboard feedback', () => { + test('success waits for the clipboard write', async () => { + const write = deferred(); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: jest.fn().mockReturnValue(write.promise) }, + }); + const operation = copyText( + 'https://example.test/share', + 'Share link copied' + ); + expect(toast.success).not.toHaveBeenCalled(); + write.resolve(); + await expect(operation).resolves.toBe(true); + expect(toast.success).toHaveBeenCalledWith('Share link copied'); + }); + + test.each(['rejected', 'unavailable'])( + '%s clipboard never reports copied', + async (scenario) => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: + scenario === 'unavailable' + ? undefined + : { writeText: jest.fn().mockRejectedValue(new Error('denied')) }, + }); + await expect(copyText('project-1', 'Project id copied')).resolves.toBe( + false + ); + expect(toast.success).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledWith( + 'Could not copy to clipboard. Try again.' + ); + } + ); +}); + +describe('visibility action labels and pending state', () => { + const renderToolbar = (isPublic: boolean | undefined) => { + (useQuery as jest.Mock).mockReturnValue({ + data: + isPublic === undefined + ? undefined + : { + getProject: { + id: 'project-1', + isPublic, + template: 'html', + uniqueProjectId: 'share-1', + }, + }, + refetch: mockRefetch, + }); + return render( + {}} + projectId="project-1" + /> + ); + }; + + test.each([true, false])( + 'desktop action describes changing current public=%s state', + async (isPublic) => { + renderToolbar(isPublic); + const action = screen.getByRole('button', { + name: isPublic ? 'Make private' : 'Make public', + }); + expect(action).toHaveAttribute( + 'title', + expect.stringContaining( + isPublic ? 'Currently public' : 'Currently private' + ) + ); + await act(async () => fireEvent.click(action)); + expect(mockSetVisibility).toHaveBeenCalledWith('project-1', !isPublic); + } + ); + + test('unknown visibility never offers publishing', () => { + renderToolbar(undefined); + expect( + screen.getByRole('button', { name: 'Loading visibility…' }) + ).toBeDisabled(); + expect( + screen.queryByRole('button', { name: 'Make public' }) + ).not.toBeInTheDocument(); + }); + + test('mobile uses the same action and prevents repeat visibility changes', async () => { + mockToolbarWidth = 420; + const result = deferred(); + mockSetVisibility.mockReturnValue(result.promise); + renderToolbar(false); + await openMenu('More actions'); + const action = screen.getByRole('menuitem', { name: /Make public/ }); + expect(action).toHaveTextContent('Currently private'); + fireEvent.click(action); + await openMenu('More actions'); + expect( + screen.getByRole('menuitem', { name: /Updating visibility/ }) + ).toHaveAttribute('data-disabled'); + fireEvent.click( + screen.getByRole('menuitem', { name: /Updating visibility/ }) + ); + expect(mockSetVisibility).toHaveBeenCalledTimes(1); + await act(async () => result.resolve()); + }); + + test('refresh rejection releases the visibility lock', async () => { + mockRefetch.mockRejectedValue(new Error('offline')); + renderToolbar(true); + fireEvent.click(screen.getByRole('button', { name: 'Make private' })); + await waitFor(() => + expect(toast.error).toHaveBeenCalledWith( + 'Could not refresh project visibility. Try again.' + ) + ); + expect(screen.getByRole('button', { name: 'Make private' })).toBeEnabled(); + }); +}); diff --git a/frontend/src/components/chat/chat-topbar.tsx b/frontend/src/components/chat/chat-topbar.tsx index 1f48f57c..faa9373a 100644 --- a/frontend/src/components/chat/chat-topbar.tsx +++ b/frontend/src/components/chat/chat-topbar.tsx @@ -25,12 +25,9 @@ import { DialogHeader, DialogTitle, } from '../ui/dialog'; -import { - CLEAR_CHAT_HISTORY, - DELETE_CHAT, - UPDATE_CHAT_TITLE, -} from '@/graphql/request'; +import { DELETE_CHAT, UPDATE_CHAT_TITLE } from '@/graphql/request'; import { useChatList } from '@/hooks/useChatList'; +import { ClearHistoryDialog } from './clear-history-dialog'; interface ChatTopbarProps { chatId?: string; @@ -52,6 +49,8 @@ export default function ChatTopbar({ const [renaming, setRenaming] = useState(false); const [draft, setDraft] = useState(''); const [confirmDelete, setConfirmDelete] = useState(false); + const [confirmClear, setConfirmClear] = useState(false); + useEffect(() => setConfirmClear(false), [chatId]); const title = chatId ? chats.find((c) => c.id === chatId)?.title || 'Untitled' @@ -70,13 +69,6 @@ export default function ChatTopbar({ onCompleted: () => refetchChats(), onError: () => toast.error('Could not rename the chat'), }); - const [clearHistory] = useMutation(CLEAR_CHAT_HISTORY, { - onCompleted: () => { - onHistoryCleared?.(); - toast.success('History cleared'); - }, - onError: () => toast.error('Could not clear the history'), - }); const [deleteChat] = useMutation(DELETE_CHAT, { onCompleted: () => { toast.success('Chat deleted'); @@ -147,7 +139,7 @@ export default function ChatTopbar({ Rename clearHistory({ variables: { chatId } })} + onSelect={() => setTimeout(() => setConfirmClear(true), 0)} > Clear history @@ -163,6 +155,13 @@ export default function ChatTopbar({ )} + diff --git a/frontend/src/components/chat/clear-history-dialog.tsx b/frontend/src/components/chat/clear-history-dialog.tsx new file mode 100644 index 00000000..f0c0b38d --- /dev/null +++ b/frontend/src/components/chat/clear-history-dialog.tsx @@ -0,0 +1,101 @@ +'use client'; + +import { useEffect, useRef, useState } from 'react'; +import { useMutation } from '@apollo/client'; +import { toast } from 'sonner'; +import { CLEAR_CHAT_HISTORY } from '@/graphql/request'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; + +interface ClearHistoryDialogProps { + chatId?: string; + title: string; + open: boolean; + onOpenChange: (open: boolean) => void; + onCleared?: () => void; +} + +/** Both chat menus use the same confirmation and in-flight guard. */ +export function ClearHistoryDialog({ + chatId, + title, + open, + onOpenChange, + onCleared, +}: ClearHistoryDialogProps) { + const [clearHistory] = useMutation(CLEAR_CHAT_HISTORY); + const [clearing, setClearing] = useState(false); + const pending = useRef(false); + const activeChatId = useRef(chatId); + activeChatId.current = chatId; + useEffect(() => { + activeChatId.current = chatId; + return () => { + activeChatId.current = undefined; + }; + }, [chatId]); + + const handleClear = async () => { + if (!chatId || pending.current) return; + pending.current = true; + setClearing(true); + try { + const { data } = await clearHistory({ variables: { chatId } }); + if (!data?.clearChatHistory) throw new Error('History was not cleared'); + // A response for the previous chat must not empty the new chat's UI. + if (activeChatId.current !== chatId) return; + onCleared?.(); + toast.success('Chat history cleared'); + onOpenChange(false); + } catch { + if (activeChatId.current === chatId) { + toast.error('Could not clear chat history. Try again.'); + } + } finally { + pending.current = false; + setClearing(false); + } + }; + + return ( + { + if (!pending.current) onOpenChange(next); + }} + > + + + Clear chat history? + + All messages in “{title || 'Untitled'}” will be removed. Your + project files stay. This cannot be undone. + +
+ + +
+
+
+
+ ); +} diff --git a/frontend/src/components/chat/code-engine/project-context.tsx b/frontend/src/components/chat/code-engine/project-context.tsx index 16056ed5..4a23762e 100644 --- a/frontend/src/components/chat/code-engine/project-context.tsx +++ b/frontend/src/components/chat/code-engine/project-context.tsx @@ -735,11 +735,11 @@ export function ProjectProvider({ children }: { children: ReactNode }) { message.includes('your own') ? 'You already own this project' : // The quota message already names the limit, the count and - // what to do about it — replacing it with "Failed to fork" + // what to do about it — replacing it with a generic remix error // would throw away the only actionable part. message.includes('which is the limit of') ? message - : 'Failed to fork project' + : 'Could not remix this project. Try again.' ); } return null; diff --git a/frontend/src/components/chat/code-engine/responsive-toolbar.tsx b/frontend/src/components/chat/code-engine/responsive-toolbar.tsx index c3bfbcef..4a719d0a 100644 --- a/frontend/src/components/chat/code-engine/responsive-toolbar.tsx +++ b/frontend/src/components/chat/code-engine/responsive-toolbar.tsx @@ -27,6 +27,7 @@ import { GET_PROJECT } from '../../../graphql/request'; import { ProjectContext } from './project-context'; import { authenticatedFetch } from '@/lib/authenticatedFetch'; import { shareUrl } from '@/lib/share'; +import { copyText } from '@/lib/copy-text'; import { cn } from '@/lib/utils'; import { DropdownMenu, @@ -75,6 +76,7 @@ const ResponsiveToolbar = ({ // Query to check if the project is already synced const { setProjectPublicStatus } = useContext(ProjectContext); const [togglingVisibility, setTogglingVisibility] = useState(false); + const visibilityPending = useRef(false); const { data: projectData, refetch: refetchProject } = useQuery(GET_PROJECT, { variables: { projectId }, skip: !projectId, @@ -116,6 +118,36 @@ const ResponsiveToolbar = ({ // toggles to `!isPublic`, so an unknown state would publish the project. const isPublic: boolean | undefined = projectData?.getProject?.isPublic; + const visibilityAction = togglingVisibility + ? 'Updating visibility…' + : isPublic === undefined + ? 'Loading visibility…' + : isPublic + ? 'Make private' + : 'Make public'; + const visibilityDescription = + isPublic === undefined + ? 'Loading the current project visibility' + : isPublic + ? 'Currently public. Make private to remove public access in CodeFox.' + : 'Currently private. Make public to let other signed-in users remix this project.'; + + const handleVisibilityChange = async () => { + if (!projectId || isPublic === undefined || visibilityPending.current) + return; + visibilityPending.current = true; + setTogglingVisibility(true); + try { + await setProjectPublicStatus(projectId, !isPublic); + await refetchProject(); + } catch { + toast.error('Could not refresh project visibility. Try again.'); + } finally { + visibilityPending.current = false; + setTogglingVisibility(false); + } + }; + // A page anyone can open, once it is public. Private projects and Next apps // have no such link — Next has no single file to serve. const share = isPublic ? shareUrl(projectData?.getProject ?? {}) : null; @@ -340,30 +372,35 @@ const ResponsiveToolbar = ({ {compactIcons && ( <> { - if (!projectId || isPublic === undefined) return; - setTogglingVisibility(true); - await setProjectPublicStatus(projectId, !isPublic); - await refetchProject(); - setTogglingVisibility(false); - }} + disabled={ + isLoading || + !projectId || + togglingVisibility || + isPublic === undefined + } + title={visibilityDescription} + onClick={handleVisibilityChange} > {isPublic ? ( ) : ( )} - {isPublic ? 'Public' : 'Private'} + + {visibilityAction} + + {visibilityDescription} + + {share && ( { - navigator.clipboard.writeText( - `${window.location.origin}${share}` - ); - toast.success('Share link copied — anyone can open it'); - }} + onClick={() => + void copyText( + `${window.location.origin}${share}`, + 'Share link copied — anyone can open it' + ) + } > Share @@ -449,8 +486,7 @@ const ResponsiveToolbar = ({ aria-label="Copy project id" onClick={() => { if (!projectId) return; - navigator.clipboard.writeText(projectId); - toast.success('Project id copied'); + void copyText(projectId, 'Project id copied'); }} > @@ -469,30 +505,16 @@ const ResponsiveToolbar = ({ togglingVisibility || isPublic === undefined } - onClick={async () => { - if (!projectId || isPublic === undefined) return; - setTogglingVisibility(true); - await setProjectPublicStatus(projectId, !isPublic); - await refetchProject(); - setTogglingVisibility(false); - }} - title={ - isPublic - ? 'Anyone can see and fork this project' - : 'Only you can see this project' - } - aria-busy={isPublic === undefined} + onClick={handleVisibilityChange} + title={visibilityDescription} + aria-busy={togglingVisibility || isPublic === undefined} > {isPublic ? ( ) : ( )} - {isPublic === undefined - ? 'Visibility' - : isPublic - ? 'Public' - : 'Private'} + {visibilityAction} {/* The published page's own url. Only shown when there is one to copy — publishing is what creates it. */} @@ -502,12 +524,12 @@ const ResponsiveToolbar = ({ size="sm" className="text-sm" title="Copy a link anyone can open" - onClick={() => { - navigator.clipboard.writeText( - `${window.location.origin}${share}` - ); - toast.success('Share link copied — anyone can open it'); - }} + onClick={() => + void copyText( + `${window.location.origin}${share}`, + 'Share link copied — anyone can open it' + ) + } > Share diff --git a/frontend/src/components/root/public-projects.tsx b/frontend/src/components/root/public-projects.tsx index 6defa4e1..27691a47 100644 --- a/frontend/src/components/root/public-projects.tsx +++ b/frontend/src/components/root/public-projects.tsx @@ -12,6 +12,7 @@ import { ProjectContext } from '@/components/chat/code-engine/project-context'; import { useAuthContext } from '@/providers/AuthProvider'; import { mediaUrl } from '@/lib/media'; import { shareUrl } from '@/lib/share'; +import { Button } from '@/components/ui/button'; interface PublicProject { id: string; @@ -79,12 +80,17 @@ export function PublicProjects({ const { forkProject } = useContext(ProjectContext); const [forking, setForking] = useState(null); - const { data, loading } = useQuery(FETCH_PUBLIC_PROJECTS, { - variables: { input: { size: limit, strategy } }, - }); + const { data, previousData, loading, error, refetch } = useQuery( + FETCH_PUBLIC_PROJECTS, + { + variables: { input: { size: limit, strategy } }, + notifyOnNetworkStatusChange: true, + } + ); - const projects: PublicProject[] = data?.fetchPublicProjects ?? []; - const empty = !loading && projects.length === 0; + const projects: PublicProject[] = + data?.fetchPublicProjects ?? previousData?.fetchPublicProjects ?? []; + const empty = !loading && !error && projects.length === 0; const handleFork = async (id: string) => { if (!isAuthorized) { @@ -153,7 +159,31 @@ export function PublicProjects({ )} - {loading ? ( + {error && ( +
+

+ Could not load public projects +

+

+ {projects.length > 0 + ? 'The projects shown may be out of date.' + : 'Try again to browse projects to remix.'} +

+ +
+ )} + {loading && projects.length === 0 ? (
    ))}
- ) : empty ? ( + ) : error && projects.length === 0 ? null : empty ? ( // The section used to disappear when nothing was public, which left a // hole where the showcase belongs and told a new user nothing. Hold // the space and say what would fill it. diff --git a/frontend/src/components/root/workbench.tsx b/frontend/src/components/root/workbench.tsx index 54bde5a7..02880ffa 100644 --- a/frontend/src/components/root/workbench.tsx +++ b/frontend/src/components/root/workbench.tsx @@ -1,7 +1,7 @@ 'use client'; import Link from 'next/link'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; import { useRouter } from 'next/navigation'; import { useMutation } from '@apollo/client'; import { @@ -75,13 +75,13 @@ export function Workbench({ onSubmit, isLoading, }: WorkbenchProps) { - const { chats, loading, refetchChats } = useChatList(); + const { chats, loading, error, refetchChats } = useChatList(); // Nine keeps the grid tidy, but the tenth project must not be unreachable. const [showAll, setShowAll] = useState(false); const recent = showAll ? chats : chats.slice(0, 9); - // With the sidebar gone, the cards are where a project gets renamed or - // deleted. One dialog serves both, keyed by mode. + // Cards rename the chat title or delete the whole project. + // One dialog serves both, keyed by mode. const [action, setAction] = useState<{ mode: 'rename' | 'delete'; id: string; @@ -93,7 +93,7 @@ export function Workbench({ const [updateTitle] = useMutation(UPDATE_CHAT_TITLE, { onCompleted: () => refetchChats(), - onError: () => toast.error('Could not rename the project'), + onError: () => toast.error('Could not rename the chat'), }); const deleted = { onCompleted: () => { @@ -106,7 +106,8 @@ export function Workbench({ // the workspace, so it is the whole delete. deleteChat is the fallback for a // chat whose project never got scaffolded — there is nothing else to reclaim. const [deleteProject] = useMutation(DELETE_PROJECT, deleted); - const [duplicate] = useMutation(DUPLICATE_PROJECT, deleted); + const [duplicate] = useMutation(DUPLICATE_PROJECT); + const duplicatePending = useRef(false); const [duplicating, setDuplicating] = useState(false); const router = useRouter(); const [deleteChat] = useMutation(DELETE_CHAT, deleted); @@ -158,6 +159,30 @@ export function Workbench({ )} + {error && ( +
+

+ Could not load your projects +

+

+ {chats.length > 0 + ? 'The projects shown may be out of date.' + : 'Try again to see your projects.'} +

+ +
+ )} {loading && chats.length === 0 ? ( // A skeleton in the shape of the thing that is coming, rather than // the word "Loading" — the row keeps its height so the page below @@ -173,7 +198,7 @@ export function Workbench({ /> ))} - ) : recent.length === 0 ? ( + ) : error && recent.length === 0 ? null : recent.length === 0 ? (

Nothing yet. Describe a project above — or start from one of @@ -246,24 +271,42 @@ export function Workbench({ } > - Rename + Rename chat { const projectId = chat.project?.id; - if (!projectId) return; + if (!projectId || duplicatePending.current) return; + duplicatePending.current = true; setDuplicating(true); duplicate({ variables: { projectId } }) .then(({ data }) => { const id = data?.duplicateProject?.id; - toast.success('Copied — opening it now'); - if (id) router.push(`/chat?id=${id}`); + if (!id) + throw new Error( + 'Could not duplicate this project. Try again.' + ); + toast.success('Project duplicated'); + void refetchChats(); + router.push(`/chat?id=${id}`); + }) + .catch((error) => { + const message = (error as Error)?.message ?? ''; + toast.error( + message.includes('which is the limit of') + ? message + : message.includes( + 'That project is not yours' + ) + ? 'You can only duplicate your own projects.' + : 'Could not duplicate this project. Try again.' + ); }) - // The server's words: the quota refusal names the - // limit and the way out. - .catch((e) => toast.error(e.message)) - .finally(() => setDuplicating(false)); + .finally(() => { + duplicatePending.current = false; + setDuplicating(false); + }); }} > @@ -333,13 +376,16 @@ export function Workbench({ {action?.mode === 'rename' ? ( - Rename project + Rename chat + + Change this chat’s title. The project name stays the same. + setDraft(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && commitRename()} - aria-label="Project title" + aria-label="Chat title" />