Skip to content

Conversation

devin-ai-integration[bot]
Copy link
Contributor

@devin-ai-integration devin-ai-integration bot commented Sep 13, 2025

Fix CodeRabbit issues: implement validation middleware and improve error handling

Summary

This PR addresses 93 CodeRabbit issues from PR #279 by implementing a comprehensive body validation middleware system and fixing several security/reliability issues:

🔧 Key Changes:

  • New validation middleware (/lib/validation/) with type-safe request body validation for all /sessions, /tutorials, and /users API endpoints
  • Fixed config import issues by replacing dynamic imports with static imports in tutorial-state/route.ts
  • Enhanced KV persistence error handling with proper success checks and error bubbling
  • Added path traversal protection for tutorial routes to prevent directory traversal attacks
  • Removed implicit any types on request body parameters with proper TypeScript interfaces
  • Standardized parseInt usage to Number.parseInt for consistency
  • Improved error responses with detailed validation messages and 400 status codes

🛡️ Security Improvements:

  • Tutorial ID validation prevents path traversal (.., /, \ characters blocked)
  • Snippet loading now has error handling and path validation
  • Request body validation prevents malformed/malicious payloads

📝 Type Safety:

  • Uses existing types from /app/chat/types.ts (Session, Message, TutorialData, etc.)
  • New comprehensive validation functions for all request types
  • Eliminates implicit any types on request bodies

