diff --git a/.github/workflows/test-depot.yml b/.github/workflows/test-depot.yml index dd7ecbb7c163..66c4a6a7180a 100644 --- a/.github/workflows/test-depot.yml +++ b/.github/workflows/test-depot.yml @@ -78,6 +78,11 @@ jobs: set -euo pipefail ./scripts/select-ci-xcode.sh + - name: Setup Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: "20" + - name: Setup Bun uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -142,6 +147,11 @@ jobs: UNIT_TEST_SUITES: ${{ inputs.unit_test_suites }} run: | set -euo pipefail + # Xcode launches the XCTest host with a sanitized environment. The + # noninteractive wrapper forwards TEST_RUNNER_* variables into that + # host, so preserve the action-provisioned Node path for tests that + # execute JavaScript helpers through /usr/bin/env. + export TEST_RUNNER_PATH="$PATH" SOURCE_PACKAGES_DIR="$PWD/.ci-source-packages" run_unit_suite() { scripts/ci/xcodebuild_noninteractive.py \ diff --git a/CLAUDE.md b/CLAUDE.md index 3154115ac1cd..6d35c8d734f0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -161,6 +161,7 @@ Detailed contributor rules live in `skills/`. Use the task-specific skill before - `cmux-testing`: regression policy, Swift Testing, test quality, test wiring, local vs CI validation. - `cmux-socket-policy`: socket command threading and focus preservation. - `cmux-shared-behavior`: shared action paths for multi-entrypoint behavior and optimistic updates. +- `cmux-project-files`: read, write, search, reference, and reorganize project-local Notes and Artifacts through the cmux CLI. - `cmux-ghostty`: Ghostty submodule and GhosttyKit workflow. - `cmux-release`: release, version bump, changelog, pretag guard, release assets. - Blacksmith Testbox (remote Linux builds for cmux-tui): warm your own box before any cmux-tui Rust or Zig diff --git a/CLI/ArtifactCLIArguments.swift b/CLI/ArtifactCLIArguments.swift new file mode 100644 index 000000000000..8400ae4765ca --- /dev/null +++ b/CLI/ArtifactCLIArguments.swift @@ -0,0 +1,5 @@ +struct ArtifactCLIArguments { + let subcommand: String + let operands: [String] + let projectPath: String? +} diff --git a/CLI/CMUXCLI+Artifacts.swift b/CLI/CMUXCLI+Artifacts.swift new file mode 100644 index 000000000000..cc191b821708 --- /dev/null +++ b/CLI/CMUXCLI+Artifacts.swift @@ -0,0 +1,342 @@ +import CmuxArtifacts +import Foundation + +extension CMUXCLI { + func runArtifactCommand( + commandArgs: [String], + jsonOutput: Bool, + processEnvironment: [String: String] + ) async throws { + let parsed = try artifactArguments(commandArgs) + let projectRoot = projectFilesProjectRoot(explicitPath: parsed.projectPath) + let repository = LocalArtifactRepository() + let terminalText = ArtifactTerminalTextSanitizer() + + do { + switch parsed.subcommand { + case "list": + guard parsed.operands.isEmpty else { + throw CLIError(message: artifactUsage(), exitCode: 2) + } + let snapshot = try await repository.snapshot(projectRoot: projectRoot) + let files = snapshot.nodes.flattenedArtifactNodes().filter { !$0.isDirectory } + if jsonOutput { + print(jsonString([ + "project_root": projectRoot.path, + "filesystem_root": snapshot.filesystemRoot.path, + "artifacts": files.map(artifactPayload), + ])) + } else if files.isEmpty { + print(String( + localized: "cli.artifact.output.empty", + defaultValue: "No artifacts found." + )) + } else { + files.forEach { print(terminalText.sanitize($0.relativePath)) } + } + + case "path": + let name = try artifactRequiredOperand(parsed.operands, subcommand: "path") + let node = try await repository.resolve(projectRoot: projectRoot, name: name) + if jsonOutput { + print(jsonString(artifactPayload(node))) + } else { + print(terminalText.sanitize(node.absolutePath)) + } + + case "open": + let name = try artifactRequiredOperand(parsed.operands, subcommand: "open") + let node = try await repository.resolve(projectRoot: projectRoot, name: name) + try openArtifact(node, projectRoot: projectRoot) + if jsonOutput { print(jsonString(artifactPayload(node))) } + + case "add": + let rawPath = try artifactRequiredOperand(parsed.operands, subcommand: "add") + let sourceURL = projectFilesURL(rawPath) + let context = try projectFilesCaptureContext( + projectRoot: projectRoot, + environment: processEnvironment + ) + let outcome = try await ArtifactCaptureService(store: repository).add( + sourceURL: sourceURL, + context: context + ) + guard let record = outcome.record else { + guard case .skipped(let reason) = outcome else { + throw CLIError(message: String( + localized: "cli.artifact.error.addRejected", + defaultValue: "The artifact was not added." + )) + } + throw CLIError(message: artifactSkipMessage(reason), exitCode: 2) + } + let absolutePath = ArtifactStorePaths(projectRoot: projectRoot).filesystemRoot + .appendingPathComponent(record.relativePath, isDirectory: false).path + if jsonOutput { + print(jsonString([ + "path": absolutePath, + "relative_path": record.relativePath, + "reference": ".cmux/\(record.relativePath)", + "digest": record.digest, + "result": artifactOutcomeName(outcome), + ])) + } else { + print(terminalText.sanitize(absolutePath)) + } + + case "search": + let query = try artifactRequiredOperand(parsed.operands, subcommand: "search") + let results = try await repository.search(projectRoot: projectRoot, query: query) + if jsonOutput { + print(jsonString([ + "query": query, + "results": results.map { result in + var payload = artifactPayload(result.node) + payload["matched_content"] = result.matchedContent + payload["snippet"] = result.snippet ?? NSNull() + return payload + }, + ])) + } else if results.isEmpty { + print(String( + localized: "cli.artifact.output.noMatches", + defaultValue: "No artifacts matched." + )) + } else { + for result in results { + if let snippet = result.snippet { + print(terminalText.sanitize("\(result.node.relativePath): \(snippet)")) + } else { + print(terminalText.sanitize(result.node.relativePath)) + } + } + } + + default: + throw CLIError(message: artifactUsage(), exitCode: 2) + } + } catch let error as ArtifactStoreError { + throw CLIError( + message: terminalText.sanitize(artifactErrorMessage(error)), + exitCode: 2 + ) + } catch let error as CLIError { + throw CLIError( + message: terminalText.sanitize(error.message), + exitCode: error.exitCode, + v2Code: error.v2Code, + vmBackendCode: error.vmBackendCode, + socketFailureKind: error.socketFailureKind + ) + } catch { + throw CLIError( + message: terminalText.sanitize(String(describing: error)), + exitCode: 2 + ) + } + } + + func artifactUsage() -> String { + String(localized: "cli.artifact.usage", defaultValue: """ + Usage: cmux artifact list [--project ] + cmux artifact path [--project ] + cmux artifact open [--project ] + cmux artifact add [--project ] + cmux artifact search [--project ] + + Browse and add ordinary files under agent-session folders in /.cmux. + Commands work without a running cmux app or socket. The project defaults + to the nearest ancestor containing .cmux or .git. + """) + } + + private func artifactArguments(_ arguments: [String]) throws -> ArtifactCLIArguments { + var projectPath: String? + var remaining: [String] = [] + var index = 0 + var pastTerminator = false + while index < arguments.count { + let argument = arguments[index] + if pastTerminator { + remaining.append(argument) + index += 1 + continue + } + if argument == "--" { + pastTerminator = true + index += 1 + continue + } + if argument == "--project" { + guard index + 1 < arguments.count else { + throw CLIError(message: String( + localized: "cli.artifact.error.projectValue", + defaultValue: "artifact: --project requires a path" + ), exitCode: 2) + } + projectPath = arguments[index + 1] + index += 2 + } else if argument.hasPrefix("--project=") { + projectPath = String(argument.dropFirst("--project=".count)) + index += 1 + } else if argument.hasPrefix("-") { + throw CLIError(message: artifactUsage(), exitCode: 2) + } else { + remaining.append(argument) + index += 1 + } + } + if let projectPath, + projectPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + throw CLIError(message: String( + localized: "cli.artifact.error.projectValue", + defaultValue: "artifact: --project requires a path" + ), exitCode: 2) + } + return ArtifactCLIArguments( + subcommand: remaining.first?.lowercased() ?? "list", + operands: Array(remaining.dropFirst()), + projectPath: projectPath + ) + } + + private func artifactRequiredOperand(_ operands: [String], subcommand: String) throws -> String { + let value = operands.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines) + guard !value.isEmpty else { + throw CLIError(message: String( + format: String( + localized: "cli.artifact.error.missingOperand", + defaultValue: "artifact %@ requires a value" + ), + subcommand + ), exitCode: 2) + } + return value + } + + private func artifactPayload(_ node: ArtifactNode) -> [String: Any] { + [ + "name": node.name, + "relative_path": node.relativePath, + "path": node.absolutePath, + "reference": ".cmux/\(node.relativePath)", + "kind": node.fileKind?.rawValue ?? "other", + "size": node.size ?? 0, + ] + } + + private func artifactOutcomeName(_ outcome: ArtifactImportOutcome) -> String { + switch outcome { + case .copied: return "copied" + case .deduplicated: return "deduplicated" + case .alreadyStored: return "already_stored" + case .skipped: return "skipped" + } + } + + private func artifactSkipMessage(_ reason: ArtifactSkipReason) -> String { + switch reason { + case .automaticCaptureDisabled: + return String( + localized: "cli.artifact.error.captureDisabled", + defaultValue: "Automatic artifact capture is disabled for this project." + ) + case .provenanceNotEligible: + return String( + localized: "cli.artifact.error.provenanceRejected", + defaultValue: "The file does not meet this project's artifact capture rules." + ) + case .notARegularFile: + return String( + localized: "cli.artifact.error.rejectedNotFile", + defaultValue: "The artifact path is not a regular file." + ) + case .pathOutsideStore: + return String( + localized: "cli.artifact.error.rejectedOutsideStore", + defaultValue: "The artifact path escaped the local store." + ) + case .corruptProvenance: + return String( + localized: "cli.artifact.error.rejectedCorruptProvenance", + defaultValue: "The artifact store's provenance metadata is corrupt." + ) + case .gitPrivacyUnavailable: + return String( + localized: "cli.artifact.error.gitPrivacyUnavailable", + defaultValue: "Automatic capture paused because Git does not prove the artifact store is ignored and untracked." + ) + case .storeBusy: + return String( + localized: "cli.artifact.error.storeBusy", + defaultValue: "The artifact store is busy. Try again." + ) + case .unsupportedExtension: + return String( + localized: "cli.artifact.error.rejectedExtension", + defaultValue: "The file extension is not allowed by this project's artifact settings." + ) + case .exceedsSizeLimit: + return String( + localized: "cli.artifact.error.rejectedSize", + defaultValue: "The file exceeds this project's artifact size limit." + ) + case .candidateLimitReached: + return String( + localized: "cli.artifact.error.candidateLimit", + defaultValue: "The artifact capture batch reached its file limit." + ) + case .scanIncomplete: + return String( + localized: "cli.artifact.error.scanIncompleteCandidate", + defaultValue: "The artifact store is too large to scan safely right now." + ) + } + } + + private func openArtifact(_ node: ArtifactNode, projectRoot: URL) throws { + try openProjectFile( + path: node.absolutePath, + allowedRoot: ArtifactStorePaths(projectRoot: projectRoot).filesystemRoot, + failureMessage: String( + format: String( + localized: "cli.artifact.error.openFailed", + defaultValue: "Could not open artifact at %@" + ), + node.absolutePath + ) + ) + } + + private func artifactErrorMessage(_ error: ArtifactStoreError) -> String { + switch error { + case .sourceNotRegularFile(let path): + return String(format: String(localized: "cli.artifact.error.notFile", defaultValue: "Not a regular file: %@"), path) + case .unsupportedExtension(let pathExtension): + return String(format: String(localized: "cli.artifact.error.unsupported", defaultValue: "Unsupported artifact extension: %@"), pathExtension) + case .fileTooLarge(let actual, let limit): + return String(format: String(localized: "cli.artifact.error.tooLarge", defaultValue: "Artifact is too large (%lld bytes; limit %lld)."), actual, limit) + case .batchByteLimitReached(let actual, let limit): + return String(format: String(localized: "cli.artifact.error.batchTooLarge", defaultValue: "Artifact batch is too large (%lld bytes; limit %lld)."), actual, limit) + case .fileCountLimitReached: + return String( + localized: "cli.artifact.error.candidateLimit", + defaultValue: "The artifact capture batch reached its file limit." + ) + case .artifactNotFound(let name): + return String(format: String(localized: "cli.artifact.error.notFound", defaultValue: "Artifact not found: %@"), name) + case .ambiguousArtifactName(let name, let matches): + return String(format: String(localized: "cli.artifact.error.ambiguous", defaultValue: "Artifact name '%@' is ambiguous: %@"), name, matches.joined(separator: ", ")) + case .scanIncomplete(let path): + return String(format: String(localized: "cli.artifact.error.scanIncomplete", defaultValue: "Artifact scan reached its safety limit: %@"), path) + case .pathOutsideStore(let path): + return String(format: String(localized: "cli.artifact.error.outsideStore", defaultValue: "Artifact path escaped the store: %@"), path) + case .corruptProvenance(let path): + return String(format: String(localized: "cli.artifact.error.corruptProvenance", defaultValue: "Artifact provenance metadata is corrupt: %@"), path) + case .gitPrivacyUnavailable(let path): + return String(format: String(localized: "cli.artifact.error.gitPrivacyPath", defaultValue: "Git privacy could not be verified for artifact store: %@"), path) + case .storeBusy(let path): + return String(format: String(localized: "cli.artifact.error.storeBusyPath", defaultValue: "Artifact store is busy: %@"), path) + } + } +} diff --git a/CLI/CMUXCLI+CommandSuggestions.swift b/CLI/CMUXCLI+CommandSuggestions.swift index 88dabf51b529..c6f85391cfd8 100644 --- a/CLI/CMUXCLI+CommandSuggestions.swift +++ b/CLI/CMUXCLI+CommandSuggestions.swift @@ -56,6 +56,7 @@ extension CMUXCLI { "__sidebar_footer_icon_balance", "__tmux-compat", "agent-hibernation", + "artifact", "ai-accounts", "automation", "auth", @@ -135,6 +136,7 @@ extension CMUXCLI { "mark-notification-read", "memory", "mobile", + "note", "mosh", "mosh-tmux", "move-surface", diff --git a/CLI/CMUXCLI+Notes.swift b/CLI/CMUXCLI+Notes.swift new file mode 100644 index 000000000000..3f51ead4a269 --- /dev/null +++ b/CLI/CMUXCLI+Notes.swift @@ -0,0 +1,323 @@ +import CmuxArtifacts +import Foundation + +extension CMUXCLI { + func runNoteCommand( + commandArgs: [String], + jsonOutput: Bool, + processEnvironment: [String: String] + ) async throws { + let parsed = try noteArguments(commandArgs) + let projectRoot = projectFilesProjectRoot(explicitPath: parsed.projectPath) + let repository = LocalArtifactRepository() + let terminalText = ArtifactTerminalTextSanitizer() + + do { + switch parsed.subcommand { + case "list": + guard parsed.operands.isEmpty else { throw noteUsageError() } + let notes = try await repository.listNotes(projectRoot: projectRoot) + if jsonOutput { + print(jsonString([ + "project_root": projectRoot.path, + "filesystem_root": ArtifactStorePaths(projectRoot: projectRoot).filesystemRoot.path, + "notes": notes.map(notePayload), + ])) + } else if notes.isEmpty { + print(String(localized: "cli.note.output.empty", defaultValue: "No notes found.")) + } else { + notes.forEach { print(terminalText.sanitize($0.relativePath)) } + } + + case "path": + let name = try noteRequiredOperand(parsed.operands, subcommand: "path") + let note = try await repository.resolveNote(projectRoot: projectRoot, name: name) + if jsonOutput { + print(jsonString(notePayload(note))) + } else { + print(terminalText.sanitize(note.absolutePath)) + } + + case "read": + let name = try noteRequiredOperand(parsed.operands, subcommand: "read") + let note = try await repository.resolveNote(projectRoot: projectRoot, name: name) + let text = try await repository.readNote(projectRoot: projectRoot, name: note.relativePath) + if jsonOutput { + var payload = notePayload(note) + payload["text"] = text + print(jsonString(payload)) + } else { + cliWriteStdout( + Data(terminalText.sanitizeTextContent(text).utf8) + ) + } + + case "write", "append": + let name = try noteRequiredOperand(parsed.operands, subcommand: parsed.subcommand) + let text = try noteInput(parsed) + let note = try await repository.writeNote( + name: name, + text: text, + mode: parsed.subcommand == "append" ? .append : .replace, + context: try projectFilesCaptureContext( + projectRoot: projectRoot, + environment: processEnvironment + ) + ) + if jsonOutput { + print(jsonString(notePayload(note))) + } else { + print(terminalText.sanitize(note.absolutePath)) + } + + case "search": + let query = try noteRequiredOperand(parsed.operands, subcommand: "search") + let results = try await repository.searchNotes(projectRoot: projectRoot, query: query) + if jsonOutput { + print(jsonString([ + "query": query, + "results": results.map { result in + var payload = notePayload(result.note) + payload["matched_content"] = result.matchedContent + payload["snippet"] = result.snippet ?? NSNull() + return payload + }, + ])) + } else if results.isEmpty { + print(String(localized: "cli.note.output.noMatches", defaultValue: "No notes matched.")) + } else { + results.forEach { result in + let line = result.snippet.map { "\(result.note.relativePath): \($0)" } + ?? result.note.relativePath + print(terminalText.sanitize(line)) + } + } + + case "open": + let name = try noteRequiredOperand(parsed.operands, subcommand: "open") + let note = try await repository.resolveNote(projectRoot: projectRoot, name: name) + try openProjectFile( + path: note.absolutePath, + allowedRoot: ArtifactStorePaths(projectRoot: projectRoot).filesystemRoot, + failureMessage: String( + format: String( + localized: "cli.note.error.openFailed", + defaultValue: "Could not open note at %@" + ), + note.absolutePath + ) + ) + if jsonOutput { print(jsonString(notePayload(note))) } + + case "rm", "delete": + guard parsed.confirmsDeletion else { + throw CLIError( + message: String( + localized: "cli.note.error.confirmDelete", + defaultValue: "note rm permanently deletes a note; pass --yes to confirm." + ), + exitCode: 2 + ) + } + let name = try noteRequiredOperand(parsed.operands, subcommand: "rm") + let note = try await repository.deleteNote(projectRoot: projectRoot, name: name) + if jsonOutput { + print(jsonString(notePayload(note))) + } else { + print(terminalText.sanitize(String( + format: String( + localized: "cli.note.output.deleted", + defaultValue: "Deleted %@" + ), + note.reference + ))) + } + + default: + throw noteUsageError() + } + } catch let error as CmuxNoteStoreError { + throw CLIError(message: terminalText.sanitize(noteErrorMessage(error)), exitCode: 2) + } catch let error as ArtifactStoreError { + throw CLIError(message: terminalText.sanitize(noteArtifactErrorMessage(error)), exitCode: 2) + } catch let error as CLIError { + throw CLIError( + message: terminalText.sanitize(error.message), + exitCode: error.exitCode, + v2Code: error.v2Code, + vmBackendCode: error.vmBackendCode, + socketFailureKind: error.socketFailureKind + ) + } catch { + throw CLIError( + message: terminalText.sanitize(String(describing: error)), + exitCode: 2 + ) + } + } + + func noteUsage() -> String { + String(localized: "cli.note.usage", defaultValue: """ + Usage: cmux note list [--project ] + cmux note path [--project ] + cmux note read [--project ] + cmux note write (--text |--stdin) [--project ] + cmux note append (--text |--stdin) [--project ] + cmux note search [--project ] + cmux note open [--project ] + cmux note rm [--project ] [--yes|-y] + + Read and write ordinary Markdown files under the current agent session's + /.cmux//notes directory. Commands work without a + running cmux app or socket. Existing notes are rediscovered after moves. + """) + } + + private func noteArguments(_ arguments: [String]) throws -> NoteCLIArguments { + var projectPath: String? + var text: String? + var readsStandardInput = false + var confirmsDeletion = false + var remaining: [String] = [] + var index = 0 + var pastTerminator = false + while index < arguments.count { + let argument = arguments[index] + if pastTerminator { + remaining.append(argument) + index += 1 + } else if argument == "--" { + pastTerminator = true + index += 1 + } else if argument == "--project" || argument == "--text" { + guard index + 1 < arguments.count else { throw noteUsageError() } + if argument == "--project" { projectPath = arguments[index + 1] } + else { text = arguments[index + 1] } + index += 2 + } else if argument.hasPrefix("--project=") { + projectPath = String(argument.dropFirst("--project=".count)) + index += 1 + } else if argument.hasPrefix("--text=") { + text = String(argument.dropFirst("--text=".count)) + index += 1 + } else if argument == "--stdin" { + readsStandardInput = true + index += 1 + } else if argument == "--yes" || argument == "-y" { + confirmsDeletion = true + index += 1 + } else if argument.hasPrefix("-") { + throw noteUsageError() + } else { + remaining.append(argument) + index += 1 + } + } + if let projectPath, + projectPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + throw CLIError(message: String( + localized: "cli.note.error.projectValue", + defaultValue: "note: --project requires a path" + ), exitCode: 2) + } + return NoteCLIArguments( + subcommand: remaining.first?.lowercased() ?? "list", + operands: Array(remaining.dropFirst()), + projectPath: projectPath, + text: text, + readsStandardInput: readsStandardInput, + confirmsDeletion: confirmsDeletion + ) + } + + private func noteInput(_ arguments: NoteCLIArguments) throws -> String { + let hasInlineText = arguments.text != nil + guard hasInlineText != arguments.readsStandardInput else { + throw CLIError(message: String( + localized: "cli.note.error.input", + defaultValue: "note write and append require exactly one of --text or --stdin" + ), exitCode: 2) + } + if let text = arguments.text { return text } + let maximumBytes = 4 * 1024 * 1024 + var data = Data() + while data.count <= maximumBytes { + let remaining = maximumBytes + 1 - data.count + guard let chunk = try FileHandle.standardInput.read( + upToCount: min(64 * 1024, remaining) + ), !chunk.isEmpty else { break } + data.append(chunk) + } + guard data.count <= maximumBytes else { + throw CLIError(message: String( + localized: "cli.note.error.inputTooLarge", + defaultValue: "Note input exceeds the 4 MiB limit." + ), exitCode: 2) + } + guard let text = String(data: data, encoding: .utf8) else { + throw CLIError(message: String( + localized: "cli.note.error.inputUTF8", + defaultValue: "Note input must be valid UTF-8." + ), exitCode: 2) + } + return text + } + + private func noteRequiredOperand(_ operands: [String], subcommand: String) throws -> String { + let value = operands.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines) + guard !value.isEmpty else { + throw CLIError(message: String( + format: String( + localized: "cli.note.error.missingOperand", + defaultValue: "note %@ requires a value" + ), + subcommand + ), exitCode: 2) + } + return value + } + + private func notePayload(_ note: CmuxProjectNote) -> [String: Any] { + [ + "name": note.name, + "relative_path": note.relativePath, + "path": note.absolutePath, + "reference": note.reference, + "size": note.size ?? 0, + ] + } + + private func noteUsageError() -> CLIError { + CLIError(message: noteUsage(), exitCode: 2) + } + + private func noteErrorMessage(_ error: CmuxNoteStoreError) -> String { + switch error { + case .invalidName(let name): + return String(format: String(localized: "cli.note.error.invalidName", defaultValue: "Invalid note name: %@"), name) + case .noteNotFound(let name): + return String(format: String(localized: "cli.note.error.notFound", defaultValue: "Note not found: %@"), name) + case .ambiguousNoteName(let name, let matches): + return String(format: String(localized: "cli.note.error.ambiguous", defaultValue: "Note name '%@' is ambiguous: %@"), name, matches.joined(separator: ", ")) + case .invalidUTF8(let path): + return String(format: String(localized: "cli.note.error.invalidUTF8", defaultValue: "Note is not valid UTF-8: %@"), path) + case .noteTooLarge(let actual, let limit): + return String(format: String(localized: "cli.note.error.tooLarge", defaultValue: "Note is too large (%lld bytes; limit %lld)."), actual, limit) + case .pathOutsideStore(let path): + return String(format: String(localized: "cli.note.error.outsideStore", defaultValue: "Note path escaped the store: %@"), path) + } + } + + private func noteArtifactErrorMessage(_ error: ArtifactStoreError) -> String { + switch error { + case .storeBusy(let path): + return String(format: String(localized: "cli.note.error.storeBusy", defaultValue: "Notes store is busy: %@"), path) + case .scanIncomplete(let path): + return String(format: String(localized: "cli.note.error.scanIncomplete", defaultValue: "Notes scan reached its safety limit: %@"), path) + case .pathOutsideStore(let path): + return String(format: String(localized: "cli.note.error.outsideStore", defaultValue: "Note path escaped the store: %@"), path) + default: + return String(localized: "cli.note.error.store", defaultValue: "The Notes filesystem could not be updated.") + } + } +} diff --git a/CLI/CMUXCLI+ProjectFiles.swift b/CLI/CMUXCLI+ProjectFiles.swift new file mode 100644 index 000000000000..0c07d1a9ee89 --- /dev/null +++ b/CLI/CMUXCLI+ProjectFiles.swift @@ -0,0 +1,347 @@ +import CmuxArtifacts +import Darwin +import Foundation + +extension CMUXCLI { + func projectFilesProjectRoot(explicitPath: String?) -> URL { + let start = explicitPath.map(projectFilesURL) + ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true) + return ArtifactProjectLocator().projectRoot(startingAt: start, fileManager: .default) + } + + func projectFilesURL(_ rawPath: String) -> URL { + let expanded = NSString(string: rawPath).expandingTildeInPath + if expanded.hasPrefix("/") { + return URL(fileURLWithPath: expanded).standardizedFileURL + } + return URL( + fileURLWithPath: expanded, + relativeTo: URL( + fileURLWithPath: FileManager.default.currentDirectoryPath, + isDirectory: true + ) + ).standardizedFileURL + } + + func projectFilesCaptureContext( + projectRoot: URL, + environment: [String: String] + ) throws -> ArtifactCaptureContext { + let agent = try projectFilesAgentIdentity(environment: environment) + return ArtifactCaptureContext( + projectRoot: projectRoot, + workspaceID: environment["CMUX_WORKSPACE_ID"], + workspaceTitle: environment["CMUX_WORKSPACE_TITLE"], + sessionID: agent.sessionID, + agentName: agent.name + ) + } + + private func projectFilesAgentIdentity( + environment: [String: String] + ) throws -> (sessionID: String?, name: String?) { + let launchName = canonicalProjectFilesAgentName( + normalizedProjectFilesEnvironmentValue(environment["CMUX_AGENT_LAUNCH_KIND"]) + ) + let sessionByAgent: [(name: String, keys: [String])] = [ + ("codex", ["CODEX_THREAD_ID", "CODEX_SESSION_ID", "CMUX_CODEX_SESSION_ID"]), + ("claude", ["CLAUDE_CODE_SESSION_ID", "CMUX_CLAUDE_SESSION_ID"]), + ("opencode", ["OPENCODE_SESSION_ID"]), + ] + var nativeIdentities: [(sessionID: String, name: String)] = [] + for candidate in sessionByAgent { + let sessionIDs = candidate.keys.compactMap { + normalizedProjectFilesEnvironmentValue(environment[$0]) + } + let uniqueSessionIDs = Set(sessionIDs) + guard uniqueSessionIDs.count <= 1 else { + throw ambiguousProjectFilesAgentIdentityError() + } + if let sessionID = sessionIDs.first { + nativeIdentities.append((sessionID: sessionID, name: candidate.name)) + } + } + if let genericSessionID = normalizedProjectFilesEnvironmentValue( + environment["CMUX_AGENT_SESSION_ID"] + ) { + let genericName = canonicalProjectFilesAgentName( + normalizedProjectFilesEnvironmentValue(environment["CMUX_AGENT_NAME"]) + ) ?? launchName + // `CMUX_AGENT_*` is inherited by nested processes and can still + // describe the parent agent. A provider-native identity is the + // authoritative child identity; never reject it because the + // inherited generic fallback differs. Use the generic pair only + // when no native provider identity was supplied. + if nativeIdentities.isEmpty { + nativeIdentities.append(( + sessionID: genericSessionID, + name: genericName ?? "agent" + )) + } + } + guard nativeIdentities.count <= 1 else { + throw ambiguousProjectFilesAgentIdentityError() + } + if let nativeIdentity = nativeIdentities.first { + if let launchName, + launchName != nativeIdentity.name { + throw ambiguousProjectFilesAgentIdentityError() + } + return nativeIdentity + } + throw missingProjectFilesAgentIdentityError() + } + + private func normalizedProjectFilesEnvironmentValue(_ value: String?) -> String? { + guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { return nil } + return value + } + + private func canonicalProjectFilesAgentName(_ value: String?) -> String? { + guard let value else { return nil } + let normalized = value.lowercased() + return CmuxTaskManagerCodingAgentDefinition.builtIns.first { + $0.launchKinds.contains(normalized) + }?.id ?? normalized + } + + private func ambiguousProjectFilesAgentIdentityError() -> CLIError { + CLIError( + message: String( + localized: "cli.projectFiles.error.ambiguousAgentIdentity", + defaultValue: "Multiple agent session identities are present; refusing to assign project files to an inherited parent session." + ), + exitCode: 2 + ) + } + + private func missingProjectFilesAgentIdentityError() -> CLIError { + CLIError( + message: String( + localized: "cli.projectFiles.error.missingAgentIdentity", + defaultValue: "A stable agent session identity is required before writing project files." + ), + exitCode: 2 + ) + } + + func openProjectFile( + path: String, + allowedRoot: URL? = nil, + failureMessage: String + ) throws { + if let allowedRoot { + try openConfinedProjectFile(path: path, allowedRoot: allowedRoot, failureMessage: failureMessage) + return + } + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/open") + process.arguments = [path] + process.environment = projectFilesLaunchServicesEnvironment() + try process.run() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CLIError( + message: ArtifactTerminalTextSanitizer().sanitize(failureMessage) + ) + } + } + + private func openConfinedProjectFile( + path: String, + allowedRoot: URL, + failureMessage: String + ) throws { + let rootDescriptor = Darwin.open( + allowedRoot.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard rootDescriptor >= 0, + let openedRootPath = openedPath(for: rootDescriptor) else { + if rootDescriptor >= 0 { _ = Darwin.close(rootDescriptor) } + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + defer { _ = Darwin.close(rootDescriptor) } + let descriptor = Darwin.open( + path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + defer { _ = Darwin.close(descriptor) } + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + let openedPath = openedPath(for: descriptor), + isPath(openedPath, insideCanonicalRoot: openedRootPath.path) else { + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + guard status.st_size >= 0, status.st_size <= 64 * 1024 * 1024 else { + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + let duplicate = fcntl(descriptor, F_DUPFD_CLOEXEC, 3) + guard duplicate >= 0, + Darwin.lseek(duplicate, 0, SEEK_SET) >= 0 else { + if duplicate >= 0 { _ = Darwin.close(duplicate) } + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + let data: Data + if status.st_size == 0 { + data = Data() + } else { + let handle = FileHandle(fileDescriptor: duplicate, closeOnDealloc: false) + guard let readData = try? handle.read(upToCount: Int(status.st_size) + 1), + readData.count <= 64 * 1024 * 1024 else { + _ = Darwin.close(duplicate) + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + data = readData + } + _ = Darwin.close(duplicate) + let systemTemporaryDirectory = FileManager.default.temporaryDirectory + let temporaryDirectory = systemTemporaryDirectory + .appendingPathComponent("cmux-project-files", isDirectory: true) + let directoryDescriptor: Int32 + do { + directoryDescriptor = try openPrivateProjectFilesDirectory(temporaryDirectory) + } catch { + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + defer { _ = Darwin.close(directoryDescriptor) } + // Keep both new copies and legacy root-level copies bounded. The + // dedicated directory prevents ordinary /tmp entries from being + // materialized or competing with editor handoffs. + guard cleanupTemporaryProjectFiles( + in: temporaryDirectory, + reservingBytes: Int64(data.count), + reservingFileCount: 1 + ) else { + throw CLIError( + message: String( + localized: "cli.projectFiles.error.tooManyOpenCopies", + defaultValue: "Too many project files are already open; close one and try again." + ), + exitCode: 2 + ) + } + cleanupTemporaryProjectFiles(in: systemTemporaryDirectory) + let temporaryName = "cmux-project-file-\(UUID().uuidString)" + + (openedPath.pathExtension.isEmpty ? "" : ".\(openedPath.pathExtension)") + let temporaryURL = temporaryDirectory.appendingPathComponent(temporaryName) + let outputDescriptor = temporaryName.withCString { + Darwin.openat( + directoryDescriptor, + $0, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + guard outputDescriptor >= 0 else { + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + do { + let output = FileHandle(fileDescriptor: outputDescriptor, closeOnDealloc: false) + try output.write(contentsOf: data) + try output.close() + } catch { + _ = Darwin.close(outputDescriptor) + _ = Darwin.unlink(temporaryURL.path) + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/open") + process.arguments = [temporaryURL.path] + process.environment = projectFilesLaunchServicesEnvironment() + do { + try process.run() + process.waitUntilExit() + } catch { + try? FileManager.default.removeItem(at: temporaryURL) + throw error + } + guard process.terminationStatus == 0 else { + try? FileManager.default.removeItem(at: temporaryURL) + throw CLIError(message: ArtifactTerminalTextSanitizer().sanitize(failureMessage)) + } + cleanupTemporaryProjectFiles(in: temporaryDirectory) + cleanupTemporaryProjectFiles(in: systemTemporaryDirectory) + } + + private func openPrivateProjectFilesDirectory(_ directory: URL) throws -> Int32 { + if mkdir(directory.path, S_IRWXU) != 0, errno != EEXIST { + throw CocoaError(.fileWriteUnknown) + } + let descriptor = Darwin.open( + directory.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw CocoaError(.fileWriteNoPermission) + } + var status = stat() + guard lstat(directory.path, &status) == 0, + (status.st_mode & S_IFMT) == S_IFDIR, + status.st_uid == geteuid(), + fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFDIR, + status.st_uid == geteuid(), + fchmod(descriptor, S_IRWXU) == 0 else { + _ = Darwin.close(descriptor) + throw CocoaError(.fileWriteNoPermission) + } + return descriptor + } + + private func projectFilesLaunchServicesEnvironment() -> [String: String] { + var environment = ProcessInfo.processInfo.environment + let scrubbedKeys = [ + "CMUX_ALLOW_SOCKET_OVERRIDE", + "CMUX_SOCKET", + "CMUX_SOCKET_ENABLE", + "CMUX_SOCKET_MODE", + "CMUX_SOCKET_PASSWORD", + "CMUX_SOCKET_PATH", + "CMUX_PANEL_ID", + "CMUX_SURFACE_ID", + "CMUX_TAB_ID", + "CMUX_WORKSPACE_ID", + ] + for key in scrubbedKeys { + environment.removeValue(forKey: key) + } + return environment + } + + @discardableResult + func cleanupTemporaryProjectFiles( + in directory: URL, + reservingBytes: Int64 = 0, + reservingFileCount: Int = 0 + ) -> Bool { + ProjectFileTemporaryCopyCleaner().cleanup( + in: directory, + reservingBytes: reservingBytes, + reservingFileCount: reservingFileCount + ) + } + + private func openedPath(for descriptor: Int32) -> URL? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + return URL(fileURLWithPath: String( + decoding: buffer.prefix { $0 != 0 }, + as: UTF8.self + )).resolvingSymlinksInPath().standardizedFileURL + } + + private func isPath(_ path: URL, insideCanonicalRoot rootPath: String) -> Bool { + let path = path.path + return path == rootPath || path.hasPrefix(rootPath + "/") + } +} diff --git a/CLI/CMUXCLI+ThemeSupport.swift b/CLI/CMUXCLI+ThemeSupport.swift index eaffdb53ce52..df0c2f067f6f 100644 --- a/CLI/CMUXCLI+ThemeSupport.swift +++ b/CLI/CMUXCLI+ThemeSupport.swift @@ -432,7 +432,7 @@ extension CMUXCLI { func isRightSidebarCLIMode(_ value: String) -> Bool { switch value.lowercased() { - case "files", "find", "vault", "sessions", "feed", "dock", "cloud", "machines", "vms", "custom", "custom-sidebar": + case "files", "find", "vault", "sessions", "artifacts", "feed", "dock", "cloud", "machines", "vms", "custom", "custom-sidebar": return true default: return false @@ -441,7 +441,7 @@ extension CMUXCLI { func normalizedRightSidebarCLIArgument(_ value: String) -> String { switch value.lowercased() { - case "files", "find", "vault", "sessions", "feed", "dock", "machines", "custom", "custom-sidebar": + case "files", "find", "vault", "sessions", "artifacts", "feed", "dock", "machines", "custom", "custom-sidebar": return value.lowercased() case "cloud", "vms": return "machines" diff --git a/CLI/NoteCLIArguments.swift b/CLI/NoteCLIArguments.swift new file mode 100644 index 000000000000..c18ce7dda45e --- /dev/null +++ b/CLI/NoteCLIArguments.swift @@ -0,0 +1,8 @@ +struct NoteCLIArguments { + let subcommand: String + let operands: [String] + let projectPath: String? + let text: String? + let readsStandardInput: Bool + let confirmsDeletion: Bool +} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 4cc6f94e7a43..20f85802c434 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -5110,6 +5110,8 @@ struct CMUXCLI { if command == "docs" { try runDocsCommand(commandArgs: commandArgs, jsonOutput: jsonOutput); return } if command == "welcome" { printWelcome(); return } if command == "sessions" || command == "session-debug" { try runSessionsCommand(commandArgs: command == "session-debug" ? ["debug"] + commandArgs : commandArgs, jsonOutput: jsonOutput, processEnv: processEnv); return } + if command == "artifact" { try await runArtifactCommand(commandArgs: commandArgs, jsonOutput: jsonOutput, processEnvironment: processEnv); return } + if command == "note" { try await runNoteCommand(commandArgs: commandArgs, jsonOutput: jsonOutput, processEnvironment: processEnv); return } if command == "__sigpipe-probe" { try runSIGPIPEProbe(commandArgs: commandArgs); return } if command == "__sigpipe-stdin-pipe-probe" { try runSIGPIPEStdinPipeProbe(); return } if command == "__sigpipe-inspect" { try runSIGPIPEInspect(commandArgs: commandArgs); return } @@ -18312,6 +18314,8 @@ struct CMUXCLI { Check connectivity to the cmux socket server. """ + case "artifact": return artifactUsage() + case "note": return noteUsage() case "iroh-diag": return String( localized: "cli.help.irohDiag", @@ -20300,7 +20304,7 @@ struct CMUXCLI { ~/.config/cmux/sidebars as a right panel; the optional name picks which one. mode Print {"visible":bool,"mode":string} - files|find|vault|sessions|feed|dock|cloud|custom + files|find|vault|sessions|artifacts|feed|dock|cloud|custom Alias for show + set + focus Flags: @@ -21036,7 +21040,7 @@ struct CMUXCLI { case "set": guard parsed.positional.count == 2 || parsed.positional.count == 3 else { - throw CLIError(message: String(localized: "cli.rightSidebar.error.setRequiresMode", defaultValue: "right-sidebar set requires a mode: files, find, vault, sessions, feed, dock, cloud, or custom [sidebar-name]")) + throw CLIError(message: String(localized: "cli.rightSidebar.error.setRequiresMode", defaultValue: "right-sidebar set requires a mode: files, find, vault, sessions, artifacts, feed, dock, cloud, or custom [sidebar-name]")) } let mode = parsed.positional[1].trimmingCharacters(in: .whitespacesAndNewlines) guard isRightSidebarCLIMode(mode) else { @@ -21056,7 +21060,7 @@ struct CMUXCLI { } return args - case "files", "find", "vault", "sessions", "feed", "dock", "cloud", "machines", "custom", "custom-sidebar": + case "files", "find", "vault", "sessions", "artifacts", "feed", "dock", "cloud", "machines", "custom", "custom-sidebar": guard parsed.positional.count == 1 else { throw CLIError(message: String(localized: "cli.rightSidebar.error.unexpectedArguments", defaultValue: "right-sidebar \(action) received unexpected arguments")) } @@ -40946,6 +40950,8 @@ export default CMUXSessionRestore; Commands: welcome + \(String(localized: "cli.artifact.helpLine", defaultValue: "artifact [--project ]")) + \(String(localized: "cli.note.helpLine", defaultValue: "note [--project ] (rm requires --yes|-y)")) docs [settings|shortcuts|api|browser|agents|dock|sidebars] settings [open [target]|path|docs|] config @@ -41058,7 +41064,7 @@ export default CMUXSessionRestore; open-notification --id jump-to-unread clear-notifications [--workspace ] [--surface ] [--window ] - right-sidebar [--workspace ] [--window ] [--no-focus] + right-sidebar [--workspace ] [--window ] [--no-focus] sidebar [name] set-status [--workspace ] [--window ] [--icon ] [--color <#hex>] [--priority ] clear-status [--workspace ] [--window ] diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+DirectoryNameMaxHeap.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+DirectoryNameMaxHeap.swift new file mode 100644 index 000000000000..bd96765b5cd7 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+DirectoryNameMaxHeap.swift @@ -0,0 +1,89 @@ +import Foundation + +extension ArtifactByteReader { + /// Retains the lexicographically smallest bounded set of directory names. + /// A max-heap keeps each replacement at O(log capacity) instead of scanning + /// every retained name for every entry in a large directory. + struct DirectoryNameMaxHeap { + let capacity: Int + var values: [String] = [] + var didExceedCapacity = false + + init(capacity: Int) { + self.capacity = max(0, capacity) + } + + mutating func insert(_ value: String) { + guard capacity > 0 else { + didExceedCapacity = true + return + } + guard values.count < capacity else { + didExceedCapacity = true + guard isOrderedAfter(values[0], than: value) else { return } + values[0] = value + siftDown(from: 0) + return + } + values.append(value) + siftUp(from: values.index(before: values.endIndex)) + } + + var sortedValues: [String] { + values.sorted(by: precedes) + } + + private mutating func siftUp(from index: Int) { + var child = index + while child > 0 { + let parent = (child - 1) / 2 + guard isOrderedAfter(values[child], than: values[parent]) else { break } + values.swapAt(child, parent) + child = parent + } + } + + private mutating func siftDown(from index: Int) { + var parent = index + while true { + let left = parent * 2 + 1 + guard left < values.count else { return } + var largest = left + let right = left + 1 + if right < values.count, + isOrderedAfter(values[right], than: values[left]) { + largest = right + } + guard isOrderedAfter(values[largest], than: values[parent]) else { return } + values.swapAt(parent, largest) + parent = largest + } + } + + private func isOrderedAfter(_ lhs: String, than rhs: String) -> Bool { + switch lhs.localizedStandardCompare(rhs) { + case .orderedDescending: + return true + case .orderedAscending: + return false + case .orderedSame: + return lhs > rhs + @unknown default: + return lhs > rhs + } + } + + private func precedes(_ lhs: String, _ rhs: String) -> Bool { + switch lhs.localizedStandardCompare(rhs) { + case .orderedAscending: + return true + case .orderedDescending: + return false + case .orderedSame: + return lhs < rhs + @unknown default: + return lhs < rhs + } + } + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+Filesystem.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+Filesystem.swift new file mode 100644 index 000000000000..b2e5f3a527b9 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader+Filesystem.swift @@ -0,0 +1,672 @@ +import Darwin +import Foundation +import UniformTypeIdentifiers + +extension ArtifactByteReader { + static let utf8SniffByteCount = 8 * 1024 + + struct VerifiedMetadata { + let fileType: mode_t + let size: Int64 + let modifiedAt: Date + let device: UInt64 + let inode: UInt64 + } + + func kind( + path: String, + isDirectory: Bool, + isRegularFile: Bool? + ) -> ChatArtifactKind { + if isDirectory { return .directory } + if isRegularFile == false { return .binary } + let fileExtension = URL(fileURLWithPath: path).pathExtension + let type = fileExtension.isEmpty ? nil : UTType(filenameExtension: fileExtension) + guard let type, !type.isDynamic else { + let verifiedRegularFile: Bool + if let isRegularFile { + verifiedRegularFile = isRegularFile + } else { + verifiedRegularFile = (try? lstatMetadata(path: path).fileType == S_IFREG) ?? false + } + guard verifiedRegularFile else { return .binary } + return isUTF8Text(path: path) ? .text : .binary + } + if type.conforms(to: .image) { return .image } + if type.conforms(to: .text) || type.conforms(to: .sourceCode) || type.conforms(to: .json) { + return .text + } + return .binary + } + + func isUTF8Text(path: String) -> Bool { + guard let opened = try? openVerifiedRegularFile(path: path) else { + return false + } + let handle = opened.handle + defer { try? handle.close() } + let bytes: Data + do { + bytes = try handle.read(upToCount: Self.utf8SniffByteCount + 1) ?? Data() + } catch { + return false + } + let sample = Data(bytes.prefix(Self.utf8SniffByteCount)) + if String(data: sample, encoding: .utf8) != nil { + return true + } + guard bytes.count > Self.utf8SniffByteCount else { + return false + } + return hasValidUTF8PrefixEndingInPartialScalar(sample) + } + + func isUTF8Text(descriptor: Int32) -> Bool { + let limit = Self.utf8SniffByteCount + var bytes = [UInt8](repeating: 0, count: limit + 1) + let count = bytes.withUnsafeMutableBytes { buffer -> Int? in + guard let baseAddress = buffer.baseAddress else { return nil } + var total = 0 + while total < buffer.count { + let result = Darwin.pread( + descriptor, + baseAddress.advanced(by: total), + buffer.count - total, + off_t(total) + ) + if result < 0 { + if Darwin.errno == EINTR { continue } + return nil + } + if result == 0 { break } + total += result + } + return total + } + guard let count else { return false } + let sample = Data(bytes.prefix(min(count, limit))) + if String(data: sample, encoding: .utf8) != nil { return true } + guard count > limit else { return false } + return hasValidUTF8PrefixEndingInPartialScalar(sample) + } + + func hasValidUTF8PrefixEndingInPartialScalar(_ data: Data) -> Bool { + let bytes = Array(data) + guard !bytes.isEmpty else { return false } + let earliestCandidate = max(0, bytes.count - 4) + for start in stride(from: bytes.count - 1, through: earliestCandidate, by: -1) { + guard let expectedLength = utf8ScalarLength(leadingByte: bytes[start]) else { + continue + } + let actualLength = bytes.count - start + guard actualLength < expectedLength, + utf8PartialScalarBytesAreValid(Array(bytes[start...])) else { + continue + } + let prefix = Data(bytes[.. (handle: FileHandle, size: Int64) { + // Resolve aliases before opening so the descriptor check below compares + // against the path the caller authorized, not a path that a concurrent + // parent-directory swap could make `path` resolve to afterward. + let expectedCanonicalPath = expectedCanonicalPath ?? canonicalPath(path) + // Set close-on-exec atomically at open; fcntl afterward cannot close the fork race. + // `O_NOFOLLOW` rejects a replaced leaf; the canonical descriptor check + // below rejects a parent-directory redirect while retaining support for + // system aliases such as `/var` -> `/private/var`. + let descriptor = Darwin.open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard descriptor >= 0 else { throw filesystemError(errno: Darwin.errno) } + + var metadata = Darwin.stat() + guard Darwin.fstat(descriptor, &metadata) == 0 else { + let errorCode = Darwin.errno + Darwin.close(descriptor) + throw filesystemError(errno: errorCode) + } + guard (metadata.st_mode & S_IFMT) == S_IFREG else { + Darwin.close(descriptor) + throw Error.notRegularFile + } + if let expectedIdentity, + ChatArtifactFileIdentity( + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) != expectedIdentity { + Darwin.close(descriptor) + throw Error.fileNotFound + } + guard descriptorMatchesPath(descriptor, expectedCanonicalPath: expectedCanonicalPath) else { + Darwin.close(descriptor) + throw Error.fileNotFound + } + + let flags = Darwin.fcntl(descriptor, F_GETFL, 0) + guard flags >= 0, + Darwin.fcntl(descriptor, F_SETFL, flags & ~O_NONBLOCK) >= 0 else { + let errorCode = Darwin.errno + Darwin.close(descriptor) + throw filesystemError(errno: errorCode) + } + + return ( + FileHandle(fileDescriptor: descriptor, closeOnDealloc: true), + max(Int64(metadata.st_size), 0) + ) + } + + /// Reads metadata through a pinned parent directory without opening the + /// target entry, so sockets, devices, and FIFOs remain side-effect free. + func verifiedMetadata( + path: String, + expectedCanonicalPath: String? = nil, + expectedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> VerifiedMetadata { + let expectedCanonicalPath = expectedCanonicalPath ?? canonicalPath(path) + if expectedCanonicalPath == "/" { + let descriptor = try openVerifiedDirectory( + path: path, + expectedCanonicalPath: expectedCanonicalPath, + expectedIdentity: expectedIdentity + ) + defer { Darwin.close(descriptor) } + return try metadata(from: descriptor) + } + let expectedURL = URL(fileURLWithPath: expectedCanonicalPath) + let expectedParentPath = expectedURL.deletingLastPathComponent().path + let parentPath = URL(fileURLWithPath: path) + .deletingLastPathComponent() + .path + let parentDescriptor = try openVerifiedParentDirectory( + path: parentPath, + expectedCanonicalPath: expectedParentPath + ) + defer { Darwin.close(parentDescriptor) } + let leafName = expectedURL.lastPathComponent + var metadata = Darwin.stat() + let result = leafName.withCString { pointer in + Darwin.fstatat(parentDescriptor, pointer, &metadata, AT_SYMLINK_NOFOLLOW) + } + guard result == 0 else { + throw filesystemError(errno: errno) + } + guard (metadata.st_mode & S_IFMT) != S_IFLNK else { + throw Error.fileNotFound + } + if let expectedIdentity, + ChatArtifactFileIdentity( + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) != expectedIdentity { + throw Error.fileNotFound + } + return VerifiedMetadata( + fileType: metadata.st_mode & S_IFMT, + size: max(Int64(metadata.st_size), 0), + modifiedAt: Date( + timeIntervalSince1970: Double(metadata.st_mtimespec.tv_sec) + + Double(metadata.st_mtimespec.tv_nsec) / 1_000_000_000 + ), + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) + } + + func openVerifiedRegularFileAt( + path: String, + expectedCanonicalPath: String, + expectedDevice: UInt64, + expectedInode: UInt64 + ) throws -> (descriptor: Int32, size: Int64) { + let expectedURL = URL(fileURLWithPath: expectedCanonicalPath) + let parentPath = URL(fileURLWithPath: path) + .deletingLastPathComponent() + .path + let parentDescriptor = try openVerifiedParentDirectory( + path: parentPath, + expectedCanonicalPath: expectedURL.deletingLastPathComponent().path + ) + defer { Darwin.close(parentDescriptor) } + let leafName = expectedURL.lastPathComponent + let descriptor = leafName.withCString { pointer in + Darwin.openat( + parentDescriptor, + pointer, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + } + guard descriptor >= 0 else { throw filesystemError(errno: errno) } + var metadata = Darwin.stat() + guard Darwin.fstat(descriptor, &metadata) == 0 else { + let errorCode = errno + Darwin.close(descriptor) + throw filesystemError(errno: errorCode) + } + guard (metadata.st_mode & S_IFMT) == S_IFREG, + UInt64(metadata.st_dev) == expectedDevice, + UInt64(metadata.st_ino) == expectedInode else { + Darwin.close(descriptor) + throw Error.fileNotFound + } + return (descriptor, max(Int64(metadata.st_size), 0)) + } + + func openVerifiedParentDirectory( + path: String, + expectedCanonicalPath: String + ) throws -> Int32 { + let flags = O_RDONLY | O_DIRECTORY | O_NONBLOCK | O_CLOEXEC + let noFollowDescriptor = Darwin.open( + path, + flags | O_NOFOLLOW + ) + let descriptor: Int32 + let descriptorCanonicalPath: String + if noFollowDescriptor >= 0 { + descriptor = noFollowDescriptor + descriptorCanonicalPath = expectedCanonicalPath + } else { + let errorCode = Darwin.errno + guard errorCode == ELOOP || errorCode == ENOTDIR else { + throw filesystemError(errno: errorCode) + } + + if let aliasTarget = systemAliasTarget(for: path), + expectedCanonicalPath == path || expectedCanonicalPath == aliasTarget { + // System aliases such as `/tmp`, `/var`, and `/etc` are symlinks in the + // lexical path's final component. Retry only with the known + // canonical target; retaining O_NOFOLLOW avoids following a + // swapped or otherwise untrusted alias. + descriptor = Darwin.open(aliasTarget, flags | O_NOFOLLOW) + guard descriptor >= 0 else { + throw filesystemError(errno: Darwin.errno) + } + descriptorCanonicalPath = aliasTarget + } else if canonicalPath(path) != expectedCanonicalPath { + // A non-system alias changed since authorization. Preserve + // the existing fail-closed error instead of misreporting the + // symlink as an ordinary non-directory. + throw Error.fileNotFound + } else { + throw filesystemError(errno: errorCode) + } + } + var metadata = Darwin.stat() + guard Darwin.fstat(descriptor, &metadata) == 0 else { + let errorCode = errno + Darwin.close(descriptor) + throw filesystemError(errno: errorCode) + } + guard (metadata.st_mode & S_IFMT) == S_IFDIR else { + Darwin.close(descriptor) + throw Error.notDirectory + } + guard descriptorMatchesPath(descriptor, expectedCanonicalPath: descriptorCanonicalPath) else { + Darwin.close(descriptor) + throw Error.fileNotFound + } + return descriptor + } + + func metadata(from descriptor: Int32) throws -> VerifiedMetadata { + var metadata = Darwin.stat() + guard Darwin.fstat(descriptor, &metadata) == 0 else { + throw filesystemError(errno: errno) + } + return VerifiedMetadata( + fileType: metadata.st_mode & S_IFMT, + size: max(Int64(metadata.st_size), 0), + modifiedAt: Date( + timeIntervalSince1970: Double(metadata.st_mtimespec.tv_sec) + + Double(metadata.st_mtimespec.tv_nsec) / 1_000_000_000 + ), + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) + } + + func extensionDerivedKind(path: String) -> ChatArtifactKind { + let fileExtension = URL(fileURLWithPath: path).pathExtension + let type = fileExtension.isEmpty ? nil : UTType(filenameExtension: fileExtension) + guard let type, !type.isDynamic else { return .binary } + if type.conforms(to: .image) { return .image } + if type.conforms(to: .text) || type.conforms(to: .sourceCode) || type.conforms(to: .json) { + return .text + } + return .binary + } + + func openVerifiedDirectory( + path: String, + expectedCanonicalPath: String? = nil, + expectedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> Int32 { + let expectedCanonicalPath = expectedCanonicalPath ?? canonicalPath(path) + let flags = O_RDONLY | O_DIRECTORY | O_NONBLOCK | O_CLOEXEC + let noFollowDescriptor = Darwin.open( + path, + flags | O_NOFOLLOW + ) + let descriptor: Int32 + let descriptorCanonicalPath: String + if noFollowDescriptor >= 0 { + descriptor = noFollowDescriptor + descriptorCanonicalPath = expectedCanonicalPath + } else { + let errorCode = Darwin.errno + guard errorCode == ELOOP || errorCode == ENOTDIR else { + throw filesystemError(errno: errorCode) + } + + if let aliasTarget = systemAliasTarget(for: path), + expectedCanonicalPath == path || expectedCanonicalPath == aliasTarget { + // System aliases such as `/tmp`, `/var`, and `/etc` are symlinks in + // the lexical path's final component. Retry only with the known + // canonical target; retaining O_NOFOLLOW avoids following a + // swapped or otherwise untrusted alias. + descriptor = Darwin.open(aliasTarget, flags | O_NOFOLLOW) + guard descriptor >= 0 else { + throw filesystemError(errno: Darwin.errno) + } + descriptorCanonicalPath = aliasTarget + } else if canonicalPath(path) != expectedCanonicalPath { + // A non-system alias changed since authorization. Preserve the + // existing fail-closed error instead of misreporting the + // symlink as an ordinary non-directory. + throw Error.fileNotFound + } else { + throw filesystemError(errno: errorCode) + } + } + var metadata = Darwin.stat() + guard Darwin.fstat(descriptor, &metadata) == 0 else { + let errorCode = Darwin.errno + Darwin.close(descriptor) + throw filesystemError(errno: errorCode) + } + guard (metadata.st_mode & S_IFMT) == S_IFDIR else { + Darwin.close(descriptor) + throw Error.notDirectory + } + if let expectedIdentity, + ChatArtifactFileIdentity( + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) != expectedIdentity { + Darwin.close(descriptor) + throw Error.fileNotFound + } + guard descriptorMatchesPath(descriptor, expectedCanonicalPath: descriptorCanonicalPath) else { + Darwin.close(descriptor) + throw Error.fileNotFound + } + return descriptor + } + + /// Counts immediate non-symlink children with one bounded `readdir` pass. + /// + /// Directory-entry types are trusted when the filesystem supplies them; + /// only `DT_UNKNOWN` entries require a no-follow metadata lookup. The + /// result is capped at the same value as ``ArtifactByteReader.list`` so a + /// gallery row never performs work proportional to an unbounded folder. + func countImmediateChildren(path: String) throws -> (count: Int, isCapped: Bool)? { + let directoryDescriptor = try openVerifiedDirectory(path: path) + defer { Darwin.close(directoryDescriptor) } + + // Keep the descriptor's close-on-exec bit while handing ownership to + // `fdopendir`; the original remains available for `fstatat` calls. + let streamDescriptor = Darwin.fcntl(directoryDescriptor, F_DUPFD_CLOEXEC, 3) + guard streamDescriptor >= 0, + let stream = fdopendir(streamDescriptor) else { + if streamDescriptor >= 0 { Darwin.close(streamDescriptor) } + throw Error.readFailed + } + defer { closedir(stream) } + + var count = 0 + var scannedEntryCount = 0 + + while true { + errno = 0 + guard let entry = readdir(stream) else { + let errorCode = errno + guard errorCode == 0 else { + throw filesystemError(errno: Int32(errorCode)) + } + break + } + scannedEntryCount += 1 + if scannedEntryCount > Self.maximumDirectoryScanEntryCount { + // A non-empty lower bound is useful to the caller, but `0+` + // is misleading when the scan saw only skipped entries. + return count == 0 + ? nil + : (count: min(count, Self.maximumDirectoryEntryCount), isCapped: true) + } + if scannedEntryCount.isMultiple(of: 512) { + try Task.checkCancellation() + } + + let name = withUnsafeBytes(of: entry.pointee.d_name) { raw in + String(cString: raw.bindMemory(to: CChar.self).baseAddress!) + } + guard name != ".", name != ".." else { continue } + + let direntType = Int32(entry.pointee.d_type) + if direntType == DT_LNK { + continue + } + if direntType == DT_UNKNOWN { + var metadata = Darwin.stat() + let metadataResult = name.withCString { pointer in + Darwin.fstatat( + directoryDescriptor, + pointer, + &metadata, + AT_SYMLINK_NOFOLLOW + ) + } + guard metadataResult == 0, + (metadata.st_mode & S_IFMT) != S_IFLNK else { + continue + } + } + + count += 1 + if count > Self.maximumDirectoryEntryCount { + return (count: Self.maximumDirectoryEntryCount, isCapped: true) + } + } + return (count: count, isCapped: false) + } + + func descriptorMatchesPath( + _ descriptor: Int32, + expectedCanonicalPath: String + ) -> Bool { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { bytes -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return false } + let openedPath = String( + decoding: buffer.prefix { $0 != 0 }, + as: UTF8.self + ) + guard !openedPath.isEmpty else { return false } + let canonicalOpenedPath = URL(fileURLWithPath: openedPath) + .resolvingSymlinksInPath() + .standardizedFileURL + .path + return systemAliasCanonicalPath(canonicalOpenedPath) + == systemAliasCanonicalPath(expectedCanonicalPath) + } + + func canonicalPath(_ path: String) -> String { + URL(fileURLWithPath: path) + .resolvingSymlinksInPath() + .standardizedFileURL + .path + } + + func systemAliasTarget(for path: String) -> String? { + switch path { + case "/tmp": + return "/private/tmp" + case "/var": + return "/private/var" + case "/etc": + return "/private/etc" + default: + return nil + } + } + + func systemAliasCanonicalPath(_ path: String) -> String { + for (alias, target) in [ + ("/tmp", "/private/tmp"), + ("/var", "/private/var"), + ("/etc", "/private/etc"), + ] { + if path == alias { + return target + } + let aliasPrefix = "\(alias)/" + if path.hasPrefix(aliasPrefix) { + return target + String(path.dropFirst(alias.count)) + } + } + return path + } + + func kindForDescriptor( + path: String, + descriptor: Int32, + isDirectory: Bool + ) -> ChatArtifactKind { + if isDirectory { return .directory } + let fileExtension = URL(fileURLWithPath: path).pathExtension + let type = fileExtension.isEmpty ? nil : UTType(filenameExtension: fileExtension) + guard let type, !type.isDynamic else { + return isUTF8Text(descriptor: descriptor) ? .text : .binary + } + if type.conforms(to: .image) { return .image } + if type.conforms(to: .text) || type.conforms(to: .sourceCode) || type.conforms(to: .json) { + return .text + } + return .binary + } + + func utf8ScalarLength(leadingByte: UInt8) -> Int? { + switch leadingByte { + case 0xC2...0xDF: + return 2 + case 0xE0...0xEF: + return 3 + case 0xF0...0xF4: + return 4 + default: + return nil + } + } + + func utf8PartialScalarBytesAreValid(_ bytes: [UInt8]) -> Bool { + guard let leadingByte = bytes.first else { return false } + for byte in bytes.dropFirst() where byte & 0xC0 != 0x80 { + return false + } + guard bytes.count > 1 else { return true } + let firstContinuation = bytes[1] + switch leadingByte { + case 0xE0: + return firstContinuation >= 0xA0 + case 0xED: + return firstContinuation <= 0x9F + case 0xF0: + return firstContinuation >= 0x90 + case 0xF4: + return firstContinuation <= 0x8F + default: + return true + } + } + + func lstatMetadata(path: String) throws -> VerifiedMetadata { + var metadata = Darwin.stat() + guard Darwin.lstat(path, &metadata) == 0 else { + throw filesystemError(errno: errno) + } + return VerifiedMetadata( + fileType: metadata.st_mode & S_IFMT, + size: max(Int64(metadata.st_size), 0), + modifiedAt: Date( + timeIntervalSince1970: Double(metadata.st_mtimespec.tv_sec) + + Double(metadata.st_mtimespec.tv_nsec) / 1_000_000_000 + ), + device: UInt64(metadata.st_dev), + inode: UInt64(metadata.st_ino) + ) + } + + func filesystemError(_ error: any Swift.Error) -> Error { + if let readerError = error as? Error { + return readerError + } + if let posixError = error as? POSIXError { + return filesystemError(errno: posixError.code.rawValue) + } + let nsError = error as NSError + if nsError.domain == NSPOSIXErrorDomain { + return filesystemError(errno: Int32(nsError.code)) + } + if let underlying = nsError.userInfo[NSUnderlyingErrorKey] as? NSError, + underlying !== nsError { + return filesystemError(underlying) + } + if let cocoaError = error as? CocoaError { + switch cocoaError.code { + case .fileReadNoSuchFile: + return .fileNotFound + case .fileReadNoPermission: + return .permissionDenied + default: + break + } + } + return .readFailed + } + + func filesystemError(errno errorCode: Int32) -> Error { + switch POSIXErrorCode(rawValue: errorCode) { + case .ENOENT, .ESTALE: + return .fileNotFound + case .EACCES, .EPERM: + return .permissionDenied + case .ENOTDIR: + return .notDirectory + case .EISDIR: + return .notRegularFile + case .ELOOP: + return .fileNotFound + default: + return .readFailed + } + } + + func mimeType(path: String, isDirectory: Bool) -> String? { + guard !isDirectory, + let type = UTType(filenameExtension: URL(fileURLWithPath: path).pathExtension) else { + return nil + } + return type.preferredMIMEType + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader.swift index a110ddafc9ea..dbd83db7727e 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ArtifactByteReader.swift @@ -10,7 +10,8 @@ import UniformTypeIdentifiers public struct ArtifactByteReader: Sendable { /// Maximum immediate children returned by one directory-list request. public static let maximumDirectoryEntryCount = 500 - private static let utf8SniffByteCount = 8 * 1024 + /// Maximum directory entries inspected before a listing is marked capped. + static let maximumDirectoryScanEntryCount = 100_000 /// Filesystem/decoder failures surfaced by artifact RPC handlers. public enum Error: Swift.Error, Sendable, Equatable { @@ -35,15 +36,118 @@ public struct ArtifactByteReader: Sendable { /// Creates a byte reader. public init() {} + /// Captures the device/inode identity for an already-authorized path. + /// + /// Callers retain the returned value and supply it to later reads so a + /// replacement inode at the same pathname cannot silently become + /// authorized. The optional canonical path keeps the capture tied to the + /// same ancestor-swap check used by fetch and listing operations. + /// + /// - Parameters: + /// - path: Path to inspect. + /// - authorizedCanonicalPath: Canonical path captured by the scope check. + /// - Returns: Stable device/inode identity for the path. + public func identity( + path: String, + authorizedCanonicalPath: String? = nil + ) throws -> ChatArtifactFileIdentity { + let metadata = try verifiedMetadata( + path: path, + expectedCanonicalPath: authorizedCanonicalPath + ) + return ChatArtifactFileIdentity( + device: metadata.device, + inode: metadata.inode + ) + } + /// Reads metadata for an already-authorized path. - public func stat(path: String) throws -> ChatArtifactStat { - let attributes = try attributes(path: path) - return stat(path: path, attributes: attributes) + /// + /// - Parameters: + /// - path: Path to inspect. + /// - authorizedCanonicalPath: Canonical path captured at authorization + /// time. Supplying it pins metadata to the same scope decision and + /// rejects an ancestor replacement before the descriptor is opened. + /// - authorizedIdentity: Device/inode captured at authorization time. + /// Supplying it rejects a replacement object at the same pathname. + public func stat( + path: String, + authorizedCanonicalPath: String? = nil, + authorizedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> ChatArtifactStat { + if let authorizedCanonicalPath { + let metadata = try verifiedMetadata( + path: path, + expectedCanonicalPath: authorizedCanonicalPath, + expectedIdentity: authorizedIdentity + ) + let kind: ChatArtifactKind + switch metadata.fileType { + case S_IFDIR: + kind = .directory + case S_IFREG: + do { + let opened = try openVerifiedRegularFileAt( + path: path, + expectedCanonicalPath: authorizedCanonicalPath, + expectedDevice: metadata.device, + expectedInode: metadata.inode + ) + defer { Darwin.close(opened.descriptor) } + kind = kindForDescriptor( + path: path, + descriptor: opened.descriptor, + isDirectory: false + ) + } catch Error.fileNotFound { + throw Error.fileNotFound + } catch { + kind = extensionDerivedKind(path: path) + } + default: + kind = .binary + } + return ChatArtifactStat( + exists: true, + isDirectory: metadata.fileType == S_IFDIR, + size: metadata.size, + modifiedAt: metadata.modifiedAt, + kind: kind, + mimeType: mimeType(path: path, isDirectory: metadata.fileType == S_IFDIR) + ) + } + if let authorizedIdentity { + let metadata = try verifiedMetadata( + path: path, + expectedIdentity: authorizedIdentity + ) + return stat(path: path, metadata: metadata) + } + return stat(path: path, metadata: try lstatMetadata(path: path)) } /// Reads one clamped byte chunk for an already-authorized file path. - public func fetch(path: String, offset: Int64, length: Int) throws -> ChatArtifactChunk { - let opened = try openVerifiedRegularFile(path: path) + /// + /// - Parameters: + /// - path: Path to read. + /// - offset: Requested byte offset, clamped to the opened file size. + /// - length: Maximum number of bytes to return. + /// - authorizedCanonicalPath: Canonical path captured at authorization + /// time. Supplying it prevents an ancestor replacement between scope + /// validation and this open from redirecting the read. + /// - authorizedIdentity: Device/inode captured at authorization time. + public func fetch( + path: String, + offset: Int64, + length: Int, + authorizedCanonicalPath: String? = nil, + authorizedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> ChatArtifactChunk { + let opened = try openVerifiedRegularFile( + path: path, + expectedCanonicalPath: authorizedCanonicalPath, + expectedIdentity: authorizedIdentity + ) let handle = opened.handle defer { try? handle.close() } let totalSize = opened.size @@ -66,37 +170,60 @@ public struct ArtifactByteReader: Sendable { private func stat( path: String, - attributes: [FileAttributeKey: Any] + metadata: VerifiedMetadata ) -> ChatArtifactStat { - let fileType = attributes[.type] as? FileAttributeType - let isDirectory = fileType == .typeDirectory - let size = (attributes[.size] as? NSNumber)?.int64Value ?? 0 - let modifiedAt = attributes[.modificationDate] as? Date ?? Date(timeIntervalSince1970: 0) + let isDirectory = metadata.fileType == S_IFDIR let kind = kind( path: path, isDirectory: isDirectory, - isRegularFile: fileType == .typeRegular + isRegularFile: metadata.fileType == S_IFREG ) return ChatArtifactStat( exists: true, isDirectory: isDirectory, - size: size, - modifiedAt: modifiedAt, + size: metadata.size, + modifiedAt: metadata.modifiedAt, kind: kind, mimeType: mimeType(path: path, isDirectory: isDirectory) ) } /// Generates a JPEG thumbnail for an already-authorized image path. - public func thumbnail(path: String, maxDimension: Int) throws -> ChatArtifactThumbnail { - let opened = try openVerifiedRegularFile(path: path) - try? opened.handle.close() - guard kind(path: path, isDirectory: false) == .image else { + /// + /// - Parameters: + /// - path: Image path to decode. + /// - maxDimension: Maximum thumbnail dimension in pixels. + /// - authorizedCanonicalPath: Canonical path captured at authorization + /// time. Supplying it prevents an ancestor replacement between scope + /// validation and this open from redirecting the decoder. + /// - authorizedIdentity: Device/inode captured at authorization time. + public func thumbnail( + path: String, + maxDimension: Int, + authorizedCanonicalPath: String? = nil, + authorizedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> ChatArtifactThumbnail { + let opened = try openVerifiedRegularFile( + path: path, + expectedCanonicalPath: authorizedCanonicalPath, + expectedIdentity: authorizedIdentity + ) + defer { try? opened.handle.close() } + guard kindForDescriptor( + path: path, + descriptor: opened.handle.fileDescriptor, + isDirectory: false + ) == .image else { throw Error.unsupportedMedia } - let url = URL(fileURLWithPath: path) - guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { - _ = try attributes(path: path) + // Keep the validated descriptor open for ImageIO. Reopening `path` + // after authorization would permit a concurrent replacement to point + // the decoder at an unrelated inode. + let descriptorURL = URL( + fileURLWithPath: "/dev/fd/\(opened.handle.fileDescriptor)", + isDirectory: false + ) + guard let source = CGImageSourceCreateWithURL(descriptorURL as CFURL, nil) else { throw Error.corruptMedia } let options: [CFString: Any] = [ @@ -134,43 +261,173 @@ public struct ArtifactByteReader: Sendable { /// /// One readdir pass collects child names; per-child filesystem metadata is /// read only for the capped entries that the listing actually returns. - public func list(path: String) throws -> ChatArtifactDirectoryListing { - let stat = try stat(path: path) - guard stat.isDirectory else { throw Error.notDirectory } - let names: [String] - do { - names = try FileManager.default.contentsOfDirectory(atPath: path) - } catch { - throw filesystemError(error) + /// + /// - Parameters: + /// - path: Directory path to list. + /// - authorizedCanonicalPath: Canonical path captured at authorization + /// time. Supplying it prevents an ancestor replacement between scope + /// validation and this open from redirecting the listing. + /// - authorizedIdentity: Device/inode captured at authorization time. + public func list( + path: String, + authorizedCanonicalPath: String? = nil, + authorizedIdentity: ChatArtifactFileIdentity? = nil + ) throws -> ChatArtifactDirectoryListing { + let directoryDescriptor = try openVerifiedDirectory( + path: path, + expectedCanonicalPath: authorizedCanonicalPath, + expectedIdentity: authorizedIdentity + ) + defer { Darwin.close(directoryDescriptor) } + // Preserve close-on-exec on the descriptor handed to `fdopendir`; a + // plain `dup` clears it during the interval before the stream closes. + let streamDescriptor = Darwin.fcntl(directoryDescriptor, F_DUPFD_CLOEXEC, 3) + guard streamDescriptor >= 0, + let stream = fdopendir(streamDescriptor) else { + if streamDescriptor >= 0 { Darwin.close(streamDescriptor) } + throw Error.readFailed } - let sortedNames = names.sorted { - $0.localizedStandardCompare($1) == .orderedAscending + defer { closedir(stream) } + + var names = DirectoryNameMaxHeap(capacity: Self.maximumDirectoryEntryCount) + var listingIncomplete = false + var scanLimitReached = false + var scannedEntryCount = 0 + while true { + errno = 0 + guard let entry = readdir(stream) else { + let errorCode = errno + guard errorCode == 0 else { + throw filesystemError(errno: Int32(errorCode)) + } + break + } + scannedEntryCount += 1 + if scannedEntryCount > Self.maximumDirectoryScanEntryCount { + scanLimitReached = true + break + } + if scannedEntryCount.isMultiple(of: 512) { + try Task.checkCancellation() + } + let name = withUnsafeBytes(of: entry.pointee.d_name) { raw in + String(cString: raw.bindMemory(to: CChar.self).baseAddress!) + } + guard name != ".", name != ".." else { continue } + let direntType = Int32(entry.pointee.d_type) + if direntType == DT_LNK { + // Symlink children are intentionally excluded from the result + // set; filtering before the bounded heap prevents them from + // consuming slots that should be available to returnable entries. + continue + } + if direntType == DT_UNKNOWN { + var childMetadata = Darwin.stat() + let metadataResult = name.withCString { pointer in + Darwin.fstatat( + directoryDescriptor, + pointer, + &childMetadata, + AT_SYMLINK_NOFOLLOW + ) + } + guard metadataResult == 0 else { + listingIncomplete = true + continue + } + guard (childMetadata.st_mode & S_IFMT) != S_IFLNK else { continue } + } + names.insert(name) } - let directoryURL = URL(fileURLWithPath: path, isDirectory: true) + let sortedNames = names.sortedValues var listed: [ChatArtifactDirectoryEntry] = [] listed.reserveCapacity(min(sortedNames.count, Self.maximumDirectoryEntryCount)) for name in sortedNames.prefix(Self.maximumDirectoryEntryCount) { - do { - let entry = directoryURL.appendingPathComponent(name) - let values = try entry.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey]) - let isDirectory = values.isDirectory ?? false - listed.append(ChatArtifactDirectoryEntry( - name: name, - isDirectory: isDirectory, - size: Int64(values.fileSize ?? 0), - kind: kind(path: entry.path, isDirectory: isDirectory) - )) - } catch { - let failure = filesystemError(error) - if failure == .fileNotFound { - continue + var metadata = Darwin.stat() + let metadataResult = name.withCString { pointer in + Darwin.fstatat( + directoryDescriptor, + pointer, + &metadata, + AT_SYMLINK_NOFOLLOW + ) + } + guard metadataResult == 0 else { + let errorCode = errno + switch POSIXErrorCode(rawValue: errorCode) { + case .ENOENT, .ESTALE, .ENOTDIR, .ELOOP: + listingIncomplete = true + default: + listingIncomplete = true + } + continue + } + let entryType = metadata.st_mode & S_IFMT + let isDirectory = entryType == S_IFDIR + guard entryType != S_IFLNK else { + listingIncomplete = true + continue + } + let kind: ChatArtifactKind + if isDirectory { + kind = .directory + } else if entryType == S_IFREG { + let childDescriptor = name.withCString { pointer in + Darwin.openat( + directoryDescriptor, + pointer, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + } + if childDescriptor >= 0 { + defer { Darwin.close(childDescriptor) } + var childMetadata = Darwin.stat() + guard Darwin.fstat(childDescriptor, &childMetadata) == 0 else { + listingIncomplete = true + continue + } + guard UInt64(childMetadata.st_dev) == UInt64(metadata.st_dev), + UInt64(childMetadata.st_ino) == UInt64(metadata.st_ino) else { + listingIncomplete = true + continue + } + kind = kindForDescriptor( + path: name, + descriptor: childDescriptor, + isDirectory: false + ) + } else { + let errorCode = errno + switch POSIXErrorCode(rawValue: errorCode) { + case .EACCES, .EPERM: + listingIncomplete = true + break + case .ENOENT, .ESTALE, .ENOTDIR, .ELOOP: + listingIncomplete = true + continue + default: + listingIncomplete = true + continue + } + // Metadata remains useful when a regular child is not + // readable. Preserve the entry and use its safe extension + // classification instead of failing the whole listing. + kind = extensionDerivedKind(path: name) } - throw failure + } else { + kind = .binary } + listed.append(ChatArtifactDirectoryEntry( + name: name, + isDirectory: isDirectory, + size: max(Int64(metadata.st_size), 0), + kind: kind + )) } return ChatArtifactDirectoryListing( entries: listed, - isTruncated: names.count > Self.maximumDirectoryEntryCount + isTruncated: names.didExceedCapacity || scanLimitReached, + isIncomplete: listingIncomplete ) } @@ -182,196 +439,4 @@ public struct ArtifactByteReader: Sendable { isRegularFile: nil ) } - - private func kind( - path: String, - isDirectory: Bool, - isRegularFile: Bool? - ) -> ChatArtifactKind { - if isDirectory { return .directory } - if isRegularFile == false { return .binary } - let fileExtension = URL(fileURLWithPath: path).pathExtension - let type = fileExtension.isEmpty ? nil : UTType(filenameExtension: fileExtension) - guard let type, !type.isDynamic else { - let verifiedRegularFile: Bool - if let isRegularFile { - verifiedRegularFile = isRegularFile - } else { - let attributes = try? attributes(path: path) - verifiedRegularFile = (attributes?[.type] as? FileAttributeType) == .typeRegular - } - guard verifiedRegularFile else { return .binary } - return isUTF8Text(path: path) ? .text : .binary - } - if type.conforms(to: .image) { return .image } - if type.conforms(to: .text) || type.conforms(to: .sourceCode) || type.conforms(to: .json) { - return .text - } - return .binary - } - - private func isUTF8Text(path: String) -> Bool { - guard let opened = try? openVerifiedRegularFile(path: path) else { - return false - } - let handle = opened.handle - defer { try? handle.close() } - let bytes: Data - do { - bytes = try handle.read(upToCount: Self.utf8SniffByteCount + 1) ?? Data() - } catch { - return false - } - let sample = Data(bytes.prefix(Self.utf8SniffByteCount)) - if String(data: sample, encoding: .utf8) != nil { - return true - } - guard bytes.count > Self.utf8SniffByteCount else { - return false - } - return hasValidUTF8PrefixEndingInPartialScalar(sample) - } - - private func hasValidUTF8PrefixEndingInPartialScalar(_ data: Data) -> Bool { - let bytes = Array(data) - guard !bytes.isEmpty else { return false } - let earliestCandidate = max(0, bytes.count - 4) - for start in stride(from: bytes.count - 1, through: earliestCandidate, by: -1) { - guard let expectedLength = utf8ScalarLength(leadingByte: bytes[start]) else { - continue - } - let actualLength = bytes.count - start - guard actualLength < expectedLength, - utf8PartialScalarBytesAreValid(Array(bytes[start...])) else { - continue - } - let prefix = Data(bytes[.. (handle: FileHandle, size: Int64) { - // Set close-on-exec atomically at open; fcntl afterward cannot close the fork race. - let descriptor = Darwin.open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) - guard descriptor >= 0 else { throw filesystemError(errno: Darwin.errno) } - - var metadata = Darwin.stat() - guard Darwin.fstat(descriptor, &metadata) == 0 else { - let errorCode = Darwin.errno - Darwin.close(descriptor) - throw filesystemError(errno: errorCode) - } - guard (metadata.st_mode & S_IFMT) == S_IFREG else { - Darwin.close(descriptor) - throw Error.notRegularFile - } - - let flags = Darwin.fcntl(descriptor, F_GETFL, 0) - guard flags >= 0, - Darwin.fcntl(descriptor, F_SETFL, flags & ~O_NONBLOCK) >= 0 else { - let errorCode = Darwin.errno - Darwin.close(descriptor) - throw filesystemError(errno: errorCode) - } - - return ( - FileHandle(fileDescriptor: descriptor, closeOnDealloc: true), - max(Int64(metadata.st_size), 0) - ) - } - - private func utf8ScalarLength(leadingByte: UInt8) -> Int? { - switch leadingByte { - case 0xC2...0xDF: - return 2 - case 0xE0...0xEF: - return 3 - case 0xF0...0xF4: - return 4 - default: - return nil - } - } - - private func utf8PartialScalarBytesAreValid(_ bytes: [UInt8]) -> Bool { - guard let leadingByte = bytes.first else { return false } - for byte in bytes.dropFirst() where byte & 0xC0 != 0x80 { - return false - } - guard bytes.count > 1 else { return true } - let firstContinuation = bytes[1] - switch leadingByte { - case 0xE0: - return firstContinuation >= 0xA0 - case 0xED: - return firstContinuation <= 0x9F - case 0xF0: - return firstContinuation >= 0x90 - case 0xF4: - return firstContinuation <= 0x8F - default: - return true - } - } - - private func attributes(path: String) throws -> [FileAttributeKey: Any] { - do { - return try FileManager.default.attributesOfItem(atPath: path) - } catch { - throw filesystemError(error) - } - } - - private func filesystemError(_ error: any Swift.Error) -> Error { - if let readerError = error as? Error { - return readerError - } - if let posixError = error as? POSIXError { - return filesystemError(errno: posixError.code.rawValue) - } - let nsError = error as NSError - if nsError.domain == NSPOSIXErrorDomain { - return filesystemError(errno: Int32(nsError.code)) - } - if let underlying = nsError.userInfo[NSUnderlyingErrorKey] as? NSError, - underlying !== nsError { - return filesystemError(underlying) - } - if let cocoaError = error as? CocoaError { - switch cocoaError.code { - case .fileReadNoSuchFile: - return .fileNotFound - case .fileReadNoPermission: - return .permissionDenied - default: - break - } - } - return .readFailed - } - - private func filesystemError(errno errorCode: Int32) -> Error { - switch POSIXErrorCode(rawValue: errorCode) { - case .ENOENT, .ESTALE: - return .fileNotFound - case .EACCES, .EPERM: - return .permissionDenied - case .ENOTDIR: - return .notDirectory - case .EISDIR: - return .notRegularFile - default: - return .readFailed - } - } - - private func mimeType(path: String, isDirectory: Bool) -> String? { - guard !isDirectory, - let type = UTType(filenameExtension: URL(fileURLWithPath: path).pathExtension) else { - return nil - } - return type.preferredMIMEType - } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactCaptureAuthorization.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactCaptureAuthorization.swift new file mode 100644 index 000000000000..306e9ab6f8ea --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactCaptureAuthorization.swift @@ -0,0 +1,30 @@ +/// A transcript occurrence that authorizes copying an artifact into project storage. +public enum ChatArtifactCaptureAuthorization: Sendable, Equatable, Codable { + /// A successful agent mutation at the associated transcript sequence. + case created(sequence: Int) + /// A user attachment at the associated transcript sequence. + case attached(sequence: Int) + + /// Transcript sequence that granted the authorization. + public var sequence: Int { + switch self { + case .created(let sequence), .attached(let sequence): sequence + } + } + + /// Capture provenance represented by this authorization. + public var provenance: ChatArtifactProvenance { + switch self { + case .created: .created + case .attached: .attached + } + } + + /// Returns the newer grant, breaking sequence ties by provenance authority. + func latest(with candidate: ChatArtifactCaptureAuthorization) -> ChatArtifactCaptureAuthorization { + if sequence != candidate.sequence { + return sequence > candidate.sequence ? self : candidate + } + return provenance.preferred(over: candidate.provenance) == provenance ? self : candidate + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactDirectoryListing.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactDirectoryListing.swift index ba0f572766bc..8022208fcc4d 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactDirectoryListing.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactDirectoryListing.swift @@ -4,20 +4,29 @@ public struct ChatArtifactDirectoryListing: Sendable, Equatable, Codable { public let entries: [ChatArtifactDirectoryEntry] /// Whether additional immediate children were omitted by the server cap. public let isTruncated: Bool + /// Whether one or more retained names could not be read consistently. + public let isIncomplete: Bool /// Creates a directory listing. /// /// - Parameters: /// - entries: Directory entries sorted by name. /// - isTruncated: Whether the server omitted additional entries. - public init(entries: [ChatArtifactDirectoryEntry], isTruncated: Bool = false) { + /// - isIncomplete: Whether a child changed or became unreadable while listing. + public init( + entries: [ChatArtifactDirectoryEntry], + isTruncated: Bool = false, + isIncomplete: Bool = false + ) { self.entries = entries self.isTruncated = isTruncated + self.isIncomplete = isIncomplete } private enum CodingKeys: String, CodingKey { case entries case isTruncated = "is_truncated" + case isIncomplete = "is_incomplete" } /// Decodes listings from current and legacy hosts. @@ -25,6 +34,7 @@ public struct ChatArtifactDirectoryListing: Sendable, Equatable, Codable { let container = try decoder.container(keyedBy: CodingKeys.self) entries = try container.decode([ChatArtifactDirectoryEntry].self, forKey: .entries) isTruncated = try container.decodeIfPresent(Bool.self, forKey: .isTruncated) ?? false + isIncomplete = try container.decodeIfPresent(Bool.self, forKey: .isIncomplete) ?? false } /// Encodes the capped-list metadata for mobile clients. @@ -32,5 +42,6 @@ public struct ChatArtifactDirectoryListing: Sendable, Equatable, Codable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(entries, forKey: .entries) try container.encode(isTruncated, forKey: .isTruncated) + try container.encode(isIncomplete, forKey: .isIncomplete) } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactFileIdentity.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactFileIdentity.swift new file mode 100644 index 000000000000..1e9dd47c8f02 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactFileIdentity.swift @@ -0,0 +1,17 @@ +/// Stable device/inode identity for one filesystem entry authorized for reading. +public struct ChatArtifactFileIdentity: Sendable, Equatable, Hashable { + /// Device number reported by `stat(2)`. + public let device: UInt64 + /// Inode number reported by `stat(2)`. + public let inode: UInt64 + + /// Creates a filesystem identity value. + /// + /// - Parameters: + /// - device: Device number reported by `stat(2)`. + /// - inode: Inode number reported by `stat(2)`. + public init(device: UInt64, inode: UInt64) { + self.device = device + self.inode = inode + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryOrderingCache.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryOrderingCache.swift index bd7ef57fac96..4773fb934bcf 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryOrderingCache.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryOrderingCache.swift @@ -50,6 +50,13 @@ public actor ChatArtifactGalleryOrderingCache { return ordered } + /// Removes every retained generation for one transcript index. + /// + /// - Parameter indexID: Stable identity of the transcript index to evict. + public func remove(indexID: String) { + entries = entries.filter { $0.key.indexID != indexID } + } + private func evictIfNeeded() { while entries.count > maximumEntryCount, let leastRecent = entries.min(by: { $0.value.access < $1.value.access })?.key { diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryRowEligibility.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryRowEligibility.swift index 65521b73e558..9b7815c3ff78 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryRowEligibility.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactGalleryRowEligibility.swift @@ -162,24 +162,10 @@ public struct ChatArtifactGalleryRowEligibility: Sendable { } } - /// Counts immediate children for a gallery directory row without sorting - /// or per-entry metadata, stopping at the shared listing limit so the cost - /// never scales past the cap for large folders. + /// Counts immediate non-symlink children for a gallery directory row. + /// The reader uses one bounded low-level directory pass and resolves only + /// entries whose filesystem type is unknown. private func directoryChildCount(path: String) -> (count: Int, isCapped: Bool)? { - guard let enumerator = FileManager.default.enumerator( - at: URL(fileURLWithPath: path, isDirectory: true), - includingPropertiesForKeys: [], - options: [.skipsSubdirectoryDescendants] - ) else { - return nil - } - var count = 0 - while enumerator.nextObject() != nil { - count += 1 - if count > ArtifactByteReader.maximumDirectoryEntryCount { - return (count: ArtifactByteReader.maximumDirectoryEntryCount, isCapped: true) - } - } - return (count: count, isCapped: false) + try? ArtifactByteReader().countImmediateChildren(path: path) } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactIndexedReference.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactIndexedReference.swift index 2ff84eee34ff..8349e975149a 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactIndexedReference.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactIndexedReference.swift @@ -2,21 +2,52 @@ import Foundation /// A transcript-derived path with de-duplicated provenance and its last position. public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identifiable { + private static let maximumDerivedPathCount = ChatToolReferencedPathExtractor.maximumPathCount + private static let maximumCanonicalAliasCount = 2_048 + /// Canonical display path when the file exists, otherwise its lexical path. public let path: String /// Highest-precedence provenance observed for the path. public let provenance: ChatArtifactProvenance /// Last transcript sequence that mentioned, attached, or edited the path. public let lastReferencedSeq: Int + /// Most recent transcript occurrence that authorizes capture, if any. + public let captureAuthorization: ChatArtifactCaptureAuthorization? /// Stable identity used by ordering and paging. public var id: String { path } - /// Creates an indexed reference. + /// Creates an indexed reference from one provenance-bearing occurrence. + /// + /// Created and attached provenance authorizes capture at `lastReferencedSeq`. + /// Use ``init(path:provenance:lastReferencedSeq:captureAuthorization:)`` + /// when aggregate provenance and the latest authorization differ. public init(path: String, provenance: ChatArtifactProvenance, lastReferencedSeq: Int) { + self.init( + path: path, + provenance: provenance, + lastReferencedSeq: lastReferencedSeq, + captureAuthorization: provenance.captureAuthorization(sequence: lastReferencedSeq) + ) + } + + /// Creates an indexed reference with independently tracked display provenance and capture authorization. + /// + /// - Parameters: + /// - path: Canonical display path. + /// - provenance: Highest-precedence provenance observed for the path. + /// - lastReferencedSeq: Last transcript sequence that mentioned the path. + /// - captureAuthorization: Most recent capture-authorizing occurrence, if any. + public init( + path: String, + provenance: ChatArtifactProvenance, + lastReferencedSeq: Int, + captureAuthorization: ChatArtifactCaptureAuthorization? + ) { self.path = path self.provenance = provenance self.lastReferencedSeq = lastReferencedSeq + self.captureAuthorization = captureAuthorization } /// Derives one record per canonical path identity from parsed transcript messages. @@ -41,6 +72,7 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi ) -> [ChatArtifactIndexedReference] { var byPath: [String: ChatArtifactIndexedReference] = [:] var canonicalPathByLexicalPath: [String: String] = [:] + var recencyHeap = ChatArtifactRecencyHeap() let detector = TerminalArtifactPathDetector() let normalizer = ChatArtifactPathNormalizer(workingDirectory: workingDirectory) for message in messages { @@ -48,25 +80,45 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi var textOccurrences: [String] = [] switch message.kind { case .fileEdit(let edit): - structuredOccurrences = [(edit.filePath, .created)] + structuredOccurrences = [(edit.filePath, .referenced)] case .attachment(let attachment): structuredOccurrences = attachment.hostPath.map { [($0, .attached)] } ?? [] case .toolUse(let toolUse): - let provenance: ChatArtifactProvenance = Self.isFileMutationTool(toolUse.toolName) + let provenance: ChatArtifactProvenance = toolUse.authorizesCreatedArtifactProvenance ? .created : .referenced - structuredOccurrences = (toolUse.referencedPaths ?? []).map { ($0, provenance) } + structuredOccurrences = (toolUse.referencedPaths ?? []) + .prefix(Self.maximumDerivedPathCount) + .map { ($0, provenance) } if let output = toolUse.output { - textOccurrences = detector.paths(in: output) + textOccurrences = detector.paths( + in: output, + maximumCount: Self.maximumDerivedPathCount + ) } case .prose(let prose): - textOccurrences = detector.paths(in: prose.text) + textOccurrences = detector.paths( + in: prose.text, + maximumCount: Self.maximumDerivedPathCount + ) case .thought(let thought): - textOccurrences = detector.paths(in: thought.text) + textOccurrences = detector.paths( + in: thought.text, + maximumCount: Self.maximumDerivedPathCount + ) case .terminal(let terminal): - textOccurrences = detector.paths(in: terminal.command) + textOccurrences = detector.paths( + in: terminal.command, + maximumCount: Self.maximumDerivedPathCount + ) if let output = terminal.output { - textOccurrences.append(contentsOf: detector.paths(in: output)) + let remaining = Self.maximumDerivedPathCount - textOccurrences.count + if remaining > 0 { + textOccurrences.append(contentsOf: detector.paths( + in: output, + maximumCount: remaining + )) + } } case .permissionRequest, .question, .status, .unsupported: break @@ -81,7 +133,9 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi seq: message.seq, canonicalizer: canonicalizer, canonicalPathByLexicalPath: &canonicalPathByLexicalPath, - into: &byPath + into: &byPath, + recencyHeap: &recencyHeap, + maximumPathCount: Self.maximumDerivedPathCount ) } for rawPath in textOccurrences where @@ -93,7 +147,9 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi seq: message.seq, canonicalizer: canonicalizer, canonicalPathByLexicalPath: &canonicalPathByLexicalPath, - into: &byPath + into: &byPath, + recencyHeap: &recencyHeap, + maximumPathCount: Self.maximumDerivedPathCount ) } } @@ -111,7 +167,9 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi seq: reference.seq, canonicalizer: canonicalizer, canonicalPathByLexicalPath: &canonicalPathByLexicalPath, - into: &byPath + into: &byPath, + recencyHeap: &recencyHeap, + maximumPathCount: Self.maximumDerivedPathCount ) } return Array(byPath.values) @@ -123,41 +181,61 @@ public struct ChatArtifactIndexedReference: Sendable, Equatable, Codable, Identi seq: Int, canonicalizer: ChatArtifactPathCanonicalizer, canonicalPathByLexicalPath: inout [String: String], - into byPath: inout [String: ChatArtifactIndexedReference] + into byPath: inout [String: ChatArtifactIndexedReference], + recencyHeap: inout ChatArtifactRecencyHeap, + maximumPathCount: Int ) { - let canonicalPath: String - if let cached = canonicalPathByLexicalPath[path] { - canonicalPath = cached - } else { - canonicalPath = canonicalizer.canonicalPathKey(for: path) + let canonicalPath = canonicalPathByLexicalPath[path] + ?? canonicalizer.canonicalPathKey(for: path) + if canonicalPathByLexicalPath[path] == nil, + canonicalPathByLexicalPath.count < Self.maximumCanonicalAliasCount { canonicalPathByLexicalPath[path] = canonicalPath } let previous = byPath[canonicalPath] - byPath[canonicalPath] = ChatArtifactIndexedReference( + let candidateAuthorization = provenance.captureAuthorization(sequence: seq) + let captureAuthorization: ChatArtifactCaptureAuthorization? + if let previousAuthorization = previous?.captureAuthorization, + let candidateAuthorization { + captureAuthorization = previousAuthorization.latest(with: candidateAuthorization) + } else { + captureAuthorization = previous?.captureAuthorization ?? candidateAuthorization + } + let updated = ChatArtifactIndexedReference( path: canonicalPath, - provenance: Self.higherPrecedence(previous?.provenance, provenance), - lastReferencedSeq: max(previous?.lastReferencedSeq ?? Int.min, seq) + provenance: previous?.provenance.preferred(over: provenance) ?? provenance, + lastReferencedSeq: max(previous?.lastReferencedSeq ?? Int.min, seq), + captureAuthorization: captureAuthorization ) + byPath[canonicalPath] = updated + recencyHeap.insert( + path: canonicalPath, + seq: updated.lastReferencedSeq, + evictionPriority: Self.evictionPriority(for: updated.provenance) + ) + while byPath.count > maximumPathCount { + guard let oldest = recencyHeap.pop() else { break } + guard let current = byPath[oldest.path], + current.lastReferencedSeq == oldest.seq, + Self.evictionPriority(for: current.provenance) == oldest.evictionPriority else { + continue + } + byPath.removeValue(forKey: oldest.path) + } + if recencyHeap.count > maximumPathCount * 4 { + recencyHeap.compact( + currentSequences: byPath.mapValues(\.lastReferencedSeq), + currentEvictionPriorities: byPath.mapValues { + Self.evictionPriority(for: $0.provenance) + } + ) + } } - private static func isFileMutationTool(_ toolName: String) -> Bool { - let normalized = toolName.split(separator: ".").last.map(String.init) ?? toolName - return normalized.lowercased() == "apply_patch" - } - - private static func higherPrecedence( - _ lhs: ChatArtifactProvenance?, - _ rhs: ChatArtifactProvenance - ) -> ChatArtifactProvenance { - guard let lhs else { return rhs } - return Self.rank(lhs) <= Self.rank(rhs) ? lhs : rhs - } - - private static func rank(_ provenance: ChatArtifactProvenance) -> Int { + private static func evictionPriority(for provenance: ChatArtifactProvenance) -> Int { switch provenance { - case .created: 0 + case .referenced: 0 case .attached: 1 - case .referenced: 2 + case .created: 2 } } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactLRUCache.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactLRUCache.swift index e45e6a2a397f..d7393bb92b4e 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactLRUCache.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactLRUCache.swift @@ -47,4 +47,10 @@ public struct ChatArtifactLRUCache: S entries.removeValue(forKey: leastRecent) } } + + /// Removes and returns one retained value without affecting other recency. + @discardableResult + public mutating func removeValue(forKey key: Key) -> Value? { + entries.removeValue(forKey: key)?.value + } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactProvenance.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactProvenance.swift index ff1a0affbe57..d046a12a2b56 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactProvenance.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactProvenance.swift @@ -11,4 +11,26 @@ public enum ChatArtifactProvenance: String, Sendable, Equatable, Codable, CaseIt let container = try decoder.singleValueContainer() self = (try? container.decode(String.self)).flatMap(Self.init(rawValue:)) ?? .referenced } + + /// Returns the provenance that grants stronger capture authority. + func preferred(over candidate: ChatArtifactProvenance) -> ChatArtifactProvenance { + capturePrecedence <= candidate.capturePrecedence ? self : candidate + } + + /// Converts capture-authorizing provenance into its sequence-bound grant. + func captureAuthorization(sequence: Int) -> ChatArtifactCaptureAuthorization? { + switch self { + case .created: .created(sequence: sequence) + case .attached: .attached(sequence: sequence) + case .referenced: nil + } + } + + private var capturePrecedence: Int { + switch self { + case .created: 0 + case .attached: 1 + case .referenced: 2 + } + } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeap.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeap.swift new file mode 100644 index 000000000000..fc2165e1ce77 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeap.swift @@ -0,0 +1,78 @@ +/// Bounded min-heap used to evict weak-provenance, least-recently referenced paths. +struct ChatArtifactRecencyHeap { + private var entries: [ChatArtifactRecencyHeapEntry] = [] + + var count: Int { entries.count } + + mutating func insert(path: String, seq: Int, evictionPriority: Int) { + entries.append(ChatArtifactRecencyHeapEntry( + path: path, + evictionPriority: evictionPriority, + seq: seq + )) + siftUp(from: entries.count - 1) + } + + mutating func pop() -> ChatArtifactRecencyHeapEntry? { + guard !entries.isEmpty else { return nil } + if entries.count == 1 { return entries.removeLast() } + let result = entries[0] + entries[0] = entries.removeLast() + siftDown(from: 0) + return result + } + + mutating func compact( + currentSequences: [String: Int], + currentEvictionPriorities: [String: Int] + ) { + entries = currentSequences.map { + ChatArtifactRecencyHeapEntry( + path: $0.key, + evictionPriority: currentEvictionPriorities[$0.key] ?? 0, + seq: $0.value + ) + } + guard entries.count > 1 else { return } + for index in stride(from: entries.count / 2 - 1, through: 0, by: -1) { + siftDown(from: index) + } + } + + private func precedes( + _ lhs: ChatArtifactRecencyHeapEntry, + _ rhs: ChatArtifactRecencyHeapEntry + ) -> Bool { + if lhs.evictionPriority != rhs.evictionPriority { + return lhs.evictionPriority < rhs.evictionPriority + } + if lhs.seq != rhs.seq { return lhs.seq < rhs.seq } + return lhs.path < rhs.path + } + + private mutating func siftUp(from index: Int) { + var child = index + while child > 0 { + let parent = (child - 1) / 2 + guard precedes(entries[child], entries[parent]) else { return } + entries.swapAt(child, parent) + child = parent + } + } + + private mutating func siftDown(from index: Int) { + var parent = index + while true { + let left = parent * 2 + 1 + guard left < entries.count else { return } + var candidate = left + let right = left + 1 + if right < entries.count, precedes(entries[right], entries[left]) { + candidate = right + } + guard precedes(entries[candidate], entries[parent]) else { return } + entries.swapAt(parent, candidate) + parent = candidate + } + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeapEntry.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeapEntry.swift new file mode 100644 index 000000000000..30b656519550 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactRecencyHeapEntry.swift @@ -0,0 +1,7 @@ +/// One path/provenance/sequence entry in the artifact recency heap. +struct ChatArtifactRecencyHeapEntry { + let path: String + /// Lower values are weaker capture provenance and are evicted first. + let evictionPriority: Int + let seq: Int +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactSaveResult.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactSaveResult.swift new file mode 100644 index 000000000000..179b31fc5fc0 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactSaveResult.swift @@ -0,0 +1,23 @@ +import Foundation + +/// Stable project-local location returned after saving a chat artifact. +public struct ChatArtifactSaveResult: Codable, Equatable, Sendable { + /// Absolute path to the persisted artifact on the Mac. + public let path: String + /// Path relative to the project's `.cmux` filesystem. + public let relativePath: String + /// Prompt-ready project-relative reference. + public let reference: String + + /// Creates the location returned for a persisted chat artifact. + /// + /// - Parameters: + /// - path: Absolute path to the persisted file on the Mac. + /// - relativePath: Path relative to the project's `.cmux` filesystem. + /// - reference: Prompt-ready project-relative reference. + public init(path: String, relativePath: String, reference: String) { + self.path = path + self.relativePath = relativePath + self.reference = reference + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactStat.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactStat.swift index d2f7610687c6..34bb090c612a 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactStat.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatArtifactStat.swift @@ -14,6 +14,8 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { public let kind: ChatArtifactKind /// Best-effort MIME type inferred by the Mac, when known. public let mimeType: String? + /// Whether the Mac's effective project policy permits saving this file. + public let canSaveToArtifacts: Bool? /// Creates artifact metadata. /// @@ -24,13 +26,15 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { /// - modifiedAt: Last modification time. /// - kind: Preview category. /// - mimeType: Best-effort MIME type. + /// - canSaveToArtifacts: Effective Mac-side save eligibility, when supplied. public init( exists: Bool, isDirectory: Bool, size: Int64, modifiedAt: Date, kind: ChatArtifactKind, - mimeType: String? = nil + mimeType: String? = nil, + canSaveToArtifacts: Bool? = nil ) { self.exists = exists self.isDirectory = isDirectory @@ -38,6 +42,7 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { self.modifiedAt = modifiedAt self.kind = kind self.mimeType = mimeType + self.canSaveToArtifacts = canSaveToArtifacts } private enum CodingKeys: String, CodingKey { @@ -47,6 +52,7 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { case modifiedAt = "modified_at" case kind case mimeType = "mime_type" + case canSaveToArtifacts = "can_save_to_artifacts" } public init(from decoder: any Decoder) throws { @@ -61,6 +67,10 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { } kind = try container.decode(ChatArtifactKind.self, forKey: .kind) mimeType = try container.decodeIfPresent(String.self, forKey: .mimeType) + canSaveToArtifacts = try container.decodeIfPresent( + Bool.self, + forKey: .canSaveToArtifacts + ) } public func encode(to encoder: any Encoder) throws { @@ -71,5 +81,6 @@ public struct ChatArtifactStat: Sendable, Equatable, Codable { try container.encode(modifiedAt.timeIntervalSince1970, forKey: .modifiedAt) try container.encode(kind, forKey: .kind) try container.encodeIfPresent(mimeType, forKey: .mimeType) + try container.encodeIfPresent(canSaveToArtifacts, forKey: .canSaveToArtifacts) } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatToolUse+ArtifactMutation.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatToolUse+ArtifactMutation.swift new file mode 100644 index 000000000000..d1307a7c880a --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ChatToolUse+ArtifactMutation.swift @@ -0,0 +1,18 @@ +extension ChatToolUse { + /// Paths whose created provenance depends on a successful mutation result. + var artifactMutationPaths: [String] { + guard isArtifactMutation else { return [] } + return referencedPaths ?? [] + } + + /// Whether this completed tool invocation authorizes created provenance. + var authorizesCreatedArtifactProvenance: Bool { + guard isArtifactMutation else { return false } + return artifactMutationAuthorized == true + } + + private var isArtifactMutation: Bool { + let normalized = toolName.split(separator: ".").last.map(String.init) ?? toolName + return normalized.lowercased() == "apply_patch" + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/PanelArtifactAuthorizationStore.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/PanelArtifactAuthorizationStore.swift index 843edeb85a78..209ba5d811a9 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/PanelArtifactAuthorizationStore.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/PanelArtifactAuthorizationStore.swift @@ -10,6 +10,7 @@ public final class PanelArtifactAuthorizationStore { private let resolver: any ChatArtifactScope.FileSystemResolving private var canonicalPathByGrantKey: [GrantKey: String] = [:] + private var identityByGrantKey: [GrantKey: ChatArtifactFileIdentity] = [:] /// Creates a lifecycle-bound panel grant registry. /// @@ -44,9 +45,20 @@ public final class PanelArtifactAuthorizationStore { resolver: resolver ) else { canonicalPathByGrantKey.removeValue(forKey: key) + identityByGrantKey.removeValue(forKey: key) return nil } canonicalPathByGrantKey[key] = canonicalPath + if let identity = try? ArtifactByteReader().identity( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath + ) { + identityByGrantKey[key] = identity + } else { + // Keep the legacy path grant for injected/test resolvers, but make + // production reads recapture and verify identity before use. + identityByGrantKey.removeValue(forKey: key) + } return canonicalPath } @@ -59,6 +71,9 @@ public final class PanelArtifactAuthorizationStore { canonicalPathByGrantKey.removeValue( forKey: GrantKey(workspaceID: workspaceID, surfaceID: surfaceID) ) + identityByGrantKey.removeValue( + forKey: GrantKey(workspaceID: workspaceID, surfaceID: surfaceID) + ) } /// Resolves a request only when it canonicalizes to the panel's one-file grant. @@ -86,6 +101,35 @@ public final class PanelArtifactAuthorizationStore { return requestedCanonicalPath } + /// Returns the device/inode captured when a panel path was granted. + /// + /// A missing identity means the grant was created by a compatibility or + /// injected resolver that could not inspect the path; callers must then + /// recapture identity immediately before the operation and still verify it + /// at the descriptor boundary. + /// + /// - Parameters: + /// - workspaceID: Workspace containing the panel. + /// - surfaceID: Panel authorizing the request. + /// - requestedPath: Absolute path requested by the mobile client. + /// - Returns: Captured device/inode identity, when available. + public func authorizedIdentity( + workspaceID: String, + surfaceID: String, + requestedPath: String + ) -> ChatArtifactFileIdentity? { + let key = GrantKey(workspaceID: workspaceID, surfaceID: surfaceID) + guard let grantedPath = canonicalPathByGrantKey[key], + let requestedCanonicalPath = ChatArtifactScope.canonicalizedPath( + requestedPath, + resolver: resolver + ), + requestedCanonicalPath == grantedPath else { + return nil + } + return identityByGrantKey[key] + } + /// Resolves a request only when both the live panel path and request still /// canonicalize to the recorded grant. /// @@ -110,8 +154,8 @@ public final class PanelArtifactAuthorizationStore { let key = GrantKey(workspaceID: workspaceID, surfaceID: surfaceID) guard let grantedPath = canonicalPathByGrantKey[key], let currentCanonicalPath = ChatArtifactScope.canonicalizedPath( - currentFilePath, - resolver: resolver + currentFilePath, + resolver: resolver ), currentCanonicalPath == grantedPath, let requestedCanonicalPath = ChatArtifactScope.canonicalizedPath( @@ -123,4 +167,30 @@ public final class PanelArtifactAuthorizationStore { } return requestedCanonicalPath } + + /// Returns the captured identity when the live panel and request still + /// match the recorded path grant. + public func authorizedIdentity( + workspaceID: String, + surfaceID: String, + currentFilePath: String, + requestedPath: String + ) -> ChatArtifactFileIdentity? { + let key = GrantKey(workspaceID: workspaceID, surfaceID: surfaceID) + guard let grantedPath = canonicalPathByGrantKey[key], + let identity = identityByGrantKey[key], + let currentCanonicalPath = ChatArtifactScope.canonicalizedPath( + currentFilePath, + resolver: resolver + ), + currentCanonicalPath == grantedPath, + let requestedCanonicalPath = ChatArtifactScope.canonicalizedPath( + requestedPath, + resolver: resolver + ), + requestedCanonicalPath == grantedPath else { + return nil + } + return identity + } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationPathDetector.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationPathDetector.swift new file mode 100644 index 000000000000..777de59ba895 --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationPathDetector.swift @@ -0,0 +1,243 @@ +import Foundation + +/// Identifies shell redirection targets without guessing command-specific flag semantics. +public struct ShellArtifactMutationPathDetector: Sendable { + /// Creates a stateless shell mutation-path detector. + public init() {} + + func paths(in command: String) -> [String] { + let tokens = tokenize(command) + return paths(in: tokens) + } + + /// Returns output-redirection targets attributable to one successful shell command. + /// + /// - Parameter command: Shell command text from a successful tool execution. + /// - Returns: Normalized output paths, or an empty array when attribution is ambiguous. + public func pathsAttributedToSuccessfulCommand(in command: String) -> [String] { + let tokens = tokenize(command) + guard !tokens.contains(where: { token in + if case .boundary = token { return true } + return false + }), !containsCompoundGrouping(command) else { + return [] + } + return paths(in: tokens) + } + + private func paths(in tokens: [ShellArtifactMutationToken]) -> [String] { + var paths: [String] = [] + var seen: Set = [] + + func append(_ raw: String?) { + guard let raw, let path = normalizedPath(raw), seen.insert(path).inserted else { + return + } + paths.append(path) + } + + for index in tokens.indices { + switch tokens[index] { + case .outputRedirect: + append(nextWord(after: index, in: tokens)) + case .duplicateRedirect: + guard let target = nextWord(after: index, in: tokens), + !target.allSatisfy(\.isNumber) else { + continue + } + append(target) + case .word, .appendRedirect, .readWriteRedirect, .boundary: + break + } + } + + return paths + } + + private func containsCompoundGrouping(_ command: String) -> Bool { + var quote: Character? + var escaped = false + let characters = Array(command) + var index = 0 + while index < characters.count { + let character = characters[index] + if escaped { + escaped = false + index += 1 + continue + } + if character == "\\", quote != "'" { + escaped = true + index += 1 + continue + } + if let activeQuote = quote { + if activeQuote != "'" && character == "`" { + return true + } + if character == activeQuote { quote = nil } + index += 1 + continue + } + if character == "'" || character == "\"" { + quote = character + } else if character == "`" { + return true + } else if character == "[", characters[safe: index + 1] == "[" { + return true + } else if "(){}".contains(character) { + return true + } + index += 1 + } + return false + } + + private func tokenize(_ command: String) -> [ShellArtifactMutationToken] { + var tokens: [ShellArtifactMutationToken] = [] + var word = "" + var quote: Character? + var escaped = false + let characters = Array(command) + var index = 0 + + func flushWord() { + guard !word.isEmpty else { return } + tokens.append(.word(word)) + word = "" + } + + while index < characters.count { + let character = characters[index] + if escaped { + word.append(character) + escaped = false + index += 1 + continue + } + if character == "\\", quote != "'" { + escaped = true + index += 1 + continue + } + if let activeQuote = quote { + if character == activeQuote { + quote = nil + } else { + word.append(character) + } + index += 1 + continue + } + if character == "'" || character == "\"" { + quote = character + index += 1 + continue + } + if character == "#", word.isEmpty { + while index < characters.count, characters[index] != "\n" { + index += 1 + } + if index < characters.count { + if tokens.last != .boundary { tokens.append(.boundary) } + index += 1 + } + continue + } + if character.isWhitespace { + flushWord() + if character == "\n" { tokens.append(.boundary) } + index += 1 + continue + } + if character == "<", characters[safe: index + 1] == ">" { + flushWord() + tokens.append(.readWriteRedirect) + index += 2 + continue + } + if character == ">" { + flushWord() + if characters[safe: index + 1] == "&" { + tokens.append(.duplicateRedirect) + index += 2 + } else if characters[safe: index + 1] == ">" { + tokens.append(.appendRedirect) + index += 2 + } else { + tokens.append(.outputRedirect) + index += 1 + } + continue + } + if character == "&", characters[safe: index + 1] == ">" { + flushWord() + if characters[safe: index + 2] == ">" { + tokens.append(.appendRedirect) + index += 3 + } else { + tokens.append(.outputRedirect) + index += 2 + } + continue + } + if character == ";" || character == "|" || character == "&" { + flushWord() + if tokens.last != .boundary { tokens.append(.boundary) } + index += characters[safe: index + 1] == character ? 2 : 1 + continue + } + word.append(character) + index += 1 + } + if escaped { word.append("\\") } + flushWord() + return tokens + } + + private func nextWord( + after index: Int, + in tokens: [ShellArtifactMutationToken] + ) -> String? { + guard index + 1 < tokens.count else { return nil } + for token in tokens[(index + 1)...] { + switch token { + case .word(let word): return word + case .outputRedirect: continue + case .appendRedirect, .readWriteRedirect, .duplicateRedirect: return nil + case .boundary: return nil + } + } + return nil + } + + private func normalizedPath(_ raw: String) -> String? { + let path: String + if raw.hasPrefix("file://"), let url = URL(string: raw), url.isFileURL { + path = url.path + } else { + path = raw + } + guard !path.isEmpty, + path != "-", + path != "/dev/null", + !path.contains("\n"), + !path.contains("\0"), + !path.contains("$"), + path.hasPrefix("/") + || path.hasPrefix("./") + || path.hasPrefix("../") + || path.hasPrefix("~/") + || path.contains("/") + || !URL(fileURLWithPath: path).pathExtension.isEmpty else { + return nil + } + return path + } +} + +private extension Array { + subscript(safe index: Index) -> Element? { + indices.contains(index) ? self[index] : nil + } +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationToken.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationToken.swift new file mode 100644 index 000000000000..205c26cac69d --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/ShellArtifactMutationToken.swift @@ -0,0 +1,9 @@ +/// One lexical shell token relevant to artifact mutation detection. +enum ShellArtifactMutationToken: Equatable { + case word(String) + case outputRedirect + case appendRedirect + case readWriteRedirect + case duplicateRedirect + case boundary +} diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactAuthorizationStore.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactAuthorizationStore.swift index f07d764260ab..a50644796188 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactAuthorizationStore.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactAuthorizationStore.swift @@ -5,6 +5,7 @@ public actor TerminalArtifactAuthorizationStore { private typealias Generation = ( ordinal: UInt64, canonicalPaths: Set, + identities: [String: ChatArtifactFileIdentity], expiresAt: Date ) @@ -37,11 +38,14 @@ public actor TerminalArtifactAuthorizationStore { /// - workspaceID: Workspace containing the scanned terminal. /// - surfaceID: Scanned terminal surface. /// - canonicalPaths: Canonical paths returned to the listing client. + /// - identities: Device/inode identities captured with the scan. Paths + /// without an identity are retained for display but cannot be read. /// - date: Scan completion time. public func record( workspaceID: String, surfaceID: String, canonicalPaths: Set, + identities: [String: ChatArtifactFileIdentity] = [:], at date: Date = Date() ) { purgeExpired(at: date) @@ -52,6 +56,7 @@ public actor TerminalArtifactAuthorizationStore { generations.append(( ordinal: ordinal, canonicalPaths: canonicalPaths, + identities: identities.filter { canonicalPaths.contains($0.key) }, expiresAt: date.addingTimeInterval(timeToLive) )) if generations.count > maximumGenerationsPerSurface { @@ -83,6 +88,37 @@ public actor TerminalArtifactAuthorizationStore { } } + /// Returns unexpired path identities from retained terminal scans. + /// + /// Newer generations win when the same canonical path appears more than + /// once. Callers must carry the returned identity into every later read. + /// + /// - Parameters: + /// - workspaceID: Workspace containing the terminal. + /// - surfaceID: Terminal surface being read. + /// - date: Read time used for deterministic expiry. + /// - Returns: Device/inode identities keyed by canonical path. + public func authorizedIdentities( + workspaceID: String, + surfaceID: String, + at date: Date = Date() + ) -> [String: ChatArtifactFileIdentity] { + purgeExpired(at: date) + let key = surfaceKey(workspaceID: workspaceID, surfaceID: surfaceID) + guard let generations = generationsBySurfaceKey[key] else { return [:] } + lastAccessBySurfaceKey[key] = date + var seenPaths: Set = [] + var result: [String: ChatArtifactFileIdentity] = [:] + for generation in generations.reversed() { + for path in generation.canonicalPaths where seenPaths.insert(path).inserted { + if let identity = generation.identities[path] { + result[path] = identity + } + } + } + return result + } + private func surfaceKey(workspaceID: String, surfaceID: String) -> String { "\(workspaceID)\u{0}\(surfaceID)" } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactPathDetector.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactPathDetector.swift index 91f36f955f74..8d3a9325bebc 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactPathDetector.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Artifacts/TerminalArtifactPathDetector.swift @@ -5,6 +5,8 @@ import Foundation /// Input may include VT escape sequences, such as those emitted by a terminal /// screen export. Escape sequences are removed before path tokenization. public struct TerminalArtifactPathDetector: Sendable { + /// Maximum distinct paths returned by one bounded extraction pass. + public static let defaultMaximumPathCount = 1_024 private enum EscapeScanState { case text case escape @@ -30,11 +32,39 @@ public struct TerminalArtifactPathDetector: Sendable { /// Returns unique path-like tokens in display order. public func paths(in text: String) -> [String] { + paths(in: text, maximumCount: Self.defaultMaximumPathCount) + } + + /// Returns at most `maximumCount` unique path-like tokens in display order. + /// The bounded pass stops before retaining an unbounded token array. + public func paths(in text: String, maximumCount: Int) -> [String] { + let limit = max(0, maximumCount) + guard limit > 0 else { return [] } var seen: Set = [] var result: [String] = [] - for token in tokens(in: text) where !seen.contains(token.path) { - seen.insert(token.path) - result.append(token.path) + let stripped = Self.strippingTerminalEscapeSequences(text) + var tokenStart: String.Index? + var index = stripped.startIndex + while index < stripped.endIndex, result.count < limit { + let character = stripped[index] + if character.isWhitespace { + if let tokenStart { + let candidate = Self.trimmedCandidate(String(stripped[tokenStart.. = ["file_path", "notebook_path", "path"] + /// Maximum number of distinct structured paths retained from one tool + /// input. The bound is enforced while walking the JSON tree so a hostile + /// array cannot first materialize an unbounded intermediate path list. + static let maximumPathCount = 1_024 + /// Maximum UTF-8 size of one retained path, matching the artifact scope's + /// lexical path ceiling. + static let maximumPathBytes = 4_096 + /// Maximum aggregate UTF-8 size of paths retained for one tool input. + static let maximumAggregatePathBytes = 64 * 1_024 - func referencedPaths(in value: TranscriptJSONValue?) -> [String]? { + func referencedPaths( + in value: TranscriptJSONValue?, + maximumCount: Int = Self.maximumPathCount, + maximumBytes: Int = Self.maximumAggregatePathBytes + ) -> [String]? { guard let value else { return nil } + let limit = min(maximumCount, Self.maximumPathCount) + let byteLimit = min(maximumBytes, Self.maximumAggregatePathBytes) + guard limit > 0, byteLimit > 0 else { return nil } var paths: [String] = [] - appendReferencedPaths(in: value, key: nil, into: &paths) - let deduplicated = deduplicated(paths) - return deduplicated.isEmpty ? nil : deduplicated + paths.reserveCapacity(limit) + var seen: Set = [] + seen.reserveCapacity(limit) + var retainedBytes = 0 + _ = appendReferencedPaths( + in: value, + key: nil, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: limit, + maximumBytes: byteLimit + ) + return paths.isEmpty ? nil : paths } + /// Returns a bounded, first-seen unique copy of already extracted paths. + /// This protects parser carry-over and decoded legacy values in addition + /// to the streaming JSON walk above. + func boundedPaths( + _ paths: [String]?, + maximumCount: Int = Self.maximumPathCount, + maximumBytes: Int = Self.maximumAggregatePathBytes + ) -> [String]? { + guard let paths else { return nil } + let limit = min(maximumCount, Self.maximumPathCount) + let byteLimit = min(maximumBytes, Self.maximumAggregatePathBytes) + guard limit > 0, byteLimit > 0 else { return nil } + var bounded: [String] = [] + bounded.reserveCapacity(min(paths.count, limit)) + var seen: Set = [] + seen.reserveCapacity(min(paths.count, limit)) + var retainedBytes = 0 + for path in paths { + if append( + path, + into: &bounded, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: limit, + maximumBytes: byteLimit + ) { + break + } + } + return bounded.isEmpty ? nil : bounded + } + + @discardableResult private func appendReferencedPaths( in value: TranscriptJSONValue, key: String?, - into paths: inout [String] - ) { + into paths: inout [String], + seen: inout Set, + retainedBytes: inout Int, + maximumCount: Int, + maximumBytes: Int + ) -> Bool { + guard paths.count < maximumCount, retainedBytes < maximumBytes else { return true } if let key, Self.pathKeys.contains(key) { - appendStringValues(in: value, into: &paths) - return + return appendStringValues( + in: value, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) } switch value { case .object(let object): for (childKey, childValue) in object { - appendReferencedPaths(in: childValue, key: childKey, into: &paths) + if appendReferencedPaths( + in: childValue, + key: childKey, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) { + return true + } } case .array(let array): for item in array { - appendReferencedPaths(in: item, key: nil, into: &paths) + if appendReferencedPaths( + in: item, + key: nil, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) { + return true + } } case .string(let string): let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines) if Self.isAbsolutePathValue(trimmed), !trimmed.contains(where: \.isWhitespace) { - paths.append(trimmed) + return append( + trimmed, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) } case .number, .bool, .null: - return + break } + return paths.count >= maximumCount || retainedBytes >= maximumBytes } - private func appendStringValues(in value: TranscriptJSONValue, into paths: inout [String]) { + @discardableResult + private func appendStringValues( + in value: TranscriptJSONValue, + into paths: inout [String], + seen: inout Set, + retainedBytes: inout Int, + maximumCount: Int, + maximumBytes: Int + ) -> Bool { + guard paths.count < maximumCount, retainedBytes < maximumBytes else { return true } switch value { case .string(let string): let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { - paths.append(trimmed) + return append( + trimmed, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) } case .array(let array): for item in array { - appendStringValues(in: item, into: &paths) + if appendStringValues( + in: item, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) { + return true + } } case .object(let object): for child in object.values { - appendStringValues(in: child, into: &paths) + if appendStringValues( + in: child, + into: &paths, + seen: &seen, + retainedBytes: &retainedBytes, + maximumCount: maximumCount, + maximumBytes: maximumBytes + ) { + return true + } } case .number, .bool, .null: - return + break } + return paths.count >= maximumCount || retainedBytes >= maximumBytes } - private func deduplicated(_ paths: [String]) -> [String] { - var seen: Set = [] - var result: [String] = [] - for path in paths where !seen.contains(path) { - seen.insert(path) - result.append(path) - } - return result + private func append( + _ path: String, + into paths: inout [String], + seen: inout Set, + retainedBytes: inout Int, + maximumCount: Int, + maximumBytes: Int + ) -> Bool { + guard paths.count < maximumCount, retainedBytes < maximumBytes else { return true } + guard !seen.contains(path) else { return false } + let pathBytes = path.utf8.count + guard pathBytes <= Self.maximumPathBytes else { return false } + guard pathBytes <= maximumBytes - retainedBytes else { return true } + seen.insert(path) + paths.append(path) + retainedBytes += pathBytes + return paths.count >= maximumCount || retainedBytes >= maximumBytes } private static func isAbsolutePathValue(_ value: String) -> Bool { diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ChatTranscriptParseState.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ChatTranscriptParseState.swift index 93aee2aa54ae..00049dd5f96f 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ChatTranscriptParseState.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ChatTranscriptParseState.swift @@ -18,6 +18,9 @@ public struct ChatTranscriptParseState: Sendable, Equatable, Codable { /// ``ChatTranscriptParseResult/updatedMessages``. public var pendingToolUses: [String: [ChatMessage]] + /// Sidechain mutation targets awaiting a result, keyed by tool call ID. + public var pendingArtifactMutations: [String: [ChatArtifactTranscriptReference]] + /// Timestamp of the last line that carried one, used as the fallback /// for subsequent lines that omit a timestamp. public var lastTimestamp: Date? @@ -27,14 +30,43 @@ public struct ChatTranscriptParseState: Sendable, Equatable, Codable { /// - Parameters: /// - pendingToolUses: Tool invocations awaiting a result, keyed by /// tool call identifier. + /// - pendingArtifactMutations: Sidechain mutation targets awaiting a result. /// - lastTimestamp: Timestamp fallback for lines without one. - public init(pendingToolUses: [String: [ChatMessage]] = [:], lastTimestamp: Date? = nil) { + public init( + pendingToolUses: [String: [ChatMessage]] = [:], + pendingArtifactMutations: [String: [ChatArtifactTranscriptReference]] = [:], + lastTimestamp: Date? = nil + ) { self.pendingToolUses = pendingToolUses + self.pendingArtifactMutations = pendingArtifactMutations self.lastTimestamp = lastTimestamp } private enum CodingKeys: String, CodingKey { case pendingToolUses = "pending_tool_uses" + case pendingArtifactMutations = "pending_artifact_mutations" case lastTimestamp = "last_timestamp" } + + /// Decodes carry-over state while preserving compatibility with older state payloads. + public init(from decoder: any Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + pendingToolUses = try values.decodeIfPresent( + [String: [ChatMessage]].self, + forKey: .pendingToolUses + ) ?? [:] + pendingArtifactMutations = try values.decodeIfPresent( + [String: [ChatArtifactTranscriptReference]].self, + forKey: .pendingArtifactMutations + ) ?? [:] + lastTimestamp = try values.decodeIfPresent(Date.self, forKey: .lastTimestamp) + } + + /// Encodes all parse carry-over state. + public func encode(to encoder: any Encoder) throws { + var values = encoder.container(keyedBy: CodingKeys.self) + try values.encode(pendingToolUses, forKey: .pendingToolUses) + try values.encode(pendingArtifactMutations, forKey: .pendingArtifactMutations) + try values.encodeIfPresent(lastTimestamp, forKey: .lastTimestamp) + } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ClaudeTranscriptParser.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ClaudeTranscriptParser.swift index e0579dae7194..9e6c28b1366a 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ClaudeTranscriptParser.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/ClaudeTranscriptParser.swift @@ -162,14 +162,31 @@ public struct ClaudeTranscriptParser: Sendable { if let output { assembler.appendArtifactReferences(paths: artifactText.paths(in: output), seq: seq) } - let isError = block["is_error"]?.bool ?? false + // Keep the distinction between an explicit `false` and a missing + // flag. Mutation provenance requires positive success evidence, so a + // missing Claude error flag must not be treated as success. + let isError = block["is_error"]?.bool + let exitCode = parsedExitCode(from: output) assembler.resolve( key: callID, completion: TranscriptToolCompletion( output: output, isError: isError, - exitCode: parsedExitCode(from: output) - ) + exitCode: exitCode, + authorizesArtifactMutation: TranscriptToolCompletion.authorizesMutation( + output: output, + isError: isError, + exitCode: exitCode + ), + // Display status may use a non-empty, non-failure result even + // when Claude omitted `is_error`; mutation authorization above + // remains fail-closed until the explicit false flag arrives. + hasPositiveSuccessEvidence: output.map { + !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + && !TranscriptToolCompletion.reportsFailureWithoutExitStatus($0) + } ?? false + ), + resultSeq: seq ) } @@ -425,24 +442,28 @@ public struct ClaudeTranscriptParser: Sendable { guard let content = root["message"]?["content"] else { return } if root["type"]?.string == "user" { for block in content.array ?? [] where block["type"]?.string == "tool_result" { - if let output = resultText(from: block["content"]) { - assembler.appendArtifactReferences( - paths: artifactText.paths(in: output), - seq: seq - ) - } + resolveToolResult(block, seq: seq, into: &assembler) } return } guard root["type"]?.string == "assistant" else { return } for block in content.array ?? [] where block["type"]?.string == "tool_use" { guard let toolName = block["name"]?.string else { continue } + let callID = block["id"]?.string let input = block["input"] if toolName == "Bash", let command = input?["command"]?.string { assembler.appendArtifactReferences( paths: artifactText.paths(in: command), seq: seq ) + if let callID { + assembler.registerArtifactMutation( + paths: ShellArtifactMutationPathDetector() + .pathsAttributedToSuccessfulCommand(in: command), + pendingKey: callID, + seq: seq + ) + } } let paths = referencedPaths.referencedPaths(in: input) ?? [] if Self.isMutationTool(toolName) { @@ -450,11 +471,15 @@ public struct ClaudeTranscriptParser: Sendable { input?["file_path"]?.string, input?["notebook_path"]?.string, ].compactMap { $0 }) - assembler.appendArtifactReferences( - paths: paths.filter { targets.contains($0) }, - provenance: .created, - seq: seq - ) + let mutationTargets = paths.filter { targets.contains($0) } + assembler.appendArtifactReferences(paths: mutationTargets, seq: seq) + if let callID { + assembler.registerArtifactMutation( + paths: mutationTargets, + pendingKey: callID, + seq: seq + ) + } assembler.appendArtifactReferences( paths: paths.filter { !targets.contains($0) }, seq: seq diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser+ToolOutput.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser+ToolOutput.swift index 07d5845e7ad0..b42fc7533a7c 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser+ToolOutput.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser+ToolOutput.swift @@ -32,9 +32,21 @@ extension CodexTranscriptParser { return deduplicatedPaths(paths) } - func deduplicatedPaths(_ paths: [String]) -> [String] { + func deduplicatedPaths( + _ paths: [String], + maximumCount: Int = ChatToolReferencedPathExtractor.maximumPathCount + ) -> [String] { var seen: Set = [] - return paths.filter { !$0.isEmpty && seen.insert($0).inserted } + let limit = min(maximumCount, ChatToolReferencedPathExtractor.maximumPathCount) + guard limit > 0 else { return [] } + var result: [String] = [] + result.reserveCapacity(min(paths.count, limit)) + for path in paths { + guard !path.isEmpty, seen.insert(path).inserted else { continue } + result.append(path) + if result.count == limit { break } + } + return result } static func isApplyPatchTool(_ name: String) -> Bool { @@ -54,11 +66,15 @@ extension CodexTranscriptParser { into assembler: inout TranscriptBatchAssembler ) { guard let callID = payload["call_id"]?.string else { return } - let completion = completion(from: payload["output"]) + let isCustomToolOutput = payload["type"]?.string == "custom_tool_call_output" + let completion = completion( + from: payload["output"], + allowsTextualMutationEvidence: !isCustomToolOutput + ) if let output = completion.output { assembler.appendArtifactReferences(paths: artifactText.paths(in: output), seq: seq) } - assembler.resolve(key: callID, completion: completion) + assembler.resolve(key: callID, completion: completion, resultSeq: seq) } /// Builds a completion from an output payload, which is a plain string, @@ -66,15 +82,20 @@ extension CodexTranscriptParser { /// string, or that object inline; exit code and wall time also appear /// as text headers (`Process exited with code N`, `Exit code: N`, /// `Wall time: S seconds`). - private func completion(from value: TranscriptJSONValue?) -> TranscriptToolCompletion { + private func completion( + from value: TranscriptJSONValue?, + allowsTextualMutationEvidence: Bool + ) -> TranscriptToolCompletion { var text = outputText(from: value) - var exitCode = value?["metadata"]?["exit_code"]?.int + var structuredExitCode = value?["metadata"]?["exit_code"]?.int + var exitCode = structuredExitCode var duration = value?["metadata"]?["duration_seconds"]?.double if let raw = text, let nested = TranscriptJSONValue(jsonLine: raw), let inner = outputText(from: nested["output"]) { text = inner - exitCode = nested["metadata"]?["exit_code"]?.int ?? exitCode + structuredExitCode = nested["metadata"]?["exit_code"]?.int ?? structuredExitCode + exitCode = structuredExitCode duration = nested["metadata"]?["duration_seconds"]?.double ?? duration } if exitCode == nil, let text { @@ -91,12 +112,24 @@ extension CodexTranscriptParser { } return TranscriptToolCompletion( output: text, - isError: (exitCode ?? 0) != 0, + isError: exitCode.map { $0 != 0 }, exitCode: exitCode, - durationSeconds: duration + durationSeconds: duration, + authorizesArtifactMutation: authorizesArtifactMutation( + exitCode: allowsTextualMutationEvidence ? exitCode : structuredExitCode + ), + hasPositiveSuccessEvidence: exitCode != nil + || text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false ) } + private func authorizesArtifactMutation(exitCode: Int?) -> Bool { + // Free-form custom-tool text is not provider-authenticated success + // evidence. Only a structured zero exit code can grant Created + // provenance to a mutation path. + return exitCode == 0 + } + /// Extracts renderable output from strings, inline/nested output objects, /// and text-block arrays used by newer custom tool call records. private func outputText(from value: TranscriptJSONValue?) -> String? { diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser.swift index ed5322df0230..074be022ed2b 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/CodexTranscriptParser.swift @@ -299,7 +299,8 @@ public struct CodexTranscriptParser: Sendable { toolName: "apply_patch", summary: summary, status: .succeeded, - referencedPaths: paths.isEmpty ? nil : paths + referencedPaths: paths.isEmpty ? nil : paths, + artifactMutationAuthorized: true ) ) ) diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptBatchAssembler.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptBatchAssembler.swift index b2d9d66f1d21..1378302b7d86 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptBatchAssembler.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptBatchAssembler.swift @@ -8,6 +8,7 @@ struct TranscriptBatchAssembler { private var updatedMessages: [ChatMessage] = [] private var artifactReferences: [ChatArtifactTranscriptReference] = [] private var pending: [String: [ChatMessage]] + private var pendingArtifactMutations: [String: [ChatArtifactTranscriptReference]] private var batchIndexByMessageID: [String: Int] = [:] private let budget: TranscriptTextBudget @@ -18,6 +19,25 @@ struct TranscriptBatchAssembler { /// seq) bounds the carried state; dropping the oldest unresolved calls only /// means an extremely-late result (>N tool calls later) won't back-patch. static let maxPendingToolUses = 256 + /// Bound unresolved sidechain mutation references by both entry count and + /// UTF-8 bytes; a single malformed tool call must not retain an unbounded + /// path array across incremental parse calls. + static let maxPendingArtifactMutationReferences = 1_024 + static let maxPendingArtifactMutationBytes = 256 * 1_024 + static let maxArtifactMutationReferencesPerCall = 256 + /// Limit one registration so a single malformed tool call cannot consume + /// the entire cross-call mutation budget. + static let maxArtifactMutationBytesPerCall = 64 * 1_024 + /// Bound transcript-controlled tool-call identifiers carried between parses. + static let maxPendingArtifactMutationKeyBytes = 4_096 + static let maxArtifactMutationPathBytes = 4_096 + static let maxArtifactReferenceCount = 4_096 + static let maxArtifactReferenceBytes = 512 * 1_024 + /// Bound the path payload retained by unresolved ordinary tool calls. The + /// per-message extractor limit is smaller than the cross-call budget so a + /// burst of malformed calls cannot retain megabytes in `pendingToolUses`. + static let maxPendingToolUsePathBytes = 256 * 1_024 + static let maxPendingToolUseKeyBytes = 4_096 /// Creates an assembler seeded with carried-over pending tool uses. /// @@ -26,7 +46,12 @@ struct TranscriptBatchAssembler { /// - budget: The text budget applied to completed outputs. init(state: ChatTranscriptParseState, budget: TranscriptTextBudget) { self.pending = state.pendingToolUses + self.pendingArtifactMutations = state.pendingArtifactMutations self.budget = budget + // Sanitize persisted carry-over before the next parse line can add + // more state; malformed state must never exist unbounded in memory. + self.pending = bounded(self.pending) + self.pendingArtifactMutations = bounded(self.pendingArtifactMutations) } /// Appends a newly parsed message, optionally registering it as a tool @@ -37,6 +62,7 @@ struct TranscriptBatchAssembler { /// - pendingKey: The tool call identifier to pair a later result by, /// or `nil` for messages that never receive results. mutating func append(_ message: ChatMessage, pendingKey: String? = nil) { + let message = bounded(message) if let pendingKey { // A single tool call can register multiple messages (a // multi-question AskUserQuestion emits one card per question); @@ -58,9 +84,52 @@ struct TranscriptBatchAssembler { provenance: ChatArtifactProvenance = .referenced, seq: Int ) { - artifactReferences.append(contentsOf: paths.map { - ChatArtifactTranscriptReference(path: $0, provenance: provenance, seq: seq) - }) + for path in paths { + let bytes = path.utf8.count + guard !path.isEmpty, + bytes <= Self.maxArtifactMutationPathBytes else { continue } + artifactReferences.append(ChatArtifactTranscriptReference( + path: path, + provenance: provenance, + seq: seq + )) + } + trimArtifactReferences() + } + + /// Registers sidechain mutation targets without exposing sidechain messages. + mutating func registerArtifactMutation(paths: [String], pendingKey: String, seq: Int) { + guard !paths.isEmpty, + !pendingKey.isEmpty, + pendingKey.utf8.count <= Self.maxPendingArtifactMutationKeyBytes else { + return + } + var references: [ChatArtifactTranscriptReference] = [] + references.reserveCapacity(min(paths.count, Self.maxArtifactMutationReferencesPerCall)) + var bytes = 0 + for path in paths { + guard references.count < Self.maxArtifactMutationReferencesPerCall, + bytes < Self.maxArtifactMutationBytesPerCall else { + break + } + guard !path.isEmpty else { continue } + let pathBytes = path.utf8.count + guard pathBytes <= Self.maxArtifactMutationPathBytes else { continue } + guard pathBytes <= Self.maxArtifactMutationBytesPerCall - bytes else { + break + } + references.append(ChatArtifactTranscriptReference( + path: path, + provenance: .referenced, + seq: seq + )) + bytes += pathBytes + } + guard !references.isEmpty else { return } + pendingArtifactMutations[pendingKey] = references + // Enforce the global count/byte budget at insertion time, not only at + // the end of a whole transcript parse call. + pendingArtifactMutations = bounded(pendingArtifactMutations) } /// Pairs a tool result with its pending invocation, if registered. @@ -68,12 +137,31 @@ struct TranscriptBatchAssembler { /// - Parameters: /// - key: The tool call identifier from the result line. /// - completion: The observed result. - mutating func resolve(key: String, completion: TranscriptToolCompletion) { + mutating func resolve( + key: String, + completion: TranscriptToolCompletion, + resultSeq: Int + ) { + if let references = pendingArtifactMutations.removeValue(forKey: key), + completion.authorizesArtifactMutation { + appendArtifactReferences( + paths: references.map(\.path), + provenance: .created, + seq: resultSeq + ) + } guard let pendingMessages = pending.removeValue(forKey: key) else { return } // Apply to every message registered under this call id. For // questions, `completion.applied` resolves each by its own prompt, // so multi-question cards each get their correct answer. for pendingMessage in pendingMessages { + if completion.authorizesArtifactMutation { + appendArtifactReferences( + paths: mutationPaths(in: pendingMessage), + provenance: .created, + seq: resultSeq + ) + } guard let completed = completion.applied(to: pendingMessage, budget: budget) else { continue } @@ -95,21 +183,154 @@ struct TranscriptBatchAssembler { updatedMessages: updatedMessages, artifactReferences: artifactReferences, state: ChatTranscriptParseState( - pendingToolUses: Self.bounded(pending), + pendingToolUses: bounded(pending), + pendingArtifactMutations: bounded(pendingArtifactMutations), lastTimestamp: lastTimestamp ) ) } /// Caps carried pending tool uses to the most-recent ``maxPendingToolUses`` - /// by their newest message seq, evicting the oldest unresolved calls. - private static func bounded(_ pending: [String: [ChatMessage]]) -> [String: [ChatMessage]] { - guard pending.count > maxPendingToolUses else { return pending } - let newestFirst = pending.sorted { lhs, rhs in + /// by their newest message seq, evicting the oldest unresolved calls, and + /// caps the aggregate referenced-path bytes retained across those calls. + private func bounded(_ pending: [String: [ChatMessage]]) -> [String: [ChatMessage]] { + let newestFirst = pending.filter { + !$0.key.isEmpty && $0.key.utf8.count <= Self.maxPendingToolUseKeyBytes + }.sorted { lhs, rhs in (lhs.value.map(\.seq).max() ?? 0) > (rhs.value.map(\.seq).max() ?? 0) } - return Dictionary( - uniqueKeysWithValues: newestFirst.prefix(maxPendingToolUses).map { ($0.key, $0.value) } + var retainedPending: [String: [ChatMessage]] = [:] + retainedPending.reserveCapacity(min(newestFirst.count, Self.maxPendingToolUses)) + var retainedPathBytes = 0 + for (key, messages) in newestFirst { + guard retainedPending.count < Self.maxPendingToolUses else { break } + var retainedMessages: [ChatMessage] = [] + retainedMessages.reserveCapacity(messages.count) + for message in messages { + let remainingPathBytes = max( + 0, + Self.maxPendingToolUsePathBytes - retainedPathBytes + ) + let sanitized = bounded( + message, + maximumPathBytes: remainingPathBytes + ) + retainedMessages.append(sanitized) + retainedPathBytes += referencedPathBytes(in: sanitized) + } + retainedPending[key] = retainedMessages + } + return retainedPending + } + + /// Clamps one tool-use path payload before it enters either the visible + /// message batch or unresolved carry-over state. + private func bounded( + _ message: ChatMessage, + maximumPathBytes: Int = ChatToolReferencedPathExtractor.maximumAggregatePathBytes + ) -> ChatMessage { + guard case .toolUse(let toolUse) = message.kind else { return message } + let paths = ChatToolReferencedPathExtractor().boundedPaths( + toolUse.referencedPaths, + maximumBytes: maximumPathBytes + ) + guard paths != toolUse.referencedPaths else { return message } + let boundedToolUse = ChatToolUse( + toolName: toolUse.toolName, + summary: toolUse.summary, + inputDetail: toolUse.inputDetail, + output: toolUse.output, + status: toolUse.status, + referencedPaths: paths, + artifactMutationAuthorized: toolUse.artifactMutationAuthorized ) + return ChatMessage( + id: message.id, + seq: message.seq, + role: message.role, + timestamp: message.timestamp, + kind: .toolUse(boundedToolUse) + ) + } + + private func referencedPathBytes(in message: ChatMessage) -> Int { + guard case .toolUse(let toolUse) = message.kind else { return 0 } + return toolUse.referencedPaths?.reduce(0) { $0 + $1.utf8.count } ?? 0 + } + + private func bounded( + _ pending: [String: [ChatArtifactTranscriptReference]] + ) -> [String: [ChatArtifactTranscriptReference]] { + let newestFirst = pending.filter { + $0.key.utf8.count <= Self.maxPendingArtifactMutationKeyBytes + }.sorted { lhs, rhs in + (lhs.value.map(\.seq).max() ?? 0) > (rhs.value.map(\.seq).max() ?? 0) + } + var bounded: [String: [ChatArtifactTranscriptReference]] = [:] + var referenceCount = 0 + var byteCount = 0 + for (key, references) in newestFirst { + let keyBytes = key.utf8.count + guard keyBytes <= Self.maxPendingArtifactMutationBytes, + referenceCount < Self.maxPendingArtifactMutationReferences, + keyBytes <= Self.maxPendingArtifactMutationBytes - byteCount else { + continue + } + var retained: [ChatArtifactTranscriptReference] = [] + var retainedByteCount = keyBytes + for reference in references { + guard !reference.path.isEmpty else { continue } + let bytes = reference.path.utf8.count + guard bytes <= Self.maxArtifactMutationPathBytes else { continue } + guard referenceCount < Self.maxPendingArtifactMutationReferences else { + break + } + guard bytes <= Self.maxPendingArtifactMutationBytes - byteCount - retainedByteCount else { + break + } + retained.append(reference) + referenceCount += 1 + retainedByteCount += bytes + } + if !retained.isEmpty { + bounded[key] = retained + byteCount += retainedByteCount + } + } + return bounded + } + + private mutating func trimArtifactReferences() { + guard artifactReferences.count > Self.maxArtifactReferenceCount + || artifactReferences.reduce(0, { $0 + $1.path.utf8.count }) + > Self.maxArtifactReferenceBytes else { + return + } + var byteCount = artifactReferences.reduce(0) { $0 + $1.path.utf8.count } + var dropCount = 0 + while artifactReferences.count - dropCount > Self.maxArtifactReferenceCount + || byteCount > Self.maxArtifactReferenceBytes { + guard dropCount < artifactReferences.count else { break } + byteCount -= artifactReferences[dropCount].path.utf8.count + dropCount += 1 + } + if dropCount > 0 { + artifactReferences.removeFirst(dropCount) + } + } + + private func mutationPaths(in message: ChatMessage) -> [String] { + switch message.kind { + case .fileEdit(let edit): + return [edit.filePath] + case .toolUse(let toolUse): + return toolUse.artifactMutationPaths + case .terminal(let terminal): + return ShellArtifactMutationPathDetector() + .pathsAttributedToSuccessfulCommand(in: terminal.command) + case .prose, .thought, .permissionRequest, .question, + .status, .attachment, .unsupported: + return [] + } } } diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptToolCompletion.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptToolCompletion.swift index 9637e117f12e..b18d2cc1d929 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptToolCompletion.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Parsing/TranscriptToolCompletion.swift @@ -6,8 +6,9 @@ struct TranscriptToolCompletion: Sendable { /// The result text, already extracted from the transcript shape. let output: String? - /// Whether the transcript flagged the result as an error. - let isError: Bool + /// Whether the transcript flagged the result as an error, when it carried + /// an explicit flag. + let isError: Bool? /// The exit code, when one was parseable from the result. let exitCode: Int? @@ -15,23 +16,76 @@ struct TranscriptToolCompletion: Sendable { /// Wall-clock duration in seconds, when one was parseable. let durationSeconds: Double? + /// Whether source-specific positive evidence authorizes mutation provenance. + let authorizesArtifactMutation: Bool + + /// Whether the provider supplied positive completion evidence for display. + let hasPositiveSuccessEvidence: Bool + + /// Returns whether a tool result provides enough positive evidence to + /// authorize a file mutation. + /// + /// Claude must carry an explicit `is_error: false` flag before its output + /// can authorize a mutation. Textual exit-code headers are display data, + /// not provider-authenticated success evidence. An explicit success flag + /// also authorizes an intentionally empty result; missing flags still fail + /// closed. + static func authorizesMutation( + output: String?, + isError: Bool?, + exitCode: Int? + ) -> Bool { + if let exitCode { + return exitCode == 0 && isError == false + } + guard isError == false else { return false } + // Claude's explicit success flag is sufficient even when a command + // intentionally produces no stdout (for example, a shell redirect). + // Keep textual failure envelopes conservative when output exists. + guard let output else { return false } + guard !output.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return true + } + return !reportsFailureWithoutExitStatus(output) + } + + /// Whether the result proves the pending invocation completed successfully. + var succeeded: Bool { + // An explicit provider flag is authoritative for display. In + // particular, Claude's successful Grep result may legitimately say + // "No matches"; that text is only a failure heuristic when the + // provider omitted its status. Mutation authorization remains + // fail-closed in `authorizesMutation` below. + if let isError { + return !isError + } + if let exitCode { return exitCode == 0 } + if reportsFailureWithoutExitStatus { return false } + return hasPositiveSuccessEvidence + } + /// Creates a completion. /// /// - Parameters: /// - output: The extracted result text. - /// - isError: Whether the result was flagged as an error. + /// - isError: Whether the result was explicitly flagged as an error. /// - exitCode: The parsed exit code, when available. /// - durationSeconds: The parsed duration, when available. + /// - authorizesArtifactMutation: Whether the source proved a mutation succeeded. init( output: String?, - isError: Bool, + isError: Bool?, exitCode: Int? = nil, - durationSeconds: Double? = nil + durationSeconds: Double? = nil, + authorizesArtifactMutation: Bool, + hasPositiveSuccessEvidence: Bool = false ) { self.output = output self.isError = isError self.exitCode = exitCode self.durationSeconds = durationSeconds + self.authorizesArtifactMutation = authorizesArtifactMutation + self.hasPositiveSuccessEvidence = hasPositiveSuccessEvidence } /// Produces the completed copy of a pending tool message. @@ -47,20 +101,22 @@ struct TranscriptToolCompletion: Sendable { let completed = ChatTerminalCapture( command: capture.command, output: output.map { budget.body($0) }, - exitCode: exitCode ?? (isError ? 1 : 0), + exitCode: exitCode ?? (succeeded ? 0 : 1), durationSeconds: durationSeconds, isRunning: false ) return message.replacingKind(.terminal(completed)) case .toolUse(let toolUse): - let failed = isError || (exitCode ?? 0) != 0 let completed = ChatToolUse( toolName: toolUse.toolName, summary: toolUse.summary, inputDetail: toolUse.inputDetail, output: output.map { budget.body($0) }, - status: failed ? .failed : .succeeded, - referencedPaths: toolUse.referencedPaths + status: succeeded ? .succeeded : .failed, + referencedPaths: toolUse.referencedPaths, + artifactMutationAuthorized: toolUse.artifactMutationPaths.isEmpty + ? nil + : authorizesArtifactMutation ) return message.replacingKind(.toolUse(completed)) case .question(let question): @@ -139,6 +195,42 @@ struct TranscriptToolCompletion: Sendable { let answers = root["answers"] as? [String: Any] else { return nil } return answers.compactMapValues { $0 as? [String: Any] } } + + /// Some tools can report failure only in their text envelope. + static func reportsFailureWithoutExitStatus(_ output: String) -> Bool { + let prefix = output + .trimmingCharacters(in: .whitespacesAndNewlines) + .prefix(400) + .lowercased() + // Only provider-style prefixes are status evidence. The remainder of + // a transcript is arbitrary command output; scanning its lines for + // words such as "error" or "failed" mislabels valid grep/read data. + let firstLine = prefix.split(whereSeparator: \.isNewline).first ?? "" + return firstLine.hasPrefix("script failed") + || firstLine.hasPrefix("tool failed") + || firstLine.hasPrefix("apply_patch verification failed") + || firstLine.hasPrefix("error:") + || firstLine.hasPrefix("permission denied") + || firstLine.hasPrefix("access denied") + || firstLine.hasPrefix("operation not permitted") + || firstLine == "failed" + || firstLine.hasPrefix("failed:") + || firstLine.hasPrefix("failed to ") + || firstLine.hasPrefix("patch failed") + || firstLine == "failure" + || firstLine.hasPrefix("failure:") + || firstLine == "unable" + || firstLine.hasPrefix("unable to ") + || firstLine == "exception" + || firstLine.hasPrefix("exception:") + || firstLine == "no matches" + || firstLine.hasPrefix("no matches ") + } + + private var reportsFailureWithoutExitStatus: Bool { + guard let output else { return false } + return Self.reportsFailureWithoutExitStatus(output) + } } extension ChatMessage { diff --git a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Source/ChatEventSource.swift b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Source/ChatEventSource.swift index 0614046552f1..70b049ef6bc8 100644 --- a/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Source/ChatEventSource.swift +++ b/Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Source/ChatEventSource.swift @@ -8,6 +8,8 @@ public protocol ChatEventSource: Sendable { var supportsArtifacts: Bool { get } /// Whether this source supports recursive artifact folder browsing. var supportsArtifactFolders: Bool { get } + /// Whether referenced files can be persisted into project-local Artifacts. + var supportsArtifactSave: Bool { get } /// Fetches a page of transcript history for a session. /// @@ -117,6 +119,9 @@ public protocol ChatEventSource: Sendable { /// - path: Absolute Mac host directory path. /// - Returns: A capped directory listing. func artifactList(sessionID: String, path: String) async throws -> ChatArtifactDirectoryListing + + /// Persists a referenced file into the session project's artifact store. + func artifactSave(sessionID: String, path: String) async throws -> ChatArtifactSaveResult } public extension ChatEventSource { @@ -126,6 +131,9 @@ public extension ChatEventSource { /// Unsupported-by-default recursive artifact folder capability. var supportsArtifactFolders: Bool { false } + /// Unsupported-by-default project artifact-save capability. + var supportsArtifactSave: Bool { false } + /// Unsupported-by-default artifact stat implementation. func artifactStat(sessionID: String, path: String) async throws -> ChatArtifactStat { throw ChatArtifactError.unsupported @@ -171,4 +179,9 @@ public extension ChatEventSource { func artifactList(sessionID: String, path: String) async throws -> ChatArtifactDirectoryListing { throw ChatArtifactError.unsupported } + + /// Unsupported-by-default project artifact-save implementation. + func artifactSave(sessionID: String, path: String) async throws -> ChatArtifactSaveResult { + throw ChatArtifactError.unsupported + } } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactByteReaderTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactByteReaderTests.swift index 6196388406bc..fafd9576edd8 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactByteReaderTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactByteReaderTests.swift @@ -35,6 +35,163 @@ struct ArtifactByteReaderTests { } } + @Test("directory listings do not follow child symlinks") + func listingSkipsSymlinkChild() throws { + try withTemporaryDirectory { directory in + let outside = directory.deletingLastPathComponent() + .appendingPathComponent("cmux-artifact-list-outside-\(UUID().uuidString)") + try "private".write(to: outside, atomically: true, encoding: .utf8) + defer { try? FileManager.default.removeItem(at: outside) } + let link = directory.appendingPathComponent("linked.txt") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside) + + let listing = try ArtifactByteReader().list(path: directory.path) + + #expect(!listing.entries.contains { $0.name == link.lastPathComponent }) + } + } + + @Test("directory listings retain readable siblings beside special children") + func listingRetainsSiblingBesideFIFO() throws { + try withTemporaryDirectory { directory in + let fifo = directory.appendingPathComponent("pipe") + try #require(Darwin.mkfifo(fifo.path, 0o600) == 0) + let readable = directory.appendingPathComponent("readable.txt") + try Data("visible".utf8).write(to: readable) + + let listing = try ArtifactByteReader().list(path: directory.path) + + #expect(listing.entries.contains { $0.name == readable.lastPathComponent }) + #expect(listing.entries.first { $0.name == fifo.lastPathComponent }?.kind == .binary) + } + } + + @Test("symlink children do not consume the returnable-entry cap") + func symlinkChildrenDoNotConsumeEntryCap() throws { + try withTemporaryDirectory { directory in + let target = directory.appendingPathComponent("target.txt") + try Data("target".utf8).write(to: target) + for index in 0.. /tmp/claude-report.html"], + ]]) + let result = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "bash-render", + "content": "rendered", "is_error": false, + ]]) + + let parsed = ClaudeTranscriptParser().parse( + lines: [invocation, result], + startingSeq: 0 + ) + let artifact = try #require( + indexedArtifacts(parsed).first { $0.path.hasSuffix("/tmp/claude-report.html") } + ) + + #expect(artifact.provenance == .created) + #expect(artifact.captureAuthorization == .created(sequence: 1)) + } + + @Test("Claude success without a content field remains read-only") + func missingClaudeToolContentIsReference() throws { + let invocation = claudeLine(type: "assistant", content: [[ + "type": "tool_use", "id": "missing-content", "name": "Write", + "input": ["file_path": "/tmp/missing-content.md", "content": "draft"], + ]]) + let result = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "missing-content", "is_error": false, + ]]) + + let parsed = ClaudeTranscriptParser().parse( + lines: [invocation, result], + startingSeq: 0 + ) + let artifact = try #require(indexedArtifacts(parsed).first) + + #expect(artifact.provenance == .referenced) + #expect(artifact.captureAuthorization == nil) + } + + @Test("Failed Codex apply_patch remains a read-only reference") + func failedCodexPatchIsReference() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "apply_patch", + "arguments": #"{"patch":"*** Begin Patch\n*** Update File: generated.md\n@@\n-old\n+new\n*** End Patch"}"#, + "call_id": "patch", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "patch", + "output": "Exit code: 1\nOutput:\npermission denied", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.path == "/repo/generated.md") + #expect(artifact.provenance == .referenced) + } + + @Test("Codex custom-tool failure text without an exit status remains read-only") + func codexCustomToolFailureWithoutExitStatusIsReference() throws { + let patch = "*** Begin Patch\n*** Add File: /tmp/generated.md\n+draft\n*** End Patch" + let call = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call", + "name": "apply_patch", + "input": patch, + "call_id": "custom-patch", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call_output", + "call_id": "custom-patch", + "output": "Script failed\napply_patch verification failed: context did not match", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.path.hasSuffix("/tmp/generated.md")) + #expect(artifact.provenance == .referenced) + guard case .toolUse(let toolUse) = try #require(result.messages.first).kind else { + Issue.record("Expected a completed tool use") + return + } + #expect(toolUse.status == .failed) + } + + @Test("Codex custom-tool textual exit headers do not authorize mutations") + func codexCustomToolTextualExitHeaderIsReference() throws { + let patch = "*** Begin Patch\n*** Add File: /tmp/textual-exit.md\n+draft\n*** End Patch" + let call = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call", + "name": "apply_patch", + "input": patch, + "call_id": "custom-textual-exit", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call_output", + "call_id": "custom-textual-exit", + "output": "Exit code: 0\nOutput: success", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.provenance == .referenced) + #expect(artifact.captureAuthorization == nil) + } + + @Test("Unknown Codex custom-tool output does not authorize a mutation") + func unknownCodexCustomToolOutputIsReference() throws { + let patch = "*** Begin Patch\n*** Add File: /tmp/generated.md\n+draft\n*** End Patch" + let call = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call", + "name": "apply_patch", + "input": patch, + "call_id": "custom-patch", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "custom_tool_call_output", + "call_id": "custom-patch", + "output": "permission denied", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.path.hasSuffix("/tmp/generated.md")) + #expect(artifact.provenance == .referenced) + } + + @Test("Successful shell redirections are created but shell inputs remain references") + func successfulShellRedirectionClassifiesOnlyOutputTargetAsCreated() throws { + let renderCall = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"python3 render.py > /tmp/rendered.html"}"#, + "call_id": "render", + ]) + let renderOutput = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "render", + "output": "Process exited with code 0\nOutput:\nrender complete", + ]) + let readCall = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"cat /tmp/existing.md"}"#, + "call_id": "read", + ]) + let readOutput = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "read", + "output": "Process exited with code 0\nOutput:\nexisting contents", + ]) + + let result = CodexTranscriptParser().parse( + lines: [renderCall, renderOutput, readCall, readOutput], + startingSeq: 0 + ) + let artifacts = indexedArtifacts(result) + + #expect(artifacts.first { $0.path.hasSuffix("/tmp/rendered.html") }?.provenance == .created) + #expect(artifacts.first { $0.path.hasSuffix("/tmp/existing.md") }?.provenance == .referenced) + } + + @Test( + "Successful shell append redirections remain references", + arguments: [">>", "&>>"] + ) + func successfulShellAppendRedirectionFailsClosed(_ redirect: String) throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": json([ + "cmd": "true \(redirect) /Users/me/private.json", + ]), + "call_id": "append", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "append", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path == "/Users/me/private.json" } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Unexecuted compound-shell redirections remain references") + func compoundShellRedirectionFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"if false; then echo x > /tmp/report.md; fi"}"#, + "call_id": "conditional", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "conditional", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path.hasSuffix("/tmp/report.md") } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Backtick command substitutions remain references") + func backtickCommandSubstitutionFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": json([ + "cmd": "echo `false > /Users/me/private.md`", + ]), + "call_id": "backtick", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "backtick", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path == "/Users/me/private.md" } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Shell comparison operators do not authorize artifact mutations") + func shellConditionalComparisonFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"[[ z > /Users/me/private.md ]]"}"#, + "call_id": "comparison", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "comparison", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path == "/Users/me/private.md" } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Shell read-write redirection does not authorize artifact creation") + func shellReadWriteRedirectionFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"cat <> /Users/me/private.json"}"#, + "call_id": "read-write", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "read-write", + "output": "Process exited with code 0\nOutput:\nprivate contents", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path == "/Users/me/private.json" } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Shell comments do not authorize artifact mutations") + func shellCommentRedirectionFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"true # > /Users/me/private.json"}"#, + "call_id": "comment", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "comment", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifact = try #require( + indexedArtifacts(result).first { $0.path == "/Users/me/private.json" } + ) + + #expect(artifact.provenance == .referenced) + } + + @Test("Generic output flags do not authorize copying an external file") + func genericOutputFlagFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"true --output /Users/me/private.json"}"#, + "call_id": "true", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "true", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifacts = indexedArtifacts(result) + + #expect(artifacts.first { $0.path == "/Users/me/private.json" }?.provenance == .referenced) + #expect(artifacts.allSatisfy { $0.provenance == .referenced }) + } + + @Test("Option-bearing positional shell commands fail closed for mutation provenance") + func positionalShellCommandFailsClosed() throws { + let call = codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": #"{"cmd":"touch -r /Users/me/private.md /tmp/stamp.md"}"#, + "call_id": "touch", + ]) + let output = codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": "touch", + "output": "Process exited with code 0\nOutput:\n", + ]) + + let result = CodexTranscriptParser().parse(lines: [call, output], startingSeq: 0) + let artifacts = indexedArtifacts(result) + + #expect(artifacts.first { $0.path == "/Users/me/private.md" }?.provenance == .referenced) + #expect(artifacts.allSatisfy { $0.provenance == .referenced }) + } + + @Test("Failed sidechain mutations do not grant created provenance") + func failedSidechainMutationIsReference() throws { + let invocation = claudeLine(type: "assistant", content: [[ + "type": "tool_use", "id": "side-write", "name": "Write", + "input": ["file_path": "/tmp/side.md", "content": "draft"], + ]], isSidechain: true) + let failure = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "side-write", + "content": "permission denied", "is_error": true, + ]], isSidechain: true) + + let result = ClaudeTranscriptParser().parse(lines: [invocation, failure], startingSeq: 0) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.path.hasSuffix("/tmp/side.md")) + #expect(artifact.provenance == .referenced) + } + + @Test("Successful sidechain authorization survives incremental parse calls") + func successfulSidechainMutationAcrossParseCalls() throws { + let invocation = claudeLine(type: "assistant", content: [[ + "type": "tool_use", "id": "side-write", "name": "Write", + "input": ["file_path": "/tmp/side.md", "content": "draft"], + ]], isSidechain: true) + let parser = ClaudeTranscriptParser() + let first = parser.parse(lines: [invocation], startingSeq: 0) + let success = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "side-write", + "content": "saved", "is_error": false, + ]], isSidechain: true) + + let second = parser.parse(lines: [success], startingSeq: 1, state: first.state) + let artifact = try #require(indexedArtifacts(second).first) + + #expect(artifact.path.hasSuffix("/tmp/side.md")) + #expect(artifact.provenance == .created) + #expect(artifact.lastReferencedSeq == 1) + } + + @Test("Successful sidechain Bash redirection is created across parse calls") + func successfulSidechainBashAcrossParseCalls() throws { + let invocation = claudeLine(type: "assistant", content: [[ + "type": "tool_use", "id": "side-bash", "name": "Bash", + "input": ["command": "python render.py > /tmp/side-report.html"], + ]], isSidechain: true) + let parser = ClaudeTranscriptParser() + let first = parser.parse(lines: [invocation], startingSeq: 0) + let success = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "side-bash", + "content": "rendered", "is_error": false, + ]], isSidechain: true) + + let second = parser.parse(lines: [success], startingSeq: 1, state: first.state) + let artifact = try #require(indexedArtifacts(second).first) + + #expect(artifact.path.hasSuffix("/tmp/side-report.html")) + #expect(artifact.provenance == .created) + #expect(artifact.captureAuthorization == .created(sequence: 1)) + } + + @Test("Failed sidechain Bash redirection remains referenced") + func failedSidechainBashRemainsReferenced() throws { + let invocation = claudeLine(type: "assistant", content: [[ + "type": "tool_use", "id": "side-bash", "name": "Bash", + "input": ["command": "python render.py > /tmp/side-report.html"], + ]], isSidechain: true) + let failure = claudeLine(type: "user", content: [[ + "type": "tool_result", "tool_use_id": "side-bash", + "content": "permission denied", "is_error": true, + ]], isSidechain: true) + + let result = ClaudeTranscriptParser().parse( + lines: [invocation, failure], + startingSeq: 0 + ) + let artifact = try #require(indexedArtifacts(result).first) + + #expect(artifact.path.hasSuffix("/tmp/side-report.html")) + #expect(artifact.provenance == .referenced) + #expect(artifact.captureAuthorization == nil) + } + + private func indexedArtifacts( + _ result: ChatTranscriptParseResult + ) -> [ChatArtifactIndexedReference] { + ChatArtifactIndexedReference.derive( + from: result.messages, + supplementalReferences: result.artifactReferences, + workingDirectory: "/repo" + ) + } + + private func claudeLine( + type: String, + content: [[String: Any]], + isSidechain: Bool = false + ) -> String { + json([ + "type": type, + "isSidechain": isSidechain, + "uuid": UUID().uuidString, + "timestamp": "2026-07-21T12:00:00.000Z", + "message": ["role": type == "assistant" ? "assistant" : "user", "content": content], + ]) + } + + private func codexLine(type: String, payload: [String: Any]) -> String { + json([ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": type, + "payload": payload, + ]) + } + + private func json(_ object: [String: Any]) -> String { + let data = try! JSONSerialization.data(withJSONObject: object) + return String(decoding: data, as: UTF8.self) + } +} diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactParityFixtureTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactParityFixtureTests.swift index cc1d6b04025b..ab455767948d 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactParityFixtureTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ArtifactParityFixtureTests.swift @@ -117,15 +117,15 @@ struct ArtifactParityFixtureTests { try expectCodex("/private/tmp/parity/A2-new.txt", provenance: .created) } - @Test("A3 old custom apply-patch markers are Created") + @Test("A3 old custom apply-patch markers remain referenced") func a3() throws { - try expectCodex("/private/tmp/parity/A3-add.txt", provenance: .created) - try expectCodex("/private/tmp/parity/A3-update.txt", provenance: .created) + try expectCodex("/private/tmp/parity/A3-add.txt", provenance: .referenced) + try expectCodex("/private/tmp/parity/A3-update.txt", provenance: .referenced) } - @Test("A4 deleted-later file remains lexical") + @Test("A4 deleted-later file remains a reference") func a4() throws { - try expectCodex("/private/tmp/parity/A4-deleted.txt", provenance: .created) + try expectCodex("/private/tmp/parity/A4-deleted.txt", provenance: .referenced) } @Test("N1 tmp aliases merge") @@ -184,11 +184,11 @@ struct ArtifactParityFixtureTests { ) } - @Test("Created provenance survives later prose while sequence advances") + @Test("Unresolved mutation provenance remains referenced while sequence advances") func provenanceAndSequence() throws { let fixture = try ArtifactParityFixture.load(.claude) let artifact = try #require(fixture.artifact(path: "/private/tmp/parity/RANK-created.txt")) - #expect(artifact.provenance == .created) + #expect(artifact.provenance == .referenced) #expect(artifact.lastReferencedSeq == 2) } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactCanonicalIdentityTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactCanonicalIdentityTests.swift index f0afc5ba9068..91a73ea3af55 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactCanonicalIdentityTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactCanonicalIdentityTests.swift @@ -19,13 +19,19 @@ struct ChatArtifactCanonicalIdentityTests { editMessage(id: "created", seq: 4, path: target), toolMessage(id: "referenced", seq: 9, path: symlink), ], + supplementalReferences: [ChatArtifactTranscriptReference( + path: target, + provenance: .created, + seq: 5 + )], canonicalizer: canonicalizer ) #expect(records == [ChatArtifactIndexedReference( path: canonical, provenance: .created, - lastReferencedSeq: 9 + lastReferencedSeq: 9, + captureAuthorization: .created(sequence: 5) )]) } @@ -99,15 +105,23 @@ struct ChatArtifactCanonicalIdentityTests { try Data("let value = 1".utf8).write(to: target) try FileManager.default.createSymbolicLink(at: symlink, withDestinationURL: target) - let records = ChatArtifactIndexedReference.derive(from: [ - editMessage(id: "created", seq: 4, path: target.path), - toolMessage(id: "referenced", seq: 9, path: symlink.path), - ]) + let records = ChatArtifactIndexedReference.derive( + from: [ + editMessage(id: "created", seq: 4, path: target.path), + toolMessage(id: "referenced", seq: 9, path: symlink.path), + ], + supplementalReferences: [ChatArtifactTranscriptReference( + path: target.path, + provenance: .created, + seq: 5 + )] + ) #expect(records == [ChatArtifactIndexedReference( path: try lexicalPath(target.path), provenance: .created, - lastReferencedSeq: 9 + lastReferencedSeq: 9, + captureAuthorization: .created(sequence: 5) )]) } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryOrderingCacheTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryOrderingCacheTests.swift index 73273a05a9db..ac675ec7a608 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryOrderingCacheTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryOrderingCacheTests.swift @@ -34,6 +34,23 @@ struct ChatArtifactGalleryOrderingCacheTests { #expect(invalidated.map(\.path) == ["/latest", "/newer"]) } + @Test("removing an index evicts its retained generation") + func removalEvictsRetainedGeneration() async { + let cache = ChatArtifactGalleryOrderingCache() + let original = [item("/original", seq: 1)] + let replacement = [item("/replacement", seq: 2)] + + _ = await cache.ordered(original, indexID: "session", generation: "one") + await cache.remove(indexID: "session") + let afterRemoval = await cache.ordered( + replacement, + indexID: "session", + generation: "one" + ) + + #expect(afterRemoval.map(\.path) == ["/replacement"]) + } + private func item(_ path: String, seq: Int) -> ChatArtifactIndexedReference { ChatArtifactIndexedReference( path: path, diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryTests.swift index 2c23b6b64bda..b273d93cfe8f 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactGalleryTests.swift @@ -273,6 +273,43 @@ struct ChatArtifactGalleryTests { #expect(folder.childCountIsCapped) } + @Test("directory child counts skip symlinks without spending the entry cap") + func directoryChildCountSkipsSymlinks() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-gallery-symlink-count-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + let target = root.appendingPathComponent("target.txt") + try Data("target".utf8).write(to: target) + for index in 0.. ChatMessageKind { + .toolUse(ChatToolUse( + toolName: "apply_patch", summary: "patch", + status: .succeeded, + referencedPaths: [path], artifactMutationAuthorized: true + )) + } } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactLRUCacheTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactLRUCacheTests.swift index 8cacb578d3d5..b4e41461d5fa 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactLRUCacheTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatArtifactLRUCacheTests.swift @@ -18,4 +18,16 @@ struct ChatArtifactLRUCacheTests { #expect(cache.value(forKey: "two") == nil) #expect(cache.value(forKey: "three") == 3) } + + @Test("removal releases one retained entry") + func removeValue() { + var cache = ChatArtifactLRUCache(capacity: 2) + cache.insert(1, forKey: "one") + cache.insert(2, forKey: "two") + + #expect(cache.removeValue(forKey: "one") == 1) + #expect(cache.count == 1) + #expect(cache.value(forKey: "one") == nil) + #expect(cache.value(forKey: "two") == 2) + } } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatMessageBatchClassificationTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatMessageBatchClassificationTests.swift new file mode 100644 index 000000000000..f420b9dd87ba --- /dev/null +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatMessageBatchClassificationTests.swift @@ -0,0 +1,34 @@ +import Foundation +import Testing +@testable import CmuxAgentChat + +@Suite("Chat message batch classification") +struct ChatMessageBatchClassificationTests { + @Test("Only committed agent prose settles the streaming preview") + func detectsAgentProse() { + let userProse = message(role: .user, timestamp: 1, kind: .prose(ChatProse(text: "prompt"))) + let agentThought = message(role: .agent, timestamp: 2, kind: .thought(ChatThought(text: "thinking"))) + let agentProse = message(role: .agent, timestamp: 3, kind: .prose(ChatProse(text: "answer"))) + + #expect(![userProse, agentThought].containsAgentProse) + #expect([userProse, agentThought, agentProse].containsAgentProse) + } + + private func message( + role: ChatRole, + timestamp: TimeInterval, + kind: ChatMessageKind + ) -> ChatMessage { + ChatMessage( + id: "\(timestamp)", + seq: Int(timestamp), + role: role, + timestamp: date(timestamp), + kind: kind + ) + } + + private func date(_ timestamp: TimeInterval) -> Date { + Date(timeIntervalSince1970: timestamp) + } +} diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ClaudeTranscriptParserTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ClaudeTranscriptParserTests.swift index 9cdc68a1fbdb..182e915f9c6d 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ClaudeTranscriptParserTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ClaudeTranscriptParserTests.swift @@ -53,7 +53,7 @@ struct ClaudeTranscriptParserTests { uuid: String = "r-1", toolUseID: String, content: Any, - isError: Bool? = nil, + isError: Bool? = false, timestamp: String = "2026-06-12T05:08:23.317Z" ) -> String { var block: [String: Any] = ["tool_use_id": toolUseID, "type": "tool_result", "content": content] @@ -164,6 +164,128 @@ struct ClaudeTranscriptParserTests { #expect(grep.output == "No matches") } + @Test("Claude results without positive success evidence fail closed") + func unknownResultFailsClosed() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_unknown", "name": "Grep", + "input": ["pattern": "needle", "path": "/tmp"]], + ]), + toolResultLine(toolUseID: "toolu_unknown", content: "Failure: unexpected failure text", isError: nil), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .failed) + } + + @Test("Successful tool output mentioning errors remains successful") + func successfulOutputMentioningErrors() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_grep", "name": "Grep", + "input": ["pattern": "error", "path": "/tmp"]], + ]), + toolResultLine( + toolUseID: "toolu_grep", + content: "Found 2 error records", + isError: nil + ), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .succeeded) + } + + @Test("Provider failure prefixes remain failure evidence") + func failurePrefixWithDetails() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_failed", "name": "Grep", + "input": ["pattern": "needle", "path": "/tmp"]], + ]), + toolResultLine( + toolUseID: "toolu_failed", + content: "Error: permission denied\nadditional details", + isError: nil + ), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .failed) + } + + @Test("A standalone failure marker remains failure evidence") + func standaloneFailureMarker() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_failed_marker", "name": "Grep", + "input": ["pattern": "needle", "path": "/tmp"]], + ]), + toolResultLine( + toolUseID: "toolu_failed_marker", + content: "Failed", + isError: nil + ), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .failed) + } + + @Test("A failure marker with trailing details remains failure evidence") + func failureMarkerWithTrailingDetails() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_failed_details", "name": "Grep", + "input": ["pattern": "needle", "path": "/tmp"]], + ]), + toolResultLine( + toolUseID: "toolu_failed_details", + content: "Failed\ncontext from the tool", + isError: nil + ), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .failed) + } + + @Test("Explicit Claude success status wins over the No matches display heuristic") + func explicitSuccessStatusWinsForNoMatches() { + let lines = [ + assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_grep_success", "name": "Grep", + "input": ["pattern": "needle", "path": "/tmp"]], + ]), + toolResultLine( + toolUseID: "toolu_grep_success", + content: "No matches", + isError: false + ), + ] + let result = parser.parse(lines: lines, startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.status == .succeeded) + } + @Test("Edit tool maps to a fileEdit with line counts and a -/+ diff") func editTool() { let line = assistantLine(blocks: [ @@ -199,7 +321,7 @@ struct ClaudeTranscriptParserTests { #expect(edit.deletions == 0) } - @Test("MultiEdit and NotebookEdit map to file edits for Created provenance") + @Test("MultiEdit and NotebookEdit remain referenced until results arrive") func multiEditAndNotebookEditTools() { let line = assistantLine(blocks: [ ["type": "tool_use", "id": "toolu_multi", "name": "MultiEdit", @@ -224,7 +346,7 @@ struct ClaudeTranscriptParserTests { "/repo/Sources/App.swift", "/repo/Notes/Research.ipynb", ]) - #expect(artifacts.allSatisfy { $0.provenance == .created }) + #expect(artifacts.allSatisfy { $0.provenance == .referenced }) } @Test("unknown tools map to a generic toolUse with summary and input detail") @@ -245,6 +367,50 @@ struct ClaudeTranscriptParserTests { #expect(tool.referencedPaths == ["/repo/main.swift"]) } + @Test("Structured tool path extraction is bounded while preserving first-seen order") + func structuredToolPathsAreBounded() { + let paths = (0..<2_000).map { "/repo/structured-\($0).txt" } + let line = assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_many_paths", "name": "Read", + "input": ["path": paths]], + ]) + let result = parser.parse(lines: [line], startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + #expect(tool.referencedPaths?.count == ChatToolReferencedPathExtractor.maximumPathCount) + #expect(tool.referencedPaths?.first == paths.first) + #expect(tool.referencedPaths?.last == paths[ChatToolReferencedPathExtractor.maximumPathCount - 1]) + } + + @Test("Structured tool path extraction rejects oversized paths and caps aggregate bytes") + func structuredToolPathsRespectByteBounds() { + let oversized = "/repo/" + String(repeating: "x", count: ChatToolReferencedPathExtractor.maximumPathBytes) + + "-too-long" + let paths = [oversized] + (0..<200).map { + "/repo/byte-bound-\($0)-" + String(repeating: "y", count: 500) + } + let line = assistantLine(blocks: [ + ["type": "tool_use", "id": "toolu_byte_bound", "name": "Read", + "input": ["path": paths]], + ]) + let result = parser.parse(lines: [line], startingSeq: 0) + guard case .toolUse(let tool) = result.messages[0].kind else { + Issue.record("expected toolUse kind") + return + } + let retained = tool.referencedPaths ?? [] + #expect(!retained.contains(oversized)) + #expect(retained.allSatisfy { + $0.utf8.count <= ChatToolReferencedPathExtractor.maximumPathBytes + }) + #expect( + retained.reduce(0) { $0 + $1.utf8.count } + <= ChatToolReferencedPathExtractor.maximumAggregatePathBytes + ) + } + @Test("ChatToolUse wire coding preserves optional referenced paths and decodes legacy payloads") func toolReferencedPathsWireCoding() throws { let coding = ChatWireCoding() @@ -412,12 +578,12 @@ struct ClaudeTranscriptParserTests { #expect(result.messages.isEmpty) #expect(result.artifactReferences == [ - ChatArtifactTranscriptReference(path: "/tmp/app.js", provenance: .created, seq: 7), - ChatArtifactTranscriptReference(path: "/tmp/app.c", provenance: .created, seq: 7), + ChatArtifactTranscriptReference(path: "/tmp/app.js", provenance: .referenced, seq: 7), + ChatArtifactTranscriptReference(path: "/tmp/app.c", provenance: .referenced, seq: 7), ]) } - @Test("only a sidechain mutation target is created") + @Test("only a sidechain mutation target remains pending authorization") func sidechainMutationTargetProvenance() { let line = sidechainAssistantLine(blocks: [[ "type": "tool_use", "id": "toolu_write", "name": "Write", @@ -427,7 +593,7 @@ struct ClaudeTranscriptParserTests { #expect(result.messages.isEmpty) #expect(result.artifactReferences == [ - ChatArtifactTranscriptReference(path: "/tmp/a", provenance: .created, seq: 9), + ChatArtifactTranscriptReference(path: "/tmp/a", provenance: .referenced, seq: 9), ChatArtifactTranscriptReference(path: "/tmp/b", provenance: .referenced, seq: 9), ]) } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/CodexTranscriptParserTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/CodexTranscriptParserTests.swift index 3074099c28f9..faa464177bd1 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/CodexTranscriptParserTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/CodexTranscriptParserTests.swift @@ -272,7 +272,7 @@ struct CodexTranscriptParserTests { #expect(tool.status == .succeeded) } - @Test("function_call apply_patch extracts path arguments for Created provenance") + @Test("function_call apply_patch remains referenced until its result") func applyPatchFunctionCall() throws { let call = functionCallLine( name: "apply_patch", @@ -289,7 +289,7 @@ struct CodexTranscriptParserTests { workingDirectory: "/repo" ).first) #expect(artifact.path == "/repo/Sources/App.swift") - #expect(artifact.provenance == .created) + #expect(artifact.provenance == .referenced) } @Test("patch_apply_end emits a succeeded apply_patch tool use with Created paths") diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/PanelArtifactAuthorizationStoreTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/PanelArtifactAuthorizationStoreTests.swift index 46fa13939fa8..1a798222afb2 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/PanelArtifactAuthorizationStoreTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/PanelArtifactAuthorizationStoreTests.swift @@ -90,6 +90,28 @@ struct PanelArtifactAuthorizationStoreTests { ) == "/safe/panel.md") } + @Test("a real panel grant captures the authorized inode") + func realGrantCapturesIdentity() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-panel-identity-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let file = directory.appendingPathComponent("panel.md") + try Data("authorized".utf8).write(to: file) + + let store = PanelArtifactAuthorizationStore() + #expect(store.record( + workspaceID: "workspace", + surfaceID: "surface", + filePath: file.path + ) != nil) + #expect(store.authorizedIdentity( + workspaceID: "workspace", + surfaceID: "surface", + requestedPath: file.path + ) != nil) + } + private struct FakeResolver: ChatArtifactScope.FileSystemResolving { var symlinks: [String: String] = [:] diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/Resources/ArtifactParity/claude-adversarial.jsonl b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/Resources/ArtifactParity/claude-adversarial.jsonl index bde977435b93..d7c59b20f76a 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/Resources/ArtifactParity/claude-adversarial.jsonl +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/Resources/ArtifactParity/claude-adversarial.jsonl @@ -7,7 +7,7 @@ {"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-list","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"read-nested","content":"/tmp/parity/O3-list-01.txt\n/tmp/parity/O3-list-02.txt\n/tmp/parity/O3-list-03.txt\n/tmp/parity/O3-list-04.txt\n/tmp/parity/O3-list-05.txt\n/tmp/parity/O3-list-06.txt\n/tmp/parity/O3-list-07.txt\n/tmp/parity/O3-list-08.txt\n/tmp/parity/O3-list-09.txt\n/tmp/parity/O3-list-10.txt\n/tmp/parity/O3-list-11.txt\n/tmp/parity/O3-list-12.txt\n/tmp/parity/O3-list-13.txt\n/tmp/parity/O3-list-14.txt\n/tmp/parity/O3-list-15.txt\n/tmp/parity/O3-list-16.txt\n/tmp/parity/O3-list-17.txt\n/tmp/parity/O3-list-18.txt\n/tmp/parity/O3-list-19.txt\n/tmp/parity/O3-list-20.txt\n/tmp/parity/O3-list-21.txt\n/tmp/parity/O3-list-22.txt\n/tmp/parity/O3-list-23.txt\n/tmp/parity/O3-list-24.txt\n/tmp/parity/O3-list-25.txt\n/tmp/parity/O3-list-26.txt\n/tmp/parity/O3-list-27.txt\n/tmp/parity/O3-list-28.txt\n/tmp/parity/O3-list-29.txt\n/tmp/parity/O3-list-30.txt\n/tmp/parity/O3-list-31.txt\n/tmp/parity/O3-list-32.txt\n/tmp/parity/O3-list-33.txt\n/tmp/parity/O3-list-34.txt\n/tmp/parity/O3-list-35.txt\n/tmp/parity/O3-list-36.txt\n/tmp/parity/O3-list-37.txt\n/tmp/parity/O3-list-38.txt\n/tmp/parity/O3-list-39.txt\n/tmp/parity/O3-list-40.txt\n/tmp/parity/O3-list-41.txt\n/tmp/parity/O3-list-42.txt\n/tmp/parity/O3-list-43.txt\n/tmp/parity/O3-list-44.txt\n/tmp/parity/O3-list-45.txt\n/tmp/parity/O3-list-46.txt\n/tmp/parity/O3-list-47.txt\n/tmp/parity/O3-list-48.txt\n/tmp/parity/O3-list-49.txt\n/tmp/parity/O3-list-50.txt"}]}} {"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-array","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"array-result","content":[{"type":"text","text":"first /tmp/parity/O5-array-one.txt"},{"type":"tool_reference","tool_name":"noop"},{"type":"text","text":"second /tmp/parity/O5-array-two.txt"}]}]}} {"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-huge","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"huge-result","content":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx /tmp/parity/O6-beyond-budget.png"}]}} -{"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-write","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"created-write","content":"Wrote 1 line to ../../K2-created.txt"}]}} +{"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-write","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"created-write","content":"Wrote 1 line to ../../K2-created.txt","is_error":false}]}} {"parentUuid":null,"isSidechain":true,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"side-write","type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"side-write-call","name":"Write","input":{"file_path":"/tmp/parity/SIDE-created.txt","content":"/tmp/parity/SIDE-content.txt"}}]}} -{"parentUuid":null,"isSidechain":true,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"side-result","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"side-write-call","content":"Subagent output /tmp/parity/SIDE-output.txt"}]}} +{"parentUuid":null,"isSidechain":true,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"side-result","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"side-write-call","content":"Subagent output /tmp/parity/SIDE-output.txt","is_error":false}]}} {"parentUuid":null,"isSidechain":false,"sessionId":"fixture-claude","cwd":"/Users/test/project","timestamp":"2026-07-13T12:00:00.000Z","uuid":"r-task","type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"task-main","content":"done"}]}} diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactAuthorizationStoreTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactAuthorizationStoreTests.swift index 0bd33c8c93c6..3f486b04410d 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactAuthorizationStoreTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactAuthorizationStoreTests.swift @@ -84,6 +84,38 @@ struct TerminalArtifactAuthorizationStoreTests { ).isEmpty) } + @Test("retained scan identities follow the newest generation") + func retainedIdentities() async { + let store = TerminalArtifactAuthorizationStore( + timeToLive: 60, + maximumGenerationsPerSurface: 2 + ) + let first = ChatArtifactFileIdentity(device: 1, inode: 10) + let second = ChatArtifactFileIdentity(device: 1, inode: 11) + let start = Date(timeIntervalSince1970: 100) + + await store.record( + workspaceID: "workspace", + surfaceID: "surface", + canonicalPaths: ["/safe/report.txt"], + identities: ["/safe/report.txt": first], + at: start + ) + await store.record( + workspaceID: "workspace", + surfaceID: "surface", + canonicalPaths: ["/safe/report.txt"], + identities: ["/safe/report.txt": second], + at: start.addingTimeInterval(1) + ) + + #expect(await store.authorizedIdentities( + workspaceID: "workspace", + surfaceID: "surface", + at: start.addingTimeInterval(2) + ) == ["/safe/report.txt": second]) + } + private struct FakeResolver: ChatArtifactScope.FileSystemResolving { let files: Set diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactPathDetectorTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactPathDetectorTests.swift index 6c11262dc3ee..7c4a702b9656 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactPathDetectorTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TerminalArtifactPathDetectorTests.swift @@ -168,4 +168,17 @@ struct TerminalArtifactPathDetectorTests { "./relative/note.md", ]) } + + @Test("bounded extraction stops before retaining an unbounded path set") + func boundedExtraction() { + let text = (0..<2_000) + .map { "/tmp/generated/path-\($0).txt" } + .joined(separator: " ") + + let paths = TerminalArtifactPathDetector().paths(in: text) + + #expect(paths.count == 1_024) + #expect(paths.first == "/tmp/generated/path-0.txt") + #expect(paths.last == "/tmp/generated/path-1023.txt") + } } diff --git a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TranscriptBatchAssemblerTests.swift b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TranscriptBatchAssemblerTests.swift index 750c9ad8b161..f78fd232d2c7 100644 --- a/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TranscriptBatchAssemblerTests.swift +++ b/Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/TranscriptBatchAssemblerTests.swift @@ -4,13 +4,23 @@ import Testing @testable import CmuxAgentChat @Suite struct TranscriptBatchAssemblerTests { - private static func toolUse(seq: Int) -> ChatMessage { + private static func toolUse( + seq: Int, + referencedPaths: [String]? = nil + ) -> ChatMessage { ChatMessage( id: "m\(seq)", seq: seq, role: .agent, timestamp: Date(timeIntervalSince1970: 1_781_000_000 + Double(seq)), - kind: .toolUse(ChatToolUse(toolName: "Read", summary: "s\(seq)", status: .running)) + kind: .toolUse( + ChatToolUse( + toolName: "Read", + summary: "s\(seq)", + status: .running, + referencedPaths: referencedPaths + ) + ) ) } @@ -45,4 +55,147 @@ import Testing let state = assembler.result(lastTimestamp: nil).state #expect(state.pendingToolUses.count == 10) } + + @Test("pending tool-use paths are bounded by per-path and aggregate UTF-8 bytes") + func pendingToolUsePathBytesBounded() { + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState(), + budget: TranscriptTextBudget() + ) + let oversized = "/tmp/" + String(repeating: "x", count: 5_000) + for seq in 0..<300 { + let paths = [oversized] + (0..<8).map { "/tmp/kept-\(seq)-\($0)-" + String(repeating: "y", count: 1_000) } + assembler.append( + Self.toolUse(seq: seq, referencedPaths: paths), + pendingKey: "call-\(seq)" + ) + } + + let pending = assembler.result(lastTimestamp: nil).state.pendingToolUses + let pathValues = pending.values.flatMap { messages in + messages.compactMap { message -> [String]? in + guard case .toolUse(let toolUse) = message.kind else { return nil } + return toolUse.referencedPaths + }.flatMap { $0 } + } + let pathBytes = pathValues.reduce(0) { $0 + $1.utf8.count } + + #expect(pathBytes <= TranscriptBatchAssembler.maxPendingToolUsePathBytes) + #expect(pathValues.allSatisfy { + $0.utf8.count <= ChatToolReferencedPathExtractor.maximumPathBytes + }) + #expect(!pathValues.contains(oversized)) + #expect(pending.count == TranscriptBatchAssembler.maxPendingToolUses) + } + + @Test("pending artifact mutation references are bounded by count") + func pendingArtifactMutationReferenceCountBounded() { + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState(), + budget: TranscriptTextBudget() + ) + for key in 0..<2_000 { + assembler.registerArtifactMutation( + paths: ["/tmp/artifact-\(key).md"], + pendingKey: "mutation-\(key)", + seq: key + ) + } + + let pending = assembler.result(lastTimestamp: nil).state.pendingArtifactMutations + let referenceCount = pending.values.reduce(0) { $0 + $1.count } + + #expect(referenceCount <= 1_024) + #expect(pending["mutation-1_999"] != nil) + #expect(pending["mutation-0"] == nil) + } + + @Test("pending artifact mutation references are bounded by UTF-8 bytes") + func pendingArtifactMutationBytesBounded() { + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState(), + budget: TranscriptTextBudget() + ) + let pathPrefix = "/tmp/" + String(repeating: "x", count: 1_000) + for key in 0..<400 { + let paths = (0..<8).map { "\(pathPrefix)-\(key)-\($0).md" } + assembler.registerArtifactMutation( + paths: paths, + pendingKey: "mutation-\(key)", + seq: key + ) + } + + let pending = assembler.result(lastTimestamp: nil).state.pendingArtifactMutations + let byteCount = pending.values + .flatMap { $0 } + .reduce(0) { $0 + $1.path.utf8.count } + + #expect(byteCount <= 256 * 1_024) + } + + @Test("pending artifact mutation keys are bounded and included in the byte budget") + func pendingArtifactMutationKeysBounded() { + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState(), + budget: TranscriptTextBudget() + ) + for key in 0..<400 { + assembler.registerArtifactMutation( + paths: ["/tmp/artifact.md"], + pendingKey: String(repeating: "k", count: 1_000) + "-\(key)", + seq: key + ) + } + + let pending = assembler.result(lastTimestamp: nil).state.pendingArtifactMutations + let carriedBytes = pending.reduce(0) { total, entry in + total + entry.key.utf8.count + + entry.value.reduce(0) { $0 + $1.path.utf8.count } + } + + #expect(carriedBytes <= 256 * 1_024) + #expect(pending.count < 400) + } + + @Test("oversized persisted artifact mutation keys are discarded") + func oversizedPersistedArtifactMutationKeyDiscarded() { + let oversizedKey = String(repeating: "x", count: 10_000) + let reference = ChatArtifactTranscriptReference( + path: "/tmp/artifact.md", + provenance: .referenced, + seq: 1 + ) + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState( + pendingArtifactMutations: [oversizedKey: [reference]] + ), + budget: TranscriptTextBudget() + ) + + #expect(assembler.result(lastTimestamp: nil).state.pendingArtifactMutations.isEmpty) + + assembler.registerArtifactMutation( + paths: [reference.path], + pendingKey: oversizedKey, + seq: 2 + ) + #expect(assembler.result(lastTimestamp: nil).state.pendingArtifactMutations.isEmpty) + } + + @Test("supplemental artifact references are bounded during one parse") + func artifactReferencesBoundedDuringParse() { + var assembler = TranscriptBatchAssembler( + state: ChatTranscriptParseState(), + budget: TranscriptTextBudget() + ) + assembler.appendArtifactReferences( + paths: (0..<20_000).map { "/tmp/reference-\($0).md" }, + seq: 1 + ) + + let references = assembler.result(lastTimestamp: nil).artifactReferences + #expect(references.count <= 4_096) + #expect(references.reduce(0) { $0 + $1.path.utf8.count } <= 512 * 1_024) + } } diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactFolderView.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactFolderView.swift index af8f775ec316..6258f1e10db8 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactFolderView.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactFolderView.swift @@ -20,6 +20,7 @@ struct ChatArtifactFolderView: View { @Environment(\.chatArtifactLoader) private var loader @State private var state: LoadState = .loading + @State private var loadAttempt = UUID() var body: some View { content @@ -39,10 +40,40 @@ struct ChatArtifactFolderView: View { breadcrumb Divider() if listing.entries.isEmpty { - Text(String(localized: "chat.artifact.folder.empty", defaultValue: "No items", bundle: .module)) - .font(.subheadline) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, maxHeight: .infinity) + VStack(spacing: 8) { + Text(String(localized: "chat.artifact.folder.empty", defaultValue: "No items", bundle: .module)) + .font(.subheadline) + .foregroundStyle(.secondary) + if listing.isIncomplete || listing.isTruncated { + Text(String( + localized: "chat.artifact.folder.incomplete_empty", + defaultValue: "This folder could not be listed completely. Tap Retry to try again.", + bundle: .module + )) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } else { + Text(String( + localized: "chat.artifact.folder.empty_refresh", + defaultValue: "New items may appear after a refresh.", + bundle: .module + )) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + Button { + Task { await load() } + } label: { + Label( + String(localized: "chat.artifact.retry", defaultValue: "Retry", bundle: .module), + systemImage: "arrow.clockwise" + ) + } + .buttonStyle(.bordered) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) } else { List { Section { @@ -67,8 +98,18 @@ struct ChatArtifactFolderView: View { bundle: .module )) } + if listing.isIncomplete { + Text(String( + localized: "chat.artifact.folder.changed_while_loading", + defaultValue: "Some items changed while loading. Pull to refresh.", + bundle: .module + )) + } } } + .refreshable { + await load() + } } } case .failed(let error): @@ -130,16 +171,55 @@ struct ChatArtifactFolderView: View { } private func load() async { - await MainActor.run { state = .loading } + let (attempt, previousState) = await MainActor.run { + let previousState = state + let attempt = UUID() + loadAttempt = attempt + state = .loading + return (attempt, previousState) + } do { let listing = try await loader.list(path: path) - guard !Task.isCancelled else { return } - await MainActor.run { state = .listing(listing) } + guard !Task.isCancelled else { + await restoreStateAfterCancellation( + previousState, + attempt: attempt + ) + return + } + await MainActor.run { + guard loadAttempt == attempt else { return } + state = .listing(listing) + } } catch is CancellationError { - return + await restoreStateAfterCancellation(previousState, attempt: attempt) } catch { let failure = (error as? ChatArtifactError) ?? .loadFailed - await MainActor.run { state = .failed(failure) } + await MainActor.run { + guard loadAttempt == attempt else { return } + state = .failed(failure) + } + } + } + + private func restoreStateAfterCancellation( + _ previousState: LoadState, + attempt: UUID + ) async { + await MainActor.run { + guard loadAttempt == attempt else { return } + switch previousState { + case .loading: + // An initial load that is cancelled while the view remains + // mounted needs a recoverable state instead of a permanent + // spinner. The retry button in the failure view starts a new + // attempt. + state = .failed(.loadFailed) + case .listing, .failed: + // Refresh cancellation must leave the last usable snapshot + // visible so the user can pull to refresh again. + state = previousState + } } } diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactLoader.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactLoader.swift index 017701803620..a01f76ee9607 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactLoader.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactLoader.swift @@ -88,6 +88,8 @@ public struct ChatArtifactLoader: Sendable { public let supportsArtifacts: Bool /// Whether directory stat results may route into a navigable folder browser. public let supportsDirectoryBrowsing: Bool + /// Whether chat-scoped files can be persisted into project Artifacts. + public let supportsArtifactSave: Bool /// Authorization and cache namespace for artifact operations. public let scope: ChatArtifactLoaderScope /// Identity of the immutable event source captured by this loader. @@ -109,6 +111,7 @@ public struct ChatArtifactLoader: Sendable { ) async throws -> Void private let thumbnailHandler: @Sendable (_ path: String, _ maxDimension: Int) async throws -> ChatArtifactThumbnail private let listHandler: @Sendable (_ path: String) async throws -> ChatArtifactDirectoryListing + private let saveHandler: @Sendable (_ path: String) async throws -> ChatArtifactSaveResult private let thumbnailCache: ChatArtifactThumbnailCache private let contentCache: ChatArtifactContentCache private let diagnosticLog: DiagnosticLog? @@ -119,6 +122,7 @@ public struct ChatArtifactLoader: Sendable { /// - Parameters: /// - supportsArtifacts: Whether artifact operations are available. /// - supportsDirectoryBrowsing: Whether directory stat results may be listed. + /// - supportsArtifactSave: Whether chat-scoped files can be persisted into project Artifacts. /// - scope: Cache and authorization namespace for this loader. /// - sourceIdentity: Identity of the immutable event source captured by this loader. /// - cache: Thumbnail cache shared by rows and viewers. @@ -129,9 +133,11 @@ public struct ChatArtifactLoader: Sendable { /// containing the result of `fetch`. /// - thumbnail: Thumbnail operation for image artifacts. /// - list: Immediate-directory listing operation. + /// - save: Project-local persistence operation. public init( supportsArtifacts: Bool = false, supportsDirectoryBrowsing: Bool = false, + supportsArtifactSave: Bool = false, scope: ChatArtifactLoaderScope = .unsupported, sourceIdentity: String? = nil, cache: ChatArtifactThumbnailCache = ChatArtifactThumbnailCache(), @@ -156,10 +162,14 @@ public struct ChatArtifactLoader: Sendable { }, list: @escaping @Sendable (_ path: String) async throws -> ChatArtifactDirectoryListing = { _ in throw ChatArtifactError.unsupported + }, + save: @escaping @Sendable (_ path: String) async throws -> ChatArtifactSaveResult = { _ in + throw ChatArtifactError.unsupported } ) { self.supportsArtifacts = supportsArtifacts self.supportsDirectoryBrowsing = supportsDirectoryBrowsing + self.supportsArtifactSave = supportsArtifactSave self.scope = scope self.sourceIdentity = sourceIdentity self.thumbnailCache = cache @@ -182,6 +192,7 @@ public struct ChatArtifactLoader: Sendable { } thumbnailHandler = thumbnail listHandler = list + saveHandler = save } /// Creates an artifact loader backed by a chat event source. @@ -204,6 +215,7 @@ public struct ChatArtifactLoader: Sendable { self.init( supportsArtifacts: source.supportsArtifacts, supportsDirectoryBrowsing: source.supportsArtifactFolders, + supportsArtifactSave: source.supportsArtifactSave, scope: .chat(sessionID: sessionID), sourceIdentity: sourceIdentity, cache: cache, @@ -227,6 +239,9 @@ public struct ChatArtifactLoader: Sendable { }, list: { path in try await source.artifactList(sessionID: sessionID, path: path) + }, + save: { path in + try await source.artifactSave(sessionID: sessionID, path: path) } ) } @@ -451,6 +466,17 @@ public struct ChatArtifactLoader: Sendable { return try await listHandler(path) } + /// Persists a chat-authorized file into the session project's artifact store. + /// + /// - Parameter path: Absolute host path authorized by the chat artifact scope. + /// - Returns: Stable project-local path and prompt reference. + public func save(path: String) async throws -> ChatArtifactSaveResult { + guard supportsArtifactSave else { + throw ChatArtifactError.unsupported + } + return try await saveHandler(path) + } + private func thumbnailCacheKey( path: String, maxDimension: Int, diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenu.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenu.swift index 3637599ad233..439d10e2905c 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenu.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenu.swift @@ -63,7 +63,7 @@ struct ChatArtifactViewerActionsMenu: View, Equatable { systemImage: "ellipsis.circle" ) } - .disabled(snapshot.fileActionState.isRunning) + .disabled(snapshot.fileActionState.isRunning || value.isSavingToArtifacts) } @ViewBuilder @@ -80,6 +80,20 @@ struct ChatArtifactViewerActionsMenu: View, Equatable { isRunning: snapshot.fileActionState.isRunning, onAction: { action in actions.performFileAction(action, snapshot) } ) + if value.loaderSupportsArtifactSave, snapshot.canSaveToArtifacts { + Button { + actions.saveToArtifacts(snapshot.path) + } label: { + Label( + String( + localized: "chat.artifact.save_to_artifacts", + defaultValue: "Save to cmux Artifacts", + bundle: .module + ), + systemImage: "shippingbox" + ) + } + } } @ViewBuilder diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuActions.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuActions.swift index 8f49c573461e..744652309c13 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuActions.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuActions.swift @@ -2,6 +2,7 @@ struct ChatArtifactViewerActionsMenuActions { let prepareShare: (String) -> Void let prepareSave: (String) -> Void + let saveToArtifacts: (String) -> Void let toggleSearch: (String) -> Void let toggleGoToLine: (String) -> Void let requestTop: (String) -> Void diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuValue.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuValue.swift index 5207e8d568ba..e1499e57af44 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuValue.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerActionsMenuValue.swift @@ -4,5 +4,7 @@ struct ChatArtifactViewerActionsMenuValue: Equatable, Sendable { let loaderScope: ChatArtifactLoaderScope let loaderSupportsArtifacts: Bool let loaderSupportsDirectoryBrowsing: Bool + let loaderSupportsArtifactSave: Bool + let isSavingToArtifacts: Bool } #endif diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerModel.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerModel.swift index a9918cf7d0f0..33244a3c6520 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerModel.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerModel.swift @@ -46,6 +46,10 @@ final class ChatArtifactViewerModel { && (activeStat?.size ?? .max) <= Self.maximumCopyContentsBytes } + var canSaveToArtifacts: Bool { + activeStat?.canSaveToArtifacts == true + } + func load( path: String, loader: ChatArtifactLoader, diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageModel.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageModel.swift index d137f659ef2c..fdffdcfd4d65 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageModel.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageModel.swift @@ -57,6 +57,7 @@ final class ChatArtifactViewerPageModel { hasFileActions: viewerModel.hasFileActions, isTextFile: viewerModel.isTextFile, canCopyContents: viewerModel.canCopyContents, + canSaveToArtifacts: viewerModel.canSaveToArtifacts, retryGeneration: retryGeneration, topRequestID: topRequestID, bottomRequestID: bottomRequestID, diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageSnapshot.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageSnapshot.swift index 944bbe687f6f..c66595278fa1 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageSnapshot.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPageSnapshot.swift @@ -14,6 +14,7 @@ struct ChatArtifactViewerPageSnapshot: Identifiable, Equatable, Sendable { let hasFileActions: Bool let isTextFile: Bool let canCopyContents: Bool + let canSaveToArtifacts: Bool let retryGeneration: Int let topRequestID: Int let bottomRequestID: Int diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPager.swift b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPager.swift index d0b0add9dc2f..d9c8305a51ab 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPager.swift +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Artifacts/ChatArtifactViewerPager.swift @@ -19,16 +19,26 @@ struct ChatArtifactViewerPager: View { @Environment(\.chatArtifactLoader) private var loader @State private var model: ChatArtifactViewerPagerModel @State private var zoomedPath: String? + @State private var isSavingToArtifacts = false + @State private var artifactSaveTask: Task? + @State private var artifactSaveOperationTask: Task? + @State private var artifactSaveCleanupTask: Task? + private let artifactSaveClock: any Clock + private let artifactSaveTimeout: Duration init( initialPath: String, scope: ChatArtifactViewerScope, swipeOrder: ChatArtifactGallerySwipeOrder, + artifactSaveClock: any Clock = ContinuousClock(), + artifactSaveTimeout: Duration = .seconds(30), onDone: @escaping () -> Void ) { self.initialPath = initialPath self.scope = scope self.swipeOrder = swipeOrder + self.artifactSaveClock = artifactSaveClock + self.artifactSaveTimeout = artifactSaveTimeout self.onDone = onDone _model = State(initialValue: ChatArtifactViewerPagerModel( initialPath: initialPath, @@ -53,7 +63,9 @@ struct ChatArtifactViewerPager: View { snapshot: model.toolbarSnapshot, loaderScope: loader.scope, loaderSupportsArtifacts: loader.supportsArtifacts, - loaderSupportsDirectoryBrowsing: loader.supportsDirectoryBrowsing + loaderSupportsDirectoryBrowsing: loader.supportsDirectoryBrowsing, + loaderSupportsArtifactSave: loader.supportsArtifactSave, + isSavingToArtifacts: isSavingToArtifacts || artifactSaveCleanupTask != nil ), actions: viewerActionsMenuActions ) @@ -84,6 +96,9 @@ struct ChatArtifactViewerPager: View { .onChange(of: swipeOrder) { _, newOrder in model.update(swipeOrder: newOrder) } + #if os(iOS) + .onDisappear(perform: cancelOwnedTasks) + #endif } @ViewBuilder @@ -192,6 +207,7 @@ struct ChatArtifactViewerPager: View { prepareSave: { path in Task { await model.prepareSave(for: path, loader: loader) } }, + saveToArtifacts: saveToArtifacts, toggleSearch: { path in model.toggleSearch(for: path, loader: loader) }, toggleGoToLine: model.toggleGoToLine, requestTop: model.requestTop, @@ -255,6 +271,138 @@ struct ChatArtifactViewerPager: View { ) } + private func saveToArtifacts(path: String) { + guard !isSavingToArtifacts, artifactSaveCleanupTask == nil else { return } + isSavingToArtifacts = true + let loader = loader + let clock = artifactSaveClock + let timeout = artifactSaveTimeout + let operationTask = Task { + try await loader.save(path: path) + } + artifactSaveOperationTask = operationTask + artifactSaveTask = Task { @MainActor in + do { + let result = try await Self.saveArtifact( + operationTask: operationTask, + clock: clock, + timeout: timeout + ) + try Task.checkCancellation() + toasts.present(.success( + String( + format: String( + localized: "chat.artifact.saved_to_artifacts", + defaultValue: "Saved as %@", + bundle: .module + ), + result.reference + ), + systemImage: "shippingbox" + )) + artifactSaveOperationTask = nil + artifactSaveTask = nil + isSavingToArtifacts = false + } catch is CancellationError { + operationTask.cancel() + guard !Task.isCancelled else { return } + artifactSaveOperationTask = nil + artifactSaveTask = nil + isSavingToArtifacts = false + } catch ChatArtifactSaveTimeout.expired { + guard !Task.isCancelled else { + operationTask.cancel() + return + } + // The UI deadline is independent from the host operation. Keep + // the latter owned until it settles so a retry cannot overlap + // a potentially still-mutating save request. + operationTask.cancel() + artifactSaveOperationTask = nil + artifactSaveTask = nil + isSavingToArtifacts = false + artifactSaveCleanupTask = Task { @MainActor in + _ = try? await operationTask.value + guard !Task.isCancelled else { return } + artifactSaveCleanupTask = nil + } + toasts.present(.failure( + String( + localized: "chat.artifact.save_to_artifacts_failed", + defaultValue: "Couldn’t save this file to cmux Artifacts.", + bundle: .module + ), + systemImage: "shippingbox" + )) + } catch { + guard !Task.isCancelled else { + operationTask.cancel() + artifactSaveOperationTask = nil + artifactSaveTask = nil + isSavingToArtifacts = false + return + } + toasts.present(.failure( + String( + localized: "chat.artifact.save_to_artifacts_failed", + defaultValue: "Couldn’t save this file to cmux Artifacts.", + bundle: .module + ), + systemImage: "shippingbox" + )) + artifactSaveOperationTask = nil + artifactSaveTask = nil + isSavingToArtifacts = false + } + } + } + + private static func saveArtifact( + operationTask: Task, + clock: any Clock, + timeout: Duration + ) async throws -> ChatArtifactSaveResult { + let (stream, continuation) = AsyncThrowingStream.makeStream() + let observationTask = Task { + do { + continuation.yield(try await operationTask.value) + continuation.finish() + } catch { + continuation.finish(throwing: error) + } + } + let timeoutTask = Task { + do { + try await clock.sleep(for: timeout) + } catch { + return + } + continuation.finish(throwing: ChatArtifactSaveTimeout.expired) + } + continuation.onTermination = { _ in + observationTask.cancel() + timeoutTask.cancel() + } + return try await withTaskCancellationHandler { + for try await result in stream { + return result + } + throw ChatArtifactSaveTimeout.expired + } onCancel: { + continuation.finish(throwing: CancellationError()) + } + } + + private func cancelOwnedTasks() { + artifactSaveTask?.cancel() + artifactSaveTask = nil + artifactSaveOperationTask?.cancel() + artifactSaveOperationTask = nil + artifactSaveCleanupTask?.cancel() + artifactSaveCleanupTask = nil + isSavingToArtifacts = false + } + private var fileActionFailurePresentation: ChatArtifactFailurePresentation { ChatArtifactFailurePresentation( error: model.toolbarSnapshot.fileActionState.failure ?? .loadFailed, @@ -264,3 +412,7 @@ struct ChatArtifactViewerPager: View { #endif } + +private enum ChatArtifactSaveTimeout: Error { + case expired +} diff --git a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Resources/Localizable.xcstrings b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Resources/Localizable.xcstrings index cdf727c63649..a31c3c65c37b 100644 --- a/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Resources/Localizable.xcstrings +++ b/Packages/iOS/CmuxAgentChatUI/Sources/CmuxAgentChatUI/Resources/Localizable.xcstrings @@ -4131,6 +4131,74 @@ } } }, + "chat.artifact.folder.incomplete_empty": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This folder could not be listed completely. Tap Retry to try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このフォルダを完全に一覧表示できませんでした。再試行をタップしてください。" + } + } + } + }, + "chat.artifact.folder.empty_refresh": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "New items may appear after a refresh." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "更新すると新しい項目が表示されることがあります。" + } + } + } + }, + "chat.artifact.folder.changed_while_loading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Some items changed while loading. Pull to refresh." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "読み込み中に一部の項目が変更されました。引っ張って更新してください。" + } + } + } + }, + "chat.artifact.folder.changed_empty": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Some items changed while loading. Tap Retry to try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "読み込み中に一部の項目が変更されました。再試行をタップしてください。" + } + } + } + }, "chat.artifact.folder.load_failed": { "extractionState": "manual", "localizations": { @@ -7848,6 +7916,57 @@ } } }, + "chat.artifact.save_to_artifacts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Save to cmux Artifacts" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux アーティファクトに保存" + } + } + } + }, + "chat.artifact.save_to_artifacts_failed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t save this file to cmux Artifacts." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このファイルを cmux アーティファクトに保存できませんでした。" + } + } + } + }, + "chat.artifact.saved_to_artifacts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Saved as %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ として保存しました" + } + } + } + }, "markdown.web.remoteImageBlocked": { "extractionState": "manual", "localizations": { diff --git a/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactLoaderTests.swift b/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactLoaderTests.swift index 2119cb8f1055..416e52576efe 100644 --- a/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactLoaderTests.swift +++ b/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactLoaderTests.swift @@ -181,6 +181,17 @@ struct ChatArtifactLoaderTests { #expect(await source.listRequestCount() == 1) } + @Test func chatSaveCapabilityRoutesToTheSessionSource() async throws { + let source = CountingArtifactSource() + let loader = ChatArtifactLoader(source: source, sessionID: "session-1") + + let result = try await loader.save(path: "/tmp/plan.md") + + #expect(loader.supportsArtifactSave) + #expect(result.reference == ".cmux/codex-session-1/artifacts/plan.md") + #expect(await source.lastSaveRequest() == "session-1:/tmp/plan.md") + } + @Test func panelScopeResolvesBytesAndPinsDirectoryBrowsingOff() async throws { let source = CountingTerminalArtifactSource() let loader = ChatArtifactLoader( @@ -254,8 +265,10 @@ private actor DataAccumulator { private actor CountingArtifactSource: ChatEventSource { nonisolated let supportsArtifacts = true + nonisolated let supportsArtifactSave = true private let thumbnailData: Data private var requests = 0 + private var saveRequest: String? init(thumbnailData: Data = Data([1, 2, 3])) { self.thumbnailData = thumbnailData @@ -265,6 +278,10 @@ private actor CountingArtifactSource: ChatEventSource { requests } + func lastSaveRequest() -> String? { + saveRequest + } + func history(sessionID: String, beforeSeq: Int?, limit: Int) async throws -> ChatHistoryPage { throw ChatArtifactError.unsupported } @@ -311,6 +328,15 @@ private actor CountingArtifactSource: ChatEventSource { func artifactList(sessionID: String, path: String) async throws -> ChatArtifactDirectoryListing { throw ChatArtifactError.unsupported } + + func artifactSave(sessionID: String, path: String) async throws -> ChatArtifactSaveResult { + saveRequest = "\(sessionID):\(path)" + return ChatArtifactSaveResult( + path: "/project/.cmux/codex-session-1/artifacts/plan.md", + relativePath: "codex-session-1/artifacts/plan.md", + reference: ".cmux/codex-session-1/artifacts/plan.md" + ) + } } private actor CountingTerminalArtifactSource { diff --git a/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactViewerModelTests.swift b/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactViewerModelTests.swift index e3454ff31cd8..e568ab5f6512 100644 --- a/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactViewerModelTests.swift +++ b/Packages/iOS/CmuxAgentChatUI/Tests/CmuxAgentChatUITests/ChatArtifactViewerModelTests.swift @@ -76,6 +76,38 @@ struct ChatArtifactViewerModelTests { #expect(unreachableModel.state == .failure(error: .macUnreachable, actualSize: nil)) } + @Test("Save-to-Artifacts eligibility follows the Mac stat policy") + @MainActor + func saveEligibilityFollowsHostPolicy() async { + let loader = ChatArtifactLoader( + supportsArtifacts: true, + stat: { _ in + ChatArtifactStat( + exists: true, + isDirectory: false, + size: 0, + modifiedAt: Date(timeIntervalSince1970: 0), + kind: .text, + mimeType: "text/plain", + canSaveToArtifacts: true + ) + }, + stream: { _, onChunk in + try await onChunk(ChatArtifactChunk( + data: Data(), + offset: 0, + totalSize: 0, + eof: true + )) + } + ) + let model = ChatArtifactViewerModel() + + await model.load(path: "/tmp/eligible.txt", loader: loader) + + #expect(model.canSaveToArtifacts) + } + @Test("damaged image bytes become a visible failure") @MainActor func damagedImageDoesNotBecomeABlankPreview() async { diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index d5e655b43b6d..c3f65a3d6f46 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -713,6 +713,19 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { "mobile.task.models.list", "mobile.directory.list", "mobile.directory.search": return false + case "mobile.chat.artifact.stat", "mobile.chat.artifact.fetch", + "mobile.chat.artifact.thumbnail", "mobile.chat.artifact.list", + "mobile.chat.artifact.gallery": + // Chat artifact handlers authorize the requested path against the + // session transcript. There is no workspace selector in these + // requests for an attach ticket to prove, so retain the ticket + // context and let the host's session-scoped policy decide. + return false + case "mobile.chat.artifact.save": + // Save is a Mac-scoped mutation. Retain a valid ticket context so + // the host can reject a workspace/terminal-scoped ticket instead + // of silently widening it to Stack-only account authorization. + return false case "workspace.create", "mobile.task.attachment.upload": return false case "workspace.action", "workspace.close", "mobile.surface.focus", diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCChatArtifactAuthTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCChatArtifactAuthTests.swift new file mode 100644 index 000000000000..0e2141e3cfdc --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCChatArtifactAuthTests.swift @@ -0,0 +1,65 @@ +import CMUXMobileCore +import Foundation +import Testing +@testable import CmuxMobileRPC + +@Suite struct MobileCoreRPCChatArtifactAuthTests { + @Test(arguments: [ + "mobile.chat.artifact.stat", + "mobile.chat.artifact.fetch", + "mobile.chat.artifact.thumbnail", + "mobile.chat.artifact.list", + "mobile.chat.artifact.save", + "mobile.chat.artifact.gallery", + ]) + func chatArtifactRequestsRetainSessionAuthorizationContext(method: String) async throws { + let route = try hostPortRoute( + kind: .debugLoopback, + host: "127.0.0.1", + port: 58_465 + ) + + for workspaceID in ["workspace-main", ""] { + let transport = QueuedCancellationProbeTransport() + let runtime = TestMobileSyncRuntime( + transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), + stackAccessToken: "test-stack-token" + ) + let ticket = try CmxAttachTicket( + workspaceID: workspaceID, + terminalID: nil, + macDeviceID: "test-mac", + macDisplayName: "Test Mac", + routes: [route], + expiresAt: Date().addingTimeInterval(60), + authToken: "ticket-secret" + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: ticket, + allowsStackAuthFallback: true + ) + var params: [String: Any] = ["session_id": "session"] + if method != "mobile.chat.artifact.gallery" { + params["path"] = "/tmp/artifact" + } + let request = try MobileCoreRPCClient.requestData( + method: method, + params: params + ) + let task = Task { try await client.sendRequest(request) } + let sent = try await transport.waitForSentRequestCount(1) + task.cancel() + await transport.releaseFirstSend() + _ = try? await task.value + + let frame = try #require(sent.first) + #expect(frame.method == method) + #expect(frame.attachToken == "ticket-secret") + #expect(frame.stackAccessToken == "test-stack-token") + #expect(frame.hasAuth) + await client.disconnect() + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileChatEventSource.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileChatEventSource.swift index 1931da92b12f..586876e9b090 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileChatEventSource.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileChatEventSource.swift @@ -29,6 +29,8 @@ public actor MobileChatEventSource: ChatEventSource { public nonisolated let supportsArtifacts: Bool /// Whether the connected Mac supports recursive chat folder browsing. public nonisolated let supportsArtifactFolders: Bool + /// Whether the connected Mac supports saving chat files to project Artifacts. + public nonisolated let supportsArtifactSave: Bool /// Whether the connected Mac supports terminal-scoped directory listing. public nonisolated let supportsTerminalArtifactList: Bool /// Whether the connected Mac supports lifecycle-bound panel file reads. @@ -40,12 +42,20 @@ public actor MobileChatEventSource: ChatEventSource { /// Creates the adapter. /// - /// - Parameter client: The connected RPC client for the paired Mac. + /// - Parameters: + /// - client: The connected RPC client for the paired Mac. + /// - supportsArtifacts: Whether basic chat artifact operations are available. + /// - supportsArtifactGallery: Whether session-wide artifact gallery paging is available. + /// - supportsArtifactFolders: Whether recursive chat folder browsing is available. + /// - supportsArtifactSave: Whether chat artifacts can be persisted into project Artifacts. + /// - supportsTerminalArtifactList: Whether terminal-scoped directory listing is available. + /// - supportsArtifactLane: Whether artifact bytes may use the peer-bound Iroh lane. public init( client: MobileCoreRPCClient, supportsArtifacts: Bool = false, supportsArtifactGallery: Bool = false, supportsArtifactFolders: Bool = false, + supportsArtifactSave: Bool = false, supportsTerminalArtifactList: Bool = false, supportsPanelArtifacts: Bool = false, supportsArtifactLane: Bool = false, @@ -56,6 +66,7 @@ public actor MobileChatEventSource: ChatEventSource { self.supportsArtifacts = supportsArtifacts self.supportsArtifactGallery = supportsArtifactGallery self.supportsArtifactFolders = supportsArtifactFolders + self.supportsArtifactSave = supportsArtifactSave self.supportsTerminalArtifactList = supportsTerminalArtifactList self.supportsPanelArtifacts = supportsPanelArtifacts self.supportsArtifactLane = supportsArtifactLane @@ -372,6 +383,25 @@ public actor MobileChatEventSource: ChatEventSource { } } + /// Persists one chat-authorized host file into the session project's artifact store. + /// + /// - Parameters: + /// - sessionID: Session whose artifact scope authorizes the path. + /// - path: Absolute host path to persist. + /// - Returns: Stable project-local path and prompt reference. + public func artifactSave(sessionID: String, path: String) async throws -> ChatArtifactSaveResult { + guard supportsArtifactSave else { + throw ChatArtifactError.unsupported + } + return try await artifactCall( + method: "mobile.chat.artifact.save", + params: [ + "session_id": sessionID, + "path": path, + ] + ) + } + /// Fetches one stable page of the session-wide artifact gallery. /// /// - Parameters: diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AgentChat.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AgentChat.swift index 4b9b23257ce5..cd6bad51183a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AgentChat.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AgentChat.swift @@ -13,6 +13,7 @@ extension MobileShellComposite { supportsArtifacts: supportsChatArtifacts, supportsArtifactGallery: supportsChatArtifactGallery, supportsArtifactFolders: supportsChatArtifactFolders, + supportsArtifactSave: supportsChatArtifactSave, supportsTerminalArtifactList: supportsTerminalArtifactList, supportsPanelArtifacts: supportsPanelArtifacts, supportsArtifactLane: supportsIrohArtifactLane, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift index d0331397c583..4b7965b48f72 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift @@ -166,6 +166,10 @@ extension MobileShellComposite { public var supportsDogfoodFeedback: Bool { supportedHostCapabilities.contains(Self.dogfoodFeedbackCapability) } /// Whether the Mac supports chat artifact stat/fetch/thumbnail/list RPCs. public var supportsChatArtifacts: Bool { supportedHostCapabilities.contains(Self.chatArtifactCapability) } + /// Whether chat artifact paths can be saved into the project-local store. + public var supportsChatArtifactSave: Bool { + supportedHostCapabilities.contains(Self.chatArtifactSaveCapability) + } /// Whether the Mac supports session-wide artifact gallery paging and search. public var supportsChatArtifactGallery: Bool { supportedHostCapabilities.contains(Self.chatArtifactGalleryCapability) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 0bdabe701b42..65b66b2b682b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -144,6 +144,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { static let taskAttachmentCapability = "task.attachments.v1" static let taskModelsCapability = "task.models.v1" static let chatArtifactCapability = "chat.artifact.v1" + static let chatArtifactSaveCapability = "chat.artifact.save.v1" static let chatArtifactGalleryCapability = "chat.artifact.gallery.v1" static let terminalArtifactCapability = "terminal.artifact.v1" static let panelArtifactCapability = "panel.artifact.v1" diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShellReleaseGateSupport/MobileIrohReleaseGateRPCMethodInventory.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShellReleaseGateSupport/MobileIrohReleaseGateRPCMethodInventory.swift index 4c80e2395843..79ad017d66cf 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShellReleaseGateSupport/MobileIrohReleaseGateRPCMethodInventory.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShellReleaseGateSupport/MobileIrohReleaseGateRPCMethodInventory.swift @@ -26,6 +26,7 @@ extension MobileShellComposite { "mobile.chat.artifact.fetch", "mobile.chat.artifact.gallery", "mobile.chat.artifact.list", + "mobile.chat.artifact.save", "mobile.chat.artifact.stat", "mobile.chat.artifact.thumbnail", "mobile.chat.history", diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift index cdf1b3d681b5..3266c3fdc41d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift @@ -25,17 +25,20 @@ import Testing "terminal.artifact.v1", ] #expect(!store.supportsChatArtifactFolders) + #expect(!store.supportsChatArtifactSave) #expect(!store.supportsTerminalArtifactList) #expect(!store.supportsPanelArtifacts) #expect(!store.supportsIrohArtifactLane) store.supportedHostCapabilities.formUnion([ "chat.artifact.folders.v1", + "chat.artifact.save.v1", "terminal.artifact.list.v1", "iroh.artifact_lane.v1", "panel.artifact.v1", ]) #expect(store.supportsChatArtifactFolders) + #expect(store.supportsChatArtifactSave) #expect(store.supportsTerminalArtifactList) #expect(store.supportsIrohArtifactLane) #expect(store.supportsPanelArtifacts) diff --git a/Packages/macOS/CmuxArtifacts/Package.swift b/Packages/macOS/CmuxArtifacts/Package.swift new file mode 100644 index 000000000000..e087a0c67e3c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Package.swift @@ -0,0 +1,31 @@ +// swift-tools-version: 6.0 + +import PackageDescription + +let package = Package( + name: "CmuxArtifacts", + platforms: [ + .macOS(.v14), + ], + products: [ + .library(name: "CmuxArtifacts", targets: ["CmuxArtifacts"]), + ], + dependencies: [ + .package(path: "../CmuxFoundation"), + ], + targets: [ + .target( + name: "CmuxArtifacts", + dependencies: ["CmuxFoundation"], + swiftSettings: [ + .swiftLanguageMode(.v6), + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("InternalImportsByDefault"), + ] + ), + .testTarget( + name: "CmuxArtifactsTests", + dependencies: ["CmuxArtifacts"] + ), + ] +) diff --git a/Packages/macOS/CmuxArtifacts/README.md b/Packages/macOS/CmuxArtifacts/README.md new file mode 100644 index 000000000000..21b601b13746 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/README.md @@ -0,0 +1,48 @@ +# CmuxArtifacts + +`CmuxArtifacts` owns cmux's local, project-scoped session filesystem. + +Each agent session owns an ordinary directory under `/.cmux/`, with +`artifacts/` and `notes/` as sibling content directories: + +```text +/.cmux/ + / + _session.json + _workspace.json + artifacts/ + notes/ + .metadata/ + provenance/ + imports/ +``` + +`LocalArtifactRepository` treats every live scan as authoritative. Users and +agents may rename or reorganize files and session folders with Finder or the +shell; small marker files let later writes rediscover a moved session without a +path index. `ArtifactCaptureService` applies conservative automatic-capture +limits before importing agent-created files. Content-addressed capture history +lives under `.cmux/.metadata/provenance/`, so file moves do not lose +deduplication or provenance. + +App, CLI, and sidebar callers share `LocalArtifactRepository`; artifact callers +use `ArtifactStoring` and Note callers use `NoteStoring`. UI code must project +`ArtifactSnapshot` values into immutable rows instead of retaining the +repository below a list boundary. Prompt-ready references are stable +project-relative paths such as `.cmux//notes/plan.md`. + +Projects can override the conservative defaults with a partial +`.cmux/artifacts.json` file. Supported keys are `automaticCaptureEnabled`, +`captureCreatedAndAttached`, `captureReferencedEphemeral`, `maximumFileBytes`, +`maximumTextFileBytes`, `maximumTranscriptScanBytes`, +`maximumAutomaticCaptureBytes`, `maximumFilesPerCapture`, +`deduplicationScanNodeLimit`, +`deduplicationHashByteLimit`, `contentSearchMaximumBytes`, +`contentSearchTotalMaximumBytes`, `maximumSearchResults`, `allowedExtensions`, and +`ephemeralPathPrefixes`; omitted keys inherit the defaults in +`ArtifactCaptureConfiguration`. + +Unstructured referenced paths must remain inside the project and beneath one of +the normalized `ephemeralPathPrefixes`. Structured created and attached paths +use their authoritative provenance instead; external references require a +manual add. diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactAncestorDirectories.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactAncestorDirectories.swift new file mode 100644 index 000000000000..453eae838703 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactAncestorDirectories.swift @@ -0,0 +1,29 @@ +import Foundation + +/// Iterates from a filesystem directory through its ancestors, including the root directory. +struct ArtifactAncestorDirectories: IteratorProtocol, Sequence { + private var nextDirectory: URL? + + init(startingAt directory: URL) { + nextDirectory = directory.standardizedFileURL + } + + mutating func next() -> URL? { + guard let current = nextDirectory else { return nil } + let currentPath = current.path + guard currentPath != "/" else { + nextDirectory = nil + return current + } + + let rawParentPath = (currentPath as NSString).deletingLastPathComponent + let parentPath = rawParentPath.isEmpty ? "/" : rawParentPath + guard parentPath != currentPath else { + nextDirectory = nil + return current + } + + nextDirectory = URL(fileURLWithPath: parentPath, isDirectory: true).standardizedFileURL + return current + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactBoundedFileReader.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactBoundedFileReader.swift new file mode 100644 index 000000000000..892423169724 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactBoundedFileReader.swift @@ -0,0 +1,84 @@ +import Darwin +import Foundation + +/// Reads one regular artifact through a no-follow descriptor with a hard byte cap. +struct ArtifactBoundedFileReader { + let fileManager: FileManager + + func pathEntryExists(url: URL) throws -> Bool { + var status = stat() + if lstat(url.path, &status) == 0 { return true } + if errno == ENOENT { return false } + throw CocoaError(.fileReadUnknown) + } + + func data( + url: URL, + allowedRoot: URL, + maximumBytes: Int64, + expectedIdentity: ArtifactFileIdentity? = nil + ) throws -> Data? { + try Task.checkCancellation() + guard maximumBytes >= 0, maximumBytes < Int.max else { return nil } + let descriptor = Darwin.open( + url.path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { return nil } + defer { Darwin.close(descriptor) } + + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0, + status.st_size <= maximumBytes else { + return nil + } + if let expectedIdentity, + ArtifactFileIdentity( + device: UInt64(status.st_dev), + inode: UInt64(status.st_ino) + ) != expectedIdentity { + return nil + } + + var descriptorInfo = vnode_fdinfowithpath() + let pathResult = proc_pidfdinfo( + Darwin.getpid(), + descriptor, + PROC_PIDFDVNODEPATHINFO, + &descriptorInfo, + Int32(MemoryLayout.size) + ) + guard pathResult > 0 else { return nil } + let descriptorPath = withUnsafeBytes(of: &descriptorInfo.pvip.vip_path) { rawBuffer -> String in + guard let baseAddress = rawBuffer.baseAddress else { return "" } + return String(cString: baseAddress.assumingMemoryBound(to: CChar.self)) + } + let descriptorURL = URL(fileURLWithPath: descriptorPath, isDirectory: false) + guard ArtifactPathResolver(fileManager: fileManager) + .relativePath(descriptorURL, root: allowedRoot) != nil else { + return nil + } + + let limit = Int(maximumBytes) + var data = Data() + data.reserveCapacity(min(Int(status.st_size), limit)) + var buffer = [UInt8](repeating: 0, count: min(64 * 1024, limit + 1)) + while data.count <= limit { + try Task.checkCancellation() + let requested = min(buffer.count, limit + 1 - data.count) + guard requested > 0 else { break } + let count = buffer.withUnsafeMutableBytes { bytes in + Darwin.read(descriptor, bytes.baseAddress, requested) + } + if count == 0 { break } + if count < 0 { + if errno == EINTR { continue } + return nil + } + data.append(contentsOf: buffer.prefix(count)) + } + return data.count <= limit ? data : nil + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCandidate.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCandidate.swift new file mode 100644 index 000000000000..7f5e38ffde8d --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCandidate.swift @@ -0,0 +1,32 @@ +public import Foundation + +/// A detected filesystem path that may be eligible for automatic capture. +public struct ArtifactCandidate: Equatable, Sendable { + /// Source file on the local filesystem. + public let sourceURL: URL + /// Detection provenance used by automatic-capture policy. + public let provenance: ArtifactProvenance + /// Canonical path authorized before an explicit save, when one exists. + public let expectedCanonicalPath: String? + /// Device/inode authorized before an explicit save, when one exists. + public let expectedIdentity: ArtifactFileIdentity? + + /// Creates a detected artifact candidate. + /// + /// - Parameters: + /// - sourceURL: Source file on the local filesystem. + /// - provenance: How the artifact pipeline found the path. + /// - expectedCanonicalPath: Previously authorized canonical identity. + /// - expectedIdentity: Previously authorized device/inode identity. + public init( + sourceURL: URL, + provenance: ArtifactProvenance, + expectedCanonicalPath: String? = nil, + expectedIdentity: ArtifactFileIdentity? = nil + ) { + self.sourceURL = sourceURL + self.provenance = provenance + self.expectedCanonicalPath = expectedCanonicalPath + self.expectedIdentity = expectedIdentity + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration+Codable.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration+Codable.swift new file mode 100644 index 000000000000..d0544990ec18 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration+Codable.swift @@ -0,0 +1,90 @@ +import Foundation + +extension ArtifactCaptureConfiguration { + private enum CodingKeys: String, CodingKey { + case automaticCaptureEnabled + case captureCreatedAndAttached + case captureReferencedEphemeral + case maximumFileBytes + case maximumTextFileBytes + case maximumTranscriptScanBytes + case maximumAutomaticCaptureBytes + case maximumFilesPerCapture + case deduplicationScanNodeLimit + case deduplicationHashByteLimit + case contentSearchMaximumBytes + case contentSearchTotalMaximumBytes + case maximumSearchResults + case allowedExtensions + case ephemeralPathPrefixes + } + + /// Decodes a partial project configuration by filling omitted keys from + /// ``defaultValue``. + public init(from decoder: any Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + let defaults = Self.defaultValue + self.init( + automaticCaptureEnabled: try values.decodeIfPresent(Bool.self, forKey: .automaticCaptureEnabled) + ?? defaults.automaticCaptureEnabled, + captureCreatedAndAttached: try values.decodeIfPresent(Bool.self, forKey: .captureCreatedAndAttached) + ?? defaults.captureCreatedAndAttached, + captureReferencedEphemeral: try values.decodeIfPresent(Bool.self, forKey: .captureReferencedEphemeral) + ?? defaults.captureReferencedEphemeral, + maximumFileBytes: try values.decodeIfPresent(Int64.self, forKey: .maximumFileBytes) + ?? defaults.maximumFileBytes, + maximumTextFileBytes: try values.decodeIfPresent(Int64.self, forKey: .maximumTextFileBytes) + ?? defaults.maximumTextFileBytes, + maximumTranscriptScanBytes: try values.decodeIfPresent( + Int64.self, + forKey: .maximumTranscriptScanBytes + ) ?? defaults.maximumTranscriptScanBytes, + maximumAutomaticCaptureBytes: try values.decodeIfPresent( + Int64.self, + forKey: .maximumAutomaticCaptureBytes + ) ?? defaults.maximumAutomaticCaptureBytes, + maximumFilesPerCapture: try values.decodeIfPresent(Int.self, forKey: .maximumFilesPerCapture) + ?? defaults.maximumFilesPerCapture, + deduplicationScanNodeLimit: try values.decodeIfPresent( + Int.self, + forKey: .deduplicationScanNodeLimit + ) ?? defaults.deduplicationScanNodeLimit, + deduplicationHashByteLimit: try values.decodeIfPresent( + Int64.self, + forKey: .deduplicationHashByteLimit + ) ?? defaults.deduplicationHashByteLimit, + contentSearchMaximumBytes: try values.decodeIfPresent(Int64.self, forKey: .contentSearchMaximumBytes) + ?? defaults.contentSearchMaximumBytes, + contentSearchTotalMaximumBytes: try values.decodeIfPresent( + Int64.self, + forKey: .contentSearchTotalMaximumBytes + ) ?? defaults.contentSearchTotalMaximumBytes, + maximumSearchResults: try values.decodeIfPresent(Int.self, forKey: .maximumSearchResults) + ?? defaults.maximumSearchResults, + allowedExtensions: try values.decodeIfPresent(Set.self, forKey: .allowedExtensions) + ?? defaults.allowedExtensions, + ephemeralPathPrefixes: try values.decodeIfPresent([String].self, forKey: .ephemeralPathPrefixes) + ?? defaults.ephemeralPathPrefixes + ) + } + + /// Encodes every effective project configuration key. + public func encode(to encoder: any Encoder) throws { + var values = encoder.container(keyedBy: CodingKeys.self) + try values.encode(automaticCaptureEnabled, forKey: .automaticCaptureEnabled) + try values.encode(captureCreatedAndAttached, forKey: .captureCreatedAndAttached) + try values.encode(captureReferencedEphemeral, forKey: .captureReferencedEphemeral) + try values.encode(maximumFileBytes, forKey: .maximumFileBytes) + try values.encode(maximumTextFileBytes, forKey: .maximumTextFileBytes) + try values.encode(maximumTranscriptScanBytes, forKey: .maximumTranscriptScanBytes) + try values.encode(maximumAutomaticCaptureBytes, forKey: .maximumAutomaticCaptureBytes) + try values.encode(maximumFilesPerCapture, forKey: .maximumFilesPerCapture) + try values.encode(deduplicationScanNodeLimit, forKey: .deduplicationScanNodeLimit) + try values.encode(deduplicationHashByteLimit, forKey: .deduplicationHashByteLimit) + try values.encode(contentSearchMaximumBytes, forKey: .contentSearchMaximumBytes) + try values.encode(contentSearchTotalMaximumBytes, forKey: .contentSearchTotalMaximumBytes) + try values.encode(maximumSearchResults, forKey: .maximumSearchResults) + try values.encode(allowedExtensions, forKey: .allowedExtensions) + try values.encode(ephemeralPathPrefixes, forKey: .ephemeralPathPrefixes) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration.swift new file mode 100644 index 000000000000..e521d486ae58 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureConfiguration.swift @@ -0,0 +1,155 @@ +import Foundation + +/// Per-project automatic-capture and search limits loaded from `.cmux/artifacts.json`. +public struct ArtifactCaptureConfiguration: Codable, Equatable, Sendable { + /// Whether transcript and terminal detections may trigger automatic capture. + public var automaticCaptureEnabled: Bool + /// Whether structured created and attached paths are copied from outside the store. + public var captureCreatedAndAttached: Bool + /// Whether unstructured project-local references under a trusted ephemeral root + /// are copied automatically. External references always require an explicit manual add. + public var captureReferencedEphemeral: Bool + /// Maximum bytes for image, video, markdown, HTML, and patch imports. + public var maximumFileBytes: Int64 + /// Stricter maximum bytes for plain and structured-text imports. + public var maximumTextFileBytes: Int64 + /// Maximum transcript bytes parsed by one automatic capture scan. + public var maximumTranscriptScanBytes: Int64 + /// Maximum aggregate source bytes staged by one automatic capture. + public var maximumAutomaticCaptureBytes: Int64 + /// Maximum candidates handled in one persistence batch before backlog continuation. + public var maximumFilesPerCapture: Int + /// Maximum files and folders visited while recovering a moved deduplication target. + public var deduplicationScanNodeLimit: Int + /// Maximum matching-size bytes hashed during one deduplication recovery scan. + public var deduplicationHashByteLimit: Int64 + /// Maximum text bytes decoded while content-searching one artifact. + public var contentSearchMaximumBytes: Int64 + /// Maximum aggregate text bytes decoded by one content search. + public var contentSearchTotalMaximumBytes: Int64 + /// Maximum filename and content matches returned by one search. + public var maximumSearchResults: Int + /// Filename extensions eligible for automatic and manual import. + public var allowedExtensions: Set + /// Trusted ephemeral prefixes used to narrow project-local referenced capture. + /// Project configuration may narrow these roots but cannot expand them. + public var ephemeralPathPrefixes: [String] + + /// Default conservative capture policy. + public static let defaultValue = ArtifactCaptureConfiguration( + automaticCaptureEnabled: true, + captureCreatedAndAttached: true, + captureReferencedEphemeral: true, + maximumFileBytes: 50 * 1024 * 1024, + maximumTextFileBytes: 2 * 1024 * 1024, + maximumTranscriptScanBytes: 8 * 1024 * 1024, + maximumAutomaticCaptureBytes: 128 * 1024 * 1024, + maximumFilesPerCapture: 32, + deduplicationScanNodeLimit: 100_000, + deduplicationHashByteLimit: 512 * 1024 * 1024, + contentSearchMaximumBytes: 1024 * 1024, + contentSearchTotalMaximumBytes: 16 * 1024 * 1024, + maximumSearchResults: 500, + allowedExtensions: [ + "png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "svg", + "mp4", "mov", "m4v", "webm", + "md", "markdown", "mdown", "mkd", "html", "htm", "diff", "patch", + "txt", "log", "json", "jsonl", "yaml", "yml", "toml", "csv", "tsv", "xml", + ], + ephemeralPathPrefixes: ["/tmp", "/private/tmp", "/var/folders"] + ) + + /// Creates a capture configuration. + /// + /// - Parameters: + /// - automaticCaptureEnabled: Whether automatic transcript capture is enabled. + /// - captureCreatedAndAttached: Whether structured created and attached paths are eligible. + /// - captureReferencedEphemeral: Whether project-local ephemeral references are eligible. + /// - maximumFileBytes: Maximum bytes for rich-media and document imports. + /// - maximumTextFileBytes: Maximum bytes for plain and structured text imports. + /// - maximumTranscriptScanBytes: Maximum transcript bytes parsed per automatic scan. + /// - maximumAutomaticCaptureBytes: Maximum aggregate bytes staged per automatic capture. + /// - maximumFilesPerCapture: Maximum candidates processed in one persistence batch. + /// - deduplicationScanNodeLimit: Maximum nodes visited during moved-file recovery. + /// - deduplicationHashByteLimit: Maximum matching-size bytes hashed during recovery. + /// - contentSearchMaximumBytes: Maximum bytes decoded from one searchable file. + /// - contentSearchTotalMaximumBytes: Maximum aggregate bytes decoded by one search. + /// - maximumSearchResults: Maximum matches returned by one search. + /// - allowedExtensions: Filename extensions eligible for import. + /// - ephemeralPathPrefixes: Trusted ephemeral roots, which normalization may only narrow. + public init( + automaticCaptureEnabled: Bool, + captureCreatedAndAttached: Bool, + captureReferencedEphemeral: Bool, + maximumFileBytes: Int64, + maximumTextFileBytes: Int64, + maximumTranscriptScanBytes: Int64, + maximumAutomaticCaptureBytes: Int64, + maximumFilesPerCapture: Int, + deduplicationScanNodeLimit: Int, + deduplicationHashByteLimit: Int64, + contentSearchMaximumBytes: Int64, + contentSearchTotalMaximumBytes: Int64, + maximumSearchResults: Int, + allowedExtensions: Set, + ephemeralPathPrefixes: [String] + ) { + self.automaticCaptureEnabled = automaticCaptureEnabled + self.captureCreatedAndAttached = captureCreatedAndAttached + self.captureReferencedEphemeral = captureReferencedEphemeral + self.maximumFileBytes = maximumFileBytes + self.maximumTextFileBytes = maximumTextFileBytes + self.maximumTranscriptScanBytes = maximumTranscriptScanBytes + self.maximumAutomaticCaptureBytes = maximumAutomaticCaptureBytes + self.maximumFilesPerCapture = maximumFilesPerCapture + self.deduplicationScanNodeLimit = deduplicationScanNodeLimit + self.deduplicationHashByteLimit = deduplicationHashByteLimit + self.contentSearchMaximumBytes = contentSearchMaximumBytes + self.contentSearchTotalMaximumBytes = contentSearchTotalMaximumBytes + self.maximumSearchResults = maximumSearchResults + self.allowedExtensions = allowedExtensions + self.ephemeralPathPrefixes = ephemeralPathPrefixes + } + + /// Returns limits normalized to safe nonnegative bounds. + public var normalized: ArtifactCaptureConfiguration { + var value = self + value.maximumFileBytes = min(max(1, maximumFileBytes), 512 * 1024 * 1024) + value.maximumTextFileBytes = min(max(1, maximumTextFileBytes), value.maximumFileBytes) + value.maximumTranscriptScanBytes = min( + max(1, maximumTranscriptScanBytes), + 128 * 1024 * 1024 + ) + value.maximumAutomaticCaptureBytes = min( + max(1, maximumAutomaticCaptureBytes), + 256 * 1024 * 1024 + ) + value.maximumFilesPerCapture = min(max(1, maximumFilesPerCapture), 256) + value.deduplicationScanNodeLimit = min(max(1, deduplicationScanNodeLimit), 1_000_000) + value.deduplicationHashByteLimit = min( + max(1, deduplicationHashByteLimit), + 4 * 1024 * 1024 * 1024 + ) + value.contentSearchMaximumBytes = min(max(1, contentSearchMaximumBytes), 8 * 1024 * 1024) + value.contentSearchTotalMaximumBytes = min( + max(value.contentSearchMaximumBytes, contentSearchTotalMaximumBytes), + 128 * 1024 * 1024 + ) + value.maximumSearchResults = min(max(1, maximumSearchResults), 5_000) + value.allowedExtensions = Set(allowedExtensions.map { $0.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) }.filter { !$0.isEmpty }) + let trustedRoots = Self.defaultValue.ephemeralPathPrefixes.map { + URL(fileURLWithPath: $0, isDirectory: true).standardizedFileURL.path + } + value.ephemeralPathPrefixes = ephemeralPathPrefixes.compactMap { rawPrefix in + guard rawPrefix.hasPrefix("/") else { return nil } + let prefix = URL(fileURLWithPath: rawPrefix, isDirectory: true).standardizedFileURL.path + guard trustedRoots.contains(where: { trustedRoot in + prefix == trustedRoot || prefix.hasPrefix(trustedRoot + "/") + }) else { + return nil + } + return prefix + } + return value + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureContext.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureContext.swift new file mode 100644 index 000000000000..1039116e161e --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureContext.swift @@ -0,0 +1,41 @@ +public import Foundation + +/// Project, workspace, and agent-session identity used to group a capture. +public struct ArtifactCaptureContext: Equatable, Sendable { + /// Root directory that owns the session-oriented `.cmux` filesystem. + public let projectRoot: URL + /// Stable cmux workspace identity, when known. + public let workspaceID: String? + /// Human-readable workspace title, when known. + public let workspaceTitle: String? + /// Stable agent session identity, when known. + public let sessionID: String? + /// Agent family such as `codex` or `claude`, when known. + public let agentName: String? + + /// Creates capture grouping context. + /// + /// - Parameters: + /// - projectRoot: Root directory that owns `.cmux`. + /// - workspaceID: Stable cmux workspace identity, when known. + /// - workspaceTitle: Human-readable workspace title, when known. + /// - sessionID: Stable agent session identity, when known. + /// - agentName: Agent family, when known. + public init( + projectRoot: URL, + workspaceID: String? = nil, + workspaceTitle: String? = nil, + sessionID: String? = nil, + agentName: String? = nil + ) { + self.projectRoot = projectRoot + self.workspaceID = workspaceID + self.workspaceTitle = workspaceTitle + self.sessionID = sessionID + self.agentName = agentName + } + + var sessionIdentity: ArtifactSessionIdentity { + ArtifactSessionIdentity(provider: agentName, sessionID: sessionID) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryFinder.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryFinder.swift new file mode 100644 index 000000000000..fa32a21375c0 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryFinder.swift @@ -0,0 +1,101 @@ +import Foundation + +/// Reuses cmux-managed grouping markers after users move or rename folders. +struct ArtifactCaptureDirectoryFinder { + let fileManager: FileManager + let decoder: JSONDecoder + let nodeBudget: Int + + func resolve( + paths: ArtifactStorePaths, + context: ArtifactCaptureContext, + pathResolver: ArtifactPathResolver, + kind: CmuxSessionContentKind = .artifacts + ) throws -> ArtifactCaptureDirectoryResolution { + let sessionIdentity = context.sessionIdentity + let markerCatalog = ArtifactMarkerDirectoryCatalog( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ) + if sessionIdentity.sessionID != nil { + let matches = try markerCatalog.sessionDirectories( + paths: paths, + pathResolver: pathResolver + ).filter { $0.marker.identity == sessionIdentity }.map(\.directory) + if let sessionRoot = try uniqueDirectory(matches, paths: paths) { + return ArtifactCaptureDirectoryResolution( + directory: sessionRoot.appendingPathComponent(kind.rawValue, isDirectory: true) + ) + } + } + + let fallback = pathResolver.contentDirectory(paths: paths, context: context, kind: kind) + if sessionIdentity.sessionID != nil { + try validateFallbackSessionMarker( + fallback: fallback, + sessionIdentity: sessionIdentity, + paths: paths + ) + return ArtifactCaptureDirectoryResolution(directory: fallback) + } + guard let workspaceID = normalized(context.workspaceID) else { + return ArtifactCaptureDirectoryResolution(directory: fallback) + } + let workspaceDirectoryPaths = Set( + try markerCatalog.workspaceDirectories( + paths: paths, + pathResolver: pathResolver + ).filter { $0.marker.workspaceID == workspaceID } + .map { $0.directory.standardizedFileURL.path } + ) + let matches = try markerCatalog.sessionDirectories( + paths: paths, + pathResolver: pathResolver + ).filter { + $0.marker.identity == sessionIdentity + && workspaceDirectoryPaths.contains($0.directory.standardizedFileURL.path) + }.map(\.directory) + guard let sessionRoot = try uniqueDirectory(matches, paths: paths) else { + return ArtifactCaptureDirectoryResolution(directory: fallback) + } + return ArtifactCaptureDirectoryResolution( + directory: sessionRoot.appendingPathComponent(kind.rawValue, isDirectory: true) + ) + } + + private func validateFallbackSessionMarker( + fallback: URL, + sessionIdentity: ArtifactSessionIdentity, + paths: ArtifactStorePaths + ) throws { + let markerURL = fallback.deletingLastPathComponent() + .appendingPathComponent(ArtifactPathResolver.sessionMarkerName) + let reader = ArtifactBoundedFileReader(fileManager: fileManager) + guard try reader.pathEntryExists(url: markerURL) else { return } + guard let data = try reader.data( + url: markerURL, + allowedRoot: paths.filesystemRoot, + maximumBytes: 256 * 1024 + ), let marker = try? decoder.decode(ArtifactSessionMarker.self, from: data), + marker.identity == sessionIdentity else { + throw ArtifactStoreError.corruptProvenance(markerURL.path) + } + } + + private func uniqueDirectory( + _ matches: [URL], + paths: ArtifactStorePaths + ) throws -> URL? { + guard matches.count <= 1 else { + throw ArtifactStoreError.corruptProvenance(paths.filesystemRoot.path) + } + return matches.first + } + + private func normalized(_ value: String?) -> String? { + guard let value else { return nil } + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryResolution.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryResolution.swift new file mode 100644 index 000000000000..8a6809b78113 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureDirectoryResolution.swift @@ -0,0 +1,6 @@ +import Foundation + +/// Marker-aware destination selected for one capture. +struct ArtifactCaptureDirectoryResolution { + let directory: URL +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureService.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureService.swift new file mode 100644 index 000000000000..f30218e0d62d --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCaptureService.swift @@ -0,0 +1,297 @@ +public import Foundation + +/// Applies project capture policy before importing detected agent artifacts. +public actor ArtifactCaptureService: ArtifactCapturing { + private static let maximumManualSelectionFiles = 1_024 + private let store: any ArtifactStoring + private let fileManager: FileManager + + /// Creates a capture service backed by a shared artifact store. + /// + /// - Parameters: + /// - store: Filesystem store used by automatic and manual capture. + /// - fileManager: Filesystem dependency used for canonical path policy. + public init(store: any ArtifactStoring, fileManager: FileManager = .default) { + self.store = store + self.fileManager = fileManager + } + + /// Returns the transcript budget when automatic capture is enabled. + /// + /// - Parameter projectRoot: Canonical project root containing `.cmux`. + /// - Returns: Normalized byte limit, or `nil` when automatic capture is disabled. + public func automaticTranscriptScanByteLimit(projectRoot: URL) async -> UInt64? { + let configuration = await store.configuration(projectRoot: projectRoot).normalized + guard configuration.automaticCaptureEnabled else { return nil } + return UInt64(configuration.maximumTranscriptScanBytes) + } + + /// Returns whether the effective project policy accepts one explicit file extension. + /// + /// Actual persistence still revalidates type, size, identity, and Git privacy. + /// + /// - Parameters: + /// - sourceURL: Candidate file whose extension is being presented. + /// - context: Project identity used to load the effective configuration. + /// - Returns: `true` when an explicit add may proceed to full validation. + public func permitsExplicitAdd( + sourceURL: URL, + context: ArtifactCaptureContext + ) async -> Bool { + let configuration = await store + .configuration(projectRoot: context.projectRoot) + .normalized + guard configuration.allowedExtensions.contains( + sourceURL.pathExtension.lowercased() + ), let values = try? sourceURL.resourceValues( + forKeys: [.isRegularFileKey, .fileSizeKey] + ), values.isRegularFile == true, let fileSize = values.fileSize, + fileSize >= 0 else { + return false + } + let limit = ArtifactFileKind(fileURL: sourceURL) == .text + ? configuration.maximumTextFileBytes + : configuration.maximumFileBytes + return Int64(fileSize) <= limit + } + + /// Captures eligible detected paths using the project's effective policy. + /// + /// Duplicate path detections in one scan are folded together and the + /// configured candidate limit is applied before any file reads occur. + /// + /// - Parameters: + /// - candidates: Paths emitted by an agent artifact detector. + /// - context: Project, workspace, and session grouping identity. + /// - capturedAt: Timestamp recorded for accepted paths. + /// - Returns: One observable outcome for every distinct candidate. + public func capture( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + capturedAt: Date = .now + ) async -> [ArtifactImportOutcome] { + let configuration = await store.configuration(projectRoot: context.projectRoot).normalized + let distinctCandidates = distinct(candidates) + guard configuration.automaticCaptureEnabled else { + return distinctCandidates.map { _ in .skipped(.automaticCaptureDisabled) } + } + + var outcomes = Array(repeating: nil, count: distinctCandidates.count) + var importCandidates: [ArtifactCandidate] = [] + var importIndices: [Int] = [] + for (index, candidate) in distinctCandidates.enumerated() { + guard index < configuration.maximumFilesPerCapture else { + outcomes[index] = .skipped(.candidateLimitReached) + continue + } + guard isEligible(candidate, context: context, configuration: configuration) else { + outcomes[index] = .skipped(.provenanceNotEligible) + continue + } + importCandidates.append(candidate) + importIndices.append(index) + } + let attempts = await store.importFiles( + candidates: importCandidates, + context: context, + configuration: configuration, + maximumBatchBytes: configuration.maximumAutomaticCaptureBytes, + capturedAt: capturedAt + ) + for (index, attempt) in zip(importIndices, attempts) { + switch attempt { + case .imported(let outcome): + outcomes[index] = outcome + case .rejected(let error): + outcomes[index] = .skipped(error.skipReason) + } + } + return outcomes.map { $0 ?? .skipped(.notARegularFile) } + } + + /// Explicitly adds files through the same validated persistence path. + /// + /// Large user selections are split into policy-sized persistence batches so + /// each batch shares one bounded deduplication scan without staging more + /// than one maximum-sized artifact at a time. + /// + /// - Parameters: + /// - sourceURLs: Existing regular files to add. + /// - context: Project, workspace, and session grouping identity. + /// - capturedAt: Timestamp recorded in provenance. + /// - Returns: One import attempt per source URL, preserving input order. + public func add( + sourceURLs: [URL], + context: ArtifactCaptureContext, + capturedAt: Date = .now + ) async -> [ArtifactImportAttempt] { + guard !sourceURLs.isEmpty else { return [] } + let configuration = await store.configuration(projectRoot: context.projectRoot).normalized + let batchSize = configuration.maximumFilesPerCapture + let batchByteLimit = configuration.maximumFileBytes + let acceptedURLs = Array(sourceURLs.prefix(Self.maximumManualSelectionFiles)) + let rejectedCount = sourceURLs.count - acceptedURLs.count + var attempts: [ArtifactImportAttempt] = [] + attempts.reserveCapacity(acceptedURLs.count + rejectedCount) + var batchStart = acceptedURLs.startIndex + while batchStart < acceptedURLs.endIndex { + guard !Task.isCancelled else { break } + let batchEnd = acceptedURLs.index( + batchStart, + offsetBy: batchSize, + limitedBy: acceptedURLs.endIndex + ) ?? acceptedURLs.endIndex + let candidates = acceptedURLs[batchStart.. 0 { + attempts.append(contentsOf: batchAttempts.prefix(completedCount)) + batchStart = acceptedURLs.index(batchStart, offsetBy: completedCount) + continue + } + attempts.append(batchAttempts.first ?? .rejected( + .sourceNotRegularFile(acceptedURLs[batchStart].path) + )) + batchStart = acceptedURLs.index(after: batchStart) + } + if rejectedCount > 0 { + attempts.append(contentsOf: repeatElement( + .rejected(.fileCountLimitReached( + actual: Int64(sourceURLs.count), + limit: Int64(Self.maximumManualSelectionFiles) + )), + count: rejectedCount + )) + } + return attempts + } + + /// Explicitly adds one file while preserving a previously authorized + /// canonical identity through the descriptor-backed import. + public func add( + sourceURL: URL, + context: ArtifactCaptureContext, + expectedCanonicalPath: String, + expectedIdentity: ArtifactFileIdentity? = nil, + capturedAt: Date = .now + ) async throws -> ArtifactImportOutcome { + let configuration = await store.configuration(projectRoot: context.projectRoot).normalized + let attempts = await store.importFiles( + candidates: [ArtifactCandidate( + sourceURL: sourceURL, + provenance: .manual, + expectedCanonicalPath: expectedCanonicalPath, + expectedIdentity: expectedIdentity + )], + context: context, + configuration: configuration, + maximumBatchBytes: configuration.maximumFileBytes, + capturedAt: capturedAt + ) + guard let attempt = attempts.first else { + throw ArtifactStoreError.sourceNotRegularFile(sourceURL.path) + } + switch attempt { + case .imported(let outcome): + return outcome + case .rejected(let error): + throw error + } + } + + private func isAggregateBatchLimit(_ attempt: ArtifactImportAttempt) -> Bool { + if case .rejected(.batchByteLimitReached) = attempt { return true } + return false + } + + private func isEligible( + _ candidate: ArtifactCandidate, + context: ArtifactCaptureContext, + configuration: ArtifactCaptureConfiguration + ) -> Bool { + switch candidate.provenance { + case .created, .attached: + return configuration.captureCreatedAndAttached + case .referenced: + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + return configuration.captureReferencedEphemeral + && pathResolver.relativePath( + candidate.sourceURL, + root: context.projectRoot + ) != nil + && pathResolver.isEphemeral( + candidate.sourceURL, + prefixes: configuration.ephemeralPathPrefixes + ) + case .manual: + return true + } + } + + private func distinct(_ candidates: [ArtifactCandidate]) -> [ArtifactCandidate] { + var indexByPath: [String: Int] = [:] + var distinct: [ArtifactCandidate] = [] + for candidate in candidates { + let path = candidate.sourceURL.standardizedFileURL.path + guard let existingIndex = indexByPath[path] else { + indexByPath[path] = distinct.count + distinct.append(candidate) + continue + } + if candidate.provenance.captureAuthority + > distinct[existingIndex].provenance.captureAuthority { + distinct[existingIndex] = candidate + } + } + return distinct + } +} + +private extension ArtifactProvenance { + var captureAuthority: Int { + switch self { + case .manual: return 3 + case .created, .attached: return 2 + case .referenced: return 1 + } + } +} + +private extension ArtifactStoreError { + var skipReason: ArtifactSkipReason { + switch self { + case .sourceNotRegularFile: + return .notARegularFile + case .unsupportedExtension: + return .unsupportedExtension + case .fileTooLarge: + return .exceedsSizeLimit + case .batchByteLimitReached: + return .candidateLimitReached + case .fileCountLimitReached: + return .candidateLimitReached + case .artifactNotFound, .ambiguousArtifactName: + return .notARegularFile + case .scanIncomplete: + return .scanIncomplete + case .pathOutsideStore: + return .pathOutsideStore + case .corruptProvenance: + return .corruptProvenance + case .gitPrivacyUnavailable: + return .gitPrivacyUnavailable + case .storeBusy: + return .storeBusy + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCapturing.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCapturing.swift new file mode 100644 index 000000000000..f0d47eebfbc3 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactCapturing.swift @@ -0,0 +1,61 @@ +public import Foundation + +/// Validated capture seam shared by automatic capture and manual UI entrypoints. +public protocol ArtifactCapturing: Sendable { + /// Captures eligible detector candidates using project policy. + /// + /// - Parameters: + /// - candidates: Paths emitted by an artifact detector. + /// - context: Project, workspace, and session grouping identity. + /// - capturedAt: Timestamp recorded for accepted paths. + /// - Returns: One result for each distinct candidate. + func capture( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + capturedAt: Date + ) async -> [ArtifactImportOutcome] + + /// Explicitly adds regular files through the validated capture path. + /// + /// - Parameters: + /// - sourceURLs: Existing regular files to add. + /// - context: Project and workspace grouping identity. + /// - capturedAt: Timestamp recorded in provenance. + /// - Returns: One import attempt per source URL, preserving input order. + func add( + sourceURLs: [URL], + context: ArtifactCaptureContext, + capturedAt: Date + ) async -> [ArtifactImportAttempt] +} + +/// Convenience operations derived from the batch-oriented capture contract. +public extension ArtifactCapturing { + /// Explicitly adds one regular file through the validated capture path. + /// + /// - Parameters: + /// - sourceURL: Existing regular file to add. + /// - context: Project and workspace grouping identity. + /// - capturedAt: Timestamp recorded in provenance. + /// - Returns: Copy, deduplication, or already-stored result. + /// - Throws: ``ArtifactStoreError`` when repository validation rejects the file. + func add( + sourceURL: URL, + context: ArtifactCaptureContext, + capturedAt: Date = .now + ) async throws -> ArtifactImportOutcome { + guard let attempt = await add( + sourceURLs: [sourceURL], + context: context, + capturedAt: capturedAt + ).first else { + throw ArtifactStoreError.sourceNotRegularFile(sourceURL.path) + } + switch attempt { + case .imported(let outcome): + return outcome + case .rejected(let error): + throw error + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationIndexBuilder.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationIndexBuilder.swift new file mode 100644 index 000000000000..59947f4044c0 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationIndexBuilder.swift @@ -0,0 +1,71 @@ +import Foundation + +/// Builds one bounded digest-to-path index for a prepared import batch. +struct ArtifactDeduplicationIndexBuilder { + let recorder: ArtifactProvenanceRecorder + let scanner: ArtifactDeduplicationScanner + let fileManager: FileManager + + func build( + prepared: [PreparedArtifactImport], + paths: ArtifactStorePaths + ) throws -> [String: URL] { + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + var existingByDigest: [String: URL] = [:] + var unresolvedBySize: [Int64: Set] = [:] + for item in prepared { + let size = item.snapshot.size + if let document = try recorder.document(paths: paths, digest: item.digest), + document.size == size { + let lastKnownURL = paths.filesystemRoot + .appendingPathComponent(document.lastKnownRelativePath, isDirectory: false) + if pathResolver.isInsideStore(lastKnownURL, paths: paths), + matches( + file: lastKnownURL, + digest: item.digest, + size: size, + paths: paths + ) { + existingByDigest[item.digest] = lastKnownURL + continue + } + } + unresolvedBySize[size, default: []].insert(item.digest) + } + guard !unresolvedBySize.isEmpty else { return existingByDigest } + try scanner.scanFiles(paths: paths, matchingSizes: Set(unresolvedBySize.keys)) { file, size in + guard let unresolvedDigests = unresolvedBySize[size], !unresolvedDigests.isEmpty, + let digest = try? ArtifactDigestCalculator(fileManager: fileManager).digest( + url: file, + expectedSize: size, + allowedRoot: paths.filesystemRoot + ), + unresolvedDigests.contains(digest) else { + return false + } + existingByDigest[digest] = file + unresolvedBySize[size]?.remove(digest) + if unresolvedBySize[size]?.isEmpty == true { + unresolvedBySize.removeValue(forKey: size) + } + return unresolvedBySize.isEmpty + } + return existingByDigest + } + + private func matches( + file: URL, + digest: String, + size: Int64, + paths: ArtifactStorePaths + ) -> Bool { + guard let existingDigest = try? ArtifactDigestCalculator(fileManager: fileManager).digest( + url: file, + expectedSize: size, + allowedRoot: paths.filesystemRoot + ) else { + return false + } + return existingDigest == digest + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationScanner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationScanner.swift new file mode 100644 index 000000000000..c01321b5fd43 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDeduplicationScanner.swift @@ -0,0 +1,87 @@ +import Foundation + +/// Exhaustively streams ordinary artifact files for stale-provenance recovery. +struct ArtifactDeduplicationScanner { + let fileManager: FileManager + let maximumDepth: Int + let nodeLimit: Int + let hashByteLimit: Int64 + + init( + fileManager: FileManager, + maximumDepth: Int = 32, + nodeLimit: Int = 100_000, + hashByteLimit: Int64 = 512 * 1024 * 1024 + ) { + self.fileManager = fileManager + self.maximumDepth = max(1, maximumDepth) + self.nodeLimit = max(1, nodeLimit) + self.hashByteLimit = max(1, hashByteLimit) + } + + /// Visits size-matching files without materializing the artifact tree. + /// + /// The visitor returns `true` once every requested digest has been found. + func scanFiles( + paths: ArtifactStorePaths, + matchingSizes: Set, + until visitor: (URL, Int64) -> Bool + ) throws { + guard !matchingSizes.isEmpty else { return } + try Task.checkCancellation() + var remainingNodes = nodeLimit + var remainingHashBytes = hashByteLimit + let keys: Set = [ + .isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey, + ] + guard let enumerator = fileManager.enumerator( + at: paths.filesystemRoot, + includingPropertiesForKeys: Array(keys), + options: [] + ) else { return } + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + + while let url = enumerator.nextObject() as? URL { + try Task.checkCancellation() + guard remainingNodes > 0 else { return } + remainingNodes -= 1 + if pathResolver.refersToSameLocation(url, paths.metadataRoot) { + enumerator.skipDescendants() + continue + } + let values = try url.resourceValues(forKeys: keys) + guard values.isSymbolicLink != true, + pathResolver.isInsideStore(url, paths: paths) else { + enumerator.skipDescendants() + continue + } + if values.isDirectory == true { + let relativeDepth = pathResolver.relativePath(url, root: paths.filesystemRoot)? + .split(separator: "/").count ?? Int.max + if relativeDepth > maximumDepth { + enumerator.skipDescendants() + } + continue + } + guard values.isRegularFile == true, + url.lastPathComponent != ArtifactPathResolver.workspaceMarkerName, + url.lastPathComponent != ArtifactPathResolver.sessionMarkerName, + !isProjectControlFile(url, root: paths.filesystemRoot), + let rawSize = values.fileSize else { + continue + } + let size = Int64(rawSize) + guard matchingSizes.contains(size), size <= remainingHashBytes else { continue } + remainingHashBytes -= size + if visitor(url, size) { return } + } + } + + private func isProjectControlFile(_ url: URL, root: URL) -> Bool { + guard url.deletingLastPathComponent().standardizedFileURL == root.standardizedFileURL else { + return false + } + return url.lastPathComponent.hasPrefix(".") + || ArtifactStorePaths.trackableControlFileNames.contains(url.lastPathComponent) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDigestCalculator.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDigestCalculator.swift new file mode 100644 index 000000000000..6ac6268432d2 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactDigestCalculator.swift @@ -0,0 +1,96 @@ +import Darwin +import CryptoKit +import Foundation + +/// Computes bounded-file SHA-256 identities for deduplication. +struct ArtifactDigestCalculator: Sendable { + private let chunkSize = 64 * 1024 + // Only FileManager's thread-safe, stateless path queries are used through this immutable reference. + nonisolated(unsafe) private let fileManager: FileManager + + init(fileManager: FileManager) { + self.fileManager = fileManager + } + + func digest(url: URL, expectedSize: Int64, allowedRoot: URL) throws -> String { + try Task.checkCancellation() + let descriptor = Darwin.open( + url.path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw ArtifactStoreError.sourceNotRegularFile(url.path) + } + defer { Darwin.close(descriptor) } + + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0, + status.st_size == expectedSize else { + throw ArtifactStoreError.sourceNotRegularFile(url.path) + } + guard let descriptorURL = descriptorURL(descriptor), + ArtifactPathResolver(fileManager: fileManager) + .relativePath(descriptorURL, root: allowedRoot) != nil else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + + var remaining = expectedSize + var hasher = SHA256() + var buffer = [UInt8](repeating: 0, count: chunkSize) + while remaining > 0 { + try Task.checkCancellation() + let requested = min(chunkSize, Int(remaining)) + let count = buffer.withUnsafeMutableBytes { bytes in + Darwin.read(descriptor, bytes.baseAddress, requested) + } + if count < 0 { + if errno == EINTR { continue } + throw ArtifactStoreError.sourceNotRegularFile(url.path) + } + guard count > 0 else { + throw ArtifactStoreError.sourceNotRegularFile(url.path) + } + hasher.update(data: Data(buffer.prefix(count))) + remaining -= Int64(count) + } + + var extraByte: UInt8 = 0 + while true { + try Task.checkCancellation() + let count = Darwin.read(descriptor, &extraByte, 1) + if count == 0 { break } + if count < 0, errno == EINTR { continue } + throw ArtifactStoreError.sourceNotRegularFile(url.path) + } + + let digits: [UInt8] = Array("0123456789abcdef".utf8) + let digest = hasher.finalize() + var encoded: [UInt8] = [] + encoded.reserveCapacity(SHA256.byteCount * 2) + for byte in digest { + encoded.append(digits[Int(byte >> 4)]) + encoded.append(digits[Int(byte & 0x0f)]) + } + return String(decoding: encoded, as: UTF8.self) + } + + private func descriptorURL(_ descriptor: Int32) -> URL? { + var descriptorInfo = vnode_fdinfowithpath() + let result = proc_pidfdinfo( + Darwin.getpid(), + descriptor, + PROC_PIDFDVNODEPATHINFO, + &descriptorInfo, + Int32(MemoryLayout.size) + ) + guard result > 0 else { return nil } + let path = withUnsafeBytes(of: &descriptorInfo.pvip.vip_path) { rawBuffer -> String in + guard let baseAddress = rawBuffer.baseAddress else { return "" } + return String(cString: baseAddress.assumingMemoryBound(to: CChar.self)) + } + guard !path.isEmpty else { return nil } + return URL(fileURLWithPath: path, isDirectory: false) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactExactPathResolver.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactExactPathResolver.swift new file mode 100644 index 000000000000..f05972fc8d0c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactExactPathResolver.swift @@ -0,0 +1,84 @@ +import Darwin +import Foundation + +/// Resolves one exact ordinary file path without walking the artifact tree. +struct ArtifactExactPathResolver { + let fileManager: FileManager + + func fileNode(relativePath: String, paths: ArtifactStorePaths) throws -> ArtifactNode? { + guard !relativePath.isEmpty, + !relativePath.contains("\0"), + !relativePath.contains("\n") else { + return nil + } + let components = relativePath.split( + separator: "/", + omittingEmptySubsequences: false + ).map(String.init) + guard !components.isEmpty, + components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }), + components.joined(separator: "/") == relativePath, + components.first != ".cmux" else { + return nil + } + + let visibilityPolicy = ArtifactStoreVisibilityPolicy(fileManager: fileManager) + var current = paths.filesystemRoot + for (index, component) in components.enumerated() { + current.appendPathComponent(component, isDirectory: index < components.count - 1) + guard !visibilityPolicy.isManagedEntry( + current, + filesystemRoot: paths.filesystemRoot + ) else { + return nil + } + guard let entryType = try filesystemEntryType(current) else { return nil } + guard entryType != S_IFLNK else { + throw ArtifactStoreError.pathOutsideStore(current.path) + } + if index < components.count - 1 { + guard entryType == S_IFDIR else { return nil } + } else { + guard entryType == S_IFREG else { return nil } + } + } + + let values = try current.resourceValues(forKeys: [ + .isRegularFileKey, + .isSymbolicLinkKey, + .fileSizeKey, + .contentModificationDateKey, + ]) + guard values.isRegularFile == true, values.isSymbolicLink != true else { + return nil + } + let fileKind = ArtifactFileKind(fileURL: current) + let fileIdentity: ArtifactFileIdentity? = switch fileKind { + case .image, .video: try? ArtifactFileIdentity.read(at: current) + default: nil + } + return ArtifactNode( + id: relativePath, + name: current.lastPathComponent, + relativePath: relativePath, + absolutePath: current.path, + isDirectory: false, + fileKind: fileKind, + size: values.fileSize.map(Int64.init), + modifiedAt: values.contentModificationDate, + fileIdentity: fileIdentity, + children: [] + ) + } + + private func filesystemEntryType(_ url: URL) throws -> mode_t? { + var status = stat() + if lstat(url.path, &status) == 0 { + return status.st_mode & S_IFMT + } + guard errno == ENOENT else { + throw CocoaError(.fileReadUnknown) + } + return nil + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileIdentity.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileIdentity.swift new file mode 100644 index 000000000000..5105213de60f --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileIdentity.swift @@ -0,0 +1,31 @@ +import Darwin +import Foundation + +/// Stable device/inode identity for one ordinary filesystem entry. +public struct ArtifactFileIdentity: Sendable, Equatable, Hashable { + /// Device number reported by `stat(2)`. + public let device: UInt64 + /// Inode number reported by `stat(2)`. + public let inode: UInt64 + + /// Creates a filesystem identity value. + public init(device: UInt64, inode: UInt64) { + self.device = device + self.inode = inode + } + + /// Reads the identity of one regular file without following a final link. + /// + /// - Parameter url: File URL to inspect. + /// - Returns: The opened file's device/inode pair. + /// - Throws: ``ArtifactStoreError/pathOutsideStore(_:)`` when the entry + /// cannot be inspected as a regular file. + static func read(at url: URL) throws -> Self { + var status = stat() + guard lstat(url.path, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + return Self(device: UInt64(status.st_dev), inode: UInt64(status.st_ino)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileKind.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileKind.swift new file mode 100644 index 000000000000..8573e7b4eb22 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFileKind.swift @@ -0,0 +1,51 @@ +public import Foundation + +/// Coarse preview and capture classification for an artifact file. +public enum ArtifactFileKind: String, Codable, CaseIterable, Sendable { + /// A bitmap or vector image. + case image + /// A video or screen recording. + case video + /// Markdown source rendered by cmux's markdown viewer. + case markdown + /// An HTML document opened in a browser pane. + case html + /// A unified diff or patch. + case patch + /// A small searchable text or structured-text file. + case text + /// A file outside the default automatic-capture allowlist. + case other + + /// Creates a classification from a file's filename extension. + /// + /// - Parameter fileURL: File URL to classify. + public init(fileURL: URL) { + switch fileURL.pathExtension.lowercased() { + case "png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "svg": + self = .image + case "mp4", "mov", "m4v", "webm": + self = .video + case "md", "markdown", "mdown", "mkd": + self = .markdown + case "html", "htm": + self = .html + case "diff", "patch": + self = .patch + case "txt", "log", "json", "jsonl", "yaml", "yml", "toml", "csv", "tsv", "xml": + self = .text + default: + self = .other + } + } + + /// Whether content search may decode the file as UTF-8 text. + public var isTextSearchable: Bool { + switch self { + case .markdown, .html, .patch, .text: + return true + case .image, .video, .other: + return false + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFuzzyMatcher.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFuzzyMatcher.swift new file mode 100644 index 000000000000..8fe5c6b8f59f --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactFuzzyMatcher.swift @@ -0,0 +1,42 @@ +import Foundation + +/// Small deterministic fuzzy scorer for artifact basenames and relative paths. +struct ArtifactFuzzyMatcher: Sendable { + static let maximumQueryBytes = 512 + + let contentQuery: String + private let normalizedQuery: String + + init(query rawQuery: String) { + contentQuery = String(decoding: rawQuery.utf8.prefix(Self.maximumQueryBytes), as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + normalizedQuery = contentQuery.folding( + options: [.caseInsensitive, .diacriticInsensitive], + locale: .current + ) + } + + var isEmpty: Bool { normalizedQuery.isEmpty } + + func score(candidate: String) -> Int? { + let candidate = candidate.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current) + guard !normalizedQuery.isEmpty else { return 0 } + if candidate == normalizedQuery { return 10_000 } + if let range = candidate.range(of: normalizedQuery) { + let offset = candidate.distance(from: candidate.startIndex, to: range.lowerBound) + return 8_000 - min(offset, 1_000) - max(0, candidate.count - normalizedQuery.count) + } + var candidateIndex = candidate.startIndex + var score = 0 + var previousMatch: String.Index? + for queryCharacter in normalizedQuery { + guard let match = candidate[candidateIndex...].firstIndex(of: queryCharacter) else { return nil } + let gap = candidate.distance(from: candidateIndex, to: match) + score += previousMatch.map { candidate.index(after: $0) == match ? 30 : 8 } ?? 15 + score -= min(gap, 20) + previousMatch = match + candidateIndex = candidate.index(after: match) + } + return score - max(0, candidate.count - normalizedQuery.count) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandError.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandError.swift new file mode 100644 index 000000000000..92bb2898d5dd --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandError.swift @@ -0,0 +1,7 @@ +import Foundation + +/// Failures specific to bounded artifact Git privacy subprocesses. +enum ArtifactGitCommandError: Error, Equatable, Sendable { + /// The subprocess exceeded its configured execution deadline. + case timedOut +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandRunning.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandRunning.swift new file mode 100644 index 000000000000..13df0040621b --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitCommandRunning.swift @@ -0,0 +1,13 @@ +import Foundation + +/// Executes bounded Git privacy checks for an artifact repository. +protocol ArtifactGitCommandRunning: Sendable { + /// Runs Git while discarding output and returns only its termination status. + func terminationStatus(arguments: [String]) async throws -> Int32 + + /// Runs Git with bounded input and captures the output needed for exact validation. + func run( + arguments: [String], + standardInput: Data? + ) async throws -> (terminationStatus: Int32, standardOutput: Data) +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitIgnoreManager.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitIgnoreManager.swift new file mode 100644 index 000000000000..519752889eb9 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitIgnoreManager.swift @@ -0,0 +1,422 @@ +import Darwin +import Foundation + +/// Adds the local artifact store to Git's per-checkout exclude file. +struct ArtifactGitIgnoreManager { + let fileManager: FileManager + private static let maximumExcludeBytes: Int64 = 1024 * 1024 + private static let maximumGitMetadataBytes: Int64 = 256 * 1024 + static var ignoreEntries: [String] { + [".cmux/**"] + ArtifactStorePaths.trackableControlFileNames.map { "!.cmux/\($0)" } + } + + func ensureIgnored(projectRoot: URL) throws { + guard let repository = locateGitRepository(startingAt: projectRoot) else { + if let marker = gitMarker(startingAt: projectRoot) { + throw ArtifactStoreError.gitPrivacyUnavailable(marker.path) + } + return + } + let ignoreEntries = try relativeIgnoreEntries( + projectRoot: projectRoot, + worktreeRoot: repository.worktreeRoot + ) + let infoDirectory = repository.commonGitDirectory.appendingPathComponent("info", isDirectory: true) + let excludeURL = infoDirectory.appendingPathComponent("exclude", isDirectory: false) + try ensureTrustedDirectory(infoDirectory) + try rejectUntrustedFileEntry(excludeURL) + let existing: String + if fileManager.fileExists(atPath: excludeURL.path) { + guard let contents = readRegularFile( + excludeURL, + allowedRoot: repository.commonGitDirectory, + maximumBytes: Self.maximumExcludeBytes + ) else { + throw ArtifactStoreError.gitPrivacyUnavailable(excludeURL.path) + } + existing = contents + } else { + existing = "" + } + let lines = existing.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + let missingEntries = ignoreEntries.filter { !lines.contains($0) } + guard !missingEntries.isEmpty else { return } + try ensureTrustedDirectory(infoDirectory) + try rejectUntrustedFileEntry(excludeURL) + try append( + entries: missingEntries, + to: excludeURL, + allowedRoot: repository.commonGitDirectory + ) + } + + /// Resolves the repository context for a fail-closed import validator. + func writeValidator( + projectRoot: URL, + commandRunner: any ArtifactGitCommandRunning + ) -> ArtifactGitPrivacyValidator? { + guard let repository = locateGitRepository(startingAt: projectRoot) else { + guard gitMarker(startingAt: projectRoot) == nil else { return nil } + return ArtifactGitPrivacyValidator( + worktreeRoot: nil, + commandRunner: commandRunner, + fileManager: fileManager + ) + } + return ArtifactGitPrivacyValidator( + worktreeRoot: repository.worktreeRoot, + commandRunner: commandRunner, + fileManager: fileManager + ) + } + + private func locateGitRepository(startingAt projectRoot: URL) -> ArtifactGitRepository? { + for current in ArtifactAncestorDirectories(startingAt: projectRoot) { + let dotGit = current.appendingPathComponent(".git", isDirectory: false) + guard filesystemEntryExists(dotGit) else { continue } + return resolveGitRepository(worktreeRoot: current, dotGit: dotGit) + } + return nil + } + + private func gitMarker(startingAt projectRoot: URL) -> URL? { + for current in ArtifactAncestorDirectories(startingAt: projectRoot) { + let marker = current.appendingPathComponent(".git", isDirectory: false) + if filesystemEntryExists(marker) { return marker } + } + return nil + } + + private func resolveGitRepository(worktreeRoot: URL, dotGit: URL) -> ArtifactGitRepository? { + guard let entryType = try? filesystemEntryType(dotGit) else { return nil } + if entryType == S_IFDIR { + let commonDirectoryFile = dotGit.appendingPathComponent("commondir", isDirectory: false) + guard isTrustedDirectory(dotGit), + !filesystemEntryExists(commonDirectoryFile) else { + return nil + } + let gitDirectory = dotGit.standardizedFileURL + return ArtifactGitRepository( + worktreeRoot: worktreeRoot, + gitDirectory: gitDirectory, + commonGitDirectory: gitDirectory + ) + } + guard entryType == S_IFREG, + let contents = readRegularFile(dotGit, allowedRoot: worktreeRoot), + contents.lowercased().hasPrefix("gitdir:") else { return nil } + let rawPath = contents.dropFirst("gitdir:".count).trimmingCharacters(in: .whitespacesAndNewlines) + let url = URL(fileURLWithPath: rawPath, relativeTo: worktreeRoot).standardizedFileURL + guard isTrustedDirectory(url) else { + return nil + } + let commonGitDirectory: URL + if let linked = linkedCommonGitDirectory(gitDirectory: url, dotGit: dotGit) { + commonGitDirectory = linked + } else if isValidatedSubmoduleGitDirectory( + url, + worktreeRoot: worktreeRoot + ) { + commonGitDirectory = url + } else { + return nil + } + return ArtifactGitRepository( + worktreeRoot: worktreeRoot, + gitDirectory: url, + commonGitDirectory: commonGitDirectory + ) + } + + private func linkedCommonGitDirectory( + gitDirectory: URL, + dotGit: URL + ) -> URL? { + let backLink = gitDirectory.appendingPathComponent("gitdir", isDirectory: false) + guard let backLinkPath = readRegularFile(backLink, allowedRoot: gitDirectory)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !backLinkPath.isEmpty else { + return nil + } + let resolvedBackLink = URL( + fileURLWithPath: backLinkPath, + relativeTo: gitDirectory + ).standardizedFileURL + guard resolvedBackLink.path == dotGit.standardizedFileURL.path else { return nil } + + let commonDirectoryFile = gitDirectory.appendingPathComponent("commondir", isDirectory: false) + guard let rawPath = readRegularFile( + commonDirectoryFile, + allowedRoot: gitDirectory + )? + .trimmingCharacters(in: .whitespacesAndNewlines), + !rawPath.isEmpty else { + return nil + } + let commonDirectory = URL( + fileURLWithPath: rawPath, + relativeTo: gitDirectory + ).standardizedFileURL + let worktreesDirectory = gitDirectory.deletingLastPathComponent().standardizedFileURL + guard worktreesDirectory.lastPathComponent == "worktrees", + worktreesDirectory.deletingLastPathComponent().standardizedFileURL.path + == commonDirectory.path, + isTrustedDirectory(commonDirectory) else { + return nil + } + return commonDirectory + } + + /// Accepts only Git-managed submodule directories under an enclosing repository's + /// `modules` tree whose `core.worktree` points back to this exact checkout. + private func isValidatedSubmoduleGitDirectory( + _ gitDirectory: URL, + worktreeRoot: URL + ) -> Bool { + let parent = worktreeRoot.deletingLastPathComponent().standardizedFileURL + guard let enclosingRepository = locateGitRepository(startingAt: parent) else { + return false + } + let candidateRoots = [ + enclosingRepository.gitDirectory, + enclosingRepository.commonGitDirectory, + ] + .map { $0.appendingPathComponent("modules", isDirectory: true).standardizedFileURL } + guard candidateRoots.contains(where: { modulesRoot in + isTrustedDescendantDirectory(gitDirectory, root: modulesRoot) + }) else { + return false + } + let config = gitDirectory.appendingPathComponent("config", isDirectory: false) + guard let configuredWorktree = submoduleWorktree( + config: config, + gitDirectory: gitDirectory + ) else { + return false + } + return configuredWorktree.path == worktreeRoot.standardizedFileURL.path + } + + private func isTrustedDescendantDirectory(_ candidate: URL, root: URL) -> Bool { + let candidate = candidate.standardizedFileURL + let root = root.standardizedFileURL + guard isTrustedDirectory(root), + let relativePath = ArtifactPathResolver(fileManager: fileManager) + .relativePath(candidate, root: root) else { + return false + } + var current = root + for component in relativePath.split(separator: "/") { + current.appendPathComponent(String(component), isDirectory: true) + guard isTrustedDirectory(current) else { return false } + } + return true + } + + private func submoduleWorktree(config: URL, gitDirectory: URL) -> URL? { + guard let contents = readRegularFile(config, allowedRoot: gitDirectory) else { return nil } + var isCoreSection = false + for rawLine in contents.split(separator: "\n", omittingEmptySubsequences: false) { + let line = rawLine.trimmingCharacters(in: .whitespacesAndNewlines) + if line.hasPrefix("[") { + isCoreSection = line.caseInsensitiveCompare("[core]") == .orderedSame + continue + } + guard isCoreSection, let separator = line.firstIndex(of: "=") else { continue } + let key = line[..= 2, value.first == "\"", value.last == "\"" { + value.removeFirst() + value.removeLast() + } + guard !value.isEmpty else { return nil } + return URL( + fileURLWithPath: value, + relativeTo: gitDirectory + ).standardizedFileURL + } + return nil + } + + private func readRegularFile( + _ url: URL, + allowedRoot: URL, + maximumBytes: Int64 = Self.maximumGitMetadataBytes + ) -> String? { + guard let data = try? ArtifactBoundedFileReader(fileManager: fileManager).data( + url: url, + allowedRoot: allowedRoot, + maximumBytes: maximumBytes + ) else { + return nil + } + return String(data: data, encoding: .utf8) + } + + private func append(entries: [String], to url: URL, allowedRoot: URL) throws { + let descriptor = Darwin.open( + url.path, + O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + guard descriptor >= 0 else { + throw ArtifactStoreError.gitPrivacyUnavailable(url.path) + } + defer { Darwin.close(descriptor) } + + // A descriptor can still point at an unrelated inode when the + // pathname was hard-linked or replaced between the preflight and + // open. Require an exclusive link and the same device/inode at the + // directory entry before inspecting or mutating its bytes. + guard descriptorMatchesExclusiveEntry(descriptor, at: url) else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + var status = stat() + guard fstat(descriptor, &status) == 0, + status.st_size >= 0 else { + throw ArtifactStoreError.gitPrivacyUnavailable(url.path) + } + let separator = status.st_size == 0 ? "" : "\n" + let data = Data((separator + entries.joined(separator: "\n") + "\n").utf8) + guard descriptorMatchesExclusiveEntry(descriptor, at: url), + fstat(descriptor, &status) == 0, + status.st_size >= 0, + status.st_size <= Self.maximumExcludeBytes - Int64(data.count) else { + throw ArtifactStoreError.gitPrivacyUnavailable(url.path) + } + var descriptorInfo = vnode_fdinfowithpath() + let pathResult = proc_pidfdinfo( + Darwin.getpid(), + descriptor, + PROC_PIDFDVNODEPATHINFO, + &descriptorInfo, + Int32(MemoryLayout.size) + ) + let descriptorPath = withUnsafeBytes(of: &descriptorInfo.pvip.vip_path) { rawBuffer in + guard let baseAddress = rawBuffer.baseAddress else { return "" } + return String(cString: baseAddress.assumingMemoryBound(to: CChar.self)) + } + guard pathResult > 0, + ArtifactPathResolver(fileManager: fileManager).relativePath( + URL(fileURLWithPath: descriptorPath), + root: allowedRoot + ) != nil else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + let written = data.withUnsafeBytes { bytes in + Darwin.write(descriptor, bytes.baseAddress, bytes.count) + } + guard written == data.count else { + throw ArtifactStoreError.gitPrivacyUnavailable(url.path) + } + } + + private func filesystemEntryExists(_ url: URL) -> Bool { + do { + return try filesystemEntryType(url) != nil + } catch { + return true + } + } + + private func isTrustedDirectory(_ url: URL) -> Bool { + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), + isDirectory.boolValue, + let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey]) else { + return false + } + return values.isSymbolicLink != true + } + + private func relativeIgnoreEntries(projectRoot: URL, worktreeRoot: URL) throws -> [String] { + guard let relativePath = ArtifactPathResolver(fileManager: fileManager).relativePath( + projectRoot, + root: worktreeRoot + ) else { + return Self.ignoreEntries + } + guard !relativePath.unicodeScalars.contains(where: { scalar in + scalar.value == 0x0A || scalar.value == 0x0D + }) else { + throw ArtifactStoreError.gitPrivacyUnavailable(worktreeRoot.path) + } + let prefix = escapedGitPattern(relativePath) + "/" + return Self.ignoreEntries.map { entry in + guard entry.hasPrefix("!") else { return prefix + entry } + return "!" + prefix + entry.dropFirst() + } + } + + private func escapedGitPattern(_ path: String) -> String { + var escaped = "" + escaped.reserveCapacity(path.count) + for character in path { + if "\\*?[]#! \t".contains(character) { + escaped.append("\\") + } + escaped.append(character) + } + return escaped + } + + private func ensureTrustedDirectory(_ url: URL) throws { + let entryType = try filesystemEntryType(url) + if entryType == nil { + try fileManager.createDirectory(at: url, withIntermediateDirectories: false) + } else if entryType != S_IFDIR { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + guard try filesystemEntryType(url) == S_IFDIR else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + } + + private func rejectUntrustedFileEntry(_ url: URL) throws { + var status = stat() + guard lstat(url.path, &status) == 0 else { + guard errno == ENOENT else { + throw CocoaError(.fileReadUnknown) + } + return + } + // `.git/info/exclude` is a mutable security boundary. A hard link + // would let this process append to a different user's inode, even + // though the final pathname itself is inside Git's metadata root. + guard (status.st_mode & S_IFMT) == S_IFREG, + status.st_nlink == 1 else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + } + + private func descriptorMatchesExclusiveEntry(_ descriptor: Int32, at url: URL) -> Bool { + var descriptorStatus = stat() + guard fstat(descriptor, &descriptorStatus) == 0, + (descriptorStatus.st_mode & S_IFMT) == S_IFREG, + descriptorStatus.st_nlink == 1 else { + return false + } + + var entryStatus = stat() + guard lstat(url.path, &entryStatus) == 0, + (entryStatus.st_mode & S_IFMT) == S_IFREG, + entryStatus.st_nlink == 1 else { + return false + } + return descriptorStatus.st_dev == entryStatus.st_dev + && descriptorStatus.st_ino == entryStatus.st_ino + } + + private func filesystemEntryType(_ url: URL) throws -> mode_t? { + var status = stat() + if lstat(url.path, &status) == 0 { + return status.st_mode & S_IFMT + } + guard errno == ENOENT else { + throw CocoaError(.fileReadUnknown) + } + return nil + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitPrivacyValidator.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitPrivacyValidator.swift new file mode 100644 index 000000000000..17838eeca0ae --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitPrivacyValidator.swift @@ -0,0 +1,68 @@ +import Foundation + +/// Reuses one tracked-store decision while validating exact write paths in batches. +struct ArtifactGitPrivacyValidator: Sendable { + let worktreeRoot: URL? + let commandRunner: any ArtifactGitCommandRunning + // Only FileManager's thread-safe, stateless path queries are used through this immutable reference. + nonisolated(unsafe) let fileManager: FileManager + + func storeIsUntracked(filesystemRoot: URL) async -> Bool { + guard let worktreeRoot else { return true } + guard let relativeCmuxPath = ArtifactPathResolver(fileManager: fileManager).relativePath( + filesystemRoot, + root: worktreeRoot + ) else { + return false + } + let trackedContentPathspecs = [":(literal)\(relativeCmuxPath)"] + + ArtifactStorePaths.trackableControlFileNames.map { + ":(exclude,literal)\(relativeCmuxPath)/\($0)" + } + guard let trackedStatus = try? await commandRunner.terminationStatus( + arguments: [ + "-C", worktreeRoot.path, + "ls-files", "--error-unmatch", "--", + ] + trackedContentPathspecs + ) else { + return false + } + return trackedStatus == 1 + } + + func permits(destinations: [URL]) async -> Bool { + guard !destinations.isEmpty else { return false } + guard let worktreeRoot else { return true } + let resolver = ArtifactPathResolver(fileManager: fileManager) + var encodedPaths: [Data] = [] + var seen: Set = [] + for destination in destinations { + guard let relativePath = resolver.relativePath(destination, root: worktreeRoot) else { + return false + } + let encodedPath = Data(relativePath.utf8) + guard seen.insert(encodedPath).inserted else { continue } + encodedPaths.append(encodedPath) + } + var standardInput = Data() + for encodedPath in encodedPaths { + standardInput.append(encodedPath) + standardInput.append(0) + } + guard let result = try? await commandRunner.run( + arguments: [ + "-C", worktreeRoot.path, + "check-ignore", "-z", "--stdin", + ], + standardInput: standardInput + ), result.terminationStatus == 0 else { + return false + } + let outputBytes = [UInt8](result.standardOutput) + var ignoredPaths: Set = [] + for pathBytes in outputBytes.split(whereSeparator: { $0 == 0 }) { + ignoredPaths.insert(Data(pathBytes)) + } + return ignoredPaths == Set(encodedPaths) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitProcessCancellation.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitProcessCancellation.swift new file mode 100644 index 000000000000..b04120408db7 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitProcessCancellation.swift @@ -0,0 +1,18 @@ +import Darwin +import Foundation + +/// Terminates a launched Git process from a synchronous cancellation callback. +// Safety: the Process reference is immutable. Launch and handler installation stay +// on the waiting task; concurrent cancellation only reads liveness and sends SIGKILL. +final class ArtifactGitProcessCancellation: @unchecked Sendable { + private let process: Process + + init(process: Process) { + self.process = process + } + + func cancel() { + guard process.isRunning else { return } + kill(process.processIdentifier, SIGKILL) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitRepository.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitRepository.swift new file mode 100644 index 000000000000..ea82b21a0e1c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactGitRepository.swift @@ -0,0 +1,8 @@ +import Foundation + +/// Validated Git metadata directories that may receive a local exclude entry. +struct ArtifactGitRepository { + let worktreeRoot: URL + let gitDirectory: URL + let commonGitDirectory: URL +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactIdentitySlug.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactIdentitySlug.swift new file mode 100644 index 000000000000..6678f8b72e6a --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactIdentitySlug.swift @@ -0,0 +1,18 @@ +import CryptoKit +import Foundation + +/// Produces compact, readable folder components without collapsing distinct identities. +struct ArtifactIdentitySlug: Sendable { + private static let hexadecimalDigits = Array("0123456789abcdef".utf8) + + func value(readableIdentity: String, stableIdentity: String) -> String { + let digest = SHA256.hash(data: Data(stableIdentity.utf8)) + var suffix: [UInt8] = [] + suffix.reserveCapacity(12) + for byte in digest.prefix(6) { + suffix.append(Self.hexadecimalDigits[Int(byte >> 4)]) + suffix.append(Self.hexadecimalDigits[Int(byte & 0x0f)]) + } + return "\(String(readableIdentity.prefix(16)))-\(String(decoding: suffix, as: UTF8.self))" + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportAttempt.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportAttempt.swift new file mode 100644 index 000000000000..968ee0bee038 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportAttempt.swift @@ -0,0 +1,9 @@ +import Foundation + +/// Store result for one candidate in a batch import. +public enum ArtifactImportAttempt: Equatable, Sendable { + /// The candidate produced an observable import outcome. + case imported(ArtifactImportOutcome) + /// The candidate failed repository validation. + case rejected(ArtifactStoreError) +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportOutcome.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportOutcome.swift new file mode 100644 index 000000000000..88bff7706722 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportOutcome.swift @@ -0,0 +1,23 @@ +import Foundation + +/// Observable result of one automatic or manual import attempt. +public enum ArtifactImportOutcome: Equatable, Sendable { + /// A new ordinary file was copied into the artifact store. + case copied(ArtifactRecord) + /// Identical bytes already existed; provenance was recorded without another copy. + case deduplicated(ArtifactRecord) + /// The source already lived inside the project `.cmux` filesystem and was recorded in place. + case alreadyStored(ArtifactRecord) + /// Policy rejected the candidate without mutating the store. + case skipped(ArtifactSkipReason) + + /// The resulting artifact record, when a file was accepted. + public var record: ArtifactRecord? { + switch self { + case .copied(let record), .deduplicated(let record), .alreadyStored(let record): + return record + case .skipped: + return nil + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingCleaner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingCleaner.swift new file mode 100644 index 000000000000..4faae926837d --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingCleaner.swift @@ -0,0 +1,160 @@ +import Darwin +import Foundation + +/// Reclaims abandoned import batches without disturbing leases held by other processes. +struct ArtifactImportStagingCleaner { + let fileManager: FileManager + let now: @Sendable () -> Date + let scanLimit: Int + let malformedEntryGracePeriod: TimeInterval + + init( + fileManager: FileManager, + now: @escaping @Sendable () -> Date, + scanLimit: Int = 256, + malformedEntryGracePeriod: TimeInterval = 6 * 60 * 60 + ) { + self.fileManager = fileManager + self.now = now + self.scanLimit = max(1, scanLimit) + self.malformedEntryGracePeriod = max(0, malformedEntryGracePeriod) + } + + func reclaimAbandonedBatches(root: URL) { + let rootDescriptor = Darwin.open( + root.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard rootDescriptor >= 0 else { + return + } + defer { _ = Darwin.close(rootDescriptor) } + guard let enumerator = fileManager.enumerator( + at: root, + includingPropertiesForKeys: [ + .contentModificationDateKey, + .isDirectoryKey, + .isSymbolicLinkKey, + ], + options: [.skipsSubdirectoryDescendants, .skipsPackageDescendants] + ) else { + return + } + var inspected = 0 + for case let entry as URL in enumerator { + guard inspected < scanLimit else { break } + inspected += 1 + reclaim(entry, rootDescriptor: rootDescriptor) + } + } + + private func reclaim(_ entry: URL, rootDescriptor: Int32) { + let name = entry.lastPathComponent + guard name.hasSuffix(ArtifactImportStagingLease.batchSuffix) + || name.hasSuffix(ArtifactImportStagingLease.claimSuffix) else { + return + } + guard let values = try? entry.resourceValues(forKeys: [ + .contentModificationDateKey, + .isDirectoryKey, + .isSymbolicLinkKey, + ]) else { + return + } + guard values.isSymbolicLink != true, values.isDirectory == true else { + removeIfStale( + name: name, + rootDescriptor: rootDescriptor, + modifiedAt: values.contentModificationDate + ) + return + } + let entryDescriptor = name.withCString { pointer in + Darwin.openat( + rootDescriptor, + pointer, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + } + guard entryDescriptor >= 0 else { + removeIfStale( + name: name, + rootDescriptor: rootDescriptor, + modifiedAt: values.contentModificationDate + ) + return + } + defer { _ = close(entryDescriptor) } + let descriptor = ArtifactImportStagingLease.leaseFilename.withCString { pointer in + Darwin.openat( + entryDescriptor, + pointer, + O_RDWR | O_CLOEXEC | O_NOFOLLOW + ) + } + guard descriptor >= 0 else { + removeIfStale( + name: name, + rootDescriptor: rootDescriptor, + directoryDescriptor: entryDescriptor, + directoryURL: entry, + modifiedAt: values.contentModificationDate + ) + return + } + defer { _ = close(descriptor) } + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG else { + removeIfStale( + name: name, + rootDescriptor: rootDescriptor, + directoryDescriptor: entryDescriptor, + directoryURL: entry, + modifiedAt: values.contentModificationDate + ) + return + } + guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { return } + defer { _ = flock(descriptor, LOCK_UN) } + removeDirectoryContents(entryDescriptor, directoryURL: entry) + _ = name.withCString { pointer in + Darwin.unlinkat(rootDescriptor, pointer, AT_REMOVEDIR) + } + } + + private func removeIfStale( + name: String, + rootDescriptor: Int32, + directoryDescriptor: Int32? = nil, + directoryURL: URL? = nil, + modifiedAt: Date? + ) { + guard let modifiedAt, + now().timeIntervalSince(modifiedAt) >= malformedEntryGracePeriod else { + return + } + if let directoryDescriptor { + removeDirectoryContents(directoryDescriptor, directoryURL: directoryURL) + _ = name.withCString { pointer in + Darwin.unlinkat(rootDescriptor, pointer, AT_REMOVEDIR) + } + } else { + _ = name.withCString { pointer in + Darwin.unlinkat(rootDescriptor, pointer, 0) + } + } + } + + private func removeDirectoryContents(_ descriptor: Int32, directoryURL: URL?) { + guard let directoryURL, + let names = try? fileManager.contentsOfDirectory(atPath: directoryURL.path) else { + return + } + for name in names where name != "." && name != ".." { + _ = name.withCString { pointer in + Darwin.unlinkat(descriptor, pointer, 0) + } + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingLease.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingLease.swift new file mode 100644 index 000000000000..45f165dfd09c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactImportStagingLease.swift @@ -0,0 +1,212 @@ +import Darwin +import Foundation + +/// Owns one process-leased staging directory for an artifact import batch. +final class ArtifactImportStagingLease { + static let leaseFilename = ".lease" + static let batchSuffix = ".artifact-import" + static let claimSuffix = ".artifact-import-claim" + + let directory: URL + private var descriptor: Int32 + private let directoryDescriptor: Int32 + private let rootDescriptor: Int32 + private let directoryName: String + private var stagedNames: Set = [] + + private init( + directory: URL, + descriptor: Int32, + directoryDescriptor: Int32, + rootDescriptor: Int32, + directoryName: String + ) { + self.directory = directory + self.descriptor = descriptor + self.directoryDescriptor = directoryDescriptor + self.rootDescriptor = rootDescriptor + self.directoryName = directoryName + } + + convenience init( + root: URL, + fileManager: FileManager, + expectedCanonicalPath: String? = nil + ) throws { + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + let identity = UUID().uuidString + let claimName = ".\(identity)\(Self.claimSuffix)" + let directoryName = "\(identity)\(Self.batchSuffix)" + let directory = root.appendingPathComponent(directoryName, isDirectory: true) + let rootDescriptor = Darwin.open( + root.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard rootDescriptor >= 0, + Self.openedPath(for: rootDescriptor) == + (expectedCanonicalPath ?? Self.canonicalPath(root)) else { + if rootDescriptor >= 0 { _ = Darwin.close(rootDescriptor) } + throw CocoaError(.fileWriteUnknown) + } + // The staging-root descriptor is also a cross-process reservation. + // Holding this non-blocking lock for the lease lifetime prevents + // multiple bounded batches from accumulating while one waits for the + // store mutation lease. + let reservationError: Int32 + if flock(rootDescriptor, LOCK_EX | LOCK_NB) == 0 { + reservationError = 0 + } else { + reservationError = errno + } + guard reservationError == 0 else { + _ = Darwin.close(rootDescriptor) + if reservationError == EWOULDBLOCK || reservationError == EAGAIN { + throw ArtifactStoreError.storeBusy(root.path) + } + throw CocoaError(.fileWriteUnknown) + } + var claimDescriptor: Int32 = -1 + var descriptor: Int32 = -1 + var keepsLease = false + defer { + if !keepsLease { + if descriptor >= 0 { + _ = flock(descriptor, LOCK_UN) + _ = close(descriptor) + } + if claimDescriptor >= 0 { + _ = Self.leaseFilename.withCString { pointer in + Darwin.unlinkat(claimDescriptor, pointer, 0) + } + _ = Darwin.close(claimDescriptor) + } + _ = directoryName.withCString { pointer in + Darwin.unlinkat(rootDescriptor, pointer, AT_REMOVEDIR) + } + _ = claimName.withCString { pointer in + Darwin.unlinkat(rootDescriptor, pointer, AT_REMOVEDIR) + } + _ = flock(rootDescriptor, LOCK_UN) + _ = Darwin.close(rootDescriptor) + } + } + guard claimName.withCString({ pointer in + Darwin.mkdirat(rootDescriptor, pointer, S_IRWXU) + }) == 0 else { + throw CocoaError(.fileWriteUnknown) + } + claimDescriptor = claimName.withCString { pointer in + Darwin.openat( + rootDescriptor, + pointer, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + } + guard claimDescriptor >= 0 else { + throw CocoaError(.fileWriteUnknown) + } + descriptor = Self.leaseFilename.withCString { pointer in + Darwin.openat( + claimDescriptor, + pointer, + O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + guard descriptor >= 0, + flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { + throw CocoaError(.fileWriteUnknown) + } + guard claimName.withCString({ claimPointer in + directoryName.withCString { directoryPointer in + Darwin.renameat( + rootDescriptor, + claimPointer, + rootDescriptor, + directoryPointer + ) + } + }) == 0 else { + throw CocoaError(.fileWriteUnknown) + } + keepsLease = true + self.init( + directory: directory, + descriptor: descriptor, + directoryDescriptor: claimDescriptor, + rootDescriptor: rootDescriptor, + directoryName: directoryName + ) + } + + func makeStagedURL() -> URL { + let name = UUID().uuidString + stagedNames.insert(name) + return directory.appendingPathComponent(name, isDirectory: false) + } + + /// Opens a staged destination relative to the pinned batch directory. + func openStagedFile(for url: URL) -> Int32? { + let name = url.lastPathComponent + guard stagedNames.contains(name) else { return nil } + return name.withCString { pointer in + Darwin.openat( + directoryDescriptor, + pointer, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + } + + /// Removes one staged entry without following a replacement symlink. + func removeStagedFile(for url: URL) { + let name = url.lastPathComponent + guard stagedNames.remove(name) != nil else { return } + _ = name.withCString { pointer in + Darwin.unlinkat(directoryDescriptor, pointer, 0) + } + } + + func finish() { + guard descriptor >= 0 else { return } + for name in stagedNames { + _ = name.withCString { pointer in + Darwin.unlinkat(directoryDescriptor, pointer, 0) + } + } + stagedNames.removeAll() + _ = Self.leaseFilename.withCString { pointer in + Darwin.unlinkat(directoryDescriptor, pointer, 0) + } + _ = Darwin.fsync(directoryDescriptor) + _ = Darwin.close(directoryDescriptor) + _ = Darwin.unlinkat(rootDescriptor, directoryName, AT_REMOVEDIR) + _ = flock(rootDescriptor, LOCK_UN) + _ = flock(descriptor, LOCK_UN) + _ = close(descriptor) + _ = Darwin.close(rootDescriptor) + descriptor = -1 + } + + deinit { + finish() + } + + private static func canonicalPath(_ url: URL) -> String { + url.resolvingSymlinksInPath().standardizedFileURL.path + } + + private static func openedPath(for descriptor: Int32) -> String? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + return canonicalPath(URL(fileURLWithPath: String( + decoding: buffer.prefix { $0 != 0 }, + as: UTF8.self + ))) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMarkerDirectoryCatalog.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMarkerDirectoryCatalog.swift new file mode 100644 index 000000000000..174107380100 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMarkerDirectoryCatalog.swift @@ -0,0 +1,87 @@ +import Foundation + +/// Bounded catalog of live directories carrying decodable cmux identity markers. +struct ArtifactMarkerDirectoryCatalog { + let fileManager: FileManager + let decoder: JSONDecoder + let nodeBudget: Int + + func sessionDirectories( + paths: ArtifactStorePaths, + pathResolver: ArtifactPathResolver + ) throws -> [(directory: URL, marker: ArtifactSessionMarker)] { + try markerDirectories( + paths: paths, + markerName: ArtifactPathResolver.sessionMarkerName, + pathResolver: pathResolver + ) + } + + func workspaceDirectories( + paths: ArtifactStorePaths, + pathResolver: ArtifactPathResolver + ) throws -> [(directory: URL, marker: ArtifactWorkspaceMarker)] { + try markerDirectories( + paths: paths, + markerName: ArtifactPathResolver.workspaceMarkerName, + pathResolver: pathResolver + ) + } + + private func markerDirectories( + paths: ArtifactStorePaths, + markerName: String, + pathResolver: ArtifactPathResolver + ) throws -> [(directory: URL, marker: Marker)] { + guard let enumerator = fileManager.enumerator( + at: paths.filesystemRoot, + includingPropertiesForKeys: [ + .isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey, + ], + options: [.skipsPackageDescendants] + ) else { return [] } + var entries: [(directory: URL, marker: Marker)] = [] + var visited = 0 + var exceededNodeBudget = false + for case let url as URL in enumerator { + guard visited < nodeBudget else { + exceededNodeBudget = true + break + } + visited += 1 + if pathResolver.refersToSameLocation(url, paths.metadataRoot) { + enumerator.skipDescendants() + continue + } + guard url.lastPathComponent == markerName, + let data = try? ArtifactBoundedFileReader(fileManager: fileManager).data( + url: url, + allowedRoot: paths.filesystemRoot, + maximumBytes: 256 * 1024 + ), + let marker = try? decoder.decode(Marker.self, from: data) else { + continue + } + let directory = url.deletingLastPathComponent() + guard let relativePath = pathResolver.relativePath( + directory, + root: paths.filesystemRoot + ) else { + continue + } + entries.append(( + directory: paths.filesystemRoot.appendingPathComponent( + relativePath, + isDirectory: true + ), + marker: marker + )) + } + guard !exceededNodeBudget else { + throw ArtifactStoreError.scanIncomplete(paths.filesystemRoot.path) + } + return entries.sorted { + $0.directory.path.localizedStandardCompare($1.directory.path) == .orderedAscending + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMetadataDocument.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMetadataDocument.swift new file mode 100644 index 000000000000..bcaa507ef7fd --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactMetadataDocument.swift @@ -0,0 +1,10 @@ +import Foundation + +/// Content-addressed provenance that survives ordinary artifact moves. +struct ArtifactMetadataDocument: Codable, Equatable, Sendable { + let version: Int + let digest: String + var lastKnownRelativePath: String + let size: Int64 + var events: [ArtifactProvenanceEvent] +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactNode.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactNode.swift new file mode 100644 index 000000000000..39fddc108b50 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactNode.swift @@ -0,0 +1,76 @@ +public import Foundation + +/// Immutable filesystem tree node projected to sidebar rows. +public struct ArtifactNode: Identifiable, Equatable, Sendable { + /// Node identity, equal to its project-relative path. + public let id: String + /// Basename shown in the tree. + public let name: String + /// Path relative to the project's `.cmux` filesystem. + public let relativePath: String + /// Absolute local path used by open, reveal, copy, and drag actions. + public let absolutePath: String + /// Whether this node is an ordinary directory. + public let isDirectory: Bool + /// Preview classification for files. + public let fileKind: ArtifactFileKind? + /// File byte size when available. + public let size: Int64? + /// Filesystem modification time when available. + public let modifiedAt: Date? + /// Device/inode identity observed for a regular file. + public let fileIdentity: ArtifactFileIdentity? + /// Eager child snapshot for directories. + public let children: [ArtifactNode] + + /// Creates an immutable artifact tree node. + /// + /// - Parameters: + /// - id: Stable node identity. + /// - name: Basename shown in the tree. + /// - relativePath: Path relative to the project `.cmux` filesystem. + /// - absolutePath: Absolute local path. + /// - isDirectory: Whether the node is a directory. + /// - fileKind: Preview classification for a file. + /// - size: File byte size when known. + /// - modifiedAt: Filesystem modification time when known. + /// - fileIdentity: Device/inode identity when the file could be inspected. + /// - children: Eager child snapshot for a directory. + public init( + id: String, + name: String, + relativePath: String, + absolutePath: String, + isDirectory: Bool, + fileKind: ArtifactFileKind?, + size: Int64?, + modifiedAt: Date?, + fileIdentity: ArtifactFileIdentity? = nil, + children: [ArtifactNode] + ) { + self.id = id + self.name = name + self.relativePath = relativePath + self.absolutePath = absolutePath + self.isDirectory = isDirectory + self.fileKind = fileKind + self.size = size + self.modifiedAt = modifiedAt + self.fileIdentity = fileIdentity + self.children = children + } +} + +extension Array where Element == ArtifactNode { + /// Returns every node in depth-first tree order. + public func flattenedArtifactNodes() -> [ArtifactNode] { + var flattened: [ArtifactNode] = [] + flattened.reserveCapacity(count) + var stack = reversed().map { $0 } + while let node = stack.popLast() { + flattened.append(node) + stack.append(contentsOf: node.children.reversed()) + } + return flattened + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactPathResolver.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactPathResolver.swift new file mode 100644 index 000000000000..2505e9baf021 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactPathResolver.swift @@ -0,0 +1,176 @@ +import Foundation + +/// Pure path policy for ephemeral detection, grouping, and confinement. +struct ArtifactPathResolver: Sendable { + static let workspaceMarkerName = "_workspace.json" + static let sessionMarkerName = "_session.json" + // Only FileManager's thread-safe, stateless path queries are used through this immutable reference. + nonisolated(unsafe) private let fileManager: FileManager + + init(fileManager: FileManager) { + self.fileManager = fileManager + } + + func isEphemeral(_ url: URL, prefixes: [String]) -> Bool { + let path = canonicalPath(url) + let trustedRoots = ArtifactCaptureConfiguration.defaultValue.ephemeralPathPrefixes.map { + canonicalPath(URL(fileURLWithPath: $0, isDirectory: true)) + } + return prefixes.contains { + let prefix = canonicalPath(URL(fileURLWithPath: $0, isDirectory: true)) + guard trustedRoots.contains(where: { trustedRoot in + contains(path: prefix, under: trustedRoot) + }) else { + return false + } + return contains( + path: path, + under: prefix + ) + } + } + + func isInsideStore(_ url: URL, paths: ArtifactStorePaths) -> Bool { + contains( + path: canonicalPath(url), + under: canonicalPath(paths.filesystemRoot) + ) + } + + func relativePath(_ url: URL, root: URL) -> String? { + let path = canonicalPath(url) + let rootPath = canonicalPath(root) + guard contains(path: path, under: rootPath), path != rootPath else { return nil } + return String(path.dropFirst(rootPath.count + 1)) + } + + func refersToSameLocation(_ lhs: URL, _ rhs: URL) -> Bool { + canonicalPath(lhs) == canonicalPath(rhs) + } + + func contentDirectory( + paths: ArtifactStorePaths, + context: ArtifactCaptureContext, + kind: CmuxSessionContentKind + ) -> URL { + let hasAgentSession = normalized(context.sessionID) != nil + let sessionPrefix = hasAgentSession + ? normalized(context.agentName) ?? "session" + : normalized(context.agentName) ?? (normalized(context.workspaceID) == nil ? "session" : "workspace") + let session = slug( + preferred: nil, + fallbackPrefix: sessionPrefix, + identity: context.sessionID ?? context.workspaceID + ) + return paths.filesystemRoot + .appendingPathComponent(session, isDirectory: true) + .appendingPathComponent(kind.rawValue, isDirectory: true) + } + + func slug(preferred: String?, fallbackPrefix: String, identity: String?) -> String { + let preferredSlug = normalized(preferred) + let identitySlug = normalized(identity).map { readableIdentity in + ArtifactIdentitySlug().value( + readableIdentity: readableIdentity, + stableIdentity: identity ?? readableIdentity + ) + } + if let preferredSlug, let identitySlug { + return "\(String(preferredSlug.prefix(48)))-\(identitySlug)" + } + if let preferredSlug { return String(preferredSlug.prefix(64)) } + if let identitySlug { return "\(fallbackPrefix)-\(identitySlug)" } + return fallbackPrefix + } + + func uniqueDestination( + source: URL, + directory: URL, + fileManager: FileManager, + reservedPaths: Set = [] + ) -> URL { + let proposed = directory.appendingPathComponent(source.lastPathComponent, isDirectory: false) + let usesCaseSensitiveNames = volumeSupportsCaseSensitiveNames( + at: directory, + fileManager: fileManager + ) == true + let isManagedMarkerName: (String) -> Bool = { name in + [Self.workspaceMarkerName, Self.sessionMarkerName].contains { markerName in + if usesCaseSensitiveNames { return name == markerName } + return name.caseInsensitiveCompare(markerName) == .orderedSame + } + } + let isReserved: (URL) -> Bool = { url in + let path = url.standardizedFileURL.path + return reservedPaths.contains { reservedPath in + if usesCaseSensitiveNames { return reservedPath == path } + return reservedPath.caseInsensitiveCompare(path) == .orderedSame + } + } + guard fileManager.fileExists(atPath: proposed.path) + || isReserved(proposed) + || isManagedMarkerName(proposed.lastPathComponent) else { + return proposed + } + let basename = source.deletingPathExtension().lastPathComponent + let pathExtension = source.pathExtension + for suffix in 2...10_000 { + var name = "\(basename)-\(suffix)" + if !pathExtension.isEmpty { name += ".\(pathExtension)" } + let candidate = directory.appendingPathComponent(name, isDirectory: false) + if !fileManager.fileExists(atPath: candidate.path), + !isReserved(candidate), + !isManagedMarkerName(candidate.lastPathComponent) { + return candidate + } + } + return directory.appendingPathComponent("\(UUID().uuidString)-\(source.lastPathComponent)") + } + + private func volumeSupportsCaseSensitiveNames( + at url: URL, + fileManager: FileManager + ) -> Bool? { + for ancestor in ArtifactAncestorDirectories(startingAt: url) { + guard fileManager.fileExists(atPath: ancestor.path), + let values = try? ancestor.resourceValues( + forKeys: [.volumeSupportsCaseSensitiveNamesKey] + ), + let supportsCaseSensitiveNames = values.volumeSupportsCaseSensitiveNames else { + continue + } + return supportsCaseSensitiveNames + } + return nil + } + + private func normalized(_ raw: String?) -> String? { + guard let raw else { return nil } + let scalars = raw.lowercased().unicodeScalars.map { scalar -> Character in + CharacterSet.alphanumerics.contains(scalar) ? Character(String(scalar)) : "-" + } + let value = String(scalars) + .split(separator: "-", omittingEmptySubsequences: true) + .joined(separator: "-") + return value.isEmpty ? nil : value + } + + private func contains(path: String, under root: String) -> Bool { + let rootPath = URL(fileURLWithPath: root).standardizedFileURL.path + return path == rootPath || path.hasPrefix(rootPath.hasSuffix("/") ? rootPath : rootPath + "/") + } + + func canonicalPath(_ url: URL) -> String { + let standardized = url.standardizedFileURL + for ancestor in ArtifactAncestorDirectories(startingAt: standardized) { + guard fileManager.fileExists(atPath: ancestor.path) else { continue } + let resolvedAncestor = ancestor.resolvingSymlinksInPath().standardizedFileURL + let unresolvedComponents = standardized.pathComponents.dropFirst(ancestor.pathComponents.count) + return unresolvedComponents.reduce(resolvedAncestor) { partialURL, component in + partialURL.appendingPathComponent(component, isDirectory: false) + } + .standardizedFileURL.path + } + return standardized.path + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProjectLocator.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProjectLocator.swift new file mode 100644 index 000000000000..d3f4fb93cba8 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProjectLocator.swift @@ -0,0 +1,36 @@ +public import Foundation + +/// Resolves the nearest project root from a working directory or file path. +public struct ArtifactProjectLocator: Sendable { + /// Creates a project locator. + public init() {} + + /// Finds the nearest ancestor containing `.cmux`, otherwise the nearest Git root. + /// + /// - Parameters: + /// - startingURL: Working directory or file URL. + /// - fileManager: Filesystem dependency used for testable lookup. + /// - Returns: Project root, falling back to the starting directory. + public func projectRoot( + startingAt startingURL: URL, + fileManager: FileManager + ) -> URL { + var isDirectory: ObjCBool = false + let standardized = startingURL.standardizedFileURL + let startingDirectory: URL + if fileManager.fileExists(atPath: standardized.path, isDirectory: &isDirectory), !isDirectory.boolValue { + startingDirectory = standardized.deletingLastPathComponent() + } else { + startingDirectory = standardized + } + for current in ArtifactAncestorDirectories(startingAt: startingDirectory) { + if fileManager.fileExists(atPath: current.appendingPathComponent(".cmux", isDirectory: true).path) { + return current + } + if fileManager.fileExists(atPath: current.appendingPathComponent(".git", isDirectory: false).path) { + return current + } + } + return startingDirectory + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenance.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenance.swift new file mode 100644 index 000000000000..ac3ccdb1ce78 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenance.swift @@ -0,0 +1,13 @@ +import Foundation + +/// Describes how cmux learned about an artifact path. +public enum ArtifactProvenance: String, Codable, CaseIterable, Sendable { + /// An agent created or edited the file. + case created + /// The file was attached to an agent conversation. + case attached + /// Agent output referred to the file without a structured creation signal. + case referenced + /// A user or agent explicitly added the file with `cmux artifact add`. + case manual +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceEvent.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceEvent.swift new file mode 100644 index 000000000000..41d558b58a3c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceEvent.swift @@ -0,0 +1,10 @@ +import Foundation + +/// One capture occurrence retained in content-addressed metadata. +struct ArtifactProvenanceEvent: Codable, Equatable, Sendable { + let sourcePath: String + let workspaceID: String? + let sessionID: String? + let provenance: ArtifactProvenance + let capturedAt: Date +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceRecorder.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceRecorder.swift new file mode 100644 index 000000000000..dccfff9773a7 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactProvenanceRecorder.swift @@ -0,0 +1,120 @@ +import Foundation + +/// Persists content-addressed capture history independently of artifact paths. +struct ArtifactProvenanceRecorder { + static let maximumDocumentBytes: Int64 = 256 * 1024 + private static let maximumEventFieldCharacters = 4_096 + + let fileManager: FileManager + let encoder: JSONEncoder + let decoder: JSONDecoder + + func document(paths: ArtifactStorePaths, digest: String) throws -> ArtifactMetadataDocument? { + let url = metadataURL(paths: paths, digest: digest) + let reader = ArtifactBoundedFileReader(fileManager: fileManager) + do { + guard try reader.pathEntryExists(url: url) else { return nil } + guard let data = try reader.data( + url: url, + allowedRoot: paths.provenanceRoot, + maximumBytes: Self.maximumDocumentBytes + ) else { + throw ArtifactStoreError.corruptProvenance(url.path) + } + return try decoder.decode(ArtifactMetadataDocument.self, from: data) + } catch let error as CancellationError { + throw error + } catch { + throw ArtifactStoreError.corruptProvenance(url.path) + } + } + + func record( + paths: ArtifactStorePaths, + digest: String, + relativePath: String, + size: Int64, + event: ArtifactProvenanceEvent, + mutationLease: ArtifactStoreMutationLease? = nil + ) throws { + let expectedFilesystemRootPath = ArtifactPathResolver(fileManager: fileManager) + .canonicalPath(paths.filesystemRoot) + try rejectSymbolicLink(at: paths.filesystemRoot) + try rejectSymbolicLink(at: paths.metadataRoot) + try rejectSymbolicLink(at: paths.provenanceRoot) + try fileManager.createDirectory(at: paths.provenanceRoot, withIntermediateDirectories: true) + try rejectSymbolicLink(at: paths.filesystemRoot) + try rejectSymbolicLink(at: paths.metadataRoot) + try rejectSymbolicLink(at: paths.provenanceRoot) + try rejectSymbolicLink(at: metadataURL(paths: paths, digest: digest)) + var document = try document(paths: paths, digest: digest) ?? ArtifactMetadataDocument( + version: 1, + digest: digest, + lastKnownRelativePath: relativePath, + size: size, + events: [] + ) + guard document.digest == digest, document.size == size else { + throw ArtifactStoreError.corruptProvenance( + metadataURL(paths: paths, digest: digest).path + ) + } + document.lastKnownRelativePath = relativePath + document.events.append(bounded(event)) + if document.events.count > 100 { + document.events.removeFirst(document.events.count - 100) + } + var data = try encoder.encode(document) + while Int64(data.count) > Self.maximumDocumentBytes, document.events.count > 1 { + document.events.removeFirst() + data = try encoder.encode(document) + } + guard Int64(data.count) <= Self.maximumDocumentBytes else { + throw ArtifactStoreError.corruptProvenance( + metadataURL(paths: paths, digest: digest).path + ) + } + if let mutationLease { + try mutationLease.writeData( + data, + toRelativePath: ".metadata/provenance/\(digest).json" + ) + } else { + let ownedLease = try ArtifactStoreMutationLease( + directory: paths.filesystemRoot, + expectedCanonicalPath: expectedFilesystemRootPath + ) + defer { ownedLease.finish() } + try ownedLease.writeData( + data, + toRelativePath: ".metadata/provenance/\(digest).json" + ) + } + } + + func metadataURL(paths: ArtifactStorePaths, digest: String) -> URL { + paths.provenanceRoot.appendingPathComponent("\(digest).json", isDirectory: false) + } + + private func bounded(_ event: ArtifactProvenanceEvent) -> ArtifactProvenanceEvent { + ArtifactProvenanceEvent( + sourcePath: String(event.sourcePath.prefix(Self.maximumEventFieldCharacters)), + workspaceID: event.workspaceID.map { + String($0.prefix(Self.maximumEventFieldCharacters)) + }, + sessionID: event.sessionID.map { + String($0.prefix(Self.maximumEventFieldCharacters)) + }, + provenance: event.provenance, + capturedAt: event.capturedAt + ) + } + + private func rejectSymbolicLink(at url: URL) throws { + guard fileManager.fileExists(atPath: url.path) else { return } + let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactRecord.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactRecord.swift new file mode 100644 index 000000000000..57ae3bc01efd --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactRecord.swift @@ -0,0 +1,52 @@ +public import Foundation + +/// Provenance returned for one imported or deduplicated artifact. +public struct ArtifactRecord: Codable, Equatable, Sendable { + /// SHA-256 content digest used for deduplication. + public let digest: String + /// Original absolute source path at capture time. + public let sourcePath: String + /// Current artifact path relative to `.cmux` at capture time. + public let relativePath: String + /// Workspace identity attached to the capture. + public let workspaceID: String? + /// Agent session identity attached to the capture. + public let sessionID: String? + /// Detection or manual provenance. + public let provenance: ArtifactProvenance + /// Capture timestamp. + public let capturedAt: Date + /// File size in bytes. + public let size: Int64 + + /// Creates recorded artifact provenance. + /// + /// - Parameters: + /// - digest: SHA-256 content digest. + /// - sourcePath: Original absolute source path. + /// - relativePath: Project `.cmux`-relative path at capture time. + /// - workspaceID: Associated workspace identity. + /// - sessionID: Associated agent-session identity. + /// - provenance: How cmux learned about the file. + /// - capturedAt: Capture timestamp. + /// - size: File size in bytes. + public init( + digest: String, + sourcePath: String, + relativePath: String, + workspaceID: String?, + sessionID: String?, + provenance: ArtifactProvenance, + capturedAt: Date, + size: Int64 + ) { + self.digest = digest + self.sourcePath = sourcePath + self.relativePath = relativePath + self.workspaceID = workspaceID + self.sessionID = sessionID + self.provenance = provenance + self.capturedAt = capturedAt + self.size = size + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSearchEngine.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSearchEngine.swift new file mode 100644 index 000000000000..ec4a5b3cae6c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSearchEngine.swift @@ -0,0 +1,73 @@ +import Foundation + +/// Searches immutable tree values and bounded UTF-8 file contents. +struct ArtifactSearchEngine { + let configuration: ArtifactCaptureConfiguration + let fileManager: FileManager + + func results(snapshot: ArtifactSnapshot, query rawQuery: String) throws -> [ArtifactSearchResult] { + try Task.checkCancellation() + let matcher = ArtifactFuzzyMatcher(query: rawQuery) + guard !matcher.isEmpty else { return [] } + var remainingContentBytes = configuration.contentSearchTotalMaximumBytes + var results: [ArtifactSearchResult] = [] + for node in snapshot.nodes.flattenedArtifactNodes() where !node.isDirectory { + try Task.checkCancellation() + let nameScore = matcher.score(candidate: node.name) + let pathScore = matcher.score(candidate: node.relativePath).map { $0 - 250 } + let contentMatch = try contentMatch( + node: node, + filesystemRoot: snapshot.filesystemRoot, + query: matcher.contentQuery, + remainingBytes: &remainingContentBytes + ) + guard nameScore != nil || pathScore != nil || contentMatch != nil else { continue } + let bestScore = max(nameScore ?? Int.min, pathScore ?? Int.min, contentMatch == nil ? Int.min : 2_000) + results.append(ArtifactSearchResult( + node: node, + score: bestScore, + matchedContent: contentMatch != nil, + snippet: contentMatch + )) + } + try Task.checkCancellation() + let sortedResults = results.sorted { + if $0.score != $1.score { return $0.score > $1.score } + return $0.node.relativePath.localizedStandardCompare($1.node.relativePath) == .orderedAscending + } + try Task.checkCancellation() + return sortedResults.prefix(configuration.maximumSearchResults).map { $0 } + } + + private func contentMatch( + node: ArtifactNode, + filesystemRoot: URL, + query: String, + remainingBytes: inout Int64 + ) throws -> String? { + try Task.checkCancellation() + guard node.fileKind?.isTextSearchable == true, remainingBytes > 0 else { + return nil + } + let maximumBytes = min(configuration.contentSearchMaximumBytes, remainingBytes) + guard let data = try ArtifactBoundedFileReader(fileManager: fileManager).data( + url: URL(fileURLWithPath: node.absolutePath), + allowedRoot: filesystemRoot, + maximumBytes: maximumBytes + ) else { + return nil + } + try Task.checkCancellation() + remainingBytes -= Int64(data.count) + guard + let text = String(data: data, encoding: .utf8), + let range = text.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) else { + return nil + } + let lineStart = text[.. + private let watcherDebounce: Duration + private let watcherClock: any Clock + private var workspace: ArtifactSidebarWorkspace? + private var nodes: [ArtifactNode] = [] + private var expandedPaths: Set = [] + private var hasInitializedExpansion = false + private let tasks = ArtifactSidebarTaskBag() + private var bindingRequestRevision: UInt64 = 0 + private var bindingRevision: UInt64 = 0 + private var latestWorkspaceTitle: (id: String, title: String?)? + private var watcherReloadInFlight = false + private var watcherReloadPending = false + private var watcherEventGeneration: UInt64 = 0 + + /// Creates a sidebar model with injected filesystem and capture seams. + /// + /// - Parameters: + /// - store: Authoritative filesystem repository. + /// - captureService: Shared validated manual-capture service. + /// - searchDebounce: Cancellable delay used to coalesce typing into searches. + /// - searchClock: Clock that owns the cancellable debounce deadline. + /// - watcherDebounce: Cancellable quiet period used to coalesce filesystem bursts. + /// - watcherClock: Clock that owns the watcher quiet-period deadline. + public init( + store: any ArtifactStoring, + captureService: any ArtifactCapturing, + searchDebounce: Duration = .milliseconds(150), + searchClock: any Clock = ContinuousClock(), + watcherDebounce: Duration = .milliseconds(100), + watcherClock: any Clock = ContinuousClock() + ) { + self.store = store + self.captureService = captureService + self.searchDebounce = searchDebounce + self.searchClock = searchClock + self.watcherDebounce = watcherDebounce + self.watcherClock = watcherClock + } + + /// Binds the model to a selected local workspace and loads its initial tree. + /// + /// Passing `nil` clears the tree and stops filesystem observation. + /// + /// - Parameter workspace: Selected local workspace, or `nil` when unavailable. + public func bind(workspace: ArtifactSidebarWorkspace?) async { + guard self.workspace != workspace else { return } + bindingRequestRevision &+= 1 + let requestRevision = bindingRequestRevision + guard var workspace else { + stop() + return + } + if latestWorkspaceTitle?.id == workspace.id { + workspace = ArtifactSidebarWorkspace( + id: workspace.id, + title: latestWorkspaceTitle?.title, + workingDirectory: workspace.workingDirectory + ) + } + let changesWorkspaceIdentity = self.workspace?.id != workspace.id + var revision = changesWorkspaceIdentity ? prepareForBinding(to: workspace) : nil + let root = await store.locateProjectRoot(startingAt: workspace.workingDirectory) + guard requestRevision == bindingRequestRevision, !Task.isCancelled else { return } + if self.workspace?.id == workspace.id, projectRoot == root { + self.workspace = workspace + return + } + + revision = revision ?? prepareForBinding(to: workspace) + guard let revision else { return } + projectRoot = root + let changes = await store.changes(projectRoot: root) + guard revision == bindingRevision, !Task.isCancelled else { return } + await reload(projectRoot: root, revision: revision) + guard revision == bindingRevision, !Task.isCancelled else { return } + startWatching(changes: changes, projectRoot: root, revision: revision) + } + + /// Reloads the current filesystem tree immediately. + public func refresh() async { + guard let projectRoot else { return } + await reload(projectRoot: projectRoot, revision: bindingRevision) + } + + /// Starts a refresh owned by this model and cancels any obsolete sidebar action. + public func requestRefresh() { + tasks.replaceAction { + Task { [weak self] in + await self?.refresh() + } + } + } + + /// Stops long-lived observation tasks when the owning UI is torn down. + public func stop() { + bindingRequestRevision &+= 1 + bindingRevision &+= 1 + tasks.cancelAll() + watcherReloadInFlight = false + watcherReloadPending = false + watcherEventGeneration = 0 + workspace = nil + projectRoot = nil + nodes = [] + rows = [] + expandedPaths = [] + hasInitializedExpansion = false + actionFailure = nil + phase = .unavailable + } + + /// Updates cosmetic workspace metadata without rebinding the filesystem watcher. + public func updateWorkspaceTitle(workspaceID: String, title: String?) { + latestWorkspaceTitle = (workspaceID, title) + guard let workspace, workspace.id == workspaceID else { return } + self.workspace = ArtifactSidebarWorkspace( + id: workspace.id, + title: title, + workingDirectory: workspace.workingDirectory + ) + } + + /// Updates filename/content search and schedules a repository query. + /// + /// - Parameter query: User-entered query. + public func setQuery(_ query: String) { + guard self.query != query else { return } + self.query = query + scheduleSearch() + } + + /// Expands or collapses a directory row. + /// + /// - Parameter relativePath: Directory path relative to the project `.cmux` filesystem. + public func toggleExpansion(relativePath: String) { + if expandedPaths.contains(relativePath) { + expandedPaths.remove(relativePath) + } else { + expandedPaths.insert(relativePath) + } + rebuildTreeRows() + } + + /// Adds user-selected files through the shared validated capture service. + /// + /// - Parameter urls: Existing local regular files selected by the user. + public func addFiles(_ urls: [URL]) async { + guard let projectRoot, let workspace else { return } + actionFailure = nil + let context = ArtifactCaptureContext( + projectRoot: projectRoot, + workspaceID: workspace.id, + workspaceTitle: workspace.title + ) + let attempts = await captureService.add( + sourceURLs: urls, + context: context, + capturedAt: .now + ) + guard !Task.isCancelled else { return } + await reload(projectRoot: projectRoot, revision: bindingRevision) + guard !Task.isCancelled else { return } + if attempts.contains(where: { attempt in + if case .rejected = attempt { return true } + return false + }) { + actionFailure = .add + } + } + + /// Starts manual capture owned by this model and cancels any obsolete sidebar action. + /// + /// - Parameter urls: Existing local regular files selected by the user. + public func requestAddFiles(_ urls: [URL]) { + tasks.replaceAction { + Task { [weak self] in + await self?.addFiles(urls) + } + } + } + + /// Clears the current recoverable action failure after presentation. + public func clearActionFailure() { + actionFailure = nil + } + + private func startWatching( + changes: AsyncStream, + projectRoot: URL, + revision: UInt64 + ) { + let signals = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + tasks.replaceWatcher { + let observer = Task { @MainActor [weak self] in + defer { signals.continuation.finish() } + for await _ in changes { + guard !Task.isCancelled, + let self, + self.bindingRevision == revision else { + break + } + self.watcherEventGeneration &+= 1 + self.watcherReloadPending = true + if !self.watcherReloadInFlight { + signals.continuation.yield(()) + } + } + } + let reloader = Task { @MainActor [weak self] in + for await _ in signals.stream { + guard !Task.isCancelled, + let self, + self.bindingRevision == revision else { + break + } + self.watcherReloadInFlight = true + var generation = self.watcherEventGeneration + repeat { + self.watcherReloadPending = false + generation = self.watcherEventGeneration + do { + try await self.watcherClock.sleep(for: self.watcherDebounce) + } catch { + break + } + guard !Task.isCancelled, + self.bindingRevision == revision else { + break + } + guard generation == self.watcherEventGeneration else { continue } + await self.reload(projectRoot: projectRoot, revision: revision) + } while self.watcherEventGeneration != generation && !Task.isCancelled + if self.bindingRevision == revision { + self.watcherReloadInFlight = false + } + } + } + return [observer, reloader] + } + } + + private func prepareForBinding(to workspace: ArtifactSidebarWorkspace) -> UInt64 { + bindingRevision &+= 1 + tasks.cancelAll() + watcherReloadInFlight = false + watcherReloadPending = false + watcherEventGeneration = 0 + self.workspace = workspace + projectRoot = nil + nodes = [] + rows = [] + expandedPaths = [] + hasInitializedExpansion = false + actionFailure = nil + phase = .loading + return bindingRevision + } + + private func reload(projectRoot: URL, revision: UInt64) async { + do { + let snapshot = try await store.snapshot(projectRoot: projectRoot) + guard revision == bindingRevision, !Task.isCancelled else { return } + nodes = snapshot.nodes + if !hasInitializedExpansion { + expandedPaths = defaultExpandedPaths(nodes: snapshot.nodes) + hasInitializedExpansion = true + } + phase = .loaded + if query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + rebuildTreeRows() + } else { + scheduleSearch() + } + } catch { + guard revision == bindingRevision, !Task.isCancelled else { return } + phase = .failed + rows = [] + } + } + + private func scheduleSearch() { + tasks.cancelSearch() + let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedQuery.isEmpty else { + rebuildTreeRows() + return + } + guard let projectRoot else { + rows = [] + return + } + let revision = bindingRevision + let store = self.store + let searchDebounce = self.searchDebounce + let searchClock = self.searchClock + tasks.replaceSearch { + Task { [weak self] in + do { + // This bounded, injected deadline is the intended search debounce and is cancelled on new input. + try await searchClock.sleep(for: searchDebounce) + let results = try await store.search(projectRoot: projectRoot, query: trimmedQuery) + guard !Task.isCancelled else { return } + self?.applySearchResults(results, revision: revision, query: trimmedQuery) + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + self?.applySearchFailure(revision: revision, query: trimmedQuery) + } + } + } + } + + private func applySearchResults( + _ results: [ArtifactSearchResult], + revision: UInt64, + query searchedQuery: String + ) { + guard revision == bindingRevision, + query.trimmingCharacters(in: .whitespacesAndNewlines) == searchedQuery else { return } + rows = results.map { result in + row(node: result.node, depth: 0, matchedContent: result.matchedContent, snippet: result.snippet) + } + } + + private func applySearchFailure(revision: UInt64, query searchedQuery: String) { + guard revision == bindingRevision, + query.trimmingCharacters(in: .whitespacesAndNewlines) == searchedQuery else { return } + rows = [] + actionFailure = .search + } + + private func rebuildTreeRows() { + guard query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + var flattenedRows: [ArtifactSidebarRowSnapshot] = [] + flattenedRows.reserveCapacity(nodes.count) + var stack = nodes.reversed().map { (node: $0, depth: 0) } + while let entry = stack.popLast() { + flattenedRows.append(row(node: entry.node, depth: entry.depth)) + if entry.node.isDirectory, expandedPaths.contains(entry.node.relativePath) { + for child in entry.node.children.reversed() { + stack.append((node: child, depth: entry.depth + 1)) + } + } + } + rows = flattenedRows + } + + private func row( + node: ArtifactNode, + depth: Int, + matchedContent: Bool = false, + snippet: String? = nil + ) -> ArtifactSidebarRowSnapshot { + ArtifactSidebarRowSnapshot( + id: node.id, + name: node.name, + relativePath: node.relativePath, + fileURL: URL(fileURLWithPath: node.absolutePath, isDirectory: node.isDirectory), + projectRoot: projectRoot, + depth: depth, + isDirectory: node.isDirectory, + isExpanded: node.isDirectory && expandedPaths.contains(node.relativePath), + fileKind: node.fileKind, + fileRevision: node.isDirectory ? nil : ArtifactSidebarFileRevision( + fileURL: URL(fileURLWithPath: node.absolutePath), + modifiedAt: node.modifiedAt, + fileIdentity: node.fileIdentity + ), + matchedContent: matchedContent, + snippet: snippet + ) + } + + private func defaultExpandedPaths(nodes: [ArtifactNode]) -> Set { + var paths: Set = [] + for node in nodes where node.isDirectory { + paths.insert(node.relativePath) + for child in node.children where child.isDirectory { + paths.insert(child.relativePath) + } + } + return paths + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarPhase.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarPhase.swift new file mode 100644 index 000000000000..cae5c462e282 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarPhase.swift @@ -0,0 +1,11 @@ +/// Loading phase for the filesystem-backed Artifacts sidebar. +public enum ArtifactSidebarPhase: Equatable, Sendable { + /// No local workspace is selected. + case unavailable + /// Project resolution or filesystem scanning is in progress. + case loading + /// A live filesystem snapshot is available. + case loaded + /// The project artifact store could not be loaded. + case failed +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarRowSnapshot.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarRowSnapshot.swift new file mode 100644 index 000000000000..6fcd13ed8cfe --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarRowSnapshot.swift @@ -0,0 +1,72 @@ +public import Foundation + +/// Immutable row value rendered below the sidebar's lazy-list boundary. +public struct ArtifactSidebarRowSnapshot: Identifiable, Equatable, Sendable { + /// Stable row identity, equal to the artifact-relative path. + public let id: String + /// Basename shown as the primary row label. + public let name: String + /// Path relative to the project's `.cmux` filesystem. + public let relativePath: String + /// Absolute local file URL used by preview and drag actions. + public let fileURL: URL + /// Resolved project root that owns the row's CMUX filesystem. + public let projectRoot: URL? + /// Tree indentation depth. + public let depth: Int + /// Whether the row represents a directory. + public let isDirectory: Bool + /// Whether a directory is currently expanded. + public let isExpanded: Bool + /// Preview classification for file rows. + public let fileKind: ArtifactFileKind? + /// File identity and modification time used to invalidate previews. + public let fileRevision: ArtifactSidebarFileRevision? + /// Whether a content-search match contributed to this result. + public let matchedContent: Bool + /// Bounded content-search excerpt, when available. + public let snippet: String? + + /// Creates an immutable sidebar row. + /// + /// - Parameters: + /// - id: Stable row identity. + /// - name: Basename shown in the row. + /// - relativePath: Path relative to the project `.cmux` filesystem. + /// - fileURL: Absolute local file URL. + /// - projectRoot: Resolved project root owning the row, when available. + /// - depth: Tree indentation depth. + /// - isDirectory: Whether the row is a directory. + /// - isExpanded: Whether the directory is expanded. + /// - fileKind: Preview classification for a file. + /// - fileRevision: File identity and modification time used for preview invalidation. + /// - matchedContent: Whether file contents matched a search. + /// - snippet: Bounded single-line content excerpt. + public init( + id: String, + name: String, + relativePath: String, + fileURL: URL, + projectRoot: URL? = nil, + depth: Int, + isDirectory: Bool, + isExpanded: Bool, + fileKind: ArtifactFileKind?, + fileRevision: ArtifactSidebarFileRevision? = nil, + matchedContent: Bool = false, + snippet: String? = nil + ) { + self.id = id + self.name = name + self.relativePath = relativePath + self.fileURL = fileURL + self.projectRoot = projectRoot?.standardizedFileURL + self.depth = depth + self.isDirectory = isDirectory + self.isExpanded = isExpanded + self.fileKind = fileKind + self.fileRevision = fileRevision + self.matchedContent = matchedContent + self.snippet = snippet + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarTaskBag.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarTaskBag.swift new file mode 100644 index 000000000000..b901ad5dbe12 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarTaskBag.swift @@ -0,0 +1,45 @@ +import Foundation + +/// Owns cancellable sidebar work without imposing an executor on ARC teardown. +final class ArtifactSidebarTaskBag { + private var watchers: [Task] = [] + private var search: Task? + private var action: Task? + + deinit { + cancelAll() + } + + @MainActor + func replaceWatcher(with makeTasks: () -> [Task]) { + watchers.forEach { $0.cancel() } + watchers = makeTasks() + } + + @MainActor + func replaceSearch(with makeTask: () -> Task) { + search?.cancel() + search = makeTask() + } + + @MainActor + func replaceAction(with makeTask: () -> Task) { + action?.cancel() + action = makeTask() + } + + @MainActor + func cancelSearch() { + search?.cancel() + search = nil + } + + func cancelAll() { + watchers.forEach { $0.cancel() } + watchers.removeAll() + search?.cancel() + search = nil + action?.cancel() + action = nil + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarWorkspace.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarWorkspace.swift new file mode 100644 index 000000000000..785bdce2951a --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSidebarWorkspace.swift @@ -0,0 +1,23 @@ +public import Foundation + +/// Immutable selected-workspace input used to bind the Artifacts sidebar. +public struct ArtifactSidebarWorkspace: Equatable, Sendable { + /// Stable cmux workspace identity. + public let id: String + /// Human-readable workspace title used for capture grouping. + public let title: String? + /// Current local working directory from which the project root is resolved. + public let workingDirectory: URL + + /// Creates a sidebar workspace snapshot. + /// + /// - Parameters: + /// - id: Stable cmux workspace identity. + /// - title: Human-readable workspace title. + /// - workingDirectory: Current local working directory. + public init(id: String, title: String? = nil, workingDirectory: URL) { + self.id = id + self.title = title + self.workingDirectory = workingDirectory.standardizedFileURL + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSkipReason.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSkipReason.swift new file mode 100644 index 000000000000..70ce9542a066 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSkipReason.swift @@ -0,0 +1,27 @@ +import Foundation + +/// Reason a capture candidate was rejected safely. +public enum ArtifactSkipReason: String, Equatable, Sendable { + /// Automatic capture is disabled by project configuration. + case automaticCaptureDisabled + /// The candidate's provenance and location do not meet automatic policy. + case provenanceNotEligible + /// The path does not resolve to a regular file. + case notARegularFile + /// The requested path does not remain confined to the local artifact store. + case pathOutsideStore + /// Existing provenance metadata is corrupt and must not be overwritten. + case corruptProvenance + /// Git does not prove the artifact store is ignored and untracked. + case gitPrivacyUnavailable + /// Another process currently owns the artifact store mutation lease. + case storeBusy + /// The filename extension is not allowlisted. + case unsupportedExtension + /// The file exceeds the configured size limit. + case exceedsSizeLimit + /// This scan already reached its configured candidate limit. + case candidateLimitReached + /// Store discovery reached its bounded scan limit and must not be retried immediately. + case scanIncomplete +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSnapshot.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSnapshot.swift new file mode 100644 index 000000000000..2762a6a6ab45 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSnapshot.swift @@ -0,0 +1,27 @@ +public import Foundation + +/// One authoritative filesystem scan of a project's artifact store. +public struct ArtifactSnapshot: Equatable, Sendable { + /// Project root used for the scan. + public let projectRoot: URL + /// Absolute project `.cmux` directory. + public let filesystemRoot: URL + /// Top-level tree nodes. + public let nodes: [ArtifactNode] + /// Whether the scan stopped at its defensive node budget. + public let isTruncated: Bool + + /// Creates a filesystem snapshot. + /// + /// - Parameters: + /// - projectRoot: Project root used for the scan. + /// - filesystemRoot: Absolute project `.cmux` filesystem root. + /// - nodes: Top-level immutable tree nodes. + /// - isTruncated: Whether a defensive scan limit stopped traversal. + public init(projectRoot: URL, filesystemRoot: URL, nodes: [ArtifactNode], isTruncated: Bool) { + self.projectRoot = projectRoot + self.filesystemRoot = filesystemRoot + self.nodes = nodes + self.isTruncated = isTruncated + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshot.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshot.swift new file mode 100644 index 000000000000..412376a95798 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshot.swift @@ -0,0 +1,7 @@ +import Foundation + +/// Immutable, size-bounded copy of one import source. +struct ArtifactSourceSnapshot { + let url: URL + let size: Int64 +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshotter.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshotter.swift new file mode 100644 index 000000000000..0d2ef74eec41 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactSourceSnapshotter.swift @@ -0,0 +1,140 @@ +import Darwin +import Foundation + +/// Stages source bytes once so validation, hashing, and persistence agree. +struct ArtifactSourceSnapshotter { + let fileManager: FileManager + let chunkSize = 64 * 1024 + + func snapshot( + source: URL, + paths: ArtifactStorePaths, + configuration: ArtifactCaptureConfiguration, + maximumBytes: Int64?, + stagedURL: URL, + expectedCanonicalPath: String? = nil, + expectedIdentity: ArtifactFileIdentity? = nil, + stagingLease: ArtifactImportStagingLease? = nil + ) throws -> ArtifactSourceSnapshot { + try Task.checkCancellation() + let normalizedConfiguration = configuration.normalized + let pathExtension = source.pathExtension.lowercased() + guard normalizedConfiguration.allowedExtensions.contains(pathExtension) else { + throw ArtifactStoreError.unsupportedExtension(pathExtension) + } + let limit = ArtifactFileKind(fileURL: source) == .text + ? normalizedConfiguration.maximumTextFileBytes + : normalizedConfiguration.maximumFileBytes + let batchLimit = maximumBytes.map { max(0, $0) } + + try rejectSymbolicLink(at: paths.importStagingRoot) + try fileManager.createDirectory(at: paths.importStagingRoot, withIntermediateDirectories: true) + try rejectSymbolicLink(at: paths.importStagingRoot) + let sourceDescriptor = open( + source.path, + O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK + ) + guard sourceDescriptor >= 0 else { + throw ArtifactStoreError.sourceNotRegularFile(source.path) + } + let sourceHandle = FileHandle(fileDescriptor: sourceDescriptor, closeOnDealloc: true) + defer { try? sourceHandle.close() } + + var sourceStatus = stat() + guard fstat(sourceDescriptor, &sourceStatus) == 0, + (sourceStatus.st_mode & S_IFMT) == S_IFREG else { + throw ArtifactStoreError.sourceNotRegularFile(source.path) + } + if let expectedIdentity, + ArtifactFileIdentity( + device: UInt64(sourceStatus.st_dev), + inode: UInt64(sourceStatus.st_ino) + ) != expectedIdentity { + throw ArtifactStoreError.pathOutsideStore(source.path) + } + if let expectedCanonicalPath { + let resolver = ArtifactPathResolver(fileManager: fileManager) + guard let openedPath = openedPath(for: sourceDescriptor), + resolver.canonicalPath(URL(fileURLWithPath: openedPath)) + == expectedCanonicalPath else { + throw ArtifactStoreError.pathOutsideStore(source.path) + } + } + guard sourceStatus.st_size <= limit else { + throw ArtifactStoreError.fileTooLarge(actual: sourceStatus.st_size, limit: limit) + } + if let batchLimit, sourceStatus.st_size > batchLimit { + throw ArtifactStoreError.batchByteLimitReached( + actual: sourceStatus.st_size, + limit: batchLimit + ) + } + + let stagedDescriptor: Int32 + if let stagingLease { + stagedDescriptor = stagingLease.openStagedFile(for: stagedURL) ?? -1 + } else { + stagedDescriptor = open( + stagedURL.path, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + guard stagedDescriptor >= 0 else { + throw CocoaError(.fileWriteUnknown) + } + let stagedHandle = FileHandle(fileDescriptor: stagedDescriptor, closeOnDealloc: true) + var keepsStagedFile = false + defer { + try? stagedHandle.close() + if !keepsStagedFile { + if let stagingLease { + stagingLease.removeStagedFile(for: stagedURL) + } else { + try? fileManager.removeItem(at: stagedURL) + } + } + } + + var size: Int64 = 0 + while true { + try Task.checkCancellation() + guard let data = try sourceHandle.read(upToCount: chunkSize), !data.isEmpty else { break } + size += Int64(data.count) + guard size <= limit else { + throw ArtifactStoreError.fileTooLarge(actual: size, limit: limit) + } + if let batchLimit, size > batchLimit { + throw ArtifactStoreError.batchByteLimitReached(actual: size, limit: batchLimit) + } + try stagedHandle.write(contentsOf: data) + } + try stagedHandle.synchronize() + try stagedHandle.close() + keepsStagedFile = true + return ArtifactSourceSnapshot(url: stagedURL, size: size) + } + + private func rejectSymbolicLink(at url: URL) throws { + guard fileManager.fileExists(atPath: url.path) else { return } + let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + } + + /// Returns the kernel-resolved path for an already-open descriptor. + /// + /// Validating the descriptor after O_NOFOLLOW closes the parent symlink + /// TOCTOU window: a swapped directory can no longer redirect the bytes we + /// stage without producing a different resolved path. + private func openedPath(for descriptor: Int32) -> String? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + return String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreError.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreError.swift new file mode 100644 index 000000000000..a5a0cc3139fb --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreError.swift @@ -0,0 +1,37 @@ +import Foundation + +/// Errors surfaced by artifact persistence and CLI operations. +public enum ArtifactStoreError: Error, Equatable, Sendable { + /// The source path does not exist or is not a regular file. + case sourceNotRegularFile(String) + /// The filename extension is not permitted by project policy. + case unsupportedExtension(String) + /// The source exceeds the configured byte limit. + case fileTooLarge(actual: Int64, limit: Int64) + /// The capture batch lacks enough aggregate staging budget for a source. + /// + /// - Parameters: + /// - actual: Source byte count, or zero when the batch budget is already exhausted. + /// - limit: Aggregate byte budget reported by the rejecting capture layer. + case batchByteLimitReached(actual: Int64, limit: Int64) + /// A manual selection exceeded the maximum number of files accepted in one request. + /// + /// - Parameters: + /// - actual: Number of files supplied in the selection. + /// - limit: Maximum number of files accepted by the capture service. + case fileCountLimitReached(actual: Int64, limit: Int64) + /// A requested artifact name was missing. + case artifactNotFound(String) + /// A name matched more than one artifact and requires a more specific path. + case ambiguousArtifactName(String, matches: [String]) + /// A bounded filesystem scan stopped before it could produce an authoritative result. + case scanIncomplete(String) + /// The resolved path escaped the artifact store boundary. + case pathOutsideStore(String) + /// Existing content-addressed provenance could not be decoded safely. + case corruptProvenance(String) + /// Git does not prove the local artifact store is ignored and untracked. + case gitPrivacyUnavailable(String) + /// Another app or CLI process currently owns the artifact mutation boundary. + case storeBusy(String) +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreMutationLease.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreMutationLease.swift new file mode 100644 index 000000000000..05c78acbfcc3 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreMutationLease.swift @@ -0,0 +1,331 @@ +import Darwin +import Foundation + +/// Serializes artifact mutations across the app and standalone CLI processes. +final class ArtifactStoreMutationLease { + private var descriptor: Int32 + + private init(descriptor: Int32) { + self.descriptor = descriptor + } + + /// Uses the already-managed artifact directory because actor isolation cannot + /// coordinate independent processes and acquisition must not create a new path. + convenience init(directory: URL, expectedCanonicalPath: String? = nil) throws { + let descriptor = Darwin.open( + directory.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(directory.path) + } + var keepsDescriptor = false + defer { + if !keepsDescriptor { + _ = close(descriptor) + } + } + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFDIR else { + throw ArtifactStoreError.pathOutsideStore(directory.path) + } + guard Self.openedPath(for: descriptor) + == (expectedCanonicalPath ?? Self.canonicalPath(directory)) else { + throw ArtifactStoreError.pathOutsideStore(directory.path) + } + guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { + let lockError = errno + if lockError == EWOULDBLOCK || lockError == EAGAIN { + throw ArtifactStoreError.storeBusy(directory.path) + } + throw ArtifactStoreError.pathOutsideStore(directory.path) + } + keepsDescriptor = true + self.init(descriptor: descriptor) + } + + func finish() { + guard descriptor >= 0 else { return } + _ = flock(descriptor, LOCK_UN) + _ = close(descriptor) + descriptor = -1 + } + + /// Removes one store-relative entry without following replacement links in + /// any parent directory. + /// + /// Parent components are opened relative to the leased store descriptor + /// with ``O_NOFOLLOW``. The final `unlinkat` removes a replaced symlink + /// itself rather than following it, so a concurrent filesystem mutation + /// cannot redirect deletion outside the store. + func unlink( + relativePath: String, + expectedIdentity: ArtifactFileIdentity? = nil + ) throws { + let components = relativePath.split(separator: "/").map(String.init) + guard !relativePath.contains("\0"), + !components.isEmpty, + components.allSatisfy({ $0 != "." && $0 != ".." }) else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + + var openedDescriptors: [Int32] = [] + defer { + for openedDescriptor in openedDescriptors.reversed() { + _ = close(openedDescriptor) + } + } + + var parentDescriptor = descriptor + for component in components.dropLast() { + let childDescriptor = component.withCString { componentPointer in + Darwin.openat( + parentDescriptor, + componentPointer, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW + ) + } + guard childDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + openedDescriptors.append(childDescriptor) + parentDescriptor = childDescriptor + } + + if let expectedIdentity { + guard let leaf = components.last else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + let targetDescriptor = leaf.withCString { leafPointer in + Darwin.openat( + parentDescriptor, + leafPointer, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + } + guard targetDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + defer { _ = close(targetDescriptor) } + var status = stat() + guard fstat(targetDescriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + ArtifactFileIdentity( + device: UInt64(status.st_dev), + inode: UInt64(status.st_ino) + ) == expectedIdentity else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + } + guard let leaf = components.last, + leaf.withCString({ leafPointer in + Darwin.unlinkat(parentDescriptor, leafPointer, 0) + }) == 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + } + + /// Atomically writes one store-relative file through descriptor-pinned + /// parents. The caller may hold the same lease for a larger mutation. + @discardableResult + func writeData( + _ data: Data, + toRelativePath relativePath: String, + replacingExisting: Bool = true + ) throws -> Bool { + let components = relativePath.split(separator: "/").map(String.init) + guard !relativePath.contains("\0"), + !components.isEmpty, + components.allSatisfy({ $0 != "." && $0 != ".." }) else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + + var openedDescriptors: [Int32] = [] + defer { + for openedDescriptor in openedDescriptors.reversed() { + _ = close(openedDescriptor) + } + } + var parentDescriptor = descriptor + for component in components.dropLast() { + let childDescriptor = component.withCString { componentPointer in + Darwin.openat( + parentDescriptor, + componentPointer, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW + ) + } + guard childDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + openedDescriptors.append(childDescriptor) + parentDescriptor = childDescriptor + } + + guard let destinationName = components.last else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + let temporaryName = ".cmux-provenance-\(UUID().uuidString).tmp" + let temporaryDescriptor = temporaryName.withCString { name in + Darwin.openat( + parentDescriptor, + name, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + guard temporaryDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + var keepsTemporary = true + defer { + _ = close(temporaryDescriptor) + if keepsTemporary { + _ = temporaryName.withCString { name in + Darwin.unlinkat(parentDescriptor, name, 0) + } + } + } + try data.withUnsafeBytes { bytes in + guard let baseAddress = bytes.baseAddress else { return } + var offset = 0 + while offset < bytes.count { + let written = Darwin.write( + temporaryDescriptor, + baseAddress.advanced(by: offset), + bytes.count - offset + ) + if written < 0, errno == EINTR { continue } + guard written > 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + offset += written + } + } + guard Darwin.fsync(temporaryDescriptor) == 0 else { + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + let renameResult = temporaryName.withCString { sourceName in + destinationName.withCString { targetName in + if replacingExisting { + return Darwin.renameat( + parentDescriptor, + sourceName, + parentDescriptor, + targetName + ) + } + return renameatx_np( + parentDescriptor, + sourceName, + parentDescriptor, + targetName, + UInt32(RENAME_EXCL) + ) + } + } + if renameResult != 0 { + if !replacingExisting, errno == EEXIST { + return false + } + throw ArtifactStoreError.pathOutsideStore(relativePath) + } + _ = Darwin.fsync(parentDescriptor) + keepsTemporary = false + return true + } + + /// Moves a staged file into the leased store without resolving destination + /// parents again after validation. + func moveFile( + from source: URL, + toRelativePath: String, + expectedSourceParentPath: String + ) throws { + let components = toRelativePath.split(separator: "/").map(String.init) + guard !toRelativePath.contains("\0"), + !components.isEmpty, + components.allSatisfy({ $0 != "." && $0 != ".." }) else { + throw ArtifactStoreError.pathOutsideStore(toRelativePath) + } + + let sourceParent = source.deletingLastPathComponent() + let sourceDescriptor = Darwin.open( + sourceParent.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard sourceDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(source.path) + } + defer { _ = close(sourceDescriptor) } + var sourceStatus = stat() + guard fstat(sourceDescriptor, &sourceStatus) == 0, + (sourceStatus.st_mode & S_IFMT) == S_IFDIR, + Self.openedPath(for: sourceDescriptor) == expectedSourceParentPath else { + throw ArtifactStoreError.pathOutsideStore(source.path) + } + + var openedDescriptors: [Int32] = [] + defer { + for openedDescriptor in openedDescriptors.reversed() { + _ = close(openedDescriptor) + } + } + var destinationParent = descriptor + for component in components.dropLast() { + let childDescriptor = component.withCString { componentPointer in + Darwin.openat( + destinationParent, + componentPointer, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW + ) + } + guard childDescriptor >= 0 else { + throw ArtifactStoreError.pathOutsideStore(toRelativePath) + } + openedDescriptors.append(childDescriptor) + destinationParent = childDescriptor + } + + guard let sourceName = source.pathComponents.last, + let destinationName = components.last else { + throw ArtifactStoreError.pathOutsideStore(toRelativePath) + } + let result = sourceName.withCString { sourcePointer in + destinationName.withCString { destinationPointer in + renameatx_np( + sourceDescriptor, + sourcePointer, + destinationParent, + destinationPointer, + UInt32(RENAME_EXCL) + ) + } + } + guard result == 0 else { + throw ArtifactStoreError.pathOutsideStore(toRelativePath) + } + } + + private static func canonicalPath(_ url: URL) -> String { + url.resolvingSymlinksInPath().standardizedFileURL.path + } + + private static func openedPath(for descriptor: Int32) -> String? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + return Self.canonicalPath(URL(fileURLWithPath: String( + decoding: buffer.prefix { $0 != 0 }, + as: UTF8.self + ))) + } + + deinit { + finish() + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStorePaths.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStorePaths.swift new file mode 100644 index 000000000000..1ef22a13fe57 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStorePaths.swift @@ -0,0 +1,57 @@ +public import Foundation + +/// Deterministic paths inside one project's session-oriented `.cmux` filesystem. +public struct ArtifactStorePaths: Equatable, Sendable { + static let trackableControlFileNames = ["artifacts.json", "cmux.json", "dock.json"] + static let managedPathComponentNames = Set( + trackableControlFileNames + [ + ArtifactPathResolver.sessionMarkerName, + ArtifactPathResolver.workspaceMarkerName, + ".metadata", + ] + ) + + func isManagedPathComponent(_ name: String) -> Bool { + Self.managedPathComponentNames.contains { + $0.caseInsensitiveCompare(name) == .orderedSame + } + } + + /// Normalized project root. + public let projectRoot: URL + + /// Creates store paths for a project root. + /// + /// - Parameter projectRoot: Directory that owns `.cmux`. + public init(projectRoot: URL) { + self.projectRoot = projectRoot.standardizedFileURL + } + + /// Ordinary cmux filesystem root. + /// + /// Agent sessions are immediate or user-organized descendants whose + /// `artifacts` and `notes` directories remain ordinary movable folders. + public var filesystemRoot: URL { + projectRoot.appendingPathComponent(".cmux", isDirectory: true) + } + + /// Optional project capture configuration. + public var configurationFile: URL { + filesystemRoot.appendingPathComponent("artifacts.json", isDirectory: false) + } + + /// Hidden cmux-managed metadata root excluded from the sidebar tree. + public var metadataRoot: URL { + filesystemRoot.appendingPathComponent(".metadata", isDirectory: true) + } + + /// Private import staging directory excluded from the sidebar tree. + var importStagingRoot: URL { + metadataRoot.appendingPathComponent("imports", isDirectory: true) + } + + /// Content-addressed provenance directory. + public var provenanceRoot: URL { + metadataRoot.appendingPathComponent("provenance", isDirectory: true) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreVisibilityPolicy.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreVisibilityPolicy.swift new file mode 100644 index 000000000000..3e9bd1d0974e --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoreVisibilityPolicy.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Defines which live `.cmux` entries are user-visible Notes and Artifacts. +struct ArtifactStoreVisibilityPolicy { + let fileManager: FileManager + + func isManagedEntry(_ url: URL, filesystemRoot: URL) -> Bool { + if url.lastPathComponent == ArtifactPathResolver.workspaceMarkerName + || url.lastPathComponent == ArtifactPathResolver.sessionMarkerName { + return true + } + let resolver = ArtifactPathResolver(fileManager: fileManager) + if resolver.refersToSameLocation( + url, + filesystemRoot.appendingPathComponent(".metadata", isDirectory: true) + ) { + return true + } + guard url.deletingLastPathComponent().standardizedFileURL + == filesystemRoot.standardizedFileURL else { + return false + } + return url.lastPathComponent.hasPrefix(".") + || ArtifactStorePaths.trackableControlFileNames.contains(url.lastPathComponent) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoring.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoring.swift new file mode 100644 index 000000000000..097cc9fe2a1a --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactStoring.swift @@ -0,0 +1,71 @@ +public import Foundation + +/// Filesystem persistence seam shared by the app, capture service, and CLI. +public protocol ArtifactStoring: Sendable { + /// Resolves the project root that should own artifacts for a working path. + func locateProjectRoot(startingAt: URL) async -> URL + /// Loads project capture configuration. + func configuration(projectRoot: URL) async -> ArtifactCaptureConfiguration + /// Scans the live artifact filesystem into immutable values. + func snapshot(projectRoot: URL) async throws -> ArtifactSnapshot + /// Searches filenames and bounded text contents. + func search(projectRoot: URL, query: String) async throws -> [ArtifactSearchResult] + /// Imports or deduplicates one accepted regular file. + func importFile( + sourceURL: URL, + context: ArtifactCaptureContext, + provenance: ArtifactProvenance, + configuration: ArtifactCaptureConfiguration, + capturedAt: Date + ) async throws -> ArtifactImportOutcome + /// Imports one homogeneous candidate batch with shared filesystem work. + /// + /// - Parameters: + /// - candidates: Ordered source files and their provenance. + /// - context: Project and session destination identity. + /// - configuration: Per-file persistence and safety limits. + /// - maximumBatchBytes: Optional aggregate staging limit; `nil` permits every per-file-valid source. + /// - capturedAt: Timestamp recorded in provenance. + /// - Returns: One import attempt per candidate, preserving input order. + func importFiles( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + configuration: ArtifactCaptureConfiguration, + maximumBatchBytes: Int64?, + capturedAt: Date + ) async -> [ArtifactImportAttempt] + /// Resolves an exact relative path, unique basename, or unique fuzzy filename. + func resolve(projectRoot: URL, name: String) async throws -> ArtifactNode + /// Installs observation immediately and emits subsequent recursive `.cmux` filesystem changes. + func changes(projectRoot: URL) async -> AsyncStream +} + +extension ArtifactStoring { + /// Default batch behavior for injected stores that only implement single-file import. + public func importFiles( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + configuration: ArtifactCaptureConfiguration, + maximumBatchBytes: Int64?, + capturedAt: Date + ) async -> [ArtifactImportAttempt] { + var attempts: [ArtifactImportAttempt] = [] + attempts.reserveCapacity(candidates.count) + for candidate in candidates { + do { + attempts.append(.imported(try await importFile( + sourceURL: candidate.sourceURL, + context: context, + provenance: candidate.provenance, + configuration: configuration, + capturedAt: capturedAt + ))) + } catch let error as ArtifactStoreError { + attempts.append(.rejected(error)) + } catch { + attempts.append(.rejected(.sourceNotRegularFile(candidate.sourceURL.path))) + } + } + return attempts + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTerminalTextSanitizer.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTerminalTextSanitizer.swift new file mode 100644 index 000000000000..25922a995429 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTerminalTextSanitizer.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Neutralizes terminal control characters in artifact-controlled human-readable text. +public struct ArtifactTerminalTextSanitizer: Sendable { + /// Creates a stateless terminal-text sanitizer. + public init() {} + + /// Replaces C0, DEL, and C1 controls with a visible replacement character. + /// + /// JSON and other machine-readable encodings should retain their raw values + /// and must not pass through this presentation-only boundary. + /// + /// - Parameter text: Artifact-controlled text intended for a terminal. + /// - Returns: Text that cannot contain terminal control sequences. + public func sanitize(_ text: String) -> String { + guard text.unicodeScalars.contains(where: isTerminalControl) else { return text } + var sanitized = "" + sanitized.reserveCapacity(text.utf8.count) + for scalar in text.unicodeScalars { + sanitized.unicodeScalars.append( + isTerminalControl(scalar) ? "\u{FFFD}" : scalar + ) + } + return sanitized + } + + /// Preserves ordinary text layout while neutralizing terminal control sequences. + /// + /// Horizontal tabs and line feeds remain intact. Windows and legacy carriage + /// returns are normalized to line feeds so Markdown and other multiline text + /// retains its structure without permitting cursor-return control behavior. + /// + /// - Parameter text: File content intended for direct terminal output. + /// - Returns: Multiline text with unsafe terminal controls made visible. + public func sanitizeTextContent(_ text: String) -> String { + var sanitized = "" + sanitized.reserveCapacity(text.utf8.count) + var previousWasCarriageReturn = false + for scalar in text.unicodeScalars { + if previousWasCarriageReturn { + if scalar.value == 0x0A { + previousWasCarriageReturn = false + continue + } + previousWasCarriageReturn = false + } + switch scalar.value { + case 0x09, 0x0A: + sanitized.unicodeScalars.append(scalar) + case 0x0D: + sanitized.append("\n") + previousWasCarriageReturn = true + default: + sanitized.unicodeScalars.append( + isTerminalControl(scalar) ? "\u{FFFD}" : scalar + ) + } + } + return sanitized + } + + private func isTerminalControl(_ scalar: Unicode.Scalar) -> Bool { + scalar.value <= 0x1F || (0x7F...0x9F).contains(scalar.value) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTreeScanner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTreeScanner.swift new file mode 100644 index 000000000000..2ff1f58fe387 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactTreeScanner.swift @@ -0,0 +1,111 @@ +import Foundation + +/// Bounded recursive scanner that treats the live filesystem as authoritative. +struct ArtifactTreeScanner { + let fileManager: FileManager + let maximumDepth: Int + let nodeBudget: Int + private var visibilityPolicy: ArtifactStoreVisibilityPolicy { + ArtifactStoreVisibilityPolicy(fileManager: fileManager) + } + + func snapshot(paths: ArtifactStorePaths) throws -> ArtifactSnapshot { + try Task.checkCancellation() + var remaining = nodeBudget + var truncated = false + let nodes = try scanDirectory( + paths.filesystemRoot, + root: paths.filesystemRoot, + depth: 0, + remaining: &remaining, + truncated: &truncated + ) + return ArtifactSnapshot( + projectRoot: paths.projectRoot, + filesystemRoot: paths.filesystemRoot, + nodes: nodes, + isTruncated: truncated + ) + } + + private func scanDirectory( + _ directory: URL, + root: URL, + depth: Int, + remaining: inout Int, + truncated: inout Bool + ) throws -> [ArtifactNode] { + try Task.checkCancellation() + guard depth <= maximumDepth, remaining > 0, + fileManager.fileExists(atPath: directory.path) else { + if remaining <= 0 { truncated = true } + return [] + } + let keys: Set = [ + .isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, + .fileSizeKey, .contentModificationDateKey, + ] + guard let children = fileManager.enumerator( + at: directory, + includingPropertiesForKeys: Array(keys), + options: [.skipsSubdirectoryDescendants] + ) else { return [] } + var nodes: [ArtifactNode] = [] + while let url = children.nextObject() as? URL { + try Task.checkCancellation() + guard remaining > 0 else { + truncated = true + break + } + guard !visibilityPolicy.isManagedEntry(url, filesystemRoot: root) else { + continue + } + remaining -= 1 + let values = try url.resourceValues(forKeys: keys) + guard values.isSymbolicLink != true else { continue } + let isDirectory = values.isDirectory == true + guard isDirectory || values.isRegularFile == true else { continue } + guard let relativePath = relativePath(url, root: root) else { continue } + let nested: [ArtifactNode] + if isDirectory, depth < maximumDepth { + nested = try scanDirectory( + url, + root: root, + depth: depth + 1, + remaining: &remaining, + truncated: &truncated + ) + } else { + nested = [] + if isDirectory, depth >= maximumDepth { truncated = true } + } + let fileKind = isDirectory ? nil : ArtifactFileKind(fileURL: url) + let fileIdentity: ArtifactFileIdentity? = switch fileKind { + case .image?, .video?: try? ArtifactFileIdentity.read(at: url) + default: nil + } + nodes.append(ArtifactNode( + id: relativePath, + name: url.lastPathComponent, + relativePath: relativePath, + absolutePath: url.path, + isDirectory: isDirectory, + fileKind: fileKind, + size: isDirectory ? nil : values.fileSize.map(Int64.init), + modifiedAt: values.contentModificationDate, + fileIdentity: fileIdentity, + children: nested + )) + } + return nodes.sorted(by: nodeOrdering) + } + + private func relativePath(_ url: URL, root: URL) -> String? { + ArtifactPathResolver(fileManager: fileManager).relativePath(url, root: root) + } + + private func nodeOrdering(_ lhs: ArtifactNode, _ rhs: ArtifactNode) -> Bool { + if lhs.isDirectory != rhs.isDirectory { return lhs.isDirectory } + return lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWorkspaceMarker.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWorkspaceMarker.swift new file mode 100644 index 000000000000..6bcc4d6413ee --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWorkspaceMarker.swift @@ -0,0 +1,8 @@ +import Foundation + +/// Small cmux-managed identity marker stored in a capture workspace folder. +struct ArtifactWorkspaceMarker: Codable, Equatable, Sendable { + let workspaceID: String? + let workspaceTitle: String? + let createdAt: Date +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlan.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlan.swift new file mode 100644 index 000000000000..4812b1ed28d9 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlan.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Exact destinations authorized before an import batch persists files. +struct ArtifactWritePlan { + let destinations: [URL] + let copyDestinationBySnapshotPath: [String: URL] + let captureResolution: ArtifactCaptureDirectoryResolution? + + func copyDestination(for prepared: PreparedArtifactImport) -> URL? { + copyDestinationBySnapshotPath[prepared.snapshot.url.standardizedFileURL.path] + } + + /// Returns whether every destination in a refined plan was already Git-authorized. + func authorizes(_ refined: ArtifactWritePlan) -> Bool { + let authorizedPaths = Set(destinations.map { $0.standardizedFileURL.path }) + return refined.destinations.allSatisfy { + authorizedPaths.contains($0.standardizedFileURL.path) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlanner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlanner.swift new file mode 100644 index 000000000000..21ac447ea641 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ArtifactWritePlanner.swift @@ -0,0 +1,140 @@ +import Foundation + +/// Plans every path an import batch might write before persistence begins. +struct ArtifactWritePlanner { + let fileManager: FileManager + let encoder: JSONEncoder + let decoder: JSONDecoder + let nodeBudget: Int + + func plan( + prepared: [PreparedArtifactImport], + existingByDigest: [String: URL], + context: ArtifactCaptureContext, + paths: ArtifactStorePaths + ) throws -> ArtifactWritePlan { + try plan( + prepared: prepared, + existingByDigest: existingByDigest, + context: context, + paths: paths, + allowsIncompleteDiscoveryFallback: false + ) + } + + /// Plans potential writes without deduplication for pre-lease Git authorization. + /// + /// If bounded marker discovery is incomplete, this plan authorizes only the + /// deterministic fallback. The authoritative plan must still be its subset. + func conservativePlan( + prepared: [PreparedArtifactImport], + context: ArtifactCaptureContext, + paths: ArtifactStorePaths + ) throws -> ArtifactWritePlan { + try plan( + prepared: prepared, + existingByDigest: [:], + context: context, + paths: paths, + allowsIncompleteDiscoveryFallback: true + ) + } + + private func plan( + prepared: [PreparedArtifactImport], + existingByDigest: [String: URL], + context: ArtifactCaptureContext, + paths: ArtifactStorePaths, + allowsIncompleteDiscoveryFallback: Bool + ) throws -> ArtifactWritePlan { + let resolver = ArtifactPathResolver(fileManager: fileManager) + let recorder = ArtifactProvenanceRecorder( + fileManager: fileManager, + encoder: encoder, + decoder: decoder + ) + var destinations: [URL] = [] + var copyDestinationBySnapshotPath: [String: URL] = [:] + var reservedDestinationPaths: Set = [] + var captureResolution: ArtifactCaptureDirectoryResolution? + + for item in prepared { + destinations.append(recorder.metadataURL(paths: paths, digest: item.digest)) + let source = item.candidate.sourceURL + guard !resolver.isInsideStore(source, paths: paths), + existingByDigest[item.digest] == nil else { + continue + } + if captureResolution == nil { + captureResolution = try resolveCaptureDirectory( + paths: paths, + context: context, + pathResolver: resolver, + allowsIncompleteDiscoveryFallback: allowsIncompleteDiscoveryFallback + ) + } + guard let captureResolution else { continue } + let destination = resolver.uniqueDestination( + source: source, + directory: captureResolution.directory, + fileManager: fileManager, + reservedPaths: reservedDestinationPaths + ) + reservedDestinationPaths.insert(destination.standardizedFileURL.path) + copyDestinationBySnapshotPath[item.snapshot.url.standardizedFileURL.path] = destination + destinations.append(destination) + } + if let captureResolution { + destinations.append(contentsOf: missingMarkerURLs(resolution: captureResolution)) + } + var seen: Set = [] + return ArtifactWritePlan( + destinations: destinations.filter { + seen.insert($0.standardizedFileURL.path).inserted + }, + copyDestinationBySnapshotPath: copyDestinationBySnapshotPath, + captureResolution: captureResolution + ) + } + + private func resolveCaptureDirectory( + paths: ArtifactStorePaths, + context: ArtifactCaptureContext, + pathResolver: ArtifactPathResolver, + allowsIncompleteDiscoveryFallback: Bool + ) throws -> ArtifactCaptureDirectoryResolution { + do { + return try ArtifactCaptureDirectoryFinder( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ).resolve(paths: paths, context: context, pathResolver: pathResolver) + } catch ArtifactStoreError.scanIncomplete where allowsIncompleteDiscoveryFallback { + return ArtifactCaptureDirectoryResolution( + directory: pathResolver.contentDirectory( + paths: paths, + context: context, + kind: .artifacts + ) + ) + } + } + + private func missingMarkerURLs( + resolution: ArtifactCaptureDirectoryResolution + ) -> [URL] { + var urls: [URL] = [] + let sessionRoot = resolution.directory.deletingLastPathComponent() + let workspaceMarker = sessionRoot + .appendingPathComponent(ArtifactPathResolver.workspaceMarkerName) + if !fileManager.fileExists(atPath: workspaceMarker.path) { + urls.append(workspaceMarker) + } + let sessionMarker = sessionRoot + .appendingPathComponent(ArtifactPathResolver.sessionMarkerName) + if !fileManager.fileExists(atPath: sessionMarker.path) { + urls.append(sessionMarker) + } + return urls + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteAtomicWriter.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteAtomicWriter.swift new file mode 100644 index 000000000000..8227216f2942 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteAtomicWriter.swift @@ -0,0 +1,119 @@ +import Darwin +import Foundation + +/// Atomically replaces a regular note without following the destination entry. +struct CmuxNoteAtomicWriter { + let fileManager: FileManager + + init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + func write( + _ data: Data, + to destination: URL, + expectedParentPath: String? = nil + ) throws { + let parent = destination.deletingLastPathComponent() + let parentDescriptor = try openParentDirectory( + parent, + expectedCanonicalPath: expectedParentPath + ) + defer { _ = Darwin.close(parentDescriptor) } + let temporaryName = ".cmux-note-\(UUID().uuidString).tmp" + let destinationName = destination.lastPathComponent + let descriptor = temporaryName.withCString { name in + Darwin.openat( + parentDescriptor, + name, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + } + guard descriptor >= 0 else { + throw CmuxNoteStoreError.pathOutsideStore(destination.path) + } + var keepsTemporary = true + defer { + _ = Darwin.close(descriptor) + if keepsTemporary { + _ = temporaryName.withCString { name in + Darwin.unlinkat(parentDescriptor, name, 0) + } + } + } + try data.withUnsafeBytes { bytes in + guard let baseAddress = bytes.baseAddress else { return } + var offset = 0 + while offset < bytes.count { + let written = Darwin.write( + descriptor, + baseAddress.advanced(by: offset), + bytes.count - offset + ) + if written < 0, errno == EINTR { continue } + guard written > 0 else { + throw CmuxNoteStoreError.pathOutsideStore(destination.path) + } + offset += written + } + } + guard Darwin.fsync(descriptor) == 0, + temporaryName.withCString({ sourceName in + destinationName.withCString { targetName in + Darwin.renameat( + parentDescriptor, + sourceName, + parentDescriptor, + targetName + ) + } + }) == 0 else { + throw CmuxNoteStoreError.pathOutsideStore(destination.path) + } + _ = Darwin.fsync(parentDescriptor) + keepsTemporary = false + } + + private func openParentDirectory( + _ parent: URL, + expectedCanonicalPath: String? + ) throws -> Int32 { + let descriptor = Darwin.open( + parent.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw CmuxNoteStoreError.pathOutsideStore(parent.path) + } + var status = stat() + guard Darwin.fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFDIR else { + _ = Darwin.close(descriptor) + throw CmuxNoteStoreError.pathOutsideStore(parent.path) + } + if let expectedCanonicalPath { + let resolver = ArtifactPathResolver(fileManager: fileManager) + let openedCanonicalPath = openedPath(for: descriptor).map { + resolver.canonicalPath(URL(fileURLWithPath: $0)) + } + guard openedCanonicalPath == expectedCanonicalPath else { + _ = Darwin.close(descriptor) + throw CmuxNoteStoreError.pathOutsideStore(parent.path) + } + } + return descriptor + } + + private func openedPath(for descriptor: Int32) -> String? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + let path = String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self) + return ArtifactPathResolver(fileManager: fileManager) + .canonicalPath(URL(fileURLWithPath: path)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteSearchResult.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteSearchResult.swift new file mode 100644 index 000000000000..5b2dfcf28792 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteSearchResult.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Filename or bounded-content match returned by Notes search. +public struct CmuxNoteSearchResult: Identifiable, Equatable, Sendable { + /// Result identity equal to the note's current relative path. + public let id: String + /// Matched live note value. + public let note: CmuxProjectNote + /// Whether the note's UTF-8 content matched the query. + public let matchedContent: Bool + /// Bounded single-line content excerpt, when available. + public let snippet: String? + + /// Creates a Notes search result. + /// + /// - Parameters: + /// - note: Matched live note value. + /// - matchedContent: Whether note contents matched. + /// - snippet: Bounded single-line content excerpt. + public init(note: CmuxProjectNote, matchedContent: Bool, snippet: String?) { + self.id = note.id + self.note = note + self.matchedContent = matchedContent + self.snippet = snippet + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteStoreError.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteStoreError.swift new file mode 100644 index 000000000000..2bd71e0ba884 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteStoreError.swift @@ -0,0 +1,15 @@ +/// Errors surfaced by live Notes filesystem operations. +public enum CmuxNoteStoreError: Error, Equatable, Sendable { + /// A note name was empty, unsafe, or not a Markdown path. + case invalidName(String) + /// No live note matched the requested name or path. + case noteNotFound(String) + /// More than one live note matched the requested name. + case ambiguousNoteName(String, matches: [String]) + /// A note was not valid UTF-8 text. + case invalidUTF8(String) + /// A write or existing note exceeded the bounded Notes size limit. + case noteTooLarge(actual: Int64, limit: Int64) + /// The resolved note path escaped or crossed an untrusted filesystem entry. + case pathOutsideStore(String) +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWriteMode.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWriteMode.swift new file mode 100644 index 000000000000..fc2dbc56e25d --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWriteMode.swift @@ -0,0 +1,7 @@ +/// Mutation applied when writing a cmux Note. +public enum CmuxNoteWriteMode: Equatable, Sendable { + /// Replace the note's complete UTF-8 contents. + case replace + /// Append UTF-8 text to the note, creating it when absent. + case append +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWritePlan.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWritePlan.swift new file mode 100644 index 000000000000..088628c4b2dd --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxNoteWritePlan.swift @@ -0,0 +1,18 @@ +import Foundation + +/// Immutable Note mutation plan validated before entering the filesystem write phase. +struct CmuxNoteWritePlan: Sendable { + let contentDirectory: URL + let destination: URL + let existing: CmuxProjectNote? + + var privacyDestinations: [URL] { + guard existing == nil else { return [destination] } + let sessionDirectory = contentDirectory.deletingLastPathComponent() + return [ + destination, + sessionDirectory.appendingPathComponent(ArtifactPathResolver.sessionMarkerName), + sessionDirectory.appendingPathComponent(ArtifactPathResolver.workspaceMarkerName), + ] + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNote.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNote.swift new file mode 100644 index 000000000000..c9011c197af3 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNote.swift @@ -0,0 +1,48 @@ +public import Foundation + +/// One ordinary Markdown note discovered in a session's `notes` directory. +public struct CmuxProjectNote: Identifiable, Equatable, Sendable { + /// Stable-for-the-current-scan identity equal to ``relativePath``. + public let id: String + /// Note filename including its extension. + public let name: String + /// Current path relative to the project's `.cmux` filesystem. + public let relativePath: String + /// Current absolute local path. + public let absolutePath: String + /// Prompt-ready project-relative reference. + public let reference: String + /// Current byte size, when available. + public let size: Int64? + /// Current filesystem modification date, when available. + public let modifiedAt: Date? + /// Device/inode identity captured with the note snapshot, when available. + public let fileIdentity: ArtifactFileIdentity? + + /// Creates a live filesystem note value. + /// + /// - Parameters: + /// - name: Note filename including its extension. + /// - relativePath: Current `.cmux`-relative path. + /// - absolutePath: Current absolute local path. + /// - size: Current byte size, when available. + /// - modifiedAt: Current filesystem modification date, when available. + /// - fileIdentity: Device/inode identity captured with the snapshot. + public init( + name: String, + relativePath: String, + absolutePath: String, + size: Int64?, + modifiedAt: Date?, + fileIdentity: ArtifactFileIdentity? = nil + ) { + self.id = relativePath + self.name = name + self.relativePath = relativePath + self.absolutePath = absolutePath + self.reference = ".cmux/\(relativePath)" + self.size = size + self.modifiedAt = modifiedAt + self.fileIdentity = fileIdentity + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNoteResolver.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNoteResolver.swift new file mode 100644 index 000000000000..0ed7dba3ad40 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxProjectNoteResolver.swift @@ -0,0 +1,177 @@ +import Foundation + +/// Marker-backed live-tree projection and name resolution for cmux Notes. +struct CmuxProjectNoteResolver { + private static let allowedExtensions: Set = ["md", "markdown"] + let fileManager: FileManager + let decoder: JSONDecoder + let nodeBudget: Int + + func notes(snapshot: ArtifactSnapshot) throws -> [CmuxProjectNote] { + try noteNodes(snapshot: snapshot) + .map(note) + .sorted { + $0.relativePath.localizedStandardCompare($1.relativePath) == .orderedAscending + } + } + + func noteNodes(snapshot: ArtifactSnapshot) throws -> [ArtifactNode] { + let paths = ArtifactStorePaths(projectRoot: snapshot.projectRoot) + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + let noteRootPaths = Set( + try ArtifactMarkerDirectoryCatalog( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ).sessionDirectories( + paths: paths, + pathResolver: pathResolver + ).compactMap { entry in + pathResolver.relativePath(entry.directory, root: paths.filesystemRoot) + .map { $0 + "/\(CmuxSessionContentKind.notes.rawValue)" } + } + ) + return snapshot.nodes.flattenedArtifactNodes().filter { node in + isNoteNode(node, noteRootPaths: noteRootPaths) + } + } + + func resolve(snapshot: ArtifactSnapshot, rawName: String) throws -> CmuxProjectNote { + try resolve(notes: notes(snapshot: snapshot), rawName: rawName) + } + + func resolve(notes: [CmuxProjectNote], rawName: String) throws -> CmuxProjectNote { + let name = normalizedReference(rawName) + guard !name.isEmpty else { throw CmuxNoteStoreError.invalidName(rawName) } + if let exact = notes.first(where: { $0.relativePath == name }) { return exact } + + let requestedBasename = URL(fileURLWithPath: name).lastPathComponent + let requestedStem = URL(fileURLWithPath: requestedBasename).deletingPathExtension().lastPathComponent + let basenameMatches = notes.filter { candidate in + candidate.name.caseInsensitiveCompare(requestedBasename) == .orderedSame + || URL(fileURLWithPath: candidate.name) + .deletingPathExtension().lastPathComponent + .caseInsensitiveCompare(requestedStem) == .orderedSame + } + if basenameMatches.count == 1, let match = basenameMatches.first { return match } + if basenameMatches.count > 1 { + throw CmuxNoteStoreError.ambiguousNoteName( + rawName, + matches: basenameMatches.map(\.relativePath) + ) + } + + let matcher = ArtifactFuzzyMatcher(query: name) + let matches = notes.compactMap { candidate in + matcher.score(candidate: candidate.relativePath).map { (candidate, $0) } + }.sorted { $0.1 > $1.1 } + guard let best = matches.first else { throw CmuxNoteStoreError.noteNotFound(rawName) } + if matches.count > 1, matches[1].1 == best.1 { + throw CmuxNoteStoreError.ambiguousNoteName( + rawName, + matches: matches.filter { $0.1 == best.1 }.map { $0.0.relativePath } + ) + } + return best.0 + } + + func resolveExact(notes: [CmuxProjectNote], rawName: String) throws -> CmuxProjectNote { + let name = normalizedReference(rawName) + guard !name.isEmpty else { throw CmuxNoteStoreError.invalidName(rawName) } + if let exact = notes.first(where: { $0.relativePath == name }) { return exact } + guard !name.contains("/") else { throw CmuxNoteStoreError.noteNotFound(rawName) } + + let requestedBasename = URL(fileURLWithPath: name).lastPathComponent + let requestedStem = URL(fileURLWithPath: requestedBasename) + .deletingPathExtension().lastPathComponent + let matches = notes.filter { candidate in + candidate.name.caseInsensitiveCompare(requestedBasename) == .orderedSame + || URL(fileURLWithPath: candidate.name) + .deletingPathExtension().lastPathComponent + .caseInsensitiveCompare(requestedStem) == .orderedSame + } + guard matches.count <= 1 else { + throw CmuxNoteStoreError.ambiguousNoteName( + rawName, + matches: matches.map(\.relativePath) + ) + } + guard let match = matches.first else { + throw CmuxNoteStoreError.noteNotFound(rawName) + } + return match + } + + func creationRelativePath(rawName: String, paths: ArtifactStorePaths) throws -> String { + let trimmed = rawName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, + trimmed.utf8.count <= 1_024, + !trimmed.hasPrefix("/"), + !trimmed.hasPrefix(".cmux/"), + !trimmed.contains("\0"), + !trimmed.contains("\n") else { + throw CmuxNoteStoreError.invalidName(rawName) + } + var components = trimmed.split( + separator: "/", + omittingEmptySubsequences: false + ).map(String.init) + guard components.allSatisfy({ + !$0.isEmpty + && $0 != "." + && $0 != ".." + && !paths.isManagedPathComponent($0) + }) else { + throw CmuxNoteStoreError.invalidName(rawName) + } + let filename = components.removeLast() + let url = URL(fileURLWithPath: filename) + let pathExtension = url.pathExtension.lowercased() + let finalName: String + if pathExtension.isEmpty { + finalName = filename + ".md" + } else if Self.allowedExtensions.contains(pathExtension) { + finalName = filename + } else { + throw CmuxNoteStoreError.invalidName(rawName) + } + guard !finalName.hasPrefix(".") else { throw CmuxNoteStoreError.invalidName(rawName) } + components.append(finalName) + return components.joined(separator: "/") + } + + func note(_ node: ArtifactNode) -> CmuxProjectNote { + CmuxProjectNote( + name: node.name, + relativePath: node.relativePath, + absolutePath: node.absolutePath, + size: node.size, + modifiedAt: node.modifiedAt, + fileIdentity: try? ArtifactFileIdentity.read( + at: URL(fileURLWithPath: node.absolutePath, isDirectory: false) + ) + ) + } + + private func isNoteNode( + _ node: ArtifactNode, + noteRootPaths: Set + ) -> Bool { + guard !node.isDirectory, + Self.allowedExtensions.contains( + URL(fileURLWithPath: node.name).pathExtension.lowercased() + ) else { return false } + let components = node.relativePath.split(separator: "/") + return components.indices.contains { index in + components[index] == Substring(CmuxSessionContentKind.notes.rawValue) + && noteRootPaths.contains( + components[...index].joined(separator: "/") + ) + } + } + + private func normalizedReference(_ rawName: String) -> String { + let trimmed = rawName.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.hasPrefix(".cmux/") ? String(trimmed.dropFirst(".cmux/".count)) : trimmed + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxSessionContentKind.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxSessionContentKind.swift new file mode 100644 index 000000000000..08ed995020c6 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/CmuxSessionContentKind.swift @@ -0,0 +1,7 @@ +import Foundation + +/// Ordinary content directories available beneath one agent-session folder. +enum CmuxSessionContentKind: String, CaseIterable, Sendable { + case artifacts + case notes +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+BatchImport.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+BatchImport.swift new file mode 100644 index 000000000000..65106448db6b --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+BatchImport.swift @@ -0,0 +1,315 @@ +public import Foundation + +extension LocalArtifactRepository { + /// Imports a capture batch with bounded Git preflight and one authoritative mutation phase. + public func importFiles( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + configuration: ArtifactCaptureConfiguration, + maximumBatchBytes: Int64?, + capturedAt: Date + ) async -> [ArtifactImportAttempt] { + guard !candidates.isEmpty else { return [] } + let paths = ArtifactStorePaths(projectRoot: context.projectRoot) + let sourcePathResolver = ArtifactPathResolver(fileManager: fileManager) + let expectedFilesystemRootPath = sourcePathResolver.canonicalPath(paths.filesystemRoot) + let expectedStagingRootPath = sourcePathResolver.canonicalPath(paths.importStagingRoot) + do { + try prepareForMutation(paths: paths) + } catch let error as ArtifactStoreError { + return candidates.map { _ in .rejected(error) } + } catch { + return candidates.map { _ in .rejected(.pathOutsideStore(paths.filesystemRoot.path)) } + } + var attempts = Array(repeating: nil, count: candidates.count) + var preparedByIndex: [Int: PreparedArtifactImport] = [:] + let stagingLease: ArtifactImportStagingLease + do { + stagingLease = try ArtifactImportStagingLease( + root: paths.importStagingRoot, + fileManager: fileManager, + expectedCanonicalPath: expectedStagingRootPath + ) + } catch let error as ArtifactStoreError { + return candidates.map { _ in .rejected(error) } + } catch { + return candidates.map { _ in .rejected(.pathOutsideStore(paths.importStagingRoot.path)) } + } + defer { stagingLease.finish() } + let expectedStagingDirectoryPath = stagingLease.directory + .resolvingSymlinksInPath() + .standardizedFileURL + .path + let stagedURLs = candidates.map { _ in stagingLease.makeStagedURL() } + let candidateValidator = ArtifactGitIgnoreManager(fileManager: fileManager) + .writeValidator( + projectRoot: paths.projectRoot, + commandRunner: gitCommandRunner + ) + let privacyValidator: ArtifactGitPrivacyValidator? + if let candidateValidator, + await candidateValidator.storeIsUntracked(filesystemRoot: paths.filesystemRoot) { + privacyValidator = candidateValidator + } else { + privacyValidator = nil + } + guard let privacyValidator, + await privacyValidator.permits(destinations: stagedURLs) else { + return candidates.map { _ in + .rejected(.gitPrivacyUnavailable(paths.filesystemRoot.path)) + } + } + if Task.isCancelled { + return finalizedAttempts(attempts, candidates: candidates) + } + let batchByteLimit = maximumBatchBytes.map { max(0, $0) } + var stagedBytes: Int64 = 0 + candidateLoop: for (index, candidate) in candidates.enumerated() { + guard attempts[index] == nil else { continue } + if let batchByteLimit, stagedBytes >= batchByteLimit { + for remainingIndex in index.. [String: URL] { + try ArtifactDeduplicationIndexBuilder( + recorder: ArtifactProvenanceRecorder( + fileManager: fileManager, + encoder: encoder, + decoder: decoder + ), + scanner: ArtifactDeduplicationScanner( + fileManager: fileManager, + maximumDepth: maximumScanDepth, + nodeLimit: configuration.deduplicationScanNodeLimit, + hashByteLimit: configuration.deduplicationHashByteLimit + ), + fileManager: fileManager + ).build(prepared: prepared, paths: paths) + } + + private func makeWritePlan( + prepared: [PreparedArtifactImport], + existingByDigest: [String: URL], + context: ArtifactCaptureContext, + paths: ArtifactStorePaths + ) throws -> ArtifactWritePlan { + try ArtifactWritePlanner( + fileManager: fileManager, + encoder: encoder, + decoder: decoder, + nodeBudget: nodeBudget + ).plan( + prepared: prepared, + existingByDigest: existingByDigest, + context: context, + paths: paths + ) + } + + private func makeConservativeWritePlan( + prepared: [PreparedArtifactImport], + context: ArtifactCaptureContext, + paths: ArtifactStorePaths + ) throws -> ArtifactWritePlan { + try ArtifactWritePlanner( + fileManager: fileManager, + encoder: encoder, + decoder: decoder, + nodeBudget: nodeBudget + ).conservativePlan( + prepared: prepared, + context: context, + paths: paths + ) + } + + private func finalizedAttempts( + _ attempts: [ArtifactImportAttempt?], + candidates: [ArtifactCandidate] + ) -> [ArtifactImportAttempt] { + attempts.enumerated().map { index, attempt in + attempt ?? .rejected(.sourceNotRegularFile(candidates[index].sourceURL.path)) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Import.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Import.swift new file mode 100644 index 000000000000..7ab2d5a25fe5 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Import.swift @@ -0,0 +1,122 @@ +import Foundation + +extension LocalArtifactRepository { + func importPrepared( + _ prepared: PreparedArtifactImport, + context: ArtifactCaptureContext, + paths: ArtifactStorePaths, + capturedAt: Date, + existingByDigest: inout [String: URL], + captureDirectory: inout URL?, + mutationLease: ArtifactStoreMutationLease, + expectedSourceParentPath: String, + plannedDestination: URL?, + plannedResolution: ArtifactCaptureDirectoryResolution? + ) throws -> ArtifactImportOutcome { + let source = prepared.candidate.sourceURL + let size = prepared.snapshot.size + let digest = prepared.digest + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + + if pathResolver.isInsideStore(source, paths: paths), + let relativePath = pathResolver.relativePath(source, root: paths.filesystemRoot) { + let record = makeRecord( + digest: digest, + source: source, + relativePath: relativePath, + context: context, + provenance: prepared.candidate.provenance, + capturedAt: capturedAt, + size: size + ) + try recordProvenance(record, paths: paths, mutationLease: mutationLease) + existingByDigest[digest] = source + return .alreadyStored(record) + } + + if let existing = existingByDigest[digest], + let relativePath = pathResolver.relativePath(existing, root: paths.filesystemRoot) { + let record = makeRecord( + digest: digest, + source: source, + relativePath: relativePath, + context: context, + provenance: prepared.candidate.provenance, + capturedAt: capturedAt, + size: size + ) + try recordProvenance(record, paths: paths, mutationLease: mutationLease) + return .deduplicated(record) + } + + let resolution: ArtifactCaptureDirectoryResolution? + let destinationDirectory: URL + if let plannedDestination { + destinationDirectory = plannedDestination.deletingLastPathComponent() + resolution = captureDirectory.map { + pathResolver.refersToSameLocation($0, destinationDirectory) + } == true ? nil : plannedResolution + } else if let captureDirectory { + resolution = nil + destinationDirectory = captureDirectory + } else { + let resolved = try ArtifactCaptureDirectoryFinder( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ).resolve(paths: paths, context: context, pathResolver: pathResolver) + resolution = resolved + destinationDirectory = resolved.directory + } + let destination = plannedDestination ?? pathResolver.uniqueDestination( + source: source, + directory: destinationDirectory, + fileManager: fileManager + ) + if let resolution { + try createCaptureDirectory( + resolution.directory, + paths: paths, + context: context, + capturedAt: capturedAt, + mutationLease: mutationLease + ) + captureDirectory = resolution.directory + } + + guard let destinationRelativePath = pathResolver.relativePath( + destination, + root: paths.filesystemRoot + ) else { + throw ArtifactStoreError.pathOutsideStore(destination.path) + } + try mutationLease.moveFile( + from: prepared.snapshot.url, + toRelativePath: destinationRelativePath, + expectedSourceParentPath: expectedSourceParentPath + ) + var keepsDestination = false + defer { + if !keepsDestination { + try? mutationLease.unlink(relativePath: destinationRelativePath) + } + } + guard let relativePath = pathResolver.relativePath(destination, root: paths.filesystemRoot) else { + throw ArtifactStoreError.pathOutsideStore(destination.path) + } + let record = makeRecord( + digest: digest, + source: source, + relativePath: relativePath, + context: context, + provenance: prepared.candidate.provenance, + capturedAt: capturedAt, + size: size + ) + try recordProvenance(record, paths: paths, mutationLease: mutationLease) + existingByDigest[digest] = destination + keepsDestination = true + return .copied(record) + } + +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Notes.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Notes.swift new file mode 100644 index 000000000000..579c3cb2c1da --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository+Notes.swift @@ -0,0 +1,296 @@ +public import Foundation + +extension LocalArtifactRepository: NoteStoring { + private static var maximumNoteBytes: Int64 { 4 * 1024 * 1024 } + + /// Lists Markdown notes from every live session `notes` directory. + public func listNotes(projectRoot: URL) throws -> [CmuxProjectNote] { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + return try noteResolver.notes(snapshot: completeSnapshot(paths: paths)) + } + + /// Resolves a live note after arbitrary file or session-folder moves. + public func resolveNote(projectRoot: URL, name: String) throws -> CmuxProjectNote { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + return try noteResolver.resolve( + snapshot: completeSnapshot(paths: paths), + rawName: name + ) + } + + /// Reads one bounded UTF-8 note without following symbolic links. + public func readNote(projectRoot: URL, name: String) throws -> String { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + let note = try resolveNote(projectRoot: projectRoot, name: name) + return try noteText(note, paths: paths) + } + + /// Writes or appends one bounded UTF-8 note under the current session. + public func writeNote( + name: String, + text: String, + mode: CmuxNoteWriteMode, + context: ArtifactCaptureContext + ) async throws -> CmuxProjectNote { + let incoming = Data(text.utf8) + guard incoming.count <= Self.maximumNoteBytes else { + throw CmuxNoteStoreError.noteTooLarge( + actual: Int64(incoming.count), + limit: Self.maximumNoteBytes + ) + } + let paths = ArtifactStorePaths(projectRoot: context.projectRoot) + let expectedFilesystemRootPath = ArtifactPathResolver(fileManager: fileManager) + .canonicalPath(paths.filesystemRoot) + try prepareForMutation(paths: paths) + let preflightPlan = try makeNoteWritePlan( + name: name, + context: context, + paths: paths + ) + try await validateNoteWritePrivacy(plan: preflightPlan, paths: paths) + + let lease = try ArtifactStoreMutationLease( + directory: paths.filesystemRoot, + expectedCanonicalPath: expectedFilesystemRootPath + ) + defer { lease.finish() } + let plan = try makeNoteWritePlan(name: name, context: context, paths: paths) + guard plan.privacyDestinations.map(\.standardizedFileURL.path) + == preflightPlan.privacyDestinations.map(\.standardizedFileURL.path) else { + throw ArtifactStoreError.gitPrivacyUnavailable(paths.filesystemRoot.path) + } + + if plan.existing == nil { + try createCaptureDirectory( + plan.contentDirectory, + paths: paths, + context: context, + capturedAt: now(), + mutationLease: lease + ) + } + + let parent = plan.destination.deletingLastPathComponent() + try rejectSymbolicLinks(from: paths.filesystemRoot, through: parent) + try fileManager.createDirectory(at: parent, withIntermediateDirectories: true) + try rejectSymbolicLinks(from: paths.filesystemRoot, through: parent) + + let finalData: Data + if mode == .append, let existing = plan.existing { + let current = try noteData(existing, paths: paths) + let combinedCount = current.count + incoming.count + guard combinedCount <= Self.maximumNoteBytes else { + throw CmuxNoteStoreError.noteTooLarge( + actual: Int64(combinedCount), + limit: Self.maximumNoteBytes + ) + } + var combined = current + combined.append(incoming) + finalData = combined + } else { + finalData = incoming + } + let notePathResolver = ArtifactPathResolver(fileManager: fileManager) + try CmuxNoteAtomicWriter(fileManager: fileManager).write( + finalData, + to: plan.destination, + expectedParentPath: notePathResolver.canonicalPath(parent) + ) + + guard let relativePath = ArtifactPathResolver(fileManager: fileManager).relativePath( + plan.destination, + root: paths.filesystemRoot + ), let node = try ArtifactExactPathResolver(fileManager: fileManager).fileNode( + relativePath: relativePath, + paths: paths + ) else { + throw CmuxNoteStoreError.pathOutsideStore(plan.destination.path) + } + return noteResolver.note(node) + } + + /// Searches only live Markdown notes while sharing artifact search bounds. + public func searchNotes(projectRoot: URL, query: String) throws -> [CmuxNoteSearchResult] { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + let snapshot = try completeSnapshot(paths: paths) + let resolver = noteResolver + let noteSnapshot = ArtifactSnapshot( + projectRoot: snapshot.projectRoot, + filesystemRoot: snapshot.filesystemRoot, + nodes: try resolver.noteNodes(snapshot: snapshot), + isTruncated: false + ) + return try ArtifactSearchEngine( + configuration: configuration(projectRoot: projectRoot), + fileManager: fileManager + ) + .results(snapshot: noteSnapshot, query: query) + .map { result in + CmuxNoteSearchResult( + note: resolver.note(result.node), + matchedContent: result.matchedContent, + snippet: result.snippet + ) + } + } + + /// Deletes one exactly resolved note without following a replaced symbolic link. + /// + /// - Returns: Metadata for the note that was removed. + @discardableResult + public func deleteNote(projectRoot: URL, name: String) throws -> CmuxProjectNote { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + let resolver = noteResolver + let expectedFilesystemRootPath = ArtifactPathResolver(fileManager: fileManager) + .canonicalPath(paths.filesystemRoot) + let note = try resolver.resolveExact( + notes: resolver.notes(snapshot: completeSnapshot(paths: paths)), + rawName: name + ) + guard let expectedIdentity = note.fileIdentity else { + throw CmuxNoteStoreError.pathOutsideStore(note.absolutePath) + } + try prepareForMutation(paths: paths) + let lease = try ArtifactStoreMutationLease( + directory: paths.filesystemRoot, + expectedCanonicalPath: expectedFilesystemRootPath + ) + defer { lease.finish() } + do { + try lease.unlink( + relativePath: note.relativePath, + expectedIdentity: expectedIdentity + ) + } catch ArtifactStoreError.pathOutsideStore { + throw CmuxNoteStoreError.pathOutsideStore(note.absolutePath) + } + return note + } + + private func makeNoteWritePlan( + name: String, + context: ArtifactCaptureContext, + paths: ArtifactStorePaths + ) throws -> CmuxNoteWritePlan { + let resolver = noteResolver + let snapshot = try completeSnapshot(paths: paths) + let allNotes = try resolver.notes(snapshot: snapshot) + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + let resolution = try ArtifactCaptureDirectoryFinder( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ).resolve( + paths: paths, + context: context, + pathResolver: pathResolver, + kind: .notes + ) + let rawName = name.trimmingCharacters(in: .whitespacesAndNewlines) + let creationRelativePath = rawName.hasPrefix(".cmux/") + ? nil + : try resolver.creationRelativePath(rawName: name, paths: paths) + let contentRelativePath = pathResolver.relativePath( + resolution.directory, + root: paths.filesystemRoot + ) + let candidateNotes: [CmuxProjectNote] + if rawName.hasPrefix(".cmux/") { + candidateNotes = allNotes + } else if let contentRelativePath { + let prefix = contentRelativePath + "/" + candidateNotes = allNotes.filter { + $0.relativePath.hasPrefix(prefix) + } + } else { + candidateNotes = [] + } + let existing: CmuxProjectNote? + do { + if let creationRelativePath, + let contentRelativePath, + let exact = candidateNotes.first(where: { + $0.relativePath == contentRelativePath + "/" + creationRelativePath + }) { + existing = exact + } else { + existing = try resolver.resolveExact(notes: candidateNotes, rawName: name) + } + } catch CmuxNoteStoreError.noteNotFound { + existing = nil + } + + if let existing { + return CmuxNoteWritePlan( + contentDirectory: resolution.directory, + destination: URL(fileURLWithPath: existing.absolutePath, isDirectory: false), + existing: existing + ) + } + guard let creationRelativePath else { + throw CmuxNoteStoreError.noteNotFound(name) + } + return CmuxNoteWritePlan( + contentDirectory: resolution.directory, + destination: resolution.directory.appendingPathComponent(creationRelativePath), + existing: nil + ) + } + + private func validateNoteWritePrivacy( + plan: CmuxNoteWritePlan, + paths: ArtifactStorePaths + ) async throws { + let validator = ArtifactGitIgnoreManager(fileManager: fileManager) + .writeValidator( + projectRoot: paths.projectRoot, + commandRunner: gitCommandRunner + ) + guard let validator, + await validator.storeIsUntracked(filesystemRoot: paths.filesystemRoot), + await validator.permits(destinations: plan.privacyDestinations) else { + throw ArtifactStoreError.gitPrivacyUnavailable(paths.filesystemRoot.path) + } + } + + private var noteResolver: CmuxProjectNoteResolver { + CmuxProjectNoteResolver( + fileManager: fileManager, + decoder: decoder, + nodeBudget: nodeBudget + ) + } + + private func noteText(_ note: CmuxProjectNote, paths: ArtifactStorePaths) throws -> String { + let data = try noteData(note, paths: paths) + guard let text = String(data: data, encoding: .utf8) else { + throw CmuxNoteStoreError.invalidUTF8(note.relativePath) + } + return text + } + + private func noteData(_ note: CmuxProjectNote, paths: ArtifactStorePaths) throws -> Data { + if let size = note.size, size > Self.maximumNoteBytes { + throw CmuxNoteStoreError.noteTooLarge(actual: size, limit: Self.maximumNoteBytes) + } + guard let expectedIdentity = note.fileIdentity else { + throw CmuxNoteStoreError.pathOutsideStore(note.absolutePath) + } + let url = URL(fileURLWithPath: note.absolutePath, isDirectory: false) + guard let data = try ArtifactBoundedFileReader(fileManager: fileManager).data( + url: url, + allowedRoot: paths.filesystemRoot, + maximumBytes: Self.maximumNoteBytes, + expectedIdentity: expectedIdentity + ) else { + throw CmuxNoteStoreError.pathOutsideStore(note.absolutePath) + } + return data + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository.swift new file mode 100644 index 000000000000..5da662e7848d --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/LocalArtifactRepository.swift @@ -0,0 +1,458 @@ +import CmuxFoundation +public import Foundation + +/// Actor-backed local repository for one or more project artifact stores. +/// +/// Ordinary files under session folders in `.cmux` are authoritative. Hidden metadata is +/// content-addressed so user-driven file moves and renames do not invalidate +/// deduplication or provenance. +public actor LocalArtifactRepository: ArtifactStoring { + private static let maximumConfigurationBytes: Int64 = 64 * 1024 + let fileManager: FileManager + let decoder: JSONDecoder + let encoder: JSONEncoder + let gitCommandRunner: any ArtifactGitCommandRunning + let now: @Sendable () -> Date + let maximumScanDepth: Int + let nodeBudget: Int + + /// Creates a local filesystem repository. + /// + /// - Parameters: + /// - fileManager: Filesystem dependency used by storage and tests. + /// - maximumScanDepth: Defensive recursive tree depth. + /// - nodeBudget: Defensive number of files and folders scanned at once. + /// - now: Clock seam used to age malformed staging entries. + public init( + fileManager: FileManager = .default, + maximumScanDepth: Int = 32, + nodeBudget: Int = 20_000, + now: @escaping @Sendable () -> Date = { .now } + ) { + self.fileManager = fileManager + self.gitCommandRunner = SystemArtifactGitCommandRunner() + self.now = now + self.maximumScanDepth = max(1, maximumScanDepth) + self.nodeBudget = max(1, nodeBudget) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + self.decoder = decoder + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + self.encoder = encoder + } + + /// Creates a repository with an injected Git command seam for tests. + init( + fileManager: FileManager, + gitCommandRunner: any ArtifactGitCommandRunning, + maximumScanDepth: Int = 32, + nodeBudget: Int = 20_000, + now: @escaping @Sendable () -> Date = { .now } + ) { + self.fileManager = fileManager + self.gitCommandRunner = gitCommandRunner + self.now = now + self.maximumScanDepth = max(1, maximumScanDepth) + self.nodeBudget = max(1, nodeBudget) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + self.decoder = decoder + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + self.encoder = encoder + } + + /// Resolves the nearest `.cmux` or Git project root on the repository actor. + public func locateProjectRoot(startingAt url: URL) -> URL { + ArtifactProjectLocator().projectRoot(startingAt: url, fileManager: fileManager) + } + + /// Loads a partial `.cmux/artifacts.json`, failing closed for automatic capture on errors. + public func configuration(projectRoot: URL) -> ArtifactCaptureConfiguration { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + let url = paths.configurationFile + let reader = ArtifactBoundedFileReader(fileManager: fileManager) + var failureConfiguration = ArtifactCaptureConfiguration.defaultValue + failureConfiguration.automaticCaptureEnabled = false + do { + guard try reader.pathEntryExists(url: url) else { return .defaultValue } + } catch { + return failureConfiguration + } + guard let data = try? reader.data( + url: url, + allowedRoot: paths.filesystemRoot, + maximumBytes: Self.maximumConfigurationBytes + ), + let configuration = try? decoder.decode(ArtifactCaptureConfiguration.self, from: data) else { + return failureConfiguration + } + return configuration.normalized + } + + /// Scans the live ordinary-file tree without creating or repairing the store. + public func snapshot(projectRoot: URL) throws -> ArtifactSnapshot { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + return try completeSnapshot(paths: paths) + } + + /// Searches fuzzy filenames and bounded UTF-8 contents from a live scan. + public func search(projectRoot: URL, query: String) throws -> [ArtifactSearchResult] { + try Task.checkCancellation() + let snapshot = try snapshot(projectRoot: projectRoot) + try Task.checkCancellation() + let configuration = configuration(projectRoot: projectRoot) + return try ArtifactSearchEngine( + configuration: configuration, + fileManager: fileManager + ).results( + snapshot: snapshot, + query: query + ) + } + + /// Imports, deduplicates, or records a file already inside the store. + public func importFile( + sourceURL: URL, + context: ArtifactCaptureContext, + provenance: ArtifactProvenance, + configuration: ArtifactCaptureConfiguration, + capturedAt: Date + ) async throws -> ArtifactImportOutcome { + let attempts = await importFiles( + candidates: [ArtifactCandidate(sourceURL: sourceURL, provenance: provenance)], + context: context, + configuration: configuration, + maximumBatchBytes: nil, + capturedAt: capturedAt + ) + guard let attempt = attempts.first else { + throw ArtifactStoreError.sourceNotRegularFile(sourceURL.path) + } + switch attempt { + case .imported(let outcome): + return outcome + case .rejected(let error): + throw error + } + } + + /// Resolves an exact relative path, unique basename, or unique fuzzy match. + public func resolve(projectRoot: URL, name rawName: String) throws -> ArtifactNode { + let trimmedName = rawName.trimmingCharacters(in: .whitespacesAndNewlines) + let name = trimmedName.hasPrefix(".cmux/") + ? String(trimmedName.dropFirst(".cmux/".count)) + : trimmedName + let paths = ArtifactStorePaths(projectRoot: projectRoot) + try validateStoreForReading(paths: paths) + if let exact = try ArtifactExactPathResolver(fileManager: fileManager).fileNode( + relativePath: name, + paths: paths + ) { + return exact + } + let snapshot = try completeSnapshot(paths: paths) + let files = snapshot.nodes.flattenedArtifactNodes().filter { !$0.isDirectory } + let basenameMatches = files.filter { $0.name == name } + if basenameMatches.count == 1, let match = basenameMatches.first { return match } + if basenameMatches.count > 1 { + throw ArtifactStoreError.ambiguousArtifactName(name, matches: basenameMatches.map(\.relativePath)) + } + let matcher = ArtifactFuzzyMatcher(query: name) + let fuzzyMatches = files.compactMap { node in + matcher.score(candidate: node.relativePath).map { (node, $0) } + }.sorted { $0.1 > $1.1 } + guard let best = fuzzyMatches.first else { + throw ArtifactStoreError.artifactNotFound(name) + } + if fuzzyMatches.count > 1, fuzzyMatches[1].1 == best.1 { + throw ArtifactStoreError.ambiguousArtifactName( + name, + matches: fuzzyMatches.filter { $0.1 == best.1 }.map { $0.0.relativePath } + ) + } + return best.0 + } + + /// Creates a recursive watcher stream that emits on subsequent changes. + public func changes(projectRoot: URL) -> AsyncStream { + let paths = ArtifactStorePaths(projectRoot: projectRoot) + do { + try validateStoreForReading(paths: paths) + } catch { + return AsyncStream { $0.finish() } + } + let filesystemRoot = paths.filesystemRoot + let awaitsFilesystemRoot = (try? filesystemRoot.checkResourceIsReachable()) != true + let initialWatcher: RecursivePathWatcher? + if awaitsFilesystemRoot { + let filesystemRootPath = filesystemRoot.path + // FSEvents is recursive for a directory path. Before `.cmux` + // exists, filter the project-root stream at the source boundary so + // unrelated project churn cannot wake the repository or retain a + // recursive store watcher. Once the store appears, the narrower + // recursive `.cmux` watcher below takes over. + initialWatcher = RecursivePathWatcher( + paths: [paths.projectRoot.path], + eventFilter: { change in + change.paths.contains { path in + path == filesystemRootPath + || path.hasPrefix(filesystemRootPath + "/") + } + } + ) + } else { + initialWatcher = RecursivePathWatcher(paths: [filesystemRoot.path]) + } + guard let initialWatcher else { + return AsyncStream { $0.finish() } + } + return AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in + let task = Task { + var storeWatcher: RecursivePathWatcher? + if awaitsFilesystemRoot { + if (try? filesystemRoot.checkResourceIsReachable()) == true { + storeWatcher = RecursivePathWatcher(paths: [filesystemRoot.path]) + if storeWatcher != nil { + continuation.yield(()) + } + } + if storeWatcher == nil { + for await _ in initialWatcher.events { + guard !Task.isCancelled else { break } + guard (try? filesystemRoot.checkResourceIsReachable()) == true else { + continue + } + guard let watcher = RecursivePathWatcher( + paths: [filesystemRoot.path] + ) else { + continue + } + storeWatcher = watcher + continuation.yield(()) + break + } + } + await initialWatcher.stop() + } else { + storeWatcher = initialWatcher + } + + if !Task.isCancelled, let storeWatcher { + for await _ in storeWatcher.events { + guard !Task.isCancelled else { break } + continuation.yield(()) + } + await storeWatcher.stop() + } + continuation.finish() + } + continuation.onTermination = { _ in task.cancel() } + } + } + + private var scanner: ArtifactTreeScanner { + ArtifactTreeScanner( + fileManager: fileManager, + maximumDepth: maximumScanDepth, + nodeBudget: nodeBudget + ) + } + + func completeSnapshot(paths: ArtifactStorePaths) throws -> ArtifactSnapshot { + let snapshot = try scanner.snapshot(paths: paths) + guard !snapshot.isTruncated else { + throw ArtifactStoreError.scanIncomplete(paths.filesystemRoot.path) + } + return snapshot + } + + func validateStoreForReading(paths: ArtifactStorePaths) throws { + guard fileManager.fileExists(atPath: paths.filesystemRoot.path) else { return } + let values = try paths.filesystemRoot.resourceValues( + forKeys: [.isDirectoryKey, .isSymbolicLinkKey] + ) + guard values.isDirectory == true, values.isSymbolicLink != true else { + throw ArtifactStoreError.pathOutsideStore(paths.filesystemRoot.path) + } + } + + func prepareForMutation(paths: ArtifactStorePaths) throws { + try rejectSymbolicLink(at: paths.filesystemRoot) + try fileManager.createDirectory(at: paths.filesystemRoot, withIntermediateDirectories: true) + try rejectSymbolicLink(at: paths.filesystemRoot) + try rejectSymbolicLinks( + from: paths.filesystemRoot, + through: paths.provenanceRoot + ) + try rejectSymbolicLinks( + from: paths.filesystemRoot, + through: paths.importStagingRoot + ) + ArtifactImportStagingCleaner(fileManager: fileManager, now: now) + .reclaimAbandonedBatches(root: paths.importStagingRoot) + try ArtifactGitIgnoreManager(fileManager: fileManager).ensureIgnored(projectRoot: paths.projectRoot) + } + + func createCaptureDirectory( + _ contentDirectory: URL, + paths: ArtifactStorePaths, + context: ArtifactCaptureContext, + capturedAt: Date, + mutationLease: ArtifactStoreMutationLease + ) throws { + try rejectSymbolicLinks(from: paths.filesystemRoot, through: contentDirectory) + try fileManager.createDirectory(at: contentDirectory, withIntermediateDirectories: true) + try rejectSymbolicLinks(from: paths.filesystemRoot, through: contentDirectory) + let sessionDirectory = contentDirectory.deletingLastPathComponent() + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + guard let sessionRelativePath = pathResolver.relativePath( + sessionDirectory, + root: paths.filesystemRoot + ) else { + throw ArtifactStoreError.pathOutsideStore(sessionDirectory.path) + } + try writeMarkerIfMissing( + ArtifactWorkspaceMarker( + workspaceID: context.workspaceID, + workspaceTitle: context.workspaceTitle, + createdAt: capturedAt + ), + relativePath: sessionRelativePath + "/" + ArtifactPathResolver.workspaceMarkerName, + paths: paths, + mutationLease: mutationLease + ) + try writeSessionMarkerIfMissing( + ArtifactSessionMarker( + sessionID: context.sessionID, + agentName: context.agentName, + createdAt: capturedAt + ), + relativePath: sessionRelativePath + "/" + ArtifactPathResolver.sessionMarkerName, + paths: paths, + mutationLease: mutationLease + ) + } + + private func writeMarkerIfMissing( + _ value: some Encodable, + relativePath: String, + paths: ArtifactStorePaths, + mutationLease: ArtifactStoreMutationLease + ) throws { + let encodedData = try encoder.encode(value) + if try mutationLease.writeData( + encodedData, + toRelativePath: relativePath, + replacingExisting: false + ) { + return + } + guard let existing = try ArtifactBoundedFileReader(fileManager: fileManager).data( + url: paths.filesystemRoot.appendingPathComponent(relativePath), + allowedRoot: paths.filesystemRoot, + maximumBytes: 256 * 1024 + ), !existing.isEmpty else { + throw ArtifactStoreError.corruptProvenance(relativePath) + } + } + + private func writeSessionMarkerIfMissing( + _ value: ArtifactSessionMarker, + relativePath: String, + paths: ArtifactStorePaths, + mutationLease: ArtifactStoreMutationLease + ) throws { + let reader = ArtifactBoundedFileReader(fileManager: fileManager) + let encodedData = try encoder.encode(value) + if try mutationLease.writeData( + encodedData, + toRelativePath: relativePath, + replacingExisting: false + ) { + return + } + let url = paths.filesystemRoot.appendingPathComponent(relativePath) + guard let existingData = try reader.data( + url: url, + allowedRoot: paths.filesystemRoot, + maximumBytes: 256 * 1024 + ), let existing = try? decoder.decode(ArtifactSessionMarker.self, from: existingData), + existing.identity == value.identity else { + throw ArtifactStoreError.corruptProvenance(url.path) + } + } + + func rejectSymbolicLinks(from root: URL, through descendant: URL) throws { + let pathResolver = ArtifactPathResolver(fileManager: fileManager) + try rejectSymbolicLink(at: root) + guard !pathResolver.refersToSameLocation(descendant, root) else { return } + guard let relativePath = pathResolver.relativePath(descendant, root: root) else { + throw ArtifactStoreError.pathOutsideStore(descendant.path) + } + var current = root + for component in relativePath.split(separator: "/") { + current.appendPathComponent(String(component)) + try rejectSymbolicLink(at: current) + } + } + + func rejectSymbolicLink(at url: URL) throws { + guard fileManager.fileExists(atPath: url.path) else { return } + let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { + throw ArtifactStoreError.pathOutsideStore(url.path) + } + } + + func makeRecord( + digest: String, + source: URL, + relativePath: String, + context: ArtifactCaptureContext, + provenance: ArtifactProvenance, + capturedAt: Date, + size: Int64 + ) -> ArtifactRecord { + ArtifactRecord( + digest: digest, + sourcePath: source.path, + relativePath: relativePath, + workspaceID: context.workspaceID, + sessionID: context.sessionID, + provenance: provenance, + capturedAt: capturedAt, + size: size + ) + } + + func recordProvenance( + _ record: ArtifactRecord, + paths: ArtifactStorePaths, + mutationLease: ArtifactStoreMutationLease + ) throws { + let recorder = ArtifactProvenanceRecorder( + fileManager: fileManager, + encoder: encoder, + decoder: decoder + ) + try recorder.record( + paths: paths, + digest: record.digest, + relativePath: record.relativePath, + size: record.size, + event: ArtifactProvenanceEvent( + sourcePath: record.sourcePath, + workspaceID: record.workspaceID, + sessionID: record.sessionID, + provenance: record.provenance, + capturedAt: record.capturedAt + ), + mutationLease: mutationLease + ) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/NoteStoring.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/NoteStoring.swift new file mode 100644 index 000000000000..27d9eee82b6f --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/NoteStoring.swift @@ -0,0 +1,25 @@ +public import Foundation + +/// Filesystem persistence seam for movable project Notes. +public protocol NoteStoring: Sendable { + /// Lists Markdown notes from every live session `notes` directory. + func listNotes(projectRoot: URL) async throws -> [CmuxProjectNote] + /// Resolves an exact path, unique filename or stem, or unique fuzzy match. + func resolveNote(projectRoot: URL, name: String) async throws -> CmuxProjectNote + /// Reads one bounded UTF-8 note. + func readNote(projectRoot: URL, name: String) async throws -> String + /// Writes or appends one note in the current session filesystem. + func writeNote( + name: String, + text: String, + mode: CmuxNoteWriteMode, + context: ArtifactCaptureContext + ) async throws -> CmuxProjectNote + /// Searches note filenames and bounded UTF-8 contents. + func searchNotes(projectRoot: URL, query: String) async throws -> [CmuxNoteSearchResult] + /// Deletes one exactly resolved note without following symbolic links. + /// + /// - Returns: Metadata for the note that was removed. + @discardableResult + func deleteNote(projectRoot: URL, name: String) async throws -> CmuxProjectNote +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/PreparedArtifactImport.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/PreparedArtifactImport.swift new file mode 100644 index 000000000000..a53e7fd8cd17 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/PreparedArtifactImport.swift @@ -0,0 +1,8 @@ +import Foundation + +/// Immutable staged candidate used by one repository batch. +struct PreparedArtifactImport { + let candidate: ArtifactCandidate + let snapshot: ArtifactSourceSnapshot + let digest: String +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ProjectFileTemporaryCopyCleaner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ProjectFileTemporaryCopyCleaner.swift new file mode 100644 index 000000000000..bf345e414cfc --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/ProjectFileTemporaryCopyCleaner.swift @@ -0,0 +1,164 @@ +import Darwin +public import Foundation + +/// Reclaims expired editor handoff copies while enforcing bounded temporary storage. +public struct ProjectFileTemporaryCopyCleaner { + private static let maximumFileCount = 256 + private static let maximumByteCount: Int64 = 256 * 1024 * 1024 + + private let fileManager: FileManager + private let now: Date + + /// Creates a temporary-copy cleaner with injectable filesystem and clock inputs. + /// + /// - Parameters: + /// - fileManager: Filesystem used to enumerate temporary copies. + /// - now: Reference time used to determine whether a copy's lease expired. + public init(fileManager: FileManager = .default, now: Date = .now) { + self.fileManager = fileManager + self.now = now + } + + /// Removes expired copies beyond the bounds and evaluates a requested reservation. + /// + /// Fresh copies retain a 24-hour lease and are never evicted to satisfy a + /// reservation. Only regular files whose names begin with + /// `cmux-project-file-` are considered. + /// + /// - Parameters: + /// - directory: Directory containing editor handoff copies. + /// - reservingBytes: Bytes needed by the pending handoff. + /// - reservingFileCount: File slots needed by the pending handoff. + /// - Returns: Whether the protected and retained copies leave room for the reservation. + @discardableResult + public func cleanup( + in directory: URL, + reservingBytes: Int64 = 0, + reservingFileCount: Int = 0 + ) -> Bool { + guard reservingBytes >= 0, reservingBytes <= Self.maximumByteCount else { + return false + } + guard reservingFileCount >= 0, reservingFileCount <= Self.maximumFileCount else { + return false + } + // LaunchServices has no completion callback for the editor that owns + // this handoff. Treat the age threshold as a lease: fresh copies are + // never evicted by count/bytes while an editor may still use them. + let cutoff = now.addingTimeInterval(-24 * 60 * 60) + guard let enumerator = fileManager.enumerator( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey], + options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants] + ) else { return true } + let directoryPath = directory.standardizedFileURL.path + var reclaimable: [(url: URL, size: Int64, modifiedAt: Date)] = [] + var protectedCount = 0 + var protectedBytes: Int64 = 0 + var unreclaimedCount = 0 + var unreclaimedBytes: Int64 = 0 + + func recordUnreclaimed(_ size: Int64) { + unreclaimedCount += 1 + unreclaimedBytes = unreclaimedBytes > Self.maximumByteCount - size + ? Self.maximumByteCount + : unreclaimedBytes + size + } + + for case let entry as URL in enumerator { + guard entry.deletingLastPathComponent().standardizedFileURL.path == directoryPath, + entry.lastPathComponent.hasPrefix("cmux-project-file-") else { + continue + } + var status = stat() + guard lstat(entry.path, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0 else { + continue + } + let modifiedAt = Date(timeIntervalSince1970: Double(status.st_mtimespec.tv_sec)) + guard modifiedAt < cutoff else { + // Preserve the active lease even if many editor handoffs are + // open. A later cleanup after expiry reclaims this copy. + protectedCount += 1 + let size = Int64(status.st_size) + protectedBytes = protectedBytes > Self.maximumByteCount - size + ? Self.maximumByteCount + : protectedBytes + size + continue + } + let candidate = ( + url: entry, + size: Int64(status.st_size), + modifiedAt: modifiedAt + ) + if reclaimable.count < Self.maximumFileCount { + reclaimable.append(candidate) + continue + } + guard let oldestIndex = reclaimable.indices.min(by: { lhs, rhs in + if reclaimable[lhs].modifiedAt != reclaimable[rhs].modifiedAt { + return reclaimable[lhs].modifiedAt < reclaimable[rhs].modifiedAt + } + return reclaimable[lhs].url.path < reclaimable[rhs].url.path + }) else { + continue + } + let oldest = reclaimable[oldestIndex] + let candidateIsNewer = candidate.modifiedAt > oldest.modifiedAt + || (candidate.modifiedAt == oldest.modifiedAt + && candidate.url.path > oldest.url.path) + if candidateIsNewer { + if removeExpiredCopy(at: oldest.url) { + reclaimable[oldestIndex] = candidate + } else { + // The failed eviction still occupies capacity even when + // the newer candidate can be discarded successfully. + recordUnreclaimed(oldest.size) + if !removeExpiredCopy(at: candidate.url) { + recordUnreclaimed(candidate.size) + } + } + } else if !removeExpiredCopy(at: candidate.url) { + recordUnreclaimed(candidate.size) + } + } + guard protectedCount <= Self.maximumFileCount - reservingFileCount, + protectedBytes <= Self.maximumByteCount, + protectedBytes <= Self.maximumByteCount - reservingBytes else { + return false + } + let availableCount = Self.maximumFileCount - protectedCount - reservingFileCount + let availableBytes = Self.maximumByteCount - protectedBytes - reservingBytes + reclaimable.sort { + if $0.modifiedAt != $1.modifiedAt { + return $0.modifiedAt > $1.modifiedAt + } + return $0.url.path > $1.url.path + } + var retainedBytes: Int64 = 0 + var retainedCount = 0 + for entry in reclaimable { + guard retainedCount < availableCount, + entry.size <= availableBytes, + retainedBytes <= availableBytes - entry.size else { + if !removeExpiredCopy(at: entry.url) { + recordUnreclaimed(entry.size) + } + continue + } + retainedBytes += entry.size + retainedCount += 1 + } + // A zero-byte note/artifact still creates a leased temporary file, so + // reserve its slot independently of the byte reservation. Failed + // unlinks remain counted because the next open will still observe them. + return unreclaimedCount <= availableCount - retainedCount + && unreclaimedBytes <= availableBytes - retainedBytes + } + + private func removeExpiredCopy(at url: URL) -> Bool { + let result = unlink(url.path) + return result == 0 || errno == ENOENT + } +} diff --git a/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/SystemArtifactGitCommandRunner.swift b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/SystemArtifactGitCommandRunner.swift new file mode 100644 index 000000000000..85bd69a9c1ff --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Sources/CmuxArtifacts/SystemArtifactGitCommandRunner.swift @@ -0,0 +1,125 @@ +import Darwin +import Foundation + +/// Process-backed Git command runner used by the local artifact repository. +struct SystemArtifactGitCommandRunner: ArtifactGitCommandRunning { + private let executableURL: URL + private let environment: [String: String] + private let timeout: TimeInterval + private let timeoutDelay: @Sendable (TimeInterval) async throws -> Void + + init( + executableURL: URL = URL(fileURLWithPath: "/usr/bin/git"), + environment: [String: String] = ProcessInfo.processInfo.environment, + timeout: TimeInterval = 5, + timeoutDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { timeout in + try await ContinuousClock().sleep(for: .seconds(timeout)) + } + ) { + self.executableURL = executableURL + self.environment = environment.filter { !$0.key.hasPrefix("GIT_") } + self.timeout = max(0.01, timeout) + self.timeoutDelay = timeoutDelay + } + + func terminationStatus(arguments: [String]) async throws -> Int32 { + let process = makeProcess(arguments: arguments) + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + return try await execute(process) + } + + func run( + arguments: [String], + standardInput: Data? + ) async throws -> (terminationStatus: Int32, standardOutput: Data) { + let process = makeProcess(arguments: arguments) + let outputFile = try makeUnlinkedFile() + defer { try? outputFile.close() } + process.standardOutput = outputFile + let inputFile: FileHandle? + if let standardInput { + let file = try makeUnlinkedFile() + do { + try file.write(contentsOf: standardInput) + try file.seek(toOffset: 0) + process.standardInput = file + inputFile = file + } catch { + try? file.close() + throw error + } + } else { + process.standardInput = FileHandle.nullDevice + inputFile = nil + } + defer { try? inputFile?.close() } + + let terminationStatus = try await execute(process) + try Task.checkCancellation() + try outputFile.seek(toOffset: 0) + let standardOutput = try outputFile.readToEnd() ?? Data() + return (terminationStatus, standardOutput) + } + + private func execute(_ process: Process) async throws -> Int32 { + try await withThrowingTaskGroup(of: Int32.self) { group in + group.addTask { + try await waitForTermination(process) + } + group.addTask { + try await timeoutDelay(timeout) + throw ArtifactGitCommandError.timedOut + } + defer { group.cancelAll() } + guard let result = try await group.next() else { + throw CancellationError() + } + return result + } + } + + private func waitForTermination(_ process: Process) async throws -> Int32 { + let cancellation = ArtifactGitProcessCancellation(process: process) + let status = try await withTaskCancellationHandler { + try Task.checkCancellation() + return try await withCheckedThrowingContinuation { continuation in + process.terminationHandler = { finished in + continuation.resume(returning: finished.terminationStatus) + } + do { + try process.run() + // Cancellation can arrive after the handler's initial liveness + // check but before launch; this post-launch check closes that race. + if Task.isCancelled { + cancellation.cancel() + } + } catch { + process.terminationHandler = nil + continuation.resume(throwing: error) + } + } + } onCancel: { + cancellation.cancel() + } + try Task.checkCancellation() + return status + } + + private func makeProcess(arguments: [String]) -> Process { + let process = Process() + process.executableURL = executableURL + process.arguments = arguments + process.environment = environment + process.standardError = FileHandle.nullDevice + return process + } + + private func makeUnlinkedFile() throws -> FileHandle { + var template = Array("\(NSTemporaryDirectory())cmux-artifact-git.XXXXXX".utf8CString) + let descriptor = mkstemp(&template) + guard descriptor >= 0 else { throw CocoaError(.fileWriteUnknown) } + unlink(template) + return FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactAutomaticBatchCollisionTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactAutomaticBatchCollisionTests.swift new file mode 100644 index 000000000000..4d4d3257302f --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactAutomaticBatchCollisionTests.swift @@ -0,0 +1,53 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact automatic batch collisions") +struct ArtifactAutomaticBatchCollisionTests { + @Test("Case-variant filenames in one batch receive distinct destinations") + func caseVariantFilenamesReceiveDistinctDestinations() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", root.path]) == 0) + let first = try ArtifactTestSupport.write( + "lowercase", + named: "report.md", + under: root.appendingPathComponent("sources/one") + ) + let second = try ArtifactTestSupport.write( + "uppercase", + named: "REPORT.md", + under: root.appendingPathComponent("sources/two") + ) + + let attempts = await LocalArtifactRepository().importFiles( + candidates: [ + ArtifactCandidate(sourceURL: first, provenance: .created), + ArtifactCandidate(sourceURL: second, provenance: .created), + ], + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:batch", + sessionID: "session:batch" + ), + configuration: .defaultValue, + maximumBatchBytes: nil, + capturedAt: Date(timeIntervalSince1970: 1_700_000_000) + ) + let records = attempts.compactMap { attempt -> ArtifactRecord? in + guard case .imported(let outcome) = attempt else { return nil } + return outcome.record + } + + #expect(records.count == 2) + #expect(Set(records.map(\.relativePath)).count == 2) + let storedContents = try records.map { record in + try String( + contentsOf: root.appendingPathComponent(".cmux/\(record.relativePath)"), + encoding: .utf8 + ) + } + #expect(Set(storedContents) == ["lowercase", "uppercase"]) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureCandidateFoldingTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureCandidateFoldingTests.swift new file mode 100644 index 000000000000..07934496a367 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureCandidateFoldingTests.swift @@ -0,0 +1,50 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact capture candidate folding") +struct ArtifactCaptureCandidateFoldingTests { + @Test("A later authorizing detection upgrades an earlier reference") + func preservesAuthorizingProvenance() async throws { + let project = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(project) } + let external = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(external) } + let source = try ArtifactTestSupport.write("plan", named: "plan.md", under: external) + let store = ConfiguredArtifactStore( + configuration: ArtifactCaptureConfiguration.defaultValue + ) + + let outcomes = await ArtifactCaptureService(store: store).capture( + candidates: [ + ArtifactCandidate(sourceURL: source, provenance: .referenced), + ArtifactCandidate(sourceURL: source, provenance: .created), + ], + context: ArtifactCaptureContext(projectRoot: project) + ) + + #expect(outcomes.count == 1) + #expect(outcomes.first?.record?.provenance == .created) + #expect(await store.importCount == 1) + } + + @Test("Explicit manual provenance wins without changing path order") + func manualProvenanceIsStrongest() async throws { + let project = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(project) } + let source = try ArtifactTestSupport.write("plan", named: "plan.md", under: project) + let store = ConfiguredArtifactStore( + configuration: ArtifactCaptureConfiguration.defaultValue + ) + + let outcomes = await ArtifactCaptureService(store: store).capture( + candidates: [ + ArtifactCandidate(sourceURL: source, provenance: .created), + ArtifactCandidate(sourceURL: source, provenance: .manual), + ], + context: ArtifactCaptureContext(projectRoot: project) + ) + + #expect(outcomes.first?.record?.provenance == .manual) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureServiceTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureServiceTests.swift new file mode 100644 index 000000000000..23c9713c54c8 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactCaptureServiceTests.swift @@ -0,0 +1,293 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact capture service") +struct ArtifactCaptureServiceTests { + @Test("Automatic references cannot expand access beyond the project") + func restrictsReferencedPathsToProject() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let temporary = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(temporary) } + let projectLocal = try ArtifactTestSupport.write("keep", named: "project.md", under: root) + let external = try ArtifactTestSupport.write("private", named: "external.md", under: temporary) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.ephemeralPathPrefixes = [root.path, temporary.path] + let store = ConfiguredArtifactStore(configuration: configuration) + let service = ArtifactCaptureService(store: store) + let context = ArtifactCaptureContext(projectRoot: root) + + let outcomes = await service.capture( + candidates: [ + ArtifactCandidate(sourceURL: projectLocal, provenance: .referenced), + ArtifactCandidate(sourceURL: external, provenance: .referenced), + ], + context: context + ) + + #expect(outcomes.first?.record?.sourcePath == projectLocal.path) + #expect(outcomes.last == .skipped(.provenanceNotEligible)) + #expect(await store.importCount == 1) + } + + @Test("Project configuration can narrow but not expand trusted ephemeral roots") + func clampsEphemeralPrefixes() { + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.ephemeralPathPrefixes = [ + "/", + "/tmp/cmux-session", + "/private/tmp/cmux-session", + "/var/folders/zz", + "/Users/shared", + ] + + let prefixes = configuration.normalized.ephemeralPathPrefixes + #expect(!prefixes.contains("/")) + #expect(!prefixes.contains("/Users/shared")) + #expect(prefixes.contains { $0.hasSuffix("/tmp/cmux-session") }) + #expect(prefixes.contains("/var/folders/zz")) + } + + @Test("Referenced capture rejects symlinked prefixes outside trusted roots") + func rejectsSymlinkedEphemeralPrefixOutsideTrustedRoots() async throws { + let projectRoot = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("CmuxArtifactsTests-\(UUID().uuidString)", isDirectory: true) + defer { ArtifactTestSupport.remove(projectRoot) } + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + let source = try ArtifactTestSupport.write("private", named: "project.md", under: projectRoot) + + let alias = FileManager.default.temporaryDirectory + .appendingPathComponent("CmuxArtifactsPrefix-\(UUID().uuidString)", isDirectory: true) + defer { ArtifactTestSupport.remove(alias) } + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: projectRoot) + + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.ephemeralPathPrefixes = [alias.path] + let store = ConfiguredArtifactStore(configuration: configuration) + let outcomes = await ArtifactCaptureService(store: store).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .referenced)], + context: ArtifactCaptureContext(projectRoot: projectRoot) + ) + + #expect(outcomes.first == .skipped(.provenanceNotEligible)) + #expect(await store.importCount == 0) + } + + @Test("Candidate limits are enforced before imports") + func enforcesCandidateLimit() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let first = try ArtifactTestSupport.write("one", named: "one.md", under: root) + let second = try ArtifactTestSupport.write("two", named: "two.md", under: root) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.maximumFilesPerCapture = 1 + let store = ConfiguredArtifactStore(configuration: configuration) + let outcomes = await ArtifactCaptureService(store: store).capture( + candidates: [ + ArtifactCandidate(sourceURL: first, provenance: .created), + ArtifactCandidate(sourceURL: second, provenance: .created), + ], + context: ArtifactCaptureContext(projectRoot: root) + ) + #expect(outcomes.count == 2) + #expect(outcomes.last == .skipped(.candidateLimitReached)) + #expect(await store.importCount == 1) + } + + @Test("Automatic capture enforces its aggregate staged-byte budget") + func enforcesAggregateAutomaticCaptureByteLimit() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", root.path]) == 0) + _ = try ArtifactTestSupport.write( + """ + { + "maximumFileBytes": 10, + "maximumTextFileBytes": 10, + "maximumAutomaticCaptureBytes": 6 + } + """, + named: ".cmux/artifacts.json", + under: root + ) + let first = try ArtifactTestSupport.write("1111", named: "outside/first.md", under: root) + let second = try ArtifactTestSupport.write("2222", named: "outside/second.md", under: root) + + let outcomes = await ArtifactCaptureService(store: LocalArtifactRepository()).capture( + candidates: [ + ArtifactCandidate(sourceURL: first, provenance: .created), + ArtifactCandidate(sourceURL: second, provenance: .created), + ], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(outcomes.first?.record != nil) + #expect(outcomes.last == .skipped(.candidateLimitReached)) + } + + @Test("An oversized first candidate does not starve smaller later candidates") + func oversizedFirstCandidateDoesNotStarveBatch() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", root.path]) == 0) + _ = try ArtifactTestSupport.write( + """ + { + "maximumFileBytes": 10, + "maximumTextFileBytes": 10, + "maximumAutomaticCaptureBytes": 6 + } + """, + named: ".cmux/artifacts.json", + under: root + ) + let oversized = try ArtifactTestSupport.write( + "12345678", + named: "outside/oversized.md", + under: root + ) + let accepted = try ArtifactTestSupport.write( + "1234", + named: "outside/accepted.md", + under: root + ) + + let outcomes = await ArtifactCaptureService(store: LocalArtifactRepository()).capture( + candidates: [ + ArtifactCandidate(sourceURL: oversized, provenance: .created), + ArtifactCandidate(sourceURL: accepted, provenance: .created), + ], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(outcomes.first == .skipped(.exceedsSizeLimit)) + #expect(outcomes.last?.record?.sourcePath == accepted.path) + } + + @Test("Manual selections share configuration and use bounded persistence batches") + func batchesManualSelection() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.maximumFilesPerCapture = 2 + let store = ConfiguredArtifactStore(configuration: configuration) + let sources = (0..<5).map { root.appendingPathComponent("artifact-\($0).md") } + + let attempts = await ArtifactCaptureService(store: store).add( + sourceURLs: sources, + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(attempts.count == sources.count) + #expect(await store.configurationReadCount == 1) + #expect(await store.batchImportCount == 3) + #expect(await store.importCount == sources.count) + } + + @Test("Manual selections are capped before retaining the full workload") + func capsManualSelectionWorkload() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.maximumFilesPerCapture = 32 + let store = ConfiguredArtifactStore(configuration: configuration) + let sources = (0..<1_100).map { + root.appendingPathComponent("artifact-\($0).md") + } + + let attempts = await ArtifactCaptureService(store: store).add( + sourceURLs: sources, + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(attempts.count == sources.count) + #expect(await store.importCount == 1_024) + #expect(attempts.suffix(76).allSatisfy { + if case .rejected(.fileCountLimitReached(actual: 1_100, limit: 1_024)) = $0 { + return true + } + return false + }) + } + + @Test("Explicit saves reject a parent swap after authorization") + func rejectsAuthorizedPathParentSwap() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let authorizedParent = root.appendingPathComponent("authorized", isDirectory: true) + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + try FileManager.default.createDirectory(at: authorizedParent, withIntermediateDirectories: true) + let source = authorizedParent.appendingPathComponent("plan.md") + try "authorized".write(to: source, atomically: true, encoding: .utf8) + let expectedCanonicalPath = source.resolvingSymlinksInPath().standardizedFileURL.path + try "outside".write( + to: outside.appendingPathComponent("plan.md"), + atomically: true, + encoding: .utf8 + ) + try FileManager.default.removeItem(at: authorizedParent) + try FileManager.default.createSymbolicLink(at: authorizedParent, withDestinationURL: outside) + + let paths = ArtifactStorePaths(projectRoot: root) + #expect(throws: ArtifactStoreError.self) { + _ = try ArtifactSourceSnapshotter(fileManager: .default).snapshot( + source: source, + paths: paths, + configuration: .defaultValue, + maximumBytes: nil, + stagedURL: paths.importStagingRoot.appendingPathComponent("staged.md"), + expectedCanonicalPath: expectedCanonicalPath + ) + } + } + + @Test("Manual selections continue across aggregate byte-bounded batches") + func boundsManualSelectionBatchBytes() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.maximumFileBytes = 8 + configuration.maximumTextFileBytes = 4 + configuration.maximumFilesPerCapture = 3 + let store = ConfiguredArtifactStore( + configuration: configuration, + limitsAggregateBatchToFirstCandidate: true + ) + let sources = (0..<3).map { root.appendingPathComponent("artifact-\($0).md") } + + let attempts = await ArtifactCaptureService(store: store).add( + sourceURLs: sources, + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(attempts.allSatisfy { + if case .imported = $0 { return true } + return false + }) + #expect(await store.importCount == sources.count) + #expect(await store.batchImportCount == sources.count) + #expect(await store.receivedMaximumBatchBytes == [8, 8, 8]) + } + + @Test("Ephemeral prefixes match canonical macOS path aliases") + func matchesCanonicalTemporaryAlias() throws { + let temporary = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(temporary) } + let alternatePath = temporary.path.hasPrefix("/private/") + ? String(temporary.path.dropFirst("/private".count)) + : "/private\(temporary.path)" + let privateAlias = URL( + fileURLWithPath: alternatePath, + isDirectory: true + ) + + let isEphemeral = ArtifactPathResolver(fileManager: .default).isEphemeral( + privateAlias.appendingPathComponent("preview.md"), + prefixes: [temporary.path] + ) + + #expect(isEphemeral) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactConfigurationSafetyTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactConfigurationSafetyTests.swift new file mode 100644 index 000000000000..5d0aa004cbfa --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactConfigurationSafetyTests.swift @@ -0,0 +1,87 @@ +import Darwin +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact configuration safety") +struct ArtifactConfigurationSafetyTests { + @Test("Oversized configuration fails closed without decoding") + func oversizedConfigurationDisablesAutomaticCapture() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let configurationURL = ArtifactStorePaths(projectRoot: root).configurationFile + try FileManager.default.createDirectory( + at: configurationURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + var data = Data(#"{"automaticCaptureEnabled":true}"#.utf8) + data.append(Data(repeating: 0x20, count: 64 * 1024)) + try data.write(to: configurationURL) + + let configuration = await LocalArtifactRepository().configuration(projectRoot: root) + + #expect(!configuration.automaticCaptureEnabled) + } + + @Test("Symlinked configuration fails closed") + func symlinkedConfigurationDisablesAutomaticCapture() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let target = try ArtifactTestSupport.write( + #"{"automaticCaptureEnabled":true}"#, + named: "outside-artifacts.json", + under: outside + ) + let configurationURL = ArtifactStorePaths(projectRoot: root).configurationFile + try FileManager.default.createDirectory( + at: configurationURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.createSymbolicLink( + at: configurationURL, + withDestinationURL: target + ) + + let configuration = await LocalArtifactRepository().configuration(projectRoot: root) + + #expect(!configuration.automaticCaptureEnabled) + } + + @Test("A FIFO configuration fails closed without waiting for a writer") + func fifoConfigurationDoesNotBlockRepository() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let configurationURL = ArtifactStorePaths(projectRoot: root).configurationFile + try FileManager.default.createDirectory( + at: configurationURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + guard Darwin.mkfifo(configurationURL.path, S_IRUSR | S_IWUSR) == 0 else { + throw POSIXError(.EIO) + } + let rescue = Task { + do { + try await Task.sleep(for: .seconds(1)) + } catch { + return + } + let descriptor = Darwin.open(configurationURL.path, O_RDWR | O_NONBLOCK | O_CLOEXEC) + guard descriptor >= 0 else { return } + defer { Darwin.close(descriptor) } + try? await Task.sleep(for: .seconds(1)) + } + let clock = ContinuousClock() + let startedAt = clock.now + + let configuration = await LocalArtifactRepository().configuration(projectRoot: root) + let elapsed = startedAt.duration(to: clock.now) + rescue.cancel() + await rescue.value + + #expect(!configuration.automaticCaptureEnabled) + #expect(elapsed < .milliseconds(500)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDeduplicationDepthTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDeduplicationDepthTests.swift new file mode 100644 index 000000000000..b345e5bb2b58 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDeduplicationDepthTests.swift @@ -0,0 +1,38 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact deduplication scan depth") +struct ArtifactDeduplicationDepthTests { + @Test("Moved-file recovery does not descend beyond the repository scan depth") + func boundsOpenDirectoryEnumerators() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + _ = try ArtifactTestSupport.write( + "same bytes", + named: "one/two/existing.md", + under: paths.filesystemRoot + ) + let source = try ArtifactTestSupport.write( + "same bytes", + named: "outside/incoming.md", + under: root + ) + let repository = LocalArtifactRepository(maximumScanDepth: 1) + + let outcome = try await repository.importFile( + sourceURL: source, + context: ArtifactCaptureContext(projectRoot: root), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + + guard case .copied = outcome else { + Issue.record("Expected a bounded scan to copy instead of finding the deep duplicate") + return + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDigestCalculatorTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDigestCalculatorTests.swift new file mode 100644 index 000000000000..7aad005023b9 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactDigestCalculatorTests.swift @@ -0,0 +1,38 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact digest calculator") +struct ArtifactDigestCalculatorTests { + @Test("SHA-256 bytes are encoded as lowercase hexadecimal") + func encodesDigest() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write("abc", named: "digest.txt", under: root) + + let digest = try ArtifactDigestCalculator(fileManager: .default).digest( + url: source, + expectedSize: 3, + allowedRoot: root + ) + + #expect(digest == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") + } + + @Test("Digest calculation never follows a symbolic link") + func rejectsSymbolicLinks() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let target = try ArtifactTestSupport.write("abc", named: "target.txt", under: root) + let link = root.appendingPathComponent("link.txt", isDirectory: false) + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + + #expect(throws: ArtifactStoreError.self) { + _ = try ArtifactDigestCalculator(fileManager: .default).digest( + url: link, + expectedSize: 3, + allowedRoot: root + ) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitBatchingTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitBatchingTests.swift new file mode 100644 index 000000000000..8e6d23aafefe --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitBatchingTests.swift @@ -0,0 +1,104 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact Git privacy batching") +struct ArtifactGitBatchingTests { + @Test("A multi-file automatic import uses one tracked check and two ignore checks") + func batchesGitPrivacyChecks() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".git", isDirectory: true), + withIntermediateDirectories: true + ) + let logURL = root.appendingPathComponent("git-invocations.log") + try Data().write(to: logURL) + let sources = try (1...3).map { index in + try ArtifactTestSupport.write( + "artifact \(index)", + named: "outside/artifact-\(index).md", + under: root + ) + } + let repository = LocalArtifactRepository( + fileManager: .default, + gitCommandRunner: ArtifactGitInvocationRecordingRunner(logURL: logURL) + ) + + let attempts = await repository.importFiles( + candidates: sources.map { ArtifactCandidate(sourceURL: $0, provenance: .created) }, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace", + sessionID: "session" + ), + configuration: .defaultValue, + maximumBatchBytes: nil, + capturedAt: Date(timeIntervalSince1970: 1) + ) + + #expect(attempts.allSatisfy { attempt in + guard case .imported(let outcome) = attempt else { return false } + return outcome.record != nil + }) + let invocations = try String(contentsOf: logURL, encoding: .utf8) + .split(separator: "\n") + .map(String.init) + #expect(invocations.filter { $0.contains("\u{1f}ls-files\u{1f}") }.count == 1) + #expect(invocations.filter { $0.contains("\u{1f}check-ignore\u{1f}") }.count == 2) + #expect(invocations.first { $0.contains("\u{1f}ls-files\u{1f}") }? + .hasPrefix("status\u{1f}") == true) + #expect(invocations.count == 3) + } + + @Test("A conservative preflight plan authorizes a deduplicated write plan") + func conservativePlanAuthorizesDeduplication() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let source = try ArtifactTestSupport.write( + "artifact", + named: "outside/artifact.md", + under: root + ) + let staged = try ArtifactTestSupport.write( + "artifact", + named: "staged/artifact.md", + under: root + ) + let prepared = PreparedArtifactImport( + candidate: ArtifactCandidate(sourceURL: source, provenance: .created), + snapshot: ArtifactSourceSnapshot(url: staged, size: 8), + digest: "digest" + ) + let planner = ArtifactWritePlanner( + fileManager: .default, + encoder: JSONEncoder(), + decoder: JSONDecoder(), + nodeBudget: 100 + ) + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace", + sessionID: "session" + ) + + let conservative = try planner.conservativePlan( + prepared: [prepared], + context: context, + paths: paths + ) + let refined = try planner.plan( + prepared: [prepared], + existingByDigest: [ + "digest": paths.filesystemRoot.appendingPathComponent("moved.md"), + ], + context: context, + paths: paths + ) + + #expect(conservative.authorizes(refined)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitExcludeConcurrencyTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitExcludeConcurrencyTests.swift new file mode 100644 index 000000000000..3d7a8e637700 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitExcludeConcurrencyTests.swift @@ -0,0 +1,37 @@ +import Darwin +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact Git exclude concurrency") +struct ArtifactGitExcludeConcurrencyTests { + @Test("A held legacy lock cannot block Git exclude preparation") + func heldLegacyLockDoesNotBlockPreparation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let info = root.appendingPathComponent(".git/info", isDirectory: true) + try FileManager.default.createDirectory(at: info, withIntermediateDirectories: true) + let lockURL = info.appendingPathComponent("cmux-artifacts.lock") + let descriptor = Darwin.open( + lockURL.path, + O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + #expect(descriptor >= 0) + guard descriptor >= 0 else { return } + defer { Darwin.close(descriptor) } + #expect(flock(descriptor, LOCK_EX | LOCK_NB) == 0) + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + + let exclude = try String( + contentsOf: info.appendingPathComponent("exclude"), + encoding: .utf8 + ) + #expect(exclude.contains(".cmux/**")) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitIgnoreSafetyTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitIgnoreSafetyTests.swift new file mode 100644 index 000000000000..b400ff5865d3 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitIgnoreSafetyTests.swift @@ -0,0 +1,115 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact Git exclude safety") +struct ArtifactGitIgnoreSafetyTests { + @Test("An ordinary Git directory cannot redirect excludes through commondir") + func rejectsCommonDirectoryInOrdinaryRepository() async throws { + let sandbox = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(sandbox) } + let project = sandbox.appendingPathComponent("repository", isDirectory: true) + let gitDirectory = project.appendingPathComponent(".git", isDirectory: true) + try FileManager.default.createDirectory(at: gitDirectory, withIntermediateDirectories: true) + try "../..\n".write( + to: gitDirectory.appendingPathComponent("commondir", isDirectory: false), + atomically: true, + encoding: .utf8 + ) + + await #expect( + throws: ArtifactStoreError.gitPrivacyUnavailable(gitDirectory.path) + ) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: project) + ) + } + + #expect(!FileManager.default.fileExists( + atPath: sandbox.appendingPathComponent("info/exclude", isDirectory: false).path + )) + } + + @Test("A symlinked Git info directory cannot redirect exclude writes") + func rejectsSymlinkedInfoDirectory() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let gitDirectory = root.appendingPathComponent(".git", isDirectory: true) + try FileManager.default.createDirectory(at: gitDirectory, withIntermediateDirectories: true) + let outsideExclude = try ArtifactTestSupport.write( + "preserve\n", + named: "exclude", + under: outside + ) + try FileManager.default.createSymbolicLink( + at: gitDirectory.appendingPathComponent("info", isDirectory: true), + withDestinationURL: outside + ) + + await #expect(throws: (any Error).self) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + } + + #expect(try String(contentsOf: outsideExclude, encoding: .utf8) == "preserve\n") + } + + @Test("A symlinked Git exclude file cannot redirect writes") + func rejectsSymlinkedExcludeFile() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let infoDirectory = root.appendingPathComponent(".git/info", isDirectory: true) + try FileManager.default.createDirectory(at: infoDirectory, withIntermediateDirectories: true) + let outsideExclude = try ArtifactTestSupport.write( + "preserve\n", + named: "outside-exclude", + under: outside + ) + try FileManager.default.createSymbolicLink( + at: infoDirectory.appendingPathComponent("exclude", isDirectory: false), + withDestinationURL: outsideExclude + ) + + await #expect(throws: (any Error).self) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + } + + #expect(try String(contentsOf: outsideExclude, encoding: .utf8) == "preserve\n") + } + + @Test("A hard-linked Git exclude file cannot redirect writes to its other inode") + func rejectsHardLinkedExcludeFile() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let infoDirectory = root.appendingPathComponent(".git/info", isDirectory: true) + try FileManager.default.createDirectory(at: infoDirectory, withIntermediateDirectories: true) + let unrelated = try ArtifactTestSupport.write( + "preserve\n", + named: "unrelated", + under: root + ) + let exclude = infoDirectory.appendingPathComponent("exclude", isDirectory: false) + try FileManager.default.linkItem(at: unrelated, to: exclude) + + await #expect(throws: (any Error).self) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + } + + #expect(try String(contentsOf: unrelated, encoding: .utf8) == "preserve\n") + #expect(try String(contentsOf: exclude, encoding: .utf8) == "preserve\n") + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitInvocationRecordingRunner.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitInvocationRecordingRunner.swift new file mode 100644 index 000000000000..0754997ed081 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitInvocationRecordingRunner.swift @@ -0,0 +1,30 @@ +import Foundation + +@testable import CmuxArtifacts + +/// Records Git privacy invocations without shared mutable test state. +struct ArtifactGitInvocationRecordingRunner: ArtifactGitCommandRunning { + let logURL: URL + + func terminationStatus(arguments: [String]) throws -> Int32 { + try record(mode: "status", arguments: arguments) + return arguments.contains("ls-files") ? 1 : 0 + } + + func run( + arguments: [String], + standardInput: Data? + ) throws -> (terminationStatus: Int32, standardOutput: Data) { + try record(mode: "output", arguments: arguments) + let output = arguments.contains("check-ignore") ? (standardInput ?? Data()) : Data() + return (0, output) + } + + private func record(mode: String, arguments: [String]) throws { + let handle = try FileHandle(forWritingTo: logURL) + try handle.seekToEnd() + let fields = [mode] + arguments + try handle.write(contentsOf: Data((fields.joined(separator: "\u{1f}") + "\n").utf8)) + try handle.close() + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitPrivacyTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitPrivacyTests.swift new file mode 100644 index 000000000000..5259523c69ba --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitPrivacyTests.swift @@ -0,0 +1,443 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact Git privacy") +struct ArtifactGitPrivacyTests { + @Test("Automatic capture stops when a higher-priority ignore negation exposes artifacts") + func rejectsNegatedArtifactIgnore() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + try "!/.cmux/\n!/.cmux/**/\n!/.cmux/**/artifacts/**\n".write( + to: root.appendingPathComponent(".gitignore"), + atomically: true, + encoding: .utf8 + ) + let source = try ArtifactTestSupport.write( + "secret", + named: "outside/secret.md", + under: root + ) + + let outcomes = await ArtifactCaptureService(store: LocalArtifactRepository()).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(outcomes.first?.record == nil) + } + + @Test("Automatic capture stops when the artifact store already contains tracked files") + func rejectsTrackedArtifactStore() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + _ = try ArtifactTestSupport.write( + "tracked", + named: "tracked.md", + under: root.appendingPathComponent(".cmux/session/artifacts") + ) + #expect(try runGit([ + "-C", root.path, "add", "--force", ".cmux/session/artifacts/tracked.md", + ]) == 0) + let source = try ArtifactTestSupport.write( + "new secret", + named: "outside/new-secret.md", + under: root + ) + + let outcomes = await ArtifactCaptureService(store: repository).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(outcomes.first?.record == nil) + } + + @Test("Automatic capture checks extension-specific ignore rules at its real destination") + func rejectsExposedJSONDestinationWhenSyntheticProbeIsIgnored() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace", + sessionID: "session" + ) + let resolver = ArtifactPathResolver(fileManager: .default) + let artifactDirectory = resolver.contentDirectory( + paths: ArtifactStorePaths(projectRoot: root), + context: context, + kind: .artifacts + ) + let artifactRelativePath = try #require( + resolver.relativePath(artifactDirectory, root: root) + ) + let sessionRelativePath = try #require( + resolver.relativePath(artifactDirectory.deletingLastPathComponent(), root: root) + ) + try """ + !/.cmux/ + !/\(sessionRelativePath)/ + !/\(artifactRelativePath)/ + /\(artifactRelativePath)/** + !/\(artifactRelativePath)/*.json + + """.write( + to: root.appendingPathComponent(".gitignore"), + atomically: true, + encoding: .utf8 + ) + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + ".cmux/.metadata/imports/.__cmux_probe__", + ]) == 0) + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + "\(artifactRelativePath)/secret.json", + ]) == 1) + let source = try ArtifactTestSupport.write( + "secret", + named: "outside/secret.json", + under: root + ) + + let outcomes = await ArtifactCaptureService(store: repository).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: context + ) + + #expect(outcomes.first == .skipped(.gitPrivacyUnavailable)) + let files = try await repository.snapshot(projectRoot: root) + .nodes + .flattenedArtifactNodes() + .filter { !$0.isDirectory } + #expect(files.isEmpty) + } + + @Test("Manual capture stops when an exact artifact destination is Git-visible") + func rejectsExposedManualDestination() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:manual-privacy", + agentName: "codex" + ) + let resolver = ArtifactPathResolver(fileManager: .default) + let artifactDirectory = resolver.contentDirectory( + paths: ArtifactStorePaths(projectRoot: root), + context: context, + kind: .artifacts + ) + let artifactRelativePath = try #require( + resolver.relativePath(artifactDirectory, root: root) + ) + let sessionRelativePath = try #require( + resolver.relativePath(artifactDirectory.deletingLastPathComponent(), root: root) + ) + let destinationRelativePath = "\(artifactRelativePath)/private.md" + try """ + !/.cmux/ + !/\(sessionRelativePath)/ + !/\(artifactRelativePath)/ + /\(artifactRelativePath)/** + !/\(artifactRelativePath)/*.md + + """.write( + to: root.appendingPathComponent(".gitignore"), + atomically: true, + encoding: .utf8 + ) + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", destinationRelativePath, + ]) == 1) + let source = try ArtifactTestSupport.write( + "private", + named: "outside/private.md", + under: root + ) + + await #expect(throws: ArtifactStoreError.gitPrivacyUnavailable( + ArtifactStorePaths(projectRoot: root).filesystemRoot.path + )) { + _ = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + } + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(destinationRelativePath).path + )) + } + + @Test("Note writes stop when an exact Markdown destination is Git-visible") + func rejectsExposedNoteDestination() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:note-privacy", + agentName: "codex" + ) + let resolver = ArtifactPathResolver(fileManager: .default) + let notesDirectory = resolver.contentDirectory( + paths: ArtifactStorePaths(projectRoot: root), + context: context, + kind: .notes + ) + let notesRelativePath = try #require( + resolver.relativePath(notesDirectory, root: root) + ) + let sessionRelativePath = try #require( + resolver.relativePath(notesDirectory.deletingLastPathComponent(), root: root) + ) + let destinationRelativePath = "\(notesRelativePath)/plan.md" + try """ + !/.cmux/ + !/\(sessionRelativePath)/ + !/\(notesRelativePath)/ + /\(notesRelativePath)/** + !/\(notesRelativePath)/*.md + + """.write( + to: root.appendingPathComponent(".gitignore"), + atomically: true, + encoding: .utf8 + ) + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", destinationRelativePath, + ]) == 1) + + await #expect(throws: ArtifactStoreError.gitPrivacyUnavailable( + ArtifactStorePaths(projectRoot: root).filesystemRoot.path + )) { + _ = try await repository.writeNote( + name: "plan", + text: "private", + mode: .replace, + context: context + ) + } + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(destinationRelativePath).path + )) + } + + @Test("Note writes never overwrite tracked local-store content") + func rejectsTrackedNoteDestination() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:tracked-note", + agentName: "codex" + ) + let notesDirectory = ArtifactPathResolver(fileManager: .default).contentDirectory( + paths: ArtifactStorePaths(projectRoot: root), + context: context, + kind: .notes + ) + let trackedNote = try ArtifactTestSupport.write( + "tracked original", + named: "plan.md", + under: notesDirectory + ) + let relativePath = try #require( + ArtifactPathResolver(fileManager: .default).relativePath(trackedNote, root: root) + ) + #expect(try runGit([ + "-C", root.path, "add", "--force", relativePath, + ]) == 0) + + await #expect(throws: ArtifactStoreError.gitPrivacyUnavailable( + ArtifactStorePaths(projectRoot: root).filesystemRoot.path + )) { + _ = try await repository.writeNote( + name: "plan", + text: "replacement", + mode: .replace, + context: context + ) + } + #expect(try String(contentsOf: trackedNote, encoding: .utf8) == "tracked original") + } + + @Test("Reorganized project files stay ignored while root configuration stays trackable") + func ignoresReorganizedFilesButNotConfiguration() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + _ = try ArtifactTestSupport.write( + "private", + named: "organized/final.txt", + under: root.appendingPathComponent(".cmux") + ) + _ = try ArtifactTestSupport.write( + #"{"automaticCaptureEnabled":false}"#, + named: "artifacts.json", + under: root.appendingPathComponent(".cmux") + ) + + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + ".cmux/organized/final.txt", + ]) == 0) + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + ".cmux/artifacts.json", + ]) == 1) + } + + @Test("Tracked reorganized content blocks later automatic capture") + func rejectsTrackedReorganizedStoreContent() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + _ = try ArtifactTestSupport.write( + "tracked", + named: "organized/final.txt", + under: root.appendingPathComponent(".cmux") + ) + #expect(try runGit([ + "-C", root.path, "add", "--force", ".cmux/organized/final.txt", + ]) == 0) + let source = try ArtifactTestSupport.write( + "new private output", + named: "outside/new.md", + under: root + ) + + let outcomes = await ArtifactCaptureService(store: repository).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(outcomes.first == .skipped(.gitPrivacyUnavailable)) + } + + @Test("Git exclude repairs append one complete canonical block and then stay idempotent") + func appendsCanonicalIgnoreBlockOnce() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let exclude = root.appendingPathComponent(".git/info/exclude") + try "!.cmux/artifacts.json\n".write( + to: exclude, + atomically: true, + encoding: .utf8 + ) + let repository = LocalArtifactRepository() + + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let repaired = try String(contentsOf: exclude, encoding: .utf8) + let repairedLines = repaired.split(separator: "\n").map(String.init) + #expect(Set(repairedLines) == Set(ArtifactGitIgnoreManager.ignoreEntries)) + #expect(repairedLines.count == Set(repairedLines).count) + + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + #expect(try String(contentsOf: exclude, encoding: .utf8) == repaired) + } + + @Test("Oversized Git excludes fail closed before mutation preparation") + func rejectsOversizedGitExclude() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let exclude = root.appendingPathComponent(".git/info/exclude") + try String(repeating: "# generated ignore\n", count: 140_000).write( + to: exclude, + atomically: true, + encoding: .utf8 + ) + + await #expect(throws: ArtifactStoreError.gitPrivacyUnavailable(exclude.path)) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + } + } + + @Test("Concurrent nested projects retain every shared Git exclusion") + func serializesSharedExcludeUpdates() async throws { + let root = try gitRepository() + defer { ArtifactTestSupport.remove(root) } + let projectRoots = (0..<64).map { index in + root.appendingPathComponent("projects/project-\(index)", isDirectory: true) + } + for projectRoot in projectRoots { + try FileManager.default.createDirectory( + at: projectRoot, + withIntermediateDirectories: true + ) + } + + try await withThrowingTaskGroup(of: Void.self) { group in + for projectRoot in projectRoots { + group.addTask { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: projectRoot) + ) + } + } + try await group.waitForAll() + } + + let exclude = try String( + contentsOf: root.appendingPathComponent(".git/info/exclude"), + encoding: .utf8 + ) + let lines = Set(exclude.split(separator: "\n").map(String.init)) + for index in projectRoots.indices { + #expect(lines.contains("projects/project-\(index)/.cmux/**")) + } + } + + private func gitRepository() throws -> URL { + let root = try ArtifactTestSupport.temporaryDirectory() + #expect(try runGit(["init", "--quiet", root.path]) == 0) + return root + } + + @discardableResult + private func runGit(_ arguments: [String]) throws -> Int32 { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = arguments + try process.run() + process.waitUntilExit() + return process.terminationStatus + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitSubmoduleTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitSubmoduleTests.swift new file mode 100644 index 000000000000..f75ad403658c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactGitSubmoduleTests.swift @@ -0,0 +1,80 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact Git submodule privacy") +struct ArtifactGitSubmoduleTests { + @Test("Manual artifact setup writes the submodule-local exclude") + func manualSetupIgnoresArtifactsInSubmodules() async throws { + let fixture = try makeFixture() + defer { ArtifactTestSupport.remove(fixture.root) } + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: fixture.submodule) + ) + + let exclude = fixture.gitDirectory.appendingPathComponent("info/exclude", isDirectory: false) + let contents = try String(contentsOf: exclude, encoding: .utf8) + let lines = Set(contents.split(separator: "\n").map(String.init)) + #expect(lines.isSuperset(of: Set(ArtifactGitIgnoreManager.ignoreEntries))) + } + + @Test("Automatic imports remain private inside submodules") + func automaticCaptureUsesTheSubmoduleExclude() async throws { + let fixture = try makeFixture() + defer { ArtifactTestSupport.remove(fixture.root) } + let source = try ArtifactTestSupport.write( + "private plan", + named: "outside/plan.md", + under: fixture.root + ) + let outcomes = await ArtifactCaptureService(store: LocalArtifactRepository()).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: ArtifactCaptureContext(projectRoot: fixture.submodule) + ) + + let record = try #require(outcomes.first?.record) + #expect(try ArtifactTestSupport.runGit([ + "-C", fixture.submodule.path, + "check-ignore", "--quiet", "--", + ".cmux/\(record.relativePath)", + ]) == 0) + } + + private func makeFixture() throws -> (root: URL, submodule: URL, gitDirectory: URL) { + let root = try ArtifactTestSupport.temporaryDirectory() + let source = root.appendingPathComponent("source", isDirectory: true) + let superproject = root.appendingPathComponent("super", isDirectory: true) + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: superproject, withIntermediateDirectories: true) + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", source.path]) == 0) + _ = try ArtifactTestSupport.write("seed", named: "README.md", under: source) + #expect(try ArtifactTestSupport.runGit(["-C", source.path, "add", "README.md"]) == 0) + #expect(try ArtifactTestSupport.runGit([ + "-C", source.path, + "-c", "user.name=cmux tests", + "-c", "user.email=cmux@example.invalid", + "commit", "--quiet", "-m", "seed", + ]) == 0) + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", superproject.path]) == 0) + #expect(try ArtifactTestSupport.runGit([ + "-c", "protocol.file.allow=always", + "-C", superproject.path, + "submodule", "add", "--quiet", source.path, "child", + ]) == 0) + let submodule = superproject.appendingPathComponent("child", isDirectory: true) + let marker = try String( + contentsOf: submodule.appendingPathComponent(".git", isDirectory: false), + encoding: .utf8 + ) + let rawGitDirectory = marker.dropFirst("gitdir:".count) + .trimmingCharacters(in: .whitespacesAndNewlines) + let gitDirectory = URL( + fileURLWithPath: rawGitDirectory, + relativeTo: submodule + ).standardizedFileURL + return (root, submodule, gitDirectory) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactImportStagingRecoveryTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactImportStagingRecoveryTests.swift new file mode 100644 index 000000000000..5c7089990980 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactImportStagingRecoveryTests.swift @@ -0,0 +1,89 @@ +import Darwin +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact import staging recovery") +struct ArtifactImportStagingRecoveryTests { + @Test("A second import staging lease cannot overlap the first batch") + func serializesStagingLeases() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let first = try ArtifactImportStagingLease( + root: root, + fileManager: .default + ) + defer { first.finish() } + + #expect(throws: ArtifactStoreError.storeBusy(root.path)) { + _ = try ArtifactImportStagingLease( + root: root, + fileManager: .default + ) + } + } + + @Test("Reads preserve staging while preparation reclaims only unlocked batches") + func reclaimsOrphanWhilePreservingActiveBatch() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let stagingRoot = ArtifactStorePaths(projectRoot: root).importStagingRoot + try FileManager.default.createDirectory(at: stagingRoot, withIntermediateDirectories: true) + let orphan = stagingRoot.appendingPathComponent("orphan.artifact-import", isDirectory: true) + let active = stagingRoot.appendingPathComponent("active.artifact-import", isDirectory: true) + try FileManager.default.createDirectory(at: orphan, withIntermediateDirectories: false) + try FileManager.default.createDirectory(at: active, withIntermediateDirectories: false) + _ = FileManager.default.createFile( + atPath: orphan.appendingPathComponent(".lease").path, + contents: Data() + ) + let activeLeasePath = active.appendingPathComponent(".lease").path + _ = FileManager.default.createFile(atPath: activeLeasePath, contents: Data()) + let activeDescriptor = Darwin.open(activeLeasePath, O_RDWR | O_CLOEXEC | O_NOFOLLOW) + guard activeDescriptor >= 0 else { + Issue.record("Could not open the active import lease") + return + } + defer { + _ = flock(activeDescriptor, LOCK_UN) + _ = close(activeDescriptor) + } + #expect(flock(activeDescriptor, LOCK_EX | LOCK_NB) == 0) + + let repository = LocalArtifactRepository() + _ = try await repository.snapshot(projectRoot: root) + + #expect(FileManager.default.fileExists(atPath: orphan.path)) + #expect(FileManager.default.fileExists(atPath: active.path)) + + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + + #expect(!FileManager.default.fileExists(atPath: orphan.path)) + #expect(FileManager.default.fileExists(atPath: active.path)) + } + + @Test("Staging recovery never follows a stale batch symlink") + func rejectsSymlinkedStaleBatch() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let stagingRoot = ArtifactStorePaths(projectRoot: root).importStagingRoot + try FileManager.default.createDirectory(at: stagingRoot, withIntermediateDirectories: true) + let sentinel = try ArtifactTestSupport.write("keep", named: "sentinel.txt", under: outside) + let stale = stagingRoot.appendingPathComponent("stale.artifact-import", isDirectory: true) + try FileManager.default.createSymbolicLink(at: stale, withDestinationURL: outside) + + ArtifactImportStagingCleaner( + fileManager: .default, + now: { Date(timeIntervalSince1970: 10_000) }, + malformedEntryGracePeriod: 0 + ).reclaimAbandonedBatches(root: stagingRoot) + + #expect(try String(contentsOf: sentinel, encoding: .utf8) == "keep") + #expect(!FileManager.default.fileExists(atPath: stale.path)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProjectLocatorTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProjectLocatorTests.swift new file mode 100644 index 000000000000..d70cbe73bdf8 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProjectLocatorTests.swift @@ -0,0 +1,63 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact project locator") +struct ArtifactProjectLocatorTests { + @Test("Nearest cmux directory wins over an outer Git root") + func locatesNearestCmuxDirectory() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + try FileManager.default.createDirectory(at: root.appendingPathComponent(".git"), withIntermediateDirectories: true) + let project = root.appendingPathComponent("nested/project") + try FileManager.default.createDirectory(at: project.appendingPathComponent(".cmux"), withIntermediateDirectories: true) + let child = project.appendingPathComponent("Sources/Feature") + try FileManager.default.createDirectory(at: child, withIntermediateDirectories: true) + + let located = ArtifactProjectLocator().projectRoot(startingAt: child, fileManager: .default) + + #expect(located == project.standardizedFileURL) + } + + @Test("A nested Git project wins over an outer cmux directory") + func locatesNearestGitDirectory() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".cmux"), + withIntermediateDirectories: true + ) + let project = root.appendingPathComponent("nested/project") + try FileManager.default.createDirectory( + at: project.appendingPathComponent(".git"), + withIntermediateDirectories: true + ) + let child = project.appendingPathComponent("Sources/Feature") + try FileManager.default.createDirectory(at: child, withIntermediateDirectories: true) + + let located = ArtifactProjectLocator().projectRoot(startingAt: child, fileManager: .default) + + #expect(located == project.standardizedFileURL) + } + + @Test("Ancestor traversal reaches the filesystem root exactly once") + func traversesToRootOnce() { + let ancestors = Array( + ArtifactAncestorDirectories(startingAt: URL(fileURLWithPath: "/alpha/beta", isDirectory: true)) + ) + + #expect(ancestors.map(\.path) == ["/alpha/beta", "/alpha", "/"]) + } + + @Test("A directory without project markers falls back to itself") + func fallsBackWithoutMarkers() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let child = root.appendingPathComponent("nested/project", isDirectory: true) + try FileManager.default.createDirectory(at: child, withIntermediateDirectories: true) + + let located = ArtifactProjectLocator().projectRoot(startingAt: child, fileManager: .default) + + #expect(located == child.standardizedFileURL) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProvenanceRecorderCancellationTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProvenanceRecorderCancellationTests.swift new file mode 100644 index 000000000000..42fe2097fce6 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactProvenanceRecorderCancellationTests.swift @@ -0,0 +1,39 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact provenance cancellation") +struct ArtifactProvenanceRecorderCancellationTests { + @Test("Canceled provenance reads propagate cancellation") + func canceledReadPropagatesCancellation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory(at: paths.provenanceRoot, withIntermediateDirectories: true) + let recorder = ArtifactProvenanceRecorder( + fileManager: .default, + encoder: JSONEncoder(), + decoder: JSONDecoder() + ) + let document = ArtifactMetadataDocument( + version: 1, + digest: "digest", + lastKnownRelativePath: "plan.md", + size: 4, + events: [] + ) + try JSONEncoder().encode(document).write( + to: recorder.metadataURL(paths: paths, digest: "digest") + ) + + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try recorder.document(paths: paths, digest: "digest") + } + + await #expect(throws: CancellationError.self) { + _ = try await task.value + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactRepositorySafetyTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactRepositorySafetyTests.swift new file mode 100644 index 000000000000..544007abd88b --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactRepositorySafetyTests.swift @@ -0,0 +1,531 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact repository safety") +struct ArtifactRepositorySafetyTests { + @Test("Provenance rejects valid metadata with mismatched identity") + func rejectsMismatchedProvenanceIdentity() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.provenanceRoot, + withIntermediateDirectories: true + ) + let metadataURL = paths.provenanceRoot.appendingPathComponent("digest.json") + + for (embeddedDigest, embeddedSize) in [("other-digest", Int64(4)), ("digest", Int64(5))] { + let existing = ArtifactMetadataDocument( + version: 1, + digest: embeddedDigest, + lastKnownRelativePath: "old/path.md", + size: embeddedSize, + events: [] + ) + let existingData = try JSONEncoder().encode(existing) + try existingData.write(to: metadataURL) + + #expect(throws: ArtifactStoreError.corruptProvenance(metadataURL.path)) { + try recorder.record( + paths: paths, + digest: "digest", + relativePath: "workspace/session/plan.md", + size: 4, + event: event + ) + } + #expect(try Data(contentsOf: metadataURL) == existingData) + } + } + + @Test("Corrupt provenance is preserved instead of overwritten") + func preservesCorruptProvenance() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.provenanceRoot, + withIntermediateDirectories: true + ) + let metadataURL = paths.provenanceRoot.appendingPathComponent("digest.json") + let corruptData = Data("{truncated".utf8) + try corruptData.write(to: metadataURL) + + #expect(throws: ArtifactStoreError.corruptProvenance(metadataURL.path)) { + try recorder.record( + paths: paths, + digest: "digest", + relativePath: "workspace/session/plan.md", + size: 4, + event: event + ) + } + #expect(try Data(contentsOf: metadataURL) == corruptData) + } + + @Test("Provenance reads reject final symlinks") + func rejectsSymlinkedProvenanceDocument() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory(at: paths.provenanceRoot, withIntermediateDirectories: true) + let valid = ArtifactMetadataDocument( + version: 1, + digest: "digest", + lastKnownRelativePath: "plan.md", + size: 4, + events: [] + ) + let target = outside.appendingPathComponent("outside.json") + try JSONEncoder().encode(valid).write(to: target) + let metadataURL = recorder.metadataURL(paths: paths, digest: "digest") + try FileManager.default.createSymbolicLink(at: metadataURL, withDestinationURL: target) + + #expect(throws: ArtifactStoreError.corruptProvenance(metadataURL.path)) { + _ = try recorder.document(paths: paths, digest: "digest") + } + } + + @Test("Provenance reads reject oversized documents") + func rejectsOversizedProvenanceDocument() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.provenanceRoot, + withIntermediateDirectories: true + ) + let metadataURL = recorder.metadataURL(paths: paths, digest: "digest") + try Data(count: 256 * 1024 + 1) + .write(to: metadataURL) + + #expect(throws: ArtifactStoreError.corruptProvenance(metadataURL.path)) { + _ = try recorder.document(paths: paths, digest: "digest") + } + } + + @Test("Repeated provenance stays within its readable document limit") + func boundsWrittenProvenanceDocument() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let largeID = String(repeating: "session", count: 700) + let largeEvent = ArtifactProvenanceEvent( + sourcePath: "/tmp/plan.md", + workspaceID: largeID, + sessionID: largeID, + provenance: .created, + capturedAt: Date(timeIntervalSince1970: 1) + ) + for _ in 0..<100 { + try recorder.record( + paths: paths, digest: "digest", relativePath: "plan.md", + size: 4, event: largeEvent + ) + } + let metadataURL = recorder.metadataURL(paths: paths, digest: "digest") + + #expect(try Data(contentsOf: metadataURL).count <= 256 * 1024) + #expect(try recorder.document(paths: paths, digest: "digest") != nil) + } + + @Test("Repository rejects corrupt provenance before moving another file") + func rejectsCorruptProvenanceBeforePersistence() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "same bytes", + named: "plan.md", + under: root.appendingPathComponent("outside") + ) + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace", + sessionID: "session" + ) + let first = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .created, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let record = try #require(first.record) + let paths = ArtifactStorePaths(projectRoot: root) + let metadataURL = paths.provenanceRoot.appendingPathComponent("\(record.digest).json") + let corruptData = Data("{truncated".utf8) + try corruptData.write(to: metadataURL) + let filesBefore = try await repository.snapshot(projectRoot: root) + .nodes + .flattenedArtifactNodes() + .filter { !$0.isDirectory } + + await #expect(throws: ArtifactStoreError.self) { + try await repository.importFile( + sourceURL: source, + context: context, + provenance: .created, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + + let filesAfter = try await repository.snapshot(projectRoot: root) + .nodes + .flattenedArtifactNodes() + .filter { !$0.isDirectory } + #expect(filesAfter.map(\.relativePath) == filesBefore.map(\.relativePath)) + #expect(try Data(contentsOf: metadataURL) == corruptData) + } + + @Test("Provenance rejects a symlinked cmux parent before writing") + func rejectsSymlinkedCmuxParent() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + try FileManager.default.createSymbolicLink( + at: root.appendingPathComponent(".cmux", isDirectory: true), + withDestinationURL: outside + ) + let paths = ArtifactStorePaths(projectRoot: root) + + #expect(throws: ArtifactStoreError.self) { + try recorder.record( + paths: paths, + digest: "digest", + relativePath: "workspace/session/plan.md", + size: 4, + event: event + ) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty) + } + + @Test("Mutation leases reject deletion through a symlinked parent") + func rejectsSymlinkedDeletionParent() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.filesystemRoot, + withIntermediateDirectories: true + ) + let outsideFile = try ArtifactTestSupport.write( + "outside", + named: "outside.md", + under: outside + ) + try FileManager.default.createSymbolicLink( + at: paths.filesystemRoot.appendingPathComponent("session", isDirectory: true), + withDestinationURL: outside + ) + + let lease = try ArtifactStoreMutationLease(directory: paths.filesystemRoot) + defer { lease.finish() } + #expect(throws: ArtifactStoreError.self) { + try lease.unlink(relativePath: "session/outside.md") + } + #expect(FileManager.default.fileExists(atPath: outsideFile.path)) + #expect(try String(contentsOf: outsideFile, encoding: .utf8) == "outside") + } + + @Test("Tree scans stream direct children within the node budget") + func streamsBoundedDirectoryChildren() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + for index in 0..<20 { + _ = try ArtifactTestSupport.write( + "artifact \(index)", + named: "artifact-\(index).txt", + under: paths.filesystemRoot + ) + } + let fileManager = DirectoryEnumerationRecordingFileManager() + let snapshot = try ArtifactTreeScanner( + fileManager: fileManager, + maximumDepth: 4, + nodeBudget: 3 + ).snapshot(paths: paths) + + #expect(snapshot.nodes.count == 3) + #expect(snapshot.isTruncated) + #expect(fileManager.eagerDirectoryReadCount == 0) + } + + @Test("Capture reports store-confinement failures distinctly") + func reportsStoreConfinementFailure() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + try FileManager.default.createSymbolicLink( + at: root.appendingPathComponent(".cmux", isDirectory: true), + withDestinationURL: outside + ) + let source = try ArtifactTestSupport.write("safe", named: "safe.md", under: root) + + let outcomes = await ArtifactCaptureService(store: LocalArtifactRepository()).capture( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .created)], + context: ArtifactCaptureContext(projectRoot: root) + ) + + guard case .skipped(let reason) = outcomes.first else { + Issue.record("Expected the unsafe store to reject capture") + return + } + #expect(reason.rawValue == "pathOutsideStore") + } + + @Test("Git exclude paths follow canonical project aliases") + func ignoresCanonicalProjectAlias() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try runGit(["init", "--quiet", root.path]) == 0) + let project = root.appendingPathComponent("nested/project", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + let alias = root.appendingPathComponent("project-alias", isDirectory: true) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: project) + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: alias)) + _ = try ArtifactTestSupport.write( + "private", + named: "organized/final.txt", + under: project.appendingPathComponent(".cmux") + ) + + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + "nested/project/.cmux/organized/final.txt", + ]) == 0) + } + + @Test("Git excludes artifact stores in paths containing pattern metacharacters") + func escapesGitIgnorePatternCharacters() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + try runGit(["init", "--quiet", root.path]) + let project = root.appendingPathComponent("nested[1]/project?", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: project)) + let artifact = try ArtifactTestSupport.write( + "private", + named: "plan.md", + under: project.appendingPathComponent(".cmux/session/artifacts") + ) + let relativePath = try #require( + ArtifactPathResolver(fileManager: .default).relativePath(artifact, root: root) + ) + + #expect(try runGit(["-C", root.path, "check-ignore", "--quiet", "--", relativePath]) == 0) + } + + @Test("Unreadable Git exclude content is preserved") + func preservesNonUTF8GitExcludeContent() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let info = root.appendingPathComponent(".git/info", isDirectory: true) + try FileManager.default.createDirectory(at: info, withIntermediateDirectories: true) + let exclude = info.appendingPathComponent("exclude", isDirectory: false) + let existing = Data([0xFF, 0xFE, 0x0A]) + try existing.write(to: exclude) + + await #expect(throws: (any Error).self) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: root)) + } + #expect(try Data(contentsOf: exclude) == existing) + } + + @Test("Malformed configuration fails closed for automatic capture") + func malformedConfigurationDisablesAutomaticCapture() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + _ = try ArtifactTestSupport.write( + #"{"automaticCaptureEnabled":false,"maximumFileBytes":"invalid"}"#, + named: "artifacts.json", + under: root.appendingPathComponent(".cmux") + ) + + let configuration = await LocalArtifactRepository().configuration(projectRoot: root) + + #expect(!configuration.automaticCaptureEnabled) + } + + @Test("Canceled scans stop before traversing the artifact tree") + func canceledTreeScanThrowsCancellation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + _ = try ArtifactTestSupport.write("artifact", named: "one.txt", under: paths.filesystemRoot) + let scan = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try ArtifactTreeScanner( + fileManager: .default, + maximumDepth: 4, + nodeBudget: 100 + ).snapshot(paths: paths) + } + + await #expect(throws: CancellationError.self) { + _ = try await scan.value + } + } + + @Test("Canceled content search stops before inspecting artifacts") + func canceledContentSearchThrowsCancellation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let node = ArtifactTestSupport.artifactNode( + root: root, + relativePath: "one.txt", + kind: .text + ) + let snapshot = ArtifactSnapshot( + projectRoot: root, + filesystemRoot: ArtifactStorePaths(projectRoot: root).filesystemRoot, + nodes: [node], + isTruncated: false + ) + let search = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try ArtifactSearchEngine( + configuration: .defaultValue, + fileManager: .default + ).results( + snapshot: snapshot, + query: "one" + ) + } + + await #expect(throws: CancellationError.self) { + _ = try await search.value + } + } + + @Test("A provenance failure rolls back the newly copied artifact") + func rollsBackCopyWhenProvenanceFails() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "artifact", + named: "plan.md", + under: root.appendingPathComponent("outside") + ) + let digest = try ArtifactDigestCalculator(fileManager: .default).digest( + url: source, + expectedSize: 8, + allowedRoot: root + ) + let fileManager = ProvenanceCorruptingFileManager( + metadataURL: ArtifactStorePaths(projectRoot: root).provenanceRoot + .appendingPathComponent("\(digest).json") + ) + let repository = LocalArtifactRepository(fileManager: fileManager) + + await #expect(throws: ArtifactStoreError.self) { + try await repository.importFile( + sourceURL: source, + context: ArtifactCaptureContext(projectRoot: root), + provenance: .created, + configuration: .defaultValue, + capturedAt: .now + ) + } + let files = try await repository.snapshot(projectRoot: root) + .nodes + .flattenedArtifactNodes() + .filter { !$0.isDirectory } + #expect(files.isEmpty) + } + + @Test("Untrusted Git directory redirects are not mutated") + func rejectsUntrustedGitDirectoryRedirect() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let other = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(other) } + let otherGit = other.appendingPathComponent(".git", isDirectory: true) + try FileManager.default.createDirectory(at: otherGit, withIntermediateDirectories: true) + try "gitdir: \(otherGit.path)\n".write( + to: root.appendingPathComponent(".git"), + atomically: true, + encoding: .utf8 + ) + + await #expect( + throws: ArtifactStoreError.gitPrivacyUnavailable( + root.appendingPathComponent(".git").path + ) + ) { + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: root)) + } + + #expect(!FileManager.default.fileExists( + atPath: otherGit.appendingPathComponent("info/exclude").path + )) + } + + @MainActor + @Test("A canceled deduplication scan stops before visiting files") + func cancelsDeduplicationScan() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + _ = try ArtifactTestSupport.write("same", named: "one.txt", under: paths.filesystemRoot) + let scanTask = Task { + var visits = 0 + try ArtifactDeduplicationScanner(fileManager: .default).scanFiles( + paths: paths, + matchingSizes: [4] + ) { _, _ in + visits += 1 + return false + } + return visits + } + scanTask.cancel() + + await #expect(throws: CancellationError.self) { + _ = try await scanTask.value + } + } + + private var recorder: ArtifactProvenanceRecorder { + ArtifactProvenanceRecorder( + fileManager: .default, + encoder: JSONEncoder(), + decoder: JSONDecoder() + ) + } + + private var event: ArtifactProvenanceEvent { + ArtifactProvenanceEvent( + sourcePath: "/tmp/plan.md", + workspaceID: "workspace", + sessionID: "session", + provenance: .created, + capturedAt: Date(timeIntervalSince1970: 1) + ) + } + + @discardableResult + private func runGit(_ arguments: [String]) throws -> Int32 { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = arguments + try process.run() + process.waitUntilExit() + return process.terminationStatus + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactReservedFilenameTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactReservedFilenameTests.swift new file mode 100644 index 000000000000..e0ffdd737496 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactReservedFilenameTests.swift @@ -0,0 +1,66 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact reserved filenames") +struct ArtifactReservedFilenameTests { + @Test("A first import named like the session marker preserves both files") + func firstImportNamedLikeSessionMarker() async throws { + try await assertFirstImport( + named: ArtifactPathResolver.sessionMarkerName, + expectedArtifactName: "_session-2.json" + ) + } + + @Test("A case-variant session marker name cannot alias the managed marker") + func firstImportNamedLikeCaseVariantSessionMarker() async throws { + try await assertFirstImport( + named: "_SESSION.JSON", + expectedArtifactName: "_SESSION-2.JSON" + ) + } + + @Test("A first import named like the workspace marker remains visible") + func firstImportNamedLikeWorkspaceMarker() async throws { + try await assertFirstImport( + named: ArtifactPathResolver.workspaceMarkerName, + expectedArtifactName: "_workspace-2.json" + ) + } + + private func assertFirstImport( + named sourceName: String, + expectedArtifactName: String + ) async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "user artifact", + named: sourceName, + under: root.appendingPathComponent("outside") + ) + + let outcome = try await LocalArtifactRepository().importFile( + sourceURL: source, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:reserved", + sessionID: "session:reserved" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1_700_000_000) + ) + + let record = try #require(outcome.record) + #expect(record.relativePath.hasSuffix("/\(expectedArtifactName)")) + let artifactURL = root.appendingPathComponent(".cmux/\(record.relativePath)") + #expect(try String(contentsOf: artifactURL, encoding: .utf8) == "user artifact") + let markerURL = artifactURL.deletingLastPathComponent() + .deletingLastPathComponent() + .appendingPathComponent(ArtifactPathResolver.sessionMarkerName) + #expect(FileManager.default.fileExists(atPath: markerURL.path)) + #expect(markerURL != artifactURL) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactScanBoundaryTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactScanBoundaryTests.swift new file mode 100644 index 000000000000..d08e13f7bd9e --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactScanBoundaryTests.swift @@ -0,0 +1,122 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("Artifact scan boundaries") +struct ArtifactScanBoundaryTests { + @Test("Exact relative paths resolve without a recursive tree scan") + func resolvesExactRelativePathBeyondDepthBudget() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + _ = try ArtifactTestSupport.write( + "target", + named: "one/two/target.md", + under: ArtifactStorePaths(projectRoot: root).filesystemRoot + ) + let repository = LocalArtifactRepository(maximumScanDepth: 1) + + let node = try await repository.resolve( + projectRoot: root, + name: "one/two/target.md" + ) + + #expect(node.relativePath == "one/two/target.md") + } + + @Test("Exact paths cannot expose cmux-managed metadata") + func exactResolutionHidesManagedMetadata() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let metadata = try ArtifactTestSupport.write( + #"{"sourcePath":"/tmp/private"}"#, + named: ".metadata/provenance/private.json", + under: ArtifactStorePaths(projectRoot: root).filesystemRoot + ) + + await #expect(throws: ArtifactStoreError.artifactNotFound( + ".metadata/provenance/private.json" + )) { + _ = try await LocalArtifactRepository().resolve( + projectRoot: root, + name: ".metadata/provenance/private.json" + ) + } + #expect(FileManager.default.fileExists(atPath: metadata.path)) + } + + @Test("Bounded repository snapshots and searches fail instead of appearing complete") + func incompleteScansFailExplicitly() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let artifactRoot = ArtifactStorePaths(projectRoot: root).filesystemRoot + _ = try ArtifactTestSupport.write("one", named: "one.md", under: artifactRoot) + _ = try ArtifactTestSupport.write("two", named: "two.md", under: artifactRoot) + let repository = LocalArtifactRepository(nodeBudget: 1) + + await #expect(throws: ArtifactStoreError.scanIncomplete(artifactRoot.path)) { + _ = try await repository.snapshot(projectRoot: root) + } + await #expect(throws: ArtifactStoreError.scanIncomplete(artifactRoot.path)) { + _ = try await repository.search(projectRoot: root, query: "one") + } + } + + @Test("Tree snapshots retain identity across same-path replacements with preserved mtime") + func snapshotsDistinguishSamePathReplacement() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let file = paths.filesystemRoot.appendingPathComponent("preview.png", isDirectory: false) + let fixedDate = Date(timeIntervalSince1970: 1_234_567) + _ = try ArtifactTestSupport.write("first", named: "preview.png", under: paths.filesystemRoot) + try FileManager.default.setAttributes( + [.modificationDate: fixedDate], + ofItemAtPath: file.path + ) + let scanner = ArtifactTreeScanner( + fileManager: .default, + maximumDepth: 4, + nodeBudget: 100 + ) + let firstNode = try #require(scanner.snapshot(paths: paths).nodes.first) + + _ = try ArtifactTestSupport.write("second", named: "preview.png", under: paths.filesystemRoot) + try FileManager.default.setAttributes( + [.modificationDate: fixedDate], + ofItemAtPath: file.path + ) + let secondNode = try #require(scanner.snapshot(paths: paths).nodes.first) + + #expect(firstNode.modifiedAt == secondNode.modifiedAt) + #expect(firstNode.fileIdentity != nil) + #expect(secondNode.fileIdentity != nil) + #expect(firstNode.fileIdentity != secondNode.fileIdentity) + } + + @MainActor + @Test("The sidebar reports a bounded partial tree as a load failure") + func sidebarRejectsIncompleteTree() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + _ = try ArtifactTestSupport.write( + "target", + named: "one/two/target.md", + under: ArtifactStorePaths(projectRoot: root).filesystemRoot + ) + let repository = LocalArtifactRepository(maximumScanDepth: 1) + let model = ArtifactSidebarModel( + store: repository, + captureService: ArtifactCaptureService(store: repository), + searchDebounce: .zero + ) + + await model.bind(workspace: ArtifactSidebarWorkspace( + id: "workspace", + title: "Workspace", + workingDirectory: root + )) + + #expect(model.phase == .failed) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSearchEngineTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSearchEngineTests.swift new file mode 100644 index 000000000000..f546010b40b4 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSearchEngineTests.swift @@ -0,0 +1,156 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact search engine") +struct ArtifactSearchEngineTests { + @Test("Content search rejects a file that grew beyond its stale snapshot size") + func rejectsFileGrowthAfterSnapshot() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let url = try ArtifactTestSupport.write("x", named: "artifact.txt", under: root) + let staleNode = node(url: url) + try "needle".write(to: url, atomically: true, encoding: .utf8) + let snapshot = ArtifactSnapshot( + projectRoot: root, + filesystemRoot: root, + nodes: [staleNode], + isTruncated: false + ) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.contentSearchMaximumBytes = 2 + configuration.contentSearchTotalMaximumBytes = 2 + + let results = try ArtifactSearchEngine( + configuration: configuration, + fileManager: .default + ).results( + snapshot: snapshot, + query: "needle" + ) + + #expect(results.isEmpty) + } + + @Test("Content search does not follow a symlink outside the artifact store") + func rejectsSymlinkReplacement() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let store = root.appendingPathComponent("store", isDirectory: true) + let outside = try ArtifactTestSupport.write("needle", named: "outside.txt", under: root) + try FileManager.default.createDirectory(at: store, withIntermediateDirectories: true) + let link = store.appendingPathComponent("artifact.txt") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside) + let linkedNode = ArtifactNode( + id: "artifact.txt", + name: "artifact.txt", + relativePath: "artifact.txt", + absolutePath: link.path, + isDirectory: false, + fileKind: .text, + size: Int64("needle".utf8.count), + modifiedAt: nil, + children: [] + ) + let snapshot = ArtifactSnapshot( + projectRoot: root, + filesystemRoot: store, + nodes: [linkedNode], + isTruncated: false + ) + + let results = try ArtifactSearchEngine( + configuration: .defaultValue, + fileManager: .default + ).results( + snapshot: snapshot, + query: "needle" + ) + + #expect(results.isEmpty) + } + + @Test("Content search enforces its aggregate byte budget") + func enforcesAggregateContentBudget() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let firstURL = try ArtifactTestSupport.write("haystack", named: "a.txt", under: root) + let secondURL = try ArtifactTestSupport.write("needle", named: "b.txt", under: root) + let nodes = [node(url: firstURL), node(url: secondURL)] + let snapshot = ArtifactSnapshot( + projectRoot: root, + filesystemRoot: root, + nodes: nodes, + isTruncated: false + ) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.contentSearchTotalMaximumBytes = Int64("haystack".utf8.count) + + let capped = try ArtifactSearchEngine( + configuration: configuration, + fileManager: .default + ).results( + snapshot: snapshot, + query: "needle" + ) + + #expect(capped.isEmpty) + configuration.contentSearchTotalMaximumBytes += Int64("needle".utf8.count) + let uncapped = try ArtifactSearchEngine( + configuration: configuration, + fileManager: .default + ).results( + snapshot: snapshot, + query: "needle" + ) + #expect(uncapped.map(\.node.name) == ["b.txt"]) + #expect(uncapped.first?.matchedContent == true) + } + + @Test("Oversized queries use one bounded prefix for every candidate") + func boundsQueryBeforeScoring() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let query = String(repeating: "a", count: 4_096) + let node = ArtifactNode( + id: "large-name", + name: query + ".png", + relativePath: query + ".png", + absolutePath: root.appendingPathComponent("large-name.png").path, + isDirectory: false, + fileKind: .image, + size: 1, + modifiedAt: nil, + children: [] + ) + let snapshot = ArtifactSnapshot( + projectRoot: root, + filesystemRoot: root, + nodes: [node], + isTruncated: false + ) + let engine = ArtifactSearchEngine(configuration: .defaultValue, fileManager: .default) + + let oversizedScore = try #require(engine.results(snapshot: snapshot, query: query).first?.score) + let boundedScore = try #require( + engine.results(snapshot: snapshot, query: String(query.prefix(512))).first?.score + ) + + #expect(oversizedScore == boundedScore) + } + + private func node(url: URL) -> ArtifactNode { + let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) + return ArtifactNode( + id: url.lastPathComponent, + name: url.lastPathComponent, + relativePath: url.lastPathComponent, + absolutePath: url.path, + isDirectory: false, + fileKind: .text, + size: size, + modifiedAt: nil, + children: [] + ) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSidebarModelTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSidebarModelTests.swift new file mode 100644 index 000000000000..f22ee549adea --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactSidebarModelTests.swift @@ -0,0 +1,281 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact sidebar model") +@MainActor +struct ArtifactSidebarModelTests { + @Test("Model teardown is safe when its final reference is released off the main actor") + nonisolated func releasesOffMainActor() async { + await Task.detached { + let model = await MainActor.run { + ArtifactSidebarModel( + store: SidebarArtifactStore( + root: URL(fileURLWithPath: "/tmp/artifact-sidebar-release-test"), + nodes: [] + ), + captureService: SidebarCaptureSpy() + ) + } + + withExtendedLifetime(model) {} + }.value + } + + @Test("Binding projects an expanded immutable tree") + func bindsExpandedTree() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let file = ArtifactTestSupport.artifactNode(root: root, relativePath: "session/plan.md", kind: .markdown) + let folder = ArtifactTestSupport.artifactFolder(root: root, relativePath: "session", children: [file]) + let store = SidebarArtifactStore(root: root, nodes: [folder]) + let model = ArtifactSidebarModel( + store: store, + captureService: SidebarCaptureSpy(), + searchDebounce: .zero + ) + + await model.bind(workspace: workspace(root: root)) + + #expect(model.phase == .loaded) + #expect(model.projectRoot == root.standardizedFileURL) + #expect(model.rows.map(\.relativePath) == ["session", "session/plan.md"]) + #expect(model.rows.map(\.depth) == [0, 1]) + #expect(model.rows.allSatisfy { $0.projectRoot == root.standardizedFileURL }) + } + + @Test("Binding scans once while installing the initial filesystem watcher") + func bindingScansOnce() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let store = SidebarArtifactStore(root: root, nodes: []) + let model = ArtifactSidebarModel(store: store, captureService: SidebarCaptureSpy()) + + await model.bind(workspace: workspace(root: root)) + + #expect(await store.waitUntilWatching()) + #expect(await store.settledSnapshotCount() == 1) + } + + @Test("Search replaces tree rows with content results") + func searches() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let file = ArtifactTestSupport.artifactNode(root: root, relativePath: "notes.txt", kind: .text) + let store = SidebarArtifactStore(root: root, nodes: [file]) + await store.setSearchResults([ + ArtifactSearchResult(node: file, score: 20, matchedContent: true, snippet: "needle here") + ]) + let model = ArtifactSidebarModel( + store: store, + captureService: SidebarCaptureSpy(), + searchDebounce: .zero + ) + await model.bind(workspace: workspace(root: root)) + + model.setQuery("needle") + + #expect(await waitUntil { model.rows.first?.snippet == "needle here" }) + #expect(model.rows.first?.matchedContent == true) + #expect(await store.lastQuery == "needle") + } + + @Test("Watcher updates rows after external filesystem changes") + func watchesChanges() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let store = SidebarArtifactStore(root: root, nodes: []) + let model = ArtifactSidebarModel(store: store, captureService: SidebarCaptureSpy()) + await model.bind(workspace: workspace(root: root)) + #expect(await store.waitUntilWatching()) + let appeared = ArtifactTestSupport.artifactNode(root: root, relativePath: "appeared.md", kind: .markdown) + + await store.replaceNodes([appeared], notify: true) + + #expect(await waitUntil { model.rows.map(\.relativePath) == ["appeared.md"] }) + } + + @Test("Watcher coalesces a burst into one bounded reload") + func coalescesWatcherBurst() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let store = SidebarArtifactStore(root: root, nodes: []) + let model = ArtifactSidebarModel( + store: store, + captureService: SidebarCaptureSpy(), + watcherDebounce: .milliseconds(50) + ) + await model.bind(workspace: workspace(root: root)) + #expect(await store.waitUntilWatching()) + let baseline = await store.snapshotCount + + for index in 0..<20 { + let node = ArtifactTestSupport.artifactNode( + root: root, + relativePath: "burst-\(index).md", + kind: .markdown + ) + await store.replaceNodes([node], notify: true) + } + + #expect(await store.settledSnapshotCount() == baseline + 1) + } + + @Test("Same-path file changes update the immutable thumbnail revision") + func fileChangesUpdateThumbnailRevision() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let first = ArtifactTestSupport.artifactNode( + root: root, + relativePath: "preview.png", + kind: .image, + modifiedAt: Date(timeIntervalSince1970: 1), + fileIdentity: ArtifactFileIdentity(device: 1, inode: 10) + ) + let second = ArtifactTestSupport.artifactNode( + root: root, + relativePath: "preview.png", + kind: .image, + modifiedAt: Date(timeIntervalSince1970: 1), + fileIdentity: ArtifactFileIdentity(device: 1, inode: 11) + ) + let store = SidebarArtifactStore(root: root, nodes: [first]) + let model = ArtifactSidebarModel(store: store, captureService: SidebarCaptureSpy()) + await model.bind(workspace: workspace(root: root)) + #expect(await store.waitUntilWatching()) + let firstRows = model.rows + + await store.replaceNodes([second], notify: true) + + #expect(await waitUntil { model.rows != firstRows }) + } + + @Test("Thumbnail revisions include file identity as well as modification time") + func thumbnailRevisionIncludesFileIdentity() { + let modifiedAt = Date(timeIntervalSince1970: 1) + + #expect( + ArtifactSidebarFileRevision( + fileURL: URL(fileURLWithPath: "/tmp/preview.png"), + modifiedAt: modifiedAt, + fileIdentity: ArtifactFileIdentity(device: 1, inode: 10) + ) != ArtifactSidebarFileRevision( + fileURL: URL(fileURLWithPath: "/tmp/preview.png"), + modifiedAt: modifiedAt, + fileIdentity: ArtifactFileIdentity(device: 1, inode: 11) + ) + ) + } + + @Test("Manual add uses injected capture service and workspace context") + func addsThroughCaptureService() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = root.appendingPathComponent("outside.md") + let store = SidebarArtifactStore(root: root, nodes: []) + let capture = SidebarCaptureSpy() + let model = ArtifactSidebarModel(store: store, captureService: capture) + await model.bind(workspace: workspace(root: root)) + + await model.addFiles([source]) + + #expect(await capture.addedSourceURLs == [source]) + #expect(await capture.lastContext?.projectRoot == root.standardizedFileURL) + #expect(await capture.lastContext?.workspaceID == "workspace-1") + #expect(await capture.lastContext?.workspaceTitle == "Artifacts Test") + } + + @Test("Manual multi-select submits one batch, continues after rejection, and reloads once") + func addsSelectionAsOneBatch() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let rejected = root.appendingPathComponent("rejected.exe") + let accepted = root.appendingPathComponent("accepted.md") + let store = SidebarArtifactStore(root: root, nodes: []) + let capture = SidebarCaptureSpy(rejectedSourceURLs: [rejected]) + let model = ArtifactSidebarModel(store: store, captureService: capture) + await model.bind(workspace: workspace(root: root)) + let snapshotCountBeforeAdd = await store.snapshotCount + + await model.addFiles([rejected, accepted]) + + #expect(await capture.addCallCount == 1) + #expect(await capture.addedSourceURLs == [rejected, accepted]) + #expect(await store.snapshotCount == snapshotCountBeforeAdd + 1) + #expect(model.actionFailure == .add) + } + + @Test("Working-directory and title churn within one project does not rescan") + func sameProjectWorkspaceUpdatesDoNotRescan() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let store = SidebarArtifactStore(root: root, nodes: []) + let capture = SidebarCaptureSpy() + let model = ArtifactSidebarModel(store: store, captureService: capture) + await model.bind(workspace: workspace(root: root)) + let snapshotCountBeforeUpdate = await store.snapshotCount + + model.updateWorkspaceTitle(workspaceID: "workspace-1", title: "Renamed") + await model.bind(workspace: ArtifactSidebarWorkspace( + id: "workspace-1", + title: "Renamed", + workingDirectory: root.appendingPathComponent("nested/directory") + )) + let snapshotCountAfterUpdate = await store.snapshotCount + await model.addFiles([root.appendingPathComponent("outside.md")]) + + #expect(snapshotCountAfterUpdate == snapshotCountBeforeUpdate) + #expect(await capture.lastContext?.workspaceTitle == "Renamed") + } + + @Test("Workspace rebind clears stale rows before project resolution finishes") + func rebindClearsRowsBeforeAwaitingResolution() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let oldFile = ArtifactTestSupport.artifactNode( + root: root, + relativePath: "old-session/private.md", + kind: .markdown + ) + let store = SidebarArtifactStore(root: root, nodes: [oldFile]) + let model = ArtifactSidebarModel(store: store, captureService: SidebarCaptureSpy()) + await model.bind(workspace: workspace(root: root)) + await store.suspendNextLocate() + + let rebind = Task { @MainActor in + await model.bind(workspace: ArtifactSidebarWorkspace( + id: "workspace-2", + title: "Second Workspace", + workingDirectory: root.appendingPathComponent("second", isDirectory: true) + )) + } + await store.waitUntilLocateStarts() + + #expect(model.phase == .loading) + #expect(model.rows.isEmpty) + #expect(model.projectRoot == nil) + + await store.releaseLocate() + await rebind.value + } + + private func workspace(root: URL) -> ArtifactSidebarWorkspace { + ArtifactSidebarWorkspace( + id: "workspace-1", + title: "Artifacts Test", + workingDirectory: root + ) + } + + private func waitUntil( + attempts: Int = 100, + predicate: @escaping @MainActor () -> Bool + ) async -> Bool { + for _ in 0..= 0 else { return } + defer { Darwin.close(descriptor) } + try? await Task.sleep(for: .seconds(1)) + } + let clock = ContinuousClock() + let startedAt = clock.now + + #expect(throws: ArtifactStoreError.sourceNotRegularFile(source.path)) { + _ = try ArtifactSourceSnapshotter(fileManager: .default).snapshot( + source: source, + paths: paths, + configuration: .defaultValue, + maximumBytes: nil, + stagedURL: stagedURL + ) + } + let elapsed = startedAt.duration(to: clock.now) + rescue.cancel() + await rescue.value + + #expect(elapsed < .milliseconds(500)) + #expect(!FileManager.default.fileExists(atPath: stagedURL.path)) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactStoreMutationLeaseTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactStoreMutationLeaseTests.swift new file mode 100644 index 000000000000..24cb752e741b --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactStoreMutationLeaseTests.swift @@ -0,0 +1,184 @@ +import Darwin +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact store mutation lease") +struct ArtifactStoreMutationLeaseTests { + @Test("A second repository cannot mutate a leased store") + func rejectsConcurrentProcessMutation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "artifact", + named: "plan.md", + under: root.appendingPathComponent("outside") + ) + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.filesystemRoot, + withIntermediateDirectories: true + ) + let descriptor = Darwin.open( + paths.filesystemRoot.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW + ) + #expect(descriptor >= 0) + guard descriptor >= 0 else { return } + defer { _ = close(descriptor) } + #expect(flock(descriptor, LOCK_EX | LOCK_NB) == 0) + + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext(projectRoot: root) + let blocked = await repository.importFiles( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .manual)], + context: context, + configuration: .defaultValue, + maximumBatchBytes: nil, + capturedAt: Date(timeIntervalSince1970: 1) + ) + + #expect(blocked.first == .rejected(.storeBusy(paths.filesystemRoot.path))) + #expect(flock(descriptor, LOCK_UN) == 0) + + let retried = await repository.importFiles( + candidates: [ArtifactCandidate(sourceURL: source, provenance: .manual)], + context: context, + configuration: .defaultValue, + maximumBatchBytes: nil, + capturedAt: Date(timeIntervalSince1970: 2) + ) + guard case .imported = retried.first else { + Issue.record("Expected the import to succeed after the lease was released") + return + } + } + + @Test("A swapped destination parent cannot redirect a staged move") + func rejectsSwappedDestinationParent() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.filesystemRoot.appendingPathComponent("session/artifacts"), + withIntermediateDirectories: true + ) + let staging = root.appendingPathComponent("staging", isDirectory: true) + try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true) + let source = try ArtifactTestSupport.write("staged", named: "plan.md", under: staging) + let expectedSourceParentPath = staging.resolvingSymlinksInPath().standardizedFileURL.path + let lease = try ArtifactStoreMutationLease(directory: paths.filesystemRoot) + defer { lease.finish() } + + try FileManager.default.removeItem( + at: paths.filesystemRoot.appendingPathComponent("session") + ) + try FileManager.default.createSymbolicLink( + at: paths.filesystemRoot.appendingPathComponent("session"), + withDestinationURL: outside + ) + + #expect(throws: ArtifactStoreError.self) { + try lease.moveFile( + from: source, + toRelativePath: "session/artifacts/plan.md", + expectedSourceParentPath: expectedSourceParentPath + ) + } + #expect(FileManager.default.fileExists(atPath: source.path)) + #expect(!FileManager.default.fileExists( + atPath: outside.appendingPathComponent("artifacts/plan.md").path + )) + } + + @Test("A replaced leaf cannot be removed through an old identity") + func rejectsReplacedLeafIdentity() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let note = paths.filesystemRoot.appendingPathComponent("session/notes/plan.md") + try FileManager.default.createDirectory( + at: note.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Data("original".utf8).write(to: note) + let expectedIdentity = try ArtifactFileIdentity.read(at: note) + let replacement = note.deletingLastPathComponent().appendingPathComponent("replacement.md") + try Data("replacement".utf8).write(to: replacement) + try FileManager.default.removeItem(at: note) + try FileManager.default.moveItem(at: replacement, to: note) + + let lease = try ArtifactStoreMutationLease(directory: paths.filesystemRoot) + defer { lease.finish() } + #expect(throws: ArtifactStoreError.self) { + try lease.unlink( + relativePath: "session/notes/plan.md", + expectedIdentity: expectedIdentity + ) + } + #expect(try String(contentsOf: note, encoding: .utf8) == "replacement") + } + + @Test("Descriptor-relative metadata writes survive a swapped ancestor") + func writesThroughPinnedAncestor() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + try FileManager.default.createDirectory( + at: paths.provenanceRoot, + withIntermediateDirectories: true + ) + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let lease = try ArtifactStoreMutationLease(directory: paths.filesystemRoot) + defer { lease.finish() } + + let oldMetadata = paths.filesystemRoot.appendingPathComponent(".metadata-old") + try FileManager.default.moveItem(at: paths.metadataRoot, to: oldMetadata) + try FileManager.default.createSymbolicLink( + at: paths.metadataRoot, + withDestinationURL: outside + ) + + try lease.writeData( + Data("safe".utf8), + toRelativePath: ".metadata/provenance/digest.json" + ) + + #expect( + try String( + contentsOf: oldMetadata.appendingPathComponent("provenance/digest.json"), + encoding: .utf8 + ) == "safe" + ) + #expect(!FileManager.default.fileExists( + atPath: outside.appendingPathComponent("provenance/digest.json").path + )) + } + + @Test("An explicitly authorized store path rejects an ancestor swap") + func rejectsAncestorSwapAgainstExpectedPath() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let store = root.appendingPathComponent(".cmux", isDirectory: true) + try FileManager.default.createDirectory(at: store, withIntermediateDirectories: true) + let expected = store.resolvingSymlinksInPath().standardizedFileURL.path + try FileManager.default.createDirectory( + at: outside.appendingPathComponent(".cmux", isDirectory: true), + withIntermediateDirectories: true + ) + try FileManager.default.removeItem(at: root) + try FileManager.default.createSymbolicLink(at: root, withDestinationURL: outside) + + #expect(throws: ArtifactStoreError.self) { + _ = try ArtifactStoreMutationLease( + directory: root.appendingPathComponent(".cmux", isDirectory: true), + expectedCanonicalPath: expected + ) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTerminalTextSanitizerTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTerminalTextSanitizerTests.swift new file mode 100644 index 000000000000..769449006ba3 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTerminalTextSanitizerTests.swift @@ -0,0 +1,33 @@ +import Testing +@testable import CmuxArtifacts + +@Suite("Artifact terminal text sanitizer") +struct ArtifactTerminalTextSanitizerTests { + @Test("C0 and C1 controls become visible replacement characters") + func replacesTerminalControls() { + let unsafe = "safe\u{0}\u{7}\r\n\u{1B}\u{7F}\u{85}\u{9B}text" + + let sanitized = ArtifactTerminalTextSanitizer().sanitize(unsafe) + + #expect(sanitized == "safe��������text") + #expect(!sanitized.unicodeScalars.contains { scalar in + scalar.value <= 0x1F || (0x7F...0x9F).contains(scalar.value) + }) + } + + @Test("Ordinary Unicode text is unchanged") + func preservesOrdinaryText() { + let text = "計画/launch-plan.md — résumé" + + #expect(ArtifactTerminalTextSanitizer().sanitize(text) == text) + } + + @Test("Text content preserves tabs and line structure") + func preservesMultilineTextLayout() { + let text = "first\tcolumn\r\nsecond\rthird\n\u{1B}[31m" + + let sanitized = ArtifactTerminalTextSanitizer().sanitizeTextContent(text) + + #expect(sanitized == "first\tcolumn\nsecond\nthird\n�[31m") + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTestSupport.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTestSupport.swift new file mode 100644 index 000000000000..7b97e04a02ec --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ArtifactTestSupport.swift @@ -0,0 +1,78 @@ +import Foundation +@testable import CmuxArtifacts + +struct ArtifactTestSupport { + private init() {} + + static func temporaryDirectory() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("CmuxArtifactsTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + static func write(_ contents: String, named name: String, under directory: URL) throws -> URL { + let url = directory.appendingPathComponent(name, isDirectory: false) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try contents.write(to: url, atomically: true, encoding: .utf8) + return url + } + + static func remove(_ url: URL) { + try? FileManager.default.removeItem(at: url) + } + + @discardableResult + static func runGit(_ arguments: [String]) throws -> Int32 { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = arguments + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + process.waitUntilExit() + return process.terminationStatus + } + + static func artifactNode( + root: URL, + relativePath: String, + kind: ArtifactFileKind, + modifiedAt: Date? = nil, + fileIdentity: ArtifactFileIdentity? = nil + ) -> ArtifactNode { + ArtifactNode( + id: relativePath, + name: URL(fileURLWithPath: relativePath).lastPathComponent, + relativePath: relativePath, + absolutePath: root.appendingPathComponent(".cmux/\(relativePath)").path, + isDirectory: false, + fileKind: kind, + size: 1, + modifiedAt: modifiedAt, + fileIdentity: fileIdentity, + children: [] + ) + } + + static func artifactFolder( + root: URL, + relativePath: String, + children: [ArtifactNode] + ) -> ArtifactNode { + ArtifactNode( + id: relativePath, + name: URL(fileURLWithPath: relativePath).lastPathComponent, + relativePath: relativePath, + absolutePath: root.appendingPathComponent(".cmux/\(relativePath)").path, + isDirectory: true, + fileKind: nil, + size: nil, + modifiedAt: nil, + children: children + ) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxFilesystemIdentityTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxFilesystemIdentityTests.swift new file mode 100644 index 000000000000..7efd8f8a557a --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxFilesystemIdentityTests.swift @@ -0,0 +1,198 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("cmux filesystem identity") +struct CmuxFilesystemIdentityTests { + @Test("Note operations ignore Markdown outside a marked session Notes root") + func noteOperationsStayInsideMarkedNotesRoot() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:notes-boundary", + agentName: "codex" + ) + let note = try await repository.writeNote( + name: "plan", + text: "real note", + mode: .replace, + context: context + ) + let sessionRoot = URL(fileURLWithPath: note.absolutePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + let artifact = try ArtifactTestSupport.write( + "artifact markdown", + named: "artifacts/notes/report.md", + under: sessionRoot + ) + + let listed = try await repository.listNotes(projectRoot: root) + #expect(listed.map(\.relativePath) == [note.relativePath]) + await #expect(throws: CmuxNoteStoreError.noteNotFound("report")) { + _ = try await repository.readNote(projectRoot: root, name: "report") + } + await #expect(throws: CmuxNoteStoreError.noteNotFound("report")) { + try await repository.deleteNote(projectRoot: root, name: "report") + } + #expect(FileManager.default.fileExists(atPath: artifact.path)) + } + + @Test("Capture rejects duplicate session identity markers") + func captureRejectsDuplicateSessionMarkers() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:duplicate", + agentName: "codex" + ) + let firstSource = try ArtifactTestSupport.write( + "first", + named: "outside/first.md", + under: root + ) + let first = try await repository.importFile( + sourceURL: firstSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let originalSession = try sessionRoot(for: first, projectRoot: root) + try copySession( + originalSession, + to: root.appendingPathComponent(".cmux/backup/session-copy") + ) + let secondSource = try ArtifactTestSupport.write( + "second", + named: "outside/second.md", + under: root + ) + + await #expect(throws: ArtifactStoreError.corruptProvenance( + root.appendingPathComponent(".cmux").path + )) { + _ = try await repository.importFile( + sourceURL: secondSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + } + + @Test("Capture rejects duplicate workspace identity markers") + func captureRejectsDuplicateWorkspaceMarkers() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:duplicate", + agentName: "codex" + ) + let firstSource = try ArtifactTestSupport.write( + "first", + named: "outside/workspace-first.md", + under: root + ) + let first = try await repository.importFile( + sourceURL: firstSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let originalSession = try sessionRoot(for: first, projectRoot: root) + try copySession( + originalSession, + to: root.appendingPathComponent(".cmux/backup/workspace-copy") + ) + let secondSource = try ArtifactTestSupport.write( + "second", + named: "outside/workspace-second.md", + under: root + ) + + await #expect(throws: ArtifactStoreError.corruptProvenance( + root.appendingPathComponent(".cmux").path + )) { + _ = try await repository.importFile( + sourceURL: secondSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + } + + @Test("Workspace-only capture does not reuse an agent-session directory") + func workspaceOnlyCaptureStaysSeparateFromAgentSession() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let agentSource = try ArtifactTestSupport.write( + "agent", + named: "outside/agent.md", + under: root + ) + let agent = try await repository.importFile( + sourceURL: agentSource, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:shared", + sessionID: "session:agent", + agentName: "codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let manualSource = try ArtifactTestSupport.write( + "manual", + named: "outside/manual.md", + under: root + ) + + let manual = try await repository.importFile( + sourceURL: manualSource, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:shared" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + + #expect( + try sessionRoot(for: agent, projectRoot: root) + != sessionRoot(for: manual, projectRoot: root) + ) + } + + private func sessionRoot( + for outcome: ArtifactImportOutcome, + projectRoot: URL + ) throws -> URL { + let relativePath = try #require(outcome.record?.relativePath) + return projectRoot.appendingPathComponent(".cmux/\(relativePath)") + .deletingLastPathComponent() + .deletingLastPathComponent() + } + + private func copySession(_ source: URL, to destination: URL) throws { + try FileManager.default.createDirectory( + at: destination.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.copyItem(at: source, to: destination) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxNoteRepositoryTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxNoteRepositoryTests.swift new file mode 100644 index 000000000000..4d93df077843 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxNoteRepositoryTests.swift @@ -0,0 +1,299 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("cmux Notes repository") +struct CmuxNoteRepositoryTests { + @Test("Notes write, append, read, list, search, and delete through one live store") + func noteLifecycle() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:notes", + sessionID: "session:notes", + agentName: "codex" + ) + + let written = try await repository.writeNote( + name: "plans/launch", + text: "first needle", + mode: .replace, + context: context + ) + #expect(written.relativePath.hasSuffix("/notes/plans/launch.md")) + #expect(written.reference == ".cmux/\(written.relativePath)") + + _ = try await repository.writeNote( + name: "launch", + text: "\nsecond line", + mode: .append, + context: context + ) + #expect(try await repository.readNote(projectRoot: root, name: "launch") + == "first needle\nsecond line") + #expect(try await repository.listNotes(projectRoot: root).map(\.relativePath) + == [written.relativePath]) + let results = try await repository.searchNotes(projectRoot: root, query: "needle") + #expect(results.first?.note.relativePath == written.relativePath) + #expect(results.first?.matchedContent == true) + + try await repository.deleteNote(projectRoot: root, name: written.reference) + await #expect(throws: CmuxNoteStoreError.noteNotFound("launch")) { + _ = try await repository.readNote(projectRoot: root, name: "launch") + } + } + + @Test("Deleting a missing note does not initialize a project store") + func missingDeleteDoesNotCreateStore() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + + await #expect(throws: CmuxNoteStoreError.noteNotFound("missing")) { + _ = try await repository.deleteNote(projectRoot: root, name: "missing") + } + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux", isDirectory: true).path + )) + } + + @Test("Moved notes and session folders remain discoverable without an index") + func resolvesMovedNotesAndReusesMovedSession() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:move", + agentName: "codex" + ) + let first = try await repository.writeNote( + name: "plan", + text: "movable", + mode: .replace, + context: context + ) + let originalSession = URL(fileURLWithPath: first.absolutePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + let movedSession = root.appendingPathComponent(".cmux/organized/research-session") + try FileManager.default.createDirectory( + at: movedSession.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.moveItem(at: originalSession, to: movedSession) + let movedNote = movedSession.appendingPathComponent("notes/archive/final.md") + try FileManager.default.createDirectory( + at: movedNote.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.moveItem( + at: movedSession.appendingPathComponent("notes/plan.md"), + to: movedNote + ) + + #expect(try await repository.readNote(projectRoot: root, name: "final") == "movable") + let second = try await repository.writeNote( + name: "next", + text: "same session", + mode: .replace, + context: context + ) + #expect(second.relativePath == "organized/research-session/notes/next.md") + } + + @Test("Bare writes stay isolated to the current agent session") + func isolatesWritesBySession() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let firstContext = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:first", + agentName: "codex" + ) + let secondContext = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:second", + agentName: "codex" + ) + let first = try await repository.writeNote( + name: "plan", + text: "first", + mode: .replace, + context: firstContext + ) + + let second = try await repository.writeNote( + name: "plan", + text: "second", + mode: .replace, + context: secondContext + ) + _ = try await repository.writeNote( + name: first.reference, + text: "explicit update", + mode: .replace, + context: secondContext + ) + + let firstSessionRoot = first.relativePath.split(separator: "/").first + let secondSessionRoot = second.relativePath.split(separator: "/").first + #expect(first.relativePath.hasSuffix("/notes/plan.md")) + #expect(second.relativePath.hasSuffix("/notes/plan.md")) + #expect(firstSessionRoot != secondSessionRoot) + #expect(try String(contentsOfFile: first.absolutePath, encoding: .utf8) == "explicit update") + #expect(try String(contentsOfFile: second.absolutePath, encoding: .utf8) == "second") + } + + @Test("Note mutations require exact names instead of fuzzy matches") + func mutationsDoNotFuzzyMatch() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:exact", + agentName: "codex" + ) + let plan = try await repository.writeNote( + name: "plan", + text: "original plan", + mode: .replace, + context: context + ) + + let shortName = try await repository.writeNote( + name: "p", + text: "short note", + mode: .replace, + context: context + ) + + #expect(plan.relativePath != shortName.relativePath) + #expect(try await repository.readNote(projectRoot: root, name: "plan") == "original plan") + #expect(try await repository.readNote(projectRoot: root, name: "p") == "short note") + await #expect(throws: CmuxNoteStoreError.noteNotFound("pla")) { + try await repository.deleteNote(projectRoot: root, name: "pla") + } + #expect(try await repository.listNotes(projectRoot: root).count == 2) + } + + @Test("Notes reject traversal and never follow symlinked note files") + func rejectsUnsafePaths() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.write( + "outside", + named: "outside.md", + under: root + ) + let notes = root.appendingPathComponent(".cmux/session/notes") + try FileManager.default.createDirectory(at: notes, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: notes.appendingPathComponent("linked.md"), + withDestinationURL: outside + ) + let repository = LocalArtifactRepository() + + await #expect(throws: CmuxNoteStoreError.invalidName("../escape")) { + _ = try await repository.writeNote( + name: "../escape", + text: "unsafe", + mode: .replace, + context: ArtifactCaptureContext(projectRoot: root) + ) + } + await #expect(throws: CmuxNoteStoreError.noteNotFound("linked")) { + _ = try await repository.readNote(projectRoot: root, name: "linked") + } + #expect(try String(contentsOf: outside, encoding: .utf8) == "outside") + } + + @Test("Atomic note replacement rejects a swapped parent symlink") + func rejectsAtomicParentSwap() throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let parent = root.appendingPathComponent("notes", isDirectory: true) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let destination = parent.appendingPathComponent("plan.md") + let expectedParentPath = ArtifactPathResolver(fileManager: .default) + .canonicalPath(parent) + try FileManager.default.removeItem(at: parent) + try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: outside) + + #expect(throws: CmuxNoteStoreError.self) { + try CmuxNoteAtomicWriter().write( + Data("must stay inside".utf8), + to: destination, + expectedParentPath: expectedParentPath + ) + } + #expect(!FileManager.default.fileExists( + atPath: outside.appendingPathComponent("plan.md").path + )) + } + + @Test("Note writes reject managed control names before creating nested content") + func rejectsManagedControlPathComponentsBeforeMutation() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:managed-name", + agentName: "codex" + ) + let managedNames = [ + "_session.json", + "_SESSION.JSON", + "_workspace.json", + ".metadata", + "artifacts.json", + ] + + for managedName in managedNames { + await #expect(throws: CmuxNoteStoreError.invalidName("\(managedName)/plan")) { + _ = try await repository.writeNote( + name: "\(managedName)/plan", + text: "must not be written", + mode: .replace, + context: context + ) + } + } + + let allPaths = FileManager.default.enumerator( + at: root.appendingPathComponent(".cmux"), + includingPropertiesForKeys: nil + )?.compactMap { ($0 as? URL)?.path } ?? [] + #expect(!allPaths.contains { $0.hasSuffix("/plan.md") }) + } + + @Test("Non-UTF-8 Markdown is not silently decoded as a Note") + func rejectsInvalidUTF8() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let note = try await repository.writeNote( + name: "binary", + text: "valid", + mode: .replace, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:binary", + agentName: "codex" + ) + ) + try Data([0xFF, 0xFE]).write(to: URL(fileURLWithPath: note.absolutePath)) + + await #expect(throws: CmuxNoteStoreError.invalidUTF8(note.relativePath)) { + _ = try await repository.readNote(projectRoot: root, name: "binary") + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxSessionFilesystemTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxSessionFilesystemTests.swift new file mode 100644 index 000000000000..e4bd51e285bf --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/CmuxSessionFilesystemTests.swift @@ -0,0 +1,428 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("cmux session filesystem") +struct CmuxSessionFilesystemTests { + @Test("Artifact capture writes beneath the agent session root") + func capturesIntoSessionArtifactsDirectory() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "# Plan", + named: "outside/plan.md", + under: root + ) + + let outcome = try await LocalArtifactRepository().importFile( + sourceURL: source, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:42", + workspaceTitle: "API Work", + sessionID: "session:99", + agentName: "Codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1_700_000_000) + ) + + let record = try #require(outcome.record) + let sessionName = try #require(record.relativePath.split(separator: "/").first) + #expect(sessionName.hasPrefix("codex-session-99-")) + #expect(record.relativePath == "\(sessionName)/artifacts/plan.md") + let sessionRoot = root.appendingPathComponent(".cmux/\(sessionName)") + #expect(FileManager.default.fileExists( + atPath: sessionRoot.appendingPathComponent("artifacts/plan.md").path + )) + #expect(FileManager.default.fileExists( + atPath: sessionRoot.appendingPathComponent("_session.json").path + )) + #expect(FileManager.default.fileExists( + atPath: sessionRoot.appendingPathComponent("_workspace.json").path + )) + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux/artifacts").path + )) + #expect(FileManager.default.fileExists( + atPath: root.appendingPathComponent( + ".cmux/.metadata/provenance/\(record.digest).json" + ).path + )) + } + + @Test("The live tree includes notes beside artifacts under one session") + func scansUnifiedSessionContents() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let sessionRoot = root.appendingPathComponent(".cmux/codex-session-one") + _ = try ArtifactTestSupport.write( + "artifact", + named: "artifacts/report.txt", + under: sessionRoot + ) + _ = try ArtifactTestSupport.write( + "# Notes", + named: "notes/plan.md", + under: sessionRoot + ) + + let snapshot = try await LocalArtifactRepository().snapshot(projectRoot: root) + let paths = snapshot.nodes.flattenedArtifactNodes().map(\.relativePath) + + #expect(snapshot.filesystemRoot == root.appendingPathComponent(".cmux")) + #expect(paths.contains("codex-session-one/artifacts/report.txt")) + #expect(paths.contains("codex-session-one/notes/plan.md")) + } + + @Test("Prompt-ready cmux references resolve against the unified filesystem") + func resolvesCmuxReference() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + _ = try ArtifactTestSupport.write( + "artifact", + named: ".cmux/session/artifacts/report.txt", + under: root + ) + + let node = try await LocalArtifactRepository().resolve( + projectRoot: root, + name: ".cmux/session/artifacts/report.txt" + ) + + #expect(node.relativePath == "session/artifacts/report.txt") + } + + @Test("Moving a session keeps it as the destination for later captures") + func reusesMovedSessionRoot() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace-one", + sessionID: "session-one", + agentName: "codex" + ) + let firstSource = try ArtifactTestSupport.write("first", named: "first.md", under: root) + let first = try await repository.importFile( + sourceURL: firstSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + let firstRecord = try #require(first.record) + let originalSession = root.appendingPathComponent(".cmux/\(firstRecord.relativePath)") + .deletingLastPathComponent() + .deletingLastPathComponent() + let movedSession = root.appendingPathComponent(".cmux/organized/renamed-session") + try FileManager.default.createDirectory( + at: movedSession.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.moveItem(at: originalSession, to: movedSession) + let secondSource = try ArtifactTestSupport.write("second", named: "second.md", under: root) + + let second = try await repository.importFile( + sourceURL: secondSource, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + + #expect(second.record?.relativePath == "organized/renamed-session/artifacts/second.md") + } + + @Test("Different agent providers never share a session root when raw IDs match") + func separatesProvidersWithTheSameSessionIdentifier() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let firstSource = try ArtifactTestSupport.write("codex", named: "outside/codex.md", under: root) + let secondSource = try ArtifactTestSupport.write("claude", named: "outside/claude.md", under: root) + + let codex = try await repository.importFile( + sourceURL: firstSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "shared-session-id", + agentName: "codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let claude = try await repository.importFile( + sourceURL: secondSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "shared-session-id", + agentName: "claude" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + + let codexRoot = try #require(codex.record?.relativePath.split(separator: "/").first) + let claudeRoot = try #require(claude.record?.relativePath.split(separator: "/").first) + #expect(codexRoot != claudeRoot) + } + + @Test("Similar pending session identifiers never share a capture directory") + func separatesPendingSessionIdentifiersWithTheSameReadablePrefix() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let firstSource = try ArtifactTestSupport.write("first", named: "outside/first.md", under: root) + let secondSource = try ArtifactTestSupport.write("second", named: "outside/second.md", under: root) + + let first = try await repository.importFile( + sourceURL: firstSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "pending-claude-a1111111-1111-1111-1111-111111111111", + agentName: "claude" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let second = try await repository.importFile( + sourceURL: secondSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "pending-claude-a2222222-2222-2222-2222-222222222222", + agentName: "claude" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + + let firstRoot = try #require(first.record?.relativePath.split(separator: "/").first) + let secondRoot = try #require(second.record?.relativePath.split(separator: "/").first) + #expect(firstRoot != secondRoot) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let firstMarker = try decoder.decode( + ArtifactSessionMarker.self, + from: Data(contentsOf: root.appendingPathComponent(".cmux/\(firstRoot)/_session.json")) + ) + let secondMarker = try decoder.decode( + ArtifactSessionMarker.self, + from: Data(contentsOf: root.appendingPathComponent(".cmux/\(secondRoot)/_session.json")) + ) + #expect(firstMarker.sessionID == "pending-claude-a1111111-1111-1111-1111-111111111111") + #expect(secondMarker.sessionID == "pending-claude-a2222222-2222-2222-2222-222222222222") + } + + @Test("Short session identifiers that normalize alike never share a capture directory") + func separatesShortSessionIdentifiersWithTheSameNormalizedValue() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let firstSource = try ArtifactTestSupport.write("first", named: "outside/first.txt", under: root) + let secondSource = try ArtifactTestSupport.write("second", named: "outside/second.txt", under: root) + + let first = try await repository.importFile( + sourceURL: firstSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "Ab:C", + agentName: "codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 1) + ) + let second = try await repository.importFile( + sourceURL: secondSource, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "ab-c", + agentName: "codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + + let firstRoot = try #require(first.record?.relativePath.split(separator: "/").first) + let secondRoot = try #require(second.record?.relativePath.split(separator: "/").first) + #expect(firstRoot != secondRoot) + } + + @Test("A fallback directory with a different session marker is never reused") + func rejectsMismatchedFallbackSessionMarker() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "session:expected", + agentName: "codex" + ) + let fallback = ArtifactPathResolver(fileManager: .default).contentDirectory( + paths: paths, + context: context, + kind: .artifacts + ) + let markerURL = fallback.deletingLastPathComponent() + .appendingPathComponent(ArtifactPathResolver.sessionMarkerName) + try FileManager.default.createDirectory( + at: fallback, + withIntermediateDirectories: true + ) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode( + ArtifactSessionMarker( + sessionID: "session:different", + agentName: "codex", + createdAt: Date(timeIntervalSince1970: 1) + ) + ).write(to: markerURL) + let source = try ArtifactTestSupport.write( + "private", + named: "outside/private.md", + under: root + ) + + await #expect(throws: ArtifactStoreError.corruptProvenance(markerURL.path)) { + _ = try await LocalArtifactRepository().importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + #expect(!FileManager.default.fileExists( + atPath: fallback.appendingPathComponent(source.lastPathComponent).path + )) + } + + @Test("A fallback directory owned by another provider is never reused") + func rejectsFallbackSessionMarkerForAnotherProvider() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let context = ArtifactCaptureContext( + projectRoot: root, + sessionID: "shared-session-id", + agentName: "codex" + ) + let fallback = ArtifactPathResolver(fileManager: .default).contentDirectory( + paths: paths, + context: context, + kind: .artifacts + ) + let markerURL = fallback.deletingLastPathComponent() + .appendingPathComponent(ArtifactPathResolver.sessionMarkerName) + try FileManager.default.createDirectory( + at: fallback, + withIntermediateDirectories: true + ) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode( + ArtifactSessionMarker( + sessionID: "shared-session-id", + agentName: "claude", + createdAt: Date(timeIntervalSince1970: 1) + ) + ).write(to: markerURL) + let source = try ArtifactTestSupport.write( + "private", + named: "outside/provider-private.md", + under: root + ) + + await #expect(throws: ArtifactStoreError.corruptProvenance(markerURL.path)) { + _ = try await LocalArtifactRepository().importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + #expect(!FileManager.default.fileExists( + atPath: fallback.appendingPathComponent(source.lastPathComponent).path + )) + } + + @Test("Capture fails closed when moved-session discovery exceeds its node budget") + func rejectsIncompleteMovedSessionDiscovery() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let paths = ArtifactStorePaths(projectRoot: root) + let movedRoot = paths.filesystemRoot.appendingPathComponent("organized/session", isDirectory: true) + try FileManager.default.createDirectory(at: movedRoot, withIntermediateDirectories: true) + try JSONEncoder().encode( + ArtifactSessionMarker( + sessionID: "session-beyond-budget", + agentName: "codex", + createdAt: Date(timeIntervalSince1970: 1) + ) + ).write(to: movedRoot.appendingPathComponent(ArtifactPathResolver.sessionMarkerName)) + let source = try ArtifactTestSupport.write("new", named: "outside/new.md", under: root) + let repository = LocalArtifactRepository(nodeBudget: 1) + + await #expect(throws: ArtifactStoreError.scanIncomplete(paths.filesystemRoot.path)) { + try await repository.importFile( + sourceURL: source, + context: ArtifactCaptureContext( + projectRoot: root, + sessionID: "session-beyond-budget", + agentName: "codex" + ), + provenance: .manual, + configuration: .defaultValue, + capturedAt: Date(timeIntervalSince1970: 2) + ) + } + } + + @Test("Git excludes every session content kind without hiding project config") + func installsSessionFilesystemGitExcludes() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try ArtifactTestSupport.runGit(["init", "--quiet", root.path]) == 0) + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation( + paths: ArtifactStorePaths(projectRoot: root) + ) + let privatePaths = [ + ".cmux/session/artifacts/image.png", + ".cmux/session/notes/plan.md", + ".cmux/session/_session.json", + ".cmux/session/_workspace.json", + ".cmux/.metadata/provenance/digest.json", + ".cmux/organized/final.txt", + ] + for path in privatePaths { + _ = try ArtifactTestSupport.write( + "private", + named: path, + under: root + ) + #expect(try ArtifactTestSupport.runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", path, + ]) == 0) + } + for name in ArtifactStorePaths.trackableControlFileNames { + let path = ".cmux/\(name)" + _ = try ArtifactTestSupport.write("{}", named: path, under: root) + #expect(try ArtifactTestSupport.runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", path, + ]) == 1) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ConfiguredArtifactStore.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ConfiguredArtifactStore.swift new file mode 100644 index 000000000000..76160692a3c6 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ConfiguredArtifactStore.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import CmuxArtifacts + +actor ConfiguredArtifactStore: ArtifactStoring { + let fixedConfiguration: ArtifactCaptureConfiguration + let limitsAggregateBatchToFirstCandidate: Bool + private(set) var importCount = 0 + private(set) var batchImportCount = 0 + private(set) var configurationReadCount = 0 + private(set) var receivedMaximumBatchBytes: [Int64?] = [] + + init( + configuration: ArtifactCaptureConfiguration, + limitsAggregateBatchToFirstCandidate: Bool = false + ) { + fixedConfiguration = configuration + self.limitsAggregateBatchToFirstCandidate = limitsAggregateBatchToFirstCandidate + } + + func locateProjectRoot(startingAt: URL) -> URL { startingAt } + + func configuration(projectRoot: URL) -> ArtifactCaptureConfiguration { + configurationReadCount += 1 + return fixedConfiguration + } + + func snapshot(projectRoot: URL) throws -> ArtifactSnapshot { + ArtifactSnapshot(projectRoot: projectRoot, filesystemRoot: projectRoot, nodes: [], isTruncated: false) + } + + func search(projectRoot: URL, query: String) -> [ArtifactSearchResult] { [] } + + func importFile( + sourceURL: URL, + context: ArtifactCaptureContext, + provenance: ArtifactProvenance, + configuration: ArtifactCaptureConfiguration, + capturedAt: Date + ) throws -> ArtifactImportOutcome { + importCount += 1 + return .alreadyStored(ArtifactRecord( + digest: sourceURL.lastPathComponent, + sourcePath: sourceURL.path, + relativePath: sourceURL.lastPathComponent, + workspaceID: context.workspaceID, + sessionID: context.sessionID, + provenance: provenance, + capturedAt: capturedAt, + size: 0 + )) + } + + func importFiles( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + configuration: ArtifactCaptureConfiguration, + maximumBatchBytes: Int64?, + capturedAt: Date + ) -> [ArtifactImportAttempt] { + batchImportCount += 1 + receivedMaximumBatchBytes.append(maximumBatchBytes) + return candidates.enumerated().map { index, candidate in + if limitsAggregateBatchToFirstCandidate, + let maximumBatchBytes, + index > candidates.startIndex { + return .rejected(.batchByteLimitReached( + actual: 0, + limit: maximumBatchBytes + )) + } + do { + return .imported(try importFile( + sourceURL: candidate.sourceURL, + context: context, + provenance: candidate.provenance, + configuration: configuration, + capturedAt: capturedAt + )) + } catch let error as ArtifactStoreError { + return .rejected(error) + } catch { + return .rejected(.sourceNotRegularFile(candidate.sourceURL.path)) + } + } + } + + func resolve(projectRoot: URL, name: String) throws -> ArtifactNode { + throw ArtifactStoreError.artifactNotFound(name) + } + + func changes(projectRoot: URL) -> AsyncStream { + AsyncStream { $0.finish() } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/DirectoryEnumerationRecordingFileManager.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/DirectoryEnumerationRecordingFileManager.swift new file mode 100644 index 000000000000..12b4652c560c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/DirectoryEnumerationRecordingFileManager.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Records eager directory materialization so scanner tests can enforce streaming traversal. +// Safety: tests inject this instance into one repository actor and read counters only after awaited calls. +final class DirectoryEnumerationRecordingFileManager: FileManager, @unchecked Sendable { + private(set) var eagerDirectoryReadCount = 0 + + override func contentsOfDirectory( + at url: URL, + includingPropertiesForKeys keys: [URLResourceKey]?, + options mask: FileManager.DirectoryEnumerationOptions = [] + ) throws -> [URL] { + eagerDirectoryReadCount += 1 + return try super.contentsOfDirectory( + at: url, + includingPropertiesForKeys: keys, + options: mask + ) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/LocalArtifactRepositoryTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/LocalArtifactRepositoryTests.swift new file mode 100644 index 000000000000..2de20be445d2 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/LocalArtifactRepositoryTests.swift @@ -0,0 +1,513 @@ +import Foundation +import Testing +@testable import CmuxArtifacts + +@Suite("Local artifact repository") +struct LocalArtifactRepositoryTests { + @Test("Read operations do not create the store or edit Git excludes") + func readsDoNotMutateProject() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try runGit(["init", "--quiet", root.path]) == 0) + let exclude = root.appendingPathComponent(".git/info/exclude") + try "# preserve\n".write(to: exclude, atomically: true, encoding: .utf8) + let repository = LocalArtifactRepository() + + #expect(try await repository.snapshot(projectRoot: root).nodes.isEmpty) + #expect(try await repository.search(projectRoot: root, query: "missing").isEmpty) + #expect(try await repository.listNotes(projectRoot: root).isEmpty) + #expect(try await repository.searchNotes(projectRoot: root, query: "missing").isEmpty) + + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux").path + )) + #expect(try String(contentsOf: exclude, encoding: .utf8) == "# preserve\n") + } + + @Test("Import groups files and records hidden provenance") + func importsWithGroupingAndProvenance() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try runGit(["init", "--quiet", root.path]) == 0) + let source = try ArtifactTestSupport.write("# Plan", named: "plan.md", under: root.appendingPathComponent("source")) + let repository = LocalArtifactRepository() + let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + + let outcome = try await repository.importFile( + sourceURL: source, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace:42", + workspaceTitle: "API Work", + sessionID: "session:99", + agentName: "Codex" + ), + provenance: .created, + configuration: .defaultValue, + capturedAt: timestamp + ) + + guard case .copied(let record) = outcome else { + Issue.record("Expected a new copy") + return + } + #expect(record.relativePath.hasSuffix("/artifacts/plan.md")) + #expect(FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux/\(record.relativePath)").path + )) + #expect(FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux/.metadata/provenance/\(record.digest).json").path + )) + let snapshot = try await repository.snapshot(projectRoot: root) + let sessionRoot = try #require(record.relativePath.split(separator: "/").first) + #expect(snapshot.nodes.map(\.name) == [String(sessionRoot)]) + + let exclude = try String( + contentsOf: root.appendingPathComponent(".git/info/exclude"), + encoding: .utf8 + ) + let excludeLines = Set(exclude.split(separator: "\n").map(String.init)) + #expect(excludeLines.isSuperset(of: Set(ArtifactGitIgnoreManager.ignoreEntries))) + _ = try await repository.snapshot(projectRoot: root) + let secondExclude = try String( + contentsOf: root.appendingPathComponent(".git/info/exclude"), + encoding: .utf8 + ) + #expect(secondExclude == exclude) + } + + @Test("Content digest deduplicates after a user move") + func deduplicatesAfterMove() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write("same bytes", named: "result.txt", under: root.appendingPathComponent("outside")) + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext(projectRoot: root, workspaceID: "one", sessionID: "two") + let first = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + let original = try #require(first.record) + let originalURL = root.appendingPathComponent(".cmux/\(original.relativePath)") + let movedURL = root.appendingPathComponent(".cmux/organized/final.txt") + try FileManager.default.createDirectory(at: movedURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.moveItem(at: originalURL, to: movedURL) + + let second = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + + guard case .deduplicated(let record) = second else { + Issue.record("Expected content deduplication") + return + } + #expect(record.relativePath == "organized/final.txt") + } + + @Test("Moved-file deduplication is independent of the sidebar node budget") + func deduplicatesMovedFileBeyondSidebarBudget() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "same bytes", + named: "result.txt", + under: root.appendingPathComponent("outside") + ) + let repository = LocalArtifactRepository(nodeBudget: 1) + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "one", + sessionID: "two" + ) + let first = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + let original = try #require(first.record) + let originalURL = root.appendingPathComponent(".cmux/\(original.relativePath)") + let movedURL = root.appendingPathComponent(".cmux/organized/final.txt") + try FileManager.default.createDirectory( + at: movedURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.moveItem(at: originalURL, to: movedURL) + + let second = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + + guard case .deduplicated(let record) = second else { + Issue.record("Expected content deduplication beyond the sidebar budget") + return + } + #expect(record.relativePath == "organized/final.txt") + } + + @Test("Content deduplication includes unmanaged ordinary store files") + func deduplicatesUnmanagedStoreFile() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "same bytes", + named: "result.txt", + under: root.appendingPathComponent("outside") + ) + _ = try ArtifactTestSupport.write( + "same bytes", + named: "organized/final.txt", + under: root.appendingPathComponent(".cmux") + ) + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext(projectRoot: root, workspaceID: "one", sessionID: "two") + + let outcome = try await repository.importFile( + sourceURL: source, + context: context, + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + + guard case .deduplicated(let record) = outcome else { + Issue.record("Expected unmanaged ordinary file content to deduplicate") + return + } + #expect(record.relativePath == "organized/final.txt") + } + + @Test("A moved session folder remains the target for later captures") + func reusesMovedSessionFolder() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let context = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace-one", + sessionID: "session-one", + agentName: "codex" + ) + let firstSource = try ArtifactTestSupport.write("first", named: "first.md", under: root) + let first = try await repository.importFile( + sourceURL: firstSource, + context: context, + provenance: .created, + configuration: .defaultValue, + capturedAt: .now + ) + let firstRecord = try #require(first.record) + let originalSession = root.appendingPathComponent(".cmux/\(firstRecord.relativePath)") + .deletingLastPathComponent() + .deletingLastPathComponent() + let movedSession = root.appendingPathComponent(".cmux/organized/renamed-session") + try FileManager.default.createDirectory( + at: movedSession.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.moveItem(at: originalSession, to: movedSession) + let secondSource = try ArtifactTestSupport.write("second", named: "second.md", under: root) + + let second = try await repository.importFile( + sourceURL: secondSource, + context: context, + provenance: .created, + configuration: .defaultValue, + capturedAt: .now + ) + + #expect(second.record?.relativePath == "organized/renamed-session/artifacts/second.md") + } + + @Test("A moved workspace-only session remains the capture destination") + func reusesMovedWorkspaceOnlySession() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let firstContext = ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace-one", + agentName: "codex" + ) + let firstSource = try ArtifactTestSupport.write("first", named: "first.md", under: root) + let first = try await repository.importFile( + sourceURL: firstSource, + context: firstContext, + provenance: .created, + configuration: .defaultValue, + capturedAt: .now + ) + let firstRecord = try #require(first.record) + let originalSession = root.appendingPathComponent(".cmux/\(firstRecord.relativePath)") + .deletingLastPathComponent() + .deletingLastPathComponent() + let movedSession = root.appendingPathComponent(".cmux/my-organized-workspace") + try FileManager.default.moveItem(at: originalSession, to: movedSession) + let secondSource = try ArtifactTestSupport.write("second", named: "second.md", under: root) + + let second = try await repository.importFile( + sourceURL: secondSource, + context: ArtifactCaptureContext( + projectRoot: root, + workspaceID: "workspace-one", + agentName: "codex" + ), + provenance: .created, + configuration: .defaultValue, + capturedAt: .now + ) + + #expect(second.record?.relativePath == "my-organized-workspace/artifacts/second.md") + } + + @Test("A nested cmux project is excluded by its enclosing Git repository") + func ignoresNestedProjectStore() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + #expect(try runGit(["init", "--quiet", root.path]) == 0) + let project = root.appendingPathComponent("nested/project") + let reorganized = try ArtifactTestSupport.write( + "private", + named: "organized/final.txt", + under: project.appendingPathComponent(".cmux") + ) + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: project)) + + #expect(try runGit([ + "-C", root.path, "check-ignore", "--quiet", "--", + "nested/project/.cmux/organized/final.txt", + ]) == 0) + #expect(FileManager.default.fileExists(atPath: reorganized.path)) + } + + @Test("A linked worktree uses the common Git exclude file") + func ignoresStoreFromLinkedWorktree() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let commonGitDirectory = root.appendingPathComponent("repository/.git") + let worktreeGitDirectory = commonGitDirectory.appendingPathComponent("worktrees/feature") + let worktree = root.appendingPathComponent("feature") + try FileManager.default.createDirectory(at: worktreeGitDirectory, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: worktree, withIntermediateDirectories: true) + try "../..\n".write( + to: worktreeGitDirectory.appendingPathComponent("commondir"), + atomically: true, + encoding: .utf8 + ) + try "\(worktree.appendingPathComponent(".git").path)\n".write( + to: worktreeGitDirectory.appendingPathComponent("gitdir"), + atomically: true, + encoding: .utf8 + ) + try "gitdir: \(worktreeGitDirectory.path)\n".write( + to: worktree.appendingPathComponent(".git"), + atomically: true, + encoding: .utf8 + ) + + let repository = LocalArtifactRepository() + try await repository.prepareForMutation(paths: ArtifactStorePaths(projectRoot: worktree)) + + let exclude = try String( + contentsOf: commonGitDirectory.appendingPathComponent("info/exclude"), + encoding: .utf8 + ) + #expect(exclude == ArtifactGitIgnoreManager.ignoreEntries.joined(separator: "\n") + "\n") + #expect(!FileManager.default.fileExists( + atPath: worktreeGitDirectory.appendingPathComponent("info/exclude").path + )) + } + + @Test("Search combines fuzzy names with bounded text content") + func searchesNamesAndContents() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let artifactRoot = root.appendingPathComponent(".cmux/session/artifacts") + _ = try ArtifactTestSupport.write("release checklist", named: "launch-plan.md", under: artifactRoot) + _ = try ArtifactTestSupport.write("the hidden needle is here", named: "notes.txt", under: artifactRoot) + let repository = LocalArtifactRepository() + + let filenameResults = try await repository.search(projectRoot: root, query: "lnchpln") + #expect(filenameResults.first?.node.name == "launch-plan.md") + let contentResults = try await repository.search(projectRoot: root, query: "needle") + #expect(contentResults.first?.node.name == "notes.txt") + #expect(contentResults.first?.matchedContent == true) + #expect(contentResults.first?.snippet == "the hidden needle is here") + } + + @Test("Partial configuration inherits conservative defaults") + func loadsPartialConfiguration() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + _ = try ArtifactTestSupport.write( + #"{"automaticCaptureEnabled":false,"maximumFileBytes":100}"#, + named: "artifacts.json", + under: root.appendingPathComponent(".cmux") + ) + let configuration = await LocalArtifactRepository().configuration(projectRoot: root) + #expect(configuration.automaticCaptureEnabled == false) + #expect(configuration.maximumFileBytes == 100) + #expect(configuration.maximumTextFileBytes == 100) + #expect(configuration.maximumTranscriptScanBytes == ArtifactCaptureConfiguration.defaultValue.maximumTranscriptScanBytes) + #expect(configuration.allowedExtensions == ArtifactCaptureConfiguration.defaultValue.allowedExtensions) + } + + @Test("Import rejects files larger than the configured text limit") + func rejectsOversizedTextFile() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let source = try ArtifactTestSupport.write( + "five!", + named: "oversized.txt", + under: root.appendingPathComponent("outside") + ) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.maximumTextFileBytes = 4 + + await #expect( + throws: ArtifactStoreError.fileTooLarge(actual: 5, limit: 4) + ) { + try await LocalArtifactRepository().importFile( + sourceURL: source, + context: ArtifactCaptureContext(projectRoot: root), + provenance: .created, + configuration: configuration, + capturedAt: .now + ) + } + #expect(!FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux/session/artifacts/oversized.txt").path + )) + let stagingRoot = ArtifactStorePaths(projectRoot: root).importStagingRoot + let stagingContents = try FileManager.default.contentsOfDirectory(atPath: stagingRoot.path) + #expect(stagingContents.isEmpty) + } + + @Test("Recursive changes reflect external filesystem edits") + func watchesExternalChanges() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let repository = LocalArtifactRepository() + let changes = await repository.changes(projectRoot: root) + + _ = try ArtifactTestSupport.write( + "unrelated project file", + named: "Sources/App.swift", + under: root + ) + let unrelatedObserved = await firstResult( + operation: { + var iterator = changes.makeAsyncIterator() + return await iterator.next() != nil + }, + timeout: .milliseconds(500) + ) + #expect(unrelatedObserved == nil) + + _ = try ArtifactTestSupport.write( + "appeared outside cmux", + named: "external/new-file.md", + under: root.appendingPathComponent(".cmux/session/artifacts") + ) + let observed = await firstResult( + operation: { + var iterator = changes.makeAsyncIterator() + return await iterator.next() != nil + }, + timeout: .seconds(3) + ) + + #expect(observed == true) + } + + @Test("A symlinked cmux filesystem root is rejected without writing through it") + func rejectsSymlinkedFilesystemRoot() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + try FileManager.default.createSymbolicLink( + at: root.appendingPathComponent(".cmux"), + withDestinationURL: outside + ) + let source = try ArtifactTestSupport.write("safe", named: "safe.md", under: root) + + await #expect(throws: ArtifactStoreError.self) { + try await LocalArtifactRepository().importFile( + sourceURL: source, + context: ArtifactCaptureContext(projectRoot: root), + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty) + } + + @Test("A symlinked capture group cannot redirect an import") + func rejectsSymlinkedCaptureGroup() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let outside = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(outside) } + let cmuxRoot = root.appendingPathComponent(".cmux") + try FileManager.default.createDirectory(at: cmuxRoot, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: cmuxRoot.appendingPathComponent("session"), + withDestinationURL: outside + ) + let source = try ArtifactTestSupport.write("safe", named: "safe.md", under: root) + + await #expect(throws: ArtifactStoreError.self) { + try await LocalArtifactRepository().importFile( + sourceURL: source, + context: ArtifactCaptureContext(projectRoot: root), + provenance: .manual, + configuration: .defaultValue, + capturedAt: .now + ) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty) + } + + @discardableResult + private func runGit(_ arguments: [String]) throws -> Int32 { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = arguments + try process.run() + process.waitUntilExit() + return process.terminationStatus + } + + private func firstResult( + operation: @escaping @Sendable () async -> Bool, + timeout: Duration + ) async -> Bool? { + await withTaskGroup(of: Bool?.self) { group in + group.addTask { await operation() } + group.addTask { + // This bounded test deadline prevents a broken watcher from hanging the suite. + try? await Task.sleep(for: timeout) + return nil + } + let result = await group.next() ?? nil + group.cancelAll() + return result + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ProvenanceCorruptingFileManager.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ProvenanceCorruptingFileManager.swift new file mode 100644 index 000000000000..b6dfdb29f0b2 --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/ProvenanceCorruptingFileManager.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Injects a concurrent provenance corruption immediately after the artifact move. +final class ProvenanceCorruptingFileManager: FileManager, @unchecked Sendable { + private let metadataURL: URL + + init(metadataURL: URL) { + self.metadataURL = metadataURL + super.init() + } + + override func moveItem(at srcURL: URL, to dstURL: URL) throws { + try super.moveItem(at: srcURL, to: dstURL) + try FileManager.default.createDirectory( + at: metadataURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Data("{corrupt".utf8).write(to: metadataURL) + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarArtifactStore.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarArtifactStore.swift new file mode 100644 index 000000000000..a9f931db65de --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarArtifactStore.swift @@ -0,0 +1,109 @@ +import Foundation +@testable import CmuxArtifacts + +actor SidebarArtifactStore: ArtifactStoring { + let root: URL + private var nodes: [ArtifactNode] + private var searchResults: [ArtifactSearchResult] = [] + private var continuations: [AsyncStream.Continuation] = [] + private(set) var lastQuery: String? + private(set) var snapshotCount = 0 + private var suspendsNextLocate = false + private var locateIsSuspended = false + private var locateStarted: CheckedContinuation? + private var locateRelease: CheckedContinuation? + + init(root: URL, nodes: [ArtifactNode]) { + self.root = root.standardizedFileURL + self.nodes = nodes + } + + func setSearchResults(_ results: [ArtifactSearchResult]) { + searchResults = results + } + + func replaceNodes(_ nodes: [ArtifactNode], notify: Bool) { + self.nodes = nodes + if notify { continuations.forEach { $0.yield(()) } } + } + + func waitUntilWatching() async -> Bool { + for _ in 0..<100 { + if !continuations.isEmpty { return true } + // Bounded test deadline while the model starts its watcher task. + try? await Task.sleep(for: .milliseconds(10)) + } + return !continuations.isEmpty + } + + func settledSnapshotCount() async -> Int { + // Bounded test deadline that lets an already-buffered watcher event run. + try? await Task.sleep(for: .milliseconds(100)) + return snapshotCount + } + + func suspendNextLocate() { + suspendsNextLocate = true + } + + func waitUntilLocateStarts() async { + guard !locateIsSuspended else { return } + await withCheckedContinuation { continuation in + locateStarted = continuation + } + } + + func releaseLocate() { + locateRelease?.resume() + locateRelease = nil + } + + func locateProjectRoot(startingAt: URL) async -> URL { + if suspendsNextLocate { + suspendsNextLocate = false + locateIsSuspended = true + locateStarted?.resume() + locateStarted = nil + await withCheckedContinuation { continuation in + locateRelease = continuation + } + locateIsSuspended = false + } + return root + } + func configuration(projectRoot: URL) -> ArtifactCaptureConfiguration { .defaultValue } + func snapshot(projectRoot: URL) -> ArtifactSnapshot { + snapshotCount += 1 + return ArtifactSnapshot( + projectRoot: root, + filesystemRoot: root.appendingPathComponent(".cmux", isDirectory: true), + nodes: nodes, + isTruncated: false + ) + } + + func search(projectRoot: URL, query: String) -> [ArtifactSearchResult] { + lastQuery = query + return searchResults + } + + func importFile( + sourceURL: URL, + context: ArtifactCaptureContext, + provenance: ArtifactProvenance, + configuration: ArtifactCaptureConfiguration, + capturedAt: Date + ) throws -> ArtifactImportOutcome { + throw ArtifactStoreError.sourceNotRegularFile(sourceURL.path) + } + + func resolve(projectRoot: URL, name: String) throws -> ArtifactNode { + throw ArtifactStoreError.artifactNotFound(name) + } + + func changes(projectRoot: URL) -> AsyncStream { + let pair = AsyncStream.makeStream() + continuations.append(pair.continuation) + return pair.stream + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarCaptureSpy.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarCaptureSpy.swift new file mode 100644 index 000000000000..8ab0c9b0091c --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SidebarCaptureSpy.swift @@ -0,0 +1,46 @@ +import Foundation +@testable import CmuxArtifacts + +actor SidebarCaptureSpy: ArtifactCapturing { + private let rejectedSourceURLs: Set + private(set) var addCallCount = 0 + private(set) var addedSourceURLs: [URL] = [] + private(set) var lastContext: ArtifactCaptureContext? + + init(rejectedSourceURLs: Set = []) { + self.rejectedSourceURLs = rejectedSourceURLs + } + + func capture( + candidates: [ArtifactCandidate], + context: ArtifactCaptureContext, + capturedAt: Date + ) -> [ArtifactImportOutcome] { + candidates.map { _ in .skipped(.automaticCaptureDisabled) } + } + + func add( + sourceURLs: [URL], + context: ArtifactCaptureContext, + capturedAt: Date + ) -> [ArtifactImportAttempt] { + addCallCount += 1 + addedSourceURLs.append(contentsOf: sourceURLs) + lastContext = context + return sourceURLs.map { sourceURL in + if rejectedSourceURLs.contains(sourceURL) { + return .rejected(.unsupportedExtension(sourceURL.pathExtension)) + } + return .imported(.alreadyStored(ArtifactRecord( + digest: "digest", + sourcePath: sourceURL.path, + relativePath: sourceURL.lastPathComponent, + workspaceID: context.workspaceID, + sessionID: context.sessionID, + provenance: .manual, + capturedAt: capturedAt, + size: 1 + ))) + } + } +} diff --git a/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SystemArtifactGitCommandRunnerTests.swift b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SystemArtifactGitCommandRunnerTests.swift new file mode 100644 index 000000000000..fa6b8ef39d7a --- /dev/null +++ b/Packages/macOS/CmuxArtifacts/Tests/CmuxArtifactsTests/SystemArtifactGitCommandRunnerTests.swift @@ -0,0 +1,82 @@ +import Foundation +import Testing + +@testable import CmuxArtifacts + +@Suite("System artifact Git command runner") +struct SystemArtifactGitCommandRunnerTests { + @Test("Ambient Git repository overrides are removed") + func removesAmbientGitOverrides() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + try runGit(["init", "--quiet", root.path]) + let tracked = try ArtifactTestSupport.write("tracked", named: "tracked.md", under: root) + try runGit(["-C", root.path, "add", "tracked.md"]) + let alternateIndex = root.appendingPathComponent("alternate-index") + var environment = ProcessInfo.processInfo.environment + environment["GIT_INDEX_FILE"] = alternateIndex.path + environment["GIT_WORK_TREE"] = root.appendingPathComponent("wrong-worktree").path + let runner = SystemArtifactGitCommandRunner(environment: environment) + + let status = try await runner.terminationStatus(arguments: [ + "-C", root.path, + "ls-files", "--error-unmatch", "--", tracked.lastPathComponent, + ]) + + #expect(status == 0) + } + + @Test("Cancellation terminates a running command promptly") + func cancelsRunningCommand() async throws { + let root = try ArtifactTestSupport.temporaryDirectory() + defer { ArtifactTestSupport.remove(root) } + let started = root.appendingPathComponent("started") + let runner = SystemArtifactGitCommandRunner( + executableURL: URL(fileURLWithPath: "/bin/sh"), + environment: ["PATH": "/usr/bin:/bin"], + timeout: 5 + ) + let task = Task { + try await runner.terminationStatus(arguments: [ + "-c", "printf ready > \(started.path); while :; do :; done", + ]) + } + #expect(await waitUntilFileExists(started)) + + task.cancel() + + await #expect(throws: CancellationError.self) { + _ = try await task.value + } + } + + @Test("The command deadline terminates a stalled child") + func timesOutStalledCommand() async throws { + let runner = SystemArtifactGitCommandRunner( + executableURL: URL(fileURLWithPath: "/bin/sh"), + environment: ["PATH": "/usr/bin:/bin"], + timeout: 0.05 + ) + + await #expect(throws: ArtifactGitCommandError.timedOut) { + _ = try await runner.terminationStatus(arguments: ["-c", "while :; do :; done"]) + } + } + + private func waitUntilFileExists(_ url: URL) async -> Bool { + for _ in 0..<100 { + if FileManager.default.fileExists(atPath: url.path) { return true } + try? await Task.sleep(for: .milliseconds(10)) + } + return FileManager.default.fileExists(atPath: url.path) + } + + private func runGit(_ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = arguments + try process.run() + process.waitUntilExit() + #expect(process.terminationStatus == 0) + } +} diff --git a/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator+DaemonUpload.swift b/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator+DaemonUpload.swift index 39d130dc7789..39fc155410dc 100644 --- a/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator+DaemonUpload.swift +++ b/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator+DaemonUpload.swift @@ -155,6 +155,7 @@ extension RemoteSessionCoordinator { exec 3<&- exec 4>&- if [ -n "$watchdog_pid" ]; then kill "$watchdog_pid" 2>/dev/null || true; wait "$watchdog_pid" 2>/dev/null || true; fi + rmdir "$lock_path" 2>/dev/null || true watchdog_pid= if [ "$cat_status" -ne 0 ]; then rm -f -- "$temp_path"; fi trap - HUP INT TERM diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BetaFeaturesCatalogSection.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BetaFeaturesCatalogSection.swift index 1336599b4932..1b69f01c8f0b 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BetaFeaturesCatalogSection.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BetaFeaturesCatalogSection.swift @@ -6,6 +6,14 @@ import Foundation /// pattern `.beta.` so the cmux.json view /// groups them sensibly. public struct BetaFeaturesCatalogSection: SettingCatalogSection { + /// Artifacts: persistent project-local capture plus a searchable + /// right-sidebar filesystem tree. Defaults off while the surface is beta. + public let rightSidebarArtifacts = DefaultsKey( + id: "rightSidebar.beta.artifacts.enabled", + defaultValue: false, + userDefaultsKey: "rightSidebar.beta.artifacts.enabled" + ) + /// Right-sidebar Feed: an experimental mode that surfaces inline agent /// decisions (permission prompts, questions) in the right-sidebar mode /// switcher. Defaults off; while off, the Feed mode is hidden from the diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift index 3dfda1747e63..c0153204760f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift @@ -333,6 +333,15 @@ extension Array where Element == CuratedSettingEntry { .init(section: .customSidebars, id: "renderer", title: String(localized: "settings.customSidebars.renderer", defaultValue: "Renderer"), synonyms: "customSidebars.renderer renderer in-process in app remote worker isolated process hover focus typing input"), // Beta + .init( + section: .betaFeatures, + id: "artifacts", + title: String( + localized: "settings.betaFeatures.artifacts", + defaultValue: "Artifacts & Notes" + ), + synonyms: String(localized: "settings.search.alias.setting.betaFeatures.artifacts", defaultValue: "artifacts capture files project local right sidebar agent output beta unstable") + ), .init(section: .betaFeatures, id: "feed", title: "Feed", synonyms: "feed right sidebar agent decisions permissions questions approval beta unstable"), .init(section: .betaFeatures, id: "dock", title: "Dock", synonyms: "dock right sidebar terminal controls tui beta unstable"), .init( diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/SettingsSectionID.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/SettingsSectionID.swift index 1c087adc097a..3740133956d8 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/SettingsSectionID.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/SettingsSectionID.swift @@ -106,7 +106,7 @@ public enum SettingsSectionID: String, CaseIterable, Identifiable, Sendable, Has case .networking: return "iroh relay server private network tailscale vpn direct peer custom provider region" case .sidebarAppearance: return "sidebar details branches material terminal background" case .customSidebars: return "custom sidebars vibe swift json interpreted renderer in-process remote worker isolated" - case .betaFeatures: return "beta experimental unstable feed dock right sidebar" + case .betaFeatures: return "beta experimental unstable artifacts capture feed dock right sidebar" case .automation: return "socket integrations hooks ports claude cursor gemini naming auto naming workspace tabs" case .computerUse: return String( diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BetaFeaturesSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BetaFeaturesSection.swift index d564351a6113..44dc220bc0e3 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BetaFeaturesSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BetaFeaturesSection.swift @@ -7,6 +7,7 @@ import SwiftUI /// off by default. @MainActor public struct BetaFeaturesSection: View { + @State private var artifacts: DefaultsValueModel @State private var feed: DefaultsValueModel @State private var dock: DefaultsValueModel @State private var cloudMachines: DefaultsValueModel @@ -17,6 +18,7 @@ public struct BetaFeaturesSection: View { @State private var workspaceTodosChecklistStyle: DefaultsValueModel public init(defaultsStore: UserDefaultsSettingsStore, catalog: SettingCatalog) { + _artifacts = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.betaFeatures.rightSidebarArtifacts)) _feed = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.betaFeatures.rightSidebarFeed)) _dock = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.betaFeatures.rightSidebarDock)) _cloudMachines = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.betaFeatures.cloudMachines)) @@ -35,6 +37,8 @@ public struct BetaFeaturesSection: View { String(localized: "settings.betaFeatures.warning", defaultValue: "These features are experimental and may change or break. Enable them only when you are testing them.") ) SettingsCardDivider() + artifactsRow + SettingsCardDivider() feedRow SettingsCardDivider() dockRow @@ -57,6 +61,7 @@ public struct BetaFeaturesSection: View { private func startObservingSettings() { let models: [any SettingObservationStarting] = [ + artifacts, feed, dock, cloudMachines, @@ -69,6 +74,32 @@ public struct BetaFeaturesSection: View { models.forEach { $0.startObserving() } } + @ViewBuilder + private var artifactsRow: some View { + SettingsCardRow( + configurationReview: .settingsOnly, + searchAnchorID: "setting:betaFeatures:artifacts", + String( + localized: "settings.betaFeatures.artifacts", + defaultValue: "Artifacts & Notes" + ), + subtitle: artifacts.current + ? String( + localized: "settings.betaFeatures.artifacts.subtitleOn", + defaultValue: "Shows the project’s local artifacts and notes tree in the right sidebar." + ) + : String( + localized: "settings.betaFeatures.artifacts.subtitleOff", + defaultValue: "Hides Artifacts & Notes from the right sidebar until you enable it here." + ) + ) { + Toggle("", isOn: Binding(get: { artifacts.current }, set: { artifacts.set($0) })) + .labelsHidden() + .controlSize(.small) + .accessibilityIdentifier("SettingsBetaArtifactsToggle") + } + } + @ViewBuilder private var workspaceTodoControlsRow: some View { SettingsCardRow( diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift index 670a03c43940..1aa468a7f7bd 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift @@ -170,6 +170,7 @@ struct SettingsRowAnchorResolutionTests { "setting:mobile:iOSPairingHost", "setting:mobile:iOSPairingPort", "setting:mobile:iOSPairingDisplayName", + "setting:betaFeatures:artifacts", "setting:betaFeatures:feed", "setting:betaFeatures:dock", "setting:betaFeatures:cloudMachines", diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 7e3da03ae1de..75e16daf69ca 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -296154,6 +296154,2342 @@ } } }, + "agent.generic.notification.body.needsAttention": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ needs your attention" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ の確認が必要です" + } + } + } + }, + "agent.generic.notification.body.sentNotification": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ sent a notification" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ から通知が届きました" + } + } + } + }, + "cli.artifact.error.addRejected": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact was not added." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトを追加できませんでした。" + } + } + } + }, + "cli.artifact.error.ambiguous": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact name '%@' is ambiguous: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクト名「%@」は複数に一致します: %@" + } + } + } + }, + "cli.artifact.error.batchTooLarge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact batch is too large (%lld bytes; limit %lld)." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトのバッチが大きすぎます(%lld バイト、上限 %lld)。" + } + } + } + }, + "cli.artifact.error.candidateLimit": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact capture batch reached its file limit." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクト取得バッチのファイル数上限に達しました。" + } + } + } + }, + "cli.artifact.error.captureDisabled": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Automatic artifact capture is disabled for this project." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このプロジェクトではアーティファクトの自動取得が無効です。" + } + } + } + }, + "cli.artifact.error.corruptProvenance": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact provenance metadata is corrupt: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトの来歴メタデータが破損しています: %@" + } + } + } + }, + "cli.artifact.error.gitPrivacyPath": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Git privacy could not be verified for artifact store: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアの Git プライバシーを確認できませんでした: %@" + } + } + } + }, + "cli.artifact.error.gitPrivacyUnavailable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Automatic capture paused because Git does not prove the artifact store is ignored and untracked." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアが無視され未追跡であることを Git で確認できないため、自動取得を一時停止しました。" + } + } + } + }, + "cli.artifact.error.missingOperand": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "artifact %@ requires a value" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "artifact %@ には値が必要です" + } + } + } + }, + "cli.artifact.error.notFile": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not a regular file: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通常のファイルではありません: %@" + } + } + } + }, + "cli.artifact.error.notFound": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact not found: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトが見つかりません: %@" + } + } + } + }, + "cli.artifact.error.openFailed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not open artifact at %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ のアーティファクトを開けませんでした" + } + } + } + }, + "cli.artifact.error.outsideStore": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact path escaped the store: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトのパスがストア外を指しています: %@" + } + } + } + }, + "cli.artifact.error.projectValue": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "artifact: --project requires a path" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "artifact: --project にはパスが必要です" + } + } + } + }, + "cli.artifact.error.provenanceRejected": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The file does not meet this project's artifact capture rules." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このファイルはプロジェクトのアーティファクト取得ルールを満たしていません。" + } + } + } + }, + "cli.artifact.error.rejectedCorruptProvenance": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact store's provenance metadata is corrupt." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアの来歴メタデータが破損しています。" + } + } + } + }, + "cli.artifact.error.rejectedExtension": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The file extension is not allowed by this project's artifact settings." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このファイルの拡張子はプロジェクトのアーティファクト設定で許可されていません。" + } + } + } + }, + "cli.artifact.error.rejectedNotFile": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact path is not a regular file." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトのパスは通常のファイルではありません。" + } + } + } + }, + "cli.artifact.error.rejectedOutsideStore": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact path escaped the local store." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトのパスがローカルストア外を指しています。" + } + } + } + }, + "cli.artifact.error.rejectedSize": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The file exceeds this project's artifact size limit." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このファイルはプロジェクトのアーティファクトサイズ上限を超えています。" + } + } + } + }, + "cli.artifact.error.scanIncomplete": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact scan reached its safety limit: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトのスキャンが安全上限に達しました: %@" + } + } + } + }, + "cli.artifact.error.scanIncompleteCandidate": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact store is too large to scan safely right now." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアが大きすぎるため、安全にスキャンできません。" + } + } + } + }, + "cli.artifact.error.storeBusy": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The artifact store is busy. Try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアは使用中です。もう一度お試しください。" + } + } + } + }, + "cli.artifact.error.storeBusyPath": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact store is busy: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトストアは使用中です: %@" + } + } + } + }, + "cli.artifact.error.tooLarge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifact is too large (%lld bytes; limit %lld)." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトが大きすぎます(%lld バイト、上限 %lld)。" + } + } + } + }, + "cli.artifact.error.unsupported": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported artifact extension: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "未対応のアーティファクト拡張子です: %@" + } + } + } + }, + "cli.artifact.helpLine": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "artifact [--project ]" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "artifact [--project <パス>]" + } + } + } + }, + "cli.artifact.output.empty": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No artifacts found." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトが見つかりません。" + } + } + } + }, + "cli.artifact.output.noMatches": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No artifacts matched." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "一致するアーティファクトはありません。" + } + } + } + }, + "cli.artifact.usage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Usage: cmux artifact list [--project ]\n cmux artifact path [--project ]\n cmux artifact open [--project ]\n cmux artifact add [--project ]\n cmux artifact search [--project ]\n\nBrowse and add ordinary files under agent-session folders in /.cmux.\nCommands work without a running cmux app or socket. The project defaults\nto the nearest ancestor containing .cmux or .git." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "使用法: cmux artifact list [--project <パス>]\n cmux artifact path <名前または相対パス> [--project <パス>]\n cmux artifact open <名前または相対パス> [--project <パス>]\n cmux artifact add <パス> [--project <パス>]\n cmux artifact search <検索語> [--project <パス>]\n\n<プロジェクト>/.cmux 内のエージェントセッションフォルダにある通常ファイルを参照・追加します。\ncmux アプリやソケットが起動していなくても利用できます。プロジェクトは、\n.cmux または .git を含む最も近い親ディレクトリが既定です。" + } + } + } + }, + "cli.coderouter.error.notFound": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذر العثور على أداة سطر الأوامر المطلوبة. ثبّت الأمر ثم أعد المحاولة." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Traženi CLI nije pronađen. Instalirajte naredbu i pokušajte ponovo." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Den nødvendige CLI blev ikke fundet. Installer kommandoen, og prøv igen." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die erforderliche CLI wurde nicht gefunden. Installieren Sie den Befehl und versuchen Sie es erneut." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Required CLI not found. Install the command and retry." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontró la CLI necesaria. Instala el comando y vuelve a intentarlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La CLI requise est introuvable. Installez la commande, puis réessayez." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La CLI richiesta non è stata trovata. Installa il comando e riprova." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "必要な CLI が見つかりません。コマンドをインストールして、もう一度お試しください。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "រកមិនឃើញ CLI ដែលត្រូវការ។ សូមដំឡើងពាក្យបញ្ជា ហើយព្យាយាមម្ដងទៀត។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "필요한 CLI를 찾을 수 없습니다. 명령을 설치한 후 다시 시도하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fant ikke den nødvendige CLI-en. Installer kommandoen og prøv igjen." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie znaleziono wymaganej CLI. Zainstaluj polecenie i spróbuj ponownie." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A CLI necessária não foi encontrada. Instale o comando e tente novamente." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Не удалось найти необходимый CLI. Установите команду и повторите попытку." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบ CLI ที่จำเป็น โปรดติดตั้งคำสั่งแล้วลองอีกครั้ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Gerekli CLI bulunamadı. Komutu yükleyip tekrar deneyin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Не знайдено потрібний CLI. Установіть команду та повторіть спробу." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未找到所需的 CLI。请安装该命令后重试。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "找不到必要的 CLI。請安裝該命令後再試一次。" + } + } + } + }, + "cli.hooks.kimi.legacyCleanupWarning": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Warning: cmux hooks are active at %@, but cmux could not remove its legacy hook block from %@. Check that path and re-run `cmux hooks setup kimi` to finish cleanup." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "警告: cmux hooks は %@ で有効ですが、従来の hook ブロックを %@ から削除できませんでした。そのパスを確認し、`cmux hooks setup kimi` を再実行してクリーンアップを完了してください。" + } + } + } + }, + "cli.hooks.kimi.legacyUninstallWarning": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Warning: cmux could not remove its legacy hook block from %@. Check that path and re-run `cmux hooks uninstall kimi` to finish cleanup." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "警告: 従来の hook ブロックを %@ から削除できませんでした。そのパスを確認し、`cmux hooks uninstall kimi` を再実行してクリーンアップを完了してください。" + } + } + } + }, + "cli.note.error.ambiguous": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note name '%@' is ambiguous: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノート名「%@」は曖昧です: %@" + } + } + } + }, + "cli.note.error.confirmDelete": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "note rm permanently deletes a note; pass --yes to confirm." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "note rm はノートを完全に削除します。確認するには --yes を渡してください。" + } + } + } + }, + "cli.note.error.input": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "note write and append require exactly one of --text or --stdin" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "note write と append には --text または --stdin のどちらか一方が必要です" + } + } + } + }, + "cli.note.error.inputTooLarge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note input exceeds the 4 MiB limit." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノート入力が 4 MiB の上限を超えています。" + } + } + } + }, + "cli.note.error.inputUTF8": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note input must be valid UTF-8." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノート入力は有効な UTF-8 である必要があります。" + } + } + } + }, + "cli.note.error.invalidName": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Invalid note name: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "無効なノート名です: %@" + } + } + } + }, + "cli.note.error.invalidUTF8": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note is not valid UTF-8: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートが有効な UTF-8 ではありません: %@" + } + } + } + }, + "cli.note.error.missingOperand": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "note %@ requires a value" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "note %@ には値が必要です" + } + } + } + }, + "cli.note.error.notFound": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note not found: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートが見つかりません: %@" + } + } + } + }, + "cli.note.error.openFailed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not open note at %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ のノートを開けませんでした" + } + } + } + }, + "cli.note.error.outsideStore": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note path escaped the store: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートのパスがストア外を指しています: %@" + } + } + } + }, + "cli.note.error.projectValue": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "note: --project requires a path" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "note: --project にはパスが必要です" + } + } + } + }, + "cli.note.error.scanIncomplete": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Notes scan reached its safety limit: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートのスキャンが安全上限に達しました: %@" + } + } + } + }, + "cli.note.error.store": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The Notes filesystem could not be updated." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートのファイルシステムを更新できませんでした。" + } + } + } + }, + "cli.note.error.storeBusy": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Notes store is busy: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートストアは使用中です: %@" + } + } + } + }, + "cli.note.error.tooLarge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Note is too large (%lld bytes; limit %lld)." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートが大きすぎます(%lld バイト、上限 %lld)。" + } + } + } + }, + "cli.note.helpLine": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "note [--project ] (rm requires --yes|-y)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "note [--project <パス>] (rm には --yes|-y が必要)" + } + } + } + }, + "cli.note.output.deleted": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Deleted %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ を削除しました" + } + } + } + }, + "cli.note.output.empty": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No notes found." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ノートが見つかりません。" + } + } + } + }, + "cli.note.output.noMatches": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No notes matched." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "一致するノートはありません。" + } + } + } + }, + "cli.note.usage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Usage: cmux note list [--project ]\n cmux note path [--project ]\n cmux note read [--project ]\n cmux note write (--text |--stdin) [--project ]\n cmux note append (--text |--stdin) [--project ]\n cmux note search [--project ]\n cmux note open [--project ]\n cmux note rm [--project ] [--yes|-y]\n\nRead and write ordinary Markdown files under the current agent session's\n/.cmux//notes directory. Commands work without a\nrunning cmux app or socket. Existing notes are rediscovered after moves." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "使用法: cmux note list [--project <パス>]\n cmux note path <名前または相対パス> [--project <パス>]\n cmux note read <名前または相対パス> [--project <パス>]\n cmux note write <名前> (--text <テキスト>|--stdin) [--project <パス>]\n cmux note append <名前> (--text <テキスト>|--stdin) [--project <パス>]\n cmux note search <検索語> [--project <パス>]\n cmux note open <名前または相対パス> [--project <パス>]\n cmux note rm <名前または相対パス> [--project <パス>] [--yes|-y]\n\n現在のエージェントセッションの\n<プロジェクト>/.cmux/<エージェントセッション>/notes ディレクトリにある\n通常の Markdown ファイルを読み書きします。cmux アプリやソケットが\n起動していなくても利用でき、移動した既存ノートも再検出されます。" + } + } + } + }, + "cli.projectFiles.error.ambiguousAgentIdentity": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Multiple agent session identities are present; refusing to assign project files to an inherited parent session." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "複数のエージェントセッション ID が存在するため、継承された親セッションへのプロジェクトファイルの割り当てを拒否しました。" + } + } + } + }, + "cli.projectFiles.error.missingAgentIdentity": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A stable agent session identity is required before writing project files." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトファイルを書き込む前に、安定したエージェントセッション ID が必要です。" + } + } + } + }, + "cli.projectFiles.error.tooManyOpenCopies": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Too many project files are already open; close one and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "開いているプロジェクトファイルが多すぎます。1 つ閉じてから再試行してください。" + } + } + } + }, + "cli.vm.tui.mode.enrolling": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "enrolling this Mac" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac を登録しています" + } + } + } + }, + "featureFlags.artifacts.description": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enables the project-local Artifacts and Notes sidebar and automatic capture." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトローカルのArtifactsとNotesサイドバーおよび自動キャプチャを有効にします。" + } + } + } + }, + "featureFlags.artifacts.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifacts & Notes" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ArtifactsとNotes" + } + } + } + }, + "mobile.chat.artifact.error.capabilityDisabled": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifacts are disabled for this project." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このプロジェクトではArtifactsが無効です。" + } + } + } + }, + "mobile.chat.artifact.error.saveFailed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The file could not be saved to this project’s Artifacts." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このファイルをプロジェクトのアーティファクトに保存できませんでした。" + } + } + } + }, + "mobile.pairing.getApp.prompt": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Don't have it yet?" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "まだお持ちでないですか?" + } + } + } + }, + "mobile.pairing.needsTailscale.body": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This Mac has no Tailscale address, so your iPhone can't reach it. Install Tailscale on this Mac and your iPhone (same account), then refresh." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac には Tailscale アドレスがないため、iPhone から接続できません。この Mac と iPhone の両方に(同じアカウントで)Tailscale をインストールしてから、更新してください。" + } + } + } + }, + "mobile.pairing.req.signIn.subtitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sign in to authorize this Mac for pairing." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac のペアリングを許可するにはサインインしてください。" + } + } + } + }, + "mobile.pairing.req.signIn.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Signed in to cmux" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux にサインイン済み" + } + } + } + }, + "mobile.pairing.req.tailscale.hint": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tailscale must be installed and connected on both this Mac and your iPhone. Both devices must be connected to the same Tailscale network." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac と iPhone の両方に Tailscale をインストールして接続してください。両方のデバイスを同じ Tailscale ネットワークに接続する必要があります。" + } + } + } + }, + "mobile.pairing.req.tailscale.reachable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tailscale is connected on this Mac. It must also be installed and connected on your iPhone. Both devices must be connected to the same Tailscale network." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac は Tailscale に接続済みです。iPhone にも Tailscale をインストールして接続してください。両方のデバイスを同じ Tailscale ネットワークに接続する必要があります。" + } + } + } + }, + "mobile.pairing.req.tailscale.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tailscale" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Tailscale" + } + } + } + }, + "mobile.pairing.signIn.button": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sign In" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サインイン" + } + } + } + }, + "mobile.pairing.signIn.connecting": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "جارٍ الاتصال…" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Povezivanje…" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Forbinder…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Verbindung wird hergestellt…" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Connecting…" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conectando…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Connexion…" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Connessione…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "接続しています…" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "កំពុងភ្ជាប់…" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "연결 중…" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Kobler til…" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Łączenie…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conectando…" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Подключение…" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "กำลังเชื่อมต่อ…" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bağlanıyor…" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Підключення…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在连接…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在連接…" + } + } + } + }, + "mobile.pairing.signIn.openInBrowser": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "فتح في المتصفح" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Otvori u pregledniku" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Åbn i browser" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Im Browser öffnen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Open in Browser" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Abrir en el navegador" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ouvrir dans le navigateur" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Apri nel browser" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブラウザで開く" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បើកក្នុងកម្មវិធីរុករក" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "브라우저에서 열기" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Åpne i nettleser" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Otwórz w przeglądarce" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Abrir no navegador" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Открыть в браузере" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เปิดในเบราว์เซอร์" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Tarayıcıda Aç" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Відкрити у браузері" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "在浏览器中打开" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "在瀏覽器中打開" + } + } + } + }, + "mobile.pairing.signIn.prompt": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sign in with your cmux account to pair your iPhone." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "iPhone をペアリングするには、cmux アカウントでサインインしてください。" + } + } + } + }, + "mobile.pairing.signIn.slowHint": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "قد تتوقف نافذة تسجيل الدخول في النظام عن الاستجابة. إذا لم يحدث شيء، فافتح تسجيل الدخول في المتصفح الافتراضي بدلاً من ذلك." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Sistemski prozor za prijavu može prestati odgovarati. Ako se ništa ne dogodi, otvorite prijavu u zadanom pregledniku." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Systemets loginvindue kan holde op med at svare. Hvis der ikke sker noget, skal du i stedet åbne login i din standardbrowser." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das System-Anmeldefenster reagiert möglicherweise nicht mehr. Wenn nichts passiert, öffne die Anmeldung stattdessen in deinem Standardbrowser." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The system sign-in window may stop responding. If nothing happens, open sign-in in your default browser instead." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La ventana de inicio de sesión del sistema puede dejar de responder. Si no sucede nada, abre el inicio de sesión en tu navegador predeterminado." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La fenêtre de connexion du système peut ne plus répondre. Si rien ne se passe, ouvrez plutôt la connexion dans votre navigateur par défaut." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La finestra di accesso di sistema potrebbe smettere di rispondere. Se non succede nulla, apri l’accesso nel browser predefinito." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "システムのサインインウィンドウが応答しなくなることがあります。何も起きない場合は、デフォルトのブラウザでサインインを開いてください。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បង្អួចចូលគណនីរបស់ប្រព័ន្ធអាចឈប់ឆ្លើយតប។ ប្រសិនបើគ្មានអ្វីកើតឡើង សូមបើកការចូលគណនីក្នុងកម្មវិធីរុករកលំនាំដើមរបស់អ្នកជំនួសវិញ។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "시스템 로그인 창이 응답하지 않을 수 있습니다. 아무 반응이 없으면 기본 브라우저에서 로그인을 열어 주세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Systemets påloggingsvindu kan slutte å svare. Hvis ingenting skjer, åpner du påloggingen i standardnettleseren i stedet." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Systemowe okno logowania może przestać odpowiadać. Jeśli nic się nie dzieje, otwórz logowanie w domyślnej przeglądarce." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A janela de login do sistema pode parar de responder. Se nada acontecer, abra o login no navegador padrão." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Системное окно входа может перестать отвечать. Если ничего не происходит, откройте вход в браузере по умолчанию." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "หน้าต่างลงชื่อเข้าของระบบอาจหยุดตอบสนอง หากไม่มีอะไรเกิดขึ้น ให้เปิดการลงชื่อเข้าในเบราว์เซอร์เริ่มต้นแทน" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Sistem oturum açma penceresi yanıt vermeyi durdurabilir. Hiçbir şey olmazsa oturum açmayı varsayılan tarayıcınızda açın." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Системне вікно входу може перестати відповідати. Якщо нічого не відбувається, відкрийте вхід у браузері за умовчанням." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "系统登录窗口可能会停止响应。如果没有任何反应,请改用默认浏览器打开登录。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "系統登入視窗可能會停止回應。如果沒有任何反應,請改用預設瀏覽器開啟登入。" + } + } + } + }, + "mobile.pairing.step.install": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Install cmux on your iPhone and open it." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "iPhone に cmux をインストールして開きます。" + } + } + } + }, + "mobile.pairing.step.scan": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "On your iPhone, choose Tailscale, tap Scan QR Code, then scan the code above." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "接続方法として Tailscale を選び、「QR コードをスキャン」をタップして上のコードにカメラを向けます。" + } + } + } + }, + "mobile.pairing.step.signIn": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sign in with the same account you use on this Mac." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac と同じアカウントでサインインします。" + } + } + } + }, + "mobile.pairing.window.heading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pair your iPhone with Tailscale" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "TailscaleでiPhoneをペアリング" + } + } + } + }, + "mobile.pairing.window.subheading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "iPhones on your cmux account connect automatically. Use this code only for Tailscale." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "同じ cmux アカウントでサインインしている iPhone は自動的に接続されます。iPhone の接続方法で Tailscale を選択した場合は、このコードを使用してください。" + } + } + } + }, + "rightSidebar.artifacts.add": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add Artifact…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトを追加…" + } + } + } + }, + "rightSidebar.artifacts.add.tooltip": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add files to Artifacts" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ファイルをアーティファクトに追加" + } + } + } + }, + "rightSidebar.artifacts.addFailed.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The file may be unsupported or larger than this project’s capture limit." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "未対応のファイルか、プロジェクトの取得上限を超えている可能性があります。" + } + } + } + }, + "rightSidebar.artifacts.addFailed.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t Add Artifact" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトを追加できませんでした" + } + } + } + }, + "rightSidebar.artifacts.addPanel.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose small files to copy into this project’s local artifact store." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このプロジェクトのローカルアーティファクトストアにコピーする小さなファイルを選択してください。" + } + } + } + }, + "rightSidebar.artifacts.addPanel.prompt": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "追加" + } + } + } + }, + "rightSidebar.artifacts.addPanel.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add to cmux Artifacts" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux アーティファクトに追加" + } + } + } + }, + "rightSidebar.artifacts.collapse": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Collapse folder" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "フォルダを折りたたむ" + } + } + } + }, + "rightSidebar.artifacts.copyPath": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy Path" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "パスをコピー" + } + } + } + }, + "rightSidebar.artifacts.copyReference": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy Reference" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "参照をコピー" + } + } + } + }, + "rightSidebar.artifacts.empty.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Files in each agent session’s artifacts and notes folders will appear here." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "各エージェントセッションの artifacts と notes フォルダ内のファイルがここに表示されます。" + } + } + } + }, + "rightSidebar.artifacts.empty.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Artifacts or Notes Yet" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトやノートはまだありません" + } + } + } + }, + "rightSidebar.artifacts.expand": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expand folder" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "フォルダを展開" + } + } + } + }, + "rightSidebar.artifacts.loadFailed.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check the project folder and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトフォルダを確認して、もう一度お試しください。" + } + } + } + }, + "rightSidebar.artifacts.loadFailed.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t Load Project Files" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトファイルを読み込めませんでした" + } + } + } + }, + "rightSidebar.artifacts.loading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Loading artifacts and notes" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトとノートを読み込み中" + } + } + } + }, + "rightSidebar.artifacts.noResults.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try another filename or text search." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "別のファイル名またはテキストで検索してください。" + } + } + } + }, + "rightSidebar.artifacts.noResults.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Matches" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "一致する項目はありません" + } + } + } + }, + "rightSidebar.artifacts.noWorkspace.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open a local workspace to browse its artifacts and notes." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ローカルワークスペースを開くと、そのアーティファクトとノートを参照できます。" + } + } + } + }, + "rightSidebar.artifacts.noWorkspace.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Local Workspace" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ローカルワークスペースがありません" + } + } + } + }, + "rightSidebar.artifacts.open": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open File" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ファイルを開く" + } + } + } + }, + "rightSidebar.artifacts.retry": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Retry" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "再試行" + } + } + } + }, + "rightSidebar.artifacts.reveal": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reveal in Finder" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Finder に表示" + } + } + } + }, + "rightSidebar.artifacts.search.placeholder": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Search artifacts and notes" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトとノートを検索" + } + } + } + }, + "rightSidebar.artifacts.searchFailed.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check the project’s .cmux folder and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトの .cmux フォルダを確認して、もう一度お試しください。" + } + } + } + }, + "rightSidebar.artifacts.searchFailed.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t Search Project Files" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトファイルを検索できませんでした" + } + } + } + }, + "rightSidebar.mode.artifacts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifacts & Notes" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトとノート" + } + } + } + }, + "settings.betaFeatures.artifacts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artifacts & Notes" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクトとノート" + } + } + } + }, + "settings.betaFeatures.artifacts.subtitleOff": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hides Artifacts & Notes from the right sidebar until you enable it here." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ここで有効にするまで、右サイドバーからアーティファクトとノートを隠します。" + } + } + } + }, + "settings.betaFeatures.artifacts.subtitleOn": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shows the project’s local artifacts and notes tree in the right sidebar." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プロジェクトのローカルアーティファクトとノートのツリーを右サイドバーに表示します。" + } + } + } + }, + "settings.search.alias.setting.betaFeatures.artifacts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "artifacts notes capture files project local right sidebar agent output beta unstable" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アーティファクト ノート 取得 ファイル プロジェクト ローカル 右サイドバー エージェント 出力 ベータ 不安定" + } + } + } + }, "browser.chromium.automation.commandTimedOut": { "extractionState": "manual", "localizations": { diff --git a/Sources/App/WorkspaceRuntimeSettings.swift b/Sources/App/WorkspaceRuntimeSettings.swift index 153916e82af4..1bce97e0f0a4 100644 --- a/Sources/App/WorkspaceRuntimeSettings.swift +++ b/Sources/App/WorkspaceRuntimeSettings.swift @@ -479,15 +479,38 @@ enum AgentHibernationTrackingGate { } enum RightSidebarBetaFeatureSettings { + static let artifactsEnabledKey = "rightSidebar.beta.artifacts.enabled" static let feedEnabledKey = "rightSidebar.beta.feed.enabled" static let dockEnabledKey = "rightSidebar.beta.dock.enabled" static let cloudMachinesEnabledKey = "cloud.beta.machines.enabled" + static let defaultArtifactsEnabled = false static let defaultFeedEnabled = false static let defaultDockEnabled = false static let defaultCloudMachinesEnabled = false static let didChangeNotification = Notification.Name("rightSidebarBetaFeatureDidChange") + nonisolated static func isArtifactsEnabled(defaults: UserDefaults = .standard) -> Bool { + isArtifactsEnabled( + defaults: defaults, + remoteEnabled: CmuxFeatureFlags.offMainEffectiveValue( + for: CmuxFeatureFlags.artifactsFlag + ) + ) + } + + /// The local beta toggle is an opt-in, while the remote flag is the + /// authoritative production gate and kill switch. + nonisolated static func isArtifactsEnabled( + defaults: UserDefaults, + remoteEnabled: Bool + ) -> Bool { + let localEnabled = defaults.object(forKey: artifactsEnabledKey) == nil + ? defaultArtifactsEnabled + : defaults.bool(forKey: artifactsEnabledKey) + return localEnabled && remoteEnabled + } + nonisolated static func isFeedEnabled(defaults: UserDefaults = .standard) -> Bool { guard defaults.object(forKey: feedEnabledKey) != nil else { return defaultFeedEnabled } return defaults.bool(forKey: feedEnabledKey) diff --git a/Sources/AppDelegate+Artifacts.swift b/Sources/AppDelegate+Artifacts.swift new file mode 100644 index 000000000000..00822c674c35 --- /dev/null +++ b/Sources/AppDelegate+Artifacts.swift @@ -0,0 +1,52 @@ +import CmuxSettings +import Foundation + +extension AppDelegate { + @discardableResult + func openArtifactPatch( + _ file: ArtifactSidebarFileAccess.OpenedFile, + for tabManager: TabManager? + ) -> Bool { + guard let workspace = tabManager?.selectedWorkspace, + let cliURL = Bundle.main.resourceURL?.appendingPathComponent("bin/cmux"), + FileManager.default.isExecutableFile(atPath: cliURL.path), + let descriptor = file.duplicateForChildProcess() else { + return false + } + let socketPath = TerminalController.shared.activeSocketPath( + preferredPath: SocketControlSettings.socketPath() + ) + return launchDiffViewerProcess( + cliURL: cliURL, + socketPath: socketPath, + cwd: workspace.resolvedWorkingDirectory() ?? file.sourceURL.deletingLastPathComponent().path, + workspaceId: workspace.id, + surfaceId: workspace.focusedPanelId, + useLastTurnSource: false, + sessionId: nil, + patchFileDescriptor: descriptor + ) + } + + @discardableResult + func openArtifactPatch(_ fileURL: URL, for tabManager: TabManager?) -> Bool { + guard let workspace = tabManager?.selectedWorkspace, + let cliURL = Bundle.main.resourceURL?.appendingPathComponent("bin/cmux"), + FileManager.default.isExecutableFile(atPath: cliURL.path) else { + return false + } + let socketPath = TerminalController.shared.activeSocketPath( + preferredPath: SocketControlSettings.socketPath() + ) + return launchDiffViewerProcess( + cliURL: cliURL, + socketPath: socketPath, + cwd: workspace.resolvedWorkingDirectory() ?? fileURL.deletingLastPathComponent().path, + workspaceId: workspace.id, + surfaceId: workspace.focusedPanelId, + useLastTurnSource: false, + sessionId: nil, + patchFileURL: fileURL + ) + } +} diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 0a9ac6bf963e..e89aa6683ab5 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -1,5 +1,6 @@ import AppKit import CmuxAppKitSupportUI +import CmuxArtifacts import CmuxAuthRuntime import CmuxBrowser import CmuxCommandPalette @@ -828,7 +829,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent /// Strongly-held observers for every active TabManager. Each observer owns /// Combine subscriptions that publish workspace.updated to mobile clients. private var mobileWorkspaceListObservers: [ObjectIdentifier: MobileWorkspaceListObserver] = [:] - private let agentChatTranscriptService = AgentChatTranscriptService() + let artifactRepository = LocalArtifactRepository() + lazy var artifactCaptureService = ArtifactCaptureService(store: artifactRepository) + private lazy var agentArtifactCaptureCoordinator = AgentArtifactCaptureCoordinator(captureService: artifactCaptureService) + private lazy var agentChatTranscriptService = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: agentArtifactCaptureCoordinator, + isAutomaticArtifactCaptureEnabled: { + RightSidebarBetaFeatureSettings.isArtifactsEnabled() + } + ) /// The app's settings dependency container, handed over by `cmuxApp` via /// `configure(...)` before any main window is created. AppKit builds the /// main window's `NSHostingView` itself, so it injects this into the @@ -846,7 +856,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private var shortcutMonitor: Any? private var shortcutDefaultsObserver: NSObjectProtocol? private var menuBarVisibilityObserver: NSObjectProtocol? - private var mobileHostSettingsObserver: NSObjectProtocol? + private var runtimeServiceSettingsObserver: NSObjectProtocol? + private var runtimeServiceFeatureFlagsObserver: NSObjectProtocol? /// Applies MDM managed-policy transitions (browser/remote-control) while /// the app runs. Installed once from `installManagedPolicyEnforcement()`. var managedPolicyEnforcementObserver: ManagedPolicyEnforcementObserver? @@ -2555,7 +2566,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ensureMobileWorkspaceListObserver(for: tabManager) MobileTerminalRenderObserver.shared.start() agentChatTranscriptService.start() - installMobileHostSettingsObserver() + installRuntimeServiceSettingsObserver() installManagedPolicyEnforcement() scheduleGhosttyCrashBreadcrumbIfNeeded(notificationStore: notificationStore) startPaneMemoryGuardrailIfNeeded() @@ -7203,6 +7214,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent surfaceId: UUID?, useLastTurnSource: Bool, sessionId: String?, + patchFileURL: URL? = nil, + patchFileDescriptor: Int32? = nil, focus: Bool = true ) -> Bool { let process = Process() @@ -7210,11 +7223,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var arguments = [ "--socket", socketPath, "diff", - useLastTurnSource ? "--last-turn" : "--unstaged", + ] + if let patchFileDescriptor { + arguments.append("/dev/fd/\(patchFileDescriptor)") + } else if let patchFileURL { + arguments.append(patchFileURL.path) + } else { + arguments.append(useLastTurnSource ? "--last-turn" : "--unstaged") + } + arguments.append(contentsOf: [ "--cwd", cwd, "--workspace", workspaceId.uuidString, "--focus", focus ? "true" : "false", - ] + ]) if let surfaceId { arguments.append(contentsOf: ["--surface", surfaceId.uuidString]) } @@ -7240,6 +7261,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent let outputCollector = ProcessOutputCollector(stdout: stdoutPipe, stderr: stderrPipe) outputCollector.start() process.terminationHandler = { terminatedProcess in + if let patchFileDescriptor { + _ = close(patchFileDescriptor) + } let output = outputCollector.finish() let processIdentifier = terminatedProcess.processIdentifier let terminationStatus = terminatedProcess.terminationStatus @@ -7267,6 +7291,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent #endif return true } catch { + if let patchFileDescriptor { + _ = close(patchFileDescriptor) + } outputCollector.cancel() #if DEBUG cmuxDebugLog("openDiffViewer failed errorType=\(type(of: error))") @@ -10174,7 +10201,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent let root = ContentView( updateViewModel: updateViewModel, windowId: windowId, - titlebarControlsLayoutModel: titlebarControlsLayoutModel + titlebarControlsLayoutModel: titlebarControlsLayoutModel, + artifactStore: artifactRepository, + artifactCaptureService: artifactCaptureService ) .environmentObject(tabManager) .environmentObject(notificationStore) @@ -10657,21 +10686,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } } - private func installMobileHostSettingsObserver() { - guard mobileHostSettingsObserver == nil else { return } - mobileHostSettingsObserver = NotificationCenter.default.addObserver( + private func installRuntimeServiceSettingsObserver() { + guard runtimeServiceSettingsObserver == nil else { return } + runtimeServiceSettingsObserver = NotificationCenter.default.addObserver( forName: UserDefaults.didChangeNotification, object: nil, queue: .main ) { [weak self] _ in Task { @MainActor [weak self] in - self?.syncMobileHostService() + self?.syncRuntimeServicesToSettings() + } + } + runtimeServiceFeatureFlagsObserver = NotificationCenter.default.addObserver( + forName: .cmuxFeatureFlagsDidChange, + object: CmuxFeatureFlags.shared, + queue: .main + ) { [weak self] _ in + Task { @MainActor [weak self] in + self?.syncRuntimeServicesToSettings() } } } - private func syncMobileHostService() { + private func syncRuntimeServicesToSettings() { MobileHostService.shared.syncToSettings() + agentChatTranscriptService.reconcileAutomaticArtifactCaptureAvailability() } private func syncActivationPolicy(defaults: UserDefaults = .standard) { diff --git a/Sources/ArtifactHTMLPreviewDocument.swift b/Sources/ArtifactHTMLPreviewDocument.swift new file mode 100644 index 000000000000..5af90d4aa87a --- /dev/null +++ b/Sources/ArtifactHTMLPreviewDocument.swift @@ -0,0 +1,117 @@ +import Darwin +import Foundation + +/// A bounded, sandbox-wrapped HTML document safe to load as an artifact preview. +struct ArtifactHTMLPreviewDocument: Sendable { + private static let maximumSourceBytes = 8 * 1024 * 1024 + + let url: URL + + @concurrent + static func load( + sourceURL: URL, + allowedRoot: URL + ) async throws -> ArtifactHTMLPreviewDocument { + try ArtifactHTMLPreviewDocument(sourceURL: sourceURL, allowedRoot: allowedRoot) + } + + private init(sourceURL: URL, allowedRoot: URL) throws { + let source = String( + decoding: try Self.readSource(sourceURL, allowedRoot: allowedRoot), + as: UTF8.self + ) + let wrapper = Self.wrapper(source: source) + let encoded = Data(wrapper.utf8).base64EncodedString() + guard let url = URL(string: "data:text/html;base64,\(encoded)") else { + throw CocoaError(.fileReadCorruptFile) + } + self.url = url + } + + private static func readSource(_ sourceURL: URL, allowedRoot: URL) throws -> Data { + try Task.checkCancellation() + let descriptor = Darwin.open( + sourceURL.path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: sourceURL.path]) + } + defer { Darwin.close(descriptor) } + + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0 else { + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: sourceURL.path]) + } + guard let openedPath = openedPath(for: descriptor), + isPath(openedPath, inside: allowedRoot) else { + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: sourceURL.path]) + } + guard status.st_size <= Self.maximumSourceBytes else { + throw CocoaError(.fileReadTooLarge) + } + + var data = Data() + data.reserveCapacity(min(Int(status.st_size), Self.maximumSourceBytes)) + var buffer = [UInt8]( + repeating: 0, + count: min(64 * 1024, Self.maximumSourceBytes + 1) + ) + while data.count <= Self.maximumSourceBytes { + try Task.checkCancellation() + let requested = min(buffer.count, Self.maximumSourceBytes + 1 - data.count) + guard requested > 0 else { break } + let count = buffer.withUnsafeMutableBytes { bytes in + Darwin.read(descriptor, bytes.baseAddress, requested) + } + if count == 0 { break } + if count < 0 { + if errno == EINTR { continue } + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: sourceURL.path]) + } + data.append(contentsOf: buffer.prefix(count)) + } + guard data.count <= Self.maximumSourceBytes else { + throw CocoaError(.fileReadTooLarge) + } + return data + } + + private static func openedPath(for descriptor: Int32) -> URL? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + let path = String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self) + return URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL + } + + private static func isPath(_ path: URL, inside root: URL) -> Bool { + let rootPath = root.resolvingSymlinksInPath().standardizedFileURL.path + let path = path.path + return path == rootPath + || path.hasPrefix(rootPath.hasSuffix("/") ? rootPath : rootPath + "/") + } + + private static func wrapper(source: String) -> String { + let sourceDocument = source + .replacingOccurrences(of: "&", with: "&") + .replacingOccurrences(of: "\"", with: """) + return """ + + + + + + + + + + + """ + } +} diff --git a/Sources/ArtifactHTMLPreviewNavigationPolicy.swift b/Sources/ArtifactHTMLPreviewNavigationPolicy.swift new file mode 100644 index 000000000000..701c87e5833d --- /dev/null +++ b/Sources/ArtifactHTMLPreviewNavigationPolicy.swift @@ -0,0 +1,28 @@ +import Foundation + +/// Restricts artifact previews to their wrapper document and inert `srcdoc` frame. +struct ArtifactHTMLPreviewNavigationPolicy { + let documentURL: URL + + func allowsNavigation(to url: URL?, targetIsMainFrame: Bool?) -> Bool { + guard let url else { return false } + switch targetIsMainFrame { + case true: + return url == documentURL + || Self.withoutFragment(url) == Self.withoutFragment(documentURL) + case false: + let base = Self.withoutFragment(url).absoluteString + return base == "about:srcdoc" || base == "about:blank" + case nil: + return false + } + } + + private static func withoutFragment(_ url: URL) -> URL { + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { + return url + } + components.fragment = nil + return components.url ?? url + } +} diff --git a/Sources/ArtifactHTMLPreviewWebViewFactory.swift b/Sources/ArtifactHTMLPreviewWebViewFactory.swift new file mode 100644 index 000000000000..ba788fc320d8 --- /dev/null +++ b/Sources/ArtifactHTMLPreviewWebViewFactory.swift @@ -0,0 +1,29 @@ +import AppKit +import WebKit + +/// Builds script-free WebViews backed by an explicitly supplied data store. +@MainActor +struct ArtifactHTMLPreviewWebViewFactory { + let websiteDataStore: WKWebsiteDataStore + + func makeConfiguration() -> WKWebViewConfiguration { + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = websiteDataStore + configuration.defaultWebpagePreferences.allowsContentJavaScript = false + configuration.preferences.javaScriptCanOpenWindowsAutomatically = false + return configuration + } + + func makeWebView() -> CmuxWebView { + let webView = CmuxWebView( + frame: .zero, + configuration: makeConfiguration() + ) + webView.allowsBackForwardNavigationGestures = false + webView.underPageBackgroundColor = GhosttyBackgroundTheme.currentColor() + if #available(macOS 13.3, *) { + webView.isInspectable = false + } + return webView + } +} diff --git a/Sources/ArtifactSidebarBinding.swift b/Sources/ArtifactSidebarBinding.swift new file mode 100644 index 000000000000..793cf6d5e79a --- /dev/null +++ b/Sources/ArtifactSidebarBinding.swift @@ -0,0 +1,8 @@ +import Foundation + +/// Immutable identity used to restart artifact-sidebar workspace binding. +struct ArtifactSidebarBinding: Equatable { + let workspaceID: String? + let workingDirectory: URL? + let isVisible: Bool +} diff --git a/Sources/ArtifactSidebarFileAccess.swift b/Sources/ArtifactSidebarFileAccess.swift new file mode 100644 index 000000000000..ad6aa29788ca --- /dev/null +++ b/Sources/ArtifactSidebarFileAccess.swift @@ -0,0 +1,633 @@ +import Darwin +import Foundation +import UniformTypeIdentifiers + +/// Reopens a sidebar row with descriptor-level project-root confinement. +struct ArtifactSidebarFileAccess { + private static let previewDirectoryName = "cmux-artifact-previews" + private static let previewLockName = ".cmux-artifact-previews.lock" + private static let maximumPreviewFileCount = 256 + private static let maximumPreviewByteCount: Int64 = 256 * 1024 * 1024 + let fileManager: FileManager + + /// Keeps the descriptor that passed artifact-root validation alive while a + /// preview or diff reader consumes the file. `/dev/fd` refers to this + /// descriptor, so replacing the original pathname cannot redirect reads. + /// Descriptor-backed state is safe to pass between tasks: URLs are + /// immutable values and every bounded preview read uses `pread` with an + /// explicit offset, so callers never share a mutable file position. + final class OpenedFile: @unchecked Sendable { + let sourceURL: URL + let artifactRoot: URL + private let descriptor: Int32 + let isDirectory: Bool + + var readURL: URL { + URL(fileURLWithPath: "/dev/fd/\(descriptor)", isDirectory: isDirectory) + } + + /// Materializes a bounded, extension-preserving copy for services such + /// as Quick Look that run outside this process and cannot access our + /// descriptor namespace. The caller owns cleanup of the returned URL. + func makeTemporaryPreviewURL(maximumBytes: Int64 = 8 * 1024 * 1024) -> URL? { + guard let duplicate = duplicateReadableDescriptor() else { return nil } + return Self.materializeTemporaryPreview( + descriptor: duplicate, + pathExtension: sourceURL.pathExtension, + maximumBytes: maximumBytes + ) + } + + /// Materializes a preview copy without reading the source on the caller's actor. + /// + /// The descriptor is duplicated synchronously, then all bounded file + /// I/O and allocation run in the concurrent executor. This is used by + /// SwiftUI rows whose task bodies are main-actor isolated. + func makeTemporaryPreviewURLAsync( + maximumBytes: Int64 = 8 * 1024 * 1024 + ) async -> URL? { + guard let duplicate = duplicateReadableDescriptor() else { return nil } + return await Self.materializeTemporaryPreviewOffMain( + descriptor: duplicate, + pathExtension: sourceURL.pathExtension, + maximumBytes: maximumBytes + ) + } + + init( + sourceURL: URL, + artifactRoot: URL, + descriptor: Int32, + isDirectory: Bool = false + ) { + self.sourceURL = sourceURL + self.artifactRoot = artifactRoot + self.descriptor = descriptor + self.isDirectory = isDirectory + } + + /// Duplicates the descriptor for a trusted child process and clears + /// close-on-exec so the child can read its `/dev/fd` path. + func duplicateForChildProcess() -> Int32? { + let duplicate = fcntl(descriptor, F_DUPFD, 3) + guard duplicate >= 0 else { return nil } + let flags = fcntl(duplicate, F_GETFD) + guard flags >= 0, fcntl(duplicate, F_SETFD, flags & ~FD_CLOEXEC) == 0 else { + _ = Darwin.close(duplicate) + return nil + } + return duplicate + } + + private func duplicateReadableDescriptor() -> Int32? { + let duplicate = fcntl(descriptor, F_DUPFD_CLOEXEC, 3) + return duplicate >= 0 ? duplicate : nil + } + + private static func materializeTemporaryPreview( + descriptor: Int32, + pathExtension: String, + maximumBytes: Int64 + ) -> URL? { + defer { _ = Darwin.close(descriptor) } + guard let reservation = reserveTemporaryPreview(maximumBytes: maximumBytes) else { + return nil + } + defer { _ = Darwin.close(reservation.descriptor) } + guard let data = readPreviewData( + descriptor: descriptor, + maximumBytes: maximumBytes + ) else { + discardTemporaryPreview(reservation) + return nil + } + guard let temporaryURL = promoteTemporaryPreview( + reservation: reservation, + byteCount: Int64(data.count), + pathExtension: pathExtension + ) else { + discardTemporaryPreview(reservation) + return nil + } + guard writePreviewData(data, descriptor: reservation.descriptor) else { + _ = unlink(temporaryURL.path) + return nil + } + return temporaryURL + } + + private static func readPreviewData( + descriptor: Int32, + maximumBytes: Int64 + ) -> Data? { + guard maximumBytes >= 0, + maximumBytes <= ArtifactSidebarFileAccess.maximumPreviewByteCount, + maximumBytes < Int64(Int.max) else { + return nil + } + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0 else { + return nil + } + let fileSize = Int64(status.st_size) + let requestedBytes = fileSize >= maximumBytes + ? maximumBytes + 1 + : fileSize + 1 + guard requestedBytes <= Int64(Int.max) else { return nil } + let capacity = Int(requestedBytes) + var data = Data(count: capacity) + let count = data.withUnsafeMutableBytes { buffer -> Int? in + guard let baseAddress = buffer.baseAddress else { return 0 } + var total = 0 + while total < capacity { + let result = Darwin.pread( + descriptor, + baseAddress.advanced(by: total), + capacity - total, + off_t(total) + ) + if result < 0 { + if errno == EINTR { continue } + return nil + } + if result == 0 { break } + total += result + } + return total + } + guard let count, + Int64(count) <= maximumBytes else { + return nil + } + data.removeSubrange(count.. Bool { + data.withUnsafeBytes { buffer in + guard let baseAddress = buffer.baseAddress else { return data.isEmpty } + var total = 0 + while total < data.count { + let result = Darwin.pwrite( + descriptor, + baseAddress.advanced(by: total), + data.count - total, + off_t(total) + ) + if result < 0 { + if errno == EINTR { continue } + return false + } + guard result > 0 else { return false } + total += result + } + return true + } + } + + private static func privatePreviewDirectory() -> URL? { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent( + ArtifactSidebarFileAccess.previewDirectoryName, + isDirectory: true + ) + if mkdir(directory.path, S_IRWXU) != 0, errno != EEXIST { + return nil + } + var status = stat() + guard lstat(directory.path, &status) == 0, + (status.st_mode & S_IFMT) == S_IFDIR, + status.st_uid == geteuid(), + chmod(directory.path, S_IRWXU) == 0 else { + return nil + } + return directory + } + + /// Reserves a quota slot and file size while a BSD lock is held. + /// The lock is deliberately filesystem-backed so separate detached + /// tasks and app/CLI processes cannot both pass the same quota check. + private static func reserveTemporaryPreview( + maximumBytes: Int64 + ) -> (url: URL, descriptor: Int32)? { + guard maximumBytes >= 0, + maximumBytes <= ArtifactSidebarFileAccess.maximumPreviewByteCount, + let directory = privatePreviewDirectory() else { + return nil + } + return withPreviewDirectoryLock(in: directory) { + reclaimStalePreviewFiles(in: directory) + guard let enumerator = FileManager.default.enumerator( + at: directory, + includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey], + options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants] + ) else { + return nil + } + let directoryPath = directory.standardizedFileURL.path + var activeCount = 0 + var activeBytes: Int64 = 0 + for case let entry as URL in enumerator { + guard entry.deletingLastPathComponent().standardizedFileURL.path == directoryPath, + entry.lastPathComponent.hasPrefix("cmux-artifact-") else { + continue + } + var entryStatus = stat() + guard lstat(entry.path, &entryStatus) == 0, + (entryStatus.st_mode & S_IFMT) == S_IFREG, + entryStatus.st_size >= 0 else { + continue + } + let size = Int64(entryStatus.st_size) + activeCount = min( + ArtifactSidebarFileAccess.maximumPreviewFileCount, + activeCount + 1 + ) + if size >= ArtifactSidebarFileAccess.maximumPreviewByteCount + || activeBytes > ArtifactSidebarFileAccess.maximumPreviewByteCount - size { + activeBytes = ArtifactSidebarFileAccess.maximumPreviewByteCount + } else { + activeBytes += size + } + } + guard activeCount < ArtifactSidebarFileAccess.maximumPreviewFileCount, + maximumBytes <= ArtifactSidebarFileAccess.maximumPreviewByteCount - activeBytes else { + return nil + } + let reservationURL = directory.appendingPathComponent( + "cmux-artifact-reservation-\(UUID().uuidString)", + isDirectory: false + ) + let reservationDescriptor = Darwin.open( + reservationURL.path, + O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + guard reservationDescriptor >= 0 else { return nil } + guard ftruncate(reservationDescriptor, off_t(maximumBytes)) == 0 else { + _ = Darwin.close(reservationDescriptor) + _ = unlink(reservationURL.path) + return nil + } + return (reservationURL, reservationDescriptor) + } + } + + private static func promoteTemporaryPreview( + reservation: (url: URL, descriptor: Int32), + byteCount: Int64, + pathExtension: String + ) -> URL? { + guard byteCount >= 0, + byteCount <= ArtifactSidebarFileAccess.maximumPreviewByteCount else { + return nil + } + let directory = reservation.url.deletingLastPathComponent() + return withPreviewDirectoryLock(in: directory) { + guard ftruncate(reservation.descriptor, off_t(byteCount)) == 0 else { + return nil + } + let temporaryURL = directory + .appendingPathComponent("cmux-artifact-\(UUID().uuidString)") + .appendingPathExtension(pathExtension) + guard rename(reservation.url.path, temporaryURL.path) == 0 else { + return nil + } + return temporaryURL + } + } + + private static func discardTemporaryPreview( + _ reservation: (url: URL, descriptor: Int32) + ) { + let directory = reservation.url.deletingLastPathComponent() + _ = withPreviewDirectoryLock(in: directory) { () -> Void? in + _ = unlink(reservation.url.path) + return () + } + } + + /// Uses BSD `flock` because detached tasks and separate cmux processes + /// share this filesystem quota; the critical section never suspends. + private static func withPreviewDirectoryLock( + in directory: URL, + _ body: () -> T? + ) -> T? { + let lockURL = directory.appendingPathComponent( + ArtifactSidebarFileAccess.previewLockName, + isDirectory: false + ) + let lockDescriptor = Darwin.open( + lockURL.path, + O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, + S_IRUSR | S_IWUSR + ) + guard lockDescriptor >= 0 else { return nil } + defer { _ = Darwin.close(lockDescriptor) } + while flock(lockDescriptor, LOCK_EX) != 0 { + guard errno == EINTR else { return nil } + } + defer { _ = flock(lockDescriptor, LOCK_UN) } + return body() + } + + private static func reclaimStalePreviewFiles(in directory: URL) { + let cutoff = Date().addingTimeInterval(-24 * 60 * 60) + guard let enumerator = FileManager.default.enumerator( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey], + options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants] + ) else { + return + } + let directoryPath = directory.standardizedFileURL.path + var candidates: [(url: URL, size: Int64, modifiedAt: Date)] = [] + for case let entry as URL in enumerator { + guard entry.deletingLastPathComponent().standardizedFileURL.path == directoryPath, + entry.lastPathComponent.hasPrefix("cmux-artifact-") else { + continue + } + var status = stat() + guard lstat(entry.path, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0 else { + continue + } + let modifiedAt = Date(timeIntervalSince1970: Double(status.st_mtimespec.tv_sec)) + guard modifiedAt < cutoff else { continue } + let candidate = ( + url: entry, + size: Int64(status.st_size), + modifiedAt: modifiedAt + ) + if candidates.count < ArtifactSidebarFileAccess.maximumPreviewFileCount { + candidates.append(candidate) + continue + } + guard let oldestIndex = candidates.indices.min(by: { lhs, rhs in + if candidates[lhs].modifiedAt != candidates[rhs].modifiedAt { + return candidates[lhs].modifiedAt < candidates[rhs].modifiedAt + } + return candidates[lhs].url.path < candidates[rhs].url.path + }) else { + continue + } + let oldest = candidates[oldestIndex] + if candidate.modifiedAt > oldest.modifiedAt { + _ = unlink(oldest.url.path) + candidates[oldestIndex] = candidate + } else { + _ = unlink(candidate.url.path) + } + } + candidates.sort { + if $0.modifiedAt != $1.modifiedAt { + return $0.modifiedAt > $1.modifiedAt + } + return $0.url.path > $1.url.path + } + var retainedBytes: Int64 = 0 + for candidate in candidates { + guard candidate.size <= ArtifactSidebarFileAccess.maximumPreviewByteCount, + retainedBytes <= ArtifactSidebarFileAccess.maximumPreviewByteCount - candidate.size else { + _ = unlink(candidate.url.path) + continue + } + retainedBytes += candidate.size + } + } + + @concurrent + private static func materializeTemporaryPreviewOffMain( + descriptor: Int32, + pathExtension: String, + maximumBytes: Int64 + ) async -> URL? { + materializeTemporaryPreview( + descriptor: descriptor, + pathExtension: pathExtension, + maximumBytes: maximumBytes + ) + } + + deinit { + _ = Darwin.close(descriptor) + } + } + + init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Returns the current canonical file URL when the row still belongs to + /// the resolved project artifact root. + func validatedFileURL(for sourceURL: URL, artifactRoot: URL) -> URL? { + openedFile(for: sourceURL, artifactRoot: artifactRoot)?.sourceURL + } + + /// Creates a lazy file drag that revalidates the row at the actual + /// pasteboard handoff. The file representation is copied before its load + /// handler returns from the validated `/dev/fd` descriptor, so pathname + /// replacement cannot redirect the copy; directories use the same pinned + /// descriptor path. + /// - Parameter isDirectory: The row's snapshot kind, used to advertise a + /// folder representation only for directory rows. + func dragItemProvider( + for sourceURL: URL, + artifactRoot: URL, + isDirectory: Bool + ) -> NSItemProvider? { + guard sourceURL.isFileURL else { return nil } + let provider = NSItemProvider() + provider.suggestedName = sourceURL.lastPathComponent + let typeIdentifiers = isDirectory + ? [UTType.folder.identifier, UTType.fileURL.identifier] + : [UTType.fileURL.identifier] + for typeIdentifier in typeIdentifiers { + provider.registerFileRepresentation( + forTypeIdentifier: typeIdentifier, + fileOptions: [], + visibility: .all + ) { completion in + let access = ArtifactSidebarFileAccess() + if let opened = access.openedDragEntry( + for: sourceURL, + artifactRoot: artifactRoot + ) { + if typeIdentifier == UTType.folder.identifier, !opened.isDirectory { + completion(nil, false, nil) + return nil + } + completion(opened.readURL, false, nil) + let progress = Progress(totalUnitCount: 1) + // NSItemProvider owns the returned progress for the + // duration of the file load; this keeps the descriptor + // alive until Foundation has finished consuming the URL. + progress.cancellationHandler = { _ = opened } + progress.pausingHandler = { _ = opened } + progress.completedUnitCount = 1 + return progress + } else { + completion(nil, false, nil) + } + return nil + } + } + return provider + } + + /// Performs descriptor validation off the main actor for virtualized rows + /// and refresh tasks. + func openedFileAsync( + for sourceURL: URL, + artifactRoot: URL + ) async -> OpenedFile? { + await Task.detached(priority: .utility) { + ArtifactSidebarFileAccess().openedFile( + for: sourceURL, + artifactRoot: artifactRoot + ) + }.value + } + + /// Returns a descriptor-validated regular-file or directory URL for Finder. + func validatedRevealURL(for sourceURL: URL, artifactRoot: URL) -> URL? { + guard sourceURL.isFileURL else { return nil } + let descriptor = Darwin.open( + sourceURL.path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { return nil } + defer { _ = Darwin.close(descriptor) } + var status = stat() + guard fstat(descriptor, &status) == 0, + ((status.st_mode & S_IFMT) == S_IFREG + || (status.st_mode & S_IFMT) == S_IFDIR), + let openedPath = openedPath(for: descriptor) else { + return nil + } + let rootDescriptor = Darwin.open( + artifactRoot.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard rootDescriptor >= 0 else { return nil } + defer { _ = Darwin.close(rootDescriptor) } + var rootStatus = stat() + guard fstat(rootDescriptor, &rootStatus) == 0, + (rootStatus.st_mode & S_IFMT) == S_IFDIR, + let openedRootPath = self.openedPath(for: rootDescriptor) else { + return nil + } + let rootPath = openedRootPath.path + let path = openedPath.path + guard path == rootPath || path.hasPrefix(rootPath + "/") else { + return nil + } + return openedPath + } + + /// Validates and materializes one thumbnail source away from the main actor. + /// + /// The entire descriptor validation and bounded copy stay inside one + /// utility task so virtualized sidebar rows do not perform filesystem work + /// before their first suspension. + func makeTemporaryPreviewURLAsync( + for sourceURL: URL, + artifactRoot: URL, + maximumBytes: Int64 = 8 * 1024 * 1024 + ) async -> URL? { + await Task.detached(priority: .utility) { + guard let opened = ArtifactSidebarFileAccess().openedFile( + for: sourceURL, + artifactRoot: artifactRoot + ) else { + return nil + } + return opened.makeTemporaryPreviewURL(maximumBytes: maximumBytes) + }.value + } + + /// Opens and validates one artifact while retaining the validated inode. + func openedFile(for sourceURL: URL, artifactRoot: URL) -> OpenedFile? { + openedEntry( + for: sourceURL, + artifactRoot: artifactRoot, + allowingDirectories: false + ) + } + + private func openedDragEntry(for sourceURL: URL, artifactRoot: URL) -> OpenedFile? { + openedEntry( + for: sourceURL, + artifactRoot: artifactRoot, + allowingDirectories: true + ) + } + + private func openedEntry( + for sourceURL: URL, + artifactRoot: URL, + allowingDirectories: Bool + ) -> OpenedFile? { + guard sourceURL.isFileURL else { return nil } + let descriptor = Darwin.open( + sourceURL.path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { return nil } + + var status = stat() + guard fstat(descriptor, &status) == 0, + let openedPath = openedPath(for: descriptor) else { + _ = Darwin.close(descriptor) + return nil + } + let fileType = status.st_mode & S_IFMT + guard fileType == S_IFREG || (allowingDirectories && fileType == S_IFDIR) else { + _ = Darwin.close(descriptor) + return nil + } + let rootDescriptor = Darwin.open( + artifactRoot.path, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard rootDescriptor >= 0 else { + _ = Darwin.close(descriptor) + return nil + } + defer { _ = Darwin.close(rootDescriptor) } + var rootStatus = stat() + guard fstat(rootDescriptor, &rootStatus) == 0, + (rootStatus.st_mode & S_IFMT) == S_IFDIR, + let openedRootPath = self.openedPath(for: rootDescriptor) else { + _ = Darwin.close(descriptor) + return nil + } + let rootPath = openedRootPath.path + let path = openedPath.path + guard path == rootPath + || path.hasPrefix(rootPath.hasSuffix("/") ? rootPath : rootPath + "/") else { + _ = Darwin.close(descriptor) + return nil + } + return OpenedFile( + sourceURL: openedPath, + artifactRoot: openedRootPath, + descriptor: descriptor, + isDirectory: fileType == S_IFDIR + ) + } + + private func openedPath(for descriptor: Int32) -> URL? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + let path = String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self) + return URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL + } +} diff --git a/Sources/ArtifactSidebarPanelView.swift b/Sources/ArtifactSidebarPanelView.swift new file mode 100644 index 000000000000..a057bd123992 --- /dev/null +++ b/Sources/ArtifactSidebarPanelView.swift @@ -0,0 +1,245 @@ +import AppKit +import CmuxArtifacts +import SwiftUI + +/// Beta-gated project-file sidebar with a live `.cmux` tree and search. +struct ArtifactSidebarPanelView: View { + let model: ArtifactSidebarModel + let workspace: ArtifactSidebarWorkspace? + let isVisible: Bool + let chromeBackgroundColor: NSColor + let onOpenArtifact: (ArtifactSidebarRowSnapshot) -> Void + + var body: some View { + VStack(spacing: 0) { + searchHeader + .rightSidebarChromeBottomBorder(backgroundColor: chromeBackgroundColor) + content + } + .task(id: ArtifactSidebarBinding( + workspaceID: workspace?.id, + workingDirectory: workspace?.workingDirectory, + isVisible: isVisible + )) { + if isVisible { + await model.bind(workspace: workspace) + } else { + model.stop() + } + } + .onChange(of: workspace?.title) { _, title in + guard let workspaceID = workspace?.id else { return } + model.updateWorkspaceTitle(workspaceID: workspaceID, title: title) + } + .onDisappear { + model.stop() + } + .alert(item: actionFailureBinding) { failure in + Alert( + title: Text(failureTitle(failure)), + message: Text(failureMessage(failure)), + dismissButton: .default(Text(String(localized: "common.ok", defaultValue: "OK"))) + ) + } + .accessibilityIdentifier("ArtifactSidebarPanel") + } + + private var searchHeader: some View { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + ArtifactSidebarSearchField( + value: model.query, + placeholder: String( + localized: "rightSidebar.artifacts.search.placeholder", + defaultValue: "Search artifacts and notes" + ), + onChange: model.setQuery + ) + .frame(maxWidth: .infinity) + .accessibilityIdentifier("ArtifactSidebarSearchField") + Button(action: presentAddPanel) { + Image(systemName: "plus") + } + .buttonStyle(.plain) + .safeHelp(String(localized: "rightSidebar.artifacts.add.tooltip", defaultValue: "Add files to Artifacts")) + .accessibilityLabel(String(localized: "rightSidebar.artifacts.add.tooltip", defaultValue: "Add files to Artifacts")) + .disabled(workspace == nil) + .accessibilityIdentifier("ArtifactSidebarAddButton") + } + .padding(.horizontal, 10) + .frame(height: 36) + } + + @ViewBuilder + private var content: some View { + switch model.phase { + case .unavailable: + emptyState( + symbol: "shippingbox", + title: String(localized: "rightSidebar.artifacts.noWorkspace.title", defaultValue: "No Local Workspace"), + message: String( + localized: "rightSidebar.artifacts.noWorkspace.message", + defaultValue: "Open a local workspace to browse its artifacts and notes." + ), + showsAddButton: false + ) + case .loading: + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .accessibilityLabel(String( + localized: "rightSidebar.artifacts.loading", + defaultValue: "Loading artifacts and notes" + )) + case .failed: + VStack(spacing: 10) { + emptyState( + symbol: "exclamationmark.triangle", + title: String( + localized: "rightSidebar.artifacts.loadFailed.title", + defaultValue: "Couldn’t Load Project Files" + ), + message: String(localized: "rightSidebar.artifacts.loadFailed.message", defaultValue: "Check the project folder and try again."), + showsAddButton: false + ) + Button(String(localized: "rightSidebar.artifacts.retry", defaultValue: "Retry")) { + model.requestRefresh() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + case .loaded: + if model.rows.isEmpty { + emptyState( + symbol: model.query.isEmpty ? "shippingbox" : "magnifyingglass", + title: model.query.isEmpty + ? String( + localized: "rightSidebar.artifacts.empty.title", + defaultValue: "No Artifacts or Notes Yet" + ) + : String(localized: "rightSidebar.artifacts.noResults.title", defaultValue: "No Matches"), + message: model.query.isEmpty + ? String( + localized: "rightSidebar.artifacts.empty.message", + defaultValue: "Files in each agent session’s artifacts and notes folders will appear here." + ) + : String(localized: "rightSidebar.artifacts.noResults.message", defaultValue: "Try another filename or text search."), + showsAddButton: model.query.isEmpty + ) + } else { + artifactRows + } + } + } + + private var artifactRows: some View { + let actions = ArtifactSidebarRowActions( + activate: activate, + toggleExpansion: { model.toggleExpansion(relativePath: $0.relativePath) }, + revealInFinder: revealInFinder, + copyPath: { copyToPasteboard($0.fileURL.path) }, + copyReference: { copyToPasteboard(".cmux/\($0.relativePath)") } + ) + return ScrollView { + LazyVStack(spacing: 0) { + ForEach(model.rows) { row in + ArtifactSidebarRowView(snapshot: row, actions: actions) + } + } + .padding(.vertical, 4) + } + } + + private func revealInFinder(_ row: ArtifactSidebarRowSnapshot) { + guard let projectRoot = row.projectRoot, + let validatedURL = ArtifactSidebarFileAccess().validatedRevealURL( + for: row.fileURL, + artifactRoot: projectRoot.appendingPathComponent(".cmux", isDirectory: true) + ) else { + return + } + NSWorkspace.shared.activateFileViewerSelecting([validatedURL]) + } + + private func emptyState( + symbol: String, + title: String, + message: String, + showsAddButton: Bool + ) -> some View { + VStack(spacing: 8) { + Image(systemName: symbol) + .cmuxFont(size: 24, weight: .light) + .foregroundStyle(.tertiary) + Text(title) + .cmuxFont(.headline) + Text(message) + .cmuxFont(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 220) + if showsAddButton { + Button(String(localized: "rightSidebar.artifacts.add", defaultValue: "Add Artifact…"), action: presentAddPanel) + .controlSize(.small) + } + } + .padding(24) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private func activate(_ row: ArtifactSidebarRowSnapshot) { + if row.isDirectory { + model.toggleExpansion(relativePath: row.relativePath) + } else { + onOpenArtifact(row) + } + } + + private func presentAddPanel() { + let panel = NSOpenPanel() + panel.title = String(localized: "rightSidebar.artifacts.addPanel.title", defaultValue: "Add to cmux Artifacts") + panel.message = String(localized: "rightSidebar.artifacts.addPanel.message", defaultValue: "Choose small files to copy into this project’s local artifact store.") + panel.prompt = String(localized: "rightSidebar.artifacts.addPanel.prompt", defaultValue: "Add") + panel.canChooseDirectories = false + panel.canChooseFiles = true + panel.allowsMultipleSelection = true + guard panel.runModal() == .OK else { return } + let urls = panel.urls + model.requestAddFiles(urls) + } + + private func copyToPasteboard(_ value: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(value, forType: .string) + } + + private var actionFailureBinding: Binding { + Binding( + get: { model.actionFailure }, + set: { if $0 == nil { model.clearActionFailure() } } + ) + } + + private func failureTitle(_ failure: ArtifactSidebarFailure) -> String { + switch failure { + case .add: + return String(localized: "rightSidebar.artifacts.addFailed.title", defaultValue: "Couldn’t Add Artifact") + case .search: + return String( + localized: "rightSidebar.artifacts.searchFailed.title", + defaultValue: "Couldn’t Search Project Files" + ) + } + } + + private func failureMessage(_ failure: ArtifactSidebarFailure) -> String { + switch failure { + case .add: + return String(localized: "rightSidebar.artifacts.addFailed.message", defaultValue: "The file may be unsupported or larger than this project’s capture limit.") + case .search: + return String( + localized: "rightSidebar.artifacts.searchFailed.message", + defaultValue: "Check the project’s .cmux folder and try again." + ) + } + } +} diff --git a/Sources/ArtifactSidebarRowActions.swift b/Sources/ArtifactSidebarRowActions.swift new file mode 100644 index 000000000000..1447310aec6a --- /dev/null +++ b/Sources/ArtifactSidebarRowActions.swift @@ -0,0 +1,10 @@ +import CmuxArtifacts + +/// Closure-only action bundle passed below the project-file lazy-list boundary. +struct ArtifactSidebarRowActions { + let activate: (ArtifactSidebarRowSnapshot) -> Void + let toggleExpansion: (ArtifactSidebarRowSnapshot) -> Void + let revealInFinder: (ArtifactSidebarRowSnapshot) -> Void + let copyPath: (ArtifactSidebarRowSnapshot) -> Void + let copyReference: (ArtifactSidebarRowSnapshot) -> Void +} diff --git a/Sources/ArtifactSidebarRowView.swift b/Sources/ArtifactSidebarRowView.swift new file mode 100644 index 000000000000..787480b7fe33 --- /dev/null +++ b/Sources/ArtifactSidebarRowView.swift @@ -0,0 +1,111 @@ +import CmuxArtifacts +import Foundation +import SwiftUI + +/// Immutable project-file tree/search row. +struct ArtifactSidebarRowView: View { + let snapshot: ArtifactSidebarRowSnapshot + let actions: ArtifactSidebarRowActions + + var body: some View { + HStack(spacing: 6) { + disclosure + ArtifactSidebarThumbnailView( + fileURL: snapshot.fileURL, + artifactRoot: snapshot.projectRoot?.appendingPathComponent(".cmux", isDirectory: true), + kind: snapshot.fileKind, + isDirectory: snapshot.isDirectory, + revision: snapshot.fileRevision + ) + VStack(alignment: .leading, spacing: 1) { + Text(snapshot.name) + .lineLimit(1) + .truncationMode(.middle) + if let detailText { + Text(detailText) + .cmuxFont(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + Spacer(minLength: 0) + } + .padding(.leading, Double(snapshot.depth) * 14 + 6) + .padding(.trailing, 8) + .frame(minHeight: 32) + .contentShape(.rect) + .onTapGesture { + actions.activate(snapshot) + } + .contextMenu { + contextMenu + } + .onDrag { + guard let projectRoot = snapshot.projectRoot, + let provider = ArtifactSidebarFileAccess().dragItemProvider( + for: snapshot.fileURL, + artifactRoot: projectRoot.appendingPathComponent( + ".cmux", + isDirectory: true + ), + isDirectory: snapshot.isDirectory + ) else { + return NSItemProvider() + } + return provider + } + .accessibilityIdentifier("ArtifactSidebarRow.\(snapshot.id)") + } + + @ViewBuilder + private var disclosure: some View { + if snapshot.isDirectory { + Button { + actions.toggleExpansion(snapshot) + } label: { + Image(systemName: snapshot.isExpanded ? "chevron.down" : "chevron.right") + .cmuxFont(size: 9, weight: .semibold) + .foregroundStyle(.secondary) + .frame(width: 12, height: 24) + .contentShape(.rect) + } + .buttonStyle(.plain) + .accessibilityLabel(snapshot.isExpanded + ? String(localized: "rightSidebar.artifacts.collapse", defaultValue: "Collapse folder") + : String(localized: "rightSidebar.artifacts.expand", defaultValue: "Expand folder")) + } else { + Color.clear.frame(width: 12, height: 1) + } + } + + private var detailText: String? { + if let snippet = snapshot.snippet { return snippet } + return snapshot.depth == 0 && !snapshot.isDirectory ? snapshot.relativePath : nil + } + + @ViewBuilder + private var contextMenu: some View { + if snapshot.isDirectory { + Button(snapshot.isExpanded + ? String(localized: "rightSidebar.artifacts.collapse", defaultValue: "Collapse folder") + : String(localized: "rightSidebar.artifacts.expand", defaultValue: "Expand folder")) { + actions.toggleExpansion(snapshot) + } + } else { + Button(String(localized: "rightSidebar.artifacts.open", defaultValue: "Open File")) { + actions.activate(snapshot) + } + } + Divider() + Button(String(localized: "rightSidebar.artifacts.reveal", defaultValue: "Reveal in Finder")) { + actions.revealInFinder(snapshot) + } + Button(String(localized: "rightSidebar.artifacts.copyPath", defaultValue: "Copy Path")) { + actions.copyPath(snapshot) + } + Button(String(localized: "rightSidebar.artifacts.copyReference", defaultValue: "Copy Reference")) { + actions.copyReference(snapshot) + } + } +} diff --git a/Sources/ArtifactSidebarSearchField.swift b/Sources/ArtifactSidebarSearchField.swift new file mode 100644 index 000000000000..24200078aefb --- /dev/null +++ b/Sources/ArtifactSidebarSearchField.swift @@ -0,0 +1,17 @@ +import SwiftUI + +/// AppKit-backed search field that exposes deterministic main-window focus. +struct ArtifactSidebarSearchField: NSViewRepresentable { + let value: String + let placeholder: String + let onChange: (String) -> Void + + func makeNSView(context: Context) -> ArtifactSidebarSearchFieldView { + ArtifactSidebarSearchFieldView(frame: .zero) + } + + func updateNSView(_ searchField: ArtifactSidebarSearchFieldView, context: Context) { + searchField.update(value: value, placeholder: placeholder, onChange: onChange) + searchField.registerWithKeyboardFocusCoordinatorIfNeeded() + } +} diff --git a/Sources/ArtifactSidebarSearchFieldView.swift b/Sources/ArtifactSidebarSearchFieldView.swift new file mode 100644 index 000000000000..b9dddc6b8eb5 --- /dev/null +++ b/Sources/ArtifactSidebarSearchFieldView.swift @@ -0,0 +1,57 @@ +import AppKit + +/// Native Artifacts search endpoint registered with the owning main window. +@MainActor +final class ArtifactSidebarSearchFieldView: NSTextField { + private var onValueChanged: ((String) -> Void)? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + isBordered = false + drawsBackground = false + focusRingType = .none + isContinuous = true + target = self + action = #selector(valueChanged) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) is unavailable") + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + registerWithKeyboardFocusCoordinatorIfNeeded() + } + + override func layout() { + super.layout() + registerWithKeyboardFocusCoordinatorIfNeeded() + } + + func update(value: String, placeholder: String, onChange: @escaping (String) -> Void) { + if stringValue != value { + stringValue = value + } + placeholderString = placeholder + onValueChanged = onChange + } + + func registerWithKeyboardFocusCoordinatorIfNeeded() { + guard let window else { return } + AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerArtifactSearchField(self) + } + + func focusFromCoordinator() -> Bool { + window?.makeFirstResponder(self) == true + } + + func ownsKeyboardFocus(_ responder: NSResponder) -> Bool { + responder === self || currentEditor() === responder + } + + @objc private func valueChanged() { + onValueChanged?(stringValue) + } +} diff --git a/Sources/ArtifactSidebarThumbnailView.swift b/Sources/ArtifactSidebarThumbnailView.swift new file mode 100644 index 000000000000..90287f9b1aa4 --- /dev/null +++ b/Sources/ArtifactSidebarThumbnailView.swift @@ -0,0 +1,81 @@ +import AppKit +import CmuxArtifacts +import QuickLookThumbnailing +import SwiftUI + +/// Small Quick Look thumbnail used for image and video artifact rows. +struct ArtifactSidebarThumbnailView: View { + let fileURL: URL + let artifactRoot: URL? + let kind: ArtifactFileKind? + let isDirectory: Bool + let revision: ArtifactSidebarFileRevision? + + @State private var thumbnail: NSImage? + + var body: some View { + Group { + if let thumbnail { + Image(nsImage: thumbnail) + .resizable() + .scaledToFit() + } else { + Image(systemName: symbolName) + .resizable() + .scaledToFit() + .padding(3) + .foregroundStyle(.secondary) + } + } + .frame(width: 24, height: 24) + .clipShape(.rect(cornerRadius: 4)) + .task(id: revision) { + await loadThumbnailIfNeeded() + } + } + + private var symbolName: String { + if isDirectory { return "folder" } + switch kind { + case .image: return "photo" + case .video: return "film" + case .markdown: return "doc.richtext" + case .html: return "globe" + case .patch: return "doc.badge.gearshape" + case .text: return "doc.text" + case .other, .none: return "doc" + } + } + + @MainActor + private func loadThumbnailIfNeeded() async { + thumbnail = nil + guard kind == .image || kind == .video else { + return + } + let temporaryURL: URL? + if let artifactRoot { + temporaryURL = await ArtifactSidebarFileAccess().makeTemporaryPreviewURLAsync( + for: fileURL, + artifactRoot: artifactRoot + ) + guard temporaryURL != nil else { return } + } else { + temporaryURL = nil + } + defer { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + } + let request = QLThumbnailGenerator.Request( + fileAt: temporaryURL ?? fileURL, + size: CGSize(width: 48, height: 48), + scale: NSScreen.main?.backingScaleFactor ?? 2, + representationTypes: [.thumbnail, .icon] + ) + let representation = try? await QLThumbnailGenerator.shared.generateBestRepresentation(for: request) + guard !Task.isCancelled else { return } + thumbnail = representation?.nsImage + } +} diff --git a/Sources/BrowserPanelContentMode.swift b/Sources/BrowserPanelContentMode.swift new file mode 100644 index 000000000000..e5113c657389 --- /dev/null +++ b/Sources/BrowserPanelContentMode.swift @@ -0,0 +1,16 @@ +import Foundation + +/// Selects standard browser behavior or an isolated artifact-document preview. +enum BrowserPanelContentMode { + case standard + case artifactHTMLPreview(documentURL: URL) + + var artifactDocumentURL: URL? { + guard case .artifactHTMLPreview(let documentURL) = self else { return nil } + return documentURL + } + + var allowsSessionPersistence: Bool { + artifactDocumentURL == nil + } +} diff --git a/Sources/CmuxTaskManagerCodingAgentDefinition.swift b/Sources/CmuxTaskManagerCodingAgentDefinition.swift new file mode 100644 index 000000000000..eda17518baed --- /dev/null +++ b/Sources/CmuxTaskManagerCodingAgentDefinition.swift @@ -0,0 +1,194 @@ +import CmuxTerminalCore +import Foundation + +struct CmuxTaskManagerCodingAgentDefinition: Equatable, Sendable { + let id: String + let displayName: String + let assetName: String? + let launchKinds: [String] + let directBasenames: [String] + let argumentNeedles: [String] + let requiredArgumentPrefix: [String] + let promptTurnDetection: PromptLineTurnDetectionConfiguration? + + init( + id: String, + displayName: String, + assetName: String?, + launchKinds: [String], + directBasenames: [String], + argumentNeedles: [String], + requiredArgumentPrefix: [String] = [], + promptTurnDetection: PromptLineTurnDetectionConfiguration? = nil + ) { + self.id = id + self.displayName = displayName + self.assetName = assetName + self.launchKinds = launchKinds + self.directBasenames = directBasenames + self.argumentNeedles = argumentNeedles + self.requiredArgumentPrefix = requiredArgumentPrefix + self.promptTurnDetection = promptTurnDetection + } + + static func shouldReadArguments(processName: String, processPath: String?) -> Bool { + if let normalizedPath = normalized(processPath), + argumentInspectionPathNeedles.contains(where: { normalizedPath.contains($0) }) { + return true + } + + let basenames = candidateBasenames( + processName: processName, + processPath: processPath, + arguments: [] + ) + return basenames.contains { candidate in + argumentHostBasenames.contains(candidate) + || ambiguousDirectBasenames.contains(candidate) + || isVersionedExecutableBasename(candidate) + } + } + + static func matchingDefinition( + processName: String, + processPath: String?, + arguments: [String], + environment: [String: String] + ) -> CmuxTaskManagerCodingAgentDefinition? { + let definitions = builtIns + // The process's own executable identity outranks the launch-kind + // environment: CMUX_AGENT_LAUNCH_* is inherited by every descendant + // of the launched pane, so a later `ollama run` inside a pane that + // launched claude still carries CMUX_AGENT_LAUNCH_KIND=claude. The + // env var only identifies processes (wrappers, script hosts) whose + // executable matches no agent definition of its own. + let basenames = candidateBasenames( + processName: processName, + processPath: processPath, + arguments: arguments + ) + if let definition = definitions.first(where: { definition in + definition.matchesRequiredArguments(arguments) + && basenames.contains { definition.directBasenames.contains($0) } + }) { + return definition + } + + let launchKind = normalized(environment["CMUX_AGENT_LAUNCH_KIND"]) + if let launchKind, + let definition = definitions.first(where: { + $0.launchKinds.contains(launchKind) && $0.matchesRequiredArguments(arguments) + }) { + return definition + } + + guard !arguments.isEmpty else { return nil } + return definitions.first { definition in + definition.matchesRequiredArguments(arguments) + && definition.argumentNeedles.contains { needle in + arguments.contains { argumentMatchesNeedle(argument: $0, needle: needle) } + } + } + } + + private func matchesRequiredArguments(_ arguments: [String]) -> Bool { + guard !requiredArgumentPrefix.isEmpty else { return true } + let normalizedArguments = arguments.compactMap(Self.normalized) + let required = requiredArgumentPrefix.compactMap(Self.normalized) + guard normalizedArguments.count > required.count else { return false } + return Array(normalizedArguments.dropFirst().prefix(required.count)) == required + } + + private static let argumentHostBasenames: Set = [ + "node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "tsx", "ts-node" + ] + + private static let ambiguousDirectBasenames: Set = [ + "acli", "ollama" + ] + + private static let argumentInspectionPathNeedles = [ + "/.local/share/claude/versions/", + "/library/application support/claude/claude-code/", + ] + + private static func candidateBasenames( + processName: String, + processPath: String?, + arguments: [String] + ) -> Set { + var values = Set() + appendBasename(processName, to: &values) + if let processPath { + appendBasename(processPath, to: &values) + } + if let executable = arguments.first { + appendBasename(executable, to: &values) + } + return values + } + + private static func appendBasename(_ value: String, to values: inout Set) { + guard let normalized = normalized((value as NSString).lastPathComponent) else { return } + values.insert(normalized) + } + + private static func isVersionedExecutableBasename(_ value: String) -> Bool { + let parts = value.split(separator: ".", omittingEmptySubsequences: false) + guard (2...4).contains(parts.count) else { return false } + return parts.allSatisfy { part in + !part.isEmpty && part.unicodeScalars.allSatisfy { CharacterSet.decimalDigits.contains($0) } + } + } + + private static func argumentMatchesNeedle(argument: String, needle: String) -> Bool { + guard let normalizedArgument = normalized(argument), + let normalizedNeedle = normalized(needle) else { return false } + if normalizedNeedle.contains("/") { + return containsNeedleWithBoundaries(normalizedNeedle, in: normalizedArgument) + } + return argumentTokens(from: normalizedArgument).contains(normalizedNeedle) + } + + private static func containsNeedleWithBoundaries(_ needle: String, in value: String) -> Bool { + var searchRange = value.startIndex.. Bool { + guard let character else { return true } + return character.unicodeScalars.allSatisfy { scalar in + argumentBoundaryScalars.contains(scalar) + } + } + + private static func argumentTokens(from value: String) -> Set { + let tokens = value + .components(separatedBy: argumentTokenSeparators) + .filter { !$0.isEmpty } + return Set(tokens.flatMap { token in + let stem = (token as NSString).deletingPathExtension + return stem.isEmpty || stem == token ? [token] : [token, stem] + }) + } + + private static let argumentTokenSeparators = CharacterSet(charactersIn: "/\\ \t\r\n\u{0}:=?&#\"'`<>(),;[]{}") + + private static let argumentBoundaryScalars = CharacterSet(charactersIn: "/\\ \t\r\n\u{0}:=?&#\"'`<>(),;[]{}").union(.newlines) + + private static func normalized(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + return trimmed?.isEmpty == false ? trimmed : nil + } +} diff --git a/Sources/CommandPalette/CommandPaletteSettingsToggle.swift b/Sources/CommandPalette/CommandPaletteSettingsToggle.swift index 4260dbdbde7e..f318a73abb96 100644 --- a/Sources/CommandPalette/CommandPaletteSettingsToggle.swift +++ b/Sources/CommandPalette/CommandPaletteSettingsToggle.swift @@ -771,6 +771,20 @@ enum CommandPaletteSettingsToggleCommands { defaultsKey: SidebarWorkspaceDetailDefaults.showCustomMetadataKey, isAvailable: sidebarDetailsAvailable ), + CommandPaletteSettingToggleDescriptor( + commandId: commandIdPrefix + "rightSidebarArtifacts", + settingsKey: "betaFeatures.artifacts", + title: { + String( + localized: "settings.betaFeatures.artifacts", + defaultValue: "Artifacts & Notes" + ) + }, + sectionTitle: beta, + keywords: ["betaFeatures.artifacts", "artifacts", "notes", "capture", "files", "project", "right", "sidebar", "beta"], + defaultValue: RightSidebarBetaFeatureSettings.defaultArtifactsEnabled, + defaultsKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey + ), CommandPaletteSettingToggleDescriptor( commandId: commandIdPrefix + "rightSidebarFeed", settingsKey: "betaFeatures.feed", diff --git a/Sources/ContentView+Artifacts.swift b/Sources/ContentView+Artifacts.swift new file mode 100644 index 000000000000..f785d1d88bdb --- /dev/null +++ b/Sources/ContentView+Artifacts.swift @@ -0,0 +1,82 @@ +import AppKit +import CmuxArtifacts +import Foundation + +extension ContentView { + var selectedArtifactWorkspace: ArtifactSidebarWorkspace? { + Self.artifactSidebarWorkspace(for: tabManager.selectedWorkspace) + } + + static func artifactSidebarWorkspace(for workspace: Workspace?) -> ArtifactSidebarWorkspace? { + guard let workspace, + !workspace.isRemoteWorkspace else { return nil } + let directory = workspace.currentDirectory.trimmingCharacters(in: .whitespacesAndNewlines) + guard !directory.isEmpty else { return nil } + return ArtifactSidebarWorkspace( + id: workspace.stableId.uuidString, + title: workspace.title, + workingDirectory: URL(fileURLWithPath: directory, isDirectory: true) + ) + } + + func openArtifactFromSidebar(_ artifact: ArtifactSidebarRowSnapshot) { + guard let workspace = tabManager.selectedWorkspace, + let paneId = workspace.bonsplitController.focusedPaneId + ?? workspace.bonsplitController.allPaneIds.first else { return } + guard let projectRoot = artifact.projectRoot, + let openedFile = ArtifactSidebarFileAccess().openedFile( + for: artifact.fileURL, + artifactRoot: projectRoot.appendingPathComponent(".cmux", isDirectory: true) + ) else { + NSSound.beep() + return + } + sidebarSelectionState.selection = .tabs + switch artifact.fileKind { + case .html: + let workspaceID = workspace.id + Task { @MainActor in + guard let previewURL = await openedFile.makeTemporaryPreviewURLAsync( + maximumBytes: 8 * 1024 * 1024 + ) else { + _ = workspace.openArtifactFileSurface( + inPane: paneId, + file: openedFile, + focus: true, + reuseExisting: true + ) + return + } + defer { try? FileManager.default.removeItem(at: previewURL) } + do { + let document = try await ArtifactHTMLPreviewDocument.load( + sourceURL: previewURL, + allowedRoot: previewURL.deletingLastPathComponent() + ) + guard tabManager.selectedWorkspace?.id == workspaceID else { return } + _ = workspace.newBrowserSurface( + inPane: paneId, + url: document.url, + focus: true, + creationPolicy: .artifactPreview, + chromeVisibility: .hidden, + bypassRemoteProxy: true + ) + } catch { + NSSound.beep() + } + } + case .patch: + if AppDelegate.shared?.openArtifactPatch(openedFile, for: tabManager) != true { + NSSound.beep() + } + case .image, .video, .markdown, .text, .other, nil: + _ = workspace.openArtifactFileSurface( + inPane: paneId, + file: openedFile, + focus: true, + reuseExisting: true + ) + } + } +} diff --git a/Sources/ContentView+RightSidebarCommandPalette.swift b/Sources/ContentView+RightSidebarCommandPalette.swift index 442dded975ed..933eb2f4b750 100644 --- a/Sources/ContentView+RightSidebarCommandPalette.swift +++ b/Sources/ContentView+RightSidebarCommandPalette.swift @@ -151,6 +151,8 @@ extension ContentView { return "palette.showRightSidebarFind" case .sessions: return "palette.showRightSidebarSessions" + case .artifacts: + return "palette.showRightSidebarArtifacts" case .feed: return "palette.showRightSidebarFeed" case .dock: @@ -180,7 +182,7 @@ extension ContentView { return "palette.openFindPane" case .sessions: return "palette.openVaultPane" - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: return nil } } @@ -193,7 +195,7 @@ extension ContentView { return String(localized: "command.openFindPane.title", defaultValue: "Open Find as Pane") case .sessions: return String(localized: "command.openVaultPane.title", defaultValue: "Open Vault as Pane") - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: return nil } } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index c3c9a12291a9..2e9f435e18e9 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1,5 +1,6 @@ import AppKit import CmuxAppKitSupportUI +import CmuxArtifacts import CmuxCommandPalette import CmuxCore import CmuxFeedback @@ -847,6 +848,8 @@ struct ContentView: View { var updateViewModel: UpdateStateModel let windowId: UUID + let artifactStore: any ArtifactStoring + let artifactCaptureService: any ArtifactCapturing let featureFlags: CmuxFeatureFlags let sidebarUnread: SidebarUnreadModel let titlebarControlsLayoutModel: TitlebarControlsLayoutModel @@ -857,14 +860,20 @@ struct ContentView: View { windowId: UUID, featureFlags: CmuxFeatureFlags? = nil, sidebarUnread: SidebarUnreadModel? = nil, - titlebarControlsLayoutModel: TitlebarControlsLayoutModel? = nil + titlebarControlsLayoutModel: TitlebarControlsLayoutModel? = nil, + artifactStore: (any ArtifactStoring)? = nil, + artifactCaptureService: (any ArtifactCapturing)? = nil ) { + let resolvedArtifactStore = artifactStore ?? LocalArtifactRepository() self.updateViewModel = updateViewModel self.windowId = windowId self.featureFlags = featureFlags ?? .shared self.sidebarUnread = sidebarUnread ?? TerminalNotificationStore.shared.sidebarUnread self.titlebarControlsLayoutModel = titlebarControlsLayoutModel ?? TitlebarControlsLayoutModel() + self.artifactStore = resolvedArtifactStore + self.artifactCaptureService = artifactCaptureService + ?? ArtifactCaptureService(store: resolvedArtifactStore) } @EnvironmentObject var tabManager: TabManager @@ -1977,9 +1986,13 @@ struct ContentView: View { fileExplorerStore: fileExplorerStore, fileExplorerState: fileExplorerState, sessionIndexStore: sessionIndexStore, + featureFlags: featureFlags, titlebarHeight: RightSidebarChromeMetrics.titlebarHeight, windowAppearance: appearance, workspaceId: tabManager.selectedTabId, + artifactWorkspace: selectedArtifactWorkspace, + artifactStore: artifactStore, + artifactCaptureService: artifactCaptureService, onResumeSession: { entry in resumeSession(entry: entry) }, @@ -1989,6 +2002,9 @@ struct ContentView: View { onOpenFilePreview: { filePath in openFilePreviewFromSidebar(filePath: filePath) }, + onOpenArtifact: { artifact in + openArtifactFromSidebar(artifact) + }, onOpenAsPane: { mode in openRightSidebarToolPane(mode) }, diff --git a/Sources/FeatureFlags.swift b/Sources/FeatureFlags.swift index 239d65137fef..8ae2efab193f 100644 --- a/Sources/FeatureFlags.swift +++ b/Sources/FeatureFlags.swift @@ -59,6 +59,11 @@ final class CmuxFeatureFlags { private static let appKitSidebarListDefault = true private static let mobileTerminalFilesChipDefault = true private nonisolated static let mobileTaskComposerDefault = true +#if DEBUG + private nonisolated static let artifactsDefault = true +#else + private nonisolated static let artifactsDefault = false +#endif private static let overrideKeyPrefix = "cmux.flags.override." private static let remoteCacheKeyPrefix = "cmux.flags.remote." @@ -166,6 +171,25 @@ final class CmuxFeatureFlags { defaultWhenUnavailable: CmuxFeatureFlags.mobileTaskComposerDefault ) + // FLAG(key: right-sidebar-artifacts-enabled-release, owner: lawrencecchen, + // reviewBy: 2026-10-01, defaultWhenUnavailable: false) + // Controls the project-local Artifacts and Notes surface, including its + // right-sidebar mode and automatic capture. The beta setting remains a + // local opt-in for dogfood; this remote flag is the production gate and + // kill switch. DEBUG keeps the feature available when PostHog is absent. + nonisolated static let artifactsFlag = CmuxFeatureFlagDefinition( + key: "right-sidebar-artifacts-enabled-release", + title: String( + localized: "featureFlags.artifacts.title", + defaultValue: "Artifacts & Notes" + ), + flagDescription: String( + localized: "featureFlags.artifacts.description", + defaultValue: "Enables the project-local Artifacts and Notes sidebar and automatic capture." + ), + defaultWhenUnavailable: CmuxFeatureFlags.artifactsDefault + ) + // Order is load-bearing for the positional typed accessors below. Flags // that need a stable public definition are declared independently and // included here without repeating their key literal. @@ -288,6 +312,7 @@ final class CmuxFeatureFlags { CmuxFeatureFlags.mobileTerminalFilesChipFlag, CmuxFeatureFlags.mobileTaskComposerFlag, + CmuxFeatureFlags.artifactsFlag, ] }() @@ -339,6 +364,10 @@ final class CmuxFeatureFlags { effectiveValue(for: Self.mobileTaskComposerFlag) } + var isArtifactsEnabled: Bool { + effectiveValue(for: Self.artifactsFlag) + } + /// Effective values mirrored for nonisolated readers: the mobile host /// serves status payloads (which carry the capability list) off the main /// actor. Written only by the shared instance so test instances cannot diff --git a/Sources/Feed/FeedPanelView.swift b/Sources/Feed/FeedPanelView.swift index c2d6d4d45cef..55abbdd5b575 100644 --- a/Sources/Feed/FeedPanelView.swift +++ b/Sources/Feed/FeedPanelView.swift @@ -776,7 +776,7 @@ final class FeedKeyboardFocusView: NSView { onEscape?() return true } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { onMoveSelection?(delta) return true } @@ -800,7 +800,7 @@ final class FeedKeyboardFocusView: NSView { return } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { onMoveSelection?(delta) return } diff --git a/Sources/FileExplorerKeyboardShortcuts.swift b/Sources/FileExplorerKeyboardShortcuts.swift index 628ee0b53062..2d0f5061a4ec 100644 --- a/Sources/FileExplorerKeyboardShortcuts.swift +++ b/Sources/FileExplorerKeyboardShortcuts.swift @@ -68,7 +68,7 @@ extension FileExplorerSearchResultsTableView { extension FileExplorerSearchField { func handleOpenSelectionShortcut(_ event: NSEvent) -> Bool { if (currentEditor() as? NSTextView)?.hasMarkedText() == true { return false } - guard !RightSidebarKeyboardNavigation.isPlainPrintableText(event) else { return false } + guard !event.isPlainRightSidebarPrintableText else { return false } guard event.isFileExplorerOpenSelectionShortcut(in: fileExplorerPanelPlacement) else { return false } onCommit?() return true diff --git a/Sources/FileExplorerNSOutlineView.swift b/Sources/FileExplorerNSOutlineView.swift index 4f55f1a24e0c..9533b3e962a4 100644 --- a/Sources/FileExplorerNSOutlineView.swift +++ b/Sources/FileExplorerNSOutlineView.swift @@ -41,7 +41,7 @@ final class FileExplorerNSOutlineView: NSOutlineView { } if quickSearchActive, - RightSidebarKeyboardNavigation.isPlainPrintableText(event), + event.isPlainRightSidebarPrintableText, handleQuickSearchKey(event) { return } @@ -54,24 +54,24 @@ final class FileExplorerNSOutlineView: NSOutlineView { return } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { endQuickSearch() fileExplorerCoordinator?.moveSelection(in: self, by: delta) return } - if let action = RightSidebarKeyboardNavigation.disclosureAction(for: event) { + if let action = event.rightSidebarDisclosureAction { endQuickSearch() fileExplorerCoordinator?.performDisclosureAction(action, in: self) return } - if RightSidebarKeyboardNavigation.isPlainSlash(event) { + if event.isPlainRightSidebarSlash { beginQuickSearch() return } - if RightSidebarKeyboardNavigation.isPlainPrintableText(event) { + if event.isPlainRightSidebarPrintableText { return } super.keyDown(with: event) @@ -79,7 +79,7 @@ final class FileExplorerNSOutlineView: NSOutlineView { override func performKeyEquivalent(with event: NSEvent) -> Bool { if quickSearchActive, - RightSidebarKeyboardNavigation.isPlainPrintableText(event), + event.isPlainRightSidebarPrintableText, handleQuickSearchKey(event) { return true } @@ -89,12 +89,12 @@ final class FileExplorerNSOutlineView: NSOutlineView { if quickSearchActive, handleQuickSearchKey(event) { return true } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { endQuickSearch() fileExplorerCoordinator?.moveSelection(in: self, by: delta) return true } - if let action = RightSidebarKeyboardNavigation.disclosureAction(for: event) { + if let action = event.rightSidebarDisclosureAction { endQuickSearch() fileExplorerCoordinator?.performDisclosureAction(action, in: self) return true @@ -192,7 +192,7 @@ final class FileExplorerNSOutlineView: NSOutlineView { } return true } - guard RightSidebarKeyboardNavigation.isPlainPrintableText(event) else { + guard event.isPlainRightSidebarPrintableText else { return false } guard let text = event.charactersIgnoringModifiers, !text.isEmpty else { diff --git a/Sources/FileExplorerSearchResultsTableView.swift b/Sources/FileExplorerSearchResultsTableView.swift index 7b3db05897e8..d828d1fdb8e6 100644 --- a/Sources/FileExplorerSearchResultsTableView.swift +++ b/Sources/FileExplorerSearchResultsTableView.swift @@ -66,11 +66,11 @@ final class FileExplorerSearchResultsTableView: NSTableView { onCancel?() return } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { onMoveSelection?(delta) return } - if RightSidebarKeyboardNavigation.isPlainPrintableText(event) { + if event.isPlainRightSidebarPrintableText { return } super.keyDown(with: event) @@ -78,7 +78,7 @@ final class FileExplorerSearchResultsTableView: NSTableView { override func performKeyEquivalent(with event: NSEvent) -> Bool { if handleOpenSelectionShortcut(event) { return true } - if let delta = RightSidebarKeyboardNavigation.moveDelta(for: event) { + if let delta = event.rightSidebarMoveDelta { onMoveSelection?(delta) return true } diff --git a/Sources/FileExplorerView.swift b/Sources/FileExplorerView.swift index c84ef3b34236..3de8d6e0afb2 100644 --- a/Sources/FileExplorerView.swift +++ b/Sources/FileExplorerView.swift @@ -360,7 +360,7 @@ struct FileExplorerPanelView: NSViewRepresentable { } func performDisclosureAction( - _ action: RightSidebarKeyboardNavigation.DisclosureAction, + _ action: RightSidebarDisclosureAction, in outlineView: NSOutlineView ) { switch action { diff --git a/Sources/GhosttyTerminalView.swift b/Sources/GhosttyTerminalView.swift index eb6c77bc4ba2..26700d4d9b56 100644 --- a/Sources/GhosttyTerminalView.swift +++ b/Sources/GhosttyTerminalView.swift @@ -5106,6 +5106,30 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations { invalidateTextInputCoordinates() } + /// Resolves renderer visibility from AppKit state and the headless display-test contract. + static func effectiveRendererWindowVisibility( + occlusionVisible: Bool, + isVisible: Bool, + displayUITestRenderingEnabled: Bool + ) -> Bool { + occlusionVisible || (displayUITestRenderingEnabled && isVisible) + } + + private func effectiveRendererWindowVisibility(for window: NSWindow) -> Bool { +#if DEBUG + let displayUITestRenderingEnabled = ProcessInfo.processInfo.environment[ + "CMUX_UI_TEST_DISPLAY_RENDER_STATS" + ] == "1" +#else + let displayUITestRenderingEnabled = false +#endif + return Self.effectiveRendererWindowVisibility( + occlusionVisible: window.occlusionState.contains(.visible), + isVisible: window.isVisible, + displayUITestRenderingEnabled: displayUITestRenderingEnabled + ) + } + override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() if GhosttyApp.shared.backgroundLogEnabled { @@ -12901,7 +12925,15 @@ final class GhosttySurfaceScrollView: NSView { } ?? (0, 0, Self.contentsKey(for: surfaceView.layer)) let inWindow = (window != nil) let windowIsKey = window?.isKeyWindow ?? false - let windowOcclusionVisible = (window?.occlusionState.contains(.visible) ?? false) || (window?.isKeyWindow ?? false) + let windowOcclusionVisible = window.map { + GhosttyNSView.effectiveRendererWindowVisibility( + occlusionVisible: $0.occlusionState.contains(.visible), + isVisible: $0.isVisible, + displayUITestRenderingEnabled: ProcessInfo.processInfo.environment[ + "CMUX_UI_TEST_DISPLAY_RENDER_STATS" + ] == "1" + ) + } ?? false let appIsActive = NSApp.isActive let fr = window?.firstResponder as? NSView let isFirstResponder = fr == surfaceView || (fr?.isDescendant(of: surfaceView) ?? false) diff --git a/Sources/MainWindowFocusController.swift b/Sources/MainWindowFocusController.swift index cb0a9841a78f..8d5406562605 100644 --- a/Sources/MainWindowFocusController.swift +++ b/Sources/MainWindowFocusController.swift @@ -55,6 +55,7 @@ final class MainWindowFocusController { private weak var rightSidebarHost: RightSidebarKeyboardFocusView? private weak var fileExplorerHost: FileExplorerContainerView? private weak var fileSearchHost: FileExplorerContainerView? + private weak var artifactSearchField: ArtifactSidebarSearchFieldView? private weak var feedHost: FeedKeyboardFocusView? private weak var dockHost: DockKeyboardFocusView? @@ -127,7 +128,7 @@ final class MainWindowFocusController { fileExplorerHost = host case .find: fileSearchHost = host - case .sessions, .feed, .dock, .machines, .customSidebar: + case .sessions, .artifacts, .feed, .dock, .machines, .customSidebar: break } focusRegisteredRightSidebarEndpointIfNeeded(mode: mode) @@ -139,6 +140,11 @@ final class MainWindowFocusController { focusRegisteredRightSidebarEndpointIfNeeded(mode: .feed) } + func registerArtifactSearchField(_ searchField: ArtifactSidebarSearchFieldView) { + artifactSearchField = searchField + focusRegisteredRightSidebarEndpointIfNeeded(mode: .artifacts) + } + func registerDockHost(_ host: DockKeyboardFocusView) { dockHost = host focusRegisteredRightSidebarEndpointIfNeeded(mode: .dock) @@ -235,6 +241,9 @@ final class MainWindowFocusController { fileSearchHost?.ownsKeyboardFocus(responder) == true { return true } + if artifactSearchField?.ownsKeyboardFocus(responder) == true { + return true + } if feedHost?.ownsKeyboardFocus(responder) == true { return true } @@ -745,7 +754,7 @@ final class MainWindowFocusController { switch mode { case .files: return .outline - case .find: + case .find, .artifacts: return .searchField case .sessions, .machines, .customSidebar: return .host @@ -765,9 +774,11 @@ final class MainWindowFocusController { return fileExplorerHost?.focusOutline() == true case .find: return fileSearchHost?.focusSearchField() == true - case .sessions, .customSidebar: - return mode == .customSidebar ? focusFallbackRightSidebarHost() : false - case .machines: + case .artifacts: + return artifactSearchField?.focusFromCoordinator() == true + case .sessions: + return false + case .customSidebar, .machines: return focusFallbackRightSidebarHost() case .feed: if target == .firstItem { @@ -837,6 +848,9 @@ final class MainWindowFocusController { if fileSearchHost?.ownsKeyboardFocus(responder) == true { return .find } + if artifactSearchField?.ownsKeyboardFocus(responder) == true { + return .artifacts + } if feedHost?.ownsKeyboardFocus(responder) == true || responder is FeedKeyboardFocusResponder { return .feed } diff --git a/Sources/Mobile/AgentChat/AgentArtifactCaptureCheckpoint.swift b/Sources/Mobile/AgentChat/AgentArtifactCaptureCheckpoint.swift new file mode 100644 index 000000000000..4e07fdce049e --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactCaptureCheckpoint.swift @@ -0,0 +1,8 @@ +/// Completed transcript position for one session's automatic artifact capture. +struct AgentArtifactCaptureCheckpoint: Sendable { + let transcriptGeneration: String + let transcriptLineage: String + let transcriptExtent: UInt64 + let referenceCursor: AgentArtifactReferenceCursor? + let processedAuthorizationSequenceByPath: [String: Int] +} diff --git a/Sources/Mobile/AgentChat/AgentArtifactCaptureCoordinator.swift b/Sources/Mobile/AgentChat/AgentArtifactCaptureCoordinator.swift new file mode 100644 index 000000000000..fa8a08559b06 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactCaptureCoordinator.swift @@ -0,0 +1,303 @@ +import CmuxAgentChat +import CmuxArtifacts +import Foundation + +/// Bridges transcript artifact snapshots into the project-local artifact store. +actor AgentArtifactCaptureCoordinator { + private static let retainedSessionLimit = 64 + private static let maximumContentionRetryCount = 3 + private let captureService: ArtifactCaptureService + private let fileManager: FileManager + private let contentionRetryDelay: @Sendable (Int) async throws -> Void + private var inFlightRevisionBySession: [String: UInt64] = [:] + private var completedStateBySession = ChatArtifactLRUCache( + capacity: retainedSessionLimit + ) + + init( + captureService: ArtifactCaptureService, + fileManager: FileManager = .default, + contentionRetryDelay: @escaping @Sendable (Int) async throws -> Void = { attempt in + let milliseconds = 50 * (1 << min(max(attempt, 0), 3)) + // A bounded, cancellable backoff is the intended store-contention behavior. + try await Task.sleep(for: .milliseconds(milliseconds)) + } + ) { + self.captureService = captureService + self.fileManager = fileManager + self.contentionRetryDelay = contentionRetryDelay + } + + func maximumTranscriptScanBytes(for record: AgentChatSessionRecord) async -> UInt64? { + guard let projectRoot = projectRoot(for: record) else { return nil } + return await captureService.automaticTranscriptScanByteLimit(projectRoot: projectRoot) + } + + @discardableResult + func capture( + record: AgentChatSessionRecord, + snapshot: AgentChatArtifactIndex.Snapshot + ) async -> AgentArtifactCaptureProgress { + let completedState = completedStateBySession.value(forKey: record.sessionID) + guard !Task.isCancelled else { return .blocked } + guard let projectRoot = projectRoot(for: record), + completedState.flatMap(\.revision).map({ snapshot.revision > $0 }) ?? true else { + return .complete + } + guard inFlightRevisionBySession[record.sessionID] + .map({ snapshot.revision > $0 }) ?? true else { + return .blocked + } + inFlightRevisionBySession[record.sessionID] = snapshot.revision + defer { + if inFlightRevisionBySession[record.sessionID] == snapshot.revision { + inFlightRevisionBySession.removeValue(forKey: record.sessionID) + } + } + + let checkpoint = completedState?.checkpoint + let sameExtentRewrite = checkpoint.map { + !$0.transcriptGeneration.isEmpty + && $0.transcriptGeneration != snapshot.generation + && $0.transcriptExtent == snapshot.transcriptExtent + } ?? false + let transcriptReset = (checkpoint.map { + $0.transcriptLineage != snapshot.transcriptLineage + || snapshot.transcriptExtent < $0.transcriptExtent + } ?? false) || sameExtentRewrite + let completedCursor = transcriptReset ? nil : checkpoint?.referenceCursor + let currentPaths = Set(snapshot.artifacts.map(\.path)) + // Reference order can differ from authorization order, so consume authority per path. + var processedAuthorizationSequenceByPath: [String: Int] = transcriptReset + ? [:] + : checkpoint?.processedAuthorizationSequenceByPath.filter { + currentPaths.contains($0.key) + } ?? [:] + var seenPaths: Set = [] + let pending = snapshot.artifacts + .filter { artifact in + let cursor = AgentArtifactReferenceCursor( + sequence: artifact.lastReferencedSeq, + path: artifact.path + ) + return (completedCursor.map { cursor > $0 } ?? true) + && seenPaths.insert(artifact.path).inserted + } + .sorted { + AgentArtifactReferenceCursor(sequence: $0.lastReferencedSeq, path: $0.path) + < AgentArtifactReferenceCursor(sequence: $1.lastReferencedSeq, path: $1.path) + } + let context = ArtifactCaptureContext( + projectRoot: projectRoot, + workspaceID: record.workspaceID, + sessionID: record.sessionID, + agentName: record.agentKind.sourceName + ) + guard !pending.isEmpty else { + completedStateBySession.insert( + AgentArtifactCompletedCaptureState( + revision: snapshot.revision, + checkpoint: AgentArtifactCaptureCheckpoint( + transcriptGeneration: snapshot.generation, + transcriptLineage: snapshot.transcriptLineage, + transcriptExtent: snapshot.transcriptExtent, + referenceCursor: completedCursor, + processedAuthorizationSequenceByPath: processedAuthorizationSequenceByPath + ) + ), + forKey: record.sessionID + ) + return .complete + } + let outcomes = await captureService.capture( + candidates: pending.map { + ArtifactCandidate( + sourceURL: URL(fileURLWithPath: $0.path), + provenance: artifactProvenance( + captureProvenance( + for: $0, + processedAuthorizationSequenceByPath: processedAuthorizationSequenceByPath + ) + ) + ) + }, + context: context + ) + guard !Task.isCancelled, + inFlightRevisionBySession[record.sessionID] == snapshot.revision else { + return .blocked + } + let processedCount = outcomes.prefix { !isRetryableOutcome($0) }.count + var updatedCheckpoint = checkpoint + if processedCount > 0 { + for artifact in pending.prefix(processedCount) { + guard let authorization = freshAuthorization( + for: artifact, + processedAuthorizationSequenceByPath: processedAuthorizationSequenceByPath + ) else { continue } + processedAuthorizationSequenceByPath[artifact.path] = authorization.sequence + } + let last = pending[processedCount - 1] + updatedCheckpoint = AgentArtifactCaptureCheckpoint( + transcriptGeneration: snapshot.generation, + transcriptLineage: snapshot.transcriptLineage, + transcriptExtent: snapshot.transcriptExtent, + referenceCursor: AgentArtifactReferenceCursor( + sequence: last.lastReferencedSeq, + path: last.path + ), + processedAuthorizationSequenceByPath: processedAuthorizationSequenceByPath + ) + } + if processedCount > 0 { + completedStateBySession.insert( + AgentArtifactCompletedCaptureState( + revision: processedCount == pending.count + ? snapshot.revision + : completedState?.revision, + checkpoint: updatedCheckpoint + ), + forKey: record.sessionID + ) + } + guard processedCount < pending.count, + outcomes.indices.contains(processedCount) else { + return processedCount == pending.count ? .complete : .blocked + } + switch outcomes[processedCount] { + case .skipped(.candidateLimitReached): + return .needsContinuation + case .skipped(.scanIncomplete): + return .blocked + case .skipped(.storeBusy): + return .retryableContention + case .copied, .deduplicated, .alreadyStored, .skipped: + return .blocked + } + } + + func waitForContentionRetry(afterAttempt attempt: Int) async -> Bool { + guard attempt < Self.maximumContentionRetryCount, !Task.isCancelled else { + return false + } + do { + try await contentionRetryDelay(attempt) + return !Task.isCancelled + } catch { + return false + } + } + + func save( + context: ArtifactCaptureContext, + sourceURL: URL, + expectedCanonicalPath: String, + expectedIdentity: ChatArtifactFileIdentity, + capturedAt: Date = .now + ) async throws -> ChatArtifactSaveResult { + let outcome = try await captureService.add( + sourceURL: sourceURL, + context: context, + expectedCanonicalPath: expectedCanonicalPath, + expectedIdentity: ArtifactFileIdentity( + device: expectedIdentity.device, + inode: expectedIdentity.inode + ), + capturedAt: capturedAt + ) + guard let importedRecord = outcome.record else { + throw AgentArtifactCaptureSaveError.rejected + } + let path = ArtifactStorePaths(projectRoot: context.projectRoot).filesystemRoot + .appendingPathComponent(importedRecord.relativePath, isDirectory: false) + return ChatArtifactSaveResult( + path: path.path, + relativePath: importedRecord.relativePath, + reference: ".cmux/\(importedRecord.relativePath)" + ) + } + + func canSave( + context: ArtifactCaptureContext, + sourceURL: URL + ) async -> Bool { + await captureService.permitsExplicitAdd( + sourceURL: sourceURL, + context: context + ) + } + + /// Releases transcript progress when the owning chat session disappears. + func removeSession(sessionID: String) { + inFlightRevisionBySession.removeValue(forKey: sessionID) + _ = completedStateBySession.removeValue(forKey: sessionID) + } + + func captureContext(for record: AgentChatSessionRecord) -> ArtifactCaptureContext? { + guard let projectRoot = projectRoot(for: record) else { return nil } + return ArtifactCaptureContext( + projectRoot: projectRoot, + workspaceID: record.workspaceID, + sessionID: record.sessionID, + agentName: record.agentKind.sourceName + ) + } + + private func projectRoot(for record: AgentChatSessionRecord) -> URL? { + guard record.workingDirectoryAuthority.authorizesArtifactPersistence, + let workingDirectory = record.workingDirectory, + !workingDirectory.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return nil + } + return ArtifactProjectLocator().projectRoot( + startingAt: URL(fileURLWithPath: workingDirectory, isDirectory: true), + fileManager: fileManager + ) + } + + private func artifactProvenance(_ provenance: ChatArtifactProvenance) -> ArtifactProvenance { + switch provenance { + case .created: return .created + case .attached: return .attached + case .referenced: return .referenced + } + } + + private func captureProvenance( + for artifact: ChatArtifactIndexedReference, + processedAuthorizationSequenceByPath: [String: Int] + ) -> ChatArtifactProvenance { + freshAuthorization( + for: artifact, + processedAuthorizationSequenceByPath: processedAuthorizationSequenceByPath + )?.provenance ?? .referenced + } + + private func freshAuthorization( + for artifact: ChatArtifactIndexedReference, + processedAuthorizationSequenceByPath: [String: Int] + ) -> ChatArtifactCaptureAuthorization? { + guard let authorization = artifact.captureAuthorization, + authorization.sequence + > (processedAuthorizationSequenceByPath[artifact.path] ?? Int.min) else { + return nil + } + return authorization + } + + private func isRetryableOutcome(_ outcome: ArtifactImportOutcome) -> Bool { + switch outcome { + case .copied, .deduplicated, .alreadyStored: + return false + case .skipped(let reason): + switch reason { + case .automaticCaptureDisabled, .candidateLimitReached, .gitPrivacyUnavailable, + .storeBusy, .corruptProvenance, .scanIncomplete: + return true + case .notARegularFile, .provenanceNotEligible, .pathOutsideStore, + .unsupportedExtension, .exceedsSizeLimit: + return false + } + } + } +} diff --git a/Sources/Mobile/AgentChat/AgentArtifactCaptureProgress.swift b/Sources/Mobile/AgentChat/AgentArtifactCaptureProgress.swift new file mode 100644 index 000000000000..5ce653f5d9e1 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactCaptureProgress.swift @@ -0,0 +1,11 @@ +/// Result of one policy-bounded automatic artifact capture batch. +enum AgentArtifactCaptureProgress: Equatable, Sendable { + /// Every candidate in the snapshot has reached a terminal outcome. + case complete + /// A policy boundary left more candidates ready for another bounded batch. + case needsContinuation + /// The store is temporarily leased by another local mutation. + case retryableContention + /// Cancellation or an external safety gate requires a later event to retry. + case blocked +} diff --git a/Sources/Mobile/AgentChat/AgentArtifactCaptureSaveError.swift b/Sources/Mobile/AgentChat/AgentArtifactCaptureSaveError.swift new file mode 100644 index 000000000000..74bc34ae1807 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactCaptureSaveError.swift @@ -0,0 +1,5 @@ +import Foundation + +enum AgentArtifactCaptureSaveError: Error { + case rejected +} diff --git a/Sources/Mobile/AgentChat/AgentArtifactCompletedCaptureState.swift b/Sources/Mobile/AgentChat/AgentArtifactCompletedCaptureState.swift new file mode 100644 index 000000000000..bb2465bb2d26 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactCompletedCaptureState.swift @@ -0,0 +1,5 @@ +/// Last fully or partially persisted artifact-capture state for one chat session. +struct AgentArtifactCompletedCaptureState: Sendable { + let revision: UInt64? + let checkpoint: AgentArtifactCaptureCheckpoint? +} diff --git a/Sources/Mobile/AgentChat/AgentArtifactReferenceCursor.swift b/Sources/Mobile/AgentChat/AgentArtifactReferenceCursor.swift new file mode 100644 index 000000000000..3b44182b6ba9 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentArtifactReferenceCursor.swift @@ -0,0 +1,12 @@ +import Foundation + +/// Orders transcript artifact references so completed capture work advances monotonically. +struct AgentArtifactReferenceCursor: Comparable, Sendable { + let sequence: Int + let path: String + + static func < (lhs: AgentArtifactReferenceCursor, rhs: AgentArtifactReferenceCursor) -> Bool { + if lhs.sequence != rhs.sequence { return lhs.sequence < rhs.sequence } + return lhs.path < rhs.path + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatArtifactIndex.swift b/Sources/Mobile/AgentChat/AgentChatArtifactIndex.swift index 23d0d963288f..71f87ebd92c7 100644 --- a/Sources/Mobile/AgentChat/AgentChatArtifactIndex.swift +++ b/Sources/Mobile/AgentChat/AgentChatArtifactIndex.swift @@ -1,12 +1,36 @@ import CmuxAgentChat +import Darwin import Foundation /// Builds and caches the transcript-derived artifact scope for chat sessions. actor AgentChatArtifactIndex { + static let hardMaximumTranscriptBytes: UInt64 = 128 * 1024 * 1024 + static let maximumRetainedArtifactCount = 1_024 + struct Snapshot: Sendable { let referencedPaths: Set let artifacts: [ChatArtifactIndexedReference] let generation: String + let revision: UInt64 + let transcriptLineage: String + let transcriptExtent: UInt64 + + init( + referencedPaths: Set, + artifacts: [ChatArtifactIndexedReference], + generation: String, + revision: UInt64, + transcriptLineage: String = "", + transcriptExtent: UInt64? = nil + ) { + self.referencedPaths = referencedPaths + self.artifacts = artifacts + self.generation = generation + self.revision = revision + self.transcriptLineage = transcriptLineage + self.transcriptExtent = transcriptExtent + ?? UInt64(max(0, artifacts.map(\.lastReferencedSeq).max() ?? 0)) + } } enum Operation: Sendable { @@ -25,36 +49,127 @@ actor AgentChatArtifactIndex { let workingDirectory: String? let fileSize: UInt64 let modifiedAt: Date + let changedAt: Date + let transcriptLineage: String + let maximumFileBytes: UInt64 var generation: String { - "\(fileSize)-\(Int64(modifiedAt.timeIntervalSince1970 * 1_000_000))" + let modified = Int64(modifiedAt.timeIntervalSince1970 * 1_000_000) + let changed = Int64(changedAt.timeIntervalSince1970 * 1_000_000) + // Gallery consumers use this as the cache identity for authorized + // paths. Include every source-bound input, not just stat metadata, + // so a lineage or scan-limit change cannot reuse stale rows. + let identity = [ + transcriptPath, + workingDirectory ?? "", + transcriptLineage, + String(maximumFileBytes), + ].joined(separator: "\u{0}") + let identityDigest = AgentChatTranscriptReader() + .digest(Data(identity.utf8)) + .base64EncodedString() + return "\(fileSize)-\(modified)-\(changed)-\(identityDigest)" } } private struct CacheEntry: Sendable { let key: CacheKey let snapshot: Snapshot + let continuityStartOffset: UInt64 + let continuityByteCount: UInt64 + let continuityDigest: Data } private var cacheBySessionID = ChatArtifactLRUCache(capacity: 8) + private var nextSnapshotRevision: UInt64 = 0 func snapshot( sessionID: String, agentKind: ChatAgentKind, transcriptPath: String, - workingDirectory: String? + workingDirectory: String?, + maximumFileBytes: UInt64? = nil ) async throws -> Snapshot { - let key = try Self.cacheKey(transcriptPath: transcriptPath, workingDirectory: workingDirectory) - if let cached = cacheBySessionID.value(forKey: sessionID), cached.key == key { - return cached.snapshot + try Task.checkCancellation() + let byteLimit = min(maximumFileBytes ?? Self.hardMaximumTranscriptBytes, + Self.hardMaximumTranscriptBytes) + let opened = try Self.openTranscript( + path: transcriptPath, + workingDirectory: workingDirectory, + maximumFileBytes: byteLimit + ) + defer { try? opened.handle.close() } + let key = opened.key + let previous = cacheBySessionID.value(forKey: sessionID) + if let previous, previous.key == key { + return previous.snapshot + } + let reader = AgentChatTranscriptReader() + let matchesPreviousSlice = try previous.map { entry in + let hasSameSource = entry.key.transcriptLineage == key.transcriptLineage + && entry.key.transcriptPath == key.transcriptPath + && entry.key.workingDirectory == key.workingDirectory + && entry.key.maximumFileBytes == key.maximumFileBytes + guard hasSameSource, + entry.continuityByteCount <= key.fileSize, + entry.continuityStartOffset <= key.fileSize - entry.continuityByteCount else { + return false + } + return try reader.matchesContent( + handle: opened.handle, + startOffset: entry.continuityStartOffset, + byteCount: entry.continuityByteCount, + expectedDigest: entry.continuityDigest + ) + } ?? false + let fullyObservedPreviousContent = previous?.continuityStartOffset == 0 + if matchesPreviousSlice, + fullyObservedPreviousContent, + let previous, + previous.key.fileSize == key.fileSize { + cacheBySessionID.insert( + CacheEntry( + key: key, + snapshot: previous.snapshot, + continuityStartOffset: previous.continuityStartOffset, + continuityByteCount: previous.continuityByteCount, + continuityDigest: previous.continuityDigest + ), + forKey: sessionID + ) + return previous.snapshot } + let safelyExtendsPreviousTranscript = matchesPreviousSlice + && fullyObservedPreviousContent + && (previous?.key.fileSize ?? key.fileSize) < key.fileSize + let slice = try reader.read( + handle: opened.handle, + fileSize: key.fileSize, + maximumBytes: key.maximumFileBytes + ) + let sliceDigest = reader.digest(slice.data) + nextSnapshotRevision &+= 1 let snapshot = try Self.buildSnapshot( agentKind: agentKind, - transcriptPath: transcriptPath, + slice: slice, workingDirectory: workingDirectory, - generation: key.generation + generation: "\(key.generation)-\(sliceDigest.base64EncodedString())", + revision: nextSnapshotRevision, + transcriptLineage: key.transcriptLineage, + previousArtifacts: safelyExtendsPreviousTranscript + ? previous?.snapshot.artifacts ?? [] + : [] + ) + cacheBySessionID.insert( + CacheEntry( + key: key, + snapshot: snapshot, + continuityStartOffset: slice.lineStartOffsets.first ?? slice.transcriptExtent, + continuityByteCount: UInt64(slice.data.count), + continuityDigest: sliceDigest + ), + forKey: sessionID ) - cacheBySessionID.insert(CacheEntry(key: key, snapshot: snapshot), forKey: sessionID) return snapshot } @@ -92,44 +207,185 @@ actor AgentChatArtifactIndex { return canonicalPath.map(CanonicalPathResult.success) ?? .notInSet } - private static func cacheKey(transcriptPath: String, workingDirectory: String?) throws -> CacheKey { - let attributes = try FileManager.default.attributesOfItem(atPath: transcriptPath) - let size = (attributes[.size] as? NSNumber)?.uint64Value ?? 0 - let modifiedAt = attributes[.modificationDate] as? Date ?? Date(timeIntervalSince1970: 0) - return CacheKey( - transcriptPath: transcriptPath, + private static func openTranscript( + path: String, + workingDirectory: String?, + maximumFileBytes: UInt64 + ) throws -> (key: CacheKey, handle: FileHandle) { + let descriptor = Darwin.open( + path, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK + ) + guard descriptor >= 0 else { + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: path]) + } + let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + var status = stat() + guard fstat(descriptor, &status) == 0, + (status.st_mode & S_IFMT) == S_IFREG, + status.st_size >= 0 else { + try? handle.close() + throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: path]) + } + let size = UInt64(status.st_size) + let modifiedAt = Date( + timeIntervalSince1970: Double(status.st_mtimespec.tv_sec) + + Double(status.st_mtimespec.tv_nsec) / 1_000_000_000 + ) + let changedAt = Date( + timeIntervalSince1970: Double(status.st_ctimespec.tv_sec) + + Double(status.st_ctimespec.tv_nsec) / 1_000_000_000 + ) + let key = CacheKey( + transcriptPath: path, workingDirectory: workingDirectory, fileSize: size, - modifiedAt: modifiedAt + modifiedAt: modifiedAt, + changedAt: changedAt, + transcriptLineage: "\(path):\(status.st_dev):\(status.st_ino)", + maximumFileBytes: maximumFileBytes ) + return (key, handle) } private static func buildSnapshot( agentKind: ChatAgentKind, - transcriptPath: String, + slice: AgentChatTranscriptSlice, workingDirectory: String?, - generation: String + generation: String, + revision: UInt64, + transcriptLineage: String, + previousArtifacts: [ChatArtifactIndexedReference] ) throws -> Snapshot { - let data = try Data(contentsOf: URL(fileURLWithPath: transcriptPath), options: .mappedIfSafe) - let text = String(decoding: data, as: UTF8.self) - let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + // The reader keeps at most this many line starts, but decode records + // lazily as well so a future reader change cannot turn a byte-bounded + // suffix into an unbounded array of per-line strings. + let lines = AgentChatTranscriptReader.BoundedLineSequence( + data: slice.data, + maximumLineCount: min( + slice.lineStartOffsets.count, + AgentChatTranscriptReader.maximumRetainedLineCount + ) + ) let parseResult: ChatTranscriptParseResult switch agentKind { case .codex: - parseResult = CodexTranscriptParser().parse(lines: lines, startingSeq: 0) + parseResult = CodexTranscriptParser().parse( + lines: lines, + startingSeq: 0 + ) case .claude, .other: - parseResult = ClaudeTranscriptParser().parse(lines: lines, startingSeq: 0) + parseResult = ClaudeTranscriptParser().parse( + lines: lines, + startingSeq: 0 + ) } - let artifacts = ChatArtifactIndexedReference.derive( + let relativeArtifacts = ChatArtifactIndexedReference.derive( from: parseResult.messages, supplementalReferences: parseResult.artifactReferences, workingDirectory: workingDirectory ) + let currentArtifacts = relativeArtifacts.compactMap { artifact -> ChatArtifactIndexedReference? in + guard slice.lineStartOffsets.indices.contains(artifact.lastReferencedSeq), + let absoluteSequence = Int( + exactly: slice.lineStartOffsets[artifact.lastReferencedSeq] + ) else { + return nil + } + return ChatArtifactIndexedReference( + path: artifact.path, + provenance: artifact.provenance, + lastReferencedSeq: absoluteSequence, + captureAuthorization: absoluteAuthorization( + artifact.captureAuthorization, + lineStartOffsets: slice.lineStartOffsets + ) + ) + } + let artifacts = mergedArtifacts( + previousArtifacts, + currentArtifacts, + maximumCount: maximumRetainedArtifactCount + ) let referencedPaths = Set(artifacts.map(\.path)) return Snapshot( referencedPaths: referencedPaths, artifacts: artifacts, - generation: generation + generation: generation, + revision: revision, + transcriptLineage: transcriptLineage, + transcriptExtent: slice.transcriptExtent ) } + + private static func mergedArtifacts( + _ previous: [ChatArtifactIndexedReference], + _ current: [ChatArtifactIndexedReference], + maximumCount: Int + ) -> [ChatArtifactIndexedReference] { + var artifacts = Dictionary(uniqueKeysWithValues: previous.map { ($0.path, $0) }) + for artifact in current { + let existing = artifacts[artifact.path] + artifacts[artifact.path] = ChatArtifactIndexedReference( + path: artifact.path, + provenance: higherPrecedence(existing?.provenance, artifact.provenance), + lastReferencedSeq: max( + existing?.lastReferencedSeq ?? Int.min, + artifact.lastReferencedSeq + ), + captureAuthorization: latestAuthorization( + existing?.captureAuthorization, + artifact.captureAuthorization + ) + ) + } + return Array(artifacts.values.sorted { + if $0.lastReferencedSeq != $1.lastReferencedSeq { + return $0.lastReferencedSeq > $1.lastReferencedSeq + } + return $0.path < $1.path + }.prefix(maximumCount)) + } + + private static func higherPrecedence( + _ lhs: ChatArtifactProvenance?, + _ rhs: ChatArtifactProvenance + ) -> ChatArtifactProvenance { + guard let lhs else { return rhs } + let rank: (ChatArtifactProvenance) -> Int = { + switch $0 { + case .created: 0 + case .attached: 1 + case .referenced: 2 + } + } + return rank(lhs) <= rank(rhs) ? lhs : rhs + } + + private static func absoluteAuthorization( + _ authorization: ChatArtifactCaptureAuthorization?, + lineStartOffsets: [UInt64] + ) -> ChatArtifactCaptureAuthorization? { + guard let authorization, + lineStartOffsets.indices.contains(authorization.sequence), + let sequence = Int(exactly: lineStartOffsets[authorization.sequence]) else { + return nil + } + switch authorization { + case .created: return .created(sequence: sequence) + case .attached: return .attached(sequence: sequence) + } + } + + private static func latestAuthorization( + _ lhs: ChatArtifactCaptureAuthorization?, + _ rhs: ChatArtifactCaptureAuthorization? + ) -> ChatArtifactCaptureAuthorization? { + guard let lhs else { return rhs } + guard let rhs else { return lhs } + if lhs.sequence != rhs.sequence { + return lhs.sequence > rhs.sequence ? lhs : rhs + } + return higherPrecedence(lhs.provenance, rhs.provenance) == lhs.provenance ? lhs : rhs + } } diff --git a/Sources/Mobile/AgentChat/AgentChatObservedWorkingDirectoryResolver.swift b/Sources/Mobile/AgentChat/AgentChatObservedWorkingDirectoryResolver.swift new file mode 100644 index 000000000000..c4f5f4c7e67a --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatObservedWorkingDirectoryResolver.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Classifies process-observed working directories by their persistence authority. +struct AgentChatObservedWorkingDirectoryResolver { + func resolve( + environment: [String: String]? + ) -> (path: String?, authority: AgentChatWorkingDirectoryAuthority) { + guard let environment else { return (nil, .unknown) } + if let value = environment["CMUX_AGENT_LAUNCH_CWD"]? + .trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty { + return (value, .processObservation) + } + if let value = environment["PWD"]?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty { + return (value, .processObservation) + } + return (nil, .unknown) + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatSessionRecencyIndex.swift b/Sources/Mobile/AgentChat/AgentChatSessionRecencyIndex.swift new file mode 100644 index 000000000000..bc7a4abca4f5 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatSessionRecencyIndex.swift @@ -0,0 +1,128 @@ +import Foundation + +/// Main-actor-owned bounded min-heap for recent-session selection. +struct AgentChatSessionRecencyIndex { + private typealias Entry = (sessionID: String, lastActivityAt: Date) + + private var entries: [Entry] = [] + private var indexBySessionID: [String: Int] = [:] + private(set) var needsRebuild = false + + /// Creates an index retaining at most `capacity` recent sessions. + init(capacity: Int) { + self.capacity = max(0, capacity) + } + + private let capacity: Int + + /// Inserts or updates one session's recency key. + mutating func upsert(sessionID: String, lastActivityAt: Date) { + if let index = indexBySessionID[sessionID] { + let previousDate = entries[index].lastActivityAt + entries[index] = Entry(sessionID: sessionID, lastActivityAt: lastActivityAt) + if lastActivityAt < previousDate { + // A previously evicted record may now belong in the top-K set; + // defer to the authoritative registry before the next query. + needsRebuild = true + } + if !siftDown(from: index) { + siftUp(from: index) + } + return + } + guard capacity > 0 else { return } + let entry = Entry(sessionID: sessionID, lastActivityAt: lastActivityAt) + guard entries.count < capacity else { + guard isOlder(entries[0], than: entry) else { return } + indexBySessionID.removeValue(forKey: entries[0].sessionID) + entries[0] = entry + indexBySessionID[entry.sessionID] = 0 + _ = siftDown(from: 0) + return + } + indexBySessionID[sessionID] = entries.count + entries.append(entry) + _ = siftUp(from: entries.count - 1) + } + + /// Removes one session from the index. + mutating func remove(sessionID: String) { + guard let index = indexBySessionID.removeValue(forKey: sessionID) else { return } + needsRebuild = true + let last = entries.removeLast() + guard index < entries.count else { return } + entries[index] = last + indexBySessionID[last.sessionID] = index + if !siftDown(from: index) { + siftUp(from: index) + } + } + + /// Removes all retained entries so the owner can rebuild from authoritative records. + mutating func reset() { + entries.removeAll(keepingCapacity: true) + indexBySessionID.removeAll(keepingCapacity: true) + needsRebuild = false + } + + /// Returns the most recent retained session IDs. + func mostRecentSessionIDs(limit: Int) -> [String] { + entries + .sorted { lhs, rhs in + if lhs.lastActivityAt != rhs.lastActivityAt { + return lhs.lastActivityAt > rhs.lastActivityAt + } + return lhs.sessionID < rhs.sessionID + } + .prefix(max(0, limit)) + .map(\.sessionID) + } + + /// Moves an entry toward the heap root when it is older than its parent. + /// - Returns: Whether the entry moved. + @discardableResult + private mutating func siftUp(from index: Int) -> Bool { + var child = index + var moved = false + while child > 0 { + let parent = (child - 1) / 2 + guard isOlder(entries[child], than: entries[parent]) else { break } + swapAt(child, parent) + child = parent + moved = true + } + return moved + } + + @discardableResult + private mutating func siftDown(from index: Int) -> Bool { + var parent = index + var moved = false + while true { + let left = parent * 2 + 1 + guard left < entries.count else { return moved } + var candidate = left + let right = left + 1 + if right < entries.count, isOlder(entries[right], than: entries[left]) { + candidate = right + } + guard isOlder(entries[candidate], than: entries[parent]) else { return moved } + swapAt(parent, candidate) + parent = candidate + moved = true + } + } + + private func isOlder(_ lhs: Entry, than rhs: Entry) -> Bool { + if lhs.lastActivityAt != rhs.lastActivityAt { + return lhs.lastActivityAt < rhs.lastActivityAt + } + return lhs.sessionID > rhs.sessionID + } + + private mutating func swapAt(_ lhs: Int, _ rhs: Int) { + entries.swapAt(lhs, rhs) + indexBySessionID[entries[lhs].sessionID] = lhs + indexBySessionID[entries[rhs].sessionID] = rhs + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatSessionRecord.swift b/Sources/Mobile/AgentChat/AgentChatSessionRecord.swift index b582248b10a3..5e149f258ea7 100644 --- a/Sources/Mobile/AgentChat/AgentChatSessionRecord.swift +++ b/Sources/Mobile/AgentChat/AgentChatSessionRecord.swift @@ -20,6 +20,9 @@ struct AgentChatSessionRecord: Sendable { /// The session's working directory, when known. var workingDirectory: String? + /// Whether the working directory may choose a local persistence root. + var workingDirectoryAuthority: AgentChatWorkingDirectoryAuthority = .unknown + /// Absolute transcript JSONL path, when resolved. var transcriptPath: String? @@ -77,6 +80,27 @@ struct AgentChatSessionRecord: Sendable { hasHookLifecycleState = false } + mutating func adoptObservedWorkingDirectory( + _ value: String?, + authority: AgentChatWorkingDirectoryAuthority + ) { + guard let value, + authority.authorizesArtifactPersistence + || !workingDirectoryAuthority.authorizesArtifactPersistence else { + return + } + workingDirectory = value + workingDirectoryAuthority = authority + } + + mutating func setAuthoritativeWorkingDirectory( + _ value: String, + authority: AgentChatWorkingDirectoryAuthority + ) { + workingDirectory = value + workingDirectoryAuthority = authority + } + /// Adopts terminal/transcript bindings from a hook-store entry. The /// store is rewritten by every hook event, so its non-nil fields are /// fresher than the record's (panel UUIDs change across app @@ -97,7 +121,9 @@ struct AgentChatSessionRecord: Sendable { surfaceID = entry.surfaceID ?? surfaceID workspaceID = entry.workspaceID ?? workspaceID transcriptPath = entry.transcriptPath ?? transcriptPath - workingDirectory = entry.workingDirectory ?? workingDirectory + if let workingDirectory = entry.workingDirectory { + setAuthoritativeWorkingDirectory(workingDirectory, authority: .hook) + } if includingPID { pid = entry.pid ?? pid } @@ -112,7 +138,10 @@ struct AgentChatSessionRecord: Sendable { if surfaceID == nil { surfaceID = entry.surfaceID } if workspaceID == nil { workspaceID = entry.workspaceID } if transcriptPath == nil { transcriptPath = entry.transcriptPath } - if workingDirectory == nil { workingDirectory = entry.workingDirectory } + if let workingDirectory = entry.workingDirectory, + !workingDirectoryAuthority.authorizesArtifactPersistence { + setAuthoritativeWorkingDirectory(workingDirectory, authority: .hook) + } if includingPID, pid == nil { pid = entry.pid } } diff --git a/Sources/Mobile/AgentChat/AgentChatSessionRegistry+Lifecycle.swift b/Sources/Mobile/AgentChat/AgentChatSessionRegistry+Lifecycle.swift index c6f5ee4bbf09..d3d8de6bfc20 100644 --- a/Sources/Mobile/AgentChat/AgentChatSessionRegistry+Lifecycle.swift +++ b/Sources/Mobile/AgentChat/AgentChatSessionRegistry+Lifecycle.swift @@ -15,6 +15,7 @@ struct ObservedAgentSession: Sendable { let workspaceID: String? let pid: Int let workingDirectory: String? + let workingDirectoryAuthority: AgentChatWorkingDirectoryAuthority let transcriptPath: String? let sampledAt: Date @@ -25,6 +26,7 @@ struct ObservedAgentSession: Sendable { workspaceID: String?, pid: Int, workingDirectory: String?, + workingDirectoryAuthority: AgentChatWorkingDirectoryAuthority = .processObservation, transcriptPath: String?, sampledAt: Date = Date() ) { @@ -34,6 +36,7 @@ struct ObservedAgentSession: Sendable { self.workspaceID = workspaceID self.pid = pid self.workingDirectory = workingDirectory + self.workingDirectoryAuthority = workingDirectory == nil ? .unknown : workingDirectoryAuthority self.transcriptPath = transcriptPath self.sampledAt = sampledAt } diff --git a/Sources/Mobile/AgentChat/AgentChatSessionRegistry+ObserveScan.swift b/Sources/Mobile/AgentChat/AgentChatSessionRegistry+ObserveScan.swift index ce66ef78805b..4c87c205385e 100644 --- a/Sources/Mobile/AgentChat/AgentChatSessionRegistry+ObserveScan.swift +++ b/Sources/Mobile/AgentChat/AgentChatSessionRegistry+ObserveScan.swift @@ -17,7 +17,10 @@ extension AgentChatSessionRegistry { update(sessionID: current.sessionID) { record in record.workspaceID = session.workspaceID ?? record.workspaceID record.surfaceID = session.surfaceID - record.workingDirectory = session.workingDirectory ?? record.workingDirectory + record.adoptObservedWorkingDirectory( + session.workingDirectory, + authority: session.workingDirectoryAuthority + ) record.transcriptPath = session.transcriptPath ?? record.transcriptPath record.pid = session.pid record.setProcessObservedIdle() @@ -40,7 +43,10 @@ extension AgentChatSessionRegistry { update(sessionID: current.sessionID) { record in record.workspaceID = session.workspaceID ?? record.workspaceID record.surfaceID = session.surfaceID - record.workingDirectory = session.workingDirectory ?? record.workingDirectory + record.adoptObservedWorkingDirectory( + session.workingDirectory, + authority: session.workingDirectoryAuthority + ) record.transcriptPath = session.transcriptPath ?? record.transcriptPath record.pid = session.pid record.setProcessObservedIdle() @@ -279,6 +285,9 @@ extension AgentChatSessionRegistry { let explicitSessionOption = !isClaudeForkLaunch && (argv.map(containsExplicitSessionOption(_:)) ?? false) guard let resolved = sessionID ?? (def.id == "claude" && !explicitSessionOption ? pendingClaudeSessionID(surfaceID: surfaceID.uuidString) : nil) else { continue } + let observedDirectory = AgentChatObservedWorkingDirectoryResolver().resolve( + environment: loadedDetails?.environment + ) let candidate = Candidate( session: ObservedAgentSession( sessionID: resolved, @@ -286,7 +295,8 @@ extension AgentChatSessionRegistry { surfaceID: surfaceID.uuidString, workspaceID: process.cmuxWorkspaceID?.uuidString, pid: process.pid, - workingDirectory: observedWorkingDirectory(details?.environment), + workingDirectory: observedDirectory.path, + workingDirectoryAuthority: observedDirectory.authority, transcriptPath: transcriptPath, sampledAt: snapshot.sampledAt ), @@ -400,17 +410,6 @@ extension AgentChatSessionRegistry { return trimmed?.isEmpty == false ? trimmed : nil } - private nonisolated static func observedWorkingDirectory(_ environment: [String: String]?) -> String? { - guard let environment else { return nil } - for key in ["CMUX_AGENT_LAUNCH_CWD", "PWD"] { - if let value = environment[key]?.trimmingCharacters(in: .whitespacesAndNewlines), - !value.isEmpty { - return value - } - } - return nil - } - private func endedPendingClaudeSessionHasHistoryIdentity(_ record: AgentChatSessionRecord) -> Bool { record.transcriptPath != nil || record.hookStoreSessionID != nil } diff --git a/Sources/Mobile/AgentChat/AgentChatSessionRegistry.swift b/Sources/Mobile/AgentChat/AgentChatSessionRegistry.swift index 4569c4b9cca7..78ffe30b6dda 100644 --- a/Sources/Mobile/AgentChat/AgentChatSessionRegistry.swift +++ b/Sources/Mobile/AgentChat/AgentChatSessionRegistry.swift @@ -6,7 +6,10 @@ import Foundation /// hook events and the on-disk hook session stores. @MainActor final class AgentChatSessionRegistry { + private static let recencyIndexCapacity = 64 private var records: [String: AgentChatSessionRecord] = [:] + private var allSessionRecencyIndex = AgentChatSessionRecencyIndex(capacity: recencyIndexCapacity) + private var activeSessionRecencyIndex = AgentChatSessionRecencyIndex(capacity: recencyIndexCapacity) private var sessionSurfaceIndex = ChatSessionSurfaceIndex() private var liveSessionIDBySurfaceID: [String: String] = [:] private var liveClaudeSessionIDsBySurfaceID: [String: Set] = [:] @@ -64,6 +67,16 @@ final class AgentChatSessionRegistry { } rebuildSessionIndexes() for record in records.values { + allSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + if record.state != .ended { + activeSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + } syncProcessExitWatch(for: record) } } @@ -79,6 +92,92 @@ final class AgentChatSessionRegistry { .sorted { $0.lastActivityAt > $1.lastActivityAt } } + /// Returns the most recently active matching sessions without allocating or + /// sorting the entire retained registry. Startup consumers use this bounded + /// top-K view before creating tailers or capture work. + /// + /// - Parameters: + /// - workspaceID: Workspace UUID filter, or `nil` for all workspaces. + /// - limit: Maximum records to retain and return. + /// - excludingEnded: Whether ended records should be ignored before the + /// top-K bound is applied. + /// - Returns: At most `limit` records, most recent first. + func recentSessions( + workspaceID: String?, + limit: Int, + excludingEnded: Bool = false + ) -> [AgentChatSessionRecord] { + let capacity = max(0, limit) + guard capacity > 0 else { return [] } + if workspaceID == nil { + rebuildRecentSessionIndexesIfNeeded() + if excludingEnded { + return activeSessionRecencyIndex + .mostRecentSessionIDs(limit: capacity) + .compactMap { records[$0] } + } + return allSessionRecencyIndex + .mostRecentSessionIDs(limit: capacity) + .compactMap { records[$0] } + } + var retained: [AgentChatSessionRecord] = [] + retained.reserveCapacity(capacity) + for record in records.values + where (workspaceID == nil || record.workspaceID == workspaceID) + && (!excludingEnded || record.state != .ended) { + guard retained.count >= capacity else { + retained.append(record) + continue + } + guard let oldestIndex = retained.indices.min(by: { lhs, rhs in + Self.isOlderSession(retained[lhs], than: retained[rhs]) + }), Self.isOlderSession(retained[oldestIndex], than: record) else { + continue + } + retained[oldestIndex] = record + } + return retained.sorted { lhs, rhs in + if lhs.lastActivityAt != rhs.lastActivityAt { + return lhs.lastActivityAt > rhs.lastActivityAt + } + return lhs.sessionID < rhs.sessionID + } + } + + private static func isOlderSession( + _ lhs: AgentChatSessionRecord, + than rhs: AgentChatSessionRecord + ) -> Bool { + if lhs.lastActivityAt != rhs.lastActivityAt { + return lhs.lastActivityAt < rhs.lastActivityAt + } + return lhs.sessionID > rhs.sessionID + } + + /// Rebuilds a bounded index only after a retained top-K entry disappears. + /// Normal hook/activity updates stay O(log 64); the authoritative registry + /// is scanned only for that rare invalidation path. + private func rebuildRecentSessionIndexesIfNeeded() { + if allSessionRecencyIndex.needsRebuild { + allSessionRecencyIndex.reset() + for record in records.values { + allSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + } + } + if activeSessionRecencyIndex.needsRebuild { + activeSessionRecencyIndex.reset() + for record in records.values where record.state != .ended { + activeSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + } + } + } + /// Reconciles the session's exit watcher with its current pid. Called from /// every record-store path, so a watcher exists exactly while a session has /// a live pid and is cancelled when the pid changes, clears, or the session @@ -144,6 +243,7 @@ final class AgentChatSessionRegistry { workspaceID: session.workspaceID, surfaceID: session.surfaceID, workingDirectory: session.workingDirectory, + workingDirectoryAuthority: session.workingDirectoryAuthority, transcriptPath: session.transcriptPath, state: .idle, lastActivityAt: now, @@ -161,9 +261,15 @@ final class AgentChatSessionRegistry { if reviveEndedObservedSessionIfNeeded(current: current, observed: session, now: now) { continue } + var observedCandidate = current + observedCandidate.adoptObservedWorkingDirectory( + session.workingDirectory, + authority: session.workingDirectoryAuthority + ) let needsBackfill = current.surfaceID == nil || (current.workspaceID == nil && session.workspaceID != nil) - || (current.workingDirectory == nil && session.workingDirectory != nil) + || observedCandidate.workingDirectory != current.workingDirectory + || observedCandidate.workingDirectoryAuthority != current.workingDirectoryAuthority || (current.transcriptPath == nil && session.transcriptPath != nil) || current.pid == nil || ( @@ -178,7 +284,10 @@ final class AgentChatSessionRegistry { } if rec.surfaceID == nil { rec.surfaceID = session.surfaceID } if rec.workspaceID == nil { rec.workspaceID = session.workspaceID } - if rec.workingDirectory == nil { rec.workingDirectory = session.workingDirectory } + rec.adoptObservedWorkingDirectory( + session.workingDirectory, + authority: session.workingDirectoryAuthority + ) if rec.transcriptPath == nil { rec.transcriptPath = session.transcriptPath } if rec.pid == nil { rec.pid = session.pid } } @@ -388,7 +497,9 @@ final class AgentChatSessionRegistry { guard candidate.surfaceID != current.surfaceID || candidate.workspaceID != current.workspaceID || candidate.transcriptPath != current.transcriptPath - || candidate.workingDirectory != current.workingDirectory || candidate.hookStoreSessionID != current.hookStoreSessionID else { continue } + || candidate.workingDirectory != current.workingDirectory + || candidate.workingDirectoryAuthority != current.workingDirectoryAuthority + || candidate.hookStoreSessionID != current.hookStoreSessionID else { continue } update(sessionID: sessionID) { record in record.adoptMissingBindings(from: entry, includingPID: false) } @@ -401,6 +512,7 @@ final class AgentChatSessionRegistry { workspaceID: entry.workspaceID, surfaceID: entry.surfaceID, workingDirectory: entry.workingDirectory, + workingDirectoryAuthority: entry.workingDirectory == nil ? .unknown : .hook, transcriptPath: entry.transcriptPath, state: alive ? .idle : .ended, lastActivityAt: entry.updatedAt ?? .distantPast, @@ -493,7 +605,7 @@ final class AgentChatSessionRegistry { record.surfaceID = surfaceID } if let cwd = event.cwd, !cwd.isEmpty { - record.workingDirectory = cwd + record.setAuthoritativeWorkingDirectory(cwd, authority: .hook) } if let transcriptPath = event.transcriptPath, !transcriptPath.isEmpty { record.transcriptPath = transcriptPath @@ -641,7 +753,9 @@ final class AgentChatSessionRegistry { update(sessionID: sessionID) { record in if let normalizedSurface { record.surfaceID = normalizedSurface } if let normalizedWorkspace { record.workspaceID = normalizedWorkspace } - if let normalizedCwd { record.workingDirectory = normalizedCwd } + if let normalizedCwd { + record.setAuthoritativeWorkingDirectory(normalizedCwd, authority: .cmuxLaunch) + } record.pid = nil record.setProcessObservedIdle() record.lastActivityAt = now @@ -657,6 +771,7 @@ final class AgentChatSessionRegistry { workspaceID: normalizedWorkspace, surfaceID: normalizedSurface, workingDirectory: normalizedCwd, + workingDirectoryAuthority: normalizedCwd == nil ? .unknown : .cmuxLaunch, transcriptPath: nil, state: .idle, lastActivityAt: now, @@ -707,6 +822,7 @@ final class AgentChatSessionRegistry { || candidate.workspaceID != current.workspaceID || candidate.transcriptPath != current.transcriptPath || candidate.workingDirectory != current.workingDirectory + || candidate.workingDirectoryAuthority != current.workingDirectoryAuthority || candidate.pid != current.pid || candidate.hookStoreSessionID != current.hookStoreSessionID else { return } update(sessionID: sessionID) { record in record.adoptMissingBindings(from: entry, includingPID: record.pid == nil) @@ -719,6 +835,18 @@ final class AgentChatSessionRegistry { replacing previous: AgentChatSessionRecord? ) { records[record.sessionID] = record + allSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + if record.state == .ended { + activeSessionRecencyIndex.remove(sessionID: record.sessionID) + } else { + activeSessionRecencyIndex.upsert( + sessionID: record.sessionID, + lastActivityAt: record.lastActivityAt + ) + } syncProcessExitWatch(for: record) updateSessionIndexes(previous: previous, current: record) onRecordChanged?(record, previous) @@ -727,6 +855,8 @@ final class AgentChatSessionRegistry { /// Removes one record and reconciles every derived registry structure. private func removeRecord(sessionID: String) { guard var record = records.removeValue(forKey: sessionID) else { return } + allSessionRecencyIndex.remove(sessionID: sessionID) + activeSessionRecencyIndex.remove(sessionID: sessionID) stampVersion(&record) exitWatchers[sessionID]?.source.cancel() exitWatchers[sessionID] = nil diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptBoundedLineIterator.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptBoundedLineIterator.swift new file mode 100644 index 000000000000..8826517b006e --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptBoundedLineIterator.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Lazily decodes one bounded transcript line at a time. +struct AgentChatTranscriptBoundedLineIterator: IteratorProtocol { + let data: Data + let maximumLineCount: Int + var cursor: Data.Index + var emittedLineCount = 0 + + mutating func next() -> String? { + guard emittedLineCount < maximumLineCount, + cursor < data.endIndex else { + return nil + } + let start = cursor + while cursor < data.endIndex, data[cursor] != 0x0A { + cursor = data.index(after: cursor) + } + let end = cursor + if cursor < data.endIndex { + cursor = data.index(after: cursor) + } + emittedLineCount += 1 + return String(decoding: data[start.. AgentChatTranscriptBoundedLineIterator { + AgentChatTranscriptBoundedLineIterator( + data: data, + maximumLineCount: Swift.max(0, maximumLineCount), + cursor: data.startIndex + ) + } + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptIncrementalLineBuffer.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptIncrementalLineBuffer.swift new file mode 100644 index 000000000000..e4e22d4c9f40 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptIncrementalLineBuffer.swift @@ -0,0 +1,89 @@ +import Foundation + +/// Frames live transcript growth without retaining an unbounded JSONL record. +/// +/// Oversized records consume one sequence position and parsing resumes at the +/// next newline, preserving the absolute transcript line index for later rows. +struct AgentChatTranscriptIncrementalLineBuffer { + private let maximumLineBytes: Int + private(set) var pendingFragment = Data() + private(set) var discardsUntilNextNewline = false + + init(maximumLineBytes: Int) { + self.maximumLineBytes = max(1, maximumLineBytes) + } + + /// Replaces the retained fragment after initial backfill or rotation. + /// + /// - Returns: Whether the supplied fragment exceeded the live-line bound + /// and is now being discarded through its next newline. + @discardableResult + mutating func reset( + pendingFragment: Data = Data(), + discardsUntilNextNewline: Bool = false + ) -> Bool { + self.pendingFragment = Data() + if discardsUntilNextNewline || pendingFragment.count > maximumLineBytes { + self.discardsUntilNextNewline = true + return pendingFragment.count > maximumLineBytes + } + self.pendingFragment = pendingFragment + self.discardsUntilNextNewline = false + return false + } + + mutating func append(_ data: Data) -> ( + lines: [String], + discardedOversizedLine: Bool + ) { + guard !data.isEmpty else { + return (lines: [], discardedOversizedLine: false) + } + var lines: [String] = [] + var discardedOversizedLine = false + var cursor = data.startIndex + + while cursor < data.endIndex { + if discardsUntilNextNewline { + guard let newline = data[cursor...].firstIndex(of: 0x0A) else { + return (lines: lines, discardedOversizedLine: true) + } + lines.append("") + discardedOversizedLine = true + discardsUntilNextNewline = false + cursor = data.index(after: newline) + continue + } + + guard let newline = data[cursor...].firstIndex(of: 0x0A) else { + let suffix = data[cursor...] + if pendingFragment.count + suffix.count > maximumLineBytes { + pendingFragment = Data() + discardsUntilNextNewline = true + discardedOversizedLine = true + } else { + pendingFragment.append(contentsOf: suffix) + } + break + } + + let fragment = data[cursor.. maximumLineBytes { + lines.append("") + discardedOversizedLine = true + } else if pendingFragment.isEmpty { + lines.append(String(decoding: fragment, as: UTF8.self)) + } else { + pendingFragment.append(contentsOf: fragment) + lines.append(String(decoding: pendingFragment, as: UTF8.self)) + } + pendingFragment = Data() + cursor = data.index(after: newline) + } + + return ( + lines: lines, + discardedOversizedLine: discardedOversizedLine + ) + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailReader.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailReader.swift new file mode 100644 index 000000000000..c22203a9a27b --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailReader.swift @@ -0,0 +1,80 @@ +import Foundation + +/// Reads a fixed-size transcript suffix without mapping or scanning the file head. +struct AgentChatTranscriptInitialTailReader: Sendable { + static let defaultMaximumBytes = 4 * 1024 * 1024 + + func read(path: String, maximumBytes: Int) -> AgentChatTranscriptInitialTailSnapshot? { + guard maximumBytes > 0, + let handle = FileHandle(forReadingAtPath: path) else { + return nil + } + defer { try? handle.close() } + guard let fileSize = try? handle.seekToEnd() else { return nil } + let byteBudget = UInt64(maximumBytes) + let desiredStart = fileSize > byteBudget ? fileSize - byteBudget : 0 + let readStart = desiredStart > 0 ? desiredStart - 1 : 0 + let requestedCount = Int(min(fileSize - readStart, byteBudget + (desiredStart > 0 ? 1 : 0))) + guard (try? handle.seek(toOffset: readStart)) != nil, + let bytes = try? readBytes(handle: handle, count: requestedCount) else { + return nil + } + guard desiredStart > 0 else { + return AgentChatTranscriptInitialTailSnapshot( + data: bytes, + fileSize: fileSize, + retainedStartOffset: 0, + headTruncated: false, + discardsUntilNextNewline: false + ) + } + guard let guardByte = bytes.first else { + return AgentChatTranscriptInitialTailSnapshot( + data: Data(), + fileSize: fileSize, + retainedStartOffset: fileSize, + headTruncated: true, + discardsUntilNextNewline: true + ) + } + if guardByte == 0x0A { + return AgentChatTranscriptInitialTailSnapshot( + data: Data(bytes.dropFirst()), + fileSize: fileSize, + retainedStartOffset: desiredStart, + headTruncated: true, + discardsUntilNextNewline: false + ) + } + guard let boundary = bytes.dropFirst().firstIndex(of: 0x0A) else { + return AgentChatTranscriptInitialTailSnapshot( + data: Data(), + fileSize: fileSize, + retainedStartOffset: fileSize, + headTruncated: true, + discardsUntilNextNewline: true + ) + } + let retainedStart = bytes.index(after: boundary) + return AgentChatTranscriptInitialTailSnapshot( + data: Data(bytes[retainedStart...]), + fileSize: fileSize, + retainedStartOffset: readStart + UInt64(retainedStart), + headTruncated: true, + discardsUntilNextNewline: false + ) + } + + private func readBytes(handle: FileHandle, count: Int) throws -> Data { + var bytes = Data() + bytes.reserveCapacity(count) + while bytes.count < count { + guard let chunk = try handle.read(upToCount: count - bytes.count), + !chunk.isEmpty else { + break + } + bytes.append(chunk) + } + return bytes + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailSnapshot.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailSnapshot.swift new file mode 100644 index 000000000000..2106dca3449d --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptInitialTailSnapshot.swift @@ -0,0 +1,10 @@ +import Foundation + +/// Immutable result of one bounded transcript-tail read. +struct AgentChatTranscriptInitialTailSnapshot: Sendable { + let data: Data + let fileSize: UInt64 + let retainedStartOffset: UInt64 + let headTruncated: Bool + let discardsUntilNextNewline: Bool +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptReader.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptReader.swift new file mode 100644 index 000000000000..832add559adf --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptReader.swift @@ -0,0 +1,113 @@ +import CryptoKit +import Foundation + +/// Reads a newline-aligned transcript suffix without retaining the discarded prefix. +struct AgentChatTranscriptReader { + private static let chunkSize = 64 * 1024 + /// Maximum number of transcript records retained for one artifact index. + static let maximumRetainedLineCount = 16_384 + + func read( + handle: FileHandle, + fileSize: UInt64, + maximumBytes: UInt64 + ) throws -> AgentChatTranscriptSlice { + let retainedByteCount = min(fileSize, max(1, maximumBytes)) + let requestedStart = fileSize - retainedByteCount + + let startsAtLineBoundary: Bool + if requestedStart == 0 { + startsAtLineBoundary = true + } else { + try handle.seek(toOffset: requestedStart - 1) + startsAtLineBoundary = try handle.read(upToCount: 1)?.first == 0x0A + } + try handle.seek(toOffset: requestedStart) + var data = try read(handle: handle, byteCount: retainedByteCount) + var alignedStart = requestedStart + if !startsAtLineBoundary, let newline = data.firstIndex(of: 0x0A) { + let removedByteCount = data.distance(from: data.startIndex, to: newline) + 1 + data.removeSubrange(data.startIndex...newline) + alignedStart += UInt64(removedByteCount) + } + let relativeLineStarts = try retainedLineStartOffsets(data: data) + let trimmedPrefixCount = relativeLineStarts.first ?? 0 + if trimmedPrefixCount > 0 { + let trimmedPrefixEnd = data.index(data.startIndex, offsetBy: trimmedPrefixCount) + data.removeSubrange(data.startIndex.. Data { + Data(SHA256.hash(data: data)) + } + + func matchesContent( + handle: FileHandle, + startOffset: UInt64, + byteCount: UInt64, + expectedDigest: Data + ) throws -> Bool { + try handle.seek(toOffset: startOffset) + var hasher = SHA256() + var remaining = byteCount + while remaining > 0 { + try Task.checkCancellation() + let requested = Int(min(remaining, UInt64(Self.chunkSize))) + guard let chunk = try handle.read(upToCount: requested), !chunk.isEmpty else { + return false + } + hasher.update(data: chunk) + remaining -= UInt64(chunk.count) + } + return Data(hasher.finalize()) == expectedDigest + } + + private func retainedLineStartOffsets(data: Data) throws -> [Int] { + let limit = Self.maximumRetainedLineCount + var ring = [Int](repeating: 0, count: limit) + var retainedCount = 1 + var totalCount = 1 + var nextInsertionIndex = 1 + var cancellationCountdown = Self.chunkSize + for (index, byte) in data.enumerated() { + cancellationCountdown -= 1 + if cancellationCountdown == 0 { + try Task.checkCancellation() + cancellationCountdown = Self.chunkSize + } + guard byte == 0x0A else { continue } + ring[nextInsertionIndex] = index + 1 + nextInsertionIndex = (nextInsertionIndex + 1) % limit + totalCount += 1 + retainedCount = min(totalCount, limit) + } + let firstIndex = totalCount > limit ? nextInsertionIndex : 0 + var offsets: [Int] = [] + offsets.reserveCapacity(retainedCount) + for index in 0.. Data { + var data = Data() + data.reserveCapacity(Int(byteCount)) + var remaining = byteCount + while remaining > 0 { + try Task.checkCancellation() + let requested = Int(min(remaining, UInt64(Self.chunkSize))) + let chunk = try handle.read(upToCount: requested) ?? Data() + guard !chunk.isEmpty else { break } + data.append(chunk) + remaining -= UInt64(chunk.count) + } + return data + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptResolver.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptResolver.swift index 7bb915a78834..405994226415 100644 --- a/Sources/Mobile/AgentChat/AgentChatTranscriptResolver.swift +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptResolver.swift @@ -12,6 +12,8 @@ struct AgentChatTranscriptResolver: Sendable { private let claudeConfigRoot: URL /// Config-dir root for Codex (`$CODEX_HOME` or `~/.codex`). private let codexConfigRoot: URL + /// Maximum directory entries visited by a Codex fallback scan. + private let maximumCodexFallbackEntries: Int /// Creates a resolver. /// @@ -27,9 +29,12 @@ struct AgentChatTranscriptResolver: Sendable { /// - homeDirectory: Injectable home directory for tests. /// - environment: Injectable environment for tests; defaults to the /// process environment. Empty/whitespace override values are ignored. + /// - maximumCodexFallbackEntries: Maximum entries visited by a Codex + /// sessions-tree fallback before returning no match. init( homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, - environment: [String: String] = ProcessInfo.processInfo.environment + environment: [String: String] = ProcessInfo.processInfo.environment, + maximumCodexFallbackEntries: Int = 20_000 ) { self.homeDirectory = homeDirectory self.claudeConfigRoot = Self.configRoot( @@ -40,6 +45,7 @@ struct AgentChatTranscriptResolver: Sendable { override: environment["CODEX_HOME"], default: homeDirectory.appendingPathComponent(".codex", isDirectory: true) ) + self.maximumCodexFallbackEntries = max(0, maximumCodexFallbackEntries) } /// Resolves a config-dir root from an env override, expanding a leading `~`, @@ -54,14 +60,31 @@ struct AgentChatTranscriptResolver: Sendable { /// Resolves the transcript path for a session. /// - /// - Parameters: - /// - record: The session's registry record. - /// - deadline: Optional deadline for recursive fallback enumeration. + /// - Parameter record: The session's registry record. /// - Returns: An existing transcript path, or `nil` when none is found. + /// - Throws: ``CancellationError`` when the calling task is canceled. + func transcriptPath(for record: AgentChatSessionRecord) throws -> String? { + try transcriptPathThrowing(for: record, deadline: nil) + } + + /// Resolves a transcript path for the bounded fallback coordinator. + /// Cancellation and deadline expiry are reported as no result so the + /// coordinator can discard an abandoned attempt without caching failure. func transcriptPath( for record: AgentChatSessionRecord, - deadline: ContinuousClock.Instant? = nil + deadline: ContinuousClock.Instant? ) -> String? { + try? transcriptPathThrowing(for: record, deadline: deadline) + } + + private func transcriptPathThrowing( + for record: AgentChatSessionRecord, + deadline: ContinuousClock.Instant? + ) throws -> String? { + try Task.checkCancellation() + if let deadline, ContinuousClock.now >= deadline { + return nil + } if let recorded = recordedTranscriptPath(for: record) { return recorded } @@ -69,7 +92,7 @@ struct AgentChatTranscriptResolver: Sendable { case .claude: return claudeFallbackPath(record: record) case .codex: - return codexFallbackPath(sessionID: record.sessionID, deadline: deadline) + return try codexFallbackPath(sessionID: record.sessionID, deadline: deadline) case .other: return nil } @@ -115,8 +138,8 @@ struct AgentChatTranscriptResolver: Sendable { private func codexFallbackPath( sessionID: String, deadline: ContinuousClock.Instant? - ) -> String? { - guard !Task.isCancelled else { return nil } + ) throws -> String? { + try Task.checkCancellation() if let deadline, ContinuousClock.now >= deadline { return nil } @@ -129,11 +152,14 @@ struct AgentChatTranscriptResolver: Sendable { options: [.skipsHiddenFiles] ) else { return nil } let needle = sessionID.lowercased() + var visitedEntryCount = 0 for case let url as URL in enumerator { - guard !Task.isCancelled else { return nil } + try Task.checkCancellation() if let deadline, ContinuousClock.now >= deadline { return nil } + guard visitedEntryCount < maximumCodexFallbackEntries else { return nil } + visitedEntryCount += 1 guard url.pathExtension == "jsonl" else { continue } if url.lastPathComponent.lowercased().contains(needle) { return url.path diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptService+ArtifactCapture.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptService+ArtifactCapture.swift new file mode 100644 index 000000000000..0561fa10221c --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptService+ArtifactCapture.swift @@ -0,0 +1,431 @@ +import CmuxAgentChat +import CmuxArtifacts +import Foundation + +extension AgentChatTranscriptService { + /// Maximum historical sessions scheduled by one startup recovery pass. + /// The registry may contain arbitrarily old hook-store records, so startup + /// work is bounded to the most recently active sessions; live hook events + /// continue to schedule older sessions on demand. + private static let maximumInitialArtifactCaptureSessions = 64 + + /// Whether automatic capture needs live transcript completion events without mobile clients. + var observesTranscriptsForAutomaticArtifactCapture: Bool { + artifactCaptureCoordinator != nil && isAutomaticArtifactCaptureEnabled() + } + + /// Starts eager observation with the strongest resolution its active consumer requires. + func ensureTailerForEagerObservation(for record: AgentChatSessionRecord) { + let hasSubscribers = hasEventSubscribers() + guard hasSubscribers || observesTranscriptsForAutomaticArtifactCapture else { return } + ensureTailer( + for: record, + // A global chat.message subscriber does not identify this session; + // keep eager observation in the bounded pool. Explicit history + // requests promote only the requested session below. + ownership: .automaticArtifactCapture, + resolvePath: { resolver.boundedTranscriptPath(for: record) } + ) + } + + /// Reconciles transcript ownership after the Artifacts beta setting changes. + func reconcileAutomaticArtifactCaptureAvailability() { + let isEnabled = artifactCaptureCoordinator != nil && isAutomaticArtifactCaptureEnabled() + guard automaticArtifactCaptureWasEnabled != isEnabled else { + reconcileTranscriptTailerOwnership() + return + } + automaticArtifactCaptureWasEnabled = isEnabled + + if isEnabled { + for record in registry.recentSessions( + workspaceID: nil, + limit: Self.maxArtifactOnlyTailers, + excludingEnded: true + ) { + ensureTailerForEagerObservation(for: record) + } + scheduleInitialArtifactCaptures() + reconcileTranscriptTailerOwnership() + return + } + + let captureTasks = artifactCaptureTasks.values.compactMap(\.task) + artifactCaptureTasks.removeAll() + captureTasks.forEach { $0.cancel() } + artifactCaptureDebounceTasks.values.forEach { $0.task.cancel() } + artifactCaptureDebounceTasks.removeAll() + reconcileTranscriptTailerOwnership() + } + + /// Schedules one bounded capture pass for transcripts already present when + /// automatic capture starts or is enabled. Live tailer events continue to + /// drive later revisions; the initial pass covers turns completed offline. + func scheduleInitialArtifactCaptures() { + guard observesTranscriptsForAutomaticArtifactCapture else { return } + for record in registry.recentSessions( + workspaceID: nil, + limit: Self.maximumInitialArtifactCaptureSessions + ) { + scheduleArtifactCapture(for: record) + } + } + + /// Records the strongest current consumer for a tailer and refreshes its + /// artifact-only recency when automatic capture owns it. + func noteTailerUse( + sessionID: String, + ownership: AgentChatTranscriptTailerOwnership + ) { + guard tailers[sessionID] != nil else { return } + switch ownership { + case .mobileSubscriber: + tailerOwnership[sessionID] = .mobileSubscriber + artifactTailerLastUse.removeValue(forKey: sessionID) + artifactTailerUseCounter &+= 1 + mobileTailerLastUse[sessionID] = artifactTailerUseCounter + enforceMobileTailerLimit(protectedSessionID: sessionID) + case .automaticArtifactCapture: + guard tailerOwnership[sessionID] != .mobileSubscriber else { return } + tailerOwnership[sessionID] = .automaticArtifactCapture + mobileTailerLastUse.removeValue(forKey: sessionID) + artifactTailerUseCounter &+= 1 + artifactTailerLastUse[sessionID] = artifactTailerUseCounter + } + } + + /// Stops and forgets one tailer, including its ownership and LRU entry. + func removeTailer(sessionID: String) { + tailerOwnership.removeValue(forKey: sessionID) + artifactTailerLastUse.removeValue(forKey: sessionID) + mobileTailerLastUse.removeValue(forKey: sessionID) + tailerGenerationBySessionID.removeValue(forKey: sessionID) + guard let tailer = tailers.removeValue(forKey: sessionID) else { return } + Task { await tailer.stop() } + } + + /// Evicts the least recently used artifact-only tailers until the bounded + /// policy is satisfied. A newly requested session is protected so a full + /// cap never immediately evicts the work that caused the insertion. + func enforceArtifactTailerLimit(protectedSessionID: String? = nil) { + while artifactTailerLastUse.count > Self.maxArtifactOnlyTailers { + guard let victim = artifactTailerLastUse + .filter({ $0.key != protectedSessionID }) + .min(by: { lhs, rhs in + if lhs.value == rhs.value { return lhs.key < rhs.key } + return lhs.value < rhs.value + })?.key else { + return + } + removeTailer(sessionID: victim) + } + } + + /// Evicts least-recently-used explicitly opened mobile histories so one + /// long-lived phone cannot retain an unbounded watcher/message cache set. + func enforceMobileTailerLimit(protectedSessionID: String? = nil) { + while mobileTailerLastUse.count > Self.maxMobileSubscriberTailers { + guard let victim = mobileTailerLastUse + .filter({ $0.key != protectedSessionID }) + .min(by: { lhs, rhs in + if lhs.value == rhs.value { return lhs.key < rhs.key } + return lhs.value < rhs.value + })?.key else { + return + } + removeTailer(sessionID: victim) + } + } + + /// Reconciles tailer ownership when subscriber demand changes outside a + /// hook event. This releases subscriber-only state when neither consumer + /// needs it and demotes it into the bounded artifact pool when capture is + /// still enabled. + func reconcileTranscriptTailerOwnership() { + let hasSubscribers = hasEventSubscribers() + if hasSubscribers { + // Presence is global to the topic, not scoped to every session. + // Do not promote the entire tailer inventory just because one + // phone is connected; explicit history requests own their session. + enforceArtifactTailerLimit() + enforceMobileTailerLimit() + return + } + + if observesTranscriptsForAutomaticArtifactCapture { + for sessionID in tailers.keys { + if tailerOwnership[sessionID] == .mobileSubscriber { + tailerOwnership[sessionID] = nil + mobileTailerLastUse.removeValue(forKey: sessionID) + } + noteTailerUse(sessionID: sessionID, ownership: .automaticArtifactCapture) + } + enforceArtifactTailerLimit() + } else { + for sessionID in Array(tailers.keys) { + guard tailerOwnership[sessionID] != .mobileSubscriber else { continue } + removeTailer(sessionID: sessionID) + } + enforceMobileTailerLimit() + } + } + + /// Captures one authoritative transcript generation after an agent turn. + func scheduleArtifactCapture(for record: AgentChatSessionRecord) { + cancelDebouncedArtifactCapture(sessionID: record.sessionID) + guard let artifactCaptureCoordinator, isAutomaticArtifactCaptureEnabled() else { return } + let resolver = self.resolver + let artifactIndex = self.artifactIndex + let isAutomaticArtifactCaptureEnabled = self.isAutomaticArtifactCaptureEnabled + replaceArtifactCaptureTask(sessionID: record.sessionID) { [weak self] in + guard !Task.isCancelled, await isAutomaticArtifactCaptureEnabled() else { return } + guard let transcriptPath = resolver.boundedTranscriptPath(for: record) else { return } + guard !Task.isCancelled else { return } + guard let maximumFileBytes = await artifactCaptureCoordinator.maximumTranscriptScanBytes( + for: record + ) else { + return + } + guard let snapshot = try? await artifactIndex.snapshot( + sessionID: record.sessionID, + agentKind: record.agentKind, + transcriptPath: transcriptPath, + workingDirectory: record.workingDirectory, + maximumFileBytes: maximumFileBytes + ) else { + return + } + guard !Task.isCancelled, await isAutomaticArtifactCaptureEnabled() else { return } + let progress = await artifactCaptureCoordinator.capture(record: record, snapshot: snapshot) + await self?.scheduleIndexedArtifactCaptureContinuation( + progress: progress, + record: record, + snapshot: snapshot, + coordinator: artifactCaptureCoordinator, + isEnabled: isAutomaticArtifactCaptureEnabled, + contentionRetryAttempt: 0 + ) + } + } + + /// Coalesces streamed prose batches until the transcript has been quiet. + /// + /// Transcript tailers emit each streamed prose line independently, but a + /// full artifact-index snapshot is bounded by bytes rather than lines. + /// Waiting for a short quiet period keeps sustained output from repeatedly + /// reparsing the same large transcript while still capturing turns that do + /// not produce a Stop hook. + func scheduleDebouncedArtifactCapture(for record: AgentChatSessionRecord) { + guard artifactCaptureCoordinator != nil, + isAutomaticArtifactCaptureEnabled() else { + return + } + let sessionID = record.sessionID + artifactCaptureDebounceTasks[sessionID]?.task.cancel() + let token = UUID() + let clock = artifactCaptureDebounceClock + let task = Task { [weak self] in + do { + try await clock.sleep(for: Self.artifactCaptureDebounceDelay) + } catch { + return + } + guard !Task.isCancelled, let self else { return } + guard self.artifactCaptureDebounceTasks[sessionID]?.token == token else { + return + } + self.artifactCaptureDebounceTasks.removeValue(forKey: sessionID) + guard let currentRecord = self.registry.record(sessionID: sessionID), + currentRecord.state != .ended, + self.isAutomaticArtifactCaptureEnabled() else { + return + } + self.scheduleArtifactCapture(for: currentRecord) + } + artifactCaptureDebounceTasks[sessionID] = (token: token, task: task) + } + + /// Cancels a pending prose debounce when an immediate lifecycle event wins. + func cancelDebouncedArtifactCapture(sessionID: String) { + artifactCaptureDebounceTasks.removeValue(forKey: sessionID)?.task.cancel() + } + + /// Reuses an already-indexed gallery snapshot without parsing the transcript again. + func scheduleIndexedArtifactCapture( + record: AgentChatSessionRecord, + snapshot: AgentChatArtifactIndex.Snapshot + ) { + guard let artifactCaptureCoordinator, isAutomaticArtifactCaptureEnabled() else { return } + let isAutomaticArtifactCaptureEnabled = self.isAutomaticArtifactCaptureEnabled + replaceArtifactCaptureTask( + sessionID: record.sessionID, + operation: indexedArtifactCaptureOperation( + record: record, + snapshot: snapshot, + coordinator: artifactCaptureCoordinator, + isEnabled: isAutomaticArtifactCaptureEnabled + ) + ) + } + + private func indexedArtifactCaptureOperation( + record: AgentChatSessionRecord, + snapshot: AgentChatArtifactIndex.Snapshot, + coordinator: AgentArtifactCaptureCoordinator, + isEnabled: @escaping @MainActor @Sendable () -> Bool, + contentionRetryAttempt: Int = 0 + ) -> @Sendable () async -> Void { + { [weak self] in + guard !Task.isCancelled, await isEnabled() else { return } + let progress = await coordinator.capture(record: record, snapshot: snapshot) + await self?.scheduleIndexedArtifactCaptureContinuation( + progress: progress, + record: record, + snapshot: snapshot, + coordinator: coordinator, + isEnabled: isEnabled, + contentionRetryAttempt: contentionRetryAttempt + ) + } + } + + private func scheduleIndexedArtifactCaptureContinuation( + progress: AgentArtifactCaptureProgress, + record: AgentChatSessionRecord, + snapshot: AgentChatArtifactIndex.Snapshot, + coordinator: AgentArtifactCaptureCoordinator, + isEnabled: @escaping @MainActor @Sendable () -> Bool, + contentionRetryAttempt: Int + ) async { + guard !Task.isCancelled, isEnabled() else { return } + let nextContentionRetryAttempt: Int + switch progress { + case .needsContinuation: + nextContentionRetryAttempt = 0 + case .retryableContention: + guard await coordinator.waitForContentionRetry( + afterAttempt: contentionRetryAttempt + ), !Task.isCancelled, isEnabled() else { + return + } + nextContentionRetryAttempt = contentionRetryAttempt + 1 + case .complete, .blocked: + return + } + enqueueIndexedArtifactCaptureContinuation( + record: record, + snapshot: snapshot, + coordinator: coordinator, + isEnabled: isEnabled, + contentionRetryAttempt: nextContentionRetryAttempt + ) + } + + private func enqueueIndexedArtifactCaptureContinuation( + record: AgentChatSessionRecord, + snapshot: AgentChatArtifactIndex.Snapshot, + coordinator: AgentArtifactCaptureCoordinator, + isEnabled: @escaping @MainActor @Sendable () -> Bool, + contentionRetryAttempt: Int + ) { + guard isAutomaticArtifactCaptureEnabled(), + var active = artifactCaptureTasks[record.sessionID], + active.pending == nil else { + return + } + active.pending = indexedArtifactCaptureOperation( + record: record, + snapshot: snapshot, + coordinator: coordinator, + isEnabled: isEnabled, + contentionRetryAttempt: contentionRetryAttempt + ) + artifactCaptureTasks[record.sessionID] = active + } + + func saveArtifact( + context: ArtifactCaptureContext, + sourceURL: URL, + expectedCanonicalPath: String, + expectedIdentity: ChatArtifactFileIdentity + ) async throws -> ChatArtifactSaveResult { + guard let artifactCaptureCoordinator else { + throw AgentArtifactCaptureSaveError.rejected + } + return try await artifactCaptureCoordinator.save( + context: context, + sourceURL: sourceURL, + expectedCanonicalPath: expectedCanonicalPath, + expectedIdentity: expectedIdentity + ) + } + + func artifactCaptureContext(for record: AgentChatSessionRecord) async -> ArtifactCaptureContext? { + guard let artifactCaptureCoordinator else { return nil } + return await artifactCaptureCoordinator.captureContext(for: record) + } + + /// Cancels obsolete work and serializes coordinator cleanup before session reuse. + func removeArtifactCaptureSession(sessionID: String) { + cancelDebouncedArtifactCapture(sessionID: sessionID) + artifactCaptureTasks.removeValue(forKey: sessionID)?.task?.cancel() + guard let artifactCaptureCoordinator else { return } + replaceArtifactCaptureTask(sessionID: sessionID) { + await artifactCaptureCoordinator.removeSession(sessionID: sessionID) + } + } + + private func replaceArtifactCaptureTask( + sessionID: String, + operation: @escaping @Sendable () async -> Void + ) { + if var active = artifactCaptureTasks[sessionID] { + active.pending = operation + artifactCaptureTasks[sessionID] = active + return + } + let token = UUID() + artifactCaptureTasks[sessionID] = (token: token, task: nil, pending: nil) + let task = Task.detached(priority: .utility) { [weak self] in + var current: (@Sendable () async -> Void)? = operation + while let operation = current, !Task.isCancelled { + await operation() + guard !Task.isCancelled else { break } + current = await self?.takeNextArtifactCaptureOperation( + sessionID: sessionID, + token: token + ) + } + if Task.isCancelled { + await self?.finishArtifactCaptureTask(sessionID: sessionID, token: token) + } + } + if var entry = artifactCaptureTasks[sessionID], entry.token == token { + entry.task = task + artifactCaptureTasks[sessionID] = entry + } else { + task.cancel() + } + } + + private func finishArtifactCaptureTask(sessionID: String, token: UUID) { + guard artifactCaptureTasks[sessionID]?.token == token else { return } + artifactCaptureTasks.removeValue(forKey: sessionID) + } + + private func takeNextArtifactCaptureOperation( + sessionID: String, + token: UUID + ) -> (@Sendable () async -> Void)? { + guard var active = artifactCaptureTasks[sessionID], active.token == token else { + return nil + } + guard let pending = active.pending else { + artifactCaptureTasks.removeValue(forKey: sessionID) + return nil + } + active.pending = nil + artifactCaptureTasks[sessionID] = active + return pending + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptService+Resolution.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptService+Resolution.swift new file mode 100644 index 000000000000..dbfc0c7fd9a0 --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptService+Resolution.swift @@ -0,0 +1,63 @@ +import Foundation + +extension AgentChatTranscriptService { + /// Resolves one session transcript off the main actor and persists a successful fallback. + func resolvedTranscript( + sessionID: String + ) async throws -> (record: AgentChatSessionRecord, path: String)? { + guard var candidate = registry.record(sessionID: sessionID) else { return nil } + let resolver = self.resolver + + for _ in 0..<2 { + let resolutionRecord = candidate + let candidateTranscriptPath = candidate.transcriptPath + let candidateAgentKind = candidate.agentKind + let candidateWorkspaceID = candidate.workspaceID + let candidateSurfaceID = candidate.surfaceID + let candidateWorkingDirectory = candidate.workingDirectory + let candidateHookStoreSessionID = candidate.hookStoreLookupSessionID + let resolvedPath: String? + if let boundedPath = resolver.boundedTranscriptPath(for: resolutionRecord) { + resolvedPath = boundedPath + } else { + resolvedPath = await fallbackResolutionCoordinator.resolve(for: resolutionRecord) + } + guard let resolvedPath, + let current = registry.record(sessionID: sessionID) else { + return nil + } + guard current.transcriptPath == candidateTranscriptPath, + current.agentKind == candidateAgentKind, + current.workspaceID == candidateWorkspaceID, + current.surfaceID == candidateSurfaceID, + current.workingDirectory == candidateWorkingDirectory, + current.hookStoreLookupSessionID == candidateHookStoreSessionID else { + candidate = current + continue + } + if current.transcriptPath != resolvedPath { + registry.update(sessionID: sessionID) { $0.transcriptPath = resolvedPath } + } + guard let persisted = registry.record(sessionID: sessionID) else { return nil } + return (persisted, resolvedPath) + } + return nil + } + + /// Retries user-requested history resolution without caching cancellation as a miss. + func resolvedTranscriptRecordForHistory(sessionID: String) async -> AgentChatSessionRecord? { + failedResolutions.remove(sessionID) + do { + guard let resolved = try await resolvedTranscript(sessionID: sessionID) else { + failedResolutions.insert(sessionID) + return nil + } + return resolved.record + } catch is CancellationError { + return nil + } catch { + failedResolutions.insert(sessionID) + return nil + } + } +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptService.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptService.swift index 03a5b5638ca5..21173f4d21a2 100644 --- a/Sources/Mobile/AgentChat/AgentChatTranscriptService.swift +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptService.swift @@ -101,6 +101,11 @@ private final class AgentChatProseStreamWakeDriver { } } +enum AgentChatTranscriptTailerOwnership: Sendable, Equatable { + case mobileSubscriber + case automaticArtifactCapture +} + /// Mac-side facade for the agent chat surface: tracks sessions from hook /// events, tails their transcripts, serves history pages, and pushes /// `chat.message` events to subscribed mobile clients. @@ -108,12 +113,47 @@ private final class AgentChatProseStreamWakeDriver { final class AgentChatTranscriptService { /// The push topic chat clients subscribe to. static let eventTopic = "chat.message" + /// Maximum number of transcript tailers retained solely for automatic + /// artifact capture. Mobile-owned tailers are demand-driven and are not + /// counted against this cap. + static let maxArtifactOnlyTailers = 32 + /// Explicitly opened mobile histories retain a larger but still bounded + /// watcher/cache pool until demand can be represented per session. + static let maxMobileSubscriberTailers = 64 + /// Quiet period used to coalesce transcript prose batches before parsing + /// the full bounded transcript for automatic capture. + static let artifactCaptureDebounceDelay: Duration = .milliseconds(350) nonisolated private static let proseStreamingSnapshotMaxRows = 240 let registry: AgentChatSessionRegistry let resolver: AgentChatTranscriptResolver - private var tailers: [String: AgentChatTranscriptTailer] = [:] - private let hasEventSubscribers: @MainActor () -> Bool + let artifactIndex: AgentChatArtifactIndex + let artifactGalleryOrderingCache: ChatArtifactGalleryOrderingCache + let artifactGalleryRowCountCache: ChatArtifactGalleryRowCountCache + let artifactCaptureCoordinator: AgentArtifactCaptureCoordinator? + let isAutomaticArtifactCaptureEnabled: @MainActor @Sendable () -> Bool + var automaticArtifactCaptureWasEnabled: Bool + var artifactCaptureTasks: [String: ( + token: UUID, + task: Task?, + pending: (@Sendable () async -> Void)? + )] = [:] + var tailers: [String: AgentChatTranscriptTailer] = [:] + /// Token for the tailer currently authoritative for each session. A + /// retired actor may finish an in-flight callback after stop(); its token + /// keeps that batch from reaching the replacement/session state. + var tailerGenerationBySessionID: [String: UUID] = [:] + var tailerOwnership: [String: AgentChatTranscriptTailerOwnership] = [:] + var artifactTailerLastUse: [String: UInt64] = [:] + var mobileTailerLastUse: [String: UInt64] = [:] + var artifactCaptureDebounceTasks: [String: ( + token: UUID, + task: Task + )] = [:] + var artifactTailerUseCounter: UInt64 = 0 + let artifactCaptureDebounceClock: any Clock + private var eventSubscriptionObserver: NSObjectProtocol? + let hasEventSubscribers: @MainActor () -> Bool private let emitEventPayload: @MainActor ([String: Any]) -> Void private let now: () -> Date /// Drives the live agent-prose streaming preview. @@ -129,8 +169,8 @@ final class AgentChatTranscriptService { /// Sessions whose transcript could not be resolved cheaply; skipped until /// authoritative bindings arrive or an explicit history request retries. /// Hook delivery never runs Codex's recursive fallback scan. - private var failedResolutions: Set = [] - private let fallbackResolutionCoordinator: AgentChatFallbackTranscriptResolutionCoordinator + var failedResolutions: Set = [] + let fallbackResolutionCoordinator: AgentChatFallbackTranscriptResolutionCoordinator private var endedListability = AgentChatEndedTranscriptListabilityCache() private struct ProseTurnState { @@ -160,6 +200,12 @@ final class AgentChatTranscriptService { emitEventPayload: @escaping @MainActor ([String: Any]) -> Void = { payload in MobileHostService.emitEvent(topic: AgentChatTranscriptService.eventTopic, payload: payload) }, + artifactIndex: AgentChatArtifactIndex = AgentChatArtifactIndex(), + artifactGalleryOrderingCache: ChatArtifactGalleryOrderingCache = ChatArtifactGalleryOrderingCache(), + artifactGalleryRowCountCache: ChatArtifactGalleryRowCountCache = ChatArtifactGalleryRowCountCache(maximumAge: 2), + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator? = nil, + isAutomaticArtifactCaptureEnabled: @escaping @MainActor @Sendable () -> Bool = { true }, + artifactCaptureDebounceClock: any Clock = ContinuousClock(), now: @escaping () -> Date = { Date() }, fallbackTranscriptPathResolver: AgentChatFallbackTranscriptResolutionCoordinator.Resolver? = nil, fallbackResolutionTimeout: Duration = .seconds(3) @@ -168,6 +214,13 @@ final class AgentChatTranscriptService { self.resolver = resolver self.hasEventSubscribers = hasEventSubscribers self.emitEventPayload = emitEventPayload + self.artifactIndex = artifactIndex + self.artifactGalleryOrderingCache = artifactGalleryOrderingCache + self.artifactGalleryRowCountCache = artifactGalleryRowCountCache + self.artifactCaptureCoordinator = artifactCaptureCoordinator + self.isAutomaticArtifactCaptureEnabled = isAutomaticArtifactCaptureEnabled + self.artifactCaptureDebounceClock = artifactCaptureDebounceClock + self.automaticArtifactCaptureWasEnabled = artifactCaptureCoordinator != nil && isAutomaticArtifactCaptureEnabled() self.now = now self.fallbackResolutionCoordinator = AgentChatFallbackTranscriptResolutionCoordinator( transcriptResolver: resolver, @@ -191,6 +244,15 @@ final class AgentChatTranscriptService { hasSubscribers: { [weak self] in self?.hasEventSubscribers() ?? false } ) self.proseWakeDriver.start() + self.eventSubscriptionObserver = NotificationCenter.default.addObserver( + forName: .mobileHostEventSubscriptionsDidChange, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.reconcileTranscriptTailerOwnership() + } + } } /// Rendered screen rows (top to bottom) for a surface, the source the prose @@ -216,9 +278,7 @@ final class AgentChatTranscriptService { return Array(rows.suffix(proseStreamingSnapshotMaxRows)) } - /// A `(session, surface)` resume re-bind cmux authored during session - /// restore, buffered until the service is live (restore can run before app - /// setup assigns this service, so a direct call would be a silent no-op). + /// A cmux-authored resume re-bind buffered until the service is live. private struct PendingResumeIntent { let sessionID: String let source: String @@ -290,8 +350,22 @@ final class AgentChatTranscriptService { } // Seeding reads+parses the hook-store JSON off the main actor; kick it // off and return. Live hook events also populate the registry, and the - // seed converges within milliseconds. - Task { [weak self] in await self?.registry.seedFromHookStores() } + // seed converges within milliseconds. Once seeded, schedule one + // bounded artifact-index pass for each existing transcript so a turn + // completed while cmux was closed is not lost. + Task { @MainActor [weak self] in + guard let self else { return } + await self.registry.seedFromHookStores() + for record in self.registry.recentSessions( + workspaceID: nil, + limit: Self.maxArtifactOnlyTailers, + excludingEnded: true + ) { + self.ensureTailerForEagerObservation(for: record) + } + self.scheduleInitialArtifactCaptures() + self.reconcileTranscriptTailerOwnership() + } } /// Ingests one hook event (called from the socket dispatch path). @@ -307,14 +381,11 @@ final class AgentChatTranscriptService { default: break } - // Tail eagerly only while someone is listening, and never for an - // ended session (its transcript can no longer grow; recreating the - // tailer here would undo the ended-state eviction). - if record.state != .ended, - hasEventSubscribers() { - ensureTailer(for: record) { - resolver.boundedTranscriptPath(for: record) - } + // Tail eagerly while chat delivery or automatic artifact capture needs + // transcript completion, and never for an ended session (its transcript + // can no longer grow; recreating the tailer would undo ended-state eviction). + if record.state != .ended { + ensureTailerForEagerObservation(for: record) } // Drive the live prose-streaming preview off the turn lifecycle: a // prompt starts the in-flight turn, Stop ends it. @@ -335,6 +406,7 @@ final class AgentChatTranscriptService { } case .stop, .sessionEnd: endProseTurn(sessionID: record.sessionID) + scheduleArtifactCapture(for: record) default: break } @@ -446,13 +518,6 @@ final class AgentChatTranscriptService { } /// Serves one history page, starting the session's tailer on demand. - /// - /// - Parameters: - /// - sessionID: The session to read. - /// - beforeSeq: Strict upper bound, or `nil` for the newest page. - /// - limit: Page size cap. - /// - Returns: The page, or `nil` when the session or transcript is - /// unknown. func history(sessionID: String, beforeSeq: Int?, limit: Int) async -> ChatHistoryPage? { guard let record = registry.record(sessionID: sessionID) else { return nil } // A user opening the chat is the right moment to retry a previously @@ -461,6 +526,10 @@ final class AgentChatTranscriptService { failedResolutions.remove(sessionID) let tailer: AgentChatTranscriptTailer if let existing = tailers[sessionID] { + noteTailerUse( + sessionID: sessionID, + ownership: .mobileSubscriber + ) tailer = existing } else { let resolver = resolver @@ -471,11 +540,16 @@ final class AgentChatTranscriptService { } else { fallbackPath = await fallbackResolutionCoordinator.resolve(for: record) } + guard !Task.isCancelled else { return nil } guard let currentRecord = registry.record(sessionID: sessionID) else { return nil } failedResolutions.remove(sessionID) - guard let resolvedTailer = ensureTailer(for: currentRecord, resolvePath: { - resolver.boundedTranscriptPath(for: currentRecord) ?? fallbackPath - }) else { + guard let resolvedTailer = ensureTailer( + for: currentRecord, + ownership: .mobileSubscriber, + resolvePath: { + resolver.boundedTranscriptPath(for: currentRecord) ?? fallbackPath + } + ) else { return nil } tailer = resolvedTailer @@ -513,16 +587,47 @@ final class AgentChatTranscriptService { // MARK: - Internals @discardableResult - private func ensureTailer( + func ensureTailer(for record: AgentChatSessionRecord) -> AgentChatTranscriptTailer? { + if let existing = tailers[record.sessionID] { + noteTailerUse( + sessionID: record.sessionID, + ownership: .mobileSubscriber + ) + return existing + } + guard !failedResolutions.contains(record.sessionID), + let boundedPath = resolver.boundedTranscriptPath(for: record) else { + // Eager observation must not cache a missing bounded path as a + // failed explicit-history lookup. A later hook can still provide it. + return nil + } + return ensureTailer( + for: record, + ownership: .mobileSubscriber + ) { boundedPath } + } + + @discardableResult + func ensureTailer( for record: AgentChatSessionRecord, + ownership: AgentChatTranscriptTailerOwnership, resolvePath: () -> String? ) -> AgentChatTranscriptTailer? { if let existing = tailers[record.sessionID] { + noteTailerUse(sessionID: record.sessionID, ownership: ownership) return existing } - guard !failedResolutions.contains(record.sessionID) else { return nil } + guard ownership == .automaticArtifactCapture + || !failedResolutions.contains(record.sessionID) else { return nil } guard let path = resolvePath() else { - failedResolutions.insert(record.sessionID) + if ownership == .mobileSubscriber { + failedResolutions.insert(record.sessionID) + } else { + // Eager observation may run before a provider creates its + // transcript. Do not turn that expected startup gap into a + // permanent failure; the next hook/flag reconciliation retries. + failedResolutions.remove(record.sessionID) + } #if DEBUG cmuxDebugLog( "agentChat.transcript.resolve session=\(record.sessionID.prefix(8)) " @@ -540,14 +645,23 @@ final class AgentChatTranscriptService { #endif let sessionID = record.sessionID let agentKind = record.agentKind + let tailerGeneration = UUID() let tailer = AgentChatTranscriptTailer( sessionID: sessionID, agentKind: agentKind, path: path ) { [weak self] batch in - await self?.publishBatch(batch, sessionID: sessionID) + await self?.publishBatch( + batch, + sessionID: sessionID, + tailerGeneration: tailerGeneration + ) } tailers[sessionID] = tailer + tailerGenerationBySessionID[sessionID] = tailerGeneration + noteTailerUse(sessionID: sessionID, ownership: ownership) + enforceArtifactTailerLimit(protectedSessionID: sessionID) + enforceMobileTailerLimit(protectedSessionID: sessionID) if record.transcriptPath != path { registry.update(sessionID: record.sessionID) { $0.transcriptPath = path } } @@ -555,7 +669,18 @@ final class AgentChatTranscriptService { return tailer } - private func publishBatch(_ batch: AgentChatTranscriptTailer.Batch, sessionID: String) { + func publishBatch( + _ batch: AgentChatTranscriptTailer.Batch, + sessionID: String, + tailerGeneration: UUID? = nil + ) { + if let tailerGeneration, + tailerGenerationBySessionID[sessionID] != tailerGeneration { + return + } + if tailerOwnership[sessionID] == .automaticArtifactCapture { + noteTailerUse(sessionID: sessionID, ownership: .automaticArtifactCapture) + } #if DEBUG cmuxDebugLog( "agentChat.transcript.batch session=\(sessionID.prefix(8)) " @@ -583,9 +708,19 @@ final class AgentChatTranscriptService { emit(frame: ChatSessionEventFrame(sessionID: sessionID, event: .updated(batch.updated))) } updateLatestTranscriptSeq(sessionID: sessionID, messages: batch.appended + batch.updated) - if let completedAt = Self.completedAssistantTurnTimestamp(in: batch.appended) { + let completedAt = Self.completedAssistantTurnTimestamp(in: batch.appended) + if let completedAt { registry.noteAssistantTurnCompleted(sessionID: sessionID, at: completedAt) } + let containsAuthorizedArtifactMutation = Self.batchContainsAuthorizedArtifactMutation( + batch.appended + batch.updated + ) + if completedAt != nil + || batch.didAuthorizeArtifactMutation + || containsAuthorizedArtifactMutation, + let completedRecord = registry.record(sessionID: sessionID) { + scheduleDebouncedArtifactCapture(for: completedRecord) + } } private static func batchContainsAgentProse(_ messages: [ChatMessage], matching turnState: ProseTurnState) -> Bool { @@ -623,6 +758,31 @@ final class AgentChatTranscriptService { return completedAt } + private static func batchContainsAuthorizedArtifactMutation( + _ messages: [ChatMessage] + ) -> Bool { + messages.contains { message in + guard message.role == .agent else { return false } + switch message.kind { + case .toolUse(let toolUse): + return toolUse.artifactMutationAuthorized == true + case .terminal(let terminal): + guard !terminal.isRunning, terminal.exitCode == 0 else { return false } + return !ShellArtifactMutationPathDetector() + .pathsAttributedToSuccessfulCommand(in: terminal.command) + .isEmpty + case .fileEdit: + // File-edit cards are emitted before their sidechain result; + // their visible path is only a reference until the result + // grants created provenance. + return false + case .prose, .thought, .permissionRequest, .question, + .status, .attachment, .unsupported: + return false + } + } + } + private func handleRecordChange(_ record: AgentChatSessionRecord, previous: AgentChatSessionRecord?) { let endedRecordIsListable: Bool if record.state == .ended { @@ -638,25 +798,23 @@ final class AgentChatTranscriptService { fallbackResolutionCoordinator.cancel(sessionID: record.sessionID) failedResolutions.remove(record.sessionID) } - if stateChanged, record.state == .ended { + if stateChanged, record.state == .ended, previous != nil { + scheduleArtifactCapture(for: record) fallbackResolutionCoordinator.cancel(sessionID: record.sessionID) // The transcript can no longer grow; stop any live preview loop so // an agent that exits without a Stop hook doesn't leak the poll task. endProseTurn(sessionID: record.sessionID) - if let tailer = tailers.removeValue(forKey: record.sessionID) { - // The transcript can no longer grow; release the file watcher - // and cache instead of holding them until app quit. Evicting - // only on the TRANSITION keeps unrelated record updates (title - // discovery while paging an ended session) from churning it. - Task { await tailer.stop() } - } + // The transcript can no longer grow; release the file watcher, + // cache, ownership, and LRU entry instead of holding them until + // app quit. Evicting only on the TRANSITION keeps unrelated record + // updates (title discovery while paging an ended session) from + // churning it. + removeTailer(sessionID: record.sessionID) } - guard hasEventSubscribers() else { return } if transcriptBecameAvailable, record.state != .ended { - ensureTailer(for: record) { - resolver.boundedTranscriptPath(for: record) - } + ensureTailerForEagerObservation(for: record) } + guard hasEventSubscribers() else { return } if record.state == .ended, !endedRecordIsListable { emit(frame: ChatSessionEventFrame(sessionID: record.sessionID, event: .sessionRemoved(version: record.version))) return @@ -675,10 +833,10 @@ final class AgentChatTranscriptService { private func handleRecordRemoval(_ record: AgentChatSessionRecord) { fallbackResolutionCoordinator.cancel(sessionID: record.sessionID) endProseTurn(sessionID: record.sessionID) + removeArtifactCaptureSession(sessionID: record.sessionID) + Task { await artifactGalleryOrderingCache.remove(indexID: record.sessionID) } latestTranscriptSeqBySessionID[record.sessionID] = nil - if let tailer = tailers.removeValue(forKey: record.sessionID) { - Task { await tailer.stop() } - } + removeTailer(sessionID: record.sessionID) failedResolutions.remove(record.sessionID) endedListability.remove(sessionID: record.sessionID) guard hasEventSubscribers() else { return } @@ -708,6 +866,13 @@ final class AgentChatTranscriptService { // `isolated deinit` still has Xcode compatibility constraints in cmux, // so keep teardown synchronous while asserting that owner invariant. MainActor.assumeIsolated { + if let eventSubscriptionObserver { + NotificationCenter.default.removeObserver(eventSubscriptionObserver) + } + artifactCaptureTasks.values.compactMap(\.task).forEach { $0.cancel() } + artifactCaptureTasks.removeAll() + artifactCaptureDebounceTasks.values.forEach { $0.task.cancel() } + artifactCaptureDebounceTasks.removeAll() proseWakeDriver?.stop() proseStreamer?.stopAll() } diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptSlice.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptSlice.swift new file mode 100644 index 000000000000..71d04ac5e43a --- /dev/null +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptSlice.swift @@ -0,0 +1,8 @@ +import Foundation + +/// A bounded transcript suffix with stable absolute byte positions for its lines. +struct AgentChatTranscriptSlice { + let data: Data + let lineStartOffsets: [UInt64] + let transcriptExtent: UInt64 +} diff --git a/Sources/Mobile/AgentChat/AgentChatTranscriptTailer.swift b/Sources/Mobile/AgentChat/AgentChatTranscriptTailer.swift index 632eaf8898e5..c3769e514ad6 100644 --- a/Sources/Mobile/AgentChat/AgentChatTranscriptTailer.swift +++ b/Sources/Mobile/AgentChat/AgentChatTranscriptTailer.swift @@ -6,9 +6,9 @@ import Foundation /// incremental parsing on file growth, an in-memory message cache for /// history paging, and append/update batches for live push. /// -/// Seq stability: `seq` equals the absolute transcript line index. The -/// initial backfill may skip a long head (bounded memory), in which case -/// pages before the cache report `hasMore` honestly. +/// Seq stability: complete reads use the absolute transcript line index. A +/// byte-truncated initial backfill derives a monotonic base from its file +/// offset. Pages before the retained suffix report `hasMore` honestly. actor AgentChatTranscriptTailer { /// A live transcript change: newly appended messages and in-place /// updates (tool results that completed earlier messages). @@ -22,6 +22,9 @@ actor AgentChatTranscriptTailer { /// The transcript was truncated/replaced and the seq space /// restarted; clients must re-anchor. var didReset = false + /// A tool result positively authorized an artifact mutation even when + /// no visible chat row was emitted for the sidechain. + var didAuthorizeArtifactMutation = false } private let sessionID: String @@ -30,7 +33,9 @@ actor AgentChatTranscriptTailer { private let onBatch: @Sendable (Batch) async -> Void private let maxInitialLines: Int + private let maxInitialBytes: Int private let maxCachedMessages: Int + private let incrementalReadChunkBytes: Int private var cache: [ChatMessage] = [] private var parseState = ChatTranscriptParseState() @@ -40,7 +45,7 @@ actor AgentChatTranscriptTailer { /// rotation is detected even when the new file is the same size or /// larger (seeking to the old offset would otherwise skip its head). private var fileInode: UInt64? - private var pendingFragment = Data() + private var incrementalLineBuffer: AgentChatTranscriptIncrementalLineBuffer private var headTruncated = false private var watchTask: Task? private var watcher: FileWatcher? @@ -54,21 +59,39 @@ actor AgentChatTranscriptTailer { /// - agentKind: Selects the parser (claude or codex). /// - path: Absolute transcript JSONL path. /// - maxInitialLines: Backfill bound for the first read. + /// - maxInitialBytes: Maximum transcript suffix bytes read initially. /// - maxCachedMessages: In-memory cache cap; oldest fall out. + /// - maximumIncrementalLineBytes: Maximum retained bytes for one live + /// JSONL record before it is discarded through the next newline. + /// - incrementalReadChunkBytes: Maximum allocation for one live file read. /// - onBatch: Receives live change batches after the initial load. init( sessionID: String, agentKind: ChatAgentKind, path: String, maxInitialLines: Int = 2000, + maxInitialBytes: Int = AgentChatTranscriptInitialTailReader.defaultMaximumBytes, maxCachedMessages: Int = 4000, + maximumIncrementalLineBytes: Int = AgentChatTranscriptInitialTailReader.defaultMaximumBytes, + incrementalReadChunkBytes: Int = 64 * 1024, onBatch: @escaping @Sendable (Batch) async -> Void ) { self.sessionID = sessionID self.agentKind = agentKind self.path = path - self.maxInitialLines = maxInitialLines + self.maxInitialLines = min(max(maxInitialLines, 0), 2000) + self.maxInitialBytes = min( + max(maxInitialBytes, 1), + AgentChatTranscriptInitialTailReader.defaultMaximumBytes + ) self.maxCachedMessages = maxCachedMessages + self.incrementalReadChunkBytes = min(max(incrementalReadChunkBytes, 1), 256 * 1024) + self.incrementalLineBuffer = AgentChatTranscriptIncrementalLineBuffer( + maximumLineBytes: min( + max(maximumIncrementalLineBytes, 1), + AgentChatTranscriptInitialTailReader.defaultMaximumBytes + ) + ) self.onBatch = onBatch } @@ -143,39 +166,51 @@ actor AgentChatTranscriptTailer { // MARK: - Reading private func loadInitialTail() { - guard let handle = FileHandle(forReadingAtPath: path) else { return } - defer { try? handle.close() } - // Memory-mapped read: newline scanning walks the file without - // copying it; only the bounded tail is decoded into strings. - guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) else { - return - } - var lineStarts: [Int] = [0] - data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in - for index in 0.. retainedLineLimit { break } } } - // A trailing partial line (no terminating newline) is carried as the - // pending fragment; only complete lines are parsed and counted. - let completeLineCount = lineStarts.count - 1 - let lastCompleteEnd = lineStarts[completeLineCount] - if lastCompleteEnd < data.count { - pendingFragment = Data(data[lastCompleteEnd...]) - } - byteOffset = UInt64(data.count) - lineCount = completeLineCount + let parseStart = reverseNewlines.count > retainedLineLimit + ? reverseNewlines[retainedLineLimit] + 1 + : 0 + let lastCompleteEnd = reverseNewlines.first.map { $0 + 1 } ?? 0 + let pendingFragment = lastCompleteEnd < data.count + ? Data(data[lastCompleteEnd...]) + : Data() + let discardedInitialFragment = incrementalLineBuffer.reset( + pendingFragment: pendingFragment, + discardsUntilNextNewline: snapshot.discardsUntilNextNewline + ) + byteOffset = snapshot.fileSize + headTruncated = snapshot.headTruncated || parseStart > 0 || discardedInitialFragment + let retainedByteOffset = snapshot.retainedStartOffset + UInt64(parseStart) + let startingSequence = headTruncated + ? Int(min(retainedByteOffset, UInt64(Int.max - retainedLineLimit))) + : 0 + lineCount = startingSequence fileInode = Self.inode(ofPath: path) - let parseStartLine = max(0, completeLineCount - maxInitialLines) - headTruncated = parseStartLine > 0 var lines: [String] = [] - lines.reserveCapacity(completeLineCount - parseStartLine) - for lineIndex in parseStartLine.. byteOffset else { return } - try? handle.seek(toOffset: byteOffset) - guard let newData = try? handle.readToEnd(), !newData.isEmpty else { return } - byteOffset += UInt64(newData.count) + guard (try? handle.seek(toOffset: byteOffset)) != nil else { return } + var remainingByteCount = size - byteOffset + while remainingByteCount > 0, !Task.isCancelled { + let requestedCount = Int(min( + remainingByteCount, + UInt64(incrementalReadChunkBytes) + )) + guard let newData = try? handle.read(upToCount: requestedCount), + !newData.isEmpty else { + break + } + byteOffset += UInt64(newData.count) + remainingByteCount -= UInt64(newData.count) + await consumeIncrementalData(newData) + } + } - var buffer = pendingFragment - buffer.append(newData) - var lines: [String] = [] - var sliceStart = buffer.startIndex - for index in buffer.indices where buffer[index] == 0x0A { - lines.append(String(decoding: buffer[sliceStart.. ChatArtifactLaneDescriptor { let currentTime = now() @@ -161,11 +162,16 @@ actor MobileHostIrohArtifactTransferRegistry { guard entries.count < Self.maximumEntryCount else { throw Error.capacityExceeded } - let resolvedPath = URL(fileURLWithPath: canonicalPath) - .standardizedFileURL - .resolvingSymlinksInPath() - .path - let identity = try MobileHostIrohArtifactFileIdentity.snapshot(path: resolvedPath) + // `canonicalPath` is the path returned by the authorization scope. Do + // not resolve it again here: a replaced ancestor could otherwise make + // the capability point at a new, unauthorized target. The descriptor + // helper verifies the opened path against this authorization-time value. + let resolvedPath = URL(fileURLWithPath: canonicalPath).standardizedFileURL.path + let identity = try MobileHostIrohArtifactFileIdentity.snapshot( + path: resolvedPath, + expectedCanonicalPath: resolvedPath, + expectedIdentity: authorizedIdentity + ) guard identity.size >= 0 else { throw Error.invalidFile } let capability = try resourceID() guard entries[capability] == nil else { throw Error.capacityExceeded } @@ -235,8 +241,12 @@ struct MobileHostIrohArtifactFileIdentity: Equatable, Sendable { let modifiedSeconds: Int64 let modifiedNanoseconds: Int64 - static func snapshot(path: String) throws -> Self { - let descriptor = Darwin.open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) + static func snapshot( + path: String, + expectedCanonicalPath: String, + expectedIdentity: ChatArtifactFileIdentity + ) throws -> Self { + let descriptor = Darwin.open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) guard descriptor >= 0 else { switch POSIXErrorCode(rawValue: Darwin.errno) { case .ENOENT, .ESTALE: @@ -255,6 +265,17 @@ struct MobileHostIrohArtifactFileIdentity: Equatable, Sendable { guard (value.st_mode & S_IFMT) == S_IFREG else { throw MobileHostIrohArtifactTransferRegistry.Error.notRegularFile } + if ChatArtifactFileIdentity( + device: UInt64(value.st_dev), + inode: UInt64(value.st_ino) + ) != expectedIdentity { + throw MobileHostIrohArtifactTransferRegistry.Error.fileNotFound + } + guard let openedPath = openedPath(for: descriptor), + canonicalPath(openedPath) + == URL(fileURLWithPath: expectedCanonicalPath).standardizedFileURL.path else { + throw MobileHostIrohArtifactTransferRegistry.Error.fileNotFound + } return identity(from: value) } @@ -276,6 +297,24 @@ struct MobileHostIrohArtifactFileIdentity: Equatable, Sendable { modifiedNanoseconds: Int64(value.st_mtimespec.tv_nsec) ) } + + private static func openedPath(for descriptor: Int32) -> String? { + var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX)) + let result = buffer.withUnsafeMutableBytes { + (bytes: UnsafeMutableRawBufferPointer) -> Int32 in + guard let baseAddress = bytes.baseAddress else { return -1 } + return Darwin.fcntl(descriptor, F_GETPATH, baseAddress) + } + guard result == 0 else { return nil } + return String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self) + } + + private static func canonicalPath(_ path: String) -> String { + URL(fileURLWithPath: path) + .resolvingSymlinksInPath() + .standardizedFileURL + .path + } } /// Random-access file reader backed by DispatchIO so a slow file system never @@ -290,7 +329,7 @@ private final class MobileHostIrohArtifactDispatchReader: @unchecked Sendable { private let channel: DispatchIO init(path: String) throws { - let fileDescriptor = Darwin.open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) + let fileDescriptor = Darwin.open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) guard fileDescriptor >= 0 else { throw MobileHostIrohArtifactTransferRegistry.Error.invalidFile } diff --git a/Sources/Mobile/MobileHostService+Capabilities.swift b/Sources/Mobile/MobileHostService+Capabilities.swift index 8bcb454470bd..7f69c1d6626d 100644 --- a/Sources/Mobile/MobileHostService+Capabilities.swift +++ b/Sources/Mobile/MobileHostService+Capabilities.swift @@ -31,6 +31,7 @@ extension MobileHostService { "mobile.chat.artifact.fetch", "mobile.chat.artifact.gallery", "mobile.chat.artifact.list", + "mobile.chat.artifact.save", "mobile.chat.artifact.stat", "mobile.chat.artifact.thumbnail", "mobile.chat.history", @@ -150,7 +151,10 @@ extension MobileHostService { // no browser affordance can work. A user-level disable keeps live // panes (session restore re-materializes them), and iOS must // still be able to view/stream those, so keep advertising then. - includingBrowser: !BrowserAvailabilitySettings.isManagedByPolicy + includingBrowser: !BrowserAvailabilitySettings.isManagedByPolicy, + includingArtifacts: CmuxFeatureFlags.offMainEffectiveValue( + for: CmuxFeatureFlags.artifactsFlag + ) ) } @@ -169,7 +173,8 @@ extension MobileHostService { includingWorkspaceChanges: Bool, includingSimulator: Bool = true, includingTaskComposer: Bool = true, - includingBrowser: Bool = true + includingBrowser: Bool = true, + includingArtifacts: Bool = true ) -> [String] { var capabilities = [ Self.irohPrivatePathsCapability, @@ -229,6 +234,7 @@ extension MobileHostService { Self.taskDirectorySearchV2Capability, Self.caffeineControlCapability, "chat.artifact.v1", + "chat.artifact.save.v1", "chat.artifact.folders.v1", "chat.artifact.gallery.v1", "dogfood.v1", @@ -264,6 +270,15 @@ extension MobileHostService { ] capabilities.removeAll { taskComposerCapabilities.contains($0) } } + if !includingArtifacts { + let artifactCapabilities: Set = [ + "chat.artifact.v1", + "chat.artifact.save.v1", + "chat.artifact.folders.v1", + "chat.artifact.gallery.v1", + ] + capabilities.removeAll { artifactCapabilities.contains($0) } + } if !includingBrowser { // The embedded browser is disabled by MDM policy: every pane is // closed and none can be created, so stop advertising browser diff --git a/Sources/Mobile/MobileHostService+TicketAuthorization.swift b/Sources/Mobile/MobileHostService+TicketAuthorization.swift index 375cef515e7f..4b8c77c4bbf2 100644 --- a/Sources/Mobile/MobileHostService+TicketAuthorization.swift +++ b/Sources/Mobile/MobileHostService+TicketAuthorization.swift @@ -48,6 +48,24 @@ extension MobileHostService { // List-shaped reads may span the Mac's workspaces; same-account // Stack authorization remains the authoritative data-plane gate. return nil + case "mobile.chat.artifact.stat", "mobile.chat.artifact.fetch", + "mobile.chat.artifact.thumbnail", "mobile.chat.artifact.list", + "mobile.chat.artifact.gallery": + // Chat artifact requests are authorized by the session-scoped + // transcript/index handlers. Their session_id is not a live + // workspace selector, so an attach ticket cannot safely narrow + // these requests here; the same-account Stack gate remains the + // authority, just as it does for the other chat data-plane reads. + return nil + case "mobile.chat.artifact.save": + // Saving mutates the session project's `.cmux` tree (and its Git + // exclude state). A workspace/terminal-scoped ticket cannot + // prove that its session belongs to that scope, so require a + // Mac-wide ticket while the attach token is valid. The + // same-account Stack gate remains authoritative after expiry. + return ticketMacScopedWorkspaceMutationAuthorizationError( + authorization: authorization + ) case "mobile.sync.fetch": // Cursor-based read of the same Mac-scoped list state as // `mobile.workspace.list`; carries no workspace/terminal selection. diff --git a/Sources/Mobile/MobileHostTransportAuthorization.swift b/Sources/Mobile/MobileHostTransportAuthorization.swift index b7c717f574f6..31039afb7640 100644 --- a/Sources/Mobile/MobileHostTransportAuthorization.swift +++ b/Sources/Mobile/MobileHostTransportAuthorization.swift @@ -35,7 +35,8 @@ struct MobileHostRPCExecutionContext: Sendable { let artifactTransfers: MobileHostIrohArtifactTransferRegistry? func issueArtifactTransfer( - canonicalPath: String + canonicalPath: String, + authorizedIdentity: ChatArtifactFileIdentity ) async throws -> ChatArtifactLaneDescriptor { guard case let .irohAdmission(peer) = authorization, let artifactTransfers else { @@ -43,6 +44,7 @@ struct MobileHostRPCExecutionContext: Sendable { } return try await artifactTransfers.issue( canonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity, peer: peer ) } diff --git a/Sources/NSEvent+RightSidebarKeyboardNavigation.swift b/Sources/NSEvent+RightSidebarKeyboardNavigation.swift new file mode 100644 index 000000000000..e8934cafd02e --- /dev/null +++ b/Sources/NSEvent+RightSidebarKeyboardNavigation.swift @@ -0,0 +1,63 @@ +import AppKit + +extension NSEvent { + var rightSidebarMoveDelta: Int? { + guard type == .keyDown else { return nil } + let flags = modifierFlags.intersection(.deviceIndependentFlagsMask) + let hasCommandOrOption = !flags.intersection([.command, .option]).isEmpty + if flags.contains(.control), !hasCommandOrOption { + switch keyCode { + case 45: return 1 // Ctrl+N + case 35: return -1 // Ctrl+P + default: break + } + } + + guard flags.intersection([.command, .control, .option]).isEmpty else { + return nil + } + switch keyCode { + case 38, 125: return 1 // J or Down + case 40, 126: return -1 // K or Up + default: return nil + } + } + + var rightSidebarDisclosureAction: RightSidebarDisclosureAction? { + guard type == .keyDown else { return nil } + let flags = modifierFlags.intersection(.deviceIndependentFlagsMask) + guard flags.intersection([.command, .control, .option]).isEmpty else { + return nil + } + switch keyCode { + case 4: return .collapse // H + case 37: return .expand // L + case 123: return .collapse // Left + case 124: return .expand // Right + default: return nil + } + } + + var isPlainRightSidebarSlash: Bool { + guard type == .keyDown else { return false } + let flags = modifierFlags.intersection(.deviceIndependentFlagsMask) + guard flags.intersection([.command, .control, .option]).isEmpty else { + return false + } + return keyCode == 44 + } + + var isPlainRightSidebarPrintableText: Bool { + guard type == .keyDown else { return false } + let flags = modifierFlags.intersection(.deviceIndependentFlagsMask) + guard flags.intersection([.command, .control, .option]).isEmpty else { + return false + } + guard let text = charactersIgnoringModifiers, !text.isEmpty else { + return false + } + return text.unicodeScalars.allSatisfy { + !CharacterSet.controlCharacters.contains($0) + } + } +} diff --git a/Sources/NSView+RightSidebarKeyboardFocus.swift b/Sources/NSView+RightSidebarKeyboardFocus.swift new file mode 100644 index 000000000000..f4f22dad76db --- /dev/null +++ b/Sources/NSView+RightSidebarKeyboardFocus.swift @@ -0,0 +1,15 @@ +import AppKit + +extension NSView { + var cmuxCanAcceptRightSidebarKeyboardFocus: Bool { + guard window != nil, !isHiddenOrHasHiddenAncestor else { return false } + var view: NSView? = self + while let current = view { + if current.bounds.width <= 0.5 || current.bounds.height <= 0.5 { + return false + } + view = current.superview + } + return true + } +} diff --git a/Sources/Panels/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index 198943cba9fa..5e6d76b7f5b4 100644 --- a/Sources/Panels/BrowserNavigationDelegate.swift +++ b/Sources/Panels/BrowserNavigationDelegate.swift @@ -37,6 +37,7 @@ import WebKit var didReplaceNavigationForUserAgentPolicy: ((WKWebView, WKNavigation?, WKNavigation?) -> Void)? var didRenderPDFDocument: ((URL, Bool) -> Void)? var didClearPDFDocument: (() -> Void)? + var artifactHTMLPreviewPolicy: ArtifactHTMLPreviewNavigationPolicy? /// Direct reference to the download delegate - must be set synchronously in didBecome callbacks. var downloadDelegate: WKDownloadDelegate? /// Last attempted navigation URL, used to preserve the omnibar URL after provisional failures. @@ -324,6 +325,14 @@ import WebKit label: "BrowserNavigationDelegate.navigationAction" ).closure + let artifactNavigationAllowed = artifactHTMLPreviewPolicy?.allowsNavigation( + to: navigationAction.request.url, + targetIsMainFrame: navigationAction.targetFrame?.isMainFrame + ) == true + if artifactHTMLPreviewPolicy != nil, !artifactNavigationAllowed { + decisionHandler(.cancel) + return + } if let url = navigationAction.request.url, url.scheme == "cmux-browser-action", url.host == "bypass-ssl" { @@ -410,7 +419,8 @@ import WebKit } let isTrustedDocument = isMainFrame && url.isFileURL && owner?.isTrustedLocalFileDocument(url) == true - if !isTrustedInternal, + if !artifactNavigationAllowed, + !isTrustedInternal, !isTrustedDocument, url.scheme?.lowercased() != AuthEnvironment.callbackScheme.lowercased(), !BrowserURLAllowlistPolicy(defaults: .standard).allows(url) { @@ -805,12 +815,17 @@ import WebKit if let url = navigationResponse.response.url { let isMainFrame = navigationResponse.isForMainFrame let isTrustedInternal = trustedInternalNavigation(for: url, in: webView) + let artifactNavigationAllowed = artifactHTMLPreviewPolicy?.allowsNavigation( + to: url, + targetIsMainFrame: navigationResponse.isForMainFrame + ) == true if isMainFrame, !isTrustedInternal { (webView as? CmuxWebView)?.clearTrustedInternalNavigationGrants() } let isTrustedDocument = isMainFrame && url.isFileURL && owner?.isTrustedLocalFileDocument(url) == true - if !isTrustedInternal, + if !artifactNavigationAllowed, + !isTrustedInternal, !isTrustedDocument, !BrowserURLAllowlistPolicy(defaults: .standard).allows(url) { decisionHandler(.cancel) @@ -950,6 +965,12 @@ import WebKit /// Applies a newly changed policy to the currently displayed document. func enforceURLAllowlistPolicy(in webView: WKWebView, displayURL: URL? = nil) { guard let url = displayURL ?? webView.url else { return } + if artifactHTMLPreviewPolicy?.allowsNavigation( + to: url, + targetIsMainFrame: true + ) == true { + return + } let policy = BrowserURLAllowlistPolicy(defaults: .standard) if policy.allows(url) { return } if let owner, diff --git a/Sources/Panels/BrowserPanel+AutomationRecovery.swift b/Sources/Panels/BrowserPanel+AutomationRecovery.swift index ef4913088025..2954c3b339fe 100644 --- a/Sources/Panels/BrowserPanel+AutomationRecovery.swift +++ b/Sources/Panels/BrowserPanel+AutomationRecovery.swift @@ -119,6 +119,7 @@ extension BrowserPanel { } func registerBrowserAutomationInitScript(_ userScript: WKUserScript) -> Int { + guard contentMode.artifactDocumentURL == nil else { return 0 } browserAutomationUserScripts.append(userScript) browserAutomationInitScriptCount += 1 webView.configuration.userContentController.addUserScript(userScript) @@ -126,6 +127,7 @@ extension BrowserPanel { } func registerBrowserAutomationStyleScript(_ userScript: WKUserScript) -> Int { + guard contentMode.artifactDocumentURL == nil else { return 0 } browserAutomationUserScripts.append(userScript) browserAutomationStyleScriptCount += 1 webView.configuration.userContentController.addUserScript(userScript) @@ -142,6 +144,11 @@ extension BrowserPanel { profileID: UUID, websiteDataStore: WKWebsiteDataStore ) -> CmuxWebView { + if contentMode.artifactDocumentURL != nil { + return ArtifactHTMLPreviewWebViewFactory( + websiteDataStore: websiteDataStore + ).makeWebView() + } let replacement = Self.makeWebView( profileID: profileID, websiteDataStore: websiteDataStore diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 1be065678abd..0d8540313a36 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -1990,6 +1990,7 @@ final class BrowserPanel: Panel, ObservableObject { @Published private(set) var profileID: UUID @Published private(set) var historyStore: BrowserHistoryStore + let contentMode: BrowserPanelContentMode /// The underlying web view private(set) var webView: WKWebView @@ -3063,8 +3064,17 @@ final class BrowserPanel: Panel, ObservableObject { webView.onScreenshotCopied = { [weak self] in self?.screenshotCopiedToken &+= 1 } - webView.onContextMenuOpenLinkInNewTab = { [weak self] url in - self?.openContextMenuLinkInNewTab(url: url) + if contentMode.artifactDocumentURL == nil { + webView.onContextMenuOpenLinkInNewTab = { [weak self] url in + self?.openContextMenuLinkInNewTab(url: url) + } + webView.contextMenuDefaultBrowserOpener = nil + } else { + // Artifact previews are isolated documents. Their context-menu + // links must not escape into a normal browser surface or the + // system browser, which would bypass the preview navigation policy. + webView.onContextMenuOpenLinkInNewTab = nil + webView.contextMenuDefaultBrowserOpener = { _ in false } } configureMoveTabToNewWorkspaceContextMenu(for: webView) navigationDelegate?.resetTrustedInternalNavigationState() @@ -3073,7 +3083,7 @@ final class BrowserPanel: Panel, ObservableObject { automationNavigationCoordinator.bind(to: webViewInstanceID) webView.cmuxDownloadDelegate = downloadDelegate webView.navigationDelegate = navigationDelegate - webView.uiDelegate = uiDelegate + webView.uiDelegate = contentMode.artifactDocumentURL == nil ? uiDelegate : nil setupObservers(for: webView) setupSameDocumentNavigationMessageHandler(for: webView) setupReactGrabMessageHandler(for: webView) @@ -3165,8 +3175,10 @@ final class BrowserPanel: Panel, ObservableObject { self.applyMuteState(to: webView, reason: "navigationFinish") if self.navigationDelegate?.activeErrorPageDisplayURL == nil { self.realignRestoredSessionHistoryToLiveCurrentIfPossible() - boundHistoryStore.recordVisit(url: webView.url, title: webView.title) - self.refreshFavicon(from: webView) + if self.contentMode.artifactDocumentURL == nil { + boundHistoryStore.recordVisit(url: webView.url, title: webView.title) + self.refreshFavicon(from: webView) + } } self.applyCurrentAppWebTheme(to: webView) // Keep find-in-page open through load completion and refresh matches for the new DOM. @@ -3436,6 +3448,7 @@ final class BrowserPanel: Panel, ObservableObject { bypassRemoteProxy: Bool = false, isRemoteWorkspace: Bool = false, remoteWebsiteDataStoreIdentifier: UUID? = nil, + contentMode: BrowserPanelContentMode = .standard, websiteDataStore explicitWebsiteDataStore: WKWebsiteDataStore? = nil ) { // Register fallback defaults and normalize legacy/out-of-range settings once @@ -3447,6 +3460,7 @@ final class BrowserPanel: Panel, ObservableObject { self.externalNavigationHandler = BrowserExternalNavigationHandler() let resolvedProfileID = Self.resolvedProfileID(requested: profileID) self.profileID = resolvedProfileID + self.contentMode = contentMode self.insecureHTTPBypassHostOnce = BrowserInsecureHTTPSettings.normalizeHost(bypassInsecureHTTPHostOnce ?? "") self.bypassesRemoteWorkspaceProxy = bypassRemoteProxy self.remoteProxyEndpoint = bypassRemoteProxy ? nil : proxyEndpoint @@ -3455,15 +3469,19 @@ final class BrowserPanel: Panel, ObservableObject { self.shouldPreloadInitialNavigationInBackground = preloadInitialNavigationInBackground self.chromeState = BrowserChromeState(visibility: chromeVisibility) self.usesTransparentBackground = transparentBackground - let websiteDataStore = explicitWebsiteDataStore ?? ( - isRemoteWorkspace + let isArtifactPreview = contentMode.artifactDocumentURL != nil + let websiteDataStore = isArtifactPreview + ? WKWebsiteDataStore.nonPersistent() + : explicitWebsiteDataStore ?? ( + isRemoteWorkspace ? WKWebsiteDataStore(forIdentifier: remoteWebsiteDataStoreIdentifier ?? workspaceId) : BrowserProfileStore.shared.websiteDataStore(for: resolvedProfileID) - ) + ) let preservesExplicitEphemeralWebsiteDataStore = - explicitWebsiteDataStore != nil - && websiteDataStore !== WKWebsiteDataStore.default() - && websiteDataStore.identifier == nil + isArtifactPreview + || (explicitWebsiteDataStore != nil + && websiteDataStore !== WKWebsiteDataStore.default() + && websiteDataStore.identifier == nil) self.historyStore = preservesExplicitEphemeralWebsiteDataStore ? BrowserHistoryStore(fileURL: nil) : BrowserProfileStore.shared.historyStore(for: resolvedProfileID) @@ -3472,7 +3490,11 @@ final class BrowserPanel: Panel, ObservableObject { preservesExplicitEphemeralWebsiteDataStore let webView: CmuxWebView var adoptedPrewarmedWebView = false - if let prewarmed = Self.claimedPrewarmedWebView( + if contentMode.artifactDocumentURL != nil { + webView = ArtifactHTMLPreviewWebViewFactory( + websiteDataStore: websiteDataStore + ).makeWebView() + } else if let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, @@ -3507,13 +3529,20 @@ final class BrowserPanel: Panel, ObservableObject { } hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() - BrowserProfileStore.shared.noteUsed(resolvedProfileID) + if contentMode.artifactDocumentURL == nil { + BrowserProfileStore.shared.noteUsed(resolvedProfileID) + } // Set up navigation delegate let navDelegate = BrowserNavigationDelegate( externalNavigationHandler: externalNavigationHandler ) navDelegate.owner = self + if let documentURL = contentMode.artifactDocumentURL { + navDelegate.artifactHTMLPreviewPolicy = ArtifactHTMLPreviewNavigationPolicy( + documentURL: documentURL + ) + } navDelegate.openInNewTab = { [weak self] url in self?.openLinkInNewTab(url: url) } @@ -3751,7 +3780,7 @@ final class BrowserPanel: Panel, ObservableObject { refreshWebViewLifecycleState() guard renderInitialNavigation else { return } if let url = initialRequest.url, - !BrowserURLAllowlistPolicy(defaults: .standard).allows(url) { + !allowsNavigationURL(url) { navigationDelegate?.blockURLAllowlistNavigation(url, in: webView) } else if let url = initialRequest.url, insecureHTTPBypassHostOnce == nil, @@ -4186,7 +4215,8 @@ final class BrowserPanel: Panel, ObservableObject { @discardableResult func switchToProfile(_ requestedProfileID: UUID) -> Bool { - guard !preservesExplicitEphemeralWebsiteDataStore else { + guard contentMode.artifactDocumentURL == nil, + !preservesExplicitEphemeralWebsiteDataStore else { return false } let resolvedProfileID = BrowserProfileStore.shared.profileDefinition(id: requestedProfileID) != nil @@ -4420,6 +4450,7 @@ final class BrowserPanel: Panel, ObservableObject { } func shouldPersistSessionSnapshot() -> Bool { + guard contentMode.allowsSessionPersistence else { return false } // A non-persistent WebKit store cannot be reconstructed with the same // account or cookies. Persisting only its URL and profile would reopen // it inside a shared profile, which is unsafe for authenticated native @@ -5421,7 +5452,7 @@ final class BrowserPanel: Panel, ObservableObject { let request = URLRequest(url: url) let policy = BrowserURLAllowlistPolicy(defaults: .standard) (webView as? CmuxWebView)?.clearTrustedInternalNavigationGrants() - if !policy.allowsTrustedInternalURL(url) { + if !policy.allowsTrustedInternalURL(url) && !allowsNavigationURL(url) { navigationDelegate?.blockURLAllowlistNavigation(url, in: webView) onNavigationStarted?(nil) return nil @@ -5479,7 +5510,7 @@ final class BrowserPanel: Panel, ObservableObject { let policyAllowsURL = trustedInternalNavigation ? policy.allowsTrustedInternalURL(url) : policy.allows(url) - guard policyAllowsURL else { + guard policyAllowsURL || allowsNavigationURL(url) else { onNavigationStarted?(nil) navigationDelegate?.blockURLAllowlistNavigation(url, in: webView) return nil @@ -5515,6 +5546,17 @@ final class BrowserPanel: Panel, ObservableObject { ) } + /// App-owned artifact documents use the trusted-internal scheme policy; + /// page-initiated navigations still pass through the delegate's ordinary + /// allowlist and artifact-document policy. + private func allowsNavigationURL(_ url: URL) -> Bool { + let policy = BrowserURLAllowlistPolicy(defaults: .standard) + guard contentMode.artifactDocumentURL != nil else { + return policy.allows(url) + } + return policy.allowsTrustedInternalURL(url) + } + private func resumePendingRemoteNavigationIfNeeded() { // Resume on endpoint arrival, or directly once the pane turned local // (a stranded queue pins the hidden pane as non-discardable forever). @@ -5961,6 +6003,7 @@ extension BrowserPanel { reason: String, forceWebViewReplacement: Bool = false ) { + guard contentMode.artifactDocumentURL == nil else { return } guard forceWebViewReplacement || needsWorkspaceContextReset else { resetWebViewLifecycleMetadata() #if DEBUG diff --git a/Sources/Panels/FilePreviewImageSession.swift b/Sources/Panels/FilePreviewImageSession.swift index ffd0ee7009fe..8fb918c68d82 100644 --- a/Sources/Panels/FilePreviewImageSession.swift +++ b/Sources/Panels/FilePreviewImageSession.swift @@ -65,6 +65,6 @@ final class FilePreviewImageSession { view.isHidden = !isVisibleInUI view.setBackgroundAppearance(backgroundColor: backgroundColor, drawsBackground: drawsBackground) view.setPanel(panel) - view.setURL(panel.fileURL, revision: revision) + view.setURL(panel.readURL, revision: revision) } } diff --git a/Sources/Panels/FilePreviewMediaSession.swift b/Sources/Panels/FilePreviewMediaSession.swift index 29c9510ef79e..94bdbbce3ff8 100644 --- a/Sources/Panels/FilePreviewMediaSession.swift +++ b/Sources/Panels/FilePreviewMediaSession.swift @@ -131,7 +131,7 @@ final class FilePreviewMediaSession { drawsBackground: drawsBackground ) panel.attachPreviewFocus(root: view, primaryResponder: view, intent: .mediaPlayer) - updatePlayer(in: view, url: panel.fileURL, revision: revision) + updatePlayer(in: view, url: panel.readURL, revision: revision) } private func updatePlayer(in playerView: AVPlayerView, url: URL, revision: Int) { diff --git a/Sources/Panels/FilePreviewPDFSession.swift b/Sources/Panels/FilePreviewPDFSession.swift index bf8038d08024..f0bedc699ee1 100644 --- a/Sources/Panels/FilePreviewPDFSession.swift +++ b/Sources/Panels/FilePreviewPDFSession.swift @@ -65,6 +65,6 @@ final class FilePreviewPDFSession { view.isHidden = !isVisibleInUI view.setBackgroundAppearance(backgroundColor: backgroundColor, drawsBackground: drawsBackground) view.setPanel(panel) - view.setURL(panel.fileURL, revision: revision) + view.setURL(panel.readURL, revision: revision) } } diff --git a/Sources/Panels/FilePreviewPanel.swift b/Sources/Panels/FilePreviewPanel.swift index f721b326a547..82cdfce4fcf1 100644 --- a/Sources/Panels/FilePreviewPanel.swift +++ b/Sources/Panels/FilePreviewPanel.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxArtifacts import AppKit import Bonsplit import Combine @@ -1269,6 +1270,10 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan let stableSurfaceIdentity = PanelStableSurfaceIdentity() let panelType: PanelType = .filePreview let filePath: String + private var artifactFile: ArtifactSidebarFileAccess.OpenedFile? + private var artifactReadCopyURL: URL? + private var artifactPreviewTask: Task? + private var artifactPreviewToken = UUID() private(set) var workspaceId: UUID @Published private(set) var displayTitle: String @Published private(set) var displayIcon: String? @@ -1308,6 +1313,27 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan URL(fileURLWithPath: filePath) } + /// Descriptor-backed URL used for reads of an artifact sidebar file. + var readURL: URL { + if let artifactReadCopyURL { + return artifactReadCopyURL + } + // A refresh removes the materialized copy before asynchronously + // revalidating the pathname. Keep in-process readers on the original + // descriptor during that interval; falling back to `fileURL` would + // reopen a path that may have been replaced or symlinked elsewhere. + if let artifactFile { + return artifactFile.readURL + } + return fileURL + } + + /// Artifact sidebar previews are read-only so a replaced pathname cannot + /// redirect a save operation outside the validated inode. + var isReadOnly: Bool { + artifactFile != nil + } + var previewRevision: Int { previewRevisionState.value } @@ -1320,6 +1346,7 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan workspaceId: UUID, filePath: String, startFileWatcher: Bool = true, + artifactFile: ArtifactSidebarFileAccess.OpenedFile? = nil, fileContentChangeCoordinator: FileContentChangeCoordinator? = nil, textLoader: @escaping @Sendable (URL) async -> FilePreviewTextLoader.Result = { url in await FilePreviewTextLoader.load(url: url) @@ -1335,6 +1362,9 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan self.id = UUID() self.workspaceId = workspaceId self.filePath = filePath + self.artifactFile = artifactFile + self.artifactReadCopyURL = nil + self.artifactPreviewTask = nil self.fileContentChangeCoordinator = fileContentChangeCoordinator ?? FileContentChangeCoordinator() self.displayTitle = URL(fileURLWithPath: filePath).lastPathComponent @@ -1351,12 +1381,113 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan self.lastObservedFileState = .capture(path: filePath) prepareContentForPreviewMode() - resolvePreviewModeIfNeeded(for: fileURL) - if startFileWatcher { + if artifactFile != nil { + startArtifactPreviewLoad() + } + if artifactFile == nil { + resolvePreviewModeIfNeeded(for: fileURL) + } + if startFileWatcher, artifactFile == nil { startWatchingForFileChanges() } } + @discardableResult + private func startArtifactPreviewLoad(force: Bool = false) -> Task? { + let artifactRoot = artifactFile?.artifactRoot + if force { + artifactPreviewToken = UUID() + artifactPreviewTask?.cancel() + artifactPreviewTask = nil + textLoadCoordinator.cancel() + if let artifactReadCopyURL { + try? FileManager.default.removeItem(at: artifactReadCopyURL) + self.artifactReadCopyURL = nil + } + // Native preview sessions may receive an unrelated SwiftUI update + // while the replacement copy is being staged. Hide them until the + // newly validated copy is ready so they cannot consume a stale URL. + isFileUnavailable = true + guard artifactRoot != nil else { + isFileUnavailable = true + return nil + } + } + guard let artifactFile, artifactPreviewTask == nil else { + return artifactPreviewTask + } + let token = artifactPreviewToken + let sourcePath = filePath + let task = Task { @MainActor [weak self, artifactFile, artifactRoot, force] in + let fileForPreview: ArtifactSidebarFileAccess.OpenedFile? + if force { + guard let artifactRoot else { + if let self, self.artifactPreviewToken == token { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + } + return + } + fileForPreview = await ArtifactSidebarFileAccess().openedFileAsync( + for: URL(fileURLWithPath: sourcePath), + artifactRoot: artifactRoot + ) + guard let self, + self.artifactPreviewToken == token else { + return + } + guard let fileForPreview else { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + return + } + self.artifactFile = fileForPreview + } else { + fileForPreview = artifactFile + } + guard let fileForPreview else { + if let self, self.artifactPreviewToken == token { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + } + return + } + let temporaryURL = await fileForPreview.makeTemporaryPreviewURLAsync( + maximumBytes: ArtifactCaptureConfiguration.defaultValue.maximumFileBytes + ) + guard let self else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + guard self.artifactPreviewToken == token else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + self.artifactPreviewTask = nil + guard !self.isClosed else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + guard let temporaryURL else { + self.isFileUnavailable = true + return + } + self.artifactReadCopyURL = temporaryURL + self.previewRevisionState.increment() + if let contentTask = self.prepareContentForPreviewMode() { + await contentTask.value + } + } + artifactPreviewTask = task + return task + } + func focus() { _ = restoreFocusIntent(preferredFocusIntentForActivation()) } @@ -1367,6 +1498,9 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan func close() { isClosed = true + artifactPreviewToken = UUID() + artifactPreviewTask?.cancel() + artifactPreviewTask = nil unbindTabMetadata() stopWatchingForFileChanges() textLoadCoordinator.cancel() @@ -1374,6 +1508,10 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan selectionReader.close() nativeViewSessions.closeAll() textView = nil + if let artifactReadCopyURL { + try? FileManager.default.removeItem(at: artifactReadCopyURL) + self.artifactReadCopyURL = nil + } focusCoordinator.unregisterAll() } @@ -1521,6 +1659,9 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan @discardableResult func reloadFromDisk() -> Task { lastObservedFileState = .capture(path: filePath) + if artifactFile != nil { + return startArtifactPreviewLoad(force: true) ?? Task {} + } let fileURL = fileURL let modeResolver = modeResolver @@ -1555,10 +1696,15 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan @discardableResult private func prepareContentForPreviewMode() -> Task? { + if artifactFile != nil, artifactReadCopyURL == nil { + isFileUnavailable = true + return nil + } if previewMode == .text { return loadTextContent(replacingDirtyContent: false) } else { - isFileUnavailable = !FileManager.default.fileExists(atPath: filePath) + isFileUnavailable = artifactFile == nil + && !FileManager.default.fileExists(atPath: filePath) return nil } } @@ -1596,7 +1742,7 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan guard previewMode == .text else { return Task {} } - let fileURL = fileURL + let fileURL = readURL let textLoader = textLoader return textLoadCoordinator.submit(load: { @@ -1641,6 +1787,7 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan @discardableResult func saveTextContent() -> Task? { guard previewMode == .text else { return nil } + guard !isReadOnly else { return nil } guard !isSaving else { return nil } let currentContent = textView?.string ?? textContent guard currentContent != originalTextContent else { @@ -1655,7 +1802,7 @@ final class FilePreviewPanel: Panel, ObservableObject, FilePreviewTextEditingPan _ = replaceTextContentIfChanged(currentContent) isSaving = true activeSaveGeneration = generation - let fileURL = fileURL + let fileURL = readURL let encoding = textEncoding let textSaver = textSaver let fileContentChangeCoordinator = fileContentChangeCoordinator @@ -1781,14 +1928,14 @@ struct FilePreviewPanelView: View { PanelHeaderIconButton( systemName: "arrow.counterclockwise", label: String(localized: "filePreview.revert", defaultValue: "Revert"), - isDisabled: !panel.isDirty, + isDisabled: panel.isReadOnly || !panel.isDirty, action: { panel.loadTextContent() } ) PanelHeaderIconButton( systemName: "square.and.arrow.down", label: String(localized: "filePreview.save", defaultValue: "Save"), - isDisabled: !panel.isDirty || panel.isSaving, + isDisabled: panel.isReadOnly || !panel.isDirty || panel.isSaving, action: { panel.saveTextContent() } ) } @@ -1799,7 +1946,10 @@ struct FilePreviewPanelView: View { action: { panel.reloadFromDisk() } ) - FileExternalOpenMenu(fileURL: panel.fileURL, isDisabled: panel.isFileUnavailable) + FileExternalOpenMenu( + fileURL: panel.fileURL, + isDisabled: panel.isFileUnavailable || panel.isReadOnly + ) } } diff --git a/Sources/Panels/FilePreviewQuickLookSession.swift b/Sources/Panels/FilePreviewQuickLookSession.swift index fd076a08a86e..c4216ec5bb48 100644 --- a/Sources/Panels/FilePreviewQuickLookSession.swift +++ b/Sources/Panels/FilePreviewQuickLookSession.swift @@ -103,7 +103,7 @@ final class FilePreviewQuickLookSession { let previewView = container.livePreviewView() { panel.attachPreviewFocus(root: container, primaryResponder: previewView, intent: .quickLook) updatePreviewItem( - for: panel.fileURL, + for: panel.readURL, title: panel.displayTitle, revision: revision ) diff --git a/Sources/Panels/FilePreviewTextEditor.swift b/Sources/Panels/FilePreviewTextEditor.swift index d0d6d1ee8a71..e34b52fe12d9 100644 --- a/Sources/Panels/FilePreviewTextEditor.swift +++ b/Sources/Panels/FilePreviewTextEditor.swift @@ -8,6 +8,7 @@ import SwiftUI @MainActor protocol FilePreviewTextEditingPanel: AnyObject { var textContent: String { get } + var isReadOnly: Bool { get } var textContentRevision: Int { get } func attachTextView(_ textView: NSTextView) @@ -68,6 +69,7 @@ struct FilePreviewTextEditor: NSViewRepresentable where PanelModel: } textView.drawsBackground = drawsBackground textView.string = panel.textContent + textView.isEditable = !panel.isReadOnly context.coordinator.lastAppliedContentRevision = panel.textContentRevision context.coordinator.isHighlightingVisible = isVisibleInUI panel.attachTextView(textView) @@ -119,6 +121,7 @@ struct FilePreviewTextEditor: NSViewRepresentable where PanelModel: context.coordinator.panel = panel context.coordinator.panelIdentity = panelIdentity textView.panel = panel + textView.isEditable = !panel.isReadOnly textView.applyFilePreviewTextEditorInsets() textView.applyFilePreviewWordWrap(wordWrap, scrollView: scrollView) panel.attachTextView(textView) diff --git a/Sources/Panels/FilePreviewWorkspaceOpenSupport.swift b/Sources/Panels/FilePreviewWorkspaceOpenSupport.swift index dd18599d79b1..68ca439ca0ed 100644 --- a/Sources/Panels/FilePreviewWorkspaceOpenSupport.swift +++ b/Sources/Panels/FilePreviewWorkspaceOpenSupport.swift @@ -2,6 +2,64 @@ import Bonsplit import Foundation extension Workspace { + /// Opens an artifact through its already-validated descriptor. The panel + /// retains that descriptor and reads `/dev/fd`, so a pathname replacement + /// cannot redirect the preview after this method returns. + @discardableResult + func openArtifactFileSurface( + inPane paneId: PaneID, + file: ArtifactSidebarFileAccess.OpenedFile, + focus: Bool = true, + reuseExisting: Bool = false + ) -> (any Panel)? { + let filePath = file.sourceURL.path + if reuseExisting { + let canonical = (filePath as NSString).resolvingSymlinksInPath + for (existingID, panel) in panels { + let existingPath: String? + if let markdown = panel as? MarkdownPanel { + existingPath = markdown.filePath + } else if let preview = panel as? FilePreviewPanel { + existingPath = preview.filePath + } else { + existingPath = nil + } + let isArtifactBacked: Bool + if let markdown = panel as? MarkdownPanel { + isArtifactBacked = markdown.isReadOnly + } else if let preview = panel as? FilePreviewPanel { + isArtifactBacked = preview.isReadOnly + } else { + isArtifactBacked = false + } + guard isArtifactBacked, + let existingPath, + (existingPath as NSString).resolvingSymlinksInPath == canonical else { + continue + } + if focus { + focusPanel(existingID) + } + return panel + } + } + + if MarkdownPanelFileLinkResolver.isMarkdownPathLike(filePath) { + return newMarkdownSurface( + inPane: paneId, + filePath: filePath, + focus: focus, + artifactFile: file + ) + } + return newFilePreviewSurface( + inPane: paneId, + filePath: filePath, + focus: focus, + artifactFile: file + ) + } + @discardableResult func openFileSurfaces( inPane paneId: PaneID, diff --git a/Sources/Panels/MarkdownPanel.swift b/Sources/Panels/MarkdownPanel.swift index dbda38de8916..c76ed5c2453a 100644 --- a/Sources/Panels/MarkdownPanel.swift +++ b/Sources/Panels/MarkdownPanel.swift @@ -1,6 +1,7 @@ import AppKit import CmuxBrowser import CmuxFoundation +import CmuxArtifacts import Combine import Foundation @@ -21,6 +22,12 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel /// Absolute path to the markdown file being displayed. let filePath: String + private var artifactFile: ArtifactSidebarFileAccess.OpenedFile? + private var artifactReadCopyURL: URL? + private var artifactPreviewTask: Task? + private var artifactPreviewToken = UUID() + private var artifactContentTask: Task? + private var artifactContentToken = UUID() /// The workspace this panel belongs to. private(set) var workspaceId: UUID @@ -49,6 +56,16 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel /// Whether the file has been deleted or is unreadable. @Published private(set) var isFileUnavailable: Bool = false + /// Whether this panel is backed by a descriptor-protected artifact read. + var isReadOnly: Bool { + artifactFile != nil + } + + /// Root used to confine relative images and links in an artifact preview. + var artifactResourceRoot: URL? { + artifactFile?.artifactRoot + } + /// Token incremented to trigger focus flash animation. @Published private(set) var focusFlashToken: Int = 0 @@ -145,6 +162,7 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel workspaceId: UUID, filePath: String, fontSize: Double? = nil, + artifactFile: ArtifactSidebarFileAccess.OpenedFile? = nil, fileContentChangeCoordinator: FileContentChangeCoordinator? = nil, textLoader: @escaping @Sendable (URL) async -> FilePreviewTextLoader.Result = { url in await FilePreviewTextLoader.load( @@ -160,6 +178,10 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel self.id = UUID() self.workspaceId = workspaceId self.filePath = filePath + self.artifactFile = artifactFile + self.artifactReadCopyURL = nil + self.artifactPreviewTask = nil + self.artifactContentTask = nil self.fontSize = MarkdownFontSizeSettings.clamp(fontSize ?? defaultSize) self.fontFamily = defaultFamily self.maxContentWidth = defaultMaxWidth @@ -171,15 +193,19 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel self.fileContentChangeCoordinator = fileContentChangeCoordinator ?? FileContentChangeCoordinator() - // Initial disk hydration must not overwrite edits made while a large - // file is loading; explicit reload/revert paths retain the destructive - // default through `loadTextContent(replacingDirtyContent:)`. - // Seed the observation fingerprint before registration so the - // coordinator's initial reconciliation does not enqueue a duplicate - // full-file read when the file has not changed. - lastObservedFileState = .capture(path: filePath) - _ = loadFileContent(replacingDirtyContent: false) - startWatchingForFileChanges() + if artifactFile == nil { + // Initial disk hydration must not overwrite edits made while a + // large file is loading; explicit reload/revert paths retain the + // destructive default through `loadTextContent(replacingDirtyContent:)`. + // Seed the observation fingerprint before registration so the + // coordinator's initial reconciliation does not enqueue a duplicate + // full-file read when the file has not changed. + lastObservedFileState = .capture(path: filePath) + _ = loadFileContent(replacingDirtyContent: false) + startWatchingForFileChanges() + } else { + startArtifactPreviewLoad() + } observeTypographyDefaults() rendererSession.onMarkdownRendered = { [weak self] in self?.replayPendingPreviewFocusAfterWindowAttach() @@ -263,6 +289,130 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel executeFindSearch(state.needle) } + @discardableResult + private func startArtifactPreviewLoad(force: Bool = false) -> Task? { + let artifactRoot = artifactFile?.artifactRoot + if force { + artifactPreviewToken = UUID() + artifactPreviewTask?.cancel() + artifactPreviewTask = nil + artifactContentToken = UUID() + artifactContentTask?.cancel() + artifactContentTask = nil + if let artifactReadCopyURL { + try? FileManager.default.removeItem(at: artifactReadCopyURL) + self.artifactReadCopyURL = nil + } + guard artifactRoot != nil else { + isFileUnavailable = true + return nil + } + } + guard let artifactFile, artifactPreviewTask == nil else { return artifactPreviewTask } + let token = artifactPreviewToken + let sourcePath = filePath + let task = Task { @MainActor [weak self, artifactFile, artifactRoot, force] in + let fileForPreview: ArtifactSidebarFileAccess.OpenedFile? + if force { + guard let artifactRoot else { + if let self, self.artifactPreviewToken == token { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + } + return + } + fileForPreview = await ArtifactSidebarFileAccess().openedFileAsync( + for: URL(fileURLWithPath: sourcePath), + artifactRoot: artifactRoot + ) + guard let self, + self.artifactPreviewToken == token else { + return + } + guard let fileForPreview else { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + return + } + self.artifactFile = fileForPreview + } else { + fileForPreview = artifactFile + } + guard let fileForPreview else { + if let self, self.artifactPreviewToken == token { + self.artifactPreviewTask = nil + self.isFileUnavailable = true + } + return + } + let temporaryURL = await fileForPreview.makeTemporaryPreviewURLAsync( + maximumBytes: Int64(FilePreviewTextLoader.maximumLoadedTextBytes) + ) + guard let self else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + guard self.artifactPreviewToken == token else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + guard !self.isClosed else { + if let temporaryURL { + try? FileManager.default.removeItem(at: temporaryURL) + } + return + } + self.artifactPreviewTask = nil + guard let temporaryURL else { + self.isFileUnavailable = true + return + } + self.artifactReadCopyURL = temporaryURL + _ = self.startArtifactContentLoad() + } + artifactPreviewTask = task + return task + } + + /// Loads a materialized artifact copy through the concurrent text-loader + /// seam, then publishes the bounded result back on this main-actor panel. + @discardableResult + private func startArtifactContentLoad( + replacingDirtyContent: Bool = true + ) -> Task? { + artifactContentTask?.cancel() + artifactContentTask = nil + artifactContentToken = UUID() + guard let artifactReadCopyURL else { + isFileUnavailable = true + return nil + } + let readURL = artifactReadCopyURL + let contentToken = artifactContentToken + let task = Task { @MainActor [weak self, readURL, contentToken, replacingDirtyContent] in + let result = await FilePreviewTextLoader.load( + url: readURL, + maximumBytes: FilePreviewTextLoader.maximumLoadedTextBytes + ) + guard let self, + !Task.isCancelled, + !self.isClosed, + self.artifactContentToken == contentToken, + self.artifactReadCopyURL == readURL else { return } + self.artifactContentTask = nil + self.applyFileLoadResult( + result, + replacingDirtyContent: replacingDirtyContent + ) + } + artifactContentTask = task + return task + } + /// Adopt a changed typography default (from another viewer's "Set as Default" /// or a `cmux.json` reload), but only while this viewer still matches the /// default it was tracking — i.e. the user has not customized it. @@ -411,6 +561,12 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel func close() { unfocus() isClosed = true + artifactPreviewToken = UUID() + artifactPreviewTask?.cancel() + artifactPreviewTask = nil + artifactContentToken = UUID() + artifactContentTask?.cancel() + artifactContentTask = nil pendingPreviewFocus = false searchState = nil rendererSession.close() @@ -418,6 +574,10 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel selectionReader.close() GlobalSearchCoordinator.shared.purgePanel(id: id) textView = nil + if let artifactReadCopyURL { + try? FileManager.default.removeItem(at: artifactReadCopyURL) + self.artifactReadCopyURL = nil + } stopWatchingForFileChanges() if let typographyDefaultsObserver { NotificationCenter.default.removeObserver(typographyDefaultsObserver) @@ -477,7 +637,10 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel /// Re-reads the file without discarding an unsaved TextEdit buffer. @discardableResult func reloadFromDisk() -> Task { - loadFileContent(replacingDirtyContent: false) + if artifactFile != nil { + return startArtifactPreviewLoad(force: true) ?? Task {} + } + return loadFileContent(replacingDirtyContent: false) } func attachTextView(_ textView: NSTextView) { @@ -512,6 +675,7 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel @discardableResult func saveTextContent() -> Task? { + guard !isReadOnly else { return nil } guard !isSaving else { return nil } let currentContent = textView?.string ?? textContent guard currentContent != originalTextContent else { @@ -578,6 +742,9 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel replacingDirtyContent: Bool = true, isStaleReadRetry: Bool = false ) -> Task { + if artifactFile != nil { + return startArtifactContentLoad(replacingDirtyContent: replacingDirtyContent) ?? Task {} + } if !isStaleReadRetry { staleReadRetryCount = 0 } @@ -671,6 +838,55 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel GlobalSearchCoordinator.shared.captureMarkdownPanel(self) } + private func applyFileLoadResult( + _ result: FilePreviewTextLoader.Result, + replacingDirtyContent: Bool + ) { + switch result { + case .loaded(let newContent, let encoding): + applyLoadedContent( + newContent, + encoding: encoding, + replacingDirtyContent: replacingDirtyContent + ) + case .unavailable: + guard replacingDirtyContent || !isDirty else { + isFileUnavailable = true + GlobalSearchCoordinator.shared.captureMarkdownPanel(self) + return + } + content = "" + textContent = "" + originalTextContent = "" + isDirty = false + isFileUnavailable = true + GlobalSearchCoordinator.shared.captureMarkdownPanel(self) + } + } + + private func applyLoadedContent( + _ newContent: String, + encoding: String.Encoding, + replacingDirtyContent: Bool + ) { + if !replacingDirtyContent && isDirty { + originalTextContent = newContent + textEncoding = encoding + isDirty = textContent != newContent + isFileUnavailable = false + GlobalSearchCoordinator.shared.captureMarkdownPanel(self) + return + } + + content = newContent + textContent = newContent + originalTextContent = newContent + textEncoding = encoding + isDirty = false + isFileUnavailable = false + GlobalSearchCoordinator.shared.captureMarkdownPanel(self) + } + private func applyPendingSearchNeedleIfPossible() { guard let needle = pendingSearchNeedle, let textView else { @@ -701,6 +917,8 @@ final class MarkdownPanel: Panel, ObservableObject, FilePreviewTextEditingPanel } deinit { + artifactPreviewTask?.cancel() + artifactContentTask?.cancel() if let typographyDefaultsObserver { NotificationCenter.default.removeObserver(typographyDefaultsObserver) } diff --git a/Sources/Panels/MarkdownPanelView.swift b/Sources/Panels/MarkdownPanelView.swift index 831aeac29b7c..62514d244e32 100644 --- a/Sources/Panels/MarkdownPanelView.swift +++ b/Sources/Panels/MarkdownPanelView.swift @@ -81,6 +81,7 @@ struct MarkdownPanelView: View { panelId: panel.id, workspaceId: panel.workspaceId, filePath: panel.filePath, + allowedLocalResourceRoot: panel.artifactResourceRoot, fontSize: panel.fontSize, fontFamily: panel.fontFamily, maxContentWidth: panel.maxContentWidth, @@ -136,14 +137,14 @@ struct MarkdownPanelView: View { PanelHeaderIconButton( systemName: "arrow.counterclockwise", label: String(localized: "markdown.toolbar.revert", defaultValue: "Revert"), - isDisabled: !panel.isDirty, + isDisabled: panel.isReadOnly || !panel.isDirty, action: { panel.loadTextContent() } ) PanelHeaderIconButton( systemName: "square.and.arrow.down", label: String(localized: "markdown.toolbar.save", defaultValue: "Save"), - isDisabled: !panel.isDirty || panel.isSaving, + isDisabled: panel.isReadOnly || !panel.isDirty || panel.isSaving, action: { panel.saveTextContent() } ) } @@ -163,7 +164,7 @@ struct MarkdownPanelView: View { ) FileExternalOpenMenu( fileURL: URL(fileURLWithPath: panel.filePath), - isDisabled: panel.isFileUnavailable + isDisabled: panel.isFileUnavailable || panel.isReadOnly ) } } diff --git a/Sources/Panels/MarkdownWebRenderer.swift b/Sources/Panels/MarkdownWebRenderer.swift index fa59369e8676..e3dc402df650 100644 --- a/Sources/Panels/MarkdownWebRenderer.swift +++ b/Sources/Panels/MarkdownWebRenderer.swift @@ -14,6 +14,7 @@ struct MarkdownWebRenderer: NSViewRepresentable { let panelId: UUID let workspaceId: UUID let filePath: String + let allowedLocalResourceRoot: URL? /// Body font size in points, applied as `pageZoom` and to shell-managed SVG zoom. let fontSize: Double /// Body prose font-family name (empty = System). Applied as an inline @@ -29,7 +30,12 @@ struct MarkdownWebRenderer: NSViewRepresentable { var onViewAttachedToWindow: () -> Void = {} func makeCoordinator() -> Coordinator { - session.coordinator(panelId: panelId, workspaceId: workspaceId, filePath: filePath) + session.coordinator( + panelId: panelId, + workspaceId: workspaceId, + filePath: filePath, + allowedLocalResourceRoot: allowedLocalResourceRoot + ) } func makeNSView(context: Context) -> WKWebView { @@ -107,7 +113,12 @@ struct MarkdownWebRenderer: NSViewRepresentable { func updateNSView(_ nsView: WKWebView, context: Context) { // Re-bind panel metadata in case SwiftUI recreated the wrapper while // the panel-owned renderer session kept the same coordinator. - context.coordinator.bind(panelId: panelId, workspaceId: workspaceId, filePath: filePath) + context.coordinator.bind( + panelId: panelId, + workspaceId: workspaceId, + filePath: filePath, + allowedLocalResourceRoot: allowedLocalResourceRoot + ) (nsView as? MarkdownWebView)?.onPointerDown = onRequestPanelFocus (nsView as? MarkdownWebView)?.setVisibleInUI(isVisibleInUI) applyBackground(to: nsView) @@ -160,6 +171,7 @@ struct MarkdownWebRenderer: NSViewRepresentable { var panelId: UUID = UUID() var workspaceId: UUID = UUID() var filePath: String = "" + var allowedLocalResourceRoot: URL? private var pendingMarkdown: String = "" private var pendingTheme: MarkdownWebTheme = .resolve(backgroundColor: GhosttyBackgroundTheme.currentColor()) private var lastMarkdown: String? = nil @@ -205,10 +217,16 @@ struct MarkdownWebRenderer: NSViewRepresentable { } #endif - func bind(panelId: UUID, workspaceId: UUID, filePath: String) { + func bind( + panelId: UUID, + workspaceId: UUID, + filePath: String, + allowedLocalResourceRoot: URL? = nil + ) { self.panelId = panelId self.workspaceId = workspaceId self.filePath = filePath + self.allowedLocalResourceRoot = allowedLocalResourceRoot } /// Records the desired body font size and applies it as `pageZoom`. @@ -558,12 +576,44 @@ struct MarkdownWebRenderer: NSViewRepresentable { let fileURL = localImageFileURL(from: requestURL) let mimeType = fileURL .flatMap { Self.localImageMimeType(for: $0.pathExtension) } ?? "image/png" + if let fileURL, + let allowedLocalResourceRoot { + return Task { @MainActor in + // Descriptor validation and the bounded staging copy + // both run behind the async utility seam. Never open, + // stat, or resolve an artifact path synchronously on + // the main actor while WebKit is requesting images. + guard let temporaryURL = await ArtifactSidebarFileAccess() + .makeTemporaryPreviewURLAsync( + for: fileURL, + artifactRoot: allowedLocalResourceRoot, + maximumBytes: 8 * 1024 * 1024 + ) else { + return ImageLoadResult(data: Data(), mimeType: mimeType) + } + guard !Task.isCancelled else { + try? FileManager.default.removeItem(at: temporaryURL) + return ImageLoadResult(data: Data(), mimeType: mimeType) + } + defer { + try? FileManager.default.removeItem(at: temporaryURL) + } + return await Task.detached(priority: .userInitiated) { + guard FileManager.default.isReadableFile(atPath: temporaryURL.path) else { + return ImageLoadResult(data: Data(), mimeType: mimeType) + } + let data = (try? Data(contentsOf: temporaryURL)) ?? Data() + return ImageLoadResult(data: data, mimeType: mimeType) + }.value + } + } + let loadURL = allowedLocalResourceRoot == nil ? fileURL : nil return Task.detached(priority: .userInitiated) { - guard let fileURL, - FileManager.default.isReadableFile(atPath: fileURL.path) else { + guard let loadURL, + FileManager.default.isReadableFile(atPath: loadURL.path) else { return ImageLoadResult(data: Data(), mimeType: mimeType) } - let data = (try? Data(contentsOf: fileURL)) ?? Data() + let data = (try? Data(contentsOf: loadURL)) ?? Data() return ImageLoadResult(data: data, mimeType: mimeType) } } @@ -598,6 +648,17 @@ struct MarkdownWebRenderer: NSViewRepresentable { return nil } + // Artifact roots are validated by `makeTemporaryPreviewURLAsync`, + // which opens the descriptor and resolves containment off-main. Keep + // this parser branch filesystem-free so a WebKit image request never + // performs synchronous artifact I/O on the main actor. + if allowedLocalResourceRoot != nil { + guard Self.localImageMimeType(for: fileURL.pathExtension) != nil else { + return nil + } + return fileURL + } + let markdownDirectory = URL(fileURLWithPath: markdownFilePath) .deletingLastPathComponent() .standardizedFileURL @@ -606,9 +667,11 @@ struct MarkdownWebRenderer: NSViewRepresentable { return nil } - let markdownRoot = markdownDirectory.path.hasSuffix("/") - ? markdownDirectory.path - : markdownDirectory.path + "/" + let resourceRoot = allowedLocalResourceRoot?.resolvingSymlinksInPath() + .standardizedFileURL ?? markdownDirectory + let markdownRoot = resourceRoot.path.hasSuffix("/") + ? resourceRoot.path + : resourceRoot.path + "/" let standardizedURL = fileURL .standardizedFileURL .resolvingSymlinksInPath() @@ -660,6 +723,9 @@ struct MarkdownWebRenderer: NSViewRepresentable { } private func openMarkdownFile(_ path: String) { + // Artifact previews are intentionally read-only and do not open + // mutable relative documents through the pathname-based route. + guard allowedLocalResourceRoot == nil else { return } #if DEBUG NSLog("MarkdownPanel.openMarkdownFile path=\(path)") #endif diff --git a/Sources/Panels/MarkdownWebSupport.swift b/Sources/Panels/MarkdownWebSupport.swift index da7b53634cb5..2d5ca83e5734 100644 --- a/Sources/Panels/MarkdownWebSupport.swift +++ b/Sources/Panels/MarkdownWebSupport.swift @@ -445,9 +445,15 @@ final class MarkdownRendererSession { func coordinator( panelId: UUID, workspaceId: UUID, - filePath: String + filePath: String, + allowedLocalResourceRoot: URL? = nil ) -> MarkdownWebRenderer.Coordinator { - ownedCoordinator.bind(panelId: panelId, workspaceId: workspaceId, filePath: filePath) + ownedCoordinator.bind( + panelId: panelId, + workspaceId: workspaceId, + filePath: filePath, + allowedLocalResourceRoot: allowedLocalResourceRoot + ) return ownedCoordinator } diff --git a/Sources/RightSidebarDisclosureAction.swift b/Sources/RightSidebarDisclosureAction.swift new file mode 100644 index 000000000000..12f26da7d2e4 --- /dev/null +++ b/Sources/RightSidebarDisclosureAction.swift @@ -0,0 +1,5 @@ +/// A tree disclosure command produced by right-sidebar keyboard navigation. +enum RightSidebarDisclosureAction { + case collapse + case expand +} diff --git a/Sources/RightSidebarKeyboardFocusBridge.swift b/Sources/RightSidebarKeyboardFocusBridge.swift new file mode 100644 index 000000000000..60cc0aeab946 --- /dev/null +++ b/Sources/RightSidebarKeyboardFocusBridge.swift @@ -0,0 +1,12 @@ +import AppKit +import SwiftUI + +struct RightSidebarKeyboardFocusBridge: NSViewRepresentable { + func makeNSView(context: Context) -> RightSidebarKeyboardFocusView { + RightSidebarKeyboardFocusView(frame: NSRect(x: 0, y: 0, width: 1, height: 1)) + } + + func updateNSView(_ nsView: RightSidebarKeyboardFocusView, context: Context) { + nsView.registerWithKeyboardFocusCoordinatorIfNeeded() + } +} diff --git a/Sources/RightSidebarKeyboardFocusView.swift b/Sources/RightSidebarKeyboardFocusView.swift new file mode 100644 index 000000000000..48371da6813a --- /dev/null +++ b/Sources/RightSidebarKeyboardFocusView.swift @@ -0,0 +1,74 @@ +import AppKit +import Bonsplit + +final class RightSidebarKeyboardFocusView: NSView { + override var acceptsFirstResponder: Bool { true } + override var canBecomeKeyView: Bool { true } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard let window else { return } + AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerRightSidebarHost(self) +#if DEBUG + dlog( + "rs.focus.host.attach win=\(window.windowNumber) canAccept=\(cmuxCanAcceptRightSidebarKeyboardFocus ? 1 : 0) " + + "fr=\(Self.responderTypeDescription(window.firstResponder))" + ) +#endif + } + + func registerWithKeyboardFocusCoordinatorIfNeeded() { + guard let window else { return } + AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerRightSidebarHost(self) + } + + override func layout() { + super.layout() + registerWithKeyboardFocusCoordinatorIfNeeded() + } + + override func keyDown(with event: NSEvent) { + if let mode = AppDelegate.shared?.rightSidebarModeShortcut(for: event) { + _ = AppDelegate.shared?.focusRightSidebarInActiveMainWindow( + mode: mode, + focusFirstItem: true, + preferredWindow: window + ) + return + } + if event.keyCode == 53 { + if let window, + AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.focusTerminal() == true { + return + } + window?.makeFirstResponder(nil) + return + } + if let characters = event.charactersIgnoringModifiers, !characters.isEmpty { + return + } + super.keyDown(with: event) + } + + func focusHostFromCoordinator() -> Bool { + guard let window else { +#if DEBUG + dlog("rs.focus.host.focus result=0 reason=noWindow") +#endif + return false + } + let result = window.makeFirstResponder(self) +#if DEBUG + dlog( + "rs.focus.host.focus result=\(result ? 1 : 0) win=\(window.windowNumber) " + + "fr=\(Self.responderTypeDescription(window.firstResponder))" + ) +#endif + return result + } + + private static func responderTypeDescription(_ responder: NSResponder?) -> String { + guard let responder else { return "nil" } + return String(describing: type(of: responder)) + } +} diff --git a/Sources/RightSidebarMode+Availability.swift b/Sources/RightSidebarMode+Availability.swift index f8f7ab1947ff..a4ea5d1526c7 100644 --- a/Sources/RightSidebarMode+Availability.swift +++ b/Sources/RightSidebarMode+Availability.swift @@ -10,6 +10,8 @@ extension RightSidebarMode { return .find case "vault", "sessions": return .sessions + case "artifacts": + return .artifacts case "feed": return .feed case "dock": @@ -25,15 +27,22 @@ extension RightSidebarMode { static func availableModes(defaults: UserDefaults = .standard) -> [RightSidebarMode] { availableModes( + artifactsEnabled: RightSidebarBetaFeatureSettings.isArtifactsEnabled(defaults: defaults), feedEnabled: RightSidebarBetaFeatureSettings.isFeedEnabled(defaults: defaults), dockEnabled: RightSidebarBetaFeatureSettings.isDockEnabled(defaults: defaults), machinesEnabled: CloudMachinesFeature.offMainIsEnabled(defaults: defaults) ) } - static func availableModes(feedEnabled: Bool, dockEnabled: Bool, machinesEnabled: Bool) -> [RightSidebarMode] { + static func availableModes( + artifactsEnabled: Bool, + feedEnabled: Bool, + dockEnabled: Bool, + machinesEnabled: Bool + ) -> [RightSidebarMode] { allCases.filter { $0.isAvailable( + artifactsEnabled: artifactsEnabled, feedEnabled: feedEnabled, dockEnabled: dockEnabled, machinesEnabled: machinesEnabled @@ -41,8 +50,24 @@ extension RightSidebarMode { } } + /// Preserves the Cloud sidebar availability API for callers that do not + /// participate in the Artifacts beta gate. + static func availableModes( + feedEnabled: Bool, + dockEnabled: Bool, + machinesEnabled: Bool + ) -> [RightSidebarMode] { + availableModes( + artifactsEnabled: false, + feedEnabled: feedEnabled, + dockEnabled: dockEnabled, + machinesEnabled: machinesEnabled + ) + } + func isAvailable(defaults: UserDefaults = .standard) -> Bool { isAvailable( + artifactsEnabled: RightSidebarBetaFeatureSettings.isArtifactsEnabled(defaults: defaults), feedEnabled: RightSidebarBetaFeatureSettings.isFeedEnabled(defaults: defaults), dockEnabled: RightSidebarBetaFeatureSettings.isDockEnabled(defaults: defaults), machinesEnabled: CloudMachinesFeature.offMainIsEnabled(defaults: defaults) @@ -75,10 +100,17 @@ extension RightSidebarMode { return index + 1 } - func isAvailable(feedEnabled: Bool, dockEnabled: Bool, machinesEnabled: Bool) -> Bool { + func isAvailable( + artifactsEnabled: Bool, + feedEnabled: Bool, + dockEnabled: Bool, + machinesEnabled: Bool + ) -> Bool { switch self { case .files, .find, .sessions: return true + case .artifacts: + return artifactsEnabled case .feed: return feedEnabled case .dock: @@ -93,6 +125,21 @@ extension RightSidebarMode { && FileExplorerState.persistedCustomSidebarName() != nil } } + + /// Preserves the Cloud sidebar availability API for callers that do not + /// participate in the Artifacts beta gate. + func isAvailable( + feedEnabled: Bool, + dockEnabled: Bool, + machinesEnabled: Bool + ) -> Bool { + isAvailable( + artifactsEnabled: false, + feedEnabled: feedEnabled, + dockEnabled: dockEnabled, + machinesEnabled: machinesEnabled + ) + } } enum RightSidebarKeyboardNavigation { diff --git a/Sources/RightSidebarMode.swift b/Sources/RightSidebarMode.swift new file mode 100644 index 000000000000..48f44de13e4c --- /dev/null +++ b/Sources/RightSidebarMode.swift @@ -0,0 +1,82 @@ +import AppKit + +/// Mode shown in the right sidebar (the panel toggled by ⌘⌥B). +enum RightSidebarMode: String, CaseIterable, Codable, Sendable { + case files + case find + case sessions + case artifacts + case feed + case dock + case machines + case customSidebar = "custom-sidebar" + + var label: String { + switch self { + case .files: return String(localized: "rightSidebar.mode.files", defaultValue: "Files") + case .find: return String(localized: "rightSidebar.mode.find", defaultValue: "Find") + case .sessions: return String(localized: "rightSidebar.mode.sessions", defaultValue: "Vault") + case .artifacts: + return String( + localized: "rightSidebar.mode.artifacts", + defaultValue: "Artifacts & Notes" + ) + case .feed: return String(localized: "rightSidebar.mode.feed", defaultValue: "Feed") + case .dock: return String(localized: "rightSidebar.mode.dock", defaultValue: "Dock") + case .machines: return String(localized: "rightSidebar.mode.machines", defaultValue: "Cloud") + case .customSidebar: return String(localized: "rightSidebar.mode.customSidebar", defaultValue: "Custom") + } + } + + var symbolName: String { + switch self { + case .files: return "folder" + case .find: return "magnifyingglass" + case .sessions: return "books.vertical" + case .artifacts: return "shippingbox" + case .feed: return "dot.radiowaves.left.and.right" + case .dock: return "dock.rectangle" + case .machines: return "cloud" + case .customSidebar: return "wand.and.stars" + } + } + + var shortcutAction: KeyboardShortcutSettings.Action? { + switch self { + case .files: return .switchRightSidebarToFiles + case .find: return .switchRightSidebarToFind + case .sessions: return .switchRightSidebarToSessions + case .feed: return .switchRightSidebarToFeed + case .dock: return .switchRightSidebarToDock + case .machines: return .switchRightSidebarToMachines + case .artifacts, .customSidebar: return nil + } + } + + static let paneModes: [RightSidebarMode] = [.files, .find, .sessions] + + var canOpenAsPane: Bool { + Self.paneModes.contains(self) + } + + static func modeShortcut(for event: NSEvent) -> RightSidebarMode? { + modeShortcut(for: event, allowingAction: { _ in true }) + } + + static func modeShortcut( + for event: NSEvent, + allowingAction: (KeyboardShortcutSettings.Action) -> Bool + ) -> RightSidebarMode? { + guard event.type == .keyDown else { return nil } + for mode in RightSidebarMode.allCases { + guard let action = mode.shortcutAction, + allowingAction(action), + mode.isAvailable(), + KeyboardShortcutSettings.shortcut(for: action).matches(event: event) else { + continue + } + return mode + } + return nil + } +} diff --git a/Sources/RightSidebarPanelView.swift b/Sources/RightSidebarPanelView.swift index 609c0f9de977..9e27abc7a55f 100644 --- a/Sources/RightSidebarPanelView.swift +++ b/Sources/RightSidebarPanelView.swift @@ -2,6 +2,7 @@ import AppKit import Bonsplit import CMUXAgentLaunch import CmuxAppKitSupportUI +import CmuxArtifacts import CmuxFoundation import CmuxSettings import CmuxSettingsUI @@ -12,67 +13,6 @@ import CmuxSwiftRenderUI import SwiftUI import UniformTypeIdentifiers -private func rightSidebarDebugResponder(_ responder: NSResponder?) -> String { - guard let responder else { return "nil" } - return String(describing: type(of: responder)) -} - -/// Mode shown in the right sidebar (the panel toggled by ⌘⌥B). -enum RightSidebarMode: String, CaseIterable, Codable, Sendable { - case files - case find - case sessions - case feed - case dock - case machines - case customSidebar = "custom-sidebar" - - var label: String { - switch self { - case .files: return String(localized: "rightSidebar.mode.files", defaultValue: "Files") - case .find: return String(localized: "rightSidebar.mode.find", defaultValue: "Find") - case .sessions: return String(localized: "rightSidebar.mode.sessions", defaultValue: "Vault") - case .feed: return String(localized: "rightSidebar.mode.feed", defaultValue: "Feed") - case .dock: return String(localized: "rightSidebar.mode.dock", defaultValue: "Dock") - case .machines: return String(localized: "rightSidebar.mode.machines", defaultValue: "Cloud") - case .customSidebar: return String(localized: "rightSidebar.mode.customSidebar", defaultValue: "Custom") - } - } - - - var symbolName: String { - switch self { - case .files: return "folder" - case .find: return "magnifyingglass" - case .sessions: return "books.vertical" - case .feed: return "dot.radiowaves.left.and.right" - case .dock: return "dock.rectangle" - case .machines: return "cloud" - case .customSidebar: return "wand.and.stars" - } - } - - var shortcutAction: KeyboardShortcutSettings.Action? { - switch self { - case .files: return .switchRightSidebarToFiles - case .find: return .switchRightSidebarToFind - case .sessions: return .switchRightSidebarToSessions - case .feed: return .switchRightSidebarToFeed - case .dock: return .switchRightSidebarToDock - case .machines: return .switchRightSidebarToMachines - case .customSidebar: return nil - } - } -} - -extension RightSidebarMode { - static let paneModes: [RightSidebarMode] = [.files, .find, .sessions] - - var canOpenAsPane: Bool { - Self.paneModes.contains(self) - } -} - enum RightSidebarContentMountPolicy { static func shouldMountContent(isRightSidebarVisible: Bool, hasMountedContent: Bool) -> Bool { isRightSidebarVisible || hasMountedContent @@ -85,47 +25,27 @@ enum FileExplorerRootSyncPolicy { switch mode { case .files, .find: return true - case .sessions, .feed, .dock, .machines, .customSidebar: + case .sessions, .artifacts, .feed, .dock, .machines, .customSidebar: return false } } } -extension RightSidebarMode { - static func modeShortcut(for event: NSEvent) -> RightSidebarMode? { - modeShortcut(for: event, allowingAction: { _ in true }) - } - - static func modeShortcut( - for event: NSEvent, - allowingAction: (KeyboardShortcutSettings.Action) -> Bool - ) -> RightSidebarMode? { - guard event.type == .keyDown else { return nil } - for mode in RightSidebarMode.allCases { - guard let action = mode.shortcutAction, - allowingAction(action), - mode.isAvailable(), - KeyboardShortcutSettings.shortcut(for: action).matches(event: event) else { - continue - } - return mode - } - return nil - } -} - /// Right sidebar root view. Hosts a segmented mode picker plus the active panel. struct RightSidebarPanelView: View { @ObservedObject var tabManager: TabManager @ObservedObject var fileExplorerStore: FileExplorerStore @ObservedObject var fileExplorerState: FileExplorerState @ObservedObject var sessionIndexStore: SessionIndexStore + let featureFlags: CmuxFeatureFlags let titlebarHeight: CGFloat let windowAppearance: WindowAppearanceSnapshot let workspaceId: UUID? + let artifactWorkspace: ArtifactSidebarWorkspace? let onResumeSession: ((SessionEntry) -> Void)? let onOpenSession: ((SessionEntry) -> Void)? let onOpenFilePreview: (String) -> Void + let onOpenArtifact: (ArtifactSidebarRowSnapshot) -> Void let onOpenAsPane: (RightSidebarMode) -> Void let onClose: () -> Void /// Live data context for the Custom mode's JS/Swift sidebar (built by the @@ -139,6 +59,7 @@ struct RightSidebarPanelView: View { @State private var focusShortcutHintMonitor = WindowScopedShortcutHintModifierMonitor(activation: .commandOnly) @State private var closeShortcutHintMonitor = WindowScopedShortcutHintModifierMonitor(activation: .commandOnly) @State private var hasMountedRightSidebarContent = false + @State private var artifactSidebarModel: ArtifactSidebarModel @State private var draggingModeBarMode: RightSidebarMode? @State private var keyboardShortcutSettingsObserver = KeyboardShortcutSettingsObserver.shared private let alwaysShowShortcutHints = ShortcutHintDebugSettings().alwaysShowHints @@ -151,6 +72,9 @@ struct RightSidebarPanelView: View { private var feedEnabled = RightSidebarBetaFeatureSettings.defaultFeedEnabled @AppStorage(RightSidebarBetaFeatureSettings.dockEnabledKey) private var dockEnabled = RightSidebarBetaFeatureSettings.defaultDockEnabled + @AppStorage(RightSidebarBetaFeatureSettings.artifactsEnabledKey) + private var artifactsEnabled = RightSidebarBetaFeatureSettings.defaultArtifactsEnabled + @AppStorage(RightSidebarBetaFeatureSettings.cloudMachinesEnabledKey) private var cloudMachinesBetaEnabled = RightSidebarBetaFeatureSettings.defaultCloudMachinesEnabled @LiveSetting(\.customSidebars.renderer) private var customSidebarRenderer @@ -160,6 +84,47 @@ struct RightSidebarPanelView: View { @State private var customSidebarWorkerClient: RenderWorkerClient? @State private var managedPolicyRevision = 0 + init( + tabManager: TabManager, + fileExplorerStore: FileExplorerStore, + fileExplorerState: FileExplorerState, + sessionIndexStore: SessionIndexStore, + featureFlags: CmuxFeatureFlags, + titlebarHeight: CGFloat, + windowAppearance: WindowAppearanceSnapshot, + workspaceId: UUID?, + artifactWorkspace: ArtifactSidebarWorkspace?, + artifactStore: any ArtifactStoring, + artifactCaptureService: any ArtifactCapturing, + onResumeSession: ((SessionEntry) -> Void)?, + onOpenSession: ((SessionEntry) -> Void)?, + onOpenFilePreview: @escaping (String) -> Void, + onOpenArtifact: @escaping (ArtifactSidebarRowSnapshot) -> Void, + onOpenAsPane: @escaping (RightSidebarMode) -> Void, + onClose: @escaping () -> Void, + customSidebarDataContext: @escaping (Date) -> [String: SwiftValue] + ) { + self.tabManager = tabManager + self.fileExplorerStore = fileExplorerStore + self.fileExplorerState = fileExplorerState + self.sessionIndexStore = sessionIndexStore + self.featureFlags = featureFlags + self.titlebarHeight = titlebarHeight + self.windowAppearance = windowAppearance + self.workspaceId = workspaceId + self.artifactWorkspace = artifactWorkspace + self.onResumeSession = onResumeSession + self.onOpenSession = onOpenSession + self.onOpenFilePreview = onOpenFilePreview + self.onOpenArtifact = onOpenArtifact + self.onOpenAsPane = onOpenAsPane + self.onClose = onClose + self.customSidebarDataContext = customSidebarDataContext + _artifactSidebarModel = State( + initialValue: ArtifactSidebarModel(store: artifactStore, captureService: artifactCaptureService) + ) + } + // Re-reading the observable store inside modeBar causes SwiftUI to // track the pending count so the badge updates live when hooks push // new items. @@ -170,6 +135,7 @@ struct RightSidebarPanelView: View { private var featureAvailableModes: [RightSidebarMode] { _ = managedPolicyRevision return RightSidebarMode.availableModes( + artifactsEnabled: artifactsEnabled && featureFlags.isArtifactsEnabled, feedEnabled: feedEnabled, dockEnabled: dockEnabled, machinesEnabled: CloudMachinesFeature.isEnabled @@ -267,6 +233,10 @@ struct RightSidebarPanelView: View { } .onChange(of: feedEnabled) { _, _ in refreshModeAvailabilityAndFocusIfNeeded() } .onChange(of: dockEnabled) { _, _ in refreshModeAvailabilityAndFocusIfNeeded() } + .onChange(of: artifactsEnabled) { _, _ in refreshModeAvailabilityAndFocusIfNeeded() } + .onChange(of: featureFlags.isArtifactsEnabled) { _, _ in + refreshModeAvailabilityAndFocusIfNeeded() + } .onChange(of: cloudMachinesBetaEnabled) { _, _ in refreshModeAvailabilityAndFocusIfNeeded() } .onReceive(NotificationCenter.default.publisher(for: RightSidebarTabPreferences.didChangeNotification)) { _ in refreshModeAvailabilityAndFocusIfNeeded() @@ -508,6 +478,14 @@ struct RightSidebarPanelView: View { .onAppear { sessionIndexStore.setCurrentDirectoryIfChanged(sessionIndexDirectory) } + case .artifacts: + ArtifactSidebarPanelView( + model: artifactSidebarModel, + workspace: artifactWorkspace, + isVisible: fileExplorerState.isVisible, + chromeBackgroundColor: windowAppearance.resolvedChromeBackgroundColor, + onOpenArtifact: onOpenArtifact + ) case .feed: FeedPanelView( chromeBackgroundColor: windowAppearance.resolvedChromeBackgroundColor @@ -628,95 +606,44 @@ struct RightSidebarPanelView: View { } } -private struct RightSidebarKeyboardFocusBridge: NSViewRepresentable { - func makeNSView(context: Context) -> RightSidebarKeyboardFocusView { - let view = RightSidebarKeyboardFocusView(frame: NSRect(x: 0, y: 0, width: 1, height: 1)) - return view - } - - func updateNSView(_ nsView: RightSidebarKeyboardFocusView, context: Context) { - nsView.registerWithKeyboardFocusCoordinatorIfNeeded() - } -} - -final class RightSidebarKeyboardFocusView: NSView { - override var acceptsFirstResponder: Bool { true } - override var canBecomeKeyView: Bool { true } - - override func viewDidMoveToWindow() { - super.viewDidMoveToWindow() - guard let window else { return } - AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerRightSidebarHost(self) -#if DEBUG - dlog( - "rs.focus.host.attach win=\(window.windowNumber) canAccept=\(cmuxCanAcceptRightSidebarKeyboardFocus ? 1 : 0) " + - "fr=\(rightSidebarDebugResponder(window.firstResponder))" - ) -#endif - } - - func registerWithKeyboardFocusCoordinatorIfNeeded() { - guard let window else { return } - AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerRightSidebarHost(self) - } - - override func layout() { - super.layout() - registerWithKeyboardFocusCoordinatorIfNeeded() - } - - override func keyDown(with event: NSEvent) { - if let mode = AppDelegate.shared?.rightSidebarModeShortcut(for: event) { - _ = AppDelegate.shared?.focusRightSidebarInActiveMainWindow( - mode: mode, - focusFirstItem: true, - preferredWindow: window - ) - return - } - if event.keyCode == 53 { - if let window, - AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.focusTerminal() == true { - return - } - window?.makeFirstResponder(nil) - return - } - if let characters = event.charactersIgnoringModifiers, !characters.isEmpty { - return - } - super.keyDown(with: event) - } - - func focusHostFromCoordinator() -> Bool { - guard let window else { -#if DEBUG - dlog("rs.focus.host.focus result=0 reason=noWindow") -#endif - return false - } - let result = window.makeFirstResponder(self) -#if DEBUG - dlog( - "rs.focus.host.focus result=\(result ? 1 : 0) win=\(window.windowNumber) " + - "fr=\(rightSidebarDebugResponder(window.firstResponder))" +extension RightSidebarPanelView { + /// Creates a sidebar for callers that do not supply an artifact workspace. + init( + tabManager: TabManager, + fileExplorerStore: FileExplorerStore, + fileExplorerState: FileExplorerState, + sessionIndexStore: SessionIndexStore, + titlebarHeight: CGFloat, + windowAppearance: WindowAppearanceSnapshot, + workspaceId: UUID?, + onResumeSession: ((SessionEntry) -> Void)?, + onOpenSession: ((SessionEntry) -> Void)? = nil, + onOpenFilePreview: @escaping (String) -> Void, + onOpenAsPane: @escaping (RightSidebarMode) -> Void, + onClose: @escaping () -> Void, + customSidebarDataContext: @escaping (Date) -> [String: SwiftValue] = { _ in [:] } + ) { + let artifactRepository = LocalArtifactRepository() + self.init( + tabManager: tabManager, + fileExplorerStore: fileExplorerStore, + fileExplorerState: fileExplorerState, + sessionIndexStore: sessionIndexStore, + featureFlags: .shared, + titlebarHeight: titlebarHeight, + windowAppearance: windowAppearance, + workspaceId: workspaceId, + artifactWorkspace: nil, + artifactStore: artifactRepository, + artifactCaptureService: ArtifactCaptureService(store: artifactRepository), + onResumeSession: onResumeSession, + onOpenSession: onOpenSession, + onOpenFilePreview: onOpenFilePreview, + onOpenArtifact: { _ in }, + onOpenAsPane: onOpenAsPane, + onClose: onClose, + customSidebarDataContext: customSidebarDataContext ) -#endif - return result - } -} - -extension NSView { - var cmuxCanAcceptRightSidebarKeyboardFocus: Bool { - guard window != nil, !isHiddenOrHasHiddenAncestor else { return false } - var view: NSView? = self - while let current = view { - if current.bounds.width <= 0.5 || current.bounds.height <= 0.5 { - return false - } - view = current.superview - } - return true } } diff --git a/Sources/RightSidebarRemoteCommand.swift b/Sources/RightSidebarRemoteCommand.swift index b6d163f5d43d..db7f30592f66 100644 --- a/Sources/RightSidebarRemoteCommand.swift +++ b/Sources/RightSidebarRemoteCommand.swift @@ -136,7 +136,7 @@ extension RightSidebarRemoteRequest { return .success(.init(command: .getState, target: target)) case "set": guard positional.count == 2 || positional.count == 3 else { - return .failure(.init(message: String(localized: "rightSidebar.remote.error.usage.set", defaultValue: "ERROR: Usage: right_sidebar set [sidebar-name] [--no-focus] [--workspace=] [--window=]"))) + return .failure(.init(message: String(localized: "rightSidebar.remote.error.usage.set", defaultValue: "ERROR: Usage: right_sidebar set [sidebar-name] [--no-focus] [--workspace=] [--window=]"))) } let rawMode = positional[1].trimmingCharacters(in: .whitespacesAndNewlines) if let mode = RightSidebarMode.from(cliArgument: rawMode) { @@ -147,7 +147,7 @@ extension RightSidebarRemoteRequest { return .success(.init(command: .setCustomSidebar(name: name, focus: !noFocus), target: target)) } guard positional.count == 2 else { - return .failure(.init(message: String(localized: "rightSidebar.remote.error.usage.set", defaultValue: "ERROR: Usage: right_sidebar set [sidebar-name] [--no-focus] [--workspace=] [--window=]"))) + return .failure(.init(message: String(localized: "rightSidebar.remote.error.usage.set", defaultValue: "ERROR: Usage: right_sidebar set [sidebar-name] [--no-focus] [--workspace=] [--window=]"))) } return .success(.init(command: .setMode(mode, focus: !noFocus), target: target)) } diff --git a/Sources/RightSidebarToolPanel.swift b/Sources/RightSidebarToolPanel.swift index 444ef2227f1a..d676ccea4614 100644 --- a/Sources/RightSidebarToolPanel.swift +++ b/Sources/RightSidebarToolPanel.swift @@ -83,7 +83,7 @@ final class RightSidebarToolPanel: Panel, ObservableObject { case .sessions: guard let store = sessionIndexStoreStorage else { return } syncSessionIndexRoot(from: workspace, store: store) - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: break } } @@ -143,7 +143,7 @@ final class RightSidebarToolPanel: Panel, ObservableObject { guard let anchor = sessionIndexFocusAnchorView, let window = anchor.window else { return } _ = window.makeFirstResponder(anchor) - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: break } } @@ -165,7 +165,7 @@ final class RightSidebarToolPanel: Panel, ObservableObject { case .sessions: guard sessionIndexFocusAnchorView?.ownsKeyboardFocus(responder) == true else { return nil } return .panel - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: return nil } } @@ -304,7 +304,7 @@ struct RightSidebarToolPanelView: View { RightSidebarToolFocusAnchor(onViewChange: panel.attachSessionIndexFocusAnchor) .frame(width: 0, height: 0) ) - case .feed, .dock, .machines, .customSidebar: + case .artifacts, .feed, .dock, .machines, .customSidebar: EmptyView() } } diff --git a/Sources/SettingsNavigation.swift b/Sources/SettingsNavigation.swift index e619aea0f25a..df9255ab05ad 100644 --- a/Sources/SettingsNavigation.swift +++ b/Sources/SettingsNavigation.swift @@ -456,6 +456,15 @@ enum SettingsSearchIndex { setting(.sidebarAppearance, "right-sidebar-tabs", String(localized: "settings.sidebar.rightTabs", defaultValue: "Right Sidebar Tabs"), "right sidebar tabs show hide reorder order files find vault feed dock cloud mode switcher customize"), setting(.customSidebars, "enabled", String(localized: "settings.customSidebars.enabled", defaultValue: "Show Custom Sidebars"), "custom sidebars enable show vibe swift json interpreted picker"), setting(.customSidebars, "renderer", String(localized: "settings.customSidebars.renderer", defaultValue: "Renderer"), "renderer in-process in app remote worker isolated process hover focus typing input"), + setting( + .betaFeatures, + "artifacts", + String( + localized: "settings.betaFeatures.artifacts", + defaultValue: "Artifacts & Notes" + ), + "artifacts notes capture files project local right sidebar agent output" + ), setting(.betaFeatures, "feed", String(localized: "settings.betaFeatures.feed", defaultValue: "Feed"), "feed right sidebar agent decisions permissions questions"), setting(.betaFeatures, "dock", String(localized: "settings.betaFeatures.dock", defaultValue: "Dock"), "dock right sidebar terminal controls tui"), setting(.betaFeatures, "cloudMachines", String(localized: "settings.betaFeatures.cloudMachines", defaultValue: "Cloud Machines"), "cloud machines vm right sidebar beta virtual machine persistent computer"), @@ -524,6 +533,7 @@ enum SettingsSearchIndex { ) private static let settingsPathAnchorIDs: [String: String] = [ + "rightSidebar.beta.artifacts.enabled": settingID(for: .betaFeatures, idSuffix: "artifacts"), "rightSidebar.beta.feed.enabled": settingID(for: .betaFeatures, idSuffix: "feed"), "rightSidebar.beta.dock.enabled": settingID(for: .betaFeatures, idSuffix: "dock"), "app.language": settingID(for: .app, idSuffix: "language"), diff --git a/Sources/SettingsSearchAliases.swift b/Sources/SettingsSearchAliases.swift index fa41a210d428..a78a48494a7c 100644 --- a/Sources/SettingsSearchAliases.swift +++ b/Sources/SettingsSearchAliases.swift @@ -24,7 +24,7 @@ enum SettingsSearchAliasIndex { case .customSidebars: return localized("settings.search.alias.section.customSidebars", defaultValue: "custom sidebars vibe code swift json interpreted renderer in-process remote worker isolated") case .betaFeatures: - return localized("settings.search.alias.section.betaFeatures", defaultValue: "beta experimental unstable preview feed dock right sidebar") + return localized("settings.search.alias.section.betaFeatures", defaultValue: "beta experimental unstable preview artifacts capture feed dock right sidebar") case .automation: return localized("settings.search.alias.section.automation", defaultValue: "api cli control socket mcp agents hooks ports") case .computerUse: @@ -143,6 +143,7 @@ enum SettingsSearchAliasIndex { "sidebarAppearance:notification-badge-position": localized("settings.search.alias.setting.app.notification-badge-position", defaultValue: "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace"), "sidebarAppearance:show-metadata": localized("settings.search.alias.setting.app.show-metadata", defaultValue: "sidebar.showCustomMetadata metadata meta report_meta status custom block"), "sidebarAppearance:right-max-width": localized("settings.search.alias.setting.sidebarAppearance.right-max-width", defaultValue: "sidebar.rightMaxWidth dock right sidebar max width terminal reservation cap logs lazygit"), + "betaFeatures:artifacts": localized("settings.search.alias.setting.betaFeatures.artifacts", defaultValue: "artifacts capture files project local right sidebar agent output beta unstable"), "betaFeatures:feed": localized("settings.search.alias.setting.betaFeatures.feed", defaultValue: "feed right sidebar agent decisions permissions questions approval beta unstable"), "betaFeatures:dock": localized("settings.search.alias.setting.betaFeatures.dock", defaultValue: "dock right sidebar terminal controls tui beta unstable"), "mobile:iOSPairingHost": localized("settings.search.alias.setting.mobile.iOSPairingHost", defaultValue: "ios iphone ipad mobile pairing local network permission sync"), diff --git a/Sources/TaskManagerTypes.swift b/Sources/TaskManagerTypes.swift index c63ff32a6676..207bc1ea0067 100644 --- a/Sources/TaskManagerTypes.swift +++ b/Sources/TaskManagerTypes.swift @@ -1,5 +1,4 @@ import Darwin -import CmuxTerminalCore import Foundation import SwiftUI @@ -465,195 +464,3 @@ enum CmuxTaskManagerFormat { timeFormatter.string(from: date) } } - -struct CmuxTaskManagerCodingAgentDefinition: Equatable, Sendable { - let id: String - let displayName: String - let assetName: String? - let launchKinds: [String] - let directBasenames: [String] - let argumentNeedles: [String] - let requiredArgumentPrefix: [String] - let promptTurnDetection: PromptLineTurnDetectionConfiguration? - - init( - id: String, - displayName: String, - assetName: String?, - launchKinds: [String], - directBasenames: [String], - argumentNeedles: [String], - requiredArgumentPrefix: [String] = [], - promptTurnDetection: PromptLineTurnDetectionConfiguration? = nil - ) { - self.id = id - self.displayName = displayName - self.assetName = assetName - self.launchKinds = launchKinds - self.directBasenames = directBasenames - self.argumentNeedles = argumentNeedles - self.requiredArgumentPrefix = requiredArgumentPrefix - self.promptTurnDetection = promptTurnDetection - } - - static func shouldReadArguments(processName: String, processPath: String?) -> Bool { - if let normalizedPath = normalized(processPath), - argumentInspectionPathNeedles.contains(where: { normalizedPath.contains($0) }) { - return true - } - - let basenames = candidateBasenames( - processName: processName, - processPath: processPath, - arguments: [] - ) - return basenames.contains { candidate in - argumentHostBasenames.contains(candidate) - || ambiguousDirectBasenames.contains(candidate) - || isVersionedExecutableBasename(candidate) - } - } - - static func matchingDefinition( - processName: String, - processPath: String?, - arguments: [String], - environment: [String: String] - ) -> CmuxTaskManagerCodingAgentDefinition? { - let definitions = builtIns - // The process's own executable identity outranks the launch-kind - // environment: CMUX_AGENT_LAUNCH_* is inherited by every descendant - // of the launched pane, so a later `ollama run` inside a pane that - // launched claude still carries CMUX_AGENT_LAUNCH_KIND=claude. The - // env var only identifies processes (wrappers, script hosts) whose - // executable matches no agent definition of its own. - let basenames = candidateBasenames( - processName: processName, - processPath: processPath, - arguments: arguments - ) - if let definition = definitions.first(where: { definition in - definition.matchesRequiredArguments(arguments) - && basenames.contains { definition.directBasenames.contains($0) } - }) { - return definition - } - - let launchKind = normalized(environment["CMUX_AGENT_LAUNCH_KIND"]) - if let launchKind, - let definition = definitions.first(where: { - $0.launchKinds.contains(launchKind) && $0.matchesRequiredArguments(arguments) - }) { - return definition - } - - guard !arguments.isEmpty else { return nil } - return definitions.first { definition in - definition.matchesRequiredArguments(arguments) - && definition.argumentNeedles.contains { needle in - arguments.contains { argumentMatchesNeedle(argument: $0, needle: needle) } - } - } - } - - private func matchesRequiredArguments(_ arguments: [String]) -> Bool { - guard !requiredArgumentPrefix.isEmpty else { return true } - let normalizedArguments = arguments.compactMap(Self.normalized) - let required = requiredArgumentPrefix.compactMap(Self.normalized) - guard normalizedArguments.count > required.count else { return false } - return Array(normalizedArguments.dropFirst().prefix(required.count)) == required - } - - private static let argumentHostBasenames: Set = [ - "node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "tsx", "ts-node" - ] - - private static let ambiguousDirectBasenames: Set = [ - "acli", "ollama" - ] - - private static let argumentInspectionPathNeedles = [ - "/.local/share/claude/versions/", - "/library/application support/claude/claude-code/", - ] - - private static func candidateBasenames( - processName: String, - processPath: String?, - arguments: [String] - ) -> Set { - var values = Set() - appendBasename(processName, to: &values) - if let processPath { - appendBasename(processPath, to: &values) - } - if let executable = arguments.first { - appendBasename(executable, to: &values) - } - return values - } - - private static func appendBasename(_ value: String, to values: inout Set) { - guard let normalized = normalized((value as NSString).lastPathComponent) else { return } - values.insert(normalized) - } - - private static func isVersionedExecutableBasename(_ value: String) -> Bool { - let parts = value.split(separator: ".", omittingEmptySubsequences: false) - guard (2...4).contains(parts.count) else { return false } - return parts.allSatisfy { part in - !part.isEmpty && part.unicodeScalars.allSatisfy { CharacterSet.decimalDigits.contains($0) } - } - } - - private static func argumentMatchesNeedle(argument: String, needle: String) -> Bool { - guard let normalizedArgument = normalized(argument), - let normalizedNeedle = normalized(needle) else { return false } - if normalizedNeedle.contains("/") { - return containsNeedleWithBoundaries(normalizedNeedle, in: normalizedArgument) - } - return argumentTokens(from: normalizedArgument).contains(normalizedNeedle) - } - - private static func containsNeedleWithBoundaries(_ needle: String, in value: String) -> Bool { - var searchRange = value.startIndex.. Bool { - guard let character else { return true } - return character.unicodeScalars.allSatisfy { scalar in - argumentBoundaryScalars.contains(scalar) - } - } - - private static func argumentTokens(from value: String) -> Set { - let tokens = value - .components(separatedBy: argumentTokenSeparators) - .filter { !$0.isEmpty } - return Set(tokens.flatMap { token in - let stem = (token as NSString).deletingPathExtension - return stem.isEmpty || stem == token ? [token] : [token, stem] - }) - } - - private static let argumentTokenSeparators = CharacterSet(charactersIn: "/\\ \t\r\n\u{0}:=?&#\"'`<>(),;[]{}") - - private static let argumentBoundaryScalars = CharacterSet(charactersIn: "/\\ \t\r\n\u{0}:=?&#\"'`<>(),;[]{}").union(.newlines) - - private static func normalized(_ value: String?) -> String? { - let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) - .lowercased() - return trimmed?.isEmpty == false ? trimmed : nil - } -} diff --git a/Sources/TerminalController+MobileChat.swift b/Sources/TerminalController+MobileChat.swift index a2860b0d09e2..f5be87a78b7d 100644 --- a/Sources/TerminalController+MobileChat.swift +++ b/Sources/TerminalController+MobileChat.swift @@ -34,6 +34,17 @@ extension TerminalController { params: [String: Any], executionContext: MobileHostRPCExecutionContext? = nil ) async -> V2CallResult { + if method.hasPrefix("mobile.chat.artifact."), + !CmuxFeatureFlags.offMainEffectiveValue(for: CmuxFeatureFlags.artifactsFlag) { + return .err( + code: "capability_disabled", + message: String( + localized: "mobile.chat.artifact.error.capabilityDisabled", + defaultValue: "Artifacts are disabled for this project." + ), + data: ["capability": "chat.artifact.v1"] + ) + } switch method { case "mobile.chat.sessions": return await v2MobileChatSessions(params: params) @@ -58,6 +69,8 @@ extension TerminalController { return await v2MobileChatArtifactThumbnail(params: params) case "mobile.chat.artifact.list": return await v2MobileChatArtifactList(params: params) + case "mobile.chat.artifact.save": + return await v2MobileChatArtifactSave(params: params) case "mobile.chat.artifact.gallery": return await v2MobileChatArtifactGallery(params: params) default: diff --git a/Sources/TerminalController+MobileChatArtifacts.swift b/Sources/TerminalController+MobileChatArtifacts.swift index 1d76d2934b3a..e6ab560fbff9 100644 --- a/Sources/TerminalController+MobileChatArtifacts.swift +++ b/Sources/TerminalController+MobileChatArtifacts.swift @@ -1,4 +1,5 @@ import CmuxAgentChat +import CmuxArtifacts import CmuxSettings import Foundation @@ -49,7 +50,10 @@ extension TerminalController { let pageSize = min(max(v2Int(params, "page_size") ?? 60, 1), 100) let query = v2RawString(params, "query") let includeDirectories = v2Bool(params, "include_directories") ?? false - let orderedItems = await TerminalControllerChatArtifactIndexProvider.ordering.ordered( + guard let service = agentChatTranscriptService else { + return mobileChatArtifactError(.notFound, path: "") + } + let orderedItems = await service.artifactGalleryOrderingCache.ordered( indexedSession.snapshot.artifacts, indexID: indexedSession.sessionID, generation: indexedSession.snapshot.generation @@ -84,19 +88,31 @@ extension TerminalController { guard let service = agentChatTranscriptService else { throw MobileChatArtifactIndexError.unavailable } - guard let record = service.sessionRecord(sessionID: sessionID) else { - throw MobileChatArtifactIndexError.sessionNotFound - } - guard let transcriptPath = service.resolver.transcriptPath(for: record) else { + let resolved: (record: AgentChatSessionRecord, path: String) + do { + guard let transcript = try await service.resolvedTranscript(sessionID: sessionID) else { + throw MobileChatArtifactIndexError.sessionNotFound + } + resolved = transcript + } catch let error as MobileChatArtifactIndexError { + throw error + } catch { throw MobileChatArtifactIndexError.sessionUnavailable } - let snapshot = try await TerminalControllerChatArtifactIndexProvider.shared.snapshot( - sessionID: record.sessionID, - agentKind: record.agentKind, - transcriptPath: transcriptPath, - workingDirectory: record.workingDirectory + let maximumFileBytes = await service.artifactCaptureCoordinator? + .maximumTranscriptScanBytes(for: resolved.record) + let snapshot = try await service.artifactIndex.snapshot( + sessionID: resolved.record.sessionID, + agentKind: resolved.record.agentKind, + transcriptPath: resolved.path, + workingDirectory: resolved.record.workingDirectory, + maximumFileBytes: maximumFileBytes ) - return (record.sessionID, snapshot) + if service.observesTranscriptsForAutomaticArtifactCapture, + maximumFileBytes != nil { + service.scheduleIndexedArtifactCapture(record: resolved.record, snapshot: snapshot) + } + return (resolved.record.sessionID, snapshot) } /// Returns the stat-filtered count for the gallery's default landing view. @@ -111,7 +127,8 @@ extension TerminalController { // the sweep is existence-only over the raw snapshot, runs off the // caller inside the cache actor, and concurrent misses on the same // (session, generation, filters) key share one computation. - await TerminalControllerChatArtifactIndexProvider.rowCounts.total( + guard let service = agentChatTranscriptService else { return 0 } + return await service.artifactGalleryRowCountCache.total( sessionID: sessionID, generation: generation, includeDirectories: includeDirectories, @@ -127,15 +144,37 @@ extension TerminalController { } func v2MobileChatArtifactStat(params: [String: Any]) async -> V2CallResult { - let resolution = await mobileChatArtifactResolution(params: params, operation: .file) + let resolution = await mobileChatArtifactResolution(params: params, operation: .stat) guard case .success(let resolved) = resolution else { return resolution.failureResult } do { let stat = try await Task.detached { - try ArtifactByteReader().stat(path: resolved.canonicalPath) + try ArtifactByteReader().stat( + path: resolved.canonicalPath, + authorizedCanonicalPath: resolved.canonicalPath, + authorizedIdentity: resolved.authorizedIdentity + ) }.value - return ChatArtifactWire.result(stat) + let canSaveToArtifacts: Bool + if let context = resolved.authorizedCaptureContext, + let coordinator = agentChatTranscriptService?.artifactCaptureCoordinator { + canSaveToArtifacts = await coordinator.canSave( + context: context, + sourceURL: URL(fileURLWithPath: resolved.canonicalPath) + ) + } else { + canSaveToArtifacts = false + } + return ChatArtifactWire.result(ChatArtifactStat( + exists: stat.exists, + isDirectory: stat.isDirectory, + size: stat.size, + modifiedAt: stat.modifiedAt, + kind: stat.kind, + mimeType: stat.mimeType, + canSaveToArtifacts: canSaveToArtifacts + )) } catch let error as ArtifactByteReader.Error { return mobileArtifactReadFailure(error, path: resolved.requestedPath) } catch { @@ -171,12 +210,19 @@ extension TerminalController { } return ChatArtifactWire.result( try await executionContext.issueArtifactTransfer( - canonicalPath: resolved.canonicalPath + canonicalPath: resolved.canonicalPath, + authorizedIdentity: resolved.authorizedIdentity ) ) } let chunk = try await Task.detached { - try ArtifactByteReader().fetch(path: resolved.canonicalPath, offset: offset, length: length) + try ArtifactByteReader().fetch( + path: resolved.canonicalPath, + offset: offset, + length: length, + authorizedCanonicalPath: resolved.canonicalPath, + authorizedIdentity: resolved.authorizedIdentity + ) }.value return ChatArtifactWire.result(chunk) } catch let error as MobileHostIrohArtifactTransferRegistry.Error { @@ -220,7 +266,12 @@ extension TerminalController { let maxDimension = min(max(v2Int(params, "max_dimension") ?? 512, 64), 1024) do { let thumbnail = try await Task.detached { - try ArtifactByteReader().thumbnail(path: resolved.canonicalPath, maxDimension: maxDimension) + try ArtifactByteReader().thumbnail( + path: resolved.canonicalPath, + maxDimension: maxDimension, + authorizedCanonicalPath: resolved.canonicalPath, + authorizedIdentity: resolved.authorizedIdentity + ) }.value return ChatArtifactWire.result(thumbnail) } catch let error as ArtifactByteReader.Error { @@ -237,7 +288,11 @@ extension TerminalController { } do { let listing = try await Task.detached { - try ArtifactByteReader().list(path: resolved.canonicalPath) + try ArtifactByteReader().list( + path: resolved.canonicalPath, + authorizedCanonicalPath: resolved.canonicalPath, + authorizedIdentity: resolved.authorizedIdentity + ) }.value return ChatArtifactWire.result(listing) } catch let error as ArtifactByteReader.Error { @@ -250,26 +305,74 @@ extension TerminalController { } } - private enum ChatArtifactOperation { + func v2MobileChatArtifactSave(params: [String: Any]) async -> V2CallResult { + let resolution = await mobileChatArtifactResolution(params: params, operation: .save) + guard case .success(let resolved) = resolution else { + return resolution.failureResult + } + return await v2MobileChatArtifactSave(resolved: resolved) + } + + func v2MobileChatArtifactSave(resolved: ResolvedChatArtifact) async -> V2CallResult { + guard let service = agentChatTranscriptService else { + return mobileChatArtifactError(.notFound, path: resolved.requestedPath) + } + do { + guard let captureContext = resolved.authorizedCaptureContext else { + throw AgentArtifactCaptureSaveError.rejected + } + let result = try await service.saveArtifact( + context: captureContext, + sourceURL: URL(fileURLWithPath: resolved.canonicalPath, isDirectory: false), + expectedCanonicalPath: resolved.canonicalPath, + expectedIdentity: resolved.authorizedIdentity + ) + return ChatArtifactWire.result(result) + } catch { + return .err( + code: "artifact_save_failed", + message: String( + localized: "mobile.chat.artifact.error.saveFailed", + defaultValue: "The file could not be saved to this project’s Artifacts." + ), + data: ["path": resolved.requestedPath] + ) + } + } + + enum ChatArtifactOperation: Sendable { + case stat case file case list + case save var indexOperation: AgentChatArtifactIndex.Operation { switch self { - case .file: + case .stat, .file, .save: return .file case .list: return .list } } + + var resolvesCaptureProject: Bool { + switch self { + case .stat, .save: + return true + case .file, .list: + return false + } + } } - private struct ResolvedChatArtifact: Sendable { + struct ResolvedChatArtifact: Sendable { + let authorizedCaptureContext: ArtifactCaptureContext? let requestedPath: String let canonicalPath: String + let authorizedIdentity: ChatArtifactFileIdentity } - private enum ChatArtifactResolution { + enum ChatArtifactResolution { case success(ResolvedChatArtifact) case failure(V2CallResult) @@ -283,7 +386,7 @@ extension TerminalController { } } - private func mobileChatArtifactResolution( + func mobileChatArtifactResolution( params: [String: Any], operation: ChatArtifactOperation ) async -> ChatArtifactResolution { @@ -303,27 +406,48 @@ extension TerminalController { guard let service = agentChatTranscriptService else { return .failure(.err(code: "unavailable", message: Self.chatServiceUnavailableErrorMessage, data: nil)) } - guard let record = service.sessionRecord(sessionID: sessionID) else { - return .failure(mobileChatArtifactError(.notFound, path: requestedPath)) - } - guard let transcriptPath = service.resolver.transcriptPath(for: record) else { + let resolved: (record: AgentChatSessionRecord, path: String) + do { + guard let transcript = try await service.resolvedTranscript(sessionID: sessionID) else { + return .failure(mobileChatArtifactError(.notFound, path: requestedPath)) + } + resolved = transcript + } catch { return .failure(mobileChatArtifactError(.sessionUnavailable, path: requestedPath)) } do { - let pathResult = try await TerminalControllerChatArtifactIndexProvider.shared.canonicalPath( - sessionID: record.sessionID, - agentKind: record.agentKind, - transcriptPath: transcriptPath, - workingDirectory: record.workingDirectory, + let pathResult = try await service.artifactIndex.canonicalPath( + sessionID: resolved.record.sessionID, + agentKind: resolved.record.agentKind, + transcriptPath: resolved.path, + workingDirectory: resolved.record.workingDirectory, requestedPath: requestedPath, operation: operation.indexOperation, directoryAccessMode: mobileArtifactDirectoryAccessMode() ) switch pathResult { case .success(let canonicalPath): + let authorizedIdentity: ChatArtifactFileIdentity + do { + authorizedIdentity = try await Task.detached(priority: .utility) { + try ArtifactByteReader().identity( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath + ) + }.value + } catch let error as ArtifactByteReader.Error { + return .failure(mobileArtifactReadFailure(error, path: requestedPath)) + } catch { + return .failure(mobileArtifactReadFailure(.readFailed, path: requestedPath)) + } + let captureContext = operation.resolvesCaptureProject + ? await service.artifactCaptureContext(for: resolved.record) + : nil return .success(ResolvedChatArtifact( + authorizedCaptureContext: captureContext, requestedPath: requestedPath, - canonicalPath: canonicalPath + canonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity )) case .canonicalizationFailed: debugLogMobileChatArtifactDenial( diff --git a/Sources/TerminalController+MobileSurfaces.swift b/Sources/TerminalController+MobileSurfaces.swift index 8de9f6cecc06..bd3570d75b2a 100644 --- a/Sources/TerminalController+MobileSurfaces.swift +++ b/Sources/TerminalController+MobileSurfaces.swift @@ -199,13 +199,18 @@ extension TerminalController { } func v2MobilePanelArtifactStat(params: [String: Any]) async -> V2CallResult { - let resolution = mobilePanelArtifactCanonicalPath(params: params) - guard let canonicalPath = resolution.canonicalPath else { + let resolution = await mobilePanelArtifactCanonicalPath(params: params) + guard let canonicalPath = resolution.canonicalPath, + let authorizedIdentity = resolution.authorizedIdentity else { return resolution.failure ?? mobilePanelArtifactInternalError() } do { let stat = try await Task.detached(priority: .utility) { - try ArtifactByteReader().stat(path: canonicalPath) + try ArtifactByteReader().stat( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity + ) }.value return mobilePanelArtifactResult(stat) } catch ArtifactByteReader.Error.fileNotFound { @@ -236,8 +241,9 @@ extension TerminalController { params: [String: Any], executionContext: MobileHostRPCExecutionContext? = nil ) async -> V2CallResult { - let resolution = mobilePanelArtifactCanonicalPath(params: params) - guard let canonicalPath = resolution.canonicalPath else { + let resolution = await mobilePanelArtifactCanonicalPath(params: params) + guard let canonicalPath = resolution.canonicalPath, + let authorizedIdentity = resolution.authorizedIdentity else { return resolution.failure ?? mobilePanelArtifactInternalError() } let offset = max(0, Int64(v2Int(params, "offset") ?? 0)) @@ -255,7 +261,8 @@ extension TerminalController { } return mobilePanelArtifactResult( try await executionContext.issueArtifactTransfer( - canonicalPath: canonicalPath + canonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity ) ) } @@ -263,7 +270,9 @@ extension TerminalController { try ArtifactByteReader().fetch( path: canonicalPath, offset: offset, - length: length + length: length, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity ) }.value return mobilePanelArtifactResult(chunk) @@ -323,8 +332,9 @@ extension TerminalController { } func v2MobilePanelArtifactThumbnail(params: [String: Any]) async -> V2CallResult { - let resolution = mobilePanelArtifactCanonicalPath(params: params) - guard let canonicalPath = resolution.canonicalPath else { + let resolution = await mobilePanelArtifactCanonicalPath(params: params) + guard let canonicalPath = resolution.canonicalPath, + let authorizedIdentity = resolution.authorizedIdentity else { return resolution.failure ?? mobilePanelArtifactInternalError() } let maxDimension = min(max(v2Int(params, "max_dimension") ?? 512, 64), 1024) @@ -332,7 +342,9 @@ extension TerminalController { let thumbnail = try await Task.detached(priority: .utility) { try ArtifactByteReader().thumbnail( path: canonicalPath, - maxDimension: maxDimension + maxDimension: maxDimension, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: authorizedIdentity ) }.value return mobilePanelArtifactResult(thumbnail) @@ -355,11 +367,15 @@ extension TerminalController { private func mobilePanelArtifactCanonicalPath( params: [String: Any] - ) -> (canonicalPath: String?, failure: V2CallResult?) { + ) async -> ( + canonicalPath: String?, + authorizedIdentity: ChatArtifactFileIdentity?, + failure: V2CallResult? + ) { guard let requestedWorkspaceID = v2UUID(params, "workspace_id"), let requestedSurfaceID = v2UUID(params, "surface_id"), let requestedPath = mobileNonEmpty(v2RawString(params, "path")) else { - return (nil, .err( + return (nil, nil, .err( code: "invalid_params", message: String( localized: "mobile.panel.artifact.error.invalidParams", @@ -375,7 +391,7 @@ extension TerminalController { resolved.workspace.id == requestedWorkspaceID, resolvedSurfaceID == requestedSurfaceID, let panel = resolved.workspace.panels[resolvedSurfaceID] else { - return (nil, .err( + return (nil, nil, .err( code: "not_found", message: String( localized: "mobile.panel.artifact.error.panelNotFound", @@ -399,7 +415,7 @@ extension TerminalController { workspaceID: requestedWorkspaceID.uuidString, surfaceID: requestedSurfaceID.uuidString ) - return (nil, .err( + return (nil, nil, .err( code: "not_found", message: String( localized: "mobile.panel.artifact.error.panelNotFound", @@ -419,14 +435,14 @@ extension TerminalController { // canonicalization fails), but the phone must hear the accurate // story: the file is gone, not that access was denied. if !FileManager.default.fileExists(atPath: currentFilePath) { - return (nil, mobilePanelArtifactFileError( + return (nil, nil, mobilePanelArtifactFileError( code: "file_not_found", key: "mobile.chat.artifact.error.fileNotFound", defaultValue: "That file is no longer available on the Mac.", path: requestedPath )) } - return (nil, .err( + return (nil, nil, .err( code: "forbidden", message: String( localized: "mobile.panel.artifact.error.forbidden", @@ -435,7 +451,32 @@ extension TerminalController { data: ["path": requestedPath] )) } - return (canonicalPath, nil) + let authorizedIdentity: ChatArtifactFileIdentity + if let recordedIdentity = panelArtifactAuthorizationStore.authorizedIdentity( + workspaceID: requestedWorkspaceID.uuidString, + surfaceID: requestedSurfaceID.uuidString, + currentFilePath: currentFilePath, + requestedPath: requestedPath + ) { + authorizedIdentity = recordedIdentity + } else { + do { + authorizedIdentity = try await Task.detached(priority: .utility) { + try ArtifactByteReader().identity( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath + ) + }.value + } catch { + return (nil, nil, mobilePanelArtifactFileError( + code: "file_not_found", + key: "mobile.chat.artifact.error.fileNotFound", + defaultValue: "That file is no longer available on the Mac.", + path: requestedPath + )) + } + } + return (canonicalPath, authorizedIdentity, nil) } private func mobilePanelArtifactResult(_ value: T) -> V2CallResult { diff --git a/Sources/TerminalController+MobileTerminalArtifacts.swift b/Sources/TerminalController+MobileTerminalArtifacts.swift index 70d4d2aaaeb8..8c7184b6a1c2 100644 --- a/Sources/TerminalController+MobileTerminalArtifacts.swift +++ b/Sources/TerminalController+MobileTerminalArtifacts.swift @@ -89,7 +89,7 @@ extension TerminalController { return TerminalArtifactWire.result( TerminalArtifactScanResponse( artifacts: [], - galleryRowTotal: scanned.artifacts.count + galleryRowTotal: scanned.response.artifacts.count ) ) } @@ -119,13 +119,15 @@ extension TerminalController { ) } } - let response = await Task.detached(priority: .utility) { + let scanned = await Task.detached(priority: .utility) { context.scan(includeDirectories: includeDirectories) }.value + let response = scanned.response await terminalArtifactAuthorizationStore.record( workspaceID: context.workspaceID, surfaceID: context.surfaceID, - canonicalPaths: Set(response.artifacts.map(\.path)) + canonicalPaths: Set(response.artifacts.map(\.path)), + identities: scanned.identities ) return TerminalArtifactWire.result(response) } @@ -139,8 +141,12 @@ extension TerminalController { let outcome = try await Task.detached(priority: .utility) { do { return TerminalArtifactStatOutcome.success( - try context.authorizedStat { reader, canonicalPath in - try reader.stat(path: canonicalPath) + try context.authorizedStat { reader, canonicalPath, identity in + try reader.stat( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: identity + ) } ) } catch TerminalArtifactReadContext.Error.forbidden { @@ -193,18 +199,27 @@ extension TerminalController { data: nil ) } - let canonicalPath = try await Task.detached(priority: .utility) { - try context.authorizedRead { _, canonicalPath in canonicalPath } + let authorizedPath = try await Task.detached(priority: .utility) { + try context.authorizedRead { _, canonicalPath, identity in + (canonicalPath, identity) + } }.value return TerminalArtifactWire.result( try await executionContext.issueArtifactTransfer( - canonicalPath: canonicalPath + canonicalPath: authorizedPath.0, + authorizedIdentity: authorizedPath.1 ) ) } let chunk = try await Task.detached(priority: .utility) { - try context.authorizedRead { reader, canonicalPath in - try reader.fetch(path: canonicalPath, offset: offset, length: length) + try context.authorizedRead { reader, canonicalPath, identity in + try reader.fetch( + path: canonicalPath, + offset: offset, + length: length, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: identity + ) } }.value return TerminalArtifactWire.result(chunk) @@ -239,8 +254,13 @@ extension TerminalController { let maxDimension = min(max(v2Int(params, "max_dimension") ?? 512, 64), 1024) do { let thumbnail = try await Task.detached(priority: .utility) { - try context.authorizedRead { reader, canonicalPath in - try reader.thumbnail(path: canonicalPath, maxDimension: maxDimension) + try context.authorizedRead { reader, canonicalPath, identity in + try reader.thumbnail( + path: canonicalPath, + maxDimension: maxDimension, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: identity + ) } }.value return TerminalArtifactWire.result(thumbnail) @@ -261,8 +281,12 @@ extension TerminalController { } do { let listing = try await Task.detached(priority: .utility) { - try context.authorizedDirectoryList { reader, canonicalPath in - try reader.list(path: canonicalPath) + try context.authorizedDirectoryList { reader, canonicalPath, identity in + try reader.list( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath, + authorizedIdentity: identity + ) } }.value return TerminalArtifactWire.result(listing) @@ -302,6 +326,12 @@ extension TerminalController { surfaceID: surfaceID ) : [] + let scanAuthorizedIdentities = requiresPath + ? await terminalArtifactAuthorizationStore.authorizedIdentities( + workspaceID: workspaceID, + surfaceID: surfaceID + ) + : [:] let directoryAccessMode = mobileArtifactDirectoryAccessMode() return v2MainSync { () -> TerminalArtifactContextResolution in guard let resolved = mobileCanonicalTerminalTarget(params: params) else { @@ -344,6 +374,7 @@ extension TerminalController { requestedPath: v2RawString(params, "path"), sessionID: sessionID, scanAuthorizedPaths: scanAuthorizedPaths, + scanAuthorizedIdentities: scanAuthorizedIdentities, directoryAccessMode: directoryAccessMode )) } @@ -448,6 +479,7 @@ private struct TerminalArtifactReadContext: Sendable { let requestedPath: String? let sessionID: String? private let scanAuthorizedPaths: Set + private let scanAuthorizedIdentities: [String: ChatArtifactFileIdentity] private let directoryAccessMode: ChatArtifactScope.DirectoryAccessMode init( @@ -458,6 +490,7 @@ private struct TerminalArtifactReadContext: Sendable { requestedPath: String?, sessionID: String?, scanAuthorizedPaths: Set, + scanAuthorizedIdentities: [String: ChatArtifactFileIdentity], directoryAccessMode: ChatArtifactScope.DirectoryAccessMode ) { self.workspaceID = workspaceID @@ -467,10 +500,13 @@ private struct TerminalArtifactReadContext: Sendable { self.requestedPath = requestedPath self.sessionID = sessionID self.scanAuthorizedPaths = scanAuthorizedPaths + self.scanAuthorizedIdentities = scanAuthorizedIdentities self.directoryAccessMode = directoryAccessMode } - func scan(includeDirectories: Bool) -> TerminalArtifactScanResponse { + func scan( + includeDirectories: Bool + ) -> (response: TerminalArtifactScanResponse, identities: [String: ChatArtifactFileIdentity]) { let reader = ArtifactByteReader() let scope = TerminalArtifactScope( terminalText: terminalText, @@ -478,9 +514,16 @@ private struct TerminalArtifactReadContext: Sendable { resolver: ChatArtifactScope.FoundationResolver(), directoryAccessMode: directoryAccessMode ) + var identities: [String: ChatArtifactFileIdentity] = [:] let artifacts = scope.artifactPaths(limit: 200).compactMap { path -> TerminalArtifactReference? in guard let stat = try? reader.stat(path: path) else { return nil } guard includeDirectories || !stat.isDirectory else { return nil } + if let identity = try? reader.identity( + path: path, + authorizedCanonicalPath: path + ) { + identities[path] = identity + } return TerminalArtifactReference( path: path, kind: stat.kind, @@ -489,11 +532,14 @@ private struct TerminalArtifactReadContext: Sendable { modifiedAt: stat.modifiedAt ) } - return TerminalArtifactScanResponse(artifacts: artifacts, sessionID: sessionID) + return ( + TerminalArtifactScanResponse(artifacts: artifacts, sessionID: sessionID), + identities + ) } func authorizedRead( - _ operation: (ArtifactByteReader, String) throws -> T + _ operation: (ArtifactByteReader, String, ChatArtifactFileIdentity) throws -> T ) throws -> T { guard let requestedPath else { throw Error.forbidden } let resolver = ChatArtifactScope.FoundationResolver() @@ -503,7 +549,11 @@ private struct TerminalArtifactReadContext: Sendable { resolver: resolver ) if let canonicalPath = snapshotScope.canonicalFilePath(for: requestedPath) { - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity( + for: canonicalPath, + requireStored: scanAuthorizedPaths.contains(canonicalPath) + ) + return try operation(ArtifactByteReader(), canonicalPath, identity) } let scope = TerminalArtifactScope( terminalText: terminalText, @@ -514,13 +564,14 @@ private struct TerminalArtifactReadContext: Sendable { guard let canonicalPath = scope.canonicalPath(for: requestedPath) else { throw Error.forbidden } - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity(for: canonicalPath) + return try operation(ArtifactByteReader(), canonicalPath, identity) } /// Stat may be answered for any path the scope would let the client list, /// because listing already reveals more than the directory's own metadata. func authorizedStat( - _ operation: (ArtifactByteReader, String) throws -> T + _ operation: (ArtifactByteReader, String, ChatArtifactFileIdentity) throws -> T ) throws -> T { guard let requestedPath else { throw Error.forbidden } let resolver = ChatArtifactScope.FoundationResolver() @@ -530,10 +581,18 @@ private struct TerminalArtifactReadContext: Sendable { resolver: resolver ) if let canonicalPath = snapshotScope.canonicalFilePath(for: requestedPath) { - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity( + for: canonicalPath, + requireStored: scanAuthorizedPaths.contains(canonicalPath) + ) + return try operation(ArtifactByteReader(), canonicalPath, identity) } if let canonicalPath = snapshotScope.canonicalDirectoryListPath(for: requestedPath) { - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity( + for: canonicalPath, + requireStored: scanAuthorizedPaths.contains(canonicalPath) + ) + return try operation(ArtifactByteReader(), canonicalPath, identity) } let scope = TerminalArtifactScope( terminalText: terminalText, @@ -542,12 +601,14 @@ private struct TerminalArtifactReadContext: Sendable { directoryAccessMode: directoryAccessMode ) if let canonicalPath = scope.canonicalPath(for: requestedPath) { - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity(for: canonicalPath) + return try operation(ArtifactByteReader(), canonicalPath, identity) } guard let canonicalPath = scope.canonicalDirectoryListPath(for: requestedPath) else { throw Error.forbidden } - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity(for: canonicalPath) + return try operation(ArtifactByteReader(), canonicalPath, identity) } /// Explains why a stat authorization denied, for the DEBUG denial log. @@ -580,7 +641,7 @@ private struct TerminalArtifactReadContext: Sendable { } func authorizedDirectoryList( - _ operation: (ArtifactByteReader, String) throws -> T + _ operation: (ArtifactByteReader, String, ChatArtifactFileIdentity) throws -> T ) throws -> T { guard let requestedPath else { throw Error.forbidden } let resolver = ChatArtifactScope.FoundationResolver() @@ -590,7 +651,11 @@ private struct TerminalArtifactReadContext: Sendable { resolver: resolver ) if let canonicalPath = snapshotScope.canonicalDirectoryListPath(for: requestedPath) { - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity( + for: canonicalPath, + requireStored: scanAuthorizedPaths.contains(canonicalPath) + ) + return try operation(ArtifactByteReader(), canonicalPath, identity) } let scope = TerminalArtifactScope( terminalText: terminalText, @@ -601,7 +666,22 @@ private struct TerminalArtifactReadContext: Sendable { guard let canonicalPath = scope.canonicalDirectoryListPath(for: requestedPath) else { throw Error.forbidden } - return try operation(ArtifactByteReader(), canonicalPath) + let identity = try authorizedIdentity(for: canonicalPath) + return try operation(ArtifactByteReader(), canonicalPath, identity) + } + + private func authorizedIdentity( + for canonicalPath: String, + requireStored: Bool = false + ) throws -> ChatArtifactFileIdentity { + if let identity = scanAuthorizedIdentities[canonicalPath] { + return identity + } + guard !requireStored else { throw Error.forbidden } + return try ArtifactByteReader().identity( + path: canonicalPath, + authorizedCanonicalPath: canonicalPath + ) } } diff --git a/Sources/TerminalNotificationPolicyAgentContext.swift b/Sources/TerminalNotificationPolicyAgentContext.swift index 42500828df81..513bc61cd770 100644 --- a/Sources/TerminalNotificationPolicyAgentContext.swift +++ b/Sources/TerminalNotificationPolicyAgentContext.swift @@ -32,4 +32,3 @@ struct TerminalNotificationPolicyAgentContext: Codable, Sendable, Equatable { self.sessionId = sessionId } } - diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 27ed88bb2c10..d54b93dd9e2a 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2602,6 +2602,7 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos enum BrowserPanelCreationPolicy { case userInitiated case automationPreload + case artifactPreview case restoration /// Config-driven layout application (`cmux.json` layouts, saved /// layouts, `cmux layout`). Unlike `.restoration`, applying a layout @@ -2614,12 +2615,17 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos /// (it re-materializes pre-existing panes); an MDM-managed disable is /// checked separately and refuses every path. var permitsCreationWhenBrowserDisabled: Bool { - self == .restoration + self == .restoration || self == .artifactPreview } var preloadsInitialNavigationInBackground: Bool { self == .automationPreload } + + func contentMode(initialURL: URL?) -> BrowserPanelContentMode { + guard self == .artifactPreview, let initialURL else { return .standard } + return .artifactHTMLPreview(documentURL: initialURL) + } } static let terminalScrollBarHiddenDidChangeNotification = Notification.Name( @@ -9742,6 +9748,7 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, + contentMode: creationPolicy.contentMode(initialURL: url), websiteDataStore: websiteDataStore ) configureBrowserPanel(browserPanel) @@ -9863,6 +9870,7 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, + contentMode: creationPolicy.contentMode(initialURL: url), websiteDataStore: websiteDataStore ) configureBrowserPanel(browserPanel) @@ -10085,7 +10093,8 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos inPane paneId: PaneID, filePath: String, focus: Bool? = nil, - targetIndex: Int? = nil + targetIndex: Int? = nil, + artifactFile: ArtifactSidebarFileAccess.OpenedFile? = nil ) -> MarkdownPanel? { guard !isRetiredFromOwningTabManager else { return nil } let shouldFocusNewTab = focus ?? (bonsplitController.focusedPaneId == paneId) @@ -10095,6 +10104,7 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos let markdownPanel = MarkdownPanel( workspaceId: id, filePath: filePath, + artifactFile: artifactFile, fileContentChangeCoordinator: fileContentChangeCoordinator ) panels[markdownPanel.id] = markdownPanel @@ -10341,7 +10351,8 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos inPane paneId: PaneID, filePath: String, focus: Bool? = nil, - targetIndex: Int? = nil + targetIndex: Int? = nil, + artifactFile: ArtifactSidebarFileAccess.OpenedFile? = nil ) -> FilePreviewPanel? { guard !isRetiredFromOwningTabManager else { return nil } let shouldFocusNewTab = focus ?? (bonsplitController.focusedPaneId == paneId) @@ -10351,6 +10362,7 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos let filePreviewPanel = FilePreviewPanel( workspaceId: id, filePath: filePath, + artifactFile: artifactFile, fileContentChangeCoordinator: fileContentChangeCoordinator ) panels[filePreviewPanel.id] = filePreviewPanel @@ -10836,6 +10848,10 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos pendingClosedBrowserRestoreSnapshots.removeValue(forKey: tab.id) return } + guard browserPanel.contentMode.allowsSessionPersistence else { + pendingClosedBrowserRestoreSnapshots.removeValue(forKey: tab.id) + return + } let fallbackPlan = browserCloseFallbackPlan( forPaneId: pane.id.uuidString, diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index f7387c54bc3f..f1232d1940e7 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -17,8 +17,19 @@ A5C017000000000000000007 /* AccountSignInView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5C017000000000000000008 /* AccountSignInView.swift */; }; A9E020000000000000000006 /* agent-session-react in Resources */ = {isa = PBXBuildFile; fileRef = A9E010000000000000000006 /* agent-session-react */; }; A9E020000000000000000007 /* agent-session-solid in Resources */ = {isa = PBXBuildFile; fileRef = A9E010000000000000000007 /* agent-session-solid */; }; + A85870000000000000000053 /* AgentArtifactAutomaticPathBoundTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000052 /* AgentArtifactAutomaticPathBoundTests.swift */; }; + A8587000000000000000004B /* AgentArtifactCaptureCheckpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000004A /* AgentArtifactCaptureCheckpoint.swift */; }; + A85870000000000000000021 /* AgentArtifactCaptureCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000020 /* AgentArtifactCaptureCoordinator.swift */; }; + A85870000000000000000049 /* AgentArtifactCaptureCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000048 /* AgentArtifactCaptureCoordinatorTests.swift */; }; + A85870000000000000000063 /* AgentArtifactCaptureCoordinatorTestStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000062 /* AgentArtifactCaptureCoordinatorTestStore.swift */; }; + A8587000000000000000006F /* AgentArtifactCaptureProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000006E /* AgentArtifactCaptureProgress.swift */; }; + A85870000000000000000045 /* AgentArtifactCaptureSaveError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000044 /* AgentArtifactCaptureSaveError.swift */; }; + A8610D000000000000000001 /* AgentArtifactCompletedCaptureState.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D000000000000000002 /* AgentArtifactCompletedCaptureState.swift */; }; + C7A858700000000000000002 /* AgentArtifactProjectAuthorityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A858700000000000000001 /* AgentArtifactProjectAuthorityTests.swift */; }; + A8587000000000000000002B /* AgentArtifactReferenceCursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000002A /* AgentArtifactReferenceCursor.swift */; }; C7AF10000000000000000005 /* AgentChatArtifactGalleryBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7AF10000000000000000006 /* AgentChatArtifactGalleryBuilder.swift */; }; C7AF10000000000000000001 /* AgentChatArtifactIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7AF10000000000000000002 /* AgentChatArtifactIndex.swift */; }; + A8587000000000000000004D /* AgentChatArtifactIndexSafetyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000004C /* AgentChatArtifactIndexSafetyTests.swift */; }; 5FAC71D5AC71D5AC71D50001 /* AgentChatChildRunTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FAC71D5AC71D5AC71D50002 /* AgentChatChildRunTests.swift */; }; C7A52E000000000000000002 /* AgentChatEndedTranscriptListabilityCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A52E000000000000000001 /* AgentChatEndedTranscriptListabilityCache.swift */; }; C7A53F000000000000000002 /* AgentChatFallbackTranscriptResolutionCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A53F000000000000000001 /* AgentChatFallbackTranscriptResolutionCoordinator.swift */; }; @@ -27,7 +38,9 @@ C7A531000000000000000002 /* AgentChatObservationHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A531000000000000000001 /* AgentChatObservationHandle.swift */; }; C7A532000000000000000002 /* AgentChatObservationInFlight.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A532000000000000000001 /* AgentChatObservationInFlight.swift */; }; C7A530000000000000000002 /* AgentChatObservationScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A530000000000000000001 /* AgentChatObservationScope.swift */; }; + C7A85870000000000000000A /* AgentChatObservedWorkingDirectoryResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A858700000000000000009 /* AgentChatObservedWorkingDirectoryResolver.swift */; }; 99230001992300019923000C /* AgentChatResumeIntentRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99230001992300019923000B /* AgentChatResumeIntentRecorder.swift */; }; + A8587F000000000000000031 /* AgentChatSessionRecencyIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587F000000000000000030 /* AgentChatSessionRecencyIndex.swift */; }; ACA7C4A70000000000000001 /* AgentChatSessionRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A70000000000000002 /* AgentChatSessionRecord.swift */; }; C7A52D100000000000000012 /* AgentChatSessionRegistry+ChildRuns.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A52D100000000000000011 /* AgentChatSessionRegistry+ChildRuns.swift */; }; C8711A000000000000000002 /* AgentChatSessionRegistry+CodexRolloutFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8711A000000000000000001 /* AgentChatSessionRegistry+CodexRolloutFiles.swift */; }; @@ -42,12 +55,24 @@ C7A51D100000000000000002 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A51D100000000000000001 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift */; }; C7A51D000000000000000002 /* AgentChatSessionRegistryObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A51D000000000000000001 /* AgentChatSessionRegistryObservationTests.swift */; }; C0DE71A00000000000000001 /* AgentChatThemeSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE71A00000000000000002 /* AgentChatThemeSync.swift */; }; + A8587F000000000000000032 /* AgentChatTranscriptBoundedLineIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587F000000000000000033 /* AgentChatTranscriptBoundedLineIterator.swift */; }; + A8587F000000000000000034 /* AgentChatTranscriptBoundedLineSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587F000000000000000035 /* AgentChatTranscriptBoundedLineSequence.swift */; }; + A8610B000000000000000002 /* AgentChatTranscriptIncrementalLineBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610B000000000000000001 /* AgentChatTranscriptIncrementalLineBuffer.swift */; }; + C7A858700000000000000006 /* AgentChatTranscriptInitialTailReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A858700000000000000005 /* AgentChatTranscriptInitialTailReader.swift */; }; + A8610D000000000000000003 /* AgentChatTranscriptInitialTailSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D000000000000000004 /* AgentChatTranscriptInitialTailSnapshot.swift */; }; + A8587F000000000000000011 /* AgentChatTranscriptReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587F000000000000000010 /* AgentChatTranscriptReader.swift */; }; + C7A85870000000000000000B /* AgentChatTranscriptResolutionReviewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A85870000000000000000C /* AgentChatTranscriptResolutionReviewTests.swift */; }; ACA7C4A70000000000000005 /* AgentChatTranscriptResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A70000000000000006 /* AgentChatTranscriptResolver.swift */; }; 992300019923000199230008 /* AgentChatTranscriptResumeIntentRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 992300019923000199230007 /* AgentChatTranscriptResumeIntentRecorder.swift */; }; + A85870000000000000000023 /* AgentChatTranscriptService+ArtifactCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000022 /* AgentChatTranscriptService+ArtifactCapture.swift */; }; A1B2C3D4E5F60718293A4B5D /* AgentChatTranscriptService+ArtifactSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F60718293A4B5C /* AgentChatTranscriptService+ArtifactSession.swift */; }; + C7A85870000000000000000D /* AgentChatTranscriptService+Resolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A85870000000000000000E /* AgentChatTranscriptService+Resolution.swift */; }; C7A52F000000000000000002 /* AgentChatTranscriptService+Wire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A52F000000000000000001 /* AgentChatTranscriptService+Wire.swift */; }; ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */; }; + A8587F000000000000000021 /* AgentChatTranscriptSlice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587F000000000000000020 /* AgentChatTranscriptSlice.swift */; }; ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */; }; + C7A858700000000000000004 /* AgentChatTranscriptTailerBoundedReadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A858700000000000000003 /* AgentChatTranscriptTailerBoundedReadTests.swift */; }; + C7A858700000000000000008 /* AgentChatWorkingDirectoryAuthority.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A858700000000000000007 /* AgentChatWorkingDirectoryAuthority.swift */; }; C0A710A10000000000000002 /* AgentCursorPointerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0A710A10000000000000001 /* AgentCursorPointerView.swift */; }; 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */; }; 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */; }; @@ -204,7 +229,9 @@ A5C01700000000000000000D /* AppDelegate+AccountSignInWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5C01700000000000000000E /* AppDelegate+AccountSignInWorkspace.swift */; }; 804100000000000000000009 /* AppDelegate+AdjacentNavigationShortcut.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80410000000000000000000A /* AppDelegate+AdjacentNavigationShortcut.swift */; }; C0DE45AC0000000000000001 /* AppDelegate+AgentChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE45AC0000000000000002 /* AppDelegate+AgentChat.swift */; }; +C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */; }; C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */; }; + A8587000000000000000003D /* AppDelegate+Artifacts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000003C /* AppDelegate+Artifacts.swift */; }; 986900010000000000000001 /* AppDelegate+BrowserActionRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 986900010000000000000002 /* AppDelegate+BrowserActionRouting.swift */; }; D35A00000000000000000001 /* AppDelegate+BrowserDesignMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35B00000000000000000001 /* AppDelegate+BrowserDesignMode.swift */; }; C4A570010000000000000001 /* AppDelegate+CanvasShortcutRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A570010000000000000002 /* AppDelegate+CanvasShortcutRouting.swift */; }; @@ -278,6 +305,23 @@ A5001621 /* AppleScriptSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001620 /* AppleScriptSupport.swift */; }; A5001A02A1B2C3D4E5F60718 /* AppWindowBackdropControllerDependencies.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001A03A1B2C3D4E5F60718 /* AppWindowBackdropControllerDependencies.swift */; }; A5001A00A1B2C3D4E5F60718 /* AppWindowChromeComposition.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001A01A1B2C3D4E5F60718 /* AppWindowChromeComposition.swift */; }; + A85870000000000000000047 /* ArtifactCLIArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000046 /* ArtifactCLIArguments.swift */; }; + A8610D00000000000000000D /* ArtifactCLIIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D00000000000000000E /* ArtifactCLIIntegrationTests.swift */; }; + A85870000000000000000051 /* ArtifactCLITerminalSafetyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000050 /* ArtifactCLITerminalSafetyTests.swift */; }; + A85870000000000000000067 /* ArtifactHTMLPreviewDocument.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000066 /* ArtifactHTMLPreviewDocument.swift */; }; + A8610D000000000000000005 /* ArtifactHTMLPreviewNavigationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D000000000000000006 /* ArtifactHTMLPreviewNavigationPolicy.swift */; }; + A85870000000000000000065 /* ArtifactHTMLPreviewSecurityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000064 /* ArtifactHTMLPreviewSecurityTests.swift */; }; + A8610D000000000000000007 /* ArtifactHTMLPreviewWebViewFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D000000000000000008 /* ArtifactHTMLPreviewWebViewFactory.swift */; }; + A8610D00000000000000000F /* ArtifactRightSidebarModeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D000000000000000010 /* ArtifactRightSidebarModeTests.swift */; }; + A85870000000000000000069 /* ArtifactRuntimeLifecycleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000068 /* ArtifactRuntimeLifecycleTests.swift */; }; + A8610D00000000000000000B /* ArtifactSidebarBinding.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D00000000000000000C /* ArtifactSidebarBinding.swift */; }; + A85870000000000000000071 /* ArtifactSidebarFileAccess.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000070 /* ArtifactSidebarFileAccess.swift */; }; + A85870000000000000000031 /* ArtifactSidebarPanelView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000030 /* ArtifactSidebarPanelView.swift */; }; + A85870000000000000000033 /* ArtifactSidebarRowActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000032 /* ArtifactSidebarRowActions.swift */; }; + A85870000000000000000035 /* ArtifactSidebarRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000034 /* ArtifactSidebarRowView.swift */; }; + A8587000000000000000006B /* ArtifactSidebarSearchField.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000006A /* ArtifactSidebarSearchField.swift */; }; + A8587000000000000000006D /* ArtifactSidebarSearchFieldView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000006C /* ArtifactSidebarSearchFieldView.swift */; }; + A85870000000000000000037 /* ArtifactSidebarThumbnailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000036 /* ArtifactSidebarThumbnailView.swift */; }; A5001100 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A5001101 /* Assets.xcassets */; }; 961300000000000000000003 /* AttributedString+SidebarRowLinks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 961300000000000000000004 /* AttributedString+SidebarRowLinks.swift */; }; D9FEC58D5BACCF76459F1BBE /* AuthEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43430FA5929121E2EAAB3091 /* AuthEnvironment.swift */; }; @@ -470,6 +514,7 @@ C67540060000000000000001 /* BrowserPanel+PDFDocumentActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C67540060000000000000002 /* BrowserPanel+PDFDocumentActions.swift */; }; B424PWAD000000000000PW01 /* BrowserPanel+PrewarmedWebViewAdoption.swift in Sources */ = {isa = PBXBuildFile; fileRef = B424PWAD000000000000PW02 /* BrowserPanel+PrewarmedWebViewAdoption.swift */; }; A5001402 /* BrowserPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001412 /* BrowserPanel.swift */; }; + A8610D000000000000000009 /* BrowserPanelContentMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610D00000000000000000A /* BrowserPanelContentMode.swift */; }; B1F0C0090000000000000001 /* BrowserPanelDeveloperToolsLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0C0090000000000000002 /* BrowserPanelDeveloperToolsLifecycle.swift */; }; C62530010000000000000001 /* BrowserPanelReloadMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C62530010000000000000002 /* BrowserPanelReloadMode.swift */; }; B65060010000000000000002 /* BrowserPanelSessionRestoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B65060010000000000000001 /* BrowserPanelSessionRestoreTests.swift */; }; @@ -816,6 +861,9 @@ A5001001 /* cmuxApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001011 /* cmuxApp.swift */; }; C9A2B00000000000000000B3 /* CmuxAppKitSupportUI in Frameworks */ = {isa = PBXBuildFile; productRef = C9A2B00000000000000000B2 /* CmuxAppKitSupportUI */; }; C9A2B00000000000000000C3 /* CmuxAppKitSupportUI in Frameworks */ = {isa = PBXBuildFile; productRef = C9A2B00000000000000000C2 /* CmuxAppKitSupportUI */; }; + A85870000000000000000003 /* CmuxArtifacts in Frameworks */ = {isa = PBXBuildFile; productRef = A85870000000000000000002 /* CmuxArtifacts */; }; + A85870000000000000000004 /* CmuxArtifacts in Frameworks */ = {isa = PBXBuildFile; productRef = A85870000000000000000002 /* CmuxArtifacts */; }; + A85870000000000000000005 /* CmuxArtifacts in Frameworks */ = {isa = PBXBuildFile; productRef = A85870000000000000000002 /* CmuxArtifacts */; }; 5EDB6027B346C46521A93C74 /* CMUXAuthCore in Frameworks */ = {isa = PBXBuildFile; productRef = 29813FE5A6CBC1019289A251 /* CMUXAuthCore */; }; A99940010000000000000001 /* CMUXAuthCore in Frameworks */ = {isa = PBXBuildFile; productRef = 29813FE5A6CBC1019289A251 /* CMUXAuthCore */; }; 53750003A0B1C2D3E4F50003 /* CmuxAuthRuntime in Frameworks */ = {isa = PBXBuildFile; productRef = 53750002A0B1C2D3E4F50002 /* CmuxAuthRuntime */; }; @@ -841,6 +889,7 @@ 9758B0119758B0119758B011 /* CMUXCLI+AmpExtensionSourcePart1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9758B0019758B0019758B001 /* CMUXCLI+AmpExtensionSourcePart1.swift */; }; 9758B0129758B0129758B012 /* CMUXCLI+AmpExtensionSourcePart2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9758B0029758B0029758B002 /* CMUXCLI+AmpExtensionSourcePart2.swift */; }; 9758B0139758B0139758B013 /* CMUXCLI+AmpExtensionSourcePart3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9758B0039758B0039758B003 /* CMUXCLI+AmpExtensionSourcePart3.swift */; }; + A85870000000000000000011 /* CMUXCLI+Artifacts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000010 /* CMUXCLI+Artifacts.swift */; }; A106490E0000000000000001 /* CMUXCLI+Automation.swift in Sources */ = {isa = PBXBuildFile; fileRef = A106490D0000000000000001 /* CMUXCLI+Automation.swift */; }; 0CB4E9797AD54D3BB9CF06F9 /* CMUXCLI+AutoNaming.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5257257034CA4729B1211166 /* CMUXCLI+AutoNaming.swift */; }; 6D9C51AB30A64B1ABC819142 /* CMUXCLI+AutoNaming.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5257257034CA4729B1211166 /* CMUXCLI+AutoNaming.swift */; }; @@ -884,6 +933,7 @@ 906902000000000000000002 /* CMUXCLI+MemoryAttribution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 906902000000000000000001 /* CMUXCLI+MemoryAttribution.swift */; }; 812600000000000000000005 /* CMUXCLI+MoshTerminalTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 812600000000000000000006 /* CMUXCLI+MoshTerminalTransport.swift */; }; D7AB0000000000000000000D /* CMUXCLI+MoveTabToNewWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB0000000000000000000E /* CMUXCLI+MoveTabToNewWorkspace.swift */; }; + A85870000000000000000055 /* CMUXCLI+Notes.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000054 /* CMUXCLI+Notes.swift */; }; 54D273BB0F1A89BFEA1E00E1 /* CMUXCLI+NotificationFormatting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6BF7B8DE8A42DA3620CADA /* CMUXCLI+NotificationFormatting.swift */; }; B9000072A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */; }; C08672010000000000000005 /* CMUXCLI+PiCompactedFeed.swift in Sources */ = {isa = PBXBuildFile; fileRef = C08672010000000000000006 /* CMUXCLI+PiCompactedFeed.swift */; }; @@ -894,6 +944,7 @@ C05555010000000000000005 /* CMUXCLI+PiExtensionSourcePart1.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000006 /* CMUXCLI+PiExtensionSourcePart1.swift */; }; C05555010000000000000007 /* CMUXCLI+PiExtensionSourcePart2.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */; }; B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */; }; + A85870000000000000000057 /* CMUXCLI+ProjectFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000056 /* CMUXCLI+ProjectFiles.swift */; }; C73660010000000000000001 /* CMUXCLI+RemotePTYErrors.swift in Sources */ = {isa = PBXBuildFile; fileRef = C73660010000000000000002 /* CMUXCLI+RemotePTYErrors.swift */; }; REE0CA0000000000000000C2 /* CMUXCLI+Remotes.swift in Sources */ = {isa = PBXBuildFile; fileRef = REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */; }; 925800000000000000000002 /* CMUXCLI+Restore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 925800000000000000000001 /* CMUXCLI+Restore.swift */; }; @@ -1081,10 +1132,14 @@ C01E00AA00000000000000A3 /* CmuxSyntaxHighlighting in Frameworks */ = {isa = PBXBuildFile; productRef = C01E00AA00000000000000A2 /* CmuxSyntaxHighlighting */; }; C01E00AA00000000000000A4 /* CmuxSyntaxHighlighting in Frameworks */ = {isa = PBXBuildFile; productRef = C01E00AA00000000000000A2 /* CmuxSyntaxHighlighting */; }; 0A1107110000000000000016 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000017 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift */; }; + A8610C000000000000000004 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000017 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift */; }; + A8610C000000000000000002 /* CmuxTaskManagerCodingAgentDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610C000000000000000001 /* CmuxTaskManagerCodingAgentDefinition.swift */; }; + A8610C000000000000000003 /* CmuxTaskManagerCodingAgentDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8610C000000000000000001 /* CmuxTaskManagerCodingAgentDefinition.swift */; }; 906901000000000000000004 /* CmuxTaskManagerMemoryAttribution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 906901000000000000000003 /* CmuxTaskManagerMemoryAttribution.swift */; }; 906901000000000000000006 /* CmuxTaskManagerMemoryGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 906901000000000000000005 /* CmuxTaskManagerMemoryGroup.swift */; }; 90690100000000000000000C /* CmuxTaskManagerMemoryGroupAttribution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90690100000000000000000B /* CmuxTaskManagerMemoryGroupAttribution.swift */; }; C750500000000000000000A3 /* CmuxTerminal in Frameworks */ = {isa = PBXBuildFile; productRef = C750500000000000000000A2 /* CmuxTerminal */; }; + A8610C000000000000000005 /* CmuxTerminalCore in Frameworks */ = {isa = PBXBuildFile; productRef = C750200000000000000000A2 /* CmuxTerminalCore */; }; C750200000000000000000A3 /* CmuxTerminalCore in Frameworks */ = {isa = PBXBuildFile; productRef = C750200000000000000000A2 /* CmuxTerminalCore */; }; CFF12E0000000000000000A3 /* CmuxTestSupport in Frameworks */ = {isa = PBXBuildFile; productRef = CFF12E0000000000000000A2 /* CmuxTestSupport */; }; A2977C204AD69CF268D38EE3 /* CmuxTestWindowReleaseGuard.m in Sources */ = {isa = PBXBuildFile; fileRef = EA9B442F20273D64D2BA1FC5 /* CmuxTestWindowReleaseGuard.m */; }; @@ -1236,6 +1291,7 @@ 3023A1003023A1003023A100 /* ConfigSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3023B1003023B1003023B100 /* ConfigSource.swift */; }; D1F0A01100000000000000B1 /* ConnectivityInvalidationSubscriberCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A01100000000000000B2 /* ConnectivityInvalidationSubscriberCoordinator.swift */; }; C0DE43000000000000000005 /* ContentView+AgentChatCommandPalette.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE43000000000000000006 /* ContentView+AgentChatCommandPalette.swift */; }; + A8587000000000000000003F /* ContentView+Artifacts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000003E /* ContentView+Artifacts.swift */; }; C0DEA7710000000000000001 /* ContentView+AuthCommandPalette.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEA7710000000000000002 /* ContentView+AuthCommandPalette.swift */; }; CA52E0010000000000000000 /* ContentView+CanvasCommandPalette.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA52F0010000000000000000 /* ContentView+CanvasCommandPalette.swift */; }; C51A720000000000000001A1 /* ContentView+CommandPaletteSurfaceMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = C51A720000000000000001A2 /* ContentView+CommandPaletteSurfaceMetadata.swift */; }; @@ -1806,6 +1862,8 @@ F2100000000000000000000B /* MobileBrowserStreamCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1100000000000000000000B /* MobileBrowserStreamCoordinator.swift */; }; F2100000000000000000000C /* MobileBrowserStreamSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1100000000000000000000C /* MobileBrowserStreamSession.swift */; }; F2100000000000000000000D /* MobileBrowserWireEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1100000000000000000000D /* MobileBrowserWireEncoder.swift */; }; + A8587000000000000000004F /* MobileChatArtifactAuthorizationSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000004E /* MobileChatArtifactAuthorizationSnapshotTests.swift */; }; + C0DEA7710000000000000009 /* MobileConnectTitlebarAccessory.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEA771000000000000000A /* MobileConnectTitlebarAccessory.swift */; }; C1A070000000000000000001 /* MobileHostAuthorizationSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A070000000000000000011 /* MobileHostAuthorizationSupport.swift */; }; 6AA2F2E8BEB19ED6B8E125DB /* MobileHostAuthorizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BD519CFE74530A46DF0925D /* MobileHostAuthorizationTests.swift */; }; C7A50B000000000000000016 /* MobileHostBuildIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A50B000000000000000015 /* MobileHostBuildIdentity.swift */; }; @@ -1905,6 +1963,8 @@ A1122301A1B2C3D4E5F60718 /* NewWorkspaceButtonHitAreaUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1122302A1B2C3D4E5F60718 /* NewWorkspaceButtonHitAreaUITests.swift */; }; C0DE77060000000000000003 /* NewWorkspaceMenuModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE77060000000000000004 /* NewWorkspaceMenuModel.swift */; }; A5FB1400 /* NewWorkspaceMenuModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5FB1401 /* NewWorkspaceMenuModelTests.swift */; }; + A85870000000000000000059 /* NoteCLIArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000058 /* NoteCLIArguments.swift */; }; + A85870000000000000000061 /* NoteCLIIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000060 /* NoteCLIIntegrationTests.swift */; }; 734F49D37E543DD01C2F4FEF /* NotificationAndMenuBarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2C075029771815DD5DA1332 /* NotificationAndMenuBarTests.swift */; }; C06552010000000000000003 /* NotificationBurstCoalescer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C06552010000000000000004 /* NotificationBurstCoalescer.swift */; }; 7490C00D7490C00D7490C00D /* NotificationCacheMemoryPressureResponder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7490D00D7490D00D7490D00D /* NotificationCacheMemoryPressureResponder.swift */; }; @@ -1958,7 +2018,9 @@ D7769000000000000000000F /* NotificationsPopoverMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = D77690000000000000000010 /* NotificationsPopoverMetrics.swift */; }; D77690000000000000000007 /* NotificationsPopoverResizeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = D77690000000000000000008 /* NotificationsPopoverResizeHandle.swift */; }; D77690000000000000000009 /* NotificationsPopoverResizeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7769000000000000000000A /* NotificationsPopoverResizeView.swift */; }; + A86100000000000000000002 /* NSEvent+RightSidebarKeyboardNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = A86100000000000000000001 /* NSEvent+RightSidebarKeyboardNavigation.swift */; }; C01E00080000000000000001 /* NSTextView+FilePreviewTabWidth.swift in Sources */ = {isa = PBXBuildFile; fileRef = C01E00080000000000000002 /* NSTextView+FilePreviewTabWidth.swift */; }; + A85870000000000000000043 /* NSView+RightSidebarKeyboardFocus.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000042 /* NSView+RightSidebarKeyboardFocus.swift */; }; 25C58D231850D0F414A62F19 /* NSView+WindowPointHitTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EFC842F5002FB86145AEF1E /* NSView+WindowPointHitTest.swift */; }; D36090020000000000000001 /* NSWindow+CmuxPeerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = D36090020000000000000002 /* NSWindow+CmuxPeerWindow.swift */; }; 645645000000000000000002 /* NumberedShortcutSwapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 645645000000000000000001 /* NumberedShortcutSwapTests.swift */; }; @@ -2274,7 +2336,11 @@ AA1B2C3D4E5F60720 /* RightSidebarChromeHeightUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA1B2C3D4E5F60721 /* RightSidebarChromeHeightUITests.swift */; }; B7F9A604B7F9A604B7F9A604 /* RightSidebarChromeStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7F9A605B7F9A605B7F9A605 /* RightSidebarChromeStyle.swift */; }; C3408A000000000000000003 /* RightSidebarCommandPaletteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3408A000000000000000004 /* RightSidebarCommandPaletteTests.swift */; }; + A86100000000000000000004 /* RightSidebarDisclosureAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = A86100000000000000000003 /* RightSidebarDisclosureAction.swift */; }; + A8587000000000000000003B /* RightSidebarKeyboardFocusBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8587000000000000000003A /* RightSidebarKeyboardFocusBridge.swift */; }; + A85870000000000000000041 /* RightSidebarKeyboardFocusView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000040 /* RightSidebarKeyboardFocusView.swift */; }; B37A00000000000000000003 /* RightSidebarMode+Availability.swift in Sources */ = {isa = PBXBuildFile; fileRef = B37A00000000000000000004 /* RightSidebarMode+Availability.swift */; }; + A85870000000000000000039 /* RightSidebarMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85870000000000000000038 /* RightSidebarMode.swift */; }; 46814000000000000000000D /* RightSidebarModeShortcutEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46814000000000000000000E /* RightSidebarModeShortcutEntry.swift */; }; 468110000000000000000005 /* RightSidebarModeShortcutMatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 468110000000000000000006 /* RightSidebarModeShortcutMatcher.swift */; }; FE003103 /* RightSidebarPanelView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE003003 /* RightSidebarPanelView.swift */; }; @@ -3510,8 +3576,19 @@ A5C017000000000000000008 /* AccountSignInView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSignInView.swift; sourceTree = ""; }; A9E010000000000000000006 /* agent-session-react */ = {isa = PBXFileReference; lastKnownFileType = folder; path = "agent-session-react"; sourceTree = ""; }; A9E010000000000000000007 /* agent-session-solid */ = {isa = PBXFileReference; lastKnownFileType = folder; path = "agent-session-solid"; sourceTree = ""; }; + A85870000000000000000052 /* AgentArtifactAutomaticPathBoundTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentArtifactAutomaticPathBoundTests.swift; sourceTree = ""; }; + A8587000000000000000004A /* AgentArtifactCaptureCheckpoint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactCaptureCheckpoint.swift"; sourceTree = ""; }; + A85870000000000000000020 /* AgentArtifactCaptureCoordinator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactCaptureCoordinator.swift"; sourceTree = ""; }; + A85870000000000000000048 /* AgentArtifactCaptureCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentArtifactCaptureCoordinatorTests.swift; sourceTree = ""; }; + A85870000000000000000062 /* AgentArtifactCaptureCoordinatorTestStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentArtifactCaptureCoordinatorTestStore.swift; sourceTree = ""; }; + A8587000000000000000006E /* AgentArtifactCaptureProgress.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactCaptureProgress.swift"; sourceTree = ""; }; + A85870000000000000000044 /* AgentArtifactCaptureSaveError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactCaptureSaveError.swift"; sourceTree = ""; }; + A8610D000000000000000002 /* AgentArtifactCompletedCaptureState.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactCompletedCaptureState.swift"; sourceTree = ""; }; + C7A858700000000000000001 /* AgentArtifactProjectAuthorityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentArtifactProjectAuthorityTests.swift; sourceTree = ""; }; + A8587000000000000000002A /* AgentArtifactReferenceCursor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentArtifactReferenceCursor.swift"; sourceTree = ""; }; C7AF10000000000000000006 /* AgentChatArtifactGalleryBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatArtifactGalleryBuilder.swift"; sourceTree = ""; }; C7AF10000000000000000002 /* AgentChatArtifactIndex.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatArtifactIndex.swift"; sourceTree = ""; }; + A8587000000000000000004C /* AgentChatArtifactIndexSafetyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatArtifactIndexSafetyTests.swift; sourceTree = ""; }; 5FAC71D5AC71D5AC71D50002 /* AgentChatChildRunTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatChildRunTests.swift; sourceTree = ""; }; C7A52E000000000000000001 /* AgentChatEndedTranscriptListabilityCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatEndedTranscriptListabilityCache.swift"; sourceTree = ""; }; C7A53F000000000000000001 /* AgentChatFallbackTranscriptResolutionCoordinator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatFallbackTranscriptResolutionCoordinator.swift"; sourceTree = ""; }; @@ -3520,7 +3597,9 @@ C7A531000000000000000001 /* AgentChatObservationHandle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatObservationHandle.swift"; sourceTree = ""; }; C7A532000000000000000001 /* AgentChatObservationInFlight.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatObservationInFlight.swift"; sourceTree = ""; }; C7A530000000000000000001 /* AgentChatObservationScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatObservationScope.swift"; sourceTree = ""; }; + C7A858700000000000000009 /* AgentChatObservedWorkingDirectoryResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatObservedWorkingDirectoryResolver.swift"; sourceTree = ""; }; 99230001992300019923000B /* AgentChatResumeIntentRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatResumeIntentRecorder.swift; sourceTree = ""; }; + A8587F000000000000000030 /* AgentChatSessionRecencyIndex.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatSessionRecencyIndex.swift"; sourceTree = ""; }; ACA7C4A70000000000000002 /* AgentChatSessionRecord.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatSessionRecord.swift"; sourceTree = ""; }; C7A52D100000000000000011 /* AgentChatSessionRegistry+ChildRuns.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatSessionRegistry+ChildRuns.swift"; sourceTree = ""; }; C8711A000000000000000001 /* AgentChatSessionRegistry+CodexRolloutFiles.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatSessionRegistry+CodexRolloutFiles.swift"; sourceTree = ""; }; @@ -3535,12 +3614,24 @@ C7A51D100000000000000001 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatSessionRegistryObservationReviewRegressionTests.swift; sourceTree = ""; }; C7A51D000000000000000001 /* AgentChatSessionRegistryObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatSessionRegistryObservationTests.swift; sourceTree = ""; }; C0DE71A00000000000000002 /* AgentChatThemeSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatThemeSync.swift; sourceTree = ""; }; + A8587F000000000000000033 /* AgentChatTranscriptBoundedLineIterator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptBoundedLineIterator.swift"; sourceTree = ""; }; + A8587F000000000000000035 /* AgentChatTranscriptBoundedLineSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptBoundedLineSequence.swift"; sourceTree = ""; }; + A8610B000000000000000001 /* AgentChatTranscriptIncrementalLineBuffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptIncrementalLineBuffer.swift"; sourceTree = ""; }; + C7A858700000000000000005 /* AgentChatTranscriptInitialTailReader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptInitialTailReader.swift"; sourceTree = ""; }; + A8610D000000000000000004 /* AgentChatTranscriptInitialTailSnapshot.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptInitialTailSnapshot.swift"; sourceTree = ""; }; + A8587F000000000000000010 /* AgentChatTranscriptReader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptReader.swift"; sourceTree = ""; }; + C7A85870000000000000000C /* AgentChatTranscriptResolutionReviewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatTranscriptResolutionReviewTests.swift; sourceTree = ""; }; ACA7C4A70000000000000006 /* AgentChatTranscriptResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptResolver.swift"; sourceTree = ""; }; 992300019923000199230007 /* AgentChatTranscriptResumeIntentRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatTranscriptResumeIntentRecorder.swift; sourceTree = ""; }; + A85870000000000000000022 /* AgentChatTranscriptService+ArtifactCapture.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService+ArtifactCapture.swift"; sourceTree = ""; }; A1B2C3D4E5F60718293A4B5C /* AgentChatTranscriptService+ArtifactSession.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService+ArtifactSession.swift"; sourceTree = ""; }; + C7A85870000000000000000E /* AgentChatTranscriptService+Resolution.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService+Resolution.swift"; sourceTree = ""; }; C7A52F000000000000000001 /* AgentChatTranscriptService+Wire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService+Wire.swift"; sourceTree = ""; }; ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService.swift"; sourceTree = ""; }; + A8587F000000000000000020 /* AgentChatTranscriptSlice.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptSlice.swift"; sourceTree = ""; }; ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptTailer.swift"; sourceTree = ""; }; + C7A858700000000000000003 /* AgentChatTranscriptTailerBoundedReadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentChatTranscriptTailerBoundedReadTests.swift; sourceTree = ""; }; + C7A858700000000000000007 /* AgentChatWorkingDirectoryAuthority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatWorkingDirectoryAuthority.swift"; sourceTree = ""; }; C0A710A10000000000000001 /* AgentCursorPointerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/AgentCursorPointerView.swift; sourceTree = ""; }; 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTargetResolution.swift; sourceTree = ""; }; 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTTYBindingTests.swift; sourceTree = ""; }; @@ -3692,7 +3783,9 @@ A5C01700000000000000000E /* AppDelegate+AccountSignInWorkspace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AccountSignInWorkspace.swift"; sourceTree = ""; }; 80410000000000000000000A /* AppDelegate+AdjacentNavigationShortcut.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AdjacentNavigationShortcut.swift"; sourceTree = ""; }; C0DE45AC0000000000000002 /* AppDelegate+AgentChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AgentChat.swift"; sourceTree = ""; }; +C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AgentChatNotifications.swift"; sourceTree = ""; }; C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AgentChatNotifications.swift"; sourceTree = ""; }; + A8587000000000000000003C /* AppDelegate+Artifacts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+Artifacts.swift"; sourceTree = ""; }; 986900010000000000000002 /* AppDelegate+BrowserActionRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+BrowserActionRouting.swift"; sourceTree = ""; }; D35B00000000000000000001 /* AppDelegate+BrowserDesignMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+BrowserDesignMode.swift"; sourceTree = ""; }; C4A570010000000000000002 /* AppDelegate+CanvasShortcutRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+CanvasShortcutRouting.swift"; sourceTree = ""; }; @@ -3767,6 +3860,23 @@ A5001620 /* AppleScriptSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleScriptSupport.swift; sourceTree = ""; }; A5001A03A1B2C3D4E5F60718 /* AppWindowBackdropControllerDependencies.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Windowing/AppWindowBackdropControllerDependencies.swift; sourceTree = ""; }; A5001A01A1B2C3D4E5F60718 /* AppWindowChromeComposition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Windowing/AppWindowChromeComposition.swift; sourceTree = ""; }; + A85870000000000000000046 /* ArtifactCLIArguments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactCLIArguments.swift; sourceTree = ""; }; + A8610D00000000000000000E /* ArtifactCLIIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactCLIIntegrationTests.swift; sourceTree = ""; }; + A85870000000000000000050 /* ArtifactCLITerminalSafetyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactCLITerminalSafetyTests.swift; sourceTree = ""; }; + A85870000000000000000066 /* ArtifactHTMLPreviewDocument.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactHTMLPreviewDocument.swift; sourceTree = ""; }; + A8610D000000000000000006 /* ArtifactHTMLPreviewNavigationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactHTMLPreviewNavigationPolicy.swift; sourceTree = ""; }; + A85870000000000000000064 /* ArtifactHTMLPreviewSecurityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactHTMLPreviewSecurityTests.swift; sourceTree = ""; }; + A8610D000000000000000008 /* ArtifactHTMLPreviewWebViewFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactHTMLPreviewWebViewFactory.swift; sourceTree = ""; }; + A8610D000000000000000010 /* ArtifactRightSidebarModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactRightSidebarModeTests.swift; sourceTree = ""; }; + A85870000000000000000068 /* ArtifactRuntimeLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactRuntimeLifecycleTests.swift; sourceTree = ""; }; + A8610D00000000000000000C /* ArtifactSidebarBinding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarBinding.swift; sourceTree = ""; }; + A85870000000000000000070 /* ArtifactSidebarFileAccess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarFileAccess.swift; sourceTree = ""; }; + A85870000000000000000030 /* ArtifactSidebarPanelView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarPanelView.swift; sourceTree = ""; }; + A85870000000000000000032 /* ArtifactSidebarRowActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarRowActions.swift; sourceTree = ""; }; + A85870000000000000000034 /* ArtifactSidebarRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarRowView.swift; sourceTree = ""; }; + A8587000000000000000006A /* ArtifactSidebarSearchField.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarSearchField.swift; sourceTree = ""; }; + A8587000000000000000006C /* ArtifactSidebarSearchFieldView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarSearchFieldView.swift; sourceTree = ""; }; + A85870000000000000000036 /* ArtifactSidebarThumbnailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactSidebarThumbnailView.swift; sourceTree = ""; }; A5001101 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 961300000000000000000004 /* AttributedString+SidebarRowLinks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Sidebar/AttributedString+SidebarRowLinks.swift"; sourceTree = ""; }; 43430FA5929121E2EAAB3091 /* AuthEnvironment.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AuthEnvironment.swift; sourceTree = ""; }; @@ -3951,6 +4061,7 @@ C67540060000000000000002 /* BrowserPanel+PDFDocumentActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserPanel+PDFDocumentActions.swift"; sourceTree = ""; }; B424PWAD000000000000PW02 /* BrowserPanel+PrewarmedWebViewAdoption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserPanel+PrewarmedWebViewAdoption.swift"; sourceTree = ""; }; A5001412 /* BrowserPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserPanel.swift; sourceTree = ""; }; + A8610D00000000000000000A /* BrowserPanelContentMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserPanelContentMode.swift; sourceTree = ""; }; B1F0C0090000000000000002 /* BrowserPanelDeveloperToolsLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserPanelDeveloperToolsLifecycle.swift; sourceTree = ""; }; C62530010000000000000002 /* BrowserPanelReloadMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserPanelReloadMode.swift; sourceTree = ""; }; B65060010000000000000001 /* BrowserPanelSessionRestoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserPanelSessionRestoreTests.swift; sourceTree = ""; }; @@ -4300,6 +4411,7 @@ 9758B0019758B0019758B001 /* CMUXCLI+AmpExtensionSourcePart1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+AmpExtensionSourcePart1.swift"; sourceTree = ""; }; 9758B0029758B0029758B002 /* CMUXCLI+AmpExtensionSourcePart2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+AmpExtensionSourcePart2.swift"; sourceTree = ""; }; 9758B0039758B0039758B003 /* CMUXCLI+AmpExtensionSourcePart3.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+AmpExtensionSourcePart3.swift"; sourceTree = ""; }; + A85870000000000000000010 /* CMUXCLI+Artifacts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Artifacts.swift"; sourceTree = ""; }; A106490D0000000000000001 /* CMUXCLI+Automation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Automation.swift"; sourceTree = ""; }; 5257257034CA4729B1211166 /* CMUXCLI+AutoNaming.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+AutoNaming.swift"; sourceTree = ""; }; 5257257034CA4729B121116A /* CMUXCLI+AutoNamingDispatch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+AutoNamingDispatch.swift"; sourceTree = ""; }; @@ -4342,6 +4454,7 @@ 906902000000000000000001 /* CMUXCLI+MemoryAttribution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+MemoryAttribution.swift"; sourceTree = ""; }; 812600000000000000000006 /* CMUXCLI+MoshTerminalTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+MoshTerminalTransport.swift"; sourceTree = ""; }; D7AB0000000000000000000E /* CMUXCLI+MoveTabToNewWorkspace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+MoveTabToNewWorkspace.swift"; sourceTree = ""; }; + A85870000000000000000054 /* CMUXCLI+Notes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Notes.swift"; sourceTree = ""; }; 1B6BF7B8DE8A42DA3620CADA /* CMUXCLI+NotificationFormatting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+NotificationFormatting.swift"; sourceTree = ""; }; B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+OmpExtension.swift"; sourceTree = ""; }; C08672010000000000000006 /* CMUXCLI+PiCompactedFeed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiCompactedFeed.swift"; sourceTree = ""; }; @@ -4352,6 +4465,7 @@ C05555010000000000000006 /* CMUXCLI+PiExtensionSourcePart1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtensionSourcePart1.swift"; sourceTree = ""; }; C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtensionSourcePart2.swift"; sourceTree = ""; }; B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Process.swift"; sourceTree = ""; }; + A85870000000000000000056 /* CMUXCLI+ProjectFiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+ProjectFiles.swift"; sourceTree = ""; }; C73660010000000000000002 /* CMUXCLI+RemotePTYErrors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+RemotePTYErrors.swift"; sourceTree = ""; }; REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Remotes.swift"; sourceTree = ""; }; 925800000000000000000001 /* CMUXCLI+Restore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Restore.swift"; sourceTree = ""; }; @@ -4478,6 +4592,7 @@ C0DE43000000000000000004 /* CmuxSurfaceTabBarBuiltInAction+Codable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CmuxSurfaceTabBarBuiltInAction+Codable.swift"; sourceTree = ""; }; C10D00040000000000000004 /* CmuxSurfaceTabBarBuiltInAction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxSurfaceTabBarBuiltInAction.swift; sourceTree = ""; }; 0A1107110000000000000017 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift"; sourceTree = ""; }; + A8610C000000000000000001 /* CmuxTaskManagerCodingAgentDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxTaskManagerCodingAgentDefinition.swift; sourceTree = ""; }; 906901000000000000000003 /* CmuxTaskManagerMemoryAttribution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxTaskManagerMemoryAttribution.swift; sourceTree = ""; }; 906901000000000000000005 /* CmuxTaskManagerMemoryGroup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxTaskManagerMemoryGroup.swift; sourceTree = ""; }; 90690100000000000000000B /* CmuxTaskManagerMemoryGroupAttribution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxTaskManagerMemoryGroupAttribution.swift; sourceTree = ""; }; @@ -4626,6 +4741,7 @@ 3023B1003023B1003023B100 /* ConfigSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Settings/ConfigSource.swift; sourceTree = ""; }; D1F0A01100000000000000B2 /* ConnectivityInvalidationSubscriberCoordinator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ConnectivityInvalidationSubscriberCoordinator.swift; sourceTree = ""; }; C0DE43000000000000000006 /* ContentView+AgentChatCommandPalette.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContentView+AgentChatCommandPalette.swift"; sourceTree = ""; }; + A8587000000000000000003E /* ContentView+Artifacts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContentView+Artifacts.swift"; sourceTree = ""; }; C0DEA7710000000000000002 /* ContentView+AuthCommandPalette.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContentView+AuthCommandPalette.swift"; sourceTree = ""; }; CA52F0010000000000000000 /* ContentView+CanvasCommandPalette.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContentView+CanvasCommandPalette.swift"; sourceTree = ""; }; C51A720000000000000001A2 /* ContentView+CommandPaletteSurfaceMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContentView+CommandPaletteSurfaceMetadata.swift"; sourceTree = ""; }; @@ -5187,6 +5303,8 @@ F1100000000000000000000B /* MobileBrowserStreamCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileBrowserStreamCoordinator.swift; sourceTree = ""; }; F1100000000000000000000C /* MobileBrowserStreamSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileBrowserStreamSession.swift; sourceTree = ""; }; F1100000000000000000000D /* MobileBrowserWireEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileBrowserWireEncoder.swift; sourceTree = ""; }; + A8587000000000000000004E /* MobileChatArtifactAuthorizationSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileChatArtifactAuthorizationSnapshotTests.swift; sourceTree = ""; }; + C0DEA771000000000000000A /* MobileConnectTitlebarAccessory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileConnectTitlebarAccessory.swift; sourceTree = ""; }; C1A070000000000000000011 /* MobileHostAuthorizationSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostAuthorizationSupport.swift; sourceTree = ""; }; 9BD519CFE74530A46DF0925D /* MobileHostAuthorizationTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostAuthorizationTests.swift; sourceTree = ""; }; C7A50B000000000000000015 /* MobileHostBuildIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileHostBuildIdentity.swift; sourceTree = ""; }; @@ -5286,6 +5404,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A1122302A1B2C3D4E5F60718 /* NewWorkspaceButtonHitAreaUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceButtonHitAreaUITests.swift; sourceTree = ""; }; C0DE77060000000000000004 /* NewWorkspaceMenuModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceMenuModel.swift; sourceTree = ""; }; A5FB1401 /* NewWorkspaceMenuModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceMenuModelTests.swift; sourceTree = ""; }; + A85870000000000000000058 /* NoteCLIArguments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteCLIArguments.swift; sourceTree = ""; }; + A85870000000000000000060 /* NoteCLIIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteCLIIntegrationTests.swift; sourceTree = ""; }; D2C075029771815DD5DA1332 /* NotificationAndMenuBarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationAndMenuBarTests.swift; sourceTree = ""; }; C06552010000000000000004 /* NotificationBurstCoalescer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationBurstCoalescer.swift; sourceTree = ""; }; 7490D00D7490D00D7490D00D /* NotificationCacheMemoryPressureResponder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/NotificationCacheMemoryPressureResponder.swift; sourceTree = ""; }; @@ -5339,7 +5459,9 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef D77690000000000000000010 /* NotificationsPopoverMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/NotificationsPopoverMetrics.swift; sourceTree = ""; }; D77690000000000000000008 /* NotificationsPopoverResizeHandle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/NotificationsPopoverResizeHandle.swift; sourceTree = ""; }; D7769000000000000000000A /* NotificationsPopoverResizeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/NotificationsPopoverResizeView.swift; sourceTree = ""; }; + A86100000000000000000001 /* NSEvent+RightSidebarKeyboardNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSEvent+RightSidebarKeyboardNavigation.swift"; sourceTree = ""; }; C01E00080000000000000002 /* NSTextView+FilePreviewTabWidth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/NSTextView+FilePreviewTabWidth.swift"; sourceTree = ""; }; + A85870000000000000000042 /* NSView+RightSidebarKeyboardFocus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSView+RightSidebarKeyboardFocus.swift"; sourceTree = ""; }; 2EFC842F5002FB86145AEF1E /* NSView+WindowPointHitTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSView+WindowPointHitTest.swift"; sourceTree = ""; }; D36090020000000000000002 /* NSWindow+CmuxPeerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/NSWindow+CmuxPeerWindow.swift"; sourceTree = ""; }; 645645000000000000000001 /* NumberedShortcutSwapTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NumberedShortcutSwapTests.swift; sourceTree = ""; }; @@ -5651,7 +5773,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef AA1B2C3D4E5F60721 /* RightSidebarChromeHeightUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarChromeHeightUITests.swift; sourceTree = ""; }; B7F9A605B7F9A605B7F9A605 /* RightSidebarChromeStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarChromeStyle.swift; sourceTree = ""; }; C3408A000000000000000004 /* RightSidebarCommandPaletteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarCommandPaletteTests.swift; sourceTree = ""; }; + A86100000000000000000003 /* RightSidebarDisclosureAction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RightSidebarDisclosureAction.swift"; sourceTree = ""; }; + A8587000000000000000003A /* RightSidebarKeyboardFocusBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarKeyboardFocusBridge.swift; sourceTree = ""; }; + A85870000000000000000040 /* RightSidebarKeyboardFocusView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarKeyboardFocusView.swift; sourceTree = ""; }; B37A00000000000000000004 /* RightSidebarMode+Availability.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RightSidebarMode+Availability.swift"; sourceTree = ""; }; + A85870000000000000000038 /* RightSidebarMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarMode.swift; sourceTree = ""; }; 46814000000000000000000E /* RightSidebarModeShortcutEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarModeShortcutEntry.swift; sourceTree = ""; }; 468110000000000000000006 /* RightSidebarModeShortcutMatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarModeShortcutMatcher.swift; sourceTree = ""; }; FE003003 /* RightSidebarPanelView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RightSidebarPanelView.swift; sourceTree = ""; }; @@ -6780,6 +6906,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A5B00003A1B2C3D4E5F60718 /* CMUXAgentLaunch in Frameworks */, 9758E0039758E0039758E003 /* CmuxAgentSessionStore in Frameworks */, C9A2B00000000000000000B3 /* CmuxAppKitSupportUI in Frameworks */, + A85870000000000000000003 /* CmuxArtifacts in Frameworks */, 5EDB6027B346C46521A93C74 /* CMUXAuthCore in Frameworks */, 53750003A0B1C2D3E4F50003 /* CmuxAuthRuntime in Frameworks */, E3B7A30000000000000000C3 /* CmuxBrowser in Frameworks */, @@ -6850,6 +6977,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef files = ( A77A0004A1B2C3D4E5F60001 /* CmuxAgentJournal in Frameworks */, A5B00004A1B2C3D4E5F60718 /* CMUXAgentLaunch in Frameworks */, + A85870000000000000000004 /* CmuxArtifacts in Frameworks */, C79470010000000000000005 /* CmuxControlSocket in Frameworks */, CF00F00000000000000000A4 /* CmuxFoundation in Frameworks */, CE57E10000000000000000B4 /* CmuxSentryReporting in Frameworks */, @@ -6859,6 +6987,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C51A700000000000000000A5 /* CmuxSimulator in Frameworks */, C5A1FED000000000000000C2 /* CmuxSwiftRender in Frameworks */, C5A1FED100000000000000D2 /* CmuxSwiftRenderUI in Frameworks */, + A8610C000000000000000005 /* CmuxTerminalCore in Frameworks */, + B9000024A1B2C3D4E5F60719 /* Sentry in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -6878,6 +7008,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef AC4A6E7C4A700001AC4A0005 /* CmuxAgentChat in Frameworks */, 9758E0049758E0049758E004 /* CmuxAgentSessionStore in Frameworks */, C9A2B00000000000000000C3 /* CmuxAppKitSupportUI in Frameworks */, + A85870000000000000000005 /* CmuxArtifacts in Frameworks */, A99940010000000000000001 /* CMUXAuthCore in Frameworks */, A99940020000000000000001 /* CmuxAuthRuntime in Frameworks */, D7032A060000000000000001 /* CmuxBrowser in Frameworks */, @@ -7043,8 +7174,16 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef ACA7C4A70000000000000100 /* AgentChat */ = { isa = PBXGroup; children = ( + A8587000000000000000004A /* AgentArtifactCaptureCheckpoint.swift */, + A8610D000000000000000002 /* AgentArtifactCompletedCaptureState.swift */, + A85870000000000000000020 /* AgentArtifactCaptureCoordinator.swift */, + A8587000000000000000006E /* AgentArtifactCaptureProgress.swift */, + A8587000000000000000002A /* AgentArtifactReferenceCursor.swift */, + A85870000000000000000044 /* AgentArtifactCaptureSaveError.swift */, ACA7C4A70000000000000002 /* AgentChatSessionRecord.swift */, C7AF10000000000000000002 /* AgentChatArtifactIndex.swift */, + A8587F000000000000000010 /* AgentChatTranscriptReader.swift */, + A8587F000000000000000020 /* AgentChatTranscriptSlice.swift */, C7AF10000000000000000006 /* AgentChatArtifactGalleryBuilder.swift */, ACA7C4A70000000000000004 /* AgentChatHookSessionStore.swift */, C8711C000000000000000001 /* CodexRolloutIdentity.swift */, @@ -7053,6 +7192,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7A532000000000000000001 /* AgentChatObservationInFlight.swift */, C7A530000000000000000001 /* AgentChatObservationScope.swift */, ACA7C4A70000000000000006 /* AgentChatTranscriptResolver.swift */, + ACA7C4A70000000000000008 /* AgentChatSessionRegistry.swift */, + A8587F000000000000000030 /* AgentChatSessionRecencyIndex.swift */, + A8587F000000000000000033 /* AgentChatTranscriptBoundedLineIterator.swift */, + A8587F000000000000000035 /* AgentChatTranscriptBoundedLineSequence.swift */, + C7A52D100000000000000001 /* AgentChatSessionRegistry+Lifecycle.swift */, ACA7C4A70000000000000008 /* AgentChatSessionRegistry.swift */, C7A52D100000000000000001 /* AgentChatSessionRegistry+Lifecycle.swift */, C7A52D100000000000000011 /* AgentChatSessionRegistry+ChildRuns.swift */, @@ -7062,7 +7206,14 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7A52E000000000000000001 /* AgentChatEndedTranscriptListabilityCache.swift */, C7A53F000000000000000001 /* AgentChatFallbackTranscriptResolutionCoordinator.swift */, ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */, + A8610B000000000000000001 /* AgentChatTranscriptIncrementalLineBuffer.swift */, + C7A858700000000000000005 /* AgentChatTranscriptInitialTailReader.swift */, + A8610D000000000000000004 /* AgentChatTranscriptInitialTailSnapshot.swift */, + C7A858700000000000000007 /* AgentChatWorkingDirectoryAuthority.swift */, + C7A858700000000000000009 /* AgentChatObservedWorkingDirectoryResolver.swift */, ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */, + A85870000000000000000022 /* AgentChatTranscriptService+ArtifactCapture.swift */, + C7A85870000000000000000E /* AgentChatTranscriptService+Resolution.swift */, C7A52F000000000000000001 /* AgentChatTranscriptService+Wire.swift */, A1B2C3D4E5F60718293A4B5C /* AgentChatTranscriptService+ArtifactSession.swift */, C7A533000000000000000001 /* ClaudeSessionCanonicalizationContext.swift */, @@ -8060,6 +8211,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 110433011104330111043301 /* AgentRestoreSuppressionJournal.swift */, 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */, 8F8DA1BC7420DEC238C4CB0B /* AgentResumeLiveness.swift */, + A8610C000000000000000001 /* CmuxTaskManagerCodingAgentDefinition.swift */, 110431011104310111043101 /* LiveAgentSessionOwnerIndex.swift */, 110439011104390111043901 /* LiveAgentSessionOwnerSessionKey.swift */, 110436011104360111043601 /* LiveAgentSessionOwner.swift */, @@ -8981,6 +9133,20 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A5001642 /* RemoteInteractiveShellBootstrapBuilder.swift */, A5001641 /* RemoteRelayZshBootstrap.swift */, C0DE43000000000000000002 /* CmuxAgentChatConfig.swift */, + A85870000000000000000070 /* ArtifactSidebarFileAccess.swift */, + A85870000000000000000030 /* ArtifactSidebarPanelView.swift */, + A8610D00000000000000000C /* ArtifactSidebarBinding.swift */, + A8587000000000000000006A /* ArtifactSidebarSearchField.swift */, + A8587000000000000000006C /* ArtifactSidebarSearchFieldView.swift */, + A85870000000000000000066 /* ArtifactHTMLPreviewDocument.swift */, + A8610D000000000000000006 /* ArtifactHTMLPreviewNavigationPolicy.swift */, + A8610D000000000000000008 /* ArtifactHTMLPreviewWebViewFactory.swift */, + A8610D00000000000000000A /* BrowserPanelContentMode.swift */, + A8587000000000000000003C /* AppDelegate+Artifacts.swift */, + A8587000000000000000003E /* ContentView+Artifacts.swift */, + A85870000000000000000032 /* ArtifactSidebarRowActions.swift */, + A85870000000000000000034 /* ArtifactSidebarRowView.swift */, + A85870000000000000000036 /* ArtifactSidebarThumbnailView.swift */, A5001651 /* CmuxConfig.swift */, 468110000000000000000002 /* CmuxNotificationHookCache.swift */, 468140000000000000000006 /* CmuxNotificationHookCacheEntry.swift */, @@ -9099,7 +9265,13 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef B7F9A601B7F9A601B7F9A601 /* RightSidebarChromeGeometryReporting.swift */, B7F9A605B7F9A605B7F9A605 /* RightSidebarChromeStyle.swift */, B7F9A603B7F9A603B7F9A603 /* WindowChromeMetrics.swift */, + A8587000000000000000003A /* RightSidebarKeyboardFocusBridge.swift */, + A85870000000000000000040 /* RightSidebarKeyboardFocusView.swift */, + A85870000000000000000042 /* NSView+RightSidebarKeyboardFocus.swift */, + A85870000000000000000038 /* RightSidebarMode.swift */, B37A00000000000000000004 /* RightSidebarMode+Availability.swift */, + A86100000000000000000001 /* NSEvent+RightSidebarKeyboardNavigation.swift */, + A86100000000000000000003 /* RightSidebarDisclosureAction.swift */, B37A0000000000000000000E /* RightSidebarRemoteCommand.swift */, FE003003 /* RightSidebarPanelView.swift */, 46814000000000000000000E /* RightSidebarModeShortcutEntry.swift */, @@ -9339,6 +9511,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */, C08672010000000000000008 /* PiCompactedFeedEventExpander.swift */, B9000070A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift */, + A85870000000000000000010 /* CMUXCLI+Artifacts.swift */, + A85870000000000000000046 /* ArtifactCLIArguments.swift */, + A85870000000000000000054 /* CMUXCLI+Notes.swift */, + A85870000000000000000056 /* CMUXCLI+ProjectFiles.swift */, + A85870000000000000000058 /* NoteCLIArguments.swift */, A10020000000000000000008 /* CMUXCLI+SurfaceSelection.swift */, 906902000000000000000001 /* CMUXCLI+MemoryAttribution.swift */, C51A75000000000000000002 /* CMUXCLI+JSONOutput.swift */, @@ -9395,6 +9572,19 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C11322A20000000000000001 /* CloudManualMirrorTransportTests.swift */, 9520B0019520B0019520B001 /* HermesFirstClassSupportTests.swift */, A11CE0020000000000000001 /* AboutLicensesResourceTests.swift */, + A8610D00000000000000000E /* ArtifactCLIIntegrationTests.swift */, + A85870000000000000000050 /* ArtifactCLITerminalSafetyTests.swift */, + A8610D000000000000000010 /* ArtifactRightSidebarModeTests.swift */, + A85870000000000000000068 /* ArtifactRuntimeLifecycleTests.swift */, + A85870000000000000000060 /* NoteCLIIntegrationTests.swift */, + A85870000000000000000048 /* AgentArtifactCaptureCoordinatorTests.swift */, + A85870000000000000000062 /* AgentArtifactCaptureCoordinatorTestStore.swift */, + A8587000000000000000004E /* MobileChatArtifactAuthorizationSnapshotTests.swift */, + A8587000000000000000004C /* AgentChatArtifactIndexSafetyTests.swift */, + A85870000000000000000052 /* AgentArtifactAutomaticPathBoundTests.swift */, + C7A858700000000000000001 /* AgentArtifactProjectAuthorityTests.swift */, + C7A85870000000000000000C /* AgentChatTranscriptResolutionReviewTests.swift */, + A85870000000000000000064 /* ArtifactHTMLPreviewSecurityTests.swift */, F2000001A1B2C3D4E5F60718 /* UpdatePillReleaseVisibilityTests.swift */, F3000001A1B2C3D4E5F60718 /* CJKIMEInputTests.swift */, FA0000000000000000000002 /* CloudManualInputOptionBackspaceTests.swift */, @@ -9464,6 +9654,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7A51C000000000000000001 /* AgentChatSessionRegistryHookStoreTests.swift */, C7A51E100000000000000001 /* AgentChatSessionRegistryLifecycleReviewRegressionTests.swift */, C7A51E000000000000000001 /* AgentChatSessionRegistryLifecycleTests.swift */, + C7A858700000000000000003 /* AgentChatTranscriptTailerBoundedReadTests.swift */, C7A51D100000000000000001 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift */, C7A51D000000000000000001 /* AgentChatSessionRegistryObservationTests.swift */, C8711B000000000000000001 /* CodexCodeModeRolloutIdentityTests.swift */, @@ -10368,6 +10559,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 29813FE5A6CBC1019289A251 /* CMUXAuthCore */, 53750002A0B1C2D3E4F50002 /* CmuxAuthRuntime */, AC4A6E7C4A700001AC4A0002 /* CmuxAgentChat */, + A85870000000000000000002 /* CmuxArtifacts */, 9758E0029758E0029758E002 /* CmuxAgentSessionStore */, C0DE45000000000000000002 /* CmuxExtensionKit */, C0DE4A000000000000000002 /* CmuxSidebarProviderKit */, @@ -10434,6 +10626,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef ); name = "cmux-cli"; packageProductDependencies = ( + A5001251 /* Sentry */, + A85870000000000000000002 /* CmuxArtifacts */, A5B00002A1B2C3D4E5F60718 /* CMUXAgentLaunch */, A77A0002A1B2C3D4E5F60001 /* CmuxAgentJournal */, C750100000000000000000A2 /* CmuxControlSocket */, @@ -10441,6 +10635,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C5A1FED100000000000000D3 /* CmuxSwiftRenderUI */, C5A1FED200000000000000E3 /* CmuxSidebarInterpreterClient */, C51A700000000000000000A2 /* CmuxSimulator */, + C750200000000000000000A2 /* CmuxTerminalCore */, CD0CFE5200000000CD0CFE52 /* CmuxSettings */, CF00F00000000000000000A2 /* CmuxFoundation */, CE57E10000000000000000B2 /* CmuxSentryReporting */, @@ -10500,6 +10695,9 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef ); name = cmuxTests; packageProductDependencies = ( + A85870000000000000000002 /* CmuxArtifacts */, + A5B00002A1B2C3D4E5F60718 /* CMUXAgentLaunch */, + A77A0002A1B2C3D4E5F60001 /* CmuxAgentJournal */, 29813FE5A6CBC1019289A251 /* CMUXAuthCore */, 53750002A0B1C2D3E4F50002 /* CmuxAuthRuntime */, A5B00002A1B2C3D4E5F60718 /* CMUXAgentLaunch */, @@ -10601,6 +10799,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 40B63BB4A170F0BD2D1DEFD1 /* XCLocalSwiftPackageReference "CMUXAuthCore" */, 53750001A0B1C2D3E4F50001 /* XCLocalSwiftPackageReference "CmuxAuthRuntime" */, AC4A6E7C4A700001AC4A0003 /* XCLocalSwiftPackageReference "CmuxAgentChat" */, + A85870000000000000000001 /* XCLocalSwiftPackageReference "CmuxArtifacts" */, C0DE45000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */, C0DE4A000000000000000003 /* XCLocalSwiftPackageReference "CmuxSidebarProviderKit" */, C0DE49000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionSidebarExamples" */, @@ -10891,6 +11090,12 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A5C017000000000000000009 /* AccountSignInPanel.swift in Sources */, A5C01700000000000000000B /* AccountSignInPanelView.swift in Sources */, A5C017000000000000000007 /* AccountSignInView.swift in Sources */, + A8587000000000000000004B /* AgentArtifactCaptureCheckpoint.swift in Sources */, + A85870000000000000000021 /* AgentArtifactCaptureCoordinator.swift in Sources */, + A8587000000000000000006F /* AgentArtifactCaptureProgress.swift in Sources */, + A85870000000000000000045 /* AgentArtifactCaptureSaveError.swift in Sources */, + A8610D000000000000000001 /* AgentArtifactCompletedCaptureState.swift in Sources */, + A8587000000000000000002B /* AgentArtifactReferenceCursor.swift in Sources */, C7AF10000000000000000005 /* AgentChatArtifactGalleryBuilder.swift in Sources */, C7AF10000000000000000001 /* AgentChatArtifactIndex.swift in Sources */, C7A52E000000000000000002 /* AgentChatEndedTranscriptListabilityCache.swift in Sources */, @@ -10899,20 +11104,32 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7A531000000000000000002 /* AgentChatObservationHandle.swift in Sources */, C7A532000000000000000002 /* AgentChatObservationInFlight.swift in Sources */, C7A530000000000000000002 /* AgentChatObservationScope.swift in Sources */, + C7A85870000000000000000A /* AgentChatObservedWorkingDirectoryResolver.swift in Sources */, + A8587F000000000000000031 /* AgentChatSessionRecencyIndex.swift in Sources */, ACA7C4A70000000000000001 /* AgentChatSessionRecord.swift in Sources */, C7A52D100000000000000012 /* AgentChatSessionRegistry+ChildRuns.swift in Sources */, C8711A000000000000000002 /* AgentChatSessionRegistry+CodexRolloutFiles.swift in Sources */, C7A52D100000000000000002 /* AgentChatSessionRegistry+Lifecycle.swift in Sources */, C7A52D200000000000000002 /* AgentChatSessionRegistry+LiveAgentPID.swift in Sources */, C7A52D000000000000000002 /* AgentChatSessionRegistry+ObserveScan.swift in Sources */, - ACA7C4A70000000000000007 /* AgentChatSessionRegistry.swift in Sources */, + ACA7C4A70000000000000007 /* AgentChatSessionRegistry.swift in Sources */, C0DE71A00000000000000001 /* AgentChatThemeSync.swift in Sources */, + A8587F000000000000000032 /* AgentChatTranscriptBoundedLineIterator.swift in Sources */, + A8587F000000000000000034 /* AgentChatTranscriptBoundedLineSequence.swift in Sources */, + A8610B000000000000000002 /* AgentChatTranscriptIncrementalLineBuffer.swift in Sources */, + C7A858700000000000000006 /* AgentChatTranscriptInitialTailReader.swift in Sources */, + A8610D000000000000000003 /* AgentChatTranscriptInitialTailSnapshot.swift in Sources */, + A8587F000000000000000011 /* AgentChatTranscriptReader.swift in Sources */, ACA7C4A70000000000000005 /* AgentChatTranscriptResolver.swift in Sources */, 992300019923000199230008 /* AgentChatTranscriptResumeIntentRecorder.swift in Sources */, + A85870000000000000000023 /* AgentChatTranscriptService+ArtifactCapture.swift in Sources */, A1B2C3D4E5F60718293A4B5D /* AgentChatTranscriptService+ArtifactSession.swift in Sources */, + C7A85870000000000000000D /* AgentChatTranscriptService+Resolution.swift in Sources */, C7A52F000000000000000002 /* AgentChatTranscriptService+Wire.swift in Sources */, ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */, + A8587F000000000000000021 /* AgentChatTranscriptSlice.swift in Sources */, ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */, + C7A858700000000000000008 /* AgentChatWorkingDirectoryAuthority.swift in Sources */, C0A710A10000000000000002 /* AgentCursorPointerView.swift in Sources */, 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */, A9F200000000000000000001 /* AgentExecutableResolver.swift in Sources */, @@ -11023,6 +11240,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 804100000000000000000009 /* AppDelegate+AdjacentNavigationShortcut.swift in Sources */, C0DE45AC0000000000000001 /* AppDelegate+AgentChat.swift in Sources */, C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources */, + A8587000000000000000003D /* AppDelegate+Artifacts.swift in Sources */, 986900010000000000000001 /* AppDelegate+BrowserActionRouting.swift in Sources */, D35A00000000000000000001 /* AppDelegate+BrowserDesignMode.swift in Sources */, C4A570010000000000000001 /* AppDelegate+CanvasShortcutRouting.swift in Sources */, @@ -11074,6 +11292,17 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A5001621 /* AppleScriptSupport.swift in Sources */, A5001A02A1B2C3D4E5F60718 /* AppWindowBackdropControllerDependencies.swift in Sources */, A5001A00A1B2C3D4E5F60718 /* AppWindowChromeComposition.swift in Sources */, + A85870000000000000000067 /* ArtifactHTMLPreviewDocument.swift in Sources */, + A8610D000000000000000005 /* ArtifactHTMLPreviewNavigationPolicy.swift in Sources */, + A8610D000000000000000007 /* ArtifactHTMLPreviewWebViewFactory.swift in Sources */, + A8610D00000000000000000B /* ArtifactSidebarBinding.swift in Sources */, + A85870000000000000000071 /* ArtifactSidebarFileAccess.swift in Sources */, + A85870000000000000000031 /* ArtifactSidebarPanelView.swift in Sources */, + A85870000000000000000033 /* ArtifactSidebarRowActions.swift in Sources */, + A85870000000000000000035 /* ArtifactSidebarRowView.swift in Sources */, + A8587000000000000000006B /* ArtifactSidebarSearchField.swift in Sources */, + A8587000000000000000006D /* ArtifactSidebarSearchFieldView.swift in Sources */, + A85870000000000000000037 /* ArtifactSidebarThumbnailView.swift in Sources */, 961300000000000000000003 /* AttributedString+SidebarRowLinks.swift in Sources */, D9FEC58D5BACCF76459F1BBE /* AuthEnvironment.swift in Sources */, A10649160000000000000001 /* AutomationActionExecutionResult.swift in Sources */, @@ -11210,6 +11439,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C67540060000000000000001 /* BrowserPanel+PDFDocumentActions.swift in Sources */, B424PWAD000000000000PW01 /* BrowserPanel+PrewarmedWebViewAdoption.swift in Sources */, A5001402 /* BrowserPanel.swift in Sources */, + A8610D000000000000000009 /* BrowserPanelContentMode.swift in Sources */, B1F0C0090000000000000001 /* BrowserPanelDeveloperToolsLifecycle.swift in Sources */, C62530010000000000000001 /* BrowserPanelReloadMode.swift in Sources */, A5001404 /* BrowserPanelView.swift in Sources */, @@ -11445,6 +11675,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C0DE43000000000000000003 /* CmuxSurfaceTabBarBuiltInAction+Codable.swift in Sources */, C10D00030000000000000003 /* CmuxSurfaceTabBarBuiltInAction.swift in Sources */, 0A1107110000000000000016 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift in Sources */, + A8610C000000000000000002 /* CmuxTaskManagerCodingAgentDefinition.swift in Sources */, 906901000000000000000004 /* CmuxTaskManagerMemoryAttribution.swift in Sources */, 906901000000000000000006 /* CmuxTaskManagerMemoryGroup.swift in Sources */, 90690100000000000000000C /* CmuxTaskManagerMemoryGroupAttribution.swift in Sources */, @@ -11536,6 +11767,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 3023A1003023A1003023A100 /* ConfigSource.swift in Sources */, D1F0A01100000000000000B1 /* ConnectivityInvalidationSubscriberCoordinator.swift in Sources */, C0DE43000000000000000005 /* ContentView+AgentChatCommandPalette.swift in Sources */, + A8587000000000000000003F /* ContentView+Artifacts.swift in Sources */, C0DEA7710000000000000001 /* ContentView+AuthCommandPalette.swift in Sources */, CA52E0010000000000000000 /* ContentView+CanvasCommandPalette.swift in Sources */, C51A720000000000000001A1 /* ContentView+CommandPaletteSurfaceMetadata.swift in Sources */, @@ -12034,7 +12266,9 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef D7769000000000000000000F /* NotificationsPopoverMetrics.swift in Sources */, D77690000000000000000007 /* NotificationsPopoverResizeHandle.swift in Sources */, D77690000000000000000009 /* NotificationsPopoverResizeView.swift in Sources */, + A86100000000000000000002 /* NSEvent+RightSidebarKeyboardNavigation.swift in Sources */, C01E00080000000000000001 /* NSTextView+FilePreviewTabWidth.swift in Sources */, + A85870000000000000000043 /* NSView+RightSidebarKeyboardFocus.swift in Sources */, 25C58D231850D0F414A62F19 /* NSView+WindowPointHitTest.swift in Sources */, D36090020000000000000001 /* NSWindow+CmuxPeerWindow.swift in Sources */, 7A0CE1000000000000000714 /* NWConnection+Async.swift in Sources */, @@ -12230,7 +12464,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7C5FAF2145342F395DB4C40 /* RestoredAgentLifecycleCoordinator.swift in Sources */, B7F9A600B7F9A600B7F9A600 /* RightSidebarChromeGeometryReporting.swift in Sources */, B7F9A604B7F9A604B7F9A604 /* RightSidebarChromeStyle.swift in Sources */, + A86100000000000000000004 /* RightSidebarDisclosureAction.swift in Sources */, + A8587000000000000000003B /* RightSidebarKeyboardFocusBridge.swift in Sources */, + A85870000000000000000041 /* RightSidebarKeyboardFocusView.swift in Sources */, B37A00000000000000000003 /* RightSidebarMode+Availability.swift in Sources */, + A85870000000000000000039 /* RightSidebarMode.swift in Sources */, 46814000000000000000000D /* RightSidebarModeShortcutEntry.swift in Sources */, 468110000000000000000005 /* RightSidebarModeShortcutMatcher.swift in Sources */, FE003103 /* RightSidebarPanelView.swift in Sources */, @@ -13062,6 +13300,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C3744E030000000000000002 /* AgentPIDProcessIdentity.swift in Sources */, 89930002AABBCCDDEEFF0002 /* AgentProcessBindingResolution.swift in Sources */, 394139F275D94FB49356E9C7 /* AgentSurfaceResumeBindingClearOutcome.swift in Sources */, + A85870000000000000000047 /* ArtifactCLIArguments.swift in Sources */, A10649260000000000000001 /* AutomationConfigMutationCoordinator.swift in Sources */, A10649060000000000000001 /* AutomationConfigStore.swift in Sources */, A10649180000000000000001 /* AutomationConfigStoreError.swift in Sources */, @@ -13093,6 +13332,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 9758B0119758B0119758B011 /* CMUXCLI+AmpExtensionSourcePart1.swift in Sources */, 9758B0129758B0129758B012 /* CMUXCLI+AmpExtensionSourcePart2.swift in Sources */, 9758B0139758B0139758B013 /* CMUXCLI+AmpExtensionSourcePart3.swift in Sources */, + A85870000000000000000011 /* CMUXCLI+Artifacts.swift in Sources */, A106490E0000000000000001 /* CMUXCLI+Automation.swift in Sources */, 6D9C51AB30A64B1ABC819142 /* CMUXCLI+AutoNaming.swift in Sources */, 6D9C51AB30A64B1ABC81914A /* CMUXCLI+AutoNamingDispatch.swift in Sources */, @@ -13135,6 +13375,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 906902000000000000000002 /* CMUXCLI+MemoryAttribution.swift in Sources */, 812600000000000000000005 /* CMUXCLI+MoshTerminalTransport.swift in Sources */, D7AB0000000000000000000D /* CMUXCLI+MoveTabToNewWorkspace.swift in Sources */, + A85870000000000000000055 /* CMUXCLI+Notes.swift in Sources */, 54D273BB0F1A89BFEA1E00E1 /* CMUXCLI+NotificationFormatting.swift in Sources */, B9000072A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift in Sources */, C08672010000000000000005 /* CMUXCLI+PiCompactedFeed.swift in Sources */, @@ -13144,7 +13385,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C08672010000000000000001 /* CMUXCLI+PiExtensionSourceDispatch.swift in Sources */, C05555010000000000000005 /* CMUXCLI+PiExtensionSourcePart1.swift in Sources */, C05555010000000000000007 /* CMUXCLI+PiExtensionSourcePart2.swift in Sources */, - B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */, + B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */, + A85870000000000000000057 /* CMUXCLI+ProjectFiles.swift in Sources */, C73660010000000000000001 /* CMUXCLI+RemotePTYErrors.swift in Sources */, REE0CA0000000000000000C2 /* CMUXCLI+Remotes.swift in Sources */, 925800000000000000000002 /* CMUXCLI+Restore.swift in Sources */, @@ -13195,6 +13437,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C8923639133F158AF1B6A0FB /* CMUXCLI+VPN.swift in Sources */, 7A0CE1000000000000000102 /* CMUXCLI+VPNAppManaged.swift in Sources */, 06CC2F6C1340C7424D1C7E0A /* CMUXCLI+WorkspaceTodo.swift in Sources */, + A8610C000000000000000004 /* CmuxTaskManagerCodingAgentDefinition+BuiltIns.swift in Sources */, + A8610C000000000000000003 /* CmuxTaskManagerCodingAgentDefinition.swift in Sources */, 918100000000000000000051 /* CodexHookFailureCandidate.swift in Sources */, 918100000000000000000041 /* CodexHookFailureSummary.swift in Sources */, 918100000000000000000061 /* CodexHookUserInputCandidate.swift in Sources */, @@ -13226,6 +13470,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C0DE1065100000000000000A /* LocalTmuxSessionListParser.swift in Sources */, C0DE1065100000000000000C /* LocalTmuxSessionReconciler.swift in Sources */, C0DE10651000000000000001 /* LocalTmuxSessionRegistry.swift in Sources */, + A85870000000000000000059 /* NoteCLIArguments.swift in Sources */, C08672010000000000000007 /* PiCompactedFeedEventExpander.swift in Sources */, 835000000000000000000002 /* RemoteInitialCommandBootstrap.swift in Sources */, B9000028A1B2C3D4E5F60719 /* RemoteInteractiveShellBootstrapBuilder.swift in Sources */, @@ -13327,6 +13572,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A11CE0010000000000000001 /* AboutLicensesResourceTests.swift in Sources */, A5C01700000000000000000F /* AccountSignInModelTests.swift in Sources */, + A85870000000000000000053 /* AgentArtifactAutomaticPathBoundTests.swift in Sources */, + A85870000000000000000049 /* AgentArtifactCaptureCoordinatorTests.swift in Sources */, + A85870000000000000000063 /* AgentArtifactCaptureCoordinatorTestStore.swift in Sources */, + C7A858700000000000000002 /* AgentArtifactProjectAuthorityTests.swift in Sources */, + A8587000000000000000004D /* AgentChatArtifactIndexSafetyTests.swift in Sources */, 5FAC71D5AC71D5AC71D50001 /* AgentChatChildRunTests.swift in Sources */, C7A540000000000000000002 /* AgentChatFallbackTranscriptResolutionCoordinatorTests.swift in Sources */, 99230001992300019923000C /* AgentChatResumeIntentRecorder.swift in Sources */, @@ -13336,6 +13586,8 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef C7A51E000000000000000002 /* AgentChatSessionRegistryLifecycleTests.swift in Sources */, C7A51D100000000000000002 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift in Sources */, C7A51D000000000000000002 /* AgentChatSessionRegistryObservationTests.swift in Sources */, + C7A85870000000000000000B /* AgentChatTranscriptResolutionReviewTests.swift in Sources */, + C7A858700000000000000004 /* AgentChatTranscriptTailerBoundedReadTests.swift in Sources */, 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */, A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */, 8740E0018740E0018740E001 /* AgentHibernationEvaluationSchedulingTests.swift in Sources */, @@ -13396,6 +13648,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef A11EAA000000000000000000 /* AppearanceSettingsTests.swift in Sources */, C8046FF15781CC7E4F8EAEA6 /* AppHostWindowReleaseGuardTests.swift in Sources */, A7206E010000000000000001 /* AppIconAppearanceObserverTests.swift in Sources */, + A8610D00000000000000000D /* ArtifactCLIIntegrationTests.swift in Sources */, + A85870000000000000000051 /* ArtifactCLITerminalSafetyTests.swift in Sources */, + A85870000000000000000065 /* ArtifactHTMLPreviewSecurityTests.swift in Sources */, + A8610D00000000000000000F /* ArtifactRightSidebarModeTests.swift in Sources */, + A85870000000000000000069 /* ArtifactRuntimeLifecycleTests.swift in Sources */, A47E00010000000000000001 /* AuthEnvironmentTests.swift in Sources */, A10649350000000000000001 /* AutomationProcessSessionTests.swift in Sources */, A10649110000000000000001 /* AutomationRuleTests.swift in Sources */, @@ -13775,6 +14032,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 7490A0017490A0017490A001 /* MemoryPressureMonitorTests.swift in Sources */, 606500010000000000000001 /* MenuBarOnlyActivationPolicyTests.swift in Sources */, C0DE70520000000000000002 /* MenuBarProfilingLauncherTests.swift in Sources */, + A8587000000000000000004F /* MobileChatArtifactAuthorizationSnapshotTests.swift in Sources */, 6AA2F2E8BEB19ED6B8E125DB /* MobileHostAuthorizationTests.swift in Sources */, C1A071000000000000000002 /* MobileHostConnectionEventLaneTests.swift in Sources */, C1A071000000000000000003 /* MobileHostConnectionLifecycleTests.swift in Sources */, @@ -13800,6 +14058,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef D5EB22366F37AB2B52CD4B2A /* NewMachineModelTests.swift in Sources */, EBEEFD57F5B44FD3D569C2A7 /* NewMachineModelUncappedPlanTests.swift in Sources */, A5FB1400 /* NewWorkspaceMenuModelTests.swift in Sources */, + A85870000000000000000061 /* NoteCLIIntegrationTests.swift in Sources */, 734F49D37E543DD01C2F4FEF /* NotificationAndMenuBarTests.swift in Sources */, D7AB00000000000000B021 /* NotificationDismissSyncTests.swift in Sources */, C0DEFEE50000000000000001 /* NotificationFeedHistoryTests.swift in Sources */, @@ -14756,6 +15015,10 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef isa = XCLocalSwiftPackageReference; relativePath = Packages/Shared/CmuxAgentChat; }; + A85870000000000000000001 /* XCLocalSwiftPackageReference "CmuxArtifacts" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Packages/macOS/CmuxArtifacts; + }; C0DE45000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */ = { isa = XCLocalSwiftPackageReference; relativePath = Packages/macOS/CmuxExtensionKit; @@ -14963,6 +15226,11 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef package = AC4A6E7C4A700001AC4A0003 /* XCLocalSwiftPackageReference "CmuxAgentChat" */; productName = CmuxAgentChat; }; + A85870000000000000000002 /* CmuxArtifacts */ = { + isa = XCSwiftPackageProductDependency; + package = A85870000000000000000001 /* XCLocalSwiftPackageReference "CmuxArtifacts" */; + productName = CmuxArtifacts; + }; C0DE45000000000000000002 /* CmuxExtensionKit */ = { isa = XCSwiftPackageProductDependency; package = C0DE45000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */; diff --git a/cmux.xcworkspace/contents.xcworkspacedata b/cmux.xcworkspace/contents.xcworkspacedata index a87f5c881dc9..a1443d35beeb 100644 --- a/cmux.xcworkspace/contents.xcworkspacedata +++ b/cmux.xcworkspace/contents.xcworkspacedata @@ -129,6 +129,9 @@ + + diff --git a/cmuxTests/AgentArtifactAutomaticPathBoundTests.swift b/cmuxTests/AgentArtifactAutomaticPathBoundTests.swift new file mode 100644 index 000000000000..ab2df693c228 --- /dev/null +++ b/cmuxTests/AgentArtifactAutomaticPathBoundTests.swift @@ -0,0 +1,132 @@ +import CMUXAgentLaunch +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Automatic artifact transcript path bounds") +struct AgentArtifactAutomaticPathBoundTests { + @MainActor + @Test( + "Artifact-only hook observation does not scan the Codex sessions tree", + arguments: [ + WorkstreamEvent.HookEventName.sessionStart, + WorkstreamEvent.HookEventName.userPromptSubmit, + ] + ) + func artifactOnlyHookObservationUsesBoundedResolution( + hookEventName: WorkstreamEvent.HookEventName + ) throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-hook-bound-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let projectRoot = root.appendingPathComponent("project", isDirectory: true) + let codexHome = root.appendingPathComponent("codex-home", isDirectory: true) + let sessionsDay = codexHome.appendingPathComponent("sessions/2026/07/21", isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: sessionsDay, withIntermediateDirectories: true) + let sessionID = "019f8c1c-1111-7222-8333-555555555555" + try Data().write(to: sessionsDay.appendingPathComponent( + "rollout-2026-07-21T00-00-00-\(sessionID).jsonl", + isDirectory: false + )) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + resolver: AgentChatTranscriptResolver( + homeDirectory: root, + environment: ["CODEX_HOME": codexHome.path] + ), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ) + ) + + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: hookEventName, + source: "codex", + workspaceId: "workspace", + transcriptPath: nil, + cwd: projectRoot.path + )) + + let session = try #require(service.debugSessionDump().first) + #expect(session["tailer_active"] as? Bool == false) + #expect(session["transcript_path"] == nil) + #expect(session["resolution_failed"] as? Bool == false) + } + + @MainActor + @Test("Automatic Codex capture does not scan the sessions tree without a recorded path") + func codexCaptureRequiresAnAuthoritativeTranscriptPath() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-path-bound-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let projectRoot = root.appendingPathComponent("project", isDirectory: true) + let codexHome = root.appendingPathComponent("codex-home", isDirectory: true) + let sessionsDay = codexHome.appendingPathComponent("sessions/2026/07/21", isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: sessionsDay, withIntermediateDirectories: true) + let artifact = root.appendingPathComponent("generated-plan.md", isDirectory: false) + try "plan".write(to: artifact, atomically: true, encoding: .utf8) + let sessionID = "019f8c1c-1111-7222-8333-444444444444" + let transcript = sessionsDay.appendingPathComponent( + "rollout-2026-07-21T00-00-00-\(sessionID).jsonl", + isDirectory: false + ) + try codexArtifactLine(path: artifact.path) + .write(to: transcript, atomically: true, encoding: .utf8) + let repository = LocalArtifactRepository() + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + resolver: AgentChatTranscriptResolver( + homeDirectory: root, + environment: ["CODEX_HOME": codexHome.path] + ), + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: repository) + ) + ) + let record = AgentChatSessionRecord( + sessionID: sessionID, + agentKind: .codex, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + + service.scheduleArtifactCapture(for: record) + let task = try #require(service.artifactCaptureTasks[sessionID]?.task) + await task.value + + #expect(!FileManager.default.fileExists( + atPath: ArtifactStorePaths(projectRoot: projectRoot).filesystemRoot.path + )) + } + + private func codexArtifactLine(path: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": "response_item", + "payload": [ + "type": "message", + "role": "assistant", + "content": [["type": "output_text", "text": "Saved artifact to \(path)"]], + ], + ]) + return String(decoding: data, as: UTF8.self) + } +} diff --git a/cmuxTests/AgentArtifactCaptureCoordinatorTestStore.swift b/cmuxTests/AgentArtifactCaptureCoordinatorTestStore.swift new file mode 100644 index 000000000000..5a06ca9a6f97 --- /dev/null +++ b/cmuxTests/AgentArtifactCaptureCoordinatorTestStore.swift @@ -0,0 +1,106 @@ +import CmuxArtifacts +import Foundation + +actor OutOfOrderCaptureStore: ArtifactStoring { + private let suspendsFirstImport: Bool + private let rejectsFirstImportAsBusy: Bool + private let captureConfiguration: ArtifactCaptureConfiguration + private var firstImportStarted: CheckedContinuation? + private var firstImportRelease: CheckedContinuation? + private(set) var importCount = 0 + private(set) var importedPaths: [String] = [] + + init( + suspendsFirstImport: Bool = true, + rejectsFirstImportAsBusy: Bool = false, + maximumFilesPerCapture: Int = ArtifactCaptureConfiguration.defaultValue.maximumFilesPerCapture, + configuration: ArtifactCaptureConfiguration = .defaultValue + ) { + self.suspendsFirstImport = suspendsFirstImport + self.rejectsFirstImportAsBusy = rejectsFirstImportAsBusy + var configuration = configuration + configuration.maximumFilesPerCapture = maximumFilesPerCapture + captureConfiguration = configuration + } + + func waitUntilFirstImportStarts() async { + guard importCount == 0 else { return } + await withCheckedContinuation { continuation in + firstImportStarted = continuation + } + } + + func releaseFirstImport() { + firstImportRelease?.resume() + firstImportRelease = nil + } + + func locateProjectRoot(startingAt url: URL) -> URL { + url + } + + func configuration(projectRoot _: URL) -> ArtifactCaptureConfiguration { + captureConfiguration + } + + func snapshot(projectRoot: URL) throws -> ArtifactSnapshot { + ArtifactSnapshot( + projectRoot: projectRoot, + filesystemRoot: projectRoot.appendingPathComponent(".cmux"), + nodes: [], + isTruncated: false + ) + } + + func search(projectRoot _: URL, query _: String) -> [ArtifactSearchResult] { + [] + } + + func importFile( + sourceURL _: URL, + context _: ArtifactCaptureContext, + provenance _: ArtifactProvenance, + configuration _: ArtifactCaptureConfiguration, + capturedAt _: Date + ) throws -> ArtifactImportOutcome { + .skipped(.notARegularFile) + } + + func importFiles( + candidates: [ArtifactCandidate], + context _: ArtifactCaptureContext, + configuration _: ArtifactCaptureConfiguration, + maximumBatchBytes _: Int64?, + capturedAt _: Date + ) async -> [ArtifactImportAttempt] { + importCount += 1 + if importCount == 1, rejectsFirstImportAsBusy { + firstImportStarted?.resume() + firstImportStarted = nil + return candidates.map { _ in + .rejected(.storeBusy("artifact store")) + } + } + importedPaths.append(contentsOf: candidates.map(\.sourceURL.path)) + if importCount == 1 { + firstImportStarted?.resume() + firstImportStarted = nil + } + if importCount == 1, suspendsFirstImport { + await withCheckedContinuation { continuation in + firstImportRelease = continuation + } + } + return candidates.map { _ in + .imported(.skipped(.notARegularFile)) + } + } + + func resolve(projectRoot _: URL, name: String) throws -> ArtifactNode { + throw ArtifactStoreError.artifactNotFound(name) + } + + func changes(projectRoot _: URL) -> AsyncStream { + AsyncStream { $0.finish() } + } +} diff --git a/cmuxTests/AgentArtifactCaptureCoordinatorTests.swift b/cmuxTests/AgentArtifactCaptureCoordinatorTests.swift new file mode 100644 index 000000000000..2e91a9db52a7 --- /dev/null +++ b/cmuxTests/AgentArtifactCaptureCoordinatorTests.swift @@ -0,0 +1,856 @@ +import CMUXAgentLaunch +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +struct AgentArtifactCaptureCoordinatorTests { + @MainActor + @Test("Startup schedules capture for a transcript already present on disk") + func startupSchedulesExistingTranscriptCapture() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let transcript = projectRoot.appendingPathComponent("startup.jsonl") + let artifact = projectRoot.appendingPathComponent("startup.md") + try "captured".write(to: artifact, atomically: true, encoding: .utf8) + try codexCommandLines( + command: "true > \(artifact.path)", + callID: "startup-capture" + ) + .joined(separator: "\n") + .write(to: transcript, atomically: true, encoding: .utf8) + + var record = captureRecord( + projectRoot: projectRoot, + agentKind: .codex, + sessionID: "startup-session", + state: .ended + ) + record.transcriptPath = transcript.path + let registry = AgentChatSessionRegistry( + hookStore: AgentChatHookSessionStore( + homeDirectory: projectRoot.appendingPathComponent("empty-home", isDirectory: true) + ), + restoredRecords: [record] + ) + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ), + isAutomaticArtifactCaptureEnabled: { true } + ) + + service.start() + await store.waitUntilFirstImportStarts() + + #expect(await store.importedPaths == [artifact.path]) + } + + @MainActor + @Test func scheduledCaptureContinuesPolicyBacklogWithoutNewEvent() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore( + suspendsFirstImport: false, + maximumFilesPerCapture: 1 + ) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: coordinator + ) + let record = captureRecord(projectRoot: projectRoot) + let snapshot = snapshot( + revision: 1, + artifacts: (1...3).map { index in + (projectRoot.appendingPathComponent("artifact-\(index).md").path, index) + } + ) + + service.scheduleIndexedArtifactCapture(record: record, snapshot: snapshot) + let task = try #require(service.artifactCaptureTasks[record.sessionID]?.task) + await task.value + + #expect(await store.importedPaths.count == 3) + #expect(await store.importCount == 3) + } + + @Test func newerSnapshotCapturesOnlyNewTranscriptReferences() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot) + let oldPath = projectRoot.appendingPathComponent("old.md").path + let newPath = projectRoot.appendingPathComponent("new.md").path + + await coordinator.capture( + record: record, + snapshot: snapshot(revision: 1, artifacts: [(oldPath, 1)]) + ) + await coordinator.capture( + record: record, + snapshot: snapshot(revision: 2, artifacts: [(oldPath, 1), (newPath, 2)]) + ) + + #expect(await store.importedPaths == [oldPath, newPath]) + } + + @Test func sameSizeTranscriptRewriteResetsCaptureCursor() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let oldPath = projectRoot.appendingPathComponent("z-old.md").path + let rewrittenPath = projectRoot.appendingPathComponent("a-new.md").path + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot) + let first = AgentChatArtifactIndex.Snapshot( + referencedPaths: [oldPath], + artifacts: [ChatArtifactIndexedReference( + path: oldPath, + provenance: .created, + lastReferencedSeq: 1 + )], + generation: "generation-1", + revision: 1, + transcriptExtent: 100 + ) + let rewritten = AgentChatArtifactIndex.Snapshot( + referencedPaths: [rewrittenPath], + artifacts: [ChatArtifactIndexedReference( + path: rewrittenPath, + provenance: .created, + lastReferencedSeq: 1 + )], + generation: "generation-2", + revision: 2, + transcriptExtent: 100 + ) + + await coordinator.capture(record: record, snapshot: first) + await coordinator.capture(record: record, snapshot: rewritten) + + #expect(await store.importedPaths == [oldPath, rewrittenPath]) + } + + @Test func missingSourceDoesNotStarveLaterArtifact() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let missing = projectRoot.appendingPathComponent("missing.md") + let source = projectRoot.appendingPathComponent("available.md") + try "available".write(to: source, atomically: true, encoding: .utf8) + let store = LocalArtifactRepository() + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot) + let indexed = snapshot( + revision: 1, + artifacts: [(missing.path, 1), (source.path, 2)] + ) + + await coordinator.capture(record: record, snapshot: indexed) + + let snapshot = try await store.snapshot(projectRoot: projectRoot) + #expect(snapshot.nodes.flattenedArtifactNodes().contains { $0.name == source.lastPathComponent }) + } + + @Test func busyStoreDoesNotCheckpointAnAutomaticArtifact() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore( + suspendsFirstImport: false, + rejectsFirstImportAsBusy: true + ) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot) + let indexed = snapshot( + revision: 1, + path: projectRoot.appendingPathComponent("plan.md").path + ) + + await coordinator.capture(record: record, snapshot: indexed) + await coordinator.capture(record: record, snapshot: indexed) + + #expect(await store.importCount == 2) + #expect(await store.importedPaths == [projectRoot.appendingPathComponent("plan.md").path]) + } + + @Test func transcriptTruncationResetsTheCompletedReferenceCursor() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let transcript = projectRoot.appendingPathComponent("transcript.jsonl") + let oldPath = projectRoot.appendingPathComponent("old.md").path + let newPath = projectRoot.appendingPathComponent("new.md").path + try (Array(repeating: "{}", count: 20) + [codexArtifactLine(path: oldPath)]) + .joined(separator: "\n") + .write(to: transcript, atomically: true, encoding: .utf8) + let index = AgentChatArtifactIndex() + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot, agentKind: .codex) + + let first = try await index.snapshot( + sessionID: record.sessionID, + agentKind: record.agentKind, + transcriptPath: transcript.path, + workingDirectory: record.workingDirectory + ) + await coordinator.capture(record: record, snapshot: first) + try codexArtifactLine(path: newPath) + .write(to: transcript, atomically: true, encoding: .utf8) + let truncated = try await index.snapshot( + sessionID: record.sessionID, + agentKind: record.agentKind, + transcriptPath: transcript.path, + workingDirectory: record.workingDirectory + ) + await coordinator.capture(record: record, snapshot: truncated) + + #expect(await store.importedPaths == [oldPath, newPath]) + } + + @MainActor + @Test func sameSnapshotReplacementFinishesActiveBatchBeforePendingWork() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore(maximumFilesPerCapture: 1) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: coordinator + ) + let record = captureRecord(projectRoot: projectRoot) + let snapshot = snapshot( + revision: 1, + artifacts: [ + (projectRoot.appendingPathComponent("one.md").path, 1), + (projectRoot.appendingPathComponent("two.md").path, 2), + ] + ) + + service.scheduleIndexedArtifactCapture(record: record, snapshot: snapshot) + let activeTask = try #require(service.artifactCaptureTasks[record.sessionID]?.task) + await store.waitUntilFirstImportStarts() + service.scheduleIndexedArtifactCapture(record: record, snapshot: snapshot) + await store.releaseFirstImport() + await activeTask.value + + #expect(await store.importedPaths.count == 2) + } + + @Test func sequentialStaleSnapshotDoesNotRegressCompletedGeneration() async throws { + let projectRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: projectRoot) } + + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = AgentChatSessionRecord( + sessionID: "session", + agentKind: .claude, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let older = snapshot( + revision: 1, + path: projectRoot.appendingPathComponent("older.md").path + ) + let newer = snapshot( + revision: 2, + path: projectRoot.appendingPathComponent("newer.md").path + ) + + await coordinator.capture(record: record, snapshot: newer) + await coordinator.capture(record: record, snapshot: older) + await coordinator.capture(record: record, snapshot: newer) + + #expect(await store.importCount == 1) + } + + @MainActor + @Test func completedCaptureTaskIsReleased() async throws { + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: coordinator + ) + let record = AgentChatSessionRecord( + sessionID: "session", + agentKind: .claude, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: FileManager.default.temporaryDirectory.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let snapshot = AgentChatArtifactIndex.Snapshot( + referencedPaths: [], + artifacts: [], + generation: "empty", + revision: 1 + ) + + service.scheduleIndexedArtifactCapture(record: record, snapshot: snapshot) + let task = try #require(service.artifactCaptureTasks[record.sessionID]?.task) + await task.value + + #expect(service.artifactCaptureTasks[record.sessionID] == nil) + } + + @MainActor + @Test func automaticCaptureTracksLiveArtifactsBetaAvailability() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + var artifactsBetaEnabled = false + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: coordinator, + isAutomaticArtifactCaptureEnabled: { artifactsBetaEnabled } + ) + let record = captureRecord(projectRoot: projectRoot) + let indexed = snapshot( + revision: 1, + path: projectRoot.appendingPathComponent("plan.md").path + ) + + service.scheduleIndexedArtifactCapture(record: record, snapshot: indexed) + #expect(service.artifactCaptureTasks[record.sessionID] == nil) + + artifactsBetaEnabled = true + service.scheduleIndexedArtifactCapture(record: record, snapshot: indexed) + let task = try #require(service.artifactCaptureTasks[record.sessionID]?.task) + await task.value + + #expect(await store.importCount == 1) + } + + @MainActor + @Test func streamedProseBatchesShareOneDebouncedCapture() throws { + let registry = AgentChatSessionRegistry() + let sessionID = UUID().uuidString + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + registry.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: nil, + cwd: projectRoot.path, + ppid: nil + )) + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + ) + let firstMessage = ChatMessage( + id: "prose-1", + seq: 1, + role: .agent, + timestamp: Date(timeIntervalSince1970: 1), + kind: .prose(ChatProse(text: "first chunk")) + ) + let secondMessage = ChatMessage( + id: "prose-2", + seq: 2, + role: .agent, + timestamp: Date(timeIntervalSince1970: 2), + kind: .prose(ChatProse(text: "second chunk")) + ) + + service.publishBatch( + AgentChatTranscriptTailer.Batch( + appended: [firstMessage], + updated: [], + discoveredTitle: nil + ), + sessionID: sessionID + ) + let firstToken = try #require( + service.artifactCaptureDebounceTasks[sessionID]?.token + ) + service.publishBatch( + AgentChatTranscriptTailer.Batch( + appended: [secondMessage], + updated: [], + discoveredTitle: nil + ), + sessionID: sessionID + ) + let secondToken = try #require( + service.artifactCaptureDebounceTasks[sessionID]?.token + ) + + #expect(firstToken != secondToken) + #expect(service.artifactCaptureDebounceTasks.count == 1) + #expect(service.artifactCaptureTasks[sessionID] == nil) + } + + @MainActor + @Test func lateAuthorizedToolUpdateSchedulesDebouncedCapture() throws { + let registry = AgentChatSessionRegistry() + let sessionID = UUID().uuidString + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + registry.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: nil, + cwd: projectRoot.path, + ppid: nil + )) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService( + store: OutOfOrderCaptureStore(suspendsFirstImport: false) + ) + ) + ) + let updatedTool = ChatMessage( + id: "apply-patch", + seq: 4, + role: .agent, + timestamp: Date(timeIntervalSince1970: 4), + kind: .toolUse(ChatToolUse( + toolName: "apply_patch", + summary: "apply_patch plan.md", + status: .succeeded, + referencedPaths: [projectRoot.appendingPathComponent("plan.md").path], + artifactMutationAuthorized: true + )) + ) + + service.publishBatch( + AgentChatTranscriptTailer.Batch( + appended: [], + updated: [updatedTool], + discoveredTitle: nil + ), + sessionID: sessionID + ) + + #expect(service.artifactCaptureDebounceTasks[sessionID] != nil) + #expect(service.artifactCaptureTasks[sessionID] == nil) + } + + @MainActor + @Test func sidechainMutationAuthorizationSchedulesCaptureWithoutVisibleRow() throws { + let registry = AgentChatSessionRegistry() + let sessionID = UUID().uuidString + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + registry.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: nil, + cwd: projectRoot.path, + ppid: nil + )) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService( + store: OutOfOrderCaptureStore(suspendsFirstImport: false) + ) + ) + ) + + service.publishBatch( + AgentChatTranscriptTailer.Batch( + appended: [], + updated: [], + discoveredTitle: nil, + didAuthorizeArtifactMutation: true + ), + sessionID: sessionID + ) + + #expect(service.artifactCaptureDebounceTasks[sessionID] != nil) + } + + @MainActor + @Test func successfulReadOnlyTerminalDoesNotScheduleCapture() throws { + let registry = AgentChatSessionRegistry() + let sessionID = UUID().uuidString + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + registry.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: nil, + cwd: projectRoot.path, + ppid: nil + )) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService( + store: OutOfOrderCaptureStore(suspendsFirstImport: false) + ) + ) + ) + service.publishBatch( + AgentChatTranscriptTailer.Batch( + appended: [ChatMessage( + id: "ls", + seq: 1, + role: .agent, + timestamp: Date(timeIntervalSince1970: 2), + kind: .terminal(ChatTerminalCapture( + command: "ls -la", + output: "notes.md", + exitCode: 0, + isRunning: false + ))) + ], + updated: [], + discoveredTitle: nil + ), + sessionID: sessionID + ) + + #expect(service.artifactCaptureDebounceTasks[sessionID] == nil) + } + + @MainActor + @Test func deinitCancelsActiveAutomaticCaptureTask() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore() + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = captureRecord(projectRoot: projectRoot) + let indexed = snapshot( + revision: 1, + path: projectRoot.appendingPathComponent("plan.md").path + ) + var service: AgentChatTranscriptService? = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: coordinator + ) + service?.scheduleIndexedArtifactCapture(record: record, snapshot: indexed) + let captureTask = try #require(service?.artifactCaptureTasks[record.sessionID]?.task) + await store.waitUntilFirstImportStarts() + service = nil + + #expect(captureTask.isCancelled) + await store.releaseFirstImport() + await captureTask.value + } + + @MainActor + @Test func completedTranscriptTurnsCaptureWithoutMobileSubscribers() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let artifact = projectRoot.appendingPathComponent("completed-plan.md") + try "plan".write(to: artifact, atomically: true, encoding: .utf8) + let transcript = projectRoot.appendingPathComponent("transcript.jsonl") + try "".write(to: transcript, atomically: true, encoding: .utf8) + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + ) + let sessionID = "24ec0052-450c-4914-b1dd-2ee80d4bc84b" + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: transcript.path, + cwd: projectRoot.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: 1) + )) + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == true) + try claudeArtifactLine(path: artifact.path).write( + to: transcript, + atomically: true, + encoding: .utf8 + ) + + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .stop, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: transcript.path, + cwd: projectRoot.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: 2) + )) + let task = try #require(service.artifactCaptureTasks[sessionID]?.task) + await task.value + + #expect(await store.importedPaths == [artifact.path]) + } + + @Test func automaticTranscriptSnapshotRejectsFinalSymlinks() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let target = projectRoot.appendingPathComponent("real.jsonl") + let transcript = projectRoot.appendingPathComponent("transcript.jsonl") + try Data("{}\n".utf8).write(to: target) + try FileManager.default.createSymbolicLink(at: transcript, withDestinationURL: target) + + await #expect(throws: (any Error).self) { + _ = try await AgentChatArtifactIndex().snapshot( + sessionID: "session", + agentKind: .claude, + transcriptPath: transcript.path, + workingDirectory: projectRoot.path, + maximumFileBytes: 1_024 + ) + } + } + + @Test func completedCaptureProgressIsBoundedAcrossEndedSessions() async throws { + let projectRoot = try temporaryProjectRoot() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + for index in 0...64 { + let record = captureRecord( + projectRoot: projectRoot, + sessionID: "ended-\(index)", + state: .ended + ) + let path = projectRoot.appendingPathComponent("artifact-\(index).md").path + await coordinator.capture( + record: record, + snapshot: snapshot(revision: 1, artifacts: [(path, 1)]) + ) + } + let oldest = captureRecord(projectRoot: projectRoot, sessionID: "ended-0", state: .ended) + let oldestPath = projectRoot.appendingPathComponent("artifact-0.md").path + await coordinator.capture( + record: oldest, + snapshot: snapshot(revision: 1, artifacts: [(oldestPath, 1)]) + ) + + #expect(await store.importCount == 66) + } + + @Test func olderCaptureFinishingLastDoesNotRegressCompletedGeneration() async throws { + let projectRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: projectRoot) } + + let store = OutOfOrderCaptureStore() + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = AgentChatSessionRecord( + sessionID: "session", + agentKind: .claude, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let older = snapshot( + revision: 1, + path: projectRoot.appendingPathComponent("older.md").path + ) + let newer = snapshot( + revision: 2, + path: projectRoot.appendingPathComponent("newer.md").path + ) + + let olderTask = Task { + await coordinator.capture(record: record, snapshot: older) + } + await store.waitUntilFirstImportStarts() + + await coordinator.capture(record: record, snapshot: newer) + await store.releaseFirstImport() + await olderTask.value + + await coordinator.capture(record: record, snapshot: newer) + + #expect(await store.importCount == 2) + } + + private func snapshot( + revision: UInt64, + path: String + ) -> AgentChatArtifactIndex.Snapshot { + snapshot(revision: revision, artifacts: [(path, Int(revision))]) + } + + private func snapshot( + revision: UInt64, + artifacts: [(path: String, sequence: Int)] + ) -> AgentChatArtifactIndex.Snapshot { + return AgentChatArtifactIndex.Snapshot( + referencedPaths: Set(artifacts.map(\.path)), + artifacts: artifacts.map { + ChatArtifactIndexedReference( + path: $0.path, + provenance: .created, + lastReferencedSeq: $0.sequence + ) + }, + generation: String(revision), + revision: revision + ) + } + + private func temporaryProjectRoot() throws -> URL { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + private func captureRecord( + projectRoot: URL, + agentKind: ChatAgentKind = .claude, + sessionID: String = "session", + state: ChatAgentState = .idle + ) -> AgentChatSessionRecord { + AgentChatSessionRecord( + sessionID: sessionID, + agentKind: agentKind, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: state, + lastActivityAt: .now, + title: nil, + pid: nil + ) + } + + private func codexArtifactLine(path: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": "response_item", + "payload": [ + "type": "message", + "role": "assistant", + "content": [["type": "output_text", "text": "Saved artifact to \(path)"]], + ], + ]) + return String(decoding: data, as: UTF8.self) + } + + private func codexCommandLines(command: String, callID: String) throws -> [String] { + [ + try codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": try json(["cmd": command]), + "call_id": callID, + ]), + try codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": callID, + "output": "Process exited with code 0\nOutput:\n", + ]), + ] + } + + private func codexLine(type: String, payload: [String: Any]) throws -> String { + try json([ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": type, + "payload": payload, + ]) + } + + private func json(_ object: [String: Any]) throws -> String { + String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self) + } + + private func claudeArtifactLine(path: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "type": "assistant", + "isSidechain": false, + "uuid": UUID().uuidString, + "timestamp": "2026-07-21T12:00:00.000Z", + "message": [ + "role": "assistant", + "content": [[ + "type": "tool_use", + "id": "write-plan", + "name": "Write", + "input": ["file_path": path, "content": "plan"], + ]], + ], + ]) + return String(decoding: data, as: UTF8.self) + } +} diff --git a/cmuxTests/AgentArtifactProjectAuthorityTests.swift b/cmuxTests/AgentArtifactProjectAuthorityTests.swift new file mode 100644 index 000000000000..ac70d37015fe --- /dev/null +++ b/cmuxTests/AgentArtifactProjectAuthorityTests.swift @@ -0,0 +1,100 @@ +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Artifact project authority") +struct AgentArtifactProjectAuthorityTests { + @Test("An unverified working directory cannot select an artifact store") + func unverifiedWorkingDirectoryFailsClosed() async { + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = AgentChatSessionRecord( + sessionID: "observed-session", + agentKind: .codex, + workspaceID: "workspace", + surfaceID: "surface", + workingDirectory: "/tmp/inherited-project", + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + + #expect(await coordinator.captureContext(for: record) == nil) + } + + @MainActor + @Test("Process PWD remains readable but cannot authorize persistence") + func processObservationDoesNotAuthorizePersistence() async throws { + let registry = AgentChatSessionRegistry() + registry.applyObservedSessions([ + ObservedAgentSession( + sessionID: "observed-session", + agentKind: .codex, + surfaceID: "surface", + workspaceID: "workspace", + pid: Int(ProcessInfo.processInfo.processIdentifier), + workingDirectory: "/tmp/inherited-project", + transcriptPath: nil + ), + ]) + let record = try #require(registry.record(sessionID: "observed-session")) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService( + store: OutOfOrderCaptureStore(suspendsFirstImport: false) + ) + ) + + #expect(record.workingDirectory == "/tmp/inherited-project") + #expect(record.workingDirectoryAuthority == .processObservation) + #expect(await coordinator.captureContext(for: record) == nil) + } + + @Test("Observed launch cwd is preferred but remains non-authoritative") + func classifiesObservedDirectoryAuthority() { + let resolver = AgentChatObservedWorkingDirectoryResolver() + + let inherited = resolver.resolve(environment: ["PWD": "/tmp/inherited"]) + let launched = resolver.resolve(environment: [ + "CMUX_AGENT_LAUNCH_CWD": "/project/launch", + "PWD": "/tmp/inherited", + ]) + + #expect(inherited.path == "/tmp/inherited") + #expect(inherited.authority == .processObservation) + #expect(launched.path == "/project/launch") + #expect(launched.authority == .processObservation) + } + + @MainActor + @Test("A cmux resume binding authorizes its project directory") + func cmuxResumeBindingAuthorizesPersistence() async throws { + let registry = AgentChatSessionRegistry() + registry.noteResumeInitiated( + sessionID: "resumed-session", + source: "codex", + surfaceID: "surface", + workspaceID: "workspace", + workingDirectory: "/tmp/cmux-authoritative-project" + ) + let record = try #require(registry.record(sessionID: "resumed-session")) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService( + store: OutOfOrderCaptureStore(suspendsFirstImport: false) + ) + ) + + #expect(record.workingDirectoryAuthority == .cmuxLaunch) + #expect(await coordinator.captureContext(for: record) != nil) + } +} diff --git a/cmuxTests/AgentChatArtifactIndexSafetyTests.swift b/cmuxTests/AgentChatArtifactIndexSafetyTests.swift new file mode 100644 index 000000000000..f7df7327207e --- /dev/null +++ b/cmuxTests/AgentChatArtifactIndexSafetyTests.swift @@ -0,0 +1,474 @@ +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +struct AgentChatArtifactIndexSafetyTests { + @Test func transcriptLineSequenceDecodesOnlyItsBoundedPrefix() { + let data = Data((0..<10).map { "line-\($0)\n" }.joined().utf8) + let lines = Array(AgentChatTranscriptReader.BoundedLineSequence( + data: data, + maximumLineCount: 3 + )) + + #expect(lines == ["line-0", "line-1", "line-2"]) + } + + @Test func cacheGenerationIncludesTranscriptIdentityAndScanLimit() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + let alias = root.appendingPathComponent("alias.jsonl") + try Data("{}\n".utf8).write(to: transcript) + try FileManager.default.linkItem(at: transcript, to: alias) + + let index = AgentChatArtifactIndex() + let fullSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .claude, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 4_096 + ) + let narrowSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .claude, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 2_048 + ) + let aliasSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .claude, + transcriptPath: alias.path, + workingDirectory: root.path, + maximumFileBytes: 4_096 + ) + + #expect(fullSnapshot.generation != narrowSnapshot.generation) + #expect(fullSnapshot.generation != aliasSnapshot.generation) + } + + @Test func oversizedTranscriptDoesNotTrustArtifactsOutsideItsCurrentTail() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + let firstArtifactPath = root.appendingPathComponent("first.md").path + let secondArtifactPath = root.appendingPathComponent("second.md").path + let prefix = Array(repeating: String(repeating: "x", count: 80), count: 20) + let artifactLine = try codexArtifactLine(path: firstArtifactPath) + let initialTranscript = (prefix + [artifactLine]).joined(separator: "\n") + try initialTranscript.write(to: transcript, atomically: true, encoding: .utf8) + let firstArtifactOffset = (prefix.joined(separator: "\n") + "\n").utf8.count + let index = AgentChatArtifactIndex() + + let firstSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 512 + ) + let firstArtifact = try #require(firstSnapshot.artifacts.first) + #expect(firstArtifact.path == firstArtifactPath) + #expect(firstArtifact.lastReferencedSeq == firstArtifactOffset) + + let appendedPrefix = Array(repeating: String(repeating: "y", count: 80), count: 20) + let appendedLines = appendedPrefix + [try codexArtifactLine(path: secondArtifactPath)] + let secondArtifactOffset = initialTranscript.utf8.count + + 1 + + appendedPrefix.joined(separator: "\n").utf8.count + + 1 + let handle = try FileHandle(forWritingTo: transcript) + try handle.seekToEnd() + try handle.write(contentsOf: Data(("\n" + appendedLines.joined(separator: "\n")).utf8)) + try handle.close() + let secondSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 512 + ) + + let artifacts = Dictionary(uniqueKeysWithValues: secondSnapshot.artifacts.map { + ($0.path, $0.lastReferencedSeq) + }) + #expect(artifacts[firstArtifactPath] == nil) + #expect(artifacts[secondArtifactPath] == secondArtifactOffset) + + try FileManager.default.setAttributes( + [.modificationDate: Date(timeIntervalSinceNow: 60)], + ofItemAtPath: transcript.path + ) + let metadataOnlySnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 512 + ) + let metadataOnlyArtifacts = Dictionary(uniqueKeysWithValues: + metadataOnlySnapshot.artifacts.map { ($0.path, $0.lastReferencedSeq) } + ) + #expect(metadataOnlyArtifacts[firstArtifactPath] == nil) + #expect(metadataOnlyArtifacts[secondArtifactPath] == secondArtifactOffset) + } + + @Test func canceledSnapshotStopsBeforeTranscriptParsing() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + try Data("{}\n".utf8).write(to: transcript) + + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try await AgentChatArtifactIndex().snapshot( + sessionID: "session", + agentKind: .claude, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 1_024 + ) + } + + await #expect(throws: CancellationError.self) { + _ = try await task.value + } + } + + @Test func inPlaceTranscriptRewriteDropsPreviousAuthorization() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + let oldArtifactPath = root.appendingPathComponent("old.md").path + let newArtifactPath = root.appendingPathComponent("new.md").path + let initialTranscript = try codexArtifactLine(path: oldArtifactPath) + try Data(initialTranscript.utf8).write(to: transcript) + let index = AgentChatArtifactIndex() + + let initialSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 4_096 + ) + #expect(initialSnapshot.referencedPaths == [oldArtifactPath]) + + let replacementTranscript = try codexArtifactLine(path: newArtifactPath) + + "\n" + + String(repeating: "{}\n", count: 512) + #expect(replacementTranscript.utf8.count > initialTranscript.utf8.count) + let handle = try FileHandle(forWritingTo: transcript) + try handle.truncate(atOffset: 0) + try handle.write(contentsOf: Data(replacementTranscript.utf8)) + try handle.close() + + let replacementSnapshot = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 4_096 + ) + + #expect(replacementSnapshot.referencedPaths == [newArtifactPath]) + #expect(!replacementSnapshot.referencedPaths.contains(oldArtifactPath)) + } + + @Test func retainedArtifactAuthorizationIsBoundedByRecency() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + let artifactPaths = (0...1_024).map { + root.appendingPathComponent("artifact-\($0).md").path + } + let lines = try artifactPaths.map(codexArtifactLine(path:)) + try Data(lines.joined(separator: "\n").utf8).write(to: transcript) + + let snapshot = try await AgentChatArtifactIndex().snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 4 * 1024 * 1024 + ) + + #expect(snapshot.artifacts.count == 1_024) + #expect(snapshot.referencedPaths.count == 1_024) + #expect(snapshot.referencedPaths.contains(try #require(artifactPaths.last))) + #expect(!snapshot.referencedPaths.contains(try #require(artifactPaths.first))) + } + + @Test func laterReadDoesNotReuseEarlierMutationAuthorization() async throws { + let projectRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + let externalRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: externalRoot, withIntermediateDirectories: true) + defer { + try? FileManager.default.removeItem(at: projectRoot) + try? FileManager.default.removeItem(at: externalRoot) + } + let artifact = externalRoot.appendingPathComponent("private.md") + try "generated".write(to: artifact, atomically: true, encoding: .utf8) + let transcript = projectRoot.appendingPathComponent("transcript.jsonl") + let createdLines = try codexCommandLines( + command: "true > \(artifact.path)", + callID: "create" + ) + try createdLines.joined(separator: "\n") + .write(to: transcript, atomically: true, encoding: .utf8) + let index = AgentChatArtifactIndex() + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = AgentChatSessionRecord( + sessionID: "session", + agentKind: .codex, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: transcript.path, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + + let created = try await index.snapshot( + sessionID: record.sessionID, + agentKind: record.agentKind, + transcriptPath: transcript.path, + workingDirectory: record.workingDirectory + ) + await coordinator.capture(record: record, snapshot: created) + try "unrelated private contents".write( + to: artifact, + atomically: true, + encoding: .utf8 + ) + let readLines = try codexCommandLines( + command: "cat \(artifact.path)", + callID: "read" + ) + let handle = try FileHandle(forWritingTo: transcript) + try handle.seekToEnd() + try handle.write(contentsOf: Data(("\n" + readLines.joined(separator: "\n")).utf8)) + try handle.close() + let read = try await index.snapshot( + sessionID: record.sessionID, + agentKind: record.agentKind, + transcriptPath: transcript.path, + workingDirectory: record.workingDirectory + ) + + await coordinator.capture(record: record, snapshot: read) + + #expect(await store.importCount == 1) + #expect(await store.importedPaths == [artifact.path]) + } + + @Test func captureContinuationPreservesAnOlderUnprocessedAuthorization() async throws { + let projectRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + let externalRoot = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: projectRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: externalRoot, withIntermediateDirectories: true) + defer { + try? FileManager.default.removeItem(at: projectRoot) + try? FileManager.default.removeItem(at: externalRoot) + } + let first = externalRoot.appendingPathComponent("first.md") + let delayed = externalRoot.appendingPathComponent("delayed.md") + try "first".write(to: first, atomically: true, encoding: .utf8) + try "delayed".write(to: delayed, atomically: true, encoding: .utf8) + let store = OutOfOrderCaptureStore( + suspendsFirstImport: false, + maximumFilesPerCapture: 1 + ) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + let record = AgentChatSessionRecord( + sessionID: "session", + agentKind: .codex, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: projectRoot.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let snapshot = AgentChatArtifactIndex.Snapshot( + referencedPaths: [first.path, delayed.path], + artifacts: [ + ChatArtifactIndexedReference( + path: first.path, + provenance: .created, + lastReferencedSeq: 50, + captureAuthorization: .created(sequence: 50) + ), + ChatArtifactIndexedReference( + path: delayed.path, + provenance: .created, + lastReferencedSeq: 100, + captureAuthorization: .created(sequence: 1) + ), + ], + generation: "generation", + revision: 1, + transcriptLineage: "lineage", + transcriptExtent: 101 + ) + + let firstProgress = await coordinator.capture(record: record, snapshot: snapshot) + let secondProgress = await coordinator.capture(record: record, snapshot: snapshot) + + #expect(firstProgress == .needsContinuation) + #expect(secondProgress == .complete) + #expect(await store.importedPaths == [first.path, delayed.path]) + } + + @Test func fragmentedTranscriptRetainsABoundedLineIndex() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("fragmented.jsonl") + let data = Data(Array(repeating: "{}\n", count: 20_000).joined().utf8) + try data.write(to: transcript) + let handle = try FileHandle(forReadingFrom: transcript) + defer { try? handle.close() } + + let slice = try AgentChatTranscriptReader().read( + handle: handle, + fileSize: UInt64(data.count), + maximumBytes: UInt64(data.count) + ) + + #expect(slice.lineStartOffsets.count <= 16_384) + #expect(slice.data.count < data.count) + } + + @Test func oversizedPrefixRewriteDropsRetainedArtifactAuthority() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("transcript.jsonl") + let removedArtifact = root.appendingPathComponent("removed.md").path + let retainedArtifact = root.appendingPathComponent("retained.md").path + let createdLines = try codexCommandLines( + command: "true > \(removedArtifact)", + callID: "create" + ) + let initialTranscript = createdLines.joined(separator: "\n") + try initialTranscript.write(to: transcript, atomically: true, encoding: .utf8) + let index = AgentChatArtifactIndex() + let initial = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 1_024 + ) + #expect(initial.artifacts.first?.captureAuthorization != nil) + + let appendedLines = Array(repeating: "{}", count: 256) + + [try codexArtifactLine(path: retainedArtifact)] + let handle = try FileHandle(forWritingTo: transcript) + try handle.seekToEnd() + try handle.write(contentsOf: Data(("\n" + appendedLines.joined(separator: "\n")).utf8)) + try handle.close() + let appended = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 1_024 + ) + #expect(appended.referencedPaths.contains(removedArtifact)) + + let rewrite = try FileHandle(forWritingTo: transcript) + try rewrite.seek(toOffset: 0) + try rewrite.write(contentsOf: Data(repeating: 0x20, count: initialTranscript.utf8.count)) + try rewrite.close() + let rewritten = try await index.snapshot( + sessionID: "session", + agentKind: .codex, + transcriptPath: transcript.path, + workingDirectory: root.path, + maximumFileBytes: 1_024 + ) + + #expect(!rewritten.referencedPaths.contains(removedArtifact)) + #expect(!rewritten.artifacts.contains { $0.path == removedArtifact }) + #expect(rewritten.referencedPaths.contains(retainedArtifact)) + } + + private func codexArtifactLine(path: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": "response_item", + "payload": [ + "type": "message", + "role": "assistant", + "content": [["type": "output_text", "text": "Saved artifact to \(path)"]], + ], + ]) + return String(decoding: data, as: UTF8.self) + } + + private func codexCommandLines(command: String, callID: String) throws -> [String] { + [ + try codexLine(type: "response_item", payload: [ + "type": "function_call", + "name": "exec_command", + "arguments": json(["cmd": command]), + "call_id": callID, + ]), + try codexLine(type: "response_item", payload: [ + "type": "function_call_output", + "call_id": callID, + "output": "Process exited with code 0\nOutput:\n", + ]), + ] + } + + private func codexLine(type: String, payload: [String: Any]) throws -> String { + try json([ + "timestamp": "2026-07-21T12:00:00.000Z", + "type": type, + "payload": payload, + ]) + } + + private func json(_ object: [String: Any]) throws -> String { + String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self) + } +} diff --git a/cmuxTests/AgentChatSessionRegistryLifecycleReviewRegressionTests.swift b/cmuxTests/AgentChatSessionRegistryLifecycleReviewRegressionTests.swift index 2b55d334bff0..1ad1965cc1b8 100644 --- a/cmuxTests/AgentChatSessionRegistryLifecycleReviewRegressionTests.swift +++ b/cmuxTests/AgentChatSessionRegistryLifecycleReviewRegressionTests.swift @@ -1,5 +1,6 @@ import CMUXAgentLaunch import CmuxAgentChat +import CmuxArtifacts import Foundation @preconcurrency import Network import Testing @@ -11,6 +12,35 @@ import Testing #endif struct AgentChatSessionRegistryLifecycleReviewRegressionTests { + @MainActor + @Test func cancelledHistoryResolutionIsNotCachedAsMissing() async throws { + let home = try temporaryHomeDirectory() + let registry = AgentChatSessionRegistry() + let service = AgentChatTranscriptService( + registry: registry, + resolver: AgentChatTranscriptResolver(homeDirectory: home, environment: [:]) + ) + let sessionID = "24ec0052-450c-4914-b1dd-2ee80d4bc84b" + registry.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .sessionStart, + source: "codex", + workspaceId: UUID().uuidString, + surfaceId: UUID().uuidString, + cwd: "/Users/example/project", + ppid: 123 + )) + + let historyTask = Task { @MainActor in + await service.history(sessionID: sessionID, beforeSeq: nil, limit: 20) + } + historyTask.cancel() + _ = await historyTask.value + + let debugRecord = try #require(service.debugSessionDump().first) + #expect(debugRecord["resolution_failed"] as? Bool == false) + } + @MainActor @Test func liveCodexHookDefersFallbackTranscriptScanUntilHistoryOpen() async throws { let home = try temporaryHomeDirectory() @@ -438,6 +468,98 @@ struct AgentChatSessionRegistryLifecycleReviewRegressionTests { }) } + @MainActor + @Test func removedAndReusedSessionIDCapturesTheSameRevisionAgain() async throws { + let projectRoot = try temporaryHomeDirectory() + defer { try? FileManager.default.removeItem(at: projectRoot) } + let source = projectRoot.appendingPathComponent("plan.md") + try "plan".write(to: source, atomically: true, encoding: .utf8) + let coordinator = AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ) + let registry = AgentChatSessionRegistry() + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: coordinator + ) + let surfaceID = UUID().uuidString + let workspaceID = UUID().uuidString + let pendingSessionID = AgentChatSessionRegistry.pendingClaudeSessionID( + surfaceID: surfaceID + ) + let indexed = AgentChatArtifactIndex.Snapshot( + referencedPaths: [source.path], + artifacts: [ChatArtifactIndexedReference( + path: source.path, + provenance: .created, + lastReferencedSeq: 1 + )], + generation: "generation", + revision: 1 + ) + + registry.noteResumeInitiated( + sessionID: pendingSessionID, + source: "claude", + surfaceID: surfaceID, + workspaceID: workspaceID, + workingDirectory: projectRoot.path + ) + let firstRecord = try #require(registry.record(sessionID: pendingSessionID)) + service.scheduleIndexedArtifactCapture(record: firstRecord, snapshot: indexed) + let firstTask = try #require(service.artifactCaptureTasks[pendingSessionID]?.task) + await firstTask.value + #expect(try provenanceEventCount(projectRoot: projectRoot) == 1) + + let realSessionID = UUID().uuidString + registry.noteResumeInitiated( + sessionID: realSessionID, + source: "claude", + surfaceID: surfaceID, + workspaceID: workspaceID, + workingDirectory: projectRoot.path + ) + _ = registry.noteHookEvent(WorkstreamEvent( + sessionId: realSessionID, + hookEventName: .sessionStart, + source: "claude", + workspaceId: workspaceID, + surfaceId: surfaceID, + cwd: projectRoot.path, + ppid: nil + )) + #expect(registry.record(sessionID: pendingSessionID) == nil) + + registry.noteResumeInitiated( + sessionID: pendingSessionID, + source: "claude", + surfaceID: surfaceID, + workspaceID: workspaceID, + workingDirectory: projectRoot.path + ) + let reusedRecord = try #require(registry.record(sessionID: pendingSessionID)) + service.scheduleIndexedArtifactCapture(record: reusedRecord, snapshot: indexed) + let reusedTask = try #require(service.artifactCaptureTasks[pendingSessionID]?.task) + await reusedTask.value + + #expect(try provenanceEventCount(projectRoot: projectRoot) == 2) + } + + private func provenanceEventCount(projectRoot: URL) throws -> Int { + let provenanceRoot = projectRoot.appendingPathComponent( + ".cmux/.metadata/provenance", + isDirectory: true + ) + let documents = try FileManager.default.contentsOfDirectory( + at: provenanceRoot, + includingPropertiesForKeys: nil + ) + let document = try #require(documents.first) + let data = try Data(contentsOf: document) + let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + return (json["events"] as? [[String: Any]])?.count ?? 0 + } + private func temporaryHomeDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory .appendingPathComponent("cmux-agent-chat-\(UUID().uuidString)", isDirectory: true) diff --git a/cmuxTests/AgentChatTranscriptResolutionReviewTests.swift b/cmuxTests/AgentChatTranscriptResolutionReviewTests.swift new file mode 100644 index 000000000000..762d33140fd1 --- /dev/null +++ b/cmuxTests/AgentChatTranscriptResolutionReviewTests.swift @@ -0,0 +1,84 @@ +import CmuxAgentChat +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Agent chat transcript resolution review", .serialized) +struct AgentChatTranscriptResolutionReviewTests { + @Test("Codex fallback scanning obeys its entry bound") + func codexFallbackScanningIsBounded() throws { + let fixture = try makeCodexFixture(sessionID: "bounded-session") + defer { try? FileManager.default.removeItem(at: fixture.root) } + let resolver = AgentChatTranscriptResolver( + homeDirectory: fixture.home, + environment: [:], + maximumCodexFallbackEntries: 0 + ) + + #expect(try resolver.transcriptPath(for: fixture.record) == nil) + } + + @MainActor + @Test("Mobile artifact indexing persists a successful Codex fallback") + func mobileArtifactIndexingPersistsFallbackPath() async throws { + let fixture = try makeCodexFixture(sessionID: "persisted-session") + defer { try? FileManager.default.removeItem(at: fixture.root) } + let registry = AgentChatSessionRegistry(restoredRecords: [fixture.record]) + let service = AgentChatTranscriptService( + registry: registry, + resolver: AgentChatTranscriptResolver(homeDirectory: fixture.home, environment: [:]) + ) + let controller = TerminalController.shared + let previousService = controller.agentChatTranscriptService + controller.agentChatTranscriptService = service + defer { controller.agentChatTranscriptService = previousService } + + let indexed = try await controller.mobileChatArtifactIndexedSession( + sessionID: fixture.record.sessionID + ) + + #expect(indexed != nil) + #expect(registry.record(sessionID: fixture.record.sessionID)?.transcriptPath + == fixture.transcript.path) + } + + private func makeCodexFixture( + sessionID: String + ) throws -> (root: URL, home: URL, transcript: URL, record: AgentChatSessionRecord) { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("agent-chat-resolution-\(UUID().uuidString)", isDirectory: true) + let home = root.appendingPathComponent("home", isDirectory: true) + let project = root.appendingPathComponent("project", isDirectory: true) + let transcript = home + .appendingPathComponent(".codex/sessions/2026/07/22", isDirectory: true) + .appendingPathComponent("rollout-2026-07-22T00-00-00-\(sessionID).jsonl") + try FileManager.default.createDirectory( + at: transcript.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + try Data().write(to: transcript) + return ( + root, + home, + transcript, + AgentChatSessionRecord( + sessionID: sessionID, + agentKind: .codex, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: project.path, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + ) + } +} diff --git a/cmuxTests/AgentChatTranscriptTailerBoundedReadTests.swift b/cmuxTests/AgentChatTranscriptTailerBoundedReadTests.swift new file mode 100644 index 000000000000..2e0c60ab8e01 --- /dev/null +++ b/cmuxTests/AgentChatTranscriptTailerBoundedReadTests.swift @@ -0,0 +1,336 @@ +import CMUXAgentLaunch +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Agent chat transcript tailer bounds") +struct AgentChatTranscriptTailerBoundedReadTests { + @Test("Initial backfill retains a byte-bounded transcript suffix") + func initialBackfillIsByteBounded() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-transcript-tail-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("session.jsonl") + let padding = String(repeating: "x", count: 1_000_000) + let lines = try (0..<6).map { index in + try claudeUserLine(id: index, content: "marker-\(index)-\(padding)") + } + try Data((lines.joined(separator: "\n") + "\n").utf8).write(to: transcript) + + let tailer = AgentChatTranscriptTailer( + sessionID: "session", + agentKind: .claude, + path: transcript.path + ) { _ in } + await tailer.start() + let page = await tailer.history(beforeSeq: nil, limit: 20) + await tailer.stop() + + #expect(page.messages.count < lines.count) + guard let last = page.messages.last, + case .prose(let prose) = last.kind else { + Issue.record("Expected the newest retained transcript line") + return + } + #expect(prose.text.hasPrefix("marker-5-")) + #expect(page.hasMore) + } + + @Test(.timeLimit(.minutes(1))) + func incrementalGrowthDiscardsOversizedLineAndResynchronizes() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-transcript-growth-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("session.jsonl") + try Data().write(to: transcript) + let batches = AsyncStream.makeStream( + bufferingPolicy: .bufferingNewest(8) + ) + defer { batches.continuation.finish() } + let tailer = AgentChatTranscriptTailer( + sessionID: "session", + agentKind: .claude, + path: transcript.path + ) { batch in + batches.continuation.yield(batch) + } + await tailer.start() + + let oversized = try claudeUserLine( + id: 0, + content: String( + repeating: "x", + count: AgentChatTranscriptInitialTailReader.defaultMaximumBytes + 1_024 + ) + ) + let survivor = try claudeUserLine(id: 1, content: "survivor") + let handle = try FileHandle(forWritingTo: transcript) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: Data("\(oversized)\n\(survivor)\n".utf8)) + + var iterator = batches.stream.makeAsyncIterator() + var observedSurvivor = false + while let batch = await iterator.next() { + observedSurvivor = batch.appended.contains { message in + guard case .prose(let prose) = message.kind else { return false } + return prose.text == "survivor" + } + if observedSurvivor { break } + } + let page = await tailer.history(beforeSeq: nil, limit: 20) + await tailer.stop() + + #expect(observedSurvivor) + #expect(page.messages.count == 1) + #expect(page.messages.first?.seq == 1) + #expect(page.hasMore) + } + + private func claudeUserLine(id: Int, content: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "type": "user", + "isSidechain": false, + "uuid": "user-\(id)", + "timestamp": "2026-07-22T12:00:00.000Z", + "message": ["role": "user", "content": content], + ]) + return String(decoding: data, as: UTF8.self) + } +} + +@Suite("Agent chat transcript tailer ownership") +@MainActor +struct AgentChatTranscriptTailerOwnershipTests { + @Test("Automatic-capture tailers are capped with least-recently-used eviction") + func automaticCaptureTailersAreCappedAndEvictedByRecency() async throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { true }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { true } + ) + let expectedCap = 32 + let total = expectedCap + 1 + + try makeTranscript(at: root, index: 0) + noteSession(index: 0, root: root, service: service) + try makeTranscript(at: root, index: 1) + noteSession(index: 1, root: root, service: service) + + // Touch the first session after the second one was created. The second + // session should therefore be the first artifact-only tailer evicted. + if let first = service.registry.record(sessionID: sessionID(index: 0)) { + service.ensureTailerForEagerObservation(for: first) + } + for index in 2.. AgentChatTranscriptService { + AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { true } + ) + } + + private func noteSession( + index: Int, + root: URL, + service: AgentChatTranscriptService + ) { + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID(index: index), + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: root.appendingPathComponent("session-\(index).jsonl").path, + cwd: root.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: TimeInterval(index + 1)) + )) + } + + private func makeTranscript(at root: URL, index: Int) throws -> URL { + let transcript = root.appendingPathComponent("session-\(index).jsonl") + try Data().write(to: transcript) + return transcript + } + + private func sessionID(index: Int) -> String { + "tailer-session-\(index)" + } + + private func temporaryDirectory() throws -> URL { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-tailers-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + private func stopRemainingTailers(in service: AgentChatTranscriptService) async { + for tailer in service.tailers.values { + await tailer.stop() + } + } +} diff --git a/cmuxTests/ArtifactCLIIntegrationTests.swift b/cmuxTests/ArtifactCLIIntegrationTests.swift new file mode 100644 index 000000000000..1d71e922bffc --- /dev/null +++ b/cmuxTests/ArtifactCLIIntegrationTests.swift @@ -0,0 +1,144 @@ +import Foundation +import Testing + +@Suite("Artifact CLI integration") +struct ArtifactCLIIntegrationTests { + @Test("Commands persist, list, resolve, and search without a cmux socket") + func commandsPersistListResolveAndSearchWithoutSocket() throws { + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-artifact-cli-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + let git = Process() + git.executableURL = URL(fileURLWithPath: "/usr/bin/git") + git.arguments = ["init", "--quiet", projectRoot.path] + git.standardOutput = FileHandle.nullDevice + git.standardError = FileHandle.nullDevice + try git.run() + git.waitUntilExit() + #expect(git.terminationStatus == 0) + defer { try? fileManager.removeItem(at: projectRoot) } + let source = projectRoot.appendingPathComponent("source/launch-plan.md", isDirectory: false) + try fileManager.createDirectory( + at: source.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try "release needle".write(to: source, atomically: true, encoding: .utf8) + let cliPath = try BundledCLITestSupport.bundledCLIPath(for: BundledCLILinkageTests.self) + + let added = try runCLI( + cliPath, + ["artifact", "add", source.path, "--project", projectRoot.path, "--json"] + ) + #expect(added.status == 0, Comment(rawValue: added.stderr)) + let addedPayload = try jsonObject(added.stdout) + let storedPath = try #require(addedPayload["path"] as? String) + let relativePath = try #require(addedPayload["relative_path"] as? String) + #expect(fileManager.fileExists(atPath: storedPath)) + #expect(relativePath.hasSuffix("/launch-plan.md")) + + let listed = try runCLI( + cliPath, + ["artifact", "list", "--project", projectRoot.path, "--json"] + ) + #expect(listed.status == 0, Comment(rawValue: listed.stderr)) + let listedPayload = try jsonObject(listed.stdout) + let artifacts = try #require(listedPayload["artifacts"] as? [[String: Any]]) + #expect(artifacts.compactMap { $0["relative_path"] as? String } == [relativePath]) + + let resolved = try runCLI( + cliPath, + ["artifact", "path", relativePath, "--project", projectRoot.path] + ) + #expect(resolved.status == 0, Comment(rawValue: resolved.stderr)) + #expect(resolved.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == storedPath) + + let searched = try runCLI( + cliPath, + ["artifact", "search", "needle", "--project", projectRoot.path, "--json"] + ) + #expect(searched.status == 0, Comment(rawValue: searched.stderr)) + let searchedPayload = try jsonObject(searched.stdout) + let results = try #require(searchedPayload["results"] as? [[String: Any]]) + #expect(results.compactMap { $0["relative_path"] as? String } == [relativePath]) + #expect(results.first?["matched_content"] as? Bool == true) + + let noteWrite = try runCLI( + cliPath, + [ + "note", "write", "release-note", "--text", "note body", + "--project", projectRoot.path, "--json", "--id-format", "refs", + ] + ) + #expect(noteWrite.status == 0, Comment(rawValue: noteWrite.stderr)) + let noteWritePayload = try jsonObject(noteWrite.stdout) + #expect((noteWritePayload["relative_path"] as? String)?.hasSuffix("/release-note.md") == true) + + let noteRead = try runCLI( + cliPath, + ["note", "read", "release-note", "--project", projectRoot.path, "--json"] + ) + #expect(noteRead.status == 0, Comment(rawValue: noteRead.stderr)) + let noteReadPayload = try jsonObject(noteRead.stdout) + #expect(noteReadPayload["text"] as? String == "note body") + + let emptySource = projectRoot.appendingPathComponent("source/empty.txt", isDirectory: false) + #expect(fileManager.createFile(atPath: emptySource.path, contents: Data())) + let emptyAdded = try runCLI( + cliPath, + ["artifact", "add", emptySource.path, "--project", projectRoot.path, "--json"] + ) + #expect(emptyAdded.status == 0, Comment(rawValue: emptyAdded.stderr)) + let emptyRelativePath = try #require( + jsonObject(emptyAdded.stdout)["relative_path"] as? String + ) + let emptyOpened = try runCLI( + cliPath, + ["artifact", "open", emptyRelativePath, "--project", projectRoot.path] + ) + #expect(emptyOpened.status == 0, Comment(rawValue: emptyOpened.stderr)) + + let missing = try runCLI( + cliPath, + ["artifact", "open", "missing.md", "--project", projectRoot.path] + ) + #expect(missing.status != 0) + #expect(missing.stderr.contains("Artifact not found")) + } + + private func runCLI( + _ executablePath: String, + _ arguments: [String] + ) throws -> (status: Int32, stdout: String, stderr: String) { + let process = Process() + let stdout = Pipe() + let stderr = Pipe() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_WORKSPACE_ID"] = "artifact-cli-test-workspace" + environment["CMUX_CODEX_SESSION_ID"] = "artifact-cli-test-session" + process.environment = environment + process.standardInput = FileHandle.nullDevice + process.standardOutput = stdout + process.standardError = stderr + try process.run() + process.waitUntilExit() + return ( + process.terminationStatus, + String(decoding: stdout.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self), + String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + ) + } + + private func jsonObject(_ text: String) throws -> [String: Any] { + try #require( + JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any], + "Expected JSON object, got: \(text)" + ) + } +} diff --git a/cmuxTests/ArtifactCLITerminalSafetyTests.swift b/cmuxTests/ArtifactCLITerminalSafetyTests.swift new file mode 100644 index 000000000000..6f538c7ac322 --- /dev/null +++ b/cmuxTests/ArtifactCLITerminalSafetyTests.swift @@ -0,0 +1,122 @@ +import Foundation +import Testing + +@Suite("Artifact CLI terminal safety") +struct ArtifactCLITerminalSafetyTests { + @Test("Human output sanitizes controls while JSON preserves artifact text") + func sanitizesOnlyHumanOutput() throws { + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-artifact-cli-safety-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory( + at: projectRoot.appendingPathComponent(".git", isDirectory: true), + withIntermediateDirectories: true + ) + defer { try? fileManager.removeItem(at: projectRoot) } + let controlledName = "artifact-\u{1B}]2;owned\u{7}\u{85}.md" + let controlledContent = "needle \u{1B}[31mred\u{7}\rreturn" + let source = projectRoot.appendingPathComponent("source", isDirectory: true) + .appendingPathComponent(controlledName, isDirectory: false) + try fileManager.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true) + try controlledContent.write(to: source, atomically: true, encoding: .utf8) + let cliPath = try BundledCLITestSupport.bundledCLIPath(for: BundledCLILinkageTests.self) + + let added = try runCLI( + cliPath, + ["artifact", "add", source.path, "--project", projectRoot.path, "--json"] + ) + #expect(added.status == 0) + let addedPayload = try jsonObject(added.stdout) + let relativePath = try #require(addedPayload["relative_path"] as? String) + #expect(relativePath.contains(controlledName)) + let reference = try #require(addedPayload["reference"] as? String) + #expect(reference == ".cmux/\(relativePath)") + + let humanList = try runCLI( + cliPath, + ["artifact", "list", "--project", projectRoot.path] + ) + #expect(humanList.status == 0) + #expect(!containsUnsafeTerminalControl(humanList.stdout)) + + let humanPath = try runCLI( + cliPath, + ["artifact", "path", reference, "--project", projectRoot.path] + ) + #expect(humanPath.status == 0) + #expect(!containsUnsafeTerminalControl(humanPath.stdout)) + + let humanSearch = try runCLI( + cliPath, + ["artifact", "search", "needle", "--project", projectRoot.path] + ) + #expect(humanSearch.status == 0) + #expect(!containsUnsafeTerminalControl(humanSearch.stdout)) + + let jsonSearch = try runCLI( + cliPath, + ["artifact", "search", "needle", "--project", projectRoot.path, "--json"] + ) + #expect(jsonSearch.status == 0) + let searchPayload = try jsonObject(jsonSearch.stdout) + let results = try #require(searchPayload["results"] as? [[String: Any]]) + #expect(results.first?["relative_path"] as? String == relativePath) + #expect((results.first?["snippet"] as? String)?.contains("\u{1B}[31m") == true) + + let humanError = try runCLI( + cliPath, + ["artifact", "path", "missing-\u{1B}]2;owned\u{7}.md", "--project", projectRoot.path] + ) + #expect(humanError.status != 0) + #expect(!containsUnsafeTerminalControl(humanError.stderr)) + } + + private func runCLI( + _ executablePath: String, + _ arguments: [String] + ) throws -> (status: Int32, stdout: String, stderr: String) { + let process = Process() + let stdout = Pipe() + let stderr = Pipe() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + var environment = ProcessInfo.processInfo.environment + let agentIdentityKeys = Set([ + "CODEX_THREAD_ID", + "CODEX_SESSION_ID", + "CMUX_CODEX_SESSION_ID", + "CLAUDE_CODE_SESSION_ID", + "CMUX_CLAUDE_SESSION_ID", + "OPENCODE_SESSION_ID", + ]) + for key in Array(environment.keys) + where key.hasPrefix("CMUX_") || agentIdentityKeys.contains(key) { + environment.removeValue(forKey: key) + } + environment["CMUX_AGENT_SESSION_ID"] = "artifact-cli-terminal-safety" + environment["CMUX_AGENT_NAME"] = "codex" + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + process.environment = environment + process.standardInput = FileHandle.nullDevice + process.standardOutput = stdout + process.standardError = stderr + try process.run() + process.waitUntilExit() + return ( + process.terminationStatus, + String(decoding: stdout.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self), + String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + ) + } + + private func jsonObject(_ text: String) throws -> [String: Any] { + try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + } + + private func containsUnsafeTerminalControl(_ text: String) -> Bool { + text.unicodeScalars.contains { scalar in + scalar.value != 0x0A + && (scalar.value <= 0x1F || (0x7F...0x9F).contains(scalar.value)) + } + } +} diff --git a/cmuxTests/ArtifactHTMLPreviewSecurityTests.swift b/cmuxTests/ArtifactHTMLPreviewSecurityTests.swift new file mode 100644 index 000000000000..5660005350c2 --- /dev/null +++ b/cmuxTests/ArtifactHTMLPreviewSecurityTests.swift @@ -0,0 +1,316 @@ +import Foundation +import CmuxSettings +import Testing +import WebKit + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Artifact HTML preview security") +struct ArtifactHTMLPreviewSecurityTests { + @Test("Untrusted HTML is wrapped in an isolated non-navigating data document") + func wrapsActiveContentInASandbox() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-html-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let source = root.appendingPathComponent("artifact.html", isDirectory: false) + try """ + + + sibling + """.write(to: source, atomically: true, encoding: .utf8) + + let document = try await ArtifactHTMLPreviewDocument.load( + sourceURL: source, + allowedRoot: root + ) + let prefix = "data:text/html;base64," + #expect(document.url.absoluteString.hasPrefix(prefix)) + let encoded = String(document.url.absoluteString.dropFirst(prefix.count)) + let data = try #require(Data(base64Encoded: encoded)) + let wrapper = String(decoding: data, as: UTF8.self) + + #expect(wrapper.contains("sandbox=\"\"")) + #expect(wrapper.contains("default-src 'none'")) + #expect(wrapper.contains("script-src 'none'")) + #expect(wrapper.contains("connect-src 'none'")) + #expect(wrapper.contains("navigate-to 'none'")) + #expect(!wrapper.contains(source.path)) + } + + @Test("Artifact previews reject symbolic links and oversized sources") + func rejectsUntrustedSourceEntries() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-html-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let target = root.appendingPathComponent("target.html", isDirectory: false) + try "

private

".write(to: target, atomically: true, encoding: .utf8) + let symbolicLink = root.appendingPathComponent("linked.html", isDirectory: false) + try FileManager.default.createSymbolicLink(at: symbolicLink, withDestinationURL: target) + let oversized = root.appendingPathComponent("oversized.html", isDirectory: false) + try Data().write(to: oversized) + let oversizedHandle = try FileHandle(forWritingTo: oversized) + try oversizedHandle.truncate( + atOffset: UInt64(8 * 1024 * 1024) + 1 + ) + try oversizedHandle.close() + + await #expect(throws: CocoaError.self) { + _ = try await ArtifactHTMLPreviewDocument.load( + sourceURL: symbolicLink, + allowedRoot: root + ) + } + await #expect(throws: CocoaError.self) { + _ = try await ArtifactHTMLPreviewDocument.load( + sourceURL: oversized, + allowedRoot: root + ) + } + } + + @Test("Artifact previews reject a swapped parent symlink") + func rejectsSwappedParentSymlink() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-html-\(UUID().uuidString)", isDirectory: true) + let outside = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-html-outside-\(UUID().uuidString)", isDirectory: true) + defer { + try? FileManager.default.removeItem(at: root) + try? FileManager.default.removeItem(at: outside) + } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let parent = root.appendingPathComponent("session", isDirectory: true) + let source = parent.appendingPathComponent("artifact.html") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + try "

authorized

".write(to: source, atomically: true, encoding: .utf8) + try "

outside

".write( + to: outside.appendingPathComponent("artifact.html"), + atomically: true, + encoding: .utf8 + ) + try FileManager.default.removeItem(at: parent) + try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: outside) + + #expect(ArtifactSidebarFileAccess().validatedFileURL( + for: source, + artifactRoot: root + ) == nil) + await #expect(throws: CocoaError.self) { + _ = try await ArtifactHTMLPreviewDocument.load( + sourceURL: source, + allowedRoot: root + ) + } + } + + @Test("Descriptor-backed artifact reads stay on the opened inode") + func descriptorReadSurvivesPathReplacement() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-open-\(UUID().uuidString)", isDirectory: true) + let outside = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-open-outside-\(UUID().uuidString)", isDirectory: true) + defer { + try? FileManager.default.removeItem(at: root) + try? FileManager.default.removeItem(at: outside) + } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let source = root.appendingPathComponent("artifact.txt") + try "authorized".write(to: source, atomically: true, encoding: .utf8) + let opened = try #require( + ArtifactSidebarFileAccess().openedFile(for: source, artifactRoot: root) + ) + try "outside".write( + to: outside.appendingPathComponent("artifact.txt"), + atomically: true, + encoding: .utf8 + ) + try FileManager.default.removeItem(at: source) + try FileManager.default.createSymbolicLink( + at: source, + withDestinationURL: outside.appendingPathComponent("artifact.txt") + ) + + #expect(try String(contentsOf: opened.readURL, encoding: .utf8) == "authorized") + let temporary = try #require(opened.makeTemporaryPreviewURL()) + defer { try? FileManager.default.removeItem(at: temporary) } + #expect(temporary.pathExtension == "txt") + #expect(try String(contentsOf: temporary, encoding: .utf8) == "authorized") + let filePermissions = try #require( + FileManager.default.attributesOfItem(atPath: temporary.path)[.posixPermissions] + as? NSNumber + ).intValue + let directoryPermissions = try #require( + FileManager.default.attributesOfItem( + atPath: temporary.deletingLastPathComponent().path + )[.posixPermissions] as? NSNumber + ).intValue + #expect(filePermissions & 0o077 == 0) + #expect(directoryPermissions & 0o077 == 0) + let asyncTemporary = try #require( + await opened.makeTemporaryPreviewURLAsync() + ) + defer { try? FileManager.default.removeItem(at: asyncTemporary) } + #expect(try String(contentsOf: asyncTemporary, encoding: .utf8) == "authorized") + } + + @Test("File preview panels keep descriptor reads after copy teardown") + @MainActor + func filePreviewPanelDoesNotFallbackToReplacedPath() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-panel-open-\(UUID().uuidString)", isDirectory: true) + let outside = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-panel-outside-\(UUID().uuidString)", isDirectory: true) + defer { + try? FileManager.default.removeItem(at: root) + try? FileManager.default.removeItem(at: outside) + } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let source = root.appendingPathComponent("artifact.txt", isDirectory: false) + let outsideSource = outside.appendingPathComponent("artifact.txt", isDirectory: false) + try "authorized".write(to: source, atomically: true, encoding: .utf8) + try "outside".write(to: outsideSource, atomically: true, encoding: .utf8) + let opened = try #require( + ArtifactSidebarFileAccess().openedFile(for: source, artifactRoot: root) + ) + + let panel = FilePreviewPanel( + workspaceId: UUID(), + filePath: opened.sourceURL.path, + startFileWatcher: false, + artifactFile: opened + ) + panel.close() + try FileManager.default.removeItem(at: source) + try FileManager.default.createSymbolicLink(at: source, withDestinationURL: outsideSource) + + #expect(panel.readURL == opened.readURL) + #expect(try String(contentsOf: panel.readURL, encoding: .utf8) == "authorized") + } + + @Test("Concurrent descriptor previews keep independent offsets and stay bounded") + func concurrentDescriptorPreviewsStayBounded() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-artifact-preview-quota-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let source = root.appendingPathComponent("artifact.txt", isDirectory: false) + try "authorized".write(to: source, atomically: true, encoding: .utf8) + let opened = try #require( + ArtifactSidebarFileAccess().openedFile(for: source, artifactRoot: root) + ) + + var previews: [URL] = [] + await withTaskGroup(of: URL?.self) { group in + for _ in 0..<300 { + group.addTask { + await opened.makeTemporaryPreviewURLAsync(maximumBytes: 32) + } + } + for await preview in group { + if let preview { previews.append(preview) } + } + } + defer { + for preview in previews { + try? FileManager.default.removeItem(at: preview) + } + } + + #expect(!previews.isEmpty) + #expect(previews.count <= 256) + for preview in previews { + #expect(try String(contentsOf: preview, encoding: .utf8) == "authorized") + } + } + + @Test("Artifact previews use an ephemeral script-free WebKit configuration") + @MainActor + func configuresAnIsolatedWebView() { + let configuration = ArtifactHTMLPreviewWebViewFactory( + websiteDataStore: .nonPersistent() + ).makeConfiguration() + + #expect(!configuration.websiteDataStore.isPersistent) + #expect(!configuration.defaultWebpagePreferences.allowsContentJavaScript) + #expect(configuration.userContentController.userScripts.isEmpty) + #expect(!configuration.preferences.javaScriptCanOpenWindowsAutomatically) + } + + @Test("Artifact previews permit only their wrapper and inert srcdoc frame") + func blocksFollowUpNavigationAndPopups() throws { + let documentURL = try #require(URL(string: "data:text/html;base64,PGh0bWw+")) + let policy = ArtifactHTMLPreviewNavigationPolicy(documentURL: documentURL) + + #expect(policy.allowsNavigation(to: documentURL, targetIsMainFrame: true)) + #expect(policy.allowsNavigation( + to: URL(string: documentURL.absoluteString + "#section"), + targetIsMainFrame: true + )) + #expect(policy.allowsNavigation(to: URL(string: "about:srcdoc"), targetIsMainFrame: false)) + #expect(policy.allowsNavigation(to: URL(string: "about:srcdoc#section"), targetIsMainFrame: false)) + #expect(!policy.allowsNavigation(to: URL(string: "https://example.com"), targetIsMainFrame: true)) + #expect(!policy.allowsNavigation(to: URL(fileURLWithPath: "/private/sibling.txt"), targetIsMainFrame: false)) + #expect(!policy.allowsNavigation(to: documentURL, targetIsMainFrame: nil)) + } + + @Test("App-owned preview documents use the trusted internal allowlist path") + func trustedPreviewURLSurvivesManagedAllowlist() throws { + let documentURL = try #require(URL(string: "data:text/html;base64,PGh0bWw+")) + let allowlist = BrowserURLAllowlistPolicy(managedPatterns: ["internal.example"]) + + #expect(!allowlist.allows(documentURL)) + #expect(allowlist.allowsTrustedInternalURL(documentURL)) + } + + @Test("Artifact previews never enter normal browser session persistence") + func excludesPreviewDocumentsFromRestoration() throws { + let documentURL = try #require(URL(string: "data:text/html;base64,PGh0bWw+")) + + #expect(!BrowserPanelContentMode.artifactHTMLPreview( + documentURL: documentURL + ).allowsSessionPersistence) + #expect(BrowserPanelContentMode.standard.allowsSessionPersistence) + } + + @Test("Closing an artifact preview never stages it for normal browser reopening") + @MainActor + func excludesPreviewDocumentsFromClosedBrowserHistory() throws { + let workspace = Workspace() + let documentURL = try #require(URL(string: "data:text/html;base64,PGh0bWw+")) + let paneID = try #require(workspace.bonsplitController.focusedPaneId) + let browserPanel = try #require(workspace.newBrowserSurface( + inPane: paneID, + url: documentURL, + focus: false, + creationPolicy: .artifactPreview + )) + let tabID = try #require(workspace.surfaceIdFromPanelId(browserPanel.id)) + let tab = try #require(workspace.bonsplitController.tab(tabID)) + var closedSnapshot: ClosedBrowserPanelRestoreSnapshot? + workspace.onClosedBrowserPanel = { snapshot in + closedSnapshot = snapshot + } + + #expect(workspace.splitTabBar( + workspace.bonsplitController, + shouldCloseTab: tab, + inPane: paneID + )) + workspace.splitTabBar( + workspace.bonsplitController, + didCloseTab: tabID, + fromPane: paneID + ) + + #expect(closedSnapshot == nil) + } +} diff --git a/cmuxTests/ArtifactRightSidebarModeTests.swift b/cmuxTests/ArtifactRightSidebarModeTests.swift new file mode 100644 index 000000000000..d15ca92c6acf --- /dev/null +++ b/cmuxTests/ArtifactRightSidebarModeTests.swift @@ -0,0 +1,92 @@ +import CmuxCommandPalette +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Artifact right-sidebar mode", .serialized) +@MainActor +struct ArtifactRightSidebarModeTests { + @Test("Beta availability clamps disabled mode and preserves enabled mode") + func betaAvailabilityControlsPersistence() { + withSavedArtifactsDefault { defaults in + defaults.set(false, forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + let state = FileExplorerState() + + state.mode = .artifacts + #expect(state.mode == .files) + + defaults.set(true, forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + state.mode = .artifacts + #expect(state.mode == .artifacts) + } + } + + @Test("Remote Artifacts flag is a hard gate over the local beta opt-in") + func remoteFlagControlsLocalOptIn() { + withSavedArtifactsDefault { defaults in + defaults.set(true, forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + #expect(!RightSidebarBetaFeatureSettings.isArtifactsEnabled( + defaults: defaults, + remoteEnabled: false + )) + #expect(RightSidebarBetaFeatureSettings.isArtifactsEnabled( + defaults: defaults, + remoteEnabled: true + )) + + defaults.set(false, forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + #expect(!RightSidebarBetaFeatureSettings.isArtifactsEnabled( + defaults: defaults, + remoteEnabled: true + )) + } + } + + @Test("CLI mode parsing recognizes artifacts") + func parsesCLIArgument() { + #expect(RightSidebarMode.from(cliArgument: "artifacts") == .artifacts) + } + + @Test("Artifacts has no hidden fixed shortcut") + func hasNoModeShortcut() { + #expect(RightSidebarMode.artifacts.shortcutAction == nil) + } + + @Test("Command palette contribution follows the beta gate") + func commandPaletteContributionFollowsBetaGate() throws { + try withSavedArtifactsDefault { defaults in + defaults.removeObject(forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + let commandID = ContentView.commandPaletteRightSidebarModeCommandID(.artifacts) + var contributions = ContentView.commandPaletteRightSidebarModeCommandContributions() + #expect(!contributions.contains { $0.commandId == commandID }) + + defaults.set(true, forKey: RightSidebarBetaFeatureSettings.artifactsEnabledKey) + contributions = ContentView.commandPaletteRightSidebarModeCommandContributions() + let contribution = try #require(contributions.first { $0.commandId == commandID }) + let context = CommandPaletteContextSnapshot() + #expect(contribution.title(context) == RightSidebarMode.artifacts.label) + #expect(ContentView.commandPaletteShortcutAction(forCommandID: commandID) == nil) + } + } + + private func withSavedArtifactsDefault( + _ body: (UserDefaults) throws -> T + ) rethrows -> T { + let defaults = UserDefaults.standard + let key = RightSidebarBetaFeatureSettings.artifactsEnabledKey + let previous = defaults.object(forKey: key) + defer { + if let previous { + defaults.set(previous, forKey: key) + } else { + defaults.removeObject(forKey: key) + } + } + return try body(defaults) + } +} diff --git a/cmuxTests/ArtifactRuntimeLifecycleTests.swift b/cmuxTests/ArtifactRuntimeLifecycleTests.swift new file mode 100644 index 000000000000..5009ee807785 --- /dev/null +++ b/cmuxTests/ArtifactRuntimeLifecycleTests.swift @@ -0,0 +1,478 @@ +import AppKit +import CMUXAgentLaunch +import CmuxAgentChat +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Artifact runtime lifecycle") +@MainActor +struct ArtifactRuntimeLifecycleTests { + @Test("Shell mutation detection preserves fd-duplication redirects") + func shellMutationDetectionPreservesFileTargetsAroundFdDuplication() { + let detector = ShellArtifactMutationPathDetector() + + #expect( + detector.pathsAttributedToSuccessfulCommand( + in: "python3 render.py > /tmp/out.html 2>&1" + ) == ["/tmp/out.html"] + ) + #expect( + detector.pathsAttributedToSuccessfulCommand( + in: "python3 render.py >> /tmp/out.html 2>&1" + ) == ["/tmp/out.html"] + ) + #expect( + detector.pathsAttributedToSuccessfulCommand( + in: "python3 render.py >& /tmp/out.html" + ) == ["/tmp/out.html"] + ) + #expect( + detector.pathsAttributedToSuccessfulCommand( + in: "python3 render.py 2>&1" + ).isEmpty + ) + } + + @Test("Workspace grouping uses the restart-stable workspace identity") + func workspaceGroupingUsesStableIdentity() throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let workspace = Workspace(workingDirectory: root.path) + + let selection = try #require(ContentView.artifactSidebarWorkspace(for: workspace)) + + #expect(selection.id == workspace.stableId.uuidString) + #expect(selection.id != workspace.id.uuidString) + } + + @Test("Disabling automatic capture releases artifact-only transcript tailers") + func disablingCaptureReleasesArtifactOnlyTailers() throws { + let fixture = try transcriptFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + var captureEnabled = true + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { captureEnabled } + ) + service.noteHookEvent(fixture.event) + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == true) + + captureEnabled = false + service.reconcileAutomaticArtifactCaptureAvailability() + + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == false) + } + + @Test("Disabling automatic capture preserves mobile-owned transcript tailers") + func disablingCapturePreservesSubscriberTailers() throws { + let fixture = try transcriptFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + var captureEnabled = true + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { true }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { captureEnabled } + ) + service.noteHookEvent(fixture.event) + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == true) + + captureEnabled = false + service.reconcileAutomaticArtifactCaptureAvailability() + + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == true) + } + + @Test("Enabling automatic capture does not resolve unrecorded Codex transcripts") + func enablingCaptureSkipsUnrecordedCodexTranscripts() throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + var captureEnabled = false + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + resolver: AgentChatTranscriptResolver(homeDirectory: root, environment: [:]), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { captureEnabled } + ) + service.noteHookEvent(WorkstreamEvent( + sessionId: UUID().uuidString, + hookEventName: .sessionStart, + source: "codex", + workspaceId: UUID().uuidString, + surfaceId: nil, + transcriptPath: nil, + cwd: root.path, + ppid: nil, + receivedAt: .now + )) + + captureEnabled = true + service.reconcileAutomaticArtifactCaptureAvailability() + + let session = try #require(service.debugSessionDump().first) + #expect(session["tailer_active"] as? Bool == false) + #expect(session["resolution_failed"] as? Bool == false) + } + + @Test("Enabling automatic capture adopts a recorded Codex transcript") + func enablingCaptureAdoptsRecordedCodexTranscript() throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let transcript = root.appendingPathComponent("recorded.jsonl") + try Data().write(to: transcript) + var captureEnabled = false + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + resolver: AgentChatTranscriptResolver(homeDirectory: root, environment: [:]), + hasEventSubscribers: { false }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ), + isAutomaticArtifactCaptureEnabled: { captureEnabled } + ) + service.noteHookEvent(WorkstreamEvent( + sessionId: UUID().uuidString, + hookEventName: .sessionStart, + source: "codex", + workspaceId: UUID().uuidString, + surfaceId: nil, + transcriptPath: transcript.path, + cwd: root.path, + ppid: nil, + receivedAt: .now + )) + + captureEnabled = true + service.reconcileAutomaticArtifactCaptureAvailability() + + #expect(service.debugSessionDump().first?["tailer_active"] as? Bool == true) + } + + @Test("Transcript-observed completion captures without a Stop hook") + func transcriptObservedCompletionCapturesWithoutStopHook() async throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let artifact = root.appendingPathComponent("hookless-plan.md") + try "plan".write(to: artifact, atomically: true, encoding: .utf8) + let transcript = root.appendingPathComponent("transcript.jsonl") + try claudeArtifactLine(path: artifact.path).write( + to: transcript, + atomically: true, + encoding: .utf8 + ) + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { false }, + emitEventPayload: { _ in }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + ) + let sessionID = UUID().uuidString + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: transcript.path, + cwd: root.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: 1) + )) + + service.publishBatch( + assistantCompletionBatch(timestamp: Date(timeIntervalSince1970: 2)), + sessionID: sessionID + ) + let task = try #require(service.artifactCaptureTasks[sessionID]?.task) + await task.value + + #expect(await store.importedPaths == [artifact.path]) + } + + @Test("Transcript flush after Stop schedules a newer automatic capture") + func transcriptFlushAfterStopSchedulesNewerCapture() async throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let artifact = root.appendingPathComponent("late-plan.md") + try "plan".write(to: artifact, atomically: true, encoding: .utf8) + let transcript = root.appendingPathComponent("transcript.jsonl") + try "".write(to: transcript, atomically: true, encoding: .utf8) + let store = OutOfOrderCaptureStore(suspendsFirstImport: false) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + hasEventSubscribers: { false }, + emitEventPayload: { _ in }, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store) + ) + ) + let sessionID = UUID().uuidString + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: transcript.path, + cwd: root.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: 1) + )) + service.noteHookEvent(WorkstreamEvent( + sessionId: sessionID, + hookEventName: .stop, + source: "claude", + workspaceId: "workspace", + surfaceId: nil, + transcriptPath: transcript.path, + cwd: root.path, + ppid: nil, + receivedAt: Date(timeIntervalSince1970: 2) + )) + let stopCapture = try #require(service.artifactCaptureTasks[sessionID]?.task) + await stopCapture.value + + try claudeArtifactLine(path: artifact.path).write( + to: transcript, + atomically: true, + encoding: .utf8 + ) + service.publishBatch( + assistantCompletionBatch(timestamp: Date(timeIntervalSince1970: 3)), + sessionID: sessionID + ) + let flushCapture = try #require(service.artifactCaptureTasks[sessionID]?.task) + await flushCapture.value + + #expect(await store.importedPaths == [artifact.path]) + } + + @Test("Automatic capture retries transient store contention") + func captureRetriesTransientStoreContention() async throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("artifact.md", isDirectory: false) + try "artifact".write(to: source, atomically: true, encoding: .utf8) + let store = OutOfOrderCaptureStore( + suspendsFirstImport: false, + rejectsFirstImportAsBusy: true + ) + let service = AgentChatTranscriptService( + registry: AgentChatSessionRegistry(), + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: store), + contentionRetryDelay: { _ in } + ) + ) + let record = AgentChatSessionRecord( + sessionID: "contention-session", + agentKind: .claude, + workspaceID: "workspace", + surfaceID: nil, + workingDirectory: root.path, + workingDirectoryAuthority: .hook, + transcriptPath: nil, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let snapshot = AgentChatArtifactIndex.Snapshot( + referencedPaths: [source.path], + artifacts: [ChatArtifactIndexedReference( + path: source.path, + provenance: .created, + lastReferencedSeq: 1 + )], + generation: "contention", + revision: 1 + ) + + service.scheduleIndexedArtifactCapture(record: record, snapshot: snapshot) + let task = try #require(service.artifactCaptureTasks[record.sessionID]?.task) + await task.value + + #expect(await store.importCount == 2) + #expect(await store.importedPaths == [source.path]) + } + + @Test("Referenced capture honors configured ephemeral roots within the project") + func referencedCaptureHonorsConfiguredEphemeralRoots() async throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let allowedDirectory = root.appendingPathComponent("allowed", isDirectory: true) + let excludedDirectory = root.appendingPathComponent("excluded", isDirectory: true) + try FileManager.default.createDirectory( + at: allowedDirectory, + withIntermediateDirectories: true + ) + try FileManager.default.createDirectory( + at: excludedDirectory, + withIntermediateDirectories: true + ) + let allowed = allowedDirectory.appendingPathComponent("allowed.md") + let excluded = excludedDirectory.appendingPathComponent("excluded.md") + try "allowed".write(to: allowed, atomically: true, encoding: .utf8) + try "excluded".write(to: excluded, atomically: true, encoding: .utf8) + var configuration = ArtifactCaptureConfiguration.defaultValue + configuration.ephemeralPathPrefixes = [allowedDirectory.path] + let store = OutOfOrderCaptureStore( + suspendsFirstImport: false, + configuration: configuration + ) + + let outcomes = await ArtifactCaptureService(store: store).capture( + candidates: [ + ArtifactCandidate(sourceURL: allowed, provenance: .referenced), + ArtifactCandidate(sourceURL: excluded, provenance: .referenced), + ], + context: ArtifactCaptureContext(projectRoot: root) + ) + + #expect(await store.importedPaths == [allowed.path]) + #expect(outcomes.count == 2) + #expect(outcomes.last == .skipped(.provenanceNotEligible)) + } + + @Test("Artifacts focus waits for its search endpoint instead of accepting the sidebar host") + func artifactsFocusTargetsSearchEndpoint() { + let defaults = UserDefaults.standard + let key = RightSidebarBetaFeatureSettings.artifactsEnabledKey + let previousValue = defaults.object(forKey: key) + defaults.set(true, forKey: key) + defer { restore(previousValue, forKey: key) } + + let fileExplorerState = FileExplorerState() + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 180), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + let contentView = NSView(frame: window.contentView?.bounds ?? .zero) + window.contentView = contentView + let controller = MainWindowFocusController( + windowId: UUID(), + window: window, + tabManager: TabManager(), + fileExplorerState: fileExplorerState + ) + let fallbackHost = RightSidebarKeyboardFocusView( + frame: NSRect(x: 0, y: 0, width: 24, height: 24) + ) + let searchField = ArtifactSidebarSearchFieldView( + frame: NSRect(x: 0, y: 0, width: 160, height: 24) + ) + contentView.addSubview(fallbackHost) + controller.registerRightSidebarHost(fallbackHost) + defer { + _ = window.makeFirstResponder(nil) + searchField.removeFromSuperview() + fallbackHost.removeFromSuperview() + window.contentView = nil + window.orderOut(nil) + } + + #expect(controller.focusRightSidebar(mode: .artifacts, focusFirstItem: true)) + #expect(controller.debugPendingRightSidebarFocusMode == .artifacts) + + contentView.addSubview(searchField) + controller.registerArtifactSearchField(searchField) + + #expect(controller.debugPendingRightSidebarFocusMode == nil) + if let responder = window.firstResponder { + #expect(searchField.ownsKeyboardFocus(responder)) + } else { + Issue.record("Expected the Artifacts search field to own keyboard focus") + } + } + + private func transcriptFixture() throws -> (root: URL, event: WorkstreamEvent) { + let root = try temporaryDirectory() + let transcript = root.appendingPathComponent("transcript.jsonl") + try Data().write(to: transcript) + return ( + root, + WorkstreamEvent( + sessionId: UUID().uuidString, + hookEventName: .userPromptSubmit, + source: "claude", + workspaceId: UUID().uuidString, + surfaceId: nil, + transcriptPath: transcript.path, + cwd: root.path, + ppid: nil, + receivedAt: .now + ) + ) + } + + private func assistantCompletionBatch( + timestamp: Date + ) -> AgentChatTranscriptTailer.Batch { + AgentChatTranscriptTailer.Batch( + appended: [ChatMessage( + id: UUID().uuidString, + seq: 1, + role: .agent, + timestamp: timestamp, + kind: .prose(ChatProse(text: "Done")) + )], + updated: [], + discoveredTitle: nil + ) + } + + private func claudeArtifactLine(path: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "type": "assistant", + "isSidechain": false, + "uuid": UUID().uuidString, + "timestamp": "2026-07-21T12:00:00.000Z", + "message": [ + "role": "assistant", + "content": [[ + "type": "tool_use", + "id": "write-plan", + "name": "Write", + "input": ["file_path": path, "content": "plan"], + ]], + ], + ]) + return String(decoding: data, as: UTF8.self) + } + + private func temporaryDirectory() throws -> URL { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + private func restore(_ value: Any?, forKey key: String) { + if let value { + UserDefaults.standard.set(value, forKey: key) + } else { + UserDefaults.standard.removeObject(forKey: key) + } + } +} diff --git a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift index 25aca0101162..88fbd17e78bc 100644 --- a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift +++ b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift @@ -1,5 +1,6 @@ import XCTest import Darwin +import CmuxArtifacts #if canImport(cmux_DEV) @testable import cmux_DEV #elseif canImport(cmux) @@ -3766,6 +3767,8 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { ("sessions-alias", ["right-sidebar", "sessions"], "right_sidebar set sessions", "OK", ""), ("feed-alias", ["right-sidebar", "feed"], "right_sidebar set feed", "OK", ""), ("dock-alias", ["right-sidebar", "dock"], "right_sidebar set dock", "OK", ""), + ("set-artifacts", ["right-sidebar", "set", "artifacts"], "right_sidebar set artifacts", "OK", ""), + ("artifacts-alias", ["right-sidebar", "artifacts"], "right_sidebar set artifacts", "OK", ""), ("mode", ["right-sidebar", "mode"], "right_sidebar mode", #"{"visible":true,"mode":"find"}"#, #"{"visible":true,"mode":"find"}"# + "\n"), ] @@ -3803,6 +3806,189 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { } } + func testNoteRemovalRequiresExplicitConfirmation() async throws { + let root = try makeTemporaryDirectory(prefix: "cmux-note-rm-confirm") + let git = runProcess( + executablePath: "/usr/bin/env", + arguments: ["git", "-C", root.path, "init", "--quiet"], + environment: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin"], + timeout: 10 + ) + XCTAssertFalse(git.timedOut, git.stderr) + XCTAssertEqual(git.status, 0, git.stderr) + + let environment = [ + "PATH": ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin", + "HOME": root.path, + "CMUX_CLI_SENTRY_DISABLED": "1", + "CMUX_WORKSPACE_ID": "workspace:note-confirm", + "CLAUDE_CODE_SESSION_ID": "note-confirm-session", + ] + let cliPath = try bundledCLIPath() + let write = runProcess( + executablePath: cliPath, + arguments: ["note", "write", "draft", "--text", "hello", "--project", root.path], + environment: environment, + timeout: 10 + ) + XCTAssertFalse(write.timedOut, write.stderr) + XCTAssertEqual(write.status, 0, write.stderr) + let repository = LocalArtifactRepository() + let writtenNotes = try await repository.listNotes(projectRoot: root) + XCTAssertEqual(writtenNotes.count, 1) + + let unconfirmedRemoval = runProcess( + executablePath: cliPath, + arguments: ["note", "rm", "draft", "--project", root.path], + environment: environment, + timeout: 10 + ) + XCTAssertFalse(unconfirmedRemoval.timedOut, unconfirmedRemoval.stderr) + XCTAssertEqual(unconfirmedRemoval.status, 2, unconfirmedRemoval.stderr) + XCTAssertTrue(unconfirmedRemoval.stderr.contains("--yes"), unconfirmedRemoval.stderr) + let preservedNotes = try await repository.listNotes(projectRoot: root) + XCTAssertEqual(preservedNotes.count, 1) + + let confirmedRemoval = runProcess( + executablePath: cliPath, + arguments: ["note", "rm", "draft", "--project", root.path, "--yes"], + environment: environment, + timeout: 10 + ) + XCTAssertFalse(confirmedRemoval.timedOut, confirmedRemoval.stderr) + XCTAssertEqual(confirmedRemoval.status, 0, confirmedRemoval.stderr) + let remainingNotes = try await repository.listNotes(projectRoot: root) + XCTAssertTrue(remainingNotes.isEmpty) + } + + func testProjectFileWriteRejectsUnboundProviderFallback() throws { + let root = try makeTemporaryDirectory(prefix: "cmux-project-file-identity") + let cliPath = try bundledCLIPath() + let result = runProcess( + executablePath: cliPath, + arguments: ["note", "write", "draft", "--text", "hello", "--project", root.path], + environment: [ + "PATH": ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin", + "HOME": root.path, + "CMUX_CLI_SENTRY_DISABLED": "1", + "CMUX_AGENT_LAUNCH_KIND": "codex", + ], + timeout: 10 + ) + XCTAssertFalse(result.timedOut, result.stderr) + XCTAssertEqual(result.status, 2, result.stderr) + XCTAssertTrue(result.stderr.contains("session identity"), result.stderr) + XCTAssertFalse( + FileManager.default.fileExists( + atPath: root.appendingPathComponent(".cmux").path + ) + ) + } + + func testProjectFileCleanupBoundsRetainedEditorCopies() throws { + let directory = try makeTemporaryDirectory(prefix: "cmux-project-file-cleanup") + for index in 0..<300 { + let url = directory.appendingPathComponent("cmux-project-file-\(index).md") + XCTAssertTrue( + FileManager.default.createFile( + atPath: url.path, + contents: Data("copy-\(index)".utf8) + ) + ) + try FileManager.default.setAttributes( + [.modificationDate: Date(timeIntervalSinceNow: -2 * 24 * 60 * 60)], + ofItemAtPath: url.path + ) + } + + ProjectFileTemporaryCopyCleaner().cleanup(in: directory) + + let copies = try FileManager.default.contentsOfDirectory(atPath: directory.path) + .filter { $0.hasPrefix("cmux-project-file-") } + XCTAssertLessThanOrEqual(copies.count, 256) + } + + func testProjectFileCleanupReservesSlotForZeroByteHandoff() throws { + let directory = try makeTemporaryDirectory(prefix: "cmux-project-file-zero-byte-cleanup") + for index in 0..<256 { + let url = directory.appendingPathComponent("cmux-project-file-zero-\(index)") + XCTAssertTrue( + FileManager.default.createFile( + atPath: url.path, + contents: Data() + ) + ) + } + + XCTAssertFalse( + ProjectFileTemporaryCopyCleaner().cleanup( + in: directory, + reservingBytes: 0, + reservingFileCount: 1 + ), + "A zero-byte handoff must still reserve one temporary-file slot" + ) + } + + func testProjectFileCleanupReclaimsExpiredCopiesForReservation() throws { + let directory = try makeTemporaryDirectory(prefix: "cmux-project-file-expired-reservation") + let now = Date() + for index in 0..<256 { + let url = directory.appendingPathComponent("cmux-project-file-expired-\(index)") + XCTAssertTrue( + FileManager.default.createFile( + atPath: url.path, + contents: Data("copy-\(index)".utf8) + ) + ) + try FileManager.default.setAttributes( + [.modificationDate: now.addingTimeInterval(-2 * 24 * 60 * 60)], + ofItemAtPath: url.path + ) + } + + XCTAssertTrue( + ProjectFileTemporaryCopyCleaner(now: now).cleanup( + in: directory, + reservingFileCount: 1 + ), + "Expired copies must be reclaimed before reserving a new handoff slot" + ) + let copies = try FileManager.default.contentsOfDirectory(atPath: directory.path) + .filter { $0.hasPrefix("cmux-project-file-") } + XCTAssertLessThanOrEqual(copies.count, 255) + } + + func testProjectFileCleanupCountsFailedUnlinksAgainstReservation() throws { + let directory = try makeTemporaryDirectory(prefix: "cmux-project-file-unlink-failure") + let now = Date() + for index in 0..<256 { + let url = directory.appendingPathComponent("cmux-project-file-unlink-\(index)") + XCTAssertTrue( + FileManager.default.createFile( + atPath: url.path, + contents: Data("copy-\(index)".utf8) + ) + ) + try FileManager.default.setAttributes( + [.modificationDate: now.addingTimeInterval(-2 * 24 * 60 * 60)], + ofItemAtPath: url.path + ) + } + defer { + _ = chmod(directory.path, 0o700) + } + XCTAssertEqual(chmod(directory.path, 0o500), 0) + + XCTAssertFalse( + ProjectFileTemporaryCopyCleaner(now: now).cleanup( + in: directory, + reservingFileCount: 1 + ), + "A failed unlink must continue to occupy its temporary-file slot" + ) + } + func testRightSidebarInvalidCommandValidatesBeforeTargetResolution() throws { let cliPath = try bundledCLIPath() let missingSocketPath = "/tmp/cmux-test-missing-\(UUID().uuidString).sock" diff --git a/cmuxTests/FileDropOverlayViewTests.swift b/cmuxTests/FileDropOverlayViewTests.swift index 5b3d2bcab800..b6866e6395b4 100644 --- a/cmuxTests/FileDropOverlayViewTests.swift +++ b/cmuxTests/FileDropOverlayViewTests.swift @@ -4,6 +4,7 @@ import SwiftUI import Testing import WebKit import CmuxUpdater +import CmuxArtifacts #if canImport(cmux_DEV) @testable import cmux_DEV @@ -17,7 +18,13 @@ struct FileDropOverlayViewTests { private func makeContentViewWindow(windowId: UUID = UUID()) -> NSWindow { _ = NSApplication.shared - let root = ContentView(updateViewModel: UpdateStateModel(), windowId: windowId) + let artifactRepository = LocalArtifactRepository() + let root = ContentView( + updateViewModel: UpdateStateModel(), + windowId: windowId, + artifactStore: artifactRepository, + artifactCaptureService: ArtifactCaptureService(store: artifactRepository) + ) .environmentObject(TabManager()) .environmentObject(TerminalNotificationStore.shared) .environmentObject(SidebarState()) diff --git a/cmuxTests/FilePreviewTextEditorTextKitTests.swift b/cmuxTests/FilePreviewTextEditorTextKitTests.swift index b157aee3c177..9fd395d73e91 100644 --- a/cmuxTests/FilePreviewTextEditorTextKitTests.swift +++ b/cmuxTests/FilePreviewTextEditorTextKitTests.swift @@ -384,6 +384,7 @@ struct FilePreviewTextEditorTextKitTests { private final class TextEditingPanelSpy: FilePreviewTextEditingPanel { var textContent = "" + var isReadOnly = false var saveCount = 0 func attachTextView(_: NSTextView) {} diff --git a/cmuxTests/GhosttyTerminalViewVisibilityPolicyTests.swift b/cmuxTests/GhosttyTerminalViewVisibilityPolicyTests.swift index 916e1fd23401..836eac54384b 100644 --- a/cmuxTests/GhosttyTerminalViewVisibilityPolicyTests.swift +++ b/cmuxTests/GhosttyTerminalViewVisibilityPolicyTests.swift @@ -26,6 +26,22 @@ private final class PortalBindLayoutCountingView: NSView { @MainActor @Suite(.serialized) struct GhosttyTerminalViewVisibilityPolicyTests { + @Test func ordinaryOccludedWindowPausesItsRenderer() { + #expect(!GhosttyNSView.effectiveRendererWindowVisibility( + occlusionVisible: false, + isVisible: true, + displayUITestRenderingEnabled: false + )) + } + + @Test func headlessDisplayTestKeepsOrderedWindowRendering() { + #expect(GhosttyNSView.effectiveRendererWindowVisibility( + occlusionVisible: false, + isVisible: true, + displayUITestRenderingEnabled: true + )) + } + @Test func staleRepresentableCannotOverwriteCurrentHostAttentionColor() { let panel = TerminalPanel(workspaceId: UUID()) let paneId = PaneID() diff --git a/cmuxTests/HiddenRightSidebarContentMountingTests.swift b/cmuxTests/HiddenRightSidebarContentMountingTests.swift index 0f2bf7322ae8..d7faae3dbe04 100644 --- a/cmuxTests/HiddenRightSidebarContentMountingTests.swift +++ b/cmuxTests/HiddenRightSidebarContentMountingTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxAppKitSupportUI +import CmuxArtifacts import CmuxSettings import SwiftUI import Testing @@ -62,17 +63,23 @@ struct HiddenRightSidebarContentMountingTests { ) defer { window.orderOut(nil) } + let artifactRepository = LocalArtifactRepository() let rootView = RightSidebarPanelView( tabManager: TabManager(), fileExplorerStore: FileExplorerStore(), fileExplorerState: fileExplorerState, sessionIndexStore: SessionIndexStore(), + featureFlags: .shared, titlebarHeight: 36, windowAppearance: .rightSidebarPanelViewTestDefault, workspaceId: nil, + artifactWorkspace: nil, + artifactStore: artifactRepository, + artifactCaptureService: ArtifactCaptureService(store: artifactRepository), onResumeSession: nil, onOpenSession: nil, onOpenFilePreview: { _ in }, + onOpenArtifact: { _ in }, onOpenAsPane: { _ in }, onClose: {}, customSidebarDataContext: { _ in [:] } diff --git a/cmuxTests/MarkdownPanelTests.swift b/cmuxTests/MarkdownPanelTests.swift index 2d9e686f8a37..3c280905b384 100644 --- a/cmuxTests/MarkdownPanelTests.swift +++ b/cmuxTests/MarkdownPanelTests.swift @@ -432,6 +432,7 @@ final class MarkdownPanelTests: XCTestCase { panelId: panelId, workspaceId: workspaceId, filePath: filePath, + allowedLocalResourceRoot: nil, fontSize: 15, fontFamily: MarkdownFontFamily.systemDefault, maxContentWidth: MarkdownMaxWidthSettings.defaultCSSPixels, @@ -448,6 +449,7 @@ final class MarkdownPanelTests: XCTestCase { panelId: panelId, workspaceId: workspaceId, filePath: filePath, + allowedLocalResourceRoot: nil, fontSize: 15, fontFamily: MarkdownFontFamily.systemDefault, maxContentWidth: MarkdownMaxWidthSettings.defaultCSSPixels, @@ -925,6 +927,9 @@ final class MarkdownPanelTests: XCTestCase { let configuration = WKWebViewConfiguration() let coordinator = MarkdownWebRenderer.Coordinator() coordinator.filePath = markdownURL.path + // Exercise the descriptor-confined artifact image path, whose + // validation and staging must remain off the main actor. + coordinator.allowedLocalResourceRoot = directoryURL configuration.setURLSchemeHandler(coordinator, forURLScheme: MarkdownWebRenderer.localImageURLScheme) let webView = MarkdownWebView(frame: frame, configuration: configuration) coordinator.webView = webView diff --git a/cmuxTests/MobileChatArtifactAuthorizationSnapshotTests.swift b/cmuxTests/MobileChatArtifactAuthorizationSnapshotTests.swift new file mode 100644 index 000000000000..0341504c4f26 --- /dev/null +++ b/cmuxTests/MobileChatArtifactAuthorizationSnapshotTests.swift @@ -0,0 +1,115 @@ +import CmuxArtifacts +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Mobile chat artifact authorization snapshot", .serialized) +struct MobileChatArtifactAuthorizationSnapshotTests { + @MainActor + @Test("Save stays bound to the session project that authorized the artifact") + func saveUsesAuthorizedSessionProject() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("MobileChatArtifactAuthorization-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let authorizedProject = root.appendingPathComponent("authorized", isDirectory: true) + let resumedProject = root.appendingPathComponent("resumed", isDirectory: true) + try FileManager.default.createDirectory( + at: authorizedProject.appendingPathComponent(".git", isDirectory: true), + withIntermediateDirectories: true + ) + try FileManager.default.createDirectory( + at: resumedProject.appendingPathComponent(".git", isDirectory: true), + withIntermediateDirectories: true + ) + let source = authorizedProject.appendingPathComponent("plan.md", isDirectory: false) + try "authorized plan".write(to: source, atomically: true, encoding: .utf8) + let transcript = authorizedProject.appendingPathComponent("transcript.jsonl", isDirectory: false) + let transcriptLines = try [ + claudeLine(type: "assistant", content: [[ + "type": "tool_use", + "id": "write-plan", + "name": "Write", + "input": ["file_path": source.path, "content": "authorized plan"], + ]]), + claudeLine(type: "user", content: [[ + "type": "tool_result", + "tool_use_id": "write-plan", + "content": "saved", + "is_error": false, + ]]), + ] + try transcriptLines.joined(separator: "\n").write( + to: transcript, + atomically: true, + encoding: .utf8 + ) + let sessionID = "session-authorization-snapshot" + let record = AgentChatSessionRecord( + sessionID: sessionID, + agentKind: .claude, + workspaceID: "workspace-authorized", + surfaceID: nil, + workingDirectory: authorizedProject.path, + workingDirectoryAuthority: .hook, + transcriptPath: transcript.path, + state: .idle, + lastActivityAt: .now, + title: nil, + pid: nil + ) + let registry = AgentChatSessionRegistry(restoredRecords: [record]) + let service = AgentChatTranscriptService( + registry: registry, + artifactCaptureCoordinator: AgentArtifactCaptureCoordinator( + captureService: ArtifactCaptureService(store: LocalArtifactRepository()) + ) + ) + let controller = TerminalController.shared + let previousService = controller.agentChatTranscriptService + controller.agentChatTranscriptService = service + defer { controller.agentChatTranscriptService = previousService } + + let resolution = await controller.mobileChatArtifactResolution( + params: ["session_id": sessionID, "path": source.path], + operation: .save + ) + guard case .success(let resolved) = resolution else { + Issue.record("Expected the transcript snapshot to authorize the artifact") + return + } + registry.noteResumeInitiated( + sessionID: sessionID, + source: "claude", + surfaceID: nil, + workspaceID: "workspace-resumed", + workingDirectory: resumedProject.path + ) + + let result = await controller.v2MobileChatArtifactSave(resolved: resolved) + guard case .ok(let rawPayload) = result, + let payload = rawPayload as? [String: Any], + let savedPath = payload["path"] as? String else { + Issue.record("Expected the authorized artifact save to succeed") + return + } + let authorizedArtifacts = ArtifactStorePaths(projectRoot: authorizedProject).filesystemRoot.path + "/" + #expect(savedPath.hasPrefix(authorizedArtifacts)) + #expect(savedPath.hasSuffix("/artifacts/plan.md")) + } + + private func claudeLine(type: String, content: [[String: Any]]) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [ + "type": type, + "isSidechain": false, + "uuid": UUID().uuidString, + "timestamp": "2026-07-21T12:00:00.000Z", + "message": ["role": type == "assistant" ? "assistant" : "user", "content": content], + ]) + return String(decoding: data, as: UTF8.self) + } +} diff --git a/cmuxTests/MobileHostIrohAdmissionTests.swift b/cmuxTests/MobileHostIrohAdmissionTests.swift index c8cd8265d6f5..2f68dbe5e02d 100644 --- a/cmuxTests/MobileHostIrohAdmissionTests.swift +++ b/cmuxTests/MobileHostIrohAdmissionTests.swift @@ -219,6 +219,20 @@ extension MobileHostAuthorizationTests { @MainActor @Suite(.serialized) struct IrohTailscaleVersionSkewMacGateTests { + @Test func artifactCapabilitiesFollowTheExplicitGate() { + let enabled = MobileHostService.mobileHostCapabilities( + includingWorkspaceChanges: false, + includingArtifacts: true + ) + let disabled = MobileHostService.mobileHostCapabilities( + includingWorkspaceChanges: false, + includingArtifacts: false + ) + #expect(enabled.contains("chat.artifact.save.v1")) + #expect(!disabled.contains("chat.artifact.save.v1")) + #expect(!disabled.contains("chat.artifact.v1")) + } + #if DEBUG @Test func testIrohRPCMethodInventorySurvivesTheFramedWirePath() async throws { let requestID = "iroh-rpc-inventory" @@ -554,9 +568,57 @@ extension MobileHostAuthorizationTests { try #require(Darwin.mkfifo(fifo.path, 0o600) == 0) let registry = MobileHostIrohArtifactTransferRegistry() let peer = try irohPeer(endpointCharacter: "f") + let identity = ChatArtifactFileIdentity(device: 0, inode: 0) await #expect(throws: MobileHostIrohArtifactTransferRegistry.Error.notRegularFile) { - try await registry.issue(canonicalPath: fifo.path, peer: peer) + try await registry.issue( + canonicalPath: fifo.path, + authorizedIdentity: identity, + peer: peer + ) + } + } + + @Test func testIrohArtifactIssueRejectsReplacedAuthorizedAncestor() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-iroh-artifact-ancestor-swap-\(UUID().uuidString)", + isDirectory: true + ) + let insideDirectory = root.appendingPathComponent("inside", isDirectory: true) + let outsideDirectory = root.appendingPathComponent("outside", isDirectory: true) + try FileManager.default.createDirectory( + at: insideDirectory, + withIntermediateDirectories: true + ) + try FileManager.default.createDirectory( + at: outsideDirectory, + withIntermediateDirectories: true + ) + let authorizedFile = insideDirectory.appendingPathComponent("preview.bin") + let outsideFile = outsideDirectory.appendingPathComponent("preview.bin") + try Data("authorized".utf8).write(to: authorizedFile, options: .atomic) + try Data("outside".utf8).write(to: outsideFile, options: .atomic) + let authorizedPath = authorizedFile.resolvingSymlinksInPath().standardizedFileURL.path + let authorizedIdentity = try ArtifactByteReader().identity( + path: authorizedPath, + authorizedCanonicalPath: authorizedPath + ) + defer { try? FileManager.default.removeItem(at: root) } + + try FileManager.default.removeItem(at: insideDirectory) + try FileManager.default.createSymbolicLink( + at: insideDirectory, + withDestinationURL: outsideDirectory + ) + + let registry = MobileHostIrohArtifactTransferRegistry() + let peer = try irohPeer(endpointCharacter: "e") + await #expect(throws: MobileHostIrohArtifactTransferRegistry.Error.fileNotFound) { + try await registry.issue( + canonicalPath: authorizedPath, + authorizedIdentity: authorizedIdentity, + peer: peer + ) } } @@ -575,9 +637,14 @@ extension MobileHostAuthorizationTests { ) let peer = try irohPeer(endpointCharacter: "a") let otherPeer = try irohPeer(endpointCharacter: "b") + let identity = try ArtifactByteReader().identity( + path: fixture.path, + authorizedCanonicalPath: fixture.path + ) let descriptor = try await registry.issue( canonicalPath: fixture.path, + authorizedIdentity: identity, peer: peer ) @@ -663,7 +730,14 @@ extension MobileHostAuthorizationTests { resourceID: { resourceID } ) let peer = try irohPeer(endpointCharacter: "c") - _ = try await registry.issue(canonicalPath: fixture.path, peer: peer) + _ = try await registry.issue( + canonicalPath: fixture.path, + authorizedIdentity: try ArtifactByteReader().identity( + path: fixture.path, + authorizedCanonicalPath: fixture.path + ), + peer: peer + ) let send = RecordingMobileHostIrohArtifactSendStream() let receive = RecordingMobileHostIrohArtifactReceiveStream() let handler = MobileHostIrohArtifactLaneHandler(registry: registry) @@ -697,7 +771,14 @@ extension MobileHostAuthorizationTests { resourceID: { resourceID } ) let peer = try irohPeer(endpointCharacter: "d") - _ = try await registry.issue(canonicalPath: fixture.path, peer: peer) + _ = try await registry.issue( + canonicalPath: fixture.path, + authorizedIdentity: try ArtifactByteReader().identity( + path: fixture.path, + authorizedCanonicalPath: fixture.path + ), + peer: peer + ) let send = MutatingMobileHostIrohArtifactSendStream(path: fixture.path) let receive = RecordingMobileHostIrohArtifactReceiveStream() @@ -794,7 +875,7 @@ private struct MobileHostIrohArtifactFixture { let file = directory.appendingPathComponent("private-preview.bin") try contents.write(to: file, options: .atomic) self.directory = directory - self.path = file.path + self.path = file.resolvingSymlinksInPath().standardizedFileURL.path } func remove() { diff --git a/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift b/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift index 44d1b6ba067e..851af3284e86 100644 --- a/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift +++ b/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift @@ -461,6 +461,47 @@ struct MobileHostWorkspaceTicketAuthorizationTests { } } + @Test func chatArtifactRequestsUseSessionAuthorizationForBothTicketScopes() throws { + let methods = [ + "mobile.chat.artifact.stat", + "mobile.chat.artifact.fetch", + "mobile.chat.artifact.thumbnail", + "mobile.chat.artifact.list", + "mobile.chat.artifact.save", + "mobile.chat.artifact.gallery", + ] + for workspaceID in ["workspace", ""] { + let ticket = try scopedAttachTicket(workspaceID: workspaceID) + for method in methods { + var params: [String: Any] = ["session_id": "session"] + if method != "mobile.chat.artifact.gallery" { + params["path"] = "/tmp/artifact" + } + let request = MobileHostRPCRequest( + id: method, + method: method, + params: params, + auth: MobileHostRPCAuth( + attachToken: ticket.authToken, + stackAccessToken: nil + ) + ) + let error = MobileHostService.ticketAuthorizationError( + ticket: ticket, + request: request + ) + let expectedCode = method == "mobile.chat.artifact.save" + && !workspaceID.isEmpty + ? "forbidden" + : nil + #expect( + error?.code == expectedCode, + "\(method) authorization mismatch for workspaceID=\(workspaceID)" + ) + } + } + } + private func scopedAttachTicket(workspaceID: String) throws -> CmxAttachTicket { let route = try CmxAttachRoute( id: "debug", diff --git a/cmuxTests/NoteCLIIntegrationTests.swift b/cmuxTests/NoteCLIIntegrationTests.swift new file mode 100644 index 000000000000..3158a86fd7ee --- /dev/null +++ b/cmuxTests/NoteCLIIntegrationTests.swift @@ -0,0 +1,372 @@ +import Foundation +import Testing + +@Suite("Note CLI integration") +struct NoteCLIIntegrationTests { + @Test("Notes are ordinary movable files in the current agent session") + func writesReadsSearchesAndRediscoversMovedNotes() throws { + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-cli-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory( + at: projectRoot.appendingPathComponent(".git", isDirectory: true), + withIntermediateDirectories: true + ) + defer { try? fileManager.removeItem(at: projectRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + let environment = [ + "CMUX_AGENT_NAME": "codex", + "CMUX_AGENT_SESSION_ID": "session:cli", + "CMUX_WORKSPACE_ID": "workspace:cli", + ] + + let written = try runCLI( + cliPath, + [ + "note", "write", "plan", "--text", "first needle", + "--project", projectRoot.path, "--json", + ], + environment: environment + ) + #expect(written.status == 0) + let writtenPayload = try jsonObject(written.stdout) + let relativePath = try #require(writtenPayload["relative_path"] as? String) + #expect(relativePath.hasSuffix("/notes/plan.md")) + let sessionRoot = try #require(relativePath.split(separator: "/").first) + let path = try #require(writtenPayload["path"] as? String) + #expect(fileManager.fileExists(atPath: path)) + + let appended = try runCLI( + cliPath, + ["note", "append", "plan", "--stdin", "--project", projectRoot.path], + standardInput: "\nsecond line", + environment: environment + ) + #expect(appended.status == 0) + + let read = try runCLI( + cliPath, + ["note", "read", "plan", "--project", projectRoot.path], + environment: environment + ) + #expect(read.status == 0) + #expect(read.stdout == "first needle\nsecond line") + + let searched = try runCLI( + cliPath, + ["note", "search", "needle", "--project", projectRoot.path, "--json"], + environment: environment + ) + #expect(searched.status == 0) + let searchedPayload = try jsonObject(searched.stdout) + let results = try #require(searchedPayload["results"] as? [[String: Any]]) + #expect(results.first?["relative_path"] as? String == relativePath) + + let moved = projectRoot.appendingPathComponent( + ".cmux/\(sessionRoot)/notes/organized/renamed.md" + ) + try fileManager.createDirectory( + at: moved.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try fileManager.moveItem(at: URL(fileURLWithPath: path), to: moved) + + let movedRead = try runCLI( + cliPath, + ["note", "read", "renamed", "--project", projectRoot.path], + environment: environment + ) + #expect(movedRead.status == 0) + #expect(movedRead.stdout == "first needle\nsecond line") + + let artifacts = try runCLI( + cliPath, + ["artifact", "search", "renamed", "--project", projectRoot.path, "--json"], + environment: environment + ) + #expect(artifacts.status == 0) + let artifactPayload = try jsonObject(artifacts.stdout) + let artifactResults = try #require(artifactPayload["results"] as? [[String: Any]]) + #expect(artifactResults.first?["relative_path"] as? String + == "\(sessionRoot)/notes/organized/renamed.md") + } + + @Test("Note writes require exactly one input source") + func writesRejectMissingOrConflictingInputSources() throws { + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-input-cli-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: projectRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + let environment = [ + "CMUX_AGENT_NAME": "codex", + "CMUX_AGENT_SESSION_ID": "session:input", + ] + let invalidArguments = [ + ["note", "write", "missing", "--project", projectRoot.path], + [ + "note", "write", "conflicting", "--text", "text", "--stdin", + "--project", projectRoot.path, + ], + ] + + for arguments in invalidArguments { + let result = try runCLI( + cliPath, + arguments, + environment: environment + ) + + #expect(result.status == 2) + } + #expect(!fileManager.fileExists(atPath: projectRoot.appendingPathComponent(".cmux").path)) + } + + @Test("Note removal requires an exact name") + func removalDoesNotUseFuzzyMatches() throws { + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-rm-cli-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: projectRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + let environment = [ + "CMUX_AGENT_NAME": "codex", + "CMUX_AGENT_SESSION_ID": "session:rm", + ] + let written = try runCLI( + cliPath, + [ + "note", "write", "planning", "--text", "keep me", + "--project", projectRoot.path, "--json", + ], + environment: environment + ) + #expect(written.status == 0) + let path = try #require(jsonObject(written.stdout)["path"] as? String) + + let removed = try runCLI( + cliPath, + ["note", "rm", "plan", "--project", projectRoot.path], + environment: environment + ) + + #expect(removed.status == 2) + #expect(fileManager.fileExists(atPath: path)) + } + + @Test("Agent-native session identifiers select distinct project-file roots") + func nativeAgentSessionIdentifiersTakePrecedence() throws { + let cases: [(environment: [String: String], sessionID: String, agentName: String)] = [ + (["CODEX_THREAD_ID": "codex-thread"], "codex-thread", "codex"), + (["CODEX_SESSION_ID": "codex-session"], "codex-session", "codex"), + ([ + "CODEX_THREAD_ID": "codex-consistent", + "CODEX_SESSION_ID": "codex-consistent", + ], "codex-consistent", "codex"), + (["CLAUDE_CODE_SESSION_ID": "claude-session"], "claude-session", "claude"), + (["OPENCODE_SESSION_ID": "opencode-session"], "opencode-session", "opencode"), + ] + let fileManager = FileManager.default + let projectRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-native-session-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: projectRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + var sessionRoots: Set = [] + + for (index, testCase) in cases.enumerated() { + var environment = testCase.environment + environment["CMUX_AGENT_SESSION_ID"] = "generic-fallback" + environment["CMUX_AGENT_NAME"] = "generic" + environment["CMUX_WORKSPACE_ID"] = "shared-workspace" + let written = try runCLI( + cliPath, + [ + "note", "write", "plan-\(index)", "--text", "private", + "--project", projectRoot.path, "--json", + ], + environment: environment + ) + #expect(written.status == 0) + let payload = try jsonObject(written.stdout) + let relativePath = try #require(payload["relative_path"] as? String) + let sessionRoot = String(try #require(relativePath.split(separator: "/").first)) + sessionRoots.insert(sessionRoot) + let markerURL = projectRoot.appendingPathComponent( + ".cmux/\(sessionRoot)/_session.json" + ) + let marker = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: markerURL)) + as? [String: Any] + ) + #expect(marker["sessionID"] as? String == testCase.sessionID) + #expect(marker["agentName"] as? String == testCase.agentName) + } + + #expect(sessionRoots.count == cases.count) + } + + @Test("Agent wrapper launch kinds agree with their native session identifiers") + func wrapperLaunchKindsUseNativeAgentFamilies() throws { + let cases: [(launchKind: String, sessionKey: String, sessionID: String, agentName: String)] = [ + ("omx", "CODEX_THREAD_ID", "wrapper-codex", "codex"), + ("omc", "CLAUDE_CODE_SESSION_ID", "wrapper-claude", "claude"), + ("omo", "OPENCODE_SESSION_ID", "wrapper-opencode", "opencode"), + ] + let fileManager = FileManager.default + let testRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-wrapper-session-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: testRoot, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: testRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + + for testCase in cases { + let projectRoot = testRoot.appendingPathComponent( + testCase.launchKind, + isDirectory: true + ) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + let result = try runCLI( + cliPath, + [ + "note", "write", "plan", "--text", "private", + "--project", projectRoot.path, "--json", + ], + environment: [ + "CMUX_AGENT_LAUNCH_KIND": testCase.launchKind, + testCase.sessionKey: testCase.sessionID, + ] + ) + + #expect(result.status == 0) + let payload = try jsonObject(result.stdout) + let relativePath = try #require(payload["relative_path"] as? String) + let sessionRoot = String(try #require(relativePath.split(separator: "/").first)) + let markerURL = projectRoot.appendingPathComponent( + ".cmux/\(sessionRoot)/_session.json" + ) + let marker = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: markerURL)) + as? [String: Any] + ) + #expect(marker["sessionID"] as? String == testCase.sessionID) + #expect(marker["agentName"] as? String == testCase.agentName) + } + } + + @Test("Conflicting native agent identities never select an inherited parent session") + func conflictingNativeAgentIdentitiesFailClosed() throws { + let fileManager = FileManager.default + let testRoot = fileManager.temporaryDirectory + .appendingPathComponent("cmux-note-ambiguous-session-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: testRoot, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: testRoot) } + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: BundledCLILinkageTests.self + ) + let conflictingEnvironments: [[String: String]] = [ + [ + "CMUX_AGENT_LAUNCH_KIND": "codex", + "CODEX_THREAD_ID": "inherited-parent-codex", + "CLAUDE_CODE_SESSION_ID": "current-child-claude", + ], + [ + "CMUX_AGENT_LAUNCH_KIND": "codex", + "CODEX_THREAD_ID": "inherited-parent-codex", + "CODEX_SESSION_ID": "current-child-codex", + ], + [ + "CMUX_AGENT_LAUNCH_KIND": "codex", + "CLAUDE_CODE_SESSION_ID": "current-child-claude", + ], + [ + "CMUX_AGENT_LAUNCH_KIND": "amp", + "CMUX_AGENT_SESSION_ID": "current-child-amp", + "CODEX_THREAD_ID": "inherited-parent-codex", + ], + [ + "CMUX_AGENT_LAUNCH_KIND": "codexTeams", + "CLAUDE_CODE_SESSION_ID": "current-child-claude", + ], + [ + "CMUX_AGENT_LAUNCH_KIND": "claudeTeams", + "CODEX_THREAD_ID": "current-child-codex", + ], + ] + + for (index, environment) in conflictingEnvironments.enumerated() { + let projectRoot = testRoot.appendingPathComponent("case-\(index)", isDirectory: true) + try fileManager.createDirectory(at: projectRoot, withIntermediateDirectories: true) + let result = try runCLI( + cliPath, + [ + "note", "write", "plan", "--text", "private", + "--project", projectRoot.path, + ], + environment: environment + ) + + #expect(result.status == 2) + #expect(!fileManager.fileExists(atPath: projectRoot.appendingPathComponent(".cmux").path)) + } + } + + private func runCLI( + _ executablePath: String, + _ arguments: [String], + standardInput: String? = nil, + environment additions: [String: String] + ) throws -> (status: Int32, stdout: String, stderr: String) { + let process = Process() + let stdin = Pipe() + let stdout = Pipe() + let stderr = Pipe() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + for key in [ + "CODEX_THREAD_ID", + "CODEX_SESSION_ID", + "CLAUDE_CODE_SESSION_ID", + "OPENCODE_SESSION_ID", + ] { + environment.removeValue(forKey: key) + } + environment.merge(additions) { _, supplied in supplied } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + process.environment = environment + process.standardInput = stdin + process.standardOutput = stdout + process.standardError = stderr + try process.run() + if let standardInput { + try stdin.fileHandleForWriting.write(contentsOf: Data(standardInput.utf8)) + } + try stdin.fileHandleForWriting.close() + process.waitUntilExit() + return ( + process.terminationStatus, + String(decoding: stdout.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self), + String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + ) + } + + private func jsonObject(_ text: String) throws -> [String: Any] { + try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + } +} diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index 6f3f755284d6..269ea966b57e 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -17,8 +17,12 @@ final class OpenCodeHookRegressionTests: XCTestCase { let pluginURL = repoRoot.appendingPathComponent("Resources/opencode-plugin.js", isDirectory: false) XCTAssertTrue(fileManager.fileExists(atPath: pluginURL.path)) + // AF_UNIX socket paths are capped at 104 bytes on macOS. Keep the + // generated directory name short because CI temporary-directory roots + // can already consume most of that budget. + let shortID = String(UUID().uuidString.prefix(8)) let root = fileManager.temporaryDirectory.appendingPathComponent( - "cmux-opencode-feed-\(UUID().uuidString)", isDirectory: true + "cmux-opencode-\(shortID)", isDirectory: true ) try fileManager.createDirectory(at: root, withIntermediateDirectories: true) defer { try? fileManager.removeItem(at: root) } diff --git a/cmuxTests/PostHogAnalyticsPropertiesTests.swift b/cmuxTests/PostHogAnalyticsPropertiesTests.swift index ac11763da48a..30ac0d8a8b06 100644 --- a/cmuxTests/PostHogAnalyticsPropertiesTests.swift +++ b/cmuxTests/PostHogAnalyticsPropertiesTests.swift @@ -271,6 +271,31 @@ struct PostHogAnalyticsPropertiesTests { #expect(!offlineRelaunch.isMobileTerminalFilesChipEnabled) } + @MainActor + @Test("Artifacts feature flag accepts a remote enable and kill switch") + func artifactsFeatureFlagKillSwitch() throws { + let suiteName = "cmux.feature.flags.artifacts.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + var remoteValues: [String: Any] = [:] + let flags = CmuxFeatureFlags(defaults: defaults) { key in + remoteValues[key] + } + let flag = CmuxFeatureFlags.artifactsFlag + + remoteValues[flag.key] = true + flags.applyLoadedFlags() + #expect(flags.isArtifactsEnabled) + + remoteValues[flag.key] = false + flags.applyLoadedFlags() + #expect(!flags.isArtifactsEnabled) + + let offlineRelaunch = CmuxFeatureFlags(defaults: defaults) { _ in nil } + #expect(!offlineRelaunch.isArtifactsEnabled) + } + @MainActor @Test("successful control-plane omission clears a cached remote disable") func successfulControlPlaneOmissionClearsCachedDisable() async throws { diff --git a/cmuxTests/ReleasingWindowControllerTests.swift b/cmuxTests/ReleasingWindowControllerTests.swift index f27d5cd83749..c14fa57f03a7 100644 --- a/cmuxTests/ReleasingWindowControllerTests.swift +++ b/cmuxTests/ReleasingWindowControllerTests.swift @@ -57,6 +57,23 @@ struct ReleasingWindowControllerTests { #expect(controller.window === secondWindow) } + @Test + func contentViewWindowReferenceDoesNotRetainWindow() { + var window: NSWindow? = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 120, height: 80), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + weak var weakWindow = window + let reference = WeakWindowReference(window) + + window = nil + + #expect(weakWindow == nil) + #expect(reference.window == nil) + } + private final class CountingReleasingWindowController: ReleasingWindowController { var makeWindowCount = 0 var closedWindowIdentifiers: [String] = [] diff --git a/cmuxTests/RightSidebarRemoteCommandTests.swift b/cmuxTests/RightSidebarRemoteCommandTests.swift index 0d320bf5ebb4..01796ff4eb4b 100644 --- a/cmuxTests/RightSidebarRemoteCommandTests.swift +++ b/cmuxTests/RightSidebarRemoteCommandTests.swift @@ -136,6 +136,10 @@ extension TerminalControllerSocketSecurityTests { "right_sidebar set vault --no-focus", RightSidebarRemoteRequest(command: .setMode(.sessions, focus: false), target: RightSidebarRemoteTarget()) ), + ( + "right_sidebar set artifacts --no-focus", + RightSidebarRemoteRequest(command: .setMode(.artifacts, focus: false), target: RightSidebarRemoteTarget()) + ), ( "right_sidebar sessions", RightSidebarRemoteRequest(command: .setMode(.sessions, focus: true), target: RightSidebarRemoteTarget()) diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index b9df4b135401..c7b8f19e2c31 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -2,6 +2,7 @@ import Testing import AppKit import CmuxNotifications import CmuxUpdater +import CmuxArtifacts import CoreGraphics import Observation import SwiftUI @@ -226,7 +227,13 @@ final class WorkspaceContentViewVisibilityTests { } let notificationStore = TerminalNotificationStore.shared let counts = MinimalModeBodyProbeCounts() - let root = ContentView(updateViewModel: UpdateStateModel(), windowId: UUID()) + let artifactRepository = LocalArtifactRepository() + let root = ContentView( + updateViewModel: UpdateStateModel(), + windowId: UUID(), + artifactStore: artifactRepository, + artifactCaptureService: ArtifactCaptureService(store: artifactRepository) + ) .environmentObject(tabManager) .environmentObject(notificationStore) .environmentObject(SidebarState()) diff --git a/skills/cmux-project-files/SKILL.md b/skills/cmux-project-files/SKILL.md new file mode 100644 index 000000000000..723e07c2eaae --- /dev/null +++ b/skills/cmux-project-files/SKILL.md @@ -0,0 +1,100 @@ +--- +name: cmux-project-files +description: Read, write, find, import, reference, open, and reorganize project-local cmux Notes and Artifacts. Use when an agent needs to persist plans or Markdown notes, save generated images/video/HTML/patches/text files, retrieve prior agent output, search the project's `.cmux` filesystem, or provide a prompt-ready local file reference. +--- + +# cmux Project Files + +Use the `cmux note` and `cmux artifact` commands as the shared interface to the +project-local filesystem. Let the CLI discover the project and current agent +session; never invent or hard-code a session folder name. + +## Filesystem contract + +Treat live files as authoritative: + +```text +/.cmux/ + / + _session.json + _workspace.json + artifacts/ + notes/ + .metadata/ +``` + +Artifacts and Notes are ordinary local files. A user or agent may rename and +organize content with Finder or shell tools, and later CLI calls rescan the live +tree. Keep Notes under a session's `notes/` directory and Artifacts under its +`artifacts/` directory. Do not edit `_session.json`, `_workspace.json`, or +`.metadata/`. + +Commands default to the nearest ancestor containing `.cmux` or `.git`. Add +`--project ` when the intended project is not the current one. Add +`--json` when consuming command output programmatically. + +## Work with Notes + +Create or replace a Markdown note: + +```bash +cmux note write plan --text "# Plan" +``` + +Use `--stdin` instead of `--text` for multiline or generated content. Append, +read, discover, search, open, or remove Notes with: + +```bash +printf '\nNext step' | cmux note append plan --stdin +cmux note read plan +cmux note list +cmux note path plan +cmux note search "next step" +cmux note open plan +cmux note rm plan --yes +``` + +Note removal is destructive and requires the explicit `--yes` confirmation +flag. + +Names may be a filename, stem, `.cmux/...` reference, or unambiguous relative +path. Prefer the returned `reference` from JSON output when mentioning a Note in +an agent prompt. + +## Work with Artifacts + +Import an existing generated file through capture policy and provenance: + +```bash +cmux artifact add ./output/report.html +``` + +Discover, resolve, open, and search Artifacts and other visible session files: + +```bash +cmux artifact list +cmux artifact path report.html +cmux artifact search "report" +cmux artifact open report.html +``` + +Use `cmux artifact path --json` to obtain an absolute path before reading +the contents with ordinary file tools. Never add whole build directories or +bypass the CLI's type and size limits. + +## Move and reference files + +Resolve a file with `cmux note path` or `cmux artifact path` before moving or +renaming it. Keep the file inside the project's `.cmux` filesystem and preserve +the session markers. Subsequent list, search, read, and path commands rediscover +the new live location. + +Use prompt references in this form: + +```text +.cmux//notes/plan.md +.cmux//artifacts/report.html +``` + +Copy the exact `.cmux/...` value returned by the CLI; do not reconstruct the +session component yourself. diff --git a/skills/cmux-project-files/agents/openai.yaml b/skills/cmux-project-files/agents/openai.yaml new file mode 100644 index 000000000000..bed988fdaa4f --- /dev/null +++ b/skills/cmux-project-files/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "cmux Project Files" + short_description: "Read and write local agent Notes and Artifacts" + default_prompt: "Use $cmux-project-files to save and retrieve project Notes and Artifacts through the cmux CLI." diff --git a/vendor/bonsplit b/vendor/bonsplit index d967a8612e52..cb9bcfa8b841 160000 --- a/vendor/bonsplit +++ b/vendor/bonsplit @@ -1 +1 @@ -Subproject commit d967a8612e52827cfef8c9343394c98e30dc8801 +Subproject commit cb9bcfa8b841278ec952a7c9689387b1348b4aa1