Skip to content

Refactor data parameter in TranscriptionWorkerClient.ts to use explicit types instead of any#220

Open
ysdede wants to merge 1 commit intomasterfrom
jules-fix-transcription-worker-message-types-10979186477214833768
Open

Refactor data parameter in TranscriptionWorkerClient.ts to use explicit types instead of any#220
ysdede wants to merge 1 commit intomasterfrom
jules-fix-transcription-worker-message-types-10979186477214833768

Conversation

@ysdede
Copy link
Copy Markdown
Owner

@ysdede ysdede commented Mar 22, 2026

🎯 What: Typed the data parameter in handleMessage method of TranscriptionWorkerClient.ts to replace the unsafe any type with a discriminated union WorkerIncomingMessage.

💡 Why: This improves maintainability and code readability by providing a single source of truth for the structure of messages emitted by transcription.worker.ts, making the contract clearer and enabling better static analysis.

Verification: Verified that handleMessage continues to work exactly as before, as no logic was changed. Compiled the project and ran unit tests (which previously lacked type safety for these messages) successfully.

Result: Improved type safety and developer experience when interfacing with the transcription background worker without changing runtime behavior.


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

Summary by Sourcery

Enhancements:

  • Introduce a discriminated union type for incoming transcription worker messages and use it in the worker client message handler to replace the previous untyped parameter.

Replaced `any` with a new `WorkerIncomingMessage` discriminated union in `src/lib/transcription/TranscriptionWorkerClient.ts` to strictly type the incoming messages from the worker.
@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 28 minutes and 34 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: 78c2d74a-f882-4539-9658-421c2a40fbf4

📥 Commits

Reviewing files that changed from the base of the PR and between 474dbe6 and 03fdf8f.

📒 Files selected for processing (1)
  • src/lib/transcription/TranscriptionWorkerClient.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-fix-transcription-worker-message-types-10979186477214833768

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

Type worker incoming messages with discriminated union

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Replace unsafe any type with discriminated union WorkerIncomingMessage
• Define explicit message types for worker communication contract
• Improve type safety in handleMessage method without behavior changes
Diagram
flowchart LR
  A["handleMessage data: any"] -->|"Replace with typed union"| B["WorkerIncomingMessage"]
  B -->|"Covers message types"| C["MODEL_PROGRESS, MODEL_STATE, V3_CONFIRMED, V3_PENDING, ERROR"]
  C -->|"Enables static analysis"| D["Better type safety"]
Loading

Grey Divider

File Changes

1. src/lib/transcription/TranscriptionWorkerClient.ts ✨ Enhancement +11/-1

Type worker messages with discriminated union

• Added WorkerIncomingMessage discriminated union type covering all valid worker message types
• Typed handleMessage method parameter from any to WorkerIncomingMessage
• Includes specific message types: MODEL_PROGRESS, MODEL_STATE, V3_CONFIRMED, V3_PENDING, ERROR
• Maintains backward compatibility with fallback for unknown message types

src/lib/transcription/TranscriptionWorkerClient.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 (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Missing TRANSCRIPTION_RESULT variant 🐞 Bug ✓ Correctness
Description
WorkerIncomingMessage cannot represent { type: 'TRANSCRIPTION_RESULT', payload: ... } messages
emitted by transcription.worker.ts because the union’s fallback branch requires id: number, but
that worker message has no id.
Code

src/lib/transcription/TranscriptionWorkerClient.ts[R104-110]

+export type WorkerIncomingMessage =
+    | { type: 'MODEL_PROGRESS'; payload: ModelProgress; id?: number }
+    | { type: 'MODEL_STATE'; payload: ModelState; id?: number }
+    | { type: 'V3_CONFIRMED'; payload: { text: string; words: any[] }; id?: number }
+    | { type: 'V3_PENDING'; payload: { text: string; words: any[] }; id?: number }
+    | { type: 'ERROR'; payload: string; id?: number }
+    | { type: string; payload?: any; id: number };
Evidence
transcription.worker.ts emits postMessage({ type: 'TRANSCRIPTION_RESULT', payload: result })
without an id (fire-and-forget callback). In the PR, the WorkerIncomingMessage union only allows
no-id messages for specific literal types (MODEL_PROGRESS, MODEL_STATE, V3_CONFIRMED,
V3_PENDING, ERROR), while its catch-all branch requires id: number, making
TRANSCRIPTION_RESULT unrepresentable and the “Valid incoming messages” contract false.

src/lib/transcription/TranscriptionWorkerClient.ts[103-111]
src/lib/transcription/transcription.worker.ts[37-45]

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

### Issue description
`WorkerIncomingMessage` is exported as the set of valid incoming worker messages, but it currently cannot represent the `{ type: 'TRANSCRIPTION_RESULT', payload: ... }` message that the worker emits without an `id`. This makes the type contract incorrect and undermines the goal of having a single source of truth.

### Issue Context
The worker emits fire-and-forget callback messages (no `id`) and request/response messages (with `id`). The union’s catch-all requires `id: number`, so any additional fire-and-forget message types must be explicitly modeled.

### Fix Focus Areas
- src/lib/transcription/TranscriptionWorkerClient.ts[103-111]
- src/lib/transcription/transcription.worker.ts[37-45]

### What to change
- Add an explicit union member for `TRANSCRIPTION_RESULT` matching the worker’s shape (no `id`).
 - Example:
   - `| { type: 'TRANSCRIPTION_RESULT'; payload: /* correct payload type */; id?: number }`
- (Optional but recommended) Consider tightening the fallback branch so it doesn’t unintentionally constrain future non-id messages (e.g., split fallback into `id?: number` or remove it in favor of explicit variants).

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

  • The WorkerIncomingMessage union ends with a catch‑all { type: string; payload?: any; id: number } branch, which largely defeats the purpose of the explicit union; consider tightening this to known message types (e.g., via keyof WorkerMessageMap) or a more constrained fallback shape.
  • For the V3_CONFIRMED and V3_PENDING cases, replacing words: any[] with a concrete Word-like type (or at least unknown[] with a narrow cast at usage sites) would further improve type safety and better document the expected payload structure.
  • The id property is optional on most members of WorkerIncomingMessage but required on the generic fallback case; if id is genuinely optional for some messages, consider reflecting that consistently or splitting messages into Request/Event variants to avoid confusion.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `WorkerIncomingMessage` union ends with a catch‑all `{ type: string; payload?: any; id: number }` branch, which largely defeats the purpose of the explicit union; consider tightening this to known message types (e.g., via `keyof WorkerMessageMap`) or a more constrained fallback shape.
- For the `V3_CONFIRMED` and `V3_PENDING` cases, replacing `words: any[]` with a concrete `Word`-like type (or at least `unknown[]` with a narrow cast at usage sites) would further improve type safety and better document the expected payload structure.
- The `id` property is optional on most members of `WorkerIncomingMessage` but required on the generic fallback case; if `id` is genuinely optional for some messages, consider reflecting that consistently or splitting messages into `Request`/`Event` variants to avoid confusion.

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 refactors the TranscriptionWorkerClient.ts file to improve type safety and developer experience. It replaces the any type for the data parameter in the handleMessage method with a more specific discriminated union type, WorkerIncomingMessage. This change enhances code maintainability and readability without altering the existing runtime behavior.

Highlights

  • Type Safety: The data parameter in the handleMessage method of TranscriptionWorkerClient.ts has been updated to use a discriminated union type WorkerIncomingMessage instead of any.
  • Improved Maintainability: This change enhances code readability and maintainability by providing a single source of truth for the structure of messages emitted by transcription.worker.ts.
  • No Runtime Changes: The existing functionality of handleMessage remains unchanged, ensuring no impact on runtime behavior.
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 is a great step towards improving type safety in the communication with the transcription worker. By replacing any with the WorkerIncomingMessage discriminated union, the code becomes more maintainable and readable. I've provided a couple of suggestions to further enhance type safety by completely eliminating any from the new type definition, which would make the message contract even more robust.

| { type: 'V3_CONFIRMED'; payload: { text: string; words: any[] }; id?: number }
| { type: 'V3_PENDING'; payload: { text: string; words: any[] }; id?: number }
| { type: 'ERROR'; payload: string; id?: number }
| { type: string; payload?: any; id: number };
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

This generic catch-all with payload?: any significantly weakens the discriminated union and undermines the goal of this refactoring. You can create a more specific type for the payload of response messages by creating a union of all possible response types from WorkerMessageMap. This would significantly improve type safety and make the contract with the worker much safer.

Suggested change
| { type: string; payload?: any; id: number };
| { type: string; payload?: void | TranscriptionResult | { text: string } | TokenStreamResult | V4ProcessResult | null; id: number };

Comment on lines +107 to +108
| { type: 'V3_CONFIRMED'; payload: { text: string; words: any[] }; id?: number }
| { type: 'V3_PENDING'; payload: { text: string; words: any[] }; id?: number }
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 any[] for the words property is a missed opportunity to improve type safety, which is the main goal of this pull request. Consider using a more specific type for the elements in the words array. The existing TranscriptionWord type (which would need to be added to the imports from ./types) seems like a good candidate. If its structure doesn't match, a new interface should be defined for these V3 tokens.

Suggested change
| { type: 'V3_CONFIRMED'; payload: { text: string; words: any[] }; id?: number }
| { type: 'V3_PENDING'; payload: { text: string; words: any[] }; id?: number }
| { type: 'V3_CONFIRMED'; payload: { text: string; words: TranscriptionWord[] }; id?: number }
| { type: 'V3_PENDING'; payload: { text: string; words: TranscriptionWord[] }; id?: number }

Comment on lines +104 to +110
export type WorkerIncomingMessage =
| { type: 'MODEL_PROGRESS'; payload: ModelProgress; id?: number }
| { type: 'MODEL_STATE'; payload: ModelState; id?: number }
| { type: 'V3_CONFIRMED'; payload: { text: string; words: any[] }; id?: number }
| { type: 'V3_PENDING'; payload: { text: string; words: any[] }; id?: number }
| { type: 'ERROR'; payload: string; id?: number }
| { type: string; payload?: any; id: number };
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 transcription_result variant 🐞 Bug ✓ Correctness

WorkerIncomingMessage cannot represent { type: 'TRANSCRIPTION_RESULT', payload: ... } messages
emitted by transcription.worker.ts because the union’s fallback branch requires id: number, but
that worker message has no id.
Agent Prompt
### Issue description
`WorkerIncomingMessage` is exported as the set of valid incoming worker messages, but it currently cannot represent the `{ type: 'TRANSCRIPTION_RESULT', payload: ... }` message that the worker emits without an `id`. This makes the type contract incorrect and undermines the goal of having a single source of truth.

### Issue Context
The worker emits fire-and-forget callback messages (no `id`) and request/response messages (with `id`). The union’s catch-all requires `id: number`, so any additional fire-and-forget message types must be explicitly modeled.

### Fix Focus Areas
- src/lib/transcription/TranscriptionWorkerClient.ts[103-111]
- src/lib/transcription/transcription.worker.ts[37-45]

### What to change
- Add an explicit union member for `TRANSCRIPTION_RESULT` matching the worker’s shape (no `id`).
  - Example:
    - `| { type: 'TRANSCRIPTION_RESULT'; payload: /* correct payload type */; id?: number }`
- (Optional but recommended) Consider tightening the fallback branch so it doesn’t unintentionally constrain future non-id messages (e.g., split fallback into `id?: number` or remove it in favor of explicit variants).

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

@ysdede ysdede changed the title 🧹 Refactor data parameter in TranscriptionWorkerClient.ts to use explicit types instead of any Refactor data parameter in TranscriptionWorkerClient.ts to use explicit types instead of any 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