Skip to content

feat(wren-ui): Reasoning UI#1414

Merged
andreashimin merged 33 commits into
mainfrom
feat/reasoning-ui
Mar 19, 2025
Merged

feat(wren-ui): Reasoning UI#1414
andreashimin merged 33 commits into
mainfrom
feat/reasoning-ui

Conversation

@andreashimin
Copy link
Copy Markdown
Contributor

@andreashimin andreashimin commented Mar 17, 2025

Description

This PR refactors the user query flow for Text-to-SQL to clarify each step, ensuring a more structured and intuitive experience. It enhances the logical progression of the query process, improving clarity and usability while providing a more seamless interaction for users.

Screenshots

image
image
image

Remarks

  • Waiting for cancel flow new API

Summary by CodeRabbit

  • New Features

    • Introduced a new Preparation component for managing and displaying answer preparation status.
    • Added new components for displaying SQL generation status, organizing data, and retrieving related models.
    • Enabled the option to re-run a task directly from the interface.
    • Rolled out a redesigned input component for a smoother question submission experience.
    • Implemented a new ErrorBoundary component for enhanced error visibility within the application.
    • Expanded GraphQL type definitions to include additional fields for asking tasks and introduced new mutation capabilities.
  • Improvements

    • Enhanced loading indicators with customizable sizing.
    • Optimized user interface responsiveness and error handling during answer generation.
    • Updated state management for improved handling of asynchronous tasks and user interactions.
    • Improved caching and state management logic for better performance and reliability.
    • Streamlined the handling of responses and asynchronous tasks in the HomeThread component.
    • Simplified the telemetry setup by integrating a new global configuration provider.

@andreashimin andreashimin requested a review from fredalai March 17, 2025 03:34
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 17, 2025

Walkthrough

This pull request introduces extensive changes across the codebase. GraphQL type definitions are updated to include additional fields and a new mutation for rerunning asking tasks. Components throughout the UI have been refactored or newly added—ranging from loading spinners and preparation steps to prompt handling and answer results. Several hooks and utility functions have been introduced or updated for state management, process state transitions, and global configuration. Telemetry setup is removed from the app component and replaced with a global configuration provider.

Changes

