Skip to content

Overall optimization#1250

Merged
duckduckhero merged 8 commits intomainfrom
overall-optimization
Jul 30, 2025
Merged

Overall optimization#1250
duckduckhero merged 8 commits intomainfrom
overall-optimization

Conversation

@duckduckhero
Copy link
Contributor

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 30, 2025

📝 Walkthrough

Walkthrough

This set of changes refactors data fetching and state management in several React components, particularly within the contact finder and workspace calendar features. It introduces batch data fetching, simplifies prop usage, updates query logic, and adjusts UI and provider wrapping based on route. Translation files are also updated for new UI strings.

Changes

Cohort / File(s) Change Summary
ContactView Refactor
apps/desktop/src/components/finder/views/contact-view.tsx
Refactored to fetch all people globally, fetch user profile separately, and merge user into people list. Removed organization-member-specific queries and conditional state sync useEffects. Updated cache invalidations and added a "You" badge in the UI.
Chat Logic Message Limit
apps/desktop/src/components/right-panel/hooks/useChatLogic.ts
Increased free user message allowance per conversation from 2 to 3, updated the restriction message, and adjusted the enforcement threshold logic.
Workspace Calendar Batch Fetching
apps/desktop/src/components/workspace-calendar/index.tsx
Added batch queries for participants, linked events, and event sessions. Updated rendering to pass batch-fetched data to NoteCard and EventCard components. Rendering logic now uses these props instead of per-item queries.
EventCard Prop Refactor
apps/desktop/src/components/workspace-calendar/event-card.tsx
Refactored to accept session and participants as props instead of fetching them internally. Updated memoization and rendering logic accordingly.
NoteCard Prop Refactor
apps/desktop/src/components/workspace-calendar/note-card.tsx
Refactored to accept participants and linkedEvent as props instead of fetching them internally. Updated memoization and rendering logic accordingly.
Right Panel Provider Window Label
apps/desktop/src/contexts/right-panel.tsx
Added logic to check the current window label and only enable the chat panel feature flag query in the main window. No changes to exported signatures.
Route-based License Provider
apps/desktop/src/routes/app.tsx
Used route location to conditionally wrap main content in the LicenseRefreshProvider, disabling it for finder routes. Minor code cleanup and no changes to exported signatures.
Translation Updates (EN)
apps/desktop/src/locales/en/messages.po
Added translation for "(Optional for localhost)", updated source references, and marked an obsolete translation string for API key entry.
Translation Updates (KO)
apps/desktop/src/locales/ko/messages.po
Added translation for "(Optional for localhost)", updated source references, and marked an obsolete translation string for API key entry.

Sequence Diagram(s)

sequenceDiagram
    participant UI as ContactView UI
    participant Query as React Query
    participant DB as Database/API

    UI->>Query: Fetch organizations (global)
    UI->>Query: Fetch all people (global)
    UI->>Query: Fetch user profile
    Query->>DB: getOrganizations()
    Query->>DB: getAllPeople()
    Query->>DB: getUserProfile(userId)
    Query-->>UI: organizations, allPeople, userProfile

    UI->>UI: Merge user profile into people list (if needed)
    UI->>UI: Filter people by selected organization (client-side)
    UI->>Query: Fetch person sessions (only if person selected)
    Query->>DB: getPersonSessions(personId)
    Query-->>UI: person sessions
Loading
sequenceDiagram
    participant Calendar as WorkspaceCalendar
    participant Query as React Query
    participant DB as Database/API
    participant NoteCard as NoteCard/EventCard

    Calendar->>Query: Batch fetch participants for sessions
    Calendar->>Query: Batch fetch linked events for sessions
    Calendar->>Query: Batch fetch event sessions for events
    Query->>DB: getParticipants(sessionIds)
    Query->>DB: getLinkedEvents(sessionIds)
    Query->>DB: getEventSessions(eventIds)
    Query-->>Calendar: participants, linkedEvents, eventSessions

    Calendar->>NoteCard: Render with participants, linkedEvent
    Calendar->>EventCard: Render with session, participants
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

  • Finder view merge #1213: Introduced the original ContactView component and related finder view infrastructure; this PR directly modifies and builds upon that code.
  • Delete human #1238: Also modifies the ContactView component, specifically adding person deletion logic, which may interact with or be affected by the refactor in this PR.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch overall-optimization

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need 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)

  • @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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

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
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 (3)
apps/desktop/src/routes/app.tsx (1)

57-59: Consider using a more precise route detection method.

Using pathname.includes("/finder") could match unintended routes. Consider using a more specific pattern like pathname.startsWith("/app/finder") or checking against an exact route list.

-  // Check if we're in the finder route
-  const isFinderRoute = location.pathname.includes("/finder");
+  // Check if we're in the finder route
+  const isFinderRoute = location.pathname.startsWith("/app/finder");
apps/desktop/src/components/workspace-calendar/index.tsx (1)

40-56: Consider adding error handling for individual query failures.

Using Promise.all will reject if any single query fails. Consider using Promise.allSettled or wrapping individual queries in try-catch to handle partial failures gracefully.

-      const results = await Promise.all(
-        allSessionIds.map(async (sessionId) => {
-          const participants = await dbCommands.sessionListParticipants(sessionId);
-          return {
-            sessionId,
-            participants: participants.sort((a, b) => {
-              if (a.is_user && !b.is_user) {
-                return 1;
-              }
-              if (!a.is_user && b.is_user) {
-                return -1;
-              }
-              return 0;
-            }),
-          };
-        }),
-      );
+      const results = await Promise.allSettled(
+        allSessionIds.map(async (sessionId) => {
+          try {
+            const participants = await dbCommands.sessionListParticipants(sessionId);
+            return {
+              sessionId,
+              participants: participants.sort((a, b) => {
+                if (a.is_user && !b.is_user) {
+                  return 1;
+                }
+                if (!a.is_user && b.is_user) {
+                  return -1;
+                }
+                return 0;
+              }),
+            };
+          } catch (error) {
+            console.error(`Failed to fetch participants for session ${sessionId}:`, error);
+            return { sessionId, participants: [] };
+          }
+        }),
+      );
+      const successfulResults = results
+        .filter(result => result.status === 'fulfilled')
+        .map(result => (result as PromiseFulfilledResult<any>).value);
+      return Object.fromEntries(successfulResults.map(r => [r.sessionId, r.participants]));
apps/desktop/src/components/finder/views/contact-view.tsx (1)

51-63: Consider handling cases where there are more than 100 people.

The hardcoded limit of 100 in listHumans({ search: [100, ""] }) could silently truncate results. Consider implementing pagination or at least showing a warning when the limit is reached.

   const { data: allPeople = [] } = useQuery({
     queryKey: ["all-people", userId],
     queryFn: async () => {
       try {
-        const allHumans = await dbCommands.listHumans({ search: [100, ""] });
+        // Fetch with a higher limit or implement pagination
+        const allHumans = await dbCommands.listHumans({ search: [1000, ""] });
+        if (allHumans.length === 1000) {
+          console.warn("Contact list may be truncated. Consider implementing pagination.");
+        }
         return allHumans;
       } catch (error) {
         console.error("Error fetching all people:", error);
         return [];
       }
     },
   });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5172054 and 6c24a6f.

📒 Files selected for processing (9)
  • apps/desktop/src/components/finder/views/contact-view.tsx (9 hunks)
  • apps/desktop/src/components/right-panel/hooks/useChatLogic.ts (1 hunks)
  • apps/desktop/src/components/workspace-calendar/event-card.tsx (2 hunks)
  • apps/desktop/src/components/workspace-calendar/index.tsx (4 hunks)
  • apps/desktop/src/components/workspace-calendar/note-card.tsx (3 hunks)
  • apps/desktop/src/contexts/right-panel.tsx (2 hunks)
  • apps/desktop/src/locales/en/messages.po (4 hunks)
  • apps/desktop/src/locales/ko/messages.po (4 hunks)
  • apps/desktop/src/routes/app.tsx (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,ts,tsx,rs}

⚙️ CodeRabbit Configuration File

**/*.{js,ts,tsx,rs}: 1. No error handling.
2. No unused imports, variables, or functions.
3. For comments, keep it minimal. It should be about "Why", not "What".

Files:

  • apps/desktop/src/components/right-panel/hooks/useChatLogic.ts
  • apps/desktop/src/contexts/right-panel.tsx
  • apps/desktop/src/components/workspace-calendar/note-card.tsx
  • apps/desktop/src/components/workspace-calendar/event-card.tsx
  • apps/desktop/src/routes/app.tsx
  • apps/desktop/src/components/workspace-calendar/index.tsx
  • apps/desktop/src/components/finder/views/contact-view.tsx
🔇 Additional comments (20)
apps/desktop/src/contexts/right-panel.tsx (3)

6-6: LGTM - Clean import addition

The import is properly structured and used appropriately for window-specific feature control.


95-96: LGTM - Clear window context detection

The window label detection and main window check is implemented cleanly and provides a clear way to differentiate between window contexts.


101-101: Excellent performance optimization

Conditionally enabling the query based on window context prevents unnecessary API calls in non-main windows while maintaining proper functionality where needed.

apps/desktop/src/components/right-panel/hooks/useChatLogic.ts (2)

141-141: Verify the intended message limit

The change from >= 2 to >= 4 allows 2 user messages (4 total including AI responses) before requiring a pro license. This contradicts the AI summary which claims it was changed to allow 3 messages per session.

Please confirm the intended behavior:

  • Current code allows 2 user messages before license requirement
  • AI summary suggests 3 messages were intended
#!/bin/bash
# Search for other references to message limits in chat logic
rg -A 3 -B 3 "messages.*length.*>=|message.*limit|conversation.*limit" --type ts

Likely an incorrect or invalid review comment.


148-148: LGTM - Improved user messaging

The wording change from "session" to "conversation" is more user-friendly and intuitive. The "2 messages" is consistent with the code logic.

apps/desktop/src/locales/ko/messages.po (3)

259-261: LGTM - New translation entry added

The new translation entry for "(Optional for localhost)" is properly formatted and linked to the correct source file reference.


397-397: LGTM - Source references updated

The line number updates for "API Key" and "Create Note" correctly reflect code refactoring in the source files.

Also applies to: 607-607


718-719: LGTM - Obsolete translation marked

The API key prompt translation is properly marked as obsolete, indicating it's no longer used in the codebase.

apps/desktop/src/locales/en/messages.po (3)

259-261: LGTM - Consistent translation addition

The new translation entry matches the Korean translation file and maintains proper internationalization consistency.


397-397: LGTM - Consistent source reference updates

The source line updates are consistent with the Korean translation file and reflect the same code refactoring changes.

Also applies to: 607-607


718-719: LGTM - Consistent obsolete marking

The obsolete translation entry is consistently marked across both language files.

apps/desktop/src/components/workspace-calendar/note-card.tsx (4)

7-7: LGTM - Import types added for new props

The additional type imports are necessary for the new prop types being added to the component.


14-15: LGTM - Well-structured prop refactoring

The new optional props with sensible defaults (null for linkedEvent, empty array for participants) provide a clean interface for the parent component to pass data.

Also applies to: 19-20


26-26: LGTM - Consistent prop usage in memoized computation

The participantsPreview computation is properly updated to work with the direct prop values instead of query data objects.

Also applies to: 31-31, 37-37


77-77: LGTM - Consistent linkedEvent prop usage

All display references consistently use the linkedEvent prop directly, removing the previous .data property accesses.

Also applies to: 83-83, 119-119

apps/desktop/src/components/workspace-calendar/event-card.tsx (1)

9-23: Good refactoring to lift data fetching to parent component.

The change from internal data fetching to prop-based data passing improves component reusability and aligns with React best practices. The default values for session and participants provide good fallback behavior.

apps/desktop/src/routes/app.tsx (1)

117-122: Validate Session Providers in Non-Main Windows

Non-main windows currently render only:

<div className="h-screen w-screen overflow-hidden">
  <Outlet />
</div>

without wrapping in SessionsProvider or OngoingSessionProvider. Any component rendered here that calls useSession or useOngoingSession will throw at runtime. For example:

  • apps/desktop/src/routes/app.note.$id.tsx
  • apps/desktop/src/routes/app.control.tsx

Please verify that none of the routes or components loaded in non-main windows rely on these hooks, or consider wrapping the non-main <Outlet /> in the required providers to prevent errors.

apps/desktop/src/components/workspace-calendar/index.tsx (1)

32-60: Well-structured batch data fetching implementation.

The batch queries efficiently fetch all required data upfront and use proper caching strategies. The Object.fromEntries pattern provides O(1) lookup performance.

Note: The participant sorting places users at the end of the list. Verify this is the intended behavior across all UI contexts.

apps/desktop/src/components/finder/views/contact-view.tsx (2)

83-115: Good improvements to the person sessions query.

The safety check prevents the query from running with null values, and the explicit cache settings (gcTime: 5 minutes, staleTime: 30 seconds) provide better control over data freshness.


32-36: Global organization fetch is consistent and intentional
We confirmed via ast-grep and rg that dbCommands.listOrganizations(null) is already used in these desktop components:

  • apps/desktop/src/routes/app.human.$id.tsx
  • apps/desktop/src/stores/search.ts
  • apps/desktop/src/components/command-palette.tsx
  • apps/desktop/src/components/finder/views/contact-view.tsx

The binding listOrganizations(filter: ListOrganizationFilter | null) returns all organizations when passed null (filters only apply to search/pagination). Since this matches existing usage and backend access control remains responsible for privacy, no changes are needed here.

@duckduckhero duckduckhero merged commit fe015a5 into main Jul 30, 2025
7 checks passed
This was referenced Aug 1, 2025
This was referenced Aug 20, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 13, 2025
@ComputelessComputer ComputelessComputer deleted the overall-optimization branch December 14, 2025 15:23
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

Comments