Skip to content

feat(wren-ui): adjustment API (ai-env-changed)#1501

Merged
wwwy3y3 merged 22 commits intoepic/adjust-answerfrom
feature/adjustment-api
Apr 2, 2025
Merged

feat(wren-ui): adjustment API (ai-env-changed)#1501
wwwy3y3 merged 22 commits intoepic/adjust-answerfrom
feature/adjustment-api

Conversation

@wwwy3y3
Copy link
Copy Markdown
Member

@wwwy3y3 wwwy3y3 commented Mar 31, 2025

Description

Thread Response Adjustment

This PR introduces a new feature that allows users to adjust thread responses by providing feedback on SQL generation reasoning or directly applying SQL modifications.

Features

  • Added support for two types of adjustments:

    1. Reasoning Adjustment: Users can provide feedback on table selection and SQL generation reasoning
    2. Direct SQL Adjustment: Users can directly modify the SQL query
  • Background task tracking for adjustment processes with status updates

  • Support for canceling and rerunning adjustment tasks

  • Persistence of adjustment data in the database

API Examples

1. Adjust thread response by providing feedback on SQL generation reasoning

  • A new thread response will be created.
mutation AdjustThreadResponse($responseId: Int!, $data: AdjustThreadResponseInput!) {
  adjustThreadResponse(responseId: $responseId, data: $data) {
    id
    threadId
    question
    sql
    // ...
}

payload
Bring in thread response id, sqlGenerationReasoning & tables

{
  "responseId": 60,
  "data": {
    "sqlGenerationReasoning": "1. Identify the relevant tables: ...",
    "tables": [
              "olist_customers_dataset",
              "olist_order_payments_dataset",
              "olist_orders_dataset"
            ]
  }
}

2. Tracking status

query AdjustmentTask($taskId: String!) {
  adjustmentTask(taskId: $taskId) {
    queryId
    status
    error {
      code
      shortMessage
      message
      stacktrace
    }
    sql
    traceId
  }
}

payload

{
  "taskId": "da25e969-6c02-47df-95de-8b703996cde2"
}

response

{
  "data": {
    "adjustmentTask": {
      "queryId": "da25e969-6c02-47df-95de-8b703996cde2",
      "status": "FINISHED",
      "error": null,
      "sql": "SELECT \"c\".\"customer_state\" AS \"customer_state\", SUM(\"p\".\"payment_value\") AS \"total_payment_value\" FROM \"olist_customers_dataset\" AS \"c\" JOIN \"olist_orders_dataset\" AS \"o\" ON \"c\".\"customer_id\" = \"o\".\"customer_id\" JOIN \"olist_order_payments_dataset\" AS \"p\" ON \"o\".\"order_id\" = \"p\".\"order_id\" GROUP BY \"c\".\"customer_state\"",
      "traceId": "c302b67f-6203-48f3-a318-0234abadde43"
    }
  }
}

3. Thread response query

  • You could also check the status of the adjustment task thru adjustmentTask field.
  • adjustment recorded what changes did users make
  • adjustment.payload.type shows what type of adjustment users made. If thru reasoning adjustments, type would be REASONING
  • adjustment.payload.originalThreadResponseId stands for the thread response we make adjustment based on.
query Thread($threadId: Int!) {
  thread(threadId: $threadId) {
    id
    responses {
      id
      threadId
      question
      sql
      // ...
      adjustment {
        type
        payload
      }
      adjustmentTask {
        queryId
        status
        error {
          code
          shortMessage
          message
          stacktrace
        }
        sql
        traceId
      }
    }
  }
}

Response

//...
"askingTask": null,
          "adjustment": {
            "type": "REASONING",
            "payload": {
              "originalThreadResponseId": 60,
              "retrievedTables": [
                "olist_customers_dataset",
                "olist_order_payments_dataset",
                "olist_orders_dataset"
              ],
              "sqlGenerationReasoning": "1. Identify the relevant tables: To answer the user's question about the total payment value made by customers grouped by customer state, we need to focus on the `olist_customers_dataset` and `olist_order_payments_dataset` tables. The `olist_orders_dataset` ..."
            }
          },
          "adjustmentTask": {
            "queryId": "e99be6df-c5eb-495a-8331-a2b5419c0863",
            "status": "FINISHED",
            "error": null,
            "sql": "SELECT \"c\".\"customer_state\" AS \"customer_state\", SUM(\"p\".\"payment_value\") AS \"total_payment_value\" FROM \"olist_customers_dataset\" AS \"c\" JOIN \"olist_orders_dataset\" AS \"o\" ON \"c\".\"customer_id\" = \"o\".\"customer_id\" JOIN \"olist_order_payments_dataset\" AS \"p\" ON \"o\".\"order_id\" = \"p\".\"order_id\" GROUP BY \"c\".\"customer_state\"",
            "traceId": "f82185fd-d791-4c84-bb80-911c2afe47ad"
          }
        },