File(s) Change Summary
wren-ui/src/apollo/client/graphql/__types__.ts, .../home.generated.ts, .../home.ts Updated GraphQL types and fragments: expanded AskingTask with new optional fields, replaced viewId with taskId, made sql optional, and added the new rerunAskingTask mutation with its argument type.
wren-ui/src/components/PageLoading.tsx Extended LoadingProps with optional size, width, height, and className; introduced a new Spinner component rendering LoadingOutlined.
wren-ui/src/components/learning/index.tsx Introduced a conditional check to safely set the collapse block’s transition style, preventing runtime errors.
wren-ui/src/components/pages/home/preparation/*.tsx Added new React components: Preparation and its step components (Generating, Organizing, and Retrieving) to manage and display the answer preparation process.
wren-ui/src/components/pages/home/prompt/*.tsx Introduced a new PromptInput component, refactored Prompt and PromptResult components (renaming callbacks and updating state management) for handling user input and displaying results.
wren-ui/src/components/pages/home/promptThread/*.tsx Refactored PromptThread and answer components (AnswerResult, BreakdownAnswer, ChartAnswer, TextBasedAnswer) to remove obsolete props, integrate with the new prompt thread store, and streamline data flow.
wren-ui/src/components/pages/home/promptThread/store.tsx, wren-ui/src/hooks/useStoreContext.tsx, wren-ui/src/hooks/useAskProcessState.tsx, wren-ui/src/hooks/useAskPrompt.tsx Added new store context and hooks for managing prompt threads and process state. Introduced ProcessStateMachine, new utility functions, and updated cache update methods.
wren-ui/src/hooks/useGlobalConfig.tsx Introduced a new global configuration React context with a provider and corresponding hook (useGlobalConfig).
wren-ui/src/pages/_app.tsx, wren-ui/src/pages/home/[id].tsx, wren-ui/src/pages/home/index.tsx Refactored page components: telemetry setup logic removed and replaced with GlobalConfigProvider; updated thread handling, renamed callbacks (e.g. onSelect to onCreateResponse), and added new asynchronous handling for unfinished tasks.
wren-ui/src/utils/enum/home.ts, wren-ui/src/utils/env.ts, wren-ui/src/utils/telemetry.ts Updated the PROCESS_STATE enum (added CORRECTING and STOPPED), exported the UserConfig type, and added a new telemetry module integrating PostHog for client-side user tracking.

Possibly related PRs

Suggested labels

module/ui, module/ai-service

Suggested reviewers

  • fredalai
  • wwwy3y3

Poem

Hop, hop, hop, I type away,
New fields and mutations brighten the day.
My whiskers twitch at each refactor so fine,
In code and queries, everything aligns.
A bunny’s cheer for a sprint so grand—
Leaping into improvements across the land!

🐰🌟

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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
Copy Markdown
Contributor

@fredalai fredalai left a comment

Choose a reason for hiding this comment

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

Found a bug here:

prepare: have a View
step 1: use the View's questions to ask
Actual behavior: No new thread page is navigated
Expected behavior: Go to new thread page

2025-03-18.9.46.47.mov

Comment thread wren-ui/src/pages/home/index.tsx
Comment thread wren-ui/src/pages/home/index.tsx
@andreashimin andreashimin force-pushed the feat/reasoning-ui branch 2 times, most recently from 40701e3 to 29bcff2 Compare March 18, 2025 08:12
@andreashimin andreashimin requested a review from fredalai March 18, 2025 08:12
Base automatically changed from feature/reasoning-api to main March 18, 2025 08:56
Comment thread wren-ui/src/components/pages/home/promptThread/AnswerResult.tsx Outdated
Comment thread wren-ui/src/components/pages/home/preparation/index.tsx
Comment thread wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx Outdated
Copy link
Copy Markdown
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: 11

🔭 Outside diff range comments (1)
wren-ui/src/apollo/server/services/askingService.ts (1)

377-443: 🛠️ Refactor suggestion

Shifting to IAskingTaskTracker
Integrating askingTaskTracker centralizes task operations, which improves maintainability. Double-check that concurrency (multiple tasks per thread) is handled gracefully.

♻️ Duplicate comments (1)
wren-ui/src/components/pages/home/preparation/index.tsx (1)

102-105: ⚠️ Potential issue

Enhance error handling for task request failures.

The component should handle cases where the task request has failed while continuing to poll for instant recommended questions.

Add error handling to catch and display appropriate messages when the task fails but polling continues:

const processState = useMemo(
  () => convertAskingTaskToProcessState(askingTask),
  [askingTask],
);
+ 
+ const hasError = useMemo(
+   () => askingTask.status === AskingTaskStatus.FAILED,
+   [askingTask.status]
+ );

Then update the UI to display an error message when hasError is true.

🧹 Nitpick comments (34)
wren-ui/src/utils/enum/home.ts (1)

13-14: Enhanced process state tracking with new states

The addition of CORRECTING and STOPPED states to the PROCESS_STATE enum appropriately extends the tracking capabilities for the asking task flow. These new states will help provide better visibility into task progress and status.

Consider adding comments to document when these states are expected to occur in the process flow, which would enhance maintainability for future developers.

 export enum PROCESS_STATE {
   IDLE,
   UNDERSTANDING,
   SEARCHING,
   PLANNING,
   GENERATING,
-  CORRECTING,
+  CORRECTING, // When the system is correcting errors in the generated output
   FINISHED,
   FAILED,
-  STOPPED,
+  STOPPED,   // When the user manually stops the task execution
   NO_RESULT,
 }

Also applies to: 16-16

wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1)

10-37: Well-structured component with clear state visualization.

The component effectively communicates the SQL generation process state to users through appropriate messaging and loading indicators. The conditional rendering logic is clean and easy to understand.

One minor suggestion: consider adding aria attributes for improved accessibility:

- <Spinner className="gray-6" size={12} />
+ <Spinner className="gray-6" size={12} aria-label="Generating SQL statement" />

- <Spinner className="gray-6" size={16} />
+ <Spinner className="gray-6" size={16} aria-label="Wrapping up" />
wren-ui/src/utils/telemetry.ts (1)

5-29: Well-implemented PostHog initialization with proper browser-side check.

The PostHog setup function correctly handles Next.js SSR by checking for client-side execution and configures the telemetry service with appropriate settings. The PostHog configuration is comprehensive, with careful consideration of privacy concerns (masked inputs) and development environment handling.

Consider storing the debug message behind a debug flag rather than always logging to console:

-        console.log('PostHog initialized.');
+        if (env.isDevelopment) {
+          console.log('PostHog initialized.');
+        }
wren-ui/src/hooks/useStoreContext.tsx (1)

1-33: Good context management pattern

The useStoreContext hook provides a clean mechanism for dynamically creating and managing React contexts. This will help with state management across the refactored query flow components.

Consider adding TypeScript generics to the hook to make it more type-safe:

- const createStore = (id: string) => {
+ const createStore = <T,>(id: string) => {
-   if (contextMap.has(id)) return contextMap.get(id);
+   if (contextMap.has(id)) return contextMap.get(id) as React.Context<T>;
-   const context = createContext(null);
+   const context = createContext<T | null>(null);
    contextMap.set(id, context);
-   return context;
+   return context;
  };

- const useStore = (id: string) => {
+ const useStore = <T,>(id: string) => {
    const context = contextMap.get(id);
    if (!context) throw new Error(`Context not found for id: ${id}`);
-   return useContext(context);
+   return useContext(context) as T;
  };
wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (2)

17-31: Consider memoizing the scroll function

The scroll logic is well-implemented with appropriate effects that trigger based on different conditions. Consider memoizing the scrollBottom function with useCallback to prevent unnecessary re-creation on renders.

- const scrollBottom = () => {
+ const scrollBottom = useCallback(() => {
    if ($wrapper.current) {
      $wrapper.current.scrollTo({
        top: $wrapper.current.scrollHeight,
      });
    }
-  };
+  }, []);

33-52: Consider more responsive height constraints

The component's UI is well-structured with conditional rendering based on loading state. However, the hardcoded max height calc(100vh - 550px) might not be flexible across different screen sizes. Consider making this value more responsive or configurable via props.

  <div
    ref={$wrapper}
    className="gray-7 text-sm mt-2"
-   style={{ maxHeight: 'calc(100vh - 550px)', overflowY: 'auto' }}
+   style={{ maxHeight: 'calc(100vh - 550px)', overflowY: 'auto', minHeight: '100px' }}

Alternatively, consider making it configurable through props:

interface Props {
  stream: string;
  loading?: boolean;
+ maxHeight?: string;
}

// Then use it in the style
style={{ maxHeight: props.maxHeight || 'calc(100vh - 550px)', overflowY: 'auto' }}
wren-ui/src/components/PageLoading.tsx (1)

39-41: New Spinner component provides a simplified loading indicator

The new Spinner component offers a streamlined version of the loading indicator, which is useful for inline or smaller loading states. It effectively uses the className and size props for customization.

Note that while the LoadingProps interface was extended with width and height properties, these aren't used in this component. Consider either utilizing these properties or documenting which components use which properties.

wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (1)

27-37: Add handling for empty tables array

The component doesn't handle the case where the tables array is empty. Consider adding a conditional check to display an appropriate message when no tables are found.

{loading ? (
  <div className="d-flex align-center gx-2">
    Searching
    <Spinner className="gray-6" size={12} />
  </div>
) : (
  <>
-   <div className="mb-1">3 tables found</div>
-   <TagIterator data={data} />
+   {tables.length > 0 ? (
+     <>
+       <div className="mb-1">{tables.length} tables found</div>
+       <TagIterator data={data} />
+     </>
+   ) : (
+     <div className="mb-1">No tables found</div>
+   )}
  </>
)}
wren-ui/src/hooks/useGlobalConfig.tsx (1)

12-33: Add proper TypeScript typing for the children prop

The GlobalConfigProvider component is missing proper TypeScript typing for the children prop. You should specify the React.ReactNode type to ensure type safety.

-export const GlobalConfigProvider = ({ children }) => {
+export const GlobalConfigProvider = ({ children }: { children: React.ReactNode }) => {
wren-ui/src/components/pages/home/promptThread/store.tsx (1)

60-60: Add type safety check before casting

The current type cast to IPromptThreadStore doesn't have any safety checks. If the store doesn't exist, this could lead to runtime errors.

-  return storeContext.useStore(STORE.PROMPT_THREAD) as IPromptThreadStore;
+  const store = storeContext.useStore(STORE.PROMPT_THREAD);
+  if (!store) {
+    throw new Error('PromptThreadStore must be used within a PromptThreadProvider');
+  }
+  return store as IPromptThreadStore;
wren-ui/src/components/pages/home/prompt/Input.tsx (2)

33-35: Add proper type for the event parameter

The syncInputValue function has an untyped event parameter. You should add proper React typing for better type safety.

-  const syncInputValue = (event) => {
+  const syncInputValue = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
     setInputValue(event.target.value);
   };

52-63: Enhance accessibility with ARIA attributes

The TextArea could benefit from additional ARIA attributes to improve accessibility for users with disabilities.

       ref={$promptInput}
       // disable grammarly
       data-gramm="false"
       size="large"
       autoSize
       placeholder="Ask to explore your data"
       value={inputValue}
       onInput={syncInputValue}
       onPressEnter={inputEnter}
       disabled={isDisabled}
+      aria-label="Data exploration query input"
+      role="textbox"
+      aria-multiline="true"
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1)

128-129: Consider using a more consistent pattern for optional field handling.

The current implementation works correctly, but consider using the nullish coalescing operator for consistency:

-      sql: data.sql ? data.sql : undefined,
-      viewId: data.viewId ? data.viewId : undefined,
+      sql: data.sql ?? undefined,
+      viewId: data.viewId ?? undefined,

This would handle both null and undefined cases consistently and matches the pattern used in modern TypeScript codebases.

wren-ui/src/apollo/server/schema.ts (1)

992-992: New mutation enables task rerunning.

The rerunAskingTask mutation allows users to retry the reasoning process from a specific response, enhancing the interactive nature of the reasoning UI.

Consider adding documentation comments to explain the purpose and behavior of this mutation, particularly how it differs from createAskingTask and what happens to existing responses when a task is rerun.

wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (1)

96-101: Error handling should use the ErrorHandler system.

According to the retrieved learning from PR #1090, error handling for dashboard operations should be implemented through the ErrorHandler system instead of handling errors inline.

Replace the inline error handling with the ErrorHandler system:

const [createDashboardItem] = useCreateDashboardItemMutation({
-  onError: (error) => console.error(error),
+  onError: (error) => ErrorHandler.handleError(error, 'Failed to pin chart to dashboard'),
  onCompleted: () => {
    message.success('Successfully pinned chart to dashboard.');
  },
});
wren-ui/src/components/pages/home/promptThread/index.tsx (1)

101-106: Improved scroll behavior logic.

The effect that controls scrolling now uses specialized functions to determine when a response is complete, making the code more readable and maintainable.

Consider consolidating the getIsFinished and getAnswerIsFinished functions into a single utility or adding comments to clarify their different purposes, as having two separate "is finished" functions could be confusing to developers.

wren-ui/src/hooks/useAskProcessState.tsx (1)

87-148: ProcessStateMachine class with static members only.

  • The static-only pattern works but may be simplified into standalone functions if preferred.
  • Using this in a static context can sometimes be substituted with the class name for clarity.
🧰 Tools
🪛 Biome (1.9.4)

[error] 87-148: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 130-130: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 137-137: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (1)

42-45: Improve error handling for non-plain objects.

Currently, the code throws a generic 'Unexpected dbdata' error. Providing more context, such as the offending object's structure, could help with faster debugging.

  if (!isPlainObject(data)) {
-   throw new Error('Unexpected dbdata');
+   throw new Error(`Unexpected dbdata: ${JSON.stringify(data)}`);
  }
wren-ui/src/apollo/server/services/askingTaskTracker.ts (1)

219-222: Potential concurrency and load.

Polling every second can cause unnecessary load if many tasks accumulate. Consider using a configurable scheduler with backoff or a job queue (e.g., Bull, Agenda) to scale more efficiently.

wren-ui/src/components/pages/home/prompt/Result.tsx (1)

158-160: Use optional chaining for the function call.

Rather than onIntentSQLAnswer && onIntentSQLAnswer(), you can simplify it with optional chaining. This is more idiomatic and addresses the analyzer hint.

- if (type === AskingTaskType.TEXT_TO_SQL) {
-   onIntentSQLAnswer && onIntentSQLAnswer();
- }
+ if (type === AskingTaskType.TEXT_TO_SQL) {
+   onIntentSQLAnswer?.();
+ }
🧰 Tools
🪛 Biome (1.9.4)

[error] 158-158: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

wren-ui/src/hooks/useAskPrompt.tsx (7)

39-45: Consider clarifying function names or adding docstrings.
The canGenerateAnswer and canFetchThreadResponse utilities are helpful, but it might be beneficial to document the intended calling context or add inline comments for better readability.


47-49: Minor naming alignment
isReadyToThreadResponse might be clearer as isReadyForThreadResponse, to read more naturally.

-export const isReadyToThreadResponse = (askingTask: AskingTask) =>
+export const isReadyForThreadResponse = (askingTask: AskingTask) =>

60-69: Consider renaming for clarity
isNeedRecommendedQuestions is slightly awkward syntactically. A name like needsRecommendedQuestions or shouldFetchRecommendedQuestions might be more natural.


74-110: Safe concurrency handling in cache update
handleUpdateThreadCache directly updates the cache based on the queryId. This is valid, but be mindful of concurrent updates if multiple tasks for the same thread run in parallel. Review whether more robust concurrency controls might be needed.


211-218: Verify early return usage
checkFetchAskingStreamTask returns early if askingStreamTask is already set. Ensure we don’t need to refresh or override an existing stream when a new task is triggered.


250-259: Graceful cancellation
Using nextTick(1000) ensures polling stops before continuing. If cancellations become more frequent, consider a more direct approach to confirm the task is fully canceled, rather than a fixed delay.


261-281: Robust error handling
onReRun tries to rerun the task and update the cache. Make sure no partial updates happen if the rerun fails halfway. Logging is good; additional UI feedback on error might be helpful.

wren-ui/src/apollo/server/services/askingService.ts (3)

118-119: Return type changed to TrackedAskingResult | null
This is more robust, but confirm any calling code checks for null properly to avoid runtime errors.


567-598: Rerun logic
Properly reuses createAskingTask. If any advanced merging or partial reusability of prior results is needed, you might add a more detailed strategy in the future.


1001-1024: getAskingHistory
Filtering out the canceled thread response is a good improvement. Check for performance if the thread has many historical responses. Possibly limit further if needed.

wren-ui/src/components/pages/home/promptThread/AnswerResult.tsx (3)

150-159: isNeedGenerateAnswer
Function has a straightforward approach: it checks if the background task is not started and the answer is not finished. The naming is slightly off grammatically, but logically it works.

-const isNeedGenerateAnswer = (answerDetail: ThreadResponseAnswerDetail) => {
+const needsAnswerGeneration = (answerDetail: ThreadResponseAnswerDetail) => {

161-175: Refined store usage
Use of usePromptThreadStore() to unify new logic is a net improvement. Clarify any potential race conditions if multiple answer details get updated rapidly.


262-264: TextBasedAnswer
Seamless that you pass the entire props object. Just ensure performance is not impacted by rerenders when props changes.

wren-ui/src/apollo/client/graphql/__types__.ts (1)

742-744: MutationRerunAskingTaskArgs for responseId
This new argument structure is simple and self-explanatory. Consider whether you need extra parameters if rerun logic might vary by context. Otherwise, looks good.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07dcf81 and 24c2c77.

⛔ Files ignored due to path filters (1)
  • wren-ui/public/images/icon/message-ai.svg is excluded by !**/*.svg
📒 Files selected for processing (44)
  • wren-ui/migrations/20250509000000_create_asking_task.js (1 hunks)
  • wren-ui/migrations/20250509000001_add_task_id_to_thread.js (1 hunks)
  • wren-ui/src/apollo/client/graphql/__types__.ts (6 hunks)
  • wren-ui/src/apollo/client/graphql/home.generated.ts (10 hunks)
  • wren-ui/src/apollo/client/graphql/home.ts (4 hunks)
  • wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts (1 hunks)
  • wren-ui/src/apollo/server/models/adaptor.ts (1 hunks)
  • wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (1 hunks)
  • wren-ui/src/apollo/server/repositories/index.ts (1 hunks)
  • wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (3 hunks)
  • wren-ui/src/apollo/server/resolvers.ts (1 hunks)
  • wren-ui/src/apollo/server/resolvers/askingResolver.ts (13 hunks)
  • wren-ui/src/apollo/server/schema.ts (5 hunks)
  • wren-ui/src/apollo/server/services/askingService.ts (11 hunks)
  • wren-ui/src/apollo/server/services/askingTaskTracker.ts (1 hunks)
  • wren-ui/src/apollo/server/services/index.ts (1 hunks)
  • wren-ui/src/apollo/server/telemetry/telemetry.ts (1 hunks)
  • wren-ui/src/apollo/server/utils/error.ts (3 hunks)
  • wren-ui/src/common.ts (7 hunks)
  • wren-ui/src/components/PageLoading.tsx (1 hunks)
  • wren-ui/src/components/learning/index.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/index.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (1 hunks)
  • wren-ui/src/components/pages/home/prompt/Input.tsx (1 hunks)
  • wren-ui/src/components/pages/home/prompt/Result.tsx (10 hunks)
  • wren-ui/src/components/pages/home/prompt/index.tsx (4 hunks)
  • wren-ui/src/components/pages/home/promptThread/AnswerResult.tsx (3 hunks)
  • wren-ui/src/components/pages/home/promptThread/BreakdownAnswer.tsx (2 hunks)
  • wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (4 hunks)
  • wren-ui/src/components/pages/home/promptThread/TextBasedAnswer.tsx (3 hunks)
  • wren-ui/src/components/pages/home/promptThread/index.tsx (4 hunks)
  • wren-ui/src/components/pages/home/promptThread/store.tsx (1 hunks)
  • wren-ui/src/hooks/useAskProcessState.tsx (2 hunks)
  • wren-ui/src/hooks/useAskPrompt.tsx (8 hunks)
  • wren-ui/src/hooks/useGlobalConfig.tsx (1 hunks)
  • wren-ui/src/hooks/useStoreContext.tsx (1 hunks)
  • wren-ui/src/pages/_app.tsx (2 hunks)
  • wren-ui/src/pages/home/[id].tsx (5 hunks)
  • wren-ui/src/pages/home/index.tsx (2 hunks)
  • wren-ui/src/utils/enum/home.ts (1 hunks)
  • wren-ui/src/utils/env.ts (1 hunks)
  • wren-ui/src/utils/telemetry.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (1)
Learnt from: andreashimin
PR: Canner/WrenAI#1090
File: wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx:107-112
Timestamp: 2025-03-13T01:43:25.329Z
Learning: Error handling for dashboard operations should be implemented through the ErrorHandler system instead of handling errors inline. This ensures consistent error handling across the application.
wren-ui/src/apollo/server/services/askingService.ts (1)
Learnt from: wwwy3y3
PR: Canner/WrenAI#1388
File: wren-ui/src/apollo/server/services/askingService.ts:599-604
Timestamp: 2025-03-17T19:26:10.835Z
Learning: Error handling for non-existent asking tasks in WrenAI is handled at the resolver level rather than in the service implementation.
🧬 Code Definitions (11)
wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1)
wren-ui/src/components/PageLoading.tsx (1) (1)
  • Spinner (39:41)
wren-ui/src/pages/_app.tsx (1)
wren-ui/src/hooks/useGlobalConfig.tsx (1) (1)
  • GlobalConfigProvider (12:33)
wren-ui/src/utils/telemetry.ts (1)
wren-ui/src/utils/env.ts (1) (1)
  • UserConfig (8:13)
wren-ui/src/common.ts (2)
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (1) (1)
  • AskingTaskRepository (27:71)
wren-ui/src/apollo/server/services/askingTaskTracker.ts (1) (1)
  • AskingTaskTracker (56:471)
wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (1)
wren-ui/src/components/pages/home/promptThread/store.tsx (1) (1)
  • usePromptThreadStore (58:61)
wren-ui/src/hooks/useAskProcessState.tsx (1)
wren-ui/src/apollo/client/graphql/__types__.ts (1) (1)
  • AskingTask (26:39)
wren-ui/src/components/pages/home/promptThread/TextBasedAnswer.tsx (1)
wren-ui/src/components/pages/home/promptThread/store.tsx (1) (1)
  • usePromptThreadStore (58:61)
wren-ui/src/hooks/useGlobalConfig.tsx (2)
wren-ui/src/utils/env.ts (2) (2)
  • UserConfig (8:13)
  • getUserConfig (16:23)
wren-ui/src/utils/telemetry.ts (1) (1)
  • trackUserTelemetry (31:45)
wren-ui/src/apollo/server/services/askingService.ts (4)
wren-ui/src/apollo/server/services/askingTaskTracker.ts (2) (2)
  • TrackedAskingResult (31:35)
  • IAskingTaskTracker (43:54)
wren-ui/src/apollo/server/resolvers/askingResolver.ts (1) (1)
  • Task (38:40)
wren-ui/src/apollo/server/repositories/threadRepository.ts (1) (1)
  • Thread (17:27)
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1) (1)
  • ThreadResponse (42:52)
wren-ui/src/apollo/server/services/askingTaskTracker.ts (4)
wren-ui/src/apollo/server/models/adaptor.ts (2) (2)
  • AskResult (117:131)
  • AskInput (61:66)
wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts (1) (1)
  • IWrenAIAdaptor (46:109)
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (2) (2)
  • IAskingTaskRepository (23:25)
  • AskingTask (12:21)
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1) (1)
  • IThreadResponseRepository (54:60)
wren-ui/src/components/pages/home/prompt/index.tsx (2)
wren-ui/src/hooks/useAskProcessState.tsx (1) (1)
  • getIsProcessing (9:16)
wren-ui/src/components/pages/home/prompt/Input.tsx (1) (1)
  • PromptInput (16:75)
🪛 Biome (1.9.4)
wren-ui/src/hooks/useAskProcessState.tsx

[error] 87-148: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 130-130: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 137-137: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

wren-ui/src/components/pages/home/prompt/Result.tsx

[error] 158-158: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

wren-ui/src/apollo/server/services/askingTaskTracker.ts

[error] 160-160: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

wren-ui/src/components/pages/home/prompt/index.tsx

[error] 125-125: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 126-126: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (176)
wren-ui/src/common.ts (7)

18-18: Proper integration of AskingTaskRepository

The addition of AskingTaskRepository to the imports list properly prepares for its instantiation and usage within the components initialization function.


33-33: Proper import of AskingTaskTracker service

The AskingTaskTracker import has been correctly added to the services import section, maintaining consistent code organization.


68-68: Correct initialization of askingTaskRepository

The repository is properly instantiated with the knex connection, maintaining the pattern used for other repositories.


111-116: Well-structured initialization of AskingTaskTracker

The AskingTaskTracker is properly instantiated with all its required dependencies. The dependency injection approach follows the existing pattern and promotes testability.


127-127: Proper integration with AskingService

The askingTaskTracker is correctly passed to the AskingService constructor, allowing the service to utilize the new tracking functionality.


171-172: Correct export of askingTaskRepository

The askingTaskRepository is properly included in the returned components, following the established pattern for exposing repositories.


188-188: Correct export of askingTaskTracker

The askingTaskTracker is properly exposed in the returned components, making it available for use throughout the application.

wren-ui/src/apollo/server/services/index.ts (1)

9-9: Proper export of askingTaskTracker module

The new export statement correctly follows the existing pattern in this file, making the askingTaskTracker module available for import elsewhere in the application.

wren-ui/src/apollo/server/repositories/index.ts (1)

18-18: Proper export of askingTaskRepository module

The new export statement correctly follows the existing pattern in this file, making the askingTaskRepository module available for import elsewhere in the application.

wren-ui/src/utils/env.ts (1)

