adds claude-generated commit messages and a recent commits panel to the git view - adds log tailing in the explorer, branch merging and a clean up button

This commit is contained in:
2026-11-04 10:07:52 +01:00
parent 600d4874d2
commit cc6651c08a
49 changed files with 1944 additions and 180 deletions
@@ -5,6 +5,8 @@ public enum TerminalKind: String, Sendable, Equatable, CaseIterable {
case agent
/// The bottom pane: a plain login shell.
case shell
/// The Explorer's log block: `tail -f` on one file.
case tail
}
/// Executable, arguments and environment for one terminal pane.
@@ -21,7 +23,7 @@ public struct TerminalLaunch: Sendable, Equatable {
self.workingDirectory = workingDirectory
}
/// The launch for a pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
/// The launch for the agent or shell pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
/// files (nvm etc.) but leaves no prompt line or echoed command behind.
public static func make(kind: TerminalKind, config: HelderConfig, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
let shell = config.terminal.shell ?? base["SHELL"] ?? "/bin/zsh"
@@ -30,6 +32,12 @@ public struct TerminalLaunch: Sendable, Equatable {
return TerminalLaunch(executable: shell, arguments: args, environment: environment(from: base), workingDirectory: cwd)
}
/// `tail -f` on a project-relative path, run directly without a shell.
public static func tail(path: String, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
TerminalLaunch(executable: "/usr/bin/tail", arguments: ["-f", path], environment: environment(from: base),
workingDirectory: projectRoot ?? base["HOME"] ?? "/")
}
/// The child environment. A GUI launch inherits no locale and no COLORTERM, which turns
/// multibyte output into mojibake and shifts the CLI's 24-bit colours; npm's prefix
/// variables make nvm refuse to load. `TERM_PROGRAM` tells the agent it runs in Helder.
+34 -15
View File
@@ -9,8 +9,8 @@ public enum ContextTarget: Sendable, Equatable {
case directory(path: String)
/// A file row in the Git view; a deleted file has nothing to open.
case gitRow(path: String, isDeleted: Bool)
/// The caret beside the Git view's Commit button.
case commitMenu
/// A row in the Git view's Branches panel; `current` is the checked-out branch.
case branch(name: String, remote: Bool, current: String, isDirty: Bool)
/// The empty space under the tree: the project folder itself.
case projectRoot
case terminal(TerminalKind, hasSelection: Bool)
@@ -19,7 +19,7 @@ public enum ContextTarget: Sendable, Equatable {
switch self {
case let .editor(reference, _, _): reference.path
case let .file(path), let .directory(path), let .gitRow(path, _): path
case .projectRoot, .terminal, .commitMenu: ""
case .projectRoot, .terminal, .branch: ""
}
}
}
@@ -36,7 +36,8 @@ public enum ContextAction: Sendable, Equatable {
case openFile(String)
/// Reverts unstaged changes: modified and deleted files come back from the index, new files are removed.
case gitDiscard([String])
case commit(andPush: Bool)
/// The Git view's Clean up: every unstaged change reverted to the index, every untracked file and folder removed.
case gitCleanUp
/// Opens the Diff of the open file at this line.
case showDiff(String, line: Int)
case rename(String, isDirectory: Bool)
@@ -52,16 +53,20 @@ public enum ContextAction: Sendable, Equatable {
case bouwen(String)
/// Reads a Markdown file's prose aloud.
case readAloudFile(String)
/// Runs `tail -f` on a `.log` file in the Explorer's tail block, replacing any running tail.
case tailLog(String)
case readAloudText(String)
/// Sends the editor selection to Plak as it is, code and all.
case plak(String)
/// Sends the pane's selection to Plak; the text is fetched when the item runs.
case plakTerminalSelection(TerminalKind)
/// Merges this branch into the current one.
case mergeBranch(String)
/// Destructive items read in amber-deep.
public var isDestructive: Bool {
switch self {
case .gitDiscard, .delete: true
case .gitDiscard, .gitCleanUp, .delete: true
default: false
}
}
@@ -69,7 +74,7 @@ public enum ContextAction: Sendable, Equatable {
/// The menu's main item, set in bold.
public var isEmphasized: Bool {
switch self {
case .openFile, .commit(andPush: true): true
case .openFile: true
default: false
}
}
@@ -78,7 +83,15 @@ public enum ContextAction: Sendable, Equatable {
/// A menu entry, or a separator between groups.
public enum ContextMenuEntry: Sendable, Equatable {
case action(ContextAction, label: String)
/// Shown dimmed with its `hint` as tooltip; the keyboard skips it and a click does nothing.
case disabled(ContextAction, label: String, hint: String)
case separator
/// The keyboard can land on it.
public var isSelectable: Bool {
if case .action = self { return true }
return false
}
}
public enum ContextActions {
@@ -86,8 +99,9 @@ public enum ContextActions {
public static func header(for target: ContextTarget, projectName: String) -> String {
switch target {
case let .file(path), let .gitRow(path, _): path
case let .branch(name, _, _, _): name
case .projectRoot: projectName + "/"
case .editor, .directory, .terminal, .commitMenu: ""
case .editor, .directory, .terminal: ""
}
}
@@ -110,7 +124,7 @@ public enum ContextActions {
.action(.revealInFinder(""), label: "Show in Finder"),
]
case let .file(path):
return fileHead(path) + readAloudFile(path) + [
return fileHead(path) + readAloudFile(path) + tailLog(path) + [
.separator,
.action(.rename(path, isDirectory: false), label: "Rename file"),
.action(.revealInFinder(path), label: "Show in Finder"),
@@ -136,19 +150,20 @@ public enum ContextActions {
.separator, .action(.plakTerminalSelection(kind), label: "Plak")] : []
let waitWhat: [ContextMenuEntry] = hasSelection && kind == .agent
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
let paste: [ContextMenuEntry] = kind == .tail ? [] : [.action(.pasteIntoTerminal(kind), label: "Paste")]
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : []) + paste + readAloud + waitWhat
case let .gitRow(path, isDeleted):
let open: [ContextMenuEntry] = isDeleted ? [] : [.action(.openFile(path), label: "Open in editor"), .separator]
return open + [
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
.action(.copyReference(path), label: "Copy reference"),
]
case .commitMenu:
return [
.action(.commit(andPush: false), label: "Commit"),
.action(.commit(andPush: true), label: "Commit and push"),
]
case let .branch(name, remote, current, isDirty):
if !remote && name == current { return [] }
let label = "Merge into \(current)"
return [isDirty
? .disabled(.mergeBranch(name), label: label, hint: "Commit or discard your changes first")
: .action(.mergeBranch(name), label: label)]
}
}
@@ -163,6 +178,10 @@ public enum ContextActions {
FileType.isMarkdown(path) ? [.separator, .action(.readAloudFile(path), label: "Read aloud")] : []
}
private static func tailLog(_ path: String) -> [ContextMenuEntry] {
(path as NSString).pathExtension.lowercased() == "log" ? [.separator, .action(.tailLog(path), label: "Tail log")] : []
}
/// Selected Markdown is read as prose; a selection with no prose left, such as one code block, is read as it is.
private static func readAloudSelection(_ code: String, path: String) -> [ContextMenuEntry] {
let prose = FileType.isMarkdown(path) ? MarkdownSpeech.plainText(MarkdownParser.parse(code)) : ""
@@ -0,0 +1,71 @@
import Foundation
/// The staged changes as `git diff --cached` prints them: the `--stat` summary and the full patch.
public struct StagedDiff: Sendable, Equatable {
public var stat: String
public var patch: String
public init(stat: String, patch: String) {
self.stat = stat
self.patch = patch
}
public var isEmpty: Bool {
patch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
/// The prompt that asks the Claude CLI for one commit message, and the cleaning of its answer.
public enum CommitMessagePrompt {
public static let maxPatchCharacters = 60_000
public static let examples = [
"Adds a new button on the header to navigate to profile",
"Fixed security issue that made it possible to hack a file upload",
"Makes sure the register form does not accept R&B fans - Enforces password rules on login form",
]
/// The full prompt; a patch over `limit` characters is cut and the prompt says so, the stat always stays whole.
public static func make(_ diff: StagedDiff, limit: Int = maxPatchCharacters) -> String {
let isCut = diff.patch.count > limit
let patch = isCut ? String(diff.patch.prefix(limit)) : diff.patch
var lines = [
"Write ONE git commit message for the staged changes below.",
"",
"Rules:",
"- One single sentence on one line. No body, no quotes, no prefix such as \"feat:\". A trailing period is not needed.",
"- English. Start with a verb in the third person or in the past tense.",
"- When two separate things changed, join them with \" - \" in that one line.",
"- Reply with the message only, nothing else.",
"",
"Examples:",
"- \(examples[0])",
"- \(examples[1])",
"- \(examples[2]) (two things changed)",
"",
"Changed files (git diff --cached --stat):",
diff.stat.trimmingCharacters(in: .newlines),
"",
"Diff (git diff --cached):",
]
if isCut {
lines.append("(The diff is cut after \(limit) characters; the file list above is complete.)")
}
lines.append(patch.trimmingCharacters(in: .newlines))
return lines.joined(separator: "\n")
}
/// The first non-empty line, Markdown fence lines skipped, without surrounding quotes or backticks and with single spaces;
/// nil when nothing is left.
public static func clean(_ output: String) -> String? {
let wrappers: Set<Character> = ["\"", "'", "`", "“", "”", "‘", "’"]
guard var line = output.split(whereSeparator: \.isNewline)
.map({ $0.trimmingCharacters(in: .whitespaces) })
.first(where: { !$0.isEmpty && !$0.hasPrefix("```") }) else { return nil }
while let first = line.first, let last = line.last, line.count >= 2, wrappers.contains(first), wrappers.contains(last) {
line = String(line.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)
}
line = line.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
return line.isEmpty ? nil : line
}
}
+50
View File
@@ -0,0 +1,50 @@
import Foundation
/// One commit of HEAD's recent history, as the Git view's commit list shows it.
public struct GitCommitSummary: Sendable, Equatable {
public var hash: String
public var subject: String
public var author: String
public var date: Date
public init(hash: String, subject: String, author: String, date: Date) {
self.hash = hash
self.subject = subject
self.author = author
self.date = date
}
}
public enum GitCommitLogParsing {
public static let limit = 30
/// NUL between fields and a record separator after each commit, so no subject can split a record.
public static let arguments = ["log", "-n", "\(limit)", "--no-color", "--format=%h%x00%s%x00%an%x00%ct%x1e"]
/// Reads the records `arguments` prints, newest first; a malformed record is skipped.
public static func commits(_ raw: String) -> [GitCommitSummary] {
raw.split(separator: "\u{1e}").compactMap { record in
let text = record.trimmingCharacters(in: .newlines)
let fields = text.split(separator: "\0", omittingEmptySubsequences: false)
guard fields.count == 4, !fields[0].isEmpty, let seconds = TimeInterval(fields[3]) else { return nil }
return GitCommitSummary(hash: String(fields[0]), subject: String(fields[1]), author: String(fields[2]),
date: Date(timeIntervalSince1970: seconds))
}
}
}
public enum RelativeTime {
/// "just now", "5 min ago", "3 h ago", "2 d ago", "3 w ago", "4 mo ago", "2 y ago"; a future date reads "just now".
public static func text(_ date: Date, now: Date) -> String {
let seconds = Int(now.timeIntervalSince(date))
let minute = 60, hour = 3_600, day = 86_400
switch seconds {
case ..<minute: return "just now"
case ..<hour: return "\(seconds / minute) min ago"
case ..<day: return "\(seconds / hour) h ago"
case ..<(7 * day): return "\(seconds / day) d ago"
case ..<(30 * day): return "\(seconds / (7 * day)) w ago"
case ..<(365 * day): return "\(seconds / (30 * day)) mo ago"
default: return "\(seconds / (365 * day)) y ago"
}
}
}
@@ -0,0 +1,87 @@
import Foundation
import HelderCore
/// Why no commit message came back; `detail` is the toast's mono line.
public enum CommitMessageError: Error, Equatable {
case notFound
case timedOut
/// The CLI could not start or exited non-zero; the first stderr line, else the exit code.
case failed(String)
/// The CLI answered with nothing usable.
case empty
public var detail: String {
switch self {
case .notFound: "claude not found"
case .timedOut: "timed out"
case let .failed(reason): reason
case .empty: "claude returned no message"
}
}
}
/// Writes a commit message for a prompt built by `CommitMessagePrompt`.
public protocol CommitMessageGenerating: Sendable {
/// The cleaned one-line message; throws `CommitMessageError`, or `CancellationError` when the caller went away.
func generate(prompt: String) async throws -> String
}
/// Runs the Claude CLI in print mode, with no tools, in the project root.
public struct ClaudeCommitMessageService: CommitMessageGenerating {
public let root: URL
private let runner: ProcessRunning
private let locator: ExecutableLocator
private let timeout: TimeInterval
/// No `--model`: the CLI's own default model writes the message.
public static let arguments = [
"-p", "--output-format", "text", "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands",
"--tools", "",
]
public init(root: URL, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .agent, timeout: TimeInterval = 90) {
self.root = root
self.runner = runner
self.locator = locator
self.timeout = timeout
}
/// The found binary's folder goes first on the child's PATH, so the CLI finds its own helpers.
public func generate(prompt: String) async throws -> String {
guard let binary = locator.locate("claude") else { throw CommitMessageError.notFound }
var environment = ProcessInfo.processInfo.environment
let folder = binary.deletingLastPathComponent().path
environment["PATH"] = [folder, environment["PATH"]].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ":")
let runner = self.runner, root = self.root, timeout = self.timeout
let outcome = try await withThrowingTaskGroup(of: ProcessResult?.self) { group -> ProcessResult? in
group.addTask {
do {
return try await runner.run(binary.path, arguments: Self.arguments, in: root, environment: environment, input: prompt)
} catch ProcessRunnerError.executableNotFound {
throw CommitMessageError.notFound
} catch let ProcessRunnerError.launchFailed(reason) {
throw CommitMessageError.failed(reason)
}
}
group.addTask {
try await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000))
return nil
}
defer { group.cancelAll() }
return try await group.next() ?? nil
}
guard let result = outcome else { throw CommitMessageError.timedOut }
guard result.succeeded else {
throw CommitMessageError.failed(Self.reason(stderr: result.stderr) ?? "claude exited with code \(result.exitCode)")
}
guard let message = CommitMessagePrompt.clean(result.stdout) else { throw CommitMessageError.empty }
return message
}
/// The first stderr line; the CLI prints notices such as a sign-in expiry as "Warning: …" before the real error.
static func reason(stderr: String) -> String? {
let lines = stderr.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
return lines.first { !$0.hasPrefix("Warning:") } ?? lines.first
}
}
@@ -112,6 +112,21 @@ public actor GitService: GitServicing {
return "\(name) <\(email)>"
}
public func recentCommits() async -> [GitCommitSummary] {
guard let result = try? await Self.run(GitCommitLogParsing.arguments, root: root, runner: runner), result.succeeded else {
return []
}
return GitCommitLogParsing.commits(result.stdout)
}
/// No external diff driver, so the patch is git's own text whatever the user configured.
public func stagedDiff() async -> StagedDiff? {
async let stat = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff", "--stat"], root: root, runner: runner)
async let patch = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff"], root: root, runner: runner)
guard let stat = await stat, stat.succeeded, let patch = await patch, patch.succeeded else { return nil }
return StagedDiff(stat: stat.stdout, patch: patch.stdout)
}
private func configValue(_ key: String) async -> String? {
guard let result = try? await Self.run(["config", "--get", key], root: root, runner: runner), result.succeeded else { return nil }
let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -31,6 +31,10 @@ public protocol GitServicing: Sendable {
func branches() async -> GitBranchList
/// `user.name <user.email>` from git config, nil when unset.
func author() async -> String?
/// The last 30 commits of HEAD, newest first; empty without commits or outside a repository.
func recentCommits() async -> [GitCommitSummary]
/// `git diff --cached` as stat and patch; nil when git fails, e.g. outside a repository.
func stagedDiff() async -> StagedDiff?
}
extension GitServicing {
@@ -20,6 +20,16 @@ public struct ExecutableLocator: Sendable {
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
}
/// `standard` plus the folders the Claude CLI installs itself into, which a GUI app's PATH never holds.
public static var agent: ExecutableLocator {
let home = FileManager.default.homeDirectoryForCurrentUser.path
var locator = standard
for dir in ["\(home)/.local/bin", "\(home)/.claude/local"] where !locator.directories.contains(dir) {
locator.directories.append(dir)
}
return locator
}
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
public func locate(_ name: String) -> URL? {
let fm = FileManager.default
@@ -25,12 +25,21 @@ public protocol ProcessRunning: Sendable {
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
/// Like `run`, with `input` written to the child's stdin, which is then closed.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
}
extension ProcessRunning {
/// Refuses, so a runner that cannot feed stdin never runs a child that would wait on it.
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult {
throw ProcessRunnerError.launchFailed("stdin is not supported by \(type(of: self))")
}
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
@@ -53,18 +62,23 @@ public struct ProcessRunner: ProcessRunning {
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: nil)
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: Data(input.utf8), onLine: nil)
}
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: onLine)
}
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
input: Data?, onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, input: input, onLine: onLine)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
job.start(continuation)
@@ -118,12 +132,14 @@ private final class Job: @unchecked Sendable {
private var cancelled = false
private var continuation: CheckedContinuation<ProcessResult, Error>?
private let onLine: (@Sendable (String, Bool) -> Void)?
private let input: Data?
/// Keeps `onLine` to one call at a time, though both pipes feed it.
private let emitLock = NSLock()
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?, input: Data?,
onLine: (@Sendable (String, Bool) -> Void)?) {
self.onLine = onLine
self.input = input
process.executableURL = url
process.arguments = arguments
if let directory { process.currentDirectoryURL = directory }
@@ -136,6 +152,8 @@ private final class Job: @unchecked Sendable {
let err = Pipe()
process.standardOutput = out
process.standardError = err
let stdin = input.map { _ in Pipe() }
if let stdin { process.standardInput = stdin }
let group = DispatchGroup()
var outData = Data()
@@ -159,6 +177,10 @@ private final class Job: @unchecked Sendable {
self.continuation = continuation
lock.unlock()
if let stdin, let input {
DispatchQueue.global().async { Self.write(input, to: stdin.fileHandleForWriting) }
}
group.enter()
DispatchQueue.global().async { [self] in
outData = drain(out.fileHandleForReading, isError: false)
@@ -178,6 +200,14 @@ private final class Job: @unchecked Sendable {
}
}
/// Writes on its own thread, since a child that stops reading would block it. A child that exits
/// early makes the write fail instead of raising SIGPIPE, which would end the app.
private static func write(_ data: Data, to handle: FileHandle) {
_ = fcntl(handle.fileDescriptor, F_SETNOSIGPIPE, 1)
try? handle.write(contentsOf: data)
try? handle.close()
}
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
private func resume(with result: Result<ProcessResult, Error>) {
lock.lock()
@@ -43,6 +43,7 @@ public struct ContextMenuHeader: View {
/// One 30pt menu item. Highlighted: `raised` fill, 2pt amber left rule, text-1 500 label, amber icon.
/// A tinted icon keeps its tint when highlighted; destructive items stay amber-deep in every state.
/// Disabled is 40% opacity and the arrow; it still takes hover, so a tooltip on it can show.
public struct ContextMenuRow: View {
var label: String
var systemImage: String?
@@ -51,9 +52,10 @@ public struct ContextMenuRow: View {
var isHighlighted: Bool
var isDestructive: Bool
var isEmphasized: Bool
var isDisabled: Bool
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
isHighlighted: Bool, isDestructive: Bool = false, isEmphasized: Bool = false) {
isHighlighted: Bool, isDestructive: Bool = false, isEmphasized: Bool = false, isDisabled: Bool = false) {
self.label = label
self.systemImage = systemImage
self.iconTint = iconTint
@@ -61,6 +63,7 @@ public struct ContextMenuRow: View {
self.isHighlighted = isHighlighted
self.isDestructive = isDestructive
self.isEmphasized = isEmphasized
self.isDisabled = isDisabled
}
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
@@ -93,8 +96,9 @@ public struct ContextMenuRow: View {
.overlay(alignment: .leading) {
Rectangle().fill(isHighlighted ? Palette.amber : .clear).frame(width: Metrics.accentRule)
}
.opacity(isDisabled ? 0.4 : 1)
.contentShape(Rectangle())
.pointerHand()
.pointerHand(!isDisabled)
}
private var labelRole: TypeRole {
@@ -216,6 +216,10 @@ private struct DiffContextMenu: View {
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { choose(action) }
case let .disabled(action, label, _):
ContextMenuRow(label, systemImage: ContextMenuOverlay.symbol(for: action),
iconTint: ContextMenuOverlay.tint(for: action).color,
isHighlighted: false, isDisabled: true)
}
}
}
+63 -5
View File
@@ -1,7 +1,8 @@
import HelderCore
import SwiftUI
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy.
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy,
/// with the tail block under it while a `.log` file is tailed.
public struct ExplorerColumn: View {
let model: WorkspaceModel
@State private var columnFrame = CGRect.zero
@@ -15,10 +16,18 @@ public struct ExplorerColumn: View {
public var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
if let store = model.explorer {
tree(store)
} else {
Spacer()
GeometryReader { proxy in
VStack(spacing: 0) {
if let store = model.explorer {
tree(store)
} else {
Spacer()
}
if let path = model.terminal.tailedPath {
TailBlock(model: model, path: path)
.frame(height: proxy.size.height * Self.tailFraction)
}
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -27,6 +36,8 @@ public struct ExplorerColumn: View {
.simultaneousGesture(TapGesture().onEnded { model.pointerFocused(.explorer) })
}
private static let tailFraction = 0.4
private var isActive: Bool { model.layout.activePanel == .explorer }
private var showHidden: Bool { model.layout.showHidden }
@@ -107,6 +118,53 @@ public struct ExplorerColumn: View {
}
}
/// `tail -f` on one log file: a header with the file name and a close button over a live terminal.
private struct TailBlock: View {
let model: WorkspaceModel
let path: String
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 8) {
Text("Tail").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer(minLength: 8)
Text(PathUtils.basename(path))
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
.help(path)
CloseTailButton { model.perform(.closeTail) }
}
.padding(.leading, 12)
.padding(.trailing, 8)
.frame(height: Metrics.panelHeader)
.hairline(.top)
.zIndex(1)
TerminalPane(kind: .tail, store: model.terminal, scale: model.layout.textScale)
.id(model.terminal.tailGeneration)
}
}
}
private struct CloseTailButton: View {
let action: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: action) {
GitIconView(icon: .x, size: 14)
.foregroundStyle(isHovered ? Palette.text1 : Palette.text4)
.padding(4)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($isHovered)
.tip("Stop tailing", edge: .trailing)
}
}
/// One tree row: indent, chevron, folder glyph or type badge, name, change letter.
private struct TreeRowView: View {
let row: TreeRow
@@ -3,6 +3,7 @@ import HelderCore
import SwiftUI
/// Local and origin branches; a click switches, but only while the working tree is clean.
/// A right click offers to merge the branch into the current one.
struct GitBranchesPanel: View {
let model: WorkspaceModel
let store: SourceControlStore
@@ -60,7 +61,8 @@ struct GitBranchesPanel: View {
name: name, remote: remote, current: current, locked: !current && store.isDirty,
meta: current ? "current" : (tracked ? "tracked" : ""),
action: canSwitch ? (remote && !tracked ? "checkout →" : "switch →") : "",
clickable: !current && !isCurrentUpstream
clickable: !current && !isCurrentUpstream,
menu: .branch(name: name, remote: remote, current: store.state.branch, isDirty: store.isDirty)
)
}
}
@@ -74,6 +76,7 @@ private struct BranchItem {
let meta: String
let action: String
let clickable: Bool
let menu: ContextTarget
}
private struct BranchRow: View {
@@ -112,6 +115,9 @@ private struct BranchRow: View {
model.perform(.switchBranch(item.name, remote: item.remote))
}
.pointerHand(item.clickable && !item.locked)
.overlay(RightClickArea { point in
model.perform(.showContextMenu(item.menu, anchor: point))
})
.tracksHover($isHovered)
.modifier(LockedTip(isLocked: item.locked))
}
@@ -131,12 +137,12 @@ private struct LockedTip: ViewModifier {
/// Puts the enclosing scroll view's scrollers over the content, so rows keep their 16px right padding.
/// A legacy scroller would take its width from the rows whenever the list overflows.
private struct OverlayScrollers: NSViewRepresentable {
struct OverlayScrollers: NSViewRepresentable {
func makeNSView(context: Context) -> OverlayScrollersProbe { OverlayScrollersProbe() }
func updateNSView(_ view: OverlayScrollersProbe, context: Context) { view.apply() }
}
private final class OverlayScrollersProbe: NSView {
final class OverlayScrollersProbe: NSView {
private var observer: NSObjectProtocol?
override func viewDidMoveToWindow() {
+78 -41
View File
@@ -2,7 +2,7 @@ import AppKit
import HelderCore
import SwiftUI
/// The message field over the author, the ⌘↵ hint and the Commit split button.
/// The message field over Gen. Commit Message, the author, the ⌘↵ hint and the three commit buttons.
struct GitCommitBlock: View {
let model: WorkspaceModel
let store: SourceControlStore
@@ -22,12 +22,13 @@ struct GitCommitBlock: View {
}
.animation(Metrics.colorTransition, value: isFocused)
HStack(spacing: 16) {
GenerateMessageButton(model: model, store: store)
if let author = store.author {
Text(author).typeRole(Typography.path).foregroundStyle(Palette.textMuted).lineLimit(1)
}
Text("⌘↵ commits").typeRole(Typography.path).foregroundStyle(Palette.text4).fixedSize()
Spacer(minLength: 0)
CommitSplitButton(model: model, store: store)
CommitButtons(model: model, store: store)
}
.padding(.leading, 16)
.padding(.trailing, 14)
@@ -43,57 +44,93 @@ struct GitCommitBlock: View {
}
}
/// `Commit N files` plus a caret that opens Commit / Commit and push. Amber only when git would accept it,
/// but both parts always run, so git's own refusal shows in the console.
private struct CommitSplitButton: View {
/// `Gen. Commit Message`: the Claude CLI writes the message for the staged changes. Dims while nothing is staged
/// and while a message is being written.
private struct GenerateMessageButton: View {
let model: WorkspaceModel
let store: SourceControlStore
@State private var mainHovered = false
@State private var caretHovered = false
@State private var caretFrame = CGRect.zero
@State private var hovered = false
var body: some View {
let ready = store.canCommitNow
let count = store.stagedPathCount
HStack(spacing: 0) {
Button { model.perform(.commit) } label: {
Text(count > 0 ? "Commit \(count) file\(count == 1 ? "" : "s")" : "Nothing staged")
let color = hovered ? Palette.text1 : Palette.text3
Button { model.perform(.generateCommitMessage) } label: {
HStack(spacing: 7) {
SparkGlyph()
.stroke(color, style: StrokeStyle(lineWidth: 1.1 * 12 / 16, lineJoin: .round))
.frame(width: 12, height: 12)
Text(store.isGeneratingMessage ? "Generating…" : "Gen. Commit Message")
.typeRole(Typography.gitCommitButton)
.padding(.horizontal, 18)
.frame(minWidth: GitMetrics.commitButtonMinWidth)
.frame(height: GitMetrics.commitButton)
.background(fill(ready: ready, hovered: mainHovered))
.contentShape(Rectangle())
.foregroundStyle(color)
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($mainHovered)
Button(action: openMenu) {
GitIconView(icon: .chevronDown, size: 14)
.frame(width: GitMetrics.commitButton, height: GitMetrics.commitButton)
.background(fill(ready: ready, hovered: caretHovered))
.overlay(alignment: .leading) { Rectangle().fill(Palette.editor).frame(width: Metrics.hairline) }
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($caretHovered)
.background(GlobalFrameReader(frame: $caretFrame))
.padding(.horizontal, 12)
.frame(height: GitMetrics.commitButton)
.background(hovered ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($hovered)
.disabledLook(!store.canGenerateMessage)
.fixedSize()
}
}
/// `Add, Stage & Commit` and `Commit N files` beside the primary `Commit and push`. The last two dim while nothing is staged;
/// with files staged they always run, so git's refusal of an empty message shows in the console.
private struct CommitButtons: View {
let model: WorkspaceModel
let store: SourceControlStore
@State private var stageAllHovered = false
@State private var commitHovered = false
@State private var pushHovered = false
var body: some View {
let count = store.stagedPathCount
HStack(spacing: 8) {
secondaryButton("Add, Stage & Commit", command: .stageAllAndCommit, hovered: $stageAllHovered)
.disabledLook(!store.canStageAllAndCommit)
HStack(spacing: 8) {
secondaryButton(count > 0 ? "Commit \(count) file\(count == 1 ? "" : "s")" : "Nothing staged",
command: .commit, hovered: $commitHovered)
Button { model.perform(.commitAndPush) } label: {
Text("Commit and push")
.typeRole(Typography.gitCommitButton)
.foregroundStyle(store.canCommitNow ? Palette.badgeText : Palette.textMuted)
.padding(.horizontal, 18)
.frame(height: GitMetrics.commitButton)
.background(pushFill, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($pushHovered)
}
.disabledLook(count == 0)
}
.foregroundStyle(ready ? Palette.badgeText : Palette.textMuted)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.fixedSize()
}
private func fill(ready: Bool, hovered: Bool) -> Color {
if ready { return hovered ? Palette.amberDeep : Palette.amber }
return hovered ? Palette.commitIdleHover : Palette.raised
private func secondaryButton(_ title: String, command: Command, hovered: Binding<Bool>) -> some View {
Button { model.perform(command) } label: {
Text(title)
.typeRole(Typography.gitCommitButton)
.foregroundStyle(hovered.wrappedValue ? Palette.text1 : Palette.text3)
.padding(.horizontal, 18)
.frame(minWidth: GitMetrics.commitButtonMinWidth)
.frame(height: GitMetrics.commitButton)
.background(hovered.wrappedValue ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover(hovered)
}
/// The menu hangs under the caret, right-aligned to it.
private func openMenu() {
let anchor = CGPoint(x: caretFrame.maxX - Metrics.contextMenuWidth, y: caretFrame.maxY + 4)
model.perform(.showContextMenu(.commitMenu, anchor: anchor))
private var pushFill: Color {
if store.canCommitNow { return pushHovered ? Palette.amberDeep : Palette.amber }
return pushHovered ? Palette.commitIdleHover : Palette.raised
}
}
@@ -0,0 +1,83 @@
import HelderCore
import SwiftUI
/// The bottom strip's right end on a wide window: the last commits of the current branch, read-only.
struct GitCommitsPanel: View {
let store: SourceControlStore
var body: some View {
VStack(spacing: 0) {
header
if !store.state.isRepository {
placeholder("— no repository")
} else if store.recentCommits.isEmpty {
placeholder("no commits yet")
} else {
ScrollView {
TimelineView(.periodic(from: .now, by: 30)) { context in
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(store.recentCommits, id: \.hash) { commit in
CommitRow(commit: commit, now: context.date)
}
}
.padding(.bottom, 12)
}
.background(OverlayScrollers())
}
.scrollIndicators(.automatic)
}
Spacer(minLength: 0)
}
.clipped()
}
private var header: some View {
HStack(spacing: 12) {
Text("[ commits ]").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
Spacer(minLength: 0)
if store.state.isRepository {
Text(store.state.branch)
.typeRole(Typography.path)
.foregroundStyle(Palette.textMuted)
.lineLimit(1)
.truncationMode(.middle)
}
}
.padding(.horizontal, 16)
.frame(height: GitMetrics.stripHeader)
}
private func placeholder(_ text: String) -> some View {
Text(text)
.typeRole(Typography.path)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 16)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
private struct CommitRow: View {
let commit: GitCommitSummary
let now: Date
var body: some View {
HStack(spacing: 10) {
Text(commit.hash).typeRole(Typography.gitStats).foregroundStyle(Palette.amber).fixedSize()
Text(commit.subject)
.typeRole(Typography.path)
.foregroundStyle(Palette.text2)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 0) {
Text(commit.author).lineLimit(1).truncationMode(.tail).frame(maxWidth: 140, alignment: .trailing)
Text(" · \(RelativeTime.text(commit.date, now: now))").fixedSize()
}
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.layoutPriority(1)
}
.padding(.horizontal, 16)
.frame(height: GitMetrics.branchRow)
}
}
+5 -2
View File
@@ -1,7 +1,7 @@
import HelderCore
import SwiftUI
/// `[ git ]`, the branch and its place against origin, then Pull, Push and Close.
/// `[ git ]`, the branch and its place against origin, then Pull, Push, Clean up and Close.
struct GitTopBar: View {
let model: WorkspaceModel
let store: SourceControlStore
@@ -21,9 +21,12 @@ struct GitTopBar: View {
trailing: state.behind > 0 ? "↓\(state.behind)" : nil) { model.perform(.pull) }
GitBarButton(icon: .arrowUpFromLine, label: store.busy == .push ? "Pushing…" : "Push",
trailing: state.ahead > 0 ? "↑\(state.ahead)" : nil) { model.perform(.push) }
GitBarButton(icon: .eraser, label: "Clean up", trailing: nil) { model.perform(.context(.gitCleanUp)) }
.disabledLook(!store.canCleanUp)
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘G") { model.perform(.closeGitView) }
}
.padding(.horizontal, 14)
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
.padding(.trailing, 14)
.frame(height: GitMetrics.topBar)
.background(Palette.panel)
.hairline(.bottom)
+36 -7
View File
@@ -25,18 +25,27 @@ struct GitView: View {
}
}
/// The console left, the branches right, 230pt tall.
/// The console left, the branches right, 230pt tall; a wide window adds the commit list after them.
private struct GitBottomStrip: View {
let model: WorkspaceModel
let store: SourceControlStore
var body: some View {
HStack(spacing: 0) {
GitConsolePanel(model: model, store: store)
.frame(maxWidth: .infinity)
Hairline(.vertical)
GitBranchesPanel(model: model, store: store)
.frame(maxWidth: .infinity)
GeometryReader { proxy in
let layout = GitStripLayout(width: proxy.size.width)
HStack(spacing: 0) {
GitConsolePanel(model: model, store: store)
.frame(width: layout.console)
Hairline(.vertical)
GitBranchesPanel(model: model, store: store)
.frame(width: layout.branches)
if let commits = layout.commits {
Hairline(.vertical)
GitCommitsPanel(store: store)
.frame(width: commits)
}
Spacer(minLength: 0)
}
}
.frame(height: GitMetrics.bottomStrip)
.background(Palette.panel)
@@ -44,6 +53,23 @@ private struct GitBottomStrip: View {
}
}
/// The widths of the bottom strip's panels for one strip width.
struct GitStripLayout: Equatable {
var console: CGFloat
var branches: CGFloat
/// Nil while the room left after the two capped panels is under `GitMetrics.commitsMinWidth`.
var commits: CGFloat?
init(width: CGFloat) {
let hairline = Metrics.hairline
let share = max(0, (width - hairline) / 2).rounded(.down)
console = min(GitMetrics.consoleMaxWidth, share)
branches = min(GitMetrics.branchesMaxWidth, share)
let left = width - console - branches - 2 * hairline
commits = left >= GitMetrics.commitsMinWidth ? left : nil
}
}
/// The Git view's fixed sizes, from the design handoff.
enum GitMetrics {
static let topBar: CGFloat = 44
@@ -68,6 +94,9 @@ enum GitMetrics {
static let diffGutter: CGFloat = 52
static let diffGap: CGFloat = 28
static let bottomStrip: CGFloat = 230
static let consoleMaxWidth: CGFloat = 820
static let branchesMaxWidth: CGFloat = 820
static let commitsMinWidth: CGFloat = 260
static let stripHeader: CGFloat = 32
static let branchRow: CGFloat = 28
}
@@ -4,18 +4,19 @@ import SwiftUI
enum MenuCursor {
static func first(in entries: [ContextMenuEntry]) -> Int? {
entries.firstIndex { $0 != .separator }
entries.firstIndex(where: \.isSelectable)
}
/// The next selectable entry in `step` direction, wrapping around and skipping separators.
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int {
guard !entries.isEmpty else { return current }
/// The next selectable entry in `step` direction, wrapping around and skipping separators and disabled
/// entries; nil when the menu has none.
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int? {
guard !entries.isEmpty else { return nil }
var index = current
for _ in entries.indices {
index = (index + step + entries.count) % entries.count
if entries[index] != .separator { return index }
if entries[index].isSelectable { return index }
}
return current
return nil
}
}
@@ -82,6 +83,10 @@ struct ContextMenuOverlay: View {
isEmphasized: action.isEmphasized)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { onPerform(action) }
case let .disabled(action, label, hint):
ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color,
isHighlighted: false, isDisabled: true)
.tip(hint)
}
}
}
@@ -110,11 +115,11 @@ struct ContextMenuOverlay: View {
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
switch action {
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText, .readAloudTerminalSelection,
.plak, .plakTerminalSelection, .openFile, .commit: .plain
.plak, .plakTerminalSelection, .openFile, .mergeBranch, .tailLog: .plain
case .newFile, .newFolder: .add
case .copyFileName, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .showDiff, .rename: .rename
case .gitDiscard, .delete: .danger
case .gitDiscard, .gitCleanUp, .delete: .danger
}
}
@@ -127,16 +132,17 @@ struct ContextMenuOverlay: View {
case .plak, .plakTerminalSelection: "note.text.badge.plus"
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
case .openFile: "doc.text"
case .commit(andPush: false): "checkmark"
case .commit(andPush: true): "arrow.up.to.line"
case .pasteIntoTerminal: "doc.on.clipboard"
case .newFile: "doc.badge.plus"
case .newFolder: "folder.badge.plus"
case .showDiff: "arrow.left.arrow.right"
case .gitDiscard: "arrow.uturn.backward"
case .gitCleanUp: "eraser"
case .rename: "pencil"
case .revealInFinder: "folder"
case .delete: "trash"
case .mergeBranch: "arrow.triangle.merge"
case .tailLog: "terminal"
}
}
}
@@ -33,7 +33,8 @@ struct SchemaTopBar: View {
.disabledLook(!store.hasCommand)
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘D") { model.perform(.closeSchemaView) }
}
.padding(.horizontal, 14)
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
.padding(.trailing, 14)
.frame(height: SchemaViewMetrics.topBar)
.background(Palette.panel)
.hairline(.bottom)
+11
View File
@@ -114,10 +114,21 @@ public enum Command: Equatable, Sendable {
/// ⌘A outside a text field: the whole open file in its pane.
case selectAllInFile
// MARK: Explorer tail
/// The tail block's close button: ends `tail -f` and removes the block.
case closeTail
// MARK: Git
/// ⌘↵ and the Commit button: always runs git, so its refusal shows in the console.
case commit
/// The Commit and push button: pushes only after a successful commit.
case commitAndPush
/// The Add, Stage & Commit button: stages every change, then commits without a push.
case stageAllAndCommit
/// The Gen. Commit Message button: the Claude CLI writes a message for the staged changes.
case generateCommitMessage
/// ⌘P
case push
case pull
+164 -10
View File
@@ -42,7 +42,11 @@ public final class SourceControlStore {
/// `user.name <user.email>`, read when the view opens.
public private(set) var author: String?
public private(set) var branches = GitBranchList.empty
/// The last 30 commits of HEAD, read with the branches.
public private(set) var recentCommits: [GitCommitSummary] = []
public private(set) var busy: GitBusy?
/// True while the Claude CLI writes a commit message for the staged changes.
public private(set) var isGeneratingMessage = false
public private(set) var lines: [GitConsoleEntry] = []
public var consoleInput = ""
public private(set) var history: [String] = []
@@ -58,10 +62,11 @@ public final class SourceControlStore {
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
/// Asks for the keyboard in the message field, after git refused an empty message.
/// Asks for the keyboard in the message field, after an empty message was refused.
@ObservationIgnored public var focusMessage: () -> Void = {}
@ObservationIgnored private let git: GitServicing
@ObservationIgnored private let commitMessages: CommitMessageGenerating?
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
@ObservationIgnored private var refreshGeneration = 0
@ObservationIgnored private var pollTask: Task<Void, Never>?
@@ -74,9 +79,12 @@ public final class SourceControlStore {
/// The status error already in the console, so a poll that keeps failing logs it once.
@ObservationIgnored private var loggedStatusError: String?
/// `derive` runs off the main actor, since it diffs every changed file.
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
/// `derive` runs off the main actor, since it diffs every changed file. Without `commitMessages` the
/// generate button stays off.
public init(git: GitServicing, commitMessages: CommitMessageGenerating? = nil,
derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
self.git = git
self.commitMessages = commitMessages
self.derive = derive
}
@@ -91,19 +99,37 @@ public final class SourceControlStore {
return out
}
/// Any change, staged or not; it locks branch switching.
/// Any change, staged or not; it locks branch switching and merging.
public var isDirty: Bool { !state.changes.isEmpty }
/// Distinct changed paths, a file with two rows once.
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
/// Distinct paths with an unstaged row: what Clean up throws away.
public var cleanUpPathCount: Int { Set(state.changes.filter { !$0.staged }.map(\.path)).count }
/// Off while a push or pull runs, and during a conflict, which only a resolution may touch.
public var canCleanUp: Bool {
busy == nil && cleanUpPathCount > 0 && !state.changes.contains { $0.status == .unmerged }
}
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
/// Off without changes, while a push or pull runs, and during a conflict: staging a conflicted file marks it resolved.
public var canStageAllAndCommit: Bool {
busy == nil && isDirty && !state.changes.contains { $0.status == .unmerged }
}
/// The ready look of the Commit button; the button itself always runs git.
public var canCommitNow: Bool {
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
}
/// The Gen. Commit Message button's on state.
public var canGenerateMessage: Bool {
commitMessages != nil && stagedPathCount > 0 && !isGeneratingMessage
}
public var syncLabel: String {
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
}
@@ -144,6 +170,31 @@ public final class SourceControlStore {
commitMessage = SourceControlText.normalizeCommitMessage(value)
}
public static let generateFailedTitle = "Couldn't generate a commit message"
/// Replaces the draft with the message the Claude CLI writes for the staged diff, then focuses the field.
/// Ignored while one is being written or nothing is staged.
public func generateCommitMessage() async {
guard let commitMessages, canGenerateMessage else { return }
isGeneratingMessage = true
defer { isGeneratingMessage = false }
guard let staged = await git.stagedDiff(), !staged.isEmpty else {
notify(Self.generateFailedTitle, "no staged diff")
return
}
do {
let message = try await commitMessages.generate(prompt: CommitMessagePrompt.make(staged))
setCommitMessage(message)
focusMessage()
} catch is CancellationError {
return
} catch let error as CommitMessageError {
notify(Self.generateFailedTitle, error.detail)
} catch {
notify(Self.generateFailedTitle, "\(error)")
}
}
// MARK: Reading git
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
@@ -183,11 +234,16 @@ public final class SourceControlStore {
branches = await git.branches()
}
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
public func reloadRecentCommits() async {
recentCommits = await git.recentCommits()
}
/// The Git view opened: reads the author, the branches and the recent commits, then fetches origin so ahead/behind are honest.
/// Without an origin there is nothing to fetch, so the console stays quiet.
public func viewOpened() async {
author = await git.author()
await reloadBranches()
await reloadRecentCommits()
await loadIfNeeded()
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
isFetching = true
@@ -199,10 +255,12 @@ public final class SourceControlStore {
// MARK: Staging
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
public func stage(_ paths: [String]) async {
guard !paths.isEmpty else { return }
await run(["add", "--"] + paths)
@discardableResult
public func stage(_ paths: [String]) async -> Bool {
guard !paths.isEmpty else { return true }
let result = await run(["add", "--"] + paths)
await afterCommand()
return result.succeeded
}
/// A staged rename takes its source along, or the old path stays staged as deleted.
@@ -232,13 +290,71 @@ public final class SourceControlStore {
await afterCommand()
}
/// Reverts unstaged edits to the index and removes untracked files and folders; staged content and ignored files stay.
public func cleanUp() async {
guard canCleanUp else { return }
let unstaged = state.changes.filter { !$0.staged }
let count = cleanUpPathCount
var failure: (GitCommandResult, [String])?
if unstaged.contains(where: { $0.status != .added }) {
let arguments = ["restore", "--worktree", "--", "."]
let result = await run(arguments)
if !result.succeeded { failure = (result, arguments) }
}
if unstaged.contains(where: { $0.status == .added }) {
// No -x: ignored files such as .env, vendor/ and node_modules/ must survive.
let arguments = ["clean", "-fd"]
let result = await run(arguments)
if !result.succeeded && failure == nil { failure = (result, arguments) }
}
await afterCommand()
if case let (result, arguments)? = failure {
notify("Clean up failed", Self.failureDetail(of: result, arguments: arguments))
} else {
notify("Cleaned up \(count) file\(count == 1 ? "" : "s")", nil)
}
}
private func unstagedStatus(_ path: String) -> GitStatus? {
state.changes.first { !$0.staged && $0.path == path }?.status
}
/// The confirm dialog a discard needs, or nil to run it straight away; restoring deleted files never asks.
/// The confirm dialog a discard, clean up or merge needs, or nil to run it straight away; restoring deleted files never asks.
/// A merge that `mergeBranch` refuses (dirty tree, current branch) asks nothing, so the refusal toast shows at once.
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
guard case let .gitDiscard(paths) = action, config.confirmDiscard, !paths.isEmpty else { return nil }
switch action {
case let .gitDiscard(paths): discardConfirmation(paths, action: action)
case let .mergeBranch(name): mergeConfirmation(name, action: action)
case .gitCleanUp: cleanUpConfirmation()
default: nil
}
}
/// Always asks, whatever `confirmDiscard` says; nil only when `cleanUp` would refuse anyway.
private func cleanUpConfirmation() -> ConfirmRequest? {
guard canCleanUp else { return nil }
let count = cleanUpPathCount
return ConfirmRequest(
title: "Clean up \(count) file\(count == 1 ? "" : "s")?",
body: "New files are removed from disk and unstaged changes are reverted. Staged changes stay. This cannot be undone.",
confirmLabel: "Clean up",
action: .gitCleanUp
)
}
private func mergeConfirmation(_ name: String, action: ContextAction) -> ConfirmRequest? {
let current = state.branch
guard !isDirty, name != current else { return nil }
return ConfirmRequest(
title: "Merge \(name) into \(current)?",
body: "Git merges the commits of \(name) into \(current). A conflict stops the merge for you to resolve.",
confirmLabel: "Merge",
action: action
)
}
private func discardConfirmation(_ paths: [String], action: ContextAction) -> ConfirmRequest? {
guard config.confirmDiscard, !paths.isEmpty else { return nil }
let statuses = paths.map(unstagedStatus)
let hasNew = statuses.contains(.added)
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
@@ -272,6 +388,18 @@ public final class SourceControlStore {
if andPush { await push() }
}
/// Stages every unstaged path, new files included, then commits without a push.
/// An empty message stages nothing, so a refusal never leaves the files half done.
public func stageAllAndCommit() async {
guard canStageAllAndCommit else { return }
guard !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty else {
focusMessage()
return
}
guard await stage(state.unstagedPaths) else { return }
await commit()
}
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
public func push() async {
guard busy == nil else { return }
@@ -337,6 +465,31 @@ public final class SourceControlStore {
return true
}
/// Runs `git merge --no-edit` into the current branch; refuses with a toast while the tree is dirty, without asking git.
@discardableResult
public func mergeBranch(_ name: String) async -> Bool {
if isDirty {
let count = changedPathCount
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you merge.", nil)
return false
}
let current = state.branch
guard name != current else { return false }
let arguments = ["merge", "--no-edit", name]
let result = await run(arguments)
await afterCommand()
guard result.succeeded else {
if state.changes.contains(where: { $0.status == .unmerged }) {
notify("Merge conflict — resolve, then commit", nil)
} else {
notify("Merge failed", Self.failureDetail(of: result, arguments: arguments))
}
return false
}
notify("Merged \(name) into \(current)", nil)
return true
}
// MARK: Console
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
@@ -404,6 +557,7 @@ public final class SourceControlStore {
private func afterCommand() async {
await refresh()
await reloadBranches()
await reloadRecentCommits()
}
private func log(_ text: String, _ kind: GitLineKind) {
+44 -4
View File
@@ -46,12 +46,18 @@ public final class TerminalStore {
public private(set) var isConfigured = false
public private(set) var agentExited = false
public private(set) var shellExited = false
public private(set) var tailExited = false
/// The file the Explorer's tail block follows; nil while no block is shown.
public private(set) var tailedPath: String?
/// Moves on every new tail, so the block builds a fresh pane and the old file's output never stays.
public private(set) var tailGeneration = 0
/// True while the agent's composer holds typed or pasted text, so the next paste starts on a new line.
public private(set) var agentComposerHasText = false
@ObservationIgnored public let projectRoot: String?
@ObservationIgnored public private(set) var agent: TerminalSessionHandle?
@ObservationIgnored public private(set) var shell: TerminalSessionHandle?
@ObservationIgnored public private(set) var tail: TerminalSessionHandle?
@ObservationIgnored private let environment: [String: String]
/// A right-click in a pane: its kind, whether it holds a selection, the click in window coordinates.
@ObservationIgnored public var contextMenuRequested: ((TerminalKind, Bool, CGPoint) -> Void)?
@@ -63,7 +69,10 @@ public final class TerminalStore {
/// Executable, arguments, environment and cwd for a pane.
public func launch(for kind: TerminalKind) -> TerminalLaunch {
TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
guard kind == .tail else {
return TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
}
return TerminalLaunch.tail(path: tailedPath ?? "", projectRoot: projectRoot, environment: environment)
}
/// argv[0] with a leading dash, which makes the shell a login shell: a Finder-launched app
@@ -76,6 +85,7 @@ public final class TerminalStore {
switch kind {
case .agent: agent
case .shell: shell
case .tail: tail
}
}
@@ -89,15 +99,37 @@ public final class TerminalStore {
case .shell:
shell = handle
if shellExited { shellExited = false }
case .tail:
tail = handle
if tailExited { tailExited = false }
}
}
/// Attaches a pane and spawns its process.
public func start(_ kind: TerminalKind, on handle: TerminalSessionHandle) {
if kind == .tail && tailedPath == nil { return }
attach(handle, as: kind)
let launch = launch(for: kind)
Log.info("pty", "spawn \(kind.rawValue): \(launch.executable) \(launch.arguments.joined(separator: " ")) in \(launch.workingDirectory)")
handle.start(launch, argv0: Self.loginArgv0(for: launch.executable))
let argv0 = kind == .tail ? (launch.executable as NSString).lastPathComponent : Self.loginArgv0(for: launch.executable)
handle.start(launch, argv0: argv0)
}
/// Shows the tail block on `path`; a running tail is killed first, and the block's new pane spawns the fresh one.
public func startTail(_ path: String) {
tail.map(Self.terminate)
tail = nil
tailExited = false
tailedPath = path
tailGeneration += 1
}
/// Kills the tail and removes its block.
public func closeTail() {
tail.map(Self.terminate)
tail = nil
tailExited = false
tailedPath = nil
}
/// Kills whatever runs in the pane and spawns it again with the current config.
@@ -112,6 +144,7 @@ public final class TerminalStore {
switch kind {
case .agent: agentExited = true
case .shell: shellExited = true
case .tail: tailExited = true
}
if let exitCode, exitCode != 0 {
Log.warn("pty", "\(kind.rawValue) exited unexpectedly with code \(exitCode)")
@@ -121,7 +154,11 @@ public final class TerminalStore {
}
public func hasExited(_ kind: TerminalKind) -> Bool {
kind == .agent ? agentExited : shellExited
switch kind {
case .agent: agentExited
case .shell: shellExited
case .tail: tailExited
}
}
/// Feed every keystroke the user sends to the agent: Enter empties the composer, printable text fills it.
@@ -157,16 +194,19 @@ public final class TerminalStore {
agent = nil
} else if shell === handle {
shell = nil
} else if tail === handle {
tail = nil
} else {
return
}
Self.terminate(handle)
}
/// Kills both processes; call it before the window closes or the store is replaced.
/// Kills every process, the tail included; call it before the window closes or the store is replaced.
public func terminateAll() {
agent.map(Self.terminate)
shell.map(Self.terminate)
closeTail()
agent = nil
shell = nil
}
@@ -14,11 +14,14 @@ extension WorkspaceModel {
}
}
/// A target without entries, such as the current branch, opens no menu.
func showContextMenu(_ target: ContextTarget, anchor: CGPoint) {
let entries = ContextActions.entries(for: target)
guard !entries.isEmpty else { return }
overlay.present(.contextMenu(ContextMenuRequest(
target: target,
header: ContextActions.header(for: target, projectName: name),
entries: ContextActions.entries(for: target),
entries: entries,
anchor: anchor
)))
}
@@ -78,8 +81,12 @@ extension WorkspaceModel {
case let .openFile(path):
closeGitView()
open(path)
case let .commit(andPush):
track { await sourceControl?.commit(andPush: andPush) }
case let .mergeBranch(name):
guard let sourceControl else { return }
track {
await sourceControl.mergeBranch(name)
self.scheduleRefresh([.tree, .openFiles])
}
case let .passOnFileName(name):
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
case let .bouwen(name):
@@ -92,6 +99,8 @@ extension WorkspaceModel {
readAloud.read(text)
case let .readAloudFile(path):
readAloudFile(path)
case let .tailLog(path):
terminal.startTail(path)
case let .readAloudTerminalSelection(kind):
let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text))
@@ -113,6 +122,12 @@ extension WorkspaceModel {
if let text = terminal.selection(kind) { app.system.copy(text) }
case let .pasteIntoTerminal(kind):
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
case .gitCleanUp:
guard let sourceControl else { return }
track {
await sourceControl.cleanUp()
self.scheduleRefresh([.tree, .openFiles])
}
case let .gitDiscard(paths):
track {
await sourceControl?.discard(paths)
@@ -52,7 +52,7 @@ extension WorkspaceModel {
rowFrames = [:]
let notify: (String, String?) -> Void = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
let sourceControl = SourceControlStore(git: services.git)
let sourceControl = SourceControlStore(git: services.git, commitMessages: services.commitMessages)
sourceControl.notify = notify
sourceControl.focusMessage = { [weak self] in self?.focusRequest = FocusRequest(.commitMessage) }
self.sourceControl = sourceControl
@@ -176,10 +176,20 @@ public final class WorkspaceModel {
case .cycleMode: editor?.togglePreview()
case let .passSelection(info): passSelection(info)
case .selectAllInFile: editor?.selectAll()
case .closeTail: terminal.closeTail()
case .commit:
guard let sourceControl else { return }
track { await sourceControl.commit() }
case .commitAndPush:
guard let sourceControl else { return }
track { await sourceControl.commit(andPush: true) }
case .stageAllAndCommit:
guard let sourceControl else { return }
track { await sourceControl.stageAllAndCommit() }
case .generateCommitMessage:
guard let sourceControl else { return }
track { await sourceControl.generateCommitMessage() }
case .push:
guard let sourceControl else { return }
track { await sourceControl.push() }
@@ -12,9 +12,12 @@ public struct WorkspaceServices {
public var recentFiles: RecentFilesStoring
/// The Schema view's dump reading and `helder:schema` runs.
public var schema: SchemaServicing
/// The Git view's Gen. Commit Message: the Claude CLI in print mode.
public var commitMessages: CommitMessageGenerating
public init(git: GitServicing, files: FileServicing, search: SearchServicing, symbols: SymbolServicing,
config: ConfigServicing, recentFiles: RecentFilesStoring, schema: SchemaServicing) {
config: ConfigServicing, recentFiles: RecentFilesStoring, schema: SchemaServicing,
commitMessages: CommitMessageGenerating) {
self.git = git
self.files = files
self.search = search
@@ -22,6 +25,7 @@ public struct WorkspaceServices {
self.config = config
self.recentFiles = recentFiles
self.schema = schema
self.commitMessages = commitMessages
}
public static func live(root: URL) -> WorkspaceServices {
@@ -34,7 +38,8 @@ public struct WorkspaceServices {
symbols: SymbolService(root: root, config: config),
config: config,
recentFiles: RecentFilesStore(root: root),
schema: SchemaService(root: root)
schema: SchemaService(root: root),
commitMessages: ClaudeCommitMessageService(root: root)
)
}
}