Skip to content

v4 ai improvements #1863

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Apr 2, 2025
Merged

v4 ai improvements #1863

merged 14 commits into from
Apr 2, 2025

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Apr 2, 2025

Replaces toolTask with being able to create an "ai tool" from a schemaTask:

import { ai } from "@trigger.dev/sdk/ai";

export const myTool = ai.tool(mySchemaTask);

This means that now the ai SDK is an optional peer dependency of the @trigger.dev/sdk package.

This PR also has changed how we do partial spans, now partial spans will be created for all otel spans, not just our internal ones.

Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Walkthrough

This PR introduces numerous enhancements across several repositories. A new debugging configuration is added for a d3-demo, and various UI components are updated for improved styling and logging. Core modules now include expanded exports, updated type guards, and refined span processing logic. The Trigger SDK receives new AI functionalities with associated deprecation warnings. Additionally, two new projects—d3-chat and d3-openai-agents—are introduced with complete setups including Next.js pages, UI components, migration scripts, Slack integrations, and configuration files. Minor error-handling improvements are also applied in the CLI entry point.

Changes

Files Change Summary
.vscode/launch.json Added a new "Debug d3-demo" launch configuration for Node Terminal-based debugging using pnpm exec trigger dev in the d3-demo reference directory.
apps/webapp/app/components/runs/v3/RunIcon.tsx, apps/webapp/app/v3/otlpExporter.server.ts, apps/webapp/app/v3/utils/enrichCreatableEvents.server.ts, apps/webapp/package.json Updated RunIcon to pass className to PythonLogoIcon; enhanced OTLPExporter logging by adding a prefix parameter; modified enrichStyle function for refined icon logic based on system and message; package.json received a trivial newline addition.
packages/core/src/v3/index.ts, .../otel/tracingSDK.ts, .../taskContext/otelProcessors.ts, .../tracer.ts, packages/core/src/v3/types/schemas.ts, packages/core/src/v3/workers/taskExecutor.ts Expanded schema exports and added new type guards; integrated a tracer into the TaskContextSpanProcessor; updated constructor and added helper methods (isPartialSpan, createPartialSpan); removed partial span creation in TriggerTracer; updated STYLE_ICON from "clock" to "tabler-clock".
packages/trigger-sdk/package.json, packages/trigger-sdk/src/v3/ai.ts, packages/trigger-sdk/src/v3/shared.ts Introduced a new AI module export with functions (toolFromTask, getToolOptionsFromMetadata, convertTaskSchemaToToolParameters) and updated dependency versions; added a deprecation notice for createToolTask.
Files under references/d3-chat/ (e.g. package.json, requirements.in/.txt, src/app, src/components, src/lib, src/trigger, tailwind.config.ts, trigger.config.ts) Added a full new Next.js project "d3-chat" with its own package, dependency, and migration configurations; new UI components (layout, header, chat container, chat input, chat message, tool call message, avatar); Slack interaction route; trigger tasks for chat, crawler, sandbox, and schemas; complete Tailwind and trigger configurations.
Files under references/d3-openai-agents/ (e.g. .gitignore, README.md, components.json, next.config.ts, package.json, postcss.config.mjs, src/app, src/extensions, src/lib, src/trigger, tsconfig.json) Introduced a new Next.js project "d3-openai-agents" with a reconfigured package (name change, new scripts, dependency updates), added PostCSS and global CSS files, component configuration, Slack API route, Playwright extension for installing Chromium, migration and utility scripts, and trigger modules for SQL approval, along with a TypeScript configuration.
packages/cli-v3/src/entryPoints/dev-run-worker.ts Enhanced error handling in the zodIpc connection's EXECUTE_TASK_RUN handler by including detailed error messages and stack traces.

Sequence Diagram(s)

sequenceDiagram
  participant SC as Slack Client
  participant API as Slack Interaction Route
  participant Auth as Auth Module
  participant Wait as Token Completion API
  SC->>API: POST payload with Slack action
  API->>API: Verify request via middleware
  API->>Auth: Authenticate request
  API->>Wait: Process action (approve/deny token)
  API->>SC: Return 200 OK or error response
Loading
sequenceDiagram
  participant U as User
  participant P as Next.js Page
  participant T as todoChat Trigger
  participant Tool as Task Execution Tool
  U->>P: Submits chat message
  P->>T: Sends task with schema for SQL query
  T->>Tool: Executes tool call (e.g., SQL, crawler)
  Tool-->>T: Returns result/approval request
  T->>P: Updates chat with response
  P->>U: Displays updated chat content
Loading

Poem

Oh, what a hop, a skip, a bound,
I’ve seen new configs and code all around.
Debug tools and schemas shine so bright,
Chat interfaces and Slack routes take flight.
With every line, my whiskers twitch in glee—
A code rabbit celebrating these changes with glee!
🐇✨


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
🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

changeset-bot bot commented Apr 2, 2025

🦋 Changeset detected

Latest commit: e35a3ca

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 18 packages
Name Type
@trigger.dev/sdk Patch
@trigger.dev/python Patch
d3-chat Patch
references-d3-openai-agents Patch
@trigger.dev/build Patch
@trigger.dev/core Patch
@trigger.dev/react-hooks Patch
@trigger.dev/redis-worker Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
trigger.dev Patch
@internal/redis Patch
@internal/run-engine Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/zod-worker Patch
references-nextjs-realtime Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 14

🧹 Nitpick comments (36)
references/d3-chat/requirements.in (1)

1-2: Consider pinning dependency versions.

While using a .in file without version constraints is common with pip-tools workflow, it's a good practice to specify at least minimum versions or version ranges to prevent compatibility issues when dependencies release breaking changes.

Consider adding version constraints:

-crawl4ai
-playwright
+crawl4ai>=0.1.0
+playwright>=1.32.0
references/d3-chat/src/components/header.tsx (1)

1-15: Make the user ID configurable

The component currently hardcodes the user ID "user_123456" in the UI. Consider making this a prop to improve component reusability.