8-8: Type export provides better reusability

Exporting the UserConfig type makes it accessible from other modules, which allows for better type checking across the application and supports the refactored user query flow mentioned in the PR objectives.

wren-ui/src/apollo/server/telemetry/telemetry.ts (1)

54-54: Telemetry event added for new rerun task functionality

This new telemetry event aligns with the PR objectives of refactoring the user query flow, allowing tracking when users rerun asking tasks. The naming convention follows the established pattern and clearly indicates the context and action being tracked.

wren-ui/src/apollo/server/resolvers.ts (1)

94-94:

Details

✅ Verification successful

New mutation for rerunning asking tasks

The addition of the rerunAskingTask resolver function to the Mutations object provides the GraphQL API endpoint needed for the new task rerunning functionality. This directly supports the PR objective of refactoring the user query flow and enhancing the interaction experience.


🏁 Script executed:

#!/bin/bash
# Verify that the corresponding resolver function exists in askingResolver.ts
echo "Checking for rerunAskingTask implementation in askingResolver.ts..."
rg "rerunAskingTask" --type ts -A 5 -B 5 "wren-ui/src/apollo/server/resolvers/askingResolver.ts"

# Verify that the mutation is also defined in the GraphQL schema
echo "Checking for rerunAskingTask mutation in the GraphQL schema..."
rg "rerunAskingTask" --type ts "wren-ui/src/apollo/server/schema.ts"

Length of output: 1533


Verified & Approved: New Mutation for Rerunning Asking Tasks

  • Confirmed that the rerunAskingTask resolver is implemented in wren-ui/src/apollo/server/resolvers/askingResolver.ts.
  • The GraphQL schema in wren-ui/src/apollo/server/schema.ts correctly declares the rerunAskingTask(responseId: Int!): Task! mutation.
  • These changes successfully support the PR objective of refactoring the user query flow and enhancing the interaction experience.
wren-ui/migrations/20250509000001_add_task_id_to_thread.js (3)

1-14: Database migration adds task ID relationship to thread responses

This migration creates a relationship between thread responses and asking tasks by adding a foreign key, which is necessary for the refactored query flow. The implementation correctly handles the case where asking tasks are deleted by setting the reference to null rather than cascading deletes.


16-25: Proper rollback function to remove the foreign key

The down migration correctly removes both the foreign key constraint and the column, ensuring clean rollbacks if needed.


1-26:

Details

❓ Verification inconclusive

Verify migration date in filename

The migration filename contains what appears to be a future date (2025-05-09). While this won't affect functionality, it's worth confirming if this naming convention is intentional for your migration versioning.


🏁 Script executed:

#!/bin/bash
# Check the pattern of other migration filenames in the project
echo "Listing other migration files for comparison:"
fd "^\d+.*\.js$" wren-ui/migrations/ --exec ls -la {}

Length of output: 4124


Migration Timestamp Confirmation

After reviewing the migration filenames in the project, it appears that using a 2025-05-09 timestamp is consistent with the current naming convention (see, for example, the companion file 20250509000000_create_asking_task.js). This indicates that the future-dated timestamp is likely an intentional part of your migration ordering strategy. Please confirm that this naming approach is deliberate.

wren-ui/src/apollo/server/models/adaptor.ts (1)

125-130: Expanded properties enhance the AskResult type with detailed response information.

The addition of these optional properties (rephrasedQuestion, sqlGenerationReasoning, retrievedTables, invalidSql, and traceId) provides more comprehensive information about the SQL generation process, which aligns well with the PR objective of refactoring the user query flow. These fields will likely enable improved feedback and transparency in the Text-to-SQL feature.

wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1)

4-8: Clean interface definition for the component props.

The props interface is well-defined with clear, descriptive boolean properties that represent different states of the SQL generation process.

wren-ui/src/components/learning/index.tsx (1)

254-255: Improved null safety when setting transition style.

Good defensive programming change. This update prevents potential runtime errors by checking if $collapseBlock.current exists before attempting to set its style property.

wren-ui/src/utils/telemetry.ts (1)

31-45: Clean implementation of page view tracking with proper cleanup.

The tracking implementation properly handles the setup and teardown of event listeners, preventing potential memory leaks. The conditional initialization based on user preferences respects user privacy choices.

wren-ui/src/pages/_app.tsx (1)

6-6: Clean refactoring with GlobalConfigProvider

The introduction of GlobalConfigProvider and the restructuring of the component hierarchy is a good improvement. This change centralizes the configuration management and separates the telemetry setup logic from the App component.

Also applies to: 22-30

wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts (1)

643-653: Enhanced result data structure

The additional fields enriching the AskResult object (rephrasedQuestion, intentReasoning, etc.) provide more comprehensive information about the query processing, which aligns with the PR's goal of improving the Text-to-SQL user query flow.

wren-ui/migrations/20250509000000_create_asking_task.js (1)

1-34: Well-structured database migration

The migration creates a new asking_task table with appropriate fields and relationships. The schema is properly designed with:

  • Unique constraints on query_id
  • Foreign key relationships with appropriate cascade behavior
  • Default values where needed
  • Automatic timestamp management

This table structure will effectively support the enhanced query flow tracking.

wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1)

1-16: Well-structured component with clear prop interfaces

The component is well-organized with appropriate imports and a clear interface definition. The isDone flag is a good pattern to derive state from props.

wren-ui/src/components/PageLoading.tsx (1)

29-32: Interface extension enhances component flexibility

Adding these optional properties to the LoadingProps interface enables more customization options for loading indicators throughout the application.

wren-ui/src/components/pages/home/promptThread/BreakdownAnswer.tsx (2)

14-15: Simplified props signature improves code clarity

Accepting the full AnswerResultProps type directly instead of using Pick simplifies the component interface and makes it more maintainable. Removing the unused motion property also cleans up the code.


42-57: Simplified className structure

Removing the conditional class application (likely from clsx) in favor of a direct className string improves code readability and simplifies the component structure without changing functionality.

wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (3)

5-8: Well-defined props interface

The interface is clear and appropriately defines the expected props for this component.


10-15: Good separation of concerns with TagTemplate and TagIterator

Using a separate component for tag rendering and leveraging the makeIterable utility is a clean approach for rendering lists of items.


24-24: Use "models" instead of "tables"

A previous review comment suggested using "models" instead of "tables" for consistency with the rest of the codebase.

wren-ui/src/apollo/client/graphql/home.ts (4)

58-84: Well-structured GraphQL fragment

The new COMMON_ASKING_TASK fragment is well-structured and follows the existing patterns in the codebase. It properly includes all necessary fields and reuses the COMMON_ERROR fragment consistently.


107-109: Good modularization of GraphQL fragments

The update to use the COMMON_ASKING_TASK fragment in the COMMON_RESPONSE fragment is a good improvement for code modularity and maintainability. The proper import of the fragment at line 115 ensures consistency.

Also applies to: 115-115


146-152: Good refactoring using fragment

The update to the ASKING_TASK query to use the COMMON_ASKING_TASK fragment instead of listing all fields explicitly is a good improvement that enhances maintainability and consistency.


198-204:

Details

✅ Verification successful

Verify integration of the new RERUN_ASKING_TASK mutation

The new mutation looks good, but we should verify that it's properly integrated with the backend resolver and the client-side code that will use it.


🏁 Script executed:

#!/bin/bash
# Check if the rerunAskingTask mutation is properly implemented in the resolver

# Look for the resolver implementation
rg -A 5 "rerunAskingTask.*\(.*\)" --type ts

Length of output: 2408


Integration Verified: RERUN_ASKING_TASK mutation works as expected

Verification confirms that:

  • The mutation is correctly defined in wren-ui/src/apollo/client/graphql/home.ts and properly propagated to the generated file.
  • The GraphQL schema in wren-ui/src/apollo/server/schema.ts includes the expected signature (rerunAskingTask(responseId: Int!): Task!).
  • The corresponding resolver in wren-ui/src/apollo/server/resolvers/askingResolver.ts binds the mutation method.
  • The client-side integration, as seen in wren-ui/src/hooks/useAskPrompt.tsx, correctly uses the useRerunAskingTaskMutation hook.

No changes are needed.

wren-ui/src/components/pages/home/promptThread/TextBasedAnswer.tsx (3)

8-8: Good addition of store integration.

Adding the import for usePromptThreadStore enables the component to leverage centralized state management, improving code organization.


36-38: Simplified props interface improves component flexibility.

Changing from Pick<AnswerResultProps, | 'threadResponse' | 'isLastThreadResponse' | 'onInitPreviewDone' | 'onRegenerateTextBasedAnswer'> to AnswerResultProps makes the component more maintainable and reduces the need to update the prop interface when new properties are added.


109-110: Improved state management with store function.

Replacing the prop callback with a store function follows better state management practices and centralizes the regeneration logic.

wren-ui/src/pages/home/index.tsx (4)

115-115: Simplified question submission.

Removing the nextTick call streamlines the function as it was likely unnecessary. The function now directly submits the question to the prompt.


118-126: Function renaming improves clarity of purpose.

Renaming onSelect to onCreateResponse better reflects the function's purpose. The implementation is also simplified by removing the recommendation questions generation logic.


139-141: Updated props for RecommendedQuestionsInstruction component.

The props have been correctly updated to reflect the renamed function and simplified loading state.


143-147: Updated props for Prompt component.

The Prompt component now correctly receives the renamed onCreateResponse function.

wren-ui/src/components/pages/home/preparation/index.tsx (3)

43-96: Well-structured PreparationStatus component.

