Conversation
|
This repository is associated with MrgSub whose free trial has ended. Subscribe at jazzberry.ai. |
|
Caution Review failedThe pull request is closed. WalkthroughThis update introduces an Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant AgentRPC
participant Agent
participant DB
Client->>AgentRPC: getThread(threadId, includeDrafts)
AgentRPC->>Agent: getThread(threadId, includeDrafts)
Agent->>DB: getThreadFromDB(threadId, includeDrafts)
DB-->>Agent: Thread (with/without drafts, isLatestDraft)
Agent-->>AgentRPC: Thread response
AgentRPC-->>Client: Thread response
sequenceDiagram
participant WorkflowRunner
participant DB
participant Gmail
participant Logger
WorkflowRunner->>DB: Fetch agent/thread data
WorkflowRunner->>Gmail: Fetch Gmail history/threads
WorkflowRunner->>Logger: Log execution steps
WorkflowRunner->>DB: Sync threads, process labels
WorkflowRunner->>DB: Clean up processing flags
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (9)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
This stack of pull requests is managed by Graphite. Learn more about stacking. |
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
🚨 Bugbot Trial ExpiredYour Bugbot trial has expired. Please purchase a license in the Cursor dashboard to continue using Bugbot. |
There was a problem hiding this comment.
cubic analysis
7 issues found across 9 files • Review in cubic
React with 👍 or 👎 to teach cubic. You can also tag @cubic-dev-ai to give feedback, ask questions, or re-run the review.
| ): Promise<boolean> => { | ||
| if (!thread.messages || thread.messages.length === 0) return false; | ||
| if (!thread.messages || thread.messages.length === 0) { | ||
| console.log('[SHOULD_GENERATE_DRAFT] No messages in thread'); |
There was a problem hiding this comment.
Direct console.log calls in server-side code bypass the project’s structured logging system, making log filtering and correlation harder in production environments. Replace with the standard logger or remove these statements. (Based on your team's feedback about avoiding console statements in production code.)
Prompt for AI agents
Address the following comment on apps/server/src/thread-workflow-utils/index.ts at line 11:
<comment>Direct console.log calls in server-side code bypass the project’s structured logging system, making log filtering and correlation harder in production environments. Replace with the standard logger or remove these statements. (Based on your team's feedback about avoiding console statements in production code.)</comment>
<file context>
@@ -1,66 +1,70 @@
import type { IGetThreadResponse } from '../lib/driver/types';
import { composeEmail } from '../trpc/routes/ai/compose';
-import { getZeroAgent } from '../lib/server-utils';
import { type ParsedMessage } from '../types';
import { connection } from '../db/schema';
const shouldGenerateDraft = async (
thread: IGetThreadResponse,
foundConnection: typeof connection.$inferSelect,
</file context>
| const { activeConnection } = ctx; | ||
| const agent = await getZeroAgent(activeConnection.id); | ||
| return await agent.getThread(input.id); | ||
| return await agent.getThread(input.id, true); |
There was a problem hiding this comment.
agent.getThread is now called with includeDrafts=true, which (per the PR description) adds an isLatestDraft flag to the response. However, the tRPC endpoint still validates the response against IGetThreadResponseSchema, which does not contain this field. Zod will silently strip the flag, preventing the client from seeing it and defeating the purpose of the change. Update the schema (and the .output typing) to include isLatestDraft or use .passthrough() to allow the extra key. (Based on your team's feedback about keeping runtime schemas in sync with new response fields.)
Prompt for AI agents
Address the following comment on apps/server/src/trpc/routes/mail.ts at line 43:
<comment>agent.getThread is now called with includeDrafts=true, which (per the PR description) adds an `isLatestDraft` flag to the response. However, the tRPC endpoint still validates the response against `IGetThreadResponseSchema`, which does not contain this field. Zod will silently strip the flag, preventing the client from seeing it and defeating the purpose of the change. Update the schema (and the .output typing) to include `isLatestDraft` or use `.passthrough()` to allow the extra key. (Based on your team's feedback about keeping runtime schemas in sync with new response fields.)</comment>
<file context>
@@ -40,7 +40,7 @@ export const mailRouter = router({
.query(async ({ input, ctx }) => {
const { activeConnection } = ctx;
const agent = await getZeroAgent(activeConnection.id);
- return await agent.getThread(input.id);
+ return await agent.getThread(input.id, true);
}),
count: activeDriverProcedure
</file context>
| try { | ||
| console.log('[THREAD_WORKFLOW] Getting thread:', threadId); | ||
| thread = await agent.getThread(threadId.toString()); | ||
| console.log('[THREAD_WORKFLOW] Found thread with messages:', thread.messages.length); |
There was a problem hiding this comment.
Assumes thread.messages is always defined; calling .length on undefined can throw at runtime.
Prompt for AI agents
Address the following comment on apps/server/src/pipelines.ts at line 792:
<comment>Assumes `thread.messages` is always defined; calling `.length` on undefined can throw at runtime.</comment>
<file context>
@@ -709,4 +734,533 @@ export class WorkflowRunner extends DurableObject<Env> {
Effect.provide(loggerLayer),
);
}
+
+ /** Testing workflows without Effect */
+ public runThreadWorkflowWithoutEffect(params: ThreadWorkflowParams): Promise<string> {
+ return this.runThreadWorkflowWithoutEffectImpl(params);
+ }
+
</file context>
| console.log('[THREAD_WORKFLOW] Found thread with messages:', thread.messages.length); | |
| console.log('[THREAD_WORKFLOW] Found thread with messages:', thread.messages?.length ?? 0); |
| const response = await this.env.gmail_processing_threads.put(historyProcessingKey, 'true', { | ||
| expirationTtl: 3600, | ||
| }); | ||
| lockAcquired = response !== null; |
There was a problem hiding this comment.
Lock acquisition check always succeeds because KV put() returns void (undefined); response !== null will never be false, so concurrent executions are not prevented.
Prompt for AI agents
Address the following comment on apps/server/src/pipelines.ts at line 987:
<comment>Lock acquisition check always succeeds because KV `put()` returns void (undefined); `response !== null` will never be false, so concurrent executions are not prevented.</comment>
<file context>
@@ -709,4 +734,533 @@ export class WorkflowRunner extends DurableObject<Env> {
Effect.provide(loggerLayer),
);
}
+
+ /** Testing workflows without Effect */
+ public runThreadWorkflowWithoutEffect(params: ThreadWorkflowParams): Promise<string> {
+ return this.runThreadWorkflowWithoutEffectImpl(params);
+ }
+
</file context>
| "AUTORAG_ID": "", | ||
| "USE_OPENAI": "true", | ||
| "CLOUDFLARE_ACCOUNT_ID": "397b3b4fac213b9b382d0f1fafdbb215", | ||
| "CLOUDFLARE_API_TOKEN": "wbrJ9McsQhjCxv1pzxLLK8keT-0tM1ab-QbmESg6", |
There was a problem hiding this comment.
A live Cloudflare API token is committed in plain text; this is a serious security leak that grants full account access.
Prompt for AI agents
Address the following comment on apps/server/wrangler.jsonc at line 137:
<comment>A live Cloudflare API token is committed in plain text; this is a serious security leak that grants full account access.</comment>
<file context>
@@ -130,9 +130,11 @@
"DROP_AGENT_TABLES": "false",
"THREAD_SYNC_MAX_COUNT": "5",
"THREAD_SYNC_LOOP": "false",
- "DISABLE_WORKFLOWS": "false",
+ "DISABLE_WORKFLOWS": "true",
"AUTORAG_ID": "",
"USE_OPENAI": "true",
+ "CLOUDFLARE_ACCOUNT_ID": "397b3b4fac213b9b382d0f1fafdbb215",
+ "CLOUDFLARE_API_TOKEN": "wbrJ9McsQhjCxv1pzxLLK8keT-0tM1ab-QbmESg6",
</file context>
| "CLOUDFLARE_API_TOKEN": "wbrJ9McsQhjCxv1pzxLLK8keT-0tM1ab-QbmESg6", | |
| "CLOUDFLARE_API_TOKEN": "${CLOUDFLARE_API_TOKEN}", |
|
|
||
| generateLabels: async (context) => { | ||
| const summaryResult = context.results?.get('generate-thread-summary'); | ||
| console.log(summaryResult, context.results); |
There was a problem hiding this comment.
Dumping summaryResult together with context.results can leak sensitive data and flood the logs; prefer structured logging or limit the output.
Prompt for AI agents
Address the following comment on apps/server/src/thread-workflow-utils/workflow-functions.ts at line 397:
<comment>Dumping summaryResult together with context.results can leak sensitive data and flood the logs; prefer structured logging or limit the output.</comment>
<file context>
@@ -413,6 +394,7 @@ export const workflowFunctions: Record<string, WorkflowFunction> = {
generateLabels: async (context) => {
const summaryResult = context.results?.get('generate-thread-summary');
+ console.log(summaryResult, context.results);
if (!summaryResult?.summary) {
console.log('[WORKFLOW_FUNCTIONS] No summary available for label generation');
</file context>
| console.log(summaryResult, context.results); | |
| console.log('[WORKFLOW_FUNCTIONS] Summary generation result:', { summary: summaryResult?.summary }); |
| }; | ||
|
|
||
| history.forEach((historyItem) => { | ||
| historyItem.messagesAdded?.forEach((msg) => { |
There was a problem hiding this comment.
Rule violated: Detect Typescript Performance Bottlenecks
Nested forEach over messagesAdded inside another forEach over history can cause significant performance issues when Gmail history contains many entries. Consider flattening data or using maps/sets to avoid O(n²) iteration.
Prompt for AI agents
Address the following comment on apps/server/src/pipelines.ts at line 1101:
<comment>Nested forEach over `messagesAdded` inside another forEach over `history` can cause significant performance issues when Gmail history contains many entries. Consider flattening data or using maps/sets to avoid O(n²) iteration.</comment>
<file context>
@@ -709,4 +734,533 @@ export class WorkflowRunner extends DurableObject<Env> {
Effect.provide(loggerLayer),
);
}
+
+ /** Testing workflows without Effect */
+ public runThreadWorkflowWithoutEffect(params: ThreadWorkflowParams): Promise<string> {
+ return this.runThreadWorkflowWithoutEffectImpl(params);
+ }
+
</file context>

Description
Added support for draft detection in email threads to improve the auto-draft generation workflow. This PR adds an
isLatestDraftflag to thread responses, allowing the system to check if a draft already exists in a thread without making additional API calls. The workflow engine has been optimized to skip draft generation for threads that already have drafts, automated emails, or messages older than 7 days.Additionally, implemented non-Effect.ts versions of the workflow functions to provide an alternative implementation path that doesn't rely on the Effect library, which will help with testing and debugging.
Type of Change
Areas Affected
Testing Done
Checklist
Additional Notes
The draft detection improvements reduce unnecessary API calls to check for existing drafts, which should improve performance and reduce the likelihood of hitting API rate limits. The workflow engine now also properly skips automated emails and old threads, focusing resources on generating drafts only for relevant conversations.
By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.
Summary by CodeRabbit
New Features
Improvements
Configuration