feat: complete rewrite of course (#622)

* theming improvements

* border style improvements

* refactor: migrate org routes to server-side data fetching

Move client-side API calls to server-side load functions for better
performance, security, and SEO. Implement permission-based course filtering

* refactor: clean up course and community components

This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization.

* refactor: fix video formatting on website and other styles

* refactor: update course and dashboard components for improved styling and functionality

* more icon improvements

* refactor: streamline course and dashboard components

This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability.

* refactor: enhance lesson completion logic

* chore: delete all emails on dashboard and move other api routes to backend.

move all emails to the backend and

* feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management.

* get app loading

* fix ui and build error of cio/api

* refactor: move direct database queries to query layer

- Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds
- Refactor services to use query functions instead of direct db queries
- Add transaction support to updateCourseVersion and updateLessonsSectionId
- Fix getProfileByGroupMemberId to return profile directly (not nested)
- Fix updateLessonsSectionId to use .returning() instead of rowCount

This aligns services with architecture pattern where services orchestrate queries rather than executing them directly.

* exercise saving improvements

* fix and optimise exercise creation

* refactor: update dialog components for improved styling and functionality

- Adjusted dialog content width and maximum constraints for better responsiveness.
- Changed heading font size for consistency in the new exercise modal.
- Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button.

* refactor: enhance course and exercise management components

- Introduced new components for exercise creation, editing, and viewing, improving user experience.
- Refactored existing lesson and exercise components for better organization and maintainability.
- Updated routing for exercises and lessons to streamline navigation within the course structure.
- Added new utility functions and constants to support content management across the application.

* feat: implement course content management API and UI components

- Added new API routes for updating and deleting course content, enhancing content management capabilities.
- Introduced new Svelte components for displaying and managing course content, including content lists and action handlers.
- Updated existing course routing to integrate new content management features.
- Refactored content-related utility functions for improved organization and maintainability.

* refactor: remove Supabase references and implement course section management

- Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration.
- Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections.
- Updated course services to handle section operations, ensuring consistency in course content management.
- Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability.

* chore: update .prettierignore to exclude additional file types

- Added exclusions for SQL and environment files to the Prettier ignore list.
- Included Dockerfile and .prettierignore itself to prevent formatting issues.

* feat: enhance course content management with translation support and UI improvements

- Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files.
- Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization.
- Refactored course content management components to streamline the creation and editing process, enhancing user experience.
- Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability.
- Improved styling and functionality of course content modals and steppers for better user interaction.

* feat: enhance course content management and UI components

- Updated .prettierignore to exclude storybook-static directory.
- Improved exercise creation logic by refining option handling and adding UUID support for option values.
- Enhanced navigation component with debugging output for custom links.
- Introduced a new method in CourseApi to update content items locally, improving state management during navigation.
- Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance.
- Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality.
- Implemented local patching for lesson and exercise list items to ensure UI consistency after updates.

* student + teacher invite (not fully tested)

* refactor: streamline course team member middleware

- Removed unnecessary console logging and timing for checking user permissions.
- Simplified the logic for determining if a user is a course team member or organization admin.

* reorder course sidebar to move content to its own page.

* feat: implement unified course enrollment route and API

- Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system.
- Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses.
- Updated course landing page to redirect to the new enrollment route for free courses.
- Removed obsolete invite routes and related logic, streamlining the enrollment process.
- Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments.
- Added rate limiting for enrollment requests to prevent abuse.
- Updated UI components to reflect changes in enrollment flow and messaging.

* chore: update docker stack, docs, and auth token automation

* chore: make prettier check ignore unknown file types

* fix: avoid using authClient on server file and keep authClient client focused

* chore: always get the server on demand depending on the environment

* chore: update dashboard configuration and Docker setup for environment variables

- Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable.
- Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build.
- Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used.

* chore: enhance Docker setup and documentation for production deployment

- Added a new production Docker Compose file and example environment file for published images.
- Updated README and usage documentation to include instructions for deploying with production images.
- Modified Svelte configuration to standardize the use of the posthog domain.
- Removed unnecessary console logs from the API client and layout server files for cleaner output.
- Improved overall clarity in Docker documentation regarding self-hosting and image publishing.

* chore(db): log function name in query catch blocks (console.error 'funcName error:', error)

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: multiple refresh issue

* fix: server key not passed to api

* fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation

- Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware.
- Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware.
- Adjusted examples in Docker setup and self-hosting documentation to reflect these changes.

* fix migration script

* fix: improve language handling and add database reset script

- Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary.
- Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding.

* feat: add promote ungrouped section functionality and enhance document handling in dashboard

- Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials.
- Updated the dashboard to include a new component for displaying content count badges for lessons and exercises.
- Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents.
- Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions.
- Refactored existing components for better readability and maintainability, including updates to lesson and document lists.

* chore: use root env file for docker compose

* docs: document docker no-build startup flow

* chore: add no-build option to docker full stack script

* fix(email): handle SMTP TLS mode by port

* feat(auth): add configurable cookie domain env and docs

* apps/dashboard/src/lib/utils/services/auth/session.ts

* fix(email): make sender configurable via SMTP_SENDER

* chore(i18n): regenerate locale translations and support language targeting

* chore(config): switch api to PUBLIC_SERVER_URL

* fix(i18n): persist selected locale across navigation

* feat(assets): implement organization asset management routes and services

- Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets.
- Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion.
- Integrated YouTube metadata resolution and asset attachment/detachment functionalities.
- Updated organization routes to include the new asset management routes.
- Enhanced error handling for asset-related operations.

* fix(document-list): update conditional rendering for edit mode in document list

* debug self hosted layout setup

* refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering

* feat: tags

* chore: tags roadmap + translations

* fix(api): add authMiddleware to exercise, invites, and content routers

- exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes
- invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes
- contentRouter: add authMiddleware to PUT route (DELETE already had it)

Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring
authMiddleware to be applied first. This aligns with lessonRouter pattern and
ensures explicit middleware contract regardless of global session middleware.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes

These routes require admin/tutor role per JSDoc but were using
courseMemberMiddleware which allows any course member including students.
Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR
group members and org admins.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* chore: unify pricing component between dashboard and website (#630)

* feat: modularize pricing card

* feat: initia implementation of pricing togge

* fix: minor amendment

* refactor: update pricing components for improved layout and styling

- Adjusted spacing in the pricing card layout for better visual consistency.
- Modified button styles and sizes for enhanced usability.
- Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic.

* add handle click

* chore(css): update Tailwind CSS output with new utility classes and theme variables

* fix(api): enable orgMemberMiddleware for stats route

This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code.

---------

Co-authored-by: Rotimi Best <best@classroomio.com>

* pass query parameter to signup from pricing page

* ui updates to pricing cards

* commit all PRDs

* add open api spec to api prd

* make blue default theme

* more prds

* sync option id sequence on question update

* docs: more classroomio features

* chore: more ui improvements

* docs: new component docs

* chore: CSP Configuration (#638)

* feat(validation): add GitHub repository name validation

- Add ZRepositoryName schema for validating GitHub repo names
- Add ZRepositoryOwner for owner/username validation
- Add ZRepositoryIdentifier for owner/repo format
- Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names
- Add translation keys for validation messages

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* Revert "feat(validation): add GitHub repository name validation"

This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce.

* feat(dashboard): make CSP external domains configurable via env

Move hardcoded external domains from svelte.config.js to .env configuration
for on-premise deployments with strict security policies, data residency
constraints, or CISO-driven allowlists.

- ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives
- CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS,
  CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override
- When unset, defaults retain current SaaS behavior (backward compatible)

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): self-hosted CSP uses only env vars, no defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): add all classroomio.com domains to CSP defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(docker): pass CSP domain env vars as build args to dashboard

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add SSO and token authentication routes and services

- Introduced new routes for SSO and token authentication under the organization namespace.
- Implemented SSO connection management including creation, update, activation, and deletion.
- Added token authentication configuration with support for secret rotation and status retrieval.
- Enhanced error handling for SSO and token authentication processes.
- Updated existing routes and services to integrate new functionalities.
- Improved gradebook service to fetch student marks and exercises.
- Refactored API structure for better organization and maintainability.

* update translations

* fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641)

Co-authored-by: Cursor Agent <cursoragent@cursor.com>

* feat: new exercise question types

* MinIO S3 storage backend (#639)

* feat(storage): add MinIO/S3-compatible object storage backend

- Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3)
- Create storage config module with Cloudflare R2 fallback for backward compatibility
- Refactor s3.ts to use configurable client and bucket names from config
- Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN)
- Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets
- Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads
- Update self-hosting and Cloudflare docs with MinIO option
- Update .env examples and docker USAGE.md

Fixes #635

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(media): refactor media management and integrate MinIO support

- Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components.
- Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion.
- Enhanced environment variable management for MinIO in the `.env.example` file.
- Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard.
- Introduced new media components for asset management, including asset cards and usage dialogs.

This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions.

* feat(dashboard): enhance logging and refactor auth session handling

- Added console logging for event and environment variables in hooks.server.ts to aid debugging.
- Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency.
- Updated Dockerfile to ensure the dashboard build output is present before starting the application.
- Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker.

These changes improve the observability of the application and streamline the authentication process.

* refactor(dashboard): remove debug logging and enhance Postgres healthcheck

- Removed console logging for event and environment variables in hooks.server.ts to clean up the code.
- Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready.
- Expanded self-hosting documentation to include troubleshooting steps for database recovery issues.

These changes improve code clarity and reliability in service startup sequences.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add Plyr media player icons and PDF.js integration

- Introduced new Plyr SVG icons for media player controls in both course and dashboard applications.
- Updated Plyr player configuration to use local icon assets.
- Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability.
- Enhanced PDF viewer modal z-index for better visibility.

This update improves the media player experience and ensures consistent access to necessary resources.

* feat: enhance account and organization services with type definitions and promise return types

- Updated `getAccountData` to return a structured result type including profile and organizations.
- Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety.
- Added new type imports for organization-related data structures to improve clarity and maintainability.

These changes improve type safety and enhance the overall structure of the account and organization services.

* feat: implement Redis caching for presigned URLs and refactor API interactions

- Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance.
- Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability.
- Updated various components to utilize the new `presignApi` methods for document and video upload/download operations.
- Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures.

These changes optimize the presigned URL generation process and streamline API interactions across the application.

* fix: add better-auth dependency to dashboard (#645)

* chore: unify exercise answer data format

* feat: make selfhosting run under one org for simplicity (#647)

* feat: implement self-hosting PRD + license key system

Self-hosting single-org:
- Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists
- Auto-add non-members as students in GET /account bootstrap
- getOrgSiteInfo: root domain returns single org for self-hosted
- App init: route to /lms when self-hosted + no orgs
- Hide org switcher and Add Org modal when self-hosted

Invite-only signup:
- Add settings.signup.inviteOnly via ZUpdateOrganization
- Allow public signups toggle in org auth settings
- Signup page: hide form when invite-only and no invite context
- Landing page nav: respect inviteOnly for signup link

First signup auto-verify:
- Self-hosted first signup (no orgs) auto-verifies email in createProfileHook

License key system:
- LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API
- Feature gates: SSO, token-auth, no-tracking (PostHog/Senja)
- requireLicense middleware for API routes
- Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI
- docs/LICENSE_API_CONTRACT.md for external API spec

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: get rid of carbon completely

* chore: license verification happens only for selfhosted instance

* fix: in self hosted instance, orgSite is the default

* docs: how to write math in cio editor

* Update packages/db/src/queries/organization/organization.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update apps/api/src/services/license.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: translations, cursor pr reviews, simplify license fetching and check

* refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic

* refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss

* more selfhosting improvements

* feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided

* pr reviews

* fix: correct query parameter handling in course navigation

* pr reviews

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com>
Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
Rotimi Best
2026-03-09 11:18:22 +01:00
committed by GitHub
co-authored by Rotimi Best greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Cursor Agent Abdulmuizz Hamzat Adeyemi Adetunji
parent a42565ad82
commit 1e9a82e912
1196 changed files with 118809 additions and 74705 deletions
@@ -0,0 +1,626 @@
---
name: AI assistant PRD
overview: Write a new PRD from scratch for the AI Course Assistant feature, replacing the existing placeholder at prd/ai-course-assistant/README.md. The PRD will document a hybrid execution model, configurable LLM providers, streaming chat, and the full package/API/UI architecture.
todos:
- id: write-prd
content: "Write the full PRD markdown file at prd/ai-course-assistant/README.md with all sections: purpose, architecture, execution model, package design, tools, safeguards, UI spec, self-host gating, streaming, API routes, and implementation phases"
status: pending
isProject: false
---
# AI Course Assistant PRD
## What We're Writing
Replace [prd/ai-course-assistant/README.md](prd/ai-course-assistant/README.md) with a comprehensive PRD for an AI assistant embedded in the course UI. The PRD will be a single markdown file covering architecture, UI, safeguards, package design, and implementation phases.
## Key Architectural Decisions
### Execution Model: Hybrid (Local Reads, API Writes)
The client already has course content loaded in Svelte stores (`lessonApi`, exercise `questionnaire`, etc.) when the teacher is on a page. The agent should:
- **Read context from the client** — pass the current lesson text, exercise questions, course structure to the agent as context with each message. No extra API calls to "read" content.
- **Write through the API** — all mutations route through existing API endpoints (`/course/:courseId/lesson`, `/course/:courseId/exercise`, etc.) using the full middleware stack (`authMiddleware` -> `orgMemberMiddleware` -> `courseTeamMemberMiddleware`). This gives us permission enforcement, single source of truth, and auditability for free.
- **Preview for destructive changes** — when the agent rewrites a lesson or makes a large edit, show a diff/preview in the chat with an "Apply" button. For additive actions (generate 5 questions), execute directly and confirm.
### Agent Architecture: Tool-Calling Pattern
The agent uses LLM function/tool calling (not free-form text parsing):
```mermaid
sequenceDiagram
participant Teacher
participant ChatUI as Chat UI
participant AgentAPI as Agent API
participant LLM
participant Services as Existing Services
Teacher->>ChatUI: "Generate 5 MCQ questions from this lesson"
ChatUI->>AgentAPI: POST /agent/chat (message + context)
AgentAPI->>LLM: System prompt + tools + conversation
LLM->>AgentAPI: tool_call: add_questions(exerciseId, questions[])
AgentAPI->>Services: exerciseService.addQuestions()
Services->>AgentAPI: Success
AgentAPI->>LLM: Tool result
LLM->>AgentAPI: "Done! I added 5 questions to..."
AgentAPI-->>ChatUI: SSE stream response
ChatUI->>Teacher: Shows confirmation + refreshes exercise
```
The LLM sees a set of **tools** (mapped to existing service functions) and decides which to call based on the teacher's message. The agent API executes the tool with full permission checks, then feeds the result back to the LLM for a human-friendly summary.
### SDK: Vercel AI SDK
The **Vercel AI SDK** (`ai` + `@ai-sdk/svelte` + provider packages) is the right fit:
- `@ai-sdk/svelte` provides a `Chat` class that uses Svelte 5 runes internally — same class-based reactive pattern as the project's existing `LessonApi` / `BaseApiWithErrors` ([base.svelte.ts](apps/dashboard/src/lib/utils/services/api/base.svelte.ts)).
- `streamText()` returns `toUIMessageStreamResponse()` which works directly as a Hono response — zero glue code ([Hono cookbook](https://sdk.vercel.ai/cookbook/api-servers/hono)).
- Tool calling is built-in with Zod schemas (already used everywhere in the project). The SDK handles the function-calling protocol, multi-step execution, and streaming tool results.
- Provider abstraction lets us swap between `@ai-sdk/openai` and `@ai-sdk/anthropic` by changing one line.
- The wire protocol carries text chunks, tool call events, tool results, and finish signals. The `Chat` class on the client parses all of this automatically.
**Packages to install:**
- `ai` — core (`streamText`, `tool`, types) — in `packages/ai-assistant` and `apps/api`
- `@ai-sdk/svelte` — Svelte 5 `Chat` class — in `apps/dashboard`
- `@ai-sdk/openai` — OpenAI provider — in `packages/ai-assistant`
- `@ai-sdk/anthropic` — Anthropic provider — in `packages/ai-assistant`
- `zod` — already installed everywhere
### Package: `packages/ai-assistant`
A thin, backend-focused package consumed by `apps/api`. No UI code. The heavy lifting is done by the Vercel AI SDK; this package provides project-specific configuration on top.
Responsibilities:
- **Provider factory** — creates the right AI SDK `LanguageModel` from env vars (`AI_PROVIDER`, `AI_API_KEY`, `AI_MODEL`). Wraps `@ai-sdk/openai` and `@ai-sdk/anthropic`.
- **Role-aware tool registry** — `getToolSchemas(role)` returns the right Zod schemas per role. No implementations — those live in the API.
- **Role-aware system prompt** — `buildSystemPrompt(context)` generates different LLM instructions for teachers vs students.
- **Shared types** — `AgentRole`, `AgentContext`, tool names, config types. Used by both `apps/api` and `apps/dashboard`.
Suggested structure:
```
packages/ai-assistant/
src/
index.ts # Public exports
types.ts # AgentRole, AgentContext, AIProviderConfig, tool name constants
providers/
index.ts # createModel(config) factory
tools/
index.ts # getToolSchemas(role) registry
shared.ts # Read-only tool schemas (both roles)
teacher.ts # Mutation tool schemas (teacher only, v1)
student.ts # Learning tool schemas (student only, v2 stubs)
prompt/
system-prompt.ts # buildSystemPrompt(context) — role-aware
teacher.ts # Teacher prompt template
student.ts # Student prompt template (v2 stub)
package.json
tsconfig.json
```
Note: the agent loop itself is NOT in this package — `streamText()` from the `ai` core package handles the full loop (prompt -> LLM -> tool call -> execute -> respond -> repeat). The Hono route assembles tools (schema from package + execute from services) and calls `streamText`.
### Foundation Layer: Role-Aware Design
The agent is not just a teacher tool — it's a **course assistant** that behaves differently per role. The foundation must support this from day one, even though students are gated off in v1.
`**AgentRole`** — the core discriminator:
- `'teacher'` — can read AND mutate course content (update lessons, generate questions, create drafts)
- `'student'` — can only read and discuss content (explain concepts, answer questions, quiz on material)
**Role detection** — server-side, automatic:
- The API route checks the user's course membership via existing queries (`isCourseTeamMemberOrOrgAdmin`)
- Team members (ADMIN/TUTOR role in `groupmember`) get `role: 'teacher'`
- Regular course members (STUDENT role) get `role: 'student'`
- In v1, `role: 'student'` returns a 403. In v2, it loads the student tool set.
**Tool registry** — `getToolSchemas(role)` returns the right set:
- `shared` tools (read-only): `get_course_structure`, `get_lesson_content`, `get_exercise_questions` — available to both roles
- `teacher` tools (mutations): `update_lesson_content`, `create_lesson_draft`, `add_exercise_questions` — teacher only
- `student` tools (v2): `explain_concept`, `quiz_me`, `clarify_exercise` — student only, stubs for now
Teachers get `shared + teacher`. Students get `shared + student`. This ensures students can never access mutation tools, even via prompt injection.
**System prompt** — role-aware via `buildSystemPrompt(context)`:
- Teacher: "You are helping a teacher organize and author course content. You can update lessons, create new content, and generate questions."
- Student (v2): "You are helping a student learn. You can explain concepts, answer questions about the material, and help with exercises. You cannot modify any course content."
**Single API endpoint** — `/agent/chat` serves both roles. Role is detected server-side (not passed by the client, preventing spoofing). The endpoint loads tools and prompt based on the detected role.
### Agent Tools
#### V1 Core Tools (7 tools)
Start small with the essentials for content authoring. Additional tools are added in later phases.
| Tool | Type | Description | Service |
| ----------------------- | ----- | ---------------------------------------------------- | ----------------------------------------------------- |
| `get_course_structure` | read | Get sections, lessons, exercises tree | `getCourseContentItems` + `listCourseSections` |
| `get_lesson_content` | read | Get a specific lesson's note/text | `getLesson` |
| `get_exercise_details` | read | Get exercise with all questions and options | `getExercise` |
| `create_lesson` | write | Create a new lesson in a section (title + content) | `createLesson` |
| `update_lesson_content` | write | Update the note/text content of a lesson | `updateLessonService` + `upsertLessonLanguageService` |
| `create_exercise` | write | Create a new exercise with questions and options | `createExercise` |
| `add_questions` | write | Add questions (with options) to an existing exercise | `updateExerciseService` (diff-based) |
#### Phase 2+ Tools (added after v1 is stable)
**Lessons**: `update_lesson_metadata`, `delete_lesson`, `reorder_lessons`, `update_lesson_translation`
**Sections**: `create_section`, `update_section`, `reorder_sections`, `delete_section`
**Exercises**: `update_exercise_metadata`, `update_question`, `delete_question`, `delete_exercise`, `create_exercise_from_template`
**Other**: `update_course_tags`, `create_newsfeed_post`, `list_exercise_templates`
#### Phase 4 Student Tools (v2)
`explain_concept`, `quiz_me`, `clarify_exercise`, `get_my_progress`, `get_my_submissions`
#### Tool Execution Rules
Each tool handler in the API will:
1. Extract IDs from tool arguments
2. Verify the target resource belongs to the course/org in context
3. Verify user is course team member or org admin (teacher tools)
4. **Check token balance** before LLM call (see Token Usage section)
5. Call the existing service function
6. Return structured result to the agent
#### No-Hallucination Boundary
The system prompt includes an explicit list of what the agent CANNOT do. When a user asks for any of these, the agent responds with a clear, helpful decline and suggests the closest available action. The agent must **never**:
- Pretend to perform an action it doesn't have a tool for
- Fabricate data it hasn't retrieved via a tool call
- Claim to have made a change unless a tool call succeeded
**Explicit CANNOT-do list (included verbatim in system prompt):**
- Cannot create, delete, or clone courses
- Cannot update course-level settings (title, description, logo, status)
- Cannot manage course members, invitations, or roles
- Cannot grade submissions or assign marks
- Cannot handle payments or attendance
- Cannot upload files, images, videos, or documents
- Cannot manage sections, reorder content, or delete content (v1 — added in Phase 2)
- Cannot manage org settings, members, or billing
- Cannot access data from other courses or organizations
- Cannot browse the internet or fetch external URLs
- Cannot send emails or notifications
**System prompt template:**
```
You are an AI assistant for ClassroomIO. You help teachers create and organize
course content.
You have access to specific tools listed below. If a user asks you to do something
NOT covered by your tools, respond clearly:
"I can't do that yet. [Brief reason]. Here's what I can help with: [closest action]."
NEVER pretend to perform an action you don't have a tool for.
NEVER fabricate data you haven't retrieved via a tool.
NEVER claim to have made a change unless a tool call returned success.
When drafting new content, always present it for review before creating.
Things you explicitly CANNOT do:
[list from above]
```
### Token-Based Usage Tracking
AI usage is metered by tokens. Each org gets a monthly base allowance from their plan, with the option to buy extra credit packs when exhausted.
#### How It Works
```mermaid
flowchart LR
subgraph check [Before LLM Call]
CheckBalance["Check: monthly_allowance\n+ credit_balance\n- tokens_used > 0?"]
end
subgraph call [LLM Call]
StreamText["streamText() executes"]
Usage["AI SDK returns\npromptTokens + completionTokens"]
end
subgraph record [After LLM Call]
RecordUsage["Record usage in\nai_token_usage table"]
UpdateBalance["Deduct from monthly\nallowance first,\nthen credits"]
end
CheckBalance -->|"Yes"| StreamText
CheckBalance -->|"No"| Reject["Return 402:\nToken limit reached"]
StreamText --> Usage
Usage --> RecordUsage
RecordUsage --> UpdateBalance
```
#### Plan-Based Allowances
Tied to the existing `organization_plan` table ([schema.ts](packages/db/src/schema.ts) line 1324). Each plan gets a monthly token allowance:
- **BASIC**: 0 tokens (AI assistant not available on free plan — or a small trial allowance, TBD)
- **EARLY_ADOPTER**: X tokens/month (e.g. 500K tokens — roughly 50-100 conversations)
- **ENTERPRISE**: Y tokens/month (higher, e.g. 2M tokens — or unlimited)
Allowance resets on the 1st of each month (or billing cycle start).
#### Extra Credit Packs
When the monthly allowance is exhausted, the org can buy credit packs:
- Credits are one-time purchases, do NOT expire, do NOT reset monthly
- Deduction order: monthly allowance first, then credits
- Purchase flow: upgrade modal / settings page -> payment -> credits added to `ai_credit_balance`
#### Database Design
New table: `ai_token_usage` — tracks per-request usage for auditing and aggregation.
```sql
CREATE TABLE ai_token_usage (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id UUID NOT NULL REFERENCES organization(id),
user_id UUID NOT NULL,
course_id UUID NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
total_tokens INTEGER GENERATED ALWAYS AS (prompt_tokens + completion_tokens) STORED,
model TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_ai_token_usage_org_month ON ai_token_usage (org_id, created_at);
```
New table: `ai_credit_balance` — tracks purchased credits per org.
```sql
CREATE TABLE ai_credit_balance (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id UUID NOT NULL REFERENCES organization(id) UNIQUE,
balance INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```
Allowances live in a config constant (or the plan's `payload` JSONB field), not a separate table. The plan already has `payload: jsonb()` which can store `{ "aiTokenAllowance": 500000 }`.
#### Token Tracking Flow (in the agent route)
1. **Before LLM call**: query `ai_token_usage` for current month + `ai_credit_balance`. Calculate: `remaining = (allowance - used_this_month) + credit_balance`. If `remaining <= 0`, return 402 with `{ error: "Token limit reached", upgradeUrl: "..." }`.
2. **After LLM call**: the Vercel AI SDK's `streamText()` result exposes `usage` with `promptTokens` and `completionTokens`. Insert a row into `ai_token_usage`.
3. **Deduction logic**: monthly allowance is consumed first (it's implicit — just the sum of usage this month vs the allowance). Credits are only touched when `used_this_month > allowance`. The credit deduction is: `max(0, total_tokens - max(0, allowance - used_before_this_request))`.
#### API Endpoints for Token Management
- `GET /agent/usage` — returns `{ used, allowance, creditBalance, remaining }` for the current org. Used by dashboard to show usage meter.
- `POST /agent/credits` — purchase credits (integrates with payment provider). Protected by `orgAdminMiddleware`.
#### Dashboard UI
- **Usage meter**: in the AI assistant sidebar header or org settings, show a progress bar: "X / Y tokens used this month" with remaining count.
- **Exhausted state**: when tokens run out, the chat input is disabled with a message: "Monthly AI token limit reached. [Buy more credits] or wait for reset on [date]."
- **Credits section**: in org settings, show credit balance and "Buy more" button.
### Safeguards
Four layers of protection:
1. **Route-level middleware** — agent API route uses `authMiddleware` + `orgMemberMiddleware` + at minimum `courseMemberMiddleware`. Role detection happens inside the handler. Defined in [apps/api/src/middlewares/](apps/api/src/middlewares/).
2. **Tool-level permission checks** — the tool set itself is the primary guard. Students physically cannot call `update_lesson_content` because it's not in their tool set. Additionally, each tool's execute function re-verifies resource ownership to prevent prompt injection (LLM tricked into passing a different `courseId`).
3. **Token budget enforcement** — every LLM call checks the org's remaining token balance. If exhausted, returns 402 before any LLM call is made. Usage is recorded after each call for accurate tracking.
4. **Rate limiting** — per-user, per-org rate limits on agent API calls (requests/minute). Prevents abuse even within token budget. Self-hosted is uncapped (user's own API key, their cost).
### Self-Hosted vs Cloud
- **Cloud**: AI assistant enabled by default. ClassroomIO provides the LLM API key server-side. Teachers see the button, no setup needed. Usage may be metered per plan tier.
- **Self-hosted**: AI assistant **disabled by default**. To enable, the self-hosted admin sets `AI_API_KEY` and optionally `AI_PROVIDER` / `AI_MODEL` in their environment. When configured, the assistant becomes available. When not configured, the button is hidden (check via a server-side flag exposed to the client, e.g. a `GET /agent/status` endpoint or a field in the org config response).
This is simpler than storing API keys in the database and avoids security concerns around key storage.
### UI Specification
- **Trigger**: "AI Assistant" button in the course sidebar navigation ([course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)), below the existing nav items. In v1, only visible to teachers/admins (not students). Hidden when self-hosted and no AI key configured.
- **Panel**: Right sidebar using `@cio/ui` Sheet (`side="right"`, ~420px). Does NOT replace the left sidebar — both can be open simultaneously.
- **Chat interface**: Message list (user/assistant turns), text input with send button, streaming token display, quick-action chips.
- **Role-aware quick actions**: The chat panel accepts the detected `role` to show the right chips:
- Teacher (v1): "Draft a lesson", "Generate questions", "Improve this text"
- Student (v2): "Explain this lesson", "Quiz me on this topic", "Help me with this exercise"
- **Context awareness**: Client passes `courseId`, current `lessonId` or `exerciseId`. The role is NOT sent from the client — it's detected server-side to prevent spoofing.
- **Apply flow**: For large content changes (teacher only), the agent response includes a structured preview. The chat UI renders a diff with "Apply" / "Discard" buttons. Applying triggers the API write and refreshes the relevant store.
- **Existing `ai-button.svelte`**: The hidden [ai-button.svelte](apps/dashboard/src/lib/features/course/components/lesson/ai-button.svelte) component in the lesson editor can be removed or repurposed — the new sidebar chat replaces its functionality.
- **v2 student surface**: The same chat panel component can be rendered in the student course view (course-app). The `Chat` class and Sheet are identical — only the quick-action chips differ, and the server loads different tools/prompts based on role.
### Streaming
The Vercel AI SDK provides a structured SSE protocol via `toUIMessageStreamResponse()`. It carries:
- Text chunks (tokens stream one by one — ChatGPT-like typing)
- Tool call events (when the LLM decides to call a tool)
- Tool results (when the tool execution completes)
- Finish signals
On the frontend, the `Chat` class from `@ai-sdk/svelte` consumes this protocol automatically. No manual SSE parsing needed.
### How the Backend Code Works
The Hono route assembles everything:
1. **Provider factory** (`packages/ai-assistant`) creates a `LanguageModel` from env vars
2. **Tool schemas** (`packages/ai-assistant`) define Zod input schemas for each tool
3. **Tool execute functions** (inline in the Hono route) call existing services from `apps/api/src/services/`
4. `**streamText()`** (from `ai` core) runs the agent loop: sends system prompt + tools + messages to LLM, executes tool calls, feeds results back, repeats up to `stopWhen: stepCountIs(5)`, streams everything to the client
The route returns `result.toUIMessageStreamResponse()` directly as the Hono response.
### How the Frontend Code Works
The `Chat` class from `@ai-sdk/svelte` is instantiated once per chat panel. It:
1. Manages `messages` array as reactive `$state` (same pattern as `LessonApi`)
2. `sendMessage({ text })` sends a POST to the Hono endpoint, starts consuming the SSE stream
3. Updates `messages` reactively as tokens arrive — the UI re-renders automatically
4. Exposes `status` (`'idle'` | `'streaming'`) and `stop()` for abort
5. Each message has a `parts` array — `{ type: 'text', text }` for text, `{ type: 'tool-{name}', state: 'call' | 'result', result? }` for tool calls
The `Chat` class accepts:
- `api` — URL of the Hono endpoint (e.g., `${PUBLIC_API_URL}/agent/chat`)
- `headers` — we pass `{ 'cio-org-id': orgId }` via a reactive getter
- `body` — extra data merged into every request: `{ courseId, context: { lessonId, exerciseId } }`
- `credentials: 'include'` — sends auth cookies for Better Auth session
- `onFinish` — callback to refresh page data after the agent completes
### What the Chat UI Looks Like
**Empty state**: welcome message + quick-action chips ("Draft a lesson", "Generate questions", "Improve this text"). Clicking a chip fills the input and sends.
**During conversation**:
- User messages appear right-aligned with `bg-primary` styling
- Assistant messages appear left-aligned with `bg-muted` styling
- Text streams in token by token (automatic via `Chat` class)
- Tool calls render as inline status cards inside the assistant bubble:
- `state: 'call'` shows spinner + "Generating questions..."
- `state: 'result'` shows checkmark + "5 questions added"
- Stop button replaces send button while streaming
**After agent completes a mutation**:
- `onFinish` callback fires
- The relevant store refreshes (e.g., `lessonApi.get()` or exercise reload)
- Teacher sees updated content on the page without manual refresh
**Tool part rendering**: The AI SDK names tool parts as `tool-{toolName}`. In the Svelte template:
```svelte
{#each message.parts as part}
{#if part.type === 'text'}
<div class="prose">{@html renderMarkdown(part.text)}</div>
{:else if part.type === 'tool-update_lesson_content'}
<ToolStatusCard label="Updating lesson" state={part.state} />
{:else if part.type === 'tool-add_exercise_questions'}
<ToolStatusCard label="Generating questions" state={part.state}
successText={part.state === 'result' ? `${part.result.count} questions added` : undefined} />
{/if}
{/each}
```
### Example Agent Flows
These walk through what actually happens end-to-end for each key use case — which tools fire, what the teacher sees, and design decisions involved.
#### Flow 1: "Research photosynthesis and write a first draft lesson for Section 2"
```mermaid
sequenceDiagram
participant Teacher
participant Chat as Chat UI
participant API as Agent API
participant LLM
participant Svc as Services
Teacher->>Chat: "Research photosynthesis and write a first draft for Section 2"
Chat->>API: POST /agent/chat
API->>LLM: system prompt + tools + message
Note over LLM: Step 1 - Understand course context
LLM->>API: tool_call: get_course_structure(courseId)
API->>Svc: getCourseStructure()
Svc-->>API: sections, lessons, exercises tree
API->>LLM: tool result
Note over LLM: Step 2 - Read existing style
LLM->>API: tool_call: get_lesson_content(lessonId)
API->>Svc: getLessonById()
Svc-->>API: lesson HTML content
API->>LLM: tool result
Note over LLM: Step 3 - Present draft for review
LLM-->>Chat: Streams draft text inline in chat
LLM-->>Chat: "Here's a draft... shall I create it?"
Teacher->>Chat: "Looks good, create it"
Chat->>API: POST /agent/chat (follow-up)
API->>LLM: conversation continues
Note over LLM: Step 4 - Create after confirmation
LLM->>API: tool_call: create_lesson_draft(title, content, sectionId)
API->>Svc: createLessonService()
Svc-->>API: { lessonId, title }
API->>LLM: tool result
LLM-->>Chat: "Created 'Photosynthesis' in Section 2"
Note over Chat: onFinish -> content tree refreshes
Chat->>Teacher: New lesson appears in sidebar
```
**What "research" means**: The agent does NOT have internet access. "Research" means two things:
1. The LLM uses its training data knowledge about the topic (extensive for most academic subjects)
2. The agent reads existing course content via `get_course_structure` and `get_lesson_content` to understand the teacher's style, depth, and what's already been covered
**Confirmation before creation**: The system prompt instructs the LLM to present the draft in the chat first and ask for confirmation before calling `create_lesson_draft`. This is a prompt-engineering pattern, not a code constraint — the system prompt will say: "When drafting a new lesson, first present the full draft in your response and ask the teacher to confirm before creating it. Only call create_lesson_draft after the teacher approves." This gives a natural review gate via multi-turn conversation without requiring a custom "preview mode" in the API.
**Future consideration**: If real web research is needed, a `web_search` tool can be added to the tool registry. The foundation supports it cleanly — just another tool schema + execute function. Not in v1.
**What the teacher sees in the chat**:
1. User bubble: their request
2. Assistant bubble starts streaming:
- Tool card: "Getting course structure..." -> checkmark
- Tool card: "Reading existing lesson..." -> checkmark
- Text streams in: the full draft lesson content, rendered as markdown
- Text: "Would you like me to create this as a lesson in Section 2?"
3. Teacher types "yes" or "looks good, but change X"
4. Assistant bubble:
- Tool card: "Creating lesson draft..." -> checkmark
- Text: "Created 'Photosynthesis: Converting Light to Energy' in Section 2. You can find it in the content tree."
5. Content tree refreshes, new lesson appears
#### Flow 2: "Generate 5 MCQ questions from this lesson"
The teacher is viewing a lesson and opens the AI assistant.
1. Teacher sends: "Generate 5 multiple choice questions from this lesson"
2. The `Chat` class sends `{ courseId, messages, context: { lessonId: 'current-lesson-id' } }`
3. The system prompt includes: "The teacher is currently viewing lesson ID: {lessonId}"
4. LLM calls `get_lesson_content(lessonId)` to read the lesson text
5. LLM generates 5 questions based on the content
6. LLM calls `add_exercise_questions(exerciseId, questions)` — if there's a linked exercise, it adds there. If not, it tells the teacher there's no exercise linked and asks if it should create one.
7. Result streams back with tool status cards and a summary
**What the teacher sees**:
- Tool card: "Reading lesson content..." -> checkmark
- Tool card: "Adding 5 questions..." -> checkmark
- Text: "I've added 5 multiple-choice questions to the exercise. Here's a summary: 1. What is the primary function of... [etc]"
- Exercise data refreshes automatically
#### Flow 3: "Update the introduction paragraph of this lesson"
The teacher is editing a lesson and wants the AI to improve specific text.
1. Teacher sends: "Rewrite the introduction paragraph to be more engaging"
2. Context includes the current `lessonId`
3. LLM calls `get_lesson_content(lessonId)` to read the full lesson
4. LLM identifies the introduction paragraph, rewrites it
5. **System prompt instructs**: "When updating existing lesson content, show the proposed changes and ask for confirmation before applying." — this is the "preview for destructive changes" pattern
6. LLM presents the new introduction in the chat
7. Teacher says "apply it" or "make it shorter"
8. LLM calls `update_lesson_content(lessonId, fullUpdatedContent)`
9. Lesson store refreshes, teacher sees the updated text in the editor
**Important**: `update_lesson_content` replaces the full lesson note. The LLM must reconstruct the complete lesson HTML with only the introduction changed. The system prompt will instruct: "When updating lesson content, always preserve all existing content. Only modify the specific section the teacher asked about."
#### Flow 4 (v2): Student asks "I don't understand the Calvin cycle"
1. Student is viewing a lesson about photosynthesis
2. Student sends: "I don't understand the Calvin cycle, can you explain it more simply?"
3. Role detected as `'student'` — student tool set loaded (read-only)
4. LLM calls `get_lesson_content(lessonId)` to read what the lesson says about the Calvin cycle
5. LLM generates a simplified explanation based on the lesson content + its training knowledge
6. Response streams back — pure text, no tool mutations, no changes to any data
**Key difference from teacher flow**: No mutation tools are available. The agent can only read course content and generate text responses. The tool set IS the security boundary.
### LLM Provider Abstraction
Configurable via environment variables:
- `AI_PROVIDER` — `openai` | `anthropic` (default: `openai`)
- `AI_API_KEY` — the provider API key
- `AI_MODEL` — model name override (default: provider's recommended model)
The provider factory in `packages/ai-assistant` normalizes this into a single `LanguageModel` instance that `streamText()` consumes. Both OpenAI and Anthropic support function/tool calling natively through the AI SDK.
### Conversation Persistence
For v1, conversation history is **session-scoped** — managed entirely in-memory by the `Chat` class on the client. When the teacher closes the sidebar or navigates away, the conversation resets. No database table needed.
v2 consideration: persist conversations per course in the database for history/continuity.
## API Routes
New route domain: `/agent`
- `GET /agent/status` — returns `{ enabled, role, usage: { used, allowance, creditBalance, remaining } }`. Used by client to show/hide the button, configure chips, and display usage meter.
- `POST /agent/chat` — the single chat endpoint. Accepts `{ courseId, messages, context }`. Checks token balance, detects role, loads tools/prompt, returns SSE stream. Records token usage after completion.
- `GET /agent/usage` — returns detailed usage stats for the current org (current month usage, allowance, credit balance, history).
- `POST /agent/credits` — purchase additional credits. Protected by `orgAdminMiddleware`.
Registered in [apps/api/src/app.ts](apps/api/src/app.ts) as `.route('/agent', agentRouter)`.
## Implementation Phases
### Phase 1: Foundation (scaffold + role-aware chat shell + token tables)
- Create `packages/ai-assistant` with `AgentRole`, `AgentContext` types, provider factory, role-aware tool registry (v1: 7 core tools), and role-aware system prompt with no-hallucination boundary
- Add `ai_token_usage` and `ai_credit_balance` tables to DB schema, add token allowance to plan payload
- Add `GET /agent/status` and `POST /agent/chat` route skeleton in `apps/api` with role detection (students get 403 in v1) and token balance check
- Add "AI Assistant" button to course sidebar (gated on status endpoint + plan check)
- Build right sidebar Sheet with basic chat UI (hardcoded echo responses)
### Phase 2: Agent Core (LLM integration + v1 tools + usage tracking)
- Implement provider factory (OpenAI + Anthropic) using `createModel(config)`
- Wire v1 core tools (7 tools) to existing services via `streamText()` with `stopWhen: stepCountIs(5)`
- Record `promptTokens` + `completionTokens` after each call; enforce balance check before each call
- Connect chat UI to streaming API via `@ai-sdk/svelte` `Chat` class; render streamed tokens and tool status cards
- Add usage meter to AI assistant sidebar header
- Implement `onFinish` store refresh for lesson/exercise data
### Phase 3: Polish + Safeguards + Credits
- Add tool-level permission re-validation (verify resource belongs to course/org)
- Add rate limiting (per-user, per-org, requests/minute)
- Add quick-action chips and context-aware suggestions
- Self-host env var detection and `GET /agent/status` logic
- Add conversation context windowing (trim long histories)
- Implement `POST /agent/credits` for purchasing credit packs
- Add credit purchase UI in org settings + exhausted-state UI in chat
- Add `GET /agent/usage` for detailed usage dashboard
### Phase 4: More Tools
- Add Phase 2+ tools (sections, reorder, delete, translations, templates, tags, newsfeed)
- Update no-hallucination boundary to remove "cannot manage sections" etc.
### Phase 5: Student Assistant (v2)
- Implement student tool schemas and execute functions
- Write student system prompt template
- Remove the v1 student 403 gate
- Add student quick-action chips
- Surface the AI assistant button in the student course view (course-app)
- Student usage counts against the org's token budget (same pool)
## Files to Create / Modify
**New files:**
- `prd/ai-course-assistant/README.md` — this PRD (replace existing)
**Files referenced (not modified in PRD phase):**
- [packages/db/src/schema.ts](packages/db/src/schema.ts) — where `ai_token_usage` and `ai_credit_balance` tables will be added (near `organizationPlan` at line 1324)
- [packages/utils/src/plans/constants.ts](packages/utils/src/plans/constants.ts) — where AI token allowance feature constants will be added
- [apps/api/src/app.ts](apps/api/src/app.ts) — where agent route will be registered
- [apps/api/src/middlewares/](apps/api/src/middlewares/) — existing middleware to reuse
- [apps/api/src/services/](apps/api/src/services/) — existing services the agent will call
- [apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte) — where the AI button goes
- [apps/dashboard/src/lib/utils/store/org.ts](apps/dashboard/src/lib/utils/store/org.ts) — where plan-based derived stores live (e.g., `isFreePlan`, `currentOrgPlan`)
@@ -0,0 +1,199 @@
---
name: Course Enroll Route Migration
overview: "Replace `/invite/s/:token` with `/course/:slug/enroll`. One unified enrollment endpoint: free courses enroll directly (no invite); paid courses require invite_token. Remove public-link and invite creation for free enrollment."
todos: []
isProject: false
---
# Course Enroll Route Migration Plan
## Summary
Migrate from `/invite/s/:token` to a course-scoped enroll route. **One request for both flows:**
- **Free courses:** `/course/:slug/enroll` – Join calls `POST /course/:courseId/enroll` (no token). User is enrolled directly; no invite creation.
- **Paid/invited:** `/course/:slug/enroll?invite_token=xxx` – Join calls `POST /course/:courseId/enroll` with `inviteToken`. Without token, request fails.
## Architecture
```mermaid
flowchart TB
subgraph free [Free Course Flow]
A1[Landing: Enroll click] --> A2[goto /course/slug/enroll]
A2 --> A3[Page loads, validates free]
A3 --> A4[User auths if needed]
A4 --> A5[Join click]
A5 --> A6["POST /course/:id/enroll (no token)"]
A6 --> A7[Direct enroll: add to org + group]
A7 --> A8[Redirect to LMS]
end
subgraph paid [Paid/Invited Flow]
B1[Email link] --> B2[course/slug/enroll?invite_token=xxx]
B2 --> B3[Page loads, validates token]
B3 --> B4[User auths if needed]
B4 --> B5[Join click]
B5 --> B6["POST /course/:id/enroll with inviteToken"]
B6 --> B7[Validate token, consume invite, enroll]
B7 --> B8[Redirect to LMS]
end
```
---
## Part 1: New Enroll Route
### 1.1 Create route files
**Add:** [apps/dashboard/src/routes/course/[slug]/enroll/+page.server.ts](apps/dashboard/src/routes/course/[slug]/enroll/+page.server.ts)
**Add:** [apps/dashboard/src/routes/course/[slug]/enroll/+page.svelte](apps/dashboard/src/routes/course/[slug]/enroll/+page.svelte)
**Server load logic – one request per branch:**
- **With `invite_token`:** Single call to `GET /invite/student/:token`. Response must include course (slug, cost, title, description, allowNewStudent, status, isPublished), organization (siteName, name, theme), invite (status, etc.). No separate course or org fetch. Extend the invite API response to be self-contained (add course.slug, course.cost, org.theme to the query/response).
- **Without `invite_token` (free):** Single call to `GET /course/slug/:slug` (or a dedicated enroll-context endpoint). Response must include course and org (with theme). Extend the course-by-slug response to include org if it does not already, so no separate OrgApiServer.getOrgBySiteName call.
- **Validation rules:** Same as before – 404, requiresPaymentOrInvite, etc. Determine "free" via `isCourseFree(calculatedCost)`.
**Page component logic:**
- When `requiresPaymentOrInvite: true`: render message "You need to pay for this course or be invited to get access" with link back to `/course/:slug`
- When `invite` present or free (no invite): show course info + Join button
- On Join:
1. If not logged in → `goto(/signup?redirect=/course/:slug/enroll)` (preserve redirect, append `?invite_token=` if present)
2. If logged in → call `**POST /course/:courseId/enroll`** with body `{ inviteToken?: string }`:
- **Free:** no `inviteToken`, backend enrolls directly
- **Paid/invited:** pass `inviteToken` from URL; backend validates and consumes invite
3. Redirect to `result.data.redirectTo || '/lms'`
- Set theme and currentOrg from load data
### 1.2 Add route to PUBLIC_ROUTES
**File:** [apps/dashboard/src/lib/utils/constants/routes.ts](apps/dashboard/src/lib/utils/constants/routes.ts)
- Add `^/course/.*/enroll` to `PUBLIC_ROUTES` so unauthenticated users can load the enroll page (they will be prompted to auth when clicking Join)
---
## Part 2: Update Landing Page Enroll Flow
**File:** [apps/dashboard/src/lib/features/ui/course-landing-page/components/pricing-section.svelte](apps/dashboard/src/lib/features/ui/course-landing-page/components/pricing-section.svelte)
- For **free** course: remove `POST /invite/student/public-link` call; change to `goto(\`/course/${courseData.slug}/enroll)`
---
## Part 3: New Unified Enrollment API
**Add:** `POST /course/:courseId/enroll` (authenticated). Body: `{ inviteToken?: string }`
**Logic:** With `inviteToken` → reuse `acceptStudentInvite`; without token → only free courses, direct enroll (no invite). Remove public-link and accept routes.
**Part 3b – Build Enroll URL for emails:** [apps/api/src/services/course/invite.ts](apps/api/src/services/course/invite.ts)
- Add `buildEnrollLink(courseSlug: string, token: string, orgSiteName?: string): string`
- Construct: `https://${orgSiteName || 'app'}.classroomio.com/course/${courseSlug}/enroll?invite_token=${encodeURIComponent(token)}`
- Use same base-URL logic as elsewhere (dev vs prod; see [newsfeed](apps/api/src/services/newsfeed/newsfeed.ts) for org subdomain pattern)
- Replace `buildInviteLink` with `buildEnrollLink` in createSingleInvite/email flow; remove buildInviteLink
- Pass `courseSlug` and `orgSiteName` from course/org data in createStudentInvite and createEmailInviteAndSend
- createPublicStudentInvite removed; email flow uses buildEnrollLink for invite URLs in emails
---
## Part 4: Redirect Preservation (from earlier discussion)
**Files:** [apps/dashboard/src/routes/(auth)/login/+page.svelte](apps/dashboard/src/routes/(auth)/login/+page.svelte), [apps/dashboard/src/routes/(auth)/signup/+page.svelte](apps/dashboard/src/routes/(auth)/signup/+page.svelte)
- On successful auth, preserve `redirect` query param: `window.location.href = redirect ? \`/?redirect=${encodeURIComponent(redirect)} : '/'`
**File:** [apps/dashboard/src/lib/features/app/init.svelte.ts](apps/dashboard/src/lib/features/app/init.svelte.ts)
- In `routeUserToNextPage`, move the `redirect` check **before** the `isOrgSite && pathname === '/'` early return so redirect is honored on org sites
---
## Part 5: Delete invite/s Route and Remove Obsolete Code
All logic from the old invite page moves to the new enroll route. Delete the invite/s route entirely.
### 5.1 Delete invite/s route files
**Delete:**
- [apps/dashboard/src/routes/invite/s/[hash]/+page.svelte](apps/dashboard/src/routes/invite/s/[hash]/+page.svelte)
- [apps/dashboard/src/routes/invite/s/[hash]/+layout.server.ts](apps/dashboard/src/routes/invite/s/[hash]/+layout.server.ts)
- [apps/dashboard/src/routes/invite/s/](apps/dashboard/src/routes/invite/s/) directory (delete if empty after removing [hash])
If [invite/t](apps/dashboard/src/routes/invite/t/) (teacher invite) exists, keep it; only student invite s/ is removed.
### 5.2 Remove obsolete constants
**File:** [apps/dashboard/src/lib/utils/constants/routes.ts](apps/dashboard/src/lib/utils/constants/routes.ts)
- Remove `INVITE_STUDENT: '/invite/s'` from `ROUTE`
- Remove `^${ROUTE.INVITE_STUDENT}/.`* from `ROUTES_TO_HIDE_NAV`
- Add enroll route to `PUBLIC_ROUTES`: `^/course/.*/enroll` (or equivalent)
### 5.3 Remove obsolete backend function
**File:** [apps/api/src/services/course/invite.ts](apps/api/src/services/course/invite.ts)
- Remove `buildInviteLink(token)` (replaced by `buildEnrollLink`)
- Ensure no remaining callers of `buildInviteLink`; update all to use `buildEnrollLink(courseSlug, token, orgSiteName)`
### 5.4 API routes – add, remove, rename, extend
- **Add:** `POST /course/:courseId/enroll` (unified endpoint; see Part 3)
- **Remove:** `POST /invite/student/public-link`, `POST /invite/student/:token/accept`
- **Rename:** `GET /invite/student/:token/preview` → `GET /invite/student/:token`
- **Extend** `GET /invite/student/:token` response: include `course.slug`, `course.cost`, `org.theme` so enroll page needs no extra fetches
- **Extend** `GET /course/slug/:slug` response: include `org` (id, name, siteName, theme) so free-enroll page needs no separate org fetch
---
## Part 6: People Page – Email Invite Links
When teachers send email invites, the link in the email must use the new format. The backend change in Part 3 covers this: `buildEnrollLink(courseSlug, token, orgSiteName)` will be used when generating links for `studentCourseInvite` email.
---
## Part 7: Email-Only Invites Plan (from planning doc)
Per [email-only-invites-plan.md](planning/secure-student-invites/email-only-invites-plan.md):
- Add Zod refine to `ZCreateCourseInvite`: require `recipientEmails` or `recipientCsv` (broad scope)
- Remove quick-link tab/section from People invite modal; make email the default
- Update `invitation-modal.svelte` to remove QuickLinkSection and set `activeStudentTab = 'email'`
---
## File Change Summary
| File | Action |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `routes/course/[slug]/enroll/+page.server.ts` | Create – load course, invite preview, validation |
| `routes/course/[slug]/enroll/+page.svelte` | Create – enroll UI, Join flow |
| `lib/utils/constants/routes.ts` | Add enroll to PUBLIC_ROUTES; remove INVITE_STUDENT |
| `features/ui/course-landing-page/.../pricing-section.svelte` | Free: goto `/course/:slug/enroll` |
| `api/services/course/invite.ts` | Add enrollInCourse, buildEnrollLink; extend previewStudentInvite with slug, cost, org.theme; remove public-link, accept, buildInviteLink |
| `routes/(auth)/login/+page.svelte` | Preserve redirect param |
| `routes/(auth)/signup/+page.svelte` | Preserve redirect param |
| `features/app/init.svelte.ts` | Honor redirect before org-site early return |
| `routes/invite/s/[hash]/+page.svelte` | Delete |
| `routes/invite/s/[hash]/+layout.server.ts` | Delete |
| `packages/utils/validation/course/invite.ts` | Zod refine for recipients |
| `features/course/people/invitation-modal.svelte` | Remove quick-link, default to email |
| `features/course/people/quick-link-section.svelte` | Delete |
| `api/routes/invite/invite.ts` | Rename GET /student/:token/preview to GET /student/:token; remove public-link, accept |
| `api/services/course/course.ts` or course route | Extend getCourse (slug) response to include org with theme for enroll page |
---
## Dependency Notes
- Course slug available from `getCourseById`/`getCourseWithOrgData`; ensure slug is selected in queries.
- `acceptStudentInvite` logic is reused when enroll is called with `inviteToken`.
@@ -0,0 +1,511 @@
---
name: ""
overview: ""
todos: []
isProject: false
---
# Course Page UI Extraction and Storybook Integration (Detailed Plan)
## Overview
Extract the course page UI (sidebar + content shell) into a reusable `CoursePage` component in `packages/ui`, add a Storybook story under `Pages/CoursePage` that accepts JSON to form the whole page, and wire the dashboard layout to use it. **Content rendering in Storybook is view-mode only** (lesson and exercise). Edit mode stays in the dashboard and is out of scope.
---
## Part 0: Prerequisites and Reference Files to Read
Before starting, a junior dev should read these files to understand the patterns:
1. **Exercise Question pattern** (how JSON fixtures drive UI):
- `[packages/storybook/src/molecules/exercise-question/exercise-question.stories.svelte](packages/storybook/src/molecules/exercise-question/exercise-question.stories.svelte)`
- `[packages/storybook/src/molecules/exercise-question/question-fixtures.ts](packages/storybook/src/molecules/exercise-question/question-fixtures.ts)`
- `[packages/ui/src/custom/exercise-question/question-renderer.svelte](packages/ui/src/custom/exercise-question/question-renderer.svelte)`
2. **Current course layout** (what we are extracting):
- `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)`
- `[apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)`
3. **View vs Edit mode** (view mode only in Storybook):
- Exercise view: `[apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte)` uses `ExerciseQuestion.QuestionList` with `mode: 'view'`
- Lesson view: `[apps/dashboard/src/lib/features/course/components/lesson/utils.ts](apps/dashboard/src/lib/features/course/components/lesson/utils.ts)` – Note, Slide, Video, Document in view mode
---
## Part 1: Define the JSON Config Schema
### Step 1.1: Create the types file
**Create file**: `packages/ui/src/custom/course-page/course-page-types.ts`
**Purpose**: Define the shape of the JSON that drives the CoursePage. No imports from dashboard or API.
**Contents** (copy and adapt):
```typescript
/**
* JSON config for CoursePage. Used by Storybook (fixtures) and Dashboard (built from course/org state).
*/
export interface CoursePageConfig {
course: { id: string; title: string };
sidebar: CourseSidebarConfig;
/** Used by Storybook for view-mode content. Dashboard uses content snippet instead. */
content?: CourseContentViewConfig;
}
export interface CourseSidebarConfig {
backUrl: string;
backLabel: string;
navItems: CourseNavItem[];
}
export interface CourseNavItem {
id: string;
title: string;
url: string;
isActive: boolean;
isLesson?: boolean;
icon?: CourseNavIconKey;
contentTree?: CourseContentTreeSection[];
contentCount?: { lessons: number; exercises: number };
}
export type CourseNavIconKey =
| 'newsfeed'
| 'content'
| 'analytics'
| 'attendance'
| 'submissions'
| 'marks'
| 'certificates'
| 'landingpage'
| 'people'
| 'settings'
| 'section';
export interface CourseContentTreeSection {
id: string;
title: string;
items: CourseContentTreeItem[];
}
export interface CourseContentTreeItem {
id: string;
title: string;
type: 'LESSON' | 'EXERCISE';
url?: string;
isComplete?: boolean;
isUnlocked?: boolean;
}
/**
* View-mode content config for Storybook. Dashboard does NOT use this – it renders route children.
*/
export type CourseContentViewConfig =
| { type: 'lesson'; data: LessonViewData }
| { type: 'exercise'; data: ExerciseViewData }
| { type: 'placeholder'; data: { label: string } };
export interface LessonViewData {
title: string;
note?: string; // HTML string
slideUrl?: string;
videos?: { link: string; type: string; metadata?: Record<string, unknown> }[];
documents?: { title: string; url: string }[];
}
export interface ExerciseViewData {
title: string;
questions: Record<string, unknown>[];
answersByKey?: Record<string, unknown>;
}
```
**Check**: File compiles with `pnpm exec tsc --noEmit` in `packages/ui`.
---
## Part 2: Create the CoursePage UI Components
### Step 2.1: Icon lookup map
**Create file**: `packages/ui/src/custom/course-page/icon-map.ts`
**Purpose**: Map string keys from config to the actual icon components.
**Contents**:
```typescript
import type { Component } from 'svelte';
import TableOfContentsIcon from '@lucide/svelte/icons/table-of-contents';
import {
NewsFeedIcon,
ContentIcon,
AnalyticsIcon,
AttendanceIcon,
SubmissionIcon,
MarksIcon,
CertificateIcon,
LandingPageIcon,
PeopleIcon,
SettingsIcon
} from '@cio/ui/custom/moving-icons';
import type { CourseNavIconKey } from './course-page-types';
export const COURSE_NAV_ICON_MAP: Record<CourseNavIconKey, Component> = {
section: TableOfContentsIcon,
newsfeed: NewsFeedIcon,
content: ContentIcon,
analytics: AnalyticsIcon,
attendance: AttendanceIcon,
submissions: SubmissionIcon,
marks: MarksIcon,
certificates: CertificateIcon,
landingpage: LandingPageIcon,
people: PeopleIcon,
settings: SettingsIcon
};
export function getCourseNavIcon(key: CourseNavIconKey | undefined): Component | null {
if (!key) return null;
return COURSE_NAV_ICON_MAP[key] ?? null;
}
```
**Check**: Imports resolve. Moving-icons live at `packages/ui/src/custom/moving-icons`.
---
### Step 2.2: Course page sidebar
**Create file**: `packages/ui/src/custom/course-page/course-page-sidebar.svelte`
**Purpose**: Renders the sidebar from `CourseSidebarConfig`. No dashboard/API deps.
**Logic**:
- Use `@cio/ui/base/sidebar` primitives: `Sidebar.Root`, `Sidebar.Header`, `Sidebar.Content`, `Sidebar.Group`, `Sidebar.Menu`, `Sidebar.MenuItem`, `Sidebar.MenuButton`, `Sidebar.MenuSub`, `Sidebar.MenuSubItem`, `Sidebar.MenuSubButton`, `Sidebar.Rail`.
- For each `navItem`: if `isLesson` and `contentTree` exists and item `isActive`, render the collapsible tree; otherwise render a simple link.
- Use `getCourseNavIcon(navItem.icon)` for icons.
- Back button: link to `config.sidebar.backUrl` with label `config.sidebar.backLabel`.
- Sidebar header: render a simple "Course" placeholder (or accept a `sidebarHeader` snippet later).
- Use `resolve` from `$app/paths` for URLs – but CoursePage is in packages/ui which may not have SvelteKit. **Alternative**: pass `basePath` or use plain `href={item.url}` since URLs come from config.
**Note**: `packages/ui` typically does NOT have `$app/paths` (SvelteKit). Use `item.url` directly as `href={item.url}` since config supplies full URLs.
**Content tree for Lessons**: Use `Collapsible.Root` + `Collapsible.Trigger` + `Collapsible.Content` from `@cio/ui/base/collapsible`. Each section maps to a collapsible; items inside link to `item.url`. Reuse `LessonIcon` and `ExerciseIcon` from `@cio/ui/custom/moving-icons` for item types.
**Structure** (pseudocode):
```
Sidebar.Root collapsible="icon"
Sidebar.Header
slot or "Course"
Sidebar.Content
Sidebar.Group
Button/link back: backLabel -> backUrl
Sidebar.Menu
for each navItem
if isLesson && isActive && contentTree
render link + CourseContentTree (collapsible sections)
else
render link only
Sidebar.Rail
```
**CourseContentTree for config**: Create a small component that renders sections/items from `contentTree` (from config, not courseApi). Each item links to `item.url` or builds path from `courseId` + `item.id` + `item.type`. For Storybook we can use `item.url` from the fixture.
---
### Step 2.3: Course page header
**Create file**: `packages/ui/src/custom/course-page/course-page-header.svelte`
**Purpose**: Simple header: Sidebar.Trigger + course title. No Search/notifications (dashboard keeps those).
**Props**: `title: string`
**Contents**:
```svelte
<script lang="ts">
import * as Sidebar from '@cio/ui/base/sidebar';
import { Separator } from '@cio/ui/base/separator';
interface Props { title?: string; }
let { title = '' }: Props = $props();
</script>
<header class="...">
<Sidebar.Trigger />
<Separator orientation="vertical" />
<p class="...">{title}</p>
</header>
```
Copy classes from `[CourseHeader](apps/dashboard/src/lib/features/course/components/course-header.svelte)`.
---
### Step 2.4: View-mode content renderer (Lesson + Exercise)
**Create file**: `packages/ui/src/custom/course-page/course-content-view.svelte`
**Purpose**: Renders view-mode content from `CourseContentViewConfig`. Used only in Storybook.
**Props**: `config: CourseContentViewConfig`
**Logic**:
- If `config.type === 'lesson'`: render `LessonViewContent` with `config.data`
- If `config.type === 'exercise'`: render `ExerciseQuestion.QuestionList` (or `QuestionRenderer` per question) with `mode: 'view'`, `questions`, `answersByKey`, `disabled: true`
- If `config.type === 'placeholder'`: render a simple card with `config.data.label`
**Create file**: `packages/ui/src/custom/course-page/lesson-view-content.svelte`
**Purpose**: Read-only lesson view. Accepts `LessonViewData` as props.
**Rendering** (copy structure from dashboard view mode, but data-driven):
- **Note**: Use `sanitizeHtml` from `@cio/ui/tools/sanitize` + `<div>{@html sanitized}</div>`. If `!data.note`, render nothing.
- **Slide**: If `data.slideUrl`, render `<iframe src={slideUrl} title="Slides" width="100%" height="569" class="..." allowfullscreen />`. Add `?embed` for Canva URLs (see `slide.svelte`).
- **Videos**: For each `data.videos`, render `MediaPlayer` with `source: { type: video.type, url: video.link, metadata: video.metadata }`, `options: { maxHeight: '569px', width: '100%', controls: true }`.
- **Documents**: Simple list: for each `data.documents`, render `<a href={doc.url}>{doc.title}</a>`. No inline PDF viewer (dashboard keeps that).
Keep it minimal – we are matching view-mode output, not edit UI.
**Exercise view**: Use `ExerciseQuestion.QuestionList` with:
- `contract: { mode: 'view', questions: data.questions, answersByKey: data.answersByKey ?? buildFromAnswers(data), labels, disabled: true }`
- `questions` must be `ExerciseQuestionModel[]` (same shape as `[question-fixtures](packages/storybook/src/molecules/exercise-question/question-fixtures.ts)` – id, key, title, questionType, options, settings).
- `answersByKey`: map from `getExerciseQuestionContractKey(question, index)` to answer value. Either pass in fixture or build from `{ questionKey: answer }` map.
- `labels`: Use empty object `{}` – `getExerciseQuestionLabel` in `@cio/question-types` has fallbacks. Alternatively add `labels?: ExerciseQuestionLabels` to `ExerciseViewData` so fixtures can override.
---
### Step 2.5: Main CoursePage component
**Create file**: `packages/ui/src/custom/course-page/course-page.svelte`
**Purpose**: Root layout. `Sidebar.Provider` → `CoursePageSidebar` + `Sidebar.Inset` (header + content).
**Props**:
- `config: CoursePageConfig` (required)
- `content?: Snippet` (optional) – when provided, render this instead of `CourseContentView`. Dashboard passes `{@render children()}`.
- `sidebarHeader?: Snippet` (optional) – override header inside sidebar
- `sidebarFooter?: Snippet` (optional)
**Structure**:
```svelte
<Sidebar.Provider>
<CoursePageSidebar config={config.sidebar} {sidebarHeader} {sidebarFooter} />
<Sidebar.Inset>
<CoursePageHeader title={config.course.title} />
<Page.Root class="...">
{#if content}
{@render content()}
{:else if config.content}
<CourseContentView config={config.content} />
{:else}
<Empty variant="page" ... />
{/if}
</Page.Root>
</Sidebar.Inset>
</Sidebar.Provider>
```
---
### Step 2.6: Index and exports
**Create file**: `packages/ui/src/custom/course-page/index.ts`
```typescript
export { default as CoursePage } from './course-page.svelte';
export { default as CoursePageSidebar } from './course-page-sidebar.svelte';
export { default as CoursePageHeader } from './course-page-header.svelte';
export { default as CourseContentView } from './course-content-view.svelte';
export { default as LessonViewContent } from './lesson-view-content.svelte';
export * from './course-page-types';
export * from './icon-map';
```
**Update**: `packages/ui/src/index.ts` – add:
```typescript
export * as CoursePage from './custom/course-page';
```
---
## Part 3: Storybook Fixtures and Stories
### Step 3.1: Create course page fixtures
**Create file**: `packages/storybook/src/pages/course-page/course-page-fixtures.ts`
**Purpose**: JSON configs that form the whole course page. Include sidebar + view-mode content.
**Fixtures**:
1. `LESSON_VIEW_FIXTURE`: `content.type === 'lesson'` with sample note HTML, 1 video, 1 document.
2. `EXERCISE_VIEW_FIXTURE`: `content.type === 'exercise'` with 2–3 questions from `question-fixtures` (reuse RADIO_FIXTURE, CHECKBOX_FIXTURE questions) and matching answers.
3. `FULL_INSTRUCTOR_FIXTURE`: All nav items, Lessons active with content tree, `content.type === 'placeholder'` with label "Lessons list" (actual list rendering deferred).
4. `STUDENT_MINIMAL_FIXTURE`: News Feed, Lessons (with tree), Certificates. Content = placeholder.
**Example** (LESSON_VIEW_FIXTURE):
```typescript
import type { CoursePageConfig } from '@cio/ui/custom/course-page';
export const LESSON_VIEW_FIXTURE: CoursePageConfig = {
course: { id: 'course-1', title: 'Introduction to Svelte' },
sidebar: {
backUrl: '/org/acme/courses',
backLabel: 'Courses',
navItems: [
{ id: 'newsfeed', title: 'News Feed', url: '/courses/course-1', isActive: false, icon: 'newsfeed' },
{ id: 'lessons', title: 'Content', url: '/courses/course-1/lessons', isActive: true, isLesson: true, icon: 'content', contentTree: [...], contentCount: { lessons: 3, exercises: 2 } }
]
},
content: {
type: 'lesson',
data: {
title: 'Getting Started',
note: '<p>Welcome to the course...</p>',
videos: [{ link: 'https://...', type: 'youtube', metadata: {} }],
documents: [{ title: 'PDF', url: '#' }]
}
}
};
```
---
### Step 3.2: Create Storybook stories
**Create file**: `packages/storybook/src/pages/course-page/course-page.stories.svelte`
**Structure**:
- Title: `Pages/CoursePage`
- Parameters: `layout: 'fullscreen'`
- Stories:
1. **LessonView** – uses `LESSON_VIEW_FIXTURE`, no content snippet → `CourseContentView` renders lesson view.
2. **ExerciseView** – uses `EXERCISE_VIEW_FIXTURE`, no content snippet → `CourseContentView` renders exercise view (QuestionList with mode 'view').
3. **InstructorFull** – uses `FULL_INSTRUCTOR_FIXTURE`, content placeholder.
4. **StudentMinimal** – uses `STUDENT_MINIMAL_FIXTURE`.
**Pattern** (same as exercise-question):
```svelte
<script module lang="ts">
import { defineMeta } from '@storybook/addon-svelte-csf';
import { CoursePage } from '@cio/ui';
import { LESSON_VIEW_FIXTURE } from './course-page-fixtures';
const { Story } = defineMeta({
title: 'Pages/CoursePage',
component: CoursePage.CoursePage,
parameters: { layout: 'fullscreen' },
tags: ['autodocs']
});
</script>
<Story name="LessonView">
{#snippet template()}
<CoursePage.CoursePage config={LESSON_VIEW_FIXTURE} />
{/snippet}
</Story>
```
**Important**: Do NOT pass a content snippet for Lesson/Exercise stories – the config drives `CourseContentView` in view mode only. Edit mode is not in scope.
---
## Part 4: Dashboard Integration
### Step 4.1: Config adapter
**Create file**: `apps/dashboard/src/lib/features/course/utils/course-page-config.ts`
**Purpose**: Build `CoursePageConfig` from real course/org state.
**Function**: `buildCoursePageConfig(params: { course, path, courseId, isStudent, ... }): CoursePageConfig`
**Logic**:
- Copy the nav item logic from `course-sidebar-navigation.svelte` (which items to show, `isActive`, urls).
- Use `getNavItemRoute`, `getLessonsRoute` from `$features/course/utils/functions`.
- Use `getCourseContent(course)` for content tree and counts.
- `content` in config: leave undefined (dashboard uses content snippet, not config.content).
- Use `$t(...)` for labels.
---
### Step 4.2: Update layout
**Update file**: `apps/dashboard/src/routes/courses/[id]/+layout.svelte`
**Changes**:
- When `isCourseReady`: call `buildCoursePageConfig(...)` to get config.
- Import `CoursePage` from `@cio/ui`.
- Replace the current layout structure with:
```svelte
<CoursePage.CoursePage config={config} content={children}>
{@render children?.()}
</CoursePage.CoursePage>
```
(Or pass `content` as a snippet that renders `children`.)
- Keep: `Dialog.Root` (not permitted), `ContentCreateModal`, `Confetti` for exercise page.
- Pass `sidebarHeader` = OrgLogo, `sidebarFooter` = UpgradePoweredBy when applicable.
**Alternative (incremental)**: Keep `CourseSidebar` and `CourseHeader` in the dashboard initially. Only replace the shell (Provider + Inset + Page.Root) with `CoursePage` and pass the existing sidebar as a slot. Then migrate sidebar to use config in a follow-up.
---
## Part 5: Out of Scope (Document for Later)
- **Edit mode**: Lesson edit (Note, Slide, Video, Document tabs) and Exercise edit (EditMode, add question, etc.) remain in dashboard only. Do not add edit UI to `CoursePage` or Storybook.
- **ContentCreateModal**: Stays in dashboard. Optional: add a placeholder in CoursePage for "add content" if config says so.
- **Search / Notifications**: Stay in dashboard header.
- **Actual Lessons list page** (list of sections/items): Can be a placeholder in Storybook for now. Full rendering can be broken down later.
---
## Part 6: Verification Checklist
- `pnpm --filter @cio/ui build` passes
- `pnpm --filter @cio/storybook dev` runs, story `Pages/CoursePage` shows all 4 stories
- LessonView story shows sanitized note, video, document in view mode
- ExerciseView story shows questions in view mode (read-only, with sample answers)
- Dashboard `courses/[id]` layout uses `CoursePage` and renders correctly
- No edit-mode UI (pencil, add question, etc.) in Storybook
---
## File Summary (Execution Order)
| Order | Action | Path |
| ----- | ------ | --------------------------------------------------------------------- |
| 1 | Create | `packages/ui/src/custom/course-page/course-page-types.ts` |
| 2 | Create | `packages/ui/src/custom/course-page/icon-map.ts` |
| 3 | Create | `packages/ui/src/custom/course-page/lesson-view-content.svelte` |
| 4 | Create | `packages/ui/src/custom/course-page/course-content-view.svelte` |
| 5 | Create | `packages/ui/src/custom/course-page/course-page-sidebar.svelte` |
| 6 | Create | `packages/ui/src/custom/course-page/course-page-header.svelte` |
| 7 | Create | `packages/ui/src/custom/course-page/course-page.svelte` |
| 8 | Create | `packages/ui/src/custom/course-page/index.ts` |
| 9 | Update | `packages/ui/src/index.ts` |
| 10 | Create | `packages/storybook/src/pages/course-page/course-page-fixtures.ts` |
| 11 | Create | `packages/storybook/src/pages/course-page/course-page.stories.svelte` |
| 12 | Create | `apps/dashboard/src/lib/features/course/utils/course-page-config.ts` |
| 13 | Update | `apps/dashboard/src/routes/courses/[id]/+layout.svelte` |
@@ -0,0 +1,180 @@
---
name: Course Page UI Storybook
overview: Extract the course page UI (sidebar + content shell) into a reusable `CoursePage` component in `packages/ui`, add a Storybook story under `Pages/CoursePage` that accepts JSON to form the whole page, and wire the dashboard layout to use it by passing data.
todos: []
isProject: false
---
# Course Page UI Extraction and Storybook Integration
## Current State
- **Layout**: `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)` uses `Sidebar.Provider` → `CourseSidebar` + `Sidebar.Inset` (CourseHeader + children in `Page.Root`)
- **Sidebar**: `[course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)` has nav items (News Feed, Lessons + content tree, Analytics, Attendance, Submissions, Marks, Certificates, Landing Page, People, Settings) with conditional visibility via `courseApi`, `$currentOrg`, `$globalStore`, etc.
- **Pattern reference**: Exercise questions use `packages/ui` components + `packages/storybook` fixtures (JSON) and `QuestionTypeModes` for different modes; stories under `Molecules/ExerciseQuestion`
## Architecture
```mermaid
flowchart TB
subgraph packages_ui [packages/ui]
CoursePage[CoursePage Component]
CoursePageSidebar[CoursePageSidebar]
CoursePageTypes[course-page-types.ts]
end
subgraph packages_storybook [packages/storybook]
CoursePageStories[Pages/CoursePage Stories]
CoursePageFixtures[course-page-fixtures.ts]
end
subgraph dashboard [apps/dashboard]
Layout[courses/[id]/+layout.svelte]
ConfigAdapter[Config Adapter - build config from course/org state]
end
CoursePageFixtures -->|JSON config| CoursePageStories
CoursePageStories -->|renders| CoursePage
ConfigAdapter -->|JSON config| Layout
Layout -->|passes config + children| CoursePage
```
## 1. Define JSON Config Schema
Create `[packages/ui/src/custom/course-page/course-page-types.ts](packages/ui/src/custom/course-page/course-page-types.ts)` with a config-driven shape:
```ts
// Core types - no dashboard/API imports
export interface CoursePageConfig {
course: { id: string; title: string };
sidebar: CourseSidebarConfig;
/** Optional - used by Storybook for mock content; dashboard uses children instead */
content?: { type: string; data?: unknown };
}
export interface CourseSidebarConfig {
backUrl: string;
backLabel: string;
navItems: CourseNavItem[];
}
export interface CourseNavItem {
id: string;
title: string;
url: string;
isActive: boolean;
isLesson?: boolean;
icon?: 'newsfeed' | 'content' | 'analytics' | 'attendance' | 'submissions' | 'marks' | 'certificates' | 'landingpage' | 'people' | 'settings' | 'section';
contentTree?: CourseContentTreeSection[];
contentCount?: { lessons: number; exercises: number };
}
export interface CourseContentTreeSection {
id: string;
title: string;
items: { id: string; title: string; type: 'LESSON' | 'EXERCISE'; url?: string; isComplete?: boolean; isUnlocked?: boolean }[];
}
```
Icon mapping: string keys → existing `@cio/ui/custom/moving-icons` (NewsFeedIcon, ContentIcon, etc.)
## 2. Create CoursePage Component in packages/ui
**Location**: `packages/ui/src/custom/course-page/`
**Components**:
- `course-page.svelte` – Root: `Sidebar.Provider` + `CoursePageSidebar` + `Sidebar.Inset` (header + content slot)
- `course-page-sidebar.svelte` – Renders sidebar from `CourseSidebarConfig` (no `courseApi`, org stores, or translations – uses config only)
- `course-page-header.svelte` – Simple header: Sidebar.Trigger + course title (Search/notifications stay in dashboard for now)
**Props**:
- `config: CoursePageConfig` (required)
- `content` snippet (optional) – dashboard passes `{@render children()}`, Storybook passes a mock renderer
**Sidebar behavior**:
- Uses `@cio/ui/base/sidebar` primitives
- Renders nav items from `config.sidebar.navItems`
- For `isLesson` items, renders expandable content tree from `contentTree`
- No OrgLogo/UpgradePoweredBy in the UI package – use placeholder (e.g. "Org Logo") or accept optional `sidebarHeader` snippet for customization
## 3. Placeholder for Dashboard-Specific Pieces
The current sidebar uses:
- `OrgLogo` (from `$features/ui/sidebar`)
- `UpgradePoweredBy` (org plan)
- `ContentCreateModal`, `ContentCountBadges`, `IconButton` for add content
**Approach**: CoursePage accepts optional snippets:
- `sidebarHeader` – default: simple "Course" text; dashboard overrides with OrgLogo
- `sidebarFooter` – default: empty; dashboard overrides with UpgradePoweredBy when free plan
- For add-content button and ContentCountBadges on the Lessons item: include in config (`showAddButton`, `contentCount`) and render when present; dashboard passes these, Storybook omits or mocks
## 4. Storybook Integration
**New folder**: `packages/storybook/src/pages/course-page/`
**Files**:
- `course-page-fixtures.ts` – JSON fixtures defining full course page configs:
- `FULL_INSTRUCTOR_FIXTURE` – all nav items, Lessons expanded with 2 sections and sample lessons/exercises
- `STUDENT_MINIMAL_FIXTURE` – News Feed, Lessons, Certificates only
- `CONTENT_FOCUS_FIXTURE` – Lessons active with rich content tree
- `course-page.stories.svelte` – Stories under `Pages/CoursePage`:
- **Default** – uses FULL_INSTRUCTOR_FIXTURE, content area shows placeholder based on `config.content.type`
- **Student view** – uses STUDENT_MINIMAL_FIXTURE
- **Lessons expanded** – uses CONTENT_FOCUS_FIXTURE
**Content placeholder**: For Storybook, when `config.content` is present, render a simple card: "Content: {type}" and optionally stringify `data` for inspection. Actual content rendering is out of scope.
## 5. Dashboard Integration
**Adapter**: Create `apps/dashboard/src/lib/features/course/utils/course-page-config.ts`:
- `buildCoursePageConfig(course, path, { isStudent, ... })` – maps real course/org state to `CoursePageConfig`
- Reuses `getCourseContent`, `getNavItemRoute`, `getLessonsRoute`, `NAV_IDS`, translation keys
**Layout update**: `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)`:
- When `isCourseReady`: compute config via `buildCoursePageConfig`
- Render `CoursePage` from `@cio/ui` with `config` and `content` snippet = `{@render children()}`
- Keep existing logic: `Dialog.Root` (not permitted), `ContentCreateModal`, `Confetti`, loading state
- Dashboard-specific pieces (OrgLogo, UpgradePoweredBy, add-content button) passed as snippets where the adapter indicates they should show
**Alternative (simpler first pass)**: Keep `CourseSidebar` and `CourseHeader` in the dashboard; extract only a "shell" that accepts config. The shell would be the `Sidebar.Provider` + `Sidebar.Inset` + `Page.Root` structure, with sidebar and header as slots. That allows incremental migration.
## 6. Exports and Wiring
- Add `packages/ui/src/custom/course-page/index.ts` and export from `packages/ui/src/index.ts`
- Ensure `packages/storybook` depends on `@cio/ui` (already does)
- Storybook stories path: `../src/pages/course-page/*.stories.svelte` (covered by existing `../src/**/*.stories.@(js|ts|svelte)`)
## 7. Out of Scope (Deferred)
- Actual content renderers (News Feed, Lessons list, Analytics, etc.) driven by JSON – user said "can be broken down later"
- `ContentCreateModal` integration in the CoursePage component
- Search and notifications in the header – remain dashboard-specific for now
## File Summary
| Action | Path |
| ------ | --------------------------------------------------------------------- |
| Create | `packages/ui/src/custom/course-page/course-page-types.ts` |
| Create | `packages/ui/src/custom/course-page/course-page-sidebar.svelte` |
| Create | `packages/ui/src/custom/course-page/course-page-header.svelte` |
| Create | `packages/ui/src/custom/course-page/course-page.svelte` |
| Create | `packages/ui/src/custom/course-page/index.ts` |
| Update | `packages/ui/src/index.ts` (export CoursePage) |
| Create | `packages/storybook/src/pages/course-page/course-page-fixtures.ts` |
| Create | `packages/storybook/src/pages/course-page/course-page.stories.svelte` |
| Create | `apps/dashboard/src/lib/features/course/utils/course-page-config.ts` |
| Update | `apps/dashboard/src/routes/courses/[id]/+layout.svelte` |
@@ -0,0 +1,156 @@
---
name: Global presigned URL strategy
overview: Add Redis caching for presigned download URLs on the API, and introduce a PresignApi class on the frontend so all presign requests go through one API class instead of calling classroomio.course.presign directly.
todos: []
isProject: false
---
# Global Presigned URL Strategy – Redis Cache
## Current state
Every place that needs a presigned download URL calls S3 `getSignedUrl` with no caching:
| Caller | When | Goes through |
| ----------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [lesson-media.ts](apps/api/src/utils/lesson-media.ts) | Enrich single lesson (documents/videos) | `generateDocumentDownloadPresignedUrls` / `generateVideoDownloadPresignedUrls` |
| [presign.ts](apps/api/src/routes/course/presign.ts) | Client calls `POST /presign/document/download` or `/video/download` | Same S3 utils |
| Client `enrichFileUploadAnswersWithUrls` | Open exercise submission | Client → `POST presign/document/download` |
**Problem**: Same fileKey generates a new presigned URL every time—whether loading a lesson again, opening the grading modal again, or re-requesting media. Server-side enrichment for lessons does not cache; each lesson load hits S3 again.
---
## Proposed approach: Redis cache in API
Cache presigned URLs in Redis at the S3 utils layer so all callers benefit without changes.
```mermaid
flowchart TB
subgraph callers [Callers]
LessonMedia[lesson-media.ts]
PresignRoute[presign routes]
Future[future submission enrichment]
end
subgraph s3Utils [apps/api/src/utils/s3.ts]
GenUrls[generateDownloadPresignedUrls]
end
subgraph cache [Redis Cache]
Check["GET presign:download:{bucket}:{key}"]
Store["SETEX TTL 50min"]
end
LessonMedia --> GenUrls
PresignRoute --> GenUrls
Future --> GenUrls
GenUrls --> Check
Check -->|"hit"| Return[Return cached URL]
Check -->|"miss"| S3[getSignedUrl from AWS SDK]
S3 --> Store
Store --> Return
```
---
## Part A: Redis cache (API)
### 1. Add Redis cache inside presigned URL logic
**File**: [apps/api/src/utils/s3.ts](apps/api/src/utils/s3.ts)
- Import `redis` from [redis/redis.ts](apps/api/src/utils/redis/redis.ts)
- Inside `generateDownloadPresignedUrls`:
- Cache key: `presign:download:{bucketName}:{fileKey}` (bucket distinguishes documents vs videos)
- TTL: 3000 seconds (50 min); presigned URLs are typically valid 1 hour
- Use `redis.mget()` for batch lookup of cache keys before generating
- For cache hits: add to result
- For misses: generate via `getSignedUrl`, store with `redis.setex()`, add to result
- `generateVideoDownloadPresignedUrls` and `generateDocumentDownloadPresignedUrls` call `generateDownloadPresignedUrls`, so they automatically use the cache; no changes needed
### 2. Graceful Redis failure
- If Redis is down or `mget`/`setex` fails, fall back to generating URLs without cache (current behavior)
- Log the error but do not fail the request
---
## Part B: PresignApi class (frontend)
Create a single API class responsible for all presigned URL requests so components never call `classroomio.course.presign...` directly.
### 1. PresignApi class
**New file**: [apps/dashboard/src/lib/features/course/api/presign.svelte.ts](apps/dashboard/src/lib/features/course/api/presign.svelte.ts)
- Extend `BaseApiWithErrors`, use `this.execute<RequestType>()` per AGENTS.md
- Methods:
- `getDocumentUploadUrl(fileName: string, fileType: string)` → `{ url, fileKey }`
- `getDocumentDownloadUrls(keys: string[])` → `Record<string, string>`
- `getVideoUploadUrl(fileName: string, fileType: string)` → `{ url, fileKey }`
- `getVideoDownloadUrls(keys: string[])` → `Record<string, string>`
- Each method wraps `classroomio.course.presign.document.upload`, `document.download`, `video.upload`, or `video.download`
- Export singleton: `export const presignApi = new PresignApi()`
### 2. Types in `utils/types.ts`
**File**: [apps/dashboard/src/lib/features/course/utils/types.ts](apps/dashboard/src/lib/features/course/utils/types.ts)
- Add request types inferred from API: `DocumentUploadPresignRequest`, `DocumentDownloadPresignRequest`, etc.
### 3. Export from course api
**File**: [apps/dashboard/src/lib/features/course/api/index.ts](apps/dashboard/src/lib/features/course/api/index.ts)
- Export `presignApi` from presign.svelte.ts
### 4. Callers to update
| Caller | Current | Change |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| [view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte) | `classroomio.course.presign.document.upload.$post` and `document.download.$post` in `handleFileUpload` | Use `presignApi.getDocumentUploadUrl` and `presignApi.getDocumentDownloadUrls`; remove `classroomio` import |
| [functions.ts](apps/dashboard/src/lib/features/course/utils/functions.ts) `enrichFileUploadAnswersWithUrls` | `classroomio.course.presign.document.download.$post` | Use `presignApi.getDocumentDownloadUrls` (needs access to presignApi singleton) |
| [media-manager.svelte.ts](apps/dashboard/src/lib/features/media/api/media-manager.svelte.ts) `getAssetDownloadUrl` | `classroomio.course.presign.document.download` or `video.download` | Use `presignApi.getDocumentDownloadUrls` or `presignApi.getVideoDownloadUrls` |
| [presign.ts](apps/dashboard/src/lib/utils/services/courses/presign.ts) `GenericUploader` | Calls `classroomio.course.presign...` in `getPresignedUrl` and `getDownloadPresignedUrl` | Use `presignApi` methods instead |
**Note**: `enrichFileUploadAnswersWithUrls` is a pure function in `functions.ts`. It would need to either:
- Accept `presignApi` (or a fetch function) as a parameter, or
- Import `presignApi` directly from `$features/course/api`
The latter is simpler; we import presignApi where needed.
---
## Files to change
| File | Change |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [apps/api/src/utils/s3.ts](apps/api/src/utils/s3.ts) | Add Redis cache check/store inside `generateDownloadPresignedUrls` |
| [apps/dashboard/src/lib/features/course/api/presign.svelte.ts](apps/dashboard/src/lib/features/course/api/presign.svelte.ts) | New: PresignApi class |
| [apps/dashboard/src/lib/features/course/utils/types.ts](apps/dashboard/src/lib/features/course/utils/types.ts) | Add presign request types |
| [apps/dashboard/src/lib/features/course/api/index.ts](apps/dashboard/src/lib/features/course/api/index.ts) | Export presignApi |
| [view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte) | Use presignApi; remove classroomio import |
| [functions.ts](apps/dashboard/src/lib/features/course/utils/functions.ts) | Use presignApi.getDocumentDownloadUrls |
| [media-manager.svelte.ts](apps/dashboard/src/lib/features/media/api/media-manager.svelte.ts) | Use presignApi for download URLs |
| [presign.ts](apps/dashboard/src/lib/utils/services/courses/presign.ts) | GenericUploader uses presignApi |
---
## Benefits
- **Lesson documents/videos**: Re-loading the same lesson uses cached URLs
- **Presign API**: Repeated client calls for same keys hit cache
- **Exercise submissions**: When client calls `enrichFileUploadAnswersWithUrls` (or future server enrichment), cache reduces S3 calls
- **Media manager**: Same pattern—shared cache across the app
@@ -0,0 +1,292 @@
---
name: JWT Token Exchange
overview: Implement a JWT token exchange endpoint that lets customers automatically log their users into ClassroomIO from their own app -- no re-login required. This uses a per-org signing secret and Better Auth's `setSessionCookie` to create sessions from externally-signed JWTs.
todos:
- id: db-schema
content: Add `organization_token_auth` table to schema.ts and create migration 0008
status: pending
- id: db-queries
content: Create token-auth.ts queries (get, create, rotate, delete, toggle active)
status: pending
- id: validation
content: Add Zod schemas for token exchange (ZTokenExchangeQuery, ZTokenExchangePayload) and token auth admin operations
status: pending
- id: extract-provisioning
content: Extract reusable `ensureOrgMembership(userId, email, orgId, roleId?)` from sso-provisioning.ts
status: pending
- id: token-exchange-service
content: "Create token-exchange.ts service: decode JWT, verify signature, find/create user, ensure membership"
status: pending
- id: better-auth-plugin
content: Create Better Auth plugin with `createAuthEndpoint` for `/token-exchange` using `setSessionCookie`
status: pending
- id: admin-service
content: Create token-auth.ts service (enterprise plan check, secret generation, conflict checks) and route (HTTP concerns only, delegates to service, uses handleError)
status: pending
- id: admin-routes
content: Create token-auth route file, export, and register in app.ts
status: pending
- id: error-codes
content: Add token exchange and token auth error codes to errors.ts
status: pending
- id: frontend-types
content: Add request types for token auth endpoints in org/utils/types.ts (infer from RPC client)
status: pending
- id: frontend-api
content: Create TokenAuthApi class extending BaseApiWithErrors in org/api/token-auth.svelte.ts
status: pending
- id: frontend-ui
content: Create token-auth.svelte settings page, route page, navigation entry, and settings index registration
status: pending
- id: translations
content: Add en.json translation keys for all token auth UI strings (no hardcoded English)
status: pending
- id: build-verify
content: Run build, check types, verify migration
status: pending
isProject: false
---
# JWT Token Exchange for Seamless Auto-Login
## Architecture
```mermaid
sequenceDiagram
participant CustomerApp as Customer App
participant CustomerBackend as Customer Backend
participant CIO as ClassroomIO API
participant BetterAuth as Better Auth
participant DB as Database
CustomerApp->>CustomerBackend: User wants to access ClassroomIO
CustomerBackend->>CustomerBackend: Sign JWT with org secret
CustomerBackend->>CustomerApp: Return signed JWT
CustomerApp->>CIO: GET /auth/token-exchange?token=xxx&redirect=/courses
CIO->>DB: Look up org signing secret by org_id from JWT
CIO->>CIO: Verify JWT signature + expiry with jose
CIO->>DB: Find user by email
alt User does not exist
CIO->>BetterAuth: Create user via auth.api.signUpEmail (internal)
BetterAuth->>DB: Insert user + account
Note over CIO: createProfileHook fires automatically
end
CIO->>DB: Ensure org membership (reuse provisioning logic)
CIO->>BetterAuth: setSessionCookie(ctx, session/user)
CIO->>CustomerApp: 302 Redirect to target page (with session cookie)
```
## Step 1: Database -- Add `organization_token_auth` table
Create a new table rather than overloading `organization_sso_config`, since token exchange is conceptually separate from OIDC SSO and should work independently (an org might want token exchange without configuring Okta/Auth0).
**New table: `organization_token_auth`**
- `id` (uuid, PK)
- `organization_id` (uuid, unique FK to organization, cascade delete)
- `signing_secret` (text, not null) -- HMAC secret for HS256 JWT verification
- `is_active` (boolean, default false)
- `created_by_profile_id` (uuid FK to profile)
- `created_at`, `updated_at` (timestamptz)
Files to change:
- [packages/db/src/schema.ts](packages/db/src/schema.ts) -- add `organizationTokenAuth` table definition after line 1934
- New migration file: `packages/db/src/migrations/0008_add_token_auth_table.sql`
- [packages/db/src/types.ts](packages/db/src/types.ts) -- add inferred types
## Step 2: Database Queries
**Location**: `packages/db/src/queries/organization/token-auth.ts` (per ARCHITECTURE.md Layer 1 pattern)
Create [packages/db/src/queries/organization/token-auth.ts](packages/db/src/queries/organization/token-auth.ts) with pure DB functions -- no business logic, no HTTP calls, no transactions (those belong in the service layer):
- `getTokenAuthByOrgId(orgId)` -- look up signing secret for an org
- `createTokenAuth(data: TNewOrganizationTokenAuth)` -- insert new record, use `.returning()`
- `updateTokenAuth(orgId, data: Partial<TOrganizationTokenAuth>)` -- update fields, use `.returning()`
- `deleteTokenAuth(orgId)` -- remove the record
Every `catch` block must log with function name for traceability: `console.error('getTokenAuthByOrgId error:', error)`.
## Step 3: Validation Schemas
**Location**: `packages/utils/src/validation/organization/token-auth.ts` (per ARCHITECTURE.md -- shared validation in `@cio/utils/validation`, used by both API and frontend)
Create [packages/utils/src/validation/organization/token-auth.ts](packages/utils/src/validation/organization/token-auth.ts):
- `ZTokenExchangeQuery` -- validates the `token` (string, min 1) and optional `redirect` (string) query params
- `ZTokenExchangePayload` -- validates the decoded JWT payload: `sub` (string), `email` (email), `name` (string, optional), `org_id` (uuid), `iat` (number), `exp` (number)
Export `T`* inferred types alongside each schema (`export type TTokenExchangeQuery = z.infer<typeof ZTokenExchangeQuery>`).
## Step 4: Service -- Token Exchange Logic
**Location**: `apps/api/src/services/auth/token-exchange.ts` (per ARCHITECTURE.md Layer 2 -- business logic lives in services, throws `AppError` with error codes and status codes, returns structured data not HTTP responses)
Create [apps/api/src/services/auth/token-exchange.ts](apps/api/src/services/auth/token-exchange.ts):
```typescript
export async function exchangeToken(token: string): Promise<{ user: User; orgId: string; }>
```
This function:
1. Decode JWT **without** verifying to extract `org_id` from payload
2. Look up signing secret via `getTokenAuthByOrgId(orgId)` -- throw `AppError(ErrorCodes.TOKEN_EXCHANGE_ORG_NOT_FOUND, 404)` if not found or `AppError(ErrorCodes.TOKEN_EXCHANGE_NOT_ENABLED, 403)` if inactive
3. Verify JWT with `jose.jwtVerify(token, secret, { algorithms: ['HS256'] })` -- validates signature + expiry
4. Reject tokens older than 5 minutes (`maxTokenAge: '5m'`)
5. Validate payload against `ZTokenExchangePayload`
6. Find existing user by email in the `user` table (Better Auth's table)
7. If no user exists, create one via `auth.api.signUpEmail` with a random password (the user will never use it -- they always come through token exchange). The `createProfileHook` fires automatically and `ssoProvisioningHook` handles org membership
8. If user exists but is not an org member, run the provisioning logic from [packages/db/src/auth/hooks/sso-provisioning.ts](packages/db/src/auth/hooks/sso-provisioning.ts) (extracted into a reusable function that accepts userId + orgId rather than relying on email domain matching)
9. Return the user object and orgId
## Step 5: Provisioning -- Extract Reusable Function
Refactor [packages/db/src/auth/hooks/sso-provisioning.ts](packages/db/src/auth/hooks/sso-provisioning.ts) to extract a reusable `ensureOrgMembership(userId, email, orgId, roleId?)` function that:
- Checks if membership already exists
- If not, checks for pending invite (accept it) or creates membership with default role
The existing `ssoProvisioningHook` continues to call this function (it just adds the domain-lookup step on top). The new token exchange service also calls it directly with the `org_id` from the JWT.
## Step 6: Route -- Public Token Exchange Endpoint
Create [apps/api/src/routes/auth/token-exchange.ts](apps/api/src/routes/auth/token-exchange.ts):
```
GET /auth/token-exchange?token=<jwt>&redirect=<url>
```
This is a **public** endpoint (no `authMiddleware`). Flow:
1. Validate query params with `ZTokenExchangeQuery`
2. Call `exchangeToken(token)` from the service
3. Create a Better Auth session using internal API (see below)
4. Set the session cookie using `setSessionCookie` from `better-auth/cookies`
5. Redirect (302) to the `redirect` param or default to `/`
**Session creation approach** -- Based on the [Better Auth discussion #2125](https://github.com/better-auth/better-auth/discussions/2125), use `setSessionCookie` from `better-auth/cookies` combined with creating the session through Better Auth's internal context. The route will be implemented as a Better Auth plugin endpoint using `createAuthEndpoint` from `better-auth/api` to get access to the auth context needed by `setSessionCookie`.
Register as a Better Auth plugin in [packages/db/src/auth.ts](packages/db/src/auth.ts) (not as a regular Hono route) so it gets the internal context:
```typescript
import { tokenExchange } from './auth/plugins/token-exchange';
// in plugins array:
plugins: [admin(), anonymous(), jwt(), sso({}), tokenExchange()]
```
This means the endpoint lives at `/api/auth/token-exchange` (under Better Auth's route namespace).
## Step 7: Admin Routes -- Secret Management
**Location**: `apps/api/src/routes/organization/token-auth.ts` (per ARCHITECTURE.md Layer 3 -- routes handle HTTP concerns only: validation, auth, serialization)
Create [apps/api/src/routes/organization/token-auth.ts](apps/api/src/routes/organization/token-auth.ts). Routes delegate to the service layer and use `handleError` in catch blocks. Use `authMiddleware` + `orgAdminMiddleware`. Non-null assert `user` (`c.get('user')!`) since `authMiddleware` guarantees it.
- `POST /organization/token-auth` -- generate signing secret (requires admin + enterprise plan). Returns `201` with secret shown once
- `GET /organization/token-auth` -- get token auth status (active/inactive, created date -- **never** returns the full secret, only last 4 chars). Returns `200`
- `POST /organization/token-auth/rotate` -- rotate the secret (returns new secret once). Returns `200`
- `DELETE /organization/token-auth` -- delete token auth config. Returns `200`
- `PUT /organization/token-auth/activate` -- toggle active/inactive. Returns `200`
Create the corresponding service [apps/api/src/services/organization/token-auth.ts](apps/api/src/services/organization/token-auth.ts) for business logic (enterprise plan check, secret generation via `crypto.randomBytes(32).toString('hex')`, conflict checks). Routes must not contain business logic.
Export and register in [apps/api/src/app.ts](apps/api/src/app.ts):
```typescript
.route('/organization/token-auth', organizationTokenAuthRouter)
```
## Step 8: Error Codes
Add to [apps/api/src/utils/errors.ts](apps/api/src/utils/errors.ts):
- `TOKEN_EXCHANGE_INVALID_TOKEN`
- `TOKEN_EXCHANGE_EXPIRED`
- `TOKEN_EXCHANGE_ORG_NOT_FOUND`
- `TOKEN_EXCHANGE_NOT_ENABLED`
- `TOKEN_AUTH_ALREADY_EXISTS`
## Step 9: Frontend -- Request Types
**Location**: `apps/dashboard/src/lib/features/org/utils/types.ts` (per AGENTS.md -- define request types in `{domain}/utils/types.ts` for reusability)
Add request types for all token auth endpoints:
```typescript
export type CreateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$post'];
export type GetTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$get'];
export type RotateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['rotate']['$post'];
export type DeleteTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$delete'];
export type ActivateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['activate']['$put'];
```
Never import types from `@cio/db/queries` into dashboard code -- infer everything from the RPC client.
## Step 10: Frontend API Class
**Location**: `apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts` (per AGENTS.md -- API class pattern: extends `BaseApiWithErrors`, handles all logic so components are thin)
Create [apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts](apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts):
- Class `TokenAuthApi extends BaseApiWithErrors`
- Reactive state: `tokenAuth = $state<TokenAuthStatus | null>(null)`, `generatedSecret = $state<string | null>(null)`
- Methods using `this.execute<RequestType>()` (never call RPC directly):
- `getStatus()` -- fetch token auth status
- `generateSecret()` -- create new config, store returned secret in `generatedSecret`
- `rotateSecret()` -- rotate, store new secret in `generatedSecret`
- `deleteTokenAuth()` -- delete config
- `activateTokenAuth()` -- toggle active
Use Zod client-side validation where applicable. Use `snackbar.success('translation.key')` with translation keys (not raw English strings).
Export singleton: `export const tokenAuthApi = new TokenAuthApi()`
## Step 11: Frontend -- Admin UI Component
**Location**: `apps/dashboard/src/lib/features/settings/pages/token-auth.svelte` (kebab-case per AGENTS.md naming convention)
Create [apps/dashboard/src/lib/features/settings/pages/token-auth.svelte](apps/dashboard/src/lib/features/settings/pages/token-auth.svelte) as a separate settings page (not inlined into sso.svelte -- keeps components focused):
- Import `tokenAuthApi` from `$features/org/api/token-auth.svelte`
- Use `$t('key.path')` for all user-facing text (no hardcoded English in markup)
- Use `t('key.path')` in script blocks, `t.get('key.path')` outside Svelte components
- Use UI components from `@cio/ui`:
- `@cio/ui/base/button` for actions (Generate, Rotate, Delete)
- `@cio/ui/base/badge` for active/inactive status
- `@cio/ui/base/switch` for activate toggle
- `@cio/ui/base/field` for form layout (`Field.Group`, `Field.Set`, `Field.Legend`, `Field.Description`)
- Do NOT use native `<input>`, `<label>`, `<textarea>` -- use `@cio/ui` equivalents
- Theme color classes must use `ui:` prefix in dashboard code (e.g. `ui:text-muted-foreground`, `ui:text-primary`)
- Component should be thin -- call API methods, render UI, no business logic
- `UpgradeBanner` for enterprise plan gating (same pattern as sso.svelte)
- Integration Guide section with a code snippet block showing the customer-facing JWT signing example
Create route page at [apps/dashboard/src/routes/org/[slug]/settings/token-auth/+page.svelte](apps/dashboard/src/routes/org/[slug]/settings/token-auth/+page.svelte) as a thin wrapper.
Add navigation entry in [apps/dashboard/src/lib/features/ui/navigation/org-navigation.ts](apps/dashboard/src/lib/features/ui/navigation/org-navigation.ts) and register the page in [apps/dashboard/src/lib/features/settings/pages/index.ts](apps/dashboard/src/lib/features/settings/pages/index.ts).
## Step 12: Translations
Add keys to [apps/dashboard/src/lib/utils/translations/en.json](apps/dashboard/src/lib/utils/translations/en.json) for all UI strings in the token auth section. All user-facing copy must go through translations -- snackbar messages use keys directly (e.g. `snackbar.success('snackbar.token_auth.created')`).
## Step 12: Build and Verify
Run `pnpm --filter @cio/api build` to verify types compile. Run the migration against a dev database.
## Dependencies
- `jose` npm package -- for JWT verification. Check if already installed; if not, add to `apps/api` or `packages/db`.
## Security Considerations
- Tokens must be short-lived (max 5 minutes, recommend 60 seconds)
- Signing secrets are 256-bit random hex strings
- HMAC-SHA256 (HS256) is used -- simple symmetric signing, appropriate for server-to-server where both parties share the secret
- The secret is shown to the admin exactly once on generation/rotation
- Rate limiting on the `/auth/token-exchange` endpoint (already covered by the global rate limiter, but consider stricter limits)
- Enterprise plan gating on secret generation (same as SSO)
@@ -0,0 +1,300 @@
---
name: ""
overview: ""
todos: []
isProject: false
---
# Unify Renderer Format with AnswerData
## Overview
Eliminate the impedance mismatch between UI (ExerciseAnswerValue) and storage (AnswerData) by having renderers emit and consume AnswerData directly. This removes the need for `serialize` and `toRendererValue` in the codec.
## Current State
- **Renderers** emit `ExerciseAnswerValue` (heterogeneous: optionId, boolean, string, string[], etc.)
- **Storage** uses `AnswerData` (discriminated union)
- **serialize** converts ExerciseAnswerValue → AnswerData
- **toRendererValue** converts AnswerData → ExerciseAnswerValue (for display)
## Target State
- **Renderers** emit and consume `AnswerData` directly
- **Storage** uses `AnswerData`
- **Codec** only has `toApiPayload` and `fromApiPayload` (for API flat format)
- No serialize, no toRendererValue
---
## Phase 1: Update Types and Contracts
### 1.1 exercise-types.ts
- Add `AnswerData` to imports/re-exports (or keep in answer-data.ts)
- Change `ExerciseQuestionRendererProps.answer` from `ExerciseAnswerValue` to `AnswerData | null`
- Change `onAnswerChange` from `(answer: ExerciseAnswerValue) => void` to `(answer: AnswerData) => void`
- Optionally deprecate or remove `ExerciseAnswerValue` from renderer contracts (it may still be used internally in some components)
### 1.2 render-contract.ts
- Change `ExerciseQuestionRenderContract.answer` to `AnswerData | null`
- Change `ExerciseQuestionListRenderContract.answersByKey` to `Record<string, AnswerData>`
### 1.3 form-state.ts
- Change `answers: Record<string, ExerciseAnswerValue>` to `answers: Record<string, AnswerData>`
---
## Phase 2: Update Take Renderers (12 files)
Each take renderer must:
1. Accept `answer?: AnswerData` (typed for its question type)
2. Extract display value from AnswerData (e.g. `answer?.optionId` for RADIO)
3. Call `onAnswerChange(AnswerData)` when user submits, constructing the correct AnswerData shape
| Renderer | Current emit | New emit (AnswerData) |
| ----------------- | -------------------------- | ------------------------------------------------- |
| radio/take | optionId (number) | `{ type: 'RADIO', optionId }` |
| checkbox/take | optionIds (number[]) | `{ type: 'CHECKBOX', optionIds }` |
| true-false/take | boolean | `{ type: 'TRUE_FALSE', value: boolean }` |
| textarea/take | string | `{ type: 'TEXTAREA', text }` |
| short-answer/take | string | `{ type: 'SHORT_ANSWER', text }` |
| numeric/take | number | `{ type: 'NUMERIC', value }` |
| fill-blank/take | string | string[] |
| file-upload/take | { fileKey, fileName, ... } | `{ type: 'FILE_UPLOAD', fileKey, fileName, ... }` |
| matching/take | pairs[] | `{ type: 'MATCHING', pairs }` |
| ordering/take | string[] | `{ type: 'ORDERING', orderedValues }` |
| link/take | string[] | `{ type: 'LINK', urls }` |
| hotspot/take | coordinates[] | `{ type: 'HOTSPOT', coordinates }` |
### Per-renderer pattern
```svelte
<!-- Before -->
let { answer, onAnswerChange } = $props();
onAnswerChange(selectedOptionId);
<!-- After -->
let { answer, onAnswerChange } = $props();
// answer is RadioAnswerData | undefined
const displayValue = answer?.optionId;
onAnswerChange({ type: 'RADIO', optionId: selectedOptionId });
```
---
## Phase 3: Update Preview Renderers (10 files)
Preview renderers display the answer in read-only mode. They receive `answer` and render it.
- **radio/preview**, **checkbox/preview**, **true-false/preview**: Extract optionId/optionIds/value from AnswerData for display
- **textarea/preview**, **short-answer/preview**: Extract text
- **numeric/preview**: Extract value
- **fill-blank/preview**: Extract values
- **file-upload/preview**: Extract fileKey, fileName, etc.
- **matching/preview**, **ordering/preview**, **link/preview**, **hotspot/preview**: Extract pairs/orderedValues/urls/coordinates
Preview components need the question (with options) for RADIO/CHECKBOX/TRUE_FALSE to resolve ids to labels for display. The AnswerData gives the structure; options give the labels.
---
## Phase 4: Update Dashboard Components
### 4.1 view-mode.svelte
- Change `questionnaireMetaData.answers` to `Record<string, AnswerData>`
- Replace `mapAnswerToApiPayload` usage: call `toApiPayload(answer, questionId)` directly (answer is already AnswerData)
- Remove `serializeAnswer` call from the submit flow
- `onSharedAnswerChange` receives AnswerData
- `checkForSubmission` / `formatAnswers`: answers from API are AnswerData → pass through to questionnaireMetaData
### 4.2 preview.svelte
- `grades`, `answers` in questionnaireMetaData: use AnswerData
- Pass AnswerData to QuestionRenderer contract
### 4.3 individual.svelte
- `getStudentAnswerForQuestion` returns `AnswerData` (or the raw answerData from API)
- Pass to QuestionRenderer as answer prop
### 4.4 formatAnswers (functions.ts)
- Returns `Record<string, AnswerData>` instead of `Record<string, ExerciseAnswerValue>`
- Or keep as-is if consumers expect AnswerData
### 4.5 mark-exercise-modal.svelte
- `answersToDisplay` becomes `Record<string, AnswerData>`
- Preview receives AnswerData
- `enrichFileUploadAnswersWithUrls` may need to accept AnswerData and enrich FILE_UPLOAD entries
### 4.6 summary.svelte
- `getAnswerToQuestionOfStudent` returns AnswerData
- Chart logic extracts values from AnswerData (e.g. optionIds for option-based, text for text)
### 4.7 Store (store.ts)
- `answers` in questionnaireMetaData: `Record<string, AnswerData>`
---
## Phase 5: Simplify Answer Codec
### 5.1 Remove from AnswerCodec interface
- Remove `serialize`
- Remove `toRendererValue`
### 5.2 Remove from each codec implementation
- Delete serialize implementation
- Delete toRendererValue implementation
### 5.3 Remove exported functions
- Remove `serializeAnswer`
- Remove `deserializeAnswer` (or rename to `toDisplayValue` if still needed for enrichFileUploadAnswersWithUrls, etc.)
### 5.4 Keep
- `toApiPayload` – for API submission
- `fromApiPayload` – for API write path (payload → AnswerData)
- `ANSWER_CODECS` – lookup by type
### 5.5 Add helper if needed
- `toApiPayload(data: AnswerData, questionId: number)` – already exists
- For submission: frontend has AnswerData → toApiPayload → API
- For display: AnswerData goes directly to renderer, no conversion
---
## Phase 6: Update API and Submission Flow
### 6.1 createSubmissionService
- Already uses `fromApiPayload` to convert API payload → AnswerData
- No change if API still receives flat format
### 6.2 Optional: Accept AnswerData in API
- If we change the submission API to accept `AnswerData` directly (e.g. `answers: AnswerData[]`), we can skip `fromApiPayload` and `toApiPayload` for submission. But the current API uses flat `{ questionId, optionId?, answer? }`. Plan assumes we keep that for now.
---
## Phase 7: enrichFileUploadAnswersWithUrls
- Currently expects `Record<string, unknown>` and looks for `fileKey` in values
- With AnswerData, FILE_UPLOAD answers are `{ type: 'FILE_UPLOAD', fileKey, fileName, ... }`
- Update to detect `value?.type === 'FILE_UPLOAD'` and use `value.fileKey`
- Return enriched AnswerData (add fileUrl to the object)
---
## Phase 8: Migration / Compatibility
- **No DB migration** – AnswerData format is unchanged
- **Existing data** – Already AnswerData in answer_data column
- **ExerciseAnswerValue** – Can be deprecated or removed from exercise-types once all consumers are updated
---
## Phase 9: Update ADDING_A_QUESTION_TYPE.md
**File:** `packages/question-types/ADDING_A_QUESTION_TYPE.md`
Update the guide so new question types follow the AnswerData-only flow.
### 9.1 Step 3 — Answer data type and codec
**3a. answer-data.ts** — No change; still add the AnswerData type and union.
**3b. answer-codecs.ts** — Simplify the codec example:
- Remove `serialize` — renderers emit AnswerData directly
- Remove `toRendererValue` — renderers consume AnswerData directly
- Keep only `toApiPayload` and `fromApiPayload`
Example to replace the current Step 3b block:
```typescript
const MY_NEW_TYPE_CODEC: AnswerCodec<MyNewAnswerData> = {
type: 'MY_NEW_TYPE',
toApiPayload(data, questionId) {
return { questionId, answer: JSON.stringify({ type: 'MY_NEW_TYPE', value: data.value }) };
},
fromApiPayload(payload) {
if (!payload.answer) return null;
const { value } = JSON.parse(payload.answer) as { type: 'MY_NEW_TYPE'; value: string };
return { type: 'MY_NEW_TYPE', value };
}
};
```
### 9.2 Step 7 — Implement renderers
Update the renderer section to state:
- `answer` prop is `AnswerData | null` (typed for the question type, e.g. `MyNewAnswerData`)
- `onAnswerChange` receives `AnswerData` — renderers must emit the full AnswerData shape, e.g. `onAnswerChange({ type: 'MY_NEW_TYPE', value })`
- Take renderer: extract display value from `answer?.value` (or relevant field), emit `{ type: 'MY_NEW_TYPE', value }` on change
- Preview renderer: read from `answer` (AnswerData) for display
### 9.3 Checklist
- Update checklist item for the codec to say "`AnswerCodec` (toApiPayload, fromApiPayload)" — no serialize/toRendererValue
### 9.4 Step 9 — Verify
- Update the test bullet to mention: "codec (toApiPayload ↔ fromApiPayload)"
- Remove references to "serialize" in the verification steps
---
## Files to Modify (Summary)
| Area | Files |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Types | `exercise-types.ts`, `render-contract.ts`, `form-state.ts` |
| Codec | `answer-codecs.ts` (remove serialize, toRendererValue) |
| Take renderers | 12× `packages/ui/.../renderers/*/take.svelte` |
| Preview renderers | 10× `packages/ui/.../renderers/*/preview.svelte` |
| Dashboard | `view-mode.svelte`, `preview.svelte`, `individual.svelte`, `summary.svelte`, `mark-exercise-modal.svelte`, `store.ts`, `functions.ts` |
| Utils | `enrichFileUploadAnswersWithUrls` in functions.ts |
| Storybook | `question-type-modes.svelte`, `question-fixtures.ts` if they use answer |
| ordering-utils | `applyOrderingAnswer` – change to accept AnswerData (OrderingAnswerData) |
| Docs | `packages/question-types/ADDING_A_QUESTION_TYPE.md` |
---
## Estimated Effort
- Phase 1: ~30 min
- Phase 2: ~2–3 hours (12 renderers, each ~10–15 min)
- Phase 3: ~1–2 hours (10 preview components)
- Phase 4: ~1–2 hours (dashboard)
- Phase 5: ~30 min (codec cleanup)
- Phase 6: minimal
- Phase 7: ~15 min
- Phase 8: N/A
- Phase 9: ~15 min (update ADDING_A_QUESTION_TYPE.md)
**Total: ~6–8 hours**
---
## Risks
- **Preview mode** for edit: Edit renderers may not use answer; verify which modes each renderer supports
- **ordering-utils**: `applyOrderingAnswer` merges initial items with answer; ensure it works with `OrderingAnswerData`
- **Storybook**: Update fixtures and stories to pass AnswerData