The PreparationStatus component effectively manages different states of the preparation process and provides appropriate user controls (cancel/re-run) based on the current state.


111-113: Good use of useEffect for state management.

The component correctly updates its active state based on whether the answer is prepared, ensuring the UI stays in sync with the application state.


177-208: Well-organized preparation steps with appropriate loading states.

The timeline implementation clearly presents the different steps in the preparation process (retrieving, organizing, generating) with appropriate loading indicators.

wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (3)

44-44: Database schema alignment with model interface.

The addition of an optional askingTaskId property to the ThreadResponse interface properly connects this model to the asking_task table, supporting the new reasoning UI feature as mentioned in the PR objectives.


48-48: Making sql optional supports flexible response handling.

Changing sql from required to optional allows the model to handle responses that might not yet have SQL generated, which is important for the step-by-step reasoning process.


118-119: Update method appropriately extended.

Adding sql and viewId as optional properties in the update method's data parameter aligns with the interface changes and enables more flexible updates.

wren-ui/src/apollo/server/schema.ts (4)

587-593: Enhanced AskingTask type for better reasoning flow representation.

The additional fields (rephrasedQuestion, sqlGenerationReasoning, retrievedTables, invalidSql, traceId, queryId) provide valuable context for the reasoning process, making each step of the SQL generation more transparent.


623-623: Input types shifted from view-based to task-based approach.

Changing viewId to taskId in both input types reflects the architectural shift toward a task-centered model for managing the query flow, which aligns with the PR objective of refactoring the user query flow.

Also applies to: 629-629


704-704: ThreadResponse.sql field made optional.

Making the sql field nullable in the GraphQL schema matches the repository layer changes and provides flexibility in representing responses that don't have SQL yet.


709-709: Nullable AskingTask relationships provide flexibility.

Making askingTask relationships nullable in both the ThreadResponse type and the query return type improves API robustness by handling cases where tasks might not exist.

Also applies to: 913-913

wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (3)

13-14: Improved imports for better code organization.

The imports have been updated to support the new store-based architecture, with proper typing from GraphQL types.

Also applies to: 23-23


80-82: Refactored to use centralized state management.

The component now uses usePromptThreadStore to access chart-related actions instead of receiving them through props, reducing prop drilling and improving code maintainability.


160-160: Function naming aligned with store actions.

The function name change from onRegenerateChartAnswer to onGenerateChartAnswer standardizes the API to use consistent naming across the codebase.

wren-ui/src/components/pages/home/promptThread/index.tsx (3)

5-5: Updated imports to support new architecture.

The imports now properly include the store and utility functions for checking task completion status.

Also applies to: 8-8


41-46: Simplified component props.

The AnswerResultTemplate component now has a cleaner interface with reduced props, leveraging the store for most of its functionality.


69-74: Removed props in favor of store-based state.

The PromptThread component now uses the store to access its data instead of receiving it through props, which simplifies the component and reduces prop drilling.

wren-ui/src/components/pages/home/prompt/index.tsx (15)

10-10: No issues with this import change.


22-22: Renaming the prop clarifies its intent.


35-35: Interface update appears consistent.


57-57: Prop rename to onCreateResponse.
Looks good; ensure all referencing components adhere to this updated naming for clarity.


81-84: Added state variables for tracking visibility and input.
The introduction of showResult and question streamlines your prompt flow.


87-90: Memoized isProcessing computation.
This leverages getIsProcessing to keep the rendering optimized. Good approach.


94-95: State transition on askingTask change.
Ensures the process state is updated consistently. No concerns spotted.


106-111: selectRecommendedQuestion method.
This is a neat separation for creating a response from recommended questions. Nice structure.


115-119: intentSQLAnswer handles text-to-sql response creation.
Implementation is clear; any failures are handled by your existing promise flow. Good job.


124-124: Clearing the question on close.
Helps reset the component state between sessions.


129-131: stopProcess method introduced.
Effectively cancels the operation and resets the prompt. Looks fine.


135-141: submitAsk manages submission flow.
Including a check for isProcessing prevents spamming multiple requests. Well-implemented.


155-158: Transition to using PromptInput.
Encapsulates input logic nicely and matches the component refactor. Good approach.


160-160: Minor placeholder line change.
No functional change; safe to overlook.


161-172: Conditional rendering of PromptResult.
This is straightforward, ensuring the result is only shown when applicable. Implementation looks correct.

wren-ui/src/hooks/useAskProcessState.tsx (6)

3-7: Expanding imports to include new AskingTask types.
The updated imports align with the introduction of broader state handling. No concerns.


12-15: Added SEARCHING and CORRECTING to processing states.
Keeps parity with updated enumerations. Looks consistent.


18-40: convertAskingTaskToProcessState function.
• Correctly returns NO_RESULT if there are no candidates for TEXT_TO_SQL tasks.
• Mapping from AskingTaskStatus to PROCESS_STATE is well-structured.


51-63: matchedState validates transitions via ProcessStateMachine.
Strong approach to avoid invalid transitions. Good use of console warnings.


65-67: transitionTo sets the new state.
Straightforward logic, no issues found.


69-75: isFinished and isFailed helpers.
These concise checks improve overall readability.

wren-ui/src/pages/home/[id].tsx (14)

3-10: Extended React imports and hooks.
Bringing in necessary hooks is aligned with new functionality. No issue found.


25-25: QuestionSQLPairModal import location changed.
No concerns. Organizational detail is minor.


28-28: Importing PromptThreadProvider.
Enables broader context injection. Looks fine.


163-165: Storing responses and pollingResponse in useMemo.
Prevents redundant computations. Useful for performance.


200-203: onGenerateThreadRecommendedQuestions function added.
Asynchronously fetching recommendation questions is consistent with the rest of the flow.


205-230: handleUnfinishedTasks to manage incomplete states.
• Good approach to systematically detect both incomplete asking tasks and thread responses.
• Maintains clarity in the live polling mechanism.


234-239: storeQuestionsToAskPrompt for batch storing thread questions.
Centralizes logic for recommended questions. Nicely integrated with askPrompt.


245-255: Cleanup logic in the useEffect return.
Effectively stops polling and resets prompt upon thread change or unmount.


259-262: Triggering handling of unfinished tasks and storing questions.
Implements a coherent re-initialization step whenever responses updates.


265-269: Polling stops once the response is finished.
Prevents unnecessary polling and toggles recommendation visibility. Good practice.


284-289: onCreateResponse function to create new thread response.
The simplified approach is direct and consistent with the overall data flow.


298-315: providerValue object providing multiple handlers and states.
Facilitates a well-structured context for PromptThread. Good design choice.


319-321: Wrapping PromptThread in PromptThreadProvider.
Ensures children have immediate access to shared values. Implementation is correct.


325-328: Ref passing and prop spread for Prompt.
Allows the parent to control the prompt while passing essential props seamlessly. No issue found.

wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (2)

23-25: Interface extension aligns with repository pattern.

Defining a specialized method findByQueryId(queryId: string) directly on IAskingTaskRepository is a clear and consistent approach. It improves discoverability and encapsulation of domain-specific queries.


58-70: Robust JSON stringify logic.

Serializing jsonbColumns before storing is correct. If there's any chance of cyclical references or large structures, consider safe stringification with error handling or logging to prevent silent failures or truncated data.

Do you want me to generate a script to check for cyclical JSON data in the detail column upstream in the codebase?

wren-ui/src/apollo/server/services/askingTaskTracker.ts (2)

342-349: Parallel job handling done right – but confirm concurrency limit.

Using Promise.allSettled for parallel job execution is a valid pattern. For a large number of tasks, you may want to limit concurrency to avoid saturating your service or external AI adaptor calls.

Would you like a script to track the max concurrency over a given time period by analyzing logs or checking task creation frequency? This helps verify load constraints.


37-54: Interfaces and structure are clear.

Defining the TrackedTask, TrackedAskingResult, and handling rerunFromCancelled logic in createAskingTask are well-structured and easy to follow.

wren-ui/src/components/pages/home/prompt/Result.tsx (1)

80-87: Effective use of attachLoading.

Attaching the loading state to the stop action is a nice pattern for user feedback, preventing multiple concurrent cancellations and offering a robust UX.

wren-ui/src/hooks/useAskPrompt.tsx (10)

2-2: No concerns with the new lodash imports.


7-7: Importing DetailedThread aligns with new cache update logic.


10-10: Importing ThreadResponse is consistent with the new rerun logic.


16-16: New useRerunAskingTaskMutation import looks good.


21-23: Additional imports for THREAD, ApolloClient, and nextTick look fine.


160-160: Rerun mutation usage
Defining const [rerunAskingTask] = useRerunAskingTaskMutation(); is consistent with the new rerun flow. No issues here.


224-236: Well-structured effect
The useEffect block that updates the cache when isNeedPreparing is true is appropriate. Just confirm that a re-render won’t trigger re-entrant calls when checkFetchAskingStreamTask updates the same data.


283-298: Initiating new tasks
onSubmit and onFetching appear consistent with the creation & polling flow. Looks good overall.


71-73:

Details

✅ Verification successful

Check all call sites
isNeedPreparing is straightforward, but ensure that no external calls rely on a previously removed or renamed function.


🏁 Script executed:

#!/bin/bash
# Searching references to isNeedPreparing to ensure no mismatch in usage.
rg "isNeedPreparing"

Length of output: 181


Verification Complete - No Issues Found with isNeedPreparing Call Sites

After executing the verification script, all references to isNeedPreparing are confined to its declaration and usage within the same file (wren-ui/src/hooks/useAskPrompt.tsx). There are no external call sites relying on previously removed or renamed functionality. Please proceed with confidence.


