Skip to content

feat: include task owner email in tasks response#418

Open
arpitgupta1214 wants to merge 1 commit intotestfrom
codex/task-list-owner-email-api
Open

feat: include task owner email in tasks response#418
arpitgupta1214 wants to merge 1 commit intotestfrom
codex/task-list-owner-email-api

Conversation

@arpitgupta1214
Copy link
Copy Markdown
Collaborator

@arpitgupta1214 arpitgupta1214 commented Apr 9, 2026

Summary

  • include owner_email in the default GET /api/tasks response
  • enrich tasks through a single task-domain helper
  • add handler and enrichment tests for the new response shape

Testing

  • not run locally in this fresh worktree (no node_modules installed)

Summary by cubic

Add owner_email to the tasks API response and consolidate enrichment into enrichTasks to batch Trigger metadata and email lookups. Updates getTasksHandler and adds tests.

  • New Features

    • Tasks now include owner_email (string or null) from account_emails.
    • Batched enrichment returns recent_runs and upcoming per task.
  • Refactors

    • Replaced enrichTaskWithTriggerInfo with enrichTasks and updated getTasksHandler to use it.
    • Added tests: enrichTasks.test.ts, getTasksHandler.test.ts; removed enrichTaskWithTriggerInfo and its test.

Written for commit 650512b. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor
    • Consolidated task enrichment process by refactoring individual enrichment operations into a unified bulk operation. The system now processes all task enrichments together, improving code organization and maintainability while preserving all existing functionality and returning the same enriched task information including trigger metadata and owner details.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

Warning

Rate limit exceeded

@arpitgupta1214 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 23 minutes and 28 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 23 minutes and 28 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f39b47f7-2175-4758-b3ae-e833e071fae1

📥 Commits

Reviewing files that changed from the base of the PR and between f48c06f and 650512b.

⛔ Files ignored due to path filters (3)
  • lib/tasks/__tests__/enrichTaskWithTriggerInfo.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/tasks/__tests__/enrichTasks.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/tasks/__tests__/getTasksHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (3)
  • lib/tasks/enrichTaskWithTriggerInfo.ts
  • lib/tasks/enrichTasks.ts
  • lib/tasks/getTasksHandler.ts
📝 Walkthrough

Walkthrough

The pull request consolidates task enrichment logic by removing the per-task enrichTaskWithTriggerInfo function and replacing it with a new bulk enrichTasks function that enriches multiple scheduled actions simultaneously, also fetching owner email addresses. The handler is updated to call the consolidated enrichment function.

Changes

Cohort / File(s) Summary
Bulk Enrichment Refactoring
lib/tasks/enrichTaskWithTriggerInfo.ts, lib/tasks/enrichTasks.ts
Removed per-task enrichment module and introduced new bulk enrichment function that enriches tasks with Trigger.dev metadata (recent_runs, upcoming) and owner email. The new function consolidates trigger run fetching, error handling, and account email lookup into a single operation.
Handler Integration
lib/tasks/getTasksHandler.ts
Updated import and replaced per-task enrichment mapping with direct call to enrichTasks(), delegating concurrency and iteration logic to the bulk function.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🔄 Once scattered tasks now gathered tight,
Trigger data flows in unified flight,
Email addresses map with grace,
One function rules the enrichment space! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning Pull request fails clean code error handling requirements. Silent catch blocks without logging violate error handling best practices and prevent production debugging. Add logging to catch blocks with contextual information and extract trigger enrichment logic into a helper function to reduce nesting and improve observability.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/task-list-owner-email-api

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.

@arpitgupta1214 arpitgupta1214 force-pushed the codex/task-list-owner-email-api branch from f48c06f to 650512b Compare April 9, 2026 15:01
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 9, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 9, 2026 3:06pm

Request Review

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-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.

1 issue found across 6 files

