Skip to content

Conversation

@jackshen310
Copy link
Collaborator

@jackshen310 jackshen310 commented Feb 24, 2025

Summary by CodeRabbit

  • New Features

    • Introduced asynchronous workflow execution, allowing workflows to run non-blockingly for enhanced responsiveness.
    • Added execution history tracking, providing improved monitoring and troubleshooting of workflow processes.
  • Tests

    • Deployed new tests to verify that workflow history retrieval works as expected.

@coderabbitai
Copy link

coderabbitai bot commented Feb 24, 2025

Walkthrough

The changes enhance asynchronous workflow execution across the codebase. A JSON file now marks the update as "minor" and details the new async execution and history tracking features in the @coze/api package. An example async function is added to demonstrate the new functionality. The core Runs class is updated with a modified stream method and a new history method alongside interface enhancements. A test suite is also introduced to validate the retrieval of workflow run history.

Changes

File(s) Change Summary
common/changes/@coze/api/…/fix-workflow_2025-02-24-12-00.json Updated @coze/api package metadata with a "minor" change type and added async workflow execution and history tracking features.
examples/coze-js-node/src/workflow.ts Added a new asyncWorkflow() function that asserts identifiers, creates asynchronous workflow runs, and polls for execution history until completion.
packages/coze-js/…/runs/runs.ts
packages/coze-js/…/workflows.spec.ts
Modified the Runs class by updating the stream method parameters, adding a new history method, extending interfaces with async and execution history properties, and adding tests for workflow run history retrieval.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant AW as asyncWorkflow
    participant C as Client API

    U->>AW: Invoke asyncWorkflow()
    AW->>C: Request workflow run creation (async)
    C-->>AW: Return workflow details
    loop Poll for workflow status
        AW->>C: Fetch execution history
        C-->>AW: Return current history/status
    end
    alt Status ≠ Running
        AW->>AW: Break loop and conclude execution
    else Status Running
        AW->>AW: Wait 1 second and continue polling
    end
    AW->>AW: Handle any errors encountered
Loading

Possibly related PRs

Suggested reviewers

  • jsongo

Poem

I'm a nimble rabbit in the code glade,
Hopping through async loops in a joyful parade.
I trace each workflow with a careful glance,
As histories bloom in a rhythmic dance.
With every line, my heart does leap—
A hoppy celebration, cheerful and deep!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

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

🧹 Nitpick comments (4)
examples/coze-js-node/src/workflow.ts (1)

51-77: Add error handling for workflow creation.

The workflow creation call lacks error handling.

Consider adding try-catch:

 async function asyncWorkflow() {
   assert(botId, 'botId is required');
   assert(workflowId, 'workflowId is required');
+  try {
   const workflow = await client.workflows.runs.create({
     workflow_id: workflowId,
     parameters: { input: 'Hello World' },
     is_async: true,
   });
   console.log('workflow', workflow);
+  } catch (error) {
+    console.error('Error creating workflow:', error);
+    throw error;
+  }
   // ... rest of the function
 }
packages/coze-js/test/resources/workflows.spec.ts (1)

105-120: Add test cases for error scenarios.

The current test suite only covers the success case. Consider adding tests for:

  1. Invalid workflow ID
  2. Invalid execute ID
  3. API error responses
  4. Network failures

Example additional test:

it('should handle API errors when getting workflow history', async () => {
  const errorResponse = { 
    status: 404,
    message: 'Workflow not found'
  };
  vi.spyOn(client, 'get').mockRejectedValue(errorResponse);

  await expect(
    workflows.runs.history('invalid-id', 'run-id')
  ).rejects.toEqual(errorResponse);

  expect(client.get).toHaveBeenCalledWith(
    '/v1/workflows/invalid-id/run_histories/run-id',
    undefined,
    false,
    undefined
  );
});
packages/coze-js/src/resources/workflows/runs/runs.ts (2)

97-115: Add input validation and improve JSDoc.

The history method could benefit from input validation and improved documentation.

Consider these improvements:

 /**
  * Get the workflow run history | 工作流异步运行后,查看执行结果
  * @docs zh: https://www.coze.cn/open/docs/developer_guides/workflow_history
  * @param workflowId - Required The ID of the workflow. | 必选 工作流 ID。
  * @param executeId - Required The ID of the workflow execution. | 必选 工作流执行 ID。
+ * @throws {CozeError} When workflowId or executeId is empty
  * @returns WorkflowExecuteHistory[] | 工作流执行历史
  */
 async history(
   workflowId: string,
   executeId: string,
   options?: RequestOptions,
 ) {
+  if (!workflowId?.trim()) {
+    throw new CozeError('workflowId is required');
+  }
+  if (!executeId?.trim()) {
+    throw new CozeError('executeId is required');
+  }
   const apiUrl = `/v1/workflows/${workflowId}/run_histories/${executeId}`;
   const response = await this._client.get<
     undefined,
     { data: WorkflowExecuteHistory[] }
   >(apiUrl, undefined, false, options);
   return response.data;
 }

215-231: Add JSDoc comments to WorkflowExecuteHistory interface.

The interface lacks documentation for its properties.

Consider adding JSDoc comments:

/**
 * Represents the execution history of a workflow
 */
export interface WorkflowExecuteHistory {
  /** Unique identifier for the workflow execution */
  execute_id: string;
  /** Current status of the workflow execution */
  execute_status: 'Success' | 'Running' | 'Fail';
  /** ID of the bot that executed the workflow */
  bot_id: string;
  /** ID of the connector used in the workflow */
  connector_id: string;
  /** User ID associated with the connector */
  connector_uid: string;
  /** Mode in which the workflow was run */
  run_mode: 0 | 1 | 2;
  /** Log identifier for tracing */
  logid: string;
  /** Timestamp when the execution was created */
  create_time: number;
  /** Timestamp when the execution was last updated */
  update_time: number;
  /** Output produced by the workflow */
  output: string;
  /** Token used for the execution */
  token: string;
  /** Cost associated with the execution */
  cost: string;
  /** Error code if execution failed */
  error_code: string;
  /** Error message if execution failed */
  error_message: string;
  /** URL for debugging information */
  debug_url: string;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06aef9f and b1c4766.

📒 Files selected for processing (4)
  • common/changes/@coze/api/fix-workflow_2025-02-24-12-00.json (1 hunks)
  • examples/coze-js-node/src/workflow.ts (1 hunks)
  • packages/coze-js/src/resources/workflows/runs/runs.ts (3 hunks)
  • packages/coze-js/test/resources/workflows.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node.js v20 (ubuntu-latest)
🔇 Additional comments (1)
common/changes/@coze/api/fix-workflow_2025-02-24-12-00.json (1)

1-11: LGTM! Change log accurately documents the feature.

The change log correctly captures the feature addition and uses appropriate version bump (minor) for new functionality.

@jackshen310 jackshen310 added this pull request to the merge queue Feb 26, 2025
Merged via the queue into coze-dev:main with commit 5b2fdfa Feb 26, 2025
4 checks passed
@jackshen310 jackshen310 deleted the fix/workflow branch February 26, 2025 06:45
@codecov
Copy link

codecov bot commented Feb 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

❌ Your project status has failed because the head coverage (0.00%) is below the target coverage (90.00%). You can increase the head coverage or adjust the target coverage.

@@            Coverage Diff            @@
##             main   #115       +/-   ##
=========================================
- Coverage   91.82%      0   -91.83%     
=========================================
  Files         117      0      -117     
  Lines        5469      0     -5469     
  Branches     1106      0     -1106     
=========================================
- Hits         5022      0     -5022     
+ Misses        447      0      -447     
Components Coverage Δ
coze-js ∅ <ø> (∅)
realtime-api ∅ <ø> (∅)
chat-sdk ∅ <ø> (∅)

see 117 files with indirect coverage changes

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