Review & Testing Checklist for Human (4 items - 🔴 High Risk)

  • Test all API endpoints manually - Verify POST/PUT/DELETE requests to /api/sessions/*, /api/tutorials/*, and /api/users/tutorial-state still work correctly with the new validation middleware
  • Check frontend compatibility - Ensure the new error response format ({ error, details }) doesn't break existing frontend error handling
  • Verify validation rules match expectations - Review that validation in lib/validation/middleware.ts matches the actual data structures your frontend sends (especially Message, Session types)
  • Test edge cases - Try invalid tutorial IDs, malformed JSON bodies, missing required fields to ensure validation works as expected

Notes

This change touches many API endpoints simultaneously and introduces new validation logic that could affect existing functionality. While the validation is based on existing types from /app/chat/types.ts, there could be mismatches between what the frontend actually sends vs. what the types expect.

The KV error handling improvements should make the API more resilient to storage failures, but the behavior changes could surface errors differently than before.

Requested by: @afterrburn (srith@agentuity.com)
Devin Session: https://app.devin.ai/sessions/df50e03078644f8cbe96f8c1227b902c

Summary by CodeRabbit

  • New Features
    • Unified input validation across session, tutorial, and tutorial-state APIs with consistent, readable error responses.
    • Sessions list returns an empty set with pagination when no data is available.
  • Bug Fixes
    • Safer tutorials: validated IDs/steps, range checks, and sanitized snippet paths.
    • Snippet load failures are logged and skipped instead of failing requests.
    • Clearer store errors with proper 404 vs other failures.
    • Enforced session ID match on update.
    • More reliable tutorial progress reset with explicit persistence handling.

…ports, handle KV errors

- Add comprehensive body validation middleware for /sessions, /tutorials, /users endpoints
- Fix config import issues by moving to static imports at top of files
- Add proper KV persistence error handling with success checks
- Validate tutorialId as string and prevent path traversal attacks
- Fix implicit any types on request body parameters
- Replace parseInt with Number.parseInt for consistency
- Add proper 400 error responses with detailed validation messages
- Use existing types from app/chat/types.ts for validation
- Prevent TypeError when no progress exists by handling 404 responses gracefully

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
Copy link
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Copy link
Contributor

coderabbitai bot commented Sep 13, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Introduces a reusable validation module and updates multiple API routes to use centralized JSON parsing and schema-based validation. Adds input sanitization, structured error responses, and explicit timestamp normalization. Adjusts sessions and tutorials routes to validate payloads and params before processing, with minor error message changes and safer KV interactions.

Changes

Cohort / File(s) Summary
Validation framework
lib/validation/middleware.ts, lib/validation/types.ts
Adds a schema-based validation system, helper types, reusable validators, request parsing with standardized error responses, and typed request/response interfaces for sessions, messages, tutorials, and pagination.
Sessions API
app/api/sessions/route.ts, app/api/sessions/[sessionId]/route.ts, app/api/sessions/[sessionId]/messages/route.ts
Replaces ad-hoc body parsing with parseAndValidateJSON; validates sessions and messages; normalizes timestamps; adds sessionId mismatch check (400); distinguishes 404 vs other errors in listing; maintains downstream persistence/streaming logic.
Tutorials API
app/api/tutorials/route.ts, app/api/tutorials/[id]/steps/[stepNumber]/route.ts
Adds param validation (tutorial id, step number), path sanitization for snippet reads, guarded range checks, structured validation errors, and resilient snippet loading; listing now skips unsafe entries.
User tutorial state
app/api/users/tutorial-state/route.ts
Centralizes POST/DELETE validation; persists reset via KV with explicit error handling; keeps GET unchanged; replaces dynamic imports with static ones.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant R as Route Handler
  participant V as parseAndValidateJSON
  participant S as Store/Services

  C->>R: HTTP Request (JSON)
  R->>V: Parse + Validate (schema/validator)
  alt Validation fails
    V-->>R: { success:false, response }
    R-->>C: HTTP 400 (standardized errors)
  else Validation succeeds
    V-->>R: { success:true, data }
    R->>S: Process with validated data
    S-->>R: Result / Stream / KV response
    R-->>C: HTTP 2xx JSON
  end
  note over R,V: Centralized error formatting and type-safe data
Loading
sequenceDiagram
  autonumber
  participant C as Client
  participant R as Tutorials Step Route
  participant V as Validators (id/step)
  participant FS as File System

  C->>R: GET /api/tutorials/:id/steps/:stepNumber
  R->>V: validateTutorialId(id)
  alt Invalid id
    R-->>C: 400 Validation error
  else Valid id
    R->>V: validateStepNumber(stepNumber)
    alt Invalid step
      R-->>C: 400 Validation error
    else In range?
      alt Out of range
        R-->>C: 404 Step not found
      else OK
        R->>FS: Read MDX + snippets (sanitize paths)
        alt Read error
          R->>R: Log warning, skip snippet
        end
        R-->>C: 200 JSON (metadata, mdx, snippets, totals)
      end
    end
  end
  note over R,FS: Skips entries with ".." or "\" to prevent traversal
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • rblalock
  • jhaynie

Poem

I thump my paw at structured cheer,
New schemas bloom—no chaos here.
With whiskered wisdom, I validate,
Guarding paths from sneaky fate.
Timestamps tidy, sessions neat—
Hippity-hop, our APIs beat!
(ʘ‿ʘ)/🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.78% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly identifies the primary work — implementing validation middleware and improving error handling — which matches the PR objectives and the majority of changed files. It is concise, specific, and does not contain noisy elements like file lists or vague wording. A reviewer scanning PR history would understand the main intent from this title.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

cloudflare-workers-and-pages bot commented Sep 13, 2025

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
docs 4f11153 Sep 14 2025, 05:29 PM

devin-ai-integration bot and others added 2 commits September 13, 2025 19:00
- Add SessionMessageValidationResult and SessionMessageOnlyValidationResult types
- Fix validation function return type mismatches in session routes
- Add proper bounds checking for stepIndex in tutorial route
- Ensure all validation errors use consistent error structure
- Generate missing docs.json file to resolve import errors

All TypeScript compilation errors resolved, ready for CI

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
- Add FieldSchema and ValidationSchema interfaces for declarative validation
- Implement validateField and validateObject for schema-based validation
- Add overloaded parseAndValidateJSON to accept both validators and schemas
- Maintain backward compatibility with existing validation functions
- Fix TypeScript compilation errors with explicit Message type annotations
- Enable reusable validation for current and future types

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
@afterrburn
Copy link
Contributor

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Sep 13, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai bot requested review from jhaynie and rblalock September 13, 2025 22:15
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
app/api/sessions/[sessionId]/route.ts (1)

219-234: Normalize timestamp here too to keep data contract consistent

messages/route.ts converts message.timestamp to ISO, but this POST path appends the raw timestamp. This divergence can break consumers expecting uniform ISO strings.

Apply before constructing updatedSession:

-    const { message } = validation.data;
+    const { message } = validation.data;
+    if (message.timestamp) {
+      message.timestamp = toISOString(message.timestamp);
+    }
app/api/tutorials/[id]/steps/[stepNumber]/route.ts (1)

7-9: Fix route params typing and remove unnecessary await.

params is not a Promise in Next.js route handlers; awaiting it forces an incorrect type and can mask real typing issues.

Apply:

-interface RouteParams {
-  params: Promise<{ id: string; stepNumber: string }>;
-}
+interface RouteParams {
+  params: { id: string; stepNumber: string };
+}
@@
-    const { id, stepNumber } = await params;
+    const { id, stepNumber } = params;

Also applies to: 13-13

🧹 Nitpick comments (17)
app/api/tutorials/route.ts (1)

20-22: Harden path traversal defense: normalize + allow‑list slug check

includes(".."), "/", "" can be bypassed via encodings or alternate separators. Safer to resolve to an absolute path and verify it remains under tutorialRoot, and also enforce a slug allow‑list.

Apply this diff within the loop:

-      if (entry.includes('..') || entry.includes('/') || entry.includes('\\')) {
-        continue;
-      }
+      // Stronger validation: only accept sluggy names and ensure resolved path stays under tutorialRoot
+      const isSlug = /^[A-Za-z0-9._-]+$/.test(entry);
+      const resolvedPath = resolve(tutorialRoot, entry);
+      if (!isSlug || !resolvedPath.startsWith(tutorialRoot + sep)) {
+        // optionally: console.warn(`Skipping unsafe tutorial entry: ${entry}`);
+        continue;
+      }

And update imports:

// at top
-import { join } from 'path';
+import { join, resolve, sep } from 'path';
lib/validation/types.ts (3)

1-1: Remove unused type and use path alias for consistency

TutorialData isn’t used here, and other files import via '@/...' alias. Align to avoid fragile relative paths and unused import lint errors.

-import { Session, Message, TutorialData } from '../../app/chat/types';
+import { Session, Message } from '@/app/chat/types';

31-36: Prefer unknown over any in generic defaults

unknown is safer and pushes callers to narrow types.

-export interface ApiResponse<T = any> {
+export interface ApiResponse<T = unknown> {
   success: boolean;
   data?: T;
   error?: string;
   message?: string;
 }

46-49: Avoid duplicating payload beside ApiResponse; use ApiResponse properly

Current SessionsResponse both extends ApiResponse and adds its own fields, leading to two payload shapes (data vs sessions). Wrap the payload in ApiResponse instead.

-export interface SessionsResponse extends ApiResponse {
-  sessions: Session[];
-  pagination: PaginationInfo;
-}
+export interface SessionsPayload {
+  sessions: Session[];
+  pagination: PaginationInfo;
+}
+export type SessionsResponse = ApiResponse<SessionsPayload>;
app/api/sessions/[sessionId]/messages/route.ts (2)

69-88: Validation flow reads clean; minor: coerce and default explicitly

Body shape check + validateMessage is solid. Small nit: explicitly narrow processWithAgent using === true to avoid truthy surprises.

-      const processWithAgent = body.processWithAgent !== undefined ? Boolean(body.processWithAgent) : true;
+      const processWithAgent = body.processWithAgent === true ? true : true;
+      // or simply: const processWithAgent = body.processWithAgent !== false;

284-349: SSE parsing may drop/garble events across chunk boundaries

Splitting decoded text by “\n” per chunk without buffering leftover partial lines risks JSON parse errors and lost deltas/finish events. Use a rolling buffer and TextDecoder with stream: true.

Example helper you can reuse here (and in title-gen):

function createSSELineReader() {
  const decoder = new TextDecoder();
  let buffer = '';
  return {
    push(chunk: Uint8Array): string[] {
      buffer += decoder.decode(chunk, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() ?? '';
      return lines;
    },
    flush(): string[] {
      const lines = buffer ? [buffer] : [];
      buffer = '';
      return lines;
    }
  };
}

Then inside the streaming loop, replace line splitting with the helper:

const sse = createSSELineReader();
...
const lines = sse.push(value);
for (const line of lines) { /* existing data: handling */ }
...
// after the loop
for (const line of sse.flush()) { /* finalize any remaining line */ }
app/api/sessions/route.ts (1)

23-27: Nit: specify radix when parsing integers

Explicit base avoids edge cases and linters complaining.

-    const parsedLimit = Number.parseInt(searchParams.get('limit') ?? String(DEFAULT_SESSIONS_LIMIT));
-    const parsedCursor = Number.parseInt(searchParams.get('cursor') ?? '0');
+    const parsedLimit = Number.parseInt(searchParams.get('limit') ?? String(DEFAULT_SESSIONS_LIMIT), 10);
+    const parsedCursor = Number.parseInt(searchParams.get('cursor') ?? '0', 10);
app/api/tutorials/[id]/steps/[stepNumber]/route.ts (6)

25-31: Remove redundant falsy check on validated stepIndex.

After a successful validation, data is defined and ≥1; the extra 400 path is unreachable.

-    const stepIndex = stepValidation.data;
-    if (!stepIndex) {
-      return NextResponse.json(
-        { success: false, error: 'Invalid step number' },
-        { status: 400 }
-      );
-    }
+    const stepIndex = stepValidation.data;

2-2: Prep for safer path resolution in snippet loader.

You’ll need resolve/relative to harden snippet path checks (see next comment).

-import { join } from 'path';
+import { join, resolve, relative } from 'path';

78-81: Guard invalid range requests for snippets.

If to < from, the slice is empty; bail early to avoid misleading output.

-        const startIdx = Math.max(0, (desc.from ? desc.from - 1 : 0));
-        const endIdx = Math.min(lines.length, desc.to ? desc.to : lines.length);
+        const startIdx = Math.max(0, (desc.from ? desc.from - 1 : 0));
+        const endIdx = Math.min(lines.length, desc.to ?? lines.length);
+        if (endIdx < startIdx) return;

89-107: Make the CodeFromFiles tag regex multiline-safe.

([^>]*?) won’t match attributes split across lines. Use a dot‑all class.

-    const filesTagRegex = /<CodeFromFiles\s+([^>]*?)\/>/g;
+    const filesTagRegex = /<CodeFromFiles\s+([\s\S]*?)\/>/g;

153-164: Align totalSteps with the step list actually used.

You filter index out for stepSlugs but return pages.length. This yields inconsistent pagination.

-        totalSteps: pages.length
+        totalSteps: stepSlugs.length

36-40: Optional: return 404 when child meta is missing.

A missing meta.json implies a missing tutorial; consider 404 instead of 500.

lib/validation/middleware.ts (4)

100-108: Tighten enum validation to enforce string type.

Schema constrains enumValues to strings; ensure the value is a string before includes.

-    case 'enum':
-      if (!schema.enumValues || !schema.enumValues.includes(value)) {
+    case 'enum':
+      if (typeof value !== 'string' || !schema.enumValues || !schema.enumValues.includes(value)) {
         return { 
           field: fieldName, 
           message: `must be one of: ${schema.enumValues?.join(', ')}`, 
           received: value 
         };
       }

176-181: Validate timestamp format (basic ISO-8601 check).

Prevents arbitrary strings in timestamp.

-  timestamp: { type: 'string', required: true },
+  timestamp: { 
+    type: 'string', 
+    required: true,
+    customValidator: (v, field) =>
+      Number.isFinite(Date.parse(v)) ? null : { field, message: 'must be a valid ISO-8601 date string', received: v }
+  },

289-292: Consistency: reuse createValidationError for invalid JSON.

Aligns 400 responses with the new { error, details } shape.

-    return {
-      success: false,
-      response: NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
-    };
+    return {
+      success: false,
+      response: createValidationError('Invalid JSON body', [{ field: 'body', message: 'invalid JSON' }])
+    };

141-160: Optional: support unknown-key policy.

If you need stricter schemas, add an option to reject/strip unknown fields in validateObject.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61aaac7 and 67e7160.

📒 Files selected for processing (8)
  • app/api/sessions/[sessionId]/messages/route.ts (2 hunks)
  • app/api/sessions/[sessionId]/route.ts (4 hunks)
  • app/api/sessions/route.ts (4 hunks)
  • app/api/tutorials/[id]/steps/[stepNumber]/route.ts (5 hunks)
  • app/api/tutorials/route.ts (2 hunks)
  • app/api/users/tutorial-state/route.ts (3 hunks)
  • lib/validation/middleware.ts (1 hunks)
  • lib/validation/types.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-10T14:24:52.800Z
Learnt from: afterrburn
PR: agentuity/docs#279
File: agent-docs/src/agents/agent-pulse/types.ts:2-7
Timestamp: 2025-09-10T14:24:52.800Z
Learning: The Agentuity SDK (agentuity/sdk) only exports specific types: AgentRequest, AgentResponse, AgentContext, and VectorUpsertParams. It does not export general message types like ConversationMessage or ChatMessage.

Applied to files:

  • lib/validation/types.ts
📚 Learning: 2025-07-23T12:40:34.834Z
Learnt from: CR
PR: agentuity/docs#0
File: agent-docs/.cursor/rules/sdk.mdc:0-0
Timestamp: 2025-07-23T12:40:34.834Z
Learning: Applies to agent-docs/src/agents/**/*.ts : Import types from 'agentuity/sdk'

Applied to files:

  • lib/validation/types.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Workers Builds: docs
🔇 Additional comments (10)
app/api/sessions/[sessionId]/messages/route.ts (1)

12-14: LGTM: Centralized validation imports

Adopts shared middleware/types to standardize input handling. Good move.

app/api/sessions/route.ts (2)

30-37: Good: distinguish 404 (no sessions) from other KV errors

Returning an empty payload for 404 avoids failing first‑time users; other errors propagate correctly.


82-88: LGTM: centralized validation + ISO timestamp normalization

Validation middleware and uniform timestamp handling reduce downstream parsing issues.

Also applies to: 91-99

app/api/sessions/[sessionId]/route.ts (4)

60-66: LGTM: switch to centralized session validation

Consistent with the new middleware and improves error shaping.


67-71: LGTM: explicit sessionId mismatch check

Prevents accidental cross‑session writes.


76-85: LGTM: normalize message timestamps on PUT

Ensures consistency when updating full sessions.


204-214: LGTM: message validation on POST

Inline validator keeps this route aligned with the messages route.

app/api/tutorials/[id]/steps/[stepNumber]/route.ts (1)

15-23: LGTM: centralized param validators with structured 400s.

Solid move to validateTutorialId/validateStepNumber and createValidationError.

app/api/users/tutorial-state/route.ts (2)

3-9: LGTM: static imports and centralized validation wiring.

Good consolidation of config/KV imports and validator usage.


46-52: LGTM: parse-then-validate flow with standardized 400s.

This keeps the handler lean and consistent.

devin-ai-integration bot and others added 6 commits September 13, 2025 22:33
… of truth

- Replace TypeScript interfaces with Zod schemas in app/chat/types.ts
- Derive types using z.infer<typeof Schema> instead of separate interfaces
- Update validation middleware to use Zod's safeParse and error handling
- Maintain all existing validation behavior while using industry-standard Zod
- Fix TypeScript compilation errors and import issues
- All API endpoints now use consistent Zod-based validation

This eliminates the duplicate source of truth between validation schemas and TypeScript interfaces, making the codebase more maintainable and following modern best practices.

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
- Replace custom validation logic with SessionMessageRequestSchema
- Simplify validation code by using Zod's built-in validation
- Maintain all existing functionality while using industry-standard validation

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
…ty functions

- Remove unused SessionMessageValidationResult and SessionMessageOnlyValidationResult interfaces
- Convert validateStepNumber and validateTutorialId to use Zod schemas internally
- Add StepNumberSchema and TutorialIdSchema for consistent validation
- Maintain backward compatibility with existing function signatures
- Complete elimination of duplicate source of truth between validation and types
- All validation now uses Zod schemas as single source of truth

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
@afterrburn afterrburn merged commit 4c86313 into seng/chat-prototype Sep 14, 2025
2 checks passed
@afterrburn afterrburn deleted the devin/1757789486-fix-coderabbit-issues branch September 14, 2025 17:31
@coderabbitai coderabbitai bot mentioned this pull request Sep 14, 2025
afterrburn added a commit that referenced this pull request Sep 17, 2025
* add totalChunks to metadata for tracing

* improve RAG retrieval process

* POC UI for chat based documentation

* update Start / Continue course

* expand text

* fix scrollbar problem and chat input resizing

* adding progress tracker

* center the progress bar

* testing out new terminal component and websocket servert

* fix terminal issue not staying on

* fix weird terminal display

* fix self is not defined error

* remove unnecessary terminal message

* typo

* fix weird flow

* remove duplicated butotn

* playing with coding web server

* remove websocket server

* creating api for tutorials

* fix interface

* modify tutorials workflow -- vibecoded

* dummy demo code execution api next.js

* New pulse agent using response api tools calling

* re-build the entire Pulse agent with new design

* adding tutorial step workflow

* simplify tutorial reader to have consistent api

* cleaning up some more steps

* breaking frontend to smaller components;

* link doc-qa to pulse agent

* removing unused import

* fix chat input box and have split pane for code editor

* enhancing file display

* simplify chat interface -- removing unnecessary code block displays

* add editor close button

* make side bar icons smaller

* implement chunk streaming structure

* clean up some items

* Revert "Implement Copy Page Dropdown Functionality (#239)"

This reverts commit 5eb9f16.

* fix tutorial step data handling issue

* add kv store api service

* remove unused interfaces

* remove unneeded conversation type

* reformat chat history

* add kv store api

* Simplify and refactor chat to connect with kv store

* add uuid package

* update example env

* share session context

* removing debug

* Adding session cache with SWR

* add .env to gitignore

* sync with main

* adjust chat message area width and dynamic spacing with sessionsbar

* add code editor content

* remove redundant comments

* display tutorial instruction content

* add user based session management

* enable split pane resize

* adding sessions cursor

* sessions paginated loading

* clean up env variables

* enabling direct llm access flag

* add title generation

* remove session update redundancy

* render session messages directly

* fix streaming bug on UI

* merge conflict resolution

* remove tutorial agent set up that is not currently needed

* remove package json

* rebuilt package json and remove /api/chat and /api/terminal that were mock/test

* delete dummy terminal websocket server

* Add tutorial structure rules and enhance tutorial API responses

- Introduced a new markdown file defining the structure and authoring guidelines for tutorials.
- Updated the tutorial API to return detailed step data, including snippets and metadata.
- Refactored tutorial step fetching logic to improve error handling and data retrieval.
- Implemented a new `<CodeFromFiles />` component for rendering code snippets from files.
- Enhanced chat message rendering to support tutorial content and snippets.

* chore(lockfile): sync package-lock with package.json to fix npm ci (add data-uri-to-buffer@2.0.2)

* sync package

* fix build error

* synchronize name of totalSteps

* fix linter failure

* cleaning up debug log and unused modules

* remove debug log from ChatMessage

* remove dummy tutorial content

* simplify code pieces

* add total steps

* remove unused components

* removing unused module

* Remove integration md

* replace div with interactable button

* remove unused import

* toIsoString formatting

* gracefully handle setKVValue error

* improve tool param wording

* remove unused websocket server

* add user tutorial status

* add tutorial state management

* refactor tutorial state route handlers to improve JSON body parsing and error handling

* update ChatMessage component to format code snippets with labels above code fences for improved readability

* remove python tutorial mdx

* Fix CodeRabbit issues: implement validation middleware and improve error handling (#283)

* Fix CodeRabbit issues: implement validation middleware, fix config imports, handle KV errors

- Add comprehensive body validation middleware for /sessions, /tutorials, /users endpoints
- Fix config import issues by moving to static imports at top of files
- Add proper KV persistence error handling with success checks
- Validate tutorialId as string and prevent path traversal attacks
- Fix implicit any types on request body parameters
- Replace parseInt with Number.parseInt for consistency
- Add proper 400 error responses with detailed validation messages
- Use existing types from app/chat/types.ts for validation
- Prevent TypeError when no progress exists by handling 404 responses gracefully

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Fix TypeScript compilation errors in validation middleware

- Add SessionMessageValidationResult and SessionMessageOnlyValidationResult types
- Fix validation function return type mismatches in session routes
- Add proper bounds checking for stepIndex in tutorial route
- Ensure all validation errors use consistent error structure
- Generate missing docs.json file to resolve import errors

All TypeScript compilation errors resolved, ready for CI

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation middleware to be generic and scalable

- Add FieldSchema and ValidationSchema interfaces for declarative validation
- Implement validateField and validateObject for schema-based validation
- Add overloaded parseAndValidateJSON to accept both validators and schemas
- Maintain backward compatibility with existing validation functions
- Fix TypeScript compilation errors with explicit Message type annotations
- Enable reusable validation for current and future types

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation to use Zod schemas and eliminate duplicate source of truth

- Replace TypeScript interfaces with Zod schemas in app/chat/types.ts
- Derive types using z.infer<typeof Schema> instead of separate interfaces
- Update validation middleware to use Zod's safeParse and error handling
- Maintain all existing validation behavior while using industry-standard Zod
- Fix TypeScript compilation errors and import issues
- All API endpoints now use consistent Zod-based validation

This eliminates the duplicate source of truth between validation schemas and TypeScript interfaces, making the codebase more maintainable and following modern best practices.

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration for messages API endpoint

- Replace custom validation logic with SessionMessageRequestSchema
- Simplify validation code by using Zod's built-in validation
- Maintain all existing functionality while using industry-standard validation

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration: remove redundant interfaces and convert utility functions

- Remove unused SessionMessageValidationResult and SessionMessageOnlyValidationResult interfaces
- Convert validateStepNumber and validateTutorialId to use Zod schemas internally
- Add StepNumberSchema and TutorialIdSchema for consistent validation
- Maintain backward compatibility with existing function signatures
- Complete elimination of duplicate source of truth between validation and types
- All validation now uses Zod schemas as single source of truth

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* delete lib/validation/types.ts unused module

* defensively check tutorials state

* update tools description and enhance the path checking

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: srith@agentuity.com <rithsenghorn@gmail.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>

* fix typo

* clean up

* small fixes

* revert css

* remove tutorial

* remove Tutorial page

* remove outdated readme

* remove unnecessary dependencies

* remove debug logging

* example of how tutorial is structured

* Revert "example of how tutorial is structured"

This reverts commit 6d70c4e.

* move helper out of the POST body

---------

Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>
Co-authored-by: Seng Rith <50646727+senghorn@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
devin-ai-integration bot added a commit that referenced this pull request Sep 17, 2025
* add totalChunks to metadata for tracing

* improve RAG retrieval process

* POC UI for chat based documentation

* update Start / Continue course

* expand text

* fix scrollbar problem and chat input resizing

* adding progress tracker

* center the progress bar

* testing out new terminal component and websocket servert

* fix terminal issue not staying on

* fix weird terminal display

* fix self is not defined error

* remove unnecessary terminal message

* typo

* fix weird flow

* remove duplicated butotn

* playing with coding web server

* remove websocket server

* creating api for tutorials

* fix interface

* modify tutorials workflow -- vibecoded

* dummy demo code execution api next.js

* New pulse agent using response api tools calling

* re-build the entire Pulse agent with new design

* adding tutorial step workflow

* simplify tutorial reader to have consistent api

* cleaning up some more steps

* breaking frontend to smaller components;

* link doc-qa to pulse agent

* removing unused import

* fix chat input box and have split pane for code editor

* enhancing file display

* simplify chat interface -- removing unnecessary code block displays

* add editor close button

* make side bar icons smaller

* implement chunk streaming structure

* clean up some items

* Revert "Implement Copy Page Dropdown Functionality (#239)"

This reverts commit 5eb9f16.

* fix tutorial step data handling issue

* add kv store api service

* remove unused interfaces

* remove unneeded conversation type

* reformat chat history

* add kv store api

* Simplify and refactor chat to connect with kv store

* add uuid package

* update example env

* share session context

* removing debug

* Adding session cache with SWR

* add .env to gitignore

* sync with main

* adjust chat message area width and dynamic spacing with sessionsbar

* add code editor content

* remove redundant comments

* display tutorial instruction content

* add user based session management

* enable split pane resize

* adding sessions cursor

* sessions paginated loading

* clean up env variables

* enabling direct llm access flag

* add title generation

* remove session update redundancy

* render session messages directly

* fix streaming bug on UI

* merge conflict resolution

* remove tutorial agent set up that is not currently needed

* remove package json

* rebuilt package json and remove /api/chat and /api/terminal that were mock/test

* delete dummy terminal websocket server

* Add tutorial structure rules and enhance tutorial API responses

- Introduced a new markdown file defining the structure and authoring guidelines for tutorials.
- Updated the tutorial API to return detailed step data, including snippets and metadata.
- Refactored tutorial step fetching logic to improve error handling and data retrieval.
- Implemented a new `<CodeFromFiles />` component for rendering code snippets from files.
- Enhanced chat message rendering to support tutorial content and snippets.

* chore(lockfile): sync package-lock with package.json to fix npm ci (add data-uri-to-buffer@2.0.2)

* sync package

* fix build error

* synchronize name of totalSteps

* fix linter failure

* cleaning up debug log and unused modules

* remove debug log from ChatMessage

* remove dummy tutorial content

* simplify code pieces

* add total steps

* remove unused components

* removing unused module

* Remove integration md

* replace div with interactable button

* remove unused import

* toIsoString formatting

* gracefully handle setKVValue error

* improve tool param wording

* remove unused websocket server

* add user tutorial status

* add tutorial state management

* refactor tutorial state route handlers to improve JSON body parsing and error handling

* update ChatMessage component to format code snippets with labels above code fences for improved readability

* remove python tutorial mdx

* Fix CodeRabbit issues: implement validation middleware and improve error handling (#283)

* Fix CodeRabbit issues: implement validation middleware, fix config imports, handle KV errors

- Add comprehensive body validation middleware for /sessions, /tutorials, /users endpoints
- Fix config import issues by moving to static imports at top of files
- Add proper KV persistence error handling with success checks
- Validate tutorialId as string and prevent path traversal attacks
- Fix implicit any types on request body parameters
- Replace parseInt with Number.parseInt for consistency
- Add proper 400 error responses with detailed validation messages
- Use existing types from app/chat/types.ts for validation
- Prevent TypeError when no progress exists by handling 404 responses gracefully

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Fix TypeScript compilation errors in validation middleware

- Add SessionMessageValidationResult and SessionMessageOnlyValidationResult types
- Fix validation function return type mismatches in session routes
- Add proper bounds checking for stepIndex in tutorial route
- Ensure all validation errors use consistent error structure
- Generate missing docs.json file to resolve import errors

All TypeScript compilation errors resolved, ready for CI

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation middleware to be generic and scalable

- Add FieldSchema and ValidationSchema interfaces for declarative validation
- Implement validateField and validateObject for schema-based validation
- Add overloaded parseAndValidateJSON to accept both validators and schemas
- Maintain backward compatibility with existing validation functions
- Fix TypeScript compilation errors with explicit Message type annotations
- Enable reusable validation for current and future types

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation to use Zod schemas and eliminate duplicate source of truth

- Replace TypeScript interfaces with Zod schemas in app/chat/types.ts
- Derive types using z.infer<typeof Schema> instead of separate interfaces
- Update validation middleware to use Zod's safeParse and error handling
- Maintain all existing validation behavior while using industry-standard Zod
- Fix TypeScript compilation errors and import issues
- All API endpoints now use consistent Zod-based validation

This eliminates the duplicate source of truth between validation schemas and TypeScript interfaces, making the codebase more maintainable and following modern best practices.

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration for messages API endpoint

- Replace custom validation logic with SessionMessageRequestSchema
- Simplify validation code by using Zod's built-in validation
- Maintain all existing functionality while using industry-standard validation

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration: remove redundant interfaces and convert utility functions

- Remove unused SessionMessageValidationResult and SessionMessageOnlyValidationResult interfaces
- Convert validateStepNumber and validateTutorialId to use Zod schemas internally
- Add StepNumberSchema and TutorialIdSchema for consistent validation
- Maintain backward compatibility with existing function signatures
- Complete elimination of duplicate source of truth between validation and types
- All validation now uses Zod schemas as single source of truth

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* delete lib/validation/types.ts unused module

* defensively check tutorials state

* update tools description and enhance the path checking

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: srith@agentuity.com <rithsenghorn@gmail.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>

* fix typo

* clean up

* small fixes

* revert css

* remove tutorial

* remove Tutorial page

* remove outdated readme

* remove unnecessary dependencies

* remove debug logging

* example of how tutorial is structured

* Revert "example of how tutorial is structured"

This reverts commit 6d70c4e.

* move helper out of the POST body

---------

Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>
Co-authored-by: Seng Rith <50646727+senghorn@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
afterrburn added a commit that referenced this pull request Sep 17, 2025
* add totalChunks to metadata for tracing

* improve RAG retrieval process

* POC UI for chat based documentation

* update Start / Continue course

* expand text

* fix scrollbar problem and chat input resizing

* adding progress tracker

* center the progress bar

* testing out new terminal component and websocket servert

* fix terminal issue not staying on

* fix weird terminal display

* fix self is not defined error

* remove unnecessary terminal message

* typo

* fix weird flow

* remove duplicated butotn

* playing with coding web server

* remove websocket server

* creating api for tutorials

* fix interface

* modify tutorials workflow -- vibecoded

* dummy demo code execution api next.js

* New pulse agent using response api tools calling

* re-build the entire Pulse agent with new design

* adding tutorial step workflow

* simplify tutorial reader to have consistent api

* cleaning up some more steps

* breaking frontend to smaller components;

* link doc-qa to pulse agent

* removing unused import

* fix chat input box and have split pane for code editor

* enhancing file display

* simplify chat interface -- removing unnecessary code block displays

* add editor close button

* make side bar icons smaller

* implement chunk streaming structure

* clean up some items

* Revert "Implement Copy Page Dropdown Functionality (#239)"

This reverts commit 5eb9f16.

* fix tutorial step data handling issue

* add kv store api service

* remove unused interfaces

* remove unneeded conversation type

* reformat chat history

* add kv store api

* Simplify and refactor chat to connect with kv store

* add uuid package

* update example env

* share session context

* removing debug

* Adding session cache with SWR

* add .env to gitignore

* sync with main

* adjust chat message area width and dynamic spacing with sessionsbar

* add code editor content

* remove redundant comments

* display tutorial instruction content

* add user based session management

* enable split pane resize

* adding sessions cursor

* sessions paginated loading

* clean up env variables

* enabling direct llm access flag

* add title generation

* remove session update redundancy

* render session messages directly

* fix streaming bug on UI

* merge conflict resolution

* remove tutorial agent set up that is not currently needed

* remove package json

* rebuilt package json and remove /api/chat and /api/terminal that were mock/test

* delete dummy terminal websocket server

* Add tutorial structure rules and enhance tutorial API responses

- Introduced a new markdown file defining the structure and authoring guidelines for tutorials.
- Updated the tutorial API to return detailed step data, including snippets and metadata.
- Refactored tutorial step fetching logic to improve error handling and data retrieval.
- Implemented a new `<CodeFromFiles />` component for rendering code snippets from files.
- Enhanced chat message rendering to support tutorial content and snippets.

* chore(lockfile): sync package-lock with package.json to fix npm ci (add data-uri-to-buffer@2.0.2)

* sync package

* fix build error

* synchronize name of totalSteps

* fix linter failure

* cleaning up debug log and unused modules

* remove debug log from ChatMessage

* remove dummy tutorial content

* simplify code pieces

* add total steps

* remove unused components

* removing unused module

* Remove integration md

* replace div with interactable button

* remove unused import

* toIsoString formatting

* gracefully handle setKVValue error

* improve tool param wording

* remove unused websocket server

* add user tutorial status

* add tutorial state management

* refactor tutorial state route handlers to improve JSON body parsing and error handling

* update ChatMessage component to format code snippets with labels above code fences for improved readability

* remove python tutorial mdx

* Fix CodeRabbit issues: implement validation middleware and improve error handling (#283)

* Fix CodeRabbit issues: implement validation middleware, fix config imports, handle KV errors

- Add comprehensive body validation middleware for /sessions, /tutorials, /users endpoints
- Fix config import issues by moving to static imports at top of files
- Add proper KV persistence error handling with success checks
- Validate tutorialId as string and prevent path traversal attacks
- Fix implicit any types on request body parameters
- Replace parseInt with Number.parseInt for consistency
- Add proper 400 error responses with detailed validation messages
- Use existing types from app/chat/types.ts for validation
- Prevent TypeError when no progress exists by handling 404 responses gracefully

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Fix TypeScript compilation errors in validation middleware

- Add SessionMessageValidationResult and SessionMessageOnlyValidationResult types
- Fix validation function return type mismatches in session routes
- Add proper bounds checking for stepIndex in tutorial route
- Ensure all validation errors use consistent error structure
- Generate missing docs.json file to resolve import errors

All TypeScript compilation errors resolved, ready for CI

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation middleware to be generic and scalable

- Add FieldSchema and ValidationSchema interfaces for declarative validation
- Implement validateField and validateObject for schema-based validation
- Add overloaded parseAndValidateJSON to accept both validators and schemas
- Maintain backward compatibility with existing validation functions
- Fix TypeScript compilation errors with explicit Message type annotations
- Enable reusable validation for current and future types

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation to use Zod schemas and eliminate duplicate source of truth

- Replace TypeScript interfaces with Zod schemas in app/chat/types.ts
- Derive types using z.infer<typeof Schema> instead of separate interfaces
- Update validation middleware to use Zod's safeParse and error handling
- Maintain all existing validation behavior while using industry-standard Zod
- Fix TypeScript compilation errors and import issues
- All API endpoints now use consistent Zod-based validation

This eliminates the duplicate source of truth between validation schemas and TypeScript interfaces, making the codebase more maintainable and following modern best practices.

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration for messages API endpoint

- Replace custom validation logic with SessionMessageRequestSchema
- Simplify validation code by using Zod's built-in validation
- Maintain all existing functionality while using industry-standard validation

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration: remove redundant interfaces and convert utility functions

- Remove unused SessionMessageValidationResult and SessionMessageOnlyValidationResult interfaces
- Convert validateStepNumber and validateTutorialId to use Zod schemas internally
- Add StepNumberSchema and TutorialIdSchema for consistent validation
- Maintain backward compatibility with existing function signatures
- Complete elimination of duplicate source of truth between validation and types
- All validation now uses Zod schemas as single source of truth

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* delete lib/validation/types.ts unused module

* defensively check tutorials state

* update tools description and enhance the path checking

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: srith@agentuity.com <rithsenghorn@gmail.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>

* fix typo

* clean up

* small fixes

* revert css

* remove tutorial

* remove Tutorial page

* remove outdated readme

* remove unnecessary dependencies

* remove debug logging

* example of how tutorial is structured

* Revert "example of how tutorial is structured"

This reverts commit 6d70c4e.

* move helper out of the POST body

---------

Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>
Co-authored-by: Seng Rith <50646727+senghorn@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
afterrburn added a commit that referenced this pull request Sep 20, 2025
* Seng/chat prototype (#279)

* add totalChunks to metadata for tracing

* improve RAG retrieval process

* POC UI for chat based documentation

* update Start / Continue course

* expand text

* fix scrollbar problem and chat input resizing

* adding progress tracker

* center the progress bar

* testing out new terminal component and websocket servert

* fix terminal issue not staying on

* fix weird terminal display

* fix self is not defined error

* remove unnecessary terminal message

* typo

* fix weird flow

* remove duplicated butotn

* playing with coding web server

* remove websocket server

* creating api for tutorials

* fix interface

* modify tutorials workflow -- vibecoded

* dummy demo code execution api next.js

* New pulse agent using response api tools calling

* re-build the entire Pulse agent with new design

* adding tutorial step workflow

* simplify tutorial reader to have consistent api

* cleaning up some more steps

* breaking frontend to smaller components;

* link doc-qa to pulse agent

* removing unused import

* fix chat input box and have split pane for code editor

* enhancing file display

* simplify chat interface -- removing unnecessary code block displays

* add editor close button

* make side bar icons smaller

* implement chunk streaming structure

* clean up some items

* Revert "Implement Copy Page Dropdown Functionality (#239)"

This reverts commit 5eb9f16.

* fix tutorial step data handling issue

* add kv store api service

* remove unused interfaces

* remove unneeded conversation type

* reformat chat history

* add kv store api

* Simplify and refactor chat to connect with kv store

* add uuid package

* update example env

* share session context

* removing debug

* Adding session cache with SWR

* add .env to gitignore

* sync with main

* adjust chat message area width and dynamic spacing with sessionsbar

* add code editor content

* remove redundant comments

* display tutorial instruction content

* add user based session management

* enable split pane resize

* adding sessions cursor

* sessions paginated loading

* clean up env variables

* enabling direct llm access flag

* add title generation

* remove session update redundancy

* render session messages directly

* fix streaming bug on UI

* merge conflict resolution

* remove tutorial agent set up that is not currently needed

* remove package json

* rebuilt package json and remove /api/chat and /api/terminal that were mock/test

* delete dummy terminal websocket server

* Add tutorial structure rules and enhance tutorial API responses

- Introduced a new markdown file defining the structure and authoring guidelines for tutorials.
- Updated the tutorial API to return detailed step data, including snippets and metadata.
- Refactored tutorial step fetching logic to improve error handling and data retrieval.
- Implemented a new `<CodeFromFiles />` component for rendering code snippets from files.
- Enhanced chat message rendering to support tutorial content and snippets.

* chore(lockfile): sync package-lock with package.json to fix npm ci (add data-uri-to-buffer@2.0.2)

* sync package

* fix build error

* synchronize name of totalSteps

* fix linter failure

* cleaning up debug log and unused modules

* remove debug log from ChatMessage

* remove dummy tutorial content

* simplify code pieces

* add total steps

* remove unused components

* removing unused module

* Remove integration md

* replace div with interactable button

* remove unused import

* toIsoString formatting

* gracefully handle setKVValue error

* improve tool param wording

* remove unused websocket server

* add user tutorial status

* add tutorial state management

* refactor tutorial state route handlers to improve JSON body parsing and error handling

* update ChatMessage component to format code snippets with labels above code fences for improved readability

* remove python tutorial mdx

* Fix CodeRabbit issues: implement validation middleware and improve error handling (#283)

* Fix CodeRabbit issues: implement validation middleware, fix config imports, handle KV errors

- Add comprehensive body validation middleware for /sessions, /tutorials, /users endpoints
- Fix config import issues by moving to static imports at top of files
- Add proper KV persistence error handling with success checks
- Validate tutorialId as string and prevent path traversal attacks
- Fix implicit any types on request body parameters
- Replace parseInt with Number.parseInt for consistency
- Add proper 400 error responses with detailed validation messages
- Use existing types from app/chat/types.ts for validation
- Prevent TypeError when no progress exists by handling 404 responses gracefully

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Fix TypeScript compilation errors in validation middleware

- Add SessionMessageValidationResult and SessionMessageOnlyValidationResult types
- Fix validation function return type mismatches in session routes
- Add proper bounds checking for stepIndex in tutorial route
- Ensure all validation errors use consistent error structure
- Generate missing docs.json file to resolve import errors

All TypeScript compilation errors resolved, ready for CI

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation middleware to be generic and scalable

- Add FieldSchema and ValidationSchema interfaces for declarative validation
- Implement validateField and validateObject for schema-based validation
- Add overloaded parseAndValidateJSON to accept both validators and schemas
- Maintain backward compatibility with existing validation functions
- Fix TypeScript compilation errors with explicit Message type annotations
- Enable reusable validation for current and future types

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Refactor validation to use Zod schemas and eliminate duplicate source of truth

- Replace TypeScript interfaces with Zod schemas in app/chat/types.ts
- Derive types using z.infer<typeof Schema> instead of separate interfaces
- Update validation middleware to use Zod's safeParse and error handling
- Maintain all existing validation behavior while using industry-standard Zod
- Fix TypeScript compilation errors and import issues
- All API endpoints now use consistent Zod-based validation

This eliminates the duplicate source of truth between validation schemas and TypeScript interfaces, making the codebase more maintainable and following modern best practices.

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration for messages API endpoint

- Replace custom validation logic with SessionMessageRequestSchema
- Simplify validation code by using Zod's built-in validation
- Maintain all existing functionality while using industry-standard validation

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* Complete Zod migration: remove redundant interfaces and convert utility functions

- Remove unused SessionMessageValidationResult and SessionMessageOnlyValidationResult interfaces
- Convert validateStepNumber and validateTutorialId to use Zod schemas internally
- Add StepNumberSchema and TutorialIdSchema for consistent validation
- Maintain backward compatibility with existing function signatures
- Complete elimination of duplicate source of truth between validation and types
- All validation now uses Zod schemas as single source of truth

Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>

* delete lib/validation/types.ts unused module

* defensively check tutorials state

* update tools description and enhance the path checking

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: srith@agentuity.com <rithsenghorn@gmail.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>

* fix typo

* clean up

* small fixes

* revert css

* remove tutorial

* remove Tutorial page

* remove outdated readme

* remove unnecessary dependencies

* remove debug logging

* example of how tutorial is structured

* Revert "example of how tutorial is structured"

This reverts commit 6d70c4e.

* move helper out of the POST body

---------

Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>
Co-authored-by: Seng Rith <50646727+senghorn@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* remove unused component

* gracefully return empty array when tutorial does not exist

* cleanup agent-docs readme and bun

* move agent IDs to config since they are not secrets

* update agent url configs

* fix config issue

* fix env

---------

Signed-off-by: Seng Rith <50646727+afterrburn@users.noreply.github.com>
Co-authored-by: afterrburn <sun_rsh@outlook.com>
Co-authored-by: Seng Rith <50646727+senghorn@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant