Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 34 additions & 16 deletions Sources/RestorableAgentSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,11 @@ struct RestorableAgentSessionIndex: Sendable {
let kind: RestorableAgentKind
}

private struct PanelIDKindKey: Hashable {
let panelId: UUID
let kind: RestorableAgentKind
}

private let entriesByPanel: [PanelKey: Entry]
private let entriesByPanelId: [UUID: Entry]

Expand Down Expand Up @@ -1090,6 +1095,7 @@ struct RestorableAgentSessionIndex: Sendable {
}
var hookCandidatesBySession: [SessionKey: Entry] = [:]
var hookCandidatesByPanelAndKind: [PanelKindKey: Entry] = [:]
var hookCandidatesByPanelIdAndKind: [PanelIDKindKey: Entry] = [:]

for (kind, registration) in hookKinds {
let fileURL = kind.hookStoreFileURL(homeDirectory: homeDirectory)
Expand Down Expand Up @@ -1143,6 +1149,7 @@ struct RestorableAgentSessionIndex: Sendable {
let key = PanelKey(workspaceId: workspaceId, panelId: panelId)
let sessionKey = SessionKey(kind: kind, sessionId: normalizedSessionId)
let panelKindKey = PanelKindKey(panelKey: key, kind: kind)
let panelIDKindKey = PanelIDKindKey(panelId: panelId, kind: kind)
let liveProcessID = liveScopedProcessID(
for: effectiveRecord,
kind: kind,
Expand All @@ -1167,6 +1174,12 @@ struct RestorableAgentSessionIndex: Sendable {
) {
hookCandidatesByPanelAndKind[panelKindKey] = entry
}
if shouldReplaceHookEntry(
existing: hookCandidatesByPanelIdAndKind[panelIDKindKey],
incoming: entry
) {
hookCandidatesByPanelIdAndKind[panelIDKindKey] = entry
}
if shouldReplaceHookEntry(
existing: hookCandidatesBySession[sessionKey],
incoming: entry
Expand All @@ -1186,7 +1199,27 @@ struct RestorableAgentSessionIndex: Sendable {
let sameKindPanelCandidate = hookCandidatesByPanelAndKind[
PanelKindKey(panelKey: key, kind: detected.snapshot.kind)
]
if let existing = Self.matchingHookEntry(
let sameKindStablePanelCandidate = sameKindPanelCandidate ?? hookCandidatesByPanelIdAndKind[
PanelIDKindKey(panelId: key.panelId, kind: detected.snapshot.kind)
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Panel-Only Fallback Can Collide

When the hook store contains more than one Pi record with the same stable panelId and kind across different old workspaces, this fallback drops the workspace from the lookup and lets shouldReplaceHookEntry choose a single winner. A restored process whose exact workspace key misses can then receive another workspace's hook snapshot while keeping its own live process IDs, so the UI can show or resume the wrong Pi session for that panel.

Rule Used: Flag correctness-critical detection/identity deriv... (source)

if detected.sessionIDSource == .inferredLatestSessionFile,
let panelCandidate = sameKindStablePanelCandidate {
// Latest-file detection is ambiguous when multiple panels or restored workspaces share a
// cwd. Prefer the hook-store identity for this stable panel/surface while still carrying
// live process evidence for the restored panel. The workspace UUID can rotate during
// session restore, but the surface id is intentionally reused on the normal restore path.
resolved[key] = Entry(
snapshot: panelCandidate.snapshot,
lifecycle: panelCandidate.lifecycle,
updatedAt: panelCandidate.updatedAt,
processIDs: detected.processIDs,
agentProcessIDs: detected.agentProcessIDs,
agentProcessIdentities: agentProcessIdentities(
for: detected.agentProcessIDs,
processIdentityProvider: processIdentityProvider
)
)
} else if let existing = Self.matchingHookEntry(
for: detected.snapshot,
resolved: resolved[key],
panelCandidate: sameKindPanelCandidate,
Expand All @@ -1205,21 +1238,6 @@ struct RestorableAgentSessionIndex: Sendable {
processIdentityProvider: processIdentityProvider
)
)
} else if detected.sessionIDSource == .inferredLatestSessionFile,
let panelCandidate = sameKindPanelCandidate {
// Latest-file detection is ambiguous when multiple panels share a cwd; preserve the exact
// hook-store identity while still carrying live process evidence for this panel.
resolved[key] = Entry(
snapshot: panelCandidate.snapshot,
lifecycle: panelCandidate.lifecycle,
updatedAt: panelCandidate.updatedAt,
processIDs: detected.processIDs,
agentProcessIDs: detected.agentProcessIDs,
agentProcessIdentities: agentProcessIdentities(
for: detected.agentProcessIDs,
processIdentityProvider: processIdentityProvider
)
)
} else {
resolved[key] = Entry(
snapshot: detected.snapshot,
Expand Down
97 changes: 97 additions & 0 deletions cmuxTests/RestorableAgentSessionIndexTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,103 @@ final class RestorableAgentSessionIndexTests: XCTestCase {
XCTAssertEqual(restoredSessionIds, sessionIds)
}

func testPiDetectedLatestSessionDoesNotCollapseExactHookRecordsAfterWorkspaceIdRotation() throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("cmux-pi-restore-workspace-rotation-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }

let cwd = root.appendingPathComponent("repo", isDirectory: true)
let sessionsRoot = root.appendingPathComponent("pi-sessions", isDirectory: true)
let projectDirectory = try XCTUnwrap(PiSessionLocator.projectDirectoryName(for: cwd.path))
let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true)
try fm.createDirectory(at: cwd, withIntermediateDirectories: true)
try fm.createDirectory(at: projectSessions, withIntermediateDirectories: true)

var registration = CmuxVaultAgentRegistration.builtInPi
registration.sessionDirectory = sessionsRoot.path
let registry = CmuxVaultAgentRegistry(registrations: [registration])
let oldWorkspaceIds = [UUID(), UUID(), UUID()]
let restoredWorkspaceIds = [UUID(), UUID(), UUID()]
let panels = [UUID(), UUID(), UUID()]
let sessionIds = ["pi-session-a", "pi-session-b", "pi-session-c"]
var hookSessions: [String: [String: Any]] = [:]
for (index, sessionId) in sessionIds.enumerated() {
let sessionFile = projectSessions.appendingPathComponent("\(sessionId).jsonl", isDirectory: false)
try "{}\n".write(to: sessionFile, atomically: true, encoding: .utf8)
try fm.setAttributes(
[.modificationDate: Date(timeIntervalSince1970: TimeInterval(1_000 + index))],
ofItemAtPath: sessionFile.path
)
hookSessions[sessionId] = driftedAgentHookRecord(
launcher: "pi",
sessionId: sessionId,
workspaceId: oldWorkspaceIds[index],
panelId: panels[index],
recordedCwd: cwd.path,
launchCwd: cwd.path,
updatedAt: TimeInterval(10 + index)
)
}
try writeHookStore(root: root, storeFilename: "pi-hook-sessions.json", sessions: hookSessions)

let processes = panels.enumerated().map { index, panelId in
CmuxTopProcessInfo(
pid: 4_300 + index,
parentPID: 1,
name: "pi",
path: "/usr/local/bin/pi",
ttyDevice: nil,
cmuxWorkspaceID: restoredWorkspaceIds[index],
cmuxSurfaceID: panelId,
cmuxAttributionReason: "cmux-test",
processGroupID: nil,
terminalProcessGroupID: nil,
cpuPercent: 0,
residentBytes: 0,
virtualBytes: 0,
threadCount: 1
)
}
let processSnapshot = CmuxTopProcessSnapshot(
processes: processes,
sampledAt: Date(timeIntervalSince1970: 0),
includesProcessDetails: true
)
let detectedSnapshots = RestorableAgentSessionIndex.processDetectedSnapshots(
registry: registry,
fileManager: fm,
processSnapshot: processSnapshot,
capturedAt: 42,
processArgumentsProvider: { processId in
guard processes.contains(where: { $0.pid == processId }) else { return nil }
return CmuxTopProcessArguments(
arguments: ["/usr/local/bin/pi"],
environment: [
"PWD": cwd.path,
"PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path,
]
)
}
)

let detectedSessionIds = Set(detectedSnapshots.values.map { $0.snapshot.sessionId })
XCTAssertEqual(detectedSessionIds.count, 1, "Pi latest-file detection is ambiguous for same-cwd workspaces")

let index = RestorableAgentSessionIndex.load(
homeDirectory: root.path,
fileManager: fm,
registry: registry,
detectedSnapshots: detectedSnapshots,
processArgumentsProvider: { _ in nil }
)
let restoredSessionIds = try zip(restoredWorkspaceIds, panels).map { workspaceId, panelId in
try XCTUnwrap(index.snapshot(workspaceId: workspaceId, panelId: panelId)).sessionId
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

XCTAssertEqual(restoredSessionIds, sessionIds)
}

func testPiInferredLatestFallbackUsesSameKindPanelHookWhenAnotherKindIsNewer() throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
Expand Down