-
Notifications
You must be signed in to change notification settings - Fork 1
Implement Copy Page Dropdown Functionality #239
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Create API endpoint for extracting page content as markdown - Add CopyPageDropdown component with Radix UI Popover - Integrate dropdown into DocsLayout header alongside search - Support copy to clipboard, view markdown, and external tool integrations - Install gray-matter dependency for MDX parsing - All functionality tested and confirmed working Co-Authored-By: Rick Blalock <rickblalock@mac.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
WalkthroughA new Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant DocsLayout
participant CopyPageDropdown
participant API (page-content)
participant FileSystem
User->>DocsLayout: Loads docs page
DocsLayout->>CopyPageDropdown: Renders dropdown
User->>CopyPageDropdown: Clicks dropdown action (e.g., Copy Markdown)
CopyPageDropdown->>API (page-content): GET /api/page-content?path=...
API (page-content)->>FileSystem: Read .mdx file(s)
FileSystem-->>API (page-content): Return file content
API (page-content)-->>CopyPageDropdown: Return JSON (content, title, description)
CopyPageDropdown-->>User: Perform action (copy, view, open in AI chat)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15 minutes Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ Finishing Touches🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Deploying with
|
Status | Name | Latest Commit | Preview URL | Updated (UTC) |
---|---|---|---|---|
✅ Deployment successful! View logs |
docs | 7a90f3b | Commit Preview URL Branch Preview URL |
Jul 31 2025, 01:30 PM |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Nitpick comments (1)
app/api/page-content/route.ts (1)
21-26
: Optimize file existence check.The current approach reads the entire file just to check if it exists, which is inefficient. Use
fs.access()
orfs.stat()
instead.- try { - await readFile(indexPath, 'utf-8'); - filePath = indexPath; - } catch { - filePath = directPath; - } + try { + await fs.access(indexPath); + filePath = indexPath; + } catch { + filePath = directPath; + }Don't forget to import
fs
fromfs/promises
.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.json
is excluded by!**/package-lock.json
📒 Files selected for processing (4)
app/(docs)/layout.tsx
(2 hunks)app/api/page-content/route.ts
(1 hunks)components/CopyPageDropdown.tsx
(1 hunks)package.json
(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
app/(docs)/layout.tsx (1)
Learnt from: CR
PR: agentuity/docs#0
File: .cursor/rules/mdx.mdc:0-0
Timestamp: 2025-07-01T12:36:29.712Z
Learning: This is MDX so some react components can be used
components/CopyPageDropdown.tsx (1)
Learnt from: CR
PR: agentuity/docs#0
File: .cursor/rules/mdx.mdc:0-0
Timestamp: 2025-07-01T12:36:29.712Z
Learning: This is MDX so some react components can be used
⏰ 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 (5)
app/(docs)/layout.tsx (2)
6-6
: Clean import of the new component.The import path looks correct and follows the project's import patterns.
16-22
: Well-integrated component placement.The
CopyPageDropdown
is appropriately placed alongside other UI controls in the large screen layout. The responsive design withmax-md:hidden
ensures it only appears on larger screens where there's sufficient space.app/api/page-content/route.ts (1)
37-40
: Appropriate error handling.The error handling provides generic responses without exposing internal details, which is good for security. Console logging helps with debugging.
components/CopyPageDropdown.tsx (2)
83-96
: Good accessibility implementation.The component uses proper ARIA labels and Radix UI primitives for accessibility. The popover implementation follows best practices.
98-130
: Well-implemented loading states.The buttons are properly disabled during loading operations, providing good user feedback and preventing multiple simultaneous requests.
const { searchParams } = new URL(request.url); | ||
const path = searchParams.get('path'); | ||
|
||
if (!path) { | ||
return new Response('Path parameter required', { status: 400 }); | ||
} | ||
|
||
let filePath; | ||
const basePath = join(process.cwd(), 'content'); | ||
|
||
const indexPath = join(basePath, path, 'index.mdx'); | ||
const directPath = join(basePath, `${path}.mdx`); | ||
|
||
try { | ||
await readFile(indexPath, 'utf-8'); | ||
filePath = indexPath; | ||
} catch { | ||
filePath = directPath; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical security vulnerability: Path traversal attack possible.
The path
parameter is used directly in file path construction without validation, allowing potential path traversal attacks. An attacker could use paths like ../../../etc/passwd
to access files outside the content directory.
Add path validation to prevent directory traversal:
const path = searchParams.get('path');
if (!path) {
return new Response('Path parameter required', { status: 400 });
}
+ // Validate path to prevent directory traversal
+ if (path.includes('..') || path.includes('/') || path.startsWith('.')) {
+ return new Response('Invalid path parameter', { status: 400 });
+ }
let filePath;
const basePath = join(process.cwd(), 'content');
Also consider using path.resolve()
and checking if the resolved path is within the content directory.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const { searchParams } = new URL(request.url); | |
const path = searchParams.get('path'); | |
if (!path) { | |
return new Response('Path parameter required', { status: 400 }); | |
} | |
let filePath; | |
const basePath = join(process.cwd(), 'content'); | |
const indexPath = join(basePath, path, 'index.mdx'); | |
const directPath = join(basePath, `${path}.mdx`); | |
try { | |
await readFile(indexPath, 'utf-8'); | |
filePath = indexPath; | |
} catch { | |
filePath = directPath; | |
} | |
const { searchParams } = new URL(request.url); | |
const path = searchParams.get('path'); | |
if (!path) { | |
return new Response('Path parameter required', { status: 400 }); | |
} | |
// Validate path to prevent directory traversal | |
if (path.includes('..') || path.includes('/') || path.startsWith('.')) { | |
return new Response('Invalid path parameter', { status: 400 }); | |
} | |
let filePath; | |
const basePath = join(process.cwd(), 'content'); | |
const indexPath = join(basePath, path, 'index.mdx'); | |
const directPath = join(basePath, `${path}.mdx`); | |
try { | |
await readFile(indexPath, 'utf-8'); | |
filePath = indexPath; | |
} catch { | |
filePath = directPath; | |
} |
🤖 Prompt for AI Agents
In app/api/page-content/route.ts around lines 8 to 26, the path parameter from
the URL is used directly to construct file paths, which allows path traversal
attacks. To fix this, validate and sanitize the path parameter by resolving it
with path.resolve() and then verify that the resolved path is within the
intended content directory. If the resolved path escapes the content directory,
reject the request with an error. This prevents attackers from accessing files
outside the allowed directory.
} catch (error) { | ||
console.error('Error fetching page content:', error); | ||
return null; | ||
} finally { | ||
setIsLoading(false); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve user feedback for errors.
Currently, errors are only logged to the console. Users don't receive any feedback when operations fail, which creates a poor user experience.
Consider adding user-visible error states or toast notifications to inform users when operations fail.
🤖 Prompt for AI Agents
In components/CopyPageDropdown.tsx around lines 29 to 34, the catch block only
logs errors to the console without informing users. Enhance user experience by
adding a user-visible error notification, such as setting an error state to
display a message in the UI or triggering a toast notification, so users are
aware when the fetch operation fails.
- Update ChatGPT URL to use chatgpt.com domain for reliable ?q= support - Update Claude URL to use /new path instead of /chat - Add URL.revokeObjectURL cleanup to prevent memory leaks - Extract duplicate markdown formatting logic into helper function Addresses CodeRabbit feedback from PR #239 Co-Authored-By: Rick Blalock <rickblalock@mac.com>
- Return 404 for non-existent pages instead of 500 internal server error - Add path validation to prevent directory traversal attacks - Improve error handling with proper nested try-catch blocks - Resolves internal server errors reported in network tab Co-Authored-By: Rick Blalock <rickblalock@mac.com>
- Wrap validateEnv() in try-catch to prevent build failures - Show warnings instead of errors during build time - Maintains runtime validation while allowing successful deployment Co-Authored-By: Rick Blalock <rickblalock@mac.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
app/layout.tsx
(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
app/layout.tsx (1)
Learnt from: CR
PR: agentuity/docs#0
File: agent-docs/.cursor/rules/sdk.mdc:0-0
Timestamp: 2025-07-01T12:36:46.237Z
Learning: Applies to agent-docs/src/agents/**/*.ts : Use structured error handling with try/catch blocks
🧬 Code Graph Analysis (1)
app/layout.tsx (1)
lib/env.ts (1)
validateEnv
(36-51)
⏰ 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
- Remove unused filePath variable from API endpoint - Resolves ESLint @typescript-eslint/no-unused-vars error - Allows Workers build to complete successfully Co-Authored-By: Rick Blalock <rickblalock@mac.com>
…ager.devin.ai/proxy/github.com/agentuity/docs into devin/1752665854-copy-page-dropdown - Integrate remote updates to app/layout.tsx - Keep local linting fix for unused filePath variable erges an updated upstream into a topic branch.
- validateEnv() already handles errors internally and returns boolean - Use boolean return value instead of redundant try-catch - Addresses CodeRabbit review comment about unnecessary double error handling Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
…com/agentuity/docs into devin/1752665854-copy-page-dropdown
- Add package overrides to force gray-matter to use js-yaml@^3.14.1 - Addresses CodeRabbit security concern about unmaintained dependencies - Maintains compatibility while using latest secure js-yaml 3.x version - Applied to both main package.json and agent-docs/package.json Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
This reverts commit 5eb9f16.
- Replace runtime file system access with pre-built docs.json approach - Follow same pattern as llms.txt route for Cloudflare Workers compatibility - Maintain same API interface for frontend component - Add path matching logic for both direct and index.mdx patterns Fixes #239 production 404 errors by using build-time generated JSON instead of Node.js fs operations that don't work in Cloudflare Workers. Co-Authored-By: srith@agentuity.com <rithsenghorn@gmail.com>
- Replace runtime file system access with pre-built docs.json approach - Follow same pattern as llms.txt route for Cloudflare Workers compatibility - Maintain same API interface for frontend component - Add path matching logic for both direct and index.mdx patterns Fixes #239 production 404 errors by using build-time generated JSON instead of Node.js fs operations that don't work in Cloudflare Workers. Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: srith@agentuity.com <rithsenghorn@gmail.com>
This reverts commit 5eb9f16.
* 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>
* 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>
* 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>
* 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>
Remove Unnecessary Try-Catch Wrapper Around Environment Validation
Summary
Addressed CodeRabbit review comment by removing redundant try-catch wrapper around
validateEnv()
call inapp/layout.tsx
. ThevalidateEnv()
function already handles errors internally and returns a boolean value, making the outer try-catch unreachable dead code. The change replaces the redundant error handling with proper consumption of the boolean return value for cleaner, more maintainable code.Key Change:
validateEnv()
catches errors internallyvalidateEnv()
boolean return value for proper error handlingReview & Testing Checklist for Human
Recommended test plan:
Diagram
Notes
validateEnv()
already has comprehensive error handling internally and returns a boolean, making the outer try-catch redundantLink to Devin run: https://app.devin.ai/sessions/6ef9662401374613bcfe0e6019a73bd6
Requested by: srith@agentuity.com
Summary by CodeRabbit