Skip to content

[Code Health] Define types for ONNX Runtime session and state#223

Open
ysdede wants to merge 1 commit intomasterfrom
fix/onnxruntime-types-7812390940331716981
Open

[Code Health] Define types for ONNX Runtime session and state#223
ysdede wants to merge 1 commit intomasterfrom
fix/onnxruntime-types-7812390940331716981

Conversation

@ysdede
Copy link
Copy Markdown
Owner

@ysdede ysdede commented Mar 22, 2026

🎯 What: Replaced the use of any types for the ONNX Runtime session and state variables with their strict types (InferenceSession and Tensor) from onnxruntime-web.
💡 Why: This improves the maintainability and type safety of SileroVAD.ts. By leveraging the actual typings instead of any, future changes or updates are properly protected by TypeScript compilation checks, reducing the risk of runtime errors.
Verification: Verified that pnpm test runs cleanly and successfully, and that no unrequested dependencies were added to package.json. The TypeScript compiler (tsc) was also run and confirmed that ort typings are matched correctly.
Result: A more readable, predictable, and strongly-typed file with identical runtime behavior.


PR created automatically by Jules for task 7812390940331716981 started by @ysdede

Summary by Sourcery

Enhancements:

  • Replace loosely-typed ONNX Runtime session and state properties with strict InferenceSession and Tensor types from onnxruntime-web to improve type safety.

Replaces `any` typings with `InferenceSession` and `Tensor` from `onnxruntime-web`
in `SileroVAD.ts` to improve maintainability and strictly enforce correct ONNX type
boundaries. Also updates the global `ort` declaration to extract types via
`typeof import('onnxruntime-web')` natively.
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 22, 2026

Warning

Rate limit exceeded

@ysdede has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 27 minutes and 9 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d5e7b2b8-8a59-4f5c-973e-2552cd1aa0f5

📥 Commits

Reviewing files that changed from the base of the PR and between 474dbe6 and 606769e.

📒 Files selected for processing (1)
  • src/lib/vad/SileroVAD.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/onnxruntime-types-7812390940331716981

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link
Copy Markdown

Review Summary by Qodo

Replace any types with strict ONNX Runtime typings in SileroVAD

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Replace any types with strict InferenceSession and Tensor typings
• Update global ort declaration to use native type extraction
• Improve type safety and maintainability of VAD implementation
• Enable TypeScript compiler protection for ONNX Runtime boundaries
Diagram
flowchart LR
  A["SileroVAD.ts<br/>any types"] -->|"Replace with<br/>InferenceSession & Tensor"| B["SileroVAD.ts<br/>Strict types"]
  C["ort: any"] -->|"Update to<br/>typeof import"| D["ort: typeof<br/>onnxruntime-web"]
  B --> E["Better type safety<br/>& maintainability"]
  D --> E
Loading

Grey Divider

File Changes

1. src/lib/vad/SileroVAD.ts ✨ Enhancement +7/-6

Replace any types with strict ONNX Runtime typings

• Import InferenceSession and Tensor types from onnxruntime-web
• Replace global ort declaration from any to typeof import('onnxruntime-web')
• Replace session property type from any to InferenceSession
• Replace state tensor properties (stateH, stateC, srTensor) from any to Tensor
• Add type assertion for results.stateN as Tensor in session run method

src/lib/vad/SileroVAD.ts


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review bot commented Mar 22, 2026

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Missing onnxruntime-web dependency 🐞 Bug ⛯ Reliability
Description
SileroVAD.ts now requires TypeScript to resolve the onnxruntime-web module at compile time (via
import type and typeof import(...)), but onnxruntime-web is not a direct dependency in this
repo. In installs where parakeet.js's transitive dependencies are not hoisted to the root (common
in strict/isolated setups), tsc will fail with "Cannot find module 'onnxruntime-web'" even though
runtime still relies on a global ort.
Code

src/lib/vad/SileroVAD.ts[R2-5]

+import type { InferenceSession, Tensor } from 'onnxruntime-web';

// Use the globally-exposed ort from parakeet.js / onnxruntime-web
-declare const ort: any;
+declare const ort: typeof import('onnxruntime-web');
Evidence
The PR adds compile-time references to the onnxruntime-web module (type-only import and
typeof-import). Type-only constructs still require module resolution during compilation. However,
package.json does not list onnxruntime-web as a dependency; the project appears to expect it
only as a transitive dependency of parakeet.js (see vite.config.js reading onnxruntime-web
version from parakeet.js), which is not guaranteed to be resolvable from this package in all
dependency layouts.

src/lib/vad/SileroVAD.ts[1-6]
package.json[30-35]
vite.config.js[38-42]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`src/lib/vad/SileroVAD.ts` imports and type-queries `onnxruntime-web`, which requires the module to be resolvable at TypeScript compile time. The repo does not declare `onnxruntime-web` as a direct dependency, so builds can fail when the transitive dependency is not hoisted.

### Issue Context
Runtime still expects a globally-exposed `ort` (from `parakeet.js`), but compilation now depends on `onnxruntime-web` being resolvable.

### Fix Focus Areas
- package.json[1-40]
- src/lib/vad/SileroVAD.ts[1-6]

### Implementation notes
- Add `onnxruntime-web` to `dependencies` (preferred if the app expects it at runtime) or `devDependencies` (if truly only needed for types and guaranteed at runtime via global injection).
- Keep versions aligned with the expected runtime version (your README/vite config suggests `1.24.1`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Unchecked stateN tensor cast 🐞 Bug ✓ Correctness
Description
process() assigns results.stateN to this.stateH using an unchecked cast, so if the ONNX output
key is missing/renamed, stateH becomes undefined at runtime and later session.run() calls can
fail when feeding state. This undermines the goal of stricter typing by still allowing invalid
output shapes/keys to slip through without a runtime guard.
Code

src/lib/vad/SileroVAD.ts[141]

+        this.stateH = results.stateN as Tensor;
Evidence
results is accessed via string keys (results.output, results.stateN) and no guard checks that
stateN exists before overwriting stateH. Immediately afterward, stateH is used as the state
feed on the next call, so a missing output will propagate into a bad feed value and can crash
inference.

src/lib/vad/SileroVAD.ts[124-142]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`this.stateH = results.stateN as Tensor;` overwrites the persistent state without verifying that `results.stateN` exists and is a Tensor/OnnxValue of the expected type.

### Issue Context
The next `process()` call feeds `this.stateH` back into `session.run()`. If `stateN` is missing or not the expected type, the next inference can fail.

### Fix Focus Areas
- src/lib/vad/SileroVAD.ts[124-145]

### Implementation notes
- Add a runtime guard:
 - Check `&#x27;stateN&#x27; in results` and that it is truthy before assignment.
 - Optionally verify it looks like an ORT Tensor (e.g., has `data`/`dims` depending on ort API) before assigning.
- If missing, throw a clear error listing available output keys to aid debugging (e.g., `Object.keys(results)`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • Rather than asserting results.stateN as Tensor, consider giving results a more precise typed shape (e.g., a typed RunNamedOutput or custom interface) so the compiler tracks the stateN type without needing a cast.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Rather than asserting `results.stateN as Tensor`, consider giving `results` a more precise typed shape (e.g., a typed `RunNamedOutput` or custom interface) so the compiler tracks the `stateN` type without needing a cast.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the type safety and maintainability of the SileroVAD.ts file by replacing the use of any types with specific types from the onnxruntime-web library. This change ensures better code reliability and reduces the likelihood of runtime errors.

Highlights

  • Type Safety: Replaced any types with strict types (InferenceSession and Tensor) from onnxruntime-web for ONNX Runtime session and state variables.
  • Maintainability: Improved maintainability of SileroVAD.ts by leveraging actual typings, reducing the risk of runtime errors through TypeScript compilation checks.
  • Verification: Verified that pnpm test runs cleanly and successfully, and that no unrequested dependencies were added to package.json. Confirmed that ort typings are matched correctly by running the TypeScript compiler (tsc).
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively improves type safety in SileroVAD.ts by replacing any with strict types from onnxruntime-web, which is a great step for maintainability. I have two suggestions to further enhance the code quality: one regarding an unused class property and another to make a type cast safer with a runtime check.

private stateC: any | null = null;
private srTensor: any | null = null;
private stateH: Tensor | null = null;
private stateC: Tensor | null = null;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The class property stateC is declared and typed, but it appears to be unused throughout the class. To improve code clarity and reduce the memory footprint, it should be removed.


// Update persistent state
this.stateH = results.stateN;
this.stateH = results.stateN as Tensor;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using as Tensor performs an unsafe type cast. While it satisfies the compiler, it offers no runtime safety and could lead to errors if the model's output format changes. A more robust approach is to perform a runtime type check using instanceof to validate that results.stateN is indeed a Tensor before assignment.

Suggested change
this.stateH = results.stateN as Tensor;
if (!(results.stateN instanceof ortLib.Tensor)) {
throw new Error(`VAD model returned unexpected type for 'stateN'. Expected a Tensor.`);
}
this.stateH = results.stateN;

Comment on lines +2 to +5
import type { InferenceSession, Tensor } from 'onnxruntime-web';

// Use the globally-exposed ort from parakeet.js / onnxruntime-web
declare const ort: any;
declare const ort: typeof import('onnxruntime-web');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Missing onnxruntime-web dependency 🐞 Bug ⛯ Reliability

SileroVAD.ts now requires TypeScript to resolve the onnxruntime-web module at compile time (via
import type and typeof import(...)), but onnxruntime-web is not a direct dependency in this
repo. In installs where parakeet.js's transitive dependencies are not hoisted to the root (common
in strict/isolated setups), tsc will fail with "Cannot find module 'onnxruntime-web'" even though
runtime still relies on a global ort.
Agent Prompt
### Issue description
`src/lib/vad/SileroVAD.ts` imports and type-queries `onnxruntime-web`, which requires the module to be resolvable at TypeScript compile time. The repo does not declare `onnxruntime-web` as a direct dependency, so builds can fail when the transitive dependency is not hoisted.

### Issue Context
Runtime still expects a globally-exposed `ort` (from `parakeet.js`), but compilation now depends on `onnxruntime-web` being resolvable.

### Fix Focus Areas
- package.json[1-40]
- src/lib/vad/SileroVAD.ts[1-6]

### Implementation notes
- Add `onnxruntime-web` to `dependencies` (preferred if the app expects it at runtime) or `devDependencies` (if truly only needed for types and guaranteed at runtime via global injection).
- Keep versions aligned with the expected runtime version (your README/vite config suggests `1.24.1`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@ysdede ysdede changed the title 🧹 [Code Health] Define types for ONNX Runtime session and state [Code Health] Define types for ONNX Runtime session and state Mar 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant