Dispatch Task Management

repository·main·Indexed 42 days ago

https://github.com/nkasco/dispatchtodoapp

A self-hosted task management application featuring a dark UI, keyboard-friendly UX, and integrated daily planning. Built with Node.js, SQLite, and Drizzle ORM, it supports Docker deployment, GitHub OAuth authentication, and AI chat integration via the Vercel AI SDK. Key features include task and note CRUD APIs, a daily dispatch workflow for task aggregation, and role-based access control for administrators.

Tokens
18.9K
Snippets
54
Records
92
Agent score
52%

What's inside Dispatch

  1. Understand the Dispatch project structure

    main

    The project is organized into several key directories that define its functionality:

    • src/app/: Contains Next.js App Router pages and API route handlers (REST endpoints).
    • src/components/: Reusable UI components, including layout shells, specialized page views, and utility components like ToastProvider and SearchOverlay.
    • src/lib/: Core logic and utilities, including API authentication helpers (withAuth), a typed API client (client.ts), and AI/encryption helpers.
    • src/mcp-server/: A standalone Model Context Protocol (MCP) HTTP server providing tools for tasks, notes, projects, and search.
    • src/db/: Database schema definitions (Drizzle) and the SQLite client.
    • src/test/: Test utilities including an in-memory SQLite factory and auth mocking.
  2. Configure user timezone for consistent date logic

    main

    To prevent 'today' from resolving incorrectly due to date drift, Dispatch uses a per-user profile timezone preference.

    • Default Behavior: If no preference is set, the application auto-defaults to the user's browser/system timezone.
    • Usage: This timezone is used consistently across the Dashboard, Inbox, Dispatch, and Assistant/MCP date contexts to ensure 'today' is accurate for the user.
  3. Data Model and Schema Overview

    main

    The application data is organized into Auth and Domain tables.

    Auth Tables

    • users: Stores identity, roles (member/admin), and assistant settings.
    • accounts: Links OAuth provider records to users.
    • sessions: Tracks session tokens and expiry.

    Domain Tables

    • tasks: Manages tasks with status (open, in_progress, done) and priority (low, medium, high).
    • notes: Stores text-based notes.
    • projects: Groups tasks with a status (active, paused, completed) and one of six colors (blue, emerald, amber, rose, violet, slate).
    • dispatches: Daily workflow summaries indexed by userId and date (YYYY-MM-DD).
    • apiKeys: Stores user-generated keys for programmatic access.
    • aiConfigs: Stores encrypted AI provider credentials and model settings.
    • chatConversations & chatMessages: Stores history for the Personal Assistant.

    Soft-Delete Mechanism

    Tasks, notes, and projects use a soft-delete pattern. Instead of being removed from the database, a deletedAt timestamp is set.

    • Soft-deleted items are hidden from standard list, get, and search queries.
    • Items can be restored or permanently deleted via the Recycle Bin (/recycle-bin).
    • Items are automatically purged after 30 days.
  4. Configure Import Behavior and Data Fidelity

    main

    When performing an import, users can control the level of detail and the handling of specific data types through the following mechanisms:

    • Field Mapping: For CSV/spreadsheet imports, use the field-mapping UI to pair columns with Dispatch fields. The system includes smart auto-detection and provides fallback labels for non-native fields.
    • Import Controls: Users can opt-in or opt-out of importing specific data types to balance speed versus fidelity, including:
      • Completed/archived items
      • Closed projects/boards
      • Comments/history
      • Attachments/assets
    • Duplicate Detection: The system uses source fingerprints and stable external IDs to handle repeated imports. Users can choose between several behaviors: skip, create copy, or merge.
    • Timezone Handling: Due dates, reminders, and date-only values are handled using the user's profile timezone. If the source export is ambiguous, explicit fallback rules are applied.
  5. Daily Dispatch Workflow and API

    main

    The 'Dispatch' feature aggregates tasks and notes into a daily view.

    Data Model

    • dispatches table: Contains id, userId, date (unique per user per day), summary (markdown), and finalized (boolean).
    • dispatch_tasks table: A join table used to link specific tasks to a dispatch entry.

    Key Workflows

    • Auto-creation: The /dispatch page automatically creates an entry for the current date if one does not exist.
    • Task Linking: Tasks can be linked or unlinked to a dispatch via the /api/dispatches/[id]/tasks endpoint.
    • Completing a Day: Using the /api/dispatches/[id]/complete endpoint marks the dispatch as finalized and automatically rolls any unfinished tasks over to the next day.
  6. How administrator roles and account management work

    main

    Dispatch implements a role-based access control system for administration.

    • Bootstrap Logic: The very first account created in the system is automatically assigned the administrator role.
    • Role Delegation: Administrators have the authority to promote or demote other user accounts to or from administrator status.
    • Admin Actions: Administrators can perform the following user-management actions:
      • Reset user passwords.
      • Freeze or unfreeze account access.
      • Create new user accounts.
      • Delete existing user accounts.
    • Access: The Administration settings section is surfaced from the Profile page and is only visible to accounts with the administrator role.
  7. Core Principles and Architecture of Dispatch

    main

    Dispatch is a local-first, single-user web application designed for managing tasks, notes, and projects.

    Key Architectural Concepts:

    • Local-first: The application runs on localhost and persists all data to a local SQLite file using better-sqlite3 and Drizzle ORM. There is no cloud dependency for storage.
    • Single-user Authentication: Access is gated via GitHub OAuth2 or local email/password credentials. Even though it is local, authentication is used to prevent accidental exposure if the local port is reachable on a network.
    • REST API Driven: The React SPA communicates with Next.js API Route Handlers using standard JSON REST patterns. It does not use GraphQL.
    • Actionable AI: A Personal Assistant (Beta) can invoke application actions through a local Model Context Protocol (MCP) server.
    • Zero-ops Persistence: Uses SQLite for simple, serverless data management.
  8. Core Data Model: Tasks and Notes

    main

    The application's core domain is built around two primary entities stored in SQLite via Drizzle:

    Tasks

    Stored in the tasks table with the following schema:

    • id: Unique identifier
    • userId: Owner of the task
    • title: Task name
    • description: Detailed text
    • status: Enum (open, in_progress, done)
    • priority: Enum (low, medium, high)
    • dueDate: Scheduled date
    • createdAt / updatedAt: Timestamps

    Notes

    Stored in the notes table with the following schema:

    • id: Unique identifier
    • userId: Owner of the note
    • title: Note title
    • content: Markdown text
    • createdAt / updatedAt: Timestamps
  9. Authentication Methods in Dispatch

    main

    Dispatch supports multiple ways to authenticate, depending on your setup and access needs:

    1. User Login (Web UI)

    • GitHub OAuth: Enabled if AUTH_GITHUB_ID and AUTH_GITHUB_SECRET environment variables are configured.
    • Local Credentials: Email and password registration/login using bcryptjs hashing. New users can register via POST /api/auth/register.
    • Role-based Access: The first account created is automatically assigned the admin role.

    2. Programmatic Access (API Keys)

    For scripts or external tools, you can use API Key authentication. Keys are managed at the /api/api-keys endpoint. Supported headers are:

    • Authorization: Bearer <key>
    • X-API-Key: <key>

    3. Security Constraints

    • All API routes (except /api/auth/*) require a valid session.
    • The withAuth wrapper in src/lib/api.ts enforces session requirements at the route level.
    • Frozen accounts are blocked from signing in and accessing protected APIs.
  10. Extend AI capabilities with MCP (Model Context Protocol)

    main

    To allow the AI assistant to perform actions within Dispatch (like managing tasks, notes, or projects), the system uses a Model Context Protocol (MCP) server.

    Architecture:

    1. MCP Server: A separate Node.js process (src/mcp-server/) running on a configurable port (default 3001). It uses NodeStreamableHTTPServerTransport to serve tools.
    2. MCP Client: The POST /api/ai/chat endpoint creates an @ai-sdk/mcp client per request, fetches available tools, and passes them to the streamText() call.
    3. Tool Scoping: All tool operations are strictly scoped to the authenticated userId passed from the chat API to the MCP server to ensure data isolation.

    Available Tool Categories:

    • Task Tools: list-tasks, create-task, update-task, complete-task, delete-task.
    • Note Tools: list-notes, create-note, update-note, delete-note.
    • Project Tools: list-projects, create-project, update-project, get-project-tasks.
    • Dispatch Tools: get-today-dispatch, update-dispatch-summary, link-task-to-dispatch, unlink-task-from-dispatch, complete-dispatch.
    • Search Tool: search (cross-entity search across tasks, notes, projects, and dispatches).
  11. Integrate AI Chat using Vercel AI SDK

    main

    Dispatch incorporates a conversational AI assistant using the Vercel AI SDK (ai) as a unified abstraction layer. This allows the application to support multiple cloud providers (OpenAI, Anthropic, Google Gemini) and local models (Ollama, LM Studio) through a single streamText() API.

    Key dependencies for AI integration include:

    • ai: Core SDK
    • @ai-sdk/react: For the useChat() hook in the UI
    • @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google: Provider-specific packages
    • @ai-sdk/openai-compatible: For local models like Ollama or LM Studio via OpenAI-compatible endpoints.
    npm install ai @ai-sdk/react @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google @ai-sdk/openai-compatible
  12. Reliable outbound synchronization logic

    main

    To ensure task mutations are reliably delivered to external connectors, Dispatch implements a durable outbound sync pipeline. This pipeline includes:

    • Change log/outbox: Tracks pending changes.
    • Retry mechanism: Handles transient failures.
    • Idempotency keys: Prevents duplicate processing.
    • Backoff: Manages retry timing.
    • Conflict Resolution: Uses a 'last-write-wins' policy by default, providing per-item conflict markers when necessary.