Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/lib/taskLoadError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'
import { getTaskLoadErrorMessage } from './taskLoadError'

describe('getTaskLoadErrorMessage', () => {
it('does not blame Supabase when the app is using local demo storage', () => {
expect(getTaskLoadErrorMessage(new Error('Browser storage is unavailable'), true)).toContain('Browser storage is unavailable')
})
it('explains when the hosted tasks table has not been migrated', () => {
expect(getTaskLoadErrorMessage({ code: '42P01', message: 'relation "public.tasks" does not exist' })).toContain('Apply supabase/migrations/20250915000000_initial_schema.sql')
})
it('explains RLS and permission failures', () => {
expect(getTaskLoadErrorMessage({ code: '42501', message: 'permission denied for table tasks' })).toContain('RLS policies')
})
it('explains invalid session or API key errors', () => {
expect(getTaskLoadErrorMessage({ code: 'PGRST301', message: 'JWT expired' })).toContain('Sign out and sign in again')
})
it('explains network failures without hiding the actual problem', () => {
expect(getTaskLoadErrorMessage(new Error('Failed to fetch'))).toContain('cannot reach Supabase')
})
})
25 changes: 25 additions & 0 deletions src/lib/taskLoadError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
type SupabaseTaskError = { code?: string; message?: string; details?: string; hint?: string }

export function getTaskLoadErrorMessage(error: unknown, demoMode = false): string {
if (demoMode) {
const message = error instanceof Error ? error.message : ''
return message || 'Taskflow could not read browser storage. Enable site storage and reload the page.'
}
const value = (error && typeof error === 'object' ? error : {}) as SupabaseTaskError
const code = value.code || ''
const message = value.message || (error instanceof Error ? error.message : '')

if (code === '42P01' || code === 'PGRST205' || /relation .*tasks.* does not exist|could not find the table .*tasks/i.test(message)) {
return 'The tasks table is missing from this Supabase project. Apply supabase/migrations/20250915000000_initial_schema.sql in the Supabase SQL Editor, then reload the app.'
}
if (code === '42501' || /permission denied|row-level security|violates row-level security/i.test(message)) {
return 'Supabase denied access to the tasks table. Check that the tasks RLS policies from the Taskflow migration are installed and that you are signed in with the correct account.'
}
if (code === 'PGRST301' || code === '401' || /invalid jwt|jwt expired|invalid token/i.test(message)) {
return 'Your Supabase session or public API key is invalid or expired. Sign out and sign in again, then verify the Vercel Supabase URL and anon/publishable key.'
}
if (/failed to fetch|networkerror|fetch failed|name_not_resolved/i.test(message)) {
return 'The browser cannot reach Supabase. Check the VITE_SUPABASE_URL in Vercel, the project status, and your network connection.'
}
return message || 'Unknown Supabase error. Verify the Vercel environment variables and Supabase project configuration.'
}
4 changes: 3 additions & 1 deletion src/pages/TasksPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { TaskForm } from '../components/TaskForm'
import { EmptyState } from '../components/EmptyState'
import type { Task, TaskInput, TaskPriority, TaskStatus } from '../types'
import { filterAndSortTasks, paginateTasks } from '../lib/taskFilters'
import { getTaskLoadErrorMessage } from '../lib/taskLoadError'
import { isDemoMode } from '../lib/supabase'

export function TasksPage() {
const {user}=useAuth()
Expand All @@ -28,7 +30,7 @@ export function TasksPage() {
<label className="toolbar-field">Sort by<select value={sort} onChange={e=>setSort(e.target.value as 'created'|'due'|'priority')}><option value="created">Newest</option><option value="due">Due date</option><option value="priority">Priority</option></select></label>
<div className="view-toggle" aria-label="Task view"><button className={view==='list'?'active':''} onClick={()=>setView('list')}>List</button><button className={view==='board'?'active':''} onClick={()=>setView('board')}>Kanban</button></div>
</div>
{isLoading?<div className="loading-list"><span className="spinner"/>Loading tasks…</div>:error?<div className="error-panel">Couldn’t load your tasks. Check your Supabase connection and try again.<button className="button secondary" onClick={()=>refetch()}>Try again</button></div>:shown.length===0?<EmptyState filtered={tasks.length>0} onAdd={()=>setOpen(true)}/>:view==='board'?<TaskBoard tasks={shown} onStatusChange={(taskId,status)=>updateStatus.mutate({taskId,status})}/>:<><div className="task-list">{paginateTasks(shown,visibleCount).map(task=><TaskCard key={task.id} task={task} onStatusChange={status=>updateStatus.mutate({taskId:task.id,status})} onEdit={()=>{setEditing(task);setOpen(true)}} onDelete={()=>removeTask(task)}/>)}</div>{shown.length>visibleCount&&<div className="load-more"><button className="button secondary" onClick={()=>setVisibleCount(count=>count+10)}>Load more tasks</button><span>{Math.min(visibleCount,shown.length)} of {shown.length}</span></div>}</>}
{isLoading?<div className="loading-list"><span className="spinner"/>Loading tasks…</div>:error?<div className="error-panel">Couldn’t load your tasks. {getTaskLoadErrorMessage(error, isDemoMode)}<button className="button secondary" onClick={()=>refetch()}>Try again</button></div>:shown.length===0?<EmptyState filtered={tasks.length>0} onAdd={()=>setOpen(true)}/>:view==='board'?<TaskBoard tasks={shown} onStatusChange={(taskId,status)=>updateStatus.mutate({taskId,status})}/>:<><div className="task-list">{paginateTasks(shown,visibleCount).map(task=><TaskCard key={task.id} task={task} onStatusChange={status=>updateStatus.mutate({taskId:task.id,status})} onEdit={()=>{setEditing(task);setOpen(true)}} onDelete={()=>removeTask(task)}/>)}</div>{shown.length>visibleCount&&<div className="load-more"><button className="button secondary" onClick={()=>setVisibleCount(count=>count+10)}>Load more tasks</button><span>{Math.min(visibleCount,shown.length)} of {shown.length}</span></div>}</>}
</section>
{open&&<div className="modal-backdrop" role="presentation"><div className="modal" role="dialog" aria-modal="true" aria-label={editing?'Edit task':'New task'}><TaskForm task={editing} onSubmit={save} onCancel={()=>{setOpen(false);setEditing(null)}} isSaving={create.isPending||update.isPending}/></div></div>}
</div>
Expand Down
6 changes: 6 additions & 0 deletions src/services/tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ describe('demo task CRUD and ownership',()=>{
expect(await listTasks('u1')).toHaveLength(1)
expect(await listTasks('u2')).toHaveLength(0)
})
it('recovers from malformed local task storage without crashing the tasks page',async()=>{
localStorage.setItem('taskflow-demo-tasks','{not valid json')
expect(await listTasks('u1')).toEqual([])
expect(localStorage.getItem('taskflow-demo-tasks')).toBeNull()
expect(localStorage.getItem('taskflow-demo-tasks-corrupt-backup')).toBe('{not valid json')
})
it('supports status updates through the same owner-scoped update path',async()=>{
localStorage.setItem('taskflow-demo-tasks',JSON.stringify([task]))
await (await import('./tasks')).updateTaskStatus('u1','task-1','done')
Expand Down
23 changes: 21 additions & 2 deletions src/services/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,27 @@ import type { Task, TaskInput, TaskStatus } from '../types'
const demoTasksKey = 'taskflow-demo-tasks'

function readDemoTasks(userId: string): Task[] {
const stored = localStorage.getItem(demoTasksKey)
return stored ? (JSON.parse(stored) as Task[]).filter((task) => task.user_id === userId) : []
let stored: string | null
try {
stored = localStorage.getItem(demoTasksKey)
} catch {
throw new Error('Browser storage is unavailable. Enable site storage for Taskflow and reload the page.')
}
if (!stored) return []
try {
const parsed: unknown = JSON.parse(stored)
if (!Array.isArray(parsed)) throw new Error('Stored tasks are not a list')
return (parsed as Task[]).filter((task) => task && task.user_id === userId)
} catch {
// Preserve the malformed value for recovery, then reset only the Taskflow tasks key.
try {
localStorage.setItem('taskflow-demo-tasks-corrupt-backup', stored)
localStorage.removeItem(demoTasksKey)
} catch {
throw new Error('Taskflow demo data is unreadable and browser storage cannot repair it. Enable site storage, then reload.')
}
return []
}
}
function writeDemoTasks(tasks: Task[]) { localStorage.setItem(demoTasksKey, JSON.stringify(tasks)) }

Expand Down
Loading