From 41a5ac1e4198b38e4b892be2bb7e6b2ac99586aa Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 30 Jul 2026 23:51:53 -0700 Subject: [PATCH 01/36] Test Pi managed extension refresh --- tests/test_pi_extension_install.py | 48 +++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index e12160f9e855..76ebab1bd09e 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -14,7 +14,12 @@ import time from pathlib import Path -from claude_teams_test_utils import install_pi_extension, resolve_cmux_cli +from claude_teams_test_utils import ( + FOCUSED_SURFACE_ID, + FOCUSED_WORKSPACE_ID, + install_pi_extension, + resolve_cmux_cli, +) def make_executable(path: Path, content: str) -> None: @@ -86,6 +91,47 @@ def main() -> int: print("FAIL: generated Pi extension does not import the current Pi package") return 1 + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n" + "// stale managed fixture using synchronous hook dispatch\n" + 'import { spawnSync } from "node:child_process";\n', + encoding="utf-8", + ) + refresh_env = os.environ.copy() + refresh_env["PI_CODING_AGENT_DIR"] = str(config_dir) + refresh_env["CMUX_WORKSPACE_ID"] = FOCUSED_WORKSPACE_ID + refresh_env["CMUX_SURFACE_ID"] = FOCUSED_SURFACE_ID + subprocess.run( + [ + cli_path, + "--socket", + str(root / "missing-pi-refresh.sock"), + "hooks", + "pi", + "session-start", + "--workspace", + FOCUSED_WORKSPACE_ID, + "--surface", + FOCUSED_SURFACE_ID, + ], + input=json.dumps( + { + "session_id": "pi-managed-extension-refresh", + "cwd": str(root), + "hook_event_name": "SessionStart", + "event": "SessionStart", + } + ), + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if extension_path.read_text(encoding="utf-8") != extension_text: + print("FAIL: Pi session-start did not refresh the stale cmux-managed extension") + return 1 + bin_dir = root / "bin" bin_dir.mkdir() fake_pi = bin_dir / "pi" From b2e2deeecba7bcf7f8d3c9bac474462c18f99fc7 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 30 Jul 2026 23:57:55 -0700 Subject: [PATCH 02/36] Refresh managed Pi extension on session start --- CLI/CMUXCLI+PiExtension.swift | 16 ++++++++++++++++ CLI/cmux.swift | 3 +++ 2 files changed, 19 insertions(+) diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift index 9ea3d8d04b6e..ee4fcbc507c4 100644 --- a/CLI/CMUXCLI+PiExtension.swift +++ b/CLI/CMUXCLI+PiExtension.swift @@ -26,6 +26,22 @@ extension CMUXCLI { } } + func refreshManagedPiExtensionIfNeeded(_ def: AgentHookDef) { + let extensionURL = piExtensionURL(for: def) + do { + let existing = try existingPiExtensionContents(at: extensionURL) + guard !existing.isEmpty, + existing.contains(Self.piExtensionMarker), + existing != Self.piExtensionSource + else { + return + } + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + } catch { + // Hook delivery must continue when a managed extension cannot be refreshed. + } + } + func installPiExtensionHooks(_ def: AgentHookDef) throws { let extensionURL = piExtensionURL(for: def) let fileManager = FileManager.default diff --git a/CLI/cmux.swift b/CLI/cmux.swift index d1e1af346e8d..d66750f9f1ad 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -35234,6 +35234,9 @@ export default CMUXSessionRestore; print(subcommandUsage("hooks") ?? "Usage: cmux hooks ") return true } + if def.name == "pi", action == "session-start" { + refreshManagedPiExtensionIfNeeded(def) + } let actionArgs = Array(rest.dropFirst()) switch action { case "inject-args" where def.name == "codex": From d5303e2222feba58c67092bea58d3fe74d4ba909 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 00:55:48 -0700 Subject: [PATCH 03/36] Test Pi lifecycle hook responsiveness --- tests/test_pi_extension_dispatch.py | 98 +++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index 0760424e84d7..40e272f21989 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -161,6 +161,103 @@ def check_responsiveness(bun: str, root: Path, extension_path: Path) -> int: return 0 +def check_ui_lifecycle_handlers_return_immediately( + bun: str, + root: Path, + extension_path: Path, +) -> int: + lifecycle_log = root / "ui-lifecycle-latency.log" + lifecycle_cmux = root / "ui-lifecycle-latency-cmux" + make_executable( + lifecycle_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf 'start %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" +sleep 0.15 +printf 'end %s\n' "$*" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" +printf '{"workspace_id":"00000000-0000-0000-0000-000000008673","surface_id":"00000000-0000-0000-0000-000000008672","resume_binding":{"kind":"pi","checkpoint_id":"pi-ui-latency-session"}}\n' +""", + ) + lifecycle_source = """ +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const ctx = { + cwd: "/tmp/pi-ui-latency-project", + isIdle() { return true; }, + sessionManager: { getSessionId() { return "pi-ui-latency-session"; } } +}; +async function measure(label, action) { + const startedAt = performance.now(); + await Promise.resolve(action()); + const elapsed = performance.now() - startedAt; + console.log(`${label}_ms=${elapsed}`); + if (elapsed >= 75) throw new Error(`${label} blocked Pi for ${elapsed}ms`); +} +await measure("session_start", () => handlers.get("session_start")({}, ctx)); +await measure("prompt_submit", () => handlers.get("before_agent_start")({ prompt: "hello" }, ctx)); +await measure("completion", () => handlers.get("agent_end")({ + messages: [{ role: "assistant", content: "done" }], + stopReason: "completed" +}, ctx)); + +const logPath = process.env.CMUX_TEST_PI_UI_LATENCY_LOG; +const deadline = performance.now() + 5000; +while (performance.now() < deadline) { + const text = await Bun.file(logPath).text(); + const completed = text.split("\\n").filter((line) => line.startsWith("end ")).length; + if (completed >= 6) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=lifecycle_cmux, + source=lifecycle_source, + extra_env={"CMUX_TEST_PI_UI_LATENCY_LOG": str(lifecycle_log)}, + ) + if result.returncode != 0: + print("FAIL: Pi UI lifecycle handler awaited cmux subprocess work") + print(f"exit={result.returncode}") + print(f"stdout={result.stdout.strip()}") + print(f"stderr={result.stderr.strip()}") + return 1 + + timings = {} + for line in result.stdout.splitlines(): + if "_ms=" not in line: + continue + key, value = line.split("=", 1) + timings[key] = float(value) + if set(timings) != {"session_start_ms", "prompt_submit_ms", "completion_ms"}: + print(f"FAIL: Pi UI lifecycle timing output was incomplete: {result.stdout!r}") + return 1 + if any(value >= 75 for value in timings.values()): + print(f"FAIL: Pi UI lifecycle handlers were observably blocking: {timings!r}") + return 1 + + calls = lifecycle_log.read_text(encoding="utf-8").splitlines() + completed = [line for line in calls if line.startswith("end ")] + expected = ( + "hooks pi session-start", + "--json surface resume set", + "--json surface resume get", + "hooks pi prompt-submit", + "hooks pi notification", + "hooks pi stop", + ) + if len(completed) != len(expected) or any( + command not in line for command, line in zip(expected, completed) + ): + print(f"FAIL: detached Pi lifecycle work lost command ordering: {calls!r}") + return 1 + return 0 + + def check_panel_only_target_fails_closed(bun: str, root: Path, extension_path: Path) -> int: marker = root / "panel-only-cmux-called" fake_cmux = root / "panel-only-cmux" @@ -2103,6 +2200,7 @@ def check_stale_surface(bun: str, root: Path, extension_path: Path) -> int: def run_checks(bun: str, root: Path, extension_path: Path) -> int: checks = ( check_responsiveness, + check_ui_lifecycle_handlers_return_immediately, check_panel_only_target_fails_closed, check_feed_backlog, check_terminal_feed_compaction, From 0994ab74c1d75824a25d983f7b7cfd2e19d2b0db Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 00:59:42 -0700 Subject: [PATCH 04/36] Detach Pi lifecycle hooks from UI events --- CLI/CMUXCLI+PiExtensionSourcePart2.swift | 55 +++++++++++++--- tests/test_pi_extension_dispatch.py | 84 +++++++++++++++++++++--- tests/test_pi_extension_install.py | 27 +++++--- 3 files changed, 137 insertions(+), 29 deletions(-) diff --git a/CLI/CMUXCLI+PiExtensionSourcePart2.swift b/CLI/CMUXCLI+PiExtensionSourcePart2.swift index 8cc92922fe38..1a6599770f97 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart2.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart2.swift @@ -366,8 +366,33 @@ async function publishPendingCompletion( export default function cmuxPiSessionExtension(pi: ExtensionAPI) { const dispatcher = new PiCmuxCommandDispatcher(); const sessionStates = new Map(); + const lifecycleTasks = new Set>(); + + const trackLifecycleTask = ( + task: Promise, + context: PiExtensionContextSnapshot, + ): void => { + let tracked: Promise; + tracked = task + .then(() => undefined) + .catch((error) => { + warn(context, "cmux lifecycle task failed", { + error_available: error !== undefined, + }); + }) + .finally(() => { + lifecycleTasks.delete(tracked); + }); + lifecycleTasks.add(tracked); + }; + + const drainLifecycleTasks = async (): Promise => { + while (lifecycleTasks.size > 0) { + await Promise.all([...lifecycleTasks]); + } + }; - pi.on("session_start", async (_event, ctx) => { + pi.on("session_start", (_event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; if (sessionId) { @@ -376,15 +401,20 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { state.feedDeliveryFailed = false; state.stopped = false; } - const ok = await sendHook(dispatcher, "session-start", context); - if (ok && sessionId) await ensureResumeBinding(dispatcher, context, sessionId); + trackLifecycleTask((async () => { + const ok = await sendHook(dispatcher, "session-start", context); + if (ok && sessionId) await ensureResumeBinding(dispatcher, context, sessionId); + })(), context); }); - pi.on("before_agent_start", async (event, ctx) => { + pi.on("before_agent_start", (event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; const turnId = sessionId ? beginTurn(sessionStates, sessionId, event) : undefined; - await sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }); + trackLifecycleTask( + sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }), + context, + ); }); pi.on("tool_execution_start", async (event, ctx) => { @@ -409,7 +439,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { sendFeed(dispatcher, sessionStates, "PostCompact", context, event); }); - pi.on("agent_end", async (event, ctx) => { + pi.on("agent_end", (event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; if (!sessionId) return; @@ -423,17 +453,23 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { }; // Older Pi versions do not emit agent_settled, so retain their established completion behavior. if (!supportsAgentSettled()) { - await publishPendingCompletion(dispatcher, sessionStates, context, sessionId); + trackLifecycleTask( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId), + context, + ); } }); - pi.on("agent_settled", async (_event, ctx) => { + pi.on("agent_settled", (_event, ctx) => { const context = snapshotContext(ctx); const isIdle = ctx.isIdle(); const sessionId = context.sessionId; if (!sessionId || !isIdle) return; // Consume pending completion before subprocess calls so duplicate settlement cannot notify twice. - await publishPendingCompletion(dispatcher, sessionStates, context, sessionId); + trackLifecycleTask( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId), + context, + ); }); pi.on("session_shutdown", async (event, ctx) => { @@ -449,6 +485,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { terminationReason: firstString(objectValue(event, ["reason"])) || "session_shutdown", }; } + await drainLifecycleTasks(); await dispatcher.finishFeedForSession(sessionId); const feedDelivered = !state.feedDeliveryFailed; state.feedDeliveryFailed = false; diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index 40e272f21989..efcc02b9ec1e 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -206,7 +206,10 @@ def check_ui_lifecycle_handlers_return_immediately( const logPath = process.env.CMUX_TEST_PI_UI_LATENCY_LOG; const deadline = performance.now() + 5000; while (performance.now() < deadline) { - const text = await Bun.file(logPath).text(); + let text = ""; + try { + text = await Bun.file(logPath).text(); + } catch (_) {} const completed = text.split("\\n").filter((line) => line.startsWith("end ")).length; if (completed >= 6) break; await new Promise((resolve) => setTimeout(resolve, 10)); @@ -250,8 +253,23 @@ def check_ui_lifecycle_handlers_return_immediately( "hooks pi notification", "hooks pi stop", ) - if len(completed) != len(expected) or any( - command not in line for command, line in zip(expected, completed) + indexes = { + command: [index for index, line in enumerate(completed) if command in line] + for command in expected + } + if ( + len(completed) != len(expected) + or any(len(found) != 1 for found in indexes.values()) + or not ( + indexes["hooks pi session-start"][0] + < indexes["hooks pi prompt-submit"][0] + < indexes["hooks pi notification"][0] + < indexes["hooks pi stop"][0] + ) + or not ( + indexes["--json surface resume set"][0] + < indexes["--json surface resume get"][0] + ) ): print(f"FAIL: detached Pi lifecycle work lost command ordering: {calls!r}") return 1 @@ -1211,7 +1229,14 @@ def check_completion_order(bun: str, root: Path, extension_path: Path) -> int: }, ctx); } const logPath = process.env.CMUX_TEST_PI_CANCELLATION_LOG; -while (!(await Bun.file(logPath).text()).includes("hooks feed")) { +async function readLog() { + try { + return await Bun.file(logPath).text(); + } catch (_) { + return ""; + } +} +while (!(await readLog()).includes("hooks feed")) { await new Promise((resolve) => setTimeout(resolve, 10)); } for (const index of [3, 1, 2, 0]) { @@ -1231,7 +1256,11 @@ def check_completion_order(bun: str, root: Path, extension_path: Path) -> int: toolName: "bash", result: { content: [{ type: "text", text: "late" }] } }, ctx); -await new Promise((resolve) => setTimeout(resolve, 250)); +const completionDeadline = performance.now() + 5000; +while (performance.now() < completionDeadline) { + if ((await readLog()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} """ completion = run_extension( bun=bun, @@ -1499,6 +1528,11 @@ def check_completion_drain_deadline(bun: str, root: Path, extension_path: Path) messages: [{ role: "assistant", content: "done" }], stopReason: "completed" }, ctx); +const completionDeadline = performance.now() + 5000; +while (performance.now() < completionDeadline) { + if ((await Bun.file(logPath).text()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} console.log(`ordered_completion_ms=${performance.now() - startedAt}`); """ ordered = run_extension( @@ -1605,6 +1639,11 @@ def handle_term(_signum, _frame): messages: [{ role: "assistant", content: "done" }], stopReason: "completed" }, ctx); +const completionDeadline = performance.now() + 6000; +while (performance.now() < completionDeadline) { + if ((await Bun.file(logPath).text()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} console.log(`completion_ms=${performance.now() - startedAt}`); """ deadline = run_extension( @@ -2058,6 +2097,16 @@ def check_runtime_isolation(bun: str, root: Path, extension_path: Path) -> int: { prompt: "healthy runtime" }, context("pi-runtime-healthy") ); +await Promise.all([ + staleHandlers.get("session_shutdown")( + { reason: "runtime isolation test" }, + context("pi-runtime-stale"), + ), + healthyHandlers.get("session_shutdown")( + { reason: "runtime isolation test" }, + context("pi-runtime-healthy"), + ), +]); """ runtime = run_extension( bun=bun, @@ -2071,7 +2120,13 @@ def check_runtime_isolation(bun: str, root: Path, extension_path: Path) -> int: print(f"FAIL: runtime-isolation harness failed: {runtime.stderr!r}") return 1 runtime_calls = runtime_log.read_text(encoding="utf-8").splitlines() - if len(runtime_calls) != 2 or "pi-runtime-healthy" not in runtime_calls[-1]: + prompt_calls = [line for line in runtime_calls if "hooks pi prompt-submit" in line] + prompt_sessions = { + session_id + for session_id in ("pi-runtime-stale", "pi-runtime-healthy") + if any(session_id in line for line in prompt_calls) + } + if len(prompt_calls) != 2 or prompt_sessions != {"pi-runtime-stale", "pi-runtime-healthy"}: print(f"FAIL: stale surface leaked across Pi extension runtimes: {runtime_calls!r}") return 1 @@ -2103,18 +2158,22 @@ def check_session_isolation_within_runtime(bun: str, root: Path, extension_path: cwd: "/tmp/pi-session-isolation-project", sessionManager: { getSessionId() { return sessionId; } }, }); +const staleContext = context("pi-session-stale"); +const healthyContext = context("pi-session-healthy"); await handlers.get("before_agent_start")( { prompt: "stale session" }, - context("pi-session-stale"), + staleContext, ); await handlers.get("before_agent_start")( { prompt: "stale session retry" }, - context("pi-session-stale"), + staleContext, ); await handlers.get("before_agent_start")( { prompt: "healthy session" }, - context("pi-session-healthy"), + healthyContext, ); +await handlers.get("session_shutdown")({ reason: "session isolation test" }, staleContext); +await handlers.get("session_shutdown")({ reason: "session isolation test" }, healthyContext); """ result = run_extension( bun=bun, @@ -2128,7 +2187,12 @@ def check_session_isolation_within_runtime(bun: str, root: Path, extension_path: print(f"FAIL: same-runtime session isolation harness failed: {result.stderr!r}") return 1 calls = session_log.read_text(encoding="utf-8").splitlines() - if len(calls) != 2 or "pi-session-healthy" not in calls[-1]: + prompt_calls = [line for line in calls if "hooks pi prompt-submit" in line] + if ( + len(prompt_calls) != 2 + or sum("pi-session-stale" in line for line in prompt_calls) != 1 + or sum("pi-session-healthy" in line for line in prompt_calls) != 1 + ): print(f"FAIL: stale surface disabled another Pi session in the same runtime: {calls!r}") return 1 return 0 diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index 76ebab1bd09e..d90e7e357e0b 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -46,9 +46,9 @@ def wait_for_text( def payloads_from_log(text: str) -> list[dict[str, object]]: payloads: list[dict[str, object]] = [] - for raw in text.split("\n---\n"): + for raw in text.splitlines(): raw = raw.strip() - if not raw: + if not raw or raw == "---": continue try: payload = json.loads(raw) @@ -177,8 +177,7 @@ def main() -> int: set -euo pipefail printf '%s\n' "$*" >> "$CMUX_TEST_PI_ARGS_LOG" payload="$(cat)" -printf '%s' "$payload" >> "$CMUX_TEST_PI_STDIN_LOG" -printf '\n---\n' >> "$CMUX_TEST_PI_STDIN_LOG" +printf '%s\n' "$payload" >> "$CMUX_TEST_PI_STDIN_LOG" { printf 'kind=%s\n' "${CMUX_AGENT_LAUNCH_KIND-}" printf 'cwd=%s\n' "${CMUX_AGENT_LAUNCH_CWD-}" @@ -316,6 +315,14 @@ def main() -> int: const lines = (await Bun.file(path).text()).split("\\n"); return lines.filter((line) => line.includes("hooks pi notification") || line.includes("hooks pi stop")).length; } +async function waitForCompletionHookCount(expectedCount) { + const deadline = Date.now() + 5000; + while (Date.now() < deadline) { + if (await completionHookCount() === expectedCount) return; + await Bun.sleep(10); + } + throw new Error(`timed out waiting for ${expectedCount} completion hooks`); +} async function waitForFeedEvent(eventName, expectedCount) { const path = process.env.CMUX_TEST_PI_ARGS_LOG; const deadline = Date.now() + 5000; @@ -418,7 +425,7 @@ def main() -> int: agentIdle = true; await handlers.get("agent_settled")({}, ctx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("agent_settled did not emit notification and stop"); +await waitForCompletionHookCount(completionCount); await handlers.get("agent_settled")({}, ctx); if (await completionHookCount() !== completionCount) throw new Error("duplicate agent_settled emitted completion twice"); await handlers.get("session_shutdown")({ reason: "quit" }, ctx); @@ -476,7 +483,7 @@ def main() -> int: if (await completionHookCount() !== completionCount) throw new Error("failed notification was attempted before settlement"); await handlers.get("agent_settled")({}, notificationFailureCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("settlement did not attempt failed notification and stop"); +await waitForCompletionHookCount(completionCount); await handlers.get("agent_settled")({}, notificationFailureCtx); if (await completionHookCount() !== completionCount) throw new Error("failed notification was retried after duplicate settlement"); process.argv.splice( @@ -500,7 +507,7 @@ def main() -> int: stopReason: "completed" }, legacyCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("legacy Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); process.argv.splice( 0, process.argv.length, @@ -522,7 +529,7 @@ def main() -> int: stopReason: "completed" }, unknownCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("unknown Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); process.argv.splice( 0, process.argv.length, @@ -544,7 +551,7 @@ def main() -> int: stopReason: "completed" }, malformedCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("malformed Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); """ check = subprocess.run( [bun, "--eval", check_source], @@ -570,7 +577,7 @@ def main() -> int: ) stdin_log = wait_for_text( fake_stdin_log, - 62, + 38, timeout=20.0, expected_substrings=('"hook_event_name":"PostToolUse"',), ) From 713bd781575defc051b06c6e87652910f07e8034 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 04:43:14 -0700 Subject: [PATCH 05/36] Test titlebar layout invalidation --- .../UpdatePillReleaseVisibilityTests.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index d875686420a2..264140d8b289 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -247,6 +247,41 @@ struct TitlebarControlsSizingPolicyTests { checkTrue(titlebarControlsShouldApplyLayout(previous: baseline, next: offsetChanged)) } + @Test + @MainActor + func testLayoutModelOnlyRecomputesForTitlebarInputs() { + let suiteName = "TitlebarControlsLayoutModel-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defer { defaults.removePersistentDomain(forName: suiteName) } + let notificationCenter = NotificationCenter() + var computationCount = 0 + let model = TitlebarControlsLayoutModel( + defaults: defaults, + notificationCenter: notificationCenter + ) { config in + computationCount += 1 + return NSSize(width: config.buttonSize, height: config.buttonSize) + } + + checkEqual(computationCount, 1) + checkEqual(model.snapshot.style, .classic) + + defaults.set(true, forKey: "unrelatedTitlebarTestSetting") + notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + checkEqual(computationCount, 1) + + defaults.set(TitlebarControlsStyle.compact.rawValue, forKey: TitlebarControlsStyle.storageKey) + notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + checkEqual(computationCount, 2) + checkEqual(model.snapshot.style, .compact) + + notificationCenter.post(name: KeyboardShortcutSettings.didChangeNotification, object: nil) + checkEqual(computationCount, 3) + + notificationCenter.post(name: GlobalFontMagnification.didChangeNotification, object: nil) + checkEqual(computationCount, 4) + } + @Test func testTitlebarControlsListenForWindowGeometryChanges() { checkTrue(TitlebarWindowGeometryNotifications.names.contains(NSWindow.didResizeNotification)) From 92cba432aa3fa10d20c3bfbb0849496f4d58952e Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 09:22:16 -0700 Subject: [PATCH 06/36] Cache titlebar layout inputs --- Sources/ContentView.swift | 9 +- ...alModeSidebarTitlebarControlsOverlay.swift | 4 +- Sources/Update/UpdateTitlebarAccessory.swift | 186 ++++++++++++++---- 3 files changed, 156 insertions(+), 43 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 69d0b70ed260..2bfade652933 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -828,6 +828,7 @@ struct ContentView: View { // stays available as an unobserved singleton for actions and pass-down. @EnvironmentObject var sidebarUnread: SidebarUnreadModel var notificationStore: TerminalNotificationStore { .shared } + @ObservedObject private var titlebarControlsLayoutModel = TitlebarControlsLayoutModel.shared @EnvironmentObject var sidebarState: SidebarState @EnvironmentObject var sidebarSelectionState: SidebarSelectionState @EnvironmentObject var cmuxConfigStore: CmuxConfigStore @@ -2029,7 +2030,8 @@ struct ContentView: View { } private var fullscreenControls: some View { TitlebarControlsView( - notificationStore: TerminalNotificationStore.shared, + unreadModel: sidebarUnread, + layoutModel: titlebarControlsLayoutModel, viewModel: fullscreenControlsViewModel, onToggleSidebar: { sidebarState.toggle() }, onToggleNotifications: { [fullscreenControlsViewModel] in @@ -2063,8 +2065,7 @@ struct ContentView: View { /// Used to reserve space in the title row so the title flows to the right of /// the controls, which are themselves mounted once in the band overlay. private var fullscreenControlsWidth: CGFloat { - let style = TitlebarControlsStyle.stored(rawValue: titlebarControlsStyleRawValue) - return TitlebarControlsLayoutMetrics.contentSize(config: style.config).width + titlebarControlsLayoutModel.snapshot.contentSize.width } private var titlebarDebugChromeSnapshot: MinimalModeTitlebarDebugSnapshot { @@ -10773,7 +10774,7 @@ struct VerticalTabsSidebar: View, Equatable { private func minimalModeSidebarTitlebarControlsOverlay() -> some View { MinimalModeSidebarTitlebarControlsOverlay( - notificationStore: notificationStore, + unreadModel: sidebarUnread, leadingInset: CGFloat(titlebarDebugChromeSnapshot.leftControlsLeadingInset), topPadding: minimalModeSidebarTitlebarControlsTopPadding, onToggleSidebar: onToggleSidebar, diff --git a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift index 830cdb348947..78302cfbf1da 100644 --- a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift +++ b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift @@ -2,7 +2,7 @@ import AppKit import SwiftUI struct MinimalModeSidebarTitlebarControlsOverlay: View { - let notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel let leadingInset: CGFloat let topPadding: CGFloat let onToggleSidebar: () -> Void @@ -21,7 +21,7 @@ struct MinimalModeSidebarTitlebarControlsOverlay: View { var body: some View { if isMinimalMode { HiddenTitlebarSidebarControlsView( - notificationStore: notificationStore, + unreadModel: unreadModel, onToggleSidebar: onToggleSidebar, onToggleNotifications: onToggleNotifications, onNewTab: onNewTab, diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 2a13419c3c1d..aaf3451779a5 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -139,6 +139,96 @@ struct TitlebarControlsStyleConfig { let hoverBackground: Bool } +struct TitlebarControlsLayoutModelSnapshot: Equatable { + let style: TitlebarControlsStyle + let contentSize: NSSize + let revision: UInt64 +} + +/// Owns the expensive shortcut/font-derived titlebar size once for every +/// titlebar surface. Unrelated defaults and notification activity must not +/// invalidate titlebar geometry. +@MainActor +final class TitlebarControlsLayoutModel: ObservableObject { + typealias ContentSizeProvider = (TitlebarControlsStyleConfig) -> NSSize + + static let shared = TitlebarControlsLayoutModel() + + @Published private(set) var snapshot: TitlebarControlsLayoutModelSnapshot + + private let defaults: UserDefaults + private let notificationCenter: NotificationCenter + private let contentSizeProvider: ContentSizeProvider + private var observers: [NSObjectProtocol] = [] + + init( + defaults: UserDefaults = .standard, + notificationCenter: NotificationCenter = .default, + contentSizeProvider: @escaping ContentSizeProvider = { + TitlebarControlsLayoutMetrics.contentSize(config: $0) + } + ) { + self.defaults = defaults + self.notificationCenter = notificationCenter + self.contentSizeProvider = contentSizeProvider + let style = TitlebarControlsStyle.stored(in: defaults) + snapshot = TitlebarControlsLayoutModelSnapshot( + style: style, + contentSize: contentSizeProvider(style.config), + revision: 0 + ) + + observers.append( + notificationCenter.addObserver( + forName: UserDefaults.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.refreshStyleIfNeeded() + } + } + ) + for name in [ + KeyboardShortcutSettings.didChangeNotification, + GlobalFontMagnification.didChangeNotification, + ] { + observers.append( + notificationCenter.addObserver( + forName: name, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.recompute() + } + } + ) + } + } + + deinit { + for observer in observers { + notificationCenter.removeObserver(observer) + } + } + + private func refreshStyleIfNeeded() { + let style = TitlebarControlsStyle.stored(in: defaults) + guard style != snapshot.style else { return } + recompute(style: style) + } + + private func recompute(style: TitlebarControlsStyle? = nil) { + let style = style ?? snapshot.style + snapshot = TitlebarControlsLayoutModelSnapshot( + style: style, + contentSize: contentSizeProvider(style.config), + revision: snapshot.revision &+ 1 + ) + } +} + enum TitlebarControlsVisualMetrics { static let verticalLift: CGFloat = 0 @@ -869,8 +959,31 @@ private final class TitlebarControlRightClickNSView: NSView { } } +private struct TitlebarNotificationBadge: View { + @ObservedObject var unreadModel: SidebarUnreadModel + let config: TitlebarControlsStyleConfig + @Environment(\.cmuxGlobalFontMagnificationPercent) private var globalFontPercent + + var body: some View { + let unreadCount = unreadModel.totalUnreadCount + if unreadCount > 0 { + Text("\(min(unreadCount, 99))") + .cmuxFont( + size: titlebarNotificationBadgeFontSize(for: config) + / max(1, GlobalFontMagnification.scale(for: globalFontPercent)), + weight: .semibold + ) + .foregroundColor(.white) + .frame(width: config.badgeSize, height: config.badgeSize) + .background(Circle().fill(cmuxAccentColor())) + .offset(x: config.badgeOffset.width, y: config.badgeOffset.height) + } + } +} + struct TitlebarControlsView: View { - @ObservedObject var notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel + @ObservedObject var layoutModel: TitlebarControlsLayoutModel @ObservedObject var viewModel: TitlebarControlsViewModel let onToggleSidebar: () -> Void let onToggleNotifications: () -> Void @@ -879,9 +992,6 @@ struct TitlebarControlsView: View { let onFocusHistoryForward: () -> Void let visibilityMode: TitlebarControlsVisibilityMode @ObservedObject private var popoverVisibilityState = NotificationsPopoverVisibilityState.shared - @AppStorage(TitlebarControlsStyle.storageKey) private var styleRawValue = TitlebarControlsStyle.defaultRawValue - @Environment(\.cmuxGlobalFontMagnificationPercent) private var globalFontPercent - @State private var shortcutRefreshTick = 0 @State private var appearanceRefreshTick = 0 @State private var isHoveringControls = false @State private var hostWindowNumber: Int? @@ -927,17 +1037,11 @@ struct TitlebarControlsView: View { } var body: some View { - // Force the `.safeHelp(...)` tooltips to re-evaluate when shortcuts are changed in settings. - // (The titlebar controls don't otherwise re-render on UserDefaults changes.) - let _ = shortcutRefreshTick let _ = appearanceRefreshTick - let _ = globalFontPercent - let style = TitlebarControlsStyle.stored(rawValue: styleRawValue) + let layoutSnapshot = layoutModel.snapshot + let style = layoutSnapshot.style let config = style.config - let contentSize = TitlebarControlsLayoutMetrics.contentSize( - config: config, - titlebarShortcutHintXOffset: titlebarShortcutHintXOffset - ) + let contentSize = layoutSnapshot.contentSize let foregroundColor = Color(nsColor: titlebarControlForegroundNSColor(opacity: 1.0)) controlsGroup(config: config, foregroundColor: foregroundColor) .padding(.leading, TitlebarControlsLayoutMetrics.hintLeadingPadding) @@ -966,9 +1070,6 @@ struct TitlebarControlsView: View { .onHover { hovering in isHoveringControls = hovering } - .onReceive(NotificationCenter.default.publisher(for: KeyboardShortcutSettings.didChangeNotification)) { _ in - shortcutRefreshTick &+= 1 - } .onReceive(NotificationCenter.default.publisher(for: .tabManagerFocusHistoryRevisionDidChange)) { _ in focusHistoryAvailabilityRevision &+= 1 } @@ -1007,7 +1108,6 @@ struct TitlebarControlsView: View { private func controlsGroup(config: TitlebarControlsStyleConfig, foregroundColor: Color) -> some View { let hintLayoutItems = titlebarHintLayoutItems(config: config) let focusHistoryAvailability = focusHistoryNavigationAvailabilitySnapshot - let badgeBaseFontSize = titlebarNotificationBadgeFontSize(for: config) / max(1, GlobalFontMagnification.scale(for: globalFontPercent)) let content = HStack(spacing: config.spacing) { TitlebarControlButton( config: config, @@ -1045,15 +1145,7 @@ struct TitlebarControlsView: View { iconGeometryKeyPrefix: "titlebarControl_showNotificationsIcon" ) - if notificationStore.unreadCount > 0 { - Text("\(min(notificationStore.unreadCount, 99))") - // Fixed-size badge; cap effective glyph size. - .cmuxFont(size: badgeBaseFontSize, weight: .semibold) - .foregroundColor(.white) - .frame(width: config.badgeSize, height: config.badgeSize) - .background(Circle().fill(cmuxAccentColor())) - .offset(x: config.badgeOffset.width, y: config.badgeOffset.height) - } + TitlebarNotificationBadge(unreadModel: unreadModel, config: config) } .frame(width: config.buttonSize, height: config.buttonSize) } @@ -1385,7 +1477,7 @@ private struct MinimalModeTitlebarButtonHitRegionView: NSViewRepresentable { } struct HiddenTitlebarSidebarControlsView: View { - @ObservedObject var notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel let onToggleSidebar: () -> Void let onToggleNotifications: (NSView?) -> Void let onNewTab: () -> Void @@ -1396,14 +1488,14 @@ struct HiddenTitlebarSidebarControlsView: View { @State private var isHoveringHost = false @State private var isHoveringWindowChrome = false @State private var hostWindowNumber: Int? - @AppStorage(TitlebarControlsStyle.storageKey) private var styleRawValue = TitlebarControlsStyle.defaultRawValue + @ObservedObject private var layoutModel = TitlebarControlsLayoutModel.shared private var shouldPinControls: Bool { isHoveringHost || isHoveringWindowChrome || popoverVisibilityState.isShown(in: hostWindowNumber) } var body: some View { - let style = TitlebarControlsStyle.stored(rawValue: styleRawValue) + let style = layoutModel.snapshot.style ZStack(alignment: .leading) { WindowAccessor { window in @@ -1436,7 +1528,8 @@ struct HiddenTitlebarSidebarControlsView: View { .allowsHitTesting(false) TitlebarControlsView( - notificationStore: notificationStore, + unreadModel: unreadModel, + layoutModel: layoutModel, viewModel: viewModel, onToggleSidebar: onToggleSidebar, onToggleNotifications: { [viewModel] in @@ -1790,6 +1883,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private let hostingView: NonDraggableHostingView private let containerView: NSView private let notificationStore: TerminalNotificationStore + private let layoutModel: TitlebarControlsLayoutModel private lazy var notificationsPopover: NSPopover = makeNotificationsPopover() private var pendingSizeUpdate = false private var intrinsicSizeNeedsRefresh = true @@ -1800,13 +1894,17 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private var windowGeometryObservers: [NSObjectProtocol] = [] private let viewModel = TitlebarControlsViewModel() private var userDefaultsObserver: NSObjectProtocol? + private var layoutModelCancellable: AnyCancellable? + private var lastShowsWorkspaceTitlebar = !WorkspacePresentationModeSettings.isMinimal() var popoverIsShownForTesting: Bool { notificationsPopover.isShown } private var showsWorkspaceTitlebar: Bool { !WorkspacePresentationModeSettings.isMinimal() } init(notificationStore: TerminalNotificationStore, settingsRuntime: SettingsRuntime?) { let containerView = TitlebarAccessoryContainerView() + let layoutModel = TitlebarControlsLayoutModel.shared self.containerView = containerView self.notificationStore = notificationStore + self.layoutModel = layoutModel let toggleSidebar = { [weak containerView] in _ = AppDelegate.shared?.toggleSidebarInActiveMainWindow(preferredWindow: containerView?.window) } @@ -1821,7 +1919,8 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont _ = AppDelegate.shared?.activeTabManagerForCommands(preferredWindow: containerView?.window)?.navigateForward() } let rootView = TitlebarControlsView( - notificationStore: notificationStore, + unreadModel: notificationStore.sidebarUnread, + layoutModel: layoutModel, viewModel: viewModel, onToggleSidebar: toggleSidebar, onToggleNotifications: toggleNotifications, @@ -1862,12 +1961,25 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont object: nil, queue: .main ) { [weak self] _ in - self?.applyWorkspaceTitlebarVisibility() - if self?.showsWorkspaceTitlebar == true { - self?.restoreSizeAfterMinimalMode() - self?.scheduleSizeUpdate() + guard let self else { return } + let shouldShow = self.showsWorkspaceTitlebar + guard shouldShow != self.lastShowsWorkspaceTitlebar else { return } + self.applyWorkspaceTitlebarVisibility() + if shouldShow { + self.restoreSizeAfterMinimalMode() } } + layoutModelCancellable = layoutModel.$snapshot + .dropFirst() + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + MainActor.assumeIsolated { + self?.scheduleSizeUpdate( + invalidateIntrinsicSize: true, + invalidateLayout: true + ) + } + } applyWorkspaceTitlebarVisibility() scheduleSizeUpdate(invalidateIntrinsicSize: true) @@ -1951,8 +2063,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont updateObservedWindowIfNeeded() applyWorkspaceTitlebarVisibility() guard showsWorkspaceTitlebar else { return } - let style = TitlebarControlsStyle.stored() - let contentSize = TitlebarControlsLayoutMetrics.contentSize(config: style.config) + let contentSize = layoutModel.snapshot.contentSize if intrinsicSizeNeedsRefresh { hostingView.invalidateIntrinsicContentSize() intrinsicSizeNeedsRefresh = false @@ -2009,6 +2120,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private func applyWorkspaceTitlebarVisibility() { let shouldShow = showsWorkspaceTitlebar + lastShowsWorkspaceTitlebar = shouldShow self.isHidden = !shouldShow view.isHidden = !shouldShow view.alphaValue = shouldShow ? 1 : 0 From 6fed64d00d62c8478cd912a9ab23efb751b928f1 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 10:38:17 -0700 Subject: [PATCH 07/36] Test unread invalidation scope --- .../WorkspaceContentViewVisibilityTests.swift | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index 94000bd5c1e5..c157e24e9a41 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -1,5 +1,6 @@ import Testing import AppKit +import Combine import CmuxUpdater import CoreGraphics import SwiftUI @@ -257,6 +258,132 @@ final class WorkspaceContentViewVisibilityTests { ) } + @Test + @MainActor + func testUnreadChangeDoesNotReevaluateContentViewRoot() async throws { + _ = NSApplication.shared + + let suiteName = "WorkspaceContentViewUnreadTests.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + defer { + defaults.removePersistentDomain(forName: suiteName) + } + defaults.set( + CmuxExtensionSidebarSelection.defaultProviderId, + forKey: CmuxExtensionSidebarSelection.defaultsKey + ) + + let tabManager = TabManager() + let workspaceId = try #require(tabManager.selectedTabId) + let unread = SidebarUnreadModel() + let counts = MinimalModeBodyProbeCounts() + let root = ContentView(updateViewModel: UpdateStateModel(), windowId: UUID()) + .environmentObject(tabManager) + .environmentObject(TerminalNotificationStore.shared) + .environmentObject(unread) + .environmentObject(SidebarState()) + .environmentObject(SidebarSelectionState()) + .environmentObject(FileExplorerState()) + .environmentObject(CmuxConfigStore()) + .environment( + \.minimalModeInvalidationProbe, + MinimalModeInvalidationProbe( + contentViewBody: { counts.contentViewBody += 1 }, + workspaceContentBody: { counts.workspaceContentBody += 1 }, + verticalTabsSidebarBody: { counts.verticalTabsSidebarBody += 1 } + ) + ) + .defaultAppStorage(defaults) + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 900, height: 640), + styleMask: [.titled, .closable, .resizable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = MainWindowHostingView(rootView: root) + defer { + window.contentView = nil + window.close() + } + + await Self.drainMainRunLoop(for: window) + counts.reset() + + unread.apply( + totalUnreadCount: 1, + summaries: [ + workspaceId: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [ + SidebarSurfaceUnreadKey(workspaceId: workspaceId, surfaceId: nil), + ], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + await Self.drainMainRunLoop(for: window) + + #expect( + counts.contentViewBody == 0, + "Unread changes must update their leaf consumers without rebuilding ContentView." + ) + #expect( + counts.workspaceContentBody == 0, + "Unread changes must not rebuild terminal or browser content." + ) + #expect( + counts.verticalTabsSidebarBody > 0, + "The sidebar must still receive the unread change." + ) + } + + @Test + @MainActor + func testUnreadApplyPublishesOneAtomicSnapshot() { + let workspaceId = UUID() + let surfaceId = UUID() + let unread = SidebarUnreadModel() + var publicationCount = 0 + let cancellable = unread.objectWillChange.sink { + publicationCount += 1 + } + let summaries = [ + workspaceId: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ] + let surfaceKeys: Set = [ + SidebarSurfaceUnreadKey(workspaceId: workspaceId, surfaceId: surfaceId), + ] + let focusedIndicators = [workspaceId: surfaceId] + let manualUnreadWorkspaceIds: Set = [workspaceId] + + unread.apply( + totalUnreadCount: 1, + summaries: summaries, + unreadSurfaceKeys: surfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedIndicators, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + #expect(publicationCount == 1) + + unread.apply( + totalUnreadCount: 1, + summaries: summaries, + unreadSurfaceKeys: surfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedIndicators, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + #expect(publicationCount == 1, "Applying an equivalent snapshot must stay silent.") + withExtendedLifetime(cancellable) {} + } + @MainActor private static func drainMainRunLoop(for window: NSWindow, iterations: Int = 20) async { for _ in 0.. Date: Fri, 31 Jul 2026 12:03:09 -0700 Subject: [PATCH 08/36] Scope unread invalidation to leaf views --- Sources/ContentView.swift | 41 +++++--- Sources/DockUnreadPanelProjection.swift | 14 ++- Sources/TerminalNotificationStore.swift | 125 ++++++++++++++++------- cmuxTests/FileDropOverlayViewTests.swift | 2 +- 4 files changed, 122 insertions(+), 60 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 2bfade652933..f514bb7aa4e2 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -820,14 +820,11 @@ struct ContentView: View { } @EnvironmentObject var tabManager: TabManager - // ContentView observes the coalesced unread projection, NOT the notification - // store. Reading `notificationStore` directly here would re-render the entire - // content view + sidebar on every notification publish (terminal/agent - // activity), which reconstructs every workspace row and starves the main - // thread (issue #2586 class; surfaced as scroll lag). `notificationStore` - // stays available as an unobserved singleton for actions and pass-down. - @EnvironmentObject var sidebarUnread: SidebarUnreadModel + // Unread state is read imperatively by actions and passed to leaf observers. + // ContentView itself must not observe it: one agent notification would + // otherwise rebuild the terminal, sidebar, and window chrome together. var notificationStore: TerminalNotificationStore { .shared } + var sidebarUnread: SidebarUnreadModel { notificationStore.sidebarUnread } @ObservedObject private var titlebarControlsLayoutModel = TitlebarControlsLayoutModel.shared @EnvironmentObject var sidebarState: SidebarState @EnvironmentObject var sidebarSelectionState: SidebarSelectionState @@ -1015,8 +1012,12 @@ struct ContentView: View { return exactFitsWithinPane ? exactRect : paneRect } - private func tmuxWorkspacePaneWindowOverlayState(for window: NSWindow) -> TmuxWorkspacePaneOverlayRenderState? { + private func tmuxWorkspacePaneWindowOverlayState( + for window: NSWindow, + unreadSnapshot explicitUnreadSnapshot: SidebarUnreadSnapshot? = nil + ) -> TmuxWorkspacePaneOverlayRenderState? { guard let workspace = tabManager.selectedWorkspace else { return nil } + let unreadSnapshot = explicitUnreadSnapshot ?? sidebarUnread.snapshot let usesWorkspacePaneOverlay = TmuxOverlayExperimentSettings.target().usesWorkspacePaneOverlay let resolvedActivePaneBorderColorHex = WorkspaceTabColorSettings.normalizedHex(activePaneBorderColorHex) let shouldShowActivePaneBorder = shouldShowActivePaneBorder(for: workspace, colorHex: resolvedActivePaneBorderColorHex) @@ -1030,7 +1031,7 @@ struct ContentView: View { let unreadRects: [CGRect] if usesWorkspacePaneOverlay { - let isWorkspaceManuallyUnread = sidebarUnread.hasManualUnread(forWorkspaceId: workspace.id) + let isWorkspaceManuallyUnread = unreadSnapshot.hasManualUnread(forWorkspaceId: workspace.id) let workspaceManualUnreadPanelId = workspace.representativePanelIdForWorkspaceManualUnread() if let layoutSnapshot, let contentView { unreadRects = layoutSnapshot.panes.compactMap { pane in @@ -1042,7 +1043,7 @@ struct ContentView: View { } let shouldShowUnread = Workspace.shouldShowUnreadIndicator( - hasUnreadNotification: sidebarUnread.hasVisibleNotificationIndicator( + hasUnreadNotification: unreadSnapshot.hasVisibleNotificationIndicator( forWorkspaceId: workspace.id, surfaceId: panelId ), @@ -1139,9 +1140,15 @@ struct ContentView: View { ) } - private func refreshTmuxWorkspacePaneWindowOverlay(in window: NSWindow?) { + private func refreshTmuxWorkspacePaneWindowOverlay( + in window: NSWindow?, + unreadSnapshot: SidebarUnreadSnapshot? = nil + ) { guard let window else { return } - let tmuxOverlayState = tmuxWorkspacePaneWindowOverlayState(for: window) + let tmuxOverlayState = tmuxWorkspacePaneWindowOverlayState( + for: window, + unreadSnapshot: unreadSnapshot + ) WindowTmuxWorkspacePaneOverlayController.controller( for: window, createIfNeeded: tmuxOverlayState != nil @@ -2840,6 +2847,16 @@ struct ContentView: View { scheduleTitlebarTextRefresh() }) + view = AnyView(view.onReceive(sidebarUnread.$snapshot.dropFirst()) { snapshot in + // Update the AppKit-owned pane overlay directly. The titlebar badge + // and sidebar rows observe their own leaves, so no ContentView state + // mutation is needed for unread changes. + refreshTmuxWorkspacePaneWindowOverlay( + in: observedWindow, + unreadSnapshot: snapshot + ) + }) + view = AnyView(view.onReceive(NotificationCenter.default.publisher(for: .workspacePaneGeometryDidChange)) { notification in guard let tabId = notification.userInfo?[GhosttyNotificationKey.tabId] as? UUID, tabId == tabManager.selectedTabId else { return } diff --git a/Sources/DockUnreadPanelProjection.swift b/Sources/DockUnreadPanelProjection.swift index 1e4b5d5b9679..ea5aac982274 100644 --- a/Sources/DockUnreadPanelProjection.swift +++ b/Sources/DockUnreadPanelProjection.swift @@ -25,18 +25,16 @@ final class DockUnreadPanelProjection { self.workspaceID = workspaceID self.panelIDs = panelIDs self.isActive = isActive - unreadSurfaceKeys = source.unreadSurfaceKeys - focusedReadIndicatorByWorkspaceID = source.focusedReadIndicatorByWorkspaceId + unreadSurfaceKeys = source.snapshot.unreadSurfaceKeys + focusedReadIndicatorByWorkspaceID = source.snapshot.focusedReadIndicatorByWorkspaceId refresh() - unreadSubscription = source.$unreadSurfaceKeys.combineLatest( - source.$focusedReadIndicatorByWorkspaceId - ).sink { [weak self] unreadSurfaceKeys, focusedReadIndicatorByWorkspaceID in - // Both publishers are main-actor-owned and publish synchronously + unreadSubscription = source.$snapshot.sink { [weak self] snapshot in + // The publisher is main-actor-owned and emits one complete value // from SidebarUnreadModel.apply(). MainActor.assumeIsolated { self?.receive( - unreadSurfaceKeys: unreadSurfaceKeys, - focusedReadIndicatorByWorkspaceID: focusedReadIndicatorByWorkspaceID + unreadSurfaceKeys: snapshot.unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceID: snapshot.focusedReadIndicatorByWorkspaceId ) } } diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 1c8858e9ffaa..6e806d56e926 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -1,5 +1,6 @@ import CmuxFoundation import AppKit +import Combine import Foundation import os import UserNotifications @@ -2325,22 +2326,75 @@ struct SidebarSurfaceUnreadKey: Hashable { var surfaceId: UUID? } -/// Lightweight observable that the workspace sidebar and `ContentView` observe -/// instead of `TerminalNotificationStore`. `TerminalNotificationStore` drives it -/// from its single `refreshUnreadPresentation()` coalescing hub with equality -/// guards, so notification activity that does not change any workspace's badge, -/// latest-text, per-surface unread, or read-indicator never fires -/// `objectWillChange` here. That is what stops high-frequency notification churn -/// from re-rendering the workspace list (issue #2586 class of sidebar re-render -/// spins). The query methods mirror the equivalent `TerminalNotificationStore` -/// reads exactly so callers can switch source without behavior change. +/// One atomic unread-state publication. A single notification can change the +/// total, workspace summary, and surface indicator together; publishing those +/// fields independently makes every observer render several intermediate +/// states for one logical update. +struct SidebarUnreadSnapshot: Equatable { + var totalUnreadCount: Int = 0 + var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:] + var unreadSurfaceKeys: Set = [] + var focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:] + var manualUnreadWorkspaceIds: Set = [] + + func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { + summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary( + unreadCount: 0, + latestNotificationText: nil + ) + } + + func unreadCount(forWorkspaceId id: UUID) -> Int { + summary(forWorkspaceId: id).unreadCount + } + + func latestNotificationText(forWorkspaceId id: UUID) -> String? { + summary(forWorkspaceId: id).latestNotificationText + } + + func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { + unreadCount(forWorkspaceId: id) > 0 + } + + func hasManualUnread(forWorkspaceId id: UUID) -> Bool { + manualUnreadWorkspaceIds.contains(id) + } + + func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) + } + + func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || + (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) + } + + func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { workspaceIsUnread(forWorkspaceId: $0) } + } + + func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } + } +} + +/// Lightweight observable for leaf unread consumers such as the workspace +/// sidebar and titlebar badge. `TerminalNotificationStore` drives it from its +/// single `refreshUnreadPresentation()` hub with one atomic, equality-guarded +/// snapshot, so one logical notification cannot publish several intermediate +/// renders. `ContentView` deliberately keeps an unobserved reference and routes +/// pane-overlay updates directly. The query methods mirror the equivalent +/// `TerminalNotificationStore` reads so callers can switch source without a +/// behavior change. @MainActor final class SidebarUnreadModel: ObservableObject { - @Published private(set) var totalUnreadCount: Int = 0 - @Published private(set) var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:] - @Published private(set) var unreadSurfaceKeys: Set = [] - @Published private(set) var focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:] - @Published private(set) var manualUnreadWorkspaceIds: Set = [] + @Published private(set) var snapshot = SidebarUnreadSnapshot() + + var totalUnreadCount: Int { snapshot.totalUnreadCount } + var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] { snapshot.summaryByWorkspaceId } + var unreadSurfaceKeys: Set { snapshot.unreadSurfaceKeys } + var focusedReadIndicatorByWorkspaceId: [UUID: UUID] { snapshot.focusedReadIndicatorByWorkspaceId } + var manualUnreadWorkspaceIds: Set { snapshot.manualUnreadWorkspaceIds } func apply( totalUnreadCount: Int, @@ -2349,57 +2403,50 @@ final class SidebarUnreadModel: ObservableObject { focusedReadIndicatorByWorkspaceId: [UUID: UUID], manualUnreadWorkspaceIds: Set ) { - if self.totalUnreadCount != totalUnreadCount { - self.totalUnreadCount = totalUnreadCount - } - if summaryByWorkspaceId != summaries { - summaryByWorkspaceId = summaries - } - if self.unreadSurfaceKeys != unreadSurfaceKeys { - self.unreadSurfaceKeys = unreadSurfaceKeys - } - if self.focusedReadIndicatorByWorkspaceId != focusedReadIndicatorByWorkspaceId { - self.focusedReadIndicatorByWorkspaceId = focusedReadIndicatorByWorkspaceId - } - if self.manualUnreadWorkspaceIds != manualUnreadWorkspaceIds { - self.manualUnreadWorkspaceIds = manualUnreadWorkspaceIds - } + let next = SidebarUnreadSnapshot( + totalUnreadCount: totalUnreadCount, + summaryByWorkspaceId: summaries, + unreadSurfaceKeys: unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedReadIndicatorByWorkspaceId, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + guard snapshot != next else { return } + snapshot = next } func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { - summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary(unreadCount: 0, latestNotificationText: nil) + snapshot.summary(forWorkspaceId: id) } func unreadCount(forWorkspaceId id: UUID) -> Int { - summary(forWorkspaceId: id).unreadCount + snapshot.unreadCount(forWorkspaceId: id) } func latestNotificationText(forWorkspaceId id: UUID) -> String? { - summary(forWorkspaceId: id).latestNotificationText + snapshot.latestNotificationText(forWorkspaceId: id) } func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { - unreadCount(forWorkspaceId: id) > 0 + snapshot.workspaceIsUnread(forWorkspaceId: id) } func hasManualUnread(forWorkspaceId id: UUID) -> Bool { - manualUnreadWorkspaceIds.contains(id) + snapshot.hasManualUnread(forWorkspaceId: id) } func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) + snapshot.hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) } func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || - (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) + snapshot.hasVisibleNotificationIndicator(forWorkspaceId: id, surfaceId: surfaceId) } func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { workspaceIsUnread(forWorkspaceId: $0) } + snapshot.canMarkWorkspaceRead(forWorkspaceIds: ids) } func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } + snapshot.canMarkWorkspaceUnread(forWorkspaceIds: ids) } } diff --git a/cmuxTests/FileDropOverlayViewTests.swift b/cmuxTests/FileDropOverlayViewTests.swift index 0eac941fb581..430fb5443297 100644 --- a/cmuxTests/FileDropOverlayViewTests.swift +++ b/cmuxTests/FileDropOverlayViewTests.swift @@ -20,7 +20,7 @@ struct FileDropOverlayViewTests { let root = ContentView(updateViewModel: UpdateStateModel(), windowId: windowId) .environmentObject(TabManager()) .environmentObject(TerminalNotificationStore.shared) - // ContentView reads SidebarUnreadModel from the environment. A missing + // The sidebar reads SidebarUnreadModel from the environment. A missing // @EnvironmentObject is a SwiftUI fatalError rather than a nil, so leaving it out does // not fail this test, it kills the app host and discards every verdict still pending in // it. The model belongs to the notification store, so hand over that store's instance From f9184b3461e3bb4e2aaebe0d0c255d3a7663f3c9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:12:15 -0700 Subject: [PATCH 09/36] Test targeted sidebar unread updates --- .../WorkspaceContentViewVisibilityTests.swift | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index c157e24e9a41..370a214a2456 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -260,7 +260,7 @@ final class WorkspaceContentViewVisibilityTests { @Test @MainActor - func testUnreadChangeDoesNotReevaluateContentViewRoot() async throws { + func testUnreadChangeUpdatesOnlyAffectedSidebarRow() async throws { _ = NSApplication.shared let suiteName = "WorkspaceContentViewUnreadTests.\(UUID().uuidString)" @@ -310,6 +310,17 @@ final class WorkspaceContentViewVisibilityTests { } await Self.drainMainRunLoop(for: window) + let workspaceCell = try #require( + window.contentView.flatMap { root in + Self.descendants(of: root) + .compactMap { $0 as? SidebarWorkspaceRowTableCellView } + .first { $0.currentModelForMeasurement?.workspaceId == workspaceId } + } + ) + var appliedUnreadCount: Int? + workspaceCell.applyModelProbeForTesting = { model in + appliedUnreadCount = model.unreadCount + } counts.reset() unread.apply( @@ -337,8 +348,12 @@ final class WorkspaceContentViewVisibilityTests { "Unread changes must not rebuild terminal or browser content." ) #expect( - counts.verticalTabsSidebarBody > 0, - "The sidebar must still receive the unread change." + counts.verticalTabsSidebarBody == 0, + "Unread changes must not rebuild every row through VerticalTabsSidebar." + ) + #expect( + appliedUnreadCount == 1, + "The affected visible AppKit row must still receive the unread badge." ) } @@ -393,6 +408,10 @@ final class WorkspaceContentViewVisibilityTests { } } + private static func descendants(of view: NSView) -> [NSView] { + view.subviews + view.subviews.flatMap { descendants(of: $0) } + } + @Test func testNonSelectedNonRetiringWorkspaceIsFullyHidden() { #expect( From baaa5a1caebc303a0e9af9f3ab6cf53431d2c104 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:32:30 -0700 Subject: [PATCH 10/36] Route unread updates to affected sidebar rows --- Sources/ContentView.swift | 42 +++++++++--- .../Cells/SidebarGroupHeaderRowModel.swift | 12 ++-- .../Cells/SidebarWorkspaceRowModel.swift | 4 +- .../SidebarWorkspaceTableController.swift | 68 ++++++++++++++++++- ...idebarWorkspaceTableRowConfiguration.swift | 56 ++++++++++++++- .../SidebarWorkspaceTableView.swift | 2 + Sources/TerminalNotificationStore.swift | 9 ++- .../VerticalTabsSidebar+WorkspaceGroups.swift | 52 +++++++++++--- cmuxTests/SidebarLazyLayoutScaleTests.swift | 1 + .../WorkspaceContentViewVisibilityTests.swift | 6 +- 10 files changed, 220 insertions(+), 32 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index f514bb7aa4e2..b7a58d3583f5 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -807,16 +807,19 @@ struct ContentView: View { var updateViewModel: UpdateStateModel let windowId: UUID let featureFlags: CmuxFeatureFlags + let sidebarUnread: SidebarUnreadModel @MainActor init( updateViewModel: UpdateStateModel, windowId: UUID, - featureFlags: CmuxFeatureFlags? = nil + featureFlags: CmuxFeatureFlags? = nil, + sidebarUnread: SidebarUnreadModel? = nil ) { self.updateViewModel = updateViewModel self.windowId = windowId self.featureFlags = featureFlags ?? .shared + self.sidebarUnread = sidebarUnread ?? TerminalNotificationStore.shared.sidebarUnread } @EnvironmentObject var tabManager: TabManager @@ -824,7 +827,6 @@ struct ContentView: View { // ContentView itself must not observe it: one agent notification would // otherwise rebuild the terminal, sidebar, and window chrome together. var notificationStore: TerminalNotificationStore { .shared } - var sidebarUnread: SidebarUnreadModel { notificationStore.sidebarUnread } @ObservedObject private var titlebarControlsLayoutModel = TitlebarControlsLayoutModel.shared @EnvironmentObject var sidebarState: SidebarState @EnvironmentObject var sidebarSelectionState: SidebarSelectionState @@ -1695,6 +1697,7 @@ struct ContentView: View { fileExplorerState: fileExplorerState, featureFlags: featureFlags, isPresented: sidebarState.isVisible, + sidebarUnread: sidebarUnread, windowId: windowId, onSendFeedback: presentFeedbackComposer, onToggleSidebar: { sidebarState.toggle() }, @@ -10483,6 +10486,7 @@ struct VerticalTabsSidebar: View, Equatable { && lhs.updateViewModel === rhs.updateViewModel && lhs.fileExplorerState === rhs.fileExplorerState && lhs.featureFlags === rhs.featureFlags + && lhs.sidebarUnread === rhs.sidebarUnread && lhs.isPresented == rhs.isPresented } @@ -10490,6 +10494,7 @@ struct VerticalTabsSidebar: View, Equatable { @ObservedObject var fileExplorerState: FileExplorerState var featureFlags: CmuxFeatureFlags = .shared var isPresented: Bool = true + let sidebarUnread: SidebarUnreadModel let windowId: UUID let onSendFeedback: () -> Void let onToggleSidebar: () -> Void @@ -10497,11 +10502,8 @@ struct VerticalTabsSidebar: View, Equatable { let observedWindowReference: WeakWindowReference var observedWindow: NSWindow? { observedWindowReference.window } @EnvironmentObject var tabManager: TabManager - // Observe the coalesced unread projection instead of the notification store - // so notification churn (terminal/agent activity) no longer reconstructs - // every workspace row. The store stays available as an unobserved singleton - // for context-menu actions and pass-down. See SidebarUnreadModel / #2586. - @EnvironmentObject var sidebarUnread: SidebarUnreadModel + // Plain reference by design. Native row and titlebar subscribers own the + // unread invalidation boundary, so this O(workspaces) root stays inert. var notificationStore: TerminalNotificationStore { .shared } @EnvironmentObject var cmuxConfigStore: CmuxConfigStore @Binding var selection: SidebarSelection @@ -10558,6 +10560,9 @@ struct VerticalTabsSidebar: View, Equatable { /// notifications) would otherwise stay unrendered until the next /// unrelated sidebar change. The bump forces one fresh rebuild. @State private var appKitPostResizeRefreshToken: UInt64 = 0 + /// The legacy SwiftUI list still consumes unread state at its container + /// boundary. Kept separate so the default AppKit list never subscribes. + @State private var legacyUnreadRefreshToken: UInt64 = 0 @State private var workspaceScrollContentMinHeight: CGFloat = 0 @State private var checklistPopoverWorkspaceId: UUID? // Pending keyed refresh ids are intentionally non-observed. Workspace @@ -11121,6 +11126,9 @@ struct VerticalTabsSidebar: View, Equatable { AnyView( legacyWorkspaceScrollArea(renderContext: renderContext) .onAppear { WindowTerminalPortal.usesCoalescedAnchorFailsafe = false } + .onReceive(sidebarUnread.$snapshot.dropFirst()) { _ in + legacyUnreadRefreshToken &+= 1 + } ) } } @@ -11185,6 +11193,7 @@ struct VerticalTabsSidebar: View, Equatable { } private func legacyWorkspaceScrollArea(renderContext: WorkspaceListRenderContext) -> some View { + let _ = legacyUnreadRefreshToken let scrollInsets = SidebarWorkspaceScrollInsets.workspaceList return GeometryReader { viewport in // Keep viewport geometry as a downward-only layout input. Writing @@ -11405,7 +11414,8 @@ struct VerticalTabsSidebar: View, Equatable { workspaceIds: isPresented ? renderContext.workspaceIds : tabManager.tabs.map(\.id), selectedWorkspaceId: selectedWorkspaceId, selectedScrollTargetWorkspaceId: selectedScrollTargetWorkspaceId, - isPresented: isPresented + isPresented: isPresented, + unreadSource: sidebarUnread ) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .mask( @@ -11880,7 +11890,18 @@ struct VerticalTabsSidebar: View, Equatable { actions: rowActions, groupId: input.groupId, isPinned: input.workspace.isPinned, - environment: environment + environment: environment, + unreadRebuild: { + [model, workspaceId = tab.id, + showsNotificationMessage = input.settings.showsNotificationMessage] snapshot in + let summary = snapshot.summary(forWorkspaceId: workspaceId) + var fresh = model + fresh.unreadCount = summary.unreadCount + fresh.latestNotificationText = showsNotificationMessage + ? summary.latestNotificationText + : nil + return fresh + } ) } @@ -11898,6 +11919,9 @@ struct VerticalTabsSidebar: View, Equatable { private func extensionSidebarScrollArea(renderContext: WorkspaceListRenderContext) -> some View { extensionSidebarScrollAreaContent(renderContext: renderContext) .sidebarProcessTitleObservations(ids: renderContext.workspaceIds, models: renderContext.tabs.map(\.sidebarProcessTitleObservation)) { refreshExtensionSidebarSnapshot() } + .onReceive(sidebarUnread.$snapshot.dropFirst()) { _ in + refreshExtensionSidebarSnapshot() + } .onAppear { refreshExtensionSidebarObservationPublishers(tabs: renderContext.tabs) } .onChange(of: renderContext.workspaceIds) { _, _ in refreshExtensionSidebarObservationPublishers(tabs: renderContext.tabs) diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift index a1afc9bf8249..0abdc0de73ae 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift @@ -19,12 +19,12 @@ struct SidebarGroupHeaderRowModel: Equatable, Hashable { let isMultiSelected: Bool let multiSelectionBackgroundStyle: SidebarWorkspaceRowBackgroundStyle let memberCount: Int - let anchorUnreadCount: Int - let canMarkRead: Bool - let canMarkUnread: Bool - let hasLatestNotifications: Bool - let canMarkAllRead: Bool - let canMarkAllUnread: Bool + var anchorUnreadCount: Int + var canMarkRead: Bool + var canMarkUnread: Bool + var hasLatestNotifications: Bool + var canMarkAllRead: Bool + var canMarkAllUnread: Bool /// Resolved modifier-hold hint (for example "⌘3"); nil hides the pill. let shortcutHintText: String? let shortcutHintXOffset: Double diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift index 718f22245070..7c538108c73d 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift @@ -21,8 +21,8 @@ struct SidebarWorkspaceRowModel: Equatable { var isMultiSelected: Bool let canCloseWorkspace: Bool let accessibilityWorkspaceCount: Int - let unreadCount: Int - let latestNotificationText: String? + var unreadCount: Int + var latestNotificationText: String? let showsAgentActivity: Bool let rowSpacing: CGFloat let isBeingDragged: Bool diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift index c1f608b1eaf5..c3e644422fed 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift @@ -1,5 +1,6 @@ import AppKit import Bonsplit +import Combine import CmuxAppKitSupportUI import CmuxFoundation import SwiftUI @@ -31,6 +32,9 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private var appKitDropIndicator: SidebarDropIndicator? private var appKitDropIndicatorScope: SidebarWorkspaceReorderDropIndicatorScope = .raw private var appKitDropIndicatorIncludesRowTargets = false + private weak var unreadSource: SidebarUnreadModel? + private var unreadSnapshot = SidebarUnreadSnapshot() + private var unreadCancellable: AnyCancellable? private var clipBoundsObserver: NSObjectProtocol? private var resizeDidEndObserver: NSObjectProtocol? private lazy var mutationScheduler = SidebarWorkspaceTableMutationScheduler( @@ -57,6 +61,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS NotificationCenter.default.removeObserver(resizeDidEndObserver) } previewBailoutTask?.cancel() + unreadCancellable?.cancel() } func makeContainerView() -> SidebarWorkspaceTableContainerView { let container = SidebarWorkspaceTableContainerView() @@ -156,6 +161,10 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS let postUpdateActions = detachLoadedCells() workspaceDragSessionDidEnd() actions = nil + unreadCancellable?.cancel() + unreadCancellable = nil + unreadSource = nil + unreadSnapshot = SidebarUnreadSnapshot() rows.removeAll(keepingCapacity: false) workspaceIds.removeAll(keepingCapacity: false) selectedScrollTargetWorkspaceId = nil @@ -172,6 +181,63 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS mutationScheduler.stagePostUpdateActions(postUpdateActions) } + /// Installs one unread subscription for the native table. Snapshot changes + /// are projected directly into affected visible cells, bypassing SwiftUI's + /// `VerticalTabsSidebar.body` and its O(workspaces) row construction. + func setUnreadSource(_ source: SidebarUnreadModel) { + guard unreadSource !== source else { return } + unreadCancellable?.cancel() + unreadSource = source + unreadSnapshot = source.snapshot + unreadCancellable = source.$snapshot + .dropFirst() + .receive(on: DispatchQueue.main) + .sink { [weak self] snapshot in + MainActor.assumeIsolated { + self?.applyUnreadSnapshot(snapshot) + } + } + } + + private func applyUnreadSnapshot(_ nextSnapshot: SidebarUnreadSnapshot) { + let previousSnapshot = unreadSnapshot + unreadSnapshot = nextSnapshot + guard isPresentationActive, let table = containerView?.tableView else { return } + + let candidateIds = Set(previousSnapshot.summaryByWorkspaceId.keys) + .union(nextSnapshot.summaryByWorkspaceId.keys) + let changedWorkspaceIds = Set(candidateIds.filter { + previousSnapshot.summary(forWorkspaceId: $0) + != nextSnapshot.summary(forWorkspaceId: $0) + }) + guard !changedWorkspaceIds.isEmpty else { return } + + var changedRows = IndexSet() + for row in rows.indices { + let configuration = rows[row] + guard !configuration.appKitUnreadDependencyWorkspaceIds.isDisjoint( + with: changedWorkspaceIds + ) else { + continue + } + let updated = configuration.applyingUnreadSnapshot(nextSnapshot) + guard !configuration.hasEquivalentContent(to: updated) else { continue } + rows[row] = updated + changedRows.insert(row) + } + guard !changedRows.isEmpty else { return } + + let heightChanges = rowHeightCache.prepareRows( + at: changedRows, + in: rows, + columnWidth: currentColumnWidth() + ) + reconfigureVisibleRows(changedRows) + if !heightChanges.isEmpty { + noteHeightOfRowsWithoutAnimation(table, heightChanges) + } + } + func setPresentationActive(_ isActive: Bool, workspaceIds liveWorkspaceIds: [UUID]) { guard isPresentationActive != isActive else { if !isActive { @@ -277,7 +343,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private func flushApply(_ input: SidebarWorkspaceTableApplyInput) { guard isPresentationActive, let containerView else { return } - let nextRows = input.rows + let nextRows = input.rows.map { $0.applyingUnreadSnapshot(unreadSnapshot) } let actions = input.actions let nextWorkspaceIds = input.workspaceIds let selectedWorkspaceId = input.selectedWorkspaceId diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift index 8a21ea699fc4..48d94c782ce4 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift @@ -39,6 +39,12 @@ struct SidebarWorkspaceTableRowConfiguration { /// pump (metadata/branch/PR updates repaint one cell, no container render). let appKitWorkspaceRowWorkspace: Workspace? let appKitWorkspaceRowRebuild: (@MainActor () -> SidebarWorkspaceRowModel)? + /// Workspace ids whose unread summaries affect this row, plus factories + /// that repaint only the matching AppKit cell from the latest atomic + /// unread snapshot. They are intentionally excluded from row equality. + let appKitUnreadDependencyWorkspaceIds: Set + let appKitWorkspaceUnreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarWorkspaceRowModel)? + let appKitGroupHeaderUnreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarGroupHeaderRowModel)? private let environment: SidebarWorkspaceTableEnvironmentSnapshot private let equivalenceValue: Any @@ -69,6 +75,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = [] + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = nil self.environment = environment self.equivalenceValue = equivalenceValue self.isEquivalentValue = isEquivalentValue @@ -97,6 +106,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = [] + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = nil self.equivalenceValue = equivalenceValue self.isEquivalentValue = { value in guard let value = value as? Content else { return false } @@ -107,7 +119,9 @@ struct SidebarWorkspaceTableRowConfiguration { init( groupHeaderModel: SidebarGroupHeaderRowModel, actions: SidebarGroupHeaderRowActions, - environment: SidebarWorkspaceTableEnvironmentSnapshot + environment: SidebarWorkspaceTableEnvironmentSnapshot, + unreadDependencyWorkspaceIds: Set = [], + unreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarGroupHeaderRowModel)? = nil ) { self.id = .group(groupHeaderModel.groupId) self.workspaceId = groupHeaderModel.anchorWorkspaceId @@ -122,6 +136,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = unreadDependencyWorkspaceIds + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = unreadRebuild self.equivalenceValue = groupHeaderModel self.isEquivalentValue = { value in guard let value = value as? SidebarGroupHeaderRowModel else { return false } @@ -136,7 +153,8 @@ struct SidebarWorkspaceTableRowConfiguration { isPinned: Bool, environment: SidebarWorkspaceTableEnvironmentSnapshot, workspace: Workspace? = nil, - rebuild: (@MainActor () -> SidebarWorkspaceRowModel)? = nil + rebuild: (@MainActor () -> SidebarWorkspaceRowModel)? = nil, + unreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarWorkspaceRowModel)? = nil ) { self.id = .workspace(workspaceRowModel.workspaceId) self.workspaceId = workspaceRowModel.workspaceId @@ -151,6 +169,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = actions self.appKitWorkspaceRowWorkspace = workspace self.appKitWorkspaceRowRebuild = rebuild + self.appKitUnreadDependencyWorkspaceIds = [workspaceRowModel.workspaceId] + self.appKitWorkspaceUnreadRebuild = unreadRebuild + self.appKitGroupHeaderUnreadRebuild = nil self.equivalenceValue = workspaceRowModel self.isEquivalentValue = { value in guard let value = value as? SidebarWorkspaceRowModel else { return false } @@ -163,6 +184,37 @@ struct SidebarWorkspaceTableRowConfiguration { && isEquivalentValue(other.equivalenceValue) } + func applyingUnreadSnapshot(_ snapshot: SidebarUnreadSnapshot) -> Self { + if let rebuild = appKitWorkspaceUnreadRebuild, + let actions = appKitWorkspaceRowActions { + let model = rebuild(snapshot) + guard model != appKitWorkspaceRowModel else { return self } + return Self( + workspaceRowModel: model, + actions: actions, + groupId: groupId, + isPinned: isPinned, + environment: environment, + workspace: appKitWorkspaceRowWorkspace, + rebuild: appKitWorkspaceRowRebuild, + unreadRebuild: rebuild + ) + } + if let rebuild = appKitGroupHeaderUnreadRebuild, + let actions = appKitGroupHeaderActions { + let model = rebuild(snapshot) + guard model != appKitGroupHeaderModel else { return self } + return Self( + groupHeaderModel: model, + actions: actions, + environment: environment, + unreadDependencyWorkspaceIds: appKitUnreadDependencyWorkspaceIds, + unreadRebuild: rebuild + ) + } + return self + } + /// Keeps the immutable paint model while dropping every live action, /// workspace, and hosted-content capture during retained hidden display. func presentationSnapshot() -> Self { diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift index 4dd14b652d31..32e101e0bb57 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift @@ -8,6 +8,7 @@ struct SidebarWorkspaceTableView: NSViewRepresentable { let selectedWorkspaceId: UUID? let selectedScrollTargetWorkspaceId: UUID? let isPresented: Bool + let unreadSource: SidebarUnreadModel #if DEBUG @Environment(\.sidebarLazyContractProbe) private var sidebarLazyContractProbe @@ -25,6 +26,7 @@ struct SidebarWorkspaceTableView: NSViewRepresentable { #if DEBUG context.coordinator.reconfigurationProbe = sidebarLazyContractProbe.tableRootViewReconfigure #endif + context.coordinator.setUnreadSource(unreadSource) context.coordinator.setPresentationActive(isPresented, workspaceIds: workspaceIds) guard isPresented else { return } context.coordinator.apply( diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 6e806d56e926..7a25a66a107f 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -549,15 +549,17 @@ final class TerminalNotificationStore: ObservableObject { result.reserveCapacity(ids.count) for id in ids { let count = unreadCount(forTabId: id) - let latestText: String? = indexes.latestByTabId[id].flatMap { notification in + let latestNotification = indexes.latestByTabId[id] + let latestText: String? = latestNotification.flatMap { notification in let text = notification.body.isEmpty ? notification.title : notification.body let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? nil : trimmed } - if count == 0, latestText == nil { continue } + if count == 0, latestNotification == nil { continue } result[id] = SidebarWorkspaceUnreadSummary( unreadCount: count, - latestNotificationText: latestText + latestNotificationText: latestText, + hasLatestNotification: latestNotification != nil ) } return result @@ -2318,6 +2320,7 @@ final class TerminalNotificationStore: ObservableObject { struct SidebarWorkspaceUnreadSummary: Equatable { var unreadCount: Int var latestNotificationText: String? + var hasLatestNotification: Bool = false } /// Workspace + surface pair used to mirror the store's per-surface unread set. diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 2b336dfb82a5..c9bf1c77875c 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -31,24 +31,31 @@ extension VerticalTabsSidebar { ) let cwdContextMenuItems = resolvedConfig?.contextMenuItems ?? [] let newWorkspacePlacement = resolvedConfig?.newWorkspacePlacement + let unreadSnapshot = sidebarUnread.snapshot let anchorUnreadCount: Int = { if group.isCollapsed { return memberWorkspaceIds.reduce(0) { partial, workspaceId in - partial + notificationStore.unreadCount(forTabId: workspaceId) + partial + unreadSnapshot.unreadCount(forWorkspaceId: workspaceId) } } - return notificationStore.unreadCount(forTabId: group.anchorWorkspaceId) + return unreadSnapshot.unreadCount(forWorkspaceId: group.anchorWorkspaceId) }() let anchorIds = [group.anchorWorkspaceId] - let canMarkAnchorRead = notificationStore.canMarkWorkspaceRead(forTabIds: anchorIds) - let canMarkAnchorUnread = notificationStore.canMarkWorkspaceUnread(forTabIds: anchorIds) - let anchorHasLatestNotification = notificationStore.latestNotification(forTabId: group.anchorWorkspaceId) != nil + let canMarkAnchorRead = unreadSnapshot.canMarkWorkspaceRead(forWorkspaceIds: anchorIds) + let canMarkAnchorUnread = unreadSnapshot.canMarkWorkspaceUnread(forWorkspaceIds: anchorIds) + let anchorHasLatestNotification = unreadSnapshot + .summary(forWorkspaceId: group.anchorWorkspaceId) + .hasLatestNotification // "Mark all workspaces in group" targets the contained workspaces only, // never the anchor: the anchor is the group's own row, whose read status // is owned by the separate "Mark Group as Read/Unread" actions. let nonAnchorMemberIds = memberWorkspaceIds.filter { $0 != group.anchorWorkspaceId } - let canMarkAllRead = notificationStore.canMarkWorkspaceRead(forTabIds: nonAnchorMemberIds) - let canMarkAllUnread = notificationStore.canMarkWorkspaceUnread(forTabIds: nonAnchorMemberIds) + let canMarkAllRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + let canMarkAllUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate().topVisible( forTabId: group.anchorWorkspaceId, draggedTabId: dragState.draggedTabId, @@ -203,7 +210,36 @@ extension VerticalTabsSidebar { return SidebarWorkspaceTableRowConfiguration( groupHeaderModel: model, actions: actions, - environment: renderContext.environment + environment: renderContext.environment, + unreadDependencyWorkspaceIds: Set(memberWorkspaceIds) + .union([group.anchorWorkspaceId]), + unreadRebuild: { + [model, anchorWorkspaceId = group.anchorWorkspaceId, + isCollapsed = group.isCollapsed, memberWorkspaceIds, + nonAnchorMemberIds] snapshot in + var fresh = model + fresh.anchorUnreadCount = isCollapsed + ? memberWorkspaceIds.reduce(0) { + $0 + snapshot.unreadCount(forWorkspaceId: $1) + } + : snapshot.unreadCount(forWorkspaceId: anchorWorkspaceId) + fresh.canMarkRead = snapshot.canMarkWorkspaceRead( + forWorkspaceIds: [anchorWorkspaceId] + ) + fresh.canMarkUnread = snapshot.canMarkWorkspaceUnread( + forWorkspaceIds: [anchorWorkspaceId] + ) + fresh.hasLatestNotifications = snapshot + .summary(forWorkspaceId: anchorWorkspaceId) + .hasLatestNotification + fresh.canMarkAllRead = snapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + fresh.canMarkAllUnread = snapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) + return fresh + } ) } diff --git a/cmuxTests/SidebarLazyLayoutScaleTests.swift b/cmuxTests/SidebarLazyLayoutScaleTests.swift index 5afec960c582..2d1733d4e413 100644 --- a/cmuxTests/SidebarLazyLayoutScaleTests.swift +++ b/cmuxTests/SidebarLazyLayoutScaleTests.swift @@ -146,6 +146,7 @@ final class SidebarLazyLayoutScaleTests { let root = VerticalTabsSidebar( updateViewModel: UpdateStateModel(), fileExplorerState: FileExplorerState(), + sidebarUnread: unread, windowId: UUID(), onSendFeedback: {}, onToggleSidebar: {}, diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index 370a214a2456..e81fbb48ad7a 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -278,7 +278,11 @@ final class WorkspaceContentViewVisibilityTests { let workspaceId = try #require(tabManager.selectedTabId) let unread = SidebarUnreadModel() let counts = MinimalModeBodyProbeCounts() - let root = ContentView(updateViewModel: UpdateStateModel(), windowId: UUID()) + let root = ContentView( + updateViewModel: UpdateStateModel(), + windowId: UUID(), + sidebarUnread: unread + ) .environmentObject(tabManager) .environmentObject(TerminalNotificationStore.shared) .environmentObject(unread) From 4d950929f85ff144e0377f5e55b0fce35c91f9d4 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 14:13:57 -0700 Subject: [PATCH 11/36] Test heartbeat identity write suppression --- cmuxTests/MobileHostIdentityTests.swift | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cmuxTests/MobileHostIdentityTests.swift b/cmuxTests/MobileHostIdentityTests.swift index c566135507a7..b056e7107653 100644 --- a/cmuxTests/MobileHostIdentityTests.swift +++ b/cmuxTests/MobileHostIdentityTests.swift @@ -176,6 +176,37 @@ struct MobileHostIdentityTests { #expect(defaults.string(forKey: "mobileHost.deviceID") == sharedID.lowercased()) } + @Test func repeatedSharedDeviceIDReadDoesNotRepublishDefaultsChange() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let sharedIDURL = directory.appendingPathComponent("mobile-host-device-id") + let sharedID = "3D56C547-271C-47D8-84F6-5C79C9394A37".lowercased() + try sharedID.write(to: sharedIDURL, atomically: true, encoding: .utf8) + + let suiteName = "mobile-host-identity-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set(sharedID, forKey: "mobileHost.deviceID") + + var notificationCount = 0 + let observer = NotificationCenter.default.addObserver( + forName: UserDefaults.didChangeNotification, + object: defaults, + queue: nil + ) { _ in + notificationCount += 1 + } + defer { NotificationCenter.default.removeObserver(observer) } + + #expect(MobileHostIdentity.deviceID( + defaults: defaults, + sharedIDURL: sharedIDURL + ) == sharedID) + #expect(notificationCount == 0) + } + @Test func migratesExistingBundleIDToSharedFile() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) From 3c4b3b758e6a5274f33c4d431c6a6376b971c535 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 14:14:10 -0700 Subject: [PATCH 12/36] Suppress redundant heartbeat defaults writes --- Sources/Mobile/MobileHostIdentity.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/Mobile/MobileHostIdentity.swift b/Sources/Mobile/MobileHostIdentity.swift index 22acbcc6c11f..4e6a8cef69ea 100644 --- a/Sources/Mobile/MobileHostIdentity.swift +++ b/Sources/Mobile/MobileHostIdentity.swift @@ -28,7 +28,7 @@ enum MobileHostIdentity { bundleIdentifier: String? = Bundle.main.bundleIdentifier ) -> String { if let id = readSharedDeviceID(from: sharedIDURL) { - defaults.set(id, forKey: deviceIDKey) + persistDeviceIDIfNeeded(id, defaults: defaults) return id } @@ -83,10 +83,17 @@ enum MobileHostIdentity { return normalizedID(existing) } + private static func persistDeviceIDIfNeeded(_ id: String, defaults: UserDefaults) { + let stored = defaults.string(forKey: deviceIDKey)? + .trimmingCharacters(in: .whitespacesAndNewlines) + guard stored != id else { return } + defaults.set(id, forKey: deviceIDKey) + } + private static func settleSharedDeviceID(_ candidate: String, defaults: UserDefaults, sharedIDURL: URL?) -> String { let candidate = cmxCanonicalDeviceID(candidate) guard let sharedIDURL else { - defaults.set(candidate, forKey: deviceIDKey) + persistDeviceIDIfNeeded(candidate, defaults: defaults) return candidate } try? FileManager.default.createDirectory( @@ -96,13 +103,13 @@ enum MobileHostIdentity { let data = Data(candidate.utf8) if !FileManager.default.createFile(atPath: sharedIDURL.path, contents: data) { if let winner = readSharedDeviceID(from: sharedIDURL) { - defaults.set(winner, forKey: deviceIDKey) + persistDeviceIDIfNeeded(winner, defaults: defaults) return winner } try? data.write(to: sharedIDURL, options: .atomic) } let settled = readSharedDeviceID(from: sharedIDURL) ?? candidate - defaults.set(settled, forKey: deviceIDKey) + persistDeviceIDIfNeeded(settled, defaults: defaults) return settled } From 3c63d5369fe91f6860d88411cba04bd334765158 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 19:48:30 -0700 Subject: [PATCH 13/36] Localize unread and titlebar observation ownership --- .../SidebarUnreadSnapshot.swift | 228 ++++++++++++++++++ .../SidebarUnreadSnapshotTests.swift | 84 +++++++ Sources/AppDelegate.swift | 14 +- ...MUXInstalledExtensionSidebarHostView.swift | 75 +++++- Sources/ContentView.swift | 185 ++++++++++---- Sources/DockPanelView.swift | 1 + Sources/DockUnreadPanelProjection.swift | 18 +- ...alModeSidebarTitlebarControlsOverlay.swift | 3 + .../CustomSidebarPaneDataContextCache.swift | 1 + Sources/Panels/CustomSidebarPanelView.swift | 1 + Sources/Panels/PanelContentView.swift | 1 + .../SidebarWorkspaceTableController.swift | 25 +- ...idebarWorkspaceTableRowConfiguration.swift | 1 + .../SidebarWorkspaceTableView.swift | 1 + Sources/TerminalNotificationStore.swift | 144 +---------- Sources/Update/UpdateTitlebarAccessory.swift | 73 ++++-- .../VerticalTabsSidebar+WorkspaceGroups.swift | 1 + cmuxTests/DockRuntimeParityTests.swift | 1 + cmuxTests/FileDropOverlayViewTests.swift | 7 +- .../SidebarHiddenPresentationTests.swift | 1 - cmuxTests/SidebarLazyLayoutScaleTests.swift | 2 +- .../SidebarPointerInteractionScaleTests.swift | 1 + .../TitlebarInteractiveControlTests.swift | 12 +- .../WorkspaceContentViewVisibilityTests.swift | 15 +- 24 files changed, 629 insertions(+), 266 deletions(-) create mode 100644 Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift create mode 100644 Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift new file mode 100644 index 000000000000..abd7fbb6cd72 --- /dev/null +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift @@ -0,0 +1,228 @@ +public import Foundation +import Observation + +/// The unread values rendered for one workspace row. +public struct SidebarWorkspaceUnreadSummary: Equatable, Sendable { + /// The workspace's displayed unread count. + public var unreadCount: Int + /// The trimmed body or title of the latest notification, when present. + public var latestNotificationText: String? + /// Whether the workspace has a latest notification that can be cleared. + public var hasLatestNotification: Bool + + /// Creates one workspace unread summary. + public init( + unreadCount: Int, + latestNotificationText: String?, + hasLatestNotification: Bool = false + ) { + self.unreadCount = unreadCount + self.latestNotificationText = latestNotificationText + self.hasLatestNotification = hasLatestNotification + } +} + +/// A workspace and optional surface pair in the unread set. +public struct SidebarSurfaceUnreadKey: Hashable, Sendable { + /// The owning workspace identifier. + public var workspaceId: UUID + /// The surface identifier, or `nil` for a workspace-wide notification. + public var surfaceId: UUID? + + /// Creates one workspace or surface unread key. + public init(workspaceId: UUID, surfaceId: UUID?) { + self.workspaceId = workspaceId + self.surfaceId = surfaceId + } +} + +/// One atomic unread-state publication shared by all presentation surfaces. +public struct SidebarUnreadSnapshot: Equatable, Sendable { + /// Total unread count rendered by global badges. + public var totalUnreadCount: Int + /// Per-workspace row summaries, omitting default empty summaries. + public var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] + /// Workspace and surface pairs with unread notifications. + public var unreadSurfaceKeys: Set + /// Focused surfaces whose read indicator remains visible. + public var focusedReadIndicatorByWorkspaceId: [UUID: UUID] + /// Workspaces explicitly marked unread by the user. + public var manualUnreadWorkspaceIds: Set + + /// Creates one complete unread snapshot. + public init( + totalUnreadCount: Int = 0, + summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:], + unreadSurfaceKeys: Set = [], + focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:], + manualUnreadWorkspaceIds: Set = [] + ) { + self.totalUnreadCount = totalUnreadCount + self.summaryByWorkspaceId = summaryByWorkspaceId + self.unreadSurfaceKeys = unreadSurfaceKeys + self.focusedReadIndicatorByWorkspaceId = focusedReadIndicatorByWorkspaceId + self.manualUnreadWorkspaceIds = manualUnreadWorkspaceIds + } + + /// Returns the workspace summary, or an empty summary when absent. + public func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { + summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary( + unreadCount: 0, + latestNotificationText: nil + ) + } + + /// Returns the workspace's displayed unread count. + public func unreadCount(forWorkspaceId id: UUID) -> Int { + summary(forWorkspaceId: id).unreadCount + } + + /// Returns the workspace's latest notification text. + public func latestNotificationText(forWorkspaceId id: UUID) -> String? { + summary(forWorkspaceId: id).latestNotificationText + } + + /// Returns whether the workspace has any displayed unread state. + public func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { + unreadCount(forWorkspaceId: id) > 0 + } + + /// Returns whether the workspace was explicitly marked unread. + public func hasManualUnread(forWorkspaceId id: UUID) -> Bool { + manualUnreadWorkspaceIds.contains(id) + } + + /// Returns whether the workspace or surface has an unread notification. + public func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) + } + + /// Returns whether the surface should render its notification indicator. + public func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || + (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) + } + + /// Returns whether any supplied workspace can be marked read. + public func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { workspaceIsUnread(forWorkspaceId: $0) } + } + + /// Returns whether any supplied workspace can be marked unread. + public func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } + } +} + +/// Main-actor unread source of truth for leaf UI projections. +/// +/// Mutations publish one equality-guarded snapshot. SwiftUI tracks ``snapshot`` +/// through Observation, while AppKit consumers use ``snapshotChanges()`` so the +/// app does not add Combine state or broad root-view subscriptions. +@MainActor +@Observable +public final class SidebarUnreadModel { + /// The latest complete unread state. + public private(set) var snapshot = SidebarUnreadSnapshot() + + /// Total unread count rendered by global badges. + public var totalUnreadCount: Int { snapshot.totalUnreadCount } + /// Current per-workspace unread summaries. + public var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] { + snapshot.summaryByWorkspaceId + } + /// Current workspace and surface unread keys. + public var unreadSurfaceKeys: Set { snapshot.unreadSurfaceKeys } + /// Current focused read-indicator surfaces. + public var focusedReadIndicatorByWorkspaceId: [UUID: UUID] { + snapshot.focusedReadIndicatorByWorkspaceId + } + /// Workspaces explicitly marked unread. + public var manualUnreadWorkspaceIds: Set { snapshot.manualUnreadWorkspaceIds } + + @ObservationIgnored + private var snapshotObservers: [UUID: AsyncStream.Continuation] = [:] + + /// Creates an empty unread model. + public init() {} + + /// Returns a stream of changed snapshots, buffering only the newest value. + public func snapshotChanges() -> AsyncStream { + AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in + let id = UUID() + snapshotObservers[id] = continuation + continuation.onTermination = { [weak self] _ in + Task { @MainActor in + self?.snapshotObservers[id] = nil + } + } + } + } + + /// Atomically applies one complete unread state and publishes only changes. + public func apply( + totalUnreadCount: Int, + summaries: [UUID: SidebarWorkspaceUnreadSummary], + unreadSurfaceKeys: Set, + focusedReadIndicatorByWorkspaceId: [UUID: UUID], + manualUnreadWorkspaceIds: Set + ) { + let next = SidebarUnreadSnapshot( + totalUnreadCount: totalUnreadCount, + summaryByWorkspaceId: summaries, + unreadSurfaceKeys: unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedReadIndicatorByWorkspaceId, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + guard snapshot != next else { return } + snapshot = next + for observer in snapshotObservers.values { + observer.yield(next) + } + } + + /// Returns the summary for one workspace. + public func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { + snapshot.summary(forWorkspaceId: id) + } + + /// Returns the unread count for one workspace. + public func unreadCount(forWorkspaceId id: UUID) -> Int { + snapshot.unreadCount(forWorkspaceId: id) + } + + /// Returns the latest notification text for one workspace. + public func latestNotificationText(forWorkspaceId id: UUID) -> String? { + snapshot.latestNotificationText(forWorkspaceId: id) + } + + /// Returns whether one workspace is unread. + public func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { + snapshot.workspaceIsUnread(forWorkspaceId: id) + } + + /// Returns whether one workspace was manually marked unread. + public func hasManualUnread(forWorkspaceId id: UUID) -> Bool { + snapshot.hasManualUnread(forWorkspaceId: id) + } + + /// Returns whether a workspace or surface has an unread notification. + public func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + snapshot.hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) + } + + /// Returns whether a surface should show its notification indicator. + public func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + snapshot.hasVisibleNotificationIndicator(forWorkspaceId: id, surfaceId: surfaceId) + } + + /// Returns whether any supplied workspace can be marked read. + public func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { + snapshot.canMarkWorkspaceRead(forWorkspaceIds: ids) + } + + /// Returns whether any supplied workspace can be marked unread. + public func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { + snapshot.canMarkWorkspaceUnread(forWorkspaceIds: ids) + } +} diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift new file mode 100644 index 000000000000..d9a8a764cedf --- /dev/null +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -0,0 +1,84 @@ +import Foundation +import Testing +@testable import CmuxNotifications + +@Suite("Sidebar unread snapshot") +struct SidebarUnreadSnapshotTests { + @Test + func queriesResolveMissingAndSurfaceState() { + let workspaceID = UUID() + let surfaceID = UUID() + let snapshot = SidebarUnreadSnapshot( + totalUnreadCount: 2, + summaryByWorkspaceId: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 2, + latestNotificationText: "Pi finished", + hasLatestNotification: true + ), + ], + unreadSurfaceKeys: [ + SidebarSurfaceUnreadKey(workspaceId: workspaceID, surfaceId: surfaceID), + ], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [workspaceID] + ) + + #expect(snapshot.totalUnreadCount == 2) + #expect(snapshot.unreadCount(forWorkspaceId: workspaceID) == 2) + #expect(snapshot.latestNotificationText(forWorkspaceId: workspaceID) == "Pi finished") + #expect(snapshot.hasManualUnread(forWorkspaceId: workspaceID)) + #expect(snapshot.hasVisibleNotificationIndicator( + forWorkspaceId: workspaceID, + surfaceId: surfaceID + )) + #expect(snapshot.summary(forWorkspaceId: UUID()).unreadCount == 0) + } + + @Test + @MainActor + func modelStreamsOnlyChangedAtomicSnapshots() async { + let workspaceID = UUID() + let model = SidebarUnreadModel() + var iterator = model.snapshotChanges().makeAsyncIterator() + + model.apply( + totalUnreadCount: 1, + summaries: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + let first = await iterator.next() + #expect(first == model.snapshot) + + var nextIterator = model.snapshotChanges().makeAsyncIterator() + model.apply( + totalUnreadCount: 1, + summaries: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + model.apply( + totalUnreadCount: 0, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + let second = await nextIterator.next() + #expect(second?.totalUnreadCount == 0) + #expect(second?.summaryByWorkspaceId.isEmpty == true) + } +} diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index be1cdd6d1f9e..571570b2d5ce 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -862,7 +862,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var debugFocusedTerminalKeyRepairObserverForTesting: ((NSWindow, NSEvent, NSResponder?) -> Void)? #endif private lazy var updateController = UpdateController(log: updateLog) - private lazy var titlebarAccessoryController = UpdateTitlebarAccessoryController(updateLog: updateLog, settingsRuntime: settingsRuntime) + private let titlebarControlsLayoutModel = TitlebarControlsLayoutModel() + private lazy var titlebarAccessoryController = UpdateTitlebarAccessoryController( + updateLog: updateLog, + settingsRuntime: settingsRuntime, + layoutModel: titlebarControlsLayoutModel + ) private let windowDecorationsController = WindowDecorationsController() private var menuBarExtraController: MenuBarExtraController? private var transientGlobalSearchMenuBarExtraController: MenuBarExtraController? @@ -8958,10 +8963,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } #endif - let root = ContentView(updateViewModel: updateViewModel, windowId: windowId) + let root = ContentView( + updateViewModel: updateViewModel, + windowId: windowId, + titlebarControlsLayoutModel: titlebarControlsLayoutModel + ) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(sidebarState) .environmentObject(sidebarSelectionState) .environmentObject(fileExplorerState) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b61ca8e1d121..574d9f3f58de 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxNotifications @_spi(CmuxHostTransport) import CmuxSidebar @_spi(CmuxHostTransport) import CmuxExtensionKit import AppKit @@ -132,12 +133,50 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { } } +@MainActor +private final class CMUXSidebarSnapshotCache { + private(set) var snapshot: CmuxSidebarSnapshot? + + func replace(with next: CmuxSidebarSnapshot) -> CmuxSidebarSnapshot { + guard let current = snapshot else { + snapshot = next + return next + } + guard current != next else { return current } + var updated = next + updated.sequence = max(next.sequence, current.sequence &+ 1) + snapshot = updated + return updated + } + + func applyUnread(_ unread: SidebarUnreadSnapshot) -> CmuxSidebarSnapshot? { + guard var next = snapshot else { return nil } + var changed = false + for index in next.workspaces.indices { + let summary = unread.summary(forWorkspaceId: next.workspaces[index].id) + if next.workspaces[index].unreadCount != summary.unreadCount { + next.workspaces[index].unreadCount = summary.unreadCount + changed = true + } + if next.workspaces[index].latestNotification != summary.latestNotificationText { + next.workspaces[index].latestNotification = summary.latestNotificationText + changed = true + } + } + guard changed else { return nil } + next.sequence &+= 1 + snapshot = next + return next + } +} + struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" var snapshotProvider: @MainActor () -> CmuxSidebarSnapshot var snapshotUpdateToken: UInt64 = 0 + let unreadSource: SidebarUnreadModel var actionHandler: @MainActor (CmuxSidebarAction) -> CmuxSidebarActionResult var onUseDefaultSidebar: @MainActor () -> Void = {} @@ -158,6 +197,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var isShowingAccessReview = false @State private var keptLimitedManifestKeys = CMUXSidebarExtensionLimitedChoiceStore().choices() @State private var hostReloadToken: UInt64 = 0 + @State private var snapshotCache = CMUXSidebarSnapshotCache() var body: some View { Group { @@ -173,7 +213,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { xpcHost.attach( connection: connection, bundleIdentifier: identity.bundleIdentifier, - snapshotProvider: snapshotProvider, + snapshotProvider: { + snapshotCache.snapshot ?? snapshotProvider() + }, actionHandler: actionHandler, onGrantChanged: { grant in effectiveGrant = grant @@ -253,14 +295,26 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } .task { - xpcHost.update(snapshotProvider: snapshotProvider, actionHandler: actionHandler) + _ = snapshotCache.replace(with: snapshotProvider()) + xpcHost.update( + snapshotProvider: { snapshotCache.snapshot ?? snapshotProvider() }, + actionHandler: actionHandler + ) await observeExtensionAvailability() } - .onChange(of: snapshotProvider().sequence) { _, _ in - xpcHost.sendSnapshotDidChange() + .task { + for await unreadSnapshot in unreadSource.snapshotChanges() { + guard !Task.isCancelled else { return } + if snapshotCache.snapshot == nil { + _ = snapshotCache.replace(with: snapshotProvider()) + } + guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { continue } + xpcHost.sendSnapshotDidChange(snapshot) + } } .onChange(of: snapshotUpdateToken) { _, _ in - xpcHost.sendSnapshotDidChange() + let snapshot = snapshotCache.replace(with: snapshotProvider()) + xpcHost.sendSnapshotDidChange(snapshot) } .onDisappear { xpcHost.invalidate() @@ -1122,8 +1176,17 @@ private final class CMUXSidebarExtensionHostXPC { func sendSnapshotDidChange() { guard let extensionProxy, let snapshotProvider else { return } + sendSnapshotDidChange(snapshotProvider()) + } + + func sendSnapshotDidChange(_ snapshot: CmuxSidebarSnapshot) { + guard let extensionProxy else { return } do { - extensionProxy.sidebarSnapshotDidChange(try CmuxSidebarXPCCodec.encodeSnapshot(filteredSnapshot(from: snapshotProvider))) + extensionProxy.sidebarSnapshotDidChange( + try CmuxSidebarXPCCodec.encodeSnapshot( + snapshot.filtered(for: allowedScopes, actionScopes: allowedActionScopes) + ) + ) } catch { #if DEBUG cmuxDebugLog("extension.sidebar.xpc.snapshot.encode.failed error=\(error.localizedDescription)") diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index a222dd41eb51..2170ee3cf730 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -4,6 +4,7 @@ import CmuxCommandPalette import CmuxCore import CmuxFeedback import CmuxFoundation +import CmuxNotifications import CmuxPanes import CmuxSettings import CmuxWorkspaces @@ -803,23 +804,46 @@ private final class SelectedWorkspaceDirectoryObserver: ObservableObject { } } +/// Restricts unread Observation invalidation to the subtree that reads the +/// snapshot instead of making `ContentView` or `VerticalTabsSidebar` observers. +private struct SidebarUnreadSnapshotReader: View { + let source: SidebarUnreadModel + let content: (SidebarUnreadSnapshot) -> Content + + init( + source: SidebarUnreadModel, + @ViewBuilder content: @escaping (SidebarUnreadSnapshot) -> Content + ) { + self.source = source + self.content = content + } + + var body: some View { + content(source.snapshot) + } +} + struct ContentView: View { var updateViewModel: UpdateStateModel let windowId: UUID let featureFlags: CmuxFeatureFlags let sidebarUnread: SidebarUnreadModel + let titlebarControlsLayoutModel: TitlebarControlsLayoutModel @MainActor init( updateViewModel: UpdateStateModel, windowId: UUID, featureFlags: CmuxFeatureFlags? = nil, - sidebarUnread: SidebarUnreadModel? = nil + sidebarUnread: SidebarUnreadModel? = nil, + titlebarControlsLayoutModel: TitlebarControlsLayoutModel? = nil ) { self.updateViewModel = updateViewModel self.windowId = windowId self.featureFlags = featureFlags ?? .shared self.sidebarUnread = sidebarUnread ?? TerminalNotificationStore.shared.sidebarUnread + self.titlebarControlsLayoutModel = titlebarControlsLayoutModel + ?? TitlebarControlsLayoutModel() } @EnvironmentObject var tabManager: TabManager @@ -827,7 +851,6 @@ struct ContentView: View { // ContentView itself must not observe it: one agent notification would // otherwise rebuild the terminal, sidebar, and window chrome together. var notificationStore: TerminalNotificationStore { .shared } - @ObservedObject private var titlebarControlsLayoutModel = TitlebarControlsLayoutModel.shared @EnvironmentObject var sidebarState: SidebarState @EnvironmentObject var sidebarSelectionState: SidebarSelectionState @EnvironmentObject var cmuxConfigStore: CmuxConfigStore @@ -1698,6 +1721,7 @@ struct ContentView: View { featureFlags: featureFlags, isPresented: sidebarState.isVisible, sidebarUnread: sidebarUnread, + titlebarControlsLayoutModel: titlebarControlsLayoutModel, windowId: windowId, onSendFeedback: presentFeedbackComposer, onToggleSidebar: { sidebarState.toggle() }, @@ -2850,14 +2874,17 @@ struct ContentView: View { scheduleTitlebarTextRefresh() }) - view = AnyView(view.onReceive(sidebarUnread.$snapshot.dropFirst()) { snapshot in + view = AnyView(view.task { // Update the AppKit-owned pane overlay directly. The titlebar badge // and sidebar rows observe their own leaves, so no ContentView state // mutation is needed for unread changes. - refreshTmuxWorkspacePaneWindowOverlay( - in: observedWindow, - unreadSnapshot: snapshot - ) + for await snapshot in sidebarUnread.snapshotChanges() { + guard !Task.isCancelled else { return } + refreshTmuxWorkspacePaneWindowOverlay( + in: observedWindow, + unreadSnapshot: snapshot + ) + } }) view = AnyView(view.onReceive(NotificationCenter.default.publisher(for: .workspacePaneGeometryDidChange)) { notification in @@ -10490,6 +10517,7 @@ struct VerticalTabsSidebar: View, Equatable { && lhs.fileExplorerState === rhs.fileExplorerState && lhs.featureFlags === rhs.featureFlags && lhs.sidebarUnread === rhs.sidebarUnread + && lhs.titlebarControlsLayoutModel === rhs.titlebarControlsLayoutModel && lhs.isPresented == rhs.isPresented } @@ -10498,6 +10526,7 @@ struct VerticalTabsSidebar: View, Equatable { var featureFlags: CmuxFeatureFlags = .shared var isPresented: Bool = true let sidebarUnread: SidebarUnreadModel + let titlebarControlsLayoutModel: TitlebarControlsLayoutModel let windowId: UUID let onSendFeedback: () -> Void let onToggleSidebar: () -> Void @@ -10563,9 +10592,6 @@ struct VerticalTabsSidebar: View, Equatable { /// notifications) would otherwise stay unrendered until the next /// unrelated sidebar change. The bump forces one fresh rebuild. @State private var appKitPostResizeRefreshToken: UInt64 = 0 - /// The legacy SwiftUI list still consumes unread state at its container - /// boundary. Kept separate so the default AppKit list never subscribes. - @State private var legacyUnreadRefreshToken: UInt64 = 0 @State private var workspaceScrollContentMinHeight: CGFloat = 0 @State private var checklistPopoverWorkspaceId: UUID? // Pending keyed refresh ids are intentionally non-observed. Workspace @@ -10639,13 +10665,16 @@ struct VerticalTabsSidebar: View, Equatable { /// `ForEach(workspaces) { w in Text(w.title) }`) and re-render when it /// changes. A value snapshot built fresh each render, never the store /// itself, so it respects the sidebar snapshot-boundary rule. - private func customSidebarDataContext(now: Date) -> [String: SwiftValue] { + private func customSidebarDataContext( + now: Date, + unreadSnapshot: SidebarUnreadSnapshot + ) -> [String: SwiftValue] { let selectedId = tabManager.selectedTabId let workspaces = tabManager.tabs.enumerated().map { index, workspace in workspace.customSidebarWorkspaceSnapshot( index: index, selectedId: selectedId, - unreadCount: sidebarUnread.unreadCount(forWorkspaceId: workspace.id) + unreadCount: unreadSnapshot.unreadCount(forWorkspaceId: workspace.id) ) } let selectedWorkspace = tabManager.tabs.first { $0.id == selectedId } @@ -10653,7 +10682,7 @@ struct VerticalTabsSidebar: View, Equatable { workspaces: workspaces, selectedWorkspaceId: selectedId, selectedWorkspaceTitle: selectedWorkspace?.customTitle ?? selectedWorkspace?.title ?? "", - totalUnreadCount: sidebarUnread.totalUnreadCount, + totalUnreadCount: unreadSnapshot.totalUnreadCount, now: now ) return CustomSidebarDataContextBuilder().dataContext(for: snapshot) @@ -10800,6 +10829,7 @@ struct VerticalTabsSidebar: View, Equatable { private func minimalModeSidebarTitlebarControlsOverlay() -> some View { MinimalModeSidebarTitlebarControlsOverlay( unreadModel: sidebarUnread, + layoutModel: titlebarControlsLayoutModel, leadingInset: CGFloat(titlebarDebugChromeSnapshot.leftControlsLeadingInset), topPadding: minimalModeSidebarTitlebarControlsTopPadding, onToggleSidebar: onToggleSidebar, @@ -11127,11 +11157,13 @@ struct VerticalTabsSidebar: View, Equatable { ) } else { AnyView( - legacyWorkspaceScrollArea(renderContext: renderContext) - .onAppear { WindowTerminalPortal.usesCoalescedAnchorFailsafe = false } - .onReceive(sidebarUnread.$snapshot.dropFirst()) { _ in - legacyUnreadRefreshToken &+= 1 - } + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + legacyWorkspaceScrollArea( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot + ) + } + .onAppear { WindowTerminalPortal.usesCoalescedAnchorFailsafe = false } ) } } @@ -11195,8 +11227,10 @@ struct VerticalTabsSidebar: View, Equatable { } } - private func legacyWorkspaceScrollArea(renderContext: WorkspaceListRenderContext) -> some View { - let _ = legacyUnreadRefreshToken + private func legacyWorkspaceScrollArea( + renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot + ) -> some View { let scrollInsets = SidebarWorkspaceScrollInsets.workspaceList return GeometryReader { viewport in // Keep viewport geometry as a downward-only layout input. Writing @@ -11209,7 +11243,11 @@ struct VerticalTabsSidebar: View, Equatable { ) ScrollViewReader { scrollProxy in ScrollView(.vertical) { - workspaceScrollContent(renderContext: renderContext, minHeight: contentMinHeight) + workspaceScrollContent( + renderContext: renderContext, + minHeight: contentMinHeight, + unreadSnapshot: unreadSnapshot + ) } .coordinateSpace(name: SidebarPointerInteractionMonitor.coordinateSpaceName) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) @@ -11922,9 +11960,6 @@ struct VerticalTabsSidebar: View, Equatable { private func extensionSidebarScrollArea(renderContext: WorkspaceListRenderContext) -> some View { extensionSidebarScrollAreaContent(renderContext: renderContext) .sidebarProcessTitleObservations(ids: renderContext.workspaceIds, models: renderContext.tabs.map(\.sidebarProcessTitleObservation)) { refreshExtensionSidebarSnapshot() } - .onReceive(sidebarUnread.$snapshot.dropFirst()) { _ in - refreshExtensionSidebarSnapshot() - } .onAppear { refreshExtensionSidebarObservationPublishers(tabs: renderContext.tabs) } .onChange(of: renderContext.workspaceIds) { _, _ in refreshExtensionSidebarObservationPublishers(tabs: renderContext.tabs) @@ -11940,6 +11975,7 @@ struct VerticalTabsSidebar: View, Equatable { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, snapshotUpdateToken: extensionSidebarUpdateToken, + unreadSource: sidebarUnread, actionHandler: { handleCMUXSidebarExtensionAction($0) }, onUseDefaultSidebar: { CmuxExtensionSidebarSelection.setProviderId(CmuxSidebarProviderDescriptor.defaultWorkspacesID) @@ -11975,18 +12011,23 @@ struct VerticalTabsSidebar: View, Equatable { // can mount the other renderer for one tick before flipping; // harmless (the host shuts the short-lived client down on // unmount). - TimelineView(.periodic(from: .now, by: 1)) { timeline in - CustomSidebarSurface( - fileURL: customSidebarURL, - dataContext: customSidebarDataContext(now: timeline.date), - dispatch: makeCmuxSidebarActionDispatch(), - contentInsets: CustomSidebarContentInsets( - top: SidebarWorkspaceScrollInsets.workspaceList.top, - bottom: SidebarWorkspaceScrollInsets.workspaceList.bottom - ), - rendersInProcess: customSidebarRenderer == .inProcess, - client: $sidebarRenderWorkerClient - ) + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + TimelineView(.periodic(from: .now, by: 1)) { timeline in + CustomSidebarSurface( + fileURL: customSidebarURL, + dataContext: customSidebarDataContext( + now: timeline.date, + unreadSnapshot: unreadSnapshot + ), + dispatch: makeCmuxSidebarActionDispatch(), + contentInsets: CustomSidebarContentInsets( + top: SidebarWorkspaceScrollInsets.workspaceList.top, + bottom: SidebarWorkspaceScrollInsets.workspaceList.bottom + ), + rendersInProcess: customSidebarRenderer == .inProcess, + client: $sidebarRenderWorkerClient + ) + } } .mask( SidebarWorkspaceScrollEdgeFadeMask( @@ -11995,9 +12036,19 @@ struct VerticalTabsSidebar: View, Equatable { ) ) } else { - TimelineView(.periodic(from: .now, by: 30)) { timeline in - let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) - extensionSidebarTimelineContent(renderContext: renderContext, model: model, now: timeline.date) + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + TimelineView(.periodic(from: .now, by: 30)) { timeline in + let model = extensionSidebarRenderModel( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot, + now: timeline.date + ) + extensionSidebarTimelineContent( + renderContext: renderContext, + model: model, + now: timeline.date + ) + } } } } @@ -12209,10 +12260,14 @@ struct VerticalTabsSidebar: View, Equatable { private func extensionSidebarRenderModel( renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot, now: Date ) -> CmuxSidebarProviderRenderModel { let _ = extensionSidebarUpdateToken - let snapshot = extensionSidebarSnapshot(renderContext: renderContext) + let snapshot = extensionSidebarSnapshot( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot + ) return extensionSidebarRenderModel(snapshot: snapshot, now: now) } @@ -12240,13 +12295,20 @@ struct VerticalTabsSidebar: View, Equatable { } private func extensionSidebarSnapshot( - renderContext: WorkspaceListRenderContext + renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot ) -> CmuxSidebarProviderSnapshot { - extensionSidebarSnapshot(workspaces: renderContext.tabs) + extensionSidebarSnapshot( + workspaces: renderContext.tabs, + unreadSnapshot: unreadSnapshot + ) } private func extensionSidebarSnapshotForCurrentTabs() -> CmuxSidebarProviderSnapshot { - extensionSidebarSnapshot(workspaces: tabManager.tabs) + extensionSidebarSnapshot( + workspaces: tabManager.tabs, + unreadSnapshot: sidebarUnread.snapshot + ) } private func cmuxSidebarSnapshotForCurrentTabs() -> CmuxSidebarSnapshot { @@ -12465,16 +12527,24 @@ struct VerticalTabsSidebar: View, Equatable { } } - private func extensionSidebarSnapshot(workspaces: [Workspace]) -> CmuxSidebarProviderSnapshot { + private func extensionSidebarSnapshot( + workspaces: [Workspace], + unreadSnapshot: SidebarUnreadSnapshot + ) -> CmuxSidebarProviderSnapshot { CmuxSidebarProviderSnapshot( sequence: UInt64(max(0, CmuxEventBus.shared.latestSequence)), selectedWorkspaceId: tabManager.selectedTabId, - workspaces: workspaces.map(extensionWorkspaceSnapshot(for:)), + workspaces: workspaces.map { + extensionWorkspaceSnapshot(for: $0, unreadSnapshot: unreadSnapshot) + }, windowId: windowId ) } - private func extensionWorkspaceSnapshot(for workspace: Workspace) -> CmuxSidebarProviderWorkspace { + private func extensionWorkspaceSnapshot( + for workspace: Workspace, + unreadSnapshot: SidebarUnreadSnapshot + ) -> CmuxSidebarProviderWorkspace { let rootPath = extensionSidebarRootPath(for: workspace) return CmuxSidebarProviderWorkspace( id: workspace.id, @@ -12486,8 +12556,8 @@ struct VerticalTabsSidebar: View, Equatable { branchSummary: workspace.sidebarGitBranchesInDisplayOrder().first?.branch, remoteDisplayTarget: workspace.remoteDisplayTarget, remoteConnectionState: workspace.remoteConnectionState.rawValue, - unreadCount: sidebarUnread.unreadCount(forWorkspaceId: workspace.id), - latestNotificationText: sidebarUnread.latestNotificationText(forWorkspaceId: workspace.id), + unreadCount: unreadSnapshot.unreadCount(forWorkspaceId: workspace.id), + latestNotificationText: unreadSnapshot.latestNotificationText(forWorkspaceId: workspace.id), latestSubmittedMessage: workspace.latestSubmittedMessage, latestSubmittedAt: workspace.latestSubmittedAt, listeningPorts: workspace.listeningPorts, @@ -13009,7 +13079,13 @@ struct VerticalTabsSidebar: View, Equatable { } private func extensionWorkspaceSnapshot(for workspaceId: UUID) -> CmuxSidebarProviderWorkspace? { - tabManager.tabs.first { $0.id == workspaceId }.map(extensionWorkspaceSnapshot(for:)) + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }) else { + return nil + } + return extensionWorkspaceSnapshot( + for: workspace, + unreadSnapshot: sidebarUnread.snapshot + ) } private func extensionSidebarTreeSectionTitle(_ section: CmuxSidebarProviderTreeSection) -> String { @@ -13059,7 +13135,8 @@ struct VerticalTabsSidebar: View, Equatable { private func workspaceScrollContent( renderContext: WorkspaceListRenderContext, - minHeight: CGFloat + minHeight: CGFloat, + unreadSnapshot: SidebarUnreadSnapshot ) -> some View { let signpost = SidebarProfilingSignposts.begin("sidebar-scroll-content", "workspaces=\(renderContext.workspaceCount) renderItems=\(renderContext.workspaceRenderItems.count) minHeight=\(minHeight)"); defer { SidebarProfilingSignposts.end(signpost) } let shouldCollectWorkspaceDropTargets = SidebarDropPlanner().shouldCollectWorkspaceDropTargets( @@ -13074,7 +13151,8 @@ struct VerticalTabsSidebar: View, Equatable { // #5845; regressed by #6033). Drop/tap = background; indicator on rows. let content = workspaceRows( renderContext: renderContext, - shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets + shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets, + unreadSnapshot: unreadSnapshot ) .overlay(alignment: .bottom) { if emptyAreaTopDropIndicatorVisible() { @@ -13135,14 +13213,15 @@ struct VerticalTabsSidebar: View, Equatable { @ViewBuilder private func workspaceRows( renderContext: WorkspaceListRenderContext, - shouldCollectWorkspaceDropTargets: Bool + shouldCollectWorkspaceDropTargets: Bool, + unreadSnapshot: SidebarUnreadSnapshot ) -> some View { let signpost = SidebarProfilingSignposts.begin("sidebar-workspace-rows", "renderItems=\(renderContext.workspaceRenderItems.count) collectDropTargets=\(shouldCollectWorkspaceDropTargets)") let renderItems = renderContext.workspaceRenderItems // Reduce live models to cheap immutable values above the LazyVStack. // Shared notification/selection projections are built once here; full // row trees and row-specific closure binding remain lazy. - let unreadSummariesByWorkspaceId = sidebarUnread.summaryByWorkspaceId + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let notificationIndex = SidebarWorkspaceNotificationIndex( notifications: notificationStore.notifications ) diff --git a/Sources/DockPanelView.swift b/Sources/DockPanelView.swift index 7d616f9cc813..113cd4f70b16 100644 --- a/Sources/DockPanelView.swift +++ b/Sources/DockPanelView.swift @@ -1,6 +1,7 @@ import AppKit import Bonsplit import CmuxAppKitSupportUI +import CmuxNotifications import CmuxTerminal import SwiftUI diff --git a/Sources/DockUnreadPanelProjection.swift b/Sources/DockUnreadPanelProjection.swift index ea5aac982274..7e0f78c10a0b 100644 --- a/Sources/DockUnreadPanelProjection.swift +++ b/Sources/DockUnreadPanelProjection.swift @@ -1,4 +1,4 @@ -import Combine +import CmuxNotifications import Foundation import Observation @@ -14,7 +14,7 @@ final class DockUnreadPanelProjection { @ObservationIgnored private var isActive = false @ObservationIgnored private var unreadSurfaceKeys: Set @ObservationIgnored private var focusedReadIndicatorByWorkspaceID: [UUID: UUID] - @ObservationIgnored private var unreadSubscription: AnyCancellable? + @ObservationIgnored private nonisolated(unsafe) var unreadTask: Task? init( source: SidebarUnreadModel, @@ -28,11 +28,11 @@ final class DockUnreadPanelProjection { unreadSurfaceKeys = source.snapshot.unreadSurfaceKeys focusedReadIndicatorByWorkspaceID = source.snapshot.focusedReadIndicatorByWorkspaceId refresh() - unreadSubscription = source.$snapshot.sink { [weak self] snapshot in - // The publisher is main-actor-owned and emits one complete value - // from SidebarUnreadModel.apply(). - MainActor.assumeIsolated { - self?.receive( + let changes = source.snapshotChanges() + unreadTask = Task { @MainActor [weak self] in + for await snapshot in changes { + guard let self, !Task.isCancelled else { return } + self.receive( unreadSurfaceKeys: snapshot.unreadSurfaceKeys, focusedReadIndicatorByWorkspaceID: snapshot.focusedReadIndicatorByWorkspaceId ) @@ -40,6 +40,10 @@ final class DockUnreadPanelProjection { } } + deinit { + unreadTask?.cancel() + } + func updateContext(panelIDs: Set, isActive: Bool) { guard self.panelIDs != panelIDs || self.isActive != isActive else { return } self.panelIDs = panelIDs diff --git a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift index 78302cfbf1da..4e3f2412a2a9 100644 --- a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift +++ b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift @@ -1,8 +1,10 @@ import AppKit +import CmuxNotifications import SwiftUI struct MinimalModeSidebarTitlebarControlsOverlay: View { let unreadModel: SidebarUnreadModel + let layoutModel: TitlebarControlsLayoutModel let leadingInset: CGFloat let topPadding: CGFloat let onToggleSidebar: () -> Void @@ -22,6 +24,7 @@ struct MinimalModeSidebarTitlebarControlsOverlay: View { if isMinimalMode { HiddenTitlebarSidebarControlsView( unreadModel: unreadModel, + layoutModel: layoutModel, onToggleSidebar: onToggleSidebar, onToggleNotifications: onToggleNotifications, onNewTab: onNewTab, diff --git a/Sources/Panels/CustomSidebarPaneDataContextCache.swift b/Sources/Panels/CustomSidebarPaneDataContextCache.swift index cc5f712e2759..39b35069abce 100644 --- a/Sources/Panels/CustomSidebarPaneDataContextCache.swift +++ b/Sources/Panels/CustomSidebarPaneDataContextCache.swift @@ -1,4 +1,5 @@ import CmuxSidebar +import CmuxNotifications import CmuxSwiftRender import Foundation diff --git a/Sources/Panels/CustomSidebarPanelView.swift b/Sources/Panels/CustomSidebarPanelView.swift index 5fe8535d7609..e20c23d82e2d 100644 --- a/Sources/Panels/CustomSidebarPanelView.swift +++ b/Sources/Panels/CustomSidebarPanelView.swift @@ -1,4 +1,5 @@ import CmuxAppKitSupportUI +import CmuxNotifications import CmuxSettings import CmuxSettingsUI import CmuxSidebar diff --git a/Sources/Panels/PanelContentView.swift b/Sources/Panels/PanelContentView.swift index 8e868a7193a6..ca69eabbbd02 100644 --- a/Sources/Panels/PanelContentView.swift +++ b/Sources/Panels/PanelContentView.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxNotifications import SwiftUI import Foundation import Bonsplit diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift index c3e644422fed..d70c4be5b769 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift @@ -1,8 +1,8 @@ import AppKit import Bonsplit -import Combine import CmuxAppKitSupportUI import CmuxFoundation +import CmuxNotifications import SwiftUI /// Main-actor owner of the default sidebar table lifecycle and its AppKit interactions. @@ -34,7 +34,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private var appKitDropIndicatorIncludesRowTargets = false private weak var unreadSource: SidebarUnreadModel? private var unreadSnapshot = SidebarUnreadSnapshot() - private var unreadCancellable: AnyCancellable? + private nonisolated(unsafe) var unreadTask: Task? private var clipBoundsObserver: NSObjectProtocol? private var resizeDidEndObserver: NSObjectProtocol? private lazy var mutationScheduler = SidebarWorkspaceTableMutationScheduler( @@ -61,7 +61,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS NotificationCenter.default.removeObserver(resizeDidEndObserver) } previewBailoutTask?.cancel() - unreadCancellable?.cancel() + unreadTask?.cancel() } func makeContainerView() -> SidebarWorkspaceTableContainerView { let container = SidebarWorkspaceTableContainerView() @@ -161,8 +161,8 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS let postUpdateActions = detachLoadedCells() workspaceDragSessionDidEnd() actions = nil - unreadCancellable?.cancel() - unreadCancellable = nil + unreadTask?.cancel() + unreadTask = nil unreadSource = nil unreadSnapshot = SidebarUnreadSnapshot() rows.removeAll(keepingCapacity: false) @@ -186,17 +186,16 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS /// `VerticalTabsSidebar.body` and its O(workspaces) row construction. func setUnreadSource(_ source: SidebarUnreadModel) { guard unreadSource !== source else { return } - unreadCancellable?.cancel() + unreadTask?.cancel() unreadSource = source unreadSnapshot = source.snapshot - unreadCancellable = source.$snapshot - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] snapshot in - MainActor.assumeIsolated { - self?.applyUnreadSnapshot(snapshot) - } + let changes = source.snapshotChanges() + unreadTask = Task { @MainActor [weak self] in + for await snapshot in changes { + guard let self, !Task.isCancelled else { return } + self.applyUnreadSnapshot(snapshot) } + } } private func applyUnreadSnapshot(_ nextSnapshot: SidebarUnreadSnapshot) { diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift index 48d94c782ce4..8790b4c03690 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift @@ -1,3 +1,4 @@ +import CmuxNotifications import SwiftUI struct SidebarWorkspaceTableContextMenuActions { diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift index 32e101e0bb57..821c1a3e153b 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift @@ -1,3 +1,4 @@ +import CmuxNotifications import SwiftUI /// Container-level bridge mounting the AppKit-owned default workspace list once. diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 7a25a66a107f..9de79c65c61d 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxNotifications import AppKit import Combine import Foundation @@ -2310,146 +2311,3 @@ final class TerminalNotificationStore: ObservableObject { NSApp?.dockTile.badgeLabel = label } } - -/// Immutable per-workspace unread projection rendered by the sidebar. Equatable -/// so the coalesced model only republishes when a workspace's badge or -/// latest-message text actually changes. `latestNotificationText` is the -/// trimmed body-or-title of the latest notification (read or unread) and is NOT -/// gated by the `showsSidebarNotificationMessage` setting; the sidebar applies -/// that gate at its read site. -struct SidebarWorkspaceUnreadSummary: Equatable { - var unreadCount: Int - var latestNotificationText: String? - var hasLatestNotification: Bool = false -} - -/// Workspace + surface pair used to mirror the store's per-surface unread set. -struct SidebarSurfaceUnreadKey: Hashable { - var workspaceId: UUID - var surfaceId: UUID? -} - -/// One atomic unread-state publication. A single notification can change the -/// total, workspace summary, and surface indicator together; publishing those -/// fields independently makes every observer render several intermediate -/// states for one logical update. -struct SidebarUnreadSnapshot: Equatable { - var totalUnreadCount: Int = 0 - var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:] - var unreadSurfaceKeys: Set = [] - var focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:] - var manualUnreadWorkspaceIds: Set = [] - - func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { - summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary( - unreadCount: 0, - latestNotificationText: nil - ) - } - - func unreadCount(forWorkspaceId id: UUID) -> Int { - summary(forWorkspaceId: id).unreadCount - } - - func latestNotificationText(forWorkspaceId id: UUID) -> String? { - summary(forWorkspaceId: id).latestNotificationText - } - - func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { - unreadCount(forWorkspaceId: id) > 0 - } - - func hasManualUnread(forWorkspaceId id: UUID) -> Bool { - manualUnreadWorkspaceIds.contains(id) - } - - func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) - } - - func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || - (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) - } - - func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { workspaceIsUnread(forWorkspaceId: $0) } - } - - func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } - } -} - -/// Lightweight observable for leaf unread consumers such as the workspace -/// sidebar and titlebar badge. `TerminalNotificationStore` drives it from its -/// single `refreshUnreadPresentation()` hub with one atomic, equality-guarded -/// snapshot, so one logical notification cannot publish several intermediate -/// renders. `ContentView` deliberately keeps an unobserved reference and routes -/// pane-overlay updates directly. The query methods mirror the equivalent -/// `TerminalNotificationStore` reads so callers can switch source without a -/// behavior change. -@MainActor -final class SidebarUnreadModel: ObservableObject { - @Published private(set) var snapshot = SidebarUnreadSnapshot() - - var totalUnreadCount: Int { snapshot.totalUnreadCount } - var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] { snapshot.summaryByWorkspaceId } - var unreadSurfaceKeys: Set { snapshot.unreadSurfaceKeys } - var focusedReadIndicatorByWorkspaceId: [UUID: UUID] { snapshot.focusedReadIndicatorByWorkspaceId } - var manualUnreadWorkspaceIds: Set { snapshot.manualUnreadWorkspaceIds } - - func apply( - totalUnreadCount: Int, - summaries: [UUID: SidebarWorkspaceUnreadSummary], - unreadSurfaceKeys: Set, - focusedReadIndicatorByWorkspaceId: [UUID: UUID], - manualUnreadWorkspaceIds: Set - ) { - let next = SidebarUnreadSnapshot( - totalUnreadCount: totalUnreadCount, - summaryByWorkspaceId: summaries, - unreadSurfaceKeys: unreadSurfaceKeys, - focusedReadIndicatorByWorkspaceId: focusedReadIndicatorByWorkspaceId, - manualUnreadWorkspaceIds: manualUnreadWorkspaceIds - ) - guard snapshot != next else { return } - snapshot = next - } - - func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { - snapshot.summary(forWorkspaceId: id) - } - - func unreadCount(forWorkspaceId id: UUID) -> Int { - snapshot.unreadCount(forWorkspaceId: id) - } - - func latestNotificationText(forWorkspaceId id: UUID) -> String? { - snapshot.latestNotificationText(forWorkspaceId: id) - } - - func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { - snapshot.workspaceIsUnread(forWorkspaceId: id) - } - - func hasManualUnread(forWorkspaceId id: UUID) -> Bool { - snapshot.hasManualUnread(forWorkspaceId: id) - } - - func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - snapshot.hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) - } - - func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - snapshot.hasVisibleNotificationIndicator(forWorkspaceId: id, surfaceId: surfaceId) - } - - func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { - snapshot.canMarkWorkspaceRead(forWorkspaceIds: ids) - } - - func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { - snapshot.canMarkWorkspaceUnread(forWorkspaceIds: ids) - } -} diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 3f350ab0aa72..2c90b6a25aac 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -2,9 +2,11 @@ import AppKit import Bonsplit import Combine import CmuxFoundation +import CmuxNotifications import CmuxSettings import CmuxSettingsUI import CmuxTestSupport +import Observation import SwiftUI enum TitlebarControlsStyle: Int, CaseIterable, Identifiable { @@ -149,17 +151,18 @@ struct TitlebarControlsLayoutModelSnapshot: Equatable { /// titlebar surface. Unrelated defaults and notification activity must not /// invalidate titlebar geometry. @MainActor -final class TitlebarControlsLayoutModel: ObservableObject { +@Observable +final class TitlebarControlsLayoutModel { typealias ContentSizeProvider = (TitlebarControlsStyleConfig) -> NSSize - static let shared = TitlebarControlsLayoutModel() - - @Published private(set) var snapshot: TitlebarControlsLayoutModelSnapshot + private(set) var snapshot: TitlebarControlsLayoutModelSnapshot private let defaults: UserDefaults - private let notificationCenter: NotificationCenter + @ObservationIgnored + private nonisolated(unsafe) let notificationCenter: NotificationCenter private let contentSizeProvider: ContentSizeProvider - private var observers: [NSObjectProtocol] = [] + @ObservationIgnored + private nonisolated(unsafe) var observers: [NSObjectProtocol] = [] init( defaults: UserDefaults = .standard, @@ -208,9 +211,14 @@ final class TitlebarControlsLayoutModel: ObservableObject { } deinit { + removeObservers() + } + + private nonisolated func removeObservers() { for observer in observers { notificationCenter.removeObserver(observer) } + observers.removeAll() } private func refreshStyleIfNeeded() { @@ -960,7 +968,7 @@ private final class TitlebarControlRightClickNSView: NSView { } private struct TitlebarNotificationBadge: View { - @ObservedObject var unreadModel: SidebarUnreadModel + let unreadModel: SidebarUnreadModel let config: TitlebarControlsStyleConfig @Environment(\.cmuxGlobalFontMagnificationPercent) private var globalFontPercent @@ -983,7 +991,7 @@ private struct TitlebarNotificationBadge: View { struct TitlebarControlsView: View { let unreadModel: SidebarUnreadModel - @ObservedObject var layoutModel: TitlebarControlsLayoutModel + let layoutModel: TitlebarControlsLayoutModel @ObservedObject var viewModel: TitlebarControlsViewModel let onToggleSidebar: () -> Void let onToggleNotifications: () -> Void @@ -1478,6 +1486,7 @@ private struct MinimalModeTitlebarButtonHitRegionView: NSViewRepresentable { struct HiddenTitlebarSidebarControlsView: View { let unreadModel: SidebarUnreadModel + let layoutModel: TitlebarControlsLayoutModel let onToggleSidebar: () -> Void let onToggleNotifications: (NSView?) -> Void let onNewTab: () -> Void @@ -1488,8 +1497,6 @@ struct HiddenTitlebarSidebarControlsView: View { @State private var isHoveringHost = false @State private var isHoveringWindowChrome = false @State private var hostWindowNumber: Int? - @ObservedObject private var layoutModel = TitlebarControlsLayoutModel.shared - private var shouldPinControls: Bool { isHoveringHost || isHoveringWindowChrome || popoverVisibilityState.isShown(in: hostWindowNumber) } @@ -1894,14 +1901,16 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private var windowGeometryObservers: [NSObjectProtocol] = [] private let viewModel = TitlebarControlsViewModel() private var userDefaultsObserver: NSObjectProtocol? - private var layoutModelCancellable: AnyCancellable? private var lastShowsWorkspaceTitlebar = !WorkspacePresentationModeSettings.isMinimal() var popoverIsShownForTesting: Bool { notificationsPopover.isShown } private var showsWorkspaceTitlebar: Bool { !WorkspacePresentationModeSettings.isMinimal() } - init(notificationStore: TerminalNotificationStore, settingsRuntime: SettingsRuntime?) { + init( + notificationStore: TerminalNotificationStore, + settingsRuntime: SettingsRuntime?, + layoutModel: TitlebarControlsLayoutModel + ) { let containerView = TitlebarAccessoryContainerView() - let layoutModel = TitlebarControlsLayoutModel.shared self.containerView = containerView self.notificationStore = notificationStore self.layoutModel = layoutModel @@ -1969,17 +1978,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont self.restoreSizeAfterMinimalMode() } } - layoutModelCancellable = layoutModel.$snapshot - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - MainActor.assumeIsolated { - self?.scheduleSizeUpdate( - invalidateIntrinsicSize: true, - invalidateLayout: true - ) - } - } + observeLayoutModel() applyWorkspaceTitlebarVisibility() scheduleSizeUpdate(invalidateIntrinsicSize: true) @@ -2002,6 +2001,21 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont scheduleSizeUpdate(invalidateIntrinsicSize: true) } + private func observeLayoutModel() { + withObservationTracking { + _ = layoutModel.snapshot + } onChange: { [weak self] in + Task { @MainActor [weak self] in + guard let self else { return } + self.scheduleSizeUpdate( + invalidateIntrinsicSize: true, + invalidateLayout: true + ) + self.observeLayoutModel() + } + } + } + override func viewDidLayout() { super.viewDidLayout() let observedWindowChanged = updateObservedWindowIfNeeded() @@ -2598,6 +2612,7 @@ private struct NotificationsPopoverView: View { final class UpdateTitlebarAccessoryController { private let updateLog: UpdateLogStore private let settingsRuntime: SettingsRuntime? + private let layoutModel: TitlebarControlsLayoutModel private var didStart = false private let attachedWindows = NSHashTable.weakObjects() private var observers: [NSObjectProtocol] = [] @@ -2609,9 +2624,14 @@ final class UpdateTitlebarAccessoryController { private var detachedNotificationsPopover: NSPopover? private var detachedNotificationsPopoverDelegate: DetachedNotificationsPopoverDelegate? - init(updateLog: UpdateLogStore, settingsRuntime: SettingsRuntime?) { + init( + updateLog: UpdateLogStore, + settingsRuntime: SettingsRuntime?, + layoutModel: TitlebarControlsLayoutModel + ) { self.updateLog = updateLog self.settingsRuntime = settingsRuntime + self.layoutModel = layoutModel } deinit { @@ -2757,7 +2777,8 @@ final class UpdateTitlebarAccessoryController { if !window.titlebarAccessoryViewControllers.contains(where: { $0.view.identifier == controlsIdentifier }) { let controls = TitlebarControlsAccessoryViewController( notificationStore: TerminalNotificationStore.shared, - settingsRuntime: settingsRuntime + settingsRuntime: settingsRuntime, + layoutModel: layoutModel ) controls.layoutAttribute = .left controls.view.identifier = controlsIdentifier diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index c9bf1c77875c..15a0204686a5 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -1,5 +1,6 @@ import AppKit import CmuxFoundation +import CmuxNotifications import SwiftUI import CmuxSettings import CmuxWorkspaces diff --git a/cmuxTests/DockRuntimeParityTests.swift b/cmuxTests/DockRuntimeParityTests.swift index ed10f8397347..118a80fca9a0 100644 --- a/cmuxTests/DockRuntimeParityTests.swift +++ b/cmuxTests/DockRuntimeParityTests.swift @@ -2,6 +2,7 @@ import AppKit import Bonsplit import Combine import CmuxControlSocket +import CmuxNotifications import CmuxTerminal import Foundation import Testing diff --git a/cmuxTests/FileDropOverlayViewTests.swift b/cmuxTests/FileDropOverlayViewTests.swift index 430fb5443297..c4eaec78ab0b 100644 --- a/cmuxTests/FileDropOverlayViewTests.swift +++ b/cmuxTests/FileDropOverlayViewTests.swift @@ -4,6 +4,7 @@ import SwiftUI import Testing import WebKit import CmuxUpdater +import CmuxNotifications #if canImport(cmux_DEV) @testable import cmux_DEV @@ -20,12 +21,6 @@ struct FileDropOverlayViewTests { let root = ContentView(updateViewModel: UpdateStateModel(), windowId: windowId) .environmentObject(TabManager()) .environmentObject(TerminalNotificationStore.shared) - // The sidebar reads SidebarUnreadModel from the environment. A missing - // @EnvironmentObject is a SwiftUI fatalError rather than a nil, so leaving it out does - // not fail this test, it kills the app host and discards every verdict still pending in - // it. The model belongs to the notification store, so hand over that store's instance - // rather than a detached one. - .environmentObject(TerminalNotificationStore.shared.sidebarUnread) .environmentObject(SidebarState()) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) diff --git a/cmuxTests/SidebarHiddenPresentationTests.swift b/cmuxTests/SidebarHiddenPresentationTests.swift index 239641602941..ac26b7d65693 100644 --- a/cmuxTests/SidebarHiddenPresentationTests.swift +++ b/cmuxTests/SidebarHiddenPresentationTests.swift @@ -215,7 +215,6 @@ struct SidebarHiddenPresentationTests { ) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(sidebarState) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) diff --git a/cmuxTests/SidebarLazyLayoutScaleTests.swift b/cmuxTests/SidebarLazyLayoutScaleTests.swift index 2d1733d4e413..d509d535d657 100644 --- a/cmuxTests/SidebarLazyLayoutScaleTests.swift +++ b/cmuxTests/SidebarLazyLayoutScaleTests.swift @@ -1,6 +1,7 @@ import Testing import AppKit import CmuxSidebar +import CmuxNotifications import CmuxUpdater import SwiftUI @@ -159,7 +160,6 @@ final class SidebarLazyLayoutScaleTests { ) .frame(width: 280) .environmentObject(tabManager) - .environmentObject(unread) .environmentObject(CmuxConfigStore()) .environmentObject(TerminalNotificationStore.shared) .environmentObject(SidebarState()) diff --git a/cmuxTests/SidebarPointerInteractionScaleTests.swift b/cmuxTests/SidebarPointerInteractionScaleTests.swift index fbf46752ff8d..9289485830ad 100644 --- a/cmuxTests/SidebarPointerInteractionScaleTests.swift +++ b/cmuxTests/SidebarPointerInteractionScaleTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxSidebar +import CmuxNotifications import CoreGraphics import OSLog import Testing diff --git a/cmuxTests/TitlebarInteractiveControlTests.swift b/cmuxTests/TitlebarInteractiveControlTests.swift index 23aac6b6419f..97a2d5d3325a 100644 --- a/cmuxTests/TitlebarInteractiveControlTests.swift +++ b/cmuxTests/TitlebarInteractiveControlTests.swift @@ -151,7 +151,11 @@ struct TitlebarInteractiveControlTests { defer { window.orderOut(nil) } window.isMovable = false - let controller = TitlebarControlsAccessoryViewController(notificationStore: TerminalNotificationStore.shared, settingsRuntime: nil) + let controller = TitlebarControlsAccessoryViewController( + notificationStore: TerminalNotificationStore.shared, + settingsRuntime: nil, + layoutModel: TitlebarControlsLayoutModel() + ) let container = controller.view container.frame = NSRect(x: 0, y: 0, width: 180, height: 44) window.contentView = container @@ -185,7 +189,11 @@ struct TitlebarInteractiveControlTests { @Test func accessoryControlsRemainNonDraggable() { _ = NSApplication.shared - let controller = TitlebarControlsAccessoryViewController(notificationStore: TerminalNotificationStore.shared, settingsRuntime: nil) + let controller = TitlebarControlsAccessoryViewController( + notificationStore: TerminalNotificationStore.shared, + settingsRuntime: nil, + layoutModel: TitlebarControlsLayoutModel() + ) let container = controller.view container.frame = NSRect(x: 0, y: 0, width: 180, height: 44) diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index 66c9ff3240bd..395f8517dccc 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -1,8 +1,9 @@ import Testing import AppKit -import Combine +import CmuxNotifications import CmuxUpdater import CoreGraphics +import Observation import SwiftUI import Bonsplit @@ -205,7 +206,6 @@ final class WorkspaceContentViewVisibilityTests { let root = ContentView(updateViewModel: UpdateStateModel(), windowId: UUID()) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(SidebarState()) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) @@ -285,7 +285,6 @@ final class WorkspaceContentViewVisibilityTests { ) .environmentObject(tabManager) .environmentObject(TerminalNotificationStore.shared) - .environmentObject(unread) .environmentObject(SidebarState()) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) @@ -368,7 +367,9 @@ final class WorkspaceContentViewVisibilityTests { let surfaceId = UUID() let unread = SidebarUnreadModel() var publicationCount = 0 - let cancellable = unread.objectWillChange.sink { + withObservationTracking { + _ = unread.snapshot + } onChange: { publicationCount += 1 } let summaries = [ @@ -392,6 +393,11 @@ final class WorkspaceContentViewVisibilityTests { ) #expect(publicationCount == 1) + withObservationTracking { + _ = unread.snapshot + } onChange: { + publicationCount += 1 + } unread.apply( totalUnreadCount: 1, summaries: summaries, @@ -400,7 +406,6 @@ final class WorkspaceContentViewVisibilityTests { manualUnreadWorkspaceIds: manualUnreadWorkspaceIds ) #expect(publicationCount == 1, "Applying an equivalent snapshot must stay silent.") - withExtendedLifetime(cancellable) {} } @Test From d5d163f2341c3fde1bc955d3edc1eb23e840bb01 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 19:54:20 -0700 Subject: [PATCH 14/36] Fix restore argument helper compilation --- ...faceResumeCommandCanonicalizer+PortableAgentExecutable.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift b/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift index b839d2bca528..f02983b1a30a 100644 --- a/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift +++ b/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift @@ -75,7 +75,7 @@ extension SurfaceResumeBindingSnapshot { !value.isEmpty else { return nil } - AgentRestoreCLIArgument(rawValue: value)?.rawValue + return AgentRestoreCLIArgument(rawValue: value)?.rawValue } private func resolvedStartupCommand(repairPortableAgentExecutable: Bool) -> String { From 4f18eec928cc855200dbd60008bf54d4b1985b48 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 20:06:37 -0700 Subject: [PATCH 15/36] Address unread ownership review findings --- .../SidebarUnreadSnapshotTests.swift | 15 +++++++++- ...MUXInstalledExtensionSidebarHostView.swift | 9 +++++- Sources/ContentView.swift | 8 ++++-- Sources/DockUnreadPanelProjection.swift | 2 ++ .../SidebarWorkspaceTableController.swift | 2 ++ .../VerticalTabsSidebar+WorkspaceGroups.swift | 28 +++++++++---------- 6 files changed, 45 insertions(+), 19 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift index d9a8a764cedf..2ebb1f5651f0 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -1,4 +1,6 @@ import Foundation +import Observation +import os import Testing @testable import CmuxNotifications @@ -57,7 +59,12 @@ struct SidebarUnreadSnapshotTests { let first = await iterator.next() #expect(first == model.snapshot) - var nextIterator = model.snapshotChanges().makeAsyncIterator() + let publicationCount = OSAllocatedUnfairLock(initialState: 0) + withObservationTracking { + _ = model.snapshot + } onChange: { + publicationCount.withLock { $0 += 1 } + } model.apply( totalUnreadCount: 1, summaries: [ @@ -70,6 +77,12 @@ struct SidebarUnreadSnapshotTests { focusedReadIndicatorByWorkspaceId: [:], manualUnreadWorkspaceIds: [] ) + #expect( + publicationCount.withLock { $0 } == 0, + "An equivalent snapshot must not publish." + ) + + var nextIterator = model.snapshotChanges().makeAsyncIterator() model.apply( totalUnreadCount: 0, summaries: [:], diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 574d9f3f58de..94bb9ce080e4 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -168,6 +168,10 @@ private final class CMUXSidebarSnapshotCache { snapshot = next return next } + + func containsWorkspaces(_ workspaceIDs: [UUID]) -> Bool { + snapshot?.workspaces.map(\.id) == workspaceIDs + } } struct CMUXInstalledExtensionSidebarHostView: View { @@ -175,6 +179,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" var snapshotProvider: @MainActor () -> CmuxSidebarSnapshot + var workspaceIDsProvider: @MainActor () -> [UUID] var snapshotUpdateToken: UInt64 = 0 let unreadSource: SidebarUnreadModel var actionHandler: @MainActor (CmuxSidebarAction) -> CmuxSidebarActionResult @@ -305,7 +310,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { .task { for await unreadSnapshot in unreadSource.snapshotChanges() { guard !Task.isCancelled else { return } - if snapshotCache.snapshot == nil { + // Rebuild rich metadata only when workspace membership changed. + // The common unread-only path stays a cheap cache patch. + if !snapshotCache.containsWorkspaces(workspaceIDsProvider()) { _ = snapshotCache.replace(with: snapshotProvider()) } guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { continue } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 2170ee3cf730..6c737fd994f6 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -11552,7 +11552,8 @@ struct VerticalTabsSidebar: View, Equatable { // whether a change class re-renders the sidebar subtree or skips it. cmuxDebugLog("sidebar.table.rowsBuild items=\(renderContext.workspaceRenderItems.count)") #endif - let unreadSummariesByWorkspaceId = sidebarUnread.summaryByWorkspaceId + let unreadSnapshot = sidebarUnread.snapshot + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let notificationIndex = SidebarWorkspaceNotificationIndex( notifications: notificationStore.notifications ) @@ -11573,7 +11574,7 @@ struct VerticalTabsSidebar: View, Equatable { group: group, memberWorkspaceIds: renderContext.memberWorkspaceIdsByGroupId[group.id] ?? [], renderContext: renderContext, - unreadSummariesByWorkspaceId: unreadSummariesByWorkspaceId, + unreadSnapshot: unreadSnapshot, notificationIndex: notificationIndex, shouldCollectWorkspaceDropTargets: false ) @@ -11974,6 +11975,7 @@ struct VerticalTabsSidebar: View, Equatable { if effectiveExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, + workspaceIDsProvider: { tabManager.tabs.map(\.id) }, snapshotUpdateToken: extensionSidebarUpdateToken, unreadSource: sidebarUnread, actionHandler: { handleCMUXSidebarExtensionAction($0) }, @@ -13243,7 +13245,7 @@ struct VerticalTabsSidebar: View, Equatable { group: group, memberWorkspaceIds: renderContext.memberWorkspaceIdsByGroupId[group.id] ?? [], renderContext: renderContext, - unreadSummariesByWorkspaceId: unreadSummariesByWorkspaceId, + unreadSnapshot: unreadSnapshot, notificationIndex: notificationIndex, shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets ) diff --git a/Sources/DockUnreadPanelProjection.swift b/Sources/DockUnreadPanelProjection.swift index 7e0f78c10a0b..53e0d40df9b4 100644 --- a/Sources/DockUnreadPanelProjection.swift +++ b/Sources/DockUnreadPanelProjection.swift @@ -14,6 +14,8 @@ final class DockUnreadPanelProjection { @ObservationIgnored private var isActive = false @ObservationIgnored private var unreadSurfaceKeys: Set @ObservationIgnored private var focusedReadIndicatorByWorkspaceID: [UUID: UUID] + // Written only by init and deinit. The unsafe escape exists solely so + // nonisolated deinit can cancel it. @ObservationIgnored private nonisolated(unsafe) var unreadTask: Task? init( diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift index d70c4be5b769..692015cbc827 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift @@ -34,6 +34,8 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private var appKitDropIndicatorIncludesRowTargets = false private weak var unreadSource: SidebarUnreadModel? private var unreadSnapshot = SidebarUnreadSnapshot() + // Written only by setUnreadSource(), dismantleContainerView(), and deinit. + // The unsafe escape exists solely so nonisolated deinit can cancel it. private nonisolated(unsafe) var unreadTask: Task? private var clipBoundsObserver: NSObjectProtocol? private var resizeDidEndObserver: NSObjectProtocol? diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 15a0204686a5..f0fd2f9b0547 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -248,10 +248,11 @@ extension VerticalTabsSidebar { group: WorkspaceGroup, memberWorkspaceIds: [UUID], renderContext: WorkspaceListRenderContext, - unreadSummariesByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary], + unreadSnapshot: SidebarUnreadSnapshot, notificationIndex: SidebarWorkspaceNotificationIndex, shouldCollectWorkspaceDropTargets: Bool ) -> SidebarWorkspaceGroupRowSnapshot { + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let settings = renderContext.tabItemSettings let isAnchorActive = tabManager.selectedTabId == group.anchorWorkspaceId let isMultiSelected = selectedTabIds.contains(group.anchorWorkspaceId) @@ -281,13 +282,12 @@ extension VerticalTabsSidebar { } return unreadSummariesByWorkspaceId[group.anchorWorkspaceId]?.unreadCount ?? 0 }() - let anchorIds = [group.anchorWorkspaceId] - let canMarkAnchorRead = anchorIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) > 0 - } - let canMarkAnchorUnread = anchorIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) == 0 - } + let canMarkAnchorRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: [group.anchorWorkspaceId] + ) + let canMarkAnchorUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: [group.anchorWorkspaceId] + ) let anchorHasLatestNotification = notificationIndex.hasNotification( workspaceId: group.anchorWorkspaceId ) @@ -295,12 +295,12 @@ extension VerticalTabsSidebar { // never the anchor: the anchor is the group's own row, whose read status // is owned by the separate "Mark Group as Read/Unread" actions. let nonAnchorMemberIds = memberWorkspaceIds.filter { $0 != group.anchorWorkspaceId } - let canMarkAllRead = nonAnchorMemberIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) > 0 - } - let canMarkAllUnread = nonAnchorMemberIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) == 0 - } + let canMarkAllRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + let canMarkAllUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) let rowId = SidebarWorkspaceRenderItemID.group(group.id) let isPointerHovering = pointerInteractionMonitor.hoveredRowId == rowId let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate().topVisible( From 1c212ee5fd98d267e5be4f18a5c5d14a44fc35d1 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 20:08:56 -0700 Subject: [PATCH 16/36] Publish refreshed extension membership snapshots --- Sources/CMUXInstalledExtensionSidebarHostView.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 94bb9ce080e4..1e8f49b922b5 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -312,10 +312,15 @@ struct CMUXInstalledExtensionSidebarHostView: View { guard !Task.isCancelled else { return } // Rebuild rich metadata only when workspace membership changed. // The common unread-only path stays a cheap cache patch. + let membershipRefresh: CmuxSidebarSnapshot? if !snapshotCache.containsWorkspaces(workspaceIDsProvider()) { - _ = snapshotCache.replace(with: snapshotProvider()) + membershipRefresh = snapshotCache.replace(with: snapshotProvider()) + } else { + membershipRefresh = nil + } + guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) ?? membershipRefresh else { + continue } - guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { continue } xpcHost.sendSnapshotDidChange(snapshot) } } From f3d1df0edde05e4a2a61218d55ee5e03f9600299 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 20:10:41 -0700 Subject: [PATCH 17/36] Align projected-surface dismissal expectation --- .../NotificationDismissalModelTests.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift index 4e39da05e22b..f2b2bb423759 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift @@ -251,7 +251,7 @@ struct NotificationDismissalModelTests { #expect(host.log.contains("notificationFlash")) } - @Test func focusedWorkspaceDismissalUsesProjectedSurfaceIdentity() { + @Test func focusedWorkspaceDismissalStartsWithProjectedSurfaceIdentity() { let workspaceId = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! let containerId = UUID(uuidString: "22222222-2222-2222-2222-222222222222")! let projectedSurfaceId = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! @@ -269,8 +269,11 @@ struct NotificationDismissalModelTests { context: .explicitWorkspaceResume ) - #expect(host.log.contains("markRead:3333")) - #expect(!host.log.contains("markRead:2222")) + #expect(host.log == [ + "markRead:3333", "markRead:2222", + "clearFocusedRead:3333", "clearFocusedRead:2222", + "notificationFlash", + ]) } @Test func pendingSelectionContextTakeClearsIt() { From c39d076ad9784fe169e7f6a4c66063eb98267036 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:32:50 -0700 Subject: [PATCH 18/36] Add regressions for Pi lifecycle isolation --- .../SidebarUnreadSnapshotTests.swift | 30 ++- cmuxTests/MobileHostIdentityTests.swift | 17 +- tests/test_pi_extension_dispatch.py | 231 ++++++++++++++++-- tests/test_pi_extension_install.py | 113 +++++++-- 4 files changed, 325 insertions(+), 66 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift index 2ebb1f5651f0..16ae9ad7e5ce 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -39,10 +39,16 @@ struct SidebarUnreadSnapshotTests { @Test @MainActor - func modelStreamsOnlyChangedAtomicSnapshots() async { + func modelPublishesOnlyChangedAtomicSnapshots() { let workspaceID = UUID() let model = SidebarUnreadModel() - var iterator = model.snapshotChanges().makeAsyncIterator() + final class Recorder { + var snapshots: [SidebarUnreadSnapshot] = [] + } + let recorder = Recorder() + let observation = model.observeChanges(owner: recorder) { recorder, snapshot in + recorder.snapshots.append(snapshot) + } model.apply( totalUnreadCount: 1, @@ -56,8 +62,7 @@ struct SidebarUnreadSnapshotTests { focusedReadIndicatorByWorkspaceId: [:], manualUnreadWorkspaceIds: [] ) - let first = await iterator.next() - #expect(first == model.snapshot) + #expect(recorder.snapshots == [model.snapshot]) let publicationCount = OSAllocatedUnfairLock(initialState: 0) withObservationTracking { @@ -82,7 +87,6 @@ struct SidebarUnreadSnapshotTests { "An equivalent snapshot must not publish." ) - var nextIterator = model.snapshotChanges().makeAsyncIterator() model.apply( totalUnreadCount: 0, summaries: [:], @@ -90,8 +94,18 @@ struct SidebarUnreadSnapshotTests { focusedReadIndicatorByWorkspaceId: [:], manualUnreadWorkspaceIds: [] ) - let second = await nextIterator.next() - #expect(second?.totalUnreadCount == 0) - #expect(second?.summaryByWorkspaceId.isEmpty == true) + #expect(recorder.snapshots.count == 2) + #expect(recorder.snapshots.last?.totalUnreadCount == 0) + #expect(recorder.snapshots.last?.summaryByWorkspaceId.isEmpty == true) + + observation.cancel() + model.apply( + totalUnreadCount: 1, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + #expect(recorder.snapshots.count == 2) } } diff --git a/cmuxTests/MobileHostIdentityTests.swift b/cmuxTests/MobileHostIdentityTests.swift index b056e7107653..11ec3c1e8c48 100644 --- a/cmuxTests/MobileHostIdentityTests.swift +++ b/cmuxTests/MobileHostIdentityTests.swift @@ -176,7 +176,7 @@ struct MobileHostIdentityTests { #expect(defaults.string(forKey: "mobileHost.deviceID") == sharedID.lowercased()) } - @Test func repeatedSharedDeviceIDReadDoesNotRepublishDefaultsChange() throws { + @Test func canonicalEquivalentSharedDeviceIDDoesNotRewriteDefaults() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) @@ -188,23 +188,14 @@ struct MobileHostIdentityTests { let suiteName = "mobile-host-identity-\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: suiteName)) defer { defaults.removePersistentDomain(forName: suiteName) } - defaults.set(sharedID, forKey: "mobileHost.deviceID") - - var notificationCount = 0 - let observer = NotificationCenter.default.addObserver( - forName: UserDefaults.didChangeNotification, - object: defaults, - queue: nil - ) { _ in - notificationCount += 1 - } - defer { NotificationCenter.default.removeObserver(observer) } + let legacyStoredID = " \(sharedID.uppercased())\n" + defaults.set(legacyStoredID, forKey: "mobileHost.deviceID") #expect(MobileHostIdentity.deviceID( defaults: defaults, sharedIDURL: sharedIDURL ) == sharedID) - #expect(notificationCount == 0) + #expect(defaults.string(forKey: "mobileHost.deviceID") == legacyStoredID) } @Test func migratesExistingBundleIDToSharedFile() throws { diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index efcc02b9ec1e..bc94d11e17fc 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -167,6 +167,7 @@ def check_ui_lifecycle_handlers_return_immediately( extension_path: Path, ) -> int: lifecycle_log = root / "ui-lifecycle-latency.log" + lifecycle_release = root / "ui-lifecycle-release" lifecycle_cmux = root / "ui-lifecycle-latency-cmux" make_executable( lifecycle_cmux, @@ -174,12 +175,20 @@ def check_ui_lifecycle_handlers_return_immediately( set -euo pipefail payload="$(cat)" printf 'start %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" -sleep 0.15 +for _ in {1..250}; do + if [ -f "$CMUX_TEST_PI_UI_RELEASE" ]; then break; fi + sleep 0.02 +done +if [ ! -f "$CMUX_TEST_PI_UI_RELEASE" ]; then + printf 'blocked %s\n' "$*" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" + exit 88 +fi printf 'end %s\n' "$*" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" printf '{"workspace_id":"00000000-0000-0000-0000-000000008673","surface_id":"00000000-0000-0000-0000-000000008672","resume_binding":{"kind":"pi","checkpoint_id":"pi-ui-latency-session"}}\n' """, ) lifecycle_source = """ +import { writeFileSync } from "node:fs"; const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; const mod = await import(extensionPath); const handlers = new Map(); @@ -189,19 +198,19 @@ def check_ui_lifecycle_handlers_return_immediately( isIdle() { return true; }, sessionManager: { getSessionId() { return "pi-ui-latency-session"; } } }; -async function measure(label, action) { - const startedAt = performance.now(); - await Promise.resolve(action()); - const elapsed = performance.now() - startedAt; - console.log(`${label}_ms=${elapsed}`); - if (elapsed >= 75) throw new Error(`${label} blocked Pi for ${elapsed}ms`); -} -await measure("session_start", () => handlers.get("session_start")({}, ctx)); -await measure("prompt_submit", () => handlers.get("before_agent_start")({ prompt: "hello" }, ctx)); -await measure("completion", () => handlers.get("agent_end")({ +await Promise.resolve(handlers.get("session_start")({}, ctx)); +await Promise.resolve(handlers.get("before_agent_start")({ prompt: "hello" }, ctx)); +await Promise.resolve(handlers.get("tool_execution_start")({ + toolCallId: "ui-lifecycle-tool", + toolName: "bash", + args: { command: "true" } +}, ctx)); +await Promise.resolve(handlers.get("agent_end")({ messages: [{ role: "assistant", content: "done" }], stopReason: "completed" }, ctx)); +console.log("lifecycle_handlers_returned"); +writeFileSync(process.env.CMUX_TEST_PI_UI_RELEASE, "ready"); const logPath = process.env.CMUX_TEST_PI_UI_LATENCY_LOG; const deadline = performance.now() + 5000; @@ -211,7 +220,7 @@ def check_ui_lifecycle_handlers_return_immediately( text = await Bun.file(logPath).text(); } catch (_) {} const completed = text.split("\\n").filter((line) => line.startsWith("end ")).length; - if (completed >= 6) break; + if (completed >= 7) break; await new Promise((resolve) => setTimeout(resolve, 10)); } """ @@ -221,7 +230,10 @@ def check_ui_lifecycle_handlers_return_immediately( extension_path=extension_path, fake_cmux=lifecycle_cmux, source=lifecycle_source, - extra_env={"CMUX_TEST_PI_UI_LATENCY_LOG": str(lifecycle_log)}, + extra_env={ + "CMUX_TEST_PI_UI_LATENCY_LOG": str(lifecycle_log), + "CMUX_TEST_PI_UI_RELEASE": str(lifecycle_release), + }, ) if result.returncode != 0: print("FAIL: Pi UI lifecycle handler awaited cmux subprocess work") @@ -230,17 +242,8 @@ def check_ui_lifecycle_handlers_return_immediately( print(f"stderr={result.stderr.strip()}") return 1 - timings = {} - for line in result.stdout.splitlines(): - if "_ms=" not in line: - continue - key, value = line.split("=", 1) - timings[key] = float(value) - if set(timings) != {"session_start_ms", "prompt_submit_ms", "completion_ms"}: - print(f"FAIL: Pi UI lifecycle timing output was incomplete: {result.stdout!r}") - return 1 - if any(value >= 75 for value in timings.values()): - print(f"FAIL: Pi UI lifecycle handlers were observably blocking: {timings!r}") + if "lifecycle_handlers_returned" not in result.stdout: + print(f"FAIL: Pi UI lifecycle handlers did not return before release: {result.stdout!r}") return 1 calls = lifecycle_log.read_text(encoding="utf-8").splitlines() @@ -250,6 +253,7 @@ def check_ui_lifecycle_handlers_return_immediately( "--json surface resume set", "--json surface resume get", "hooks pi prompt-submit", + "hooks feed --source pi --event PreToolUse", "hooks pi notification", "hooks pi stop", ) @@ -263,6 +267,7 @@ def check_ui_lifecycle_handlers_return_immediately( or not ( indexes["hooks pi session-start"][0] < indexes["hooks pi prompt-submit"][0] + < indexes["hooks feed --source pi --event PreToolUse"][0] < indexes["hooks pi notification"][0] < indexes["hooks pi stop"][0] ) @@ -276,6 +281,169 @@ def check_ui_lifecycle_handlers_return_immediately( return 0 +def check_completion_precedes_next_prompt(bun: str, root: Path, extension_path: Path) -> int: + transition_log = root / "turn-transition.log" + transition_cmux = root / "turn-transition-cmux" + make_executable( + transition_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf '%s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_TRANSITION_LOG" +printf '{}\n' +""", + ) + transition_source = """ +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const ctx = { + cwd: "/tmp/pi-turn-transition", + sessionManager: { getSessionId() { return "pi-turn-transition-session"; } } +}; +handlers.get("before_agent_start")({ prompt: "first" }, ctx); +handlers.get("agent_end")({ + messages: [{ role: "assistant", content: "first done" }], + stopReason: "completed" +}, ctx); +handlers.get("before_agent_start")({ prompt: "second" }, ctx); +await handlers.get("session_shutdown")({ reason: "test complete" }, ctx); +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=transition_cmux, + source=transition_source, + extra_env={"CMUX_TEST_PI_TRANSITION_LOG": str(transition_log)}, + ) + if result.returncode != 0: + print(f"FAIL: Pi turn-transition harness failed: {result.stderr!r}") + return 1 + calls = transition_log.read_text(encoding="utf-8").splitlines() + first_stop = next( + ( + index + for index, line in enumerate(calls) + if "hooks pi stop" in line + and '"turn_id":"pi-turn-transition-session:turn-1"' in line + ), + None, + ) + second_prompt = next( + ( + index + for index, line in enumerate(calls) + if "hooks pi prompt-submit" in line + and '"turn_id":"pi-turn-transition-session:turn-2"' in line + ), + None, + ) + if first_stop is None or second_prompt is None or first_stop > second_prompt: + print(f"FAIL: previous Pi completion raced the next prompt: {calls!r}") + return 1 + return 0 + + +def check_cross_session_lifecycle_isolation( + bun: str, + root: Path, + extension_path: Path, +) -> int: + lifecycle_log = root / "cross-session-lifecycle.log" + lifecycle_release = root / "cross-session-lifecycle-release" + lifecycle_cmux = root / "cross-session-lifecycle-cmux" + make_executable( + lifecycle_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf 'start %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" +if [[ "$payload" == *'"session_id":"pi-slow-session"'* ]] && [[ "$*" == *"prompt-submit"* ]]; then + for _ in {1..250}; do + if [ -f "$CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE" ]; then break; fi + sleep 0.02 + done + if [ ! -f "$CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE" ]; then + printf 'blocked %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" + exit 88 + fi +fi +printf 'end %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" +printf '{}\n' +""", + ) + lifecycle_source = """ +import { writeFileSync } from "node:fs"; +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const context = (sessionId) => ({ + cwd: "/tmp/pi-cross-session-lifecycle", + sessionManager: { getSessionId() { return sessionId; } } +}); +const slow = context("pi-slow-session"); +const healthy = context("pi-healthy-session"); +handlers.get("before_agent_start")({ prompt: "block session A" }, slow); +const logPath = process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_LOG; +while (true) { + try { + if ((await Bun.file(logPath).text()).includes("pi-slow-session")) break; + } catch (_) {} + await new Promise((resolve) => setTimeout(resolve, 10)); +} +await handlers.get("session_shutdown")({ reason: "session B complete" }, healthy); +writeFileSync(process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE, "ready"); +await handlers.get("session_shutdown")({ reason: "session A complete" }, slow); +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=lifecycle_cmux, + source=lifecycle_source, + extra_env={ + "CMUX_TEST_PI_CROSS_LIFECYCLE_LOG": str(lifecycle_log), + "CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE": str(lifecycle_release), + }, + ) + if result.returncode != 0: + print(f"FAIL: cross-session lifecycle harness failed: {result.stderr!r}") + return 1 + calls = lifecycle_log.read_text(encoding="utf-8").splitlines() + slow_prompt_end = next( + ( + index + for index, line in enumerate(calls) + if line.startswith("end ") + and "prompt-submit" in line + and '"session_id":"pi-slow-session"' in line + ), + None, + ) + healthy_stop = next( + ( + index + for index, line in enumerate(calls) + if line.startswith("end ") + and "hooks pi stop" in line + and '"session_id":"pi-healthy-session"' in line + ), + None, + ) + if ( + any(line.startswith("blocked ") for line in calls) + or healthy_stop is None + or slow_prompt_end is None + or healthy_stop > slow_prompt_end + ): + print(f"FAIL: slow Pi session delayed another session's shutdown: {calls!r}") + return 1 + return 0 + + def check_panel_only_target_fails_closed(bun: str, root: Path, extension_path: Path) -> int: marker = root / "panel-only-cmux-called" fake_cmux = root / "panel-only-cmux" @@ -1786,12 +1954,25 @@ def check_error_classification(bun: str, root: Path, extension_path: Path) -> in const mod = await import(extensionPath); const handlers = new Map(); mod.default({ on(name, handler) { handlers.set(name, handler); } }); +let notificationCount = 0; const ctx = { cwd: "/tmp/pi-ambiguous-error-project", + ui: { notify() { notificationCount += 1; } }, sessionManager: { getSessionId() { return "pi-ambiguous-error-session"; } } }; await handlers.get("before_agent_start")({ prompt: "first" }, ctx); await handlers.get("before_agent_start")({ prompt: "second" }, ctx); +const logPath = process.env.CMUX_TEST_PI_AMBIGUOUS_LOG; +const deadline = performance.now() + 5000; +while (performance.now() < deadline) { + try { + if ((await Bun.file(logPath).text()).trim().split("\\n").length >= 2) break; + } catch (_) {} + await new Promise((resolve) => setTimeout(resolve, 10)); +} +if (notificationCount !== 0) { + throw new Error(`routine cmux failure showed ${notificationCount} Pi warning toast(s)`); +} """ ambiguous = run_extension( bun=bun, @@ -2265,6 +2446,8 @@ def run_checks(bun: str, root: Path, extension_path: Path) -> int: checks = ( check_responsiveness, check_ui_lifecycle_handlers_return_immediately, + check_completion_precedes_next_prompt, + check_cross_session_lifecycle_isolation, check_panel_only_target_fails_closed, check_feed_backlog, check_terminal_feed_compaction, diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index d90e7e357e0b..ce8c40425ffc 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -6,6 +6,7 @@ from __future__ import annotations import base64 +import fcntl import json import os import shutil @@ -98,40 +99,110 @@ def main() -> int: encoding="utf-8", ) refresh_env = os.environ.copy() + isolated_home = root / "home" + isolated_home.mkdir() + refresh_env["HOME"] = str(isolated_home) + refresh_env["CFFIXED_USER_HOME"] = str(isolated_home) refresh_env["PI_CODING_AGENT_DIR"] = str(config_dir) refresh_env["CMUX_WORKSPACE_ID"] = FOCUSED_WORKSPACE_ID refresh_env["CMUX_SURFACE_ID"] = FOCUSED_SURFACE_ID - subprocess.run( - [ - cli_path, - "--socket", - str(root / "missing-pi-refresh.sock"), - "hooks", - "pi", - "session-start", - "--workspace", - FOCUSED_WORKSPACE_ID, - "--surface", - FOCUSED_SURFACE_ID, - ], - input=json.dumps( - { - "session_id": "pi-managed-extension-refresh", - "cwd": str(root), - "hook_event_name": "SessionStart", - "event": "SessionStart", - } - ), + refresh_command = [ + cli_path, + "--socket", + str(root / "missing-pi-refresh.sock"), + "hooks", + "pi", + "session-start", + "--workspace", + FOCUSED_WORKSPACE_ID, + "--surface", + FOCUSED_SURFACE_ID, + ] + refresh_payload = json.dumps( + { + "session_id": "pi-managed-extension-refresh", + "cwd": str(root), + "hook_event_name": "SessionStart", + "event": "SessionStart", + } + ) + refresh_result = subprocess.run( + refresh_command, + input=refresh_payload, capture_output=True, text=True, check=False, env=refresh_env, timeout=20, ) + if refresh_result.returncode == 0: + print("FAIL: Pi refresh fixture unexpectedly connected to its missing socket") + return 1 if extension_path.read_text(encoding="utf-8") != extension_text: print("FAIL: Pi session-start did not refresh the stale cmux-managed extension") return 1 + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n// stale managed race fixture\n", + encoding="utf-8", + ) + lock_path = extension_path.parent / ".cmux-session.lock" + replacement = "// user replacement without the cmux ownership marker\n" + with lock_path.open("a", encoding="utf-8") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + blocked_refresh = subprocess.Popen( + refresh_command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + ) + extension_path.write_text(replacement, encoding="utf-8") + fcntl.flock(lock, fcntl.LOCK_UN) + blocked_refresh.communicate(input=refresh_payload, timeout=20) + if extension_path.read_text(encoding="utf-8") != replacement: + print("FAIL: in-flight Pi refresh overwrote a replacement extension") + return 1 + + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n// stale uninstall race fixture\n", + encoding="utf-8", + ) + with lock_path.open("a", encoding="utf-8") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + blocked_refresh = subprocess.Popen( + refresh_command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + ) + blocked_uninstall = subprocess.Popen( + [cli_path, "hooks", "pi", "uninstall"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + ) + fcntl.flock(lock, fcntl.LOCK_UN) + blocked_refresh.communicate(input=refresh_payload, timeout=20) + uninstall_stdout, uninstall_stderr = blocked_uninstall.communicate(timeout=20) + if blocked_uninstall.returncode != 0: + print( + "FAIL: concurrent Pi uninstall failed: " + f"stdout={uninstall_stdout!r} stderr={uninstall_stderr!r}" + ) + return 1 + if extension_path.exists(): + print("FAIL: in-flight Pi refresh recreated an uninstalled extension") + return 1 + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + bin_dir = root / "bin" bin_dir.mkdir() fake_pi = bin_dir / "pi" From 34ea84df0802c6c2bcbb17d9d7fec6f2a3e05515 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:33:15 -0700 Subject: [PATCH 19/36] Serialize Pi lifecycle work by session --- CLI/CMUXCLI+PiExtension.swift | 120 ++++++++++++-- CLI/CMUXCLI+PiExtensionSourceDispatch.swift | 14 +- CLI/CMUXCLI+PiExtensionSourcePart1.swift | 18 +- CLI/CMUXCLI+PiExtensionSourcePart2.swift | 156 ++++++++++-------- .../SidebarUnreadSnapshot.swift | 64 +++++-- ...MUXInstalledExtensionSidebarHostView.swift | 25 ++- Sources/ContentView.swift | 29 +++- Sources/DockUnreadPanelProjection.swift | 27 +-- Sources/Mobile/MobileHostIdentity.swift | 3 +- .../SidebarWorkspaceTableController.swift | 21 +-- Sources/Update/UpdateTitlebarAccessory.swift | 18 +- 11 files changed, 335 insertions(+), 160 deletions(-) diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift index ee4fcbc507c4..4c0cbbe04089 100644 --- a/CLI/CMUXCLI+PiExtension.swift +++ b/CLI/CMUXCLI+PiExtension.swift @@ -1,4 +1,5 @@ import Foundation +import Darwin extension CMUXCLI { private static let piExtensionMarker = "cmux-pi-session-extension-marker" @@ -26,17 +27,68 @@ extension CMUXCLI { } } + private func withPiExtensionMutationLock( + at extensionURL: URL, + createParentDirectory: Bool, + fileManager: FileManager = .default, + _ operation: () throws -> T + ) throws -> T { + let directoryURL = extensionURL.deletingLastPathComponent() + if createParentDirectory { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) + } + let lockURL = directoryURL.appendingPathComponent(".cmux-session.lock", isDirectory: false) + let descriptor = Darwin.open( + lockURL.path, + O_CREAT | O_RDWR, + mode_t(S_IRUSR | S_IWUSR) + ) + guard descriptor >= 0 else { + throw piExtensionReadError(at: extensionURL) + } + defer { Darwin.close(descriptor) } + guard Darwin.flock(descriptor, LOCK_EX) == 0 else { + throw piExtensionReadError(at: extensionURL) + } + defer { Darwin.flock(descriptor, LOCK_UN) } + return try operation() + } + + private func piExtensionReadError(at url: URL) -> CLIError { + CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.readFailed", + defaultValue: "Failed to read %@" + ), + url.path + )) + } + func refreshManagedPiExtensionIfNeeded(_ def: AgentHookDef) { let extensionURL = piExtensionURL(for: def) + let fileManager = FileManager.default + guard fileManager.fileExists(atPath: extensionURL.path) else { return } do { - let existing = try existingPiExtensionContents(at: extensionURL) - guard !existing.isEmpty, - existing.contains(Self.piExtensionMarker), - existing != Self.piExtensionSource - else { - return + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: false, + fileManager: fileManager + ) { + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) + guard !existing.isEmpty, + existing.contains(Self.piExtensionMarker), + existing != Self.piExtensionSource + else { + return + } + // Revalidate immediately before replacement. All cmux install, refresh, + // and uninstall mutations share this lock, so an in-flight refresh + // cannot recreate an extension that another cmux process removed. + guard try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) == existing else { + return + } + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) } - try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) } catch { // Hook delivery must continue when a managed extension cannot be refreshed. } @@ -80,11 +132,25 @@ extension CMUXCLI { return } } - try fileManager.createDirectory( - at: extensionURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: true, + fileManager: fileManager + ) { + let current = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) + if !current.isEmpty, !current.contains(Self.piExtensionMarker) { + throw CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.notCmuxExtension", + defaultValue: "%@ exists and is not a cmux extension; leaving it alone" + ), + extensionURL.path + )) + } + if current != Self.piExtensionSource { + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + } + } print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.installed", @@ -107,8 +173,23 @@ extension CMUXCLI { )) return } - let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fm) - guard existing.contains(Self.piExtensionMarker) else { + var removed = false + var refused = false + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: false, + fileManager: fm + ) { + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fm) + guard !existing.isEmpty else { return } + guard existing.contains(Self.piExtensionMarker) else { + refused = true + return + } + try fm.removeItem(at: extensionURL) + removed = true + } + if refused { print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.refuseRemoveMissingMarker", @@ -118,7 +199,16 @@ extension CMUXCLI { )) return } - try fm.removeItem(at: extensionURL) + guard removed else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.noneFound", + defaultValue: "No Pi cmux extension found at %@" + ), + extensionURL.path + )) + return + } print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.removed", diff --git a/CLI/CMUXCLI+PiExtensionSourceDispatch.swift b/CLI/CMUXCLI+PiExtensionSourceDispatch.swift index 7937248d56b8..4605324fc10b 100644 --- a/CLI/CMUXCLI+PiExtensionSourceDispatch.swift +++ b/CLI/CMUXCLI+PiExtensionSourceDispatch.swift @@ -31,7 +31,7 @@ class PiCmuxCommandDispatcher { // CLI owns a four-second end-to-end deadline. Observe that outcome before the // extension classifies a terminal delivery as failed. private static readonly feedDrainDeadlineMs = 4500; - private controlQueue: Promise = Promise.resolve(); + private controlQueues = new Map>(); private pendingFeedCommands = new Map(); private pendingFeedKeysBySession = new Map(); private priorityFeedCommands = new Map(); @@ -56,8 +56,16 @@ class PiCmuxCommandDispatcher { input: string | undefined, context: PiExtensionContextSnapshot, ): Promise { - const scheduled = this.controlQueue.then(() => this.execute(args, cwd, input, context)); - this.controlQueue = scheduled.then(() => undefined, () => undefined); + const sessionId = context.sessionId; + const previous = this.controlQueues.get(sessionId) || Promise.resolve(); + const scheduled = previous.then(() => this.execute(args, cwd, input, context)); + let tail: Promise; + tail = scheduled + .then(() => undefined, () => undefined) + .finally(() => { + if (this.controlQueues.get(sessionId) === tail) this.controlQueues.delete(sessionId); + }); + this.controlQueues.set(sessionId, tail); return scheduled; } enqueueFeed(key: string, command: PiFeedCommand): void { diff --git a/CLI/CMUXCLI+PiExtensionSourcePart1.swift b/CLI/CMUXCLI+PiExtensionSourcePart1.swift index 68bbce698c8b..5babceaac3e1 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart1.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart1.swift @@ -466,16 +466,26 @@ function settleTurn(sessionStates: Map, sessionId: string) return completion; } -function warn(ctx: PiExtensionContextSnapshot | null, message: string, details: Record = {}): void { +function warn( + ctx: PiExtensionContextSnapshot | null, + message: string, + details: Record = {}, + notifyUser = false, +): void { const payload = { source: "cmux-pi-extension", level: "warning", message, ...details }; try { console.warn(JSON.stringify(payload)); } catch (_) { console.warn(`[cmux-pi-extension] ${message}`); } - try { - ctx?.notifyWarning?.(); - } catch (_) {} + // Hook transport is best-effort telemetry. Keep routine command failures in + // the terminal instead of interrupting Pi with a generic toast; reserve the + // UI warning for an unexpected extension-task exception. + if (notifyUser) { + try { + ctx?.notifyWarning?.(); + } catch (_) {} + } } function cmuxExecutable(): string { diff --git a/CLI/CMUXCLI+PiExtensionSourcePart2.swift b/CLI/CMUXCLI+PiExtensionSourcePart2.swift index 1a6599770f97..23204a749fb4 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart2.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart2.swift @@ -283,21 +283,19 @@ function isTerminalFeedEvent(eventName: PiFeedEventName): boolean { return eventName === "PostToolUse" || eventName === "SubagentStop"; } -function sendFeed( +function prepareFeedDispatch( dispatcher: PiCmuxCommandDispatcher, sessionStates: Map, eventName: PiFeedEventName, context: PiExtensionContextSnapshot, event: unknown, -): void { - if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return; +): (() => void) | undefined { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return undefined; const sessionId = context.sessionId; - if (!sessionId) return; - if (!dispatcher.canDispatch(sessionId)) return; - const target = surfaceTargetArgs(dispatcher, sessionId); - if (!target) return; + if (!sessionId) return undefined; + if (!dispatcher.canDispatch(sessionId)) return undefined; const state = stateFor(sessionStates, sessionId); - if (state.stopped) return; + if (state.stopped) return undefined; const cwd = context.cwd; const toolCallId = firstString(objectValue(event, ["toolCallId", "tool_call_id", "id"])); const toolName = firstString(objectValue(event, ["toolName", "tool_name", "name"])); @@ -323,14 +321,18 @@ function sendFeed( const isError = objectValue(event, ["isError", "is_error"]); if (isError !== undefined) payload.is_error = projectPiFeedValue(isError, projectionState); } - dispatcher.enqueueFeed(`${sessionId}:${toolCallId || toolName || "unknown"}`, { - args: ["hooks", "feed", "--source", "pi", "--event", eventName, ...target], - cwd, - payload, - context, - terminal: isTerminalFeedEvent(eventName), - onFailure: () => { state.feedDeliveryFailed = true; }, - }); + return () => { + const target = surfaceTargetArgs(dispatcher, sessionId); + if (!target) return; + dispatcher.enqueueFeed(`${sessionId}:${toolCallId || toolName || "unknown"}`, { + args: ["hooks", "feed", "--source", "pi", "--event", eventName, ...target], + cwd, + payload, + context, + terminal: isTerminalFeedEvent(eventName), + onFailure: () => { state.feedDeliveryFailed = true; }, + }); + }; } async function publishPendingCompletion( @@ -338,9 +340,8 @@ async function publishPendingCompletion( sessionStates: Map, context: PiExtensionContextSnapshot, sessionId: string, + completion: PendingCompletion, ): Promise { - const completion = settleTurn(sessionStates, sessionId); - if (!completion) return; await dispatcher.finishFeedForSession(sessionId); const state = stateFor(sessionStates, sessionId); const feedDelivered = !state.feedDeliveryFailed; @@ -366,30 +367,28 @@ async function publishPendingCompletion( export default function cmuxPiSessionExtension(pi: ExtensionAPI) { const dispatcher = new PiCmuxCommandDispatcher(); const sessionStates = new Map(); - const lifecycleTasks = new Set>(); + const lifecycleTails = new Map>(); - const trackLifecycleTask = ( - task: Promise, + const enqueueLifecycleTask = ( + sessionId: string, context: PiExtensionContextSnapshot, - ): void => { + operation: () => Promise | unknown, + ): Promise => { + const previous = lifecycleTails.get(sessionId) || Promise.resolve(); let tracked: Promise; - tracked = task + tracked = previous + .then(operation) .then(() => undefined) .catch((error) => { warn(context, "cmux lifecycle task failed", { error_available: error !== undefined, - }); + }, true); }) .finally(() => { - lifecycleTasks.delete(tracked); + if (lifecycleTails.get(sessionId) === tracked) lifecycleTails.delete(sessionId); }); - lifecycleTasks.add(tracked); - }; - - const drainLifecycleTasks = async (): Promise => { - while (lifecycleTasks.size > 0) { - await Promise.all([...lifecycleTasks]); - } + lifecycleTails.set(sessionId, tracked); + return tracked; }; pi.on("session_start", (_event, ctx) => { @@ -401,42 +400,50 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { state.feedDeliveryFailed = false; state.stopped = false; } - trackLifecycleTask((async () => { + if (!sessionId) return; + enqueueLifecycleTask(sessionId, context, async () => { const ok = await sendHook(dispatcher, "session-start", context); - if (ok && sessionId) await ensureResumeBinding(dispatcher, context, sessionId); - })(), context); + if (ok) await ensureResumeBinding(dispatcher, context, sessionId); + }); }); pi.on("before_agent_start", (event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; - const turnId = sessionId ? beginTurn(sessionStates, sessionId, event) : undefined; - trackLifecycleTask( - sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }), - context, - ); + if (!sessionId) return; + const turnId = beginTurn(sessionStates, sessionId, event); + enqueueLifecycleTask(sessionId, context, () => ( + sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }) + )); }); - pi.on("tool_execution_start", async (event, ctx) => { + const enqueueFeed = ( + eventName: PiFeedEventName, + event: unknown, + ctx: ExtensionContext, + ): void => { const context = snapshotContext(ctx); - const eventName = isSubagentTool(event) ? "SubagentStart" : "PreToolUse"; - sendFeed(dispatcher, sessionStates, eventName, context, event); + const sessionId = context.sessionId; + if (!sessionId) return; + const dispatch = prepareFeedDispatch(dispatcher, sessionStates, eventName, context, event); + if (!dispatch) return; + enqueueLifecycleTask(sessionId, context, dispatch); + }; + + pi.on("tool_execution_start", (event, ctx) => { + enqueueFeed(isSubagentTool(event) ? "SubagentStart" : "PreToolUse", event, ctx); }); - pi.on("tool_execution_end", async (event, ctx) => { - const context = snapshotContext(ctx); - const eventName = isSubagentTool(event) ? "SubagentStop" : "PostToolUse"; - sendFeed(dispatcher, sessionStates, eventName, context, event); + pi.on("tool_execution_end", (event, ctx) => { + enqueueFeed(isSubagentTool(event) ? "SubagentStop" : "PostToolUse", event, ctx); }); - pi.on("session_before_compact", async (event, ctx) => { - const context = snapshotContext(ctx); - sendFeed(dispatcher, sessionStates, "PreCompact", context, event); + pi.on("session_before_compact", (event, ctx) => { + enqueueFeed("PreCompact", event, ctx); }); - pi.on("session_compact", async (event, ctx) => { - const context = snapshotContext(ctx); - sendFeed(dispatcher, sessionStates, "PostCompact", context, event); + pi.on("session_compact", (event, ctx) => { + enqueueFeed("PostCompact", event, ctx); }); pi.on("agent_end", (event, ctx) => { @@ -453,10 +460,12 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { }; // Older Pi versions do not emit agent_settled, so retain their established completion behavior. if (!supportsAgentSettled()) { - trackLifecycleTask( - publishPendingCompletion(dispatcher, sessionStates, context, sessionId), - context, - ); + const completion = settleTurn(sessionStates, sessionId); + if (completion) { + enqueueLifecycleTask(sessionId, context, () => ( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId, completion) + )); + } } }); @@ -466,10 +475,12 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { const sessionId = context.sessionId; if (!sessionId || !isIdle) return; // Consume pending completion before subprocess calls so duplicate settlement cannot notify twice. - trackLifecycleTask( - publishPendingCompletion(dispatcher, sessionStates, context, sessionId), - context, - ); + const completion = settleTurn(sessionStates, sessionId); + if (completion) { + enqueueLifecycleTask(sessionId, context, () => ( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId, completion) + )); + } }); pi.on("session_shutdown", async (event, ctx) => { @@ -485,17 +496,18 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { terminationReason: firstString(objectValue(event, ["reason"])) || "session_shutdown", }; } - await drainLifecycleTasks(); - await dispatcher.finishFeedForSession(sessionId); - const feedDelivered = !state.feedDeliveryFailed; - state.feedDeliveryFailed = false; - if (!feedDelivered) warn(context, "cmux hook command failed", { session_id: sessionId }); - if (stopPayload) await sendHook(dispatcher, "stop", context, stopPayload); - try { - await clearResumeBinding(dispatcher, context, sessionId); - } finally { - releaseSessionRuntime(dispatcher, sessionStates, sessionId); - } + await enqueueLifecycleTask(sessionId, context, async () => { + await dispatcher.finishFeedForSession(sessionId); + const feedDelivered = !state.feedDeliveryFailed; + state.feedDeliveryFailed = false; + if (!feedDelivered) warn(context, "cmux hook command failed", { session_id: sessionId }); + if (stopPayload) await sendHook(dispatcher, "stop", context, stopPayload); + try { + await clearResumeBinding(dispatcher, context, sessionId); + } finally { + releaseSessionRuntime(dispatcher, sessionStates, sessionId); + } + }); }); } """# diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift index abd7fbb6cd72..6bc9d53b8dc9 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift @@ -114,11 +114,36 @@ public struct SidebarUnreadSnapshot: Equatable, Sendable { } } +/// Cancels one imperative unread-snapshot observation. +@MainActor +public final class SidebarUnreadObservation { + nonisolated(unsafe) private weak var model: SidebarUnreadModel? + nonisolated private let id: UUID + + fileprivate init(model: SidebarUnreadModel, id: UUID) { + self.model = model + self.id = id + } + + /// Stops delivering snapshot changes. + public func cancel() { + model?.removeSnapshotObserver(id) + model = nil + } + + deinit { + let model = model + let id = id + Task { @MainActor in + model?.removeSnapshotObserver(id) + } + } +} + /// Main-actor unread source of truth for leaf UI projections. /// /// Mutations publish one equality-guarded snapshot. SwiftUI tracks ``snapshot`` -/// through Observation, while AppKit consumers use ``snapshotChanges()`` so the -/// app does not add Combine state or broad root-view subscriptions. +/// through Observation, while imperative consumers register weak-owner callbacks. @MainActor @Observable public final class SidebarUnreadModel { @@ -141,22 +166,25 @@ public final class SidebarUnreadModel { public var manualUnreadWorkspaceIds: Set { snapshot.manualUnreadWorkspaceIds } @ObservationIgnored - private var snapshotObservers: [UUID: AsyncStream.Continuation] = [:] + private var snapshotObservers: [UUID: (SidebarUnreadSnapshot) -> Bool] = [:] /// Creates an empty unread model. public init() {} - /// Returns a stream of changed snapshots, buffering only the newest value. - public func snapshotChanges() -> AsyncStream { - AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in - let id = UUID() - snapshotObservers[id] = continuation - continuation.onTermination = { [weak self] _ in - Task { @MainActor in - self?.snapshotObservers[id] = nil - } - } + /// Observes changed snapshots synchronously after publication. + /// + /// The model retains neither `owner` nor the returned cancellation token. + public func observeChanges( + owner: Owner, + _ receive: @escaping @MainActor (Owner, SidebarUnreadSnapshot) -> Void + ) -> SidebarUnreadObservation { + let id = UUID() + snapshotObservers[id] = { [weak owner] snapshot in + guard let owner else { return false } + receive(owner, snapshot) + return true } + return SidebarUnreadObservation(model: self, id: id) } /// Atomically applies one complete unread state and publishes only changes. @@ -176,9 +204,15 @@ public final class SidebarUnreadModel { ) guard snapshot != next else { return } snapshot = next - for observer in snapshotObservers.values { - observer.yield(next) + var expiredObserverIDs: [UUID] = [] + for (id, observer) in snapshotObservers where !observer(next) { + expiredObserverIDs.append(id) } + for id in expiredObserverIDs { snapshotObservers[id] = nil } + } + + fileprivate func removeSnapshotObserver(_ id: UUID) { + snapshotObservers[id] = nil } /// Returns the summary for one workspace. diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 1e8f49b922b5..b9603bd7b369 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -174,6 +174,20 @@ private final class CMUXSidebarSnapshotCache { } } +private struct CMUXSidebarUnreadSnapshotObserver: View { + let source: SidebarUnreadModel + let action: @MainActor (SidebarUnreadSnapshot) -> Void + + var body: some View { + Color.clear + .frame(width: 0, height: 0) + .accessibilityHidden(true) + .onChange(of: source.snapshot) { _, snapshot in + action(snapshot) + } + } +} + struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" @@ -219,7 +233,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { connection: connection, bundleIdentifier: identity.bundleIdentifier, snapshotProvider: { - snapshotCache.snapshot ?? snapshotProvider() + snapshotCache.replace(with: snapshotProvider()) }, actionHandler: actionHandler, onGrantChanged: { grant in @@ -302,14 +316,13 @@ struct CMUXInstalledExtensionSidebarHostView: View { .task { _ = snapshotCache.replace(with: snapshotProvider()) xpcHost.update( - snapshotProvider: { snapshotCache.snapshot ?? snapshotProvider() }, + snapshotProvider: { snapshotCache.replace(with: snapshotProvider()) }, actionHandler: actionHandler ) await observeExtensionAvailability() } - .task { - for await unreadSnapshot in unreadSource.snapshotChanges() { - guard !Task.isCancelled else { return } + .background { + CMUXSidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in // Rebuild rich metadata only when workspace membership changed. // The common unread-only path stays a cheap cache patch. let membershipRefresh: CmuxSidebarSnapshot? @@ -319,7 +332,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { membershipRefresh = nil } guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) ?? membershipRefresh else { - continue + return } xpcHost.sendSnapshotDidChange(snapshot) } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 6c737fd994f6..8f705f56e54b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -823,6 +823,21 @@ private struct SidebarUnreadSnapshotReader: View { } } +/// Runs an imperative unread side effect from an isolated Observation leaf. +private struct SidebarUnreadSnapshotObserver: View { + let source: SidebarUnreadModel + let action: @MainActor (SidebarUnreadSnapshot) -> Void + + var body: some View { + Color.clear + .frame(width: 0, height: 0) + .accessibilityHidden(true) + .onChange(of: source.snapshot) { _, snapshot in + action(snapshot) + } + } +} + struct ContentView: View { var updateViewModel: UpdateStateModel let windowId: UUID @@ -2874,12 +2889,10 @@ struct ContentView: View { scheduleTitlebarTextRefresh() }) - view = AnyView(view.task { - // Update the AppKit-owned pane overlay directly. The titlebar badge - // and sidebar rows observe their own leaves, so no ContentView state - // mutation is needed for unread changes. - for await snapshot in sidebarUnread.snapshotChanges() { - guard !Task.isCancelled else { return } + view = AnyView(view.background { + // Update the AppKit-owned pane overlay from a dedicated Observation + // leaf, without making ContentView itself an unread observer. + SidebarUnreadSnapshotObserver(source: sidebarUnread) { snapshot in refreshTmuxWorkspacePaneWindowOverlay( in: observedWindow, unreadSnapshot: snapshot @@ -11552,7 +11565,9 @@ struct VerticalTabsSidebar: View, Equatable { // whether a change class re-renders the sidebar subtree or skips it. cmuxDebugLog("sidebar.table.rowsBuild items=\(renderContext.workspaceRenderItems.count)") #endif - let unreadSnapshot = sidebarUnread.snapshot + // AppKit applies the live unread snapshot inside its controller. Keep + // root row construction independent from notification publications. + let unreadSnapshot = SidebarUnreadSnapshot() let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let notificationIndex = SidebarWorkspaceNotificationIndex( notifications: notificationStore.notifications diff --git a/Sources/DockUnreadPanelProjection.swift b/Sources/DockUnreadPanelProjection.swift index 53e0d40df9b4..4ee1ace99d75 100644 --- a/Sources/DockUnreadPanelProjection.swift +++ b/Sources/DockUnreadPanelProjection.swift @@ -14,9 +14,7 @@ final class DockUnreadPanelProjection { @ObservationIgnored private var isActive = false @ObservationIgnored private var unreadSurfaceKeys: Set @ObservationIgnored private var focusedReadIndicatorByWorkspaceID: [UUID: UUID] - // Written only by init and deinit. The unsafe escape exists solely so - // nonisolated deinit can cancel it. - @ObservationIgnored private nonisolated(unsafe) var unreadTask: Task? + @ObservationIgnored private var unreadObservation: SidebarUnreadObservation? init( source: SidebarUnreadModel, @@ -27,25 +25,18 @@ final class DockUnreadPanelProjection { self.workspaceID = workspaceID self.panelIDs = panelIDs self.isActive = isActive - unreadSurfaceKeys = source.snapshot.unreadSurfaceKeys - focusedReadIndicatorByWorkspaceID = source.snapshot.focusedReadIndicatorByWorkspaceId + let initialSnapshot = source.snapshot + unreadSurfaceKeys = initialSnapshot.unreadSurfaceKeys + focusedReadIndicatorByWorkspaceID = initialSnapshot.focusedReadIndicatorByWorkspaceId refresh() - let changes = source.snapshotChanges() - unreadTask = Task { @MainActor [weak self] in - for await snapshot in changes { - guard let self, !Task.isCancelled else { return } - self.receive( - unreadSurfaceKeys: snapshot.unreadSurfaceKeys, - focusedReadIndicatorByWorkspaceID: snapshot.focusedReadIndicatorByWorkspaceId - ) - } + unreadObservation = source.observeChanges(owner: self) { projection, snapshot in + projection.receive( + unreadSurfaceKeys: snapshot.unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceID: snapshot.focusedReadIndicatorByWorkspaceId + ) } } - deinit { - unreadTask?.cancel() - } - func updateContext(panelIDs: Set, isActive: Bool) { guard self.panelIDs != panelIDs || self.isActive != isActive else { return } self.panelIDs = panelIDs diff --git a/Sources/Mobile/MobileHostIdentity.swift b/Sources/Mobile/MobileHostIdentity.swift index 4e6a8cef69ea..8a8620547065 100644 --- a/Sources/Mobile/MobileHostIdentity.swift +++ b/Sources/Mobile/MobileHostIdentity.swift @@ -84,8 +84,7 @@ enum MobileHostIdentity { } private static func persistDeviceIDIfNeeded(_ id: String, defaults: UserDefaults) { - let stored = defaults.string(forKey: deviceIDKey)? - .trimmingCharacters(in: .whitespacesAndNewlines) + let stored = normalizedID(defaults.string(forKey: deviceIDKey)) guard stored != id else { return } defaults.set(id, forKey: deviceIDKey) } diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift index 692015cbc827..ce8f67a8cdd6 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift @@ -34,9 +34,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private var appKitDropIndicatorIncludesRowTargets = false private weak var unreadSource: SidebarUnreadModel? private var unreadSnapshot = SidebarUnreadSnapshot() - // Written only by setUnreadSource(), dismantleContainerView(), and deinit. - // The unsafe escape exists solely so nonisolated deinit can cancel it. - private nonisolated(unsafe) var unreadTask: Task? + private var unreadObservation: SidebarUnreadObservation? private var clipBoundsObserver: NSObjectProtocol? private var resizeDidEndObserver: NSObjectProtocol? private lazy var mutationScheduler = SidebarWorkspaceTableMutationScheduler( @@ -63,7 +61,6 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS NotificationCenter.default.removeObserver(resizeDidEndObserver) } previewBailoutTask?.cancel() - unreadTask?.cancel() } func makeContainerView() -> SidebarWorkspaceTableContainerView { let container = SidebarWorkspaceTableContainerView() @@ -163,8 +160,8 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS let postUpdateActions = detachLoadedCells() workspaceDragSessionDidEnd() actions = nil - unreadTask?.cancel() - unreadTask = nil + unreadObservation?.cancel() + unreadObservation = nil unreadSource = nil unreadSnapshot = SidebarUnreadSnapshot() rows.removeAll(keepingCapacity: false) @@ -188,15 +185,11 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS /// `VerticalTabsSidebar.body` and its O(workspaces) row construction. func setUnreadSource(_ source: SidebarUnreadModel) { guard unreadSource !== source else { return } - unreadTask?.cancel() + unreadObservation?.cancel() unreadSource = source - unreadSnapshot = source.snapshot - let changes = source.snapshotChanges() - unreadTask = Task { @MainActor [weak self] in - for await snapshot in changes { - guard let self, !Task.isCancelled else { return } - self.applyUnreadSnapshot(snapshot) - } + applyUnreadSnapshot(source.snapshot) + unreadObservation = source.observeChanges(owner: self) { controller, snapshot in + controller.applyUnreadSnapshot(snapshot) } } diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 2c90b6a25aac..a721b70eadc5 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -1902,6 +1902,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private let viewModel = TitlebarControlsViewModel() private var userDefaultsObserver: NSObjectProtocol? private var lastShowsWorkspaceTitlebar = !WorkspacePresentationModeSettings.isMinimal() + private var lastTitlebarDebugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() var popoverIsShownForTesting: Bool { notificationsPopover.isShown } private var showsWorkspaceTitlebar: Bool { !WorkspacePresentationModeSettings.isMinimal() } @@ -1972,10 +1973,19 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont ) { [weak self] _ in guard let self else { return } let shouldShow = self.showsWorkspaceTitlebar - guard shouldShow != self.lastShowsWorkspaceTitlebar else { return } - self.applyWorkspaceTitlebarVisibility() - if shouldShow { - self.restoreSizeAfterMinimalMode() + let debugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() + let visibilityChanged = shouldShow != self.lastShowsWorkspaceTitlebar + let debugLayoutChanged = debugSnapshot != self.lastTitlebarDebugSnapshot + guard visibilityChanged || debugLayoutChanged else { return } + self.lastTitlebarDebugSnapshot = debugSnapshot + if visibilityChanged { + self.applyWorkspaceTitlebarVisibility() + if shouldShow { + self.restoreSizeAfterMinimalMode() + } + } + if debugLayoutChanged, shouldShow { + self.scheduleSizeUpdate(invalidateLayout: true) } } observeLayoutModel() From 39cc5b9769e856addecfd0c05d9926d8c5a8a731 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:50:45 -0700 Subject: [PATCH 20/36] Tighten Pi and unread regression coverage --- .../UpdatePillReleaseVisibilityTests.swift | 41 +++++++++++++++++-- .../WorkspaceContentViewVisibilityTests.swift | 25 +++++++++++ tests/test_pi_extension_dispatch.py | 15 ++----- 3 files changed, 67 insertions(+), 14 deletions(-) diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index 264140d8b289..aecc70e9cf06 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -249,7 +249,7 @@ struct TitlebarControlsSizingPolicyTests { @Test @MainActor - func testLayoutModelOnlyRecomputesForTitlebarInputs() { + func testLayoutModelOnlyRecomputesForTitlebarInputs() async { let suiteName = "TitlebarControlsLayoutModel-\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suiteName)! defer { defaults.removePersistentDomain(forName: suiteName) } @@ -268,18 +268,53 @@ struct TitlebarControlsSizingPolicyTests { defaults.set(true, forKey: "unrelatedTitlebarTestSetting") notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + await drainMainQueue() checkEqual(computationCount, 1) defaults.set(TitlebarControlsStyle.compact.rawValue, forKey: TitlebarControlsStyle.storageKey) notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + await drainMainQueue() checkEqual(computationCount, 2) checkEqual(model.snapshot.style, .compact) - notificationCenter.post(name: KeyboardShortcutSettings.didChangeNotification, object: nil) + notificationCenter.post( + name: KeyboardShortcutSettings.didChangeNotification, + object: nil, + userInfo: [ + KeyboardShortcutSettings.actionUserInfoKey: + KeyboardShortcutSettings.Action.closeWindow.rawValue, + ] + ) + await drainMainQueue() + checkEqual(computationCount, 2) + + notificationCenter.post( + name: KeyboardShortcutSettings.didChangeNotification, + object: nil, + userInfo: [ + KeyboardShortcutSettings.actionUserInfoKey: + KeyboardShortcutSettings.Action.toggleSidebar.rawValue, + ] + ) + await drainMainQueue() checkEqual(computationCount, 3) - notificationCenter.post(name: GlobalFontMagnification.didChangeNotification, object: nil) + notificationCenter.post(name: KeyboardShortcutSettings.didChangeNotification, object: nil) + await drainMainQueue() checkEqual(computationCount, 4) + + notificationCenter.post(name: GlobalFontMagnification.didChangeNotification, object: nil) + await drainMainQueue() + checkEqual(computationCount, 5) + } + + @MainActor + private func drainMainQueue() async { + await withCheckedContinuation { continuation in + DispatchQueue.main.async { + continuation.resume() + } + } } @Test diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index 395f8517dccc..7c07f631d138 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -276,6 +276,10 @@ final class WorkspaceContentViewVisibilityTests { let tabManager = TabManager() let workspaceId = try #require(tabManager.selectedTabId) + let unaffectedWorkspace = tabManager.addWorkspace( + select: false, + autoWelcomeIfNeeded: false + ) let unread = SidebarUnreadModel() let counts = MinimalModeBodyProbeCounts() let root = ContentView( @@ -320,10 +324,23 @@ final class WorkspaceContentViewVisibilityTests { .first { $0.currentModelForMeasurement?.workspaceId == workspaceId } } ) + let unaffectedWorkspaceCell = try #require( + window.contentView.flatMap { root in + Self.descendants(of: root) + .compactMap { $0 as? SidebarWorkspaceRowTableCellView } + .first { + $0.currentModelForMeasurement?.workspaceId == unaffectedWorkspace.id + } + } + ) var appliedUnreadCount: Int? + var unaffectedApplyCount = 0 workspaceCell.applyModelProbeForTesting = { model in appliedUnreadCount = model.unreadCount } + unaffectedWorkspaceCell.applyModelProbeForTesting = { _ in + unaffectedApplyCount += 1 + } counts.reset() unread.apply( @@ -358,6 +375,14 @@ final class WorkspaceContentViewVisibilityTests { appliedUnreadCount == 1, "The affected visible AppKit row must still receive the unread badge." ) + #expect( + unaffectedApplyCount == 0, + "An unread change must not reconfigure an unaffected AppKit row." + ) + #expect( + unaffectedWorkspaceCell.currentModelForMeasurement?.unreadCount == 0, + "An unread change must not copy its badge into a neighboring workspace row." + ) } @Test diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index bc94d11e17fc..f7ae071b0315 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -261,20 +261,13 @@ def check_ui_lifecycle_handlers_return_immediately( command: [index for index, line in enumerate(completed) if command in line] for command in expected } + orderedIndexes = [indexes[command][0] for command in expected if indexes[command]] + commandPhases = [line.split(" ", 1)[0] for line in calls if line.startswith(("start ", "end "))] if ( len(completed) != len(expected) or any(len(found) != 1 for found in indexes.values()) - or not ( - indexes["hooks pi session-start"][0] - < indexes["hooks pi prompt-submit"][0] - < indexes["hooks feed --source pi --event PreToolUse"][0] - < indexes["hooks pi notification"][0] - < indexes["hooks pi stop"][0] - ) - or not ( - indexes["--json surface resume set"][0] - < indexes["--json surface resume get"][0] - ) + or orderedIndexes != sorted(orderedIndexes) + or commandPhases != [phase for _ in expected for phase in ("start", "end")] ): print(f"FAIL: detached Pi lifecycle work lost command ordering: {calls!r}") return 1 From de98d6b9b4f71706487660b11bf35438e9bc4d42 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:00:51 -0700 Subject: [PATCH 21/36] Scope remaining Pi and sidebar refreshes --- CLI/CMUXCLI+PiExtensionSourcePart2.swift | 2 + ...MUXInstalledExtensionSidebarHostView.swift | 9 ++-- Sources/Update/UpdateTitlebarAccessory.swift | 54 ++++++++++++------- .../VerticalTabsSidebar+WorkspaceGroups.swift | 25 ++++++--- 4 files changed, 57 insertions(+), 33 deletions(-) diff --git a/CLI/CMUXCLI+PiExtensionSourcePart2.swift b/CLI/CMUXCLI+PiExtensionSourcePart2.swift index 23204a749fb4..2ecf8134f815 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart2.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart2.swift @@ -380,8 +380,10 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { .then(operation) .then(() => undefined) .catch((error) => { + const errorMessage = error instanceof Error ? error.message : undefined; warn(context, "cmux lifecycle task failed", { error_available: error !== undefined, + error_message: utf8Prefix(errorMessage, 512), }, true); }) .finally(() => { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b9603bd7b369..80923c5d7d34 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -325,13 +325,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { CMUXSidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in // Rebuild rich metadata only when workspace membership changed. // The common unread-only path stays a cheap cache patch. - let membershipRefresh: CmuxSidebarSnapshot? if !snapshotCache.containsWorkspaces(workspaceIDsProvider()) { - membershipRefresh = snapshotCache.replace(with: snapshotProvider()) - } else { - membershipRefresh = nil + let snapshot = snapshotCache.replace(with: snapshotProvider()) + xpcHost.sendSnapshotDidChange(snapshot) + return } - guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) ?? membershipRefresh else { + guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { return } xpcHost.sendSnapshotDidChange(snapshot) diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index a721b70eadc5..ec069672574a 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -144,7 +144,6 @@ struct TitlebarControlsStyleConfig { struct TitlebarControlsLayoutModelSnapshot: Equatable { let style: TitlebarControlsStyle let contentSize: NSSize - let revision: UInt64 } /// Owns the expensive shortcut/font-derived titlebar size once for every @@ -177,8 +176,7 @@ final class TitlebarControlsLayoutModel { let style = TitlebarControlsStyle.stored(in: defaults) snapshot = TitlebarControlsLayoutModelSnapshot( style: style, - contentSize: contentSizeProvider(style.config), - revision: 0 + contentSize: contentSizeProvider(style.config) ) observers.append( @@ -192,22 +190,29 @@ final class TitlebarControlsLayoutModel { } } ) - for name in [ - KeyboardShortcutSettings.didChangeNotification, - GlobalFontMagnification.didChangeNotification, - ] { - observers.append( - notificationCenter.addObserver( - forName: name, - object: nil, - queue: .main - ) { [weak self] _ in - MainActor.assumeIsolated { - self?.recompute() - } + observers.append( + notificationCenter.addObserver( + forName: KeyboardShortcutSettings.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] notification in + MainActor.assumeIsolated { + guard let self, self.shortcutChangeAffectsLayout(notification) else { return } + self.recompute() } - ) - } + } + ) + observers.append( + notificationCenter.addObserver( + forName: GlobalFontMagnification.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.recompute() + } + } + ) } deinit { @@ -227,12 +232,21 @@ final class TitlebarControlsLayoutModel { recompute(style: style) } + private func shortcutChangeAffectsLayout(_ notification: Notification) -> Bool { + guard let rawAction = notification.userInfo?[KeyboardShortcutSettings.actionUserInfoKey] + as? String, + let action = KeyboardShortcutSettings.Action(rawValue: rawAction) else { + // Bulk and settings-file reloads intentionally omit one action. + return true + } + return TitlebarShortcutHintActionSlot.allCases.contains { $0.action == action } + } + private func recompute(style: TitlebarControlsStyle? = nil) { let style = style ?? snapshot.style snapshot = TitlebarControlsLayoutModelSnapshot( style: style, - contentSize: contentSizeProvider(style.config), - revision: snapshot.revision &+ 1 + contentSize: contentSizeProvider(style.config) ) } } diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index f0fd2f9b0547..c16e6376df67 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -32,7 +32,9 @@ extension VerticalTabsSidebar { ) let cwdContextMenuItems = resolvedConfig?.contextMenuItems ?? [] let newWorkspacePlacement = resolvedConfig?.newWorkspacePlacement - let unreadSnapshot = sidebarUnread.snapshot + // The AppKit controller applies the current unread snapshot after row + // construction, keeping this root projection outside Observation. + let unreadSnapshot = SidebarUnreadSnapshot() let anchorUnreadCount: Int = { if group.isCollapsed { return memberWorkspaceIds.reduce(0) { partial, workspaceId in @@ -215,12 +217,19 @@ extension VerticalTabsSidebar { unreadDependencyWorkspaceIds: Set(memberWorkspaceIds) .union([group.anchorWorkspaceId]), unreadRebuild: { - [model, anchorWorkspaceId = group.anchorWorkspaceId, - isCollapsed = group.isCollapsed, memberWorkspaceIds, - nonAnchorMemberIds] snapshot in + [weak tabManager, model, groupId = group.id, + anchorWorkspaceId = group.anchorWorkspaceId, + memberWorkspaceIds] snapshot in + let liveGroup = tabManager?.workspaceGroups.first { $0.id == groupId } + let liveMemberWorkspaceIds = tabManager?.tabs.compactMap { + $0.groupId == groupId ? $0.id : nil + } ?? memberWorkspaceIds + let liveNonAnchorMemberIds = liveMemberWorkspaceIds.filter { + $0 != anchorWorkspaceId + } var fresh = model - fresh.anchorUnreadCount = isCollapsed - ? memberWorkspaceIds.reduce(0) { + fresh.anchorUnreadCount = (liveGroup?.isCollapsed ?? model.isCollapsed) + ? liveMemberWorkspaceIds.reduce(0) { $0 + snapshot.unreadCount(forWorkspaceId: $1) } : snapshot.unreadCount(forWorkspaceId: anchorWorkspaceId) @@ -234,10 +243,10 @@ extension VerticalTabsSidebar { .summary(forWorkspaceId: anchorWorkspaceId) .hasLatestNotification fresh.canMarkAllRead = snapshot.canMarkWorkspaceRead( - forWorkspaceIds: nonAnchorMemberIds + forWorkspaceIds: liveNonAnchorMemberIds ) fresh.canMarkAllUnread = snapshot.canMarkWorkspaceUnread( - forWorkspaceIds: nonAnchorMemberIds + forWorkspaceIds: liveNonAnchorMemberIds ) return fresh } From 942888b51fabb2614233c26e71aaba3e02f4f7ee Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:11:31 -0700 Subject: [PATCH 22/36] Add remaining Pi latency regressions --- .../SidebarUnreadSnapshotTests.swift | 46 +++++++++++++ tests/test_pi_extension_dispatch.py | 10 ++- tests/test_pi_extension_install.py | 64 ++++++++++++++++++- 3 files changed, 115 insertions(+), 5 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift index 16ae9ad7e5ce..7f4fb397246f 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -108,4 +108,50 @@ struct SidebarUnreadSnapshotTests { ) #expect(recorder.snapshots.count == 2) } + + @Test + @MainActor + func reentrantPublicationsRemainOrderedForEveryObserver() { + final class Recorder { + var totals: [Int] = [] + } + final class ReentrancyState { + var didPublishNestedSnapshot = false + } + + let model = SidebarUnreadModel() + let first = Recorder() + let second = Recorder() + let reentrancy = ReentrancyState() + let receive: @MainActor (Recorder, SidebarUnreadSnapshot) -> Void = { recorder, snapshot in + recorder.totals.append(snapshot.totalUnreadCount) + guard !reentrancy.didPublishNestedSnapshot else { return } + reentrancy.didPublishNestedSnapshot = true + model.apply( + totalUnreadCount: 2, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + } + let firstObservation = model.observeChanges(owner: first, receive) + let secondObservation = model.observeChanges(owner: second, receive) + defer { + firstObservation.cancel() + secondObservation.cancel() + } + + model.apply( + totalUnreadCount: 1, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + + #expect(first.totals == [1, 2]) + #expect(second.totals == [1, 2]) + #expect(model.snapshot.totalUnreadCount == 2) + } } diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index f7ae071b0315..2ce2269ca210 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -381,12 +381,18 @@ def check_cross_session_lifecycle_isolation( const healthy = context("pi-healthy-session"); handlers.get("before_agent_start")({ prompt: "block session A" }, slow); const logPath = process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_LOG; -while (true) { +const slowStartDeadline = performance.now() + 5000; +let sawSlowStart = false; +while (performance.now() < slowStartDeadline) { try { - if ((await Bun.file(logPath).text()).includes("pi-slow-session")) break; + if ((await Bun.file(logPath).text()).includes("pi-slow-session")) { + sawSlowStart = true; + break; + } } catch (_) {} await new Promise((resolve) => setTimeout(resolve, 10)); } +if (!sawSlowStart) throw new Error("slow session never entered cmux dispatch"); await handlers.get("session_shutdown")({ reason: "session B complete" }, healthy); writeFileSync(process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE, "ready"); await handlers.get("session_shutdown")({ reason: "session A complete" }, slow); diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index ce8c40425ffc..7b2b04b1b654 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -28,6 +28,24 @@ def make_executable(path: Path, content: str) -> None: path.chmod(0o755) +def communicate_or_terminate( + process: subprocess.Popen[str], + *, + input_text: str | None = None, + timeout: float = 20, +) -> tuple[str, str]: + try: + return process.communicate(input=input_text, timeout=timeout) + except subprocess.TimeoutExpired: + process.terminate() + try: + process.communicate(timeout=2) + except subprocess.TimeoutExpired: + process.kill() + process.communicate() + raise + + def wait_for_text( path: Path, expected_count: int, @@ -142,6 +160,23 @@ def main() -> int: print("FAIL: Pi session-start did not refresh the stale cmux-managed extension") return 1 + extension_path.write_text("", encoding="utf-8") + empty_refresh_result = subprocess.run( + refresh_command, + input=refresh_payload, + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if empty_refresh_result.returncode == 0: + print("FAIL: empty Pi refresh fixture unexpectedly connected to its missing socket") + return 1 + if extension_path.read_text(encoding="utf-8") != extension_text: + print("FAIL: Pi session-start did not repair an empty managed extension") + return 1 + extension_path.write_text( "// cmux-pi-session-extension-marker v2\n// stale managed race fixture\n", encoding="utf-8", @@ -159,8 +194,16 @@ def main() -> int: env=refresh_env, ) extension_path.write_text(replacement, encoding="utf-8") + try: + communicate_or_terminate( + blocked_refresh, + input_text=refresh_payload, + timeout=1, + ) + except subprocess.TimeoutExpired: + print("FAIL: Pi session-start refresh blocked on its advisory lock") + return 1 fcntl.flock(lock, fcntl.LOCK_UN) - blocked_refresh.communicate(input=refresh_payload, timeout=20) if extension_path.read_text(encoding="utf-8") != replacement: print("FAIL: in-flight Pi refresh overwrote a replacement extension") return 1 @@ -188,9 +231,24 @@ def main() -> int: text=True, env=refresh_env, ) + refresh_timed_out = False + try: + communicate_or_terminate( + blocked_refresh, + input_text=refresh_payload, + timeout=1, + ) + except subprocess.TimeoutExpired: + refresh_timed_out = True fcntl.flock(lock, fcntl.LOCK_UN) - blocked_refresh.communicate(input=refresh_payload, timeout=20) - uninstall_stdout, uninstall_stderr = blocked_uninstall.communicate(timeout=20) + try: + uninstall_stdout, uninstall_stderr = communicate_or_terminate(blocked_uninstall) + except subprocess.TimeoutExpired: + print("FAIL: concurrent Pi uninstall timed out") + return 1 + if refresh_timed_out: + print("FAIL: concurrent Pi refresh blocked behind uninstall") + return 1 if blocked_uninstall.returncode != 0: print( "FAIL: concurrent Pi uninstall failed: " From 4d65663e507b61174ef66137c5a4f8dc8373489a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:16:41 -0700 Subject: [PATCH 23/36] Avoid blocking Pi refresh and stale unread delivery --- CLI/CMUXCLI+PiExtension.swift | 21 +++++++++---- .../SidebarUnreadSnapshot.swift | 30 +++++++++++++++---- ...MUXInstalledExtensionSidebarHostView.swift | 16 +--------- Sources/ContentView.swift | 2 +- 4 files changed, 42 insertions(+), 27 deletions(-) diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift index 4c0cbbe04089..1ca5b8b683fa 100644 --- a/CLI/CMUXCLI+PiExtension.swift +++ b/CLI/CMUXCLI+PiExtension.swift @@ -27,12 +27,14 @@ extension CMUXCLI { } } + @discardableResult private func withPiExtensionMutationLock( at extensionURL: URL, createParentDirectory: Bool, + acquireNonBlocking: Bool = false, fileManager: FileManager = .default, _ operation: () throws -> T - ) throws -> T { + ) throws -> T? { let directoryURL = extensionURL.deletingLastPathComponent() if createParentDirectory { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) @@ -47,10 +49,14 @@ extension CMUXCLI { throw piExtensionReadError(at: extensionURL) } defer { Darwin.close(descriptor) } - guard Darwin.flock(descriptor, LOCK_EX) == 0 else { + let lockOperation = LOCK_EX | (acquireNonBlocking ? LOCK_NB : 0) + guard flock(descriptor, lockOperation) == 0 else { + if acquireNonBlocking, errno == EWOULDBLOCK || errno == EAGAIN { + return nil + } throw piExtensionReadError(at: extensionURL) } - defer { Darwin.flock(descriptor, LOCK_UN) } + defer { flock(descriptor, LOCK_UN) } return try operation() } @@ -72,11 +78,16 @@ extension CMUXCLI { try withPiExtensionMutationLock( at: extensionURL, createParentDirectory: false, + acquireNonBlocking: true, fileManager: fileManager ) { + guard fileManager.fileExists(atPath: extensionURL.path) else { return } let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) - guard !existing.isEmpty, - existing.contains(Self.piExtensionMarker), + if existing.isEmpty { + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + return + } + guard existing.contains(Self.piExtensionMarker), existing != Self.piExtensionSource else { return diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift index 6bc9d53b8dc9..2083510200ae 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift @@ -167,6 +167,10 @@ public final class SidebarUnreadModel { @ObservationIgnored private var snapshotObservers: [UUID: (SidebarUnreadSnapshot) -> Bool] = [:] + @ObservationIgnored + private var pendingSnapshots: [SidebarUnreadSnapshot] = [] + @ObservationIgnored + private var isPublishingSnapshot = false /// Creates an empty unread model. public init() {} @@ -202,13 +206,27 @@ public final class SidebarUnreadModel { focusedReadIndicatorByWorkspaceId: focusedReadIndicatorByWorkspaceId, manualUnreadWorkspaceIds: manualUnreadWorkspaceIds ) - guard snapshot != next else { return } - snapshot = next - var expiredObserverIDs: [UUID] = [] - for (id, observer) in snapshotObservers where !observer(next) { - expiredObserverIDs.append(id) + guard (pendingSnapshots.last ?? snapshot) != next else { return } + pendingSnapshots.append(next) + guard !isPublishingSnapshot else { return } + + isPublishingSnapshot = true + defer { + pendingSnapshots.removeAll(keepingCapacity: true) + isPublishingSnapshot = false + } + var publicationIndex = 0 + while publicationIndex < pendingSnapshots.count { + let publication = pendingSnapshots[publicationIndex] + publicationIndex += 1 + snapshot = publication + for id in Array(snapshotObservers.keys) { + guard let observer = snapshotObservers[id] else { continue } + if !observer(publication) { + snapshotObservers[id] = nil + } + } } - for id in expiredObserverIDs { snapshotObservers[id] = nil } } fileprivate func removeSnapshotObserver(_ id: UUID) { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 80923c5d7d34..882302707112 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -174,20 +174,6 @@ private final class CMUXSidebarSnapshotCache { } } -private struct CMUXSidebarUnreadSnapshotObserver: View { - let source: SidebarUnreadModel - let action: @MainActor (SidebarUnreadSnapshot) -> Void - - var body: some View { - Color.clear - .frame(width: 0, height: 0) - .accessibilityHidden(true) - .onChange(of: source.snapshot) { _, snapshot in - action(snapshot) - } - } -} - struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" @@ -322,7 +308,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { await observeExtensionAvailability() } .background { - CMUXSidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in + SidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in // Rebuild rich metadata only when workspace membership changed. // The common unread-only path stays a cheap cache patch. if !snapshotCache.containsWorkspaces(workspaceIDsProvider()) { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 8f705f56e54b..5977930974d8 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -824,7 +824,7 @@ private struct SidebarUnreadSnapshotReader: View { } /// Runs an imperative unread side effect from an isolated Observation leaf. -private struct SidebarUnreadSnapshotObserver: View { +struct SidebarUnreadSnapshotObserver: View { let source: SidebarUnreadModel let action: @MainActor (SidebarUnreadSnapshot) -> Void From 2ed483fb9a2dfe66c868c3a64401f09284ff6c4a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:29:45 -0700 Subject: [PATCH 24/36] Add manual unread action regression --- .../SidebarUnreadSnapshotTests.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift index 7f4fb397246f..3614e58c0163 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -37,6 +37,16 @@ struct SidebarUnreadSnapshotTests { #expect(snapshot.summary(forWorkspaceId: UUID()).unreadCount == 0) } + @Test + func manualUnreadStateControlsWorkspaceActionsWithoutANotificationCount() { + let workspaceID = UUID() + let snapshot = SidebarUnreadSnapshot(manualUnreadWorkspaceIds: [workspaceID]) + + #expect(snapshot.workspaceIsUnread(forWorkspaceId: workspaceID)) + #expect(snapshot.canMarkWorkspaceRead(forWorkspaceIds: [workspaceID])) + #expect(!snapshot.canMarkWorkspaceUnread(forWorkspaceIds: [workspaceID])) + } + @Test @MainActor func modelPublishesOnlyChangedAtomicSnapshots() { From a06da1d0f1587fb8ec528a2a92e01ce26e1ed381 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:31:22 -0700 Subject: [PATCH 25/36] Keep unread actions and group refreshes scoped --- .../SidebarUnreadSnapshot.swift | 12 +++++----- .../VerticalTabsSidebar+WorkspaceGroups.swift | 24 ++++++++----------- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift index 2083510200ae..9fd421ca8975 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift @@ -39,15 +39,15 @@ public struct SidebarSurfaceUnreadKey: Hashable, Sendable { /// One atomic unread-state publication shared by all presentation surfaces. public struct SidebarUnreadSnapshot: Equatable, Sendable { /// Total unread count rendered by global badges. - public var totalUnreadCount: Int + public let totalUnreadCount: Int /// Per-workspace row summaries, omitting default empty summaries. - public var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] + public let summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] /// Workspace and surface pairs with unread notifications. - public var unreadSurfaceKeys: Set + public let unreadSurfaceKeys: Set /// Focused surfaces whose read indicator remains visible. - public var focusedReadIndicatorByWorkspaceId: [UUID: UUID] + public let focusedReadIndicatorByWorkspaceId: [UUID: UUID] /// Workspaces explicitly marked unread by the user. - public var manualUnreadWorkspaceIds: Set + public let manualUnreadWorkspaceIds: Set /// Creates one complete unread snapshot. public init( @@ -84,7 +84,7 @@ public struct SidebarUnreadSnapshot: Equatable, Sendable { /// Returns whether the workspace has any displayed unread state. public func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { - unreadCount(forWorkspaceId: id) > 0 + unreadCount(forWorkspaceId: id) > 0 || hasManualUnread(forWorkspaceId: id) } /// Returns whether the workspace was explicitly marked unread. diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index c16e6376df67..ed3c2d22e84b 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -217,19 +217,15 @@ extension VerticalTabsSidebar { unreadDependencyWorkspaceIds: Set(memberWorkspaceIds) .union([group.anchorWorkspaceId]), unreadRebuild: { - [weak tabManager, model, groupId = group.id, - anchorWorkspaceId = group.anchorWorkspaceId, - memberWorkspaceIds] snapshot in - let liveGroup = tabManager?.workspaceGroups.first { $0.id == groupId } - let liveMemberWorkspaceIds = tabManager?.tabs.compactMap { - $0.groupId == groupId ? $0.id : nil - } ?? memberWorkspaceIds - let liveNonAnchorMemberIds = liveMemberWorkspaceIds.filter { - $0 != anchorWorkspaceId - } + [model, anchorWorkspaceId = group.anchorWorkspaceId, + isCollapsed = group.isCollapsed, memberWorkspaceIds, + nonAnchorMemberIds] snapshot in + // Membership and collapse are structural row inputs, so their + // changes rebuild this configuration. Reuse the render context's + // indexed members instead of rescanning every tab per unread row. var fresh = model - fresh.anchorUnreadCount = (liveGroup?.isCollapsed ?? model.isCollapsed) - ? liveMemberWorkspaceIds.reduce(0) { + fresh.anchorUnreadCount = isCollapsed + ? memberWorkspaceIds.reduce(0) { $0 + snapshot.unreadCount(forWorkspaceId: $1) } : snapshot.unreadCount(forWorkspaceId: anchorWorkspaceId) @@ -243,10 +239,10 @@ extension VerticalTabsSidebar { .summary(forWorkspaceId: anchorWorkspaceId) .hasLatestNotification fresh.canMarkAllRead = snapshot.canMarkWorkspaceRead( - forWorkspaceIds: liveNonAnchorMemberIds + forWorkspaceIds: nonAnchorMemberIds ) fresh.canMarkAllUnread = snapshot.canMarkWorkspaceUnread( - forWorkspaceIds: liveNonAnchorMemberIds + forWorkspaceIds: nonAnchorMemberIds ) return fresh } From 67246d31db605f6989b5560edbcb2f7b39f74fee Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 23:21:54 -0700 Subject: [PATCH 26/36] Add extension snapshot sequence regression --- ...MUXInstalledExtensionSidebarHostView.swift | 2 +- ...rWorkspaceSnapshotRefreshPolicyTests.swift | 42 +++++++++++++++++++ tests/test_pi_extension_install.py | 25 +++++++++-- 3 files changed, 65 insertions(+), 4 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 882302707112..49f113bc4d7e 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -134,7 +134,7 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { } @MainActor -private final class CMUXSidebarSnapshotCache { +final class CMUXSidebarSnapshotCache { private(set) var snapshot: CmuxSidebarSnapshot? func replace(with next: CmuxSidebarSnapshot) -> CmuxSidebarSnapshot { diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index e4bec409fd53..cb5a0b37e27a 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -1,6 +1,8 @@ import AppKit +import CmuxNotifications import CmuxSidebar import CmuxWorkspaces +@_spi(CmuxHostTransport) import CmuxExtensionKit import SwiftUI import Testing #if canImport(cmux_DEV) @@ -10,6 +12,46 @@ import Testing #endif @Suite struct SidebarWorkspaceSnapshotRefreshPolicyTests { + @Test @MainActor + func extensionSnapshotCacheDoesNotInflateSequenceForIdenticalProviderContent() throws { + let workspaceID = UUID() + let initial = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [CmuxSidebarWorkspace(id: workspaceID, title: "Pi")] + ) + let cache = CMUXSidebarSnapshotCache() + _ = cache.replace(with: initial) + let unread = SidebarUnreadSnapshot( + totalUnreadCount: 1, + summaryByWorkspaceId: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Done" + ), + ] + ) + let patched = try #require(cache.applyUnread(unread)) + let matchingProvider = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [ + CmuxSidebarWorkspace( + id: workspaceID, + title: "Pi", + unreadCount: 1, + latestNotification: "Done" + ), + ] + ) + + let firstPoll = cache.replace(with: matchingProvider) + let secondPoll = cache.replace(with: matchingProvider) + + #expect(firstPoll.sequence == patched.sequence) + #expect(secondPoll.sequence == patched.sequence) + } + @Test func contextMenuPinChangeUpdatesDisplayedFieldsAndDefersNoisyFields() { let current = Self.snapshot( title: "lmao", diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index 7b2b04b1b654..85620f12584b 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -9,6 +9,7 @@ import fcntl import json import os +import signal import shutil import subprocess import tempfile @@ -37,12 +38,27 @@ def communicate_or_terminate( try: return process.communicate(input=input_text, timeout=timeout) except subprocess.TimeoutExpired: - process.terminate() + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass try: process.communicate(timeout=2) except subprocess.TimeoutExpired: - process.kill() - process.communicate() + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + process.communicate(timeout=2) + except subprocess.TimeoutExpired: + for pipe in (process.stdin, process.stdout, process.stderr): + if pipe is not None: + pipe.close() + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + pass raise @@ -192,6 +208,7 @@ def main() -> int: stderr=subprocess.PIPE, text=True, env=refresh_env, + start_new_session=True, ) extension_path.write_text(replacement, encoding="utf-8") try: @@ -223,6 +240,7 @@ def main() -> int: stderr=subprocess.PIPE, text=True, env=refresh_env, + start_new_session=True, ) blocked_uninstall = subprocess.Popen( [cli_path, "hooks", "pi", "uninstall"], @@ -230,6 +248,7 @@ def main() -> int: stderr=subprocess.PIPE, text=True, env=refresh_env, + start_new_session=True, ) refresh_timed_out = False try: From 6a3e3f9a20f5bb9ba641956933530da592e69dc0 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 23:22:25 -0700 Subject: [PATCH 27/36] Preserve extension sequence for identical snapshots --- Sources/CMUXInstalledExtensionSidebarHostView.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 49f113bc4d7e..b8966627f4de 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -143,6 +143,9 @@ final class CMUXSidebarSnapshotCache { return next } guard current != next else { return current } + var contentComparableNext = next + contentComparableNext.sequence = current.sequence + guard current != contentComparableNext else { return current } var updated = next updated.sequence = max(next.sequence, current.sequence &+ 1) snapshot = updated From 3f26fb456b491103ecec2f51c6d04ac171719c72 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 23:35:04 -0700 Subject: [PATCH 28/36] Add Pi lock symlink regression --- tests/test_pi_extension_install.py | 36 ++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index 85620f12584b..a6bd37c48218 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -23,6 +23,8 @@ resolve_cmux_cli, ) +NONBLOCKING_LOCK_TIMEOUT_SECONDS = 5.0 + def make_executable(path: Path, content: str) -> None: path.write_text(content, encoding="utf-8") @@ -215,7 +217,7 @@ def main() -> int: communicate_or_terminate( blocked_refresh, input_text=refresh_payload, - timeout=1, + timeout=NONBLOCKING_LOCK_TIMEOUT_SECONDS, ) except subprocess.TimeoutExpired: print("FAIL: Pi session-start refresh blocked on its advisory lock") @@ -255,7 +257,7 @@ def main() -> int: communicate_or_terminate( blocked_refresh, input_text=refresh_payload, - timeout=1, + timeout=NONBLOCKING_LOCK_TIMEOUT_SECONDS, ) except subprocess.TimeoutExpired: refresh_timed_out = True @@ -280,6 +282,36 @@ def main() -> int: extension_path = install_pi_extension(config_dir, cli_path) extension_text = extension_path.read_text(encoding="utf-8") + stale_symlink_fixture = ( + "// cmux-pi-session-extension-marker v2\n" + "// stale lock symlink fixture\n" + ) + extension_path.write_text(stale_symlink_fixture, encoding="utf-8") + lock_path.unlink(missing_ok=True) + lock_target = root / "redirected-lock-target" + lock_target.write_text("sentinel\n", encoding="utf-8") + lock_path.symlink_to(lock_target) + symlink_result = subprocess.run( + [cli_path, "hooks", "pi", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if symlink_result.returncode == 0: + print("FAIL: Pi install followed a symlinked mutation lock") + return 1 + if extension_path.read_text(encoding="utf-8") != stale_symlink_fixture: + print("FAIL: Pi install mutated the extension through a symlinked lock") + return 1 + if lock_target.read_text(encoding="utf-8") != "sentinel\n": + print("FAIL: Pi install mutated the symlinked lock target") + return 1 + lock_path.unlink() + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + bin_dir = root / "bin" bin_dir.mkdir() fake_pi = bin_dir / "pi" From 00d661c3a56022ea11a0d3742d8166b189fb390c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 23:38:13 -0700 Subject: [PATCH 29/36] Index extension unread updates and harden Pi lock --- CLI/CMUXCLI+PiExtension.swift | 7 +- ...MUXInstalledExtensionSidebarHostView.swift | 68 +++++++++++++------ Sources/ContentView.swift | 1 - .../Cells/SidebarGroupHeaderRowModel.swift | 2 +- cmuxTests/FileDropOverlayViewTests.swift | 1 - ...rWorkspaceSnapshotRefreshPolicyTests.swift | 16 +++++ 6 files changed, 70 insertions(+), 25 deletions(-) diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift index 1ca5b8b683fa..c52cc9abfaec 100644 --- a/CLI/CMUXCLI+PiExtension.swift +++ b/CLI/CMUXCLI+PiExtension.swift @@ -42,13 +42,18 @@ extension CMUXCLI { let lockURL = directoryURL.appendingPathComponent(".cmux-session.lock", isDirectory: false) let descriptor = Darwin.open( lockURL.path, - O_CREAT | O_RDWR, + O_CREAT | O_RDWR | O_CLOEXEC | O_NOFOLLOW, mode_t(S_IRUSR | S_IWUSR) ) guard descriptor >= 0 else { throw piExtensionReadError(at: extensionURL) } defer { Darwin.close(descriptor) } + var metadata = stat() + guard Darwin.fstat(descriptor, &metadata) == 0, + metadata.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { + throw piExtensionReadError(at: extensionURL) + } let lockOperation = LOCK_EX | (acquireNonBlocking ? LOCK_NB : 0) guard flock(descriptor, lockOperation) == 0 else { if acquireNonBlocking, errno == EWOULDBLOCK || errno == EAGAIN { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b8966627f4de..5ba366f5771a 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -135,11 +135,32 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { @MainActor final class CMUXSidebarSnapshotCache { + private struct CachedUnreadState: Equatable { + let unreadCount: Int + let latestNotification: String? + + init(workspace: CmuxSidebarWorkspace) { + unreadCount = workspace.unreadCount + latestNotification = workspace.latestNotification + } + + init(summary: SidebarWorkspaceUnreadSummary) { + unreadCount = summary.unreadCount + latestNotification = summary.latestNotificationText + } + + var isEmpty: Bool { + unreadCount == 0 && latestNotification == nil + } + } + private(set) var snapshot: CmuxSidebarSnapshot? + private var workspaceIndexByID: [UUID: Int] = [:] + private var unreadStateByWorkspaceID: [UUID: CachedUnreadState] = [:] func replace(with next: CmuxSidebarSnapshot) -> CmuxSidebarSnapshot { guard let current = snapshot else { - snapshot = next + store(next) return next } guard current != next else { return current } @@ -148,23 +169,27 @@ final class CMUXSidebarSnapshotCache { guard current != contentComparableNext else { return current } var updated = next updated.sequence = max(next.sequence, current.sequence &+ 1) - snapshot = updated + store(updated) return updated } func applyUnread(_ unread: SidebarUnreadSnapshot) -> CmuxSidebarSnapshot? { guard var next = snapshot else { return nil } + var candidateWorkspaceIDs = Set(unreadStateByWorkspaceID.keys) + candidateWorkspaceIDs.formUnion(unread.summaryByWorkspaceId.keys) var changed = false - for index in next.workspaces.indices { - let summary = unread.summary(forWorkspaceId: next.workspaces[index].id) - if next.workspaces[index].unreadCount != summary.unreadCount { - next.workspaces[index].unreadCount = summary.unreadCount - changed = true - } - if next.workspaces[index].latestNotification != summary.latestNotificationText { - next.workspaces[index].latestNotification = summary.latestNotificationText - changed = true + for workspaceID in candidateWorkspaceIDs { + guard let index = workspaceIndexByID[workspaceID] else { continue } + let state = CachedUnreadState(summary: unread.summary(forWorkspaceId: workspaceID)) + guard unreadStateByWorkspaceID[workspaceID] != state else { continue } + next.workspaces[index].unreadCount = state.unreadCount + next.workspaces[index].latestNotification = state.latestNotification + if state.isEmpty { + unreadStateByWorkspaceID[workspaceID] = nil + } else { + unreadStateByWorkspaceID[workspaceID] = state } + changed = true } guard changed else { return nil } next.sequence &+= 1 @@ -172,8 +197,17 @@ final class CMUXSidebarSnapshotCache { return next } - func containsWorkspaces(_ workspaceIDs: [UUID]) -> Bool { - snapshot?.workspaces.map(\.id) == workspaceIDs + private func store(_ next: CmuxSidebarSnapshot) { + snapshot = next + workspaceIndexByID = Dictionary( + uniqueKeysWithValues: next.workspaces.enumerated().map { ($1.id, $0) } + ) + unreadStateByWorkspaceID = Dictionary( + uniqueKeysWithValues: next.workspaces.compactMap { workspace in + let state = CachedUnreadState(workspace: workspace) + return state.isEmpty ? nil : (workspace.id, state) + } + ) } } @@ -182,7 +216,6 @@ struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" var snapshotProvider: @MainActor () -> CmuxSidebarSnapshot - var workspaceIDsProvider: @MainActor () -> [UUID] var snapshotUpdateToken: UInt64 = 0 let unreadSource: SidebarUnreadModel var actionHandler: @MainActor (CmuxSidebarAction) -> CmuxSidebarActionResult @@ -312,13 +345,6 @@ struct CMUXInstalledExtensionSidebarHostView: View { } .background { SidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in - // Rebuild rich metadata only when workspace membership changed. - // The common unread-only path stays a cheap cache patch. - if !snapshotCache.containsWorkspaces(workspaceIDsProvider()) { - let snapshot = snapshotCache.replace(with: snapshotProvider()) - xpcHost.sendSnapshotDidChange(snapshot) - return - } guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { return } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 672829afc290..f3cb458856c4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -11976,7 +11976,6 @@ struct VerticalTabsSidebar: View, Equatable { if effectiveExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, - workspaceIDsProvider: { tabManager.tabs.map(\.id) }, snapshotUpdateToken: extensionSidebarUpdateToken, unreadSource: sidebarUnread, actionHandler: { handleCMUXSidebarExtensionAction($0) }, diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift index 0abdc0de73ae..916e5d403ebf 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift @@ -2,7 +2,7 @@ import AppKit import CoreGraphics import Foundation -/// Immutable render input for one pure-AppKit sidebar group header row. +/// Value-snapshot render input for one pure-AppKit sidebar group header row. /// /// Value fields only: action closures live in ``SidebarGroupHeaderRowActions`` /// and are excluded from equality so recycled cells can reconfigure cheaply diff --git a/cmuxTests/FileDropOverlayViewTests.swift b/cmuxTests/FileDropOverlayViewTests.swift index c4eaec78ab0b..29424bc54db3 100644 --- a/cmuxTests/FileDropOverlayViewTests.swift +++ b/cmuxTests/FileDropOverlayViewTests.swift @@ -4,7 +4,6 @@ import SwiftUI import Testing import WebKit import CmuxUpdater -import CmuxNotifications #if canImport(cmux_DEV) @testable import cmux_DEV diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index cb5a0b37e27a..80d1b667b328 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -50,6 +50,22 @@ import Testing #expect(firstPoll.sequence == patched.sequence) #expect(secondPoll.sequence == patched.sequence) + + let changedProvider = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [ + CmuxSidebarWorkspace( + id: workspaceID, + title: "Pi renamed", + unreadCount: 1, + latestNotification: "Done" + ), + ] + ) + let changedPoll = cache.replace(with: changedProvider) + #expect(changedPoll.sequence == patched.sequence + 1) + #expect(changedPoll.workspaces.first?.title == "Pi renamed") } @Test func contextMenuPinChangeUpdatesDisplayedFieldsAndDefersNoisyFields() { From e4bab820176301aa329d682d9a42f3561c5feff5 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 31 Jul 2026 23:50:40 -0700 Subject: [PATCH 30/36] Fix sidebar scale test construction --- cmuxTests/SidebarLazyLayoutScaleTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/cmuxTests/SidebarLazyLayoutScaleTests.swift b/cmuxTests/SidebarLazyLayoutScaleTests.swift index d509d535d657..50e69c85f7b7 100644 --- a/cmuxTests/SidebarLazyLayoutScaleTests.swift +++ b/cmuxTests/SidebarLazyLayoutScaleTests.swift @@ -148,6 +148,7 @@ final class SidebarLazyLayoutScaleTests { updateViewModel: UpdateStateModel(), fileExplorerState: FileExplorerState(), sidebarUnread: unread, + titlebarControlsLayoutModel: TitlebarControlsLayoutModel(), windowId: UUID(), onSendFeedback: {}, onToggleSidebar: {}, From 02c4387667397b4085950bd3f2a85caf36b41ade Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 00:03:55 -0700 Subject: [PATCH 31/36] Import titlebar test dependency --- cmuxTests/UpdatePillReleaseVisibilityTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index aecc70e9cf06..ee5ac5175a41 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -1,5 +1,6 @@ import Foundation import AppKit +import CmuxFoundation import Testing #if canImport(cmux_DEV) From bd437b98cf58cfba7a860b166d49c8b7dde564c8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 00:09:31 -0700 Subject: [PATCH 32/36] Fix Pi regression fixtures --- tests/test_pi_extension_dispatch.py | 7 ++++--- tests/test_pi_extension_install.py | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index 2ce2269ca210..a1610fd84508 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -200,10 +200,11 @@ def check_ui_lifecycle_handlers_return_immediately( }; await Promise.resolve(handlers.get("session_start")({}, ctx)); await Promise.resolve(handlers.get("before_agent_start")({ prompt: "hello" }, ctx)); -await Promise.resolve(handlers.get("tool_execution_start")({ +await Promise.resolve(handlers.get("tool_execution_end")({ toolCallId: "ui-lifecycle-tool", toolName: "bash", - args: { command: "true" } + result: { content: [{ type: "text", text: "done" }] }, + isError: false }, ctx)); await Promise.resolve(handlers.get("agent_end")({ messages: [{ role: "assistant", content: "done" }], @@ -253,7 +254,7 @@ def check_ui_lifecycle_handlers_return_immediately( "--json surface resume set", "--json surface resume get", "hooks pi prompt-submit", - "hooks feed --source pi --event PreToolUse", + "hooks feed --source pi --event PostToolUse", "hooks pi notification", "hooks pi stop", ) diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index a6bd37c48218..e41614897ca1 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -227,6 +227,7 @@ def main() -> int: print("FAIL: in-flight Pi refresh overwrote a replacement extension") return 1 + extension_path.unlink() extension_path = install_pi_extension(config_dir, cli_path) extension_text = extension_path.read_text(encoding="utf-8") extension_path.write_text( From 05f53221968a3042113f74edfd437357fa4a9154 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 00:17:59 -0700 Subject: [PATCH 33/36] Stabilize sidebar projection scale gate --- cmuxTests/SidebarLazyLayoutScaleTests.swift | 30 ++++++++++++++------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/cmuxTests/SidebarLazyLayoutScaleTests.swift b/cmuxTests/SidebarLazyLayoutScaleTests.swift index 50e69c85f7b7..4b7700314c88 100644 --- a/cmuxTests/SidebarLazyLayoutScaleTests.swift +++ b/cmuxTests/SidebarLazyLayoutScaleTests.swift @@ -320,21 +320,33 @@ final class SidebarLazyLayoutScaleTests { await Self.drainMainRunLoop(for: harness.window) - // The default sidebar intentionally accepts the initial value from - // both workspace publisher families. Wait for those known initial - // projections before isolating the operation count for this burst. - // Initial mount builds fallback + owner snapshots, then each of the - // two keyed publisher families delivers its accepted initial value. - let initialObservationBuildFloor = Self.workspaceCount * 4 + // Wait for initial workspace publishers to quiesce before isolating + // the operation count for this burst. The exact number of accepted + // initial projections is an implementation detail; the invariant is + // that every workspace is projected and the owner reaches a stable + // snapshot before the counter resets. let initialDeadline = ProcessInfo.processInfo.systemUptime + 3 - while harness.counter.workspaceSnapshotBuilds < initialObservationBuildFloor, + var previousInitialBuildCount = -1 + var stableInitialPasses = 0 + while stableInitialPasses < 4, ProcessInfo.processInfo.systemUptime < initialDeadline { Self.turnMainRunLoopOnce(layingOut: harness.window) await Task.yield() + let currentBuildCount = harness.counter.workspaceSnapshotBuilds + if currentBuildCount == previousInitialBuildCount { + stableInitialPasses += 1 + } else { + previousInitialBuildCount = currentBuildCount + stableInitialPasses = 0 + } } #expect( - harness.counter.workspaceSnapshotBuilds >= initialObservationBuildFloor, - "Initial keyed workspace publisher values did not reach the snapshot owner." + harness.counter.workspaceSnapshotBuilds >= Self.workspaceCount, + "Initial workspace values did not reach the snapshot owner." + ) + #expect( + stableInitialPasses == 4, + "Initial workspace publishers did not quiesce before the batch measurement." ) harness.counter.reset() From 21e48f289e6e2f9fe4c4d05aacce6f210f07e568 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 00:43:14 -0700 Subject: [PATCH 34/36] Fix titlebar observer isolation warning --- Sources/Update/UpdateTitlebarAccessory.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index fde0dff6d5a1..66df7d5750a2 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -158,7 +158,7 @@ final class TitlebarControlsLayoutModel { private let defaults: UserDefaults @ObservationIgnored - private nonisolated(unsafe) let notificationCenter: NotificationCenter + private let notificationCenter: NotificationCenter private let contentSizeProvider: ContentSizeProvider @ObservationIgnored private nonisolated(unsafe) var observers: [NSObjectProtocol] = [] From 0c7d27d9ac7293961ec8f9c8671983bdccb29878 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 01:16:04 -0700 Subject: [PATCH 35/36] Fix sidebar extension snapshot warning --- Sources/CMUXInstalledExtensionSidebarHostView.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 5ba366f5771a..fd1f6ee840a7 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1214,7 +1214,7 @@ private final class CMUXSidebarExtensionHostXPC { } func sendSnapshotDidChange() { - guard let extensionProxy, let snapshotProvider else { return } + guard let snapshotProvider else { return } sendSnapshotDidChange(snapshotProvider()) } From 480e6fa1a1445fb51d28211646a339d5d44865c3 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 1 Aug 2026 01:50:02 -0700 Subject: [PATCH 36/36] Fix restore CLI contract probe --- docs/cli-contract.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cli-contract.md b/docs/cli-contract.md index 3b299bf588d8..f7fae9f6032f 100644 --- a/docs/cli-contract.md +++ b/docs/cli-contract.md @@ -560,7 +560,7 @@ the expected text without connecting to a cmux socket. - `cmux enable-browser --help` -> `Usage: cmux enable-browser [--json]` - `cmux browser-status --help` -> `Usage: cmux browser-status [--json]` - `cmux agent-hibernation --help` -> `Usage: cmux agent-hibernation [--json]` -- `cmux restore --help` -> `Usage: cmux restore `; `--surface [id|ref]` uses the caller when omitted. +- `cmux restore --help` -> `Usage: cmux restore ` - `cmux restore-session --help` -> `Usage: cmux restore-session` - `cmux open --help` -> `Usage: cmux open ...` - `cmux feedback --help` -> `Usage: cmux feedback`