Something went wrong. Try again.
Effortlessly glide through your todos
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325import { create } from 'zustand';import { persist } from 'zustand/middleware';
import { TITLE_MAX_LENGTH, type GlideDecision, type GlideTaskStatus, type TaskId } from '@/domain/glide';
import { newTaskId } from './ids';import { mmkvJSONStorage } from './storage';import { currentOwnerId, isAdoptableOwner } from './sync/owner';
/** * The persisted shape of a task — a superset of the domain `GlideTask`. It carries the * timestamps the swipe loop needs plus the sync metadata the Convex sync engine reconciles * on: a client-owned `id`, the account `ownerId`, an `updatedAt` (the last-write-wins key), * a `syncedAt` (the `updatedAt` the server last confirmed — a row is *dirty* when * `updatedAt > syncedAt`), and a `deletedAt` tombstone. Review order derives from * `updatedAt`/`createdAt`; action order is the internal `order` field; done is `completedAt`. * See docs/engineering/convex-sync.md. */export type LocalTask = { id: TaskId; /** Account scope. `null` until adopted (signed-out rows); a fixed constant in dogfood mode. */ ownerId: string | null; title: string; resistance: number; status: GlideTaskStatus; exposureCount: number; createdAt: number; updatedAt: number; /** Stamped whenever `status` transitions. Write-only metadata — no reader yet. */ statusChangedAt?: number; /** Position within the `ready` queue. Irrelevant while open/done; freshly assigned * (append-at-end) each time a task transitions into `ready` or moves via Later. */ order?: number; /** Lifetime count of Defer while `ready`. Never reset. */ deferCount?: number; lastDecision?: GlideDecision; completedAt?: number; /** Soft-delete tombstone — kept so sync can propagate deletes. */ deletedAt?: number; /** The `updatedAt` the server last confirmed; `null` = never synced. Dirty iff `updatedAt > syncedAt`. */ syncedAt: number | null;};
/** * A task as the server hands it back (synced fields, keyed by `clientId`). Convex's * `Doc<'tasks'>` satisfies this structurally — the sync engine passes its query results * straight in. Kept here so the store doesn't import `convex/_generated`. */export type ServerTask = { clientId: TaskId; ownerId: string; title: string; status: GlideTaskStatus; resistance: number; exposureCount: number; createdAt: number; updatedAt: number; statusChangedAt?: number; order?: number; deferCount?: number; lastDecision?: GlideDecision; completedAt?: number; deletedAt?: number;};
/** A row has unsynced local edits iff its updatedAt is ahead of what the server confirmed. */export const isDirty = (t: LocalTask): boolean => t.updatedAt > (t.syncedAt ?? -1);
function serverToLocal(r: ServerTask): LocalTask { return { id: r.clientId, ownerId: r.ownerId, title: r.title, status: r.status, resistance: r.resistance, exposureCount: r.exposureCount, createdAt: r.createdAt, updatedAt: r.updatedAt, statusChangedAt: r.statusChangedAt, order: r.order, deferCount: r.deferCount, lastDecision: r.lastDecision, completedAt: r.completedAt, deletedAt: r.deletedAt, syncedAt: r.updatedAt, // server is authoritative → this row is clean };}
/** * The current action session boundary. The boundary is device-local, but the * visible tally is derived from synced task rows completed after this time so * another device completing a task in the same active pass updates the count too. */export type SessionState = { doneThisSession: number; planSessionAt: number;};
/** A handful of title-only tasks so a fresh install has something to plan. */const STARTER_TASKS = [ { title: 'Reply to the message you keep ignoring', resistance: 3 }, { title: 'Clear the right side of the desk', resistance: 1 }, { title: 'Open the tax folder', resistance: 5 }, { title: 'Put tomorrow’s walk on the calendar', resistance: 2 }, { title: 'Draft the note you’ve been avoiding', resistance: 4 },] as const;
type TaskState = { tasks: LocalTask[]; session: SessionState; /** Capture a new open task from a title. Trims + caps; empty titles are ignored. */ createTask: (title: string) => void; /** Record a planning decision: `clear` readies the task, `resistant` softens + re-sinks it. */ assess: (id: TaskId, decision: GlideDecision) => void; /** Mark a ready task done and count it toward this session's tally. */ complete: (id: TaskId) => void; /** Demote every ready task back to open — called once when Plan opens, forcing a fresh pass. */ demoteReadyTasks: () => void; /** Push a ready task to the back of the queue; bumps its lifetime defer count. */ deferNow: (id: TaskId) => void; /** Begin a Plan session: zero the action tally. */ startPlanSession: () => void; /** Ensure older persisted stores have a session boundary for synced done counts. */ ensureActionSession: () => void; /** Seed the starter tasks once, only when the store is completely empty. */ ensureStarterTasks: () => void; /** Sync: merge authoritative server rows in (last-write-wins; keeps newer local edits). */ ingestServerRows: (rows: ServerTask[]) => void; /** Sync: claim un-owned local rows into an account (the sign-in adoption path). */ adoptOwner: (ownerId: string) => void; /** Account deletion: keep this device's rows, but detach them from the deleted cloud owner. */ releaseOwner: (ownerId: string) => void;};
/** * The local source of truth. Every screen reads/writes here (via `useBoard` and the * `task-repository` seam), never Convex directly — so the whole app works offline, with no * account and no network. Persisted to MMKV; synchronous hydration means the data is * present on the first render. The Convex sync engine (src/data/sync) mirrors this store * to the server in the background when online + signed in. */export const useTaskStore = create<TaskState>()( persist( (set, get) => ({ tasks: [], session: { doneThisSession: 0, planSessionAt: 0 },
createTask: (rawTitle) => { const title = rawTitle.trim().slice(0, TITLE_MAX_LENGTH); if (title.length === 0) return; const now = Date.now(); const task: LocalTask = { id: newTaskId(), ownerId: currentOwnerId(), title, resistance: 1, status: 'open', exposureCount: 0, createdAt: now, updatedAt: now, syncedAt: null, }; set((state) => ({ tasks: [...state.tasks, task] })); },
assess: (id, decision) => { const now = Date.now(); set((state) => { // Freshly computed at the moment of transition into `ready` — always appends to // the end of the current Ready order, never reused from a stale prior value (a // task re-readied after a demote gets a brand new position, not its old one). const nextReadyOrder = decision === 'clear' ? Math.max(-1, ...state.tasks.filter((t) => t.status === 'ready').map((t) => t.order ?? -1)) + 1 : undefined; return { tasks: state.tasks.map((task): LocalTask => { if (task.id !== id || task.status === 'done') return task; const exposureCount = task.exposureCount + 1; if (decision === 'clear') { // No resistance: the task is ready to act on. return { ...task, status: 'ready', exposureCount, lastDecision: 'clear', updatedAt: now, statusChangedAt: now, order: nextReadyOrder, }; } // Still resistant: soften it (bump resistance) but leave its place in the deck. // `updatedAt` bumping IS now load-bearing for order — the open/planning deck // sorts by updatedAt-then-createdAt, so resisting sinks a task toward the back // of the next pass rather than leaving it where it was created. return { ...task, status: 'open', resistance: Math.min(task.resistance + 1, 5), exposureCount, lastDecision: 'resistant', updatedAt: now, statusChangedAt: now, }; }), }; }); },
complete: (id) => { const now = Date.now(); let actioned = false; const tasks = get().tasks.map((task): LocalTask => { if (task.id !== id || task.status === 'done') return task; actioned = true; return { ...task, status: 'done', completedAt: now, updatedAt: now, statusChangedAt: now }; }); if (!actioned) return; set((state) => ({ tasks, session: { ...state.session, doneThisSession: state.session.doneThisSession + 1 }, })); },
demoteReadyTasks: () => { const now = Date.now(); set((state) => ({ tasks: state.tasks.map((task): LocalTask => task.status !== 'ready' ? task : { ...task, status: 'open', updatedAt: now, statusChangedAt: now, order: undefined } ), })); },
deferNow: (id) => { const now = Date.now(); set((state) => { const readyMax = Math.max(-1, ...state.tasks.filter((t) => t.status === 'ready').map((t) => t.order ?? -1)); return { tasks: state.tasks.map((task): LocalTask => task.id !== id || task.status !== 'ready' ? task : { ...task, order: readyMax + 1, deferCount: (task.deferCount ?? 0) + 1, updatedAt: now } ), }; }); },
startPlanSession: () => { set({ session: { doneThisSession: 0, planSessionAt: Date.now() } }); },
ensureActionSession: () => { if (get().session.planSessionAt > 0) return; set({ session: { doneThisSession: 0, planSessionAt: Date.now() } }); },
ensureStarterTasks: () => { if (get().tasks.length > 0) return; const now = Date.now(); const owner = currentOwnerId(); const seeded: LocalTask[] = STARTER_TASKS.map((seed, index) => ({ id: newTaskId(), ownerId: owner, title: seed.title, resistance: seed.resistance, status: 'open', exposureCount: 0, createdAt: now + index, updatedAt: now, syncedAt: null, })); set({ tasks: seeded }); },
ingestServerRows: (rows) => { if (rows.length === 0) return; set((state) => { const byId = new Map(state.tasks.map((t) => [t.id, t])); for (const row of rows) { const incoming = serverToLocal(row); const local = byId.get(incoming.id); // Adopt the server row when it's newer-or-equal (this also confirms our own // just-pushed edit → marks it clean). Keep a strictly-newer local row: it's a // dirty edit that hasn't pushed yet and will win when it does. if (!local || incoming.updatedAt >= local.updatedAt) { byId.set(incoming.id, incoming); } } return { tasks: [...byId.values()] }; }); },
adoptOwner: (ownerId) => { const tasks = get().tasks; if (tasks.every((t) => t.ownerId === ownerId || !isAdoptableOwner(t.ownerId))) return; const now = Date.now(); set({ tasks: tasks.map((t) => t.ownerId === ownerId || !isAdoptableOwner(t.ownerId) ? t : { ...t, ownerId, updatedAt: now } ), }); },
releaseOwner: (ownerId) => { const tasks = get().tasks; if (tasks.every((task) => task.ownerId !== ownerId)) return; const now = Date.now(); set({ tasks: tasks.map((task) => task.ownerId === ownerId ? { ...task, ownerId: null, updatedAt: now, syncedAt: null } : task ), }); }, }), { name: 'glide.tasks', storage: mmkvJSONStorage, } ));