Skip to content

Commit 2ace344

Browse files
authored
Remove unused code and optimize database connections (#1778)
# READ CAREFULLY THEN REMOVE Remove bullet points that are not relevant. PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI. - Pull requests that do not follow these guidelines will be closed without review or comment. - If you use AI to write your PR description your pr will be close without review or comment. - If you are unsure about anything, feel free to ask for clarification. ## Description Please provide a clear description of your changes. --- ## Type of Change Please delete options that are not relevant. - [ ] 🐛 Bug fix (non-breaking change which fixes an issue) - [ ] ✨ New feature (non-breaking change which adds functionality) - [ ] 💥 Breaking change (fix or feature with breaking changes) - [ ] 📝 Documentation update - [ ] 🎨 UI/UX improvement - [ ] 🔒 Security enhancement - [ ] ⚡ Performance improvement ## Areas Affected Please check all that apply: - [ ] Email Integration (Gmail, IMAP, etc.) - [ ] User Interface/Experience - [ ] Authentication/Authorization - [ ] Data Storage/Management - [ ] API Endpoints - [ ] Documentation - [ ] Testing Infrastructure - [ ] Development Workflow - [ ] Deployment/Infrastructure ## Testing Done Describe the tests you've done: - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing performed - [ ] Cross-browser testing (if UI changes) - [ ] Mobile responsiveness verified (if UI changes) ## Security Considerations For changes involving data or authentication: - [ ] No sensitive data is exposed - [ ] Authentication checks are in place - [ ] Input validation is implemented - [ ] Rate limiting is considered (if applicable) ## Checklist - [ ] I have read the [CONTRIBUTING](https://github.com/Mail-0/Zero/blob/staging/.github/CONTRIBUTING.md) document - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in complex areas - [ ] I have updated the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix/feature works - [ ] All tests pass locally - [ ] Any dependent changes are merged and published ## Additional Notes Add any other context about the pull request here. ## Screenshots/Recordings Add screenshots or recordings here if applicable. --- _By submitting this pull request, I confirm that my contribution is made under the terms of the project's license._ <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Removed unused code and improved database connection handling to reduce resource usage and simplify maintenance. - **Refactors** - Deleted unused constants and imports. - Cleaned up database connection logic to avoid unnecessary connections and disposals. - Simplified error handling in thread retrieval. <!-- End of auto-generated description by cubic. -->
1 parent 6cc6730 commit 2ace344

File tree

4 files changed

+17
-28
lines changed

4 files changed

+17
-28
lines changed

apps/server/src/lib/prompts.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ import { format } from 'date-fns';
22
import { Tools } from '../types';
33
import dedent from 'dedent';
44

5-
const CATEGORY_IDS = ['Important', 'All Mail', 'Personal', 'Updates', 'Promotions', 'Unread'];
6-
75
export const colors = [
86
'#000000',
97
'#434343',

apps/server/src/main.ts

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,18 @@ import {
1414
userSettings,
1515
writingStyleMatrix,
1616
} from './db/schema';
17-
import { getZeroAgent } from './lib/server-utils';
1817
import { env, WorkerEntrypoint, DurableObject, RpcTarget } from 'cloudflare:workers';
1918
import { EProviders, type ISubscribeBatch, type IThreadBatch } from './types';
2019
import { oAuthDiscoveryMetadata } from 'better-auth/plugins';
2120
import { getZeroDB, verifyToken } from './lib/server-utils';
2221
import { eq, and, desc, asc, inArray } from 'drizzle-orm';
2322
import { EWorkflowType, runWorkflow } from './pipelines';
23+
import { ZeroAgent, ZeroDriver } from './routes/agent';
2424
import { contextStorage } from 'hono/context-storage';
2525
import { defaultUserSettings } from './lib/schemas';
2626
import { createLocalJWKSet, jwtVerify } from 'jose';
2727
import { routePartykitRequest } from 'partyserver';
28-
29-
import { ZeroAgent, ZeroDriver } from './routes/agent';
28+
import { getZeroAgent } from './lib/server-utils';
3029
import { enableBrainFunction } from './lib/brain';
3130
import { trpcServer } from '@hono/trpc-server';
3231
import { agentsMiddleware } from 'hono-agents';
@@ -518,7 +517,6 @@ export default class extends WorkerEntrypoint<typeof env> {
518517
if (userId) {
519518
const db = getZeroDB(userId);
520519
c.set('sessionUser', await db.findUser());
521-
(await db)[Symbol.dispose]?.();
522520
}
523521
}
524522
}
@@ -528,11 +526,6 @@ export default class extends WorkerEntrypoint<typeof env> {
528526

529527
await next();
530528

531-
if (c.var.sessionUser?.id) {
532-
const db = getZeroDB(c.var.sessionUser.id);
533-
(await db)[Symbol.dispose]?.();
534-
}
535-
536529
c.set('sessionUser', undefined);
537530
c.set('autumn', undefined as any);
538531
c.set('auth', undefined as any);

apps/server/src/routes/agent/index.ts

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,14 @@ import {
2727
type IncomingMessage,
2828
type OutgoingMessage,
2929
} from './types';
30+
import {
31+
EPrompts,
32+
type IOutgoingMessage,
33+
type ParsedMessage,
34+
type ISnoozeBatch,
35+
} from '../../types';
36+
import type { MailManager, IGetThreadResponse, IGetThreadsResponse } from '../../lib/driver/types';
3037
import { DurableObjectOAuthClientProvider } from 'agents/mcp/do-oauth-client-provider';
31-
import { EPrompts, type IOutgoingMessage, type ParsedMessage, type ISnoozeBatch } from '../../types';
32-
import type {
33-
MailManager,
34-
IGetThreadResponse,
35-
IGetThreadsResponse,
36-
} from '../../lib/driver/types';
3738
import { AiChatPrompt, GmailSearchAssistantSystemPrompt } from '../../lib/prompts';
3839
import { connectionToDriver } from '../../lib/server-utils';
3940
import type { CreateDraftData } from '../../lib/schemas';
@@ -63,7 +64,6 @@ const shouldLoop = env.THREAD_SYNC_LOOP !== 'false';
6364
export class ZeroDriver extends AIChatAgent<typeof env> {
6465
private foldersInSync: Map<string, boolean> = new Map();
6566
private syncThreadsInProgress: Map<string, boolean> = new Map();
66-
private currentFolder: string | null = 'inbox';
6767
private driver: MailManager | null = null;
6868
private agent: DurableObjectStub<ZeroAgent> | null = null;
6969
constructor(ctx: DurableObjectState, env: Env) {
@@ -506,7 +506,6 @@ export class ZeroDriver extends AIChatAgent<typeof env> {
506506
}
507507

508508
try {
509-
const startTime = Date.now();
510509
console.log(`[inboxRag] Executing AI search with parameters:`, {
511510
query,
512511
max_num_results: 3,
@@ -529,8 +528,6 @@ export class ZeroDriver extends AIChatAgent<typeof env> {
529528
},
530529
});
531530

532-
const duration = Date.now() - startTime;
533-
534531
return { result: answer.response, data: answer.data };
535532
} catch (error) {
536533
console.error(`[inboxRag] Search failed for query: "${query}"`, {
@@ -774,7 +771,7 @@ export class ZeroDriver extends AIChatAgent<typeof env> {
774771
}
775772
}
776773

777-
async getThreadFromDB(id: string, lastAttempt = false): Promise<IGetThreadResponse> {
774+
async getThreadFromDB(id: string): Promise<IGetThreadResponse> {
778775
try {
779776
const result = this.sql`
780777
SELECT
@@ -793,11 +790,13 @@ export class ZeroDriver extends AIChatAgent<typeof env> {
793790
`;
794791

795792
if (!result || result.length === 0) {
796-
if (lastAttempt) {
797-
throw new Error('Thread not found in database, Sync Failed once');
798-
}
799-
await this.syncThread({ threadId: id });
800-
return this.getThreadFromDB(id, true);
793+
return {
794+
messages: [],
795+
latest: undefined,
796+
hasUnread: false,
797+
totalReplies: 0,
798+
labels: [],
799+
} satisfies IGetThreadResponse;
801800
}
802801
const row = result[0] as { latest_label_ids: string };
803802
const storedThread = await env.THREADS_BUCKET.get(this.getThreadKey(id));

apps/server/src/routes/agent/mcp.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import { env } from 'cloudflare:workers';
2323
import { eq, and } from 'drizzle-orm';
2424
import { McpAgent } from 'agents/mcp';
2525
import { createDb } from '../../db';
26-
import { generateText } from 'ai';
2726
import z from 'zod';
2827

2928
export class ZeroMCP extends McpAgent<typeof env, Record<string, unknown>, { userId: string }> {

0 commit comments

Comments
 (0)