Confidence score: 4/5

  • Test maintainability concern in lib/tasks/__tests__/getTasksHandler.test.ts: duplicated inline task fixtures and a 124-line file could make future changes harder, but it’s unlikely to affect runtime behavior.
  • Overall risk is low since the only issue is a style/maintainability note in tests, so this looks safe to merge.
  • Pay close attention to lib/tasks/__tests__/getTasksHandler.test.ts - consider extracting shared fixtures to reduce duplication and length.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/tasks/__tests__/getTasksHandler.test.ts">

<violation number="1" location="lib/tasks/__tests__/getTasksHandler.test.ts:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This test file is 124 lines, exceeding the 100-line limit. The task fixture objects are defined inline three times (raw tasks, mock return, assertion). Extract shared test fixtures into a helper (e.g., `makeTask()` factory) to eliminate the repetition and bring the file under 100 lines.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client
    participant API as getTasksHandler
    participant DB as Supabase (PostgreSQL)
    participant Logic as NEW: enrichTasks
    participant Trigger as Trigger.dev API

    Client->>API: GET /api/tasks
    API->>API: validateGetTasksQuery()

    alt Validation Failed
        API-->>Client: Return Error Response
    else Validation Success
        API->>DB: selectScheduledActions(query)
        DB-->>API: tasks[]

        Note over API,Trigger: Start Bulk Enrichment Process
        API->>Logic: NEW: enrichTasks(tasks)

        par NEW: Fetch Account Emails
            Logic->>DB: NEW: selectAccountEmails(uniqueAccountIds)
            DB-->>Logic: account_id mapping (emails)
        and CHANGED: Batch Trigger Metadata
            loop For each task with trigger_schedule_id
                Logic->>Trigger: fetchTriggerRuns(scheduleId)
                Trigger-->>Logic: recentRuns[]
                opt if runs exist
                    Logic->>Trigger: retrieveTaskRun(latestRunId)
                    Trigger-->>Logic: payload.upcoming[]
                end
            end
        end

        Note over Logic: Map emails and trigger data to task objects
        Logic-->>API: enrichedTasks[] (including owner_email)
        API-->>Client: 200 OK (tasks with owner_email, runs, and upcoming)
    end
Loading

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

@@ -0,0 +1,124 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 9, 2026

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This test file is 124 lines, exceeding the 100-line limit. The task fixture objects are defined inline three times (raw tasks, mock return, assertion). Extract shared test fixtures into a helper (e.g., makeTask() factory) to eliminate the repetition and bring the file under 100 lines.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/tasks/__tests__/getTasksHandler.test.ts, line 1:

<comment>This test file is 124 lines, exceeding the 100-line limit. The task fixture objects are defined inline three times (raw tasks, mock return, assertion). Extract shared test fixtures into a helper (e.g., `makeTask()` factory) to eliminate the repetition and bring the file under 100 lines.</comment>

<file context>
@@ -0,0 +1,124 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest, NextResponse } from "next/server";
+import { getTasksHandler } from "@/lib/tasks/getTasksHandler";
</file context>
Fix with Cubic

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
lib/tasks/getTasksHandler.ts (1)

14-47: Refactor getTasksHandler into smaller units.

This handler is over the 20-line guideline. Consider extracting success/error response builders (private helpers) to keep orchestration concise.

As per coding guidelines, **/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php}: “Flag functions longer than 20 lines” and “Keep functions small and focused”.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/tasks/getTasksHandler.ts` around lines 14 - 47, The getTasksHandler
function is too long; extract two private
helpers—buildTasksSuccessResponse(enrichedTasks) and
buildErrorResponse(error)—that each return the corresponding NextResponse.json
payload and headers (reuse getCorsHeaders()), then refactor getTasksHandler to
simply validate the query via validateGetTasksQuery, call selectScheduledActions
and enrichTasks, and return buildTasksSuccessResponse(enrichedTasks) inside the
try block and buildErrorResponse(error) in the catch; keep references to
validateGetTasksQuery, selectScheduledActions, enrichTasks, and getCorsHeaders
to locate where to wire the helpers.
lib/tasks/enrichTasks.ts (1)

27-84: Split enrichTasks into smaller private helpers.

enrichTasks is doing multiple jobs and is substantially over the function-size limits. Extracting internal helpers (e.g., trigger enrichment + email lookup) will improve readability and testability.

As per coding guidelines, lib/**/*.ts: “Single responsibility per function” and “Keep functions under 50 lines”; and **/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php}: “Flag functions longer than 20 lines” and “Keep functions small and focused”.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/tasks/enrichTasks.ts` around lines 27 - 84, enrichTasks is doing too many
things; split it into smaller private helpers to follow single-responsibility
and size guidelines: extract the trigger enrichment logic into a helper (e.g.,
fetchTriggerInfoEntries or enrichTriggerForTasks) that takes ScheduledAction[]
and returns TriggerInfoEntry[] by moving the Promise.all(tasks.map(...)) block
and its inner logic (fetchTriggerRuns, retrieveTaskRun, payload parsing, and
error handling) out of enrichTasks; extract the account/email logic into a
helper (e.g., getAccountEmailMap or fetchAccountEmails) that calls
selectAccountEmails and builds the emailByAccountId Map; then have enrichTasks
call these helpers and assemble the final array (or use a small
buildEnrichedTasks helper) so each function (fetchTriggerInfoEntries,
getAccountEmailMap, buildEnrichedTasks) is focused and under the size limits
while reusing the existing symbols (enrichTasks, fetchTriggerRuns,
retrieveTaskRun, selectAccountEmails).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/tasks/enrichTasks.ts`:
- Around line 49-57: The two empty catch blocks in lib/tasks/enrichTasks.ts
silently drop Trigger enrichment (the payload retrieval catch and the outer
Trigger.dev API catch) — update both to emit telemetry and contextual logs
instead of failing silently: capture and report the thrown error (message/stack)
and include task identifiers (e.g., task.id, any trigger id) plus which path was
taken (payload vs API fallback), and increment a telemetry/metric counter for
Trigger enrichment fallbacks so outages are visible; update the error handling
around the recentRuns/upcoming return points (referencing recentRuns, upcoming
and task.id) to call the existing telemetry/logger helper (or
Sentry/Telemetry.track) with this context before returning the fallback values.

---

Nitpick comments:
In `@lib/tasks/enrichTasks.ts`:
- Around line 27-84: enrichTasks is doing too many things; split it into smaller
private helpers to follow single-responsibility and size guidelines: extract the
trigger enrichment logic into a helper (e.g., fetchTriggerInfoEntries or
enrichTriggerForTasks) that takes ScheduledAction[] and returns
TriggerInfoEntry[] by moving the Promise.all(tasks.map(...)) block and its inner
logic (fetchTriggerRuns, retrieveTaskRun, payload parsing, and error handling)
out of enrichTasks; extract the account/email logic into a helper (e.g.,
getAccountEmailMap or fetchAccountEmails) that calls selectAccountEmails and
builds the emailByAccountId Map; then have enrichTasks call these helpers and
assemble the final array (or use a small buildEnrichedTasks helper) so each
function (fetchTriggerInfoEntries, getAccountEmailMap, buildEnrichedTasks) is
focused and under the size limits while reusing the existing symbols
(enrichTasks, fetchTriggerRuns, retrieveTaskRun, selectAccountEmails).

In `@lib/tasks/getTasksHandler.ts`:
- Around line 14-47: The getTasksHandler function is too long; extract two
private helpers—buildTasksSuccessResponse(enrichedTasks) and
buildErrorResponse(error)—that each return the corresponding NextResponse.json
payload and headers (reuse getCorsHeaders()), then refactor getTasksHandler to
simply validate the query via validateGetTasksQuery, call selectScheduledActions
and enrichTasks, and return buildTasksSuccessResponse(enrichedTasks) inside the
try block and buildErrorResponse(error) in the catch; keep references to
validateGetTasksQuery, selectScheduledActions, enrichTasks, and getCorsHeaders
to locate where to wire the helpers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 11e67991-2b9e-44fa-9927-4330ffb8b96a

📥 Commits

Reviewing files that changed from the base of the PR and between 7705373 and f48c06f.

⛔ Files ignored due to path filters (3)
  • lib/tasks/__tests__/enrichTaskWithTriggerInfo.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/tasks/__tests__/enrichTasks.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/tasks/__tests__/getTasksHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (3)
  • lib/tasks/enrichTaskWithTriggerInfo.ts
  • lib/tasks/enrichTasks.ts
  • lib/tasks/getTasksHandler.ts
💤 Files with no reviewable changes (1)
  • lib/tasks/enrichTaskWithTriggerInfo.ts

Comment on lines +49 to +57
} catch {
// payload retrieval failed — skip upcoming
}
}

return [task.id, { recent_runs: recentRuns, upcoming }] as const;
} catch {
// Trigger.dev API failed — return task without trigger enrichment
return [task.id, { recent_runs: [], upcoming: [] }] as const;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add telemetry for fallback paths in Trigger enrichment.

Both catch blocks silently downgrade data (recent_runs/upcoming) without logging. That makes Trigger outages invisible and hard to debug in production.

Suggested fix
-          } catch {
-            // payload retrieval failed — skip upcoming
+          } catch (error) {
+            console.warn("Failed to retrieve Trigger run payload", {
+              taskId: task.id,
+              runId: latestRun.id,
+              error: error instanceof Error ? error.message : String(error),
+            });
           }
@@
-      } catch {
-        // Trigger.dev API failed — return task without trigger enrichment
+      } catch (error) {
+        console.warn("Failed to fetch Trigger runs", {
+          taskId: task.id,
+          scheduleId,
+          error: error instanceof Error ? error.message : String(error),
+        });
         return [task.id, { recent_runs: [], upcoming: [] }] as const;
       }

As per coding guidelines, **/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php}: “Handle errors gracefully”.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch {
// payload retrieval failed — skip upcoming
}
}
return [task.id, { recent_runs: recentRuns, upcoming }] as const;
} catch {
// Trigger.dev API failed — return task without trigger enrichment
return [task.id, { recent_runs: [], upcoming: [] }] as const;
} catch (error) {
console.warn("Failed to retrieve Trigger run payload", {
taskId: task.id,
runId: latestRun.id,
error: error instanceof Error ? error.message : String(error),
});
}
}
return [task.id, { recent_runs: recentRuns, upcoming }] as const;
} catch (error) {
console.warn("Failed to fetch Trigger runs", {
taskId: task.id,
scheduleId,
error: error instanceof Error ? error.message : String(error),
});
return [task.id, { recent_runs: [], upcoming: [] }] as const;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/tasks/enrichTasks.ts` around lines 49 - 57, The two empty catch blocks in
lib/tasks/enrichTasks.ts silently drop Trigger enrichment (the payload retrieval
catch and the outer Trigger.dev API catch) — update both to emit telemetry and
contextual logs instead of failing silently: capture and report the thrown error
(message/stack) and include task identifiers (e.g., task.id, any trigger id)
plus which path was taken (payload vs API fallback), and increment a
telemetry/metric counter for Trigger enrichment fallbacks so outages are
visible; update the error handling around the recentRuns/upcoming return points
(referencing recentRuns, upcoming and task.id) to call the existing
telemetry/logger helper (or Sentry/Telemetry.track) with this context before
returning the fallback values.

@arpitgupta1214
Copy link
Copy Markdown
Collaborator Author

Smoke-tested the latest branch preview:

Verified results:

  • response status was 200
  • task rows now include the new owner_email field

Example from the live response:

{
  "status": "success",
  "tasks": [
    {
      "id": "df8a6224-0eb1-49a7-86da-805d77f96b96",
      "account_id": "24994fe8-e63c-4c4a-867e-f38976e3fd31",
      "owner_email": "arpitgupta1214@gmail.com"
    }
  ]
}

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