Skip to content

chore: update dependencies and refactor workflow stages#55

Merged
ssdeanx merged 1 commit intomainfrom
develop
Dec 14, 2025
Merged

chore: update dependencies and refactor workflow stages#55
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Copy Markdown
Owner

@ssdeanx ssdeanx commented Dec 14, 2025

  • Added eslint-plugin-react-hooks and eslint-plugin-react-refresh to package.json for improved linting support.
  • Refactored document-processing-workflow.ts:
    • Updated stage identifiers from "documentProcessingAgent" to "convert-pdf-to-markdown" for clarity.
    • Changed error handling to use "data-tool-progress" type instead of "data-workflow-step-error".
  • Refactored repo-ingestion-workflow.ts:
    • Introduced type guards for result validation to improve error handling.
    • Added embeddingModel and embeddingBatchSize parameters to the mdocumentChunker.execute call.
  • Refactored research-synthesis-workflow.ts:
    • Updated stage identifiers to be more descriptive (e.g., "research-topic-item", "synthesize-research").
    • Changed error handling to use "data-tool-progress" type.
  • Refactored stock-analysis-workflow.ts:
    • Updated stage identifiers to be more descriptive (e.g., "fetch-stock-data", "get-company-news", "run-analysis", "generate-report").
    • Changed error handling to use "data-tool-progress" type.

Summary by Sourcery

Align workflow telemetry and error reporting across document processing, research synthesis, stock analysis, and repo ingestion, while tightening linting configuration and adding a small routing utility.

New Features:

  • Add a newThreadLink helper to generate chat thread URLs with unique IDs.

Enhancements:

  • Standardize workflow progress and error events to use descriptive stage identifiers and the data-tool-progress type across stock analysis, research synthesis, and document processing workflows.
  • Improve repo ingestion robustness by validating mdocumentChunker results with type guards and configuring embedding model and batch size.
  • Refine research workflow progress reporting with clearer stage names for topic research, synthesis, and report generation.

Build:

  • Extend ESLint flat config with React Hooks and React Refresh plugins, browser globals, and global ignore patterns for build output and dependencies.

Chores:

  • Add React-related ESLint plugins and their dependencies to package.json.

- Added `eslint-plugin-react-hooks` and `eslint-plugin-react-refresh` to package.json for improved linting support.
- Refactored `document-processing-workflow.ts`:
  - Updated stage identifiers from "documentProcessingAgent" to "convert-pdf-to-markdown" for clarity.
  - Changed error handling to use "data-tool-progress" type instead of "data-workflow-step-error".
- Refactored `repo-ingestion-workflow.ts`:
  - Introduced type guards for result validation to improve error handling.
  - Added `embeddingModel` and `embeddingBatchSize` parameters to the `mdocumentChunker.execute` call.
- Refactored `research-synthesis-workflow.ts`:
  - Updated stage identifiers to be more descriptive (e.g., "research-topic-item", "synthesize-research").
  - Changed error handling to use "data-tool-progress" type.
- Refactored `stock-analysis-workflow.ts`:
  - Updated stage identifiers to be more descriptive (e.g., "fetch-stock-data", "get-company-news", "run-analysis", "generate-report").
  - Changed error handling to use "data-tool-progress" type.
Copilot AI review requested due to automatic review settings December 14, 2025 09:26
@continue
Copy link
Copy Markdown

continue Bot commented Dec 14, 2025

All Green - Keep your PRs mergeable

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts

@github-actions
Copy link
Copy Markdown

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 14, 2025

Summary by CodeRabbit

  • New Features

    • Added utility function for generating unique new chat thread URLs
    • Enhanced workflow progress tracking with standardized stage identification across all workflows
  • Bug Fixes

    • Improved error handling and progress reporting in document processing workflows
    • Standardized progress messaging format across research and analysis workflows
  • Chores

    • Updated ESLint configuration with React-specific linting plugins
    • Added new development dependencies

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

The PR introduces ESLint plugin configurations for React Hooks and Refresh, adds a new utility function for generating thread links with UUIDs, and standardizes workflow progress messaging by replacing generic stage indicators with step-specific names and updating payload types to use data-tool-progress. It also adds embedding configuration parameters to document chunking.

Changes

Cohort / File(s) Change Summary
ESLint Configuration
eslint.config.js, package.json
Added imports for globals, eslint-plugin-react-hooks, eslint-plugin-react-refresh, and globalIgnores; configured recommended React Hooks settings and React Refresh next config; added browser globals to TypeScript parser; included globalIgnores for dist and node_modules directories; added corresponding dependencies in package.json.
Utility Function
lib/utils.ts
Added new newThreadLink() function that generates unique URL paths combining rootPath, agentId, and a UUID; imported uuid from @lukeed/uuid.
Workflow Progress Standardization
src/mastra/workflows/document-processing-workflow.ts, src/mastra/workflows/research-synthesis-workflow.ts, src/mastra/workflows/stock-analysis-workflow.ts
Replaced generic stage indicators (e.g., "documentProcessingAgent", "workflow", "researchAgent") with step-specific stage names across progress updates; changed error payload types from data-workflow-step-error to data-tool-progress; added status: "done" to error payloads; replaced stepId references with stage field.
Repo Ingestion Workflow Refactoring
src/mastra/workflows/repo-ingestion-workflow.ts
Refactored result handling to use isSuccessResult and isErrorObject type guards; added embeddingModel ('google/gemini-embedding-001') and embeddingBatchSize (50) parameters to mdocumentChunker.execute; wrapped conditional source expression with parentheses for clarity.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas requiring extra attention:
    • Verification that the new newThreadLink() UUID generation integrates correctly with existing thread creation logic
    • Confirmation that embedding configuration parameters (model name and batch size) are compatible with the document chunking system
    • Cross-verification of consistent stage naming conventions across all workflow files to ensure downstream consumers of progress events handle the new stage identifiers correctly
    • Validation that changing from data-workflow-step-error to data-tool-progress does not break error handling or logging in consuming code

Possibly related PRs

Suggested reviewers

  • sourcery-ai

