import { 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 } from './sync/owner'; import { mergeWorkspace, persistedWorkspaceTasks, replaceWorkspace, resolvePersistedWorkspaceOwner, serverTaskToLocal, workspaceRowsForReconciliation, type AuthIntent, } from './sync/workspace-policy'; /** * 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 manual `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; /** Manual position within the `ready` bucket ("Next Up" order). Irrelevant while open/done; * freshly assigned (append-at-end) each time a task transitions into `ready`. */ 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); /** * 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; }; export type WorkspaceState = { /** The account this one local dataset last synchronized with. Retained across sign-out. */ ownerId: string | null; /** Explicit auth flow waiting for merge/replace policy after Clerk finalizes. */ pendingAuthIntent: AuthIntent; /** Starter tasks are a one-time onboarding seed, never recreated after an intentional purge. */ starterTasksSeeded: boolean; }; /** 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; function starterTasks(ownerId: string | null): LocalTask[] { const now = Date.now(); return STARTER_TASKS.map((seed, index) => ({ id: newTaskId(), ownerId, title: seed.title, resistance: seed.resistance, status: 'open', exposureCount: 0, createdAt: now + index, updatedAt: now, syncedAt: null, })); } type TaskState = { tasks: LocalTask[]; session: SessionState; workspace: WorkspaceState; /** 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; /** Commit a manual drag-to-reorder of the ready ("Next Up") bucket. */ reorderReady: (orderedIds: TaskId[]) => 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; /** Record which explicit Clerk flow is about to finalize, surviving a mid-transition restart. */ setPendingAuthIntent: (intent: Exclude) => void; clearPendingAuthIntent: () => void; /** Apply the user's (or automatic signup/resume) reconciliation decision atomically. */ reconcileWorkspace: (ownerId: string, rows: ServerTask[], strategy: 'merge' | 'replace') => void; /** Sign-out "remove": purge only this device's task copy, never create cloud tombstones. */ clearLocalWorkspace: () => void; /** Sync: merge authoritative server rows in (last-write-wins; keeps newer local edits). */ ingestServerRows: (rows: ServerTask[]) => 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()( persist( (set, get) => ({ tasks: [], session: { doneThisSession: 0, planSessionAt: 0 }, workspace: { ownerId: null, pendingAuthIntent: null, starterTasksSeeded: false }, 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() ?? get().workspace.ownerId, 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) => { const workspaceIds = new Set( persistedWorkspaceTasks(state.tasks, state.workspace.ownerId).map((task) => task.id) ); if (!workspaceIds.has(id)) return 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((task) => workspaceIds.has(task.id) && task.status === 'ready') .map((task) => task.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(); const state = get(); const workspaceIds = new Set( persistedWorkspaceTasks(state.tasks, state.workspace.ownerId).map((task) => task.id) ); if (!workspaceIds.has(id)) return; let actioned = false; const tasks = state.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) => { const workspaceIds = new Set( persistedWorkspaceTasks(state.tasks, state.workspace.ownerId).map((task) => task.id) ); return { tasks: state.tasks.map((task): LocalTask => !workspaceIds.has(task.id) || task.status !== 'ready' ? task : { ...task, status: 'open', updatedAt: now, statusChangedAt: now, order: undefined } ), }; }); }, reorderReady: (orderedIds) => { const now = Date.now(); const idSet = new Set(orderedIds); set((state) => { const workspaceIds = new Set( persistedWorkspaceTasks(state.tasks, state.workspace.ownerId).map((task) => task.id) ); // `orderedIds` is only the "Next Up" subset (the reorderable list excludes the // current "Now" task) — so indices must start *after* whatever's not being // reordered, or a low index here could undercut Now's order and steal its slot. const untouchedMax = Math.max( -1, ...state.tasks .filter( (task) => workspaceIds.has(task.id) && task.status === 'ready' && !idSet.has(task.id) ) .map((task) => task.order ?? -1) ); const indexById = new Map(orderedIds.map((id, index) => [id, untouchedMax + 1 + index])); return { tasks: state.tasks.map((task): LocalTask => { if (!workspaceIds.has(task.id) || task.status !== 'ready') return task; const nextOrder = indexById.get(task.id); if (nextOrder === undefined || nextOrder === task.order) return task; return { ...task, order: nextOrder, updatedAt: now }; }), }; }); }, deferNow: (id) => { const now = Date.now(); set((state) => { const workspaceIds = new Set( persistedWorkspaceTasks(state.tasks, state.workspace.ownerId).map((task) => task.id) ); if (!workspaceIds.has(id)) return state; const readyMax = Math.max( -1, ...state.tasks .filter((task) => workspaceIds.has(task.id) && task.status === 'ready') .map((task) => task.order ?? -1) ); return { tasks: state.tasks.map((task): LocalTask => !workspaceIds.has(task.id) || 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: () => { const state = get(); if (state.workspace.starterTasksSeeded) return; if (state.tasks.length > 0) { set({ workspace: { ...state.workspace, starterTasksSeeded: true } }); return; } const seeded = starterTasks(currentOwnerId() ?? state.workspace.ownerId); set({ tasks: seeded, workspace: { ...state.workspace, starterTasksSeeded: true }, }); }, setPendingAuthIntent: (intent) => { set((state) => ({ workspace: { ...state.workspace, pendingAuthIntent: intent } })); }, clearPendingAuthIntent: () => { set((state) => ({ workspace: state.workspace.pendingAuthIntent === null ? state.workspace : { ...state.workspace, pendingAuthIntent: null }, })); }, reconcileWorkspace: (ownerId, rows, strategy) => { set((state) => { const reconciled = strategy === 'merge' ? mergeWorkspace( workspaceRowsForReconciliation(state.tasks, state.workspace.ownerId, ownerId), rows, ownerId ) : replaceWorkspace(rows); return { tasks: reconciled.length === 0 && !state.workspace.starterTasksSeeded ? starterTasks(ownerId) : reconciled, session: strategy === 'replace' ? { doneThisSession: 0, planSessionAt: Date.now() } : state.session, workspace: { ownerId, pendingAuthIntent: null, starterTasksSeeded: true, }, }; }); }, clearLocalWorkspace: () => { set((state) => ({ tasks: [], session: state.session, workspace: { ownerId: null, pendingAuthIntent: null, starterTasksSeeded: true, }, })); }, 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 = serverTaskToLocal(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()] }; }); }, releaseOwner: (ownerId) => { set((state) => ({ tasks: workspaceRowsForReconciliation(state.tasks, state.workspace.ownerId, ownerId).map((task) => task.ownerId === ownerId ? { ...task, ownerId: null, syncedAt: null } : task ), workspace: { ...state.workspace, ownerId: state.workspace.ownerId === ownerId ? null : state.workspace.ownerId, pendingAuthIntent: null, }, })); }, }), { name: 'glide.tasks', storage: mmkvJSONStorage, merge: (persistedState, currentState) => { const restored = persistedState as Partial; const tasks = restored.tasks ?? currentState.tasks; const workspace = { ...currentState.workspace, ...restored.workspace, }; return { ...currentState, ...restored, tasks, session: { ...currentState.session, ...restored.session, }, workspace: { ...workspace, ownerId: resolvePersistedWorkspaceOwner(tasks, workspace.ownerId), }, }; }, } ) );