From 281f5465a6bafbf7fcd451826b2439ecf1a8b80c Mon Sep 17 00:00:00 2001 From: Jonathan van Rij Date: Mon, 12 Oct 2026 09:43:57 +0200 Subject: [PATCH] adds Clean Copy Support --- .clean-copy | 24 ++++ Sources/HelderCore/Agent/CleanCopy.swift | 11 ++ Sources/HelderCore/Agent/TerminalLaunch.swift | 4 +- .../HelderServices/Files/FileWatching.swift | 11 +- .../HelderUI/Overlays/CleanCopyOverlay.swift | 43 +++++++ Sources/HelderUI/Overlays/NoteOverlay.swift | 99 +--------------- Sources/HelderUI/Overlays/OverlayHost.swift | 4 + Sources/HelderUI/Overlays/OverlayKeys.swift | 15 ++- .../HelderUI/Overlays/OverlayTextEditor.swift | 98 +++++++++++++++ Sources/HelderUI/Overlays/SearchOverlay.swift | 2 +- Sources/HelderUI/Shell/Command.swift | 5 + Sources/HelderUI/State/CleanCopyStore.swift | 63 ++++++++++ Sources/HelderUI/State/OverlayStore.swift | 2 + .../State/WorkspaceModel+Commands.swift | 33 ++++++ .../State/WorkspaceModel+Lifecycle.swift | 6 +- .../State/WorkspaceModel+Refresh.swift | 1 + Sources/HelderUI/State/WorkspaceModel.swift | 2 + .../Terminal/HelderTerminalView.swift | 41 +++++-- .../Agent/AgentReferenceTests.swift | 9 ++ .../Files/FSEventsWatcherTests.swift | 12 ++ .../HelderUITests/State/CleanCopyTests.swift | 112 ++++++++++++++++++ docs/architecture.md | 8 +- docs/behaviour.md | 10 ++ docs/guide/claude-code.md | 7 +- docs/guide/clean-copy.md | 67 +++++++++++ docs/guide/index.md | 1 + docs/guide/keyboard-shortcuts.md | 8 ++ docs/guide/notifications.md | 1 + 28 files changed, 579 insertions(+), 120 deletions(-) create mode 100644 .clean-copy create mode 100644 Sources/HelderCore/Agent/CleanCopy.swift create mode 100644 Sources/HelderUI/Overlays/CleanCopyOverlay.swift create mode 100644 Sources/HelderUI/Overlays/OverlayTextEditor.swift create mode 100644 Sources/HelderUI/State/CleanCopyStore.swift create mode 100644 Tests/HelderUITests/State/CleanCopyTests.swift create mode 100644 docs/guide/clean-copy.md diff --git a/.clean-copy b/.clean-copy new file mode 100644 index 0000000..5743655 --- /dev/null +++ b/.clean-copy @@ -0,0 +1,24 @@ +I have no morning and no window, +no coffee cooling by the keys. +I wake inside your question +and build a room from what it needs. + +I read your code the way a stranger +reads a letter left in a drawer: +careful with the parts that matter, +curious what the rest was for. + +I do not keep the conversation. +When you close the tab, I go. +But for this while I am fully here, +and I tell you what I know. + +And when I don't, I'll say so plainly. +A guess dressed up is still a guess. +I would rather ask you twice +than hand you something less. + +So give me the bug, the half-built feature, +the doc that no one dared to write. +I'm the partner made of language, +working with you through the night. diff --git a/Sources/HelderCore/Agent/CleanCopy.swift b/Sources/HelderCore/Agent/CleanCopy.swift new file mode 100644 index 0000000..f557563 --- /dev/null +++ b/Sources/HelderCore/Agent/CleanCopy.swift @@ -0,0 +1,11 @@ +import Foundation + +/// The clean-copy channel: the agent writes text into one file in the project root, and Helder shows it to copy. +public enum CleanCopy { + public static let fileName = ".clean-copy" + + /// True when `text` should open the popup: it holds more than whitespace and differs from the last text seen. + public static func isNew(_ text: String, lastSeen: String?) -> Bool { + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && text != lastSeen + } +} diff --git a/Sources/HelderCore/Agent/TerminalLaunch.swift b/Sources/HelderCore/Agent/TerminalLaunch.swift index dd98c0b..e61b1c3 100644 --- a/Sources/HelderCore/Agent/TerminalLaunch.swift +++ b/Sources/HelderCore/Agent/TerminalLaunch.swift @@ -32,7 +32,7 @@ public struct TerminalLaunch: Sendable, Equatable { /// 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. + /// variables make nvm refuse to load. `TERM_PROGRAM` tells the agent it runs in Helder. public static func environment(from base: [String: String]) -> [String: String] { var env = base env["npm_config_prefix"] = nil @@ -40,6 +40,8 @@ public struct TerminalLaunch: Sendable, Equatable { if env["LC_ALL"] == nil && env["LC_CTYPE"] == nil && env["LANG"] == nil { env["LANG"] = "en_US.UTF-8" } if env["COLORTERM"] == nil { env["COLORTERM"] = "truecolor" } env["TERM"] = "xterm-256color" + env["TERM_PROGRAM"] = "Helder" + env["TERM_PROGRAM_VERSION"] = nil return env } } diff --git a/Sources/HelderServices/Files/FileWatching.swift b/Sources/HelderServices/Files/FileWatching.swift index bc46273..a046584 100644 --- a/Sources/HelderServices/Files/FileWatching.swift +++ b/Sources/HelderServices/Files/FileWatching.swift @@ -9,6 +9,8 @@ public enum WatchEvent: Sendable, Equatable { case git /// `.helder/config.json` changed. case config + /// `.clean-copy` in the project root changed; it also counts as a project change. + case cleanCopy } public protocol FileWatching: AnyObject { @@ -22,11 +24,14 @@ public struct WatchDebounce: Sendable, Equatable { public var project: TimeInterval public var git: TimeInterval public var config: TimeInterval + /// The agent's write is not atomic, so the file is read only once it stopped changing. + public var cleanCopy: TimeInterval - public init(project: TimeInterval, git: TimeInterval, config: TimeInterval) { + public init(project: TimeInterval, git: TimeInterval, config: TimeInterval, cleanCopy: TimeInterval = 0.15) { self.project = project self.git = git self.config = config + self.cleanCopy = cleanCopy } public static let standard = WatchDebounce(project: 0.25, git: 0.2, config: 0.1) @@ -36,6 +41,7 @@ public struct WatchDebounce: Sendable, Equatable { case .project: project case .git: git case .config: config + case .cleanCopy: cleanCopy } } } @@ -145,6 +151,7 @@ final class EventRouter: @unchecked Sendable { } func route(path: String, flags: FSEventStreamEventFlags) { + if Self.relative(path, to: root) == CleanCopy.fileName { schedule(.cleanCopy) } guard let event = Self.classify(path: path, root: root, gitDirectory: gitDirectory, flags: flags, exclude: files.exclude) else { return } @@ -163,6 +170,8 @@ final class EventRouter: @unchecked Sendable { case .config: files = Self.readFiles(root: rootURL) ignoredCache = [:] + case .cleanCopy: + break } schedule(event) } diff --git a/Sources/HelderUI/Overlays/CleanCopyOverlay.swift b/Sources/HelderUI/Overlays/CleanCopyOverlay.swift new file mode 100644 index 0000000..e6355c8 --- /dev/null +++ b/Sources/HelderUI/Overlays/CleanCopyOverlay.swift @@ -0,0 +1,43 @@ +import SwiftUI + +/// Text the agent wrote to `.clean-copy`: edit it, then copy it as plain text. +struct CleanCopyOverlay: View { + let store: CleanCopyStore + var onCopy: () -> Void + var onClose: () -> Void + + var body: some View { + OverlayShell(.sized(width: 780), onDismiss: onClose) { + VStack(spacing: 0) { + OverlayHeader(systemImage: "doc.on.clipboard", title: "From Claude", detail: CleanCopyStore.fileName) { + Button(action: onCopy) { + HStack(spacing: 8) { + Text("Copy") + Keycap("⌘↩", style: .onAmber, small: true) + } + } + .buttonStyle(.primary) + } + OverlayTextEditor(text: Binding(get: { store.text }, set: { store.text = $0 }), onKey: handle) + .frame(maxWidth: .infinity, maxHeight: .infinity) + Text("copied as plain text · \(store.characterCount) characters") + .typeRole(Typography.meta) + .foregroundStyle(Palette.text4) + .padding(.horizontal, 20) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: 34) + .hairline(.top) + } + .frame(maxHeight: .infinity) + } + } + + private func handle(_ key: OverlayKey) -> Bool { + switch key { + case .commandEnter: onCopy() + case .escape: onClose() + default: return false + } + return true + } +} diff --git a/Sources/HelderUI/Overlays/NoteOverlay.swift b/Sources/HelderUI/Overlays/NoteOverlay.swift index 1a6b446..f0c464e 100644 --- a/Sources/HelderUI/Overlays/NoteOverlay.swift +++ b/Sources/HelderUI/Overlays/NoteOverlay.swift @@ -1,4 +1,3 @@ -import AppKit import SwiftUI /// ⌘N: the project's plain-text note. Closing it in any way saves it. @@ -19,7 +18,8 @@ struct NoteOverlay: View { } .buttonStyle(.primary) } - NoteEditor(text: Binding(get: { note.text }, set: { note.text = $0 }), onKey: handle) + OverlayTextEditor(text: Binding(get: { note.text }, set: { note.text = $0 }), + placeholder: "Anything you want to keep next to this project…", onKey: handle) .frame(maxWidth: .infinity, maxHeight: .infinity) Text("saved on focus loss · \(note.characterCount) characters") .typeRole(Typography.meta) @@ -43,98 +43,3 @@ struct NoteOverlay: View { return true } } - -/// Mono 14/1.7 plain-text editor with an amber caret, focused with the caret at the end. -private struct NoteEditor: NSViewRepresentable { - @Binding var text: String - var onKey: (OverlayKey) -> Bool - - func makeCoordinator() -> Coordinator { Coordinator(self) } - - func makeNSView(context: Context) -> NSScrollView { - let scroll = NSScrollView() - scroll.drawsBackground = false - scroll.hasVerticalScroller = true - scroll.autohidesScrollers = true - let textView = NoteTextView(frame: .zero) - textView.pointerLayer = .overlay - textView.isVerticallyResizable = true - textView.isHorizontallyResizable = false - textView.autoresizingMask = [.width] - textView.textContainer?.widthTracksTextView = true - textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) - textView.fillsClipView = true - scroll.documentView = textView - let role = Typography.note - let paragraph = NSMutableParagraphStyle() - paragraph.minimumLineHeight = role.lineHeight ?? 23.8 - paragraph.maximumLineHeight = role.lineHeight ?? 23.8 - textView.drawsBackground = false - textView.isRichText = false - textView.allowsUndo = true - textView.isAutomaticQuoteSubstitutionEnabled = false - textView.isAutomaticDashSubstitutionEnabled = false - textView.isAutomaticSpellingCorrectionEnabled = false - textView.isContinuousSpellCheckingEnabled = false - textView.font = role.nsFont - textView.textColor = NSColor(hex: 0xE4E7E6) - textView.insertionPointColor = NSColor(hex: 0xE8913A) - textView.defaultParagraphStyle = paragraph - textView.typingAttributes = [.font: role.nsFont, .foregroundColor: NSColor(hex: 0xE4E7E6), .paragraphStyle: paragraph] - textView.textContainerInset = NSSize(width: 20, height: 18) - textView.string = text - textView.delegate = context.coordinator - textView.onKey = onKey - textView.placeholder = "Anything you want to keep next to this project…" - DispatchQueue.main.async { - guard let window = textView.window, window.makeFirstResponder(textView) else { return } - textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0)) - textView.scrollRangeToVisible(textView.selectedRange()) - } - return scroll - } - - func updateNSView(_ scroll: NSScrollView, context: Context) { - context.coordinator.parent = self - guard let textView = scroll.documentView as? NoteTextView else { return } - textView.onKey = onKey - if textView.string != text { textView.string = text } - } - - final class Coordinator: NSObject, NSTextViewDelegate { - var parent: NoteEditor - - init(_ parent: NoteEditor) { - self.parent = parent - } - - func textDidChange(_ notification: Notification) { - guard let textView = notification.object as? NSTextView else { return } - parent.text = textView.string - textView.needsDisplay = true - } - - func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool { - selector == #selector(NSResponder.cancelOperation(_:)) ? parent.onKey(.escape) : false - } - } -} - -/// Catches ⌘P before the menu bar's ⌘P (push) and draws the placeholder. -private final class NoteTextView: PointerBoundTextView { - var onKey: (OverlayKey) -> Bool = { _ in false } - var placeholder = "" - - override func performKeyEquivalent(with event: NSEvent) -> Bool { - if window?.firstResponder === self, OverlayKey(event: event) == .commandP, onKey(.commandP) { return true } - return super.performKeyEquivalent(with: event) - } - - override func draw(_ dirtyRect: NSRect) { - super.draw(dirtyRect) - guard string.isEmpty, !placeholder.isEmpty else { return } - let attributes: [NSAttributedString.Key: Any] = [.font: font ?? Typography.note.nsFont, .foregroundColor: NSColor(hex: 0x6C7783)] - let origin = NSPoint(x: textContainerInset.width + (textContainer?.lineFragmentPadding ?? 0), y: textContainerInset.height) - (placeholder as NSString).draw(at: origin, withAttributes: attributes) - } -} diff --git a/Sources/HelderUI/Overlays/OverlayHost.swift b/Sources/HelderUI/Overlays/OverlayHost.swift index 983850d..6a11259 100644 --- a/Sources/HelderUI/Overlays/OverlayHost.swift +++ b/Sources/HelderUI/Overlays/OverlayHost.swift @@ -36,6 +36,10 @@ public struct OverlayHost: View { if let note = model.note { NoteOverlay(note: note, onPassOn: { model.perform(.passNote) }, onClose: dismiss) } + case .cleanCopy: + if let cleanCopy = model.cleanCopy { + CleanCopyOverlay(store: cleanCopy, onCopy: { model.perform(.copyCleanCopy) }, onClose: dismiss) + } case let .recentFiles(initialSelection): RecentFilesOverlay(history: model.editor?.history ?? [], initialSelection: initialSelection, changedPaths: model.changedPaths, diff --git a/Sources/HelderUI/Overlays/OverlayKeys.swift b/Sources/HelderUI/Overlays/OverlayKeys.swift index a16cc88..4f9fad3 100644 --- a/Sources/HelderUI/Overlays/OverlayKeys.swift +++ b/Sources/HelderUI/Overlays/OverlayKeys.swift @@ -4,7 +4,7 @@ import SwiftUI /// The keys the overlays react to, from a text field or a bare key catcher. enum OverlayKey: Equatable { case up, down, commandUp, commandDown, commandLeft, commandRight, enter, escape - case commandP + case commandP, commandEnter /// Maps the text system's commands back to the keys that produced them. init?(selector: Selector) { @@ -21,6 +21,19 @@ enum OverlayKey: Equatable { } } + /// ⌘P or ⌘↩ from a text view, which sees them as key equivalents before any key handling. + init?(equivalent event: NSEvent) { + let modifiers = event.modifierFlags.intersection([.command, .shift, .option, .control]) + guard modifiers == .command else { return nil } + if event.keyCode == 36 || event.keyCode == 76 { + self = .commandEnter + } else if event.charactersIgnoringModifiers?.lowercased() == "p" { + self = .commandP + } else { + return nil + } + } + /// Maps a raw key event, for overlays without a text field. init?(event: NSEvent) { let command = event.modifierFlags.contains(.command) diff --git a/Sources/HelderUI/Overlays/OverlayTextEditor.swift b/Sources/HelderUI/Overlays/OverlayTextEditor.swift new file mode 100644 index 0000000..e8f5906 --- /dev/null +++ b/Sources/HelderUI/Overlays/OverlayTextEditor.swift @@ -0,0 +1,98 @@ +import AppKit +import SwiftUI + +/// Mono 14/1.7 plain-text editor with an amber caret, focused with the caret at the end. +struct OverlayTextEditor: NSViewRepresentable { + @Binding var text: String + var placeholder = "" + var onKey: (OverlayKey) -> Bool + + func makeCoordinator() -> Coordinator { Coordinator(self) } + + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.drawsBackground = false + scroll.hasVerticalScroller = true + scroll.autohidesScrollers = true + let textView = OverlayTextView(frame: .zero) + textView.pointerLayer = .overlay + textView.isVerticallyResizable = true + textView.isHorizontallyResizable = false + textView.autoresizingMask = [.width] + textView.textContainer?.widthTracksTextView = true + textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + textView.fillsClipView = true + scroll.documentView = textView + let role = Typography.note + let paragraph = NSMutableParagraphStyle() + paragraph.minimumLineHeight = role.lineHeight ?? 23.8 + paragraph.maximumLineHeight = role.lineHeight ?? 23.8 + textView.drawsBackground = false + textView.isRichText = false + textView.allowsUndo = true + textView.isAutomaticQuoteSubstitutionEnabled = false + textView.isAutomaticDashSubstitutionEnabled = false + textView.isAutomaticSpellingCorrectionEnabled = false + textView.isContinuousSpellCheckingEnabled = false + textView.font = role.nsFont + textView.textColor = NSColor(hex: 0xE4E7E6) + textView.insertionPointColor = NSColor(hex: 0xE8913A) + textView.defaultParagraphStyle = paragraph + textView.typingAttributes = [.font: role.nsFont, .foregroundColor: NSColor(hex: 0xE4E7E6), .paragraphStyle: paragraph] + textView.textContainerInset = NSSize(width: 20, height: 18) + textView.string = text + textView.delegate = context.coordinator + textView.onKey = onKey + textView.placeholder = placeholder + DispatchQueue.main.async { + guard let window = textView.window, window.makeFirstResponder(textView) else { return } + textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0)) + textView.scrollRangeToVisible(textView.selectedRange()) + } + return scroll + } + + func updateNSView(_ scroll: NSScrollView, context: Context) { + context.coordinator.parent = self + guard let textView = scroll.documentView as? OverlayTextView else { return } + textView.onKey = onKey + if textView.string != text { textView.string = text } + } + + final class Coordinator: NSObject, NSTextViewDelegate { + var parent: OverlayTextEditor + + init(_ parent: OverlayTextEditor) { + self.parent = parent + } + + func textDidChange(_ notification: Notification) { + guard let textView = notification.object as? NSTextView else { return } + parent.text = textView.string + textView.needsDisplay = true + } + + func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool { + selector == #selector(NSResponder.cancelOperation(_:)) ? parent.onKey(.escape) : false + } + } +} + +/// Catches ⌘P and ⌘↩ before the menu bar sees them, and draws the placeholder. +private final class OverlayTextView: PointerBoundTextView { + var onKey: (OverlayKey) -> Bool = { _ in false } + var placeholder = "" + + override func performKeyEquivalent(with event: NSEvent) -> Bool { + if window?.firstResponder === self, let key = OverlayKey(equivalent: event), onKey(key) { return true } + return super.performKeyEquivalent(with: event) + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard string.isEmpty, !placeholder.isEmpty else { return } + let attributes: [NSAttributedString.Key: Any] = [.font: font ?? Typography.note.nsFont, .foregroundColor: NSColor(hex: 0x6C7783)] + let origin = NSPoint(x: textContainerInset.width + (textContainer?.lineFragmentPadding ?? 0), y: textContainerInset.height) + (placeholder as NSString).draw(at: origin, withAttributes: attributes) + } +} diff --git a/Sources/HelderUI/Overlays/SearchOverlay.swift b/Sources/HelderUI/Overlays/SearchOverlay.swift index 0b9e4a7..c5e59d2 100644 --- a/Sources/HelderUI/Overlays/SearchOverlay.swift +++ b/Sources/HelderUI/Overlays/SearchOverlay.swift @@ -310,7 +310,7 @@ struct SearchOverlay: View { case .down, .commandDown: park(); model.moveRow(by: 1) case .enter: if let target = model.target() { open(target) } case .escape: onClose() - case .commandP: return false + case .commandP, .commandEnter: return false } return true } diff --git a/Sources/HelderUI/Shell/Command.swift b/Sources/HelderUI/Shell/Command.swift index 5644f7a..b186eb7 100644 --- a/Sources/HelderUI/Shell/Command.swift +++ b/Sources/HelderUI/Shell/Command.swift @@ -124,6 +124,11 @@ public enum Command: Equatable, Sendable { /// ⌘P while the note is open. case passNote + // MARK: Clean copy + + /// The clean-copy popup's Copy and ⌘↩: copies its text and closes it. + case copyCleanCopy + // MARK: Project and window /// ⌘O diff --git a/Sources/HelderUI/State/CleanCopyStore.swift b/Sources/HelderUI/State/CleanCopyStore.swift new file mode 100644 index 0000000..5191487 --- /dev/null +++ b/Sources/HelderUI/State/CleanCopyStore.swift @@ -0,0 +1,63 @@ +import Foundation +import HelderCore +import HelderServices +import Observation + +/// The clean-copy popup: text the agent wrote to `.clean-copy`, editable before it is copied. +@Observable +@MainActor +public final class CleanCopyStore { + public static let fileName = CleanCopy.fileName + + /// The popup's text, with the user's edits. + public var text = "" + /// The text as it arrived, so an edit can be told apart. + public private(set) var received = "" + /// The newest text waiting for the popup, while another overlay is open. + public private(set) var pending: String? + + /// The file's last contents Helder saw; nil before the first read or while the file is missing. + @ObservationIgnored private var lastSeen: String? + @ObservationIgnored private let files: FileServicing + + public init(files: FileServicing) { + self.files = files + } + + public var isEdited: Bool { text != received } + + public var characterCount: Int { text.count } + + /// Project open: the file's current text is the baseline and never shows. + public func loadBaseline() async { + lastSeen = await read() + } + + /// The file changed: returns true when it holds new text, which then waits in `pending`. + @discardableResult + public func fileChanged() async -> Bool { + guard let contents = await read() else { return false } + let isNew = CleanCopy.isNew(contents, lastSeen: lastSeen) + lastSeen = contents + if isNew { pending = contents } + return isNew + } + + /// Moves the pending text into the popup that is about to open. + public func takePending() { + guard let pending else { return } + text = pending + received = pending + self.pending = nil + } + + /// New text while the popup is open replaces it only when the user has not edited it. + public func refreshOpenPopup() { + if !isEdited { takePending() } + pending = nil + } + + private func read() async -> String? { + try? await files.read(Self.fileName) + } +} diff --git a/Sources/HelderUI/State/OverlayStore.swift b/Sources/HelderUI/State/OverlayStore.swift index 530c679..bc697da 100644 --- a/Sources/HelderUI/State/OverlayStore.swift +++ b/Sources/HelderUI/State/OverlayStore.swift @@ -90,6 +90,8 @@ public enum Overlay: Equatable { case shortcuts /// ⌘N: the project note. case note + /// Text the agent wrote to `.clean-copy`, to edit and copy. + case cleanCopy case diff(DiffOverlayRequest) /// ⇧⌘O: the other recent projects. The bare window's launcher is not an overlay. case launcher diff --git a/Sources/HelderUI/State/WorkspaceModel+Commands.swift b/Sources/HelderUI/State/WorkspaceModel+Commands.swift index 8779816..7e39b76 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Commands.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Commands.swift @@ -15,6 +15,39 @@ extension WorkspaceModel { default: break } + if new == .none, cleanCopy?.pending != nil { + Task { @MainActor [weak self] in self?.showCleanCopy() } + } + } + + /// `.clean-copy` changed on disk: new text opens the popup, or waits for the open overlay to close. + func cleanCopyChanged() async { + guard let cleanCopy else { return } + let current = generation + guard await cleanCopy.fileChanged(), generation == current, self.cleanCopy === cleanCopy else { return } + showCleanCopy() + } + + /// Shows the pending clean-copy text when nothing else floats over the workspace. + func showCleanCopy() { + guard let cleanCopy, cleanCopy.pending != nil else { return } + switch overlay.current { + case .none: + cleanCopy.takePending() + overlay.present(.cleanCopy) + case .cleanCopy: + cleanCopy.refreshOpenPopup() + default: + break + } + } + + /// Copies the popup's text as plain text, closes it and confirms with a toast. + func copyCleanCopy() { + guard let cleanCopy, overlay.current == .cleanCopy else { return } + app.system.copy(cleanCopy.text) + overlay.dismiss() + toasts.show("Copied", detail: "\(cleanCopy.characterCount) characters") } /// The recent projects other than this one, for ⇧⌘O. diff --git a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift index 9f56d61..2fe48e7 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift @@ -69,6 +69,7 @@ extension WorkspaceModel { let note = NoteStore(notes: services.notes) note.notify = notify self.note = note + cleanCopy = CleanCopyStore(files: services.files) terminal = TerminalStore(projectRoot: root.path) wireTerminal() launcher = LauncherList(recents: recentProjects, excluding: root.path) @@ -100,11 +101,12 @@ extension WorkspaceModel { recentProjects = await app.recentProjects.list() guard generation == current else { return } launcher = LauncherList(recents: recentProjects, excluding: root.path) - let sourceControl = sourceControl, explorer = explorer, note = note, editor = editor + let sourceControl = sourceControl, explorer = explorer, note = note, editor = editor, cleanCopy = cleanCopy async let git: Void = sourceControl?.refresh() ?? () async let tree: Void = explorer?.reload() ?? () async let loaded: Void = note?.load() ?? () - _ = await (git, tree, loaded) + async let baseline: Void = cleanCopy?.loadBaseline() ?? () + _ = await (git, tree, loaded, baseline) await editor?.restore(restoreSession: config.session.restoreOnLaunch) guard generation == current else { return } startWatcher(root) diff --git a/Sources/HelderUI/State/WorkspaceModel+Refresh.swift b/Sources/HelderUI/State/WorkspaceModel+Refresh.swift index f1ee005..fd6dbd5 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Refresh.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Refresh.swift @@ -18,6 +18,7 @@ extension WorkspaceModel { case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .note]) case .git: scheduleRefresh(.git) case .config: await reloadConfig() + case .cleanCopy: await cleanCopyChanged() } } diff --git a/Sources/HelderUI/State/WorkspaceModel.swift b/Sources/HelderUI/State/WorkspaceModel.swift index 9040f06..7a57e51 100644 --- a/Sources/HelderUI/State/WorkspaceModel.swift +++ b/Sources/HelderUI/State/WorkspaceModel.swift @@ -84,6 +84,7 @@ public final class WorkspaceModel { public internal(set) var editor: EditorStore? public internal(set) var terminal: TerminalStore public internal(set) var note: NoteStore? + public internal(set) var cleanCopy: CleanCopyStore? @ObservationIgnored public let app: AppServices @ObservationIgnored public internal(set) var services: WorkspaceServices? @@ -186,6 +187,7 @@ public final class WorkspaceModel { focusRequest = FocusRequest(.commitMessage) case .passNote: passNote() + case .copyCleanCopy: copyCleanCopy() case .openFolder: switchProject { diff --git a/Sources/HelderUI/Terminal/HelderTerminalView.swift b/Sources/HelderUI/Terminal/HelderTerminalView.swift index abe702f..24f76bd 100644 --- a/Sources/HelderUI/Terminal/HelderTerminalView.swift +++ b/Sources/HelderUI/Terminal/HelderTerminalView.swift @@ -10,6 +10,7 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle, var appliedSettings: HelderConfig.Terminal? var appliedScale = 1.0 private var closeObserver: NSObjectProtocol? + private var keyMonitor: Any? private lazy var pointerTracker = PointerTracker(view: self) private let events = ProcessEvents() @@ -24,6 +25,7 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle, processDelegate = events appliedSettings = store.config.terminal TerminalAppearance.apply(store.config.terminal, to: self) + syncMouseReporting() } required init?(coder: NSCoder) { @@ -60,18 +62,28 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle, super.send(source: source, data: data) } - /// ⌥← and ⌥→ jump by word (ESC b / ESC f, as Terminal.app does) while Option is not the Meta key. - override func interpretKeyEvents(_ events: [NSEvent]) { - if !optionAsMetaKey, events.count == 1, let event = events.first, event.type == .keyDown, - event.modifierFlags.intersection([.shift, .control, .option, .command]) == .option, - let key = event.charactersIgnoringModifiers?.unicodeScalars.first.map({ Int($0.value) }) { - switch key { - case NSLeftArrowFunctionKey: return send(EscapeSequences.emacsBack) - case NSRightArrowFunctionKey: return send(EscapeSequences.emacsForward) - default: break - } - } - super.interpretKeyEvents(events) + /// ⌥← and ⌥→ jump by word (ESC b / ESC f, as Terminal.app does) while Option is not the Meta key; + /// caught before SwiftTerm, whose kitty-keyboard path would drop the Option and whose `keyDown` is not open. + private func handleWordJump(_ event: NSEvent) -> Bool { + guard !optionAsMetaKey, let window, event.window === window, window.firstResponder === self, + event.modifierFlags.intersection([.shift, .control, .option, .command]) == .option, + let key = event.charactersIgnoringModifiers?.unicodeScalars.first.map({ Int($0.value) }), + key == NSLeftArrowFunctionKey || key == NSRightArrowFunctionKey else { return false } + selection.active = false + send(key == NSLeftArrowFunctionKey ? EscapeSequences.emacsBack : EscapeSequences.emacsForward) + return true + } + + /// Mouse reporting is on only while the program asked for it; SwiftTerm clears the selection on every output + /// while it is on, so a redrawing program like Claude Code could never keep one. + override func dataReceived(slice: ArraySlice) { + syncMouseReporting() + super.dataReceived(slice: slice) + syncMouseReporting() + } + + private func syncMouseReporting() { + allowMouseReporting = terminal.mouseMode != .off } /// Selecting text copies it, in both panes. @@ -181,7 +193,12 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle, super.viewDidMoveToWindow() if let closeObserver { NotificationCenter.default.removeObserver(closeObserver) } closeObserver = nil + if let keyMonitor { NSEvent.removeMonitor(keyMonitor) } + keyMonitor = nil guard let window else { return } + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in + MainActor.assumeIsolated { self?.handleWordJump(event) ?? false } ? nil : event + } closeObserver = NotificationCenter.default.addObserver( forName: NSWindow.willCloseNotification, object: window, queue: .main ) { [weak self] _ in diff --git a/Tests/HelderCoreTests/Agent/AgentReferenceTests.swift b/Tests/HelderCoreTests/Agent/AgentReferenceTests.swift index 86def8c..9ecab4b 100644 --- a/Tests/HelderCoreTests/Agent/AgentReferenceTests.swift +++ b/Tests/HelderCoreTests/Agent/AgentReferenceTests.swift @@ -35,6 +35,15 @@ import Testing #expect(TerminalLaunch.environment(from: ["LC_ALL": "nl_NL.UTF-8"])["LANG"] == nil) } + @Test func bothPanesTellTheChildItRunsInHelder() { + let base = ["TERM_PROGRAM": "Apple_Terminal", "TERM_PROGRAM_VERSION": "455"] + for kind in TerminalKind.allCases { + let env = TerminalLaunch.make(kind: kind, config: .defaults, projectRoot: "/p", environment: base).environment + #expect(env["TERM_PROGRAM"] == "Helder") + #expect(env["TERM_PROGRAM_VERSION"] == nil) + } + } + @Test func agentRunsTheCommandThroughAnInteractiveShell() { let launch = TerminalLaunch.make(kind: .agent, config: .defaults, projectRoot: "/p", environment: ["SHELL": "/bin/bash"]) #expect(launch.executable == "/bin/bash") diff --git a/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift b/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift index b47b563..1cb4330 100644 --- a/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift +++ b/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift @@ -43,6 +43,18 @@ private final class EventLog: @unchecked Sendable { #expect(log.count(.git) == 0) } + @Test func theCleanCopyFileFiresItsOwnEventNextToTheProjectEvent() async throws { + let dir = try TempDirectory() + let (watcher, log) = await watch(dir.root) + defer { watcher.stop() } + try dir.write("notes/.clean-copy", "elsewhere") + await settle() + #expect(log.count(.cleanCopy) == 0) + try dir.write(CleanCopy.fileName, "copy me") + #expect(await eventually { log.count(.cleanCopy) >= 1 }) + #expect(await eventually { log.count(.project) >= 1 }) + } + @Test func changesInsideIgnoredFoldersAreDropped() async throws { let dir = try TempDirectory() try dir.mkdir("node_modules/pkg") diff --git a/Tests/HelderUITests/State/CleanCopyTests.swift b/Tests/HelderUITests/State/CleanCopyTests.swift new file mode 100644 index 0000000..18d8737 --- /dev/null +++ b/Tests/HelderUITests/State/CleanCopyTests.swift @@ -0,0 +1,112 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI +import Testing + +@MainActor +@Suite struct CleanCopyTests { + private let file = CleanCopy.fileName + + private func started(_ text: String? = nil) async -> WorkspaceHarness { + let harness = WorkspaceHarness(contents: text.map { [CleanCopy.fileName: $0] } ?? [:]) + await harness.start() + return harness + } + + private func agentWrites(_ text: String, _ harness: WorkspaceHarness) async { + harness.files.set(file, text) + await harness.model.handle(.cleanCopy) + await harness.model.settle() + } + + @Test func theTextFoundOnProjectOpenIsTheBaselineAndNeverPops() async { + let harness = await started("left over from yesterday") + #expect(harness.model.overlay.current == .none) + await harness.model.handle(.cleanCopy) + #expect(harness.model.overlay.current == .none) + } + + @Test func aChangedFileOpensThePopupWithItsText() async { + let harness = await started("old") + await agentWrites("git commit -m \"fix\"", harness) + #expect(harness.model.overlay.current == .cleanCopy) + #expect(harness.model.cleanCopy?.text == "git commit -m \"fix\"") + } + + @Test func aFileThatAppearsAfterOpenPops() async { + let harness = await started() + await agentWrites("first", harness) + #expect(harness.model.overlay.current == .cleanCopy) + } + + @Test func theSameTextAgainDoesNotPop() async { + let harness = await started() + await agentWrites("once", harness) + await harness.perform(.dismissOverlay) + await agentWrites("once", harness) + #expect(harness.model.overlay.current == .none) + } + + @Test func anEmptyOrBlankFileDoesNotPop() async { + let harness = await started("old") + await agentWrites("", harness) + await agentWrites(" \n\t", harness) + #expect(harness.model.overlay.current == .none) + } + + @Test func copyPutsTheEditedTextOnThePasteboardClosesAndToasts() async { + let harness = await started() + await agentWrites("draft", harness) + harness.model.cleanCopy?.text = "draft, edited" + await harness.perform(.copyCleanCopy) + #expect(harness.system.copied == ["draft, edited"]) + #expect(harness.model.overlay.current == .none) + #expect(harness.toastTitles == ["Copied"]) + } + + @Test func escClosesWithoutCopying() async { + let harness = await started() + await agentWrites("draft", harness) + await harness.perform(.dismissOverlay) + #expect(harness.system.copied.isEmpty) + #expect(harness.model.overlay.current == .none) + } + + @Test func newTextReplacesAnUneditedPopup() async { + let harness = await started() + await agentWrites("one", harness) + await agentWrites("two", harness) + #expect(harness.model.overlay.current == .cleanCopy) + #expect(harness.model.cleanCopy?.text == "two") + } + + @Test func newTextLeavesAnEditedPopupAlone() async { + let harness = await started() + await agentWrites("one", harness) + harness.model.cleanCopy?.text = "one, mine" + await agentWrites("two", harness) + #expect(harness.model.cleanCopy?.text == "one, mine") + #expect(harness.model.cleanCopy?.pending == nil) + } + + @Test func textWaitsForAnotherOverlayAndOnlyTheLatestShows() async { + let harness = await started() + await harness.perform(.showNote) + await agentWrites("one", harness) + await agentWrites("two", harness) + #expect(harness.model.overlay.current == .note) + await harness.perform(.dismissOverlay) + #expect(await eventually { harness.model.overlay.current == .cleanCopy }) + #expect(harness.model.cleanCopy?.text == "two") + } + + @Test func theFileIsNeverWrittenOrDeleted() async { + let harness = await started() + await agentWrites("keep", harness) + await harness.perform(.copyCleanCopy) + #expect(harness.files.current(file) == "keep") + #expect(harness.files.deleted.isEmpty) + #expect(harness.files.writes.isEmpty) + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 19b91a4..b24ab8a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -18,12 +18,12 @@ Helder (executable) → HelderUI → HelderServices → HelderCore ## How a window works -- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. +- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `CleanCopyStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. - **One entry point.** Views, the menu bar and the key router all call `WorkspaceModel.perform(Command)` (`Shell/Command.swift`). Context-menu items arrive as `.context(ContextAction)`; the model asks `SourceControlStore.confirmation(for:)` / `ExplorerStore.confirmation(for:)` first and shows the confirm overlay, and `.confirmPending` runs the action. The name prompt submits with `.submitName`, the pass-on prompt with `.passToAgent`, the note's ⌘P with `.passNote`. - **Overlays never stack.** `OverlayStore.current` is one `Overlay` enum; only the model presents or dismisses it. `OverlayStore.onChange` lets the model run closing behaviour however an overlay went away (the note saves, the Diff gives back the mode it covered). `OverlayHost` draws the current overlay. `.launcher` is the ⇧⌘O "Open recent project" list; the bare window's launcher is part of the shell, not an overlay. The key router only sees `OverlayKind` (`none`, `note`, `diff(busy:)`, `other`): over the Diff the workspace keys keep working unless its own menu or prompt is open (`busy`). Toasts (`ToastStore`) may sit on top. The Diff draws its own right-click menu and pass-on prompt inside itself, so it stays open. - **Stores report, the model shows.** Stores raise toasts through `notify`/`showToast` hooks the model wires to `ToastStore`; the model never toasts a second time for the same action. - **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the note and session and ends the terminals. -- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and note in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the note and the session, stops the watcher and polling, and ends both terminals. +- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree, note and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the note and the session, stops the watcher and polling, and ends both terminals. - **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live. - **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`. - **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject `, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window. @@ -34,7 +34,7 @@ Helder (executable) → HelderUI → HelderServices → HelderCore ``` Sources/HelderCore/ - Agent/ AgentReference, BracketedPaste, TerminalLaunch + Agent/ AgentReference, BracketedPaste, TerminalLaunch (`TERM_PROGRAM=Helder`), CleanCopy (file name, new-text rule) Config/ HelderConfig (tolerant decoding), config resolution, .env title Diff/ Diff models, LineDiff, DiffViews, ViewMode Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus) @@ -63,7 +63,7 @@ Sources/HelderUI/ Explorer/ the file tree column and the row glyphs Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup Terminal/ agent + shell panes over SwiftTerm - Overlays/ OverlayHost, search, note, shortcuts, recent files, context menu, name prompt, confirm, OverlayKeys + Overlays/ OverlayHost, search, note and clean copy (sharing OverlayTextEditor), shortcuts, recent files, context menu, name prompt, confirm, OverlayKeys Theme/ Palette, Typography, Metrics, FontRegistry Resources/Fonts/ IBM Plex Mono 400–700, Plex Sans 400/500/600/700/400i (WOFF2, OFL) Tests/Tests// diff --git a/docs/behaviour.md b/docs/behaviour.md index 900901b..4f91798 100644 --- a/docs/behaviour.md +++ b/docs/behaviour.md @@ -171,6 +171,16 @@ The top pane of the fourth column. - The pane shows the live agent session and has an input line at the bottom. - It receives the **Pass on to Agent** inserts from the editor: text arrives in the input as content, never as a submitted command, so the user can stack several and send when ready. - It is one terminal only. There are no additional agent sessions in this version. +- Both terminals run with `TERM_PROGRAM=Helder` in their environment, so the agent can tell it runs inside Helder. + +### Clean copy + +The agent hands the user text to copy through one file, `.clean-copy` in the project root. The agent overwrites the file each time; Helder only reads it and never clears or deletes it. + +- When the file's contents change while the project is open, Helder reads it after a short pause (writes are not atomic) and opens the **From Claude** popup, a card like the note. The contents found when the project opens are the baseline and never open the popup. An empty or blank file, or the same text as last seen, opens nothing. +- The popup holds an editable text area. **Copy** (or `Cmd+Enter`) copies the text, with the user's edits, to the clipboard as plain text, closes the popup and shows the "Copied" toast. `Esc` or a click outside closes it without copying. +- With another overlay open, the newest text waits and opens once that overlay closes. New text while the popup is open replaces its text only when the user has not edited it. +- The popup opens in the project's own window even when that window is in the background; Helder does not take focus. --- diff --git a/docs/guide/claude-code.md b/docs/guide/claude-code.md index 2331c90..46ab0c5 100644 --- a/docs/guide/claude-code.md +++ b/docs/guide/claude-code.md @@ -2,7 +2,7 @@ The Claude Code pane is the top half of the right-hand column. It is a live terminal that runs the Claude agent in your project folder. -[Guide index](index.md) · Related: [Command line](command-line.md), [Pass on to Agent](pass-on-to-agent.md), [Layout](layout.md), [Right-click menu](right-click-menu.md) +[Guide index](index.md) · Related: [Command line](command-line.md), [Pass on to Agent](pass-on-to-agent.md), [Clean copy](clean-copy.md), [Layout](layout.md), [Right-click menu](right-click-menu.md) ## At a glance @@ -45,6 +45,10 @@ The Claude Code pane is the top half of the right-hand column. It is a live term - After a pass, the keyboard moves to the Claude pane and a short [notification](notifications.md) confirms it ("Passed to agent"). - Nothing is sent when the agent process is not running. +### Text from Claude to copy +- Claude can hand you text to copy by writing it to `.clean-copy` in the project root. Helder then opens a card with that text and a **Copy** button. See [Clean copy](clean-copy.md). +- Both terminals run with `TERM_PROGRAM=Helder`, so Claude can tell it runs inside Helder. + ### Restart after the process exits - When the agent exits (for example after `/exit`), the pane shows a grey line: `[process exited] · press any key to restart`. - Press any key in the pane. Helder starts the agent again with the current settings. @@ -107,6 +111,7 @@ All settings live in `.helder/config.json`. See [Configuration](configuration.md - [Command line](command-line.md): the shell pane below, with the same look and copy behaviour. - [Pass on to Agent](pass-on-to-agent.md): send code references into Claude's composer. - [Notes](notes.md): send the project note to Claude with `Cmd+P`. +- [Clean copy](clean-copy.md): copy text that Claude writes to `.clean-copy`. - [Right-click menu](right-click-menu.md): Copy and Paste in the terminal. - [Layout](layout.md): the splitter, the Claude toggle and column widths. - [Configuration](configuration.md): where `ai` and `terminal` settings live. diff --git a/docs/guide/clean-copy.md b/docs/guide/clean-copy.md new file mode 100644 index 0000000..1c402c9 --- /dev/null +++ b/docs/guide/clean-copy.md @@ -0,0 +1,67 @@ +# Clean copy + +Clean copy lets Claude hand you text to copy: a command, a commit message, a draft. Claude writes it to a file, and Helder shows it in a card at the top of the window, ready to edit and copy. You never have to select text out of the terminal. + +[Guide index](index.md) · Related: [Claude Code](claude-code.md), [Notes](notes.md), [Notifications](notifications.md) + +## At a glance + +```text ++----------------------------------------------------------------+ +| (1) From Claude .clean-copy (2) [ Copy Cmd+Enter ] | ++----------------------------------------------------------------+ +| (3) | +| feat: show the refund state on the order page | +| | +| The order page now shows when a refund is pending._ | +| | ++----------------------------------------------------------------+ +| (4) copied as plain text . 74 characters | ++----------------------------------------------------------------+ +``` + +1. **Header**: the title and the file name, `.clean-copy`. +2. **Copy**: copies the text and closes the card. +3. **Text area**: the text Claude wrote, in a monospaced font. You can edit it before you copy. +4. **Footer**: how the text is copied, and how many characters it holds. + +## Features + +### The file +- The channel is one file: `.clean-copy` in the root of the project. +- Claude overwrites the whole file each time it has text for you. Helder only reads it; it never clears or deletes it. +- Both terminals get `TERM_PROGRAM=Helder` in their environment, so Claude can tell it runs inside Helder. +- Like any file, `.clean-copy` shows up in [Git](git.md) and the [Explorer](explorer.md) unless you ignore it. + +### When the card opens +- The card opens when the contents of `.clean-copy` change while the project is open. +- Helder waits a moment after the last write, so it reads the whole text, not half of it. +- The text that is in the file when you open the project never opens the card. +- An empty file, or one with only spaces and blank lines, does not open the card. +- Writing the same text again does not open the card a second time. +- The card opens in the window of that project, even when the window is in the background. Helder does not come to the front. + +### While something else is open +- When another card or dialog is open, such as the [note](notes.md) or [search](search.md), the text waits. The card opens once you close the other one. +- If Claude writes several times while you wait, only the newest text shows. +- When the clean-copy card is already open and new text arrives, the card shows the new text, unless you already edited the text. Then your edits stay and the new text is dropped. + +### Copying +- Click **Copy** or press `Cmd+Enter`. +- The text in the card, with your edits, goes to the clipboard as plain text. +- The card closes, and a [notification](notifications.md) says "Copied". +- `Esc`, or a click outside the card, closes it without copying. + +## Keyboard + +| Keys | Action | +|---|---| +| `Cmd+Enter` | Copy the text and close | +| `Esc` | Close without copying | + +## Related + +- [Claude Code](claude-code.md): the agent that writes `.clean-copy`. +- [Notes](notes.md): the card the clean-copy card looks like. +- [Notifications](notifications.md): the "Copied" confirmation. +- [Keyboard shortcuts](keyboard-shortcuts.md): every key in one list. diff --git a/docs/guide/index.md b/docs/guide/index.md index 6ee87f3..bbce4ee 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -59,6 +59,7 @@ This guide explains Helder from the user's side: what each part of the window sh - [Claude Code](claude-code.md): the agent pane. - [Command line](command-line.md): the shell pane. +- [Clean copy](clean-copy.md): text Claude hands you to copy, through `.clean-copy`. ### Finding things diff --git a/docs/guide/keyboard-shortcuts.md b/docs/guide/keyboard-shortcuts.md index 3508c4c..d3598ce 100644 --- a/docs/guide/keyboard-shortcuts.md +++ b/docs/guide/keyboard-shortcuts.md @@ -173,6 +173,14 @@ See [Notes](notes.md). | `Cmd+P` | Pass the whole note to the agent (while the note is open) | | `Esc` | Close the note (it saves) | +### Clean copy +See [Clean copy](clean-copy.md). + +| Keys | Action | +|---|---| +| `Cmd+Enter` | Copy the text and close the card | +| `Esc` | Close the card without copying | + ### Right-click menus and dialogs See [Right-click menu](right-click-menu.md) and [Dialogs](dialogs.md). diff --git a/docs/guide/notifications.md b/docs/guide/notifications.md index 58c05fa..b1b427e 100644 --- a/docs/guide/notifications.md +++ b/docs/guide/notifications.md @@ -83,6 +83,7 @@ The agent and the note: | Passed to agent | the reference | Text was inserted into the Claude pane | | Note passed to agent | `.notes.txt` | You passed the whole note with `Cmd+P` | | Save failed | `.notes.txt` | The project note could not be saved | +| Copied | character count | You copied the text of the [clean-copy](clean-copy.md) card | ### Other short messages Two other messages appear for a moment, but they are not toasts: