ronantakizawa/codereview-bench huggingface dataset:
Repository: TabbyML/tabby
File: ee/tabby-schema/src/schema/mod.rs (Rust)

Code before:
    #[error("{0}")]
    InvalidLicense(&'static str),

    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

impl<S: ScalarValue> IntoFieldError<S> for CoreError {
    fn into_field_error(self) -> FieldError<S> {
        match self {
            Self::Forbidden(msg) => FieldError::new(msg, graphql_value!({"code": "FORBIDDEN"})),
            Self::Unauthorized(msg) => {
                FieldError::new(msg, graphql_value!({"code": "UNAUTHORIZED"}))
            }
            Self::NotFound(msg) => FieldError::new(msg, graphql_value!({"code": "NOT_FOUND"})),
            Self::InvalidInput(errors) => from_validation_errors(errors),
            _ => self.into(),
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum TestModelConnectionError {
    #[error("{0}")]
    CoreError(#[from] CoreError),

    #[error("{0}")]
    ModelConnectionFailed(String),

    #[error("Model backend is not enabled")]
    NotEnabled,
}

impl<S: ScalarValue> IntoFieldError<S> for TestModelConnectionError {
    fn into_field_error(self) -> FieldError<S> {
        self.into()
    }
}

fn check_claims(ctx: &Context) -> Result<&JWTPayload, CoreError> {
    ctx.claims
        .as_ref()
        .ok_or(CoreError::Unauthorized("You're not logged in"))
}

async fn check_admin(ctx: &Context) -> Result<(), CoreError> {
    let user = check_user(ctx).await?;
    if !user.is_admin {
        return Err(CoreError::Forbidden("You must be admin to proceed"));
    }


Review comment (suggestion):
```suggestion
```

Consider adding an `Other(String)` error type instead.

Code after:
    #[error("{0}")]
    InvalidLicense(&'static str),

    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

impl<S: ScalarValue> IntoFieldError<S> for CoreError {
    fn into_field_error(self) -> FieldError<S> {
        match self {
            Self::Forbidden(msg) => FieldError::new(msg, graphql_value!({"code": "FORBIDDEN"})),
            Self::Unauthorized(msg) => {
                FieldError::new(msg, graphql_value!({"code": "UNAUTHORIZED"}))
            }
            Self::NotFound(msg) => FieldError::new(msg, graphql_value!({"code": "NOT_FOUND"})),
            Self::InvalidInput(errors) => from_validation_errors(errors),
            _ => self.into(),
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum TestModelConnectionError {
    #[error("{0}")]
    FailedToConnect(String),

    #[error("Model backend is not enabled")]
    NotEnabled,

    #[error("{0}")]
    Other(#[from] CoreError),
}

impl<S: ScalarValue> IntoFieldError<S> for TestModelConnectionError {
    fn into_field_error(self) -> FieldError<S> {
        match self {
            TestModelConnectionError::Other(err) => err.into_field_error(),
            _ => self.into(),
        }
    }
}

fn check_claims(ctx: &Context) -> Result<&JWTPayload, CoreError> {
    ctx.claims
        .as_ref()
        .ok_or(CoreError::Unauthorized("You're not logged in"))
}

async fn check_admin(ctx: &Context) -> Result<(), CoreError> {
    let user = check_user(ctx).await?;
    if !user.is_admin {
Repository: TabbyML/tabby
File: crates/http-api-bindings/src/completion/mod.rs (Rust)

Code before:
        unsupported_kind => panic!(
            "Unsupported model kind for http completion: {}",
            unsupported_kind
        ),
    }
}

const FIM_TOKEN: &str = "
";
const FIM_TEMPLATE: &str = "{prefix}
{suffix}";

pub fn build_completion_prompt(model: &HttpModelConfig) -> (Option<String>, Option<String>) {
    if model.kind == "mistral/completion" || model.kind == "openai/completion" {
        (Some(FIM_TEMPLATE.to_owned()), None)
    } else {
        (model.prompt_template.clone(), model.chat_template.clone())
    }
}

fn split_fim_prompt(prompt: &str, support_fim: bool) -> (&str, Option<&str>) {
    if support_fim {
        return (prompt, None);
    }

    let parts = prompt.splitn(2, FIM_TOKEN).collect::<Vec<_>>();
    (parts[0], parts.get(1).copied())
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;

    #[test]
    fn test_split_fim_prompt() {
        let support_fim = vec![
            "prefix
suffix",
            "prefix
",
            "
suffix",
            "
",
            "prefix",
        ];
        for input in support_fim {
            let (prompt, suffix) = split_fim_prompt(input, true);
            assert_eq!(prompt, input);
            assert!(suffix.is_none());
        }
    }

    #[test]
    fn test_split_fim_prompt_no_fim() {

Review comment (suggestion):
```suggestion
fn split_fim_prompt(prompt: &str) -> (&str, Option<&str>) {
    let parts = prompt.splitn(2, FIM_TOKEN).collect::<Vec<_>>();
    (parts[0], parts.get(1).copied())
}
```

Move the condition check to caller.

Code after:
        unsupported_kind => panic!(
            "Unsupported model kind for http completion: {}",
            unsupported_kind
        ),
    }
}

const FIM_TOKEN: &str = "
";
const FIM_TEMPLATE: &str = "{prefix}
{suffix}";

pub fn build_completion_prompt(model: &HttpModelConfig) -> (Option<String>, Option<String>) {
    if model.kind == "mistral/completion" || model.kind == "openai/completion" {
        (Some(FIM_TEMPLATE.to_owned()), None)
    } else {
        (model.prompt_template.clone(), model.chat_template.clone())
    }
}

fn split_fim_prompt(prompt: &str) -> (&str, Option<&str>) {
    let parts = prompt.splitn(2, FIM_TOKEN).collect::<Vec<_>>();
    (parts[0], parts.get(1).copied())
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;

    #[test]
    fn test_split_fim_prompt_no_fim() {
        let no_fim = vec![
            ("prefix
suffix", ("prefix", Some("suffix"))),
            ("prefix
", ("prefix", Some(""))),
            ("
suffix", ("", Some("suffix"))),
            ("
", ("", Some(""))),
            ("prefix", ("prefix", None)),
        ];
        for (input, expected) in no_fim {
            assert_eq!(split_fim_prompt(input), expected);
        }
    }
}
Repository: TabbyML/tabby
File: crates/http-api-bindings/src/completion/mod.rs (Rust)

Code before:
                true,
            );
            Arc::new(engine)
        }
        "openai/legacy_completion_no_fim" | "vllm/completion" => {
            let engine = OpenAICompletionEngine::create(
                model.model_name.clone(),
                model
                    .api_endpoint
                    .as_deref()
                    .expect("api_endpoint is required"),
                model.api_key.clone(),
                false,
            );
            Arc::new(engine)
        }
        unsupported_kind => panic!(
            "Unsupported model kind for http completion: {}",
            unsupported_kind
        ),
    }
}

const FIM_TOKEN: &str = "
";
const FIM_TEMPLATE: &str = "{prefix}
{suffix}";
const OPENAI_FIM_SUPPORT_KINDS: [&str; 3] = [
    "openai/legacy_completion",
    "openai/completion",
    "deepseek/completion",
];

pub fn build_completion_prompt(model: &HttpModelConfig) -> (Option<String>, Option<String>) {
    match model.kind.as_str() {
        x if x == "mistral/completion" || OPENAI_FIM_SUPPORT_KINDS.contains(&x) => {
            (Some(FIM_TEMPLATE.to_owned()), None)
        }
        _ => (model.prompt_template.clone(), model.chat_template.clone()),
    }
}

fn split_fim_prompt(prompt: &str) -> (&str, Option<&str>) {
    let parts = prompt.splitn(2, FIM_TOKEN).collect::<Vec<_>>();
    (parts[0], parts.get(1).copied())
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;


Review comment (suggestion):
```suggestion
const OPENAI_LEGACY_COMPLETION_FIM_ALIASES: [&str; 3] = [
```

Code after:
                true,
            );
            Arc::new(engine)
        }
        "openai/legacy_completion_no_fim" | "vllm/completion" => {
            let engine = OpenAICompletionEngine::create(
                model.model_name.clone(),
                model
                    .api_endpoint
                    .as_deref()
                    .expect("api_endpoint is required"),
                model.api_key.clone(),
                false,
            );
            Arc::new(engine)
        }
        unsupported_kind => panic!(
            "Unsupported model kind for http completion: {}",
            unsupported_kind
        ),
    }
}

const FIM_TOKEN: &str = "
";
const FIM_TEMPLATE: &str = "{prefix}
{suffix}";
const OPENAI_LEGACY_COMPLETION_FIM_ALIASES: [&str; 3] = [
    "openai/legacy_completion",
    "openai/completion",
    "deepseek/completion",
];

pub fn build_completion_prompt(model: &HttpModelConfig) -> (Option<String>, Option<String>) {
    match model.kind.as_str() {
        x if x == "mistral/completion" || OPENAI_LEGACY_COMPLETION_FIM_ALIASES.contains(&x) => {
            (Some(FIM_TEMPLATE.to_owned()), None)
        }
        _ => (model.prompt_template.clone(), model.chat_template.clone()),
    }
}

fn split_fim_prompt(prompt: &str) -> (&str, Option<&str>) {
    let parts = prompt.splitn(2, FIM_TOKEN).collect::<Vec<_>>();
    (parts[0], parts.get(1).copied())
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;
Repository: TabbyML/tabby
File: ee/tabby-ui/app/(dashboard)/system/components/worker-card.tsx (TypeScript)

Code before:
}: {
  backend: ModelHealthBackend
  errorMessage?: string
  className?: string
}) {
  const [{ data, fetching, stale, error }, reexecuteQuery] = useQuery({
    query: testModelConnectionQuery,
    variables: {
      backend
    }
  })

  const connected = !isNil(data?.testModelConnection?.latencyMs)

  if (fetching || stale) {
    return (
      <div className={cn(className)}>
        <IconSpinner />
      </div>
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5 font-semibold text-green-600 dark:text-green-500">
          {/* <IconCheck className='h-3.5 w-3.5' /> */}
          Available
        </p>
      ) : (
        <div className="flex items-center gap-0.5 font-semibold text-red-600 dark:text-red-500">
          <IconCircleAlert className="h-3.5 w-3.5" />
          Unavailable
        </div>
      )}

      <Button
        className="h-5 w-5"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRefresh className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}


Review comment (suggestion):
```suggestion
        <p className="flex items-center gap-0.5 font-semibold">
```

Code after:
  backend: ModelHealthBackend
  errorMessage?: string
  className?: string
}) {
  const [{ data, fetching, stale }, reexecuteQuery] = useQuery({
    query: testModelConnectionQuery,
    variables: {
      backend
    }
  })

  const connected = !isNil(data?.testModelConnection?.latencyMs)

  if (fetching || stale) {
    return (
      <div className={cn(className)}>
        <IconSpinner />
      </div>
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5">Connected</p>
      ) : (
        <div className="flex items-center gap-0.5 text-destructive">
          Unreachable
        </div>
      )}

      <Button
        className="h-5 w-5 rounded-sm"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRotate className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}
Repository: TabbyML/tabby
File: ee/tabby-ui/app/(dashboard)/system/components/worker-card.tsx (TypeScript)

Code before:
  const [{ data, fetching, stale, error }, reexecuteQuery] = useQuery({
    query: testModelConnectionQuery,
    variables: {
      backend
    }
  })

  const connected = !isNil(data?.testModelConnection?.latencyMs)

  if (fetching || stale) {
    return (
      <div className={cn(className)}>
        <IconSpinner />
      </div>
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5 font-semibold text-green-600 dark:text-green-500">
          {/* <IconCheck className='h-3.5 w-3.5' /> */}
          Available
        </p>
      ) : (
        <div className="flex items-center gap-0.5 font-semibold text-red-600 dark:text-red-500">
          <IconCircleAlert className="h-3.5 w-3.5" />
          Unavailable
        </div>
      )}

      <Button
        className="h-5 w-5"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRefresh className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}


Review comment (suggestion):
```suggestion
        <div className="flex items-center gap-0.5 font-semibold">
```

Code after:
    query: testModelConnectionQuery,
    variables: {
      backend
    }
  })

  const connected = !isNil(data?.testModelConnection?.latencyMs)

  if (fetching || stale) {
    return (
      <div className={cn(className)}>
        <IconSpinner />
      </div>
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5">Connected</p>
      ) : (
        <div className="flex items-center gap-0.5 text-destructive">
          Unreachable
        </div>
      )}

      <Button
        className="h-5 w-5 rounded-sm"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRotate className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}
Repository: TabbyML/tabby
File: ee/tabby-ui/app/(dashboard)/system/components/worker-card.tsx (TypeScript)

Code before:
      </div>
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5 font-semibold text-green-600 dark:text-green-500">
          {/* <IconCheck className='h-3.5 w-3.5' /> */}
          Available
        </p>
      ) : (
        <div className="flex items-center gap-0.5 font-semibold text-red-600 dark:text-red-500">
          <IconCircleAlert className="h-3.5 w-3.5" />
          Unavailable
        </div>
      )}

      <Button
        className="h-5 w-5"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRefresh className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}


Review comment (suggestion):
```suggestion
        <IconRefresh className="h-3.5 w-3.5" />
```

Use radix reload: https://www.radix-ui.com/icons

<img width="691" alt="image" src="https://github.com/user-attachments/assets/ff5f70f5-ef47-48fb-afa4-8db02db4dd9c">


Code after:
    )
  }

  return (
    <div className={cn('flex items-center gap-3', className)}>
      {connected ? (
        <p className="flex items-center gap-0.5">Connected</p>
      ) : (
        <div className="flex items-center gap-0.5 text-destructive">
          Unreachable
        </div>
      )}

      <Button
        className="h-5 w-5 rounded-sm"
        size="icon"
        variant="ghost"
        disabled={fetching}
        onClick={reexecuteQuery}
      >
        <IconRotate className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}
Repository: TabbyML/tabby
File: ee/tabby-ui/lib/hooks/use-license.ts (TypeScript)

Code before:
/**
 * check the validity of the current license
 */
export const useLicenseValidity = (options?: UseLicenseValidityOptions) => {
  const [{ data }] = useLicense()
  const licenseInfo = data?.license
  const searchParams = useSearchParams()

  const hasLicense = !!licenseInfo

  // Determine if the current license has sufficient level
  const hasSufficientLicense =
    !!licenseInfo &&
    (!options?.licenses?.length || options.licenses.includes(licenseInfo.type))

  const isLicenseOK = licenseInfo?.status === LicenseStatus.Ok

  // Determine if the current license is expired
  const isExpired = licenseInfo?.status === LicenseStatus.Expired

  // Determine if the seat count is exceeded
  const isSeatsExceeded = licenseInfo?.status === LicenseStatus?.SeatsExceeded

  // Testing parameters from searchParams
  const isTestExpired = searchParams.get('licenseExpired') === '1'
  const isTestSeatsExceeded = searchParams.get('seatsExceeded') === '1'

  return {
    hasLicense,
    // FIXME introduced testing searchParams
    isLicenseOK: isLicenseOK && !(isTestExpired || isTestSeatsExceeded),
    isExpired: isExpired || isTestExpired,
    isSeatsExceeded: isSeatsExceeded || isTestSeatsExceeded,
    hasSufficientLicense
  }
}

export { getLicenseInfo, useLicense, useLicenseInfo }


Review comment (suggestion):
```suggestion
  const isTestExpired = searchParams.get('licenseError') === 'expired'
  const isTestSeatsExceeded = searchParams.get('licenseError') === 'seatsExceed'
```

Code after:
/**
 * check the validity of the current license
 */
export const useLicenseValidity = (options?: UseLicenseValidityOptions) => {
  const [{ data }] = useLicense()
  const licenseInfo = data?.license
  const searchParams = useSearchParams()

  const hasLicense = !!licenseInfo

  // Determine if the current license has sufficient level
  const hasSufficientLicense =
    !!licenseInfo &&
    (!options?.licenses?.length || options.licenses.includes(licenseInfo.type))

  const isLicenseOK = licenseInfo?.status === LicenseStatus.Ok

  // Determine if the current license is expired
  const isExpired = licenseInfo?.status === LicenseStatus.Expired

  // Determine if the seat count is exceeded
  const isSeatsExceeded = licenseInfo?.status === LicenseStatus?.SeatsExceeded

  // Testing parameters from searchParams
  const isTestExpired = searchParams.get('licenseError') === 'expired'
  const isTestSeatsExceeded = searchParams.get('licenseError') === 'seatsExceed'

  return {
    hasLicense,
    // FIXME introduced testing searchParams
    isLicenseOK: isLicenseOK && !(isTestExpired || isTestSeatsExceeded),
    isExpired: isExpired || isTestExpired,
    isSeatsExceeded: isSeatsExceeded || isTestSeatsExceeded,
    hasSufficientLicense
  }
}

export { getLicenseInfo, useLicense, useLicenseInfo }
Repository: TabbyML/tabby
File: ee/tabby-ui/components/license-banner.tsx (TypeScript)

Code before:
      value={{ isShowLicenseBanner, setIsShowLicenseBanner }}
    >
      {children}
    </ShowLicenseBannerContext.Provider>
  )
}

export function useShowLicenseBanner(): [
  boolean,
  React.Dispatch<React.SetStateAction<boolean>>
] {
  const { isShowLicenseBanner, setIsShowLicenseBanner } = React.useContext(
    ShowLicenseBannerContext
  )
  return [isShowLicenseBanner, setIsShowLicenseBanner]
}

export function LicenseBanner() {
  const [isShowLicenseBanner, setIsShowLicenseBanner] = useShowLicenseBanner()
  const { isExpired, isSeatsExceeded } = useLicenseValidity()
  const pathname = usePathname()
  const style = isShowLicenseBanner ? { height: BANNER_HEIGHT } : { height: 0 }

  const tips = useMemo(() => {
    if (isExpired) {
      return 'Your license is expired.'
    }

    if (isSeatsExceeded) {
      return 'You have more active users than seats included in your license.'
    }

    return 'No valid license configured'
  }, [isExpired, isSeatsExceeded])

  return (
    <div
      className={cn(
        'flex items-center justify-between border-b bg-secondary px-4 text-secondary-foreground transition-all md:px-5',
        {
          'opacity-100 pointer-events-auto': isShowLicenseBanner,
          'opacity-0 pointer-events-none': !isShowLicenseBanner
        }
      )}
      style={style}
    >
      <div className="flex items-center gap-1 font-semibold text-destructive">
        <IconNotice />
        {tips}
      </div>


Review comment (suggestion):
```suggestion
      return 'Your subscription is expired.'
```

Code after:
      value={{ isShowLicenseBanner, setIsShowLicenseBanner }}
    >
      {children}
    </ShowLicenseBannerContext.Provider>
  )
}

export function useShowLicenseBanner(): [
  boolean,
  React.Dispatch<React.SetStateAction<boolean>>
] {
  const { isShowLicenseBanner, setIsShowLicenseBanner } = React.useContext(
    ShowLicenseBannerContext
  )
  return [isShowLicenseBanner, setIsShowLicenseBanner]
}

export function LicenseBanner() {
  const [isShowLicenseBanner, setIsShowLicenseBanner] = useShowLicenseBanner()
  const { isExpired, isSeatsExceeded } = useLicenseValidity()
  const pathname = usePathname()
  const style = isShowLicenseBanner ? { height: BANNER_HEIGHT } : { height: 0 }

  const tips = useMemo(() => {
    if (isExpired) {
      return 'Your subscription is expired.'
    }

    if (isSeatsExceeded) {
      return 'You have more active users than seats included in your subscription.'
    }

    return 'No valid license configured'
  }, [isExpired, isSeatsExceeded])

  return (
    <div
      className={cn(
        'flex items-center justify-between border-b bg-secondary px-4 text-secondary-foreground transition-all md:px-5',
        {
          'opacity-100 pointer-events-auto': isShowLicenseBanner,
          'opacity-0 pointer-events-none': !isShowLicenseBanner
        }
      )}
      style={style}
    >
      <div className="flex items-center gap-1 font-semibold text-destructive">
        <IconNotice />
        {tips}
      </div>
Repository: TabbyML/tabby
File: clients/vscode/src/InlineCompletionProvider.ts (TypeScript)

Code before:
      case "accept_line":
        eventData = { type: "select", selectKind: "line", elapsed };
        break;
      default:
        // unknown event type, should be unreachable
        return;
    }
    const params: EventParams = {
      ...eventData,
      eventId,
      viewId: id,
    };
    // await not required
    this.client.telemetry.postEvent(params);
  }

  /**
   * Get current display range with the current completion item
   * @return {Range | undefined} - The range with the current completion item
   */
  public getCurrentDisplayRange(): Range | undefined {
    const item = this.displayedCompletion?.completions.items[this.displayedCompletion.index];
    const range = item?.range;
    if (!range) {
      return undefined;
    }
    if (!item) {
      return undefined;
    }
    const length = (item.insertText as string).split("\n").length - 1; //remove current line count;
    const completionEnd = range.end.line + length;
    const completionRange = new Range(
      new Position(range.start.line, range.start.character),
      new Position(completionEnd == 0 ? completionEnd : completionEnd + 1, 0),
    );
    this.logger.info("current range with displayed completion item:", completionRange);

    return completionRange;
  }
}


Review comment (suggestion):

```suggestion
      // FIXME: If the item has a null range, we can use current position and text length to calculate the result range
      return undefined;
```

Code after:
      case "accept_line":
        eventData = { type: "select", selectKind: "line", elapsed };
        break;
      default:
        // unknown event type, should be unreachable
        return;
    }
    const params: EventParams = {
      ...eventData,
      eventId,
      viewId: id,
    };
    // await not required
    this.client.telemetry.postEvent(params);
  }

  /**
   * Calculate the edited range in the modified document as if the current completion item has been accepted.
   * @return {Range | undefined} - The range with the current completion item
   */
  public calcEditedRangeAfterAccept(): Range | undefined {
    const item = this.displayedCompletion?.completions.items[this.displayedCompletion.index];
    const range = item?.range;
    if (!range) {
      // FIXME: If the item has a null range, we can use current position and text length to calculate the result range
      return undefined;
    }
    if (!item) {
      return undefined;
    }
    const length = (item.insertText as string).split("\n").length - 1; //remove current line count;
    const completionRange = new Range(
      new Position(range.start.line, range.start.character),
      new Position(range.end.line + length + 1, 0),
    );
    this.logger.debug("Calculate edited range for displayed completion item:", completionRange);
    return completionRange;
  }
}