112-152:

Details

❓ Verification inconclusive

Potential mismatch in forced status
handleUpdateRerunAskingTaskCache forcibly changes UNDERSTANDING to SEARCHING. Confirm that this transition is always valid for every rerun scenario to avoid unexpected states.


🏁 Script executed:

#!/bin/bash
#!/bin/bash
# Searching for usage of handleUpdateRerunAskingTaskCache to confirm forced status transitions
rg "handleUpdateRerunAskingTaskCache"

Length of output: 190


Action: Validate Forced State Transition in Asking Task

The function handleUpdateRerunAskingTaskCache currently overrides any task with a status of UNDERSTANDING by setting it to SEARCHING (and updating the type to TEXT_TO_SQL). Our search confirms that this function is only referenced within wren-ui/src/hooks/useAskPrompt.tsx. Please verify that this forced transition is intentional and valid across all rerun scenarios. If the change is always correct, consider adding an inline comment explaining the rationale; otherwise, adjust the logic to accommodate cases where retaining the UNDERSTANDING state might be necessary.

wren-ui/src/apollo/server/services/askingService.ts (16)

28-28: Importing Project is aligned with changes requiring project context.


63-63: Replacing viewId with trackedAskingResult
This indicates deeper integration with the new tracked result flow. No immediate concerns.


100-112: Extended createAskingTask signature
The additional parameters (rerunFromCancelled, previousTaskId, threadResponseId) enhance flexibility. Ensure existing calls outside this file pass correct defaults to avoid accidental null references.


113-116: rerunAskingTask method introduction
Method signature is clear and allows rerunning from a threadResponseId. Good addition.


127-131: Doc updates
Comments for the new optional parameters are helpful. Keep them up to date if logic evolves further.


137-158: cancelAskingTask updates
Now delegating to askingTaskTracker.cancelAskingTask. Maintaining error telemetry is a good practice.


540-543: Optional rerun input
Expanding createAskingTask to handle rerun logic is consistent with the new states. Implementation is correct.


550-561: Gathering histories
Good approach to filter out the canceled response ID. This ensures the new rerun does not include canceled context.


563-564: Synchronized return shape
Returning { id: response.queryId } matches the Task interface. Looks consistent.


603-603: Maintaining telemetry
Your consistent telemetry usage for canceling tasks aids in debugging. No suggestions here.


611-616: Confirming null returns
getAskingTask returning null must be handled. The try-catch is done at the resolver layer as per learnings. That’s consistent.


617-621: getAskingTaskById
Similarly, returning null is consistent with the approach for getAskingTask.


626-629: Process doc
The step-based docstring for creating a thread is updated. Very helpful for onboarding.


642-643: Linking askingTaskId
Combining trackedAskingResult?.taskId with the new bind in askingTaskTracker is a good design to keep things in sync.


646-653: Binding logic
Appropriately binds the newly created thread response with the underlying tracked task. Straightforward.


702-710: Same pattern for newly created responses
Ensures the response has a consistent askingTaskId if present. No concerns here.

wren-ui/src/components/pages/home/promptThread/AnswerResult.tsx (12)

1-2: New useEffect and debounce imports
These expansions indicate auto-generation of answers. Looks fine.


10-13: Imported RobotSVG, ANSWER_TAB_KEYS, canGenerateAnswer
These re-organizations support the new tab-based UI and "Save to Knowledge" flow.


20-22: Refactored getAnswerIsFinished
Exporting this from TextBasedAnswer helps keep the logic DRY.


24-25: Preparation component
Adding the new preparation UI is a welcome improvement for better user feedback.


26-29: Expanded imports for AskingTaskStatus, ThreadResponse, etc.
These align with the updated task flow.


177-210: isAnswerPrepared logic
Combining !!answerDetail?.queryId and getAnswerIsFinished is good. Just ensure we handle null or undefined states.


217-231: Tab activation
onTabClick triggers generation for breakdowns or charts if missing. This is a neat incremental fetch approach. No concerns.


235-246: Conditional rendering
showAnswerTabs ensures we only see the tabs when the task is finished or the answer is prepared. This helps keep the UI from being cluttered.


250-260: Answer Tab
The 'Answer' tab fetches TextBasedAnswer if not in breakdown-only mode. This guard is correct to avoid mismatched states.


283-285: Beta Chart Tag
Labeling the chart feature as Beta is helpful for setting user expectations.


287-290: ChartAnswer usage
Providing a separate tab for chart functionality organizes the UI well.


292-324: “Save to Knowledge" and “Save as View”
The synergy between the knowledge base and saving queries as views is nicely integrated. No security concerns found.

wren-ui/src/apollo/client/graphql/__types__.ts (7)

31-37: Additions to AskingTask fields look well-structured
These new optional fields (invalidSql, queryId, rephrasedQuestion, retrievedTables, sqlGenerationReasoning, traceId) provide rich metadata about the task and help with debugging or analytics.


147-147: Swapping viewId with taskId in CreateThreadInput
This replacement aligns the thread creation flow with the new “asking task” concept. It seems coherent and does not appear to introduce backward-incompatible changes.


153-153: Mirroring taskId in CreateThreadResponseInput
Ensuring both thread and thread response structures support taskId fosters consistency and a more unified way to track the origin of the data.


561-561: New rerunAskingTask field
Introducing this mutation in the Mutation type is a welcome addition, especially if you plan to reuse the logic from a prior response or re-runnable state.


913-913: Changed askingTask field to optional
Allowing the askingTask to be Maybe<AskingTask> makes sense if certain queries do not retrieve or associate a task. The approach looks consistent with other optional fields.


1152-1152: Optional askingTask in ThreadResponse
Same reasoning as above; making it optional avoids forcing a task to exist for every response. This retains flexibility.


1157-1157: Relaxed sql to optional
Changing sql from required to optional lets you handle flows that produce no SQL. This also prevents forced placeholders.

wren-ui/src/apollo/client/graphql/home.generated.ts (14)

14-15: Expanded CommonAskingTaskFragment
Including fields like rephrasedQuestion, invalidSql, and more ensures the UI has complete details for rendering or logging.


16-16: CommonResponseFragment referencing askingTask
Referencing askingTask directly in the response fragment makes the relationship more explicit. This appears to streamline UI consumption.


30-30: Optional retrieval of askingTask
In the AskingTaskQuery, the field is now optional. This avoids errors when tasks are missing or incomplete.


42-42: ThreadQuery updates
This change indicates the query has been refined to carry newly added or modified fields in the nested data.


49-49: ThreadResponseQuery referencing optional sql
Ensuring sql can be null avoids forcing placeholders and supports incomplete states or new flows.


65-67: RerunAskingTaskMutationVariables
Introduces the responseId parameter, forming the basis for more advanced re-execution flows.


70-70: RerunAskingTaskMutation
This complements the new server-side capability to rerun tasks, returning a Task object for tracking.


85-85: CreateThreadResponseMutation with optional sql
Extending the mutation to handle optional SQL and an askingTask reference is consistent with the new design.


166-166: GenerateThreadResponseBreakdownMutation
Enhances debugging or interactive exploring of the breakdown stages. The newly optional fields are effectively integrated.


173-173: GenerateThreadResponseAnswerMutation
Similarly updated to reflect optional fields in the thread response, ensuring consistent usage of AskingTask.


180-180: GenerateThreadResponseChartMutation
Adapting the mutation to handle new optional data ensures robust, chart-friendly flows without forcing extraneous data.


188-188: AdjustThreadResponseChartMutation
This extension ensures you can adjust chart outputs while preserving optional states in the mutation’s response.


237-262: CommonAskingTaskFragmentDoc
Defining a separate GraphQL fragment for AskingTask is a clean approach to unify usage in queries and ensure type safety across the codebase.


345-348: Query AskingTask references fragment
Replacing explicit fields with the fragment spread simplifies maintenance and keeps the type definitions consistent.

wren-ui/src/apollo/server/resolvers/askingResolver.ts (21)

19-19: New import of AskingDetailTaskInput
This suggests we’re expanding how tasks are represented and passed around, improving clarity for the “asking” workflow.


29-29: New import of TrackedAskingResult
Indicates more advanced or extended tracking of results, which helps in re-running or post-processing tasks.


49-49: Added rephrasedQuestion
Captures an LLM or system rephrasing for better clarity. Good addition to track user-facing transformations.


51-51: New sqlGenerationReasoning
Providing reasoning details about SQL generation can be extremely helpful for debug logs and user insights.


52-52: New retrievedTables
Displays which tables the system used or recognized. Useful for auditing or explaining query context.


53-53: New invalidSql
Key for debugging or user feedback, especially if generated SQL is syntactically incorrect or fails.


54-54: New traceId
Trace or correlation IDs are best practice for distributed debugging. Good addition.


55-55: New queryId
Identifies the query in logs or analytics. In concert with traceId, helps with root-cause analysis.


79-79: Bound rerunAskingTask
Ensures proper scoping of this for the new method. Straightforward improvement.


110-110: Bound transformAskingTask
Similarly ensures the helper function is accessible with the correct context.


197-200: Null check on missing askResult
This avoids potential runtime errors when the result is absent, returning a clean null instead. Good defensive coding.


223-223: Calling transformAskingTask
Centralizing the transformation logic fosters maintainability and consistent output structure.


231-232: Added taskId to createThread’s input
This lines up with the new ability to create threads from an existing task. The descriptive comment clarifies usage.


