ronantakizawa/codereview-bench huggingface dataset:
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts (TypeScript)

Code before:
    }
  }

  private _hasDisconnectIntent(): boolean {
    if (!isClient) return false;

    try {
      return localStorage.getItem("websocket-disconnect-intent") === "true";
    } catch {
      return false;
    }
  }

  private _clearDisconnectIntent(): void {
    if (!isClient) return;

    try {
      localStorage.removeItem("websocket-disconnect-intent");
    } catch {
      // Ignore errors
    }
  }

  private _handleWSMessage(event: MessageEvent): void {
    const message: WebsocketMessage = JSON.parse(event.data);

    // Handle heartbeat response
    if (message.method === "heartbeat" && message.data === "pong") {
      this._handleWSHeartbeatResponse();
      return;
    }

    if (message.method === "node_execution_event") {
      message.data = parseNodeExecutionResultTimestamps(message.data);
    } else if (message.method == "graph_execution_event") {
      message.data = parseGraphExecutionTimestamps(message.data);
    }
    this.wsMessageHandlers[message.method]?.forEach((handler) =>
      handler(message.data),
    );
  }

  private _startWSHeartbeat() {
    this._stopWSHeartbeat();
    this.heartbeatIntervalID = window.setInterval(() => {
      if (this.webSocket?.readyState === WebSocket.OPEN) {
        this.webSocket.send(
          JSON.stringify({
            method: "heartbeat",
            data: "ping",
            success: true,

Review comment (suggestion):
`localStorage` so that websocket disconnection can be handled across tabs cleanly 🙏🏽 

Code after:
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      this.webSocket.close();
    }
  }

  private _hasDisconnectIntent(): boolean {
    if (!isClient) return false;

    try {
      return storage.get(Key.WEBSOCKET_DISCONNECT_INTENT) === "true";
    } catch {
      return false;
    }
  }

  private _clearDisconnectIntent(): void {
    if (!isClient) return;

    try {
      storage.clean(Key.WEBSOCKET_DISCONNECT_INTENT);
    } catch {
      Sentry.captureException(
        new Error("Failed to clear WebSocket disconnect intent"),
      );
    }
  }

  private _handleWSMessage(event: MessageEvent): void {
    const message: WebsocketMessage = JSON.parse(event.data);

    // Handle heartbeat response
    if (message.method === "heartbeat" && message.data === "pong") {
      this._handleWSHeartbeatResponse();
      return;
    }

    if (message.method === "node_execution_event") {
      message.data = parseNodeExecutionResultTimestamps(message.data);
    } else if (message.method == "graph_execution_event") {
      message.data = parseGraphExecutionTimestamps(message.data);
    }
    this.wsMessageHandlers[message.method]?.forEach((handler) =>
      handler(message.data),
    );
  }

  private _startWSHeartbeat() {
    this._stopWSHeartbeat();
    this.heartbeatIntervalID = window.setInterval(() => {
      if (this.webSocket?.readyState === WebSocket.OPEN) {
        this.webSocket.send(
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/app/(platform)/build/components/NewBlockMenu/BlockMenuSidebar/useBlockMenuSidebar.ts (TypeScript)

Code before:
import { useGetV2GetBuilderItemCounts } from "@/app/api/__generated__/endpoints/default/default";
import { useBlockMenuContext } from "../block-menu-provider";

export const useBlockMenuSidebar = () => {
  const { defaultState, setDefaultState } = useBlockMenuContext();

  const { data: blockCounts } = useGetV2GetBuilderItemCounts({
    query : {
        select : (x) =>{
            return x.data
        }
    }
  });

  return {
    blockCounts,
    setDefaultState,
    defaultState,
  }
};

Review comment (bug):
What about the loading and failure handling? Maybe we should do? 💭 

- **On failure**
  - we should show a toast with the API error message?
- **On loading**
  - we can disable the interactions on the sidebar buttons?

Code after:
import { useGetV2GetBuilderItemCounts } from "@/app/api/__generated__/endpoints/default/default";
import { useBlockMenuContext } from "../block-menu-provider";
import { CountResponse } from "@/app/api/__generated__/models/countResponse";

export const useBlockMenuSidebar = () => {
  const { defaultState, setDefaultState } = useBlockMenuContext();

  const { data: blockCounts, isLoading, isError, error} = useGetV2GetBuilderItemCounts({
    query : {
        select : (x) =>{
            return x.data as CountResponse
        }
    }
  });

  return {
    blockCounts,
    setDefaultState,
    defaultState,
    isLoading,
    isError,
    error,
  }
};
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/instrumentation-client.ts (TypeScript)

Code before:
// This file configures the initialization of Sentry on the client.
// The config you add here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";

const isProdOrDev = getAppEnv() === AppEnv.PROD || getAppEnv() === AppEnv.DEV;

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Add optional integrations for additional features
  integrations: [
    Sentry.replayIntegration(),
    Sentry.httpClientIntegration(),
    Sentry.replayCanvasIntegration(),
    Sentry.reportingObserverIntegration(),
    Sentry.browserProfilingIntegration(),
    // Sentry.feedbackIntegration({
    //   // Additional SDK configuration goes in here, for example:
    //   colorScheme: "system",
    // }),
  ],

Review comment (suggestion):
nit:

```suggestion
const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());
```

Code after:
// This file configures the initialization of Sentry on the client.
// The config you add here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";

const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Add optional integrations for additional features
  integrations: [
    Sentry.replayIntegration(),
    Sentry.httpClientIntegration(),
    Sentry.replayCanvasIntegration(),
    Sentry.reportingObserverIntegration(),
    Sentry.browserProfilingIntegration(),
    // Sentry.feedbackIntegration({
    //   // Additional SDK configuration goes in here, for example:
    //   colorScheme: "system",
    // }),
  ],
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/sentry.edge.config.ts (TypeScript)

Code before:
// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import * as Sentry from "@sentry/nextjs";
import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "./src/lib/utils";

const isProdOrDev = getAppEnv() === AppEnv.PROD || getAppEnv() === AppEnv.DEV;

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
  tracesSampleRate: 1,
  tracePropagationTargets: [
    "localhost",
    "localhost:8006",
    /^https:\/\/dev\-builder\.agpt\.co\/api/,
    /^https:\/\/.*\.agpt\.co\/api/,
  ],

  // Setting this option to true will print useful information to the console while you're setting up Sentry.
  debug: false,


Review comment (suggestion):
```suggestion
const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());
```

Code after:
// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import * as Sentry from "@sentry/nextjs";
import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "./src/lib/utils";

const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
  tracesSampleRate: 1,
  tracePropagationTargets: [
    "localhost",
    "localhost:8006",
    /^https:\/\/dev\-builder\.agpt\.co\/api/,
    /^https:\/\/.*\.agpt\.co\/api/,
  ],

  // Setting this option to true will print useful information to the console while you're setting up Sentry.
  debug: false,
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/sentry.server.config.ts (TypeScript)

Code before:
// This file configures the initialization of Sentry on the server.
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";
// import { NodeProfilingIntegration } from "@sentry/profiling-node";

const isProdOrDev = getAppEnv() === AppEnv.PROD || getAppEnv() === AppEnv.DEV;

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
  tracesSampleRate: 1,
  tracePropagationTargets: [
    "localhost",
    "localhost:8006",
    /^https:\/\/dev\-builder\.agpt\.co\/api/,
    /^https:\/\/.*\.agpt\.co\/api/,
  ],

  // Setting this option to true will print useful information to the console while you're setting up Sentry.
  debug: false,


Review comment (suggestion):
```suggestion
const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());
```

Code after:
// This file configures the initialization of Sentry on the server.
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import {
  AppEnv,
  BehaveAs,
  getAppEnv,
  getBehaveAs,
  getEnvironmentStr,
} from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";
// import { NodeProfilingIntegration } from "@sentry/profiling-node";

const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());

const isCloud = getBehaveAs() === BehaveAs.CLOUD;
const isDisabled = process.env.DISABLE_SENTRY === "true";

const shouldEnable = !isDisabled && isProdOrDev && isCloud;

Sentry.init({
  dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",

  environment: getEnvironmentStr(),

  enabled: shouldEnable,

  // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
  tracesSampleRate: 1,
  tracePropagationTargets: [
    "localhost",
    "localhost:8006",
    /^https:\/\/dev\-builder\.agpt\.co\/api/,
    /^https:\/\/.*\.agpt\.co\/api/,
  ],

  // Setting this option to true will print useful information to the console while you're setting up Sentry.
  debug: false,
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/data/execution.py (Python)

Code before:


# -------------------------- Models -------------------------- #


class BlockErrorStats(BaseModel):
    """Typed data structure for block error statistics."""

    block_id: str
    total_executions: int
    failed_executions: int

    @property
    def error_rate(self) -> float:
        """Calculate error rate as a percentage."""
        if self.total_executions == 0:
            return 0.0
        return (self.failed_executions / self.total_executions) * 100


ExecutionStatus = AgentExecutionStatus
NodeInputMask = Mapping[str, JsonValue]
NodesInputMasks = Mapping[str, NodeInputMask]

VALID_STATUS_TRANSITIONS = {
    ExecutionStatus.QUEUED: [
        ExecutionStatus.INCOMPLETE,
    ],
    ExecutionStatus.RUNNING: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.TERMINATED,  # For resuming halted execution
    ],
    ExecutionStatus.COMPLETED: [
        ExecutionStatus.RUNNING,
    ],
    ExecutionStatus.FAILED: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.RUNNING,
    ],
    ExecutionStatus.TERMINATED: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.RUNNING,
    ],
}


class GraphExecutionMeta(BaseDbModel):
    id: str  # type: ignore # Override base class to make this required

Review comment (suggestion):
put a comment on this as i'm 10000% going to forget this later
```suggestion
# dest: source 
VALID_STATUS_TRANSITIONS = {
```

Code after:


# -------------------------- Models -------------------------- #


class BlockErrorStats(BaseModel):
    """Typed data structure for block error statistics."""

    block_id: str
    total_executions: int
    failed_executions: int

    @property
    def error_rate(self) -> float:
        """Calculate error rate as a percentage."""
        if self.total_executions == 0:
            return 0.0
        return (self.failed_executions / self.total_executions) * 100


ExecutionStatus = AgentExecutionStatus
NodeInputMask = Mapping[str, JsonValue]
NodesInputMasks = Mapping[str, NodeInputMask]

# dest: source
VALID_STATUS_TRANSITIONS = {
    ExecutionStatus.QUEUED: [
        ExecutionStatus.INCOMPLETE,
    ],
    ExecutionStatus.RUNNING: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.TERMINATED,  # For resuming halted execution
    ],
    ExecutionStatus.COMPLETED: [
        ExecutionStatus.RUNNING,
    ],
    ExecutionStatus.FAILED: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.RUNNING,
    ],
    ExecutionStatus.TERMINATED: [
        ExecutionStatus.INCOMPLETE,
        ExecutionStatus.QUEUED,
        ExecutionStatus.RUNNING,
    ],
}


class GraphExecutionMeta(BaseDbModel):
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/app/(platform)/monitoring/page.tsx (TypeScript)

Code before:
"use client";
import React, { useCallback, useEffect, useState } from "react";

import {
  GraphExecutionMeta,
  Schedule,
  LibraryAgent,
  ScheduleID,
} from "@/lib/autogpt-server-api";

import { Card } from "@/components/ui/card";
import {
  AgentFlowList,
  FlowInfo,
  FlowRunInfo,
  FlowRunsList,
  FlowRunsStats,
} from "@/components/monitor";
import { SchedulesTable } from "@/components/monitor/scheduleTable";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";

const Monitor = () => {
  const [flows, setFlows] = useState<LibraryAgent[]>([]);
  const [executions, setExecutions] = useState<GraphExecutionMeta[]>([]);
  const [schedules, setSchedules] = useState<Schedule[]>([]);
  const [selectedFlow, setSelectedFlow] = useState<LibraryAgent | null>(null);
  const [selectedRun, setSelectedRun] = useState<GraphExecutionMeta | null>(
    null,
  );
  const [sortColumn, setSortColumn] = useState<keyof Schedule>("id");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  const api = useBackendAPI();


Review comment (suggestion):
these names are very long, the use of ``useGetV1`` and ``useDeleteV1`` is that needed? 

I assume its using the v1 api endpoint so that does make sense but wondering if its needed in the name

Code after:
"use client";
import React, { useCallback, useEffect, useState } from "react";

import { GraphExecutionMeta, LibraryAgent } from "@/lib/autogpt-server-api";
import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import {
  useGetV1ListExecutionSchedulesForAUser,
  useDeleteV1DeleteExecutionSchedule,
} from "@/app/api/__generated__/endpoints/schedules/schedules";

import { Card } from "@/components/ui/card";
import {
  AgentFlowList,
  FlowInfo,
  FlowRunInfo,
  FlowRunsList,
  FlowRunsStats,
} from "@/components/monitor";
import { SchedulesTable } from "@/components/monitor/scheduleTable";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";

const Monitor = () => {
  const [flows, setFlows] = useState<LibraryAgent[]>([]);
  const [executions, setExecutions] = useState<GraphExecutionMeta[]>([]);
  const [selectedFlow, setSelectedFlow] = useState<LibraryAgent | null>(null);
  const [selectedRun, setSelectedRun] = useState<GraphExecutionMeta | null>(
    null,
  );
  const [sortColumn, setSortColumn] =
    useState<keyof GraphExecutionJobInfo>("id");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  const api = useBackendAPI();
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/integrations/webhooks/utils.py (Python)

Code before:
                for field_name, value in trigger_node.input_default.items()
                if not is_credentials_field_name(field_name)
            }

            # Create a triggered preset for the graph
            await create_preset(
                graph.user_id,
                LibraryAgentPresetCreatable(
                    graph_id=graph.id,
                    graph_version=graph.version,
                    inputs=preset_inputs,
                    credentials=preset_credentials,
                    name=graph.name,
                    description=graph.description,
                    webhook_id=trigger_node.webhook_id,
                    is_active=True,
                ),
            )

            # Detach webhook from the graph node
            await set_node_webhook(trigger_node.id, None)

            n_migrated_webhooks += 1
        except Exception as e:
            logger.error(
                f"Failed to create triggered preset for graph #{graph.id}: {e}"
            )
            continue

    logger.info(f"Migrated {n_migrated_webhooks} node triggers to triggered presets")


Review comment (bug):
```suggestion
                f"Failed to migrate graph #{graph.id} trigger to preset: {e}"
```

Code after:
                for field_name, value in trigger_node.input_default.items()
                if not is_credentials_field_name(field_name)
            }

            # Create a triggered preset for the graph
            await create_preset(
                graph.user_id,
                LibraryAgentPresetCreatable(
                    graph_id=graph.id,
                    graph_version=graph.version,
                    inputs=preset_inputs,
                    credentials=preset_credentials,
                    name=graph.name,
                    description=graph.description,
                    webhook_id=trigger_node.webhook_id,
                    is_active=True,
                ),
            )

            # Detach webhook from the graph node
            await set_node_webhook(trigger_node.id, None)

            n_migrated_webhooks += 1
        except Exception as e:
            logger.error(f"Failed to migrate graph #{graph.id} trigger to preset: {e}")
            continue

    logger.info(f"Migrated {n_migrated_webhooks} node triggers to triggered presets")
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/integrations/webhooks/utils.py (Python)

Code before:
                if not is_credentials_field_name(field_name)
            }

            # Create a triggered preset for the graph
            await create_preset(
                graph.user_id,
                LibraryAgentPresetCreatable(
                    graph_id=graph.id,
                    graph_version=graph.version,
                    inputs=preset_inputs,
                    credentials=preset_credentials,
                    name=graph.name,
                    description=graph.description,
                    webhook_id=trigger_node.webhook_id,
                    is_active=True,
                ),
            )

            # Detach webhook from the graph node
            await set_node_webhook(trigger_node.id, None)

            n_migrated_webhooks += 1
        except Exception as e:
            logger.error(
                f"Failed to migrate graph #{graph.id} trigger to preset: {e}"
            )
            continue

    logger.info(f"Migrated {n_migrated_webhooks} node triggers to triggered presets")


Review comment (bug):
```suggestion
            logger.error(f"Failed to migrate graph #{graph.id} trigger to preset: {e}")
```

Code after:
                if not is_credentials_field_name(field_name)
            }

            # Create a triggered preset for the graph
            await create_preset(
                graph.user_id,
                LibraryAgentPresetCreatable(
                    graph_id=graph.id,
                    graph_version=graph.version,
                    inputs=preset_inputs,
                    credentials=preset_credentials,
                    name=graph.name,
                    description=graph.description,
                    webhook_id=trigger_node.webhook_id,
                    is_active=True,
                ),
            )

            # Detach webhook from the graph node
            await set_node_webhook(trigger_node.id, None)

            n_migrated_webhooks += 1
        except Exception as e:
            logger.error(f"Failed to migrate graph #{graph.id} trigger to preset: {e}")
            continue

    logger.info(f"Migrated {n_migrated_webhooks} node triggers to triggered presets")