Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/sound-effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ The app and Storybook share the same control implementations. Motion supports re
| Disable sounds | Silent; cancels active and pending cues |
| Tabs, hover, accordions, tooltips, continuous sliders, telemetry | Silent |

Both libraries use 35% global volume. A grouped switch produces one cue, even when it changes several sensors. Hydration and programmatic updates remain silent. Sound preferences persist across restarts; asynchronous actions cannot replay a cue cancelled by muting.
Both libraries use 70% global volume. A grouped switch produces one cue, even when it changes several sensors. Hydration and programmatic updates remain silent. Sound preferences persist across restarts; asynchronous actions cannot replay a cue cancelled by muting.

## Audio implementation

Expand Down
116 changes: 116 additions & 0 deletions tauri-app/scripts/test-feedback-email.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';

const browser = await chromium.launch();
const sent = [];
const failures = [];
let rejectNext = false;
try {
const page = await browser.newPage({ viewport: { width: 651, height: 900 } });
page.on('pageerror', error => failures.push(error.message));
await page.exposeFunction('__feedbackSend', async input => {
sent.push(input);
if (rejectNext) { rejectNext = false; throw new Error('Temporary submission failure'); }
if (process.env.FEEDBACK_PORTAL_URL) {
const fields = { name: input.name, message: input.message, app_version: '2.2.18', os: 'windows' };
if (input.email) fields.email = input.email;
if (input.includeDiagnostics) {
fields.diagnostics_summary = 'Local email integration check';
fields.diagnostics = { name: 'cleanmeter-diagnostics.txt', mimeType: 'text/plain', buffer: Buffer.from('Local integration diagnostics\n') };
}
const response = await page.request.post(`${process.env.FEEDBACK_PORTAL_URL}/api/feedback`, {
headers: { 'x-feedback-key': process.env.FEEDBACK_TEST_KEY ?? 'local-email-test-key' },
multipart: fields,
});
assert.equal(response.status(), 201, await response.text());
}
});
await page.route('**/src/lib/tauri.ts*', async route => {
const response = await route.fetch();
const source = await response.text();
const marker = 'export const submitFeedback = (input) => {';
assert.ok(source.includes(marker), 'Intercept only the desktop transport boundary');
await route.fulfill({ response, body: source.replace(marker, `${marker} return window.__feedbackSend(input);`) });
});
Comment on lines +29 to +35

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,125p' tauri-app/scripts/test-feedback-email.mjs
sed -n '245,265p' tauri-app/src/lib/tauri.ts

Repository: SupaStellar/Cleanmeter

Length of output: 7158


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- package/config references ---'
rg -n -F --glob 'tauri-app/package.json' -e '"playwright"' -e '"vite"' -e '"scripts"' -e 'test-feedback-email' tauri-app/package.json || test "$?" -eq 1
rg -n -F --glob 'tauri-app/*' -e 'vite.config' -e 'server:' -e 'esbuild' -e 'minify' -e 'test-feedback-email' tauri-app || test "$?" -eq 1
printf '%s\n' '--- exact relevant source with line numbers ---'
nl -ba tauri-app/scripts/test-feedback-email.mjs | sed -n '20,42p'
nl -ba tauri-app/src/lib/tauri.ts | sed -n '248,265p'

Repository: SupaStellar/Cleanmeter

Length of output: 10802


🌐 Web query:

official Playwright documentation page.route handler throws exception request behavior

💡 Result:

<source_evidence>
<source kind="search">
<title>BrowserContext | Playwright</title>
<location>https://playwright.dev/docs/api/class-browsercontext</location>
<excerpt>citeturn1search4 [wordlim: 200] Crawled: last week; Routing provides the capability to modify network requests that are made by any page in the browser context. ...   * `handler` function(Route, Request):Promise&lt;Object&gt; | Object# ...       * `&#39;ignoreErrors&#39;` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught ... Emitted when exception is unhandled in any of the pages in this context.

Returns

  * Promise&lt;void&gt;#

* * *

### route​

Added before v1.9 browserContext.route

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it&#39;s continued, fulfilled or aborted.

note

browserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting serviceWorkers to `&#39;block&#39;`.

Usage

An example of a naive handler that aborts all image requests:
    
    `
    
    const context = await browser.newContext();
    
    await context.route(&#39;**/*.{png,jpg,jpeg}&#39;, route =&gt; route.abort());
    
    const page = await context.newPage();
    
    await page.goto(&#39;https://example.com&#39;);
    
    await browser.close();
    
    `

or the same snippet using a regex pattern instead:
</excerpt>
</source>
<source kind="search">
<title>playwright/docs/src/api/class-route.md at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/docs/src/api/class-route.md</location>
<excerpt>citeturn0search0 [wordlim: 200] Crawled: 2 days ago; Use [`method: Route.fallback`] If you want next matching handler in the chain to be invoked. ... An error will be thrown if the number is exceeded. ... Fulfills route&#39;s request with given response.

# class: Route

  * since: v1.8

Whenever a network route is set up with [`method: Page.route`] or [`method: BrowserContext.route`], the `Route` object allows to handle the route.

Learn more about networking.

## async method: Route.abort

  * since: v1.8

Aborts the route&#39;s request.

### param: Route.abort.errorCode

  * since: v1.8

  * `errorCode` ?&lt;[string]&gt;

Optional error code. Defaults to `failed`, could be one of the following:

  * `&#39;aborted&#39;` - An operation was aborted (due to user action)
  * `&#39;accessdenied&#39;` - Permission to access a resource, other than the network, was denied
  * `&#39;addressunreachable&#39;` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
  * `&#39;blockedbyclient&#39;` - The client chose to block the request.
  * `&#39;blockedbyresponse&#39;` - The request failed because the response was delivered along with requirements which are not met (&#39;X-Frame-Options&#39; and &#39;Content-Security-Policy&#39; ancestor checks, for instance).
  * `&#39;connectionaborted&#39;` - A connection timed out as a result of not receiving an ACK for data sent.
        headers.Remove(&quot;origin&quot;);
        await route.ContinueAsync(new() { Headers = headers });
    });

Details

The [`option: headers`] option applies to both the routed request and any redirects it initiates. However, [`option: url`], [`option: method`], and [`option: postData`] only apply to the original request and are not carried over to redirected requests.

[`method: Route.continue`] will immediately send the request to the network, other matching handlers won&#39;t be invoked. Use [`method: Route.fallback`] If you want next matching handler in the chain to be invoked.

:::warning Some request headers are forbidden and cannot be overridden (for example, `Cookie`, `Host`, `Content-Length` and others, see this MDN page for full list). If an override is provided for a forbidden header, it will be ignored and the original request header will be used.

To set custom cookies, use [`method: BrowserContext.addCookies`]. :::

### option: Route.continue.url

  * since: v1.8

  * `url` &lt;[string]&gt;

If set changes the request URL. New URL must have same protocol as original one.

### option: Route.continue.method

  * since: v1.8

  * `method` &lt;[string]&gt;

If set changes the request method (e.g. GET or POST).

### option: Route.continue.postData

  * since: v1.8
  * langs: js, python

  * `postData` &lt;[string]|[Buffer]|[Serializable]&gt;

If set changes the post data of request.

### option: Route.continue.postData

  * since: v1.8
  * langs: java

  * `postData` &lt;[string]|[Buffer]&gt;

If set changes the post data of request.

### option: Route.continue.postData

  * since: v1.8
  * langs: csharp

  * `postData` &lt;[Buffer]&gt;

If set changes the post data of request.

### option: Route.continue.headers

  * since: v1.8

  * `headers` &lt;[Object]&lt;[string], [string]&gt;&gt;

If set changes the request HTTP headers. Header values will be converted to a string.

## method: Route.request

  * since: v1.8

  * returns: &lt;[Request]&gt;

A request to be routed.</excerpt>
</source>
<source kind="search">
<title>Route | Playwright</title>
<location>https://playwright.dev/docs/api/class-route</location>
<excerpt>citeturn0search1 [wordlim: 200] Crawled: last week; One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request. ... If the signal is aborted, the operation will be aborted and throw an error. ... APIResponse to fulfill route&#39;s request with.

# Route

Whenever a network route is set up with page.route() or browserContext.route(), the `Route` object allows to handle the route.

Learn more about networking.

## Methods​

### abort​

Added before v1.9 route.abort

Aborts the route&#39;s request.

Usage
    
    `
    
    await route.abort();
    
    await route.abort(errorCode);
    
    `

Arguments

  * `errorCode` string (optional)#

Optional error code. Defaults to `failed`, could be one of the following:

    * `&#39;aborted&#39;` - An operation was aborted (due to user action)
    * `&#39;accessdenied&#39;` - Permission to access a resource, other than the network, was denied
    * `&#39;addressunreachable&#39;` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
    * `&#39;blockedbyclient&#39;` - The client chose to block the request.
    * `&#39;blockedbyresponse&#39;` - The request failed because the response was delivered along with requirements which are not met (&#39;X-Frame-Options&#39; and &#39;Content-Security-Policy&#39; ancestor checks, for instance).
Defaults to `20`. Pass `0` to not follow redirects.

    * `maxRetries` number (optional) Added in: v1.46#

Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.

    * `method` string (optional)#

If set changes the request method (e.g. GET or POST).

    * `postData` string | Buffer | Serializable (optional)#

Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set.

    * `signal` AbortSignal (optional) Added in: v1.62#
</excerpt>
</source>
<source kind="search">
<title>playwright/docs/src/api/class-page.md at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md?plain=1</location>
<excerpt>citeturn0search2 [wordlim: 200] Crawled: last week; using var playwright = await Playwright.CreateAsync(); ... page.on(&#39;pageerror&#39;, exception =&gt; { ... await page.goto(&#39;data:text/html,&lt;script&gt;throw new Error(&quot;Test&quot;)&lt;/script&gt;&#39;); ... If you would like to route/listen to this network request, use [`method: BrowserContext.route`] and [`event: BrowserContext.request`] respectively instead of similar methods on the [Page]. ... Emitted when a request finishes successfully after downloading the response body.

with page.expect_event(&quot;popup&quot;) as page_info:

page.get_by_text(&quot;open the popup&quot;).click()

popup = page_info.value

print(popup.evaluate(&quot;location.href&quot;))

```

```csharp

var popup = await page.RunAndWaitForPopupAsync(async () =&gt;

{

await page.GetByText(&quot;open the popup&quot;).ClickAsync();

});

Console.WriteLine(await popup.EvaluateAsync&lt;string&gt;(&quot;location.href&quot;));

```

:::note

Use [`method: Page.waitForLoadState`] to wait until the page gets to a particular state (you should not need it in most

cases).

:::

## event: Page.request

* since: v1.8

- argument: &lt;[Request]&gt;

Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see

[`method: Page.route`] or [`method: BrowserContext.route`].

## event: Page.requestFailed

* since: v1.9

- argument: &lt;[Request]&gt;

Emitted when a request fails, for example by timing out.

```js

page.on(&#39;requestfailed&#39;, request =&gt; {

console.log(request.url() + &#39; &#39; + request.failure().errorText);

});

```

```java

page.onRequestFailed(request -&gt; {
</excerpt>
</source>
<source kind="search">
<title>playwright/packages/playwright-core/src/client/browserContext.ts at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/browserContext.ts</location>
<excerpt>citeturn0search3 [wordlim: 200] Crawled: 3 weeks ago; routeHandler.matches(route.request().url())) ... throw new Error(&#39;Route from har is not supported in thin clients&#39;);

const { responseEndTiming } = params;

const request = network.Request.from(params.request);

const response = network.Response.fromNullable(params.response);

const page = Page.fromNullable(params.page);

request._setResponseEndTiming(responseEndTiming);

this.emit(Events.BrowserContext.RequestFinished, request);

if (page)

page.emit(Events.Page.RequestFinished, request);

if (response)

response._finishedPromise.resolve(null);

}

async _onRoute(route: network.Route) {

route._context = this;

const page = route.request()._safePage();

const routeHandlers = this._routes.slice();

for (const routeHandler of routeHandlers) {

// If the page or the context was closed we stall all requests right away.

if (page?._closeWasCalled || this.isClosed())

return;

if (!routeHandler.matches(route.request().url()))

continue;

const index = this._routes.indexOf(routeHandler);

if (index === -1)

continue;

if (routeHandler.willExpire())

this._routes.splice(index, 1);

const handled = await routeHandler.handle(route);

if (!this._routes.length)

this._updateInterceptionPatterns({ internal: true }).catch(() =&gt; {});

if (handled)

return;

}

// If the page is closed or unrouteAll() was called without waiting and interception disabled,

// the method will throw an error - silence it.

this._bindings.set(name, binding);

return DisposableObject.from(result.disposable);

}

async route(url: URLMatch, handler: network.RouteHandlerCallback, options: { times?: number } = {}): Promise&lt;DisposableStub&gt; {

this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times));

await this._updateInterceptionPatterns({ title: &#39;Route requests&#39; });

return new DisposableStub(() =&gt; this.unroute(url, handler));

}

async routeWebSocket(url: URLMatch, handler: network.WebSocketRouteHandlerCallback): Promise&lt;void&gt; {

this._webSocketRoutes.unshift(new network.WebSocketRouteHandler(this._options.baseURL, url, handler));

await this._updateWebSocketInterceptionPatterns({ title: &#39;Route WebSockets&#39; });

}

async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: &#39;abort&#39; | &#39;fallback&#39;, update?: boolean, updateContent?: &#39;attach&#39; | &#39;embed&#39;, updateMode?: &#39;minimal&#39; | &#39;full&#39; } = {}): Promise&lt;void&gt; {

const localUtils = this._connection.localUtils();

if (!localUtils)

throw new Error(&#39;Route from har is not supported in thin clients&#39;);
</excerpt>
</source>
<omitted_sources count="22">Additional source records were omitted from this bounded result.</omitted_sources>
</source_evidence>

Citations:

- 1: https://playwright.dev/docs/api/class-browsercontext?utm_source=openai

🏁 Script executed:

set -o pipefail
printf '%s\n' '--- package/config ---'
sed -n '1,180p' tauri-app/package.json
for f in tauri-app/vite.config.* tauri-app/*vite*.config.*; do
  if test -f "$f"; then printf '%s\n' "--- $f"; nl -ba "$f"; fi
done
printf '%s\n' '--- relevant lines ---'
nl -ba tauri-app/scripts/test-feedback-email.mjs | sed -n '27,38p'
nl -ba tauri-app/src/lib/tauri.ts | sed -n '252,264p'

Repository: SupaStellar/Cleanmeter

Length of output: 10869


🌐 Web query:

site:playwright.dev/docs/api/class-page page.route handler throws exception abort request

💡 Result:

<source_evidence>
<source kind="search">
<title>Page | Playwright</title>
<location>https://playwright.dev/docs/api/class-page</location>
<excerpt>citeturn0search0 [wordlim: 200] Crawled: last week; The Page class emits various events (described below) which can be handled using any of Node&#39;s native `EventEmitter` methods, such as `on`, `once` or `removeListener`. ... When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. ...       * `&#39;commit&#39;` - consider operation to be finished when network response is received and the document started loading. ... The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 &quot;Not Found&quot; and 500 &quot;Internal Server Error&quot;. ...     await page.route(&#39;/api/**&#39;, async route =&gt; { ...       * If set to &#39;abort&#39; any request not found in the HAR file will be aborted. ...     page.on(&#39;pageerror&#39;, exception =&gt; {

When set to `&quot;ai&quot;`, returns a snapshot optimized for AI consumption: including element references like `[ref=e2]` and snapshots of `&lt;iframe&gt;`s. Defaults to `&quot;default&quot;`.

    * `signal` AbortSignal (optional) Added in: v1.62#

Allows to cancel the operation using an `AbortSignal`. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass `timeout: 0` to disable the timeout entirely.

    * `timeout` number (optional)#

Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout` option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

Returns

  * Promise&lt;Serializable&gt;#
If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass `timeout: 0` to disable the timeout entirely.

    * `timeout` number (optional)#

Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `navigationTimeout` option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

    * `waitUntil` &quot;load&quot; | &quot;domcontentloaded&quot; | &quot;networkidle&quot; | &quot;commit&quot; (optional)#

When to consider operation succeeded, defaults to `load`. Events can be either:

      * `&#39;domcontentloaded&#39;` - consider operation to be finished when the `DOMContentLoaded` event is fired.

  * `options` Object (optional)

    * `referer` string (optional)#

Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders().

    * `signal` AbortSignal (optional) Added in: v1.62#

Allows to cancel the operation using an `AbortSignal`. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass `timeout: 0` to disable the timeout entirely.

    * `timeout` number (optional)#

Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `navigationTimeout` option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

    * `waitUntil` &quot;load&quot; | &quot;domcontentloaded&quot; | &quot;networkidle&quot; | &quot;commit&quot; (optional)#

When to consider operation succeeded, defaults to `load`. Events can be either:

      * `&#39;domcontentloaded&#39;` - consider operation to be finished when the `DOMContentLoaded` eve…[truncated]</excerpt>
</source>
<source kind="search">
<title>Route | Playwright</title>
<location>https://playwright.dev/docs/api/class-route</location>
<excerpt>citeturn0search1 [wordlim: 200] Crawled: last week;     await route.abort(errorCode); ... One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request. ...     await page.route(&#39;https://dog.ceo/api/breeds/list/all&#39;, async route =&gt; { ... If the signal is aborted, the operation will be aborted and throw an error.

# Route

Whenever a network route is set up with page.route() or browserContext.route(), the `Route` object allows to handle the route.

Learn more about networking.

## Methods​

### abort​

Added before v1.9 route.abort

Aborts the route&#39;s request.

Usage
    
    `
    
    await route.abort();
    
    await route.abort(errorCode);
    
    `

Arguments

  * `errorCode` string (optional)#

Optional error code. Defaults to `failed`, could be one of the following:

    * `&#39;aborted&#39;` - An operation was aborted (due to user action)
    * `&#39;accessdenied&#39;` - Permission to access a resource, other than the network, was denied
    * `&#39;addressunreachable&#39;` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
    * `&#39;blockedbyclient&#39;` - The client chose to block the request.
    * `&#39;blockedbyresponse&#39;` - The request failed because the response was delivered along with requirements which are not met (&#39;X-Frame-Options&#39; and &#39;Content-Security-Policy&#39; ancestor checks, for instance).

Allows to cancel the operation using an `AbortSignal`. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass `timeout: 0` to disable the timeout entirely.

    * `timeout` number (optional) Added in: v1.33#

Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.

    * `url` string (optional)#

If set changes the request URL. New URL must have same protocol as original one.

Returns

  * Promise&lt;APIResponse&gt;#

Details

Note that headers option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply headers to the original request, but not to redirects, look into route.continue() instead.

</excerpt>
</source>
<source kind="search">
<title>Playwright Test | Playwright</title>
<location>https://playwright.dev/docs/api/class-test</location>
<excerpt>citeturn0search2 [wordlim: 200] Crawled: last week; This is useful from inside a fixture or a route handler when you have detected an unrecoverable misuse and want to fail the test right away. ...     import { test, expect } from &#39;@playwright/test&#39;; ...       await page.route(&#39;**/publish&#39;, route =&gt; { ...         return route.abort();
</excerpt>
</source>
<source kind="search">
<title>BrowserContext | Playwright</title>
<location>https://playwright.dev/docs/api/class-browsercontext</location>
<excerpt>citeturn0search3 [wordlim: 200] Crawled: last week;     await context.route(&#39;**/*.{png,jpg,jpeg}&#39;, route =&gt; route.abort()); ...     await context.route(&#39;/api/**&#39;, async route =&gt; { ... Page routes (set up with page.route()) take precedence over browser context routes when request matches both handlers. ...   * `handler` function(Route, Request):Promise&lt;Object&gt; | Object#
</excerpt>
</source>
<source kind="search">
<title>Page | Playwright</title>
<location>https://playwright.dev/docs/next/api/class-page</location>
<excerpt>citeturn0search4 [wordlim: 200] Crawled: last month; page.route() will not intercept the first request of a popup page. ... An example of a naive handler that aborts all image requests: ...     await page.route(&#39;**/*.{png,jpg,jpeg}&#39;, route =&gt; route.abort());
</excerpt>
</source>
<omitted_sources count="7">Additional source records were omitted from this bounded result.</omitted_sources>
</source_evidence>

Citations:

- 1: https://playwright.dev/docs/api/class-page?utm_source=openai

🌐 Web query:

Playwright RouteHandler.handle _ignoreException thrown route handler implementation page.route exception abort request

💡 Result:

<source_evidence>
<source kind="find_in_page">
<title>playwright/packages/playwright-core/src/client/network.ts at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/network.ts</location>
<excerpt>citeturn5view2 [wordlim: 200] Crawled: today; Content type: text/html; Source: find({&quot;ref_id&quot;:&quot;turn4view0&quot;,&quot;pattern&quot;:&quot;async abort&quot;}); Total lines: 3755
L2649: this._fallbackOverrides.postDataBuffer = Buffer.from(JSON.stringify(overrides.postData), &#39;utf-8&#39;);
L2650: 
L2651: }
L2652: 
L2653: _fallbackOverridesForContinue() {
L2654: 
L2655: return this._fallbackOverrides;
L2670: _context!: BrowserContext;
L2671: 
L2672: _didThrow: boolean = false;
L2673: 
L2674: static from(route: channels.RouteChannel): Route {
L2675: 
L2676: return (route as any)._object;
L2677: 
L2678: }
L2679: 
L2680: constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.RouteInitializer) {
L2681: 
L2682: super(parent, type, guid, initializer);
L2683: 
L2684: }
L2685: 
L2686: request(): Request {
L2687: 
L2688: return Request.from(this._initializer.request);
L2689: 
L2690: }
L2691: 
L2692: private async _raceWithTargetClose(promise: Promise&lt;any&gt;): Promise&lt;void&gt; {
L2693: // When page closes or crashes, we catch any potential rejects from this Route.
L2694: 
L2695: // Note that page could be missing when routing popup&#39;s initial request that
L2696: 
L2697: // does not have a Page initialized just yet.
L2698: 
L2699: return await this.request()._targetClosedScope().safeRace(promise);
L2700: 
L2701: }
L2702: 
L2703: async _startHandling(): Promise&lt;boolean&gt; {
L2704: 
L2705: this._handlingPromise = new ManualPromise();
L2706: 
L2707: return await this._handlingPromise;
L2708: 
L2709: }
L2710: 
L2711: async fallback(options: FallbackOverrides = {}) {
L2712: 
L2713: this._checkNotHandled();
L2714: this.request()._applyFallbackOverrides(options);
L2715: 
L2716: this._reportHandled(false);
L2717: 
L2718: }
L2719: 
L2720: async abort(errorCode?: string) {
L2721: 
L2722: await this._handleRoute(async () =&gt; {
L2723: 
L2724: await this._raceWithTargetClose(this._channel.abort({ errorCode }, kNoTimeout));
L2725: 
L2726: });
L2727: 
L2728: }
L2729: 
L2730: async _redirectNavigationRequest(url: string) {
L2731: 
L2732: await this._handleRoute(async () =&gt; {
L2733: 
L2734: await this._raceWithTargetClose(this._channel.redirectNavigationRequest({ url }, kNoTimeout));
L2735: 
L2736: });
L2737: 
L2738: }
L2739: 
L2740: @apiCall()
L2741: async fetch(options: FallbackOverrides &amp; { maxRedirects?: number, maxRetries?: number, timeout?: number, signal?: AbortSignal } = {}): Promise&lt;APIResponse&gt; {
L2742: 
L2743: return await this._context.request._innerFetch({ request: this.request(), data: options.postData, ...options });
L2744: 
L2745: }
L2746: 
L2747: async fulfill(options: { response?: api.APIResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, json?: any, path?: string } = {}) {
L2748: 
L2749: await this._handleRoute(async () =&gt; {
L2750: await this._innerFulfill(options);
L2751: 
L2752: });
L2753: 
L2754: }
L2755: 
L2756: private async _handleRoute(callback: () =&gt; Promise&lt;void&gt;) {
L2757: 
L2758: this._checkNotHandled();
L2759: 
L2760: try {
L2761: 
L2762: await callback();
L2763: 
L2764: this._reportHandled(true);
L2765: 
L2766: } catch (e) {
L2767: 
L2768: this._didThrow = true;
L2769: 
L2770: throw e;
L2771: 
L2772: }
L2773: 
L2774: }
L2775: 
L2776: private async _innerFulfill(options: { response?: api.APIResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, json?: any, path?: string } = {}): Promise&lt;void&gt; {
L2777: 
L2778: let fetchResponseUid;
L2779: let { status: statusOption, headers: headersOption, body } = options;
L2780: 
L2781: if (options.json !== undefined) {
L2782: 
L2783: assert(options.body === undefined, &#39;Can specify either body or json parameters&#39;);
L2784: 
L2785: body = JSON.stringify(options.json);
L2786: 
L2787: }
L2788: 
L2789: if (options.response instanceof APIResponse) {
L2790: 
L2791: statusOption ??= options.response.status();
L2…[truncated]</excerpt>
</source>
<source kind="open_page">
<title></title>
<location>https://raw.githubusercontent.com/microsoft/playwright-python/main/playwright/_impl/_helper.py</location>
<excerpt>citeturn2view1 [wordlim: 200] Crawled: today; Content type: text/plain; Source: open({&quot;ref_id&quot;:&quot;https://raw.githubusercontent.com/microsoft/playwright-python/main/playwright/_impl/_helper.py&quot;,&quot;lineno&quot;:null}); Total lines: 40
L0: # Copyright (c) Microsoft Corporation.
L1: #
L2: # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
L3: # you may not use this file except in compliance with the License.
L4: # You may obtain a copy of the License at
L5: #
L6: # http://www.apache.org/licenses/LICENSE-2.0
L7: #
L8: # Unless required by applicable law or agreed to in writing, software
L9: # distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
L10: # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
L11: # See the License for the specific language governing permissions and
L12: # limitations under the License.
L13: &quot;&quot;&quot;Python only: helpers of the generated API (playwright/{async,sync}_api/_generated.py).&quot;&quot;&quot;
L14: 
L15: import datetime
L16: from typing import Optional, Union, overload
L17: 
L18: 
L19: @overload
L20: def to_milliseconds(value: Union[float, datetime.timedelta]) -&gt; float: ...
L21: 
L22: 
L23: @overload
L24: def to_milliseconds(value: None) -&gt; None: ...
L25: 
L26: 
L27: @overload
L28: def to_milliseconds(
L29:     value: Union[float, datetime.timedelta, None],
L30: ) -&gt; Optional[float]: ...
L31: 
L32: def to_milliseconds(
L33:     value: Union[float, datetime.timedelta, None],
L34: ) -&gt; Optional[float]:
L35:     if value is None:
L36:         return None
L37:     if isinstance(value, datetime.timedelta):
L38:         return value / datetime.timedelta(milliseconds=1)
L39:     return value
</excerpt>
</source>
<source kind="open_page">
<title>playwright/packages/playwright-core/src/client/network.ts at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/network.ts</location>
<excerpt>citeturn4view0 [wordlim: 200] Crawled: today; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/network.ts&quot;,&quot;lineno&quot;:null}); Total lines: 3755
L0: 【0†Skip to content】
L1: ## Navigation Menu
L2: 
L3: 【1†Sign in】
L4: 
L5: Appearance settings
L6: 
L7:   * Platform
L8: 
L9:     * AI CODE CREATION
L10:       * 【2†GitHub CopilotWrite better code with AI】
L11:       * 【3†GitHub Copilot appDirect agents from issue to merge】
L12:       * 【4†MCP RegistryIntegrate external tools】
L13: 
L14:     * DEVELOPER WORKFLOWS
L15:       * 【5†ActionsAutomate any workflow】
L16:       * 【6†CodespacesInstant dev environments】
L17:       * 【7†IssuesPlan and track work】
L18:       * 【8†Code ReviewManage code changes】
L19:       * 【9†Code QualityEnforce quality at merge】
L20:     * APPLICATION SECURITY
L21:       * 【10†GitHub Advanced SecurityFind and fix vulnerabilities】
L22:       * 【11†Code securitySecure your code as you build】
L23:       * 【12†Secret protectionStop leaks before they start】
L24: 
L25:     * EXPLORE
L26:       * 【13†Why GitHub】
L27:       * 【14†Documentation†docs.github.com】
L28:       * 【15†Blog†github.blog】
L29:       * 【16†Changelog†github.blog】
L30:       * 【17†Marketplace】
L31: 
L32: 【18†View all features】
L33: 
L34:   * Solutions
L35:     * BY COMPANY SIZE
L36:       * 【19†Enterprises】
L37:       * 【20†Small and medium teams】
L38:       * 【21†Startups】
L39:       * 【22†Nonprofits】
L40: 
L41:     * BY USE CASE
L42:       * 【23†App Modernization】
L43:       * 【24†DevSecOps】
L44:       * 【25†DevOps】
L45:       * 【26†CI/CD】
L46:       * 【27†View all use cases】
L47: 
L48:     * BY INDUSTRY
L49:       * 【28†Healthcare】
L50:       * 【29†Financial services】
L51:       * 【30†Manufacturing】
L52:       * 【31†Government】
L53:       * 【32†View all industries】
L54: 
L55: 【33†View all solutions】
L56: 
L57:   * Resources
L58:     * EXPLORE BY TOPIC
L59:       * 【34†AI】
L60:       * 【35†Software Development】
L61:       * 【36†DevOps】
L62:       * 【37†Security】
L63:       * 【38†View all topics】
L64: 
L65:     * EXPLORE BY TYPE
L66:       * 【39†Customer stories】
L67:       * 【40†Events &amp; webinars】
L68:       * 【41†Ebooks &amp; reports】
L69:       * 【42†Business insights】
L70:       * 【43†GitHub Skills†skills.github.com】
L71:     * SUPPORT &amp; SERVICES
</excerpt>
</source>
<source kind="open_page">
<title>playwright/packages/playwright-core/src/client/browserContext.ts at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/browserContext.ts</location>
<excerpt>citeturn4view1 [wordlim: 200] Crawled: today; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;turn0search2&quot;,&quot;lineno&quot;:null}); Total lines: 2500
L1858: if (response)
L1859: 
L1860: response._finishedPromise.resolve(null);
L1861: 
L1862: }
L1863: 
L1864: async _onRoute(route: network.Route) {
L1865: 
L1866: route._context = this;
L1867: 
L1868: const page = route.request()._safePage();
L1869: 
L1870: const routeHandlers = this._routes.slice();
L1871: 
L1872: for (const routeHandler of routeHandlers) {
L1873: 
L1874: // If the page or the context was closed we stall all requests right away.
L1875: 
L1876: if (page?._closeWasCalled || this.isClosed())
L1877: 
L1878: return;
L1879: 
L1880: if (!routeHandler.matches(route.request().url()))
L1881: 
L1882: continue;
L1883: 
L1884: const index = this._routes.indexOf(routeHandler);
L1885: if (index === -1)
L1886: 
L1887: continue;
L1888: 
L1889: if (routeHandler.willExpire())
L1890: 
L1891: this._routes.splice(index, 1);
L1892: 
L1893: const handled = await routeHandler.handle(route);
L1894: 
L1895: if (!this._routes.length)
L1896: 
L1897: this._disableInterception().catch(() =&gt; {});
L1898: 
L1899: if (handled)
L1900: 
L1901: return;
L1902: 
L1903: }
L1904: 
L1905: // If the page is closed or unrouteAll() was called without waiting and interception disabled,
L1906: 
L1907: // the method will throw an error - silence it.
L1908: 
L1909: await route._innerContinue(true /* isFallback */).catch(() =&gt; {});
L1910: 
L1911: }
L1912: async _onWebSocketRoute(webSocketRoute: network.WebSocketRoute) {
L1913: 
L1914: const routeHandler = this._webSocketRoutes.find(route =&gt; route.matches(webSocketRoute.url()));
L1915: 
L1916: if (routeHandler)
L1917: 
L1918: await routeHandler.handle(webSocketRoute);
L1919: 
L1920: else
L1921: 
L1922: webSocketRoute.connectToServer();
L1923: 
L1924: }
L1925: 
L1926: async _onBinding(bindingCall: BindingCall) {
L1927: 
L1928: const func = this._bindings.get(bindingCall._initializer.name);
L1929: 
L1930: if (!func)
L1931: 
L1932: return;
L1933: 
L1934: await bindingCall.call(func);
L1935: 
L1936: }
L1937: 
L1938: private _serviceWorkerScope(serviceWorker: Worker) {
L1939: 
L1940: try {
L1941: let url = new URL(&#39;.&#39;, serviceWorker.url()).href;
L1942: 
L1943: if (!url.endsWith(&#39;/&#39;))
L1944: 
L1945: url += &#39;/&#39;;
L1946: 
L1947: return url;
L1948: 
L1949: } catch {
L1950: 
L1951: return null;
L1952: 
L1953: }
L1954: 
L1955: }
L1956: 
L1957: setDefaultNavigationTimeout(timeout: number | undefined) {
L1958: 
L1959: this._timeoutSettings.setDefaultNavigationTimeout(timeout);
L1960: 
L1961: }
L1962: 
L1963: setDefaultTimeout(timeout: number | undefined) {
L1964: 
L1965: this._timeoutSettings.setDefaultTimeout(timeout);
L1966: 
L1967: }
L1968: 
L1969: browser(): Browser | null {
L1970: 
L1971: return this._browser;
L1972: 
L1973: }
L1974: 
L1975: pages(): Page[] {
L1976: 
L1977: return [...this._pages];
L1978: 
L1979: }
L1980: 
L1981: isClosed(): boolean {
L2009: async addCookies(cookies: network.SetNetworkCookieParam[]): Promise&lt;void&gt; {
L2010: 
L2011: await this._channel.addCookies({ cookies }, kNoTimeout);
L2012: 
L2013: }
L2014: 
L2015: async clearCookies(options: network.ClearNetworkCookieOptions = {}): Promise&lt;void&gt; {
L2016: 
L2017: await this._channel.clearCookies(network.toClearCookiesParams(options), kNoTimeout);
L2018: 
L2019: }
L2020: 
L2021: async grantPermissions(permissions: string[], options?: { origin?: string }): Promise&lt;void&gt; {
L2022: 
L2023: await this._channel.grantPermissions({ permissions, ...options }, kNoTimeout);
L2024: 
L2025: }
L2026: async clearPermissions(): Promise&lt;void&gt; {
L2027: 
L2028: await this._channel.clearPermissions({}, kNoTimeout);
L2029: 
L2030: }
L2031: 
L2032: async setGeolocation(geolocation: { longitude: number, latitude: number, accuracy?: number } | null): Promise&lt;void&gt; {
L2033: 
L2034: await this._channel.setGeolocation({ geolocati…[truncated]</excerpt>
</source>
<source kind="open_page">
<title>playwright/docs/src/api/class-route.md at main · microsoft/playwright · GitHub</title>
<location>https://github.com/microsoft/playwright/blob/main/docs/src/api/class-route.md</location>
<excerpt>citeturn4view2 [wordlim: 200] Crawled: today; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;turn0search0&quot;,&quot;lineno&quot;:null}); Total lines: 851
L284: Details
L285: 
L286: The [`option: headers`] option applies to both the routed request and any redirects it initiates. However, [`option: url`], [`option: method`], and [`option: postData`] only apply to the original request and are not carried over to redirected requests.
L287: 
L288: [`method: Route.continue`] will immediately send the request to the network, other matching handlers won&#39;t be invoked. Use [`method: Route.fallback`] If you want next matching handler in the chain to be invoked.
L289: :::warning Some request headers are forbidden and cannot be overridden (for example, `Cookie`, `Host`, `Content-Length` and others, see 【74†this MDN page†developer.mozilla.org】 for full list). If an override is provided for a forbidden header, it will be ignored and the original request header will be used.
L290: 
L291: To set custom cookies, use [`method: BrowserContext.addCookies`]. :::
L292: ### option: Route.continue.url
L293: 
L294:   * since: v1.8
L295: 
L296:   * `url` &lt;[string]&gt;
L297: 
L298: If set changes the request URL. New URL must have same protocol as original one.
L299: 
L300: ### option: Route.continue.method
L301: 
L302:   * since: v1.8
L303: 
L304:   * `method` &lt;[string]&gt;
L305: 
L306: If set changes the request method (e.g. GET or POST).
L307: 
L308: ### option: Route.continue.postData
L309: 
L310:   * since: v1.8
L311:   * langs: js, python
L312: 
L313:   * `postData` &lt;[string]|[Buffer]|[Serializable]&gt;
L314: 
L315: If set changes the post data of request.
L316: ### option: Route.continue.postData
L317: 
L318:   * since: v1.8
L319:   * langs: java
L320: 
L321:   * `postData` &lt;[string]|[Buffer]&gt;
L322: 
L323: If set changes the post data of request.
L324: 
L325: ### option: Route.continue.postData
L326: 
L327:   * since: v1.8
L328:   * langs: csharp
L329: 
L330:   * `postData` &lt;[Buffer]&gt;
L331: 
L332: If set changes the post data of request.
L333: 
L334: ### option: Route.continue.headers
L335: 
L336:   * since: v1.8
L337: 
L338:   * `headers` &lt;[Object]&lt;[string], [string]&gt;&gt;
L339: 
L340: If set changes the request HTTP headers. Header values will be converted to a string.
L341: ## async method: Route.fallback
L342: 
L343:   * since: v1.23
L344: 
L345: Continues route&#39;s request with optional overrides. The method is similar to [`method: Route.continue`] with the difference that other matching handlers will be invoked before sending the request.
L346: 
L347: Usage
L348: When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it&#39;ll fall back to the previous one and in the end will be aborted by the first registered route.
L349: 
L350:     await page.route(&#39;**/*&#39;, async route =&gt; {
L351:       // Runs last.
L352:       await route.abort();
L353:     });
L354:     await page.route(&#39;**/*&#39;, async route =&gt; {
L355:       // Runs second.
L356:       await route.fallback();
L357:     });
L358:     await page.route(&#39;**/*&#39;, async route =&gt; {
L359:       // Runs first.
L360:       await route.fallback();
L361:     });
L362: 
L363:     page.route(&quot;**/*&quot;, route -&gt; {
L364:       // Runs last.
L365:       route.abort();
L366:     });
L367: 
L368:     page.route(&quot;**/*&quot;, route -&gt; {
L369:       // Runs second.
L370:       route.fallback();
L371:     });
L372: 
L373:     page.route(&quot;**/*&quot;, route -&gt; {
L374:       // Runs first.
L375:       route.fallback();
L376:     });
L377:     await page.route(&quot;**/*&quot;, lambda route: route.abort())  # Runs last.
L378:     await page.route(&quot;**/*&quot;, lambda route: route.fallb…[truncated]</excerpt>
</source>
<omitted_sources count="36">Additional source records were omitted from this bounded result.</omitted_sources>
</source_evidence>

Citations:

- 1: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/network.ts
- 2: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/browserContext.ts
- 3: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/network.ts

Abort the intercepted request when the marker assertion fails.

The Vite transform removes the TypeScript return annotation, so the current marker matches the emitted function prefix. If formatting changes, the assertion runs before route.fulfill. A rejected route handler does not call a terminal route method, so the request can remain pending and make the awaited page.goto time out instead of reporting the assertion directly.

Suggested fix
--- "a/tauri-app/scripts/test-feedback-email.mjs"
+++ "b/tauri-app/scripts/test-feedback-email.mjs"
@@ -26,13 +26,21 @@
       assert.equal(response.status(), 201, await response.text());
     }
   });
-  await page.route('**/src/lib/tauri.ts*', async route => {
-    const response = await route.fetch();
-    const source = await response.text();
-    const marker = 'export const submitFeedback = (input) => {';
-    assert.ok(source.includes(marker), 'Intercept only the desktop transport boundary');
-    await route.fulfill({ response, body: source.replace(marker, `${marker} return window.__feedbackSend(input);`) });
+  await page.route('**/src/lib/tauri.ts*', async route => {
+    try {
+      const response = await route.fetch();
+      const source = await response.text();
+      const marker = /export\s+const\s+submitFeedback\s*=\s*\(\s*input\s*\)\s*=>\s*\{/;
+      assert.match(source, marker, 'Intercept only the desktop transport boundary');
+      await route.fulfill({
+        response,
+        body: source.replace(marker, match => `${match} return window.__feedbackSend(input);`),
+      });
+    } catch (error) {
+      await route.abort().catch(() => {});
+      throw error;
+    }
   });
   await page.goto(process.env.APP_URL ?? 'http://127.0.0.1:1433/');
   const open = async () => {
     await page.getByRole('tab', { name: 'Help', exact: true }).click();

await page.goto(process.env.APP_URL ?? 'http://127.0.0.1:1433/');
const open = async () => {
await page.getByRole('tab', { name: 'Help', exact: true }).click();
await page.getByRole('button', { name: 'Give feedback', exact: true }).click();
};
await open();
const email = page.getByRole('textbox', { name: 'Email (optional)', exact: true });
const message = page.getByRole('textbox', { name: 'Message', exact: true });
const submit = page.getByRole('button', { name: 'Submit', exact: true });
await email.waitFor({ timeout: 5000 });
await message.fill('Anonymous email test');
await submit.click();
await page.getByRole('dialog').waitFor({ state: 'hidden' });
assert.equal(sent.at(-1).email, undefined, 'Blank email stays optional');
await open();
await email.fill('invalid');
await email.blur();
await message.fill('Contact email integration test');
assert.equal(await email.getAttribute('aria-invalid'), 'true');
assert.equal(await submit.isDisabled(), true);
const count = sent.length;
await email.fill('reply@example.com');
rejectNext = true;
await submit.click();
await page.getByRole('alert').filter({ hasText: 'Temporary submission failure' }).waitFor();
assert.equal(await email.inputValue(), 'reply@example.com');
assert.equal(await message.inputValue(), 'Contact email integration test');
assert.equal(sent.length, count + 1);
await page.getByRole('checkbox', { name: 'Include system specs and app logs' }).check();
await submit.click();
await page.getByRole('dialog').waitFor({ state: 'hidden' });
assert.equal(sent.at(-1).email, 'reply@example.com');
assert.equal(sent.at(-1).includeDiagnostics, true);
await open();
assert.equal(await email.inputValue(), '');
assert.equal(await message.inputValue(), '');
for (const colorScheme of ['light', 'dark']) {
await page.emulateMedia({ colorScheme });
for (const height of [900, 500]) {
await page.setViewportSize({ width: 651, height });
const fieldGeometry = await page.locator('#fb-name, #fb-email').evaluateAll(inputs => inputs.map(input => {
const style = getComputedStyle(input);
return {
id: input.id,
height: input.parentElement.getBoundingClientRect().height,
textSpace: input.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom),
lineHeight: parseFloat(style.lineHeight),
};
}));
assert.ok(Math.abs(fieldGeometry[0].height - fieldGeometry[1].height) < 0.5, 'Name and email fields have equal heights');
for (const field of fieldGeometry) assert.ok(field.textSpace >= field.lineHeight, `${field.id}: its text line fits inside the field without vertical clipping`);
await email.fill('invalid');
await email.blur();
await email.scrollIntoViewIfNeeded();
assert.equal(await email.getAttribute('aria-invalid'), 'true');
const errorContrast = await page.locator('#fb-email-error').evaluate(element => {
const luminance = color => {
const channels = color.match(/[\d.]+/g).slice(0, 3).map(Number).map(value => {
const s = value / 255;
return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
});
return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722;
};
const foreground = luminance(getComputedStyle(element).color);
const background = luminance(getComputedStyle(element.closest('[role="dialog"]')).backgroundColor);
return (Math.max(foreground, background) + 0.05) / (Math.min(foreground, background) + 0.05);
});
assert.ok(errorContrast >= 4.5, `Readable email error in ${colorScheme}: ${errorContrast.toFixed(2)}:1`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await mkdir('test-results', { recursive: true });
if (colorScheme === 'dark' && height === 900) await page.screenshot({ path: 'test-results/feedback-email-dark.png' });
await submit.scrollIntoViewIfNeeded();
const box = await submit.boundingBox();
assert.ok(box.y >= 0 && box.y + box.height <= height, 'Submit remains reachable at short heights');
}
}
assert.deepEqual(failures, []);
console.log('PASS optional email, validation, retry preservation, diagnostics, draft reset, both themes, short window, and submission transport');
} finally {
await browser.close();
}
2 changes: 1 addition & 1 deletion tauri-app/sound-lab/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
:root{font:16px system-ui,sans-serif;color:#eef2f8;background:#10141c;color-scheme:dark}*{box-sizing:border-box}body{margin:0}main{max-width:1050px;margin:auto;padding:40px 24px}h1{font-size:34px;margin:0 0 10px}h2{font-size:22px;margin-top:32px}p{color:#aebbd0;line-height:1.6}label{display:flex;flex-direction:column;gap:9px}button,select{font:inherit;border:1px solid #46546b;border-radius:10px;background:#252f40;color:inherit;padding:12px;cursor:pointer}button:hover{background:#364863}button:focus-visible,select:focus-visible,input:focus-visible{outline:3px solid #83e7c1;outline-offset:3px}.controls{display:flex;flex-wrap:wrap;gap:20px;background:#1a2230;padding:20px;border-radius:14px;align-items:center}.controls label{min-width:130px;flex:1}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}.cue{text-align:left;min-height:85px}.cue strong{display:block;margin-bottom:8px}.cue small{color:#b1c4dc}.inline{flex-direction:row;align-items:center!important}#status{position:sticky;bottom:12px;background:#193d32;border:1px solid #337660;padding:14px;border-radius:10px;margin-top:28px}a{color:#83e7c1}button:disabled{opacity:.45;cursor:default}input[type=range]{width:100%}
</style></head><body><main>
<h1>Sound lab</h1><p>Listen, compare, and choose your favourites. These controls only affect this playground.</p>
<div class="controls"><label>Volume <span id="volume-label">35%</span><input id="volume" type="range" min="0" max="100" value="35" aria-label="Preview volume"></label><button id="mute" aria-pressed="false">Mute</button><label class="inline"><input id="ready" type="checkbox" checked>Keep audio ready while testing</label></div>
<div class="controls"><label>Volume <span id="volume-label">70%</span><input id="volume" type="range" min="0" max="100" value="70" aria-label="Preview volume"></label><button id="mute" aria-pressed="false">Mute</button><label class="inline"><input id="ready" type="checkbox" checked>Keep audio ready while testing</label></div>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,85p' tauri-app/sound-lab/index.html
rg -n 'sound-lab/index.html|<form|id="mute"' tauri-app/sound-lab tauri-app/src docs/sound-effects.md

Repository: SupaStellar/Cleanmeter

Length of output: 3440


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- references ---'
rg -n -F --hidden --glob '!node_modules/**' --glob '!target/**' --glob '!dist/**' -e 'tauri-app/sound-lab' -e 'sound-lab' -e '<iframe' -e 'iframe' . || test "$?" -eq 1
printf '%s\n' '--- instruction/config candidates ---'
rg --files -g 'AGENTS.md' -g 'CONTRIBUTING*' -g '*STYLE*' -g '*GUIDELINE*' -g '.htmlhintrc*' -g 'package.json' -g 'README*' . | sort
printf '%s\n' '--- relevant instruction text ---'
for f in $(rg --files -g 'AGENTS.md' -g 'CONTRIBUTING*' -g '*STYLE*' -g '*GUIDELINE*' -g '.htmlhintrc*' | sort); do
  printf '\n### %s\n' "$f"
  sed -n '1,220p' "$f"
done

Repository: SupaStellar/Cleanmeter

Length of output: 2478


Add type="button" to #mute.

The sound lab is currently used as a standalone page, so form submission is not a present runtime concern. However, .htmlhintrc enables button-type-require, and this button violates that project requirement.

Proposed fix
-<button id="mute" aria-pressed="false">Mute</button>
+<button type="button" id="mute" aria-pressed="false">Mute</button>
🧰 Tools
🪛 HTMLHint (1.9.2)

[warning] 6-6: The type attribute must be present on elements.

(button-type-require)


[warning] 6-6: No matching [ label ] tag found.

(input-requires-label)


[warning] 6-6: No matching [ label ] tag found.

(input-requires-label)

<p><small>Audio readiness uses the same quiet output helper as Cleanmeter. It stops when this page loses focus or is muted. No sounds play automatically.</small></p>
<h2>Compare Cleanmeter cues</h2><p>These use the app's default sound theme. Volume follows the slider above.</p><div id="presets" class="grid"></div>
<h2>Explore the library</h2><div class="controls"><label>Library<select id="library"><option value="current">Cleanmeter - Cuelume 0.2.8</option><option value="legacy">Legacy - Cuelume 0.2.2</option></select></label><label>Theme<select id="theme"></select></label><label>Emphasis<select id="emphasis"><option>normal</option><option>subtle</option><option>strong</option></select></label><label>Direction<select id="direction"><option value="forward">Forward / on</option><option value="back">Back / off</option></select></label></div>
Expand Down
29 changes: 29 additions & 0 deletions tauri-app/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,13 +571,38 @@ pub fn grant_admin_consent(settings_mgr: State<'_, SettingsManager>) {
#[derive(serde::Deserialize)]
pub struct FeedbackInput {
pub name: String,
#[serde(default)]
pub email: Option<String>,
pub message: String,
#[serde(rename = "attachmentPath")]
pub attachment_path: Option<String>,
#[serde(rename = "includeDiagnostics", default)]
pub include_diagnostics: bool,
}

#[cfg(test)]
mod feedback_email_tests {
use super::FeedbackInput;

#[test]
fn feedback_rejects_a_non_string_contact_email() {
let input = serde_json::json!({ "name": "Test", "message": "Issue", "email": 17 });
assert!(serde_json::from_value::<FeedbackInput>(input).is_err());
}

#[test]
fn feedback_accepts_old_payloads_without_email() {
let input: FeedbackInput = serde_json::from_value(serde_json::json!({ "name": "Test", "message": "Issue" })).unwrap();
assert!(input.email.is_none());
}

#[test]
fn feedback_keeps_the_supplied_contact_email() {
let input: FeedbackInput = serde_json::from_value(serde_json::json!({ "name": "Test", "message": "Issue", "email": "reply@example.com" })).unwrap();
assert_eq!(input.email.as_deref(), Some("reply@example.com"));
}
}

// POSTs feedback to the portal. URL + write key are injected at build time via
// option_env!; if either is missing (e.g. a plain local dev build) the command
// returns an error instead of attempting a request. Touches no app state.
Expand All @@ -604,6 +629,10 @@ pub async fn submit_feedback(input: FeedbackInput, app: AppHandle) -> Result<(),
.text("app_version", env!("CARGO_PKG_VERSION"))
.text("os", std::env::consts::OS);

if let Some(email) = input.email.as_deref().map(str::trim).filter(|email| !email.is_empty()) {
form = form.text("email", email.to_owned());
}

if let Some(path) = input.attachment_path.as_deref() {
let file_path = std::path::Path::new(path);
let (bytes, mime) = crate::feedback_attachment::read(file_path).await?;
Expand Down
15 changes: 15 additions & 0 deletions tauri-app/src/app/components/stories/FeedbackDialog.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within } from "storybook/test";
import { FeedbackDialog } from "../../../components/settings/settings/FeedbackDialog";

const meta: Meta<typeof FeedbackDialog> = {
Expand All @@ -21,6 +22,20 @@ export const Default: Story = {
},
};

export const OptionalEmail: Story = {
...Default,
play: async () => {
const dialog = within(document.body).getByRole("dialog");
const email = within(dialog).getByRole("textbox", { name: "Email (optional)" });
await userEvent.type(email, "invalid");
await userEvent.tab();
await expect(email).toHaveAttribute("aria-invalid", "true");
await userEvent.clear(email);
await userEvent.type(email, "reply@example.com");
await expect(email).toHaveAttribute("aria-invalid", "false");
},
};

// Click "Add attachment" to see the picker error state.
const failingPicker = async (): Promise<null> => {
throw "The file is open in another program.";
Expand Down
40 changes: 37 additions & 3 deletions tauri-app/src/components/settings/settings/FeedbackDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ export function FeedbackDialog({
pickAttachment = pickFeedbackAttachment,
}: FeedbackDialogProps) {
const [name, setName] = React.useState("");
const [email, setEmail] = React.useState("");
const [emailTouched, setEmailTouched] = React.useState(false);
const [message, setMessage] = React.useState("");
const [attachment, setAttachment] = React.useState<Attachment | null>(null);
const [includeDiagnostics, setIncludeDiagnostics] = React.useState(false);
Expand All @@ -90,6 +92,8 @@ export function FeedbackDialog({
React.useEffect(() => {
if (!open) {
setName("");
setEmail("");
setEmailTouched(false);
setMessage("");
setAttachment(null);
setIncludeDiagnostics(false);
Expand All @@ -104,7 +108,10 @@ export function FeedbackDialog({
(attachment ? removeRef : addRef).current?.focus();
}, [attachment]);

const canSubmit = message.trim() !== "" && !submitting;
const trimmedEmail = email.trim();
const emailValid = trimmedEmail === "" || (trimmedEmail.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail));
const emailError = emailTouched && !emailValid;
const canSubmit = message.trim() !== "" && emailValid && !submitting;

// Editing the report retires the previous failure message.
const edit = (set: (value: string) => void) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
Expand Down Expand Up @@ -137,6 +144,7 @@ export function FeedbackDialog({
try {
await submitFeedback({
name: name.trim(),
email: trimmedEmail || undefined,
message: message.trim(),
attachmentPath: attachment?.path,
includeDiagnostics,
Expand Down Expand Up @@ -197,14 +205,40 @@ export function FeedbackDialog({
</Label>
<Input
id="fb-name"
className="h-10"
className="h-10 [&_input]:h-full [&_input]:min-h-0 [&_input]:py-0"
disabled={submitting}
placeholder="Ex: Leon Kennedy"
value={name}
onChange={edit(setName)}
/>
</div>

<div className="flex flex-col gap-2">
<Label className="text-body-sm-medium text-[var(--textHeading)]" htmlFor="fb-email">
Email (optional)
</Label>
<Input
id="fb-email"
type="email"
autoComplete="email"
maxLength={254}
className="h-10 [&_input]:h-full [&_input]:min-h-0 [&_input]:py-0"
disabled={submitting}
placeholder="you@example.com"
value={email}
onChange={edit(setEmail)}
onBlur={() => setEmailTouched(true)}
error={emailError}
aria-invalid={emailError}
aria-describedby={emailError ? "fb-email-error" : undefined}
/>
{emailError && (
<p id="fb-email-error" role="alert" className="text-body-sm-regular text-[var(--textDanger)] [[data-theme=dark]_&]:text-[var(--red400)]">
Enter a valid email address or leave it blank.
</p>
)}
</div>

<div className="flex flex-col gap-2">
<Label className="text-body-sm-medium text-[var(--textHeading)]" htmlFor="fb-message">
Message
Expand Down Expand Up @@ -267,7 +301,7 @@ export function FeedbackDialog({
className="w-full rounded-[4px] text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
/>
{status === "error" && (
<p role="alert" className="text-body-sm-regular text-[var(--iconDanger)]">
<p role="alert" className="text-body-sm-regular text-[var(--textDanger)] [[data-theme=dark]_&]:text-[var(--red400)]">
{error || "Couldn’t send feedback. Please try again."}
</p>
)}
Expand Down
4 changes: 2 additions & 2 deletions tauri-app/src/lib/sound-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ const enabled = () => {
return state.preferencesLoaded && state.preferences.soundEffects;
};

setVolume(0.35);
volumeLegacy(0.35);
setVolume(0.7);
volumeLegacy(0.7);
setEnabled(enabled());
enableLegacy(enabled());
const readiness = installAudioReadiness(enabled);
Expand Down
1 change: 1 addition & 0 deletions tauri-app/src/lib/tauri.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ export const onSetOpacity = (

export const submitFeedback = (input: {
name: string;
email?: string;
message: string;
attachmentPath?: string;
includeDiagnostics?: boolean;
Expand Down
Loading