🐰 Hops through the ESLint configs so neat,
Stage names now specific, the progress beats repeat,
UUID threads hopping with each brand new start,
React Hooks and embeddings, a well-crafted art!
The workflows sing clearer, data flows with care.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title accurately reflects the main changes: dependency updates (ESLint plugins) and workflow stage refactoring across multiple files.
Description check ✅ Passed The description comprehensively covers all major changes including dependency additions, workflow refactoring details, and the new utility function.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @ssdeanx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request primarily focuses on improving code quality, consistency, and robustness across several workflow files and the ESLint configuration. It introduces new linting plugins for React, standardizes workflow stage naming for better clarity, and refines error reporting mechanisms. Additionally, the repository ingestion process gains more precise control over embedding generation and enhanced result validation.

Highlights

  • Dependency Updates: Added eslint-plugin-react-hooks and eslint-plugin-react-refresh to package.json and configured them in eslint.config.js to enhance linting capabilities for React projects.
  • Workflow Stage Refactoring: Refactored stage identifiers across document-processing-workflow.ts, research-synthesis-workflow.ts, and stock-analysis-workflow.ts to use more descriptive and consistent names (e.g., 'convert-pdf-to-markdown', 'research-topic-item', 'fetch-stock-data').
  • Standardized Error Handling: Unified error handling in document-processing-workflow.ts, research-synthesis-workflow.ts, and stock-analysis-workflow.ts by consistently using the data-tool-progress type for error messages, including status: 'done' and the specific stage.
  • Repo Ingestion Enhancements: Improved the repo-ingestion-workflow.ts by introducing type guards for more robust result validation and adding embeddingModel and embeddingBatchSize parameters to the document chunking process.
  • New Utility Function: Added a newThreadLink utility function in lib/utils.ts to generate unique chat thread links using UUIDs.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Dec 14, 2025

Reviewer's Guide

Updates linting configuration and dependency set while standardizing workflow telemetry and error reporting across multiple workflows, and improves repo ingestion chunking result handling plus adds a small URL helper.

Sequence diagram for repo ingestion chunking with result type guards

sequenceDiagram
    participant RepoIngestionWorkflow
    participant MDocumentChunker
    participant ZodValidator
    participant ErrorHandler

    RepoIngestionWorkflow->>MDocumentChunker: execute(documentContent, documentMetadata, chunkingStrategy, indexName, generateEmbeddings, embeddingModel, embeddingBatchSize, chunkSize, chunkOverlap, chunkSeparator, writer, requestContext)
    MDocumentChunker-->>RepoIngestionWorkflow: result

    alt result isSuccessResult
        RepoIngestionWorkflow->>RepoIngestionWorkflow: increment processedFiles
        RepoIngestionWorkflow->>RepoIngestionWorkflow: add result.chunkCount to totalChunks
    else result is ZodError
        RepoIngestionWorkflow->>ZodValidator: inspect result
        ZodValidator-->>RepoIngestionWorkflow: validationErrorMessage
        RepoIngestionWorkflow->>ErrorHandler: throw Error(validationErrorMessage)
    else result is Error
        RepoIngestionWorkflow->>ErrorHandler: throw result
    else result isErrorObject
        RepoIngestionWorkflow->>ErrorHandler: throw Error(errorStringOrUnknown)
    else unknown result shape
        RepoIngestionWorkflow->>ErrorHandler: throw Error(Unknown error in chunking)
    end

    Note over RepoIngestionWorkflow,ErrorHandler: Errors are caught by surrounding try catch and logged, preserving workflow behavior while improving type safety
Loading

Class diagram for updated repo ingestion and utilities

classDiagram
    class RepoIngestionWorkflow {
      +ingestStep(documentContent: string, filePath: string, githubRepo: boolean, strategy: string, writer: unknown, requestContext: unknown) Promise~void~
      -processedFiles: number
      -totalChunks: number
      -isSuccessResult(result: unknown) boolean
      -isErrorObject(result: unknown) boolean
    }

    class MDocumentChunker {
      +execute(documentContent: string, documentMetadata: object, chunkingStrategy: string, indexName: string, generateEmbeddings: boolean, embeddingModel: string, embeddingBatchSize: number, chunkSize: number, chunkOverlap: number, chunkSeparator: string, writer: unknown, requestContext: unknown) Promise~ChunkResultUnion~
    }

    class ChunkResultSuccess {
      +success: true
      +chunkCount: number
    }

    class ChunkResultErrorObject {
      +error: unknown
    }

    class ZodError {
      +message: string
    }

    class Error {
      +message: string
    }

    class Utils {
      +cn(inputs: ClassValue[]) string
      +newThreadLink(rootPath: string, agentId: string) string
    }

    class UUID {
      +v4() string
    }

    RepoIngestionWorkflow --> MDocumentChunker : uses execute
    MDocumentChunker --> ChunkResultSuccess : may return
    MDocumentChunker --> ChunkResultErrorObject : may return
    MDocumentChunker --> ZodError : may throw
    RepoIngestionWorkflow --> ZodError : checks instance
    RepoIngestionWorkflow --> Error : throws on failure

    Utils ..> UUID : uses v4 for newThreadLink

    class ClassValue {
    }

    Utils --> ClassValue : cn parameter

    class ChunkResultUnion {
    }

    ChunkResultUnion <|-- ChunkResultSuccess
    ChunkResultUnion <|-- ChunkResultErrorObject
Loading

Flow diagram for standardized workflow tool progress telemetry

flowchart TD
    A[Start workflow step
    e.g. fetch-stock-data,
    research-topic-item,
    convert-pdf-to-markdown] --> B[Send writer.custom
    type data-tool-progress
    status in-progress
    stage step-specific
    message descriptive]

    B --> C[Execute core step logic
    e.g. call API,
    run AI model,
    process document]

    C --> D{Step succeeds?}

    D -- Yes --> E[Send writer.custom
    type data-tool-progress
    status done
    stage step-specific
    message completion]

    D -- No --> F[Catch error
    normalize to Error]

    F --> G[Send writer.custom
    type data-tool-progress
    status done
    stage step-specific
    error message]

    E --> H[End step
    logStepEnd
    finish span]
    G --> H
Loading

File-Level Changes

Change Details Files
Enhance ESLint configuration and dependencies for React and browser environments.
  • Import and configure globals, react-hooks, and react-refresh ESLint plugins in the flat config.
  • Add globalIgnores for build and dependency directories and declare browser globals.
  • Add eslint-plugin-react-hooks and eslint-plugin-react-refresh to package.json dependencies.
eslint.config.js
package.json
package-lock.json
Standardize document processing workflow progress and error reporting.
  • Rename convertPdfToMarkdown stage from a generic agent label to convert-pdf-to-markdown in progress events.
  • Emit completion events using stage instead of stepId for consistency.
  • Switch error events to use data-tool-progress with stage and status fields instead of data-workflow-step-error.
src/mastra/workflows/document-processing-workflow.ts
Improve repo ingestion workflow robustness when handling chunker results and embeddings.
  • Pass explicit embeddingModel and embeddingBatchSize options to mdocumentChunker.execute.
  • Introduce internal type guards to distinguish success and error result shapes from unknown results.
  • Refactor result handling branches to use the type guards and tighten error throwing behavior.
src/mastra/workflows/repo-ingestion-workflow.ts
Refine research synthesis workflow stage naming and error event format.
  • Set explicit stage identifiers for research-topic-item, synthesize-research, and generate-research-report progress events.
  • Adjust some status values (in-progress vs done) to better reflect step state transitions.
  • Replace data-workflow-step-error events with data-tool-progress, carrying stage, status, and error fields.
src/mastra/workflows/research-synthesis-workflow.ts
Refine stock analysis workflow telemetry, stages, and error reporting.
  • Update stage fields from workflow to descriptive per-step stage names in all progress events.
  • Normalize error reporting to data-tool-progress events with stage, status, and error fields instead of workflow-specific error types.
  • Minor formatting cleanup for OTEL span attribute setting and whitespace.
src/mastra/workflows/stock-analysis-workflow.ts
Add a helper to generate new chat thread links with UUIDs.
  • Import uuid v4 helper and expose a newThreadLink utility to build /{rootPath}/{agentId}/chat/{uuid}?new=true URLs.
lib/utils.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions
Copy link
Copy Markdown

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces valuable dependency updates for ESLint and performs a significant and consistent refactoring across multiple workflow files. The changes to use more descriptive stage identifiers and standardize the error and progress reporting mechanism are excellent improvements for clarity and maintainability. The introduction of type guards in repo-ingestion-workflow.ts also enhances type safety. Overall, this is a high-quality refactoring effort. I've found one minor area for improvement regarding configuration redundancy.

Comment thread eslint.config.js

export default [
{ ignores },
globalIgnores(["dist", "node_modules"]),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The use of globalIgnores here seems redundant. The ignores array defined on line 10 already includes patterns for dist/** and node_modules/**, and it's applied globally on line 52. To avoid redundancy and keep the configuration clean, you can remove this line.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • In the various data-tool-progress error paths (e.g., fetchStockDataStep, getCompanyNewsStep, runAnalysisStep, generateReportStep, synthesizeResearchStep, generateResearchReportStep, convertPdfToMarkdownStep), you’re setting status: 'done' even when reporting an error; consider using a dedicated error status or keeping status consistent with the non-error states so consumers can reliably distinguish failures.
  • In research-synthesis-workflow.ts, the initializeResearchStep still uses stage: 'researchAgent' while subsequent steps use the more descriptive per-step identifiers (e.g., research-topic-item, synthesize-research); you may want to align this stage name with the new naming convention for consistency.
  • The ESLint flat config currently applies globals.browser to all **/*.ts and **/*.tsx files; if you have Node/server-side TypeScript, consider splitting the config by directory or file pattern so that browser globals are only enabled for client-side code.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the various `data-tool-progress` error paths (e.g., `fetchStockDataStep`, `getCompanyNewsStep`, `runAnalysisStep`, `generateReportStep`, `synthesizeResearchStep`, `generateResearchReportStep`, `convertPdfToMarkdownStep`), you’re setting `status: 'done'` even when reporting an error; consider using a dedicated error status or keeping `status` consistent with the non-error states so consumers can reliably distinguish failures.
- In `research-synthesis-workflow.ts`, the `initializeResearchStep` still uses `stage: 'researchAgent'` while subsequent steps use the more descriptive per-step identifiers (e.g., `research-topic-item`, `synthesize-research`); you may want to align this stage name with the new naming convention for consistency.
- The ESLint flat config currently applies `globals.browser` to all `**/*.ts` and `**/*.tsx` files; if you have Node/server-side TypeScript, consider splitting the config by directory or file pattern so that browser globals are only enabled for client-side code.

## Individual Comments

### Comment 1
<location> `lib/utils.ts:8-12` </location>
<code_context>
 export function cn(...inputs: ClassValue[]) {
   return twMerge(clsx(inputs))
 }
+export function newThreadLink(
+  rootPath: string,
+  agentId: string,
+): `/${string}/${string}/chat/${string}?new=true` {
+  return `/${rootPath}/${agentId}/chat/${uuid()}?new=true`;
+}
</code_context>

<issue_to_address>
**suggestion:** Consider normalizing `rootPath` and `agentId` to avoid accidental double slashes in the generated URL.

If callers pass `rootPath` with or without a leading slash, or an `agentId` that already includes slashes, this helper can generate malformed URLs like `//agents//id/chat/...`. Normalizing inputs (e.g., trimming leading/trailing slashes) within this function would make it safer and more predictable to use.
</issue_to_address>

### Comment 2
<location> `eslint.config.js:63-65` </location>
<code_context>
         },
         languageOptions: {
             parser: tsparser,
+            globals: globals.browser,
             parserOptions: {
                 ecmaVersion: 2022,
</code_context>

<issue_to_address>
**issue (bug_risk):** Applying `globals.browser` to all `*.ts` / `*.tsx` files may hide issues in Node-only code.

Because this config applies `globals.browser` to all TS/TSX files, browser globals like `window` will appear valid even in server-side/Node-only modules, potentially hiding real bugs. Consider limiting `globals.browser` to known client/React files (e.g., narrower `files` patterns or a separate override) and using appropriate Node globals for backend code instead.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread lib/utils.ts
Comment on lines +8 to +12
export function newThreadLink(
rootPath: string,
agentId: string,
): `/${string}/${string}/chat/${string}?new=true` {
return `/${rootPath}/${agentId}/chat/${uuid()}?new=true`;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: Consider normalizing rootPath and agentId to avoid accidental double slashes in the generated URL.

If callers pass rootPath with or without a leading slash, or an agentId that already includes slashes, this helper can generate malformed URLs like //agents//id/chat/.... Normalizing inputs (e.g., trimming leading/trailing slashes) within this function would make it safer and more predictable to use.

Comment thread eslint.config.js
Comment on lines 63 to +65
languageOptions: {
parser: tsparser,
globals: globals.browser,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): Applying globals.browser to all *.ts / *.tsx files may hide issues in Node-only code.

Because this config applies globals.browser to all TS/TSX files, browser globals like window will appear valid even in server-side/Node-only modules, potentially hiding real bugs. Consider limiting globals.browser to known client/React files (e.g., narrower files patterns or a separate override) and using appropriate Node globals for backend code instead.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Dec 14, 2025

Greptile Overview

Greptile Summary

This PR refactors workflow progress reporting and adds ESLint plugins for React development. The workflow changes standardize stage identifiers and error handling patterns across multiple workflows.

Key Changes:

  • Added eslint-plugin-react-hooks and eslint-plugin-react-refresh to improve React linting
  • Standardized workflow progress events to use data-tool-progress type consistently
  • Updated stage identifiers from generic names like "workflow" to descriptive names like "fetch-stock-data", "research-topic-item"
  • Improved type safety in repo-ingestion-workflow.ts with type guard functions
  • Fixed typo in stock-analysis-workflow.ts ("data-workflow-p" → "data-tool-progress")

Issues Found:

  • lib/utils.ts imports @lukeed/uuid which is not in package.json - will cause runtime error
  • ESLint config has potentially invalid imports (globalIgnores from "eslint/config", reactRefresh.configs.next)
  • Redundant globalIgnores call in ESLint config
  • Error events set status: 'done' which may be semantically misleading (consider status: 'error')

Confidence Score: 3/5

  • This PR has one critical dependency issue that will cause runtime errors, plus several ESLint configuration concerns that need verification
  • Score reflects the missing @lukeed/uuid dependency which will break the application when newThreadLink is called, plus unverified ESLint imports that may cause linting to fail. The workflow refactoring itself is solid and improves consistency.
  • Pay close attention to lib/utils.ts (missing dependency) and eslint.config.js (unverified imports)

Important Files Changed

File Analysis

Filename Score Overview
eslint.config.js 3/5 Added React hooks and refresh plugins, globals import, and globalIgnores call - potential config issues
lib/utils.ts 2/5 Added newThreadLink function with @lukeed/uuid import - missing dependency in package.json
src/mastra/workflows/research-synthesis-workflow.ts 4/5 Updated stage identifiers and standardized error handling - error status set to 'done' which may be misleading
src/mastra/workflows/stock-analysis-workflow.ts 4/5 Updated stage identifiers and standardized error handling - error status set to 'done' which may be misleading

Sequence Diagram

sequenceDiagram
    participant Dev as Developer
    participant ESLint as ESLint Config
    participant Workflows as Workflow Files
    participant Utils as lib/utils.ts
    participant Deps as Dependencies

    Dev->>Deps: Add eslint-plugin-react-hooks
    Dev->>Deps: Add eslint-plugin-react-refresh
    Deps-->>ESLint: New plugins available
    
    Dev->>ESLint: Import react plugins
    Dev->>ESLint: Add globalIgnores import
    Dev->>ESLint: Configure flat config with plugins
    Note over ESLint: Added reactHooks.configs.flat.recommended<br/>Added reactRefresh.configs.next<br/>Added globals.browser
    
    Dev->>Workflows: Update document-processing-workflow.ts
    Note over Workflows: Changed stage IDs:<br/>"documentProcessingAgent" → "convert-pdf-to-markdown"<br/>Changed error type:<br/>"data-workflow-step-error" → "data-tool-progress"
    
    Dev->>Workflows: Update repo-ingestion-workflow.ts
    Note over Workflows: Added type guards for validation<br/>Added embeddingModel parameter<br/>Added embeddingBatchSize parameter
    
    Dev->>Workflows: Update research-synthesis-workflow.ts
    Note over Workflows: Updated stage IDs:<br/>"workflow" → "research-topic-item"<br/>"researchAgent" → descriptive stages<br/>Standardized error handling
    
    Dev->>Workflows: Update stock-analysis-workflow.ts
    Note over Workflows: Updated stage IDs:<br/>"workflow" → specific stages<br/>Fixed typo: "data-workflow-p" → "data-tool-progress"<br/>Standardized error handling
    
    Dev->>Utils: Add newThreadLink function
    Utils->>Deps: Import @lukeed/uuid
    Note over Utils,Deps: ⚠️ Missing dependency!<br/>@lukeed/uuid not in package.json
    
    Note over Dev: Workflow Progress Event Pattern:<br/>type: 'data-tool-progress'<br/>data: { status, message, stage }<br/>Error events use status: 'done'
Loading

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

Additional Comments (1)

  1. src/mastra/workflows/stock-analysis-workflow.ts, line 135-143 (link)

    style: Setting status: 'done' in error case may be misleading - consider status: 'error' to better indicate failure state

7 files reviewed, 6 comments

Edit Code Review Agent Settings | Greptile

Comment thread lib/utils.ts
@@ -1,6 +1,13 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
import { v4 as uuid } from "@lukeed/uuid";
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

syntax: Missing dependency: @lukeed/uuid is imported but not present in package.json

Suggested change
import { v4 as uuid } from "@lukeed/uuid";
import { v4 as uuid } from "uuid";
Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/utils.ts
Line: 3:3

Comment:
**syntax:** Missing dependency: `@lukeed/uuid` is imported but not present in `package.json`

```suggestion
import { v4 as uuid } from "uuid";
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 391 to 397
await writer?.custom({
type: 'data-workflow-step-error',
type: 'data-tool-progress',
data: {
stepId: 'synthesize-research',
stage: 'synthesize-research',
error: error instanceof Error ? error.message : 'Unknown error',
status: 'done',
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

style: Setting status: 'done' in error case may be misleading - consider status: 'error' to better indicate failure state

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/mastra/workflows/research-synthesis-workflow.ts
Line: 391:397

Comment:
**style:** Setting `status: 'done'` in error case may be misleading - consider `status: 'error'` to better indicate failure state

How can I resolve this? If you propose a fix, please make it concise.

Comment thread eslint.config.js
import tseslint from '@typescript-eslint/eslint-plugin'
import tsparser from '@typescript-eslint/parser'
import prettierConfig from 'eslint-config-prettier'
import { globalIgnores } from "eslint/config";
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

style: Verify that globalIgnores export exists in eslint/config - this import path may not be valid for ESLint

Prompt To Fix With AI
This is a comment left during a code review.
Path: eslint.config.js
Line: 8:8

Comment:
**style:** Verify that `globalIgnores` export exists in `eslint/config` - this import path may not be valid for ESLint

How can I resolve this? If you propose a fix, please make it concise.

Comment thread eslint.config.js

export default [
{ ignores },
globalIgnores(["dist", "node_modules"]),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

style: This globalIgnores call is redundant - dist and node_modules are already in the ignores array above (lines 14-15). Consider removing this line.

Prompt To Fix With AI
This is a comment left during a code review.
Path: eslint.config.js
Line: 53:53

Comment:
**style:** This `globalIgnores` call is redundant - `dist` and `node_modules` are already in the `ignores` array above (lines 14-15). Consider removing this line.

How can I resolve this? If you propose a fix, please make it concise.

Comment thread eslint.config.js
globalIgnores(["dist", "node_modules"]),
js.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.next,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

style: Verify that reactRefresh.configs.next exists - the standard config is typically reactRefresh.configs.recommended or a custom flat config object

Prompt To Fix With AI
This is a comment left during a code review.
Path: eslint.config.js
Line: 56:56

Comment:
**style:** Verify that `reactRefresh.configs.next` exists - the standard config is typically `reactRefresh.configs.recommended` or a custom flat config object

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown

@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: 7

Caution

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

⚠️ Outside diff range comments (4)
eslint.config.js (1)

63-70: Consider adding Node.js globals for server-side code.

Setting globals: globals.browser only provides browser globals. In a Next.js project with server components and API routes, Node.js globals like process may be needed. Consider combining both:

         languageOptions: {
             parser: tsparser,
-            globals: globals.browser,
+            globals: {
+                ...globals.browser,
+                ...globals.node,
+            },
             parserOptions: {
src/mastra/workflows/document-processing-workflow.ts (3)

237-244: Inconsistent error handling: still using data-workflow-step-error.

This step's error handler uses data-workflow-step-error with stepId, while convertPdfToMarkdownStep was updated to use data-tool-progress with stage. The PR objective is to standardize error handling, but this step wasn't updated.

Apply consistent error handling:

       await writer?.custom({
-        type: 'data-workflow-step-error',
+        type: 'data-tool-progress',
         data: {
-          stepId: 'load-document',
+          stage: 'load-document',
+          status: 'done',
           error: error instanceof Error ? error.message : 'Unknown error',
         },
         id: "load-document",
       });

The same inconsistency exists in indexChunksStep (lines 720-727).


219-227: Inconsistent payload field: stepId vs stage in success messages.

Success payloads use stepId here, but convertPdfToMarkdownStep (line 348) uses stage. For consistency with the error handling changes, consider standardizing all progress payloads to use stage.


405-413: Broken template literal in message string.

The message uses double quotes but contains template literal syntax ${inputData.content} which won't be interpolated. It also has a stray backtick and comma inside the string.

       await writer?.custom({
         type: 'data-tool-progress',
         data: {
           status: "done",
-          message: "Text passed through successfully ${inputData.content}`,",
+          message: `Text passed through successfully`,
           stepId: 'pass-text-through',
         },
         id: "pass-text-through",
       });

Note: Logging full inputData.content in progress messages could expose sensitive document data; consider omitting it or using a truncated preview.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf43c89 and 5d63f06.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • eslint.config.js (3 hunks)
  • lib/utils.ts (1 hunks)
  • package.json (2 hunks)
  • src/mastra/workflows/document-processing-workflow.ts (4 hunks)
  • src/mastra/workflows/repo-ingestion-workflow.ts (1 hunks)
  • src/mastra/workflows/research-synthesis-workflow.ts (16 hunks)
  • src/mastra/workflows/stock-analysis-workflow.ts (20 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

**/*.{js,jsx,ts,tsx}: Use next/dynamic for dynamic imports to load components only when needed, improving initial load time.
Use next/image component for automatic image optimization, including lazy loading and responsive images.
Use React.memo to prevent unnecessary re-renders of components.
Use the <Link prefetch> tag to prefetch pages that are likely to be visited.
Use getServerSideProps, getStaticProps, or server components for fetching data on the server-side.
Use SWR or React Query for client-side data fetching and caching.
Use CSS Modules, Styled Components, or Tailwind CSS for component-level styling. Prefer Tailwind CSS for rapid development.
Use React Context, Zustand, Jotai, or Recoil for managing global state. Avoid Redux unless necessary.
Use react-hook-form for managing forms and validation.
Only fetch the data that is needed by the component to avoid over-fetching.
Avoid long-running synchronous operations in the main thread to prevent blocking.
Always use setState or hooks to update state instead of mutating state directly.
Include a complete dependency array in useEffect hooks to prevent unexpected behavior.
Avoid writing server-side code in client components to prevent exposing secrets or causing unexpected behavior.
Use try...catch blocks for handling errors in asynchronous operations.
Implement error boundary components using getDerivedStateFromError or componentDidCatch lifecycle methods.
Sanitize user input to prevent Cross-Site Scripting (XSS) attacks. Be especially careful when rendering HTML directly from user input.
Store authentication tokens in HTTP-only cookies or local storage securely.
Implement role-based access control to restrict access to sensitive resources.
Clean up event listeners and timers in useEffect hooks to avoid memory leaks.
Only update state when necessary to reduce the number of re-renders and improve performance.
Use immutable data structures and avoid mutating data directly to prevent unexpected...

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
  • eslint.config.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

Use parameterized queries or an ORM to prevent SQL injection attacks.

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
  • eslint.config.js
**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}: Write code that speaks for itself. Comment only when necessary to explain WHY, not WHAT. Avoid obvious comments that state what the code literally does.
Avoid redundant comments that simply repeat what the code is doing
Keep comments accurate and up-to-date with code changes. Remove or update outdated comments that no longer match the implementation.
Write comments for complex business logic that explain the WHY behind specific calculations or business rules
Document non-obvious algorithms with comments explaining the algorithm choice and its reasoning
Add comments explaining what regex patterns match, especially for complex patterns
Document API constraints, rate limits, gotchas, and external dependencies with explanatory comments
Avoid commenting out dead code. Use version control instead of maintaining commented code blocks.
Do not maintain code change history or modification logs as comments. Rely on git history and commit messages instead.
Avoid decorative divider comments (e.g., lines of equals signs or asterisks) for section separation
Ensure comments are placed appropriately above or adjacent to the code they describe
Write comments using proper grammar, spelling, and professional language
Prefer self-documenting code with clear variable/function names over adding comments to explain unclear code

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
  • eslint.config.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx}: Document public APIs with TSDoc/JSDoc comments including parameter descriptions, return types, examples, and thrown exceptions
Add TSDoc comments to configuration constants and environment variables explaining their source, reasoning, or constraints
Use TSDoc annotation tags (TODO, FIXME, HACK, NOTE, WARNING, PERF, SECURITY, BUG, REFACTOR, DEPRECATED) to mark special comments
Include file headers with @fileoverview, @author, @copyright, and @license tags to document file purpose and ownership
Document function parameters with @param tags, return values with @returns tags, and exceptions with @throws tags in TSDoc comments
Use @see tags in TSDoc comments to reference related functions, methods, or documentation
Include @example tags in public API documentation with code examples showing typical usage

**/*.{ts,tsx,js,jsx}: Use Mastra mcp tools (#mastradocs, #mastraChanges, #mastraexamples, #mastraBlog) for Mastra framework development to stay updated with latest features and best practices
When working with Next.js projects, always utilize the next-devtools-mcp server for all Next.js related queries

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
  • eslint.config.js
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx}: Document interface and type definitions with TSDoc comments explaining their purpose and usage context
Document interface properties with /** */ comments explaining each field's purpose and constraints
Document generic type parameters with @template tags explaining what each type parameter represents
Use type guards with comments explaining the runtime validation logic being performed
Document advanced/complex TypeScript types with explanatory comments about their purpose and use cases

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
**/*.{css,tsx,ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use Tailwind CSS 4 with oklch color variables for styling

Files:

  • lib/utils.ts
  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
src/mastra/**/*

📄 CodeRabbit inference engine (src/AGENTS.md)

mastra modules can import from utils, but must not import from app or cli (except types)

Files:

  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
src/mastra/workflows/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use Mastra DSL for multi-step workflow definitions in src/mastra/workflows

src/mastra/workflows/**/*.ts: Define workflows using Mastra DSL patterns with proper createWorkflow and createStep from @mastra/core/workflows
Use tools and agents as building blocks in workflows; prefer composition over duplication
Define input and output schemas for each step using Zod schema validation
Implement streaming support by piping agent responses to the step writer using .pipeTo(writer) for text chunk streaming
Use .then() for sequential workflow steps
Use .parallel() for concurrent multi-step execution (e.g., fetching from multiple APIs simultaneously)
Use .branch() for conditional logic based on input data conditions
Use .dowhile() for iterative refinement loops with conditional exit criteria
Use .foreach() for concurrent iteration over collections
Use suspend() and resume() for human-in-the-loop approval workflows
Call .commit() at the end of workflow definitions to finalize the workflow
Use custom writer events with types like 'data-tool-progress' to stream step progress and status updates

Add workflows under src/mastra/workflows to orchestrate multi-step flows

Files:

  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
src/mastra/{tools,agents,workflows}/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use Zod schemas for strict input/output validation in tools, agents, and workflows

Files:

  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.ts
src/mastra/{tools,workflows}/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Use RequestContext (per-request) or agent-specific runtime context types (e.g. EditorRuntimeContext) to enforce access control in tools and workflows

Files:

  • src/mastra/workflows/document-processing-workflow.ts
  • src/mastra/workflows/stock-analysis-workflow.ts
  • src/mastra/workflows/repo-ingestion-workflow.ts
  • src/mastra/workflows/research-synthesis-workflow.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). (5)
  • GitHub Check: Sourcery review
  • GitHub Check: CodeQL analysis (javascript-typescript)
  • GitHub Check: Agent
  • GitHub Check: Codacy Security Scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
src/mastra/workflows/repo-ingestion-workflow.ts (1)

191-209: Well-structured type guards for result validation.

The type guards isSuccessResult and isErrorObject provide good runtime type narrowing. The error handling cascade (ZodError → Error → error object → unknown) is thorough.

Minor suggestion: The isSuccessResult guard could be slightly more defensive by also checking that r is not an array:

const isSuccessResult = (r: unknown): r is { success: true; chunkCount?: number } =>
  typeof r === 'object' && r !== null && !Array.isArray(r) && 'success' in r && (r as { success: unknown }).success === true;
src/mastra/workflows/stock-analysis-workflow.ts (1)

135-143: Good standardization of error handling to data-tool-progress.

The error payload now correctly uses data-tool-progress type with stage and status: 'done' fields, consistent with the PR's objective to standardize workflow progress messaging.

src/mastra/workflows/research-synthesis-workflow.ts (1)

391-399: Good: Error handling standardized to data-tool-progress.

The error handler correctly uses data-tool-progress with stage and status: 'done' fields, maintaining consistency with the updated workflow messaging pattern.

Comment thread eslint.config.js
Comment on lines 52 to +53
{ ignores },
globalIgnores(["dist", "node_modules"]),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Remove redundant globalIgnores call.

The globalIgnores(["dist", "node_modules"]) duplicates entries already present in the ignores array (lines 13-14: 'node_modules/**' and 'dist/**'). This redundancy adds no value and may cause confusion.

     { ignores },
-    globalIgnores(["dist", "node_modules"]),
     js.configs.recommended,
📝 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.

Suggested change
{ ignores },
globalIgnores(["dist", "node_modules"]),
{ ignores },
js.configs.recommended,
🤖 Prompt for AI Agents
In eslint.config.js around lines 52 to 53, remove the redundant
globalIgnores(["dist", "node_modules"]) call because those patterns are already
present in the ignores array (lines ~13-14 as 'node_modules/**' and 'dist/**');
simply delete the globalIgnores(...) entry so ignores are defined in a single
place to avoid duplication and confusion.

Comment thread lib/utils.ts
Comment on lines +8 to +13
export function newThreadLink(
rootPath: string,
agentId: string,
): `/${string}/${string}/chat/${string}?new=true` {
return `/${rootPath}/${agentId}/chat/${uuid()}?new=true`;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Add TSDoc documentation and consider input validation.

The function lacks TSDoc documentation. Per coding guidelines, public APIs should include parameter descriptions, return types, and examples. Additionally, consider validating/sanitizing rootPath and agentId to prevent malformed URLs (e.g., if they contain slashes or special characters).

+/**
+ * Generates a new chat thread URL path with a unique identifier.
+ * @param rootPath - The root path segment (e.g., 'app', 'dashboard')
+ * @param agentId - The agent identifier
+ * @returns A URL path in the format `/{rootPath}/{agentId}/chat/{uuid}?new=true`
+ * @example
+ * newThreadLink('app', 'agent-123')
+ * // => '/app/agent-123/chat/550e8400-e29b-41d4-a716-446655440000?new=true'
+ */
 export function newThreadLink(
   rootPath: string,
   agentId: string,
 ): `/${string}/${string}/chat/${string}?new=true` {
   return `/${rootPath}/${agentId}/chat/${uuid()}?new=true`;
 }
🤖 Prompt for AI Agents
In lib/utils.ts around lines 8–13, add a TSDoc block for newThreadLink
describing parameters (rootPath, agentId), the template-literal return type, and
an example usage; then validate/sanitize inputs by trimming and removing
leading/trailing slashes from rootPath and agentId, ensure they are non-empty
(throw or return a clear error), and URL-encode each segment (e.g., with
encodeURIComponent) before composing the final
`/${rootPath}/${agentId}/chat/${uuid()}?new=true` string so the generated URL is
well-formed and safe.

Comment thread package.json
Comment on lines +122 to +123
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.23",
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Move ESLint plugins to devDependencies.

ESLint plugins are development-time tools used for linting, not runtime dependencies. They should be in devDependencies to avoid unnecessary installation in production environments.

Move these entries from dependencies to devDependencies:

 "devDependencies": {
     "@mdx-js/loader": "^3.1.1",
     ...
+    "eslint-plugin-react-hooks": "^7.0.1",
+    "eslint-plugin-react-refresh": "^0.4.23",
     ...
 }

And remove from dependencies.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In package.json around lines 122-123, the ESLint plugins
"eslint-plugin-react-hooks" and "eslint-plugin-react-refresh" are incorrectly
listed under dependencies; move these two entries into devDependencies and
remove them from dependencies (update package.json accordingly or run npm
install --save-dev eslint-plugin-react-hooks@^7.0.1
eslint-plugin-react-refresh@^0.4.23 and remove the entries from dependencies),
then run an install to update lockfile.

Comment on lines 271 to +272
message: 'Converting PDF to markdown `...',
stage: "documentProcessingAgent",
stage: "convert-pdf-to-markdown",
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix typo: stray backtick in message string.

The message contains an errant backtick that appears unintentional.

           status: 'in-progress',
-          message: 'Converting PDF to markdown `...',
+          message: 'Converting PDF to markdown...',
           stage: "convert-pdf-to-markdown",
📝 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.

Suggested change
message: 'Converting PDF to markdown `...',
stage: "documentProcessingAgent",
stage: "convert-pdf-to-markdown",
status: 'in-progress',
message: 'Converting PDF to markdown...',
stage: "convert-pdf-to-markdown",
🤖 Prompt for AI Agents
In src/mastra/workflows/document-processing-workflow.ts around lines 271-272,
the log/message string "Converting PDF to markdown `..." contains a stray
backtick; remove the backtick so the message reads "Converting PDF to
markdown..." (ensure punctuation and string quoting remain valid after edit).

Comment on lines +184 to +185
embeddingModel: 'google/gemini-embedding-001',
embeddingBatchSize: 50,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Consider making embedding configuration parameters configurable.

The embedding model and batch size are hardcoded. For flexibility, consider adding these as optional inputs to the workflow schema with sensible defaults.

// In scanInputSchema, add optional embedding config:
embeddingModel: z.string().default('google/gemini-embedding-001'),
embeddingBatchSize: z.number().default(50),
🤖 Prompt for AI Agents
In src/mastra/workflows/repo-ingestion-workflow.ts around lines 184-185, the
embeddingModel and embeddingBatchSize are hardcoded; update the scan input
schema to accept optional embeddingModel (default 'google/gemini-embedding-001')
and embeddingBatchSize (default 50), then replace the hardcoded values by
reading those fields from the validated input (falling back to the defaults for
backward compatibility) so the workflow can be configured per-run without
breaking existing callers.

Comment on lines 72 to 80
await writer?.custom({
type: 'data-tool-progress',
data: {
status: "in-progress",
message: `Researching topic: ${inputData.topics}...`,
stage: "researchAgent",
status: "in-progress",
message: `Researching topic: ${inputData.topics}...`,
stage: "researchAgent",
},
id: 'initialize-research',
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Inconsistent stage naming in initializeResearchStep.

This step uses stage: "researchAgent" while other steps in this file use their step IDs (e.g., 'research-topic-item', 'synthesize-research'). For consistency, consider updating to stage: 'initialize-research'.

       await writer?.custom({
         type: 'data-tool-progress',
         data: {
           status: "in-progress",
           message: `Researching topic: ${inputData.topics}...`,
-          stage: "researchAgent",
+          stage: "initialize-research",
         },
         id: 'initialize-research',
       });
🤖 Prompt for AI Agents
In src/mastra/workflows/research-synthesis-workflow.ts around lines 72 to 80,
the progress event sets stage: "researchAgent" which is inconsistent with other
steps; update the stage value to 'initialize-research' so it matches the step ID
(and keeps stage naming consistent across the file), leaving the rest of the
writer.custom payload unchanged.

Comment on lines +126 to 127

logStepEnd('fetch-stock-data', { symbol: result.symbol, price: result.currentPrice }, Date.now() - startTime);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Minor: Extra blank line.

There's an extra blank line that appears to be a formatting artifact. Same issue at lines 258, 407, and 559.

🤖 Prompt for AI Agents
In src/mastra/workflows/stock-analysis-workflow.ts around lines 126-127 (and
similarly at lines 258, 407, and 559), there are stray extra blank lines
introduced as formatting artifacts; remove those blank lines so each statement
is directly adjacent to the next (e.g., delete the empty line after the
logStepEnd call) and run the formatter/linter to ensure consistent spacing
across the file.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors workflow error handling and enhances development tooling by adding ESLint plugins for React development. The main changes standardize error reporting across workflows by transitioning from data-workflow-step-error to data-tool-progress with more descriptive stage identifiers. Additionally, new ESLint plugins are configured to improve code quality for React components.

Key Changes

  • Error handling standardization: Updated error handling across multiple workflows to use data-tool-progress type with stage and status fields instead of data-workflow-step-error with stepId
  • Stage identifier improvements: Changed generic "workflow" stage identifiers to more descriptive names like "fetch-stock-data", "research-topic-item", and "convert-pdf-to-markdown"
  • React linting support: Added eslint-plugin-react-hooks and eslint-plugin-react-refresh dependencies with corresponding ESLint configuration

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
package.json Added eslint-plugin-react-hooks and eslint-plugin-react-refresh dependencies for improved React linting
package-lock.json Updated lock file with new plugin dependencies and transitive dependencies
eslint.config.js Configured new React plugins and added global browser environment support
src/mastra/workflows/stock-analysis-workflow.ts Refactored to use descriptive stage identifiers and standardized error handling with data-tool-progress type
src/mastra/workflows/research-synthesis-workflow.ts Updated stage names and error handling to match new pattern, improved consistency
src/mastra/workflows/repo-ingestion-workflow.ts Added type guards for result validation and included embedding configuration parameters
src/mastra/workflows/document-processing-workflow.ts Changed stage identifier and error type for consistency with other workflows
lib/utils.ts Added newThreadLink utility function for generating thread URLs with UUID

stepId: 'run-analysis',
stage: 'run-analysis',
error: error instanceof Error ? error.message : 'Unknown error',
status: 'done'
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

The error data structure is missing the 'message' field that is present in other progress updates. For consistency with the in-progress and done status messages, consider adding a message field like "Analysis failed" or similar to provide better context in error scenarios.

Suggested change
status: 'done'
status: 'done',
message: 'Analysis failed'

Copilot uses AI. Check for mistakes.
stepId: 'convert-pdf-to-markdown',
stage: 'convert-pdf-to-markdown',
status: "done",
error: error instanceof Error ? error.message : 'Unknown error',
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

The error data structure is inconsistent with other progress updates. Similar to other error handlers in this file, consider adding a 'message' field to provide better context. The current structure only includes 'stage', 'status', and 'error', while success cases include descriptive messages.

Suggested change
error: error instanceof Error ? error.message : 'Unknown error',
error: error instanceof Error ? error.message : 'Unknown error',
message: `Error in convert-pdf-to-markdown: ${error instanceof Error ? error.message : 'Unknown error'}`,

Copilot uses AI. Check for mistakes.
Comment thread eslint.config.js
import tseslint from '@typescript-eslint/eslint-plugin'
import tsparser from '@typescript-eslint/parser'
import prettierConfig from 'eslint-config-prettier'
import { globalIgnores } from "eslint/config";
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

The import { globalIgnores } from "eslint/config" appears to be incorrect. ESLint does not export a globalIgnores function from "eslint/config". The standard way to define ignores in flat config is to use the ignores property in configuration objects. The ignores array already defined on line 10 should be sufficient. This import and its usage on line 53 should be removed.

Suggested change
import { globalIgnores } from "eslint/config";

Copilot uses AI. Check for mistakes.
Comment thread eslint.config.js

export default [
{ ignores },
globalIgnores(["dist", "node_modules"]),
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

This usage of globalIgnores(["dist", "node_modules"]) is incorrect and will cause a runtime error. The globalIgnores function does not exist in ESLint's API. Additionally, these paths are already included in the ignores array defined earlier (lines 13-14). This line should be removed.

Copilot uses AI. Check for mistakes.
Comment thread eslint.config.js
globalIgnores(["dist", "node_modules"]),
js.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.next,
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

The configuration reference reactRefresh.configs.next appears to be incorrect. The eslint-plugin-react-refresh package typically exports configs.recommended or configs.vite, not configs.next. This should be verified against the actual plugin documentation and corrected to use a valid configuration export.

Suggested change
reactRefresh.configs.next,
reactRefresh.configs.recommended,

Copilot uses AI. Check for mistakes.
Comment thread lib/utils.ts
export function newThreadLink(
rootPath: string,
agentId: string,
): `/${string}/${string}/chat/${string}?new=true` {
Copy link

Copilot AI Dec 14, 2025

Choose a reason for hiding this comment

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

The function newThreadLink has a return type that is too specific. The template literal type /${string}/${string}/chat/${string}?new=true doesn't accurately represent the actual return value since uuid() returns a specific string format, not just any string. Consider using a more appropriate return type like string or a branded type if type safety for URLs is important.

Suggested change
): `/${string}/${string}/chat/${string}?new=true` {
): string {

Copilot uses AI. Check for mistakes.
@ssdeanx ssdeanx merged commit 2345500 into main Dec 14, 2025
130 of 132 checks passed
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.

2 participants