Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
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
141 changes: 141 additions & 0 deletions Sources/ClaudeSessionTranscriptSeeder.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import Darwin
import Foundation

/// Seeds a Claude Code session transcript into the project dir of a new working
/// directory before a `claude --resume <id>` launch. Claude scopes resume
/// lookups to `<config>/projects/<encoded-cwd>/`, so forking or restoring a
/// conversation into a different directory fails with "No conversation found"
/// unless the transcript is copied there first.
/// https://github.com/manaflow-ai/cmux/issues/5941
enum ClaudeSessionTranscriptSeeder {
/// Claude Code project dir name for a working directory: the absolute path
/// with every non-alphanumeric character replaced by `-`. Claude resolves
/// symlinks before encoding (Node `process.cwd()`), so `/tmp/x` is stored
/// as `-private-tmp-x`.
static func encodedProjectDirName(forWorkingDirectory workingDirectory: String) -> String {
let resolved = symlinkResolvedAbsolutePath(workingDirectory)
return String(resolved.map { character in
character.isASCII && (character.isLetter || character.isNumber) ? character : "-"
})
Comment on lines +18 to +20

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 Badge Use the existing Claude project-dir encoder

For target cwd paths containing other non-alphanumeric characters such as underscores or spaces, this new encoder seeds the transcript under a different directory than the rest of cmux still treats as Claude's project directory (RestorableAgentSessionIndex.encodeClaudeProjectDir and its tests only replace / and .). In that case the startup command still cds into the target cwd, but the copied transcript is placed in the mismatched projects/<new-encoding>/ bucket, so claude --resume can continue to report no conversation found. Please share one encoder/contract (or update all call sites/tests together) so the seed location matches the resume lookup location.

Useful? React with 👍 / 👎.

}

/// Config dirs to search for the session transcript, most specific first:
/// the launch snapshot's captured CLAUDE_CONFIG_DIR (re-applied via `env`
/// on resume, so it is the dir the resumed claude will actually read),
/// then this process's CLAUDE_CONFIG_DIR, then `~/.claude`.
static func defaultConfigDirCandidates(
launchEnvironment: [String: String]?,
processEnvironment: [String: String] = ProcessInfo.processInfo.environment,
homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
) -> [URL] {
var seenPaths = Set<String>()
var candidates: [URL] = []
func add(_ path: String?) {
guard let path, !path.trimmingCharacters(in: .whitespaces).isEmpty else { return }
let url = URL(fileURLWithPath: path)
if seenPaths.insert(url.standardizedFileURL.path).inserted {
candidates.append(url)
}
}
add(launchEnvironment?["CLAUDE_CONFIG_DIR"])
add(processEnvironment["CLAUDE_CONFIG_DIR"])
add(homeDirectory.appendingPathComponent(".claude").path)
return candidates
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

/// Copies `projects/<source>/<id>.jsonl` (and the optional `<id>/` sidecar
/// dir) into `projects/<encoded-target-cwd>/` inside the first candidate
/// config dir that has the transcript. No-op when the target project dir
/// already has it. A copy rather than a hardlink so concurrent resumes of
/// the same id from two cwds cannot interleave appends into one inode.
/// Returns true when the transcript is present in the target project dir
/// after the call. Best-effort: copy failures must never block the launch.
@discardableResult
static func seedIfNeeded(
sessionId: String,
targetWorkingDirectory: String,
configDirCandidates: [URL],
fileManager: FileManager = .default
) -> Bool {
guard isPlausibleSessionId(sessionId) else { return false }
let targetName = encodedProjectDirName(forWorkingDirectory: targetWorkingDirectory)
guard !targetName.isEmpty else { return false }
let transcriptName = "\(sessionId).jsonl"

for configDir in configDirCandidates {
let projects = configDir.appendingPathComponent("projects")
let targetDir = projects.appendingPathComponent(targetName)
let targetTranscript = targetDir.appendingPathComponent(transcriptName)

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 Badge Seed the configured Claude root, not a fallback root

When a snapshot carries CLAUDE_CONFIG_DIR, the resume command will launch Claude with that configured root, but this loop treats every candidate as both a possible source and the destination. If the configured root is empty/stale while the transcript is only found in a later fallback such as ~/.claude or the process env, seedIfNeeded copies into that fallback target and returns true, while the resumed claude --resume still reads the configured root and reports no conversation found. Please keep the active launch config root as the destination and use fallbacks only as sources, or only return success when the transcript is present in the launch root.

Useful? React with 👍 / 👎.

if fileManager.fileExists(atPath: targetTranscript.path) {
return true
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
guard let projectDirs = try? fileManager.contentsOfDirectory(
at: projects, includingPropertiesForKeys: nil) else {
continue
}
for projectDir in projectDirs where projectDir.lastPathComponent != targetName {
let sourceTranscript = projectDir.appendingPathComponent(transcriptName)
Comment on lines +87 to +94

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 Badge Choose the latest duplicate transcript when seeding

After this copy-based seeding runs once, the same Claude session id can exist in multiple projects/<cwd>/ directories; if the user continues the resumed conversation in the new cwd and later forks/restores it into a third cwd, this loop copies the first matching <session>.jsonl returned by directory enumeration rather than the most recently updated transcript. In that scenario the new pane can resume from a stale copy and miss the latest conversation turns, so the seeder should select the newest/source-authoritative transcript instead of returning on the first match.

Useful? React with 👍 / 👎.

guard isFile(at: sourceTranscript, fileManager: fileManager) else { continue }
do {
try fileManager.createDirectory(at: targetDir, withIntermediateDirectories: true)
try fileManager.copyItem(at: sourceTranscript, to: targetTranscript)
} catch {
continue
}
let sidecar = projectDir.appendingPathComponent(sessionId)
let sidecarTarget = targetDir.appendingPathComponent(sessionId)
if isDirectory(at: sidecar, fileManager: fileManager),
!fileManager.fileExists(atPath: sidecarTarget.path) {
try? fileManager.copyItem(at: sidecar, to: sidecarTarget)
}
return true
}
}
Comment on lines +87 to +113

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.

P1 Cross-configDir copy: transcript lands in the wrong config dir

seedIfNeeded iterates candidates, finds the source transcript in configDir[i], and copies it within that same dir. But the resumed Claude process reads from configDirCandidates[0] (the most-specific dir). When these two differ, the copy is placed where Claude will never look and the launch still hits "No conversation found."

Concrete failure: original session used the default ~/.claude (no CLAUDE_CONFIG_DIR in launchEnvironment), but the current cmux process has CLAUDE_CONFIG_DIR=/other in its environment. Candidates become ["/other", "~/.claude"]. The outer loop finds no transcript in /other, then finds the source in ~/.claude and copies it to ~/.claude/projects/<targetName>/. The resumed claude inherits the process environment, uses /other, and still fails.

The fix is to copy into configDirCandidates[0] (or the first writable candidate) regardless of which candidate the source was discovered in.

return false
Comment on lines +87 to +114

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 Synchronous O(N) project-dir scan on interactive path

contentsOfDirectory lists every entry under projects/, then isFile stat-checks each one, all synchronously inside seedIfNeeded. This is called from forkStartupInput and resumeStartupInput, which are invoked on the main-actor path in Workspace.forkAgentConversation (fork-to-tab, fork-to-split, fork-to-new-workspace) and restoreSessionSnapshot. For a user with hundreds of sessions the scan adds visible latency to every fork and restore. Consider moving the seeding call into an async or off-main helper so the I/O doesn't block the UI thread.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

}

/// Session ids are UUID-shaped (hex + dashes). Refusing anything else keeps
/// untrusted ids from path-escaping the projects dir.
private static func isPlausibleSessionId(_ sessionId: String) -> Bool {
!sessionId.isEmpty && sessionId.allSatisfy { character in
character == "-" || (character.isASCII && (character.isLetter || character.isNumber))
}
}

private static func isFile(at url: URL, fileManager: FileManager) -> Bool {
var isDirectory: ObjCBool = false
return fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
&& !isDirectory.boolValue
}

private static func isDirectory(at url: URL, fileManager: FileManager) -> Bool {
var isDirectory: ObjCBool = false
return fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
&& isDirectory.boolValue
}

/// realpath(3)-style resolution matching Node's `process.cwd()` (keeps the
/// `/private` prefix, unlike `URL.resolvingSymlinksInPath()` which strips
/// it). When the full path does not exist, resolves the deepest existing
/// ancestor and reattaches the remaining components.
private static func symlinkResolvedAbsolutePath(_ path: String) -> String {
let standardized = URL(fileURLWithPath: path).standardized.path
var current = standardized
var unresolvedComponents: [String] = []
while !current.isEmpty, current != "/" {
if let resolved = realpathString(current) {
return unresolvedComponents.reversed().reduce(resolved) { $0 + "/" + $1 }
}
let url = URL(fileURLWithPath: current)
unresolvedComponents.append(url.lastPathComponent)
current = url.deletingLastPathComponent().path
}
return standardized
}

private static func realpathString(_ path: String) -> String? {
guard let resolved = realpath(path, nil) else { return nil }
defer { free(resolved) }
return String(cString: resolved)
}
}
26 changes: 24 additions & 2 deletions Sources/RestorableAgentSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -710,13 +710,33 @@ struct SessionRestorableAgentSnapshot: Codable, Sendable {
)
}

/// Claude scopes `--resume <id>` lookups to `projects/<encoded-cwd>/`, so a
/// resume or fork launched in a different directory than the session's
/// origin needs the transcript seeded there first
/// (https://github.com/manaflow-ai/cmux/issues/5941). Runs at launch time,
/// right before the startup input is handed to the terminal.
private func seedClaudeTranscriptIfNeeded(fileManager: FileManager) {
guard kind == .claude,
let targetWorkingDirectory = workingDirectory ?? launchCommand?.workingDirectory else {
return
}
ClaudeSessionTranscriptSeeder.seedIfNeeded(
sessionId: sessionId,
targetWorkingDirectory: targetWorkingDirectory,
configDirCandidates: ClaudeSessionTranscriptSeeder.defaultConfigDirCandidates(
launchEnvironment: launchCommand?.environment),
fileManager: fileManager
)
}

func resumeStartupInput(
fileManager: FileManager = .default,
temporaryDirectory: URL = FileManager.default.temporaryDirectory,
allowLauncherScript: Bool = true,
allowOversizedInlineInput: Bool = false
) -> String? {
startupInput(
seedClaudeTranscriptIfNeeded(fileManager: fileManager)
return startupInput(
command: resumeCommand,
fileManager: fileManager,
temporaryDirectory: temporaryDirectory,
Expand All @@ -729,6 +749,7 @@ struct SessionRestorableAgentSnapshot: Codable, Sendable {
fileManager: FileManager = .default,
temporaryDirectory: URL = FileManager.default.temporaryDirectory
) -> String? {
seedClaudeTranscriptIfNeeded(fileManager: fileManager)
guard let command = resumeCommand,
let scriptURL = AgentResumeScriptStore.writeLauncherScript(
command: command,
Expand All @@ -753,7 +774,8 @@ struct SessionRestorableAgentSnapshot: Codable, Sendable {
temporaryDirectory: URL = FileManager.default.temporaryDirectory,
allowLauncherScript: Bool = true
) -> String? {
startupInput(
seedClaudeTranscriptIfNeeded(fileManager: fileManager)
return startupInput(
command: forkCommand,
fileManager: fileManager,
temporaryDirectory: temporaryDirectory,
Expand Down
8 changes: 8 additions & 0 deletions cmux.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@
F3000000A1B2C3D4E5F60718 /* CJKIMEInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3000001A1B2C3D4E5F60718 /* CJKIMEInputTests.swift */; };
D3571002A1B2C3D4E5F60718 /* CJKIMEMarkedSelectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3571003A1B2C3D4E5F60718 /* CJKIMEMarkedSelectionTests.swift */; };
C13519000000000000000007 /* ClaudeConfigDirectoryPathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C13519000000000000000008 /* ClaudeConfigDirectoryPathTests.swift */; };
C0DEF5941000000000000001 /* ClaudeSessionTranscriptSeeder.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF5941000000000000002 /* ClaudeSessionTranscriptSeeder.swift */; };
F5941000A1B2C3D4E5F60001 /* ClaudeSessionTranscriptSeederTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5941001A1B2C3D4E5F60001 /* ClaudeSessionTranscriptSeederTests.swift */; };
A9F200000000000000000015 /* ClaudeStreamJSONAccumulator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000015 /* ClaudeStreamJSONAccumulator.swift */; };
A5D4120DA1B2C3D4E5F60718 /* CLIAuthAliasTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D4120EA1B2C3D4E5F60718 /* CLIAuthAliasTests.swift */; };
C46790000000000000000001 /* CLIForwardingLaunchArgumentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C46790000000000000000002 /* CLIForwardingLaunchArgumentTests.swift */; };
Expand Down Expand Up @@ -949,6 +951,8 @@
F3000001A1B2C3D4E5F60718 /* CJKIMEInputTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CJKIMEInputTests.swift; sourceTree = "<group>"; };
D3571003A1B2C3D4E5F60718 /* CJKIMEMarkedSelectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CJKIMEMarkedSelectionTests.swift; sourceTree = "<group>"; };
C13519000000000000000008 /* ClaudeConfigDirectoryPathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeConfigDirectoryPathTests.swift; sourceTree = "<group>"; };
C0DEF5941000000000000002 /* ClaudeSessionTranscriptSeeder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeSessionTranscriptSeeder.swift; sourceTree = "<group>"; };
F5941001A1B2C3D4E5F60001 /* ClaudeSessionTranscriptSeederTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeSessionTranscriptSeederTests.swift; sourceTree = "<group>"; };
A9F100000000000000000015 /* ClaudeStreamJSONAccumulator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/ClaudeStreamJSONAccumulator.swift; sourceTree = "<group>"; };
A5D4120EA1B2C3D4E5F60718 /* CLIAuthAliasTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CLIAuthAliasTests.swift; sourceTree = "<group>"; };
C46790000000000000000002 /* CLIForwardingLaunchArgumentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CLIForwardingLaunchArgumentTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2158,6 +2162,7 @@
B35751000000000000000001 /* TmuxResumeParser.swift */,
A5001661 /* RestorableAgentSession.swift */,
C0DEF0C10000000000000002 /* AgentForkSupport.swift */,
C0DEF5941000000000000002 /* ClaudeSessionTranscriptSeeder.swift */,
C0DEF0C20000000000000002 /* SemanticVersion.swift */,
A5001642 /* RemoteInteractiveShellBootstrapBuilder.swift */,
A5001641 /* RemoteRelayZshBootstrap.swift */,
Expand Down Expand Up @@ -2276,6 +2281,7 @@
A9E040000000000000000001 /* CodexAppServerSessionTests.swift */,
D36A00020000000000000002 /* AgentHibernationTests.swift */,
F5410001A1B2C3D4E5F60718 /* RestorableAgentHookProviderResumeTests.swift */,
F5941001A1B2C3D4E5F60001 /* ClaudeSessionTranscriptSeederTests.swift */,
F5410005A1B2C3D4E5F60718 /* RestorableAgentHookProviderHermesTests.swift */,
F5410003A1B2C3D4E5F60718 /* RestorableAgentNonInteractiveTests.swift */,
F5410007A1B2C3D4E5F60718 /* RestorableAgentSessionIndexTests.swift */,
Expand Down Expand Up @@ -2909,6 +2915,7 @@
A5007422 /* BrowserWebAuthnSupport.swift in Sources */,
C0DE58990000000000000003 /* BrowserWebKitKeyDownDispatch.swift in Sources */,
A5001534 /* BrowserWindowPortal.swift in Sources */,
C0DEF5941000000000000001 /* ClaudeSessionTranscriptSeeder.swift in Sources */,
A9F200000000000000000015 /* ClaudeStreamJSONAccumulator.swift in Sources */,
C46790000000000000000003 /* CLIForwardingLaunchRouter.swift in Sources */,
C10D51700000000000000002 /* ClosedItemHistory.swift in Sources */,
Expand Down Expand Up @@ -3411,6 +3418,7 @@
F3000000A1B2C3D4E5F60718 /* CJKIMEInputTests.swift in Sources */,
D3571002A1B2C3D4E5F60718 /* CJKIMEMarkedSelectionTests.swift in Sources */,
C13519000000000000000007 /* ClaudeConfigDirectoryPathTests.swift in Sources */,
F5941000A1B2C3D4E5F60001 /* ClaudeSessionTranscriptSeederTests.swift in Sources */,
A5D4120DA1B2C3D4E5F60718 /* CLIAuthAliasTests.swift in Sources */,
C46790000000000000000001 /* CLIForwardingLaunchArgumentTests.swift in Sources */,
A5D41207A1B2C3D4E5F60718 /* CLIGenericHookPersistenceTests.swift in Sources */,
Expand Down
Loading
Loading