// ...

4. cancel

mutation CancelAdjustmentTask($taskId: String!) {
  cancelAdjustmentTask(taskId: $taskId)
}

payload

{
  "taskId": "4047a920-4081-4714-af7f-a23794335b26"
}

5. rerun

mutation RerunAdjustmentTask($responseId: Int!) {
  rerunAdjustmentTask(responseId: $responseId)
}

payload

{
  "responseId": 64
}

6. Apply SQL directly to do adjustment

  • A new thread response will be created.
  • adjustment.payload.type shows what type of adjustment users made. If thru reasoning adjustments, type would be APPLY_SQL
  • adjustment.payload.originalThreadResponseId stands for the thread response we make adjustment based on.
mutation AdjustThreadResponse($data: AdjustThreadResponseInput!, $responseId: Int!) {
  adjustThreadResponse(data: $data, responseId: $responseId) {
    id
    threadId
    question
    sql
    // ...
    adjustment {
      type
      payload
    }
    adjustmentTask {
      queryId
      status
      error {
        code
        shortMessage
        message
        stacktrace
      }
      sql
      traceId
    }
  }
}

payload

{
  "data": {
    "sql": "select 1"
  },
  "responseId": 65
}

thread response query will be:

{
  "id": 66,
  "threadId": 36,
  "question": "What is the total value of payments made by customers from each state?",
  "sql": "select\n  1",
  "view": null,
  "breakdownDetail": null,
  "answerDetail": {
    "queryId": null,
    "status": null,
    "error": null,
    "numRowsUsedInLLM": null,
    "content": null
  },
  "askingTask": null,
  "adjustment": {
    "type": "APPLY_SQL",
    "payload": {
      "originalThreadResponseId": 65,
      "sql": "select 1"
    }
  },
  "adjustmentTask": null
}

Summary by CodeRabbit

  • New Features
    • Introduced a new thread response adjustment workflow with interactive options to adjust, cancel, or rerun feedback tasks.
    • Expanded GraphQL functionality with additional queries and mutations to support thread response adjustments.
    • Improved task tracking and telemetry, delivering real-time update visibility for feedback processes.
    • Enhanced data handling ensures a smoother and more reliable feedback experience.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 31, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a series of changes that add adjustment functionality to thread responses. A new migration creates an adjustment JSONB column in the database. Enhancements are added to the adaptor, resolvers, GraphQL schema, and services to support feedback tasks and adjustment operations. New types, interfaces, and enums are integrated across repositories and models. An adjustment background task tracker is implemented to manage task lifecycles while telemetry and application initialization receive minor updates.

Changes