243-259: Conditional handling of taskId
Smartly retrieves an existing askingTask if the user is referencing a prior flow, else defaults to standard flow. This is a neat design pattern.


262-262: Creating thread after constructing threadInput
The approach ensures that logic validating the taskId or direct input is fully resolved before proceeding. Good flow.


302-302: Stored askingTaskId
Retaining the link to the original or newly created “asking task” ensures future references, reruns, or debugging remain consistent.


373-374: Same taskId addition for createThreadResponse
Mirrors the approach in createThread to unify logic. This enforces a consistent thread flow.


385-401: Conditional logic for response creation
Replicates the “check taskId then fallback” approach. This symmetrical pattern is both intuitive and easier to maintain.


421-437: Added rerunAskingTask resolver
Allows reusing the same prompt or logic, which can be invaluable in iterative or error-correction flows. This is a solid addition.


594-600: Async retrieval of askingTask by ID
Retrieving the stored record ensures the UI can reflect the correct state or details for the response. Good encapsulation with transformAskingTask.


629-666: transformAskingTask helper method
This is a neat approach to unify logic for building a consistent AskingTask. Your usage of Promise.all() for candidate resolution is efficient and well-structured.

Comment thread wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx Outdated
Comment thread wren-ui/src/hooks/useGlobalConfig.tsx Outdated
Comment thread wren-ui/src/hooks/useGlobalConfig.tsx Outdated
Comment thread wren-ui/src/hooks/useGlobalConfig.tsx Outdated
Comment thread wren-ui/src/components/pages/home/promptThread/store.tsx
Comment thread wren-ui/src/components/pages/home/prompt/Input.tsx Outdated
Comment thread wren-ui/src/apollo/server/utils/error.ts
Comment thread wren-ui/src/apollo/server/utils/error.ts
Comment thread wren-ui/src/apollo/server/utils/error.ts
Comment thread wren-ui/src/apollo/server/repositories/askingTaskRepository.ts
@andreashimin andreashimin requested a review from fredalai March 18, 2025 10:32
Copy link
Copy Markdown
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
wren-ui/src/components/pages/home/promptThread/ChartAnswer.tsx (1)

92-101: 🛠️ Refactor suggestion

Use ErrorHandler system instead of console.error

Based on the retrieved learnings, error handling for dashboard operations should be implemented through the ErrorHandler system instead of handling errors inline with console.error.

const [previewData, previewDataResult] = usePreviewDataMutation({
-    onError: (error) => console.error(error),
+    onError: (error) => ErrorHandler.handle(error),
  });

  const [createDashboardItem] = useCreateDashboardItemMutation({
-    onError: (error) => console.error(error),
+    onError: (error) => ErrorHandler.handle(error),
    onCompleted: () => {
      message.success('Successfully pinned chart to dashboard.');
    },
  });

Additionally, you'll need to import the ErrorHandler:

+import { ErrorHandler } from '@/utils/errorHandler';
♻️ Duplicate comments (1)
wren-ui/src/components/pages/home/preparation/index.tsx (1)

102-105: ⚠️ Potential issue

Handle task failure while polling still continues

As noted in a previous review comment, there's an issue where the task request might fail while polling for instant recommended questions continues. Consider adding explicit error handling for this case.

🧹 Nitpick comments (7)
wren-ui/src/components/pages/home/prompt/Input.tsx (1)

33-35: Add proper type annotation for the event parameter

The syncInputValue function has an untyped event parameter. You should specify the type for better type safety and code maintainability.

-  const syncInputValue = (event) => {
+  const syncInputValue = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
     setInputValue(event.target.value);
   };
wren-ui/src/components/pages/home/preparation/index.tsx (2)

50-54: Add proper type annotation for the event parameter

The onCancel function has an untyped event parameter. You should specify the type for better type safety and code maintainability.

-  const onCancel = (e) => {
+  const onCancel = (e: React.MouseEvent) => {
     e.stopPropagation();
     const stopAskingTask = attachLoading(onStopAskingTask, setStopLoading);
     stopAskingTask(askingTask.queryId);
   };

56-60: Add proper type annotation for the event parameter

Similar to the previous comment, the onReRun function also has an untyped event parameter.

-  const onReRun = (e) => {
+  const onReRun = (e: React.MouseEvent) => {
     e.stopPropagation();
     const reRunAskingTask = attachLoading(onReRunAskingTask, setReRunLoading);
     reRunAskingTask(data);
   };
wren-ui/src/components/pages/home/prompt/index.tsx (2)

115-119: Dedicated function for text-to-sql answer creation.
Allows isolated logic for “intent SQL” flow. As above, consider catching async errors explicitly.


135-142: Submission flow triggers state transitions & result display.
The function handles concurrency of “already processing” checks. Consider wrapping the await call in a try/catch block for more robust error handling.

wren-ui/src/hooks/useAskProcessState.tsx (1)

87-148: ProcessStateMachine class for robust transitions.
Encapsulating transitions in a static-only class is effective, though the linter suggests using straight functions or referencing the class name instead of this. Consider adjusting to quell lint.

Example fix for lines referencing this:

- return this.transitions[from]?.next.includes(to)
+ return ProcessStateMachine.transitions[from]?.next.includes(to)
🧰 Tools
🪛 Biome (1.9.4)

[error] 87-148: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 130-130: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 137-137: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

wren-ui/src/components/pages/home/prompt/Result.tsx (1)

158-158: Use optional chaining syntax for cleaner code.

The conditional check for onIntentSQLAnswer can be simplified with optional chaining.

-      onIntentSQLAnswer && onIntentSQLAnswer();
+      onIntentSQLAnswer?.();
🧰 Tools
🪛 Biome (1.9.4)

[error] 158-158: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🛑 Comments failed to post (1)
wren-ui/src/components/pages/home/preparation/index.tsx (1)

102-125: 💡 Verification agent

🧩 Analysis chain

Add null/undefined checks for askingTask properties

When accessing askingTask.retrievedTables and askingTask.sqlGenerationReasoning, there are no checks to ensure these properties exist. This could lead to runtime errors if they are undefined.

-  const retrievedTables = askingTask.retrievedTables || [];
-  const sqlGenerationReasoning =
-    askingTask.sqlGenerationReasoning || askingStreamTask || '';
+  const retrievedTables = askingTask?.retrievedTables || [];
+  const sqlGenerationReasoning =
+    askingTask?.sqlGenerationReasoning || askingStreamTask || '';

Handle the possibility of an undefined askingTask by implementing more defensive coding throughout the component:


🏁 Script executed:

#!/bin/bash
# Check if there are other places in preparation/index.tsx where askingTask is accessed without null checks
rg --context 2 "askingTask\." wren-ui/src/components/pages/home/preparation/index.tsx

Length of output: 1072


Enforce Consistent Null-Checks for askingTask

The current implementation adds optional chaining only for retrievedTables and sqlGenerationReasoning at one location. However, the shell script output shows that there are other instances—such as in the onCancel function (with askingTask.queryId) and multiple status checks—where askingTask is used without ensuring it’s defined. It would be safer to either:

  • Add a robust null/undefined check upfront: Return early or disable interactions if askingTask isn’t valid.
  • Apply optional chaining consistently: For example, use askingTask?.queryId and askingTask?.status in all instances, ensuring no runtime errors occur if askingTask is null or undefined.

Suggested changes:

  • Before any property access: Check if askingTask is falsy and handle appropriately (e.g., return early).
  • In property accesses: Update all instances to use optional chaining where direct null checks aren’t employed.
-  const retrievedTables = askingTask.retrievedTables || [];
-  const sqlGenerationReasoning =
-    askingTask.sqlGenerationReasoning || askingStreamTask || '';
+  const retrievedTables = askingTask?.retrievedTables || [];
+  const sqlGenerationReasoning =
+    askingTask?.sqlGenerationReasoning || askingStreamTask || '';

Also, please review all other occurrences in the file (e.g., in onCancel and status checks) to ensure they either run after a comprehensive null-check or use optional chaining.

📝 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.

  const processState = useMemo(
    () => convertAskingTaskToProcessState(askingTask),
    [askingTask],
  );
  const [isActive, setIsActive] = useState(
    processState !== PROCESS_STATE.FINISHED,
  );

  // wrapping up after answer is prepared
  useEffect(() => {
    setIsActive(!isAnswerPrepared);
  }, [isAnswerPrepared]);

  if (askingTask === null) return null;

  const showView = view !== null;
  // General steps
  const showRetrieving = retrievingNextStates.includes(processState) && !view;
  const showOrganizing = organizingNextStates.includes(processState) && !view;
  const showGenerating = generatingNextStates.includes(processState) && !view;

  const isStopped = askingTask.status === AskingTaskStatus.STOPPED;
  const retrievedTables = askingTask?.retrievedTables || [];
  const sqlGenerationReasoning =
    askingTask?.sqlGenerationReasoning || askingStreamTask || '';

Copy link
Copy Markdown
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 (9)
wren-ui/src/components/pages/home/prompt/Input.tsx (2)

33-35: Add proper type for the event parameter

The syncInputValue function has an untyped event parameter, which could lead to type safety issues.

-  const syncInputValue = (event) => {
+  const syncInputValue = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
     setInputValue(event.target.value);
   };

37-42: Consider adding error handling for the Promise

The handleAsk function calls onAsk which returns a Promise, but there's no error handling for potential failures.

   const handleAsk = () => {
     const trimmedValue = inputValue.trim();
     if (!trimmedValue) return;
     const startAsking = attachLoading(onAsk, setInnerLoading);
-    startAsking(trimmedValue);
+    startAsking(trimmedValue).catch(error => {
+      console.error('Error during ask operation:', error);
+      // Consider adding user-facing error feedback here
+    });
   };
wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx (2)

2-2: Refactor to avoid overshadowing the global Error object.

Consider renaming the imported Error type to something more descriptive (e.g., GraphQLError) to reduce confusion and avoid clashes with the global Error.

- import { Error } from '@/apollo/client/graphql/__types__';
+ import { Error as GraphQLError } from '@/apollo/client/graphql/__types__';
🧰 Tools
🪛 Biome (1.9.4)

[error] 2-2: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


9-19: Clarify or rename this component to avoid confusion with a standard React error boundary.

This component conditionally renders error content but does not implement the full error boundary lifecycle (e.g., componentDidCatch). Consider renaming it (e.g., ErrorPanel) or refactoring it to use React’s native error boundary mechanism if the intention is to catch errors in the entire subtree.

wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1)

21-27: Improve maintainability by memoizing scroll function.

The scrollBottom function is re-declared each render, which can trigger extra computations in the effect hooks. Consider wrapping it with useCallback or extracting it outside the component to enhance performance and readability.

 export default function Organizing(props: Props) {
   const $wrapper = useRef<HTMLDivElement>(null);
   const { stream, loading, error } = props;

-  const scrollBottom = () => {
+  const scrollBottom = useCallback(() => {
     if ($wrapper.current) {
       $wrapper.current.scrollTo({
         top: $wrapper.current.scrollHeight,
       });
     }
-  };
+  }, []);
wren-ui/src/components/pages/home/promptThread/store.tsx (1)

11-37: Add documentation to clarify the purpose of these store methods and fields.

This interface includes multiple properties and callback methods but lacks docstrings. Adding brief explanations for each method’s purpose, expected parameters, and return values enhances code readability and maintainability.

wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (1)

8-12: Align prop name with UI terminology.

The component uses "models" in the UI text but the prop is named "tables". For better code clarity and consistency, consider renaming the prop to match the terminology used in the UI.

interface Props {
-  tables: string[];
+  models: string[];
  loading?: boolean;
  error?: ErrorBoundaryProps['error'];
}

You would also need to update the prop usage throughout the component.

wren-ui/src/components/pages/home/preparation/index.tsx (2)

115-115: Consider replacing hardcoded step counts with dynamic values.

The component uses hardcoded step counts ('1 step' or '3 steps') which could become outdated if steps are added or removed from the workflow.

- return <div className="gray-6">{showView ? '1 step' : '3 steps'}</div>;
+ const stepCount = showView ? 1 : (showRetrieving + showOrganizing + showGenerating);
+ return <div className="gray-6">{stepCount} {stepCount === 1 ? 'step' : 'steps'}</div>;

168-172: Consider refactoring error assignment logic for better readability.

The current approach creates three separate error variables with complex conditions. This could be simplified to make the code more maintainable.

- const retrievingError =
-   !!error && retrievedTables.length === 0 ? error : null;
- const organizingError = !!error && !sqlGenerationReasoning ? error : null;
- const generatingError =
-   !!error && !(organizingError || retrievingError) ? error : null;

+ // Determine which stage has the error
+ let retrievingError = null;
+ let organizingError = null;
+ let generatingError = null;
+ 
+ if (error) {
+   if (retrievedTables.length === 0) {
+     retrievingError = error;
+   } else if (!sqlGenerationReasoning) {
+     organizingError = error;
+   } else {
+     generatingError = error;
+   }
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8289bf7 and c8242c1.

📒 Files selected for processing (9)
  • wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/index.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (1 hunks)
  • wren-ui/src/components/pages/home/prompt/Input.tsx (1 hunks)
  • wren-ui/src/components/pages/home/promptThread/store.tsx (1 hunks)
  • wren-ui/src/hooks/useGlobalConfig.tsx (1 hunks)
  • wren-ui/src/styles/components/button.less (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • wren-ui/src/styles/components/button.less
🚧 Files skipped from review as they are similar to previous changes (1)
  • wren-ui/src/hooks/useGlobalConfig.tsx
🧰 Additional context used
🧬 Code Definitions (1)
wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (2)
wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx (2) (2)
  • Props (4:7)
  • ErrorBoundary (9:19)
wren-ui/src/components/PageLoading.tsx (1) (1)
  • Spinner (39:41)
🪛 Biome (1.9.4)
wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx

[error] 2-2: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (10)
wren-ui/src/components/pages/home/prompt/Input.tsx (3)

37-42: Proper handling of empty inputs implemented

Good job implementing input validation to prevent empty queries from being submitted. This avoids unnecessary API calls and improves user experience.


44-48: Proper event typing and handling implemented

The inputEnter function properly types the event parameter and correctly handles the Enter key press, preventing default behavior appropriately.


1-77: Well-structured component with good state management

The component is well-structured following React best practices. It properly manages state transitions, handles user input, and manages focus appropriately. The conditional disabling of UI elements based on processing state improves user experience.

wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1)

14-40: Looks good, no concerns.

wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (2)

38-38: LGTM! Table count is dynamic and terminology is consistent.

The component correctly displays the number of models found dynamically using the array length, which addresses a previous concern about hardcoded values.


20-45: Well-structured component with good error handling.

The component has a clear structure with appropriate error handling through ErrorBoundary, and conditionally renders content based on the loading state. The UX flow is logical - showing a spinner during loading and displaying the found models with tags when complete.

wren-ui/src/components/pages/home/preparation/index.tsx (4)

53-64: Good use of state machine for process flow management.

The implementation of the state machine to manage different process states and transitions is well done. This approach makes the code more maintainable and easier to reason about, especially for complex workflows with multiple states.


147-150: Elegant error handling approach.

The error object is properly constructed by combining the error data with SQL validation information, providing comprehensive error details to downstream components.


66-119: Well-separated PreparationStatus component with clear responsibilities.

The PreparationStatus component is well-isolated and has clear responsibilities. It handles different UI states based on the task status, including processing, stopped, and finished states, which helps keep the main component cleaner.


134-146: Effective state management with useEffect and useMemo.

Good use of React hooks to manage the component state. The useMemo hook properly memoizes the process state to prevent unnecessary recalculations, and the useEffect hook correctly handles state updates when the answer is prepared.

Copy link
Copy Markdown
Contributor

@fredalai fredalai left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Copy Markdown
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 (2)
wren-ui/src/components/pages/home/preparation/index.tsx (2)

143-147: Consider adding null check for askingTask

The error calculation depends on askingTask?.error and askingTask?.invalidSql, but there's no early return if askingTask is null here. Although line 149 adds this check, it would be safer to include it in the useMemo dependency array.

const error = useMemo(() => {
  return askingTask?.error
    ? { ...askingTask.error, invalidSql: askingTask.invalidSql }
    : null;
-}, [askingTask?.error, askingTask?.invalidSql]);
+}, [askingTask]);

115-115: Consider using variables for step counts

Hardcoded values like "1 step" and "3 steps" could lead to maintenance issues if the number of steps changes. Consider using variables derived from the actual number of displayed steps.

- return <div className="gray-6">{showView ? '1 step' : '3 steps'}</div>;
+ const stepCount = showView ? 1 : 3; // Or calculate dynamically based on actual steps
+ return <div className="gray-6">{stepCount} {stepCount === 1 ? 'step' : 'steps'}</div>;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 29d1466 and d34dec3.

📒 Files selected for processing (5)
  • wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/index.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Generating.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Organizing.tsx (1 hunks)
  • wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • wren-ui/src/components/pages/home/preparation/step/Organizing.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx

[error] 2-2: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (8)
wren-ui/src/components/pages/home/preparation/ErrorBoundary.tsx (2)

2-2: Rename imported Error type to avoid shadowing global Error

The current import shadows the global JavaScript Error object, which can lead to confusion. Rename this import to avoid potential issues.

-import { Error } from '@/apollo/client/graphql/__types__';
+import { Error as GraphQLError } from '@/apollo/client/graphql/__types__';

Then update the Props interface:

export interface Props {
  children: React.ReactNode;
-  error?: Error & { invalidSql?: string };
+  error?: GraphQLError & { invalidSql?: string };
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 2-2: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


15-21: Good implementation of error display

The error boundary effectively separates the error presentation from the application logic, making error handling more maintainable.

wren-ui/src/components/pages/home/preparation/step/Generating.tsx (2)

4-8: Well-defined interface with optional flags

The Props interface is well-designed with clear, optional boolean flags that control the component's display state.


19-33: Clear conditional rendering based on state

The component effectively handles different states with appropriate messaging and visual indicators.

wren-ui/src/components/pages/home/preparation/step/Retrieving.tsx (2)

6-6: Consider renaming 'tables' prop to 'models'

The prop name 'tables' is inconsistent with the UI text that refers to "models". For better maintainability and clarity, consider renaming the prop to match the terminology used in the UI.

interface Props {
-  tables: string[];
+  models: string[];
  loading?: boolean;
}

Then update references to this prop throughout the component.


34-34: Using dynamic count for models found

Good implementation of dynamic text that shows the actual number of models found.

wren-ui/src/components/pages/home/preparation/index.tsx (2)

73-83: Good pattern for loading state management

Using the attachLoading utility with state setters for loading indicators is a clean pattern that keeps the component's behavior consistent.


208-248: Well-structured timeline with conditional steps

The timeline implementation effectively shows the appropriate steps based on the current process state. The error boundary wrapping provides good error handling.

Copy link
Copy Markdown
Contributor

@fredalai fredalai left a comment

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants