From e91b89294721ef4f4f8dbf59de137dc2b36b8bb2 Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Mon, 23 Nov 2026 09:00:46 +0700 Subject: [PATCH 01/19] fix: what the review of 2026-11-22 found, with a test for each The test scripts never say passed for a run that checked nothing, and those that reset a simulator's keychain take "iPhone Air" (#309, #311, #319); the iPhone tests' hosts ask no service and live in the test's home (#310). Git reads the changes whatever the user's diff prefixes (#260). Two builds' status line relays no longer run each other without end (#259). A weekly schedule with no real day is refused, and a window that crosses midnight runs all through it (#291, #290). Numbers out of range from a peer or an agent no longer stop the apps, the host or the MCP server (#296, #271, #249). A paste can no longer be ended early (#248); tabs stay tabs in the split diff (#295); keys typed during a replay reach the program (#293); an ended shell's terminal is written to no more (#275). The user's configuration that cannot be read, or is a link, is not written over (#265, #263). A command's time limit holds for all it started (#261). State the host cannot read is put aside and said (#273); a test's host keeps no build's instructions (#269); one Inbox item for a device's failed pushes (#272); the relay's answers are taken on the host's queue (#267); a peer that has not signed in is let go at once and writes nothing of its own in the log (#266, parts 1 and 2); a push fits the relay in any script (#294); a number that is no number is sent, and what cannot be read is said (#292); the host listens only on Tailscale's own address (#268). On the Mac, a git question is never answered in another folder (#297), and quitting with unsaved files asks (#298). A notice whose agent moved on is read (#321), and an agent's notification waits 10 seconds (#322). Co-Authored-By: Claude Opus 5.5 --- .../AgentTermClient/AgentTermConnection.swift | 21 ++- Sources/AgentTermHost/AgentBrowserTools.swift | 15 ++ Sources/AgentTermHost/AgentHooks.swift | 2 +- Sources/AgentTermHost/AgentSetup.swift | 42 +++-- Sources/AgentTermHost/CommitWriter.swift | 2 +- Sources/AgentTermHost/DeviceRegistry.swift | 9 +- Sources/AgentTermHost/FileBrowser.swift | 2 +- Sources/AgentTermHost/GitDiff.swift | 8 +- Sources/AgentTermHost/GitHistory.swift | 4 +- Sources/AgentTermHost/GitStash.swift | 2 +- Sources/AgentTermHost/HostEnvironment.swift | 89 +++++++-- Sources/AgentTermHost/HostServer.swift | 105 ++++++++--- Sources/AgentTermHost/KeptLinks.swift | 14 ++ Sources/AgentTermHost/NoticeCenter.swift | 2 + Sources/AgentTermHost/PTYProcess.swift | 24 ++- Sources/AgentTermHost/PushCenter.swift | 26 ++- Sources/AgentTermHost/ScheduleRunner.swift | 2 +- Sources/AgentTermHost/ScreenMirror.swift | 2 + Sources/AgentTermHost/StateFile.swift | 29 +++ Sources/AgentTermHost/StatusLineRelay.swift | 51 ++--- Sources/AgentTermHost/Tailscale.swift | 60 ++++-- Sources/AgentTermMac/AgentTermApp.swift | 23 +++ Sources/AgentTermMac/AppModel.swift | 33 +++- Sources/AgentTermMac/BrowserAgent.swift | 12 +- Sources/AgentTermProtocol/History.swift | 4 +- Sources/AgentTermProtocol/Messages.swift | 12 +- Sources/AgentTermProtocol/Notice.swift | 25 ++- Sources/AgentTermProtocol/Numbers.swift | 17 ++ Sources/AgentTermProtocol/PartFailure.swift | 8 +- Sources/AgentTermProtocol/Push.swift | 30 +++ Sources/AgentTermProtocol/Schedule.swift | 39 +++- Sources/AgentTermProtocol/SentText.swift | 20 +- Sources/AgentTermProtocol/Settings.swift | 6 +- Sources/AgentTermProtocol/Usage.swift | 2 +- Sources/AgentTermProtocol/Workspace.swift | 10 + .../AnsweringTerminalView.swift | 29 +++ .../AgentTermTerminal/FilesIntoTerminal.swift | 2 +- Sources/AgentTermTerminal/SplitDiffView.swift | 21 ++- .../TerminalController.swift | 15 +- Sources/AgentTermTerminal/UsageBar.swift | 10 +- Sources/agenttermd/main.swift | 3 + .../AgentTermHostTests/AgentShellsTests.swift | 9 +- .../ClientUnreadableTests.swift | 45 +++++ .../NoticeCenterTests.swift | 19 +- Tests/AgentTermHostTests/ParsingTests.swift | 5 +- .../AgentTermHostTests/PartFailureTests.swift | 27 +++ Tests/AgentTermHostTests/PushTests.swift | 58 ++++-- .../ReviewCoreBrowserNumbersTests.swift | 46 +++++ .../ReviewCorePTYTests.swift | 65 +++++++ .../ReviewCorePushTests.swift | 98 ++++++++++ .../ReviewCoreSupport.swift | 174 +++++++++++++++++ .../ReviewCoreTailscaleTests.swift | 64 +++++++ .../ReviewCoreTrapTests.swift | 126 +++++++++++++ .../ReviewCoreUnsignedPeerTests.swift | 80 ++++++++ .../ReviewSubConfigFilesTests.swift | 133 +++++++++++++ .../ReviewSubGitPrefixTests.swift | 72 +++++++ .../ReviewSubHostStateTests.swift | 103 +++++++++++ .../ReviewSubPushFailureTests.swift | 175 ++++++++++++++++++ .../ReviewSubStatusLineTests.swift | 135 ++++++++++++++ .../ReviewSubTimeoutTests.swift | 66 +++++++ Tests/AgentTermHostTests/ScheduleTests.swift | 19 ++ .../TestScriptHostsTests.swift | 33 ++++ .../TestScriptLogTests.swift | 134 ++++++++++++++ .../TestSimulatorChoiceTests.swift | 65 +++++++ Tests/AgentTermMacUITests/FilesTests.swift | 33 ++++ Tests/AgentTermMacUITests/GitTests.swift | 38 ++++ .../InboxBookTests.swift | 5 +- .../ReviewMessageTests.swift | 84 +++++++++ .../ReviewScheduleTests.swift | 57 ++++++ .../ReviewSentTextTests.swift | 31 ++++ .../ReviewTerminalTests.swift | 49 +++++ docs/DESIGN.md | 72 +++++-- docs/SPEC.md | 27 +-- docs/TESTING.md | 37 +++- scripts/lib-simulator.sh | 18 ++ scripts/lib-test-log.sh | 43 +++++ scripts/screenshots.sh | 7 + scripts/test-both.sh | 10 +- scripts/test-ios.sh | 30 +-- scripts/test-mac.sh | 10 +- 80 files changed, 2921 insertions(+), 213 deletions(-) create mode 100644 Sources/AgentTermHost/KeptLinks.swift create mode 100644 Sources/AgentTermHost/StateFile.swift create mode 100644 Sources/AgentTermProtocol/Numbers.swift create mode 100644 Sources/AgentTermTerminal/AnsweringTerminalView.swift create mode 100644 Tests/AgentTermHostTests/ClientUnreadableTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCoreBrowserNumbersTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCorePTYTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCorePushTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCoreSupport.swift create mode 100644 Tests/AgentTermHostTests/ReviewCoreTailscaleTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCoreTrapTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewCoreUnsignedPeerTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubConfigFilesTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubGitPrefixTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubHostStateTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubPushFailureTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubStatusLineTests.swift create mode 100644 Tests/AgentTermHostTests/ReviewSubTimeoutTests.swift create mode 100644 Tests/AgentTermHostTests/TestScriptHostsTests.swift create mode 100644 Tests/AgentTermHostTests/TestScriptLogTests.swift create mode 100644 Tests/AgentTermHostTests/TestSimulatorChoiceTests.swift create mode 100644 Tests/AgentTermProtocolTests/ReviewMessageTests.swift create mode 100644 Tests/AgentTermProtocolTests/ReviewScheduleTests.swift create mode 100644 Tests/AgentTermProtocolTests/ReviewSentTextTests.swift create mode 100644 Tests/AgentTermTerminalTests/ReviewTerminalTests.swift create mode 100644 scripts/lib-test-log.sh diff --git a/Sources/AgentTermClient/AgentTermConnection.swift b/Sources/AgentTermClient/AgentTermConnection.swift index 0166adce..483b9f42 100644 --- a/Sources/AgentTermClient/AgentTermConnection.swift +++ b/Sources/AgentTermClient/AgentTermConnection.swift @@ -36,6 +36,8 @@ public final class AgentTermConnection: @unchecked Sendable { private let queue = DispatchQueue(label: "agentterm.client") /// Touched on the main queue only. private var closed = false + /// It was said on this connection that a message could not be read. + private var saidUnreadable = false /// Joins a large message sent in pieces (`MessageParts`). private var joiner = MessageParts.Joiner() @@ -220,6 +222,15 @@ public final class AgentTermConnection: @unchecked Sendable { } /// Anything from the host is a sign of life, also a part of a message. + /// A message from the host that could not be read is said, once a + /// connection, as an error both apps show in their banner (#292): + /// before, it was dropped and nothing said so. + private func couldNotRead() { + guard !saidUnreadable else { return } + saidUnreadable = true + deliver { if !self.closed { self.onMessage?(.error(HostErrorWords.unreadableMessage)) } } + } + private func heard() { lastHeard = .now() pingSentAt = nil @@ -259,14 +270,20 @@ public final class AgentTermConnection: @unchecked Sendable { if let data, let message = MessageCoding.decode(ServerMessage.self, from: data) { self.noteProtocol(of: message) self.deliver { if !self.closed { self.onMessage?(message) } } + } else { + self.couldNotRead() } case .binary: guard let data, let frame = DataFrame(decoding: data) else { break } if frame.kind == .output { self.deliver { if !self.closed { self.onOutput?(frame.session, frame.payload) } } - } else if let whole = self.joiner.add(frame), let message = MessageCoding.decode(ServerMessage.self, from: whole) { + } else if let whole = self.joiner.add(frame) { // A large message, sent in pieces. - self.deliver { if !self.closed { self.onMessage?(message) } } + if let message = MessageCoding.decode(ServerMessage.self, from: whole) { + self.deliver { if !self.closed { self.onMessage?(message) } } + } else { + self.couldNotRead() + } } case .close: self.finish(reason: nil) diff --git a/Sources/AgentTermHost/AgentBrowserTools.swift b/Sources/AgentTermHost/AgentBrowserTools.swift index a2d2100c..0212fee2 100644 --- a/Sources/AgentTermHost/AgentBrowserTools.swift +++ b/Sources/AgentTermHost/AgentBrowserTools.swift @@ -104,6 +104,14 @@ extension AgentShellsMCP { private static func number(_ description: String) -> [String: Any] { ["type": "number", "description": description] } private static func boolean(_ description: String) -> [String: Any] { ["type": "boolean", "description": description] } + /// What each number a browser tool takes may be. + static let numberRanges: [String: ClosedRange] = [ + "x": -100_000...100_000, "y": -100_000...100_000, "seconds": 0...600, + "width": 1...10_000, "height": 1...10_000, "latitude": -90...90, "longitude": -180...180, + ] + + private static func words(_ number: Double) -> String { number == number.rounded() ? String(Int(number)) : String(number) } + /// The request a browser tool's call makes, or why it cannot be made. static func browserRequest(_ name: String, _ arguments: [String: Any]) -> Result { func text(_ key: String) -> String? { (arguments[key] as? String).flatMap { $0.isEmpty ? nil : $0 } } @@ -113,6 +121,13 @@ extension AgentShellsMCP { let tab = text("tab") ?? (arguments["tab"] as? NSNumber).map { $0.stringValue } func needs(_ key: String) -> BrowserToolError { BrowserToolError(text: "Give \(key == "tab" ? "the tab's id" : "`\(key)`") as `\(key)`.") } if !["browser_open", "browser_tabs", "browser_profiles"].contains(name), tab == nil { return .failure(needs("tab")) } + // A number out of what the browser takes, or no number ("inf", + // "nan", which JSON cannot carry), is refused at once (#249). + for (key, range) in Self.numberRanges where arguments[key] != nil { + guard let number = value(key), number.isFinite, range.contains(number) else { + return .failure(BrowserToolError(text: "`\(key)` is a number from \(Self.words(range.lowerBound)) to \(Self.words(range.upperBound)).")) + } + } let id = tab ?? "" func withRef(_ make: (String) -> BrowserRequest) -> Result { guard let ref = text("ref") else { return .failure(needs("ref")) } diff --git a/Sources/AgentTermHost/AgentHooks.swift b/Sources/AgentTermHost/AgentHooks.swift index ce0c89c7..bf58553c 100644 --- a/Sources/AgentTermHost/AgentHooks.swift +++ b/Sources/AgentTermHost/AgentHooks.swift @@ -73,7 +73,7 @@ public enum AgentHooks { private static func writeText(_ text: String, to file: URL) throws { if FileManager.default.contents(atPath: file.path) == Data(text.utf8) { return } - try Data(text.utf8).write(to: file, options: .atomic) + try Data(text.utf8).writeKeepingLinks(to: file) } // MARK: What a hook does diff --git a/Sources/AgentTermHost/AgentSetup.swift b/Sources/AgentTermHost/AgentSetup.swift index 5110053d..9eb70108 100644 --- a/Sources/AgentTermHost/AgentSetup.swift +++ b/Sources/AgentTermHost/AgentSetup.swift @@ -494,14 +494,20 @@ public final class AgentSetup: @unchecked Sendable { let command = line["command"] as? String else { return false } if command == statusLineCommand { return true } - return command.hasSuffix(" statusline") && command.contains("agenttermd") ? nil : false + return StatusLineRelay.isAgentTerms(command) ? nil : false } func setClaudeStatusLine() throws { // Settings that are not plain JSON are not rewritten. var settings = try Self.readJSON(claudeSettings) ?? [:] - if let current = settings["statusLine"] as? [String: Any], (current["command"] as? String) != statusLineCommand { - try Self.write(current, to: Self.previousStatusLine(in: directory)) + // What it takes the place of, to run after its own; another build's + // relay never over the user's own, kept before (#259): set up again + // after the other build, each would keep the other's. + if let current = settings["statusLine"] as? [String: Any], let command = current["command"] as? String, command != statusLineCommand { + let previous = Self.previousStatusLine(in: directory) + let kept = (try? Self.readJSON(previous))?["command"] as? String + let keepsTheUsers = kept.map { !$0.isEmpty && !StatusLineRelay.isAgentTerms($0) } ?? false + if !(StatusLineRelay.isAgentTerms(command) && keepsTheUsers) { try Self.write(current, to: previous) } } settings["statusLine"] = ["type": "command", "command": statusLineCommand] try Self.write(settings, to: claudeSettings) @@ -608,18 +614,32 @@ public final class AgentSetup: @unchecked Sendable { return rest } + /// A configuration file's text, nil when there is none; one that is + /// there but cannot be read as text is not taken for none (#265): it + /// would be written over. + static func readText(_ file: URL) throws -> String? { + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + guard let data = FileManager.default.contents(atPath: file.path) else { + throw Failure(text: "\(file.path) could not be read, so it was not changed.") + } + guard let text = String(data: data, encoding: .utf8) else { + throw Failure(text: "\(file.path) is not UTF-8 text, so it was not changed.") + } + return text + } + func addCodexHooks(path: String) throws { let file = codexConfig - let before = try? String(contentsOf: file, encoding: .utf8) + let before = try Self.readText(file) var text = withoutCodexHooks(before ?? "") let block = Self.events(of: "codex").flatMap(codexHook) if !text.isEmpty { text += text.hasSuffix("\n") ? "\n" : "\n\n" } text += block.joined(separator: "\n") + "\n" try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data(text.utf8).write(to: file, options: .atomic) + try Data(text.utf8).writeKeepingLinks(to: file) // Read by Codex as it reads its own, or put back as it was. if let checked = run([path, "features", "list"]), checked.status != 0 { - if let before { try? Data(before.utf8).write(to: file, options: .atomic) } else { try? FileManager.default.removeItem(at: file) } + if let before { try? Data(before.utf8).writeKeepingLinks(to: file) } else { try? FileManager.default.removeItem(at: file) } throw Failure(text: "Codex could not read its configuration with AgentTerm's hooks in it, so it was left as it was: " + checked.output.trimmingCharacters(in: .whitespacesAndNewlines)) } } @@ -629,7 +649,7 @@ public final class AgentSetup: @unchecked Sendable { guard let text = try? String(contentsOf: file, encoding: .utf8) else { return } let rest = withoutCodexHooks(text) guard rest != text else { return } - try Data(rest.utf8).write(to: file, options: .atomic) + try Data(rest.utf8).writeKeepingLinks(to: file) } // MARK: Codex's server and the session's variable @@ -682,7 +702,7 @@ public final class AgentSetup: @unchecked Sendable { while index < lines.count, !lines[index].trimmingCharacters(in: .whitespaces).hasPrefix("[") { if lines[index] == ours { lines.remove(at: index) - try Data(lines.joined(separator: "\n").utf8).write(to: file, options: .atomic) + try Data(lines.joined(separator: "\n").utf8).writeKeepingLinks(to: file) return } index += 1 @@ -697,9 +717,9 @@ public final class AgentSetup: @unchecked Sendable { func nameCodexServerVariable(path: String) throws { let file = codexConfig guard let before = try? String(contentsOf: file, encoding: .utf8), let text = withCodexServerVariable(before), text != before else { return } - try Data(text.utf8).write(to: file, options: .atomic) + try Data(text.utf8).writeKeepingLinks(to: file) guard codexServerVariable(path: path) == true else { - try? Data(before.utf8).write(to: file, options: .atomic) + try? Data(before.utf8).writeKeepingLinks(to: file) throw Failure(text: "Codex did not take the session's variable for AgentTerm's MCP server, so its configuration was left as it was.") } } @@ -796,7 +816,7 @@ public final class AgentSetup: @unchecked Sendable { static func write(_ object: Any, to file: URL) throws { try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) let data = try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) - try (data + Data("\n".utf8)).write(to: file, options: .atomic) + try (data + Data("\n".utf8)).writeKeepingLinks(to: file) } /// What AgentTerm tells an agent, as the host wrote it for the servers. diff --git a/Sources/AgentTermHost/CommitWriter.swift b/Sources/AgentTermHost/CommitWriter.swift index 01c75fd9..5d76c1e6 100644 --- a/Sources/AgentTermHost/CommitWriter.swift +++ b/Sources/AgentTermHost/CommitWriter.swift @@ -232,7 +232,7 @@ public enum CommitWriter { } private static func run(_ arguments: [String], in directory: String) -> String? { - guard let result = Subprocess.run(git, ["-C", directory, "-c", "core.quotepath=false"] + arguments, timeout: 30), result.status == 0 else { + guard let result = Subprocess.run(git, ["-C", directory, "-c", "core.quotepath=false"] + GitDiff.defaultPrefixes + arguments, timeout: 30), result.status == 0 else { return nil } return String(decoding: result.output, as: UTF8.self) diff --git a/Sources/AgentTermHost/DeviceRegistry.swift b/Sources/AgentTermHost/DeviceRegistry.swift index 4721f891..5f0a937b 100644 --- a/Sources/AgentTermHost/DeviceRegistry.swift +++ b/Sources/AgentTermHost/DeviceRegistry.swift @@ -38,6 +38,8 @@ public final class DeviceRegistry { private let file: URL? private let now: () -> Date private var records: [Record] = [] + /// Where the file of paired devices was put, when it could not be read. + public private(set) var setAside: URL? private var code: (value: String, expiresAt: Date)? public init(localToken: String, file: URL?, now: @escaping () -> Date = Date.init) { @@ -47,7 +49,12 @@ public final class DeviceRegistry { if let file, let data = try? Data(contentsOf: file) { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 - records = (try? decoder.decode([Record].self, from: data)) ?? [] + if let read = try? decoder.decode([Record].self, from: data) { + records = read + } else { + // Not written over at the next pairing (#273). + setAside = StateFile.setAside(file) + } } } diff --git a/Sources/AgentTermHost/FileBrowser.swift b/Sources/AgentTermHost/FileBrowser.swift index 6052e204..b738838b 100644 --- a/Sources/AgentTermHost/FileBrowser.swift +++ b/Sources/AgentTermHost/FileBrowser.swift @@ -68,7 +68,7 @@ public enum FileBrowser { public static func write(_ text: String, to path: String) throws { do { - try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .atomic) + try Data(text.utf8).writeKeepingLinks(to: URL(fileURLWithPath: path)) } catch { throw FileBrowserError.failed(error.localizedDescription) } diff --git a/Sources/AgentTermHost/GitDiff.swift b/Sources/AgentTermHost/GitDiff.swift index cc184d3e..5f5f146a 100644 --- a/Sources/AgentTermHost/GitDiff.swift +++ b/Sources/AgentTermHost/GitDiff.swift @@ -7,6 +7,12 @@ public enum GitDiff { private static let git = "/usr/bin/git" private static let maxPatchBytes = 400_000 private static let maxUntrackedFiles = 50 + /// Given to git before every diff `parse` reads: the names in it are + /// read after `a/` and `b/`, which the user's `diff.mnemonicPrefix` or + /// `diff.noprefix` would change (#260). Settings, not `--src-prefix` + /// and `--dst-prefix`: git 2.54's `stash show --include-untracked` puts + /// bytes of no meaning before a name given those. + static let defaultPrefixes = ["-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false"] /// Blocks while git runs. Call off the main thread. /// @@ -326,7 +332,7 @@ public enum GitDiff { } private static func run(_ arguments: [String], in directory: String, acceptStatus: Set = [0]) -> String? { - guard let result = Subprocess.run(git, ["-C", directory, "-c", "core.quotepath=false"] + arguments, timeout: 15), + guard let result = Subprocess.run(git, ["-C", directory, "-c", "core.quotepath=false"] + defaultPrefixes + arguments, timeout: 15), acceptStatus.contains(result.status) else { return nil } return String(decoding: result.output, as: UTF8.self) diff --git a/Sources/AgentTermHost/GitHistory.swift b/Sources/AgentTermHost/GitHistory.swift index 7e40e14a..30e11b71 100644 --- a/Sources/AgentTermHost/GitHistory.swift +++ b/Sources/AgentTermHost/GitHistory.swift @@ -47,8 +47,8 @@ extension GitActions { guard let result = Subprocess.run( "/usr/bin/git", - [ - "-C", directory, "show", "--first-parent", "-m", "--format=" + commitFormat + "%x00%b%x01", "--patch", "--no-color", "--no-ext-diff", + ["-C", directory] + GitDiff.defaultPrefixes + [ + "show", "--first-parent", "-m", "--format=" + commitFormat + "%x00%b%x01", "--patch", "--no-color", "--no-ext-diff", "--end-of-options", hash, "--", ], timeout: 30), diff --git a/Sources/AgentTermHost/GitStash.swift b/Sources/AgentTermHost/GitStash.swift index 4724aa76..eb007d3a 100644 --- a/Sources/AgentTermHost/GitStash.swift +++ b/Sources/AgentTermHost/GitStash.swift @@ -49,7 +49,7 @@ extension GitActions { guard let ref = ref(of: hash, in: directory) else { return nil } guard let result = Subprocess.run( - "/usr/bin/git", ["-C", directory, "stash", "show", "--include-untracked", "--patch", "--no-color", "--no-ext-diff", ref], timeout: 30), + "/usr/bin/git", ["-C", directory] + GitDiff.defaultPrefixes + ["stash", "show", "--include-untracked", "--patch", "--no-color", "--no-ext-diff", ref], timeout: 30), result.status == 0 else { return nil } return GitDiff.parse(String(decoding: result.output, as: UTF8.self)) diff --git a/Sources/AgentTermHost/HostEnvironment.swift b/Sources/AgentTermHost/HostEnvironment.swift index 1385a4f4..deb508bc 100644 --- a/Sources/AgentTermHost/HostEnvironment.swift +++ b/Sources/AgentTermHost/HostEnvironment.swift @@ -427,21 +427,47 @@ enum Subprocess { return signal == 0 ? .exited((status >> 8) & 0xff) : .signalled(signal) } - /// - Parameter mergeErrors: also capture what the command writes to standard error. + /// How long a command that reached its time limit, and everything it + /// started, is given to end at SIGTERM before it is killed, and its + /// output is read no more (#261). + static let graceAfterTimeout: TimeInterval = 1 + + /// - Parameters: + /// - mergeErrors: also capture what the command writes to standard error. + /// - input: what it reads, instead of nothing. + /// - forTheHost: whether it is one of the host's own commands, given + /// `forTheHostsOwnCommands`, or the user's, given `environment` as + /// it is. /// /// Started with `posix_spawn` and waited for with `waitpid`: Foundation's /// `Process` took some 70 ms to start a command and to see it end, which /// a git action or a look at the changes runs several of (#21). + /// + /// The time limit holds (#261): the command runs in a session and a + /// process group of its own, with no terminal, and at its limit the + /// whole group is asked to end, then killed a moment later; its output + /// is read no longer than that, also while a program it left behind + /// in another group keeps it open. static func run( _ executable: String, _ arguments: [String], cwd: String? = nil, timeout: TimeInterval = 10, mergeErrors: Bool = false, - environment: [String: String]? = nil + environment: [String: String]? = nil, input: Data? = nil, forTheHost: Bool = true ) -> Result? { var pipe: [Int32] = [0, 0] guard Darwin.pipe(&pipe) == 0 else { return nil } + var stdin: [Int32] = [-1, -1] + if input != nil, Darwin.pipe(&stdin) != 0 { + close(pipe[0]) + close(pipe[1]) + return nil + } var actions: posix_spawn_file_actions_t? posix_spawn_file_actions_init(&actions) defer { posix_spawn_file_actions_destroy(&actions) } - posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0) + if input != nil { + posix_spawn_file_actions_adddup2(&actions, stdin[0], STDIN_FILENO) + } else { + posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0) + } posix_spawn_file_actions_adddup2(&actions, pipe[1], STDOUT_FILENO) if mergeErrors { posix_spawn_file_actions_adddup2(&actions, pipe[1], STDERR_FILENO) @@ -452,12 +478,13 @@ enum Subprocess { var attributes: posix_spawnattr_t? posix_spawnattr_init(&attributes) defer { posix_spawnattr_destroy(&attributes) } - // Nothing of this process's but the three is passed on. - posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_CLOEXEC_DEFAULT)) + // Nothing of this process's but the three is passed on; a session + // of its own, whose group can be ended as one. + posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_CLOEXEC_DEFAULT | POSIX_SPAWN_SETSID)) let argv: [UnsafeMutablePointer?] = ([executable] + arguments).map { strdup($0) } + [nil] var given = environment ?? ProcessInfo.processInfo.environment - HostEnvironment.forTheHostsOwnCommands(&given) + if forTheHost { HostEnvironment.forTheHostsOwnCommands(&given) } let envp: [UnsafeMutablePointer?] = given.map { strdup("\($0.key)=\($0.value)") } + [nil] defer { argv.forEach { free($0) } @@ -466,29 +493,61 @@ enum Subprocess { var pid: pid_t = 0 let spawned = posix_spawn(&pid, executable, &actions, &attributes, argv, envp) close(pipe[1]) + if input != nil { close(stdin[0]) } guard spawned == 0 else { close(pipe[0]) + if input != nil { close(stdin[1]) } return nil } + if let input { + let writing = stdin[1] + // Set off on its own: a command that does not read it all must + // not stop its output from being read. + // A command that ends without reading it all is no signal here. + _ = fcntl(writing, F_SETNOSIGPIPE, 1) + DispatchQueue.global().async { + input.withUnsafeBytes { buffer in + var offset = 0 + while offset < buffer.count { + let n = Darwin.write(writing, buffer.baseAddress! + offset, buffer.count - offset) + if n > 0 { offset += n } else if n < 0 && errno == EINTR { continue } else { break } + } + } + close(writing) + } + } - // Stopped when it takes too long; never once it was waited for, when - // its number may be another program's. + // Stopped when it takes too long, with its group; never once it was + // reaped, when its number may be another program's. let lock = NSLock() - var ended = false + var reaped = false var stopped = false let timer = DispatchWorkItem { lock.lock() defer { lock.unlock() } - if !ended { - stopped = true - Subprocess.end(pid) + guard !reaped else { return } + stopped = true + kill(-pid, SIGTERM) + kill(-pid, SIGCONT) + DispatchQueue.global().asyncAfter(deadline: .now() + graceAfterTimeout) { + lock.lock() + defer { lock.unlock() } + if !reaped { kill(-pid, SIGKILL) } } } DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timer) - // Read before waiting so a full pipe cannot stall the child. + // Read before waiting so a full pipe cannot stall the child; no + // longer than the limit and the grace after it. + let lastRead = Date().addingTimeInterval(timeout + graceAfterTimeout + 0.5) var output = Data() var buffer = [UInt8](repeating: 0, count: 65536) while true { + let left = lastRead.timeIntervalSinceNow + guard left > 0 else { break } + var ready = pollfd(fd: pipe[0], events: Int16(POLLIN), revents: 0) + let polled = poll(&ready, 1, Int32(min(left * 1000, Double(Int32.max)).rounded(.up))) + if polled < 0 && errno == EINTR { continue } + if polled <= 0 { break } let count = read(pipe[0], &buffer, buffer.count) if count > 0 { output.append(buffer, count: count) @@ -500,11 +559,11 @@ enum Subprocess { } close(pipe[0]) // Seen to end but not reaped, so that its number is still its own - // while the timer may yet signal it; reaped once the timer cannot. + // while the timer may yet signal its group; reaped once it cannot. var info = siginfo_t() while waitid(P_PID, id_t(pid), &info, WEXITED | WNOWAIT) < 0 && errno == EINTR {} lock.lock() - ended = true + reaped = true let timedOut = stopped lock.unlock() timer.cancel() diff --git a/Sources/AgentTermHost/HostServer.swift b/Sources/AgentTermHost/HostServer.swift index 31e6cd7b..f2c523fd 100644 --- a/Sources/AgentTermHost/HostServer.swift +++ b/Sources/AgentTermHost/HostServer.swift @@ -40,6 +40,11 @@ public final class HostServer { public var foldersFile: URL? /// Where paired devices are saved. `nil` keeps them in memory only. public var devicesFile: URL? + /// Where what each agent is told is kept: the user's own words + /// (`agent-prompts.json`) and the file each agent's MCP server reads + /// (`prompts/.md`). Nil reads and writes neither (#269): a + /// host a test starts never touches a build's. + public var promptsDirectory: URL? /// Home folder whose agent files hold the conversation history. public var home: String /// Path of `agenttermd`, which Claude Code sessions run as their status @@ -78,6 +83,9 @@ public final class HostServer { /// How long an agent's hooks and MCP server have to be heard from /// before its session says they are missing (#129). Tests shorten it. public var linkGrace: TimeInterval = 20 + /// How long an agent's notice waits before it is a notification + /// (`Notice.alertDelay`, #322). Tests shorten it. + public var alertDelay: TimeInterval = Notice.alertDelay /// How long the Live Activity is kept, updated, with nothing /// working or waiting (`LiveActivityRule.keptIdle`). Tests shorten it. public var activityKeptIdle: TimeInterval = LiveActivityRule.keptIdle @@ -167,6 +175,8 @@ public final class HostServer { /// What it called itself when it said hello: "Mac" for the Mac's own /// app, a device's name for a device. var name = "" + /// It was refused and is being let go: nothing more of it is read. + var refused = false /// What the device said it is (#157); nil when it did not. var kind: DeviceKind? var identity: DeviceRegistry.Identity? @@ -390,13 +400,17 @@ public final class HostServer { public init(configuration: Configuration) { self.configuration = configuration registry = DeviceRegistry(localToken: configuration.token, file: configuration.devicesFile) - push = PushCenter(relay: configuration.pushRelay, file: configuration.pushesFile, transport: configuration.pushTransport) + push = PushCenter(relay: configuration.pushRelay, file: configuration.pushesFile, transport: configuration.pushTransport, queue: queue) notices = NoticeCenter(file: configuration.noticesFile) if let file = configuration.foldersFile, let data = try? Data(contentsOf: file), let saved = try? JSONDecoder().decode([String].self, from: data) { folders = saved } + if let file = settingsFile, let data = try? Data(contentsOf: file), MessageCoding.decode(Settings.self, from: data) == nil { + // Not written over at the next change (#273). + if let aside = StateFile.setAside(file) { setAsideAtStart.append(("settings", aside)) } + } if let file = settingsFile, let data = try? Data(contentsOf: file), let saved = MessageCoding.decode(Settings.self, from: data) { @@ -644,6 +658,14 @@ public final class HostServer { // What AgentTerm tells each agent, for its MCP server to give. writePromptsForServers() loadSchedules() + if let aside = registry.setAside { setAsideAtStart.append(("paired devices", aside)) } + for (what, aside) in setAsideAtStart { + report( + PartFailure( + part: .savedState, name: what, at: configuration.now(), restarted: false, + reason: "What it held is kept as \(aside.path), to be put back by hand.")) + } + setAsideAtStart = [] startAtLoginByDefault() let timer = DispatchSource.makeTimerSource(queue: queue) timer.schedule(deadline: .now() + min(1, configuration.scheduleInterval), repeating: configuration.scheduleInterval) @@ -664,7 +686,14 @@ public final class HostServer { let timer = DispatchSource.makeTimerSource(queue: queue) timer.schedule(deadline: .now(), repeating: 15) - timer.setEventHandler { [weak self] in self?.syncTailscaleListener() } + // Tailscale is asked which address is its own off the queue, as its + // command takes a moment (#268). + timer.setEventHandler { [weak self] in + DispatchQueue.global().async { + let own = Tailscale.ownAddresses() + self?.queue.async { self?.syncTailscaleListener(own: own) } + } + } queue.sync { tailscaleTimer = timer } timer.resume() return port @@ -794,12 +823,12 @@ public final class HostServer { /// of it when it has ended. private var runStops: [SessionID: String] = [:] - private func runKey(_ schedule: String, _ at: Date) -> String { "\(schedule)@\(Int(at.timeIntervalSince1970))" } + private func runKey(_ schedule: String, _ at: Date) -> String { "\(schedule)@\(Int(saturating: at.timeIntervalSince1970))" } /// Where what a run printed is kept. private func runOutputFile(_ schedule: String, _ at: Date) -> URL? { configuration.foldersFile?.deletingLastPathComponent().appendingPathComponent("runs", isDirectory: true) - .appendingPathComponent("\(schedule)-\(Int(at.timeIntervalSince1970)).txt") + .appendingPathComponent("\(schedule)-\(Int(saturating: at.timeIntervalSince1970)).txt") } /// When each run's session was first seen done, to close it a day later. private var runDoneAt: [SessionID: Date] = [:] @@ -827,12 +856,18 @@ public final class HostServer { /// Whether this host read its schedules, and so may save them. private var schedulesLoaded = false + /// What the host could not read as it started, and where it was put: + /// said once it runs (#273). + private var setAsideAtStart: [(what: String, at: URL)] = [] private func loadSchedules() { schedulesLoaded = true - guard let file = schedulesFile, let data = FileManager.default.contents(atPath: file.path), - let saved = MessageCoding.decode(SchedulesFile.self, from: data) - else { return } + guard let file = schedulesFile, let data = FileManager.default.contents(atPath: file.path) else { return } + guard let saved = MessageCoding.decode(SchedulesFile.self, from: data) else { + // Not written over by the next look at the schedules (#273). + if let aside = StateFile.setAside(file) { setAsideAtStart.append(("schedules", aside)) } + return + } schedules = saved.schedules schedulesChecked = saved.checked resetsRun = saved.resetsRun ?? [:] @@ -883,6 +918,7 @@ public final class HostServer { return "A schedule that skips permissions cannot be saved before its warning was shown and accepted." } guard !schedule.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return "Write what the agent is to do." } + if let refusal = schedule.when.refusal { return refusal } // Asked once now, while the user is here, rather than at 3 a.m. do { try ScheduleRunner.trustFolder(of: schedule, home: configuration.home) } catch { return "The folder could not be trusted for \(schedule.agent): \(error.localizedDescription)" @@ -1798,8 +1834,8 @@ public final class HostServer { /// Keeps a listener on the current Tailscale address, following the /// interface as it comes up, goes away or changes address. - private func syncTailscaleListener() { - let address = Tailscale.ipv4Address() + private func syncTailscaleListener(own: Set?) { + let address = Tailscale.ipv4Address(own: own) for (host, listener) in listeners where host != "127.0.0.1" && host != address { listener.cancel() listeners[host] = nil @@ -1845,7 +1881,9 @@ public final class HostServer { private static func logUnread(_ data: Data?, from client: String) { let key = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }?.keys.first ?? "" let name = key.count <= 40 && !key.isEmpty && key.allSatisfy { $0.isLetter && $0.isASCII } ? key : "not a message" - FileHandle.standardError.write(Data("agenttermd: a message from \(client.isEmpty ? "a client" : client) could not be read: \(name)\n".utf8)) + // The client's name as it gave it, on one line of the log (#266). + let who = String(client.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F }.prefix(40).map(Character.init)) + FileHandle.standardError.write(Data("agenttermd: a message from \(who.isEmpty ? "a client" : who) could not be read: \(name)\n".utf8)) } private func receive(from client: Client) { @@ -1863,6 +1901,10 @@ public final class HostServer { // one of that release would not (#214). if let data, let message = MessageCoding.decode(ClientMessage.self, from: data), message.isKnown(toHostAt: self.configuration.protocolVersion) { self.handle(message, from: client) + } else if !client.authenticated { + // A peer that has not signed in is let go at once, and + // nothing of it is written in the log (#266). + self.refuse(client, "malformed message") } else { Self.logUnread(data, from: client.name) self.send(.error("malformed message"), to: client) @@ -2051,7 +2093,12 @@ public final class HostServer { for client in clients.values where client.authenticated && noticeKey(of: client) != nil { send(.notice(notice), to: client) } - if notice.alerts { alert(notice.id) } + guard notice.alerts else { return } + // An agent's waits, to see whether the user acts meanwhile (#322): + // one handled or read by then is not shown (`alert` asks). + guard notice.waitsToAlert, configuration.alertDelay > 0 else { return alert(notice.id) } + let id = notice.id + queue.asyncAfter(deadline: .now() + configuration.alertDelay) { [weak self] in self?.alert(id) } } /// A notification on every device, over the connection or, for a @@ -2125,9 +2172,18 @@ public final class HostServer { /// a newer failure takes the place of an earlier one not seen yet. private func pushFailed(device: String, reason: String, forgotten: Bool) { let name = registry.devices().first { $0.id == device }?.name ?? "a device" - failures.removeAll { $0.part == .push && $0.name == name } let then = forgotten ? " It is no longer told through Apple until its app connects again." : "" - report(PartFailure(part: .push, name: name, at: configuration.now(), restarted: false, reason: "The relay said: \(reason).\(then)")) + let failure = PartFailure(part: .push, name: name, at: configuration.now(), restarted: false, reason: "The relay said: \(reason).\(then)") + // One for the device, the newest, in the banner; and one item in the + // Inbox while that one is not dismissed, not one per notification + // the relay did not take (#272). + let said = failures.contains { $0.part == .push && $0.name == name } + failures.removeAll { $0.part == .push && $0.name == name } + guard said else { return report(failure) } + failures.append(failure) + failures = Array(failures.suffix(FailureLog.limit)) + saveFailures() + broadcastFailures() } private func sendPushState(_ state: PushState, toDevice device: String) { @@ -3165,6 +3221,8 @@ public final class HostServer { /// Tells the client why, then closes once the message had time to arrive. private func refuse(_ client: Client, _ reason: String) { + guard !client.refused else { return } + client.refused = true send(.error(reason), to: client) queue.asyncAfter(deadline: .now() + 0.2) { [weak self, weak client] in if let self, let client { self.close(client) } @@ -3712,11 +3770,11 @@ public final class HostServer { /// What the user wrote for each agent in Settings, by agent; one that /// is not here is told the default. private lazy var agentPrompts: [String: String] = { - guard let data = FileManager.default.contents(atPath: Self.agentPromptsFile.path) else { return [:] } + guard let file = agentPromptsFile, let data = FileManager.default.contents(atPath: file.path) else { return [:] } return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:] }() - public static var agentPromptsFile: URL { HostEnvironment.supportDirectory.appendingPathComponent("agent-prompts.json") } + private var agentPromptsFile: URL? { configuration.promptsDirectory?.appendingPathComponent("agent-prompts.json") } /// What AgentTerm tells an agent by default, when it gives it the MCP /// server: to run its commands in the shells the user sees, and to use @@ -3733,8 +3791,8 @@ public final class HostServer { /// Where the agent's MCP server finds its instructions: the same words, /// which it gives as its own. Codex reads only those. - public static func promptFile(for agent: String) -> URL { - HostEnvironment.supportDirectory.appendingPathComponent("prompts", isDirectory: true).appendingPathComponent(agent + ".md") + public static func promptFile(for agent: String, in directory: URL = HostEnvironment.supportDirectory) -> URL { + directory.appendingPathComponent("prompts", isDirectory: true).appendingPathComponent(agent + ".md") } /// Writes what each agent is told where its MCP server finds it: at the @@ -3745,7 +3803,8 @@ public final class HostServer { } private func writePromptForServer(_ prompt: String?, agent: String) { - let file = Self.promptFile(for: agent) + guard let directory = configuration.promptsDirectory else { return } + let file = Self.promptFile(for: agent, in: directory) guard let prompt else { try? FileManager.default.removeItem(at: file) return @@ -3757,9 +3816,9 @@ public final class HostServer { /// The user's words for an agent, or none to go back to the default. private func setAgentPrompt(_ agent: String, _ text: String?) { if let text { agentPrompts[agent] = text } else { agentPrompts[agent] = nil } - if let data = try? JSONEncoder().encode(agentPrompts) { - try? FileManager.default.createDirectory(at: Self.agentPromptsFile.deletingLastPathComponent(), withIntermediateDirectories: true) - try? data.write(to: Self.agentPromptsFile, options: .atomic) + if let file = agentPromptsFile, let data = try? JSONEncoder().encode(agentPrompts) { + try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try? data.write(to: file, options: .atomic) } writePromptForServer(agentPrompt(for: agent), agent: agent) broadcastAgentPrompts() @@ -3927,7 +3986,9 @@ public final class HostServer { } send(.attached(session.info, request: request), to: client) let id = session.info.id - if let have, have <= session.written, session.written - have <= session.scrollback.count { + // A count out of range is no count (#271): `written - have` would + // stop the host. + if let have, have >= 0, have <= session.written, session.written - have <= session.scrollback.count { // A client that was here before, a phone after its network // changed: its terminal has all up to `have`, so only what came // since is sent, not a screen it would only draw again. diff --git a/Sources/AgentTermHost/KeptLinks.swift b/Sources/AgentTermHost/KeptLinks.swift new file mode 100644 index 00000000..d624a1a8 --- /dev/null +++ b/Sources/AgentTermHost/KeptLinks.swift @@ -0,0 +1,14 @@ +#if os(macOS) +import Foundation + +extension Data { + /// Writes as `.atomic` does, to the file a symbolic link names rather + /// than over the link (#263): the user's configuration or file kept as a + /// link into another folder (dotfiles) stays a link, and what it names + /// is what changes. An atomic write puts a new file in the place of + /// what it is given, which for a link is the link itself (macOS 27.2.1). + func writeKeepingLinks(to file: URL) throws { + try write(to: file.resolvingSymlinksInPath(), options: .atomic) + } +} +#endif diff --git a/Sources/AgentTermHost/NoticeCenter.swift b/Sources/AgentTermHost/NoticeCenter.swift index 129174a4..d88b7a98 100644 --- a/Sources/AgentTermHost/NoticeCenter.swift +++ b/Sources/AgentTermHost/NoticeCenter.swift @@ -59,6 +59,8 @@ final class NoticeCenter { guard let session = log[index].session, let state = log[index].state else { continue } if byID[session]?.state != state { log[index].handled = Notice.Handled(at: now, how: .movedOn) + // Read on every device too (#321). + if Notice.reads(.movedOn) { log[index].read = true } handled.append(log[index]) } } diff --git a/Sources/AgentTermHost/PTYProcess.swift b/Sources/AgentTermHost/PTYProcess.swift index 1a2a6943..46d4a6d3 100644 --- a/Sources/AgentTermHost/PTYProcess.swift +++ b/Sources/AgentTermHost/PTYProcess.swift @@ -38,6 +38,12 @@ public final class PTYProcess { private let master: Int32 private let queue: DispatchQueue private let writeQueue = DispatchQueue(label: "agentterm.pty.write") + /// Whether `master` is still this terminal's, read and changed on + /// `writeQueue` only: it is closed there, after every write asked + /// before, so that no write reaches the number once it is another + /// terminal's or file's (#275). + private final class Descriptor { var isOpen = true } + private let descriptor = Descriptor() private var readSource: DispatchSourceRead? private var exitSource: DispatchSourceProcess? private var finished = false @@ -69,7 +75,13 @@ public final class PTYProcess { let readSource = DispatchSource.makeReadSource(fileDescriptor: master, queue: queue) readSource.setEventHandler { [weak self] in self?.readAvailable() } - readSource.setCancelHandler { close(master) } + let writeQueue = writeQueue, descriptor = descriptor + readSource.setCancelHandler { + writeQueue.async { + descriptor.isOpen = false + close(master) + } + } self.readSource = readSource readSource.resume() @@ -87,11 +99,13 @@ public final class PTYProcess { /// Sends bytes to the program as if they were typed. public func write(_ data: Data) { guard !data.isEmpty else { return } - let fd = master + let fd = master, descriptor = descriptor // Writes can block when the program is not reading. They run on their // own queue so output keeps flowing meanwhile. - writeQueue.async { [weak self] in - guard self != nil else { return } + writeQueue.async { + // Once the program has ended its terminal is closed, and its + // number may be another's: nothing more is written (#275). + guard descriptor.isOpen else { return } data.withUnsafeBytes { buffer in var offset = 0 while offset < buffer.count { @@ -113,6 +127,8 @@ public final class PTYProcess { /// the leader of its foreground process group (#129). The shell itself /// at its prompt; nil when it cannot be told. public var foregroundCommand: String? { + // Asked of an ended program's terminal, the number may be another's. + guard !finished else { return nil } let group = tcgetpgrp(master) guard group > 0 else { return nil } return ProcessNames.command(of: group) diff --git a/Sources/AgentTermHost/PushCenter.swift b/Sources/AgentTermHost/PushCenter.swift index af7a4cc6..ac74034f 100644 --- a/Sources/AgentTermHost/PushCenter.swift +++ b/Sources/AgentTermHost/PushCenter.swift @@ -9,8 +9,9 @@ import Foundation /// (`NoticeCenter`) is encrypted with its key and sent to the relay, which /// passes it on to APNs; one handled elsewhere is taken back the same way. /// -/// Not thread-safe: the host calls it from its queue, and `transport` -/// answers on whatever queue it likes; `HostServer` brings it back. +/// Not thread-safe: the host calls it from its queue, and what `transport` +/// answers, on whatever queue it likes, is brought back to that queue +/// before anything is changed (#267). public final class PushCenter { /// What is kept for one device. struct Target: Codable, Equatable { @@ -37,11 +38,22 @@ public final class PushCenter { private let file: URL? private let transport: Transport private(set) var targets: [String: Target] = [:] + /// The queue it is used on, which the relay's answers are brought to. + private let queue: DispatchQueue? + /// The registration asked of the relay for each device and not answered + /// yet: an answer for one taken off since keeps nothing (#267). + private var asked: [String: UUID] = [:] - init(relay: URL?, file: URL?, transport: Transport? = nil) { + init(relay: URL?, file: URL?, transport: Transport? = nil, queue: DispatchQueue? = nil) { self.relay = relay self.file = file - self.transport = transport ?? Self.urlSession + self.queue = queue + let transport = transport ?? Self.urlSession + self.transport = { url, body, done in + transport(url, body) { status, data in + if let queue { queue.async { done(status, data) } } else { done(status, data) } + } + } if let file, let data = try? Data(contentsOf: file), let saved = try? JSONDecoder().decode([String: Target].self, from: data) { targets = saved } @@ -67,8 +79,13 @@ public final class PushCenter { return done(.unavailable(reason: PushWords.registrationFailed("the iPhone's key is not one"))) } let body = try! JSONSerialization.data(withJSONObject: ["token": registration.token]) + let request = UUID() + asked[device] = request transport(relay.appendingPathComponent("v1/register"), body) { [weak self] status, data in guard let self else { return } + // Taken off, or registered again, while the relay was asked. + guard self.asked[device] == request else { return } + self.asked[device] = nil guard status == 200, let data, let answer = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let ticket = answer["ticket"] as? String, let expires = answer["expires"] as? Int else { @@ -125,6 +142,7 @@ public final class PushCenter { } func unregister(device: String) { + asked[device] = nil guard targets.removeValue(forKey: device) != nil else { return } save() } diff --git a/Sources/AgentTermHost/ScheduleRunner.swift b/Sources/AgentTermHost/ScheduleRunner.swift index 8a832111..5b81877b 100644 --- a/Sources/AgentTermHost/ScheduleRunner.swift +++ b/Sources/AgentTermHost/ScheduleRunner.swift @@ -95,7 +95,7 @@ public enum ScheduleRunner { // Written by someone else since it was read: once more, from that. guard FileManager.default.contents(atPath: file.path) == read else { continue } try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try data.write(to: file, options: .atomic) + try data.writeKeepingLinks(to: file) return } // Written again every time it was looked at: not something to diff --git a/Sources/AgentTermHost/ScreenMirror.swift b/Sources/AgentTermHost/ScreenMirror.swift index cda738fd..a2599851 100644 --- a/Sources/AgentTermHost/ScreenMirror.swift +++ b/Sources/AgentTermHost/ScreenMirror.swift @@ -94,6 +94,8 @@ final class ScreenMirror: TerminalDelegate { } while rows.last?.isEmpty == true { rows.removeLast() } while rows.first?.isEmpty == true { rows.removeFirst() } + // A count below none, from a client, is none (#271). + let lines = max(0, lines) state.linesLeftOut = max(0, rows.count - lines) state.output = rows.suffix(lines).joined(separator: "\n") return state diff --git a/Sources/AgentTermHost/StateFile.swift b/Sources/AgentTermHost/StateFile.swift new file mode 100644 index 00000000..ca429c0d --- /dev/null +++ b/Sources/AgentTermHost/StateFile.swift @@ -0,0 +1,29 @@ +#if os(macOS) +import Foundation + +/// A file the host keeps its state in (#273). +enum StateFile { + /// Puts a file the host cannot read aside, under a name of its own next + /// to it (`schedules.json.unreadable`, then with the time when that is + /// taken), so that the host, which starts without what it held, never + /// writes over it. Nil when it could not be moved. + static func setAside(_ file: URL, now: Date = Date()) -> URL? { + var aside = file.appendingPathExtension("unreadable") + if FileManager.default.fileExists(atPath: aside.path) { + aside = file.appendingPathExtension("unreadable-\(Int(now.timeIntervalSince1970))") + } + do { + try FileManager.default.moveItem(at: file, to: aside) + return aside + } catch { + return nil + } + } + + /// Whether a file is there but holds what cannot be read: given what was + /// read of it, and whether it decoded. + static func isUnreadable(_ file: URL, decoded: Bool) -> Bool { + !decoded && FileManager.default.fileExists(atPath: file.path) + } +} +#endif diff --git a/Sources/AgentTermHost/StatusLineRelay.swift b/Sources/AgentTermHost/StatusLineRelay.swift index 2c17dafc..a321af90 100644 --- a/Sources/AgentTermHost/StatusLineRelay.swift +++ b/Sources/AgentTermHost/StatusLineRelay.swift @@ -38,9 +38,28 @@ public enum StatusLineRelay { } let project = (object?["workspace"] as? [String: Any])?["project_dir"] as? String ?? object?["cwd"] as? String let kept = previous.flatMap { FileManager.default.contents(atPath: $0.path) }.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } - guard let command = (kept?["command"] as? String).flatMap({ $0.isEmpty ? nil : $0 }) ?? userCommand(project: project, home: home, environment: environment) + // Another build's relay, which this one took the place of (MCP-15), + // is run once; a relay it runs runs only the user's, never a relay + // again: two builds that keep each other's would run without end + // (#259). + let relayed = environment[relayedVariable] != nil + let keptCommand = (kept?["command"] as? String).flatMap { $0.isEmpty || (relayed && isAgentTerms($0)) ? nil : $0 } + guard let command = keptCommand ?? userCommand(project: project, home: home, environment: environment) else { return Data() } - return pipe(input, through: command) + return pipe(input, through: command, relaying: isAgentTerms(command), environment: environment) + } + + /// Set for a relay that another relay runs: it then runs no relay + /// itself (#259). The one name every build reads, on purpose (the + /// owner's decision, 2026-11-23): it is what stops two builds' relays + /// running each other, and names nothing of either. + public static let relayedVariable = "AGENTTERM_STATUS_LINE_RELAYED" + + /// Whether a status line command is AgentTerm's relay, of any build: + /// `agenttermd … statusline`, with the file to save in after it or not. + public static func isAgentTerms(_ command: String) -> Bool { + let command = command.trimmingCharacters(in: .whitespacesAndNewlines) + return command.contains("agenttermd") && (command.hasSuffix(" statusline") || command.contains(" statusline ")) } /// Where the relay says why it could not save what it was given, next @@ -63,32 +82,18 @@ public enum StatusLineRelay { let command = statusLine["command"] as? String, !command.isEmpty else { continue } // Never ourselves: that would run without end. - if command.contains("agenttermd") && command.contains("statusline") { continue } + if isAgentTerms(command) { continue } return command } return nil } - private static func pipe(_ input: Data, through command: String) -> Data { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/bin/sh") - process.arguments = ["-c", command] - let stdin = Pipe(), stdout = Pipe() - process.standardInput = stdin - process.standardOutput = stdout - process.standardError = FileHandle.nullDevice - do { try process.run() } catch { return Data() } - // A status line that hangs must not hang Claude Code's. - let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } } - DispatchQueue.global().asyncAfter(deadline: .now() + 5, execute: timeout) - DispatchQueue.global().async { - try? stdin.fileHandleForWriting.write(contentsOf: input) - try? stdin.fileHandleForWriting.close() - } - let output = stdout.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - timeout.cancel() - return output + private static func pipe(_ input: Data, through command: String, relaying: Bool, environment: [String: String]) -> Data { + var environment = environment + if relaying { environment[relayedVariable] = "1" } + // A status line that hangs must not hang Claude Code's: five seconds, + // for the command and all it started (#261). + return Subprocess.run("/bin/sh", ["-c", command], timeout: 5, environment: environment, input: input, forTheHost: false)?.output ?? Data() } /// What Claude Code told the status line, as usage. diff --git a/Sources/AgentTermHost/Tailscale.swift b/Sources/AgentTermHost/Tailscale.swift index d5786204..3e2f4755 100644 --- a/Sources/AgentTermHost/Tailscale.swift +++ b/Sources/AgentTermHost/Tailscale.swift @@ -42,19 +42,38 @@ public enum Tailscale { public static func status() -> TailscaleStatus { var backendState: String? var dnsName: String? - if let cli, let result = Subprocess.run(cli, ["status", "--json"], timeout: 4), - let json = try? JSONSerialization.jsonObject(with: result.output) as? [String: Any] - { + var own: Set? + if let json = askedStatus() { backendState = json["BackendState"] as? String dnsName = (json["Self"] as? [String: Any])?["DNSName"] as? String + own = Set(json["TailscaleIPs"] as? [String] ?? []) } - return status(installed: isInstalled, backendState: backendState, address: ipv4Address(), dnsName: dnsName) + let installed = isInstalled + return status(installed: installed, backendState: backendState, address: address(among: addressesInRange(), own: own, installed: installed), dnsName: dnsName) + } + + /// What `tailscale status --json` says (Tailscale 1.104.7 has + /// `BackendState`, `Self.DNSName` and `TailscaleIPs`); nil when its + /// command is not there or does not answer. + private static func askedStatus() -> [String: Any]? { + guard let cli, let result = Subprocess.run(cli, ["status", "--json"], timeout: 4), result.status == 0 else { return nil } + return try? JSONSerialization.jsonObject(with: result.output) as? [String: Any] + } + + /// The addresses Tailscale itself says are this Mac's; nil when it + /// could not be asked. Runs its command: off the host's queue. + public static func ownAddresses() -> Set? { + askedStatus().map { Set($0["TailscaleIPs"] as? [String] ?? []) } } /// The decision behind `status()`, separated from the system calls. static func status(installed: Bool, backendState: String?, address: String?, dnsName: String?) -> TailscaleStatus { - // An address in Tailscale's range is proof enough of a working - // connection, even where the CLI cannot be found or asked. + // No Tailscale on the Mac: an address in its range is someone + // else's, a carrier's or another VPN's (#268). + guard installed else { return .notInstalled } + // An address Tailscale's own, or on a tunnel of a Mac with Tailscale, + // is proof enough of a working connection, even where the CLI + // cannot be asked. if let address, backendState == nil || backendState == "Running" { let name = dnsName.map { $0.hasSuffix(".") ? String($0.dropLast()) : $0 } return .ready(host: name?.isEmpty == false ? name! : address) @@ -63,11 +82,30 @@ public enum Tailscale { return backendState == "NeedsLogin" ? .needsLogin : .notConnected } - /// The Mac's address in the Tailscale range 100.64.0.0/10, if it is connected. - public static func ipv4Address() -> String? { + /// The Mac's Tailscale address, if it is connected: one in the range + /// 100.64.0.0/10 that Tailscale says is its own (`own`, from + /// `ownAddresses()`), or when Tailscale cannot be asked, the first on a + /// tunnel (`utun`) of a Mac that has Tailscale (#268). + public static func ipv4Address(own: Set? = nil) -> String? { + address(among: addressesInRange(), own: own, installed: isInstalled) + } + + /// The decision behind `ipv4Address`: never an address of an interface + /// that is not a tunnel (a carrier's), nor on a Mac without Tailscale, + /// nor, once Tailscale was asked, one it does not say is its own + /// (another VPN's tunnel, Cloudflare WARP's). + static func address(among found: [(interface: String, address: String)], own: Set?, installed: Bool) -> String? { + if let own { return found.first { own.contains($0.address) }?.address } + guard installed else { return nil } + return found.first { $0.interface.hasPrefix("utun") }?.address + } + + /// The interfaces that are up with an IPv4 address in 100.64.0.0/10. + static func addressesInRange() -> [(interface: String, address: String)] { var list: UnsafeMutablePointer? - guard getifaddrs(&list) == 0 else { return nil } + guard getifaddrs(&list) == 0 else { return [] } defer { freeifaddrs(list) } + var found: [(interface: String, address: String)] = [] var cursor = list while let entry = cursor { defer { cursor = entry.pointee.ifa_next } @@ -76,10 +114,10 @@ public enum Tailscale { else { continue } let raw = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { UInt32(bigEndian: $0.pointee.sin_addr.s_addr) } if raw & 0xFFC0_0000 == 0x6440_0000 { - return "\(raw >> 24).\((raw >> 16) & 0xff).\((raw >> 8) & 0xff).\(raw & 0xff)" + found.append((String(cString: entry.pointee.ifa_name), "\(raw >> 24).\((raw >> 16) & 0xff).\((raw >> 8) & 0xff).\(raw & 0xff)")) } } - return nil + return found } /// The Mac's MagicDNS name, e.g. "macbook.tail1234.ts.net". Needs the diff --git a/Sources/AgentTermMac/AgentTermApp.swift b/Sources/AgentTermMac/AgentTermApp.swift index 0c0421b3..5b519cd7 100644 --- a/Sources/AgentTermMac/AgentTermApp.swift +++ b/Sources/AgentTermMac/AgentTermApp.swift @@ -679,6 +679,29 @@ struct SettingsCard: View { } final class AppDelegate: NSObject, NSApplicationDelegate { + /// The window's model, for what quitting has to ask. + @MainActor weak static var model: AppModel? + + /// Quitting, by ⌘Q or by closing the window, with unsaved changes in + /// the open files asks first (#298): they would be lost. Closing a file, + /// switching Mac and forgetting one ask the same way. + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + MainActor.assumeIsolated { + let unsaved = Self.model?.files.documents.filter(\.isDirty).map { ($0.path as NSString).lastPathComponent } ?? [] + guard !unsaved.isEmpty else { return .terminateNow } + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = unsaved.count == 1 ? "Quit without saving \(unsaved[0])?" : "Quit without saving \(unsaved.count) files?" + alert.informativeText = + (unsaved.count == 1 ? "Its changes are lost." : "Their changes are lost: \(unsaved.joined(separator: ", ")).") + + " Cancel, then save them from the Files tab." + alert.addButton(withTitle: "Cancel") + alert.addButton(withTitle: "Quit Without Saving") + alert.buttons[1].hasDestructiveAction = true + return alert.runModal() == .alertSecondButtonReturn ? .terminateNow : .terminateCancel + } + } + func applicationDidFinishLaunching(_ notification: Notification) { // Needed when started with `swift run` instead of from an app bundle. NSApp.setActivationPolicy(.regular) diff --git a/Sources/AgentTermMac/AppModel.swift b/Sources/AgentTermMac/AppModel.swift index 879e5fa8..b0512515 100644 --- a/Sources/AgentTermMac/AppModel.swift +++ b/Sources/AgentTermMac/AppModel.swift @@ -1211,6 +1211,8 @@ final class AppModel: ObservableObject { private var pendingFolderSelection: String? init() { + // For the question before quitting with unsaved changes (#298). + AppDelegate.model = self if let value = ProcessInfo.processInfo.environment["AGENTTERM_PORT"].flatMap(UInt16.init) { port = value } // The Mac that was on screen last time is the one to come back to. if let last = UserDefaults.standard.string(forKey: Self.currentMacKey), let mac = remoteMacs.first(where: { $0.id == last }) { @@ -2400,6 +2402,7 @@ final class AppModel: ObservableObject { // MARK: Changes private func folderChanged() { + closeGitQuestions() diff = nil watchPanelFolder() if let selectedFolder { listWorktrees(selectedFolder) } @@ -2412,6 +2415,23 @@ final class AppModel: ObservableObject { refreshHistory(ofFolder: true) } + /// A git action asked about in the folder that was on show is never + /// done in the one on show now (#297): every such question is closed, + /// and that is said. + private func closeGitQuestions() { + let open = discarding != nil || pendingCommitAction != nil || droppingStash != nil || deletingBranch != nil || confirmingAbort || pendingRewrite != nil + discarding = nil + discardingIn = nil + pendingCommitAction = nil + droppingStash = nil + deletingBranch = nil + confirmingAbort = false + pendingRewrite = nil + rewriteAskedAgain?.cancel() + rewriteAskedAgain = nil + if open { notice = GitQuestionWords.closedForAnotherFolder } + } + // MARK: Handoff /// Agents a conversation of `agent` can be handed to. @@ -3281,6 +3301,8 @@ final class AppModel: ObservableObject { @Published private(set) var amending: [String: LastCommit] = [:] /// Undoing or amending that waits to be confirmed. @Published var pendingRewrite: PendingRewrite? + /// The second question about undoing a pushed commit, on its way. + private var rewriteAskedAgain: DispatchWorkItem? struct PendingRewrite: Identifiable { let action: RewriteCommitQuestion.Action @@ -3296,7 +3318,11 @@ final class AppModel: ObservableObject { private func withLastCommit(_ then: @escaping (LastCommit) -> Void) { guard let directory = panelFolder else { return } if isRemote { - lastCommitWanted = then + // The answer, for this folder only (#297). + lastCommitWanted = { [weak self] last in + guard self?.panelFolder == directory else { return } + then(last) + } connection?.send(.gitLastCommit(path: directory)) return } @@ -3350,9 +3376,12 @@ final class AppModel: ObservableObject { if pending.last.isPushed && !pending.again { // After the dialog has gone: one that is presented while // another closes is not shown. - DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in + let again = DispatchWorkItem { [weak self] in self?.pendingRewrite = PendingRewrite(action: .undo, last: pending.last, again: true) } + // Not asked again in another folder (#297). + rewriteAskedAgain = again + DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: again) return } guard let directory = panelFolder else { return } diff --git a/Sources/AgentTermMac/BrowserAgent.swift b/Sources/AgentTermMac/BrowserAgent.swift index 4ee9d3ac..247bb8e4 100644 --- a/Sources/AgentTermMac/BrowserAgent.swift +++ b/Sources/AgentTermMac/BrowserAgent.swift @@ -583,6 +583,9 @@ extension AppModel { if devtools.document != before || tab.loading { await devtools.waitForLoad(seconds: 15) } return .text("Pressed \(key). Now" + (await self.whereNow(tab))) case .scroll(_, let ref, let x, let y): + // As the agent's server takes them (#249), whoever asked. + func bounded(_ delta: Double) -> Double { delta.isFinite ? min(max(delta, -100_000), 100_000) : 0 } + let x = bounded(x), y = bounded(y) let point: CGPoint if let ref { point = try await devtools.center(of: try devtools.node(for: ref)) @@ -594,9 +597,12 @@ extension AppModel { try await devtools.mouse("mouseWheel", at: point, deltaX: x, deltaY: y) done("Scrolled") try? await Task.sleep(nanoseconds: 250_000_000) - return .text("Scrolled by \(Int(x)), \(Int(y)).") + return .text("Scrolled by \(Int(saturating: x)), \(Int(saturating: y)).") case .wait(_, let text, let gone, let seconds): - let deadline = Date().addingTimeInterval(min(max(seconds, 0), 600)) + // Numbers from a request, which may not have come through the + // agent's server, that checks them (#249). + let seconds = seconds.isFinite ? min(max(seconds, 0), 600) : 0 + let deadline = Date().addingTimeInterval(seconds) while Date() < deadline { if Task.isCancelled { break } let page = await devtools.pageText() @@ -605,7 +611,7 @@ extension AppModel { if text == nil, gone == nil, devtools.loaded || !tab.loading { return .text("The page has loaded" + (await self.whereNow(tab))) } try? await Task.sleep(nanoseconds: 250_000_000) } - return .text("Still waiting after \(Int(seconds)) seconds; the page" + (await self.whereNow(tab))) + return .text("Still waiting after \(Int(saturating: seconds)) seconds; the page" + (await self.whereNow(tab))) case .evaluate(_, let script): done("Ran a script") return .text(try await devtools.evaluate(script)) diff --git a/Sources/AgentTermProtocol/History.swift b/Sources/AgentTermProtocol/History.swift index 73752208..ec9942b7 100644 --- a/Sources/AgentTermProtocol/History.swift +++ b/Sources/AgentTermProtocol/History.swift @@ -90,7 +90,7 @@ public struct ConversationDetails: Codable, Equatable, Sendable { /// "2 h 5 min", "12 min", "40 s". public static func words(for duration: TimeInterval) -> String { - let seconds = Int(duration.rounded()) + let seconds = Int(saturating: duration.rounded()) if seconds < 60 { return "\(seconds) s" } let minutes = seconds / 60 if minutes < 60 { return "\(minutes) min" } @@ -254,7 +254,7 @@ public struct HistoryFilter: Equatable, Sendable { byDay[day, default: []].append(conversation) } for day in order { - groups.append(Group(id: "day:\(Int(day.timeIntervalSince1970))", title: Self.title(of: day, now: now, calendar: calendar), conversations: byDay[day] ?? [])) + groups.append(Group(id: "day:\(Int(saturating: day.timeIntervalSince1970))", title: Self.title(of: day, now: now, calendar: calendar), conversations: byDay[day] ?? [])) } } return groups diff --git a/Sources/AgentTermProtocol/Messages.swift b/Sources/AgentTermProtocol/Messages.swift index f1a50fa7..2bbdea28 100644 --- a/Sources/AgentTermProtocol/Messages.swift +++ b/Sources/AgentTermProtocol/Messages.swift @@ -775,20 +775,30 @@ public enum ServerMessage: Codable, Equatable, Sendable { } public enum MessageCoding { + /// A number that is no number, or infinite, which JSON has no way to + /// write, is written as text, and read back (#292): a figure of the Mac + /// that came out so would otherwise make the whole message nothing. + private static let numbers = (infinity: "Infinity", minusInfinity: "-Infinity", notANumber: "NaN") + private static let encoder: JSONEncoder = { let e = JSONEncoder() e.dateEncodingStrategy = .secondsSince1970 + e.nonConformingFloatEncodingStrategy = .convertToString( + positiveInfinity: numbers.infinity, negativeInfinity: numbers.minusInfinity, nan: numbers.notANumber) return e }() private static let decoder: JSONDecoder = { let d = JSONDecoder() d.dateDecodingStrategy = .secondsSince1970 + d.nonConformingFloatDecodingStrategy = .convertFromString( + positiveInfinity: numbers.infinity, negativeInfinity: numbers.minusInfinity, nan: numbers.notANumber) return d }() public static func encode(_ value: T) -> Data { - // Encoding these plain value types cannot fail. + // With numbers that are no numbers written as text, these plain + // value types are always encoded. (try? encoder.encode(value)) ?? Data() } diff --git a/Sources/AgentTermProtocol/Notice.swift b/Sources/AgentTermProtocol/Notice.swift index c8ac295a..2dce5613 100644 --- a/Sources/AgentTermProtocol/Notice.swift +++ b/Sources/AgentTermProtocol/Notice.swift @@ -62,8 +62,11 @@ public struct Notice: Codable, Equatable, Sendable, Identifiable { /// How long the host keeps them, and a device's Inbox too. public static let kept: TimeInterval = 30 * 24 * 3600 - /// Handled in a way that means it was looked at: read too. - public static func reads(_ how: Handled.How) -> Bool { how != .movedOn } + /// Whether being handled so makes it read: every way does (#321, the + /// owner's decision of 2026-11-23), moving on too. An agent that + /// waits goes on only once someone answered it, often in its session; + /// one that asks something else has a notice of its own for that. + public static func reads(_ how: Handled.How) -> Bool { true } /// What a notice about an agent says and offers: the words of #22. public var agentNotice: AgentNotice? { @@ -78,6 +81,19 @@ public struct Notice: Codable, Equatable, Sendable, Identifiable { /// Whether it is a notification too, or a banner and an Inbox item /// only: every agent's, and a failure that stopped work. + /// How long an agent's notice waits before it is a notification, on + /// the iPhone and the Mac (#322, the owner's decision of 2026-11-23): + /// one the user acted on meanwhile is handled, and none is shown. + public static let alertDelay: TimeInterval = 10 + + /// Whether its notification waits `alertDelay`: an agent's does; a + /// failure that stopped work, which nothing the user does takes away, + /// is shown at once. + public var waitsToAlert: Bool { + if case .agent = kind { return true } + return false + } + public var alerts: Bool { switch kind { case .agent: return true @@ -174,11 +190,16 @@ public enum NoticeWords { /// sentences for the user; these few are codes. public enum HostErrorWords { public static let olderHost = "The AgentTerm on the Mac is from an older release and cannot do this. Update it, and restart its host." + /// What a client says, once a connection, when the host sent something + /// it could not read (#292); it goes on with what it can. + public static let unreadableMessage = "unreadable message" + public static let unreadable = "Something the Mac sent could not be read, so what it said is not shown. Restart the host if something looks wrong." public static func words(for text: String) -> String { switch text { case "malformed message": return olderHost case "not allowed": return "Only the Mac's own app can do this." + case unreadableMessage: return unreadable default: return text } } diff --git a/Sources/AgentTermProtocol/Numbers.swift b/Sources/AgentTermProtocol/Numbers.swift new file mode 100644 index 00000000..cac0cf2b --- /dev/null +++ b/Sources/AgentTermProtocol/Numbers.swift @@ -0,0 +1,17 @@ +extension Int { + /// The whole number nearest below `value` that an `Int` holds: the + /// largest or the smallest one past them, 0 for not a number. For what + /// is shown of a number a peer sent, which `Int(_:)` would stop the app + /// on when it is out of range (#296). + public init(saturating value: Double) { + if value.isNaN { + self = 0 + } else if value >= Double(Int.max) { + self = .max + } else if value <= Double(Int.min) { + self = .min + } else { + self = Int(value) + } + } +} diff --git a/Sources/AgentTermProtocol/PartFailure.swift b/Sources/AgentTermProtocol/PartFailure.swift index 15b11b63..82dbf4bc 100644 --- a/Sources/AgentTermProtocol/PartFailure.swift +++ b/Sources/AgentTermProtocol/PartFailure.swift @@ -31,6 +31,10 @@ public struct PartFailure: Codable, Equatable, Identifiable, Sendable { /// A notice that could not be sent through Apple to a device /// (`name`) while it was away (#66): `reason` says why. public static let push = Part(rawValue: "push") + /// A file of what the host keeps (`name`: its schedules, its paired + /// devices, its settings) that it could not read (#273): put aside, + /// `reason` says where, and the host started without what it held. + public static let savedState = Part(rawValue: "savedState") } /// Names this report, for `dismissFailure`. @@ -111,6 +115,8 @@ extension PartFailure { return "A run of the schedule \(named)\(onMac) did not go as planned \(when)." case .push: return "A notification to \(name.map { "“\($0)”" } ?? "a device") could not be sent through Apple\(onMac) \(when)." + case .savedState: + return "The host\(onMac) could not read its \(name ?? "saved state") \(when), and started without them." default: // A part this build does not know yet. what = "A part of AgentTerm (\(part.rawValue)\(name.map { ", \($0)" } ?? ""))\(mac.map { " on \($0)" } ?? "")" @@ -126,7 +132,7 @@ extension PartFailure { public var details: String { var parts: [String] = [] switch part { - case .keepAwake, .statusLine, .schedule, .push: + case .keepAwake, .statusLine, .schedule, .push, .savedState: // Nothing ends with these: what they are for stops. break case .session: diff --git a/Sources/AgentTermProtocol/Push.swift b/Sources/AgentTermProtocol/Push.swift index 93733f88..dd501cce 100644 --- a/Sources/AgentTermProtocol/Push.swift +++ b/Sources/AgentTermProtocol/Push.swift @@ -96,6 +96,36 @@ public struct PushNotice: Codable, Equatable, Sendable { title = String(failure.headline().prefix(200)) body = String(failure.details.prefix(600)) } + fitInAPush() + } + + /// How many bytes of JSON a notice may be: sealed (a nonce and a tag + /// of 28 bytes) and in base64, at most the relay's 3,000 characters. + public static let mostBytes = 2_200 + + /// Shortens what it says until it is no more than `mostBytes` of JSON + /// (#294): the lengths above are in characters, and a character of + /// Japanese or Chinese is three bytes. Each round keeps of every text + /// the share that would fit, so none is cut much more than the others. + private mutating func fitInAPush() { + for _ in 0..<8 { + guard let size = try? JSONEncoder().encode(self).count, size > Self.mostBytes else { return } + let share = Double(Self.mostBytes) / Double(size) * 0.95 + func cut(_ text: String) -> String { String(text.prefix(Int(Double(text.count) * share))) } + name = cut(name) + folder = String(folder.suffix(Int(Double(folder.count) * share))) + title = title.map(cut) + body = body.map(cut) + if let shortened = state { + func question(_ asked: AgentQuestion) -> AgentQuestion { AgentQuestion(text: cut(asked.text), choices: asked.choices.map(cut)) } + switch shortened { + case .done(let said): state = .done(said: said.map { String($0.suffix(Int(Double($0.count) * share))) }) + case .waitingForPermission(let asked): state = .waitingForPermission(question(asked)) + case .waitingForAnswer(let asked): state = .waitingForAnswer(question(asked)) + case .working: break + } + } + } } /// What an agent's notice says and offers, with the shortened state; diff --git a/Sources/AgentTermProtocol/Schedule.swift b/Sources/AgentTermProtocol/Schedule.swift index 5e03f534..91889ea8 100644 --- a/Sources/AgentTermProtocol/Schedule.swift +++ b/Sources/AgentTermProtocol/Schedule.swift @@ -190,21 +190,28 @@ public enum ScheduleTime: Codable, Equatable, Hashable, Sendable { case .daily(let hour, let minute): return calendar.nextDate(after: date, matching: DateComponents(hour: hour, minute: minute), matchingPolicy: .nextTime) case .weekly(let weekdays, let hour, let minute): - return weekdays.compactMap { + return weekdays.filter(Self.weekdays.contains).compactMap { calendar.nextDate(after: date, matching: DateComponents(hour: hour, minute: minute, weekday: $0), matchingPolicy: .nextTime) }.min() case .limitReset: return nil case .every(let minutes, let from, let until): let step = max(minutes, 1) - let first = min(max(from ?? 0, 0), 24 * 60 - 1) - let last = min(max(until ?? 24 * 60 - 1, first), 24 * 60 - 1) - // Today's and then tomorrow's: the day after has one for sure. - for offset in 0...2 { - guard let day = calendar.date(byAdding: .day, value: offset, to: calendar.startOfDay(for: date)) else { continue } + let day = 24 * 60 + let first = min(max(from ?? 0, 0), day - 1) + var last = min(max(until ?? day - 1, 0), day - 1) + // A window that ends before it starts goes on past midnight, to + // that time of the next day, as its label says (#290). + if last < first { last += day } + // Yesterday's, whose end may be this morning, today's, then + // tomorrow's: the day after has one for sure. + for offset in -1...2 { + guard let start = calendar.date(byAdding: .day, value: offset, to: calendar.startOfDay(for: date)) else { continue } var minute = first while minute <= last { - if let moment = calendar.date(bySettingHour: minute / 60, minute: minute % 60, second: 0, of: day), moment > date { return moment } + let of = minute < day ? start : calendar.date(byAdding: .day, value: 1, to: start) + let time = minute % day + if let of, let moment = calendar.date(bySettingHour: time / 60, minute: time % 60, second: 0, of: of), moment > date { return moment } minute += step } } @@ -220,6 +227,19 @@ public enum ScheduleTime: Codable, Equatable, Hashable, Sendable { return minutes == 1 ? "minute" : "\(minutes) minutes" } + /// The days of the week, 1 Sunday to 7 Saturday, as `weekly` names them. + public static let weekdays = 1...7 + + /// Why the host refuses a weekly schedule with no day, or with a day + /// out of `weekdays` (#291). + public static let daysRefusal = "Pick the days of the week it runs on, from Sunday to Saturday." + + /// Why this time cannot be saved, nil when it can. + public var refusal: String? { + if case .weekly(let weekdays, _, _) = self, weekdays.isEmpty || !weekdays.allSatisfy(Self.weekdays.contains) { return Self.daysRefusal } + return nil + } + /// In words: "Every day at 09:00", "Mon, Wed at 18:30". public func label(calendar: Calendar = .current) -> String { func time(_ hour: Int, _ minute: Int) -> String { String(format: "%02d:%02d", hour, minute) } @@ -227,7 +247,8 @@ public enum ScheduleTime: Codable, Equatable, Hashable, Sendable { case .once(let moment): return "Once, \(moment.formatted(date: .abbreviated, time: .shortened))" case .daily(let hour, let minute): return "Every day at \(time(hour, minute))" case .weekly(let weekdays, let hour, let minute): - let names = weekdays.sorted().map { calendar.shortWeekdaySymbols[($0 - 1 + 7) % 7] } + // Only days that are days: one out of 1...7 is refused (#291). + let names = weekdays.filter(Self.weekdays.contains).sorted().map { calendar.shortWeekdaySymbols[$0 - 1] } return "\(names.joined(separator: ", ")) at \(time(hour, minute))" case .limitReset: return "When the account's limit starts over" case .every(let minutes, let from, let until): @@ -366,7 +387,7 @@ public struct ScheduleOverview: Sendable { /// To the millisecond: a moment written into a message as seconds /// since 1970 and read again can come out a fraction of a /// microsecond off, and is still the same run. - public static func id(schedule: String, at: Date) -> String { schedule + "@" + String(Int((at.timeIntervalSince1970 * 1000).rounded())) } + public static func id(schedule: String, at: Date) -> String { schedule + "@" + String(Int(saturating: (at.timeIntervalSince1970 * 1000).rounded())) } } public let running: [Run] diff --git a/Sources/AgentTermProtocol/SentText.swift b/Sources/AgentTermProtocol/SentText.swift index 275066c8..ba07d3af 100644 --- a/Sources/AgentTermProtocol/SentText.swift +++ b/Sources/AgentTermProtocol/SentText.swift @@ -32,7 +32,23 @@ public enum SentText { // the one way. guard bracketedPaste, lines.contains("\r") || text.count > typedLength else { return lines } // The end of a paste inside it would end it early, and what follows - // would be taken as typed. - return pasteStart + lines.replacingOccurrences(of: pasteEnd, with: "") + pasteEnd + // would be taken as typed: no Escape goes in, nor any other control + // character but a tab and the ends of lines, so none can be made of + // what is left either (#248). Text from a page or a file's name may + // hold them. + var kept = lines + while kept.contains(pasteEnd) { kept = kept.replacingOccurrences(of: pasteEnd, with: "") } + kept = String(String.UnicodeScalarView(kept.unicodeScalars.filter(Self.goesInAPaste))) + return pasteStart + kept + pasteEnd + } + + /// Whether a character is pasted: none of C0 but tab and Return, nor + /// Delete, nor C1. + static func goesInAPaste(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 0x09, 0x0D: return true + case 0x00...0x1F, 0x7F...0x9F: return false + default: return true + } } } diff --git a/Sources/AgentTermProtocol/Settings.swift b/Sources/AgentTermProtocol/Settings.swift index af5deb36..7daa0898 100644 --- a/Sources/AgentTermProtocol/Settings.swift +++ b/Sources/AgentTermProtocol/Settings.swift @@ -154,7 +154,7 @@ public struct SystemStats: Codable, Equatable, Sendable { public static func speed(_ bytesPerSecond: UInt64) -> String { let kilobytes = Double(bytesPerSecond) / 1024 if kilobytes >= 1000 { return String(format: "%.1f MB/s", kilobytes / 1024) } - return "\(Int(kilobytes.rounded())) KB/s" + return "\(Int(saturating: kilobytes.rounded())) KB/s" } /// The key both apps keep the choice of unit under, and its two values. @@ -169,7 +169,7 @@ public struct SystemStats: Codable, Equatable, Sendable { /// measures in Celsius; the unit is how an app shows it. public func temperatureText(unit: String) -> String { if let temperature { - return unit == Self.fahrenheit ? "\(Int((temperature * 9 / 5 + 32).rounded()))°F" : "\(Int(temperature.rounded()))°C" + return unit == Self.fahrenheit ? "\(Int(saturating: (temperature * 9 / 5 + 32).rounded()))°F" : "\(Int(saturating: temperature.rounded()))°C" } switch thermalState { case "fair": return "Warm" @@ -184,7 +184,7 @@ public struct SystemStats: Codable, Equatable, Sendable { /// "3d 4h", "5h 12m", "8m". public static func uptime(since bootedAt: Date, now: Date = Date()) -> String { - let minutes = max(0, Int(now.timeIntervalSince(bootedAt)) / 60) + let minutes = max(0, Int(saturating: now.timeIntervalSince(bootedAt)) / 60) if minutes >= 1440 { return "\(minutes / 1440)d \(minutes % 1440 / 60)h" } if minutes >= 60 { return "\(minutes / 60)h \(minutes % 60)m" } return "\(minutes)m" diff --git a/Sources/AgentTermProtocol/Usage.swift b/Sources/AgentTermProtocol/Usage.swift index 82fdb442..ee60bccd 100644 --- a/Sources/AgentTermProtocol/Usage.swift +++ b/Sources/AgentTermProtocol/Usage.swift @@ -159,6 +159,6 @@ public struct AccountUsage: Codable, Equatable, Identifiable, Sendable { /// "55% used" or "45% left", the way the agent says it. public func percentText(_ limit: AccountLimit) -> String { - showsRemaining ? "\(Int(limit.leftPercent.rounded()))% left" : "\(Int(limit.usedPercent.rounded()))% used" + showsRemaining ? "\(Int(saturating: limit.leftPercent.rounded()))% left" : "\(Int(saturating: limit.usedPercent.rounded()))% used" } } diff --git a/Sources/AgentTermProtocol/Workspace.swift b/Sources/AgentTermProtocol/Workspace.swift index fbe87187..87dc22fd 100644 --- a/Sources/AgentTermProtocol/Workspace.swift +++ b/Sources/AgentTermProtocol/Workspace.swift @@ -374,6 +374,16 @@ public struct CommitGraphRow: Equatable, Sendable { /// The numbers of the Git side panel with what they count beside them /// (#50), the same on the Mac and the iPhone: a number alone said nothing /// to the owner. +/// What both apps say about the git actions they ask about first. +public enum GitQuestionWords { + /// A question about discarding, reverting, dropping a stash, deleting a + /// branch, aborting or rewriting a commit, closed because the folder on + /// show changed while it was open (#297): it is never answered in + /// another folder. + public static let closedForAnotherFolder = + "The question was closed and nothing was done: another folder is on show now. Ask again in the folder you meant." +} + public enum CountWords { /// "1 file", "3 files": the files of a list of changes. public static func files(_ count: Int) -> String { "\(count) \(count == 1 ? "file" : "files")" } diff --git a/Sources/AgentTermTerminal/AnsweringTerminalView.swift b/Sources/AgentTermTerminal/AnsweringTerminalView.swift new file mode 100644 index 00000000..4cf79843 --- /dev/null +++ b/Sources/AgentTermTerminal/AnsweringTerminalView.swift @@ -0,0 +1,29 @@ +import Foundation +import SwiftTerm + +/// A terminal view that tells what its emulator answers apart from what the +/// user types (#293). Both reach the terminal's delegate as bytes to send; +/// here the emulator's answers (which terminal it is, where the cursor is) +/// go to `onAnswer` instead, so that a replay of what a session once asked +/// its terminal can hold back only those, never a key the user typed +/// meanwhile. +open class AnsweringTerminalView: TerminalView { + /// What the emulator answers, on the main thread, in order. + public final var onAnswer: (@MainActor (Data) -> Void)? + + nonisolated open override func send(source: Terminal, data: ArraySlice) { + let bytes = Data(data) + // On the main thread after what was fed before it, as the view + // itself sends it on. + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { + guard let self else { return } + if let onAnswer = self.onAnswer { + onAnswer(bytes) + } else { + self.terminalDelegate?.send(source: self, data: ArraySlice([UInt8](bytes))) + } + } + } + } +} diff --git a/Sources/AgentTermTerminal/FilesIntoTerminal.swift b/Sources/AgentTermTerminal/FilesIntoTerminal.swift index db9b0a6b..c4c349d4 100644 --- a/Sources/AgentTermTerminal/FilesIntoTerminal.swift +++ b/Sources/AgentTermTerminal/FilesIntoTerminal.swift @@ -9,7 +9,7 @@ import SwiftTerm /// submitted. A picture on the clipboard, a screenshot say, is not a file: /// ⌘V sends Control V, with which an agent such as Claude Code takes the /// clipboard's picture itself. Nothing is saved. -public final class FileTakingTerminalView: TerminalView { +public final class FileTakingTerminalView: AnsweringTerminalView { /// Says why nothing was typed, where nothing else would. public var refused: ((String) -> Void)? /// Whether this Mac's files and clipboard mean anything to the session: diff --git a/Sources/AgentTermTerminal/SplitDiffView.swift b/Sources/AgentTermTerminal/SplitDiffView.swift index 56799b6e..de1a9056 100644 --- a/Sources/AgentTermTerminal/SplitDiffView.swift +++ b/Sources/AgentTermTerminal/SplitDiffView.swift @@ -65,9 +65,10 @@ struct SplitDiffTexts: @unchecked Sendable { /// main thread. /// - lineHeight: The font's own line height, measured there too. init(patch: String, fontSize: CGFloat, advance: CGFloat, lineHeight: CGFloat) { - // Tabs as four blanks: a diff's lines start with a mark, which - // would put every tab stop one off. - let all = SplitDiff.rows(for: patch.replacingOccurrences(of: "\t", with: " ")) + // Tabs stay tabs, so that what is copied is the file's own (#295): + // their stops are every four characters from where the line's text + // starts, past the line's number. + let all = SplitDiff.rows(for: patch) rows = all.count let font = Self.font(fontSize) let height = Self.rowHeight(fontSize) @@ -80,6 +81,9 @@ struct SplitDiffTexts: @unchecked Sendable { style.maximumLineHeight = height style.firstLineHeadIndent = indent style.headIndent = indent + let tab = CGFloat(Self.tabWidth) * advance + style.tabStops = (1...Self.tabStopsSet).map { NSTextTab(textAlignment: .left, location: indent + CGFloat($0) * tab) } + style.defaultTabInterval = tab // Never wrapped: a row is one line on both sides, or they would // stop facing each other. style.lineBreakMode = .byClipping @@ -124,8 +128,17 @@ struct SplitDiffTexts: @unchecked Sendable { /// How many columns a line takes: two for a wide character, so that a /// line of them is not cut short. + /// How many characters apart a tab's stops are. + static let tabWidth = 4 + /// How many stops are set from where a line's text starts; past them a + /// tab goes to the next of the default interval. + static let tabStopsSet = 64 + static func columns(_ text: String) -> Int { - text.unicodeScalars.reduce(0) { $0 + ($1.value >= 0x1100 ? 2 : 1) } + text.unicodeScalars.reduce(0) { count, scalar in + if scalar == "\t" { return (count / tabWidth + 1) * tabWidth } + return count + (scalar.value >= 0x1100 ? 2 : 1) + } } /// How wide a character of the font is, and its line height: measured diff --git a/Sources/AgentTermTerminal/TerminalController.swift b/Sources/AgentTermTerminal/TerminalController.swift index 30135f17..47032dfd 100644 --- a/Sources/AgentTermTerminal/TerminalController.swift +++ b/Sources/AgentTermTerminal/TerminalController.swift @@ -37,9 +37,15 @@ public final class TerminalController: NSObject, TerminalViewDelegate { // Takes files dropped or pasted on it (#160). view = FileTakingTerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 500)) #else - view = TerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 500)) + view = AnsweringTerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 500)) #endif super.init() + // The emulator's answers are held back during a replay; what the + // user types never is (#293). + (view as? AnsweringTerminalView)?.onAnswer = { [weak self] bytes in + guard let self, !self.isReplayAnswer(bytes) else { return } + self.onInput?(bytes) + } view.font = TerminalStyle.font(size: fontSize) view.nativeBackgroundColor = TerminalStyle.background view.nativeForegroundColor = TerminalStyle.foreground @@ -381,12 +387,11 @@ public final class TerminalController: NSObject, TerminalViewDelegate { } } + /// What the user typed, pasted or did with the mouse: sent on also + /// during a replay. The emulator's answers come by `onAnswer`. public nonisolated func send(source: TerminalView, data: ArraySlice) { let bytes = Data(data) - MainActor.assumeIsolated { - guard !isReplayAnswer(bytes) else { return } - onInput?(bytes) - } + MainActor.assumeIsolated { onInput?(bytes) } } public nonisolated func setTerminalTitle(source: TerminalView, title: String) {} diff --git a/Sources/AgentTermTerminal/UsageBar.swift b/Sources/AgentTermTerminal/UsageBar.swift index 286983f7..749199b0 100644 --- a/Sources/AgentTermTerminal/UsageBar.swift +++ b/Sources/AgentTermTerminal/UsageBar.swift @@ -12,7 +12,7 @@ enum UsageStyle { /// "in 2h 10m" for today, "Fri 14:05" further out. static func shortReset(_ date: Date, now: Date = Date()) -> String { - let seconds = Int(date.timeIntervalSince(now)) + let seconds = Int(saturating: date.timeIntervalSince(now)) if seconds <= 0 { return "now" } if seconds < 3600 { return "in \(max(1, seconds / 60))m" } if seconds < 24 * 3600 { return "in \(seconds / 3600)h \((seconds % 3600) / 60)m" } @@ -89,7 +89,7 @@ public struct UsageBar: View { if let fraction = usage.contextFraction { cells.append( Cell( - id: "context", label: "Context", value: "\(Int((fraction * 100).rounded()))%", fill: fraction, used: fraction * 100, + id: "context", label: "Context", value: "\(Int(saturating: (fraction * 100).rounded()))%", fill: fraction, used: fraction * 100, note: usage.contextWindow.map { "of \(SessionUsage.short($0))" })) } else { cells.append(Cell(id: "context", label: "Context", value: SessionUsage.short(tokens), fill: 0, used: 0, note: "tokens")) @@ -113,7 +113,7 @@ public struct UsageBar: View { let left = max(0, 100 - limit.usedPercent) cells.append( Cell( - id: "recorded-\(index)", label: limit.label, value: "\(Int(left.rounded()))% left", fill: left / 100, used: limit.usedPercent, + id: "recorded-\(index)", label: limit.label, value: "\(Int(saturating: left.rounded()))% left", fill: left / 100, used: limit.usedPercent, note: limit.resetsAt.map { UsageStyle.shortReset($0) })) } } @@ -267,7 +267,7 @@ public struct UsageDetails: View { if let tokens = usage.contextTokens { if let fraction = usage.contextFraction, let window = usage.contextWindow { row( - title: "Context", text: "\(Int((fraction * 100).rounded()))% used", used: fraction * 100, + title: "Context", text: "\(Int(saturating: (fraction * 100).rounded()))% used", used: fraction * 100, caption: "\(SessionUsage.short(tokens)) of \(SessionUsage.short(window)) tokens") } else { fact("Context", "\(SessionUsage.short(tokens)) tokens") @@ -307,7 +307,7 @@ public struct UsageDetails: View { section("Account limits") { ForEach(Array(usage.limits.enumerated()), id: \.offset) { _, limit in row( - title: limit.label + " limit", text: "\(Int(max(0, 100 - limit.usedPercent).rounded()))% left", used: limit.usedPercent, fillsWithLeft: true, + title: limit.label + " limit", text: "\(Int(saturating: max(0, 100 - limit.usedPercent).rounded()))% left", used: limit.usedPercent, fillsWithLeft: true, caption: limit.resetsAt.map { UsageStyle.longReset($0, now: now) } ?? "") } } diff --git a/Sources/agenttermd/main.swift b/Sources/agenttermd/main.swift index b2dc611a..8568d0ca 100644 --- a/Sources/agenttermd/main.swift +++ b/Sources/agenttermd/main.swift @@ -314,6 +314,7 @@ do { configuration.release = release configuration.revision = revision configuration.hooksDirectory = HostEnvironment.supportDirectory.appendingPathComponent("hooks", isDirectory: true) + configuration.promptsDirectory = HostEnvironment.supportDirectory // Notices through Apple for the devices that are away (#66): the // released host's relay, none for a development build. A test names a // stand-in of its own. Not in the help. @@ -322,6 +323,8 @@ do { configuration.noticesFile = HostEnvironment.noticesFile // For the tests of the apps, which do not wait the whole grace. Not in the help. if let grace = ProcessInfo.processInfo.environment["AGENTTERM_LINK_GRACE"].flatMap(TimeInterval.init) { configuration.linkGrace = grace } + // How long a notice waits to be a notification (#322), for the tests of the apps. Not in the help. + if let delay = ProcessInfo.processInfo.environment["AGENTTERM_ALERT_DELAY"].flatMap(TimeInterval.init) { configuration.alertDelay = delay } // Gives the agents' sessions the MCP server, and takes out what earlier // builds put in the agents' own configuration, for this Mac's host // only: not for one with a state folder of its own (a test, a trial diff --git a/Tests/AgentTermHostTests/AgentShellsTests.swift b/Tests/AgentTermHostTests/AgentShellsTests.swift index 198b8133..91bbfeb9 100644 --- a/Tests/AgentTermHostTests/AgentShellsTests.swift +++ b/Tests/AgentTermHostTests/AgentShellsTests.swift @@ -350,7 +350,10 @@ final class AgentShellsHostTests: XCTestCase { try token.write(to: state.appendingPathComponent("token"), atomically: true, encoding: .utf8) stateBefore = ProcessInfo.processInfo.environment["AGENTTERM_STATE_DIR"] setenv("AGENTTERM_STATE_DIR", state.path, 1) - server = HostServer(configuration: .init(port: 0, token: token, listenOnTailscale: false, detectAgents: { [] })) + var configuration = HostServer.Configuration(port: 0, token: token, listenOnTailscale: false, detectAgents: { [] }) + // Where the MCP server, of the same state folder, reads them. + configuration.promptsDirectory = state + server = HostServer(configuration: configuration) port = try server.start() } @@ -920,6 +923,8 @@ final class AgentsUseShellsTests: XCTestCase { configuration.agentsDirectory = agents.path configuration.foldersFile = root.appendingPathComponent("state/folders.json") configuration.agentShells = AgentShellsSetup(directory: root.appendingPathComponent("state"), tool: "/usr/bin/true") + // Where its server reads them, as `agenttermd` says (#269). + configuration.promptsDirectory = root.appendingPathComponent("state") let server = HostServer(configuration: configuration) let port = try server.start() defer { server.stop() } @@ -1064,7 +1069,7 @@ extension AgentShellsHostTests { waitUntil("every device told") { mac.messages.contains { if case .agentPrompts(let custom, _) = $0 { return custom["claude"] == words } else { return false } } } - XCTAssertTrue(FileManager.default.fileExists(atPath: HostServer.agentPromptsFile.path), "the host did not keep them") + XCTAssertTrue(FileManager.default.fileExists(atPath: root.appendingPathComponent("state/agent-prompts.json").path), "the host did not keep them") let (agent, _) = try startAgent("claude", title: "told", client: mac) let request: [String: Any] = ["jsonrpc": "2.0", "id": 900, "method": "initialize", "params": [:]] diff --git a/Tests/AgentTermHostTests/ClientUnreadableTests.swift b/Tests/AgentTermHostTests/ClientUnreadableTests.swift new file mode 100644 index 00000000..4881084e --- /dev/null +++ b/Tests/AgentTermHostTests/ClientUnreadableTests.swift @@ -0,0 +1,45 @@ +import AgentTermClient +import AgentTermProtocol +import Network +import XCTest + +/// REMOTE-33 (#292): a message from the host that a client cannot read is +/// said, once a connection, rather than dropped without a word; what comes +/// after it is read as ever. +final class ClientUnreadableTests: XCTestCase { + func testAMessageThatCannotBeReadIsSaidOnce() throws { + let webSocket = NWProtocolWebSocket.Options() + let parameters = NWParameters.tcp + parameters.defaultProtocolStack.applicationProtocols.insert(webSocket, at: 0) + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) + let listener = try NWListener(using: parameters) + let queue = DispatchQueue(label: "unreadable.host") + func send(_ connection: NWConnection, _ data: Data) { + let metadata = NWProtocolWebSocket.Metadata(opcode: .text) + connection.send(content: data, contentContext: .init(identifier: "m", metadata: [metadata]), completion: .idempotent) + } + // A host that sends two messages no client can read, then one it can. + listener.newConnectionHandler = { connection in + connection.start(queue: queue) + send(connection, Data(#"{"aMessageOfNoKind":{}}"#.utf8)) + send(connection, Data("not even JSON".utf8)) + send(connection, MessageCoding.encode(ServerMessage.error("after"))) + } + let ready = DispatchSemaphore(value: 0) + listener.stateUpdateHandler = { if case .ready = $0 { ready.signal() } } + listener.start(queue: queue) + XCTAssertEqual(ready.wait(timeout: .now() + 5), .success) + defer { listener.cancel() } + let port = try XCTUnwrap(listener.port?.rawValue) + + let client = AgentTermConnection(host: "127.0.0.1", port: port, credential: .token("t"), clientName: "phone") + var errors: [String] = [] + client.onMessage = { if case .error(let text, _) = $0 { errors.append(text) } } + client.connect() + defer { client.close() } + let deadline = Date().addingTimeInterval(5) + while !errors.contains("after"), Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.05)) } + XCTAssertEqual(errors, [HostErrorWords.unreadableMessage, "after"]) + XCTAssertEqual(HostErrorWords.words(for: HostErrorWords.unreadableMessage), HostErrorWords.unreadable) + } +} diff --git a/Tests/AgentTermHostTests/NoticeCenterTests.swift b/Tests/AgentTermHostTests/NoticeCenterTests.swift index 7dd760b8..437da733 100644 --- a/Tests/AgentTermHostTests/NoticeCenterTests.swift +++ b/Tests/AgentTermHostTests/NoticeCenterTests.swift @@ -40,6 +40,22 @@ final class NoticeCenterTests: XCTestCase { XCTAssertEqual(center.log.count, 2) } + /// NOTICE-7 (#321): a notice whose agent moved on is read, on every + /// device, whatever it moved on to: working again (someone answered in + /// the session), something else asked, or its session ended. + func testANoticeWhoseAgentMovedOnIsRead() { + let center = NoticeCenter(file: file) + _ = center.update(sessions: [session(1, asked), session(2, asked), session(3, .done(said: "ok"))], now: now) + let other = AgentState.waitingForAnswer(AgentQuestion(text: "And then?", choices: ["c"])) + let (_, handled) = center.update(sessions: [session(1, .working(since: now)), session(2, other)], now: now) + XCTAssertEqual(handled.count, 3) + XCTAssertTrue(handled.allSatisfy { $0.read == true }, "moved on is not read: \(handled.map { ($0.session ?? 0, $0.read ?? false) })") + XCTAssertEqual(center.log.filter { $0.read != true }.map(\.state), [other], "only the new question is unread") + var book = InboxBook() + book.take(center.log, now: now) + XCTAssertEqual(book.unread, 1, "the Inbox of a device") + } + /// NOTICE-2: handled by a device once; opened or answered names the /// session and the state. func testANoticeIsHandledOnce() throws { @@ -112,7 +128,8 @@ final class NoticeCenterTests: XCTestCase { let third = try XCTUnwrap(center.update(sessions: [session(1, asked), session(2, .done(said: nil)), session(3, asked)], now: now).new.first) _ = center.update(sessions: [session(1, asked), session(2, .done(said: nil))], now: now) XCTAssertEqual(center.log.first { $0.id == third.id }?.handled?.how, .movedOn) - XCTAssertNil(center.log.first { $0.id == third.id }?.read, "moved on is not read") + // Read too since #321 (the owner's decision of 2026-11-23). + XCTAssertEqual(center.log.first { $0.id == third.id }?.read, true, "moved on is read") } /// NOTICE-6 (#193, #234): nothing waits to be a notification; what diff --git a/Tests/AgentTermHostTests/ParsingTests.swift b/Tests/AgentTermHostTests/ParsingTests.swift index 9bf173f6..8ec3bc19 100644 --- a/Tests/AgentTermHostTests/ParsingTests.swift +++ b/Tests/AgentTermHostTests/ParsingTests.swift @@ -148,7 +148,10 @@ final class ParsingTests: XCTestCase { XCTAssertEqual(status(true, "Stopped", "100.64.0.1"), .notConnected, "a stale address does not count when it is switched off") XCTAssertEqual(status(true, "Running", "100.101.102.103", "macbook.tail1234.ts.net."), .ready(host: "macbook.tail1234.ts.net")) XCTAssertEqual(status(true, "Running", "100.101.102.103", ""), .ready(host: "100.101.102.103")) - XCTAssertEqual(status(false, nil, "100.101.102.103"), .ready(host: "100.101.102.103"), "an address proves it works even if the app was not found") + // An address alone on a Mac without Tailscale is someone else's, a + // carrier's or another VPN's (#268, the owner's decision of + // 2026-11-23); before, it was taken for proof that Tailscale works. + XCTAssertEqual(status(false, nil, "100.101.102.103"), .notInstalled, "an address alone, on a Mac without Tailscale, was taken for Tailscale") } func testEmulatorAnswersAreToldApartFromTyping() { diff --git a/Tests/AgentTermHostTests/PartFailureTests.swift b/Tests/AgentTermHostTests/PartFailureTests.swift index f3149ff0..e32418a6 100644 --- a/Tests/AgentTermHostTests/PartFailureTests.swift +++ b/Tests/AgentTermHostTests/PartFailureTests.swift @@ -86,6 +86,33 @@ final class PartFailureTests: XCTestCase { // MARK: - A session's program /// SES-23: a program that is killed is reported; its session ends. + /// HOST-16 (#273): schedules and paired devices the host cannot read + /// are put aside, not written over, and every client is told, in both + /// apps' banner and Inbox. + func testWhatTheHostCouldNotReadIsPutAsideAndSaid() throws { + let folder = root.appendingPathComponent("state") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let schedules = folder.appendingPathComponent("schedules.json") + let devices = folder.appendingPathComponent("devices.json") + try Data(#"{"schedules":[{"of a later build":true}]}"#.utf8).write(to: schedules) + try Data(#"[{"of a later build":true}]"#.utf8).write(to: devices) + var configuration = HostServer.Configuration( + port: 0, token: token, listenOnTailscale: false, detectAgents: { [] }, foldersFile: folder.appendingPathComponent("folders.json"), + devicesFile: devices) + configuration.scheduleInterval = 0.2 + let other = HostServer(configuration: configuration) + let port = try other.start() + defer { other.stop() } + let seen = Client(port: port, token: token) + waitUntil("told") { seen.failures.filter { $0.part == .savedState }.count == 2 } + XCTAssertEqual(Set(seen.failures.filter { $0.part == .savedState }.compactMap(\.name)), ["schedules", "paired devices"]) + let headline = seen.failures.first { $0.name == "schedules" }?.headline() ?? "" + XCTAssertTrue(headline.hasPrefix("The host could not read its schedules at ") && headline.hasSuffix(", and started without them."), headline) + for file in [schedules, devices] { + XCTAssertEqual(try Data(contentsOf: file.appendingPathExtension("unreadable")).isEmpty, false, "\(file.lastPathComponent) was not kept aside") + } + } + func testAProgramThatWasKilledIsReported() throws { let seconds = startWaitingSession(title: "build") for pid in pids(of: seconds) { kill(pid, SIGKILL) } diff --git a/Tests/AgentTermHostTests/PushTests.swift b/Tests/AgentTermHostTests/PushTests.swift index a30be94c..f94cac38 100644 --- a/Tests/AgentTermHostTests/PushTests.swift +++ b/Tests/AgentTermHostTests/PushTests.swift @@ -107,6 +107,8 @@ final class PushTests: XCTestCase { configuration.pushesFile = root.appendingPathComponent("pushes.json") configuration.pushTransport = relay.transport configuration.noticesFile = noticesFile + // Short, for the tests; the wait itself is PUSH-19's (#322). + configuration.alertDelay = Self.alertDelay server = HostServer(configuration: configuration) port = try server.start() } @@ -124,6 +126,9 @@ final class PushTests: XCTestCase { /// A stand-in for Claude Code that tells its hooks, one step for each /// line on its input: working, asking permission, working, done. + /// How long a notice waits to be a notification in these tests. + private static let alertDelay: TimeInterval = 0.5 + private func standIn() throws -> URL { let script = root.appendingPathComponent("claude") let hook = Handoff.shellQuote(tool.path) + " hook claude" @@ -227,6 +232,34 @@ final class PushTests: XCTestCase { XCTAssertEqual(phone.pushState, .on) } + /// PUSH-19 (#322): an agent's notification waits, and one the user acted + /// on meanwhile (its agent moved on) is never shown; one not acted on + /// is shown once the wait is over. + func testANotificationWaitsAndIsNotShownWhenTheUserActedMeanwhile() throws { + let (mac, _, agent) = try phoneAway() + func payloads() -> Int { relay.sent.filter { $0["payload"] != nil }.count } + // It asks for a permission: in the Inbox at once, not yet a notification. + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("the Mac's app told") { mac.notices.count == 1 } + XCTAssertEqual(mac.alerts, [], "a notification before its wait") + XCTAssertEqual(payloads(), 0, "pushed before its wait") + // Answered in the session before the wait is over: it goes on. + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("handled") { mac.messages.contains { if case .noticeHandled = $0 { return true } else { return false } } } + RunLoop.main.run(until: Date().addingTimeInterval(Self.alertDelay * 3)) + XCTAssertEqual(mac.alerts, [], "the question answered meanwhile was a notification on the Mac") + XCTAssertEqual(payloads(), 0, "the question answered meanwhile was pushed") + XCTAssertNil(relay.sent.first { $0["gone"] != nil }, "nothing was pushed, so nothing is taken back") + + // Done, and nobody acts: a notification once the wait is over. + let done = Date() + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("pushed after its wait", timeout: 5) { payloads() == 1 } + XCTAssertGreaterThanOrEqual(Date().timeIntervalSince(done), Self.alertDelay, "pushed before its wait") + XCTAssertEqual(mac.alerts.count, 1, "a notification on the Mac too") + XCTAssertEqual(try opened(try XCTUnwrap(relay.sent.first { $0["payload"] != nil })).state, .done(said: "All tests pass.")) + } + /// PUSH-3: told whether someone is at the Mac or not; a phone that is /// connected is told over its connection, not through Apple. func testEveryDeviceIsToldWhetherSomeoneIsAtTheMacOrNot() throws { @@ -236,8 +269,9 @@ final class PushTests: XCTestCase { waitUntil("someone at the Mac") { inUse() == true } mac.connection.sendInput(Data("\n".utf8), to: agent) waitUntil("the Mac's app told") { mac.notices.count == 1 } - // Someone at the Mac: pushed all the same, at once (#234). - waitUntil("pushed at once", timeout: 0.6) { relay.sent.count == 1 } + // Someone at the Mac: pushed all the same, once its wait is over + // (#234, #322). + waitUntil("pushed after its wait", timeout: 3) { relay.sent.count == 1 } let phone = Client(port: port, credential: .token(phoneToken), name: "iPhone") waitUntil("the phone back") { phone.log != nil } @@ -503,9 +537,9 @@ final class PushTests: XCTestCase { } /// PUSH-8 (#234): nothing waits. While someone is at the Mac, an agent - /// that asks and an agent that is done are each a notification at - /// once, on the Mac (`noticeAlert`) and pushed to the phone away, at - /// the same moment as the notice reaches the Mac's Inbox. + /// that asks and an agent that is done are each a notification, on the + /// Mac (`noticeAlert`) and pushed to the phone away, at the same moment: + /// once its wait is over (#322), whoever is at the Mac. func testEveryNoticeIsANotificationAtOnceAlsoWhileSomeoneIsAtTheMac() throws { // Someone at the Mac from the start. lock.lock(); idle = 5; lock.unlock() @@ -520,21 +554,21 @@ final class PushTests: XCTestCase { mac.connection.sendInput(Data("\n".utf8), to: agent) waitUntil("the question in the Mac's Inbox") { mac.notices.count == 1 } let question = try XCTUnwrap(mac.notices.first).id - waitUntil("the question on both at once", timeout: 0.6) { pushed() == [question] && mac.alerts == [question] } + waitUntil("the question on both after its wait", timeout: Self.alertDelay + 0.6) { pushed() == [question] && mac.alerts == [question] } - // Answered in the terminal, then done: done is told at once too. + // Answered in the terminal, then done: done is told the same way. mac.connection.sendInput(Data("\n".utf8), to: agent) mac.connection.sendInput(Data("\n".utf8), to: agent) waitUntil("done in the Mac's Inbox") { mac.notices.count == 2 } let done = try XCTUnwrap(mac.notices.last) XCTAssertEqual(done.state, .done(said: "All tests pass.")) - waitUntil("done on both at once", timeout: 0.6) { pushed() == [question, done.id] && mac.alerts == [question, done.id] } + waitUntil("done on both after its wait", timeout: Self.alertDelay + 0.6) { pushed() == [question, done.id] && mac.alerts == [question, done.id] } XCTAssertEqual(inUse(), true, "no one at the Mac by the end") } - /// PUSH-9 (#234): a done agent's notice is not held back to be read - /// first: it is a notification at once on both, and read on the Mac - /// right after, it is taken back from the phone. + /// PUSH-9 (#234, #322): a done agent's notice is not held back to be + /// read first: it is a notification on both once its wait is over, and + /// read on the Mac right after, it is taken back from the phone. func testADoneAgentReadOnTheMacIsTakenBackFromThePhone() throws { let (mac, _, agent) = try phoneAway() mac.connection.sendInput(Data("\n".utf8), to: agent) @@ -543,7 +577,7 @@ final class PushTests: XCTestCase { waitUntil("done") { mac.notices.count == 2 } let done = try XCTUnwrap(mac.notices.last).id func pushed() -> [UInt64] { relay.sent.filter { $0["payload"] != nil }.compactMap { try? opened($0).id } } - waitUntil("done on both at once", timeout: 0.6) { pushed().contains(done) && mac.alerts.contains(done) } + waitUntil("done on both after its wait", timeout: Self.alertDelay + 0.6) { pushed().contains(done) && mac.alerts.contains(done) } mac.connection.send(.readNotices(ids: [done])) waitUntil("read, said back") { mac.read == [done] } waitUntil("taken back from the phone") { relay.sent.contains { $0["gone"] as? String == self.identifier(done) } } diff --git a/Tests/AgentTermHostTests/ReviewCoreBrowserNumbersTests.swift b/Tests/AgentTermHostTests/ReviewCoreBrowserNumbersTests.swift new file mode 100644 index 00000000..ce1e99de --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCoreBrowserNumbersTests.swift @@ -0,0 +1,46 @@ +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// #249 (review of 2026-11-22), the part in the agent's MCP server: a number +/// an agent gives a browser tool. One out of range or that is no number is +/// refused in words; it never stops the server nor makes a request that +/// cannot be sent. +final class ReviewCoreBrowserNumbersTests: XCTestCase { + /// "inf" and "nan" are read as numbers (`Double("inf")`); JSON cannot + /// carry them, so the message to the host is encoded as nothing. + func testANumberThatIsNotOneIsRefusedInWords() throws { + for (tool, arguments) in [ + ("browser_scroll", ["tab": "1", "y": "inf"] as [String: Any]), + ("browser_wait", ["tab": "1", "text": "x", "seconds": "nan"]), + ] { + switch AgentShellsMCP.browserRequest(tool, arguments) { + case .failure: break + case .success(let request): + let sent = MessageCoding.encode(ClientMessage.agentBrowser(id: 1, key: "k", request: request)) + XCTFail("\(tool) with \(arguments) was not refused; the message it makes for the host is \(sent.count) bytes long") + } + } + } + + /// `browser_emulate` with a width no screen has. Run in a process of + /// its own: `Int(width)` stops the process it runs in. + func testAWidthOutOfRangeDoesNotStopTheServer() throws { + let run = try ReviewCore.runAlone("testEmulatingAWidthOutOfRange", in: ReviewCoreTrapCases.self) + XCTAssertFalse(run.crashed, "the process that made the request was stopped (signal \(run.status)):\n\(ReviewCore.crashLines(run.said))") + XCTAssertEqual(run.status, 0, ReviewCore.crashLines(run.said)) + } + + /// A number in range is taken; one past it is refused, naming the range. + func testANumberInRangeIsTakenAndOnePastItRefused() throws { + guard case .success = AgentShellsMCP.browserRequest("browser_scroll", ["tab": "1", "y": 900]) else { return XCTFail("a scroll of 900 refused") } + guard case .success = AgentShellsMCP.browserRequest("browser_emulate", ["tab": "1", "width": 390, "height": 844]) else { + return XCTFail("a phone's size refused") + } + guard case .failure(let error) = AgentShellsMCP.browserRequest("browser_emulate", ["tab": "1", "width": 1e30, "height": 844]) else { + return XCTFail("a width of 1e30 taken") + } + XCTAssertEqual(error.text, "`width` is a number from 1 to 10000.") + } +} diff --git a/Tests/AgentTermHostTests/ReviewCorePTYTests.swift b/Tests/AgentTermHostTests/ReviewCorePTYTests.swift new file mode 100644 index 00000000..59a8b176 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCorePTYTests.swift @@ -0,0 +1,65 @@ +import AgentTermProtocol +import Darwin +import XCTest + +@testable import AgentTermHost + +/// #275 (review of 2026-11-22): a shell that has ended keeps the number of +/// its terminal's descriptor, which the system gives to the next thing +/// opened. What is still written to the ended shell, or asked of it, then +/// goes to that other thing. +final class ReviewCorePTYTests: XCTestCase { + private let queue = DispatchQueue(label: "review.pty") + + private func start(_ script: String, output: @escaping (Data) -> Void = { _ in }, exit: @escaping () -> Void = {}) throws -> PTYProcess { + var environment = OwnEnvironment.withoutAgentTerms + environment["LC_ALL"] = "en_US.UTF-8" + let process = try PTYProcess(executable: "/bin/sh", arguments: ["sh", "-c", script], environment: environment, cwd: "/tmp", size: .default, queue: queue) + queue.sync { + process.onOutput = output + process.onExit = { _ in exit() } + } + return process + } + + private func wait(_ timeout: TimeInterval = 5, until condition: () -> Bool) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while !condition() && Date() < deadline { usleep(20_000) } + return condition() + } + + /// One shell ends; another is started, as the next session is; then + /// something is written to the first, as the host's delayed steps of an + /// answer or a paste still queued are. None of it reaches the second. + func testWhatIsWrittenToAShellThatEndedNeverReachesAnotherShell() throws { + var ended = false + let first = try start("exit 0", exit: { ended = true }) + XCTAssertTrue(wait { self.queue.sync { ended } }, "the first shell did not end") + // Its descriptor is closed once its reader is cancelled, on the queue. + queue.sync {} + usleep(100_000) + var shown = Data() + let second = try start("stty -echo; cat", output: { shown.append($0) }) + defer { kill(second.pid, SIGKILL) } + usleep(300_000) + let stray = "stray-275-typed-into-the-first" + first.write(Data((stray + "\n").utf8)) + _ = wait(2) { self.queue.sync { String(decoding: shown, as: UTF8.self).contains(stray) } } + let text = queue.sync { String(decoding: shown, as: UTF8.self) } + XCTAssertFalse(text.contains(stray), "what was written to the shell that had ended was typed into the one started after it") + } + + /// A shell that has ended has no program in front: it is never told the + /// one of another shell that got its descriptor's number. + func testAShellThatEndedSaysNoProgramIsInFront() throws { + var ended = false + let first = try start("exit 0", exit: { ended = true }) + XCTAssertTrue(wait { self.queue.sync { ended } }, "the first shell did not end") + queue.sync {} + usleep(100_000) + let second = try start("exec sleep 600") + defer { kill(second.pid, SIGKILL) } + usleep(300_000) + XCTAssertNil(first.foregroundCommand, "the shell that ended says the program in front of it is the other shell's") + } +} diff --git a/Tests/AgentTermHostTests/ReviewCorePushTests.swift b/Tests/AgentTermHostTests/ReviewCorePushTests.swift new file mode 100644 index 00000000..c8b9d028 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCorePushTests.swift @@ -0,0 +1,98 @@ +import AgentTermClient +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// #267 (review of 2026-11-22): what the relay answers is put into the push +/// targets where the answer arrives, not on the host's queue, and without +/// looking whether the device is still wanted. The relay here is a stand-in: +/// nothing is sent to the network. +final class ReviewCorePushTests: XCTestCase { + private let relay = URL(string: "https://relay.invalid")! + private let answer = try! JSONSerialization.data(withJSONObject: ["ticket": "t", "expires": 4_000_000_000]) + private func registration() -> PushRegistration { PushRegistration(token: String(repeating: "ab", count: 32), key: Data(repeating: 7, count: 32), mac: "mac-1") } + + /// A device taken off (revoked, or it unregistered) while the relay was + /// still asked for its ticket is not registered by the answer that + /// comes afterwards. + func testADeviceTakenOffWhileTheRelayWasAskedIsNotRegisteredByTheLateAnswer() { + var answerLater: ((Int, Data?) -> Void)? + let center = PushCenter(relay: relay, file: nil, transport: { _, _, done in answerLater = done }) + var said: PushState? + center.register(registration(), device: "phone") { said = $0 } + XCTAssertNotNil(answerLater, "the relay was not asked") + // What `revokeDevice` and `pushUnregister` do in the host. + center.unregister(device: "phone") + answerLater?(200, answer) + XCTAssertEqual(center.state(of: "phone"), .off, "the device that was taken off is registered again, and would be sent every notice") + XCTAssertNotEqual(said, .on, "and its app was told it is registered") + } + + /// The host's process is not stopped by a relay that answers on a + /// queue of its own while a device registers and unregisters. The case + /// (`ReviewCorePushRaceCase`) runs in a process of its own: when the + /// race is hit, it stops the process it happens in. + func testARelayThatAnswersOnItsOwnQueueDoesNotStopTheHost() throws { + let run = try ReviewCore.runAlone("testTheRelaysAnswersAndTheHostDoNotTouchThePushTargetsAtOnce", in: ReviewCorePushRaceCase.self) + XCTAssertFalse(run.crashed, "the host's process was stopped (signal \(run.status)):\n\(ReviewCore.crashLines(run.said))") + XCTAssertEqual(run.status, 0, ReviewCore.crashLines(run.said)) + } +} + +/// The race of #267 itself, run alone by the test above or by hand with +/// `AGENTTERM_REVIEW_TRAPS=1`; skipped otherwise, since it stops the +/// process when it is hit. +final class ReviewCorePushRaceCase: XCTestCase { + private let relay = URL(string: "https://relay.invalid")! + private let answer = try! JSONSerialization.data(withJSONObject: ["ticket": "t", "expires": 4_000_000_000]) + private func registration() -> PushRegistration { PushRegistration(token: String(repeating: "ab", count: 32), key: Data(repeating: 7, count: 32), mac: "mac-1") } + + override func setUpWithError() throws { + try XCTSkipUnless(ReviewCore.runsTraps, "stops the process when hit: #267, run alone with \(ReviewCore.trapsVariable)=1") + } + + /// The host, with a relay that answers on a queue of its own as + /// URLSession does: a paired device registers and unregisters many + /// times. Run under the thread sanitizer + /// (`AGENTTERM_REVIEW_TRAPS=1 swift test --sanitize=thread --filter ReviewCorePushRaceCase`), + /// which says when the targets are written from two threads at once; + /// without it, it only passes or stops the process. + func testTheRelaysAnswersAndTheHostDoNotTouchThePushTargetsAtOnce() throws { + let folder = try ReviewCore.Folder("push") + defer { folder.remove() } + var configuration = folder.configuration() + configuration.pushRelay = relay + configuration.pushesFile = folder.root.appendingPathComponent("state/pushes.json") + let answers = DispatchQueue(label: "review.relay", attributes: .concurrent) + let answer = self.answer + configuration.pushTransport = { _, _, done in answers.async { done(200, answer) } } + let server = HostServer(configuration: configuration) + let port = try server.start() + defer { server.stop() } + let mac = ReviewCore.Client(port: port, name: "mac") + defer { mac.connection.close() } + XCTAssertTrue(ReviewCore.spin { mac.welcomed }) + mac.connection.send(.createPairingCode) + var code: String? + XCTAssertTrue( + ReviewCore.spin { + code = mac.messages.compactMap { if case .pairingCode(let code, _) = $0 { return code } else { return nil } }.last + return code != nil + }) + let phone = ReviewCore.Client(port: port, credential: .pairingCode(try XCTUnwrap(code)), name: "phone", kind: .iphone) + defer { phone.connection.close() } + XCTAssertTrue(ReviewCore.spin { phone.welcomed }, "the phone was not paired") + let rounds = 400 + for _ in 0.. [PushState] { phone.messages.compactMap { if case .pushState(let state) = $0 { return state } else { return nil } } } + XCTAssertTrue(ReviewCore.spin(30) { states().count >= rounds + 1 && states().last == .on }, "\(states().count) answers came, the last \(String(describing: states().last))") + } +} diff --git a/Tests/AgentTermHostTests/ReviewCoreSupport.swift b/Tests/AgentTermHostTests/ReviewCoreSupport.swift new file mode 100644 index 00000000..a0aee775 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCoreSupport.swift @@ -0,0 +1,174 @@ +import AgentTermClient +import AgentTermProtocol +import Darwin +import Foundation +import Network +import XCTest + +@testable import AgentTermHost + +/// What the tests of the review of 2026-11-22 (milestone 0.15.1) share: a +/// host of their own, a client that says what it is told to, and a way to +/// run a test that stops its process without stopping the others. +enum ReviewCore { + static let token = "review-token-0123456789abcdef0123456789" + + /// Spins the main run loop, where the clients' callbacks arrive, until + /// `condition` holds or the time is up; says whether it held. + @discardableResult + static func spin(_ timeout: TimeInterval = 10, until condition: () -> Bool) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while !condition() && Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.02)) } + return condition() + } + + /// A folder of the test's own, with the state folder the host's static + /// paths read (`AGENTTERM_STATE_DIR`) inside it: a host started by a + /// test must never read or remove what a build on this Mac keeps (#269). + final class Folder { + let root: URL + private let stateBefore: String? + + init(_ name: String) throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-\(name)-\(UUID().uuidString.prefix(8))").standardizedFileURL + try FileManager.default.createDirectory(at: root.appendingPathComponent("state"), withIntermediateDirectories: true) + stateBefore = ProcessInfo.processInfo.environment["AGENTTERM_STATE_DIR"] + setenv("AGENTTERM_STATE_DIR", root.appendingPathComponent("state").path, 1) + } + + func remove() { + if let stateBefore { setenv("AGENTTERM_STATE_DIR", stateBefore, 1) } else { unsetenv("AGENTTERM_STATE_DIR") } + try? FileManager.default.removeItem(at: root) + } + + /// A host's configuration that keeps what it keeps in this folder. + func configuration(agents: [AgentInfo] = []) -> HostServer.Configuration { + HostServer.Configuration( + port: 0, token: ReviewCore.token, listenOnTailscale: false, detectAgents: { agents }, + foldersFile: root.appendingPathComponent("state/folders.json"), home: root.path, statusLineTool: "/usr/bin/true", + usageDirectory: root.appendingPathComponent("usage")) + } + } + + /// A client as the apps are, that keeps what it was sent. + final class Client { + let connection: AgentTermConnection + var messages: [ServerMessage] = [] + var state: AgentTermConnection.State = .connecting + + init(port: UInt16, credential: AgentTermConnection.Credential = .token(ReviewCore.token), name: String, kind: DeviceKind? = nil) { + connection = AgentTermConnection(host: "127.0.0.1", port: port, credential: credential, clientName: name, kind: kind) + connection.onMessage = { [weak self] in self?.messages.append($0) } + connection.onState = { [weak self] in self?.state = $0 } + connection.connect() + } + + var welcomed: Bool { messages.contains { if case .welcome = $0 { return true } else { return false } } } + var isClosed: Bool { if case .closed = state { return true } else { return false } } + var errors: [String] { messages.compactMap { if case .error(let text, _) = $0 { return text } else { return nil } } } + var sessions: [SessionInfo]? { messages.compactMap { if case .sessions(let list) = $0 { return list } else { return nil } }.last } + var attached: SessionInfo? { messages.compactMap { if case .attached(let info, _) = $0 { return info } else { return nil } }.last } + var failures: [PartFailure] { messages.compactMap { if case .failures(let list) = $0 { return list } else { return nil } }.last ?? [] } + } + + /// A WebSocket that sends exactly the frames it is given, signed in or + /// not, and reads only when asked to. + final class RawSocket { + private let connection: NWConnection + private let queue = DispatchQueue(label: "review.raw") + private let lock = NSLock() + private var texts: [Data] = [] + private var closed = false + private var ready = false + + init(port: UInt16, reads: Bool = true) { + let webSocket = NWProtocolWebSocket.Options() + webSocket.autoReplyPing = true + webSocket.maximumMessageSize = 16 * 1024 * 1024 + let parameters = NWParameters.tcp + parameters.defaultProtocolStack.applicationProtocols.insert(webSocket, at: 0) + // A URL, as the apps' client gives: the handshake needs its host and path. + connection = NWConnection(to: .url(URL(string: "ws://127.0.0.1:\(port)/")!), using: parameters) + connection.stateUpdateHandler = { [weak self] state in + guard let self else { return } + self.lock.lock() + switch state { + case .ready: self.ready = true + case .failed, .cancelled: self.closed = true + default: break + } + self.lock.unlock() + } + connection.start(queue: queue) + if reads { receive() } + } + + private func receive() { + connection.receiveMessage { [weak self] data, context, _, error in + guard let self else { return } + let metadata = context?.protocolMetadata(definition: NWProtocolWebSocket.definition) as? NWProtocolWebSocket.Metadata + self.lock.lock() + if error != nil || metadata?.opcode == .close { self.closed = true } + if let data, metadata?.opcode == .text { self.texts.append(data) } + let over = self.closed + self.lock.unlock() + if !over { self.receive() } + } + } + + var isReady: Bool { lock.lock(); defer { lock.unlock() }; return ready } + var isClosed: Bool { lock.lock(); defer { lock.unlock() }; return closed } + /// What the host said, as messages; one it sent in parts is not joined. + var messages: [ServerMessage] { + lock.lock() + defer { lock.unlock() } + return texts.compactMap { MessageCoding.decode(ServerMessage.self, from: $0) } + } + var errors: [String] { messages.compactMap { if case .error(let text, _) = $0 { return text } else { return nil } } } + + func send(text data: Data) { + let metadata = NWProtocolWebSocket.Metadata(opcode: .text) + let context = NWConnection.ContentContext(identifier: "text", metadata: [metadata]) + connection.send(content: data, contentContext: context, completion: .idempotent) + } + + func send(_ message: ClientMessage) { send(text: MessageCoding.encode(message)) } + func close() { connection.cancel() } + } + + /// Runs one test of `ReviewCoreTrapCases` in a process of its own, as + /// `swift test` would, and says how that process ended and what it + /// wrote: a fault that stops the process it happens in (a Swift trap) + /// then fails one test and no more. + static func runAlone(_ test: String, in case: AnyClass) throws -> (status: Int32, crashed: Bool, said: String) { + let bundle = Bundle(for: `case`).bundlePath + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = ["xctest", "-XCTest", "AgentTermHostTests.\(String(describing: `case`))/\(test)", bundle] + var environment = OwnEnvironment.withoutAgentTerms + environment[trapsVariable] = "1" + process.environment = environment + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe + try process.run() + var output = Data() + let reader = DispatchQueue(label: "review.alone") + let read = DispatchSemaphore(value: 0) + reader.async { + output = pipe.fileHandleForReading.readDataToEndOfFile() + read.signal() + } + process.waitUntilExit() + _ = read.wait(timeout: .now() + 10) + return (process.terminationStatus, process.terminationReason == .uncaughtSignal, String(decoding: output, as: UTF8.self)) + } + + static let trapsVariable = "AGENTTERM_REVIEW_TRAPS" + static var runsTraps: Bool { ProcessInfo.processInfo.environment[trapsVariable] == "1" } + + /// The lines of what a process wrote that say where it stopped. + static func crashLines(_ said: String) -> String { + said.split(separator: "\n").filter { $0.contains("Fatal error") || $0.contains("error:") || $0.contains("failed") }.suffix(6).joined(separator: "\n") + } +} diff --git a/Tests/AgentTermHostTests/ReviewCoreTailscaleTests.swift b/Tests/AgentTermHostTests/ReviewCoreTailscaleTests.swift new file mode 100644 index 00000000..c52520c5 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCoreTailscaleTests.swift @@ -0,0 +1,64 @@ +import Darwin +import XCTest + +@testable import AgentTermHost + +/// #268 (review of 2026-11-22): the host takes any address in +/// 100.64.0.0/10 on any interface for this Mac's Tailscale address, and +/// listens on it. +final class ReviewCoreTailscaleTests: XCTestCase { + /// The interfaces that are up with an address in 100.64.0.0/10: name and address. + private func inRange() -> [(name: String, address: String)] { + var list: UnsafeMutablePointer? + guard getifaddrs(&list) == 0 else { return [] } + defer { freeifaddrs(list) } + var found: [(String, String)] = [] + var cursor = list + while let entry = cursor { + defer { cursor = entry.pointee.ifa_next } + guard let address = entry.pointee.ifa_addr, address.pointee.sa_family == sa_family_t(AF_INET), entry.pointee.ifa_flags & UInt32(IFF_UP) != 0 else { continue } + let raw = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { UInt32(bigEndian: $0.pointee.sin_addr.s_addr) } + if raw & 0xFFC0_0000 == 0x6440_0000 { + found.append((String(cString: entry.pointee.ifa_name), "\(raw >> 24).\((raw >> 16) & 0xff).\((raw >> 8) & 0xff).\(raw & 0xff)")) + } + } + return found + } + + /// With no Tailscale on the Mac and nothing known of it, an address in + /// the carrier-grade range (a carrier's, another VPN's) is not a + /// Tailscale connection, and no pairing code is offered for it. + func testAnAddressInTheRangeIsNotTailscaleWhereTailscaleIsNotInstalled() { + let status = Tailscale.status(installed: false, backendState: nil, address: "100.96.0.5", dnsName: nil) + XCTAssertEqual(status, .notInstalled, "an address alone, on a Mac without Tailscale, was taken for a working Tailscale connection") + } + + /// On this Mac: the address the host would listen on is the one + /// Tailscale itself says is this Mac's. Skipped where Tailscale's + /// command is not there or does not answer. Addresses are not printed: + /// only the interfaces' names and whether they agree. + func testTheAddressTheHostListensOnIsTheOneTailscaleSays() throws { + let candidates = ["/Applications/Tailscale.app/Contents/MacOS/Tailscale", "/opt/homebrew/bin/tailscale", "/usr/local/bin/tailscale"] + guard let cli = candidates.first(where: FileManager.default.isExecutableFile(atPath:)) else { throw XCTSkip("Tailscale's command is not on this Mac") } + guard let result = Subprocess.run(cli, ["ip", "-4"], timeout: 4), result.status == 0 else { throw XCTSkip("Tailscale's command did not answer") } + let own = String(decoding: result.output, as: UTF8.self).split(separator: "\n").first.map { $0.trimmingCharacters(in: .whitespaces) } ?? "" + try XCTSkipIf(own.isEmpty, "Tailscale gave no address: not connected") + let found = inRange() + let taken = Tailscale.ipv4Address(own: Tailscale.ownAddresses()) + let names = found.map(\.name).joined(separator: ", ") + let takenFrom = found.first { $0.address == taken }?.name ?? "none" + let tailscales = found.first { $0.address == own }?.name ?? "none" + XCTAssertTrue(taken == own, "interfaces up in 100.64.0.0/10: \(names); the host takes the address of \(takenFrom), Tailscale's own is on \(tailscales)") + } + + /// #268: which address is taken, whatever this Mac has. + func testOnlyTailscalesOwnAddressIsTaken() { + let warp = (interface: "utun5", address: "100.96.0.5"), tailscale = (interface: "utun11", address: "100.102.112.76") + let carrier = (interface: "en0", address: "100.70.1.2") + XCTAssertEqual(Tailscale.address(among: [warp, tailscale], own: ["100.102.112.76"], installed: true), "100.102.112.76", "another VPN's tunnel, listed first") + XCTAssertNil(Tailscale.address(among: [warp], own: [], installed: true), "Tailscale asked, and the address is not its own") + XCTAssertNil(Tailscale.address(among: [carrier], own: nil, installed: true), "a carrier's address on an interface that is no tunnel") + XCTAssertNil(Tailscale.address(among: [tailscale], own: nil, installed: false), "a Mac without Tailscale") + XCTAssertEqual(Tailscale.address(among: [carrier, tailscale], own: nil, installed: true), "100.102.112.76", "Tailscale not asked: the tunnel") + } +} diff --git a/Tests/AgentTermHostTests/ReviewCoreTrapTests.swift b/Tests/AgentTermHostTests/ReviewCoreTrapTests.swift new file mode 100644 index 00000000..dccdde17 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCoreTrapTests.swift @@ -0,0 +1,126 @@ +import AgentTermClient +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// #271 (review of 2026-11-22): a number out of range in a message from a +/// client that signed in. The host answers or refuses; it never stops, and +/// every session with it. Each case runs in a process of its own +/// (`ReviewCoreTrapCases`), since the fault stops the process it happens in. +final class ReviewCoreTrapTests: XCTestCase { + private func survives(_ test: String, file: StaticString = #filePath, line: UInt = #line) throws { + let run = try ReviewCore.runAlone(test, in: ReviewCoreTrapCases.self) + XCTAssertFalse(run.crashed, "the host's process was stopped (signal \(run.status)):\n\(ReviewCore.crashLines(run.said))", file: file, line: line) + XCTAssertEqual(run.status, 0, ReviewCore.crashLines(run.said), file: file, line: line) + } + + func testAttachingWithACountOutOfRangeDoesNotStopTheHost() throws { try survives("testAttachingWithACountOutOfRange") } + func testAskingForAMinusNumberOfLinesOfACommandDoesNotStopTheHost() throws { try survives("testAskingForAMinusNumberOfLinesOfACommand") } + func testAskingForARunsOutputAtADateOutOfRangeDoesNotStopTheHost() throws { try survives("testAskingForARunsOutputAtADateOutOfRange") } +} + +/// The cases themselves, each run alone by a test above or by hand with +/// `AGENTTERM_REVIEW_TRAPS=1`; skipped otherwise, so that the rest of the +/// tests still run (#271, #249). +final class ReviewCoreTrapCases: XCTestCase { + private var folder: ReviewCore.Folder! + private var server: HostServer! + private var port: UInt16 = 0 + + override func setUpWithError() throws { + try XCTSkipUnless(ReviewCore.runsTraps, "stops the process: #271 and #249, run alone with \(ReviewCore.trapsVariable)=1") + folder = try ReviewCore.Folder("trap") + } + + override func tearDown() { + server?.stop() + folder?.remove() + } + + private func start(_ configuration: HostServer.Configuration) throws -> ReviewCore.Client { + server = HostServer(configuration: configuration) + port = try server.start() + let client = ReviewCore.Client(port: port, name: "mac") + XCTAssertTrue(ReviewCore.spin { client.welcomed }, "the client was not welcomed") + return client + } + + /// Whether the host still answers: it is asked for its sessions again. + private func stillAnswers(_ client: ReviewCore.Client) -> Bool { + let before = client.messages.filter { if case .sessions = $0 { return true } else { return false } }.count + client.connection.send(.list) + return ReviewCore.spin(5) { client.messages.filter { if case .sessions = $0 { return true } else { return false } }.count > before } + } + + func testAttachingWithACountOutOfRange() throws { + let client = try start(folder.configuration()) + defer { client.connection.close() } + client.connection.send(.create(CreateRequest(command: "exec sleep 600", cwd: folder.root.path, title: "kept"))) + XCTAssertTrue(ReviewCore.spin { client.attached != nil }, "no session") + let session = try XCTUnwrap(client.attached).id + client.connection.send(.attach(session: session, size: .default, have: Int.min)) + XCTAssertTrue(stillAnswers(client), "the host no longer answers") + client.connection.send(.kill(session: session)) + } + + func testAskingForAMinusNumberOfLinesOfACommand() throws { + // A stand-in agent that says what its session's key is. + let agents = folder.root.appendingPathComponent("agents") + try FileManager.default.createDirectory(at: agents, withIntermediateDirectories: true) + let key = folder.root.appendingPathComponent("key") + try "#!/bin/sh\nprintf '%s' \"$AGENTTERM_MCP\" > '\(key.path).new'; mv '\(key.path).new' '\(key.path)'\nexec sleep 600\n".write( + to: agents.appendingPathComponent("claude"), atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: agents.appendingPathComponent("claude").path) + var configuration = folder.configuration() + configuration.detectAgents = { AgentDetector.detect(in: agents.path) } + configuration.agentsDirectory = agents.path + let client = try start(configuration) + defer { client.connection.close() } + client.connection.send(.create(CreateRequest(command: "claude", cwd: folder.root.path))) + XCTAssertTrue(ReviewCore.spin(15) { FileManager.default.fileExists(atPath: key.path) }, "the agent's session did not start") + let agent = try XCTUnwrap(AgentShellsMCP.Session(variable: try String(contentsOf: key, encoding: .utf8))) + client.connection.send(.agentShell(id: 1, key: agent.key, request: .open(command: nil, title: "its shell"))) + var shell: SessionID? + XCTAssertTrue( + ReviewCore.spin(15) { + shell = client.messages.compactMap { if case .agentShellResult(1, .opened(let info)) = $0 { return info.id } else { return nil } }.last + return shell != nil + }, "the agent's shell was not opened: \(client.messages.compactMap { if case .agentShellResult(_, let result) = $0 { return result } else { return nil } })") + // A command is run in it first: only a shell that has printed + // something has lines to count. + let id = try XCTUnwrap(shell) + var ran = false + for attempt in 0..<20 where !ran { + client.connection.send(.agentShell(id: 100 + attempt, key: agent.key, request: .run(session: id, command: "echo review-271"))) + ReviewCore.spin(1) { client.messages.contains { if case .agentShellResult(100 + attempt, _) = $0 { return true } else { return false } } } + ran = client.messages.contains { if case .agentShellResult(100 + attempt, .ran) = $0 { return true } else { return false } } + } + XCTAssertTrue(ran, "the command was not typed: \(client.messages.compactMap { if case .agentShellResult(_, let result) = $0 { return result } else { return nil } }.suffix(2))") + var printed = false + for attempt in 0..<20 where !printed { + client.connection.send(.agentShell(id: 200 + attempt, key: agent.key, request: .command(session: id, lines: 5))) + ReviewCore.spin(1) { client.messages.contains { if case .agentShellResult(200 + attempt, _) = $0 { return true } else { return false } } } + printed = client.messages.contains { if case .agentShellResult(200 + attempt, .command(let state)) = $0 { return state.output.contains("review-271") } else { return false } } + } + XCTAssertTrue(printed, "the shell's command printed nothing the host kept") + client.connection.send(.agentShell(id: 2, key: agent.key, request: .command(session: id, lines: -1))) + XCTAssertTrue(ReviewCore.spin(5) { client.messages.contains { if case .agentShellResult(2, _) = $0 { return true } else { return false } } }, "no answer") + XCTAssertTrue(stillAnswers(client), "the host no longer answers") + } + + func testAskingForARunsOutputAtADateOutOfRange() throws { + let client = try start(folder.configuration()) + defer { client.connection.close() } + client.connection.send(.scheduleRunOutput(id: "no-such-schedule", at: Date(timeIntervalSince1970: 1e300))) + XCTAssertTrue(stillAnswers(client), "the host no longer answers") + } + + /// #249: the request `browser_emulate` makes of a width no screen has. + func testEmulatingAWidthOutOfRange() { + switch AgentShellsMCP.browserRequest("browser_emulate", ["tab": "1", "width": 1e30, "height": 800]) { + case .failure(let refusal): XCTAssertFalse(refusal.text.isEmpty) + case .success(let request): XCTFail("neither refused nor stopped: \(request)") + } + } +} diff --git a/Tests/AgentTermHostTests/ReviewCoreUnsignedPeerTests.swift b/Tests/AgentTermHostTests/ReviewCoreUnsignedPeerTests.swift new file mode 100644 index 00000000..ee3714d1 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewCoreUnsignedPeerTests.swift @@ -0,0 +1,80 @@ +import AgentTermClient +import AgentTermProtocol +import Darwin +import XCTest + +@testable import AgentTermHost + +/// #266 (review of 2026-11-22): what a peer that has not signed in can make +/// the host do. Each test says what should happen, and fails for as long as +/// the host does otherwise. +final class ReviewCoreUnsignedPeerTests: XCTestCase { + private var folder: ReviewCore.Folder! + private var server: HostServer! + private var port: UInt16 = 0 + + override func setUpWithError() throws { + folder = try ReviewCore.Folder("unsigned") + server = HostServer(configuration: folder.configuration()) + port = try server.start() + } + + override func tearDown() { + server.stop() + folder.remove() + } + + /// A peer that has not signed in and sends something that is no message + /// is let go at once: told why once (principle 3), and not kept to send + /// more. + func testAPeerThatHasNotSignedInIsLetGoAtItsFirstFrameThatIsNoMessage() { + let peer = ReviewCore.RawSocket(port: port) + defer { peer.close() } + XCTAssertTrue(ReviewCore.spin { peer.isReady }, "the peer did not connect") + peer.send(text: Data("this is not a message".utf8)) + // Time enough for an answer and for a second frame to be taken. + ReviewCore.spin(1.5) { peer.isClosed } + peer.send(text: Data("nor is this".utf8)) + ReviewCore.spin(1.5) { peer.isClosed } + XCTAssertLessThanOrEqual(peer.errors.count, 1, "the host answered a peer that had not signed in, once for each frame: \(peer.errors)") + XCTAssertTrue(peer.isClosed, "3 seconds and two frames later the peer that never signed in is still connected") + } + + /// The name a peer gives itself never writes a line of its own into the + /// host's log, where the app later reads why the host stopped. + func testTheNameOfAPeerThatWasRefusedWritesNoLineOfItsOwnInTheLog() throws { + // What the host writes to its log (its standard error) goes to a + // file of the test's for the time of the test. + let log = folder.root.appendingPathComponent("log") + FileManager.default.createFile(atPath: log.path, contents: nil) + fflush(stderr) + let kept = dup(STDERR_FILENO) + let file = open(log.path, O_WRONLY | O_APPEND) + dup2(file, STDERR_FILENO) + var restored = false + func restore() { + guard !restored else { return } + restored = true + fflush(stderr) + dup2(kept, STDERR_FILENO) + close(kept) + close(file) + } + defer { restore() } + let forged = "agenttermd: a line the peer wrote" + let peer = ReviewCore.RawSocket(port: port) + defer { peer.close() } + XCTAssertTrue(ReviewCore.spin { peer.isReady }, "the peer did not connect") + // Refused, and in the moment before it is let go, a frame that is + // no message: the log says who sent it. + peer.send(.hello(token: "not the token", client: "x\n\(forged)")) + peer.send(text: Data("{}".utf8)) + ReviewCore.spin(3) { peer.isClosed } + restore() + let written = (try? String(contentsOf: log, encoding: .utf8)) ?? "" + let lines = written.split(separator: "\n").map(String.init) + XCTAssertFalse( + lines.contains { $0.hasPrefix(forged) }, "the log has a line that begins with what the peer called itself: \(lines.filter { $0.contains("could not be read") || $0.hasPrefix(forged) })") + } + +} diff --git a/Tests/AgentTermHostTests/ReviewSubConfigFilesTests.swift b/Tests/AgentTermHostTests/ReviewSubConfigFilesTests.swift new file mode 100644 index 00000000..9537e6af --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubConfigFilesTests.swift @@ -0,0 +1,133 @@ +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// What the host writes into files of the user's and of the agents' +/// (review of 2026-11-22): a symbolic link (#263), the folders +/// `CLAUDE_CONFIG_DIR` and `CODEX_HOME` name (#264), and a Codex +/// `config.toml` that could not be read (#265). All in a folder of the +/// test's own. +final class ReviewSubConfigFilesTests: XCTestCase { + private var root: URL! + private var home: URL { root.appendingPathComponent("home") } + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-config-\(UUID().uuidString)").standardizedFileURL + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + } + + private func setup(environment: [String: String] = [:], run: @escaping AgentSetup.Run = { _ in (0, "") }) -> AgentSetup { + AgentSetup( + directory: root.appendingPathComponent("setup"), tool: "/Apps/AgentTerm Dev.app/agenttermd", home: home.path, name: "agentterm-dev", + environment: environment, locate: { [] }, prompt: { _ in nil }, run: run) + } + + /// A file kept elsewhere (a dotfiles folder) and linked to from `path`. + private func linked(_ path: URL, text: String) throws -> URL { + let real = root.appendingPathComponent("dotfiles").appendingPathComponent(path.lastPathComponent) + try FileManager.default.createDirectory(at: real.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: true) + try text.write(to: real, atomically: true, encoding: .utf8) + try FileManager.default.createSymbolicLink(at: path, withDestinationURL: real) + return real + } + + private func isLink(_ file: URL) -> Bool { + (try? FileManager.default.attributesOfItem(atPath: file.path)[.type] as? FileAttributeType) == .typeSymbolicLink + } + + // MARK: #263 + + /// #263: Claude Code's settings kept as a link stay a link when the + /// status line is written into them, and the file linked to gets it. + func testClaudesSettingsThatAreALinkStayALink() throws { + let settings = home.appendingPathComponent(".claude/settings.json") + let real = try linked(settings, text: #"{"theme":"dark"}"#) + try setup().setClaudeStatusLine() + XCTAssertTrue(isLink(settings), "the link was replaced by a plain file") + XCTAssertTrue(try String(contentsOf: real, encoding: .utf8).contains("statusline"), "the file linked to did not get the status line") + } + + /// #263: Codex's `config.toml` kept as a link, the same. + func testCodexsConfigurationThatIsALinkStaysALink() throws { + let config = home.appendingPathComponent(".codex/config.toml") + let real = try linked(config, text: "model = \"o3\"\n") + try setup().addCodexHooks(path: "/usr/bin/true") + XCTAssertTrue(isLink(config), "the link was replaced by a plain file") + XCTAssertTrue(try String(contentsOf: real, encoding: .utf8).contains("AgentTerm's hook"), "the file linked to did not get the hooks") + } + + /// #263: a file saved from the Files tab that is a link, the same. + func testAFileSavedThroughALinkStaysALink() throws { + let file = home.appendingPathComponent("project/notes.md") + let real = try linked(file, text: "before\n") + try FileBrowser.write("after\n", to: file.path) + XCTAssertTrue(isLink(file), "the link was replaced by a plain file") + XCTAssertEqual(try String(contentsOf: real, encoding: .utf8), "after\n", "the file linked to was not written") + } + + /// #263: the folder an agent is trusted in for a schedule, the same. + func testTheTrustFileThatIsALinkStaysALink() throws { + let file = home.appendingPathComponent(".claude.json") + let real = try linked(file, text: #"{"numStartups":3}"#) + try ScheduleRunner.trustFolder(of: Schedule(name: "n", agent: "claude", folder: "/work", prompt: "p", when: .limitReset), home: home.path) + XCTAssertTrue(isLink(file), "the link was replaced by a plain file") + XCTAssertTrue(try String(contentsOf: real, encoding: .utf8).contains("/work"), "the file linked to did not get the folder") + } + + // MARK: #264 + + /// Sets a variable of this process for the test, and puts back what was there. + private func with(_ name: String, _ value: String, _ body: () throws -> Void) rethrows { + let before = ProcessInfo.processInfo.environment[name] + setenv(name, value, 1) + defer { if let before { setenv(name, before, 1) } else { unsetenv(name) } } + try body() + } + + /// #264: with `CLAUDE_CONFIG_DIR` in the host's environment, the status + /// line is written where it names (the ground of the next two tests). + func testTheStatusLineGoesWhereClaudeConfigDirNames() throws { + let own = root.appendingPathComponent("claude-own") + try setup(environment: ["CLAUDE_CONFIG_DIR": own.path]).setClaudeStatusLine() + XCTAssertTrue(FileManager.default.fileExists(atPath: own.appendingPathComponent("settings.json").path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: home.appendingPathComponent(".claude/settings.json").path)) + } + + // MARK: #265 + + /// A `config.toml` with one byte that is not UTF-8, in a comment. + private func unreadableConfig() throws -> (file: URL, data: Data) { + let config = home.appendingPathComponent(".codex/config.toml") + try FileManager.default.createDirectory(at: config.deletingLastPathComponent(), withIntermediateDirectories: true) + var data = Data("model = \"o3\"\n# caf".utf8) + data.append(0xE9) + data.append(Data("\n[features]\nweb_search = true\n".utf8)) + try data.write(to: config) + return (config, data) + } + + /// #265: a `config.toml` that cannot be read as UTF-8 is not replaced + /// by the hooks alone: what the user had is still in it, or it is left + /// as it was and the reason said. + func testAConfigurationThatCannotBeReadIsNotReplaced() throws { + let (config, before) = try unreadableConfig() + try? setup().addCodexHooks(path: "/usr/bin/true") + let after = try Data(contentsOf: config) + XCTAssertNotNil(after.range(of: Data("model = \"o3\"".utf8)), "the user's configuration is gone: \(after.count) bytes where there were \(before.count)") + } + + /// #265: and when Codex then refuses the file, it is put back as it + /// was, not deleted. + func testAConfigurationThatCannotBeReadIsNotDeletedWhenCodexRefusesIt() throws { + let (config, before) = try unreadableConfig() + XCTAssertThrowsError(try setup(run: { _ in (1, "error: could not parse config.toml") }).addCodexHooks(path: "/usr/bin/false")) + XCTAssertTrue(FileManager.default.fileExists(atPath: config.path), "the user's config.toml was deleted") + XCTAssertEqual(try? Data(contentsOf: config), before, "the user's config.toml is not what it was") + } +} diff --git a/Tests/AgentTermHostTests/ReviewSubGitPrefixTests.swift b/Tests/AgentTermHostTests/ReviewSubGitPrefixTests.swift new file mode 100644 index 00000000..ebb76cb8 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubGitPrefixTests.swift @@ -0,0 +1,72 @@ +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// #260 (review of 2026-11-22): the changes of a folder are read whatever +/// the user's git writes before a path in a diff (`diff.mnemonicPrefix`, +/// `diff.noprefix`). The settings are the temporary repository's own. +final class ReviewSubGitPrefixTests: XCTestCase { + private var root: URL! + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-prefix-\(UUID().uuidString)").standardizedFileURL + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + git("init", "-q", "-b", "main") + git("config", "user.name", "Test") + git("config", "user.email", "test@example.com") + git("config", "commit.gpgsign", "false") + try "one\n".write(to: root.appendingPathComponent("a.txt"), atomically: true, encoding: .utf8) + try "one\n".write(to: root.appendingPathComponent("b.txt"), atomically: true, encoding: .utf8) + git("add", ".") + git("commit", "-q", "-m", "init") + // One change staged, one not. + try "one\ntwo\n".write(to: root.appendingPathComponent("a.txt"), atomically: true, encoding: .utf8) + try "one\ntwo\n".write(to: root.appendingPathComponent("b.txt"), atomically: true, encoding: .utf8) + git("add", "b.txt") + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + } + + @discardableResult + private func git(_ arguments: String...) -> String { + let result = Subprocess.run("/usr/bin/git", ["-C", root.path] + arguments) + return String(decoding: result?.output ?? Data(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var changes: [String] { + GitDiff.snapshot(directory: root.path).files.map { "\($0.isStaged ? "staged" : "unstaged") \($0.path)" }.sorted() + } + + /// As git is set up by itself: the test's own ground. + func testTheChangesAreNamedAsGitIsSetUpByItself() { + XCTAssertEqual(changes, ["staged b.txt", "unstaged a.txt"]) + } + + /// #260: `diff.mnemonicPrefix` writes `i/` and `w/` (`c/` and `i/` for + /// what is staged) where the parser expects `a/` and `b/`. + func testTheChangesAreNamedWithMnemonicPrefix() { + git("config", "--local", "diff.mnemonicPrefix", "true") + XCTAssertEqual(changes, ["staged b.txt", "unstaged a.txt"]) + } + + /// #260: `diff.noprefix` writes no prefix at all. + func testTheChangesAreNamedWithNoPrefix() { + git("config", "--local", "diff.noprefix", "true") + XCTAssertEqual(changes, ["staged b.txt", "unstaged a.txt"]) + } + + /// #260: a commit's files, and a stash's, are named the same way. + func testACommitAndAStashAreNamedWithNoPrefix() { + git("commit", "-q", "-m", "second") + let hash = git("rev-parse", "HEAD") + git("stash", "push", "-q") + git("config", "--local", "diff.noprefix", "true") + git("config", "--local", "diff.mnemonicPrefix", "true") + XCTAssertEqual(GitActions.show(hash, in: root.path)?.files.map(\.path), ["b.txt"]) + guard let stash = GitActions.stashes(in: root.path).first else { return XCTFail("no stash") } + XCTAssertEqual(GitActions.stashFiles(stash.hash, in: root.path)?.map(\.path), ["a.txt"]) + } +} diff --git a/Tests/AgentTermHostTests/ReviewSubHostStateTests.swift b/Tests/AgentTermHostTests/ReviewSubHostStateTests.swift new file mode 100644 index 00000000..f5985ae7 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubHostStateTests.swift @@ -0,0 +1,103 @@ +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// What a host does to the files of its state folder (review of +/// 2026-11-22): a test's host and the instructions kept for the agents +/// (#269), and a state file that cannot be read (#273). Everything is in a +/// folder of the test's own; nothing under the real Application Support is +/// read, written or removed here. +final class ReviewSubHostStateTests: XCTestCase { + private var root: URL! + private var server: HostServer? + /// `AGENTTERM_STATE_DIR` as the tests were run with it. + private var given: String? + + /// Every host started here has the test's folder for its state folder, + /// so that none of them does to the build's own what #269 is about. + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-state-\(UUID().uuidString)").standardizedFileURL + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + given = ProcessInfo.processInfo.environment["AGENTTERM_STATE_DIR"] + setenv("AGENTTERM_STATE_DIR", root.path, 1) + } + + override func tearDown() { + server?.stop() + if let given { setenv("AGENTTERM_STATE_DIR", given, 1) } else { unsetenv("AGENTTERM_STATE_DIR") } + try? FileManager.default.removeItem(at: root) + } + + /// Whether a file of the folder still holds these bytes: the file + /// itself, or a copy the host put aside. + private func kept(_ data: Data, in folder: URL) -> Bool { + let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? [] + return names.contains { FileManager.default.contents(atPath: folder.appendingPathComponent($0).path) == data } + } + + // MARK: #269 + + /// #269: a host started as most of the host's tests start one (a port, + /// a token, no file of its own named) removes nothing from the state + /// folder of the build. The folder is stood in for by one of the + /// test's, through `AGENTTERM_STATE_DIR`, for this test only: where a + /// run of the tests without that variable looks is said by + /// `testWhereAHostOfTheTestsKeepsTheInstructions`. + func testAHostOfATestRemovesNoInstructionsOfTheBuild() throws { + let prompt = HostServer.promptFile(for: "claude") + XCTAssertTrue(prompt.path.hasPrefix(root.path), "not in the test's folder: nothing is done") + guard prompt.path.hasPrefix(root.path) else { return } + try FileManager.default.createDirectory(at: prompt.deletingLastPathComponent(), withIntermediateDirectories: true) + try "Run your commands in AgentTerm's shells.".write(to: prompt, atomically: true, encoding: .utf8) + + let host = HostServer(configuration: HostServer.Configuration(port: 0, token: "review-token-0123456789abcdef0123456789", listenOnTailscale: false, detectAgents: { [] })) + server = host + _ = try host.start() + host.stop() + server = nil + XCTAssertTrue(FileManager.default.fileExists(atPath: prompt.path), "the host of a test removed the instructions kept for Claude Code's server") + } + + /// #269: a host is given where to keep the instructions; one given + /// none (as a test's) neither reads nor writes any. + func testAHostGivenNoFolderForTheInstructionsKeepsNone() { + XCTAssertNil(HostServer.Configuration(port: 0, token: "t", listenOnTailscale: false, detectAgents: { [] }).promptsDirectory) + } + + // MARK: #273 + + /// #273: a `schedules.json` the host cannot read is not written over + /// with no schedules: it is left as it was, or kept aside. + func testSchedulesThatCannotBeReadAreNotWrittenOver() throws { + let file = root.appendingPathComponent("schedules.json") + let theirs = Data(#"{"schedules":[{"id":"s1","name":"Nightly","agent":"claude","when":{"kindOfALaterBuild":true}}]}"#.utf8) + try theirs.write(to: file) + var configuration = HostServer.Configuration( + port: 0, token: "review-token-0123456789abcdef0123456789", listenOnTailscale: false, detectAgents: { [] }, + foldersFile: root.appendingPathComponent("folders.json"), devicesFile: root.appendingPathComponent("devices.json"), home: root.path) + configuration.scheduleInterval = 0.2 + let host = HostServer(configuration: configuration) + server = host + _ = try host.start() + let deadline = Date().addingTimeInterval(3) + while Date() < deadline, FileManager.default.contents(atPath: file.path) == theirs { RunLoop.main.run(until: Date().addingTimeInterval(0.05)) } + host.stop() + server = nil + let now = String(decoding: FileManager.default.contents(atPath: file.path) ?? Data(), as: UTF8.self) + XCTAssertTrue(kept(theirs, in: root), "the schedules that could not be read are gone; the file now holds: \(now.prefix(200))") + } + + /// #273: a `devices.json` the host cannot read is not written over when + /// the next device is paired. + func testPairedDevicesThatCannotBeReadAreNotWrittenOver() throws { + let file = root.appendingPathComponent("devices.json") + let theirs = Data(#"[{"id":"d1","name":"iPhone","tokenHash":"abc","pairedAt":"of a later build"}]"#.utf8) + try theirs.write(to: file) + let registry = DeviceRegistry(localToken: "review-token-0123456789abcdef0123456789", file: file) + let code = registry.createCode().code + XCTAssertNotNil(registry.redeem(code: code, deviceName: "iPad")) + let now = String(decoding: FileManager.default.contents(atPath: file.path) ?? Data(), as: UTF8.self) + XCTAssertTrue(kept(theirs, in: root), "the paired devices that could not be read are gone; the file now holds \(now.count) bytes without “iPhone”: \(!now.contains("iPhone"))") + } +} diff --git a/Tests/AgentTermHostTests/ReviewSubPushFailureTests.swift b/Tests/AgentTermHostTests/ReviewSubPushFailureTests.swift new file mode 100644 index 00000000..a4948793 --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubPushFailureTests.swift @@ -0,0 +1,175 @@ +import AgentTermClient +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// #272 (review of 2026-11-22): while the relay cannot be reached, each +/// notification that could not be sent takes the place of the one before +/// in the banner, but adds one more item to every Inbox. The relay is a +/// stand-in: nothing reaches the network. +final class ReviewSubPushFailureTests: XCTestCase { + private final class Relay { + let lock = NSLock() + var pushes = 0 + var reachable = true + + var transport: PushCenter.Transport { + { [weak self] url, _, done in + guard let self else { return done(0, nil) } + self.lock.lock() + let reachable = self.reachable + if url.path.hasSuffix("/v1/push") { self.pushes += 1 } + self.lock.unlock() + DispatchQueue.global().async { + guard reachable else { return done(0, Data(#"{"reason":"offline"}"#.utf8)) } + if url.path.hasSuffix("/v1/register") { + done(200, Data(#"{"ticket":"signed","expires":4102444800}"#.utf8)) + } else { + done(200, Data(#"{"ok":true}"#.utf8)) + } + } + } + } + + var sent: Int { + lock.lock() + defer { lock.unlock() } + return pushes + } + } + + private final class Client { + let connection: AgentTermConnection + var messages: [ServerMessage] = [] + + init(port: UInt16, credential: AgentTermConnection.Credential, name: String, kind: DeviceKind = .iphone) { + connection = AgentTermConnection(host: "127.0.0.1", port: port, credential: credential, clientName: name, kind: kind) + connection.onMessage = { [weak self] in self?.messages.append($0) } + connection.connect() + } + + var sessions: [SessionInfo] { messages.compactMap { if case .sessions(let list) = $0 { return list } else { return nil } }.last ?? [] } + var pushState: PushState? { messages.compactMap { if case .pushState(let state) = $0 { return state } else { return nil } }.last } + var token: String? { messages.compactMap { if case .paired(_, let token) = $0 { return token } else { return nil } }.first } + var code: String? { messages.compactMap { if case .pairingCode(let code, _) = $0 { return code } else { return nil } }.last } + var devices: [DeviceInfo]? { messages.compactMap { if case .devices(let list) = $0 { return list } else { return nil } }.last } + var failures: [PartFailure] { messages.compactMap { if case .failures(let list) = $0 { return list } else { return nil } }.last ?? [] } + /// The Inbox items that say a notification could not be sent. + var pushFailureNotices: [Notice] { + messages.compactMap { message -> Notice? in + guard case .notice(let notice) = message, case .failure(let failure) = notice.kind, failure.part == .push else { return nil } + return notice + } + } + } + + private var root: URL! + private var server: HostServer! + private var port: UInt16 = 0 + private let token = "review-token-0123456789abcdef0123456789" + private var relay: Relay! + private var given: String? + private var stateSet = false + private var tool: URL { Bundle(for: ReviewSubPushFailureTests.self).bundleURL.deletingLastPathComponent().appendingPathComponent("agenttermd") } + + override func setUpWithError() throws { + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tool.path), "agenttermd is not built next to the tests") + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-push-\(UUID().uuidString)").standardizedFileURL + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + relay = Relay() + // The host's own state folder too: see #269. + given = ProcessInfo.processInfo.environment["AGENTTERM_STATE_DIR"] + setenv("AGENTTERM_STATE_DIR", root.appendingPathComponent("state").path, 1) + stateSet = true + var configuration = HostServer.Configuration( + port: 0, token: token, listenOnTailscale: false, detectAgents: { [] }, devicesFile: root.appendingPathComponent("devices.json"), + statusLineTool: tool.path, usageDirectory: root.appendingPathComponent("usage")) + configuration.hooksDirectory = root.appendingPathComponent("hooks") + configuration.home = root.path + configuration.holdAwake = { _, _ in true } + configuration.isOnPower = { true } + configuration.idleSeconds = { 6 * 60 } + configuration.refreshInterval = 0.2 + configuration.pushRelay = URL(string: "https://relay.test") + configuration.pushesFile = root.appendingPathComponent("pushes.json") + configuration.pushTransport = relay.transport + configuration.alertDelay = 0.3 + server = HostServer(configuration: configuration) + port = try server.start() + } + + override func tearDown() { + server?.stop() + if stateSet { if let given { setenv("AGENTTERM_STATE_DIR", given, 1) } else { unsetenv("AGENTTERM_STATE_DIR") } } + if let root { try? FileManager.default.removeItem(at: root) } + } + + private func waitUntil(_ what: String, timeout: TimeInterval = 10, _ condition: () -> Bool) { + let deadline = Date().addingTimeInterval(timeout) + while !condition() && Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.02)) } + XCTAssertTrue(condition(), "timed out waiting for: \(what)") + } + + /// A stand-in for Claude Code that tells its hooks, one step for each + /// line on its input: working, then asking permission and working + /// again, three times over. + private func standIn() throws -> URL { + let script = root.appendingPathComponent("claude") + let hook = Handoff.shellQuote(tool.path) + " hook claude" + let ask = """ + read line; printf '%s' '{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"make test"}}' | \(hook) PermissionRequest + read line; printf '%s' '{"hook_event_name":"PostToolUse","tool_name":"Bash"}' | \(hook) PostToolUse + """ + try """ + #!/bin/sh + read line; printf '%s' '{"hook_event_name":"UserPromptSubmit","prompt":"go"}' | \(hook) UserPromptSubmit + \(ask) + \(ask) + \(ask) + exec sleep 600 + """.write(to: script, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + return script + } + + /// #272: three notifications that the relay could not take are one + /// item in the Inbox, the newest, as they are one in the banner. + func testNotificationsTheRelayCouldNotTakeAreOneItemInTheInbox() throws { + let mac = Client(port: port, credential: .token(token), name: "mac", kind: .mac) + mac.connection.send(.createPairingCode) + waitUntil("a code") { mac.code != nil } + let pairing = Client(port: port, credential: .pairingCode(try XCTUnwrap(mac.code)), name: "iPhone") + waitUntil("paired") { pairing.token != nil } + let phoneToken = try XCTUnwrap(pairing.token) + pairing.connection.close() + let phone = Client(port: port, credential: .token(phoneToken), name: "iPhone") + waitUntil("told it is off") { phone.pushState == .off } + phone.connection.send(.pushRegister(PushRegistration(token: String(repeating: "ab", count: 32), key: PushSeal.newKey(), mac: "6B1E2C3D-mac"))) + waitUntil("registered") { phone.pushState == .on } + mac.connection.send(.create(CreateRequest(command: try standIn().path, cwd: root.path, title: "agent"))) + waitUntil("the session") { mac.sessions.count == 1 } + let agent = try XCTUnwrap(mac.sessions.first).id + mac.connection.send(.attach(session: agent, size: TermSize(cols: 80, rows: 24))) + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("working") { mac.sessions.first?.state?.isWorking == true } + phone.connection.close() + waitUntil("the phone gone") { mac.devices?.first?.isConnected == false } + + relay.lock.lock(); relay.reachable = false; relay.lock.unlock() + // Three questions, each one a notification the relay does not take. + for round in 1...3 { + let before = relay.sent + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("question \(round) sent to the relay") { relay.sent > before } + waitUntil("its failure said") { mac.pushFailureNotices.count >= 1 } + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("working again") { mac.sessions.first?.state?.isWorking == true } + } + RunLoop.main.run(until: Date().addingTimeInterval(0.5)) + XCTAssertEqual(mac.failures.filter { $0.part == .push }.count, 1, "the banner: one for the device, the newest") + XCTAssertEqual( + mac.pushFailureNotices.count, 1, + "the Inbox got \(mac.pushFailureNotices.count) items for \(relay.sent) notifications the relay did not take") + } +} diff --git a/Tests/AgentTermHostTests/ReviewSubStatusLineTests.swift b/Tests/AgentTermHostTests/ReviewSubStatusLineTests.swift new file mode 100644 index 00000000..b3086dbc --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubStatusLineTests.swift @@ -0,0 +1,135 @@ +import AgentTermProtocol +import XCTest + +@testable import AgentTermHost + +/// SETUP-11 (#259): two builds' status line relays never run each other +/// without end. A build set up after the other runs the other's after its +/// own (MCP-15), once; the relay that one runs runs only the user's, and a +/// build set up again keeps the user's own over the other build's. +final class ReviewSubStatusLineTests: XCTestCase { + private var root: URL! + private var home: URL { root.appendingPathComponent("home") } + private var tool: URL { Bundle(for: ReviewSubStatusLineTests.self).bundleURL.deletingLastPathComponent().appendingPathComponent("agenttermd") } + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-statusline-\(UUID().uuidString)").standardizedFileURL + try FileManager.default.createDirectory(at: home.appendingPathComponent(".claude"), withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + } + + private func setup(name: String, tool: String) -> AgentSetup { + AgentSetup( + directory: root.appendingPathComponent("setup-\(name)"), tool: tool, home: home.path, name: name, environment: [:], + locate: { [] }, prompt: { _ in nil }, run: { _ in nil }) + } + + private func keptCommand(_ setup: AgentSetup) throws -> String? { + let file = AgentSetup.previousStatusLine(in: root.appendingPathComponent("setup-\(setup.name)")) + guard let data = FileManager.default.contents(atPath: file.path) else { return nil } + return (try JSONSerialization.jsonObject(with: data) as? [String: Any])?["command"] as? String + } + + /// The released build is set up, then the development build, then the + /// released build again (it says its status line is "not known"). The + /// released build keeps the user's own; the development build the + /// released build's, which it took the place of. + func testSetUpAgainAfterTheOtherBuildTheUsersOwnIsKept() throws { + let settings = home.appendingPathComponent(".claude/settings.json") + try #"{"statusLine":{"type":"command","command":"printf mine"}}"#.write(to: settings, atomically: true, encoding: .utf8) + let released = setup(name: "agentterm", tool: "/Applications/AgentTerm.app/Contents/MacOS/agenttermd") + let development = setup(name: "agentterm-dev", tool: "/Applications/AgentTerm Dev.app/Contents/MacOS/agenttermd") + + try released.setClaudeStatusLine() + XCTAssertEqual(try keptCommand(released), "printf mine") + try development.setClaudeStatusLine() + XCTAssertEqual(try keptCommand(development), released.statusLineCommand) + try released.setClaudeStatusLine() + XCTAssertEqual(try keptCommand(released), "printf mine", "the released build no longer keeps the user's own status line") + } + + /// A stand-in relay that writes a line for each time it is run, and + /// whether it was run by a relay. + private func standInRelay() throws -> (command: String, ran: URL) { + let bin = root.appendingPathComponent("bin") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + let ran = root.appendingPathComponent("ran") + let standIn = bin.appendingPathComponent("agenttermd") + try "#!/bin/sh\necho \"run ${\(StatusLineRelay.relayedVariable):-}\" >> '\(ran.path)'\n".write(to: standIn, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: standIn.path) + return (Handoff.shellQuote(standIn.path) + " statusline", ran) + } + + private func lines(_ file: URL) -> [String] { + ((try? String(contentsOf: file, encoding: .utf8)) ?? "").split(separator: "\n").map(String.init) + } + + /// The other build's relay, kept, is run, and told it is run by a relay. + func testTheOtherBuildsRelayIsRunToldItIsRelayed() throws { + let (command, ran) = try standInRelay() + let previous = root.appendingPathComponent("previous-status-line.json") + try JSONSerialization.data(withJSONObject: ["type": "command", "command": command]).write(to: previous) + _ = StatusLineRelay.run(input: Data(#"{"cwd":"/tmp"}"#.utf8), file: nil, previous: previous, home: home.path, environment: [:]) + XCTAssertEqual(lines(ran), ["run 1"]) + } + + /// A relay run by a relay runs no relay it keeps. + func testARelayRunByARelayRunsNoRelay() throws { + let (command, ran) = try standInRelay() + let previous = root.appendingPathComponent("previous-status-line.json") + try JSONSerialization.data(withJSONObject: ["type": "command", "command": command]).write(to: previous) + _ = StatusLineRelay.run( + input: Data(#"{"cwd":"/tmp"}"#.utf8), file: nil, previous: previous, home: home.path, environment: [StatusLineRelay.relayedVariable: "1"]) + XCTAssertEqual(lines(ran), [], "a relay run by a relay ran the relay it keeps") + } + + /// The real `agenttermd statusline`, whose kept command leads back to + /// itself, as two builds that keep each other's do, goes round once. + /// It leads back through a stand-in that counts and gives up after 4 + /// turns, so that the test cannot run for ever: before the fix each + /// turn started the next with no end. + func testTheRealRelayDoesNotRunItselfAgain() throws { + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tool.path), "agenttermd is not built next to the tests") + let state = root.appendingPathComponent("state") + let bin = root.appendingPathComponent("bin") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + let turns = root.appendingPathComponent("turns") + let standIn = bin.appendingPathComponent("agenttermd") + try """ + #!/bin/sh + echo turn >> '\(turns.path)' + [ "$(wc -l < '\(turns.path)')" -ge 4 ] && exit 0 + exec '\(tool.path)' statusline + + """.write(to: standIn, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: standIn.path) + let previous = AgentSetup.previousStatusLine(in: state.appendingPathComponent("agent-setup")) + try FileManager.default.createDirectory(at: previous.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONSerialization.data(withJSONObject: ["type": "command", "command": Handoff.shellQuote(standIn.path) + " statusline"]).write(to: previous) + + let process = Process() + process.executableURL = tool + process.arguments = ["statusline"] + var environment = OwnEnvironment.withoutAgentTerms + environment["AGENTTERM_STATE_DIR"] = state.path + environment["HOME"] = home.path + process.environment = environment + let input = Pipe() + process.standardInput = input + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + input.fileHandleForWriting.write(Data(#"{"cwd":"/tmp"}"#.utf8)) + try input.fileHandleForWriting.close() + let deadline = Date().addingTimeInterval(30) + while process.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.05) } + if process.isRunning { process.terminate() } + _ = Subprocess.run("/usr/bin/pkill", ["-f", root.path]) + + let count = ((try? String(contentsOf: turns, encoding: .utf8)) ?? "").split(separator: "\n").count + XCTAssertEqual(count, 1, "the real relay went round \(count) times through a kept command that is an AgentTerm status line") + } +} diff --git a/Tests/AgentTermHostTests/ReviewSubTimeoutTests.swift b/Tests/AgentTermHostTests/ReviewSubTimeoutTests.swift new file mode 100644 index 00000000..76ced33c --- /dev/null +++ b/Tests/AgentTermHostTests/ReviewSubTimeoutTests.swift @@ -0,0 +1,66 @@ +import XCTest + +@testable import AgentTermHost + +/// #261 (review of 2026-11-22): the time limit of a command the host runs +/// holds, whatever the command does with the signal and whoever else holds +/// its output. Every command here ends by itself within 12 seconds, so a +/// test that fails leaves nothing running. +final class ReviewSubTimeoutTests: XCTestCase { + private let limit: TimeInterval = 5 + + /// #261: a child of the command keeps the pipe open after the command + /// itself was stopped (a hook or a startup file that leaves a program + /// in the background). + func testTheLimitHoldsWhenAChildKeepsTheOutputOpen() throws { + let started = Date() + let result = try XCTUnwrap(Subprocess.run("/bin/sh", ["-c", "/bin/sleep 12 & wait"], timeout: 0.5)) + let took = Date().timeIntervalSince(started) + XCTAssertEqual(result.ending, .timedOut) + XCTAssertLessThan(took, limit, "a command given half a second was waited for \(Int(took)) seconds") + } + + /// #261: the command does not end at SIGTERM (a login shell still in + /// its startup files does not). + func testTheLimitHoldsWhenTheCommandDoesNotEndAtTheSignal() throws { + let started = Date() + let result = try XCTUnwrap(Subprocess.run("/bin/sh", ["-c", "trap '' TERM; /bin/sleep 12"], timeout: 0.5)) + let took = Date().timeIntervalSince(started) + XCTAssertEqual(result.ending, .timedOut) + XCTAssertLessThan(took, limit, "a command given half a second was waited for \(Int(took)) seconds") + } + + private func relayTakes(_ command: String) throws -> TimeInterval { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("agentterm-review-timeout-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let previous = root.appendingPathComponent("previous-status-line.json") + try JSONSerialization.data(withJSONObject: ["type": "command", "command": command]).write(to: previous) + let started = Date() + _ = StatusLineRelay.run(input: Data(#"{"cwd":"/tmp"}"#.utf8), file: nil, previous: previous, home: root.path, environment: [:]) + return Date().timeIntervalSince(started) + } + + /// #261 (the status line relay): its 5 seconds hold for a status line + /// that is a pipeline, whose programs keep the output open after the + /// shell was stopped. (Seen to pass on 2026-11-23: Foundation's + /// `terminate` reaches the pipeline's programs too.) + func testTheStatusLineRelaysLimitHoldsForAPipeline() throws { + let took = try relayTakes("/bin/sleep 12 | /bin/cat") + XCTAssertLessThan(took, 8, "a status line limited to 5 seconds was waited for \(Int(took)) seconds") + } + + /// #261 (the status line relay): its 5 seconds hold for a status line + /// that does not end at SIGTERM. + func testTheStatusLineRelaysLimitHoldsWhenTheStatusLineDoesNotEndAtTheSignal() throws { + let took = try relayTakes("trap '' TERM; /bin/sleep 12") + XCTAssertLessThan(took, 8, "a status line limited to 5 seconds was waited for \(Int(took)) seconds") + } + + /// #261 (the status line relay): and for one that leaves a program of + /// its own session behind, holding the output. + func testTheStatusLineRelaysLimitHoldsWhenAProgramIsLeftBehind() throws { + let took = try relayTakes("/usr/bin/perl -e 'use POSIX; setsid(); sleep 12' & wait") + XCTAssertLessThan(took, 8, "a status line limited to 5 seconds was waited for \(Int(took)) seconds") + } +} diff --git a/Tests/AgentTermHostTests/ScheduleTests.swift b/Tests/AgentTermHostTests/ScheduleTests.swift index 4beea4dc..d4c2bd2f 100644 --- a/Tests/AgentTermHostTests/ScheduleTests.swift +++ b/Tests/AgentTermHostTests/ScheduleTests.swift @@ -282,6 +282,25 @@ final class SchedulerHostTests: XCTestCase { XCTAssertEqual(((settings["projects"] as? [String: Any])?[project.path] as? [String: Any])?["hasTrustDialogAccepted"] as? Bool, true) } + /// SCHED-37 (#291): a weekly schedule with no day, or a day of the week + /// out of Sunday (1) to Saturday (7), is refused in words, and nothing + /// is kept: before the fix a day of -7 was kept and sent to every device, + /// whose lists stopped the app while showing it, and the host stopped on + /// its next change. + func testAWeeklyScheduleWithADayThatIsNoneIsRefused() throws { + for days in [[-7], [0], [8], []] { + var schedule = morning() + schedule.id = "weekly-\(days)" + schedule.when = .weekly(weekdays: days, hour: 9, minute: 0) + let before = client.errors.count + client.connection.send(.saveSchedule(schedule)) + waitUntil("refused: \(days)") { self.client.errors.count > before } + XCTAssertEqual(client.errors.last, ScheduleTime.daysRefusal, "\(days)") + } + pause() + XCTAssertEqual(client.schedules, []) + } + /// SCHED-5: at its time, a session of its agent starts in its folder, /// with its prompt and the switch of its mode, named after it, once. func testAScheduleRunsAtItsTimeOnce() throws { diff --git a/Tests/AgentTermHostTests/TestScriptHostsTests.swift b/Tests/AgentTermHostTests/TestScriptHostsTests.swift new file mode 100644 index 00000000..b065dfc9 --- /dev/null +++ b/Tests/AgentTermHostTests/TestScriptHostsTests.swift @@ -0,0 +1,33 @@ +import Foundation +import XCTest + +/// TEST-14 (#310): every host a test script starts lives in the test's home +/// and never asks the agents' services with the sign-ins of the person +/// running the tests. +final class TestScriptHostsTests: XCTestCase { + private static let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + + /// The lines of the test scripts that start a host: the only ones with + /// `--local-only`. + private func hostLines() throws -> [(script: String, line: String)] { + var found: [(String, String)] = [] + for script in ["test-ios.sh", "test-both.sh", "screenshots.sh"] { + let text = try String(contentsOf: Self.repository.appendingPathComponent("scripts/\(script)"), encoding: .utf8) + for line in text.components(separatedBy: "\n") where line.contains("--local-only") && !line.trimmingCharacters(in: .whitespaces).hasPrefix("#") { + found.append((script, line)) + } + } + return found + } + + func testEveryHostOfATestScriptHasItsOwnHomeAndAsksNoService() throws { + let lines = try hostLines() + XCTAssertGreaterThanOrEqual(lines.count, 4, "the hosts of test-ios.sh (2), test-both.sh and screenshots.sh") + for (script, line) in lines { + let start = String(line.prefix(80)) + XCTAssertTrue(line.contains("--no-account-usage"), "\(script): a host asks the agents' services: \(start)…") + XCTAssertTrue(line.contains("HOME=\"$FAKE_HOME\""), "\(script): a host runs in the home of the person running the tests: \(start)…") + XCTAssertTrue(line.contains("--home \"$FAKE_HOME\""), "\(script): a host looks at the agents of the person running the tests: \(start)…") + } + } +} diff --git a/Tests/AgentTermHostTests/TestScriptLogTests.swift b/Tests/AgentTermHostTests/TestScriptLogTests.swift new file mode 100644 index 00000000..cef1e28b --- /dev/null +++ b/Tests/AgentTermHostTests/TestScriptLogTests.swift @@ -0,0 +1,134 @@ +import Foundation +import XCTest + +/// TEST-12 (#309): a run of UI tests in which nothing was checked is not +/// reported as passed by the scripts that run them. +final class TestScriptLogTests: XCTestCase { + private static let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + private static let library = repository.appendingPathComponent("scripts/lib-test-log.sh").path + + /// What `nothing_checked` says of a log: its words when nothing was + /// checked, nil when something was. + private func nothingChecked(_ log: String) throws -> String? { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("test-log-\(UUID().uuidString).log") + try log.write(to: file, atomically: true, encoding: .utf8) + defer { try? FileManager.default.removeItem(at: file) } + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/bash") + process.arguments = ["-c", "source \"$1\"; nothing_checked \"$2\"", "bash", Self.library, file.path] + let output = Pipe() + process.standardOutput = output + try process.run() + let words = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + return process.terminationStatus == 0 ? words.trimmingCharacters(in: .whitespacesAndNewlines) : nil + } + + /// The end of a log of `swift test`, as XCTest writes it, with + /// `executed` tests of which `skipped` skipped themselves. + private func log(executed: Int, skipped: Int, reason: String = "run through scripts/screenshots.sh") -> String { + var lines: [String] = [] + for index in 0.. 0 ? "with \(skipped) test\(skipped == 1 ? "" : "s") skipped and 0 failures" : "with 0 failures" + for suite in ["X", "AgentTermPackageTests.xctest", "All tests"] { + lines.append("Test Suite '\(suite)' passed at 2026-11-22 23:55:56.385.") + lines.append("\t Executed \(count), \(with) (0 unexpected) in 0.002 (0.002) seconds") + } + return lines.joined(separator: "\n") + "\n" + } + + /// What `swift test --filter` prints: each test bundle run on its own, + /// in its own "Selected tests", the one with the test among bundles + /// with none (as `test-both.sh` saw it on 2026-11-23). + private func bundles(_ counts: [(name: String, executed: Int, skipped: Int)]) -> String { + var lines: [String] = [] + for bundle in counts { + let with = bundle.skipped > 0 ? "with \(bundle.skipped) tests skipped and 0 failures" : "with 0 failures" + lines.append("Test Suite 'Selected tests' started at 2026-11-23 08:42:58.056.") + lines.append("Test Suite '\(bundle.name).xctest' started at 2026-11-23 08:42:58.057.") + if bundle.executed > 0 { + lines.append("Test Suite 'CrossTests' passed at 2026-11-23 08:43:03.360.") + lines.append("\t Executed \(bundle.executed) tests, \(with) (0 unexpected) in 5.084 (5.084) seconds") + } + lines.append("Test Suite '\(bundle.name).xctest' passed at 2026-11-23 08:43:03.360.") + lines.append("\t Executed \(bundle.executed) tests, \(with) (0 unexpected) in 5.084 (5.084) seconds") + lines.append("Test Suite 'Selected tests' passed at 2026-11-23 08:43:03.360.") + lines.append("\t Executed \(bundle.executed) tests, \(with) (0 unexpected) in 5.084 (5.085) seconds") + } + return lines.joined(separator: "\n") + "\n" + } + + /// TEST-12: the bundles are added up, not the last one taken. + func testEveryBundleOfARunIsCounted() throws { + XCTAssertNil(try nothingChecked(bundles([("AgentTermTerminalTests", 0, 0), ("AgentTermMacUITests", 1, 0), ("AgentTermEditorTests", 0, 0)]))) + XCTAssertEqual( + try nothingChecked(bundles([("AgentTermTerminalTests", 0, 0), ("AgentTermEditorTests", 0, 0)])), "no test was run") + XCTAssertEqual( + try nothingChecked(bundles([("AgentTermMacUITests", 2, 2), ("AgentTermEditorTests", 0, 0)])), "every test that was run skipped itself (2 of 2)") + } + + func testARunWhereEveryTestSkippedItselfCheckedNothing() throws { + XCTAssertEqual(try nothingChecked(log(executed: 3, skipped: 3)), "every test that was run skipped itself (3 of 3)") + XCTAssertEqual(try nothingChecked(log(executed: 1, skipped: 1)), "every test that was run skipped itself (1 of 1)") + } + + func testARunWithoutAccessibilityCheckedNothing() throws { + let reason = "allow this terminal under System Settings > Privacy & Security > Accessibility" + let words = try nothingChecked(log(executed: 5, skipped: 2, reason: reason)) + XCTAssertNotNil(words) + XCTAssertTrue(words?.contains("Accessibility") ?? false, words ?? "") + } + + func testARunOfNoTestCheckedNothing() throws { + XCTAssertEqual(try nothingChecked("Build complete!\n"), "no test was run") + XCTAssertEqual(try nothingChecked(log(executed: 0, skipped: 0)), "no test was run") + } + + func testARunWhereSomeTestsPassedCheckedSomething() throws { + XCTAssertNil(try nothingChecked(log(executed: 3, skipped: 0))) + // The pictures' tests skip themselves when not run by their script: + // the others of the run were checked all the same. + XCTAssertNil(try nothingChecked(log(executed: 4, skipped: 1))) + XCTAssertNil(try nothingChecked(log(executed: 1, skipped: 0))) + } + + /// Each script that runs UI tests asks `nothing_checked` of every run it + /// reports as passed. Before the fix `test-mac.sh` asked only whether a + /// test was executed, `test-both.sh` and `screenshots.sh` nothing, and + /// the modes of `test-ios.sh` that run one step nothing (#319). + func testEveryScriptThatRunsUITestsAsksWhetherSomethingWasChecked() throws { + for script in ["test-mac.sh", "test-both.sh", "screenshots.sh", "test-ios.sh"] { + let text = try String(contentsOf: Self.repository.appendingPathComponent("scripts/\(script)"), encoding: .utf8) + XCTAssertTrue(text.contains("source scripts/lib-test-log.sh"), "\(script) does not source lib-test-log.sh") + XCTAssertTrue(text.contains("nothing_checked \"$LOG\""), "\(script) does not ask nothing_checked of its log") + } + } + + /// TEST-15 (#319): `NARROW=only` narrows an iPad's window; on an iPhone + /// the test returns at once, having checked nothing, so the script + /// refuses it before building anything. + func testNarrowOnlyOnAnIPhoneIsRefused() throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/bash") + let script = Self.repository.appendingPathComponent("scripts/test-ios.sh").path + // Only the lines up to the refusal are run: past them the script builds. + process.arguments = ["-c", "SIM_NAME='iPhone Air'; NARROW=only; eval \"$(sed -n '/^# NARROW=only is for an iPad/,/^fi$/p' \"$1\")\"; echo went-on", "bash", script] + let output = Pipe() + process.standardOutput = output + process.standardError = output + try process.run() + let words = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + XCTAssertNotEqual(process.terminationStatus, 0, words) + XCTAssertFalse(words.contains("went-on"), words) + XCTAssertTrue(words.contains("NARROW=only narrows an iPad's window"), words) + } +} diff --git a/Tests/AgentTermHostTests/TestSimulatorChoiceTests.swift b/Tests/AgentTermHostTests/TestSimulatorChoiceTests.swift new file mode 100644 index 00000000..8d811fd9 --- /dev/null +++ b/Tests/AgentTermHostTests/TestSimulatorChoiceTests.swift @@ -0,0 +1,65 @@ +import Foundation +import XCTest + +/// TEST-13 (#311): a test script that resets a simulator's keychain, run +/// with no simulator named and not from a terminal, takes "iPhone Air", never +/// the booted simulator, which is most likely the one in use. +final class TestSimulatorChoiceTests: XCTestCase { + private static let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + + /// What `choose_test_simulator` takes, with a stand-in `xcrun` that lists + /// "iPhone Air" shut down and "iPhone 17" booted; nothing real is asked. + private func chosen(argument: String, simulator: String? = nil) throws -> String { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("sim-choice-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let xcrun = folder.appendingPathComponent("xcrun") + try """ + #!/bin/bash + cat <<'L' + == Devices == + -- iOS 27.2 -- + iPhone Air (11111111-1111-1111-1111-111111111111) (Shutdown) + iPhone 17 (22222222-2222-2222-2222-222222222222) (Booted) + L + """.write(to: xcrun, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: xcrun.path) + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/bash") + process.arguments = ["-c", "source scripts/lib-simulator.sh; choose_test_simulator \"$1\" >/dev/null; echo \"$SIM_NAME\"", "bash", argument] + process.currentDirectoryURL = Self.repository + var environment = ProcessInfo.processInfo.environment + environment["PATH"] = folder.path + ":" + (environment["PATH"] ?? "/usr/bin:/bin") + environment["SIMULATOR"] = simulator + process.environment = environment + // Not a terminal: as an agent or another script runs it. + process.standardInput = FileHandle.nullDevice + let output = Pipe() + process.standardOutput = output + try process.run() + let name = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0) + return name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func testWithNoSimulatorNamedNotFromATerminalItIsIPhoneAirAndNotTheBootedOne() throws { + XCTAssertEqual(try chosen(argument: ""), "iPhone Air") + } + + func testASimulatorNamedIsTheOneTaken() throws { + XCTAssertEqual(try chosen(argument: "iPhone 17"), "iPhone 17") + XCTAssertEqual(try chosen(argument: "", simulator: "iPhone 17"), "iPhone 17") + } + + /// Both scripts that reset the keychain choose this way. Before the fix + /// `test-both.sh` called `choose_simulator "${1:-}"`, which takes the + /// booted simulator when not run from a terminal. + func testTheScriptsThatResetAKeychainChooseThisWay() throws { + for script in ["test-ios.sh", "test-both.sh"] { + let text = try String(contentsOf: Self.repository.appendingPathComponent("scripts/\(script)"), encoding: .utf8) + XCTAssertTrue(text.contains("choose_test_simulator \"${1:-}\""), "\(script) does not use choose_test_simulator") + XCTAssertFalse(text.contains("choose_simulator \"${1:-}\""), "\(script) still takes the booted simulator") + } + } +} diff --git a/Tests/AgentTermMacUITests/FilesTests.swift b/Tests/AgentTermMacUITests/FilesTests.swift index c597149c..c2b57ade 100644 --- a/Tests/AgentTermMacUITests/FilesTests.swift +++ b/Tests/AgentTermMacUITests/FilesTests.swift @@ -1,4 +1,5 @@ import AgentTermProtocol +import AppKit import XCTest /// The Files tab of the Mac app and the files open in the middle pane. @@ -83,6 +84,38 @@ final class FilesTests: MacUITestCase { XCTAssertTrue(app.exists(.button("Save"))) } + /// Asks the app to quit as ⌘Q and the Dock's Quit do: through the + /// system, so that it may answer. + private func askToQuit() { + guard let pid = app.process?.processIdentifier else { return XCTFail("no app") } + XCTAssertTrue(NSRunningApplication(processIdentifier: pid)?.terminate() == true, "the app was not asked to quit") + } + + /// FILE-15 (#298): quitting with unsaved changes asks first; Cancel + /// keeps the app and the edits, Quit Without Saving quits. + func testQuittingWithUnsavedChangesAsksFirst() throws { + app.press(.button("Files")) + app.press(.button("notes.txt"), timeout: 15) + let editor = MacDriver.Query.role(kAXTextAreaRole as String) + let saved = "first line\nsecond line\n" + wait("the file's text in the editor") { self.app.value(of: editor) == saved } + app.write(saved + "not saved\n", into: editor) + app.wait(for: .button("Save")) + + askToQuit() + app.wait(for: .containing("Quit without saving notes.txt?"), timeout: 5) + shot("asked") + app.press(.button("Cancel")) + RunLoop.current.run(until: Date().addingTimeInterval(1)) + XCTAssertTrue(app.process?.isRunning == true, "the app quit with unsaved changes") + XCTAssertEqual(app.value(of: editor), saved + "not saved\n", "the edits were lost") + + askToQuit() + app.press(.button("Quit Without Saving"), timeout: 5) + wait("the app to quit", timeout: 10) { self.app.process?.isRunning != true } + XCTAssertEqual(read("notes.txt"), saved, "nothing was saved") + } + /// FIND-9 (#45): Go to File finds a file by part of its name and opens /// it; Find in Files finds a word with its file and line, and opens the /// file there, a Markdown file in its source. diff --git a/Tests/AgentTermMacUITests/GitTests.swift b/Tests/AgentTermMacUITests/GitTests.swift index 4ec4fd5e..3ec8a0d8 100644 --- a/Tests/AgentTermMacUITests/GitTests.swift +++ b/Tests/AgentTermMacUITests/GitTests.swift @@ -94,6 +94,44 @@ final class GitTests: MacUITestCase { XCTAssertTrue(FileManager.default.fileExists(atPath: trash.appendingPathComponent("docs/guide.md").path), "its folder went whole") } + /// GIT-82 (#297): a question about discarding, asked in one folder, is + /// never answered in another. The session in front ends while it is + /// open, and the one in a worktree of the same repository comes in + /// front: the question is closed, and that is said; the worktree's + /// change is still there. + func testAQuestionAskedInOneFolderIsNeverAnsweredInAnother() throws { + let phone = try device() + app.wait(for: .text("project, folder"), timeout: 15) + phone.send(.createInWorktree(request: CreateRequest(command: "exec sleep 600", cwd: project.path, title: "elsewhere"), branch: "feature/other", from: nil)) + wait("the worktree's session", timeout: 20) { phone.sessions.contains { $0.branch == "feature/other" } } + let other = try XCTUnwrap(phone.sessions.first { $0.branch == "feature/other" }) + // A change of the worktree's own, that discarding there would lose. + try "the other agent's work\n".write(toFile: other.cwd + "/notes.txt", atomically: true, encoding: .utf8) + phone.send(.create(CreateRequest(command: "exec sleep 600", cwd: project.path, title: "here"))) + wait("the session here", timeout: 20) { phone.sessions.contains { $0.title == "here" } } + let here = try XCTUnwrap(phone.sessions.first { $0.title == "here" }) + + app.press(.id("session-\(here.id)"), timeout: 15) + app.press(.button("Git")) + app.wait(for: .button("Stage notes.txt"), timeout: 15) + app.press(.button("Discard changes to notes.txt")) + app.wait(for: .containing("Discard the changes to notes.txt?")) + // The session in front ends while the question is open. + phone.send(.kill(session: here.id)) + wait("the session to end", timeout: 15) { !phone.sessions.contains { $0.id == here.id } } + app.wait("the worktree's session in front", timeout: 15) { self.app.first(.id("worktree-picker"))?.label.contains("feature/other") == true } + if app.exists(.button("Discard Changes")) { + // What the user would do: answer what they were asked. + app.press(.button("Discard Changes")) + } + RunLoop.main.run(until: Date().addingTimeInterval(1)) + XCTAssertEqual( + try String(contentsOfFile: other.cwd + "/notes.txt", encoding: .utf8), "the other agent's work\n", + "the discard asked in the project was done in the worktree") + app.wait(for: .containing(GitQuestionWords.closedForAnotherFolder), timeout: 5) + XCTAssertTrue(git("status", "--porcelain", in: project).contains("notes.txt"), "the project's change, which was asked about and not discarded, is gone") + } + /// GIT-68 (#50): Discard All throws away what it named and nothing /// else: not the new files past the fifty that are listed, nor a /// worktree of the repository inside the folder, as Claude Code keeps diff --git a/Tests/AgentTermProtocolTests/InboxBookTests.swift b/Tests/AgentTermProtocolTests/InboxBookTests.swift index dc0ab9b1..c340d25d 100644 --- a/Tests/AgentTermProtocolTests/InboxBookTests.swift +++ b/Tests/AgentTermProtocolTests/InboxBookTests.swift @@ -85,10 +85,9 @@ final class InboxBookTests: XCTestCase { XCTAssertEqual(book.entries.first { $0.id == 2 }?.read, true, "read in the host's log") book.take([notice(2, asked)], now: now) XCTAssertEqual(book.entries.first { $0.id == 2 }?.read, true, "never unread again") + // Moved on is read too (#321, the owner's decision of 2026-11-23). book.handled(3, Notice.Handled(at: now, how: .movedOn)) - XCTAssertEqual(book.entries.first { $0.id == 3 }?.read, false, "moved on is not read") - book.handled(3, Notice.Handled(at: now, how: .opened)) - XCTAssertEqual(book.entries.first { $0.id == 3 }?.read, true) + XCTAssertEqual(book.entries.first { $0.id == 3 }?.read, true, "moved on is read") XCTAssertEqual(book.unread, 0) // The host's log knows 2 as read; 1 and 3 were read here only. diff --git a/Tests/AgentTermProtocolTests/ReviewMessageTests.swift b/Tests/AgentTermProtocolTests/ReviewMessageTests.swift new file mode 100644 index 00000000..9003b69c --- /dev/null +++ b/Tests/AgentTermProtocolTests/ReviewMessageTests.swift @@ -0,0 +1,84 @@ +import AgentTermProtocol +import XCTest + +/// What the review of 2026-11-22 found in what is encoded, sealed and put +/// into words from numbers a peer sends (#292, #294, #296). +final class ReviewMessageTests: XCTestCase { + + // MARK: #292 + + /// #292: a message with a number JSON has no way to write (not a + /// number, infinite) is not turned into an empty frame. + func testAMessageThatCannotBeEncodedIsNotAnEmptyFrame() { + for cpu in [Double.nan, .infinity] { + let frame = MessageCoding.encode(ServerMessage.systemStats(SystemStats(cpuPercent: cpu))) + XCTAssertFalse(frame.isEmpty, "systemStats with cpuPercent \(cpu) is encoded as \(frame.count) bytes") + } + let usage = AccountUsage(agent: "claude", groups: [AccountUsageGroup(limits: [AccountLimit(id: "w", title: "Week", shortTitle: "Week", usedPercent: .nan)])]) + XCTAssertFalse(MessageCoding.encode(usage).isEmpty, "an account's usage with a percentage that is not a number is encoded as nothing") + // And read back as it was. + let read = MessageCoding.decode(ServerMessage.self, from: MessageCoding.encode(ServerMessage.systemStats(SystemStats(cpuPercent: .infinity)))) + guard case .systemStats(let stats)? = read else { return XCTFail("not read back: \(String(describing: read))") } + XCTAssertEqual(stats.cpuPercent, .infinity) + } + + // MARK: #294 + + /// #294: a notice of the longest kind fits in a push whatever it is + /// written in: the relay takes 3000 characters, and Apple 4 KB in all. + func testTheLongestNoticeFitsInAPushInAnyScript() throws { + let question = String(repeating: "この変更をどのブランチに入れますか。", count: 40) + let choices = (1...9).map { "選択肢\($0)" + String(repeating: "あ", count: 90) } + let notice = Notice( + id: UInt64.max, at: Date(), session: 4_000_000_000, name: String(repeating: "名", count: 100), folder: "/Users/someone/" + String(repeating: "フ", count: 200), + kind: .agent(.waitingForAnswer(AgentQuestion(text: question, choices: choices)))) + let pushed = PushNotice(notice) + let plain = try JSONEncoder().encode(pushed) + let sealed = try PushSeal.seal(pushed, identifier: "8C2D1E7A-0B4C-4E59-9D3A-1F2E3D4C5B6A-18446744073709551615", key: PushSeal.newKey()) + XCTAssertLessThanOrEqual(sealed.count, 3000, "the notice is \(plain.count) bytes of JSON and \(sealed.count) characters sealed; the relay takes 3000") + } + + // MARK: #296 + + /// #296: what an `Int` cannot hold is the nearest it can. + func testANumberOutOfRangeIsTheNearestWholeNumber() { + XCTAssertEqual(Int(saturating: 1e300), .max) + XCTAssertEqual(Int(saturating: -1e300), .min) + XCTAssertEqual(Int(saturating: .infinity), .max) + XCTAssertEqual(Int(saturating: .nan), 0) + XCTAssertEqual(Int(saturating: 41.9), 41) + XCTAssertEqual(Int(saturating: -2.5), -2) + XCTAssertEqual(Int(saturating: Double(Int.max)), .max) + } + + /// #296: a length of time out of range is put into words, not a stop. + func testADurationOutOfRangeDoesNotStopTheProcess() throws { + XCTAssertFalse(ConversationDetails.words(for: 1e300).isEmpty) + } + + /// #296: a run's name is made of any date that can be read from a message. + func testARunAtADateOutOfRangeDoesNotStopTheProcess() throws { + let date = try XCTUnwrap(MessageCoding.decode([Date].self, from: Data("[1e300]".utf8))?.first, "the date is not read from a message") + XCTAssertFalse(ScheduleOverview.Run.id(schedule: "s", at: date).isEmpty) + } + + /// #296: a temperature out of range is shown, not a stop. + func testATemperatureOutOfRangeDoesNotStopTheProcess() throws { + let stats = try XCTUnwrap(MessageCoding.decode(SystemStats.self, from: MessageCoding.encode(SystemStats(temperature: 1e300)))) + XCTAssertFalse(stats.temperatureText.isEmpty) + } + + /// #296: a Mac said to have started at a date out of range still has an + /// uptime in words. + func testABootDateOutOfRangeDoesNotStopTheProcess() throws { + XCTAssertFalse(SystemStats.uptime(since: Date(timeIntervalSince1970: -1e300)).isEmpty) + } + + /// #296: a percentage out of range is shown, not a stop. + func testAPercentageOutOfRangeDoesNotStopTheProcess() throws { + let limit = AccountLimit(id: "w", title: "Week", shortTitle: "Week", usedPercent: 1e300) + let usage = AccountUsage(agent: "claude", showsRemaining: false, groups: [AccountUsageGroup(limits: [limit])]) + let read = try XCTUnwrap(MessageCoding.decode(AccountUsage.self, from: MessageCoding.encode(usage))) + XCTAssertFalse(read.percentText(read.limits[0]).isEmpty) + } +} diff --git a/Tests/AgentTermProtocolTests/ReviewScheduleTests.swift b/Tests/AgentTermProtocolTests/ReviewScheduleTests.swift new file mode 100644 index 00000000..578de856 --- /dev/null +++ b/Tests/AgentTermProtocolTests/ReviewScheduleTests.swift @@ -0,0 +1,57 @@ +import AgentTermProtocol +import XCTest + +/// What the review of 2026-11-22 found in when a schedule runs and how it +/// is said (#290, #291). +final class ReviewScheduleTests: XCTestCase { + private var calendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + calendar.locale = Locale(identifier: "en_US_POSIX") + return calendar + } + + private func moment(_ day: Int, _ hour: Int, _ minute: Int) -> Date { + calendar.date(from: DateComponents(year: 2026, month: 11, day: day, hour: hour, minute: minute))! + } + + /// #290: "every 30 minutes, 22:00 to 06:00" runs every 30 minutes from + /// 22:00 until 06:00 of the next day, as its label says. + func testAWindowThatCrossesMidnightRunsAllThroughIt() { + let when = ScheduleTime.every(minutes: 30, from: 22 * 60, until: 6 * 60) + XCTAssertEqual(when.label(calendar: calendar), "Every 30 minutes, 22:00 to 06:00") + XCTAssertEqual(when.next(after: moment(10, 22, 0), calendar: calendar), moment(10, 22, 30), "the run after 22:00") + XCTAssertEqual(when.next(after: moment(10, 23, 45), calendar: calendar), moment(11, 0, 0), "the run after 23:45") + XCTAssertEqual(when.next(after: moment(11, 5, 40), calendar: calendar), moment(11, 6, 0), "the last of the window") + XCTAssertEqual(when.next(after: moment(11, 6, 0), calendar: calendar), moment(11, 22, 0), "none between 06:00 and 22:00") + } + + /// #291: a weekly schedule whose label names a day runs on a day: a day + /// of the week out of 1...7 is not shown as one that never comes. + func testAWeekdayOutOfRangeIsNotLabelledAsADayThatNeverRuns() { + for weekday in [0, 8] { + let when = ScheduleTime.weekly(weekdays: [weekday], hour: 9, minute: 0) + let label = when.label(calendar: calendar) + let next = when.next(after: moment(10, 12, 0), calendar: calendar) + let namesADay = calendar.shortWeekdaySymbols.contains { label.hasPrefix($0) } + XCTAssertFalse(namesADay && next == nil, "weekday \(weekday) is labelled “\(label)” and never runs") + } + } + + /// #291: a day of the week of -7 or lower does not stop the process in + /// `label()`; before the fix `($0 - 1 + 7) % 7` was a negative index. + func testANegativeWeekdayDoesNotStopTheProcess() throws { + let when = ScheduleTime.weekly(weekdays: [-7], hour: 9, minute: 0) + XCTAssertFalse(when.label(calendar: calendar).isEmpty) + } + + /// #291: a day of the week out of 1...7 is said to be none, in words + /// both apps and the host show. + func testADayOutOfRangeIsSaidToBeNone() { + for days in [[-7], [0], [8], [], [1, 9]] { + XCTAssertEqual(ScheduleTime.weekly(weekdays: days, hour: 9, minute: 0).refusal, ScheduleTime.daysRefusal, "\(days)") + } + XCTAssertNil(ScheduleTime.weekly(weekdays: [1, 7], hour: 9, minute: 0).refusal) + XCTAssertNil(ScheduleTime.daily(hour: 9, minute: 0).refusal) + } +} diff --git a/Tests/AgentTermProtocolTests/ReviewSentTextTests.swift b/Tests/AgentTermProtocolTests/ReviewSentTextTests.swift new file mode 100644 index 00000000..8eea1523 --- /dev/null +++ b/Tests/AgentTermProtocolTests/ReviewSentTextTests.swift @@ -0,0 +1,31 @@ +import AgentTermProtocol +import XCTest + +/// What the review of 2026-11-22 found in text sent as a paste (#248). +final class ReviewSentTextTests: XCTestCase { + private let start = "\u{1b}[200~" + private let end = "\u{1b}[201~" + + /// What is between the brackets of a paste. + private func inside(_ sent: String) -> String { + XCTAssertTrue(sent.hasPrefix(start) && sent.hasSuffix(end), "not sent as a paste") + return String(sent.dropFirst(start.count).dropLast(end.count)) + } + + /// #248: the end of a paste never stands inside the paste, also when + /// taking one out puts the pieces of another together. + func testTakingTheEndOfAPasteOutDoesNotMakeAnother() { + let text = "look at this\n\u{1b}[20" + end + "1~rm -rf build\nmore" + let sent = SentText.text(text, bracketedPaste: true) + XCTAssertFalse(inside(sent).contains(end), "the paste ends early, and what follows is typed: \(sent.debugDescription)") + } + + /// #248: no other control character goes into a paste either (an + /// Escape, a Control C); a tab and the ends of lines do. + func testNoControlCharacterButTabAndReturnIsInAPaste() { + let text = "one\tline\nand \u{1b}[2J an escape, \u{03} a control C, " + String(repeating: "x", count: 80) + let kept = inside(SentText.text(text, bracketedPaste: true)) + let controls = kept.unicodeScalars.filter { $0.value < 0x20 && $0 != "\t" && $0 != "\r" } + XCTAssertTrue(controls.isEmpty, "control characters in the paste: \(controls.map { String($0.value, radix: 16) })") + } +} diff --git a/Tests/AgentTermTerminalTests/ReviewTerminalTests.swift b/Tests/AgentTermTerminalTests/ReviewTerminalTests.swift new file mode 100644 index 00000000..fdd35799 --- /dev/null +++ b/Tests/AgentTermTerminalTests/ReviewTerminalTests.swift @@ -0,0 +1,49 @@ +import AgentTermProtocol +import AppKit +import XCTest + +@testable import AgentTermTerminal + +/// What the review of 2026-11-22 found in the terminal and the split diff +/// (#293, #295). +@MainActor +final class ReviewTerminalTests: XCTestCase { + private func spin(_ seconds: TimeInterval) { + RunLoop.main.run(until: Date().addingTimeInterval(seconds)) + } + + /// #293: what the user types while the screen is being replayed reaches + /// the program: only the emulator's answers to the replay are kept back. + func testWhatIsTypedDuringAReplayReachesTheProgram() { + let controller = TerminalController(session: 1) + var sent = Data() + controller.onInput = { sent.append($0) } + controller.replayQuiet = 5 + controller.beginReplay(size: TermSize(cols: 80, rows: 24)) + controller.feed(Data("what was on the screen\r\n".utf8)) + spin(0.1) + // A key, as the terminal view hands it over when the user types. + controller.send(source: controller.view, data: ArraySlice(Array("ls\r".utf8))) + controller.endReplay() + spin(0.3) + XCTAssertEqual(String(decoding: sent, as: UTF8.self), "ls\r", "what was typed during the replay did not reach the program") + } + + /// #295: what is copied from the split diff is the file's own: a tab of + /// the file is a tab in the text. + func testATabOfTheFileIsATabInTheSplitDiff() { + let (advance, lineHeight) = SplitDiffTexts.metrics(11.5) + let texts = SplitDiffTexts(patch: "@@ -1,2 +1,2 @@\n all:\n-\tgo build\n+\tgo test", fontSize: 11.5, advance: advance, lineHeight: lineHeight) + let left = texts.left.string.components(separatedBy: "\n") + let right = texts.right.string.components(separatedBy: "\n") + XCTAssertTrue(left.contains("\tgo build"), "the left side has \(left.map(\.debugDescription))") + XCTAssertTrue(right.contains("\tgo test"), "the right side has \(right.map(\.debugDescription))") + } + + /// #296: a limit said to start over at a date out of range is shown, + /// not a stop. + func testAResetDateOutOfRangeDoesNotStopTheProcess() { + XCTAssertFalse(UsageStyle.shortReset(Date(timeIntervalSince1970: 1e300), now: Date(timeIntervalSince1970: 0)).isEmpty) + XCTAssertEqual(UsageStyle.shortReset(Date(timeIntervalSince1970: -1e300), now: Date(timeIntervalSince1970: 0)), "now") + } +} diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 2f274c46..1ac8a4f7 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -357,7 +357,10 @@ Three things about it are deliberate: - It holds no question to the terminal (which terminal are you, where is the cursor), so a client has nothing to answer a second time. Clients - still treat it as a replay and send nothing on until `replayed`. + still treat it as a replay and send none of the emulator's answers on + until `replayed`. What the user types meanwhile is sent: the terminal + view (`AnsweringTerminalView`) hands the emulator's answers over apart + from the user's keys, and only those are held back (#293). - The emulator's own colors are left out. A client has its own. - A program's output arrives in pieces cut anywhere, also inside an escape sequence or a character. A client given the screen at such a moment would @@ -648,7 +651,12 @@ environment names (`AppChannel.usageVariable`, it took the place of, or the one of the project's or the user's settings, with the same input, and prints what that prints. Claude Code has one status line: of two builds, the one set up last has it and runs the -other's after its own, whose own then says it is not known. The host +other's after its own, whose own then says it is not known. The other's is +run with `AGENTTERM_STATUS_LINE_RELAYED` set, and a relay run with it runs +no relay it keeps, only the user's: two builds set up in turn keep each +other's, and would otherwise run each other without end (#259). The one +name both builds read, on purpose: it names nothing of either. A build set +up again after the other keeps the user's own line, not the other's. The host prefers this report over the conversation file, since it has the limits and the size of the context window. The file is removed when the session ends. @@ -1080,7 +1088,8 @@ whatever the two say, until this Mac's own app types, takes control or says `used` (a key or a click in its window, sent once after it was told no one is there) (NOTE-7). Every client is told `macInUse(Bool)`. Since #66 it holds no notice back: every device is told, whoever is at the Mac, -and since #234 no notification waits for it either. +and since #234 no notification waits for it either: an agent's waits +its 10 seconds whoever is there (#322). **On the iPhone.** Since #66 iOS's own banner, in front as behind, for a session other than the one on screen (`AgentNotifications`, from the @@ -1146,20 +1155,27 @@ Mac's own app as `local`. the device's Inbox; then `noticeAlert(id:)` for each one due, not handled nor read, that it was not shown yet. A new notice is `notice` to every client at once, for the Inbox and the Mac's floating notice. When it - `alerts`, it is a notification at once, in the same turn of the host's - queue (`tellEveryone` → `alert`): nothing waits, whether someone is at - the Mac or not, a done agent included (decided 2026-11-22, #234, which - took away the 30 seconds #180 had made a done agent, and anything while - someone was at the Mac, wait). It is due (`becameDue`, kept in + `alerts`, an agent's notice (a question, a permission, a finished task) + is a notification 10 seconds later (`Notice.alertDelay`, + `Configuration.alertDelay`), whether someone is at the Mac or not, and + only if it is then neither handled nor read: one the user acted on + meanwhile, its agent gone on, is never shown on the Mac nor the iPhone + (decided 2026-11-23, #322, over #234's "at once"; #234 had taken away + the 30 seconds #180 made a done agent wait). A failure that stopped work + is a notification at once (`Notice.waitsToAlert`). A host that stops + during the wait shows, when it starts again, none of those: their + sessions ended with it, so their notices moved on, which is read (#321). + The wait is short in the host's tests, and `AGENTTERM_ALERT_DELAY` sets + it for the apps' tests. It is due (`becameDue`, kept in `notices.json`), and is `noticeAlert(id:)` to every client in front and a push to each registered device that is away, not connected or in the background (#190), at the same moment. The Mac posts its macOS - notification on `noticeAlert` as before, so it too is at once. + notification on `noticeAlert` as before, so it waits the same. - **Read** (#180) is the host's too: `readNotices(ids:)` from a device marks them read in the log (`Notice.read`, `NoticeCenter.read`), and every client is told `noticesRead(ids:)`; each device that had one through Apple and is away has it taken back (`gone`). Handled by being answered, - opened or dismissed is read too (`Notice.reads`); moved on is not. A + opened or dismissed is read too (`Notice.reads`), and so is moved on (#321, the owner's decision of 2026-11-23): an agent that waits goes on only once someone answered it, often in its session, and one that asks something else has a notice of its own for it. A handled notice is taken back from every device whatever the way. A device keeps read in its `InboxBook` as well, and on `noticeLog` says what it read while not connected (`InboxBook.readHere(notTold:)`). - A notice is handled once (`Notice.Handled`: answered, opened, dismissed, @@ -2041,13 +2057,18 @@ the same folder can therefore be mixed up; the History tab is exact. link. The iOS Simulator has no camera, so `scripts/pair-ios.sh` uses it. - `Tailscale.status()` decides what the pairing screen shows. Tailscale counts as installed when its app or command line tool is found; as ready when the - Mac has an address in Tailscale's range and the CLI, if it answers, reports - the backend as running. An address alone is enough where the CLI is missing. - The screen re-checks every 3 seconds while it is open. -- The host listens on `127.0.0.1` and on the Mac's Tailscale address - (100.64.0.0/10), found with `getifaddrs`. It checks every 15 seconds so it - follows Tailscale going up, down or changing address. It never listens on - other interfaces. + Mac has Tailscale's address and the CLI, if it answers, reports the backend + as running. Where the CLI is missing, an address on a tunnel (`utun`) of a + Mac that has Tailscale is enough; on a Mac without Tailscale, an address in + its range is someone else's (#268). The screen re-checks every 3 seconds + while it is open. +- The host listens on `127.0.0.1` and on the Mac's Tailscale address: of the + interfaces with an address in 100.64.0.0/10 (`getifaddrs`), the one + Tailscale says is its own (`tailscale status --json`, `TailscaleIPs`, asked + off the host's queue), or when it cannot be asked the first tunnel. Another + VPN's tunnel in the same range (Cloudflare WARP) and a carrier's address are + never taken (#268). It checks every 15 seconds so it follows Tailscale going + up, down or changing address. It never listens on other interfaces. - The WebSocket itself is not encrypted. Loopback traffic stays on the Mac and Tailscale traffic is encrypted by WireGuard. - A token is still required on Tailscale, because other devices and shared @@ -2235,12 +2256,15 @@ A part of AgentTerm that stops without being asked to is reported to every client in a message of its own, `failures([PartFailure])`, rather than left for the clients to work out from a list that emptied. The parts are the host, a session's program, the hold that keeps the Mac awake, and the -status line relay (see "The other parts" below). A `PartFailure` says: +status line relay (see "The other parts" below); and, as the host starts, a +file of what it keeps (its schedules, paired devices or settings) that it +could not read (`savedState`, #273): put aside as `.unreadable`, never +written over, and the host starts without what it held. A `PartFailure` says: | Field | Means | |---|---| | `id` | Names the report, for `dismissFailure` | -| `part` | Which part: `host`, `session`, `keepAwake`, `statusLine`. Text, not a closed list, so a client reads a part added after it was built | +| `part` | Which part: `host`, `session`, `keepAwake`, `statusLine`, `schedule`, `push`, `savedState`. Text, not a closed list, so a client reads a part added after it was built | | `name` | Which one, for a part there are several of (a session); nil for the host | | `at` | When it stopped, as near as is known | | `ended` | The sessions that ended with it: name, folder, agent | @@ -2553,6 +2577,16 @@ was when a scheduled run started is written as a tree through a copy of the index (`GIT_INDEX_FILE`), not with `git stash create`, which rewrote the index too. +Each runs in a session and a process group of its own, with no terminal, +and its time limit holds (#261): at the limit the whole group is asked to +end, and killed a second later (`Subprocess.graceAfterTimeout`), and its +output is read no longer than that, also while a program it left behind in +another group keeps it open. A login shell still in its startup files, which +takes no notice of SIGTERM, and a hook that leaves a program in the +background, made a call wait with no end. The user's own status line runs +the same way, with what Claude Code gave it as its input and its own +environment (`forTheHost: false`). + ## Reporting `AgentTermTelemetry` holds the choices and the gate; `AgentTermFirebase` diff --git a/docs/SPEC.md b/docs/SPEC.md index b60d7d8c..aa0c0a49 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -282,19 +282,20 @@ happened; the Live Activity shows the host's state now (below). is left out, the one in front included (#180): being in front does not make it seen, something the user does there does (choosing it, typing into it, the notification). -- **When it is a notification** (#180; the wait taken away by the owner - on 2026-11-22, #234): every notice is in each device's Inbox, and floats - over the Mac's window, at once; it is a notification on the Mac and on - every iPhone or iPad **at once and at the same moment**, which the host - says: through Apple to each one that is away, whether someone is at the - Mac or not, an agent that is done as much as one that asks. Nothing - waits to see whether it is handled or read first; what is handled or - read afterwards on one device is taken back from the others. A host - that starts again shows nothing twice. +- **When it is a notification** (#180; #234; the wait put back by the + owner on 2026-11-23, #322): every notice is in each device's Inbox, and + floats over the Mac's window, at once. An agent's notice (it asks, or is + done) is a notification on the Mac and on every iPhone or iPad **10 + seconds later and at the same moment**, which the host says: through + Apple to each one that is away, whether someone is at the Mac or not; + one the user acted on meanwhile (answered it, opened its session, its + agent went on) is never a notification. A failure that stopped work is + one at once. What is handled or read afterwards on one device is taken + back from the others. A host that starts again shows nothing twice. - **How they sound** (#233, decided by the owner on 2026-11-22): every notification is of something that needs the user (an agent asks or is - done, a part failed and stopped work), so each comes at once, with - sound, and is **time-sensitive** on the iPhone: shown during a Focus, + done, a part failed and stopped work), so each comes with sound + (an agent's after its 10 seconds, #322), and is **time-sensitive** on the iPhone: shown during a Focus, as iOS lets the user allow for the app. An agent that stops asking brings no new notification: the earlier one is taken back. - **Handled on one, gone from all**: answered, opened or dismissed (from @@ -302,7 +303,9 @@ happened; the Live Activity shows the host's state now (below). on, and the notification goes from every other device. - **Read on one, read on all** (#180, replacing what #66 decided): a notice read on one device (picked in the Inbox, its session opened, its - notification tapped, answered or dismissed) is read on every device, and + notification tapped, answered or dismissed), or whose agent moved on + (#321: answered in its session, asked something else, its session ended), + is read on every device, and its notification goes from all of them. What is read while a device is not connected is said to the host once it is. - **On the iPhone and the iPad**, iOS's own notification banner, also diff --git a/docs/TESTING.md b/docs/TESTING.md index 1f2756a1..32974dff 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -305,6 +305,8 @@ new, `new.txt` new. "A second device" is another client on the same host. | SES-22 | A client that is still connecting | It is asked to send something | That waits and follows the greeting; the host answers it instead of closing a client whose first word was not its hello | H | | SES-23 | A session whose program waits | Its program is killed (SIGKILL) | Every client is told that the program of that session stopped unexpectedly, that it was killed, and that its session ended; it is not started again | H | | SES-24 | A session whose program ignores the hang-up; another that waits | The first is closed from a device (SIGHUP, then SIGKILL); the second is stopped by Control C (SIGINT) | Nothing is reported | H | +| SES-30 (#293) | A session's screen being replayed (attached, connected again, earlier lines loaded on the iPhone) | The user types `ls` and Return, pastes, or drops a file | It reaches the program; only the emulator's answers to what the replay asks are held back (`AnsweringTerminalView`). Before the fix everything sent during the replay was dropped, and nothing said so. `ReviewTerminalTests` | U | +| SES-31 (#275) | A shell that ended, and another started after it, given the same number for its terminal | Something is still written to the first (a delayed step of an answer, typed input), or the program in front of it is asked | Nothing reaches the second shell, and no program is said to be in front of the first: its terminal is closed after every write asked before, and written to no more. Before the fix the bytes were typed into the next shell every time, and `foregroundCommand` named its program. `ReviewCorePTYTests` | H | ### Session names and usage @@ -327,6 +329,7 @@ new, `new.txt` new. "A second device" is another client on the same host. | SYS-2 | The app connected | Look under the launch buttons in Sessions (Mac), above the sessions (iPhone) | Processor, memory, network down and up, temperature, battery, uptime, and the memory in gigabytes ("Memory 12.4/32 GB", #154) are shown | P, M | | SYS-3 | Temperature in Celsius | A second device chooses Fahrenheit | The Mac's line shows °F | H, M | | SYS-4 (#206) | Another Mac's page shown, the host's figures not come yet | The figures come | The page stays where it was shown: the line of figures has its place from the start, its figures "—" until then. Before the fix the line came with the figures and the page moved 24 points down, from (344, 187, 821, 705) to (344, 211, 821, 681) | M | +| SYS-5 (#296) | A figure out of what a whole number holds from the host: a temperature, a percentage of a limit, the time a limit starts over, a start of the Mac, a length of time, a run's date (1e300) | Shown | In words, the nearest whole number (`Int(saturating:)`), never a stop of the app. Before the fix each stopped the app that showed it. `ReviewMessageTests`, `ReviewTerminalTests` | U | ### Terminal size @@ -525,6 +528,9 @@ new, `new.txt` new. "A second device" is another client on the same host. | GIT-76 (#116) | A folder whose remotes the app is asking by itself; one with nothing under way; one with something of the user's under way | A push asked for in each; the app's own fetch asked for again | Kept, the folder busy with it from then, and handed back once to be begun when the fetch is over; begun at once; refused, and the app's own fetch not begun beside it, nor twice. Nothing kept is begun once the connection is another. The Mac and the iPhone both go by `RemoteWork` | U | | GIT-77 (#116) | A second folder whose remote takes five seconds to answer a fetch and lacks the folder's last commit; the app in front | The folder picked; while the app asks its remotes by itself, Fetch, Pull and Push looked at, and Push pressed | None is held; the push is made once the fetch is over, not beside it, and the remote has the commit. Before, they were held meanwhile, Fetch turning, and a press that got through as the fetch began was thrown away without a word | M | | GIT-78 (#151) | A submodule with a change staged in it | Write in its own box, then a message of the user's, Commit | The stand-in's message in the submodule's field, nothing committed; then the commit in the submodule, and its new commit a change of the folder | M | +| GIT-80 (#260) | A repository whose git is set up with `diff.mnemonicPrefix` or `diff.noprefix` | Its changes, staged and not, a commit's files and a stash's are read | Each file is named, as with git's own prefixes: every diff the host reads is run with both settings off. Before the fix every file had an empty name, and staging or discarding acted on `""`. On git 2.54 `--src-prefix` is no way around it: `stash show --include-untracked` puts bytes of no meaning before a name given it. `ReviewSubGitPrefixTests` | H | +| GIT-81 (#295) | A diff of a file indented with tabs (a Makefile) | Shown split, a line selected and copied | The tabs are in what is copied, as in the file, and line up every four characters from where the line's text starts. Before the fix each was four blanks. `ReviewTerminalTests` | U, picture | +| GIT-82 (#297) | A question open about discarding, reverting, cherry-picking, dropping a stash, deleting a branch, aborting, undoing or amending, asked in one folder | The folder on show changes meanwhile (the session in front ends and one in a worktree of the same repository comes in front, a notification is clicked) | The question is closed, nothing is done, and `GitQuestionWords.closedForAnotherFolder` is said. Before the fix it stayed, and confirming did it in the folder on show now: a discard asked in the project was done in another agent's worktree. `GitTests` | M | ### History @@ -602,6 +608,8 @@ new, `new.txt` new. "A second device" is another client on the same host. | HOST-13 (#204) | A program that is not an AgentTerm host (the test runner, through a `SlowProxy` in front of the host) on the app's port | Open the app | The banner says the port is in use by that program, by its name (`PortWords.inUse`); it is not called another copy's host, and neither Use This App's Host… nor Restart Host… is offered. Before the fix the banner of another copy's host named `xctest` | M | | HOST-2 | A host of another protocol version | Connect | Both apps say the versions differ | H, P | | HOST-14 (#214) | A host of protocol 32 (`protocolVersion`), which refuses what came after it as the real one does; then one of this release | A client connects and sends `readNotices` and `deviceInBackground`, then asks for the agents | The earlier host is not sent them and answers no "malformed message"; the host of this release is sent both. Before the fix the earlier host answered "malformed message", which the Mac app showed as a notice on its first opening after an update. `EarlierHostTests`. On the Mac, `HostReleaseTests.testAHostOfAnEarlierProtocolIsSaidInTheBannerOnly`: the banner says the host is from an older version, the app is connected, no notice says it a second time, and Restart Host… takes the banner away. That a notice already there goes once a host of the app's own release answers is not reached by a test | H, M | +| HOST-15 (#271) | A signed-in client that sends a count out of range: `attach` with `have` of `Int.min`, an agent's `command` with -1 lines, `scheduleRunOutput` at a date of 1e300 | The host answers | It goes on: the count is taken as none, the date as the nearest whole second. Before the fix each stopped the host and every session with it. `ReviewCoreTrapTests` | H | +| HOST-16 (#273) | `schedules.json`, `devices.json` or `settings.json` the host cannot read (a field of a later build, a file cut short) | The host starts | The file is put aside as `.unreadable`, the host starts without what it held, and every client is told in the banner and the Inbox (`PartFailure.Part.savedState`), with where the file is. Before the fix the host took it for empty and wrote over it within a second, or at the next pairing, and said nothing. `PartFailureTests`, `ReviewSubHostStateTests` | H | | HOST-12 (#121) | The app as shipped, its own host left running from an earlier release (`--app-version 0.0.1`): built from other sources (`--host-revision`), then from the same ones | Open the app | Other sources: a banner says the host is from AgentTerm 0.0.1, older than the app, and Restart Host… asks, then starts the app's own, and the banner goes. The same sources: nothing is said, a release that changes nothing of the host asks for no restart | M, P | | HOST-3 | A host with two sessions, `build` and `tests` | The host is killed (SIGKILL), and another is started on its state folder and port | Every client is told that the host stopped, about when, that `build` and `tests` ended with it, and that it was started again; so is a client that connects later, also after the host is restarted on purpose. Dismissed on one client, it is gone from all and not sent again | H | | HOST-4 | A host with two sessions | It is stopped as asked for (SIGTERM: Restart Host, replacing another copy's host, logging out), and started again | Nothing is reported | H | @@ -628,6 +636,8 @@ new, `new.txt` new. "A second device" is another client on the same host. | FILE-11 (#104) | `notes.txt` open on the Mac | Typed into; typed back to the disk's text; a text of the same length; Revert; typed twice and saved; edited, and the disk's changed | Save and Revert show only while it differs from the disk's; Revert gives the disk's text back; the last of what was typed is saved; its own edits are kept | M | | FILE-12 (#126) | A Markdown document with a heading, a table, a link, a code block and a `