File(s) Change Summary
wren-ui/migrations/2025...add_adjustment_to_thread_response.js Adds migration for an adjustment JSONB column in the thread_response table with corresponding up/down methods.
wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts Adds feedback methods (createAskFeedback, getAskFeedbackResult, cancelAskFeedback) and updates transformStatusAndError.
wren-ui/src/apollo/server/backgrounds/adjustmentBackgroundTracker.ts
wren-ui/src/apollo/server/backgrounds/index.ts
Introduces AdjustmentBackgroundTaskTracker class to manage asynchronous adjustment tasks and exports it.
wren-ui/src/apollo/server/models/adaptor.ts
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts
Adds new interfaces, enums, and types for AskFeedback and thread response adjustments, updating data structures and repository methods.
wren-ui/src/apollo/server/resolvers.ts
wren-ui/src/apollo/server/resolvers/askingResolver.ts
Integrates new GraphQL resolver fields and methods to handle adjustment tasks and thread response adjustments.
wren-ui/src/apollo/server/schema.ts Updates the GraphQL schema with new input types, enums, and types for thread adjustments and adjustment tasks, along with new Query and Mutation definitions.
wren-ui/src/apollo/server/services/askingService.ts
wren-ui/src/apollo/server/services/askingTaskTracker.ts
Enhances service layer with new methods and interfaces for thread response adjustments and refines type casting within task tracking.
wren-ui/src/apollo/server/telemetry/telemetry.ts
wren-ui/src/common.ts
Adds a new telemetry event for adjustments and introduces the askingTaskRepository parameter to the application initialization.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Resolver
    participant Service
    participant Repository
    participant BackgroundTracker
    participant DB

    Client->>Resolver: Mutation adjustThreadResponse(responseId, data)
    Resolver->>Service: adjustThreadResponseAnswer()/with SQL method
    Service->>Repository: Retrieve thread response
    Repository->>DB: Query ThreadResponse table (with adjustment column)
    DB-->>Repository: Return thread response data
    Service->>BackgroundTracker: Initiate adjustment task
    BackgroundTracker->>DB: Poll for task updates
    DB-->>BackgroundTracker: Return adjustment status/result
    BackgroundTracker-->>Service: Adjustment task result
    Service-->>Resolver: Return updated ThreadResponse
    Resolver-->>Client: Response with adjustment details
Loading

Possibly related PRs

Poem

I’m a little rabbit, hopping through the code,
Adjustments now abound on every mode.
Columns, tasks, and feedback galore,
Each new change opens up a door.
With a twitch of my nose, I cheer and sing,
Celebrating each upgrade that the changes bring!
🐇✨


🪧 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 plan to trigger planning for file edits and PR creation.
  • @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.

@wwwy3y3 wwwy3y3 requested review from andreashimin, Copilot, fredalai and onlyjackfrost and removed request for Copilot and onlyjackfrost March 31, 2025 19:40
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a new adjustment API feature for thread responses, enabling users to either provide feedback on SQL generation reasoning or directly apply SQL changes. The changes include the addition of new GraphQL types and resolvers, updates to service layers and repositories to support adjustment data, and corresponding migrations and telemetry events.

Reviewed Changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated no comments.

Show a summary per file
File Description
wren-ui/src/common.ts Injects the new askingTaskRepository dependency.
wren-ui/src/apollo/server/telemetry/telemetry.ts Adds a new telemetry event for thread response adjustments.
wren-ui/src/apollo/server/services/askingTaskTracker.ts Updates the return object to explicitly cast taskRecord.detail as AskResult.
wren-ui/src/apollo/server/services/askingService.ts Adds new methods for adjustment operations (apply SQL, provide reasoning, cancel, rerun, and retrieve tasks).
wren-ui/src/apollo/server/schema.ts Introduces new GraphQL types, inputs, enums, and mutations/queries for adjustments.
wren-ui/src/apollo/server/resolvers/askingResolver.ts Adds resolvers for adjustment operations and integrates them into the existing API.
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts Updates thread response repository to store and parse adjustment data.
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts Extends the asking task detail type to include adjustment information.
wren-ui/src/apollo/server/models/adaptor.ts Adds AskFeedback types and interfaces to support the new adjustment functionality.
Other files (backgrounds, wrenAIAdaptor, migrations) Support the new adjustment feature by introducing relevant background tracking, API calls, and schema migrations.
Comments suppressed due to low confidence (2)

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

  • [nitpick] Consider ensuring that the explicit cast to AskResult accurately reflects the structure of taskRecord.detail to avoid potential type mismatches.
      ...(taskRecord?.detail as AskResult),

wren-ui/src/apollo/server/resolvers/askingResolver.ts:725

  • [nitpick] Verify that using parent.askingTaskId to retrieve the adjustment task is appropriate and clearly distinguishes between adjustment and standard asking tasks.
        parent.askingTaskId,

@wwwy3y3
Copy link
Copy Markdown
Member Author

wwwy3y3 commented Mar 31, 2025

@coderabbitai summary

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 31, 2025

✅ Actions performed

Summary regeneration triggered.

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: 3

🧹 Nitpick comments (10)
wren-ui/src/apollo/server/backgrounds/adjustmentBackgroundTracker.ts (6)

17-18: Consider using environment-based logging levels.
By setting logger.level = 'debug' unconditionally, there is a risk of exposing detailed logs in production, which may include sensitive or verbose output. It is often preferable to load log levels from environment variables or a configuration file to ensure that debug logs are only enabled in development.


61-93: Validate polling strategy in constructor.
Starting the polling in the constructor may be desired behavior, but it can lead to potential race conditions if other dependencies are not fully initialized. Consider offering a separate init() method or a factory to ensure controlled startup, especially if future expansions require dependency readiness checks.


229-245: Avoid partial memory-database discrepancy.
getAdjustmentResult first checks the in-memory map, then falls back to the database. This approach is fine, but if a task is canceled or removed from memory, you may want to ensure the database record also reflects that status to avoid stale entries if the user queries the task again later.

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


258-260: Memory cleanup on cancellation.
cancelAdjustmentTask does not remove the canceled task from the in-memory tracking maps. If a user repeatedly creates and cancels tasks, the in-memory store could accumulate stale tasks unless the tasks are removed in a follow-up operation.


274-368: Parallel polling might overwhelm external services.
Promise.allSettled for all tasks is efficient, but if the number of tasks scales high, it could stress the AI service or database. Consider throttling or batching the jobs in smaller chunks to avoid performance bottlenecks or rate limits.


440-450: Potential for extended change detection.
isResultChanged currently checks only status diffs. If the response contents (like text or partial results) can evolve without changing status, consider expanding the check to detect those changes too.

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

659-663: Clear input for adjustments.
AdjustThreadResponseInput effectively captures the key data required for either explaining reasoning (tables, sqlGenerationReasoning) or applying direct SQL changes (sql). Ensure all fields are optional or validated if certain keys only apply to specific adjustment types.


721-724: Payload typed as JSON.
Storing the payload in JSON allows maximum flexibility. If you need stricter contracts, consider using custom scalar types or inline object fields. However, JSON is often the most practical choice for rapid iteration.

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

468-501: Check for consistent naming and error handling.
The logic flow is correct: if data.sql is present, apply it directly; otherwise, create a feedback-based adjustment. Consider adding defensive checks to ensure data.sql or data.tables is valid.

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

1062-1085: adjustThreadResponseWithSQL directly clones the context.
While the creation of a new ThreadResponse is correct, be sure it's clear to users that any subsequent modifications are not reflected in the original.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2b448c and 6242c9f.

📒 Files selected for processing (14)
  • wren-ui/migrations/20250510000000_add_adjustment_to_thread_response.js (1 hunks)
  • wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts (4 hunks)
  • wren-ui/src/apollo/server/backgrounds/adjustmentBackgroundTracker.ts (1 hunks)
  • wren-ui/src/apollo/server/backgrounds/index.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/threadResponseRepository.ts (6 hunks)
  • wren-ui/src/apollo/server/resolvers.ts (2 hunks)
  • wren-ui/src/apollo/server/resolvers/askingResolver.ts (6 hunks)
  • wren-ui/src/apollo/server/schema.ts (5 hunks)
  • wren-ui/src/apollo/server/services/askingService.ts (9 hunks)
  • wren-ui/src/apollo/server/services/askingTaskTracker.ts (1 hunks)
  • wren-ui/src/apollo/server/telemetry/telemetry.ts (1 hunks)
  • wren-ui/src/common.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1)
Learnt from: andreashimin
PR: Canner/WrenAI#1117
File: wren-ui/src/apollo/server/repositories/threadResponseRepository.ts:37-37
Timestamp: 2025-03-27T09:01:59.977Z
Learning: In the ThreadResponseRepository, the `chartType` property is intentionally typed as string in the database layer, while the ChartType enum is used specifically for AI adaptor input/output in the application layer.
🧬 Code Definitions (4)
wren-ui/src/apollo/server/services/askingTaskTracker.ts (1)
wren-ui/src/apollo/server/models/adaptor.ts (1)
  • AskResult (119-134)
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (2)
wren-ui/src/apollo/server/models/adaptor.ts (2)
  • AskResult (119-134)
  • AskFeedbackResult (313-321)
wren-ui/src/apollo/server/resolvers/askingResolver.ts (1)
  • AskingTask (51-65)
wren-ui/src/apollo/server/adaptors/wrenAIAdaptor.ts (1)
wren-ui/src/apollo/server/models/adaptor.ts (3)
  • AskFeedbackInput (296-302)
  • AsyncQueryResponse (68-70)
  • AskFeedbackResult (313-321)
wren-ui/src/apollo/server/resolvers/askingResolver.ts (3)
wren-ui/src/apollo/server/models/adaptor.ts (1)
  • WrenAIError (5-8)
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1)
  • ThreadResponse (65-76)
wren-ui/src/apollo/client/graphql/__types__.ts (1)
  • ThreadResponse (1201-1212)
🪛 Biome (1.9.4)
wren-ui/src/apollo/server/backgrounds/adjustmentBackgroundTracker.ts

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (50)
wren-ui/src/apollo/server/backgrounds/index.ts (1)

3-3: LGTM: Properly exposing the new background tracker

The export follows the established pattern, making the adjustment background tracker available to the rest of the application.

wren-ui/src/common.ts (1)

131-131: LGTM: Appropriate dependency injection for AskingService

Adding the askingTaskRepository to the AskingService constructor enables the service to directly interact with adjustment tasks, consistent with the PR objective of supporting thread response adjustments.

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

59-60: LGTM: Added telemetry event for tracking adjustment actions

The new telemetry event follows naming conventions and will properly track user interactions with the adjustment feature. Good organizational structure with the dedicated comment section.

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

407-407: Added type safety for task detail property

The explicit type cast to AskResult ensures that the properties being spread from taskRecord?.detail conform to the expected type structure, improving type safety in the returned object.

wren-ui/migrations/20250510000000_add_adjustment_to_thread_response.js (2)

1-14: Database migration looks well-structured and appropriately documented.

The up function correctly adds a nullable JSONB column called adjustment with a clear comment describing its purpose. Using JSONB is a good choice for storing structured adjustment data that may vary in format.


16-24: Rollback function properly handles column removal.

The down function correctly implements the rollback logic to drop the adjustment column if needed.

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

295-302: The AskFeedbackInput interface captures all necessary fields for the adjustment API.

The interface includes all the required parameters for providing feedback on SQL generation:

  • tables selection
  • SQL generation reasoning
  • the SQL itself
  • project identifier
  • optional configuration settings

This aligns well with the PR objective of supporting adjustments to thread responses.


304-311: The AskFeedbackStatus enum follows established patterns in the codebase.

The status enum maintains consistency with other status enums in the file (particularly AskResultStatus). The progression from UNDERSTANDING through GENERATING, CORRECTING, to terminal states like FINISHED, FAILED, or STOPPED follows a logical flow for background task management.


313-321: AskFeedbackResult interface properly structures the adjustment response data.

The interface includes all necessary fields for tracking and displaying the result of an adjustment operation. The response array is correctly typed to only allow LLM-generated SQL adjustments, which matches the PR objective of allowing users to adjust SQL generation.

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

37-39: Query resolver for adjustment task retrieval is properly added.

The resolver for fetching adjustment task status is appropriately placed in the Query section with a clear header comment indicating its purpose.


103-107:

Details

❓ Verification inconclusive

Mutation resolvers for adjustment operations follow consistent naming patterns.

The three mutation resolvers for adjustment operations (adjust, cancel, rerun) are well-organized under a dedicated "Adjustment" section header. This follows the established pattern in the codebase for grouping related resolvers.

However, there appears to be some inconsistency in the method naming. While adjustThreadResponse follows the standard pattern, the cancel and rerun methods use cancelAdjustThreadResponseAnswer and rerunAdjustThreadResponseAnswer which include "Answer" in their names, suggesting they might be specifically for answer adjustments rather than general thread response adjustments.


🏁 Script executed:

#!/bin/bash
# Check if there are other adjustment-related resolver methods in the codebase
# to verify the naming convention

rg -A 2 -B 2 "adjustThreadResponse|cancelAdjust|rerunAdjust" --type ts

Length of output: 17513


Action: Clarify Naming Consistency for Adjustment Resolvers

The adjustment-related GraphQL mutations are neatly grouped, but there’s a potential naming inconsistency worth verifying:

  • The resolver for adjusting a thread response is named adjustThreadResponse, whereas the cancellation and rerun operations are implemented as cancelAdjustThreadResponseAnswer and rerunAdjustThreadResponseAnswer (note the extra “Answer” suffix).
  • The GraphQL schema, however, exposes these as cancelAdjustmentTask and rerunAdjustmentTask, which do not mention “Answer.”
  • Please confirm whether the “Answer” suffix is intentional to indicate that these methods specifically handle answer adjustments or if they should be renamed for consistency with adjustThreadResponse.
wren-ui/src/apollo/server/repositories/askingTaskRepository.ts (3)

10-11: Import statement correctly includes the new AskFeedbackResult type.

The import has been updated to include AskFeedbackResult alongside the existing AskResult, correctly supporting the union type defined below.


12-16: New AskingTaskDetail union type properly extends the data model.

The union type approach is a good design choice that maintains backward compatibility with existing code while adding support for the new adjustment functionality. The inclusion of an optional adjustment boolean flag provides a clear indicator of whether the task detail represents an adjustment task.


22-22: The AskingTask interface is properly updated to use the new union type.

Updating the detail property to use the new AskingTaskDetail union type ensures that the repository can handle both regular AskResult objects and the new AskFeedbackResult objects with adjustment data.

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

49-59: Interface clarity is good.
The IAdjustmentBackgroundTaskTracker interface clearly defines the methods needed to manage adjustment tasks, promoting clean architecture and making it easier to mock in tests.


95-153: Robust error handling enhances reliability.
The createAdjustmentTask method properly wraps AI requests and database operations in a try/catch block. Consider including more contextual information (e.g., input parameters) when logging errors to aid debugging.


159-227: Potential concurrency considerations for rerun.
When rerunning an adjustment task, multiple users or processes could trigger concurrent reruns on the same threadResponseId. Ensure the database logic (e.g., re-updating the same asking task) has sufficient concurrency controls, or confirm that your usage patterns allow for safe updates without row locking or version checks.


370-380: Finalizing thread response logic is concise.
updateThreadResponseWhenTaskFinalized elegantly updates only the SQL field when a final result is available. This approach maintains minimal changes. Good job ensuring no extra fields are overwritten inadvertently.

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

42-45: Enum usage promotes clarity.
Defining ThreadResponseAdjustmentType as an enum strongly communicates the possible adjustment types and reduces the chance of typos or mismatches.


94-95: JSON column registration is consistent.
Adding 'adjustment' to jsonbColumns keeps data parsing consistent across repository methods. Maintaining a single array for JSON columns helps ensure new fields won't be missed when reading/writing from the DB.


130-133: Safe JSON parsing on loaded data.
The logic to parse res.adjustment if it's a string preserves schema integrity. Good job ensuring the data is not double-parsed. Using adjustment: adjustment || null also helps avoid undefined references in the application layer.

Also applies to: 139-139


153-153: Data alignment between domain and storage.
Marking the adjustment property in ThreadResponse and converting it to a JSON string on updateOne ensures database consistency. This approach follows the repository pattern neatly, keeping the domain model and DB representation distinct.

Also applies to: 170-170

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

716-719: Exposing adjustment types to the client.
GraphQL enum ThreadResponseAdjustmentType matches your backend enum, providing a straightforward contract for clients. This consistency is beneficial for strongly-typed or code-generated clients.


726-732: Adjustment task exposure.
Defining AdjustmentTask in the schema clarifies real-time or eventual result retrieval for building polling UIs. Be sure to handle potential partial data (e.g., sql might be absent if reasoning is not complete).


744-745: Aggregating all response data is user-friendly.
By including both adjustment and adjustmentTask within ThreadResponse, clients can retrieve the relevant details in a single query, simplifying client-side state management.


984-986: Separate query for adjustmentTask.
Allowing direct retrieval of adjustmentTask by taskId is helpful. Double check that taskId is unique across tasks, or else ensure additional fields for disambiguation.


1098-1105: Comprehensive mutation set.
Allowing adjusting, canceling, and rerunning tasks covers all major user flows. This separation of concerns also allows fine-grained control of user permissions, should you need to restrict certain actions.

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

33-35: Imports align well with new features.
No issues found here; these imports are consistent with the rest of the file changes.


125-131: Doc comments for new ask feedback methods look good.
This aligns with the existing style of the interface; consistent docstrings help maintain clarity.


877-878: Status union extension is appropriate.
Ensuring AskFeedbackStatus is recognized in transformStatusAndError helps unify status handling across all feedback tasks.

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

8-8: The new import is consistent.
AskFeedbackStatus is required for adjustment tasks; no issues here.


43-49: New AdjustmentTask interface enhances clarity.
This interface straightforwardly captures the essential fields for feedback tasks.


121-126: Constructor bindings are well-structured.
Binding new methods ensures they can be correctly referenced across the resolver. No issues spotted.


503-512: Cancellation logic appears straightforward.
This method properly forwards cancellation to the service; no further concerns.


514-530: Rerun flow is consistent with existing patterns.
Calling back into askingService.rerunAdjustThreadResponseAnswer keeps logic centralized.


532-547: getAdjustmentTask shapes a user-friendly response.
By mapping the service response into AdjustmentTask, client-side usage is simplified. No issues found.


705-707: Conditional return helps avoid conflicts.
Skipping askingTask if adjustment exists clarifies the code path and prevents race conditions between tasks.


715-735: adjustmentTask nested resolver is consistent.
Properly returns the new AdjustmentTask data; no major concerns.

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

12-12: Adding ProjectConfigurations is appropriate.
This import is necessary for typed project-level configs.


20-20: ThreadResponseAdjustmentType import clarifies constants usage.
Provides clear semantic meaning for the new adjustment type.


30-30: Importing repositories and Project is aligned with service expansions.
Interfaces from repositories and Project unify cross-service data usage.


41-41: New background trackers are well-integrated.
Including AdjustmentBackgroundTaskTracker and TrackedAdjustmentResult fits the pattern of other background trackers.


418-418: private askingTaskRepository field is a good addition.
Encourages internal referencing of the repository, consistent with other service fields.


419-419: adjustmentBackgroundTracker ensures new tasks remain decoupled.
This reference keeps the adjustment logic encapsulated inside a dedicated tracker.


485-488: Properly instantiating adjustmentBackgroundTracker.
Dependencies like wrenAIAdaptor, askingTaskRepository, and threadResponseRepository are passed, ensuring centralized management for feedback tasks.


1087-1112: adjustThreadResponseAnswer delegates tasks to the background tracker.
This is well-structured for asynchronous feedback processing. Make sure all exceptions from the tracker are properly propagated or handled.


1114-1117: cancelAdjustThreadResponseAnswer is straightforward.
This properly calls the background tracker’s cancellation method. No issues.


1119-1142: Rerunning adjustments inherits from existing design.
This approach aligns with the patterns used for rerunning other tasks. Good consistency.


1144-1148: getAdjustmentTask retrieval logic is consistent.
No concerns. The tracker call is encapsulated well.


1150-1154: getAdjustmentTaskById complements getAdjustmentTask.
Both ID-based and task-based retrieval are useful. This finalizes the adjustment workflow.

@wwwy3y3 wwwy3y3 changed the base branch from main to epic/adjust-answer April 1, 2025 02:47
@wwwy3y3 wwwy3y3 force-pushed the feature/adjustment-api branch from 6242c9f to d20c370 Compare April 1, 2025 02:47
@github-actions github-actions bot changed the title feat(wren-ui): adjustment API feat(wren-ui): adjustment API (ai-env-changed) Apr 1, 2025
@andreashimin andreashimin force-pushed the feature/adjustment-api branch from d0e8a51 to b7556bc Compare April 1, 2025 08:30
@wwwy3y3 wwwy3y3 merged commit 27412c5 into epic/adjust-answer Apr 2, 2025
5 of 6 checks passed
@wwwy3y3 wwwy3y3 deleted the feature/adjustment-api branch April 2, 2025 05:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants