ronantakizawa/codereview-bench huggingface dataset:
Repository: moeru-ai/airi
File: packages/stage-ui/src/components/Widgets/Stage.vue (Vue)

Code before:

onTokenLiteral(async (literal) => {
  await messageContentQueue.add(literal)
})

onTokenSpecial(async (special) => {
  await delaysQueue.add(special)
  await emotionMessageContentQueue.add(special)
})

onStreamEnd(async () => {
  await delaysQueue.add(llmInferenceEndToken)
})

onUnmounted(() => {
  lipSyncStarted.value = false
  if (window.electron) {
    window.electron.ipcRenderer.removeAllListeners('before-hide')
    window.electron.ipcRenderer.removeAllListeners('after-show')
    window.electron.ipcRenderer.removeAllListeners('before-quit')
  }
})

onMounted(() => {
// Is this a good idea?
  if (window.electron) {
    window.electron.ipcRenderer.on('before-hide', () => {
      motion.value = EmotionAngryMotionName
    })
    window.electron.ipcRenderer.on('after-show', () => {
      motion.value = EmotionHappyMotionName
    })
    window.electron.ipcRenderer.on('before-quit', () => {
      motion.value = EmotionThinkMotionName
    })
  }
})
</script>

<template>
  <div relative>
    <div h-full w-full>
      <Live2DScene
        v-if="stageView === '2d'"
        v-model:motion="motion"
        :mouth-open-size="mouthOpenSize"
        model="./assets/live2d/models/hiyori_pro_zh.zip"
        min-w="50% <lg:full" min-h="100 sm:100" h-full w-full flex-1
      />
      <VRMScene
        v-else-if="stageView === '3d'"

Review comment (suggestion):
```suggestion
  if (window.electron != null) {
```

Code after:

onTokenLiteral(async (literal) => {
  await messageContentQueue.add(literal)
})

onTokenSpecial(async (special) => {
  await delaysQueue.add(special)
  await emotionMessageContentQueue.add(special)
})

onStreamEnd(async () => {
  await delaysQueue.add(llmInferenceEndToken)
})

onUnmounted(() => {
  lipSyncStarted.value = false
  window.electron?.ipcRenderer.removeAllListeners('before-hide')
  window.electron?.ipcRenderer.removeAllListeners('after-show')
  window.electron?.ipcRenderer.removeAllListeners('before-quit')
})

onMounted(() => {
  window.electron?.ipcRenderer.on('before-hide', () => {
    motion.value = EmotionAngryMotionName
  })
  window.electron?.ipcRenderer.on('after-show', () => {
    motion.value = EmotionHappyMotionName
  })
  window.electron?.ipcRenderer.on('before-quit', () => {
    motion.value = EmotionThinkMotionName
  })
})
</script>

<template>
  <div relative>
    <div h-full w-full>
      <Live2DScene
        v-if="stageView === '2d'"
        v-model:motion="motion"
        :mouth-open-size="mouthOpenSize"
        model="./assets/live2d/models/hiyori_pro_zh.zip"
        min-w="50% <lg:full" min-h="100 sm:100" h-full w-full flex-1
      />
      <VRMScene
        v-else-if="stageView === '3d'"
        ref="vrmViewerRef"
        model="/assets/vrm/models/AvatarSample-B/AvatarSample_B.vrm"
        idle-animation="/assets/vrm/animations/idle_loop.vrma"
        min-w="50% <lg:full" min-h="100 sm:100" h-full w-full flex-1
        @error="console.error"
Repository: moeru-ai/airi
File: packages/stage-ui/src/components/Widgets/Stage.vue (Vue)

Code before:

onBeforeMessageComposed(async () => {
  setupAnalyser()
  setupLipSync()
})

onBeforeSend(async () => {
  motion.value = EmotionThinkMotionName
})

onTokenLiteral(async (literal) => {
  await messageContentQueue.add(literal)
})

onTokenSpecial(async (special) => {
  await delaysQueue.add(special)
  await emotionMessageContentQueue.add(special)
})

onStreamEnd(async () => {
  await delaysQueue.add(llmInferenceEndToken)
})

onUnmounted(() => {
  lipSyncStarted.value = false
  if (window.electron) {
    window.electron.ipcRenderer.removeAllListeners('before-hide')
    window.electron.ipcRenderer.removeAllListeners('after-show')
    window.electron.ipcRenderer.removeAllListeners('before-quit')
  }
})

onMounted(() => {
// Is this a good idea?
  if (window.electron) {
    window.electron.ipcRenderer.on('before-hide', () => {
      motion.value = EmotionAngryMotionName
    })
    window.electron.ipcRenderer.on('after-show', () => {
      motion.value = EmotionHappyMotionName
    })
    window.electron.ipcRenderer.on('before-quit', () => {
      motion.value = EmotionThinkMotionName
    })
  }
})
</script>

<template>
  <div relative>
    <div h-full w-full>

Review comment (suggestion):
```suggestion
  if (window.electron != null) {
```

Code after:

onBeforeMessageComposed(async () => {
  setupAnalyser()
  setupLipSync()
})

onBeforeSend(async () => {
  motion.value = EmotionThinkMotionName
})

onTokenLiteral(async (literal) => {
  await messageContentQueue.add(literal)
})

onTokenSpecial(async (special) => {
  await delaysQueue.add(special)
  await emotionMessageContentQueue.add(special)
})

onStreamEnd(async () => {
  await delaysQueue.add(llmInferenceEndToken)
})

onUnmounted(() => {
  lipSyncStarted.value = false
  window.electron?.ipcRenderer.removeAllListeners('before-hide')
  window.electron?.ipcRenderer.removeAllListeners('after-show')
  window.electron?.ipcRenderer.removeAllListeners('before-quit')
})

onMounted(() => {
  window.electron?.ipcRenderer.on('before-hide', () => {
    motion.value = EmotionAngryMotionName
  })
  window.electron?.ipcRenderer.on('after-show', () => {
    motion.value = EmotionHappyMotionName
  })
  window.electron?.ipcRenderer.on('before-quit', () => {
    motion.value = EmotionThinkMotionName
  })
})
</script>

<template>
  <div relative>
    <div h-full w-full>
      <Live2DScene
        v-if="stageView === '2d'"
        v-model:motion="motion"
        :mouth-open-size="mouthOpenSize"
        model="./assets/live2d/models/hiyori_pro_zh.zip"
Repository: moeru-ai/airi
File: packages/stage-ui/src/utils/live2d-zip-loader.ts (TypeScript)

Code before:
  }

  const motions = files.filter(f => f.endsWith('.mtn') || f.endsWith('.motion3.json'))
  const physics = files.find(f => f.includes('physics'))
  const pose = files.find(f => f.includes('pose'))

  const settings = new Cubism4ModelSettings({
    url: `${modelName}.model3.json`,
    Version: 3,
    FileReferences: {
      Moc: mocFile,
      Textures: textures,
      Physics: physics,
      Pose: pose,
      Motions: motions.length
        ? {
            '': motions.map(motion => ({ File: motion })),
          }
        : undefined,
    },
  })

  settings.name = modelName;

  // provide this property for FileLoader
  (settings as any)._objectURL = `DontTouchMe://${settings.url}`

  return settings
}

ZipLoader.readText = (jsZip: JSZip, path: string) => {
  const file = jsZip.file(path)

  if (!file) {
    throw new Error(`Cannot find file: ${path}`)
  }

  return file.async('text')
}

ZipLoader.getFilePaths = (jsZip: JSZip) => {
  const paths: string[] = []

  jsZip.forEach(relativePath => paths.push(relativePath))

  return Promise.resolve(paths)
}

ZipLoader.getFiles = (jsZip: JSZip, paths: string[]) =>
  Promise.all(paths.map(
    async (path) => {

Review comment (suggestion):
```suggestion
  (settings as any)._objectURL = `example://${settings.url}`
```

Code after:
  }

  const motions = files.filter(f => f.endsWith('.mtn') || f.endsWith('.motion3.json'))
  const physics = files.find(f => f.includes('physics'))
  const pose = files.find(f => f.includes('pose'))

  const settings = new Cubism4ModelSettings({
    url: `${modelName}.model3.json`,
    Version: 3,
    FileReferences: {
      Moc: mocFile,
      Textures: textures,
      Physics: physics,
      Pose: pose,
      Motions: motions.length
        ? {
            '': motions.map(motion => ({ File: motion })),
          }
        : undefined,
    },
  })

  settings.name = modelName;

  // provide this property for FileLoader
  (settings as any)._objectURL = `example://${settings.url}`

  return settings
}

ZipLoader.readText = (jsZip: JSZip, path: string) => {
  const file = jsZip.file(path)

  if (!file) {
    throw new Error(`Cannot find file: ${path}`)
  }

  return file.async('text')
}

ZipLoader.getFilePaths = (jsZip: JSZip) => {
  const paths: string[] = []

  jsZip.forEach(relativePath => paths.push(relativePath))

  return Promise.resolve(paths)
}

ZipLoader.getFiles = (jsZip: JSZip, paths: string[]) =>
  Promise.all(paths.map(
    async (path) => {
Repository: moeru-ai/airi
File: apps/stage-web/src/components/Layouts/InteractiveArea.vue (Vue)

Code before:
async function handleAudioInputChange(event: Event) {
  const target = event.target as HTMLSelectElement
  const found = audioInputs.value.find(d => d.deviceId === target.value)
  if (!found) {
    selectedAudioDevice.value = undefined
    return
  }

  selectedAudioDevice.value = found
}

watch(isAudioInputOn, async (value) => {
  if (value === 'false') {
    destroy()
    terminate()
  }
})

watch(showMicrophoneSelect, async (value) => {
  if (value) {
    await ensurePermissions()
  }
})

onMounted(() => {
  loadWhisper()
  start()
})

onAfterSend(async () => {
  messageInput.value = ''
})
</script>

<template>
  <div flex="col" items-center pt-4>
    <fieldset flex="~ row" w-fit rounded-lg>
      <label
        :class="[
          tab === 'chat' ? 'bg-primary-100 dark:bg-primary-900' : 'bg-white dark:bg-primary-950',
          tab === 'chat' ? 'text-primary-500 dark:text-primary-500' : '',
          { 'transition-colors-none ': themeColorsHueDynamic },
        ]"
        flex="~ row"
        :checked="tab === 'chat'"
        :aria-checked="tab === 'chat'"
        border="solid l-2 t-2 b-2 primary-100 dark:primary-900"
        bg="hover:primary-100 dark:hover:primary-900"
        text="primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500"
        transition="all duration-250 ease-in-out"
        cursor-pointer items-center gap-1 rounded-l-lg px-2

Review comment (suggestion):
```suggestion
  // loadWhisper()
```

Let's forget this for now.

Code after:
async function handleAudioInputChange(event: Event) {
  const target = event.target as HTMLSelectElement
  const found = audioInputs.value.find(d => d.deviceId === target.value)
  if (!found) {
    selectedAudioDevice.value = undefined
    return
  }

  selectedAudioDevice.value = found
}

watch(isAudioInputOn, async (value) => {
  if (value === 'false') {
    destroy()
    terminate()
  }
})

watch(showMicrophoneSelect, async (value) => {
  if (value) {
    await ensurePermissions()
  }
})

onMounted(() => {
  // loadWhisper()
  start()
})

onAfterSend(async () => {
  messageInput.value = ''
})
</script>

<template>
  <div flex="col" items-center pt-4>
    <fieldset flex="~ row" w-fit rounded-lg>
      <label
        :class="[
          tab === 'chat' ? 'bg-primary-100 dark:bg-primary-900' : 'bg-white dark:bg-primary-950',
          tab === 'chat' ? 'text-primary-500 dark:text-primary-500' : '',
          { 'transition-colors-none ': themeColorsHueDynamic },
        ]"
        flex="~ row"
        :checked="tab === 'chat'"
        :aria-checked="tab === 'chat'"
        border="solid l-2 t-2 b-2 primary-100 dark:primary-900"
        bg="hover:primary-100 dark:hover:primary-900"
        text="primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500"
        transition="all duration-250 ease-in-out"
        cursor-pointer items-center gap-1 rounded-l-lg px-2
Repository: moeru-ai/airi
File: apps/stage-tamagotchi/src-tauri/src/lib.rs (Rust)

Code before:
  // Already monitoring?
  if monitoring_enabled.load(Ordering::Relaxed) {
    return Ok(());
  }

  // Set to true
  state.monitoring_enabled.store(true, Ordering::Relaxed);

  // Then start interval timer for monitoring
  tauri::async_runtime::spawn(async move {
    loop {
      sleep(Duration::from_millis(32)).await; // ~30FPS check rate

      // If monitoring is already stopped, break the loop
      if !monitoring_enabled.load(Ordering::Relaxed) {
        break;
      }

      #[cfg(target_os = "macos")]
      {
        let _ = window.emit("tauri-app:window-click-through:mouse-location-and-window-frame", (get_mouse_location(), get_window_frame(&window)));
      }

      #[cfg(target_os = "windows")]
      {
        let _ = window.emit("tauri-app:window-click-through:mouse-location-and-window-frame", (get_mouse_location(), get_window_frame(&window)));
      }
    }
  });

  Ok(())
}

#[tauri::command]
async fn stop_monitor(window: tauri::Window) -> Result<(), String> {
  let window = window;
  let state = window.state::<WindowClickThroughState>();

  // Set to false
  // Termination will be triggered in the next interval check (tick)
  state.monitoring_enabled.store(false, Ordering::Relaxed);

  Ok(())
}

#[tauri::command]
async fn start_click_through(window: tauri::Window) -> Result<(), String> {
  set_click_through_enabled(&window, true)?;
  Ok(())
}


Review comment (suggestion):
```suggestion
        let _ = window.emit("tauri-app:window-click-through:position-cursor-and-window-frame", (get_mouse_location(), get_window_frame(&window)));
```

Code after:
  if monitoring_enabled.load(Ordering::Relaxed) {
    return Ok(());
  }

  // Set to true
  state.monitoring_enabled.store(true, Ordering::Relaxed);

  // Then start interval timer for monitoring
  tauri::async_runtime::spawn(async move {
    loop {
      sleep(Duration::from_millis(32)).await; // ~30FPS check rate

      // If monitoring is already stopped, break the loop
      if !monitoring_enabled.load(Ordering::Relaxed) {
        break;
      }

      #[cfg(target_os = "macos")]
      {
        let _ = window.emit("tauri-app:window-click-through:position-cursor-and-window-frame", (get_mouse_location(), get_window_frame(&window)));
      }

      #[cfg(target_os = "windows")]
      {
        let _ = window.emit("tauri-app:window-click-through:position-cursor-and-window-frame", (get_mouse_location(), get_window_frame(&window)));
      }
    }
  });

  Ok(())
}

#[tauri::command]
async fn stop_monitor(window: tauri::Window) -> Result<(), String> {
  let window = window;
  let state = window.state::<WindowClickThroughState>();

  // Set to false
  // Termination will be triggered in the next interval check (tick)
  state.monitoring_enabled.store(false, Ordering::Relaxed);

  Ok(())
}

#[tauri::command]
async fn start_click_through(window: tauri::Window) -> Result<(), String> {
  set_click_through_enabled(&window, true)?;
  Ok(())
}

#[tauri::command]
Repository: moeru-ai/airi
File: apps/stage-web/src/pages/devtools/gesture-circle.vue (Vue)

Code before:
<script setup lang="ts">
import { refDebounced, refThrottled, useElementBounding, usePointer, useResizeObserver } from '@vueuse/core'
import { computed, ref, watch } from 'vue'

interface Point {
  x: number
  y: number
}

const containerRef = ref<HTMLDivElement>()
const canvasContainerRef = ref<HTMLDivElement>()
const canvasRef = ref<HTMLCanvasElement>()
const canvasContext = ref<CanvasRenderingContext2D | undefined | null>()

const { x, y } = usePointer({ target: canvasRef })
const bounding = useElementBounding(canvasContainerRef, { immediate: true, windowResize: true })

const pointComputed = computed(() => {
  return {
    x: x.value,
    y: y.value,
  }
})

useResizeObserver(canvasContainerRef, (entries) => {
  const entry = entries[0]
  const { width, height } = entry.contentRect


Review comment (suggestion):
```suggestion
import { computed, ref, watch } from 'vue'

const minimumDataPoints = 6
```

Code after:
<script setup lang="ts">
import { refDebounced, refThrottled, useElementBounding, usePointer, useResizeObserver } from '@vueuse/core'
import { computed, ref, watch } from 'vue'

const minimumDataPoints = 6

interface Point {
  x: number
  y: number
}

const containerRef = ref<HTMLDivElement>()
const canvasContainerRef = ref<HTMLDivElement>()
const canvasRef = ref<HTMLCanvasElement>()
const canvasContext = ref<CanvasRenderingContext2D | undefined | null>()

const { x, y } = usePointer({ target: canvasRef })
const bounding = useElementBounding(canvasContainerRef, { immediate: true, windowResize: true })

const pointComputed = computed(() => {
  return {
    x: x.value,
    y: y.value,
  }
})

useResizeObserver(canvasContainerRef, (entries) => {
  const entry = entries[0]
Repository: moeru-ai/airi
File: docs/.vitepress/components/BlogPosts.vue (Vue)

Code before:
    author?: string
  }
}

const props = defineProps<{
  data: Post[]
}>()

const { t } = useI18n()
const { isDark } = useData()
const category = ref('all')
const categories = computed(() => {
  const allCategories = props.data.map(post => post.frontmatter?.category).filter(Boolean).map(post => post?.toLowerCase())
  return ['all', ...new Set(allCategories as string[])]
})

const posts = computed(() => {
  let postsData = props.data as Post[]

  if (category.value && category.value !== 'all') {
    postsData = props.data.filter(post => post.frontmatter?.category?.toLowerCase() === category.value)
  }

  return postsData
    .map(post => ({ ...post, url: withBase(post.url) }))
    .filter(post => !!(post.frontmatter as any)?.title)
})

async function stringToSeed(str: string) {
  const data = new TextEncoder().encode(str)
  const buffer = await subtle.digest('SHA-256', data)
  const view = new DataView(buffer)
  return view.getUint32(0, false) // false for big-endian
}

// A simple PRNG class to generate random numbers based on a seed.
// One of the linear congruential generator (LCG) implementation.
function createPRNG(seed: number) {
  const a = 1664525
  const c = 1013904223
  const m = 2 ** 32

  function nextInt() {
    seed = (a * seed + c) % m
    return seed
  }

  function nextFloat() {
    return nextInt() / m
  }


Review comment (suggestion):
```suggestion
    .filter(post => !!post.title)
```

Code after:
    author?: string
  }
}

const props = defineProps<{
  data: Post[]
}>()

const { t } = useI18n()
const { isDark } = useData()
const category = ref('all')
const categories = computed(() => {
  const allCategories = props.data.map(post => post.frontmatter?.category).filter(Boolean).map(post => post?.toLowerCase())
  return ['all', ...new Set(allCategories as string[])]
})

const posts = computed(() => {
  let postsData = props.data as Post[]

  if (category.value && category.value !== 'all') {
    postsData = props.data.filter(post => post.frontmatter?.category?.toLowerCase() === category.value)
  }

  return postsData
    .map(post => ({ ...post, url: withBase(post.url) }))
    .filter(post => !!post.title)
})

async function stringToSeed(str: string) {
  const data = new TextEncoder().encode(str)
  const buffer = await subtle.digest('SHA-256', data)
  const view = new DataView(buffer)
  return view.getUint32(0, false) // false for big-endian
}

// A simple PRNG class to generate random numbers based on a seed.
// One of the linear congruential generator (LCG) implementation.
function createPRNG(seed: number) {
  const a = 1664525
  const c = 1013904223
  const m = 2 ** 32

  function nextInt() {
    seed = (a * seed + c) % m
    return seed
  }

  function nextFloat() {
    return nextInt() / m
  }
Repository: moeru-ai/airi
File: packages/stage-ui/src/components/Scenes/VRM.vue (Vue)

Code before:
import { TransitionVertical } from '@proj-airi/ui'
import { OrbitControls } from '@tresjs/cientos'
import { TresCanvas } from '@tresjs/core'
import { storeToRefs } from 'pinia'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'

import DataGuiRange from '../DataGui/Range.vue'
import Collapsable from '../Misc/Collapsable.vue'
import Screen from '../Misc/Screen.vue'
import VRMModel from './VRM/Model.vue'

import { useVRM } from '../../stores'

const props = defineProps<{
  paused: boolean
}>()

const emit = defineEmits<{
  (e: 'loadModelProgress', value: number): void
  (e: 'error', value: unknown): void
}>()

const show = ref(false)

const { modelFile, modelUrl, loadSource } = storeToRefs(useVRM())

const cameraPositionX = ref(-0.17)
const cameraPositionY = ref(0)
const cameraPositionZ = ref(-1)
const vrmModelPositionX = ref(-0.18)
const vrmModelPositionY = ref(-1.32)
const vrmModelPositionZ = ref(-0.24)

const modelRef = ref<{
  setExpression: (expression: string) => void
}>()

const { t } = useI18n()

defineExpose({
  setExpression: (expression: string) => {
    modelRef.value?.setExpression(expression)
  },
})

const selectedModel = computed(() => {
  if (loadSource.value === 'file' && modelFile.value) {
    return URL.createObjectURL(modelFile.value)
  }
  else if (loadSource.value === 'url' && modelUrl.value) {

Review comment (suggestion):
```suggestion
const { modelFile, modelUrl, loadSource, selectedModel } = storeToRefs(useVRM())
```

Code after:
import { TransitionVertical } from '@proj-airi/ui'
import { OrbitControls } from '@tresjs/cientos'
import { TresCanvas } from '@tresjs/core'
import { storeToRefs } from 'pinia'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'

import DataGuiRange from '../DataGui/Range.vue'
import Collapsable from '../Misc/Collapsable.vue'
import Screen from '../Misc/Screen.vue'
import VRMModel from './VRM/Model.vue'

import { useVRM } from '../../stores'

const props = defineProps<{
  paused: boolean
}>()

const emit = defineEmits<{
  (e: 'loadModelProgress', value: number): void
  (e: 'error', value: unknown): void
}>()

const show = ref(false)

const { modelFile, modelUrl, loadSource, selectedModel } = storeToRefs(useVRM())

const cameraPositionX = ref(-0.17)
const cameraPositionY = ref(0)
const cameraPositionZ = ref(-1)
const vrmModelPositionX = ref(-0.18)
const vrmModelPositionY = ref(-1.32)
const vrmModelPositionZ = ref(-0.24)

const modelRef = ref<{
  setExpression: (expression: string) => void
}>()

const { t } = useI18n()

defineExpose({
  setExpression: (expression: string) => {
    modelRef.value?.setExpression(expression)
  },
})
</script>

<template>
  <Screen v-slot="{ height, width }" relative>
    <TresCanvas :alpha="true" :antialias="true" :width="width" :height="height">
      <OrbitControls />