Skip to content

feat: improve progress event handling and UI components#43

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

feat: improve progress event handling and UI components#43
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Dec 12, 2025

  • Updated progress event handling in NetworkProvider and WorkflowProvider to use part indices for unique IDs instead of timestamps.
  • Enhanced AGENTS.md documentation with a sequence diagram for progress event handling.
  • Adjusted width of SelectTrigger in WorkflowHeader component for better UI consistency.

Summary by Sourcery

Improve progress event handling for network and workflow contexts and align related UI and documentation.

New Features:

  • Use message part indices to generate stable unique IDs for progress events in network and workflow providers.

Enhancements:

  • Clarify progress event handling flow in AGENTS documentation with a Mermaid sequence diagram.
  • Adjust workflow header select trigger width for better layout consistency.

- Updated progress event handling in NetworkProvider and WorkflowProvider to use part indices for unique IDs instead of timestamps.
- Enhanced AGENTS.md documentation with a sequence diagram for progress event handling.
- Adjusted width of SelectTrigger in WorkflowHeader component for better UI consistency.
Copilot AI review requested due to automatic review settings December 12, 2025 15:37
@continue
Copy link

continue bot commented Dec 12, 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

@sourcery-ai
Copy link

sourcery-ai bot commented Dec 12, 2025

Reviewer's Guide

Refactors progress event handling in network and workflow providers to generate stable, deterministic IDs based on message part indices, documents the progress event flow with a new sequence diagram, and slightly adjusts a workflow header select width for UI consistency.

Sequence diagram for progress event handling with stable IDs

sequenceDiagram
    actor User as User
    participant Assistant as Assistant_Message
    participant NetworkProvider as NetworkProvider
    participant WorkflowProvider as WorkflowProvider
    participant ProgressPanel as ProgressPanel

    User->>Assistant: Run network or workflow
    Assistant->>NetworkProvider: Stream messages with parts
    Assistant->>WorkflowProvider: Stream messages with parts

    loop For_each_assistant_message_in_network
        NetworkProvider->>NetworkProvider: Iterate parts with index partIndex
        NetworkProvider->>NetworkProvider: Build id using messageId_partType_partIndex
        NetworkProvider->>NetworkProvider: Append ProgressEvent to allProgressEvents
    end

    loop For_each_assistant_message_in_workflow
        WorkflowProvider->>WorkflowProvider: Iterate parts with index partIndex
        WorkflowProvider->>WorkflowProvider: Build id using messageId_partType_partIndex
        WorkflowProvider->>WorkflowProvider: Append ProgressEvent to allProgressEvents
    end

    NetworkProvider->>ProgressPanel: Provide progressEvents for network view
    WorkflowProvider->>ProgressPanel: Provide progressEvents for workflow view
    ProgressPanel->>User: Render grouped progress items with stable IDs
Loading

Class diagram for progress event extraction with part index-based IDs

classDiagram
    class Message {
      +string id
      +string role
      +MessagePart[] parts
    }

    class MessagePart {
      +string type
      +AgentDataPart data
    }

    class AgentDataPart {
      +string text
      +string status
      +string stage
      +string stepId
      +string message
      +string agentId
      +string workflowId
    }

    class ProgressEvent {
      +string id
      +string stage
      +string status
      +string message
      +string agentId
      +string workflowId
    }

    class NetworkProvider {
      +ProgressEvent[] extractProgressEvents(messages)
    }

    class WorkflowProvider {
      +ProgressEvent[] extractProgressEvents(messages)
    }

    class ProgressPanel {
      +void render(progressEvents)
    }

    Message "1" --> "*" MessagePart : has
    MessagePart "1" --> "0..1" AgentDataPart : data

    NetworkProvider --> Message : reads
    WorkflowProvider --> Message : reads

    NetworkProvider --> ProgressEvent : creates_with_id_messageId_partType_partIndex
    WorkflowProvider --> ProgressEvent : creates_with_id_messageId_partType_partIndex

    ProgressPanel "1" --> "*" ProgressEvent : renders
Loading

File-Level Changes

Change Details Files
Make progress event IDs deterministic and tied to message parts instead of timestamps.
  • Iterate over assistant message parts using entries() to access both index and part object.
  • Construct progress event IDs using message ID, part type, and part index instead of Date.now().
  • Apply the new ID scheme to both text-based and status-based progress events so identical parts map to consistent IDs.
app/networks/providers/network-context.tsx
app/workflows/providers/workflow-context.tsx
Document the end-to-end progress event handling flow for workflows/networks.
  • Add a Mermaid sequence diagram describing how assistant messages with data-tool parts are transformed into progress events and rendered in the UI.
  • Clarify the roles of Assistant, context providers, extractor logic, state, and progress panel/dialog, including suspend/resume behavior.
app/workflows/AGENTS.md
Tweak workflow header select width for better layout.
  • Increase SelectTrigger width from w-70 to w-72 to better align with surrounding controls.
app/workflows/components/workflow-header.tsx

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

🤖 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

coderabbitai bot commented Dec 12, 2025

Summary by CodeRabbit

Release Notes

  • Documentation

    • Added comprehensive progress event handling documentation to the workflows guide, including visual sequence diagrams that illustrate how progress events flow through the application and are rendered in the workflow progress panel
  • Style

    • Refined workflow header component layout spacing

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

Walkthrough

These changes transition progress event ID generation from time-based (Date.now()) to index-based (partIndex) in network and workflow context providers, introduce documentation describing progress event handling flow, and adjust a UI component width.

Changes

Cohort / File(s) Change Summary
Progress Event ID Refactoring
app/networks/providers/network-context.tsx, app/workflows/providers/workflow-context.tsx
Replaced message.parts iteration with enumeration via message.parts.entries() to capture partIndex; updated all progress event IDs to use partIndex instead of Date.now(), making IDs deterministic per part index rather than time-based.
Documentation
app/workflows/AGENTS.md
Added new "Progress Event Handling" section with Mermaid sequence diagram describing how progress events are extracted from assistant messages, transformed into state, rendered in the progress panel, and how paused/suspend flows trigger a suspend dialog.
UI Styling
app/workflows/components/workflow-header.tsx
Adjusted SelectTrigger component width from w-70 to w-72.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • The refactoring pattern is homogeneous across both context files (same iteration and ID generation change applied consistently)
  • ID generation logic change is straightforward with no control flow modifications
  • Documentation addition is descriptive with no functional impact on code
  • Styling adjustment is trivial

Poem

🐰 From tick-tock to index bright,
Progress events now march just right,
No more Date.now() in sight,
Each part finds its place so tight,
Documentation shines its light! ✨

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 'feat: improve progress event handling and UI components' directly aligns with the main changes: updates to progress event handling in providers and enhancements to UI/documentation components.
Description check ✅ Passed The description accurately covers all key changes: progress event handling improvements, documentation enhancements, and UI adjustments—all present in the actual changeset.
✨ 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

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a617239 and 5b83e37.

📒 Files selected for processing (4)
  • app/networks/providers/network-context.tsx (2 hunks)
  • app/workflows/AGENTS.md (1 hunks)
  • app/workflows/components/workflow-header.tsx (1 hunks)
  • app/workflows/providers/workflow-context.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (17)
**/app/**

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

Use the app/ directory structure for route handlers, server components, and client components (Next.js 13+). Prefer this over the pages/ directory for new projects.

Files:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/AGENTS.md
  • app/workflows/providers/workflow-context.tsx
**/components/**/*.{js,jsx,ts,tsx}

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

Use PascalCase for component file names (e.g., ComponentName.jsx or ComponentName.tsx).

Files:

  • app/workflows/components/workflow-header.tsx
**/*.{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:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
app/**/*.{tsx,ts}

📄 CodeRabbit inference engine (app/AGENTS.md)

app/**/*.{tsx,ts}: Use Tailwind CSS 4 with oklch color variables for styling in Next.js App Router pages and layouts
Use React 19 latest features in component implementations within the app directory

Files:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
app/workflows/components/**/*.{ts,tsx}

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

app/workflows/components/**/*.{ts,tsx}: Use useChat from @ai-sdk/react with DefaultChatTransport to connect to Mastra workflow routes, mapping workflow-specific input fields through prepareSendMessagesRequest
Use useWorkflowContext() for state management in workflow components, providing workflow selection, execution control, status tracking, React Flow data, and streaming output
Use AI Elements components (Canvas, Node, Edge, Panel, Controls, Toolbar, Connection) for workflow visualization, with animated active edges and temporary pending edge types

Files:

  • app/workflows/components/workflow-header.tsx
app/workflows/**/*.{ts,tsx}

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Organize workflows feature with modular pattern: page.tsx, config/, providers/, and components/ directories with clear separation of concerns (state management, UI components, configuration)

Files:

  • app/workflows/components/workflow-header.tsx
  • app/workflows/providers/workflow-context.tsx
**/*.{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:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
**/*.{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:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
**/*.{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:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Frontend uses Next.js 16 App Router with React 19; use shadcn/ui base components (34 components) from ui/ directory

Files:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
**/*.{css,tsx,ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use Tailwind CSS 4 with oklch color variables for styling

Files:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
app/**/*.tsx

📄 CodeRabbit inference engine (AGENTS.md)

Use @ai-sdk/react for streaming and AI interactions in React components

Files:

  • app/workflows/components/workflow-header.tsx
  • app/networks/providers/network-context.tsx
  • app/workflows/providers/workflow-context.tsx
app/networks/**/*.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

app/networks/**/*.tsx: Use useChat from @ai-sdk/react with DefaultChatTransport for streaming responses from the /network route in the networks feature
Support real-time streaming with stop/cancel functionality, reasoning visualization for chain-of-thought models, and tool invocation display showing agent tool calls
Provide a responsive layout with collapsible sidebar on mobile for the networks feature

Files:

  • app/networks/providers/network-context.tsx
app/networks/providers/network-context.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

Implement state management using useNetworkContext() hook that provides selectedNetwork, networkConfig, networkStatus, messages, streamingOutput, routingSteps, and control functions (sendMessage, stopExecution, clearHistory)

Files:

  • app/networks/providers/network-context.tsx
**/*.md

📄 CodeRabbit inference engine (.github/instructions/markdown.instructions.md)

**/*.md: Use appropriate heading levels (H2, H3, etc.) to structure markdown content. Do not use H1 headings, as these will be generated from the title. Use ## for H2 and ### for H3 in a hierarchical manner. Recommend restructuring if content includes H4 or higher levels.
Use bullet points (with -) or numbered lists (with 1.) for lists in markdown. Indent nested lists with two spaces and ensure proper indentation and spacing.
Use fenced code blocks (triple backticks) for code snippets in markdown. Specify the language after the opening backticks for syntax highlighting (e.g., csharp).
Use proper markdown syntax for links: [link text](URL). Ensure that link text is descriptive and URLs are valid and accessible.
Use proper markdown syntax for images: ![alt text](image URL). Include a brief description of the image in the alt text for accessibility.
Use markdown tables (with | delimiters) for tabular data. Ensure proper formatting, alignment, and inclusion of headers.
Limit line length to 80 characters in markdown for readability. Use soft line breaks for long paragraphs.
Use appropriate whitespace in markdown to separate sections and improve readability. Use blank lines between sections and avoid excessive whitespace.
Include YAML front matter at the beginning of markdown files with required metadata fields: post_title, author1, post_slug, microsoft_alias, featured_image, categories (from /categories.txt), tags, ai_note, summary, and post_date.

Files:

  • app/workflows/AGENTS.md
app/workflows/AGENTS.md

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Include AGENTS.md documentation file in the workflows feature directory documenting architecture, components, integration patterns, and configuration

Files:

  • app/workflows/AGENTS.md
app/workflows/providers/workflow-context.tsx

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Implement workflow context provider with useChat hook from @ai-sdk/react, exporting interface with state (selectedWorkflow, workflowStatus, currentRun, activeStepIndex) and actions (selectWorkflow, runWorkflow, pauseWorkflow, resumeWorkflow, stopWorkflow, runStep, getStepStatus)

Files:

  • app/workflows/providers/workflow-context.tsx
🧬 Code graph analysis (1)
app/workflows/components/workflow-header.tsx (1)
ui/select.tsx (1)
  • SelectTrigger (185-185)
⏰ 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: Agent
  • GitHub Check: CodeQL analysis (javascript-typescript)
  • GitHub Check: Sourcery review
  • GitHub Check: Codacy Security Scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
app/workflows/components/workflow-header.tsx (1)

74-74: LGTM! Minor UI adjustment.

The SelectTrigger width adjustment from w-70 to w-72 improves UI consistency with no impact on functionality.

app/networks/providers/network-context.tsx (1)

297-337: Excellent improvement: Deterministic progress event IDs.

Switching from Date.now() to partIndex for progress event IDs provides several benefits:

  • Deterministic: Same message parts always generate identical event IDs
  • Testable: Predictable IDs improve test reliability
  • No collisions: Eliminates edge case where multiple events generated in the same millisecond could collide
  • Better React reconciliation: Stable keys improve rendering performance

The pattern ${message.id}-${part.type}-${partIndex} ensures uniqueness across all progress events.

app/workflows/AGENTS.md (1)

32-53: Valuable documentation addition.

The new "Progress Event Handling" section with the Mermaid sequence diagram clearly documents the flow from message reception through event extraction to UI rendering. The suspend/approve flow documentation is particularly helpful for understanding the workflow pause mechanism.

app/workflows/providers/workflow-context.tsx (1)

263-324: Excellent improvement: Consistent deterministic IDs.

This change mirrors the improvement in network-context.tsx, using partIndex instead of Date.now() for progress event IDs. The consistent approach across both providers ensures:

  • Predictable behavior: Same workflow execution produces identical event IDs
  • Easier debugging: Stable IDs simplify tracing events across the UI
  • No timestamp collisions: Eliminates race conditions in rapid event generation

The pattern ${message.id}-${part.type}-${partIndex} maintains uniqueness while providing determinism.


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.

@github-actions
Copy link

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

Copy link

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

  • Switching from Date.now() to partIndex for the id means multiple progress events derived from the same message.id + part.type + partIndex (e.g., text + later status) will now share the same id; if consumers rely on id being unique (e.g., as React keys or for lookups), consider including an additional discriminator (like status or a sequence counter) or keeping a monotonic suffix to avoid collisions.
  • The progress event extraction and mapping logic in NetworkProvider and WorkflowProvider is very similar; consider extracting shared helpers (e.g., for building ProgressEvent and deriving stage) to reduce duplication and keep behavior in sync across contexts.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Switching from `Date.now()` to `partIndex` for the `id` means multiple progress events derived from the same `message.id` + `part.type` + `partIndex` (e.g., text + later status) will now share the same `id`; if consumers rely on `id` being unique (e.g., as React keys or for lookups), consider including an additional discriminator (like status or a sequence counter) or keeping a monotonic suffix to avoid collisions.
- The progress event extraction and mapping logic in `NetworkProvider` and `WorkflowProvider` is very similar; consider extracting shared helpers (e.g., for building `ProgressEvent` and deriving `stage`) to reduce duplication and keep behavior in sync across contexts.

## Individual Comments

### Comment 1
<location> `app/networks/providers/network-context.tsx:305` </location>
<code_context>
             if (eventData?.data?.text?.trim()) {
               allProgressEvents.push({
-                id: `${message.id}-${part.type}-${Date.now()}`,
+                id: `${message.id}-${part.type}-${partIndex}`,
                 stage: part.type.replace("data-tool-", ""),
                 status: "in-progress",
</code_context>

<issue_to_address>
**question (bug_risk):** Using partIndex instead of Date.now() might create duplicate IDs if messages are reprocessed or parts change order.

This makes IDs deterministic, but also means reprocessed messages or reordered/updated parts can emit progress events with the same ID. If these IDs are used as keys or for de-duplication, that can introduce subtle bugs. Consider adding another stable discriminator (e.g., a per-event sequence, `eventData.status`, or some unique field from the part) to keep IDs both deterministic and distinct across logically separate events.
</issue_to_address>

### Comment 2
<location> `app/workflows/providers/workflow-context.tsx:271` </location>
<code_context>
             if (eventData?.data?.text?.trim()) {
               allProgressEvents.push({
-                id: `${message.id}-${part.type}-${Date.now()}`,
+                id: `${message.id}-${part.type}-${partIndex}`,
                 stage: part.type.replace("data-tool-", ""),
                 status: "in-progress",
</code_context>

<issue_to_address>
**question (bug_risk):** Deterministic IDs based on partIndex may collide across workflow progress updates.

Using `partIndex` instead of `Date.now()` means multiple progress updates for the same message/part/type can share an ID if this logic runs more than once or the data changes. If these IDs are used to track or update individual progress entries, collisions will make distinct updates indistinguishable. Consider including additional fields (e.g. `eventData.stepId`, `eventData.status`, or a sequence number) in the ID to keep it deterministic but unique per update.
</issue_to_address>

### Comment 3
<location> `app/workflows/AGENTS.md:52` </location>
<code_context>
+    Note over Panel: If suspendPayload exists<br/>& status="paused"
+    Panel->>Panel: Show SuspendDialog<br/>with approve/reject
+    Panel->>Context: User clicks Approve<br/>(calls approveWorkflow)
+    Context->>Context: Clear suspendPayload<br/>Resume workflow
+```
+
</code_context>

<issue_to_address>
**issue (typo):** Consider adding punctuation or a conjunction between "Clear suspendPayload" and "Resume workflow" for grammatical clarity.

Right now it reads like a run-on. Consider phrasing it as `Clear suspendPayload, then resume workflow` or `Clear suspendPayload and resume workflow` so the sequence is clearer.

```suggestion
    Context->>Context: Clear suspendPayload,<br/>then resume workflow
```
</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.

if (eventData?.data?.text?.trim()) {
allProgressEvents.push({
id: `${message.id}-${part.type}-${Date.now()}`,
id: `${message.id}-${part.type}-${partIndex}`,
Copy link

Choose a reason for hiding this comment

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

question (bug_risk): Using partIndex instead of Date.now() might create duplicate IDs if messages are reprocessed or parts change order.

This makes IDs deterministic, but also means reprocessed messages or reordered/updated parts can emit progress events with the same ID. If these IDs are used as keys or for de-duplication, that can introduce subtle bugs. Consider adding another stable discriminator (e.g., a per-event sequence, eventData.status, or some unique field from the part) to keep IDs both deterministic and distinct across logically separate events.

if (eventData && eventData.text !== null && typeof eventData.text === "string" && eventData.text.trim()) {
allProgressEvents.push({
id: `${message.id}-${part.type}-${Date.now()}`,
id: `${message.id}-${part.type}-${partIndex}`,
Copy link

Choose a reason for hiding this comment

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

question (bug_risk): Deterministic IDs based on partIndex may collide across workflow progress updates.

Using partIndex instead of Date.now() means multiple progress updates for the same message/part/type can share an ID if this logic runs more than once or the data changes. If these IDs are used to track or update individual progress entries, collisions will make distinct updates indistinguishable. Consider including additional fields (e.g. eventData.stepId, eventData.status, or a sequence number) in the ID to keep it deterministic but unique per update.

Note over Panel: If suspendPayload exists<br/>& status="paused"
Panel->>Panel: Show SuspendDialog<br/>with approve/reject
Panel->>Context: User clicks Approve<br/>(calls approveWorkflow)
Context->>Context: Clear suspendPayload<br/>Resume workflow
Copy link

Choose a reason for hiding this comment

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

issue (typo): Consider adding punctuation or a conjunction between "Clear suspendPayload" and "Resume workflow" for grammatical clarity.

Right now it reads like a run-on. Consider phrasing it as Clear suspendPayload, then resume workflow or Clear suspendPayload and resume workflow so the sequence is clearer.

Suggested change
Context->>Context: Clear suspendPayload<br/>Resume workflow
Context->>Context: Clear suspendPayload,<br/>then resume workflow

@greptile-apps
Copy link

greptile-apps bot commented Dec 12, 2025

Greptile Overview

Greptile Summary

This PR improves progress event handling by replacing timestamp-based IDs with deterministic part indices, enhancing documentation with a sequence diagram, and adjusting UI width for better consistency.

Key Changes:

  • Replaced Date.now() with partIndex for generating unique progress event IDs in both WorkflowProvider and NetworkProvider
  • Added comprehensive sequence diagram to app/workflows/AGENTS.md documenting the progress event handling flow
  • Adjusted SelectTrigger width from w-70 to w-72 in WorkflowHeader component

Benefits:

  • Part indices are deterministic and stable (same message always generates same IDs)
  • Eliminates potential ID collisions from multiple parts processed in the same millisecond
  • Improves event tracking reliability and debugging experience
  • Better documentation helps developers understand the system architecture

Confidence Score: 5/5

  • This PR is safe to merge with no risk - changes are well-scoped, logical, and improve system reliability
  • All changes are clean, well-tested patterns that improve code quality. The switch from timestamps to part indices is a clear improvement for ID uniqueness. Documentation additions enhance maintainability. The UI width adjustment is a minor visual improvement with no functional impact.
  • No files require special attention

Important Files Changed

File Analysis

Filename Score Overview
app/workflows/providers/workflow-context.tsx 5/5 replaced timestamp-based IDs with part indices for progress event tracking, improving ID uniqueness and stability
app/networks/providers/network-context.tsx 5/5 replaced timestamp-based IDs with part indices for progress event tracking, matching workflow implementation
app/workflows/AGENTS.md 5/5 added comprehensive sequence diagram documenting progress event handling flow
app/workflows/components/workflow-header.tsx 5/5 adjusted SelectTrigger width from w-70 to w-72 for better UI consistency

Sequence Diagram

sequenceDiagram
    participant Assistant as Assistant<br/>(Message)
    participant Context as Workflow/Network<br/>Context
    participant Extractor as Progress Event<br/>Extractor
    participant State as Context State
    participant Panel as Progress<br/>Panel/Dialog

    Assistant->>Context: Receive message with<br/>data-tool-* parts
    Context->>Extractor: Extract progress events<br/>from message parts
    Extractor->>Extractor: Parse stage, status,<br/>message, agentId/stepId
    Note over Extractor: Generate unique ID using<br/>message.id + part.type + partIndex
    Extractor->>State: Update progressEvents<br/>and suspendPayload
    State->>Panel: Trigger re-render with<br/>new events
    Panel->>Panel: Group by stage &<br/>render event items
    
    Note over Panel: If suspendPayload exists<br/>& status="paused"
    Panel->>Panel: Show SuspendDialog<br/>with approve/reject
    Panel->>Context: User clicks Approve<br/>(calls approveWorkflow)
    Context->>Context: Clear suspendPayload<br/>Resume workflow
Loading

Copy link

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

4 files reviewed, no comments

Edit Code Review Agent Settings | Greptile

Copy link
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 improves the stability and reliability of progress event handling in both workflow and network contexts by switching from timestamp-based IDs to index-based IDs. The change prevents duplicate or unstable IDs when messages are re-processed during re-renders. Additionally, it includes a minor UI adjustment and enhanced documentation with a sequence diagram.

Key Changes:

  • Replaced Date.now() with partIndex in progress event ID generation for deterministic, stable IDs
  • Updated both WorkflowProvider and NetworkProvider to use consistent ID generation strategy
  • Added a Mermaid sequence diagram documenting the progress event handling flow

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
app/workflows/providers/workflow-context.tsx Updated progress event ID generation to use part indices instead of timestamps (2 occurrences)
app/networks/providers/network-context.tsx Updated progress event ID generation to use part indices instead of timestamps (2 occurrences)
app/workflows/components/workflow-header.tsx Adjusted SelectTrigger width from w-70 to w-72 for improved UI consistency
app/workflows/AGENTS.md Added comprehensive sequence diagram documenting progress event handling flow

The changes are well-structured and improve the codebase by addressing a potential issue where progress event IDs could be non-deterministic when effects re-run. The documentation update provides valuable context for understanding the progress event handling architecture.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant