helloadhavan/github_issues huggingface dataset:
Repository: electron/electron
Pull request: fix: potential draggable regions crash in DevTools

Backport of #43179

See that PR for details.


Notes: Fixed a crash that could occur in some DevTools extensions containing draggable regions.

Changed files:
filename: patches/chromium/.patches
patch: @@ -130,3 +130,4 @@ fix_font_face_resolution_when_renderer_is_blocked.patch
 feat_enable_passing_exit_code_on_service_process_crash.patch
 chore_remove_reference_to_chrome_browser_themes.patch
 feat_enable_customizing_symbol_color_in_framecaptionbutton.patch
+fix_potential_draggable_region_crash_when_no_mainframeimpl.patch

filename: patches/chromium/fix_potential_draggable_region_crash_when_no_mainframeimpl.patch
patch: @@ -0,0 +1,35 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <shelley.vohr@gmail.com>
+Date: Thu, 1 Aug 2024 15:30:32 +0200
+Subject: Fix potential draggable region crash when no MainFrameImpl
+
+Fix a crash that can occur when SetSupportsDraggableRegions
+is called with `true` and there is no MainFrameImpl. When MainFrameImpl
+is nullptr, logic currently correctly returns early, but
+supports_draggable_regions_ is set before that happens. As a
+result, when SupportsDraggableRegions() is called, it will return
+true, and thus LocalFrameView::UpdateDocumentDraggableRegions() will
+call DraggableRegionsChanged(). This will trigger a crash in
+WebViewImpl::DraggableRegionsChanged(), as it assumes that
+MainFrameImpl is not null.
+
+Upstreamed in https://chromium-review.googlesource.com/c/chromium/src/+/5756619
+
+diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc
+index ef68f9cbc63772f50269520fb0198a95e4270947..948cf94e2e4af0bbbf1f9c2322d00075bdaca0b2 100644
+--- a/third_party/blink/renderer/core/exported/web_view_impl.cc
++++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
+@@ -4073,11 +4073,12 @@ bool WebViewImpl::IsFencedFrameRoot() const {
+ }
+ 
+ void WebViewImpl::SetSupportsDraggableRegions(bool supports_draggable_regions) {
+-  supports_draggable_regions_ = supports_draggable_regions;
+   if (!MainFrameImpl() || !MainFrameImpl()->GetFrame()) {
+     return;
+   }
+ 
++  supports_draggable_regions_ = supports_draggable_regions;
++
+   LocalFrame* local_frame = MainFrameImpl()->GetFrame();
+ 
+   if (supports_draggable_regions_) {
Repository: electron/electron
Pull request: fix: potential draggable regions crash in DevTools

Backport of #43179

See that PR for details.


Notes: Fixed a crash that could occur in some DevTools extensions containing draggable regions.

Changed files:
filename: patches/chromium/.patches
patch: @@ -133,3 +133,4 @@ x11_use_localized_display_label_only_for_browser_process.patch
 feat_enable_customizing_symbol_color_in_framecaptionbutton.patch
 cherry-pick-99cafbf4b4b9.patch
 cherry-pick-44b7fbf35b10.patch
+fix_potential_draggable_region_crash_when_no_mainframeimpl.patch

filename: patches/chromium/fix_potential_draggable_region_crash_when_no_mainframeimpl.patch
patch: @@ -0,0 +1,35 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <shelley.vohr@gmail.com>
+Date: Thu, 1 Aug 2024 15:30:32 +0200
+Subject: Fix potential draggable region crash when no MainFrameImpl
+
+Fix a crash that can occur when SetSupportsDraggableRegions
+is called with `true` and there is no MainFrameImpl. When MainFrameImpl
+is nullptr, logic currently correctly returns early, but
+supports_draggable_regions_ is set before that happens. As a
+result, when SupportsDraggableRegions() is called, it will return
+true, and thus LocalFrameView::UpdateDocumentDraggableRegions() will
+call DraggableRegionsChanged(). This will trigger a crash in
+WebViewImpl::DraggableRegionsChanged(), as it assumes that
+MainFrameImpl is not null.
+
+Upstreamed in https://chromium-review.googlesource.com/c/chromium/src/+/5756619
+
+diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc
+index b6c1bbe08e8e2b3bb85b5c91eac512078cd3f1b4..f234a5f3a412d9c6976018ac81d6fee8cbc51d32 100644
+--- a/third_party/blink/renderer/core/exported/web_view_impl.cc
++++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
+@@ -4039,11 +4039,12 @@ bool WebViewImpl::IsFencedFrameRoot() const {
+ }
+ 
+ void WebViewImpl::SetSupportsDraggableRegions(bool supports_draggable_regions) {
+-  supports_draggable_regions_ = supports_draggable_regions;
+   if (!MainFrameImpl() || !MainFrameImpl()->GetFrame()) {
+     return;
+   }
+ 
++  supports_draggable_regions_ = supports_draggable_regions;
++
+   LocalFrame* local_frame = MainFrameImpl()->GetFrame();
+ 
+   if (supports_draggable_regions_) {
Repository: facebook/react
Pull request: Add useSyncExternalStore to react-debug-tools

Adds support for useSyncExternalStore to react-debug-tools, which in turn adds support for React Devtools.

### Test plan

I added a test to ReactHooksInspectionIntegration, based on existing one for useMutableSource.

Changed files:
filename: packages/react-debug-tools/src/ReactDebugHooks.js
patch: @@ -269,7 +269,19 @@ function useSyncExternalStore<T>(
   subscribe: (() => void) => () => void,
   getSnapshot: () => T,
 ): T {
-  throw new Error('Not yet implemented');
+  // useSyncExternalStore() composes multiple hooks internally.
+  // Advance the current hook index the same number of times
+  // so that subsequent hooks have the right memoized state.
+  nextHook(); // SyncExternalStore
+  nextHook(); // LayoutEffect
+  nextHook(); // Effect
+  const value = getSnapshot();
+  hookLog.push({
+    primitive: 'SyncExternalStore',
+    stackError: new Error(),
+    value,
+  });
+  return value;
 }
 
 function useTransition(): [boolean, (() => void) => void] {

filename: packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js
patch: @@ -878,4 +878,37 @@ describe('ReactHooksInspectionIntegration', () => {
       },
     ]);
   });
+
+  // @gate experimental || www
+  it('should support composite useSyncExternalStore hook', () => {
+    const useSyncExternalStore = React.unstable_useSyncExternalStore;
+    function Foo() {
+      const value = useSyncExternalStore(
+        () => () => {},
+        () => 'snapshot',
+      );
+      React.useMemo(() => 'memo', []);
+      return value;
+    }
+
+    const renderer = ReactTestRenderer.create(<Foo />);
+    const childFiber = renderer.root.findByType(Foo)._currentFiber();
+    const tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
+    expect(tree).toEqual([
+      {
+        id: 0,
+        isStateEditable: false,
+        name: 'SyncExternalStore',
+        value: 'snapshot',
+        subHooks: [],
+      },
+      {
+        id: 1,
+        isStateEditable: false,
+        name: 'Memo',
+        value: 'memo',
+        subHooks: [],
+      },
+    ]);
+  });
 });
Repository: ggml-org/llama.cpp
Pull request: Sync minja patch to support inclusionAI/Ling-lite template and update tests

*Make sure to read the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md) before submitting a PR*

https://github.com/google/minja/pull/58
Credit goes to @ochafik.

#### Testing Done

- [x] `./build/bin/test-chat-template`
- [x] `./build/bin/llama-cli -m ./llama-cli -m /home/xiaodongye/.cache/huggingface/hub/models--mradermacher--Ling-lite-GGUF/snapshots/a338e70b6371205bbf2396154171e25524ca3c71/Ling-lite.Q4_K_M.gguf -ngl 999`

Changed files:
filename: common/minja/minja.hpp
patch: @@ -2606,14 +2606,18 @@ inline std::shared_ptr<Context> Context::builtins() {
     auto & text = args.at("text");
     return text.is_null() ? text : Value(strip(text.get<std::string>()));
   }));
-  globals.set("lower", simple_function("lower", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
-    auto text = args.at("text");
-    if (text.is_null()) return text;
-    std::string res;
-    auto str = text.get<std::string>();
-    std::transform(str.begin(), str.end(), std::back_inserter(res), ::tolower);
-    return Value(res);
-  }));
+  auto char_transform_function = [](const std::string & name, const std::function<char(char)> & fn) {
+    return simple_function(name, { "text" }, [=](const std::shared_ptr<Context> &, Value & args) {
+      auto text = args.at("text");
+      if (text.is_null()) return text;
+      std::string res;
+      auto str = text.get<std::string>();
+      std::transform(str.begin(), str.end(), std::back_inserter(res), fn);
+      return Value(res);
+    });
+  };
+  globals.set("lower", char_transform_function("lower", ::tolower));
+  globals.set("upper", char_transform_function("upper", ::toupper));
   globals.set("default", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
     args.expectArgs("default", {2, 3}, {0, 1});
     auto & value = args.args[0];

filename: tests/test-chat-template.cpp
patch: @@ -278,6 +278,14 @@ int main(void) {
             /* .bos_token= */ "",
             /* .eos_token= */ "",
         },
+        {
+            /* .name= */ "inclusionAI/Ling-lite",
+            /* .template_str */ "{% for message in messages %}{% set role = message['role'] | lower %}{% if role == 'user' %}{% set role = 'HUMAN' %}{% endif %}{% set role = role | upper %}{{ '<role>' + role + '</role>' + message['content'] }}{% endfor %}{% if add_generation_prompt %}{{ '<role>ASSISTANT</role>' }}{% endif %}",
+            /* .expected_output= */ "<role>SYSTEM</role>You are a helpful assistant<role>HUMAN</role>Hello<role>ASSISTANT</role>Hi there<role>HUMAN</role>Who are you<role>ASSISTANT</role>   I am an assistant   <role>HUMAN</role>Another question<role>ASSISTANT</role>",
+            /* .expected_output_jinja= */ "",
+            /* .bos_token= */ "",
+            /* .eos_token= */ "",
+        },
     };
     std::vector<char> formatted_chat(1024);
     int32_t res;
Repository: facebook/react
Pull request: Reorder VARIANT feature flags

This doesn't change any values but moves the non-hardcoded ones to the top.

The original intent was to have _as few hardcoded flags as possible_ and ideally always use `__VARIANT__`:

https://github.com/facebook/react/blob/2f156eafb83d129a729947ac2bd7089d20b208ab/packages/shared/forks/ReactFeatureFlags.www-dynamic.js#L44-L46

Seems like it's easy to miss this, so I added another comment at the bottom to clarify it.

Changed files:
filename: packages/shared/forks/ReactFeatureFlags.www-dynamic.js
patch: @@ -18,6 +18,13 @@ export const disableInputAttributeSyncing = __VARIANT__;
 export const enableFilterEmptyStringAttributesDOM = __VARIANT__;
 export const enableLegacyFBSupport = __VARIANT__;
 export const skipUnmountedBoundaries = __VARIANT__;
+export const enableUseRefAccessWarning = __VARIANT__;
+export const deletedTreeCleanUpLevel = __VARIANT__ ? 3 : 1;
+export const enableProfilerNestedUpdateScheduledHook = __VARIANT__;
+export const disableSchedulerTimeoutInWorkLoop = __VARIANT__;
+export const enableLazyContextPropagation = __VARIANT__;
+export const enableSyncDefaultUpdates = __VARIANT__;
+export const consoleManagedByDevToolsDuringStrictMode = __VARIANT__;
 
 // Enable this flag to help with concurrent mode debugging.
 // It logs information to the console about React scheduling, rendering, and commit phases.
@@ -47,17 +54,9 @@ export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
 export const enableTrustedTypesIntegration = false;
 export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
 export const disableNativeComponentFrames = false;
-
 export const createRootStrictEffectsByDefault = false;
 export const enableStrictEffects = false;
-export const enableUseRefAccessWarning = __VARIANT__;
-export const deletedTreeCleanUpLevel = __VARIANT__ ? 3 : 1;
-
-export const enableProfilerNestedUpdateScheduledHook = __VARIANT__;
-export const disableSchedulerTimeoutInWorkLoop = __VARIANT__;
-export const enableLazyContextPropagation = __VARIANT__;
-export const enableSyncDefaultUpdates = __VARIANT__;
 export const allowConcurrentByDefault = true;
 export const enablePersistentOffscreenHostContainer = false;
-
-export const consoleManagedByDevToolsDuringStrictMode = __VARIANT__;
+// You probably *don't* want to add more hardcoded ones.
+// Instead, try to add them above with the __VARIANT__ value.
Repository: vercel/next.js
Pull request: Update middleware request header

This just adds an additional header to our internal filtering list for middleware. 

Changed files:
filename: packages/next/src/server/lib/router-server.ts
patch: @@ -166,6 +166,12 @@ export async function initialize(opts: {
   renderServer.instance =
     require('./render-server') as typeof import('./render-server')
 
+  const randomBytes = new Uint8Array(8)
+  crypto.getRandomValues(randomBytes)
+  const middlewareSubrequestId = Buffer.from(randomBytes).toString('hex')
+  ;(globalThis as any)[Symbol.for('@next/middleware-subrequest-id')] =
+    middlewareSubrequestId
+
   const allowedOrigins = ['localhost', ...(config.allowedDevOrigins || [])]
   if (opts.hostname) {
     allowedOrigins.push(opts.hostname)

filename: packages/next/src/server/lib/server-ipc/utils.ts
patch: @@ -57,5 +57,16 @@ export const filterInternalHeaders = (
     if (INTERNAL_HEADERS.includes(header)) {
       delete headers[header]
     }
+
+    // If this request didn't origin from this session we filter
+    // out the "x-middleware-subrequest" header so we don't skip
+    // middleware incorrectly
+    if (
+      header === 'x-middleware-subrequest' &&
+      headers['x-middleware-subrequest-id'] !==
+        (globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]
+    ) {
+      delete headers['x-middleware-subrequest']
+    }
   }
 }

filename: packages/next/src/server/web/sandbox/context.ts
patch: @@ -373,6 +373,10 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),
             store.headers.get('x-middleware-subrequest') ?? ''
           )
         }
+        init.headers.set(
+          'x-middleware-subrequest-id',
+          (globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]
+        )
 
         const prevs =
           init.headers.get(`x-middleware-subrequest`)?.split(':') || []

filename: test/e2e/middleware-general/test/index.test.ts
patch: @@ -144,6 +144,19 @@ describe('Middleware Runtime', () => {
       }
     }
 
+    it('should filter request header properly', async () => {
+      const res = await next.fetch('/redirect-to-somewhere', {
+        headers: {
+          'x-middleware-subrequest':
+            'middleware:middleware:middleware:middleware:middleware',
+        },
+        redirect: 'manual',
+      })
+
+      expect(res.status).toBe(307)
+      expect(res.headers.get('location')).toContain('/somewhere')
+    })
+
     it('should handle 404 on fallback: false route correctly', async () => {
       const res = await next.fetch('/ssg-fallback-false/first')
       expect(res.status).toBe(200)
Repository: nodejs/node
Pull request: test: remove interval and give more time to unsync

This PR should address #54807.

I'm leaving this in Draft while testing more extensively 🚀 

Changed files:
filename: test/parallel/test-runner-watch-mode-complex.mjs
patch: @@ -3,7 +3,8 @@ import * as common from '../common/index.mjs';
 import { describe, it } from 'node:test';
 import assert from 'node:assert';
 import { spawn } from 'node:child_process';
-import { writeFileSync, unlinkSync } from 'node:fs';
+import { writeFile, unlink } from 'node:fs/promises';
+import { setTimeout } from 'node:timers/promises';
 import util from 'internal/util';
 import tmpdir from '../common/tmpdir.js';
 
@@ -46,8 +47,12 @@ test('test to delete has ran');`,
 const fixturePaths = Object.fromEntries(Object.keys(fixtureContent)
   .map((file) => [file, tmpdir.resolve(file)]));
 
-Object.entries(fixtureContent)
-  .forEach(([file, content]) => writeFileSync(fixturePaths[file], content));
+async function setupFixtures() {
+  return Promise.all(Object.entries(fixtureContent)
+    .map(([file, content]) => writeFile(fixturePaths[file], content, { flush: true })));
+}
+
+await setupFixtures();
 
 describe('test runner watch mode with more complex setup', () => {
   it('should run tests when a dependency changed after a watched test file being deleted', async () => {
@@ -76,15 +81,16 @@ describe('test runner watch mode with more complex setup', () => {
     runs.push(currentRun);
     currentRun = '';
     const fileToDeletePathLocal = tmpdir.resolve('test-to-delete.mjs');
-    unlinkSync(fileToDeletePathLocal);
+    await unlink(fileToDeletePathLocal);
+    await setTimeout(common.platformTimeout(1000));
 
     const content = fixtureContent['dependency.mjs'];
     const path = fixturePaths['dependency.mjs'];
-    const interval = setInterval(() => writeFileSync(path, content), common.platformTimeout(1000));
+    await writeFile(path, content, { flush: true });
+    await setTimeout(common.platformTimeout(1000));
     await ran2.promise;
     runs.push(currentRun);
     currentRun = '';
-    clearInterval(interval);
     child.kill();
 
     assert.strictEqual(runs.length, 2);
Repository: denoland/deno
Pull request: fix(ext/http): print `[]` around ipv6 addresses

Fixes #23650

Changed files:
filename: ext/http/00_serve.ts
patch: @@ -34,6 +34,7 @@ const {
   ObjectPrototypeIsPrototypeOf,
   PromisePrototypeCatch,
   PromisePrototypeThen,
+  StringPrototypeIncludes,
   Symbol,
   TypeError,
   TypedArrayPrototypeGetSymbolToStringTag,
@@ -656,14 +657,19 @@ function serve(arg1, arg2) {
   // If the hostname is "0.0.0.0", we display "localhost" in console
   // because browsers in Windows don't resolve "0.0.0.0".
   // See the discussion in https://github.com/denoland/deno_std/issues/1165
-  const hostname = addr.hostname == "0.0.0.0" ? "localhost" : addr.hostname;
+  const hostname = addr.hostname == "0.0.0.0" || addr.hostname == "::"
+    ? "localhost"
+    : addr.hostname;
   addr.hostname = hostname;
 
   const onListen = (scheme) => {
     if (options.onListen) {
       options.onListen(addr);
     } else {
-      console.log(`Listening on ${scheme}${addr.hostname}:${addr.port}/`);
+      const host = StringPrototypeIncludes(addr.hostname, ":")
+        ? `[${addr.hostname}]`
+        : addr.hostname;
+      console.log(`Listening on ${scheme}${host}:${addr.port}/`);
     }
   };
Repository: electron/electron
Pull request: perf: don't build unused vectors in HidChooserContext

Backport of #43192

See that PR for details.


Notes: none.

Changed files:
filename: shell/browser/hid/hid_chooser_context.cc
patch: @@ -276,13 +276,8 @@ void HidChooserContext::DeviceRemoved(device::mojom::HidDeviceInfoPtr device) {
   if (CanStorePersistentEntry(*device))
     return;
 
-  std::vector<url::Origin> revoked_origins;
-  for (auto& map_entry : ephemeral_devices_) {
-    if (map_entry.second.erase(device->guid) > 0)
-      revoked_origins.push_back(map_entry.first);
-  }
-  if (revoked_origins.empty())
-    return;
+  for (auto& [origin, guids] : ephemeral_devices_)
+    guids.erase(device->guid);
 }
 
 void HidChooserContext::DeviceChanged(device::mojom::HidDeviceInfoPtr device) {
@@ -341,11 +336,6 @@ void HidChooserContext::OnHidManagerConnectionError() {
   hid_manager_.reset();
   client_receiver_.reset();
   devices_.clear();
-
-  std::vector<url::Origin> revoked_origins;
-  revoked_origins.reserve(ephemeral_devices_.size());
-  for (const auto& map_entry : ephemeral_devices_)
-    revoked_origins.push_back(map_entry.first);
   ephemeral_devices_.clear();
 
   // Notify all device observers.
Repository: facebook/react
Pull request: Add warning and test for useSyncExternalStore when getSnapshot isn't cached

- Add a test to the React repo (useSyncExternalStore-test.js) that renders a component that uses `useSyncExternalStore`.
- Pass a `getSnapshot` function to `useSyncExternalStore` that returns a new object each time it's called
- The test will throw because of an infinite update loop. It should also log a warning in development that the result of `getSnapshot` must be cached (can bikeshed the exact text of the warning during code review)

Test Plan:
yarn test 


Changed files:
filename: packages/use-sync-external-store/src/__tests__/useSyncExternalStoreShared-test.js
patch: @@ -618,4 +618,30 @@ describe('Shared useSyncExternalStore behavior (shim and built-in)', () => {
       expect(root).toMatchRenderedOutput('A1B1');
     });
   });
+
+  test('Infinite loop if getSnapshot keeps returning new reference', () => {
+    const store = createExternalStore({});
+
+    function App() {
+      const text = useSyncExternalStore(store.subscribe, () => ({}));
+      return <Text text={JSON.stringify(text)} />;
+    }
+
+    spyOnDev(console, 'error');
+
+    expect(() => {
+      act(() => {
+        createRoot(<App />);
+      });
+    }).toThrow(
+      'Maximum update depth exceeded. This can happen when a component repeatedly ' +
+        'calls setState inside componentWillUpdate or componentDidUpdate. React limits ' +
+        'the number of nested updates to prevent infinite loops.',
+    );
+    if (__DEV__) {
+      expect(console.error.calls.argsFor(0)[0]).toMatch(
+        'The result of getSnapshot should be cached to avoid an infinite loop',
+      );
+    }
+  });
 });

filename: packages/use-sync-external-store/src/useSyncExternalStore.js
patch: @@ -29,6 +29,7 @@ export const useSyncExternalStore =
   builtInAPI !== undefined ? builtInAPI : useSyncExternalStore_shim;
 
 let didWarnOld18Alpha = false;
+let didWarnUncachedGetSnapshot = false;
 
 // Disclaimer: This shim breaks many of the rules of React, and only works
 // because of a very particular set of implementation details and assumptions
@@ -63,6 +64,16 @@ function useSyncExternalStore_shim<T>(
   // implementation details, most importantly that updates are
   // always synchronous.
   const value = getSnapshot();
+  if (__DEV__) {
+    if (!didWarnUncachedGetSnapshot) {
+      if (value !== getSnapshot()) {
+        console.error(
+          'The result of getSnapshot should be cached to avoid an infinite loop',
+        );
+        didWarnUncachedGetSnapshot = true;
+      }
+    }
+  }
 
   // Because updates are synchronous, we don't queue them. Instead we force a
   // re-render whenever the subscribed state changes by updating an some