-export function Header() {
+export function Header({ username = "user_123456" }: { username?: string }) {
  return (
    <header className="border-b border-gray-200 bg-white">
      <div className="container mx-auto px-4 py-3 flex items-center justify-between">
        <div className="flex items-center space-x-2">
          <span className="font-mono text-lg font-semibold">Todo Chat</span>
          <span className="bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded">v1.0.0</span>
        </div>
        <div className="flex items-center space-x-4">
-          <div className="text-sm text-gray-500">user_123456</div>
+          <div className="text-sm text-gray-500">{username}</div>
        </div>
      </div>
    </header>
  )
}
packages/trigger-sdk/src/v3/shared.ts (1)

227-229: Good deprecation notice for createToolTask

The deprecation notice clearly indicates that developers should use ai.tool() instead of createToolTask. This follows good practices for deprecating API methods.

However, consider adding more context such as when this function will be removed or why the change is happening to help developers plan their migration.

references/d3-chat/src/trigger/schemas.ts (1)

3-16: Consider centralizing shared schemas

These schemas appear to be identical to those in references/d3-openai-agents/src/trigger/schemas.ts. If these schemas are used across multiple repositories, consider creating a shared library to avoid duplication and ensure consistency.

references/d3-chat/src/app/layout.tsx (1)

15-18: Redundant metadata description

Both the title and description are set to "Todo Chat". Consider using a more descriptive text for the description field to improve SEO and accessibility.

export const metadata: Metadata = {
  title: "Todo Chat",
-  description: "Todo Chat",
+  description: "A chat interface for managing your todos and tasks",
};
references/d3-chat/src/app/api/slack/interaction/route.ts (2)

19-30: Add error handling for payload parsing

The current implementation assumes the payload will always be valid and available, which may not be true.

Improve the error handling:

-    const formData = await request.formData();
-    const payload = JSON.parse(formData.get("payload") as string);
+    const formData = await request.formData();
+    const payloadString = formData.get("payload");
+    
+    if (!payloadString) {
+      console.error("Missing payload in form data");
+      return new NextResponse("Bad Request: Missing payload", { status: 400 });
+    }
+    
+    let payload;
+    try {
+      payload = JSON.parse(payloadString as string);
+    } catch (error) {
+      console.error("Invalid JSON in payload", error);
+      return new NextResponse("Bad Request: Invalid payload", { status: 400 });
+    }

56-71: Add error handling for Slack API response

The code should handle network errors when sending the update to Slack.

Wrap the fetch call in a try-catch block:

-    const updateResponse = await fetch(payload.response_url, {
-      method: "POST",
-      headers: {
-        "Content-Type": "application/json",
-      },
-      body: JSON.stringify({
-        replace_original: true,
-        text: actionType === "approve" ? "Query approved" : "Query denied",
-        blocks,
-      }),
-    });
+    let updateResponse;
+    try {
+      updateResponse = await fetch(payload.response_url, {
+        method: "POST",
+        headers: {
+          "Content-Type": "application/json",
+        },
+        body: JSON.stringify({
+          replace_original: true,
+          text: actionType === "approve" ? "Query approved" : "Query denied",
+          blocks,
+        }),
+      });
+    } catch (error) {
+      console.error("Network error when updating Slack message:", error);
+      // Continue execution - don't fail the whole request if just the update fails
+    }
references/d3-chat/src/lib/slack.ts (2)

4-6: Add error handling for missing Slack token

The code initializes the Slack client without checking if the token exists.

Validate the presence of the token:

-// Initialize the Slack client
-const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
+// Initialize the Slack client
+const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
+
+if (!SLACK_BOT_TOKEN) {
+  console.warn("SLACK_BOT_TOKEN is not set. Slack messages will not be sent.");
+}
+
+const slack = new WebClient(SLACK_BOT_TOKEN);

24-27: Add validation for required environment variables

The code assumes SLACK_CHANNEL_ID will be available but doesn't validate it.

Validate the channel ID before sending the message:

      const response = await slack.chat.postMessage({
-        channel: process.env.SLACK_CHANNEL_ID!,
+        channel: process.env.SLACK_CHANNEL_ID || "",
         text: `SQL Query Approval Required for user ${userId}`, // Fallback text for notifications

Additionally, add validation at the beginning of the function:

export async function sendSQLApprovalMessage({
  query,
  userId,
  tokenId,
  publicAccessToken,
  input,
}: SendApprovalMessageParams) {
+  if (!process.env.SLACK_CHANNEL_ID) {
+    logger.warn("SLACK_CHANNEL_ID is not set. Skipping Slack message.");
+    return { ok: false, error: "SLACK_CHANNEL_ID not configured" };
+  }
+
  return await logger.trace(
references/d3-chat/src/trigger/sandbox.ts (1)

51-61: Implement error handling in the chart tool

The current tool implementation doesn't handle cases where the chart might be missing or invalid.

Add validation in the tool result transformation:

export const chartTool = ai.tool(chartTask, {
  experimental_toToolResultContent: (result) => {
+    if (!result || !result.chart) {
+      return [
+        {
+          type: "text",
+          text: "Failed to generate chart. Please try with a different description.",
+        },
+      ];
+    }
    return [
      {
        type: "image",
        data: result.chart,
        mimeType: "image/png",
      },
    ];
  },
});
references/d3-chat/src/components/tool-call-message.tsx (4)

1-5: Consider using more specific types instead of any

Using any types for input and output reduces type safety. Consider using more specific types or Record<string, unknown> for better type checking.

interface ToolCallMessageProps {
  name: string;
-  input: any;
-  output?: any;
+  input: Record<string, unknown>;
+  output?: Record<string, unknown>;
}

30-32: Add error handling for JSON stringify

JSON.stringify might throw an error if the input contains circular references. Consider adding error handling:

<pre className="bg-gray-800 text-gray-200 p-3 rounded text-xs overflow-x-auto">
-  {JSON.stringify(input, null, 2)}
+  {(() => {
+    try {
+      return JSON.stringify(input, null, 2);
+    } catch (error) {
+      return `[Error displaying input: ${error.message}]`;
+    }
+  })()}
</pre>

38-40: Add error handling for JSON stringify

Similar to the input section, add error handling for output JSON formatting:

<pre className="bg-gray-800 text-gray-200 p-3 rounded text-xs overflow-x-auto">
-  {JSON.stringify(output, null, 2)}
+  {(() => {
+    try {
+      return JSON.stringify(output, null, 2);
+    } catch (error) {
+      return `[Error displaying output: ${error.message}]`;
+    }
+  })()}
</pre>

44-63: Improve SVG loading spinner accessibility

The SVG spinner lacks accessibility attributes. Add appropriate ARIA attributes to make it more accessible:

<svg
  className="animate-spin h-4 w-4"
  xmlns="http://www.w3.org/2000/svg"
  fill="none"
  viewBox="0 0 24 24"
+  role="img"
+  aria-labelledby="loadingSpinnerTitle"
>
+  <title id="loadingSpinnerTitle">Loading spinner</title>
  <circle
    className="opacity-25"
    cx="12"
    cy="12"
    r="10"
    stroke="currentColor"
    strokeWidth="4"
  ></circle>
  <path
    className="opacity-75"
    fill="currentColor"
    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
  ></path>
</svg>
references/d3-openai-agents/src/app/api/slack/interaction/route.ts (1)

56-71: Refactor the Slack message update into a separate function

Extract the Slack message update logic into a separate function to improve readability and maintainability.

+  // Function to update the Slack message
+  async function updateSlackMessage(responseUrl: string, blocks: any[], actionType: string) {
+    const updateResponse = await fetch(responseUrl, {
+      method: "POST",
+      headers: {
+        "Content-Type": "application/json",
+      },
+      body: JSON.stringify({
+        replace_original: true,
+        text: actionType === "approve" ? "Query approved" : "Query denied",
+        blocks,
+      }),
+    });
+
+    if (!updateResponse.ok) {
+      console.error("Failed to update Slack message:", await updateResponse.text());
+      return false;
+    }
+    
+    return true;
+  }

-  // Send the update to Slack's response_url
-  const updateResponse = await fetch(payload.response_url, {
-    method: "POST",
-    headers: {
-      "Content-Type": "application/json",
-    },
-    body: JSON.stringify({
-      replace_original: true,
-      text: actionType === "approve" ? "Query approved" : "Query denied",
-      blocks,
-    }),
-  });
-
-  if (!updateResponse.ok) {
-    console.error("Failed to update Slack message:", await updateResponse.text());
-  }
+  // Send the update to Slack's response_url
+  await updateSlackMessage(payload.response_url, blocks, actionType);
references/d3-chat/src/components/chat-input.tsx (2)

17-34: Improve input field accessibility

The input field lacks important accessibility attributes. Add appropriate ARIA attributes to enhance usability for all users:

<div className="flex-grow relative">
  <input
    type="text"
    placeholder="Type your message..."
    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
    value={input}
    onChange={(e) => setInput(e.target.value)}
    onKeyDown={(e) => {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        handleSubmit();
      }
    }}
    disabled={isSubmitting}
+   aria-label="Chat message"
+   aria-disabled={isSubmitting}
+   aria-autocomplete="none"
  />
</div>

35-41: Add aria-label to submit button

Enhance accessibility by adding an appropriate aria-label to the button:

<button
  className="ml-2 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-blue-700 transition-colors"
  onClick={handleSubmit}
  disabled={isSubmitting || !input.trim()}
+  aria-label={isSubmitting ? "Sending message" : "Send message"}
>
  {isSubmitting ? "Sending..." : "Send"}
</button>
references/d3-openai-agents/src/lib/migrate.ts (2)

11-34: Consider adding indexes to improve query performance

The todos table might benefit from indexes on frequently queried fields, especially user_id and potentially status and due_date which are likely to be used in filters and sorts.

Add indexes to improve query performance:

export async function migrateUp() {
  const createTable = await sql`
    CREATE TABLE IF NOT EXISTS todos (
      id VARCHAR(255) PRIMARY KEY,
      user_id VARCHAR(255) NOT NULL,
      title VARCHAR(255) NOT NULL,
      description TEXT,
      status VARCHAR(50) NOT NULL DEFAULT 'pending',
      priority INTEGER NOT NULL DEFAULT 3,
      due_date TIMESTAMP WITH TIME ZONE,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
      completed_at TIMESTAMP WITH TIME ZONE,
      tags TEXT[], -- Array of tags
      assigned_to VARCHAR(255)
    );
  `;

+  // Add indexes for frequently queried fields
+  const createIndexes = await sql`
+    CREATE INDEX IF NOT EXISTS todos_user_id_idx ON todos(user_id);
+    CREATE INDEX IF NOT EXISTS todos_status_idx ON todos(status);
+    CREATE INDEX IF NOT EXISTS todos_due_date_idx ON todos(due_date);
+  `;

  console.log(`Created "todos" table`);

  return {
    createTable,
+    createIndexes,
  };
}

36-42: Add proper logging for failed migrations

The migration functions should log errors specifically for SQL operations:

export async function migrateDown() {
-  const dropTable = await sql`
-    DROP TABLE IF EXISTS todos;
-  `;
-
-  console.log(`Dropped "todos" table`);
+  try {
+    const dropTable = await sql`
+      DROP TABLE IF EXISTS todos;
+    `;
+    
+    console.log(`Dropped "todos" table successfully`);
+    return dropTable;
+  } catch (error) {
+    console.error(`Error dropping "todos" table:`, error);
+    throw error;
+  }
}

Apply similar error handling to the migrateUp function as well for consistency.

references/d3-chat/src/components/chat-message.tsx (1)

11-20: Combine or remove the Marked library usage
This component uses marked to tokenize the Markdown, then passes the raw tokens into ReactMarkdown. This can be redundant and potentially lead to unexpected parsing differences. Consider using a single parsing pipeline—either parse everything with marked or simplify and rely on react-markdown alone.

references/d3-chat/src/lib/migrate.ts (2)

11-34: Consider indexing 'user_id'
If queries often filter by user_id, adding an index on user_id might help performance as data grows.


44-49: Consider providing an explicit exit code on error
You might want to call process.exit(1) in the catch block to signal errors clearly in automated scripts.

references/d3-chat/src/trigger/chat.ts (3)

89-99: Add an index on 'user_id'
To optimize queries like SELECT * FROM todos WHERE user_id = ..., add an index on user_id for frequent lookups.


115-205: Make maxSteps more flexible
The maxSteps: 10 limit may restrict complex queries. Consider making this value configurable if you expect longer tool invocations.


206-229: Extract model selection from code
Hardcoding CHAT_PROVIDER to "openai" limits extensibility. Consider making it an environment variable or a user-setting for easier switching.

packages/core/src/v3/taskContext/otelProcessors.ts (1)

62-94: Partial span creation and event replication.

Cloning the original span’s attributes and replaying its events in a newly started partial span is well-executed. Consider adding a suffix (e.g., "(partial)") to the partial span name to distinguish it from the original in tracing UIs.

 function createPartialSpan(tracer: Tracer, span: Span, parentContext: Context) {
-  const partialSpan = tracer.startSpan(
-    span.name,
+  const partialSpan = tracer.startSpan(
+    `${span.name} (partial)`,
     {
       attributes: {
references/d3-chat/src/components/chat-container.tsx (3)

34-94: Ensure partial text-delta handling doesn't introduce merging conflicts.
The logic streaming text deltas into a single currentAssistantContent works correctly for incremental updates. However, consider concurrency scenarios or out-of-order deltas, which might require additional checks or synchronization, especially if future changes allow parallel prompts or multiple streams.


96-123: Validate environment variable usage or provide defaults.
When using process.env.NEXT_PUBLIC_TRIGGER_API_URL, consider fallback defaults or error handling to avoid runtime issues if the environment variable is missing. For example, you could default to a known API endpoint or gracefully handle an undefined value.

- baseURL: process.env.NEXT_PUBLIC_TRIGGER_API_URL,
+ baseURL: process.env.NEXT_PUBLIC_TRIGGER_API_URL ?? "https://api.trigger.dev",

193-197: Use dynamic user IDs instead of hardcoding.
Currently, the code uses a hardcoded userId of "user_1234". Consider retrieving the user’s real ID to maintain accuracy and consistency in multi-user environments.

submit({
-  input,
-  userId: "user_1234",
+  input,
+  userId: currentUserId, // Resolve from the authenticated user context
});
packages/trigger-sdk/src/v3/ai.ts (3)

26-29: Expand or revise the “experimental_toToolResultContent” option if needed.
Providing a custom function to transform the tool’s result content is beneficial. Verify that consumers of this API are aware of the experimental status and that documentation is updated accordingly.


30-57: Enhance error messages when creating tools from tasks without schemas.
Currently, an error is thrown if the task lacks a schema. This is correct, but consider linking to documentation or providing a clearer explanation of how to add schemas to tasks.

throw new Error(
-  "Cannot convert schemaTask to a tool because the task has no schema. Make sure the schema used in the task is either zod, arktype, or another supported schema."
+  "Cannot convert schemaTask to a tool. Ensure your task is defined with a supported schema (Zod, ArkType, etc.). Refer to the docs: <documentation-url>"
);

67-84: Support versions of schema frameworks.
convertTaskSchemaToToolParameters checks for Zod or ArkType. If your codebase might adopt other schema libraries, consider an extensible pattern or a fallback approach for partial compatibility.

references/d3-openai-agents/src/trigger/approval.ts (3)

12-68: Validate timeout and user flow for the approval task.
A 1-minute timeout might be too short or too long depending on real-world scenarios. Evaluate typical user response times to avoid accidental denials or indefinite waits.


92-102: Validate user existence logic.
getUserTodos retrieves todos by user_id. Ensure an invalid or missing user ID doesn't break your application logic, especially if it returns an empty set.


203-313: Test Slack approval workflow reliability.
sendSQLApprovalMessage relies on Slack interaction. If Slack downtimes or rate limits occur, you may need a retry mechanism, fallback channel, or alternate approval path to avoid blocking the user’s request.

references/d3-chat/requirements.txt (1)

3-219: Comprehensive Dependency List Review:
This file lists an extensive and well-documented set of dependencies along with inline comments indicating the source (e.g., “via crawl4ai”, “via litellm”). This level of detail is useful for tracking why each package is included. A few points to consider:

  • Version Verification: Some packages have version numbers that seem to be dated in the future (for example, certifi==2025.1.31 and fsspec==2025.3.2). Please verify that these versions are intentional and reflect the expected releases.
  • Consistency & Maintainability: Since this file is autogenerated, be cautious of manual modifications. It might be beneficial to add a note in the documentation indicating that any changes should be made in the source (requirements.in) rather than directly in this file.
  • New Dependencies: The inclusion of new dependencies such as crawl4ai and playwright aligns with the current PR objectives. Just ensure that these versions are compatible with the rest of the codebase and that any necessary migration or integration work has been carried out elsewhere.

Overall, the file structure and formatting look good for an autogenerated requirements file.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ce8bd1 and 4baf5c3.

⛔ Files ignored due to path filters (13)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • references/d3-chat/public/file.svg is excluded by !**/*.svg
  • references/d3-chat/public/globe.svg is excluded by !**/*.svg
  • references/d3-chat/public/next.svg is excluded by !**/*.svg
  • references/d3-chat/public/vercel.svg is excluded by !**/*.svg
  • references/d3-chat/public/window.svg is excluded by !**/*.svg
  • references/d3-chat/src/app/favicon.ico is excluded by !**/*.ico
  • references/d3-openai-agents/public/file.svg is excluded by !**/*.svg
  • references/d3-openai-agents/public/globe.svg is excluded by !**/*.svg
  • references/d3-openai-agents/public/next.svg is excluded by !**/*.svg
  • references/d3-openai-agents/public/vercel.svg is excluded by !**/*.svg
  • references/d3-openai-agents/public/window.svg is excluded by !**/*.svg
  • references/d3-openai-agents/src/app/favicon.ico is excluded by !**/*.ico
📒 Files selected for processing (49)
  • .vscode/launch.json (1 hunks)
  • apps/webapp/app/components/runs/v3/RunIcon.tsx (1 hunks)
  • apps/webapp/app/v3/otlpExporter.server.ts (3 hunks)
  • apps/webapp/app/v3/utils/enrichCreatableEvents.server.ts (2 hunks)
  • apps/webapp/package.json (1 hunks)
  • packages/cli-v3/src/entryPoints/dev-run-worker.ts (1 hunks)
  • packages/core/src/v3/index.ts (1 hunks)
  • packages/core/src/v3/otel/tracingSDK.ts (1 hunks)
  • packages/core/src/v3/taskContext/otelProcessors.ts (3 hunks)
  • packages/core/src/v3/tracer.ts (1 hunks)
  • packages/core/src/v3/types/schemas.ts (2 hunks)
  • packages/core/src/v3/workers/taskExecutor.ts (1 hunks)
  • packages/trigger-sdk/package.json (5 hunks)
  • packages/trigger-sdk/src/v3/ai.ts (1 hunks)
  • packages/trigger-sdk/src/v3/shared.ts (1 hunks)
  • references/d3-chat/package.json (1 hunks)
  • references/d3-chat/requirements.in (1 hunks)
  • references/d3-chat/requirements.txt (1 hunks)
  • references/d3-chat/src/app/api/slack/interaction/route.ts (1 hunks)
  • references/d3-chat/src/app/layout.tsx (1 hunks)
  • references/d3-chat/src/app/page.tsx (1 hunks)
  • references/d3-chat/src/components/chat-container.tsx (1 hunks)
  • references/d3-chat/src/components/chat-input.tsx (1 hunks)
  • references/d3-chat/src/components/chat-message.tsx (1 hunks)
  • references/d3-chat/src/components/header.tsx (1 hunks)
  • references/d3-chat/src/components/tool-call-message.tsx (1 hunks)
  • references/d3-chat/src/components/ui/avatar.tsx (1 hunks)
  • references/d3-chat/src/lib/migrate.ts (1 hunks)
  • references/d3-chat/src/lib/slack.ts (1 hunks)
  • references/d3-chat/src/trigger/chat.ts (1 hunks)
  • references/d3-chat/src/trigger/python/crawler.py (1 hunks)
  • references/d3-chat/src/trigger/sandbox.ts (1 hunks)
  • references/d3-chat/src/trigger/schemas.ts (1 hunks)
  • references/d3-chat/tailwind.config.ts (1 hunks)
  • references/d3-chat/trigger.config.ts (1 hunks)
  • references/d3-openai-agents/.gitignore (1 hunks)
  • references/d3-openai-agents/README.md (1 hunks)
  • references/d3-openai-agents/components.json (1 hunks)
  • references/d3-openai-agents/next.config.ts (1 hunks)
  • references/d3-openai-agents/package.json (3 hunks)
  • references/d3-openai-agents/postcss.config.mjs (1 hunks)
  • references/d3-openai-agents/src/app/api/slack/interaction/route.ts (1 hunks)
  • references/d3-openai-agents/src/app/globals.css (1 hunks)
  • references/d3-openai-agents/src/extensions/playwright.ts (1 hunks)
  • references/d3-openai-agents/src/lib/migrate.ts (1 hunks)
  • references/d3-openai-agents/src/lib/utils.ts (1 hunks)
  • references/d3-openai-agents/src/trigger/approval.ts (1 hunks)
  • references/d3-openai-agents/src/trigger/schemas.ts (1 hunks)
  • references/d3-openai-agents/tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Definitions (17)
packages/core/src/v3/otel/tracingSDK.ts (1)
packages/core/src/v3/index.ts (1)
  • VERSION (84-84)
references/d3-openai-agents/src/lib/utils.ts (1)
references/d3-chat/src/lib/utils.ts (1)
  • cn (4-6)
packages/cli-v3/src/entryPoints/dev-run-worker.ts (1)
apps/kubernetes-provider/src/index.ts (1)
  • err (680-696)
references/d3-openai-agents/src/trigger/schemas.ts (1)
references/d3-chat/src/trigger/schemas.ts (2)
  • QueryApproval (12-14)
  • QueryApproval (16-16)
references/d3-chat/trigger.config.ts (2)
references/d3-chat/src/extensions/playwright.ts (1)
  • installPlaywrightChromium (4-36)
references/d3-openai-agents/src/extensions/playwright.ts (1)
  • installPlaywrightChromium (4-36)
apps/webapp/app/components/runs/v3/RunIcon.tsx (1)
apps/webapp/app/assets/icons/PythonLogoIcon.tsx (1)
  • PythonLogoIcon (1-21)
references/d3-chat/src/trigger/schemas.ts (1)
references/d3-openai-agents/src/trigger/schemas.ts (4)
  • AgentLoopMetadata (3-8)
  • AgentLoopMetadata (10-10)
  • QueryApproval (42-44)
  • QueryApproval (46-46)
packages/core/src/v3/workers/taskExecutor.ts (2)
packages/core/src/v3/semanticInternalAttributes.ts (1)
  • SemanticInternalAttributes (1-61)
packages/core/src/v3/index.ts (1)
  • SemanticInternalAttributes (21-21)
references/d3-chat/src/app/api/slack/interaction/route.ts (1)
references/d3-openai-agents/src/app/api/slack/interaction/route.ts (1)
  • POST (11-79)
references/d3-chat/src/app/layout.tsx (1)
references/d3-openai-agents/src/app/layout.tsx (2)
  • metadata (15-18)
  • RootLayout (20-34)
references/d3-chat/src/trigger/chat.ts (2)
references/d3-chat/src/lib/slack.ts (1)
  • sendSQLApprovalMessage (15-114)
references/d3-chat/src/trigger/schemas.ts (2)
  • QueryApproval (12-14)
  • QueryApproval (16-16)
references/d3-openai-agents/src/app/api/slack/interaction/route.ts (1)
references/d3-chat/src/app/api/slack/interaction/route.ts (1)
  • POST (11-79)
packages/core/src/v3/taskContext/otelProcessors.ts (3)
packages/core/src/v3/tracer.ts (1)
  • tracer (45-53)
packages/core/src/v3/index.ts (2)
  • SemanticInternalAttributes (21-21)
  • flattenAttributes (43-43)
packages/trigger-sdk/src/v3/shared.ts (1)
  • Context (119-119)
references/d3-chat/src/components/chat-message.tsx (1)
references/d3-chat/src/components/ui/avatar.tsx (1)
  • Avatar (53-53)
references/d3-chat/src/components/chat-container.tsx (4)
references/d3-chat/src/trigger/chat.ts (2)
  • todoChat (115-204)
  • STREAMS (216-218)
references/d3-chat/src/components/tool-call-message.tsx (1)
  • ToolCallMessage (7-71)
references/d3-chat/src/components/chat-message.tsx (1)
  • ChatMessage (22-59)
references/d3-chat/src/components/chat-input.tsx (1)
  • ChatInput (8-44)
packages/core/src/v3/types/schemas.ts (1)
packages/core/src/v3/index.ts (3)
  • isSchemaZodEsque (77-77)
  • isSchemaValibotEsque (78-78)
  • isSchemaArkTypeEsque (79-79)
packages/trigger-sdk/src/v3/ai.ts (2)
packages/core/src/v3/types/schemas.ts (3)
  • Schema (74-74)
  • inferSchemaIn (91-94)
  • isSchemaZodEsque (6-16)
packages/core/src/v3/index.ts (1)
  • isSchemaZodEsque (77-77)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (81)
references/d3-openai-agents/tsconfig.json (6)

1-4: Configuration Base Validity Check.
The JSON snippet correctly initializes the base configuration with a proper ECMAScript target and library set (ES2017, "dom", "dom.iterable", "esnext"). This foundational setup is well-suited for modern web projects and Next.js usage.


5-15: Strictness and Transpilation Settings Verification.
The options such as "allowJs": true, "strict": true, and "noEmit": true ensure robust type-checking while deferring the emitting responsibility to Next.js’ build process. These are standard and beneficial defaults for a Next.js project.


16-20: Next.js Plugin Inclusion Check.
The plugins array, which includes the Next.js plugin ("name": "next"), is correctly configured. This should help in providing Next.js–specific enhancements during compilation. Verify that the necessary tooling/dependencies for this plugin are installed in the project.


21-24: Alias Paths Configuration.
The paths configuration mapping "@/*" to "./src/*" is well set up to facilitate cleaner imports. This aligns with common project structures and should help improve code readability and maintainability.


25-26: Include/Exclude Directives Check.
The "include" array covers TypeScript files and Next.js-specific type definitions, while "exclude": ["node_modules"] is typical to avoid unnecessary compilation. This setup correctly scopes the TypeScript compiler to the project files.


10-11: Module Resolution Option Verification.
The configuration sets "module": "esnext" along with "moduleResolution": "bundler", which are newer settings optimized for modern build tools. Ensure that your project’s TypeScript version supports "bundler" resolution, and update documentation/team guidelines as needed.

references/d3-openai-agents/.gitignore (10)

1-2: Header Documentation is Clear
The introductory comment provides a useful reference link to GitHub’s documentation on ignoring files, which is helpful for future maintainers.


3-12: Dependency Ignore Rules Are Well-Defined
The rules for ignoring dependency directories (such as /node_modules, /.pnp, and .yarn/*) are correctly specified. The exceptions for specific .yarn subdirectories (patches, plugins, releases, versions) are well-considered and help ensure essential files are tracked while omitting auto-managed resources.


13-15: Testing Artifacts Are Excluded
Ignoring the /coverage directory is standard practice for test coverage files. This rule helps keep the repository clean.


16-19: Next.js Build Outputs Are Appropriately Ignored
The rules for excluding Next.js build outputs (/next/ and /out/) ensure that temporary build artifacts are not committed.


20-22: Production Build Directory Is Ignored
The exclusion of the /build directory aligns well with typical production build setups, helping avoid unnecessary file commits.


23-26: Miscellaneous Files Exclusion Is Properly Handled
Ignoring common OS-specific files (e.g., .DS_Store) and PEM files is a good practice to ensure that sensitive or system-specific files do not leak into the repository.


27-32: Debug Log Files Are Carefully Excluded
The ignore patterns for various debug log files (npm, yarn, and pnpm) are comprehensive and help maintain a clean working directory.


33-35: Environment Files Exclusion Allows for Flexibility
The rule to ignore .env* files is standard for protecting sensitive configurations. The comment notes an opt-in mechanism, which is beneficial for developers who may want to commit certain environment files under controlled circumstances.


36-38: Vercel Directory Is Correctly Ignored
Excluding the .vercel directory is appropriate for preventing deployment-specific settings and configurations from being versioned.


39-41: TypeScript Build Artifacts Are Excluded
The ignore patterns for TypeScript build information files (*.tsbuildinfo) and Next.js environment types (next-env.d.ts) are correctly applied, ensuring that build artifacts are not tracked in version control.

apps/webapp/package.json (1)

261-261: Good practice to end files with a newline.

Adding a newline at the end of the file follows standard coding best practices and helps prevent issues with some tools and version control systems when concatenating files.

references/d3-openai-agents/README.md (1)

1-37: LGTM: Standard Next.js README.

This is a well-structured README file generated by create-next-app that provides clear instructions for development, learning resources, and deployment options.

apps/webapp/app/v3/otlpExporter.server.ts (1)

60-60: Improved logging with contextual prefixes.

Adding a prefix parameter to differentiate between trace and log exports in the logs is a good enhancement for debugging and monitoring. The implementation is consistent across all call sites.

Also applies to: 87-87, 101-106

packages/core/src/v3/types/schemas.ts (3)

6-16: Great addition of type guard for Zod schemas.

This type guard function correctly checks for the presence of required properties that identify a Zod schema, enhancing type safety when working with schema objects at runtime.


27-31: Well-implemented type guard for Valibot schemas.

The function provides a simple yet effective way to identify Valibot schema objects at runtime by checking for the _types property.


38-42: Solid type guard implementation for ArkType schemas.

This type guard completes the set of schema validators by checking for ArkType-specific properties (_inferIn and _infer), maintaining consistency with the other type guards.

references/d3-openai-agents/next.config.ts (1)

3-5:

❓ Verification inconclusive

Empty Next.js configuration with placeholder comment.

The Next.js configuration currently contains only a placeholder comment. If this is intentional as a starting point, it's fine. However, if specific configuration options are needed for the project, they should be added here.


🏁 Script executed:

#!/bin/bash
# Check if there are any specific Next.js config options used in imports or component files
grep -r "next/config" --include="*.ts" --include="*.tsx" references/d3-openai-agents/src

Length of output: 88


Action Required: Confirm Next.js Configuration Intent

It appears that the file references/d3-openai-agents/next.config.ts currently provides only a placeholder configuration. Our initial search for any usage of next/config in the source files did not return any references, suggesting that the project might not be leveraging any custom Next.js configuration options at the moment. If this minimal setup is intentional for your project's needs, then no changes are required. However, if you expect to rely on specific Next.js features that require additional configuration, please update the file accordingly.

  • Please verify whether the placeholder configuration is by design.
  • If specific Next.js configuration options are needed later, they should be added in this file.
packages/core/src/v3/workers/taskExecutor.ts (1)

975-975: Icon naming convention update

The icon referenced for the waitUntil functionality has been updated from "clock" to "tabler-clock", which aligns with the tabler icon naming convention used elsewhere in the codebase.

references/d3-chat/src/app/page.tsx (2)

8-15: LGTM on component structure

The component follows good React patterns with a clean separation between the header and main content, and properly passes the required props to child components.


5-7:

✅ Verification successful

Verify token security implications

The code creates a public trigger token for "todo-chat". Consider whether this token generation should have additional security controls or if the public nature is intentional.


🏁 Script executed:

#!/bin/bash
# Search for other instances of createTriggerPublicToken to understand usage patterns
rg "createTriggerPublicToken" -A 2 -B 2

Length of output: 6349


Token Security Confirmation: Intentional Public Exposure

After reviewing similar usage patterns across the codebase and documentation, it's clear that calling

const triggerToken = await auth.createTriggerPublicToken("todo-chat");

is consistent with our design for one-time trigger tokens (as seen in other examples like "chat-example", "openai-streaming", and documented in our guides). This public token creation is intentional, though you might still consider:

  • Using optional parameters (such as an explicit expirationTime) if tighter control is needed.
  • Confirming that the current token settings meet the security requirements for your specific use case.
apps/webapp/app/components/runs/v3/RunIcon.tsx (1)

76-76: Fixed styling inheritance for PythonLogoIcon

Now passing the className prop to the PythonLogoIcon component, allowing it to properly inherit styling applied to the icon. This makes styling consistent with other icon handling in the file.

references/d3-openai-agents/components.json (1)

6-12: Verify the Tailwind configuration path

The config field in the Tailwind configuration is empty. Ensure this is intentional, or specify the path to your Tailwind config file if needed.

If you're using a custom Tailwind configuration, you should specify the path relative to the project root:

  "tailwind": {
-    "config": "",
+    "config": "tailwind.config.js",
    "css": "src/app/globals.css",
    "baseColor": "neutral",
    "cssVariables": true,
    "prefix": ""
  },
packages/cli-v3/src/entryPoints/dev-run-worker.ts (1)

436-438: Improved error handling with detailed error information

Adding message and stack trace information when available enhances debugging capabilities. This change brings consistency with the error handling pattern used elsewhere in the file.

.vscode/launch.json (1)

153-160: LGTM: New debug configuration for d3-demo

This configuration follows the established pattern for debug configurations in the project and will improve the developer experience when working with the d3-demo reference implementation.

references/d3-chat/trigger.config.ts (1)

1-20: Configuration looks good and properly integrates project components

The configuration properly sets up the project with:

  1. Python extension for running Python scripts
  2. Playwright Chromium for browser automation
  3. Reasonable maximum duration setting (3600 seconds)

The configuration aligns with the imported installPlaywrightChromium extension functionality.

references/d3-openai-agents/src/app/globals.css (1)

1-122: Well-structured CSS with modern features and theming

The CSS implementation is well-organized and uses modern features:

  1. Proper use of Tailwind CSS integration
  2. Theme variables for consistent styling
  3. Dark mode support with variant customization
  4. Modern color representation with the oklch color space

The base styling and CSS variables provide a solid foundation for consistent UI styling across the application.

packages/core/src/v3/otel/tracingSDK.ts (1)

144-159: Enhanced span processor with explicit tracer

Adding a specific tracer instance to the TaskContextSpanProcessor improves the tracing capabilities by explicitly configuring the processor with the "trigger-dev-worker" tracer and version information.

This change enhances telemetry without altering control flow, ensuring proper instrumentation.

references/d3-chat/src/components/ui/avatar.tsx (2)

1-54: Well-structured component implementation using Radix UI primitives

The implementation follows React best practices with proper component composition and reusability. Each component is correctly typed with React.ComponentProps and leverages Radix UI primitives for accessibility.

Consider adding JSDoc comments to each component to document their purpose and usage patterns for better developer experience.


6-6:

✅ Verification successful

Verify the availability of the cn utility function

Ensure that the cn utility function exists in the referenced path. Based on typical implementations, this function is likely a utility for merging class names with libraries like clsx or tailwind-merge.


🏁 Script executed:

#!/bin/bash
# Check if the cn utility function exists
if [ -f "references/d3-chat/src/lib/utils.ts" ]; then
  echo "File exists, checking content:"
  cat "references/d3-chat/src/lib/utils.ts" | grep -A 10 "export function cn"
else
  echo "File not found at references/d3-chat/src/lib/utils.ts"
  # Try to find it elsewhere
  fd --type f --exec grep -l "export function cn" {} \; | head -n 5
fi

Length of output: 274


CN utility verified; no issues found.

  • The file references/d3-chat/src/lib/utils.ts contains the cn function as expected:
    export function cn(...inputs: ClassValue[]) {
      return twMerge(clsx(inputs))
    }
  • The import in references/d3-chat/src/components/ui/avatar.tsx correctly references this utility.
references/d3-chat/src/trigger/schemas.ts (1)

1-17: Well-defined Zod schemas with proper type exports

The schemas are correctly implemented using Zod with appropriate type inferences. This provides both runtime validation and compile-time type checking.

references/d3-chat/src/app/layout.tsx (1)

1-30: Standard Next.js layout implementation

The layout follows Next.js conventions with proper metadata configuration and font loading. The structure is clean and provides a solid foundation for the application.

references/d3-chat/src/trigger/python/crawler.py (1)

1-25: Functional async web crawler implementation

The implementation using crawl4ai is clean and follows Python's async patterns well. The command-line interface correctly handles the basic case of missing arguments.

packages/core/src/v3/tracer.ts (3)

16-19: LGTM!

Clean import statements for the necessary dependencies used throughout the file.


151-159: LGTM!

The simplified startSpan method without the partial span logic is clean and straightforward.


83-148:

❓ Verification inconclusive

The code looks good, but verify all partial span logic was correctly moved.

The removal of the partial span creation logic from this method simplifies the code, which is good. However, you should verify that this functionality was properly moved to the TaskContextSpanProcessor class as mentioned in the summary.


🏁 Script executed:

#!/bin/bash
# Check if the TaskContextSpanProcessor properly implements the partial span logic

# Search for the TaskContextSpanProcessor implementation
rg "class TaskContextSpanProcessor" -A 20

Length of output: 1812


Review Verification: Partial Span Logic Handling

The new implementation in packages/core/src/v3/tracer.ts shows that the code now omits the previously embedded partial span creation logic. The responsibility for initializing span attributes related to task-level context now appears to be partially delegated to the TaskContextSpanProcessor class. Inspection of the TaskContextSpanProcessor implementation confirms that it sets task-related attributes (e.g., attempt ID and number) in its onStart method. Please ensure that any additional logic (such as usage measurement attributes previously recorded in tracer.ts) is now appropriately handled elsewhere (or intentionally omitted).

  • In tracer.ts (lines 83–148), partial span creation (e.g., usage measurement and setting usage-related attributes) remains inside the finally block. Confirm if this responsibility should be entirely migrated to TaskContextSpanProcessor or if it is acceptable to keep it here.
  • The TaskContextSpanProcessor currently sets task context attributes on span start; review if further processing (like usage measurement captured in tracer.ts) needs a corresponding implementation in the processor.

Please double-check that all aspects of the partial span logic have been fully transferred as intended.

references/d3-chat/tailwind.config.ts (4)

1-3: LGTM!

Clean import of the necessary Tailwind CSS configuration types and the typography plugin.


4-11: Comprehensive Tailwind configuration setup.

Good setup of the content paths to ensure Tailwind properly processes all relevant files. The content array includes all the necessary paths for the project structure.


12-109: Well-structured theme extension with comprehensive color system.

The theme extension is well-organized with carefully defined color palettes, custom fonts, and animations. The HSL variable approach for colors allows for easy theming and dark mode support.


110-112: LGTM!

Good use of the typography plugin to enhance text styling capabilities and proper export of the configuration.

packages/core/src/v3/index.ts (1)

72-80:

✅ Verification successful

Clean export expansion of schema-related utilities.

Good addition of type guard exports (isSchemaZodEsque, isSchemaValibotEsque, isSchemaArkTypeEsque) which will improve type safety by allowing runtime checks of schema objects.


🏁 Script executed:

#!/bin/bash
# Check the implementation of the new schema type guard functions

# Find the implementation of the schema type guards in the schemas.js file
rg "function isSchema(Zod|Valibot|ArkType)Esque" -A 10 --glob "**/*.ts"

Length of output: 2254


Confirmed: Clean and Correct Export of Schema Utilities

The implementation and export of the schema type guard functions (isSchemaZodEsque, isSchemaValibotEsque, isSchemaArkTypeEsque) have been validated and work as expected. The functions correctly perform runtime checks, and the export from packages/core/src/v3/index.ts cleanly expands the schema-related utilities without any issues.

  • Verified implementations in packages/core/src/v3/types/schemas.ts match review expectations.
  • Export statement in packages/core/src/v3/index.ts accurately reflects the new additions.
apps/webapp/app/v3/utils/enrichCreatableEvents.server.ts (2)

26-26: Improved icon generation for systems.

The change correctly extracts only the first part of the system name before the period, which likely produces more accurate and consistent icons.


35-43:

❓ Verification inconclusive

Enhanced icon logic for AI-related messages.

Good addition of specific icon handling for AI tool calls and other AI-related messages. This change improves the visual representation in the UI based on the message type.


🏁 Script executed:

#!/bin/bash
# Check for references to these icons in the UI components

# Look for the tabler-tool and tabler-sparkles icons in UI components
rg "tabler-(tool|sparkles)" --glob "**/*.tsx"

Length of output: 47


Enhanced icon logic for AI-related messages – Verification Needed

The updated code introduces specific icons for AI tool calls and other AI-related messages, which is a well-considered improvement for UI clarity. However, our automated search for the icons tabler-tool and tabler-sparkles in UI components did not return any matches. Please verify manually that these icons are referenced in the appropriate UI components (e.g., React components rendering messages) and that the new logic is effectively integrated.

  • Confirm that UI components display tabler-tool for "ai.toolCall" messages.
  • Confirm that UI components display tabler-sparkles for messages starting with "ai.".

If you discover that the icons are referenced in non-.tsx files or via an indirect import, please update the search paths accordingly.


To further investigate, you can run this additional shell script from the repository's root to search across all files:

#!/bin/bash
# Search for icon references in the entire codebase
echo "Searching for 'tabler-tool'..."
rg "tabler-tool"
echo "Searching for 'tabler-sparkles'..."
rg "tabler-sparkles"

Please review the output and verify that these icons are indeed supplied where needed.

references/d3-openai-agents/src/extensions/playwright.ts (1)

1-36: Well-implemented Playwright Chromium installation extension

This extension follows good practices for containerized environments by:

  • Installing only necessary dependencies
  • Setting up proper cleanup to reduce image size
  • Using specific environment variables to control browser behavior
  • Creating fixed paths for browser installation
references/d3-chat/src/components/chat-message.tsx (2)

1-3: No major issues
The imports and the basic ChatMessageProps interface are straightforward with no apparent bugs.

Also applies to: 5-9


22-59: Consider sanitizing Markdown content
By default, react-markdown does not sanitize malicious HTML. If the content prop originates from untrusted sources, you might be exposed to XSS attacks. To mitigate this, use remark/rehype plugins, such as rehype-sanitize, or consider a trusted HTML sanitization library.

packages/trigger-sdk/package.json (5)

26-27: Additional export entries
No issues found with adding these entries in the exports section for v3 and ai.


37-40: No major issues
Defining new typesVersions for ai is valid; no concerns noted.


73-73: Verify latest 'ai' library
The library has been updated to "ai": "^4.2.0". Ensure it is stable and free from breaking changes or security issues.


82-88: Optional peer dependency
Exposing "ai": "^4.2.0" as an optional peer dependency is a reasonable approach to flexibility for your consumers.


116-126:

❓ Verification inconclusive

Validate the new 'ai' export
Confirm that the new './ai' paths for both import and require exist and compile correctly in the final output:


🏁 Script executed:

#!/bin/bash
# Ensure 'ai.js' and 'ai.d.ts' exist in both ESM and CommonJS directories
fd "ai.js" dist | grep "esm/v3/ai.js"
fd "ai.d.ts" dist | grep "esm/v3/ai.d.ts"
fd "ai.js" dist | grep "commonjs/v3/ai.js"
fd "ai.d.ts" dist | grep "commonjs/v3/ai.d.ts"

Length of output: 529


Action: Manually Verify Build Outputs for the New 'ai' Export

It appears that the automated check for files under the dist directory did not return any results. This is likely because the build artifacts are not part of the committed repository but generated during the build process. Please confirm that after running the build, the expected files are generated at the following paths:

  • dist/esm/v3/ai.js
  • dist/esm/v3/ai.d.ts
  • dist/commonjs/v3/ai.js
  • dist/commonjs/v3/ai.d.ts

Once you run the build process and verify these files exist and compile correctly, the new './ai' export in packages/trigger-sdk/package.json can be validated.

references/d3-chat/src/lib/migrate.ts (2)

1-9: Initialization logic is straightforward
The migrate function cleanly delegates to migrateUp or migrateDown.


36-42: Table drop logic is correct
Using DROP TABLE IF EXISTS is safe and straightforward.

references/d3-chat/src/trigger/chat.ts (4)

14-27: Potential SSRF risk
The crawler tool fetches arbitrary URLs, which could be exploited. Consider validating or restricting domains to mitigate SSRF attacks.


29-64: Approval flow logic
The wait token, Slack message, and subsequent check for approval appear secure and well-structured.


66-77: Execute SQL tool
The tool warns about arbitrary SQL execution, but requiring admin approval first is a sensible safeguard.


79-87: No major issues
Tool definitions for generateId and getUserId are concise and functionally correct.

Also applies to: 101-113

references/d3-chat/package.json (4)

1-4: Package configuration looks good.

Declaring the package as private under version 0.1.0 is straightforward. No issues detected here.


5-19:

❓ Verification inconclusive

Verify scripts referencing local environment paths.

The "python:install-browsers" script explicitly calls ./.venv/bin/playwright. Ensure that the virtual environment path (./.venv/bin) is correct and consistently provisioned across different environments or CI pipelines.


🏁 Script executed:

#!/bin/bash
# Confirm the existence of `.venv/bin/playwright` in the repository after environment setup.
# Ensure the script won't fail in a fresh clone or separate environment.
fd 'playwright' --exec ls -l {}

Length of output: 312


Attention: Ensure the Virtual Environment for Playwright Is Consistently Provisioned

  • The "python:install-browsers" script in references/d3-chat/package.json calls ./.venv/bin/playwright install.
  • A repository-wide search did not reveal any .venv/bin/playwright—this is expected if the virtual environment isn’t version-controlled.
  • Action Required: Verify that your setup process (both locally and in CI) reliably creates the .venv directory with the Playwright executable at the expected path. If this environment is managed externally or via setup scripts, please update documentation or include a provisioning step to avoid runtime failures.

20-43:

✅ Verification successful

Confirm the React version.

The react and react-dom dependencies are set to "^19.0.0". At the time of writing, the latest stable React version is 18.x. Verify whether 19.x is available or intended for a future release.


🌐 Web query:

What is the latest stable version of React?

💡 Result:

The latest stable version of React as of April 2025 is React 19, released on December 5, 2024[1][2][3]. This major update introduces several key features:

Main features in React 19:

  • Actions API for simplified async state management with automatic pending/error handling[2]
  • Improved Suspense with pre-warming capabilities for smoother loading states[2]
  • Enhanced hydration that better handles third-party scripts and browser extensions[2]
  • Advanced error handling with granular control through onCaughtError and onUncaughtError hooks[2]

React 19 follows semantic versioning and currently receives active support including new features, security updates, and bug fixes[1]. The npm package react@19.1.0 is listed as the most recent patch version[8].

Previous stable versions still receiving security updates include React 18 (supported until December 2024) and React 17 (security fixes only)[1]. Developers can upgrade using React 18.3 as an intermediate step to identify compatibility issues before moving to React 19[3].

Citations:


React Version Confirmed:
The latest stable version of React is now React 19, as verified by current release information. The dependency entries "react": "^19.0.0" and "react-dom": "^19.0.0" in references/d3-chat/package.json are correct and intentionally reflect this update.


44-55:

✅ Verification successful

Check Tailwind CSS version.

"tailwindcss": "^4.0.17" may be a future or custom release. Confirm that you genuinely need version 4.x instead of the stable 3.x line.


🌐 Web query:

What is the latest stable version of Tailwind CSS?

💡 Result:

The latest stable version of Tailwind CSS is v4.0, released on January 22, 2025[1][5][9]. This major update introduces significant architectural improvements and modern CSS features:

  • Performance enhancements with builds up to 5x faster and incremental builds completing in microseconds[1]
  • CSS-first configuration replacing JavaScript-based setups[1][3][9]
  • Modern web platform support including CSS variables, container queries, cascade layers, and advanced color management[1][8][9]
  • Simplified installation through automatic content detection and built-in Vite integration[1][4]

The current version (as of March 26, 2025) is 4.0.17 according to Wikipedia[8], with detailed upgrade guides available for migrating from v3.x[4][6]. Key resources include:

  • Official v4.0 announcement[1]
  • YouTube tutorials demonstrating new features and migration[9]
  • Flowbite's practical upgrade instructions[4]

Citations:


Tailwind CSS Version Confirmed

After verifying from the latest release information, the dependency "tailwindcss": "^4.0.17" in references/d3-chat/package.json indeed aligns with the current stable release (v4.0.17). No changes are needed here.

packages/core/src/v3/taskContext/otelProcessors.ts (5)

7-7: New Tracer import.

Importing Tracer from @opentelemetry/api aligns with the new partial span functionality. No concerns here.


11-11: Storing tracer as a class property.

Introducing a _tracer field maintains clarity in the processor’s implementation. Looks fine.


32-40: Partial span logic.

Creating a partial span upfront (lines 32–37) and ending it immediately (line 37) while calling this._innerProcessor.onStart(span, parentContext) ensures the original span remains intact. This approach seems correct for capturing partial metadata. No immediate issues.


58-60: isPartialSpan function.

Simple attribute check for SPAN_PARTIAL is clear and performant. No concerns.


13-14:

✅ Verification successful

Constructor change to accept a tracer.

Passing the tracer at construction is sensible. Confirm no external usage is still relying on the old constructor signature.


🏁 Script executed:

#!/bin/bash
# Search the codebase for all TaskContextSpanProcessor instantiations to ensure correct usage of new constructor signature.
ast-grep --pattern $'new TaskContextSpanProcessor($_, $_)' 

Length of output: 1454


Update Verified: New Constructor Signature Correctly Adopted
The search confirms that every instantiation of TaskContextSpanProcessor (specifically in packages/core/src/v3/otel/tracingSDK.ts) now passes two arguments—the tracer instance and the span processor—consistent with the updated constructor. No external usage relying on the old one-parameter signature was found.

references/d3-openai-agents/package.json (4)

2-2: Project name update.

Renaming to "references-d3-openai-agents" looks valid and consistent with the repository structure.


15-17: Database migration scripts.

The new "db:migrate" and "db:migrate:down" commands, leveraging tsx -r dotenv/config, appear consistent with your approach for environment-specific database migrations.


41-41: Dev dependency updates.

  • @trigger.dev/build: Using workspace:* is typical in monorepos.
  • dotenv: The added "dotenv": "16.4.7" is standard for environment configuration.
  • tsx: Updated to "4.19.3" is acceptable. If all tools remain compatible, no issues.

Also applies to: 45-45, 48-48


21-30:

✅ Verification successful

New dependencies for Slack, Postgres, and more.

Adding @slack/web-api, @vercel/postgres, and nanoid is fine if your feature requires them. Ensure these new libraries are well-integrated and used in the codebase.


🏁 Script executed:

#!/bin/bash
# Check for references to newly added dependencies
# This helps confirm the addition is aligned with actual usage.
rg '@slack/web-api|@vercel/postgres|nanoid'

Length of output: 11694


Dependency Usage & Integration Confirmed

The new dependencies have been verified across the codebase. Specifically:

  • @slack/web-api: Found in various trigger and chat modules (e.g., in both the references/d3-chat and references/d3-openai-agents directories).
  • @vercel/postgres: Confirmed in files such as src/trigger/approval.ts and migration scripts.
  • nanoid: Actively integrated in multiple parts of the codebase, including references in both agent and worker modules.

These observations confirm that the added libraries are being used as expected. Ensure ongoing tests cover their behavior, but no additional integration changes are required at this stage.

references/d3-chat/src/components/chat-container.tsx (1)

8-13: Leverage strong typing for message roles.
Defining the role property as a union of string literals is a good approach, ensuring type safety and clarity across different message types.

packages/trigger-sdk/src/v3/ai.ts (2)

85-88: Export naming is clear and concise.
Exporting ai as an object with both tool and currentToolOptions is straightforward, making library consumption easier.


59-65:

❓ Verification inconclusive

Confirm metadata retrieval aligns with usage patterns.
getToolOptionsFromMetadata returns ToolCallExecutionOptions | undefined. Confirm that downstream tools handle the undefined case properly to avoid potential runtime errors.


🏁 Script executed:

#!/bin/bash
# Verify correct usage of getToolOptionsFromMetadata in other files
rg -A 5 "getToolOptionsFromMetadata"

Length of output: 569


Metadata retrieval usage verified – please double-check downstream invocation handling.
The function getToolOptionsFromMetadata correctly returns ToolCallExecutionOptions | undefined based on the existence of metadata. In the current implementation, it’s assigned as the currentToolOptions property (i.e., a reference is provided rather than its immediate result). This suggests that the code intends for consumers to invoke the function later. While there is no obvious misuse from the grep output, please ensure that every downstream invocation of this function properly checks for an undefined return value to prevent any potential runtime errors.

references/d3-openai-agents/src/trigger/approval.ts (2)

70-70: Confirm wrapped tasks won't cause duplication or confusion.
const queryApproval = ai.tool(queryApprovalTask); is straightforward. Check for consistent naming across the codebase so it’s clear that queryApproval is derived from the same task as queryApprovalTask.


82-90: Ensure ID collisions are improbable.
Using nanoid(12) is good, but confirm that your ID combination (prefix + nanoid) is guaranteed to be unique enough for your domain scale. If collisions pose a risk, consider additional checks or a longer Nano ID.

references/d3-chat/requirements.txt (1)

1-2: Autogenerated File Header Review:
The header clearly indicates that this file was autogenerated using uv pip compile requirements.in -o requirements.txt. This is good as it reminds developers that manual changes might be overwritten by subsequent regenerations.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
.changeset/honest-files-decide.md (1)

5-5: Clarify Deprecation Message

The deprecation note stating “Deprecate toolTask and replace with ai.tool(mySchemaTask)” is clear and concise. It effectively communicates the change in usage to the developers. As a best practice, consider linking to a migration guide or additional documentation in the repository (if available) so that users can easily adapt to the new API.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4baf5c3 and e35a3ca.

📒 Files selected for processing (1)
  • .changeset/honest-files-decide.md (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
🔇 Additional comments (1)
.changeset/honest-files-decide.md (1)

1-3: Validate Changeset Header Structure

The YAML front matter using --- delimiters is correctly formatted. The entry "@trigger.dev/sdk": patch clearly indicates a patch release for the SDK. Ensure that this version bump aligns with your overall release strategy.

@matt-aitken matt-aitken merged commit 51bb3ee into main Apr 2, 2025
12 checks passed
@matt-aitken matt-aitken deleted the ea-branch-26 branch April 2, 2025 11:00
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