Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
41a5ac1
Test Pi managed extension refresh
lawrencecchen Jul 31, 2026
b2e2dee
Refresh managed Pi extension on session start
lawrencecchen Jul 31, 2026
d5303e2
Test Pi lifecycle hook responsiveness
lawrencecchen Jul 31, 2026
0994ab7
Detach Pi lifecycle hooks from UI events
lawrencecchen Jul 31, 2026
713bd78
Test titlebar layout invalidation
lawrencecchen Jul 31, 2026
92cba43
Cache titlebar layout inputs
lawrencecchen Jul 31, 2026
6fed64d
Test unread invalidation scope
lawrencecchen Jul 31, 2026
4ed2cfb
Scope unread invalidation to leaf views
lawrencecchen Jul 31, 2026
f9184b3
Test targeted sidebar unread updates
lawrencecchen Jul 31, 2026
baaa5a1
Route unread updates to affected sidebar rows
lawrencecchen Jul 31, 2026
4d95092
Test heartbeat identity write suppression
lawrencecchen Jul 31, 2026
3c4b3b7
Suppress redundant heartbeat defaults writes
lawrencecchen Jul 31, 2026
cf3dc3c
Merge remote-tracking branch 'origin/main' into feat-pi-extension-lag
lawrencecchen Aug 1, 2026
3c63d53
Localize unread and titlebar observation ownership
lawrencecchen Aug 1, 2026
e2f7aeb
Merge remote-tracking branch 'origin/main' into feat-pi-extension-lag
lawrencecchen Aug 1, 2026
d5d163f
Fix restore argument helper compilation
lawrencecchen Aug 1, 2026
4f18eec
Address unread ownership review findings
lawrencecchen Aug 1, 2026
1c212ee
Publish refreshed extension membership snapshots
lawrencecchen Aug 1, 2026
f3d1df0
Align projected-surface dismissal expectation
lawrencecchen Aug 1, 2026
ea3d89e
Merge remote-tracking branch 'origin/main' into feat-pi-extension-lag
lawrencecchen Aug 1, 2026
c39d076
Add regressions for Pi lifecycle isolation
lawrencecchen Aug 1, 2026
34ea84d
Serialize Pi lifecycle work by session
lawrencecchen Aug 1, 2026
39cc5b9
Tighten Pi and unread regression coverage
lawrencecchen Aug 1, 2026
de98d6b
Scope remaining Pi and sidebar refreshes
lawrencecchen Aug 1, 2026
942888b
Add remaining Pi latency regressions
lawrencecchen Aug 1, 2026
4d65663
Avoid blocking Pi refresh and stale unread delivery
lawrencecchen Aug 1, 2026
6ad517f
Merge remote-tracking branch 'origin/main' into feat-pi-extension-lag
lawrencecchen Aug 1, 2026
2ed483f
Add manual unread action regression
lawrencecchen Aug 1, 2026
a06da1d
Keep unread actions and group refreshes scoped
lawrencecchen Aug 1, 2026
67246d3
Add extension snapshot sequence regression
lawrencecchen Aug 1, 2026
6a3e3f9
Preserve extension sequence for identical snapshots
lawrencecchen Aug 1, 2026
3f26fb4
Add Pi lock symlink regression
lawrencecchen Aug 1, 2026
00d661c
Index extension unread updates and harden Pi lock
lawrencecchen Aug 1, 2026
e4bab82
Fix sidebar scale test construction
lawrencecchen Aug 1, 2026
02c4387
Import titlebar test dependency
lawrencecchen Aug 1, 2026
bd437b9
Fix Pi regression fixtures
lawrencecchen Aug 1, 2026
05f5322
Stabilize sidebar projection scale gate
lawrencecchen Aug 1, 2026
21e48f2
Fix titlebar observer isolation warning
lawrencecchen Aug 1, 2026
0c7d27d
Fix sidebar extension snapshot warning
lawrencecchen Aug 1, 2026
480e6fa
Fix restore CLI contract probe
lawrencecchen Aug 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CLI/CMUXCLI+PiExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
} 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
Expand Down
55 changes: 46 additions & 9 deletions CLI/CMUXCLI+PiExtensionSourcePart2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,33 @@ async function publishPendingCompletion(
export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
const dispatcher = new PiCmuxCommandDispatcher();
const sessionStates = new Map<string, SessionState>();
const lifecycleTasks = new Set<Promise<void>>();

const trackLifecycleTask = (
task: Promise<unknown>,
context: PiExtensionContextSnapshot,
): void => {
let tracked: Promise<void>;
tracked = task
.then(() => undefined)
.catch((error) => {
warn(context, "cmux lifecycle task failed", {
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
error_available: error !== undefined,
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
});
})
.finally(() => {
lifecycleTasks.delete(tracked);
});
lifecycleTasks.add(tracked);
};

const drainLifecycleTasks = async (): Promise<void> => {
while (lifecycleTasks.size > 0) {
await Promise.all([...lifecycleTasks]);
}
};

pi.on("session_start", async (_event, ctx) => {
pi.on("session_start", (_event, ctx) => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const context = snapshotContext(ctx);
const sessionId = context.sessionId;
if (sessionId) {
Expand All @@ -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 () => {
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
const ok = await sendHook(dispatcher, "session-start", context);
if (ok && sessionId) await ensureResumeBinding(dispatcher, context, sessionId);
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
})(), 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 }),
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
context,
);
});

pi.on("tool_execution_start", async (event, ctx) => {
Expand All @@ -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;
Expand All @@ -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) => {
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
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) => {
Expand All @@ -449,6 +485,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
terminationReason: firstString(objectValue(event, ["reason"])) || "session_shutdown",
};
}
await drainLifecycleTasks();
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
await dispatcher.finishFeedForSession(sessionId);
const feedDelivered = !state.feedDeliveryFailed;
state.feedDeliveryFailed = false;
Expand Down
3 changes: 3 additions & 0 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35274,6 +35274,9 @@ export default CMUXSessionRestore;
print(subcommandUsage("hooks") ?? "Usage: cmux hooks <setup|uninstall|agent>")
return true
}
if def.name == "pi", action == "session-start" {
refreshManagedPiExtensionIfNeeded(def)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The added session-start refresh performs synchronous disk I/O — a full file read on every call and a full atomic rewrite whenever stale — on the Pi session-start hook dispatch path. It runs in the cmux CLI subprocess so it doesn't block the app UI directly, but it does add a blocking disk operation to a lifecycle path this PR is meant to keep lightweight, and the rewrite only takes effect for the next session (the current one already loaded the old extension). Consider deferring the write off the synchronous dispatch path (e.g., a fire-and-forget refresh) and short-circuiting on a cheap stat/size check before reading the whole file, since the per-session cost otherwise isn't free on upgrade sessions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At CLI/cmux.swift, line 35278:

<comment>The added session-start refresh performs synchronous disk I/O — a full file read on every call and a full atomic rewrite whenever stale — on the Pi session-start hook dispatch path. It runs in the cmux CLI subprocess so it doesn't block the app UI directly, but it does add a blocking disk operation to a lifecycle path this PR is meant to keep lightweight, and the rewrite only takes effect for the *next* session (the current one already loaded the old extension). Consider deferring the write off the synchronous dispatch path (e.g., a fire-and-forget refresh) and short-circuiting on a cheap stat/size check before reading the whole file, since the per-session cost otherwise isn't free on upgrade sessions.</comment>

<file context>
@@ -35274,6 +35274,9 @@ export default CMUXSessionRestore;
                 return true
             }
+            if def.name == "pi", action == "session-start" {
+                refreshManagedPiExtensionIfNeeded(def)
+            }
             let actionArgs = Array(rest.dropFirst())
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The refresh now skips a contended lock, and Pi's handler returns before the serialized CLI child completes. The remaining steady-state file verification is bounded to the generated managed extension; an atomic rewrite occurs only after an upgrade.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The new pi session-start refresh advances the extension if the existing file differs, but every failure (unreadable/stale-extension path, permission/disk write errors) is swallowed silently with no log or telemetry in refreshManagedPiExtensionIfNeeded. Since this call is now the mechanism keeping the managed extension current on a per-session path, a silent failure means a stale Pi extension persists with zero visibility. Consider logging the caught error (via existing cliTelemetry/Logger) so refresh failures are observable, and noting the write is best-effort in the PR description.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At CLI/cmux.swift, line 35278:

<comment>The new pi session-start refresh advances the extension if the existing file differs, but every failure (unreadable/stale-extension path, permission/disk write errors) is swallowed silently with no log or telemetry in `refreshManagedPiExtensionIfNeeded`. Since this call is now the mechanism keeping the managed extension current on a per-session path, a silent failure means a stale Pi extension persists with zero visibility. Consider logging the caught error (via existing cliTelemetry/Logger) so refresh failures are observable, and noting the write is best-effort in the PR description.</comment>

<file context>
@@ -35274,6 +35274,9 @@ export default CMUXSessionRestore;
                 return true
             }
+            if def.name == "pi", action == "session-start" {
+                refreshManagedPiExtensionIfNeeded(def)
+            }
             let actionArgs = Array(rest.dropFirst())
</file context>

Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
}
let actionArgs = Array(rest.dropFirst())
switch action {
case "inject-args" where def.name == "codex":
Expand Down
Original file line number Diff line number Diff line change
@@ -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<SidebarSurfaceUnreadKey>
/// Focused surfaces whose read indicator remains visible.
public var focusedReadIndicatorByWorkspaceId: [UUID: UUID]
/// Workspaces explicitly marked unread by the user.
public var manualUnreadWorkspaceIds: Set<UUID>

/// Creates one complete unread snapshot.
public init(
totalUnreadCount: Int = 0,
summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:],
unreadSurfaceKeys: Set<SidebarSurfaceUnreadKey> = [],
focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:],
manualUnreadWorkspaceIds: Set<UUID> = []
) {
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) }
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
}

/// 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<SidebarSurfaceUnreadKey> { snapshot.unreadSurfaceKeys }
/// Current focused read-indicator surfaces.
public var focusedReadIndicatorByWorkspaceId: [UUID: UUID] {
snapshot.focusedReadIndicatorByWorkspaceId
}
/// Workspaces explicitly marked unread.
public var manualUnreadWorkspaceIds: Set<UUID> { snapshot.manualUnreadWorkspaceIds }

@ObservationIgnored
private var snapshotObservers: [UUID: AsyncStream<SidebarUnreadSnapshot>.Continuation] = [:]

/// Creates an empty unread model.
public init() {}

/// Returns a stream of changed snapshots, buffering only the newest value.
public func snapshotChanges() -> AsyncStream<SidebarUnreadSnapshot> {
AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in
let id = UUID()
snapshotObservers[id] = continuation
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
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<SidebarSurfaceUnreadKey>,
focusedReadIndicatorByWorkspaceId: [UUID: UUID],
manualUnreadWorkspaceIds: Set<UUID>
) {
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)
}
}
Loading