Repository navigation
Conversation
M4n5ter
left a comment
There was a problem hiding this comment.
English
Thanks for splitting these follow-ups out of #7338! The underlying fixes are real, and a few cleanups would make this much sharper and avoid leaving peer paths behind:
-
FrameTarget::clear_layer()leaves two zero-size peer paths broken (third-party/nsh/crates/nsh-engine/src/{frames,shader,gpu}.rs)- Adding a separate
clear_layer(&mut self)only updatesShaderView::set_layer(None), while leavingclear_frame(&mut self) -> booluntouched. - There are only three callers of
clear_frame()innsh-engine:ShaderView::set_layer(None),ShaderView::renderonwidth == 0 || height == 0(shader.rs:1024), andGpuViewrenderonwidth == 0 || height == 0(gpu.rs:603). - With
show_on_surfaces(true)on Apple/Windows,self.frame.widthis always0and frames live inself.surfaces/self.previous. Leavingclear_frame()as-is means collapsing aShaderVieworGpuViewto0×0still retains stale IOSurface/SharedTexture frames and returnsfalsefromclear_frame(), so macOS (display_frame) and Windows (view.redraw()) don't repaint to clear the old frame. - Suggestion: Drop
clear_layer()and fixclear_frame(&mut self) -> booldirectly—take()bothself.surfaces(Apple/Windows) andself.previous(Windows), foldingshown_texture().is_some()into the returnedhadflag. That fixes all three call sites in one place and keepsshader.rsproduction code untouched (smaller vendored diff). Extending theshader.rstest with a0×0resize check would cover both paths.
- Adding a separate
-
Avoid the curried closure signature on
pub fn Keymap::gives_way(third-party/nsh/crates/nsh-core/src/keymap.rs,nsh-platform-linux/src/keymap.rs)- Returning
impl Fn(&KeyBinding) -> boolmakes single-binding call sites awkward (!table.gives_way(binding.keystroke, eligible)(binding)in Linux) and introduces an implicit contract on apubmethod: the returned closure silently assumes everybindingpassed to it hasbinding.keystroke == key. - Suggestion: Keep
gives_wayas a plain predicate—pub fn gives_way(&self, binding: &KeyBinding, eligible: impl Fn(&KeyBinding) -> bool) -> bool(matching upstream's signature pluseligible)—and extract a small private helper (or explicit private policy enum) shared bygives_wayandfind_eligiblesofind_eligiblestill computes the pointer-override check once in O(N).
- Returning
-
products/maka/ios-shell/src/bridge.rs: redundant innertokio::select!and heavy test boilerplate- Keeping
if sender.is_closed()under thestatelock inregister_subscriptionis genuinely needed (whencalls.subscribe().awaitresolves andstate.lock().awaitis uncontended, the outerselect!doesn't get another poll before insertion). TheMutationProgress::emitfast path, movingdrop(subscription)before locking, and typingoutcomeasOption<Result<(), RemoteClientError>>are all clean improvements. - However, the new inner
tokio::select! { biased; _ = sender.closed() => ..., result = calls.subscribe(...) => ... }insideopen_subscriptionduplicates the outertokio::select! { biased; _ = caller.closed() => return, ... }inHostBridge::attach. It registers a secondHostSenderClosedwaker onCaller::waitingand adds anErrbranch that production never reaches (and tests don't exercise). Please remove the innerselect!. - For the two new tests (~149 lines vs. ~47 lines of production changes): the scenarios are worth covering, but both duplicate nearly identical
HostChannel/HostBridge::attach/Bundle::source/Headless::startsetup, and the first test reaches intoconnections["root"].subscriptions["stream"].1to spin in awhile !task.is_finished() { yield_now().await; }loop. Extracting a shared setup helper would tighten them up nicely.
- Keeping
-
Drop
nsh-gpufrom thenshCI suite (scripts/ci/suites.mjs)nsh-platform-macos,nsh-platform-linux, andnsh-platform-windowsall depend directly onnsh-gpu(withshaderenabled by default), soscripts/ci/plan.mjsalready routesnsh-gpuchanges tomacos-nsh,linux-nsh, andwindows-nshvia reverse dependencies (nooutside maintained suitesgap).- Meanwhile, the cross-platform
nshsuite currently builds withoutwgpu(nsh-engineruns withoutshader). Adding-p nsh-gpupulls the entirewgpu/wgpu-core/wgpu-hal/nagabuild graph into the lightweightnshsuite just to run 2 in-memory registry unit tests in a vendored crate. Best to drop this change fromsuites.mjs(or, if we really want those 2 tests run explicitly, attachnsh-gputo a platform suite that already compileswgpu).
中文
感谢把 #7338 里剩下的修复单独拆出来!底层要修的问题都是真实的,有 4 处收拾一下会更干净,也能避免漏掉同源路径:
-
FrameTarget::clear_layer()漏修了两个0×0尺寸同源路径(third-party/nsh/crates/nsh-engine/src/{frames,shader,gpu}.rs)- 另加一个
clear_layer(&mut self)只改了ShaderView::set_layer(None),把clear_frame(&mut self) -> bool原样留着没动。 - 整个
nsh-engine里clear_frame()一共只有 3 处调用:ShaderView::set_layer(None)、ShaderView::render的width == 0 || height == 0分支(shader.rs:1024),以及GpuViewrender的width == 0 || height == 0分支(gpu.rs:603)。 - 在 Apple / Windows 开启
show_on_surfaces(true)时,self.frame.width始终为0,帧存放在self.surfaces/self.previous中。不修clear_frame()会导致ShaderView或GpuView缩成0×0时旧的 IOSurface / SharedTexture 仍不释放,且clear_frame()错误返回false,使 macOS(display_frame)和 Windows(view.redraw())连重绘清帧都不会触发。 - 建议:删掉
clear_layer(),直接修clear_frame(&mut self) -> bool——同时take()清掉self.surfaces(Apple/Windows)和self.previous(Windows),并把shown_texture().is_some()折进返回值had。这样 3 个调用点一次全修,shader.rs生产代码一行不用动(vendored diff 更小);测试里顺手补一个0×0缩放断言即可同时覆盖两条路径。
- 另加一个
-
pub fn Keymap::gives_way不建议改成柯里化闭包(third-party/nsh/crates/nsh-core/src/keymap.rs、nsh-platform-linux/src/keymap.rs)- 返回
impl Fn(&KeyBinding) -> bool让单绑定调用点很别扭(Linux 端写成!table.gives_way(binding.keystroke, eligible)(binding)),还给公开 API 埋了隐式前提:返回的闭包默认调用方传入的binding一定满足binding.keystroke == key,传错键会静默套错规则。 - 建议:保持
gives_way为直白的布尔谓词pub fn gives_way(&self, binding: &KeyBinding, eligible: impl Fn(&KeyBinding) -> bool) -> bool(与上游原签名只差一个eligible参数),内部抽一个小私有 helper(或显式私有枚举)供gives_way和find_eligible共用,既保留find_eligible的 O(N) 单次扫描,也消除隐式契约。
- 返回
-
products/maka/ios-shell/src/bridge.rs:open_subscription里有冗余的tokio::select!,新增测试样板偏重register_subscription锁内的if sender.is_closed()是真正必要的(calls.subscribe().await返回后若state.lock().await无竞争不会挂起,外层select!没有机会重新 poll);MutationProgress::emit的is_closed()快速路径、把drop(subscription)提前到加锁之前、以及outcome改用Option<Result<(), RemoteClientError>>也都很干净。- 但
open_subscription里在calls.subscribe(...)外新套的那层tokio::select! { biased; _ = sender.closed() => ..., ... }与HostBridge::attach外层的tokio::select! { biased; _ = caller.closed() => return, ... }完全重复,多往Caller::waiting挂了一个无用 waker,且多出一条生产路径走不到(测试也没覆盖)的Err分支,建议直接删掉。 - 两个新增测试(约 149 行 vs 约 47 行生产改动)测的场景有价值,但重复搭了两遍几乎一样的
HostChannel/HostBridge::attach/Bundle::source/Headless::start样板,且第一个测试直接窥探内部connections["root"].subscriptions["stream"].1做while !task.is_finished() { yield_now().await; }忙等;建议抽公共 setup helper 把体积收紧。
-
建议撤回
scripts/ci/suites.mjs中把nsh-gpu加进nshsuite 的改动nsh-platform-macos、nsh-platform-linux、nsh-platform-windows全部直接依赖nsh-gpu(且默认开启shader),scripts/ci/plan.mjs会通过反向依赖自动把nsh-gpu的改动路由到macos-nsh/linux-nsh/windows-nsh,不会触发outside maintained suites。- 而跨平台轻量
nshsuite 目前不含任何wgpu依赖(nsh-engine默认不开shader)。把-p nsh-gpu塞进nsh会强行拉入整套wgpu/wgpu-core/wgpu-hal/naga编译依赖,只为跑 vendored crate 里 2 个纯内存注册表单元测试。建议直接删掉这 3 行(若确实想显式跑那 2 个单测,挂在本来就编wgpu的平台 suite 里更合适)。
YongGoose
left a comment
There was a problem hiding this comment.
The in-lock sender.is_closed() check in register_subscription is the real fix here, and it holds: HostChannel::attach closes the replaced caller before the new engine runs any JS, so a late registration from the old app always sees it closed and can no longer overwrite or abort the new app's same-ID stream. The keymap eligibility scoping and the shader clear_layer change look right to me across the platform callers. Could you fill in the template's AI use section and checklist? The commit carries Generated-by: Maka, and that trailer needs to survive the squash. Also, the summary line about tearing down stale subscriptions on reload describes behavior main already has; the change is the late-registration guard.
| assert!(view.surface().is_none(), "the cleared layer has no surface"); | ||
| assert!(!view.collect_frame(&renderer), "no stale frame can show"); |
There was a problem hiding this comment.
This assertion never runs in CI. No suite builds nsh-engine's own tests with the shader feature: the nsh suite tests -p nsh-engine without it, so shader.rs is swapped for shader_off.rs and frames.rs is cfg'd out, while macos-nsh only compiles nsh-engine/shader as a dependency and runs -p nsh-platform-apple -p nsh-platform-macos --lib. If set_layer(None) went back to clear_frame(), every job would stay green and a stale IOSurface would show again after the layer is cleared.
Since this PR already touches the nsh routing, could macos-nsh also run -p nsh-engine --features nsh-engine/shader --lib (or a filter narrowed to these tests)? One caveat: these tests return early with no GPU: skipped when Renderer::new returns None, so it's worth confirming the macOS runner actually gets a Metal device, otherwise the routed test still passes without checking anything.
| } | ||
|
|
||
| #[tokio::test(flavor = "multi_thread", worker_threads = 2)] | ||
| async fn replacing_the_app_closes_and_unregisters_its_live_subscription() { |
There was a problem hiding this comment.
nit: this test passes against main's bridge.rs unchanged. main's loop already does select! { biased; _ = caller.closed() => break None, next = subscription.next() => next }; dropping the pending next() drops the channel it took out of the RemoteSubscription, so the RPC stream closes, and the task then removes its own entry, so ios.unsubscribe returns cancelled:false. The final try_recv().is_err() can't fail either, since the server never sends an item after the replacement starts. detached_engine_subscriptions_do_not_reach_the_replacement_engine in tests/ios_shell_behaviors.rs already covers no events reaching the replacement and cancelled:false.
I'd drop this one, or move the one new assertion (the remote stream closes on reload) into that integration test. a_late_subscription_registration_cannot_replace_the_new_apps_stream is the test that fails without this change.
| let subscription = tokio::select! { | ||
| biased; | ||
| _ = sender.closed() => return Err("app closed during subscription setup".into()), | ||
| result = calls.subscribe(&rpc.endpoint, &rpc.method, rpc.input) => result.map_err(error)?, | ||
| }; |
There was a problem hiding this comment.
nit: this select duplicates the biased caller.closed() => return arm in the ios.subscribe handler, the only production caller. That arm watches the same Caller, is polled first, and drops this whole future when the app closes. The check that actually closes the race is the one under the lock in register_subscription.
| let subscription = tokio::select! { | |
| biased; | |
| _ = sender.closed() => return Err("app closed during subscription setup".into()), | |
| result = calls.subscribe(&rpc.endpoint, &rpc.method, rpc.input) => result.map_err(error)?, | |
| }; | |
| let subscription = calls | |
| .subscribe(&rpc.endpoint, &rpc.method, rpc.input) | |
| .await | |
| .map_err(error)?; |
| impl MutationProgress<'_> { | ||
| async fn emit(&self, bridge: &Bridge, root: &str, generation: u64, value: Value) { | ||
| if self.stalled.load(Ordering::Relaxed) { | ||
| if self.sender.is_closed() || self.stalled.load(Ordering::Relaxed) { |
There was a problem hiding this comment.
nit: the closed case is already handled below. HostSender::send returns Ok(false) for a closed caller, so sent doesn't advance, and the full-window path returns on self.sender.closed(). This only skips one lock acquisition, so I'd leave the original condition.
| if self.sender.is_closed() || self.stalled.load(Ordering::Relaxed) { | |
| if self.stalled.load(Ordering::Relaxed) { |
| let over = self.pointer_focus | ||
| /// opening its list). `eligible` must account for the current window, | ||
| /// focus scope and dispatch phase, also when GTK matches the keys itself. | ||
| pub fn gives_way( |
There was a problem hiding this comment.
nit: this changes the public Keymap::gives_way signature, and upstream longbridge/nsh still has gives_way(&self, binding: &KeyBinding) -> bool and no FrameTarget::clear_layer. Neither patch is recorded in third-party/nsh/SOURCE.md (#7338 listed the scoped gives_way() among the preserved patches). If they aren't recorded, the next three-way sync can take upstream's versions, and both bugs come back without a conflict to flag them. Could you note both under "Retained local capabilities"? Both bugs also exist upstream (the window-scope part and the stale surface), so sending the fixes upstream would remove the divergence altogether.
|
Thanks for the thorough review @M4n5ter! Rebased onto latest
Verified with |
d532ae0 to
6211273
Compare
M4n5ter
left a comment
There was a problem hiding this comment.
Automated Review · Reviewed at
621127385eusing Magpiecodex/gpt-6.2-sol(xhigh)
English
Verdict: Request Changes
The iOS bridge reload regressions pass, but a verified stale-frame bug remains on regular ShaderView resize-then-collapse before merge. Keep #7352 for finishing these remaining fixes on top of #7325.
Verified Findings
-
Blocker — Regular
ShaderViewstill leaves a stale frame onA → B → 0.
After sizeAhas presented, a non-zero resize toBreplaces the Apple surface pool. If the view collapses to0beforeBfinishes its first frame,clear_frame()sees no presented frame in the new pool,render()returnsfalse, and AppKit skipsdisplay_frame(). Reproduced with real Metal +CALayer(render_changed=false, layer_has_old_surface=true), which can leave stale content visible for effects withoverflow.
Fix: MirrorGpuViews::Presentationby havingShaderViewexplicitly track whether a frame has been presented to the platform, use that state when collapsing to schedule and emit the clear notification, and assertCALayer.contentsis cleared on the same sequence.
(frames.rs:118, shader.rs:1022, macos shader.rs:1543) -
Important — New rendering regressions are not wired into central CI execution.
Checked viaplan --base HEAD^and each suite's Cargo feature graph: Linuxnshselectsnsh-enginewithout theshaderfeature;macos-nshenablesshader, but only buildsnsh-engineas a dependency and runs only the menu branch ofnativetests. Wire the engine shader/GPU tests and AppKit resize test into a Metal-capable macOS job.
(suites.mjs:238, run.mjs:629) -
Nit — Stale PR description.
scripts/ci/suites.mjsis unchanged frommain(per the earlier comment removing thensh-gpusuite edit). Remove that bullet from the PR body, updateclear_layer()toclear_frame(), and describe the bridge fix accurately (a late registration from a closed app cannot overwrite/abort a reloaded app's same-ID subscription).
Test Quality & Local Verification
- Tests make up 332/568 added lines (58.5%). Keep the late-registration bridge test and the AppKit collapse-clear / re-expand redraw test. Merge the plain reload-disconnect test into the same reload scenario to drop redundant fixture setup. In the GPU consecutive-resize test, drop the internal
with_surface()-empty assertion and verify the platform clear notification directly. - Verified locally: iOS bridge
bridge::tests(12/12 passed),nsh-core/nsh-engine/nsh-gpuwithnsh-engine/shader(2078 / 102 / 2 passed; serial GPU rerun 5/5), AppKit collapse/expand + standalone Metal repro,nsh-platform-iossimulatorcargo check, CI routing (30/30), and iOS packaging (11/11). Full iOS Shell simulator build, GTK native keymap, and Windows GPU paths were not executed.
中文
结论:Request Changes
Bridge 的两个 reload 回归均已通过,但普通 ShaderView 在连续 resize 后折叠的残帧问题仍未闭合,需补齐后再合入。建议继续在 #7352 上收尾(保留已合入的 #7325)。
已验证的问题
-
Blocker — 普通
ShaderView在A → B → 0时仍会留下旧帧。
A 尺寸已上屏后,非零 resize 到 B 会先替换 Apple surface pool;B 的首帧尚未完成即折叠到 0 时,clear_frame()从新 pool 查不到已显示帧,render()返回false,AppKit 随之跳过display_frame()。已用真实 Metal +CALayer复现(render_changed=false, layer_has_old_surface=true),带overflow的 effect 在零尺寸下仍可能露出旧内容。
建议改法: 沿用GpuViews::Presentation的思路,让ShaderView显式记录已交付给平台的帧状态,折叠时据此决定调度并发出清屏通知,并在同一时序下断言CALayer.contents已清空。
(frames.rs:118, shader.rs:1022, macos shader.rs:1543) -
Important — 新增的渲染回归未接入中央 CI 执行路径。
实测plan --base HEAD^与各 suite 的 feature graph:Linuxnsh选中了nsh-engine但未开启shader;macos-nsh开启了shader,但nsh-engine仅作为依赖编译,且native测试只跑菜单分支。建议将 engine 的 shader/GPU 用例与 AppKit resize 用例接入具备 Metal 的 macOS job。
(suites.mjs:238, run.mjs:629) -
Nit — PR 正文残留旧版说明。
scripts/ci/suites.mjs与main一致(nsh-gpu已按先前评论撤出)。建议正文删掉该条 CI 变更,将clear_layer()更新为clear_frame(),并准确描述 bridge 修复点(旧 app 的迟到注册无法覆盖或中止新 app 的同 ID 订阅)。
测试质量与本地验证
- 测试占新增 332/568 行(58.5%)。建议保留迟到注册后新流正常收消息的 bridge 用例,以及 AppKit 折叠清屏/展开重绘用例;普通 reload 断开可并入同一 reload 场景减少重复 fixture;GPU 连续 resize 用例建议删掉「换 pool 后
with_surface()为空」的内部实现断言,直接验证平台收到清屏通知。 - 本地实测:iOS bridge
bridge::tests12/12 通过;nsh-core/nsh-engine/nsh-gpu(含nsh-engine/shader)2078 / 102 / 2 通过(GPU 串行复跑 5/5);AppKit 折叠/展开及独立 Metal 复现完成;nsh-platform-iossimulatorcargo check、CI 路由 30/30、iOS 打包 11/11 通过。完整 iOS Shell simulator 构建、GTK 原生按键与 Windows GPU 路径未实测。
Close idle Host streams and reject late registrations from a replaced app. Keep NSH pointer-focus overrides scoped to the eligible window, focus and dispatch phase. Retire shared GPU and shader frames on collapse even when a resize replaced the surface pool. Clear hidden AppKit layers, idle zero-area animations, and wake static GTK shaders on layout. Run the shader and AppKit regressions in the central macOS suite. Generated-by: Maka
6211273 to
c965795
Compare
Summary
Addresses review feedback and hardens
ShaderViewzero-size frame clearing, CI routing, and iOS bridge reload cleanup:ShaderViewzero-size clear & resize scheduling (nsh-engine, AppKit, GTK, Windows):has_presented_frame()) rather than guessing from the active surface pool soA → B pool swap → hidden → 0clears staleCALayer.contentseven before the view becomes visible again.nsh.timeanimated shaders after zero-size clear (wants_frame() == false) and wakes them cleanly upon re-expansion without spinning at zero size.screen_effectshaders before scheduling ticks across AppKit (main and independent windows), GTK, and Windows, and ensures GTKresized()updates size before callingtick().macos-nshandlinux-nshshader/GPU & AppKit resize test suites cleanly intoscripts/ci.mjswithout alteringthird-party/nsh/upstream.json.Verification
nsh-engineshader/GPU tests: 103 passed (including 16 shader + 5 GPU tests).nsh-platform-macosshader unit tests: 17 passed; AppKit main-thread Metal integration regressions: 3 passed (static fill collapse/expand redraw, hidden effect clear after pool swap, andnsh.timescreen_effectcollapse to0×240→ restore to320×240on the sameCALayer).maka-ios-shellbridge tests: 11 passed; NSH keymap tests: 19 passed.cargo fmt --check, ASF license headers, andgit diff --check origin/main...HEADall passed.Known test gaps