From 4dfe99e4c2dbd279940c7f4f85b23026e49964c0 Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Wed, 25 Nov 2026 09:54:23 +0700 Subject: [PATCH 1/5] Fix permission cleanup, prioritize notification replies, and stabilize RELAY-3 --- Sources/CAgentTermCEF/AgentTermCEF.m | 20 +++++++++++++++---- .../AgentTermMacUITests/BrowserUITests.swift | 16 ++++++++++++--- docs/DESIGN.md | 6 +++--- docs/SPEC.md | 3 ++- docs/TESTING.md | 3 ++- iOS/AgentTermUITests/NoticeActionTests.swift | 16 +++++++++++++++ iOS/NotificationShared/NoticeContent.swift | 6 +++--- iOS/project.yml | 3 +++ relay/test/worker.test.js | 4 +++- 9 files changed, 61 insertions(+), 16 deletions(-) create mode 100644 iOS/AgentTermUITests/NoticeActionTests.swift diff --git a/Sources/CAgentTermCEF/AgentTermCEF.m b/Sources/CAgentTermCEF/AgentTermCEF.m index 3fc4ec5..048ea66 100644 --- a/Sources/CAgentTermCEF/AgentTermCEF.m +++ b/Sources/CAgentTermCEF/AgentTermCEF.m @@ -222,6 +222,7 @@ @implementation ATCBrowser static NSMutableDictionary *g_prompt_kinds; static NSMutableDictionary *g_prompt_asked; static NSMutableDictionary *g_prompt_ids; +static NSMutableDictionary *g_prompt_browsers; static int g_next_prompt = 1; /// What a download can be cancelled with, by its id. static NSMutableDictionary *g_downloads_running; @@ -494,6 +495,12 @@ static int CEF_CALLBACK do_close(cef_life_span_handler_t *self, cef_browser_t *b static void CEF_CALLBACK on_before_close(cef_life_span_handler_t *self, cef_browser_t *browser) { (void)self; int identifier = atc_id(browser); + // An app-closed tab no longer receives events in Swift. Release its + // outstanding media callbacks here, including any still queued for delivery. + for (NSNumber *number in g_prompt_browsers.allKeys) { + if (g_prompt_browsers[number].intValue == identifier && g_prompt_kinds[number].intValue == 1) + atc_answer_permission(number.intValue, 0); + } ATCBrowser *open = g_browsers[@(identifier)]; if (open) { ATC_RELEASE(open.devtools); @@ -620,19 +627,20 @@ static void CEF_CALLBACK on_download_updated(cef_download_handler_t *self, cef_b } /// Keeps what a prompt waits on, and returns the number it is told by. -static int atc_keep_prompt(void *callback, int kind, uint32_t asked, uint64_t prompt_id) { +static int atc_keep_prompt(cef_browser_t *browser, void *callback, int kind, uint32_t asked, uint64_t prompt_id) { int number = g_next_prompt++; g_prompts[@(number)] = [NSValue valueWithPointer:callback]; g_prompt_kinds[@(number)] = @(kind); g_prompt_asked[@(number)] = @(asked); g_prompt_ids[@(number)] = @(prompt_id); + g_prompt_browsers[@(number)] = @(atc_id(browser)); return number; } static int CEF_CALLBACK on_show_permission_prompt(cef_permission_handler_t *self, cef_browser_t *browser, uint64_t prompt_id, const cef_string_t *origin, uint32_t permissions, cef_permission_prompt_callback_t *callback) { (void)self; - int number = atc_keep_prompt(callback, 0, permissions, prompt_id); + int number = atc_keep_prompt(browser, callback, 0, permissions, prompt_id); atc_emit_text(ATC_EVENT_PERMISSION, browser, atc_text(origin), nil, number, (int)permissions, 0); ATC_RELEASE(browser); return 1; @@ -642,10 +650,12 @@ static void CEF_CALLBACK on_dismiss_permission_prompt(cef_permission_handler_t * cef_permission_request_result_t result) { (void)self, (void)result; for (NSNumber *number in g_prompt_ids.allKeys) { - if (g_prompt_ids[number].unsignedLongLongValue == prompt_id && g_prompt_kinds[number].intValue == 0) { + if (g_prompt_ids[number].unsignedLongLongValue == prompt_id && g_prompt_kinds[number].intValue == 0 && + g_prompt_browsers[number].intValue == atc_id(browser)) { ATC_RELEASE((cef_permission_prompt_callback_t *)g_prompts[number].pointerValue); [g_prompts removeObjectForKey:number]; [g_prompt_ids removeObjectForKey:number]; + [g_prompt_browsers removeObjectForKey:number]; [g_prompt_kinds removeObjectForKey:number]; [g_prompt_asked removeObjectForKey:number]; atc_emit_text(ATC_EVENT_PERMISSION, browser, nil, nil, number.intValue, -1, 0); @@ -657,7 +667,7 @@ static void CEF_CALLBACK on_dismiss_permission_prompt(cef_permission_handler_t * static int CEF_CALLBACK on_request_media_access_permission(cef_permission_handler_t *self, cef_browser_t *browser, cef_frame_t *frame, const cef_string_t *origin, uint32_t permissions, cef_media_access_callback_t *callback) { (void)self; - int number = atc_keep_prompt(callback, 1, permissions, 0); + int number = atc_keep_prompt(browser, callback, 1, permissions, 0); // Media is told apart by the high bit. atc_emit_text(ATC_EVENT_PERMISSION, browser, atc_text(origin), nil, number, (int)(permissions | 0x40000000u), 0); ATC_RELEASE(frame); @@ -928,6 +938,7 @@ int atc_start(const atc_paths *paths, atc_event_fn events, void *context, char * g_prompt_kinds = [NSMutableDictionary new]; g_prompt_asked = [NSMutableDictionary new]; g_prompt_ids = [NSMutableDictionary new]; + g_prompt_browsers = [NSMutableDictionary new]; g_downloads_running = [NSMutableDictionary new]; atc_make_handlers(); atc_adopt_application(); @@ -1258,6 +1269,7 @@ void atc_answer_permission(int prompt, int allow) { [g_prompt_kinds removeObjectForKey:key]; [g_prompt_asked removeObjectForKey:key]; [g_prompt_ids removeObjectForKey:key]; + [g_prompt_browsers removeObjectForKey:key]; if (kind == 1) { cef_media_access_callback_t *callback = kept.pointerValue; if (allow) callback->cont(callback, asked); diff --git a/Tests/AgentTermMacUITests/BrowserUITests.swift b/Tests/AgentTermMacUITests/BrowserUITests.swift index 3ca940a..c1d3109 100644 --- a/Tests/AgentTermMacUITests/BrowserUITests.swift +++ b/Tests/AgentTermMacUITests/BrowserUITests.swift @@ -693,8 +693,8 @@ final class BrowserUITests: MacUITestCase { /// BROWSER-68 (#255): a page asks for the microphone, whose question /// Chromium does not take back itself; the page goes to another, and the /// question leaves the bar, refused, so that Allow never answers for a - /// page no longer shown. macOS asks first whether the test build may use - /// the microphone: the user's to answer, so the test waits for it. + /// page no longer shown. Closing another tab with a pending request + /// must also leave this tab free of that request. func testAMicrophoneQuestionOfAPageThatGoesLeavesTheBar() throws { let folder = root.appendingPathComponent("mic-site") try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) @@ -722,7 +722,6 @@ final class BrowserUITests: MacUITestCase { let tab = try XCTUnwrap(opened.text.range(of: #"tab \d+"#, options: .regularExpression).map { String(opened.text[$0].dropFirst(4)) }, opened.text) let snapshot = server.text("browser_snapshot", ["tab": tab]).text XCTAssertFalse(server.text("browser_click", ["tab": tab, "ref": try XCTUnwrap(ref(in: snapshot, "button \"Ask Mic\""), snapshot)]).failed) - // The first time, macOS asks the user about the test build first. app.wait(for: .containing("wants your microphone"), timeout: 180) shot("microphone-question") @@ -731,6 +730,17 @@ final class BrowserUITests: MacUITestCase { shot("microphone-question-gone") // The page shown is the next one, which asked nothing. XCTAssertTrue(server.text("browser_snapshot", ["tab": tab]).text.contains("Next page")) + + let another = server.text("browser_open", ["url": address]) + let closing = try XCTUnwrap(another.text.range(of: #"tab \d+"#, options: .regularExpression).map { String(another.text[$0].dropFirst(4)) }, another.text) + app.press(.id("browser-row-\(closing)")) + let page = server.text("browser_snapshot", ["tab": closing]).text + let ask = try XCTUnwrap(ref(in: page, "button \"Ask Mic\""), page) + XCTAssertFalse(server.text("browser_click", ["tab": closing, "ref": ask]).failed) + app.wait(for: .containing("wants your microphone"), timeout: 15) + XCTAssertFalse(server.text("browser_close", ["tab": closing]).failed) + app.waitGone(.id("browser-permission"), timeout: 10) + XCTAssertTrue(server.text("browser_snapshot", ["tab": tab]).text.contains("Next page")) } /// BROWSER-62 (#324): its location and notifications are named so. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index cd40c04..6dfbf9c 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1162,9 +1162,9 @@ answers `error` and types nothing. A reply given while the connection was gone waits for it. Notifications hide their text where iOS hides previews. A question's choices are actions of its notification (#55): iOS takes a notification's actions from its category, so a question with choices gets -a category of its own, named after the session, with an action for each of -the first nine choices (`AgentNotice.buttons`) and the text reply last, ten -being the most iOS shows. The body is the question alone +a category of its own, named after the request. The text reply comes first +so it stays available when iOS shows fewer actions. The first nine choices +(`AgentNotice.buttons`) follow in their original order. The body is the question alone (`AgentNotice.words`). A choice is sent as a reply is, `answer` with the choice's words as its text. diff --git a/docs/SPEC.md b/docs/SPEC.md index dc28086..d75ac08 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -439,7 +439,8 @@ happened; the Live Activity shows the host's state now (below). and a field takes an answer in words of one's own, as the agent's own list offers one after its choices (Claude Code's "Type something."); the host types it there. Once the agent no longer asks, the choices are - listed as text only. + listed as text only. An iPhone notification offers Reply first, followed + by the choices in the order the agent gave them. - **What a turn came to** (#71): an agent that is done shows, in the Inbox, what it was asked, what it answered, the commands it ran with their exit codes, and the files of its folder that changed while it diff --git a/docs/TESTING.md b/docs/TESTING.md index 1ba8ecc..6ee79f6 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -757,6 +757,7 @@ A second host stands in for the other Mac, with a project of its own. | IOS-24 (#328) | Two banners on show on the iPhone (the host died; the schedules could not be read) | The Sessions tab looked at | The banners are above every tab, in room of their own: the list starts under the last of them, and the Mac's name in the navigation bar shows. Before the fix they floated over the tab, hiding its title and the top of its list. `BADSTATE=only scripts/test-ios.sh "iPhone Air"` | P | | IOS-25 (#283) | A Mac paired on the iPhone, its host gone; another paired | The first forgotten from the list of Macs | It is tried over a connection of its own, to stop its pushes, and when it cannot be reached in 8 seconds `PushWords.notToldToStop` says so, with what to do on that Mac. One reachable is told (`pushUnregister`) whether or not it is on screen; pairing a Mac again removes what was kept under its former id. Before the fix only the Mac on screen with its pushes on was told, and nothing was said. `UNANSWERED=only scripts/test-ios.sh "iPhone Air"` | P | | IOS-26 (#320) | The stand-in asks a question with choices (`INBOXASK=only`) | Its Inbox item opened on the iPhone; words of one's own written and sent | The choices are buttons and a field takes one's own answer; the stand-in receives the words while it asks. Before the fix the choices were text only, with no way to answer | `answerFromTheInbox` | I | +| IOS-26a (#320) | A notification for a question with nine choices | Build its action category | The first action accepts a written reply and the nine choices follow in order | `NoticeActionTests` | I | | IOS-21 (#286) | The Mac not reached | A schedule saved, run, stopped, duplicated or deleted; a file staged, discarded, stashed; a branch switched; a file made, renamed or put in the Trash | Not sent, `NotConnectedWords.notDone` said at once, the schedule's form left open. Before the fix each did nothing and said nothing. A rename and a schedule saved: `UNANSWERED=only scripts/test-ios.sh "iPhone Air"`, after its host is gone; the others by reading | P | | IOS-22 (#287) | The Inbox (what agents said) and the drafts of messages, on the iPhone; the paired Macs in the Keychain | Kept; the Macs saved; the Keychain not readable as the app starts | The first two in files of the app's own, protected until the first unlock and out of the backups; the Macs changed in place, never deleted first, and not written over while they could not be read. Before the fix the first two were in the preferences, in every backup, and a failed save or an unreadable Keychain lost every paired Mac. The Keychain part with a Keychain of the test's own, `PairingStoreTests` (`PairingStore` is in `AgentTermClient` for it); where the Inbox and drafts are kept, by reading | H | @@ -1108,7 +1109,7 @@ and the test talks to the real `agenttermd mcp` with it. | BROWSER-64 (#256) | A tab in a profile whose Chromium context is not open yet (a private one's first) | It is closed before the context opens; or the context cannot be made | What waited for it is answered as not made, never left waiting; a profile whose context could not be made is tried again by the next tab. The window is milliseconds and is not hit by a test | read | | BROWSER-65 (#253) | An agent's tab open in a second profile | A device deletes that profile (`.profile(.delete)`) | Its tab closes, the agent's choice of the profile is forgotten and the profiles left are answered, as Settings > Browser does. Before the fix the tab stayed open, signed in, in a profile no list showed. `BrowserUITests` | M | | BROWSER-66 (#248) | A page of the real Chromium of the build whose element holds ESC and the end-of-paste mark (`[201~`, kept raw by HTML and given back by `outerHTML`); an agent that asked for no bracketed paste | The element picked and sent | It is typed without the mark and with no ESC. Before the fix the ESC was typed as it was, the key's sequence after it. `BrowserUITests`; `ReviewSentTextTests.testNoControlCharacterButTabAndReturnIsTypedEither` for typed text | M | -| BROWSER-68 (#255) | A page asks for the microphone | It goes to another page | The bar says "… wants your microphone" (Chromium asks first, macOS only once it is allowed); the page gone, the question leaves the bar, refused | `testAMicrophoneQuestionOfAPageThatGoesLeavesTheBar` | M | +| BROWSER-68 (#255) | A page asks for the microphone | It goes to another page | The bar says "… wants your microphone" (Chromium asks first, macOS only once it is allowed); the page gone, the question leaves the bar, refused. Closing a second tab with a pending microphone request leaves the first page usable and free of its prompt | `testAMicrophoneQuestionOfAPageThatGoesLeavesTheBar` | M | ### Vietnamese input diff --git a/iOS/AgentTermUITests/NoticeActionTests.swift b/iOS/AgentTermUITests/NoticeActionTests.swift new file mode 100644 index 0000000..9bd4170 --- /dev/null +++ b/iOS/AgentTermUITests/NoticeActionTests.swift @@ -0,0 +1,16 @@ +import AgentTermProtocol +import UserNotifications +import XCTest + +final class NoticeActionTests: XCTestCase { + // IOS-26a: the system may display only the first few actions. + func testWrittenReplyPrecedesTheChoices() throws { + let choices = (1...9).map(String.init) + let question = AgentQuestion(text: "Which one?", choices: choices) + let notice = AgentNotice(session: 1, name: "agent", folder: "/tmp", state: .waitingForAnswer(question)) + let category = try XCTUnwrap(NoticeContent.choiceCategory(of: notice, request: "question")) + XCTAssertTrue(category.actions.first is UNTextInputNotificationAction) + XCTAssertEqual(category.actions.first?.identifier, "reply") + XCTAssertEqual(category.actions.dropFirst().map(\.title), choices) + } +} diff --git a/iOS/NotificationShared/NoticeContent.swift b/iOS/NotificationShared/NoticeContent.swift index 4379691..c584ebd 100644 --- a/iOS/NotificationShared/NoticeContent.swift +++ b/iOS/NotificationShared/NoticeContent.swift @@ -24,8 +24,8 @@ enum NoticeContent { ] } - /// The category of a question with choices: a button for each, then - /// the text reply. Nil for anything else. + /// Put the text reply first so it remains available when iOS displays + /// only the first few actions. Keep the choices in the agent’s order. static func choiceCategory(of notice: AgentNotice, request: String) -> UNNotificationCategory? { let buttons = notice.buttons guard !buttons.isEmpty else { return nil } @@ -33,7 +33,7 @@ enum NoticeContent { // is unlocked first. let actions = buttons.map { UNNotificationAction(identifier: $0.id, title: $0.title, options: [.authenticationRequired]) } return UNNotificationCategory( - identifier: "agent-choices-\(request)", actions: actions + [reply], intentIdentifiers: [], options: [.hiddenPreviewsShowTitle, .customDismissAction]) + identifier: "agent-choices-\(request)", actions: [reply] + actions, intentIdentifiers: [], options: [.hiddenPreviewsShowTitle, .customDismissAction]) } /// The content of a notice, with its category for a notice that has diff --git a/iOS/project.yml b/iOS/project.yml index 02251c8..0bdfbd7 100644 --- a/iOS/project.yml +++ b/iOS/project.yml @@ -189,8 +189,11 @@ targets: platform: iOS sources: - AgentTermUITests + - NotificationShared/NoticeContent.swift dependencies: - target: AgentTerm + - package: AgentTerm + product: AgentTermProtocol settings: base: PRODUCT_BUNDLE_IDENTIFIER: com.manhpham.agentterm.uitests diff --git a/relay/test/worker.test.js b/relay/test/worker.test.js index 968006d..276c3be 100644 --- a/relay/test/worker.test.js +++ b/relay/test/worker.test.js @@ -100,7 +100,9 @@ test("RELAY-2 a push with its ticket reaches APNs as it was encrypted, signed wi test("RELAY-3 no push without the relay's ticket for that token, or with an expired one", async () => { const { ticket: t, expires } = await ticket(); - const forged = await call("/v1/push", { token: TOKEN, ticket: "x" + t.slice(1), expires, payload: "AAAA" }); + const altered = (t.startsWith("x") ? "y" : "x") + t.slice(1); + assert.notEqual(altered, t); + const forged = await call("/v1/push", { token: TOKEN, ticket: altered, expires, payload: "AAAA" }); assert.equal(forged.status, 401); const other = await call("/v1/push", { token: "b".repeat(64), ticket: t, expires, payload: "AAAA" }); assert.equal(other.status, 401); From 532ad8c077ec6d7c4d6125e149411d24bd7c926a Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Wed, 25 Nov 2026 11:02:53 +0700 Subject: [PATCH 2/5] fix: report hooks only after the first prompt, Copilot's instructions folder, and a shell's running state - A session with no hook heard is reported "No hook response" only after the first prompt was submitted and the grace passed (FirstPromptInput); "Waiting for the first hook" while MCP is connected. - Copilot's instructions are "File provided" only when its folder reached the session's environment, "Not given" otherwise. - A shell session tracks whether a program runs in it, so closing it asks only then; CloseWords.asks is removed. Co-Authored-By: Claude Opus 5.5 --- Sources/AgentTermHost/AgentHooks.swift | 10 ++- Sources/AgentTermHost/FirstPromptInput.swift | 40 +++++++++ Sources/AgentTermHost/HostServer.swift | 51 +++++++++-- Sources/AgentTermHost/PTYProcess.swift | 9 ++ Sources/AgentTermMac/AgentTermApp.swift | 4 +- Sources/AgentTermMac/AppModel.swift | 23 +++-- Sources/AgentTermMac/PaneViews.swift | 2 +- Sources/AgentTermMac/Panes.swift | 22 +++-- Sources/AgentTermMac/SessionTabs.swift | 12 +-- Sources/AgentTermMac/SidebarView.swift | 12 ++- Sources/AgentTermProtocol/AgentLink.swift | 27 +++--- Sources/AgentTermProtocol/CloseWords.swift | 6 -- Sources/AgentTermProtocol/Messages.swift | 16 ++++ Sources/AgentTermTerminal/AgentLinkMark.swift | 8 +- Tests/AgentTermHostTests/AgentLinkTests.swift | 85 ++++++++++++++++++- .../HooksAndMCPUITests.swift | 4 + Tests/AgentTermMacUITests/PaneUITests.swift | 19 ++++- .../AgentLinkPromptTests.swift | 13 ++- .../ProtocolTests.swift | 38 ++++++--- docs/DESIGN.md | 10 ++- docs/TESTING.md | 13 +-- iOS/AgentTerm/TerminalScreen.swift | 2 +- 22 files changed, 349 insertions(+), 77 deletions(-) create mode 100644 Sources/AgentTermHost/FirstPromptInput.swift diff --git a/Sources/AgentTermHost/AgentHooks.swift b/Sources/AgentTermHost/AgentHooks.swift index bf58553..26d1820 100644 --- a/Sources/AgentTermHost/AgentHooks.swift +++ b/Sources/AgentTermHost/AgentHooks.swift @@ -57,16 +57,22 @@ public enum AgentHooks { return " --settings " + Handoff.shellQuote(String(decoding: settings, as: UTF8.self)) } + static func copilotInstructionsFolder(in directory: URL) -> URL { + directory.appendingPathComponent("copilot-instructions", isDirectory: true) + } + + static let copilotInstructionsVariable = "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" + /// What an agent's environment is given besides: for Copilot CLI, the /// folder of instructions it is told to run its commands in shells the /// user sees, next to any its own environment names (MCP-13). public static func instructionsEnvironment(agent: String, directory: URL?, prompt: String?, current: [String: String]) throws -> [String: String] { guard agent == "copilot", let prompt, let directory else { return [:] } - let folder = directory.appendingPathComponent("copilot-instructions", isDirectory: true) + let folder = copilotInstructionsFolder(in: directory) let file = folder.appendingPathComponent("instructions/agentterm.instructions.md") try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) try writeText("---\napplyTo: \"**\"\n---\n" + prompt + "\n", to: file) - let name = "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" + let name = copilotInstructionsVariable let theirs = current[name].flatMap { $0.isEmpty ? nil : $0 } return [name: [theirs, folder.path].compactMap { $0 }.joined(separator: ",")] } diff --git a/Sources/AgentTermHost/FirstPromptInput.swift b/Sources/AgentTermHost/FirstPromptInput.swift new file mode 100644 index 0000000..f1c3e84 --- /dev/null +++ b/Sources/AgentTermHost/FirstPromptInput.swift @@ -0,0 +1,40 @@ +import Foundation + +/// Recognizes text followed by Return in the terminal input stream, without +/// retaining the user's message. Frames may split a paste or a key sequence. +struct FirstPromptInput { + private var characters = 0 + private var escaped = false + private var sequence: [UInt8]? + private var pasting = false + + mutating func submitted(_ data: Data) -> Bool { + for byte in data { + if let parameters = sequence { + if (0x40...0x7e).contains(byte) { + if byte == 0x7e { + if parameters == Array("200".utf8) { pasting = true } + if parameters == Array("201".utf8) { pasting = false } + } + sequence = nil + } else if parameters.count < 16 { + sequence?.append(byte) + } + } else if escaped { + escaped = false + if byte == 0x5b || byte == 0x4f { sequence = [] } + } else { + switch byte { + case 0x1b: escaped = true + case 0x0d, 0x0a: + if !pasting && characters > 0 { return true } + case 0x03, 0x15: characters = 0 // Cancel or clear the line. + case 0x08, 0x7f: characters = max(0, characters - 1) + case 0x20...0x7e, 0xc2...0xf4: characters += 1 + default: break + } + } + } + return false + } +} diff --git a/Sources/AgentTermHost/HostServer.swift b/Sources/AgentTermHost/HostServer.swift index aa45732..db17e08 100644 --- a/Sources/AgentTermHost/HostServer.swift +++ b/Sources/AgentTermHost/HostServer.swift @@ -287,9 +287,13 @@ public final class HostServer { /// in it was found (#129). Its hooks and MCP server have until a /// grace after it to be heard from. var agentSince: Date? + var firstPromptInput = FirstPromptInput() + var firstPromptAt: Date? /// Whether AgentTerm had instructions for its agent when it started /// (#172): what the session was given, whatever is saved later. var promptGiven = true + /// The Copilot instructions in the launched shell's environment. Nil when disabled. + var copilotInstructionsPrepared: Bool? /// A call of one of AgentTerm's own tools that its agent said it is /// about to make, and when: until the call comes to its server, or /// the agent says anything else (#141). @@ -317,6 +321,8 @@ public final class HostServer { /// What Settings > Shell has run first in it, typed with Return /// once it shows its prompt, as a person would. var pendingStartup: String? + /// It was started as a shell, not with a command of its own. + var isShell = true init(info: SessionInfo, process: PTYProcess, screenLines: Int) { self.info = info @@ -2885,7 +2891,7 @@ public final class HostServer { case .success(let made): if let problem = made.problem { server.send(.error(problem), to: client) } let request = CreateRequest(command: made.prepared.command, cwd: made.prepared.directory, title: Handoff.name(of: target), size: size) - if let created = server.create(request, for: client), let branch = made.branch { + if let created = server.create(request, for: client, startsWithPrompt: true), let branch = made.branch { server.sessions[created]?.info.branch = branch server.broadcastSessions() } @@ -3481,6 +3487,11 @@ public final class HostServer { // Typing takes control of the session's size. if session.arbiter.activity(client.id) { applySize(of: session) } used(by: client) + if session.info.link != nil, session.info.link?.hooks == nil, session.firstPromptAt == nil, + session.firstPromptInput.submitted(frame.payload) + { + session.firstPromptAt = configuration.now() + } session.process.write(frame.payload) // It may have stopped the turn, and not every agent says so: nor // does Antigravity when its question for leave is cancelled (#141). @@ -3521,7 +3532,7 @@ public final class HostServer { @discardableResult private func create( _ request: CreateRequest, for client: Client?, conversationID: String? = nil, openedBy: SessionID? = nil, run: Schedule? = nil, - environment more: [String: String] = [:] + environment more: [String: String] = [:], startsWithPrompt: Bool = false ) -> SessionID? { // The host's home: the user's, or a test's own, never the home of // the person running the tests. @@ -3551,10 +3562,14 @@ public final class HostServer { } // Copilot CLI does not take an MCP server's instructions: it reads // what it is told from a folder its environment names. + let copilotPrompt = agentPrompt(for: "copilot") + let instructionsVariable = AgentHooks.copilotInstructionsVariable + var copilotDirectory: URL? if let told = try? AgentHooks.instructionsEnvironment( - agent: "copilot", directory: configuration.hooksDirectory, prompt: agentPrompt(for: "copilot"), current: environment) + agent: "copilot", directory: configuration.hooksDirectory, prompt: copilotPrompt, current: environment) { environment.merge(told) { _, new in new } + if told[instructionsVariable] != nil { copilotDirectory = configuration.hooksDirectory.map(AgentHooks.copilotInstructionsFolder) } } // A schedule's run of Antigravity trusts the schedule's folder, as // the user asked by scheduling it there; for that run only. @@ -3624,13 +3639,20 @@ public final class HostServer { ) let session = Session(info: info, process: process, screenLines: configuration.screenLines) session.agentKey = agentKey + if copilotPrompt != nil { + let directories = environment[instructionsVariable]?.components(separatedBy: ",") ?? [] + session.copilotInstructionsPrepared = copilotDirectory.map { directories.contains($0.path) } ?? false + } if let agentID = info.agent { session.info.link = AgentLink() session.agentSince = configuration.now() + if run != nil || startsWithPrompt { session.firstPromptAt = session.agentSince } session.promptGiven = agentPrompt(for: agentID) != nil refreshPrompt(session) } session.marksPrepared = marksPrepared + session.isShell = isShell + if info.agent == nil { session.info.running = !isShell } session.info.openedBy = openedBy session.pendingTyped = request.typed.flatMap { $0.isEmpty ? nil : $0 } session.pendingStartup = startup @@ -3817,10 +3839,12 @@ public final class HostServer { /// while it runs, what was heard before it included. private func typedAgentFound(_ agent: String, in session: Session) { session.info.typedAgent = agent + session.firstPromptAt = nil + session.firstPromptInput = FirstPromptInput() session.agentSince = configuration.now() let early = heardEarly.removeValue(forKey: session.info.id) ?? [] session.info.link = AgentLink(hooks: early.contains(.hooks) ? true : nil, mcp: early.contains(.mcp) ? true : nil) - session.promptGiven = agentPrompt(for: agent) != nil + session.promptGiven = agent == "copilot" ? session.copilotInstructionsPrepared != nil : agentPrompt(for: agent) != nil refreshPrompt(session) } @@ -3828,7 +3852,7 @@ public final class HostServer { /// they reach its agent and what its MCP server did. private func refreshPrompt(_ session: Session) { guard let agent = session.info.agent ?? session.info.typedAgent, var link = session.info.link else { return } - link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp) + link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp, copilotPrepared: session.copilotInstructionsPrepared) session.info.link = link } @@ -3840,6 +3864,14 @@ public final class HostServer { var changed = false let now = configuration.now() for session in sessions.values { + // Whether closing it stops a program at work, asked first then. + if session.info.agent == nil { + let running = !session.isShell || session.process.runsAnotherProgram + if running != session.info.running { + session.info.running = running + changed = true + } + } if session.info.agent == nil, let front = session.process.foregroundCommand { let typed = SessionSummaries.agent(forCommand: front) if let typed, typed != session.info.typedAgent { @@ -3858,10 +3890,13 @@ public final class HostServer { } } guard var link = session.info.link, let since = session.agentSince, now.timeIntervalSince(since) >= configuration.linkGrace else { continue } - if link.hooks == nil { link.hooks = false } + let agent = session.info.agent ?? session.info.typedAgent + if link.hooks == nil, let submitted = session.firstPromptAt, now.timeIntervalSince(submitted) >= configuration.linkGrace { + link.hooks = false + } if link.mcp == nil { link.mcp = false } - if let agent = session.info.agent ?? session.info.typedAgent { - link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp) + if let agent { + link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp, copilotPrepared: session.copilotInstructionsPrepared) } if link != session.info.link { session.info.link = link diff --git a/Sources/AgentTermHost/PTYProcess.swift b/Sources/AgentTermHost/PTYProcess.swift index f515a73..ffad85d 100644 --- a/Sources/AgentTermHost/PTYProcess.swift +++ b/Sources/AgentTermHost/PTYProcess.swift @@ -153,6 +153,15 @@ public final class PTYProcess { return ProcessNames.command(of: group) } + /// Whether a program other than the one it started is in front of the + /// terminal: a command run at the shell's prompt. False at the prompt, + /// and once the program has ended. + public var runsAnotherProgram: Bool { + guard !finished else { return false } + let group = tcgetpgrp(master) + return group > 0 && group != pid + } + public func resize(_ size: TermSize) { guard !finished else { return } Self.setSize(size, on: master) diff --git a/Sources/AgentTermMac/AgentTermApp.swift b/Sources/AgentTermMac/AgentTermApp.swift index 5b519cd..79e50e3 100644 --- a/Sources/AgentTermMac/AgentTermApp.swift +++ b/Sources/AgentTermMac/AgentTermApp.swift @@ -813,9 +813,9 @@ private struct TabCommands: View { Button("Close All Files") { model.closeFileTabs(pane: pane) } .keyboardShortcut("w", modifiers: [.command, .shift]) .disabled(files.documents.isEmpty && model.diffTabFile == nil) - Button("Close Other Tabs…") { model.closeTabs(.init(keepGroup: model.frontStripTab, pane: pane)) } + Button(model.asksToClose(.init(keepGroup: model.frontStripTab, pane: pane)) ? "Close Other Tabs…" : "Close Other Tabs") { model.closeTabs(.init(keepGroup: model.frontStripTab, pane: pane)) } .disabled(model.tabCount < 2) - Button(model.sessions.isEmpty ? "Close All Tabs" : "Close All Tabs…") { model.closeTabs(.init(pane: pane)) } + Button(model.asksToClose(.init(pane: pane)) ? "Close All Tabs…" : "Close All Tabs") { model.closeTabs(.init(pane: pane)) } .disabled(model.tabCount == 0) } } diff --git a/Sources/AgentTermMac/AppModel.swift b/Sources/AgentTermMac/AppModel.swift index a7add85..38bbfb9 100644 --- a/Sources/AgentTermMac/AppModel.swift +++ b/Sources/AgentTermMac/AppModel.swift @@ -2347,14 +2347,15 @@ final class AppModel: ObservableObject { connection?.send(.kill(session: session)) } - /// A session the user asked to end, until that is confirmed. Ending - /// one stops what runs in it, an agent in the middle of its work for - /// one, and ⌘W is pressed out of habit: it asks first, as closing many - /// tabs does and as the iPhone does. + /// A session the user asked to end, until that is confirmed. Only one + /// at work is asked about (`SessionInfo.isBusy`): ending it stops an + /// agent in the middle of its turn, or a command; a shell at its prompt + /// or a done agent ends at once. @Published var pendingEnd: SessionInfo? func requestEnd(_ session: SessionID) { - pendingEnd = sessions.first { $0.id == session } + guard let info = sessions.first(where: { $0.id == session }) else { return } + if info.isBusy { pendingEnd = info } else { close(session) } } func takeControl() { @@ -2535,10 +2536,16 @@ final class AppModel: ObservableObject { sessions.filter { closes(stripTab(of: TabID.session($0)), by: request) } } - /// Closes every tab but the one the request keeps. Sessions are running - /// programs, so ending any is asked about first. + /// Closes every tab but the one the request keeps. Ending a session at + /// work is asked about first; shells at their prompt and done agents + /// end with the tabs. func closeTabs(_ request: CloseRequest = CloseRequest()) { - if sessionsEnded(by: request).isEmpty { closeTabsConfirmed(request) } else { pendingCloseRequest = request } + if asksToClose(request) { pendingCloseRequest = request } else { closeTabsConfirmed(request) } + } + + /// Whether a request is asked about first: a session it ends is at work. + func asksToClose(_ request: CloseRequest) -> Bool { + sessionsEnded(by: request).contains(where: \.isBusy) } func closeTabsConfirmed(_ request: CloseRequest) { diff --git a/Sources/AgentTermMac/PaneViews.swift b/Sources/AgentTermMac/PaneViews.swift index c2c3edd..ac2299f 100644 --- a/Sources/AgentTermMac/PaneViews.swift +++ b/Sources/AgentTermMac/PaneViews.swift @@ -271,7 +271,7 @@ struct SessionUsageBar: View { // Whether its hooks and AgentTerm's MCP server talk to the host. if let link = session.link { Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1, height: 24) - AgentLinkMark(link: link, typed: session.agent == nil ? name : nil) + AgentLinkMark(link: link, agent: agent, typed: session.agent == nil ? name : nil) } } .frame(height: 46) diff --git a/Sources/AgentTermMac/Panes.swift b/Sources/AgentTermMac/Panes.swift index e56a842..ed57ed8 100644 --- a/Sources/AgentTermMac/Panes.swift +++ b/Sources/AgentTermMac/Panes.swift @@ -274,18 +274,28 @@ extension AppModel { // MARK: Closing a tab of the strip, all it holds (#145) - /// Closes a tab of the strip and everything in it. One of the user's - /// own is asked first as `CloseWords.asks` says; an agent's is ending - /// the agent, which is always asked, and the host ends its shells and - /// closes its pages with it. + /// Closes a tab of the strip and everything in it. Shells are asked + /// about first only when one of them runs a command; pages, diffs and + /// files close at once, a file with unsaved changes asking to be saved. + /// An agent's tab is ending the agent, asked while it is at work, and + /// the host ends its shells and closes its pages with it. func requestCloseGroup(_ group: String) { - if let holder = TabID.holder(of: group) { - if CloseWords.asks(holder.kind, count: members(of: group).count) { pendingGroupClose = group } else { closeGroup(group) } + if TabID.holder(of: group) != nil { + if asksToClose(group) { pendingGroupClose = group } else { closeGroup(group) } } else if let agent = session(forTab: group) { requestEnd(agent.id) } } + /// Whether closing a tab of the strip is asked first: its agent, or + /// one of its shells, is at work (`SessionInfo.isBusy`). + func asksToClose(_ group: String) -> Bool { + if let holder = TabID.holder(of: group) { + return holder.kind == .shells && userShells(in: holder.project).contains(where: \.isBusy) + } + return session(forTab: group)?.isBusy ?? false + } + /// Closes a tab of the user's own, once asked. A file with unsaved /// changes is asked about, and stays open until it is answered. func closeGroup(_ group: String) { diff --git a/Sources/AgentTermMac/SessionTabs.swift b/Sources/AgentTermMac/SessionTabs.swift index cbdb97a..9de020a 100644 --- a/Sources/AgentTermMac/SessionTabs.swift +++ b/Sources/AgentTermMac/SessionTabs.swift @@ -165,8 +165,8 @@ private struct SessionTab: View { /// The tab of one of a project's groups of the user's own (#127): its /// shells, its pages, its diffs or its files, with how many it holds. The /// row under the strip has them, each with its own ×. The tab's × closes -/// all it holds, asked first as `CloseWords.asks` says (#145), as Chrome's -/// window closes its tabs. +/// all it holds, as Chrome's window closes its tabs (#145): asked first +/// only when a shell in it runs a command (`AppModel.asksToClose`). private struct HolderTabLabel: View { /// What is in front, which it shows (#178). @EnvironmentObject private var front: FrontState @@ -189,7 +189,7 @@ private struct HolderTabLabel: View { private func close() { model.requestCloseGroup(id) } /// What its × and its menu say: "End Shells", "Close Browser…". - private func closing(_ count: Int) -> String { CloseWords.groupAction(kind) + (CloseWords.asks(kind, count: count) ? "…" : "") } + private func closing(_ count: Int) -> String { CloseWords.groupAction(kind) + (model.asksToClose(id) ? "…" : "") } var body: some View { let members = model.members(of: id) @@ -254,7 +254,7 @@ struct TabStripMenu: View { Button("Close All Files") { model.closeFileTabs(pane: paneID) } .disabled(files.documents.isEmpty && model.diffTabFile == nil) .help("Close every file and diff of this pane. The terminals stay.") - Button(model.sessionsEnded(by: .init(pane: paneID)).isEmpty ? "Close All Tabs" : "Close All Tabs…") { model.closeTabs(.init(pane: paneID)) } + Button(model.asksToClose(.init(pane: paneID)) ? "Close All Tabs…" : "Close All Tabs") { model.closeTabs(.init(pane: paneID)) } .disabled(count == 0) .help("Close every tab of this pane, ending its sessions. Pinned tabs stay.") } @@ -268,8 +268,8 @@ struct CloseOthersButton: View { private var count: Int { request.pane.flatMap { model.paneLayout.pane($0)?.tabs.count } ?? model.tabCount } var body: some View { - // The dots say a question follows, which it does when sessions would end. - Button(model.sessionsEnded(by: request).isEmpty ? "Close Other Tabs" : "Close Other Tabs…") { model.closeTabs(request) } + // The dots say a question follows, which it does when a session at work would end. + Button(model.asksToClose(request) ? "Close Other Tabs…" : "Close Other Tabs") { model.closeTabs(request) } .disabled(count < 2) .help("Close every other tab of this pane, ending the other sessions. Pinned tabs stay.") } diff --git a/Sources/AgentTermMac/SidebarView.swift b/Sources/AgentTermMac/SidebarView.swift index f1c16b7..ec3a524 100644 --- a/Sources/AgentTermMac/SidebarView.swift +++ b/Sources/AgentTermMac/SidebarView.swift @@ -195,7 +195,7 @@ private struct HolderListRow: View { } /// Closing it from its menu, as from its tab of the strip (#145). - private var closing: String { CloseWords.groupAction(kind) + (CloseWords.asks(kind, count: count) ? "…" : "") } + private var closing: String { CloseWords.groupAction(kind) + (model.asksToClose(id) ? "…" : "") } var body: some View { HStack(spacing: 8) { @@ -207,6 +207,9 @@ private struct HolderListRow: View { .font(.system(size: 12.5)) .lineLimit(1) Spacer(minLength: 0) + if hovering { + CloseButton(help: closing) { model.requestCloseGroup(id) } + } } .padding(.leading, loose ? 8 : 24) .padding(.trailing, 8) @@ -253,6 +256,9 @@ private struct ItemListRow: View { .lineLimit(1) .truncationMode(.middle) Spacer(minLength: 0) + if hovering { + CloseButton(help: closing) { close() } + } } .padding(.leading, leading) .padding(.trailing, 8) @@ -526,6 +532,9 @@ struct FolderRow: View { .foregroundStyle(.orange) .help(waiting == 1 ? "A session waits for you" : "\(waiting) sessions wait for you") } + if hovering { + CloseButton(help: "Remove from List") { model.remove(folder) } + } } .padding(.horizontal, 6) .padding(.vertical, 6) @@ -539,6 +548,7 @@ struct FolderRow: View { .accessibilityIdentifier("folder-" + folder.path) .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton) .accessibilityAction { select() } + .accessibilityAction(named: "Remove from List") { model.remove(folder) } .help(folder.path) .contextMenu { // A folder of another Mac is not in this Mac's Finder. diff --git a/Sources/AgentTermProtocol/AgentLink.swift b/Sources/AgentTermProtocol/AgentLink.swift index fa7cb87..5b96a7b 100644 --- a/Sources/AgentTermProtocol/AgentLink.swift +++ b/Sources/AgentTermProtocol/AgentLink.swift @@ -23,8 +23,8 @@ public struct AgentLink: Codable, Equatable, Sendable { /// said it started (Claude Code, Codex), or through the session's /// environment (Copilot CLI). case given - /// Not given: they reach this agent through its MCP server, which - /// did not start. + /// The expected instructions folder could not be provided, or the + /// MCP server delivering the instructions did not start. case missing /// The user's text for this agent was empty when it started. case disabled @@ -41,7 +41,7 @@ public struct AgentLink: Codable, Equatable, Sendable { /// What the instructions came to, from how they are given to `agent` /// and whether there were any (`given`) when it started. - public static func prompt(agent: String, given: Bool, mcp: Bool?) -> Prompt? { + public static func prompt(agent: String, given: Bool, mcp: Bool?, copilotPrepared: Bool? = nil) -> Prompt? { guard given else { return .disabled } switch agent { case "claude", "codex": @@ -50,7 +50,7 @@ public struct AgentLink: Codable, Equatable, Sendable { case false?: return .missing case nil: return nil } - case "copilot": return .given + case "copilot": return copilotPrepared.map { $0 ? .given : .missing } ?? .unverified default: return .unverified } } @@ -73,8 +73,9 @@ public enum AgentLinkWords { if link.isWhole { return "Hooks and MCP connected" } if link.hooks == nil && link.mcp == nil { return "Connecting…" } switch (link.hooks, link.mcp) { - case (false, false): return "No hooks, no MCP" - case (false, _): return "No hooks" + case (nil, true): return "Waiting for the first hook" + case (false, false): return "No hook response, no MCP" + case (false, _): return "No hook response" case (_, false): return "No MCP" default: return "Connecting…" } @@ -84,7 +85,7 @@ public enum AgentLinkWords { public static func hooks(_ heard: Bool?) -> String { switch heard { case true?: return "Hooks: heard. Its state, the Inbox and notifications work." - case false?: return "Hooks: not heard. Its state is not shown, it does not come to the Inbox, and no notification is made." + case false?: return "No hook event received after the first message. Check Hooks & MCP in Settings if the agent has responded." case nil: return "Hooks: not heard yet." } } @@ -120,9 +121,9 @@ public enum AgentLinkWords { } } - public static func promptStatus(_ prompt: AgentLink.Prompt?) -> String { + public static func promptStatus(_ prompt: AgentLink.Prompt?, agent: String? = nil) -> String { switch prompt { - case .given?: return "Given" + case .given?: return agent == "copilot" ? "File provided" : "Given" case .missing?: return "Not given" case .disabled?: return "Disabled" case .unverified?: return "Unverified" @@ -131,7 +132,13 @@ public enum AgentLinkWords { } /// Why, under the row. - public static func promptDetail(_ prompt: AgentLink.Prompt?) -> String { + public static func promptDetail(_ prompt: AgentLink.Prompt?, agent: String? = nil) -> String { + switch (agent, prompt) { + case ("copilot", .given): return "AgentTerm prepared the instructions file and passed its folder to this session. Copilot does not confirm reading it." + case ("copilot", .missing): return "AgentTerm could not provide its instructions folder to this session." + case ("agy", .unverified): return "Antigravity uses a plugin rule. AgentTerm cannot confirm whether this session loaded it." + default: break + } switch prompt { case .given?: return "AgentTerm's instructions reached this session." case .missing?: return "They come through the MCP server, which did not start." diff --git a/Sources/AgentTermProtocol/CloseWords.swift b/Sources/AgentTermProtocol/CloseWords.swift index de387c5..f76fdaf 100644 --- a/Sources/AgentTermProtocol/CloseWords.swift +++ b/Sources/AgentTermProtocol/CloseWords.swift @@ -19,12 +19,6 @@ public enum CloseWords { public static let endButton = "End Session" - /// Whether closing a tab of the user's own that holds `count` is asked - /// first: ending a shell always is, as ending any session; closing pages, - /// diffs or files when there are several. - public static func asks(_ kind: HolderKind, count: Int) -> Bool { - kind == .shells ? count > 0 : count > 1 - } /// The question before a tab of the user's own is closed: "End 3 shells?". public static func groupQuestion(_ kind: HolderKind, count: Int) -> String { diff --git a/Sources/AgentTermProtocol/Messages.swift b/Sources/AgentTermProtocol/Messages.swift index 8ef40a7..4369ef4 100644 --- a/Sources/AgentTermProtocol/Messages.swift +++ b/Sources/AgentTermProtocol/Messages.swift @@ -84,6 +84,10 @@ public struct SessionInfo: Codable, Equatable, Identifiable, Sendable { /// AgentTerm: its hooks and AgentTerm's MCP server (#129). Nil for a /// session with no agent. public var link: AgentLink? + /// Whether ending this session stops a program at work: a command run + /// in a shell, or the command a session was started with. False for a + /// shell at its prompt; nil for an agent's session, whose `state` says. + public var running: Bool? public init( id: SessionID, title: String, cwd: String, size: TermSize, createdAt: Date, @@ -107,6 +111,18 @@ public struct SessionInfo: Codable, Equatable, Identifiable, Sendable { /// What to call the session in a list: its summary, or its title until /// there is one. public var displayName: String { summary ?? title } + + /// Whether ending it stops work in progress, which is asked first: an + /// agent, started or typed, that is not done with its turn (one whose + /// state is not known is taken to be at work), or a program running in + /// a shell. A shell at its prompt and a done agent end at once. + public var isBusy: Bool { + if agent != nil || typedAgent != nil { + if case .done? = state { return false } + return true + } + return running == true + } } public struct CreateRequest: Codable, Equatable, Sendable { diff --git a/Sources/AgentTermTerminal/AgentLinkMark.swift b/Sources/AgentTermTerminal/AgentLinkMark.swift index 956e060..d2b3d40 100644 --- a/Sources/AgentTermTerminal/AgentLinkMark.swift +++ b/Sources/AgentTermTerminal/AgentLinkMark.swift @@ -7,14 +7,16 @@ import SwiftUI /// to do; the same on the Mac and the iPhone (principle 9). public struct AgentLinkMark: View { let link: AgentLink + let agent: String? /// The agent typed by hand in a shell, by name, when it is one. let typed: String? /// Smaller, for a phone. let compact: Bool @State private var shown = false - public init(link: AgentLink, typed: String? = nil, compact: Bool = false) { + public init(link: AgentLink, agent: String? = nil, typed: String? = nil, compact: Bool = false) { self.link = link + self.agent = agent self.typed = typed self.compact = compact } @@ -73,8 +75,8 @@ public struct AgentLinkMark: View { id: "mcp", name: AgentLinkWords.mcpRow, status: AgentLinkWords.mcpStatus(link.mcp), detail: link.mcp == false ? AgentLinkWords.mcp(false) : nil, look: Self.look(link.mcp)), Row( - id: "prompt", name: AgentLinkWords.promptRow, status: AgentLinkWords.promptStatus(link.prompt), - detail: AgentLinkWords.promptDetail(link.prompt), look: prompt), + id: "prompt", name: AgentLinkWords.promptRow, status: AgentLinkWords.promptStatus(link.prompt, agent: agent), + detail: AgentLinkWords.promptDetail(link.prompt, agent: agent), look: prompt), ] } diff --git a/Tests/AgentTermHostTests/AgentLinkTests.swift b/Tests/AgentTermHostTests/AgentLinkTests.swift index dfff5fd..0895f97 100644 --- a/Tests/AgentTermHostTests/AgentLinkTests.swift +++ b/Tests/AgentTermHostTests/AgentLinkTests.swift @@ -47,11 +47,12 @@ final class AgentLinkTests: XCTestCase { /// With `shells`, the host gives the agents AgentTerm's MCP server and /// its instructions, kept in the test's own state folder. - private func start(grace: TimeInterval, shells: Bool = false) throws { + private func start(grace: TimeInterval, shells: Bool = false, hooksDirectory: URL? = nil) throws { let agents = root.appendingPathComponent("agents").path var configuration = HostServer.Configuration( port: 0, token: token, listenOnTailscale: false, detectAgents: { AgentDetector.detect(in: agents) }, home: root.path, usageDirectory: root.appendingPathComponent("usage")) + configuration.hooksDirectory = hooksDirectory configuration.agentsDirectory = agents configuration.foldersFile = root.appendingPathComponent("folders.json") configuration.linkGrace = grace @@ -104,6 +105,40 @@ final class AgentLinkTests: XCTestCase { wait("its server heard") { sessions.first?.link == AgentLink(hooks: true, mcp: true, prompt: .disabled) } } + func testOnlySubmittedTextStartsTheHookCheck() { + var input = FirstPromptInput() + for keys in [ + "\r", "\u{1b}[A", "\r", "x", "\u{7f}", "\r", "discard", "\u{15}", "\r", + "\u{1b}[20", "0~first line\r", "second line", "\u{1b}[201~", + ] { + XCTAssertFalse(input.submitted(Data(keys.utf8))) + } + XCTAssertTrue(input.submitted(Data("\r".utf8))) + } + + func testAgentsWithDelayedHooksWaitForTheFirstEventAfterTheGracePeriod() throws { + let agents = ["agy", "copilot", "codex", "claude"] + let trigger = root.appendingPathComponent("first-turn") + for agent in agents { + let stop = event(agent, agent == "copilot" ? "agentStop" : "Stop") + try standIn(agent, "while [ ! -f '\(trigger.path)' ]; do sleep 0.1; done\n\(stop)\nexec sleep 600") + } + try start(grace: 0.5) + for agent in agents { client.send(.create(CreateRequest(command: agent, cwd: root.path))) } + wait("all sessions past the grace period") { sessions.count == agents.count && sessions.allSatisfy { $0.link?.mcp == false } } + XCTAssertTrue(sessions.allSatisfy { $0.link?.hooks == nil }) + for session in sessions { + client.send(.attach(session: session.id, size: .default)) + client.connection(send: session.id, "hello") + } + RunLoop.main.run(until: Date().addingTimeInterval(1)) + XCTAssertTrue(sessions.allSatisfy { $0.link?.hooks == nil }, "typing alone is not a submission") + for session in sessions { client.connection(send: session.id, "\r") } + wait("no hook response after submitting") { sessions.allSatisfy { $0.link?.hooks == false } } + try Data().write(to: trigger) + wait("the first event from each agent") { sessions.allSatisfy { $0.link?.hooks == true } } + } + /// LINK-3: what an agent's session has not heard from within the grace /// of its start is said missing. func testWhatIsNotHeardIsSaidMissing() throws { @@ -111,6 +146,9 @@ final class AgentLinkTests: XCTestCase { try start(grace: 1) client.send(.create(CreateRequest(command: "claude", cwd: root.path))) wait("the session") { sessions.count == 1 } + let id = try XCTUnwrap(sessions.first?.id) + client.send(.attach(session: id, size: .default)) + client.connection(send: id, "hello\r") wait("both said missing") { sessions.first?.link == AgentLink(hooks: false, mcp: false, prompt: .disabled) } } @@ -134,7 +172,28 @@ final class AgentLinkTests: XCTestCase { try standIn("claude", "exec sleep 600") try start(grace: 1, shells: true) client.send(.create(CreateRequest(command: "claude", cwd: root.path))) - wait("not given") { sessions.first?.link == AgentLink(hooks: false, mcp: false, prompt: .missing) } + wait("not given") { sessions.first?.link == AgentLink(mcp: false, prompt: .missing) } + } + + func testCopilotCannotBeGivenInstructionsInAnUnwritableLocation() throws { + let file = root.appendingPathComponent("regular-file") + try Data().write(to: file) + try standIn("copilot", "exec sleep 600") + try start(grace: 1, shells: true, hooksDirectory: file) + client.send(.create(CreateRequest(command: "copilot", cwd: root.path))) + wait("the link check") { sessions.first?.link?.mcp == false } + XCTAssertEqual(sessions.first?.link?.prompt, .missing) + } + + func testCopilotIsGivenThePreparedDirectory() throws { + let file = root.appendingPathComponent("instructions-path") + try standIn("copilot", #"printf '%s' "$COPILOT_CUSTOM_INSTRUCTIONS_DIRS" > '\#(file.path)'; exec sleep 600"#) + try start(grace: 1, shells: true, hooksDirectory: root) + client.send(.create(CreateRequest(command: "copilot", cwd: root.path))) + wait("the link check") { sessions.first?.link?.mcp == false } + let directories = try String(contentsOf: file, encoding: .utf8).split(separator: ",") + XCTAssertEqual(directories.last.map(String.init), root.appendingPathComponent("copilot-instructions").path) + XCTAssertEqual(sessions.first?.link?.prompt, .given) } /// LINK-4: an agent typed by hand in a shell is found from the program @@ -163,6 +222,28 @@ final class AgentLinkTests: XCTestCase { XCTAssertNil(sessions.first?.state) } + /// TABS-7: a shell says it runs a program while a command it was typed + /// is in front, and not at its prompt; a session started with a command + /// runs one from its start. + func testAShellSaysWhileItRunsACommand() throws { + try start(grace: 60) + client.send(.create(CreateRequest(cwd: root.path))) + wait("the shell") { sessions.count == 1 } + let shell = try XCTUnwrap(sessions.first) + client.send(.attach(session: shell.id, size: .default)) + wait("at its prompt") { sessions.first?.running == false } + XCTAssertFalse(try XCTUnwrap(sessions.first).isBusy) + client.connection(send: shell.id, "sleep 600\r") + wait("running a command") { sessions.first?.running == true } + XCTAssertTrue(try XCTUnwrap(sessions.first).isBusy) + client.connection(send: shell.id, "\u{03}") + wait("at its prompt again") { sessions.first?.running == false } + + client.send(.create(CreateRequest(command: "sleep 600", cwd: root.path, title: "build"))) + wait("the command's session") { sessions.contains { $0.title == "build" } } + XCTAssertEqual(sessions.first { $0.title == "build" }?.running, true) + } + /// A program is named as it was started, not by its file: a link named /// as an agent is that agent, as Claude Code's command is a link to a /// file named for its version. diff --git a/Tests/AgentTermMacUITests/HooksAndMCPUITests.swift b/Tests/AgentTermMacUITests/HooksAndMCPUITests.swift index aff4c94..563c2dc 100644 --- a/Tests/AgentTermMacUITests/HooksAndMCPUITests.swift +++ b/Tests/AgentTermMacUITests/HooksAndMCPUITests.swift @@ -239,6 +239,10 @@ final class HooksAndMCPUITests: MacUITestCase { } app.press(.button("Claude Code")) app.wait(for: .id("agent-link"), timeout: 20) + wait("the agent session") { phone.sessions.contains { $0.agent == "claude" } } + let agent = try XCTUnwrap(phone.sessions.first { $0.agent == "claude" }) + phone.send(.attach(session: agent.id, size: .default)) + phone.connection.sendInput(Data("hello\r".utf8), to: agent.id) app.wait("said missing", timeout: 15) { self.label("agent-link") == AgentLinkWords.summary(AgentLink(hooks: false, mcp: false)) } let value = app.first(.id("agent-link"))?.value ?? "" XCTAssertTrue(value.contains(AgentLinkWords.fix), value) diff --git a/Tests/AgentTermMacUITests/PaneUITests.swift b/Tests/AgentTermMacUITests/PaneUITests.swift index a66261c..6d45298 100644 --- a/Tests/AgentTermMacUITests/PaneUITests.swift +++ b/Tests/AgentTermMacUITests/PaneUITests.swift @@ -54,14 +54,21 @@ final class PaneUITests: MacUITestCase { app.wait("the shell picked again") { self.app.isSelected(.id("session-\(shell.id)")) } XCTAssertFalse(app.isSelected(.id("sidebar-shells"))) XCTAssertFalse(app.isSelected(.id(folder))) + app.perform("Remove from List", on: .id(folder)) + app.waitGone(.id(folder)) + XCTAssertTrue(FileManager.default.fileExists(atPath: project.path)) + XCTAssertTrue(phone.sessions.contains { $0.id == shell.id }) } /// TABS-3 (#145): the Shells tab's × ends every shell it holds, asked - /// first; cancelled, they all run on. + /// first while one of them runs a command; cancelled, they all run on. + /// TABS-7: shells at their prompt end at once, nothing asked. func testClosingTheShellsTabEndsAllItsShells() throws { let phone = try device() try newShell(phone, count: 1) - try newShell(phone, count: 2) + let second = try newShell(phone, count: 2) + phone.connection.sendInput(Data("sleep 600\n".utf8), to: second.id) + wait("the command running") { phone.sessions.first { $0.id == second.id }?.running == true } app.perform(CloseWords.groupAction(.shells), on: .id("strip-shells")) app.wait(for: .text(CloseWords.groupQuestion(.shells, count: 2))) app.press(.button("Cancel")) @@ -70,6 +77,14 @@ final class PaneUITests: MacUITestCase { app.press(.button(CloseWords.groupButton(.shells, count: 2))) wait("both shells ended") { phone.sessions.isEmpty } app.wait("the Shells tab gone") { !self.app.exists(.id("strip-shells")) } + + // At their prompt: no question. + try newShell(phone, count: 1) + try newShell(phone, count: 2) + wait("both at their prompt") { phone.sessions.count == 2 && phone.sessions.allSatisfy { $0.running == false } } + app.perform(CloseWords.groupAction(.shells), on: .id("strip-shells")) + wait("both shells ended without a question") { phone.sessions.isEmpty } + XCTAssertFalse(app.exists(.text(CloseWords.groupQuestion(.shells, count: 2))), "it asked about idle shells") } /// PANE-9: the user does not split the window: no button in the strip, diff --git a/Tests/AgentTermProtocolTests/AgentLinkPromptTests.swift b/Tests/AgentTermProtocolTests/AgentLinkPromptTests.swift index 23573fe..e849ef9 100644 --- a/Tests/AgentTermProtocolTests/AgentLinkPromptTests.swift +++ b/Tests/AgentTermProtocolTests/AgentLinkPromptTests.swift @@ -4,6 +4,12 @@ import XCTest /// LINK-12 (#172): what AgentTerm's instructions came to in a session, from /// how they reach its agent. final class AgentLinkPromptTests: XCTestCase { + func testConnectedServerCanWaitForTheFirstHook() { + let link = AgentLink(mcp: true) + XCTAssertFalse(link.isMissing) + XCTAssertEqual(AgentLinkWords.summary(link), "Waiting for the first hook") + } + func testHowTheInstructionsReachedASession() { // Claude Code and Codex: through the MCP server. for agent in ["claude", "codex"] { @@ -12,9 +18,14 @@ final class AgentLinkPromptTests: XCTestCase { XCTAssertNil(AgentLink.prompt(agent: agent, given: true, mcp: nil), "not known while the server is not heard yet") } // Copilot CLI: the session's environment, whatever its server did. - XCTAssertEqual(AgentLink.prompt(agent: "copilot", given: true, mcp: false), .given) + XCTAssertEqual(AgentLink.prompt(agent: "copilot", given: true, mcp: false, copilotPrepared: true), .given) + XCTAssertEqual(AgentLink.prompt(agent: "copilot", given: true, mcp: true, copilotPrepared: false), .missing) + XCTAssertEqual(AgentLink.prompt(agent: "copilot", given: true, mcp: true), .unverified) + XCTAssertEqual(AgentLinkWords.promptStatus(.given, agent: "copilot"), "File provided") + XCTAssertTrue(AgentLinkWords.promptDetail(.missing, agent: "copilot").contains("instructions folder")) // Antigravity: a rule of its plugin, not seen for one session. XCTAssertEqual(AgentLink.prompt(agent: "agy", given: true, mcp: true), .unverified) + XCTAssertTrue(AgentLinkWords.promptDetail(.unverified, agent: "agy").contains("plugin rule")) // None saved when it started: disabled, for any agent. for agent in ["claude", "codex", "copilot", "agy"] { XCTAssertEqual(AgentLink.prompt(agent: agent, given: false, mcp: true), .disabled) diff --git a/Tests/AgentTermProtocolTests/ProtocolTests.swift b/Tests/AgentTermProtocolTests/ProtocolTests.swift index 0037238..b18df0b 100644 --- a/Tests/AgentTermProtocolTests/ProtocolTests.swift +++ b/Tests/AgentTermProtocolTests/ProtocolTests.swift @@ -531,11 +531,11 @@ final class ProtocolTests: XCTestCase { func testAnAgentsLinkInWordsAndOnTheWire() throws { XCTAssertEqual(AgentLinkWords.summary(AgentLink()), "Connecting…") XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: true, mcp: true)), "Hooks and MCP connected") - XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: false, mcp: true)), "No hooks") + XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: false, mcp: true)), "No hook response") XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: true, mcp: false)), "No MCP") - XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: false, mcp: false)), "No hooks, no MCP") + XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: false, mcp: false)), "No hook response, no MCP") XCTAssertEqual(AgentLinkWords.summary(AgentLink(hooks: true)), "Connecting…") - XCTAssertTrue(AgentLinkWords.hooks(false).contains("does not come to the Inbox")) + XCTAssertTrue(AgentLinkWords.hooks(false).contains("after the first message")) XCTAssertTrue(AgentLinkWords.mcp(false).contains("cannot open shells and pages")) XCTAssertTrue(AgentLink(hooks: false).isMissing) XCTAssertFalse(AgentLink(hooks: true).isMissing) @@ -578,16 +578,34 @@ final class ProtocolTests: XCTestCase { XCTAssertEqual(CloseWords.groupQuestion(.files, count: 1), "Close 1 file?") XCTAssertEqual(CloseWords.groupButton(.browser, count: 2), "Close 2 Pages") XCTAssertEqual(CloseWords.groupButton(.diffs, count: 1), "Close Diff") - // A shell is a running program: ending even one is asked, as ending - // any session is. One page, diff or file is closed at once. - XCTAssertTrue(CloseWords.asks(.shells, count: 1)) - for kind in [HolderKind.browser, .diffs, .files] { - XCTAssertFalse(CloseWords.asks(kind, count: 1), kind.title) - XCTAssertTrue(CloseWords.asks(kind, count: 2), kind.title) - } XCTAssertNotEqual(CloseWords.groupAction(.files), "Close All Files", "the pane's own item") } + /// TABS-7: ending a session is asked first only while it is at work. + func testASessionIsBusyOnlyWhileAtWork() { + var shell = SessionInfo(id: 1, title: "zsh", cwd: "/", size: .default, createdAt: Date()) + XCTAssertFalse(shell.isBusy, "a shell not heard from yet") + shell.running = false + XCTAssertFalse(shell.isBusy, "a shell at its prompt") + shell.running = true + XCTAssertTrue(shell.isBusy, "a shell running a command") + + var agent = SessionInfo(id: 2, title: "Claude Code", cwd: "/", size: .default, createdAt: Date(), agent: "claude") + XCTAssertTrue(agent.isBusy, "an agent whose state is not known") + agent.state = .working(since: Date()) + XCTAssertTrue(agent.isBusy, "an agent at work") + agent.state = .waitingForPermission(AgentQuestion(text: "Run ls?")) + XCTAssertTrue(agent.isBusy, "an agent in the middle of its turn") + agent.state = .done(said: nil) + XCTAssertFalse(agent.isBusy, "a done agent") + + var typed = SessionInfo(id: 3, title: "zsh", cwd: "/", size: .default, createdAt: Date()) + typed.running = true + typed.typedAgent = "codex" + typed.state = .done(said: nil) + XCTAssertFalse(typed.isBusy, "an agent typed in a shell, done") + } + /// MCP-36: what is wrong with the agents' server, in words, and a cause /// this build does not know still read. func testAnAgentShellsFaultInWords() throws { diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 6dfbf9c..96e992c 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1595,14 +1595,18 @@ of 0.6, and is the released build's. While the agent is told anything **Whether a session was told** (#172). `AgentLink.prompt` says what AgentTerm's instructions came to in one session: given, missing, disabled -or unverified, from how they reach its agent (`AgentLink.prompt(agent:given:mcp:)`): +or unverified, from how they reach its agent (`AgentLink.prompt`): through the MCP server for Claude Code and Codex, so given once the server is heard and missing when it is not; through the environment for Copilot -CLI, so given; through a rule of its plugin for Antigravity, which the host +CLI, shown as “File provided” once the file is written and its directory is +present in the launch environment, or “Not given” if preparation fails. +Copilot does not acknowledge reading the file. Instructions come through a rule of its plugin for Antigravity, which the host cannot see for one session. Whether there were instructions is taken when the agent starts (`Session.promptGiven`): a change in Settings later is the next session's. The mark's popover has a row each for Hooks, MCP and System -Prompt. +Prompt. The hook check waits for the first submitted message. If no hook +arrives within 20 seconds of submission, the session reports that no hook +responded. A later event changes its status to Heard. **What an agent is told.** The host works out one text for each agent: what the user saved for it in Settings > Agents (`setAgentPrompt`, kept in diff --git a/docs/TESTING.md b/docs/TESTING.md index 6ee79f6..27cc8ba 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -395,13 +395,14 @@ new, `new.txt` new. "A second device" is another client on the same host. | TAB-1 | A shell and two agents | Pick the shell in the sidebar | Each agent has a tab; the shell is in the Shells tab, in its row, not a tab of its own (#127), and its terminal is shown | M | | TAB-2 | The same | Pin an agent's tab | The host has the pin | H, M | | TAB-3 | The arrangement from TAB-2 | Quit the Mac app and open it again; look on a second device | The same arrangement on both, also after the restart | H, M | -| TAB-4 | Several tabs, the Shells tab pinned, one file with unsaved changes | Close Others, Close All | The app asks before ending sessions; the pinned tab, with the shells it holds, and the unsaved file stay | M (Close Others: it asks, and the pinned tab stays) | +| TAB-4 | Several tabs, agents at work among them, the Shells tab pinned, one file with unsaved changes | Close Others, Close All | The app asks before ending a session at work (TABS-7); the pinned tab, with the shells it holds, and the unsaved file stay | M (Close Others: it asks, and the pinned tab stays) | | TAB-5 | A file open and a diff picked | Look at the strip of tabs | The Files and Diffs tabs next to the sessions, the file and the diff in their rows | M (as part of FILE-3 and GIT-4) | | TAB-6 (#127) | An agent's session on the iPhone | Pin it from its row's menu | Its row says it is pinned; the host has the pin | P | | TAB-7 (#169) | A tab, a page, a group or a session with its × | The pointer is over it; a click beside the glyph, within the control | An 18-point control with a background closes it; a click outside it selects | hand: the tests press elements through accessibility, which does not show where a click lands | | TABS-1 (#127) | An agent, its shell, a shell of the user's, a shell whose agent ended | Which have tabs of their own | The agent only: the Mac and the phones keep the same ones in the arrangement | U | -| TABS-2 (#145) | Closing a tab of the strip, ending an agent with 0, 1 or several shells and pages | What is asked, in `CloseWords` | "End 3 shells?", "Close 2 Pages", "Its 2 shells and 1 page are closed with it."; one shell asked, one page, diff or file not; the Files tab's item is not the pane's "Close All Files" | U | -| TABS-3 (#145) | Two shells of the user's | End Shells on the Shells tab; Cancel; again, End 2 Shells | "End 2 shells?"; both still run; both end and the tab goes | M | +| TABS-2 (#145) | Closing a tab of the strip, ending an agent with 0, 1 or several shells and pages | What is asked, in `CloseWords` | "End 3 shells?", "Close 2 Pages", "Its 2 shells and 1 page are closed with it."; the Files tab's item is not the pane's "Close All Files" | U | +| TABS-3 (#145) | Two shells of the user's, one running `sleep 600` | End Shells on the Shells tab; Cancel; again, End 2 Shells | "End 2 shells?"; both still run; both end and the tab goes | M | +| TABS-7 | A shell at its prompt, a shell running a command, a session started with a command, an agent working, waiting or done | Close each from the list at the left or the strip: its ×, its menu, Close Others, Close All, ⌘W | Asked first only for a command running or an agent not done (one whose state is not known counts as at work); a shell at its prompt, a done agent and pages, diffs and files close at once, a file with unsaved changes asking to be saved; a menu item has "…" only when it will ask | U, H, M | | TABS-6 (#152) | A shell of the user's, picked | Pick the folder in the list; the Shells row; the shell | The folder's row alone is marked, the shell still shown; then the Shells row alone, with End Shells in its menu; then the shell alone | M | | TABS-5 (#146) | A new agent, its conversation not named yet, with a shell beside it | Read the agent's item in its row, and its tab | The item says "Agent"; the tab says "Claude Code": never the same | M (PANE-20's test) | | TABS-4 (#145) | An agent with a page it opened and a shell from + Shell | End Session on the agent's tab | The question names its shell and its page; the agent and its shell end, the page closes; no Shells or Browser tab of the user's is left with them | M | @@ -993,7 +994,7 @@ A second host stands in for the other Mac, with a project of its own. | SETUP-8 (#142) | Codex's config.toml with the user's own and AgentTerm's hooks; a table written where Codex 0.169.1 writes one it adds (above the comments the file ends with); hooks a build before wrote between marks, a table of Codex's between them | Install again; Remove | What Codex added is there after both, each hook once; taken out, the file is the user's and Codex's to the letter; the marks of before go with their hooks, and what was between them stays | H | | SETUP-9 (#129) | The stand-ins; the agent's own command for the server run as the user copies it; AgentTerm's own command alone (`agenttermd setup `) | AgentTerm's command; the agent's; taken out, each its part. Codex: its command first, then AgentTerm's; its command again | AgentTerm's command adds only what the agent has no command for, and takes only that out; the server is the agent's command's. Codex's server, added and given nothing of its session, is said so, with what to do; AgentTerm's command names the variable under the lines Codex wrote; Codex's command run again loses it, and that is said; taken out, config.toml is empty of both | H | | LINK-2 (#129) | A stand-in Claude Code whose hook writes its start, and whose server says it started | Its session starts | Its link: not known, then hooks heard, then both | H | -| LINK-3 (#129) | A stand-in that says nothing | Its session starts | Both said missing once the grace is over | H | +| LINK-3 (#129) | A stand-in that says nothing | Start the session and send a message | MCP is checked from launch. A missing hook is reported after the first message and its grace period | H | | LINK-4 (#129) | A shell; a program named `claude` typed in it, its hook said first | Typed; Control C | The shell is the agent's while it runs, its hooks heard (its state shown), its server said missing; then a shell again, with nothing of the agent's | H | | LINK-5 (#129) | Each link | Said | "Connecting…", "Hooks and MCP connected", "No hooks", "No MCP", "No hooks, no MCP", in the same words on both apps | U | | LINK-6 (#129) | A stand-in Claude Code on the Mac | Its session | Its usage band's mark says "No hooks, no MCP" once the grace is over, with what to do | M | @@ -1002,9 +1003,11 @@ A second host stands in for the other Mac, with a project of its own. | LINK-9 (#129) | A shell of the user's on the Mac | A program named `claude` typed in it; Control C | While it runs, the shell shows the usage band and the mark of its hooks and server; then a shell again, without them | M | | LINK-10 (#140) | The processes of a hook and of a server as each real agent starts them (2026-11-18): Claude Code and Codex with `--no-daemon`, whose hooks have no terminal; Copilot CLI and Antigravity; Codex's shared app server; a shell between; a test that starts the server itself; an agent that ended | Asked which agent in no terminal started it | The agent that started it is looked for past the shells; only Codex's app server, in no terminal, is found; a program that is no shell is not looked past; one that cannot be asked is not said to have no terminal | U | | LINK-11 (#140) | A host and an agent's session; the real `agenttermd`; a program named `codex`, in no terminal, with that session's environment, as Codex's shared app server has the one of the session that started it; the same program in a session's terminal | It runs its hook of a prompt and AgentTerm's MCP server | In no terminal: the server offers no tools, the hook writes nothing, the session's link and state stay as they were. In a terminal: all of the tools, the hooks and the server heard, the state shown | H | -| LINK-12 (#172) | Claude Code and Codex with their MCP server heard, not heard, not yet; Copilot CLI; Antigravity; no instructions saved | What the instructions came to | Given, not given, checking; given; unverified; disabled, whatever the agent | U | +| LINK-12 (#172) | Claude Code and Codex with their MCP server heard, not heard, not yet; Copilot CLI; Antigravity; no instructions saved | What the instructions came to | Given, not given, checking; file provided or not given for Copilot; unverified for Antigravity; disabled for any agent with no instructions | U | | LINK-13 (#172) | Instructions saved for Claude Code; the stand-in, which has neither hooks nor an MCP server | Its session's mark is opened | Three rows, Hooks, MCP and System Prompt, each with its mark and state: not heard, not connected, not given, red | M | | LINK-14 (#172) | A host that gives Claude Code AgentTerm's MCP server and its instructions; a stand-in | Its session started; its server heard, or not within the grace | Checking until the server is heard, then given; not given when it is not heard. A host with no instructions (a test's) says disabled from the start, whatever is heard | H | +| LINK-14a | Copilot launched with instructions configured | Launch with a writable instructions directory and then with a regular file blocking the directory | The first process receives the directory. The second reports Not given after the link check | `AgentLinkTests` | H | +| LINK-14b | All four agents idle before their first turn | Type without submitting, submit, wait past the timeout, then deliver a hook | Hooks stay pending while typing. The unanswered submission shows No hook response. A late hook changes it to Heard | `AgentLinkTests` | H | | LINK-15 (#172) | Instructions saved for Claude Code; a stand-in heard when the test says, its hooks first, then its MCP server; the mark's popover open from the start | The session goes on with the popover open | Checking for all three; the hooks heard (green), the MCP server still checking; then all green, the instructions given; the popover's rows follow the mark's (pictures looked at) | M | | LINK-16 (#172) | A stand-in Claude Code whose hooks are heard and which starts no MCP server; then no instructions for it; a stand-in Antigravity with instructions | Its session started; the instructions taken out in Settings; a new session; Antigravity's | Hooks green, MCP red, the instructions not given; the running session still says so after the edit; the new one, disabled; Antigravity's, unverified, in the popover (pictures looked at) | M | | HOOKS-1 (#129) | Stand-in Claude Code and Codex; Copilot CLI and Antigravity not installed | Settings > Hooks & MCP; Install Claude Code; Remove | Each agent and what it has; not installed said, with no button; the commands shown, each with what it is for: Claude Code's own for the server, AgentTerm's for its hooks and status line, and those that take them out; Install runs them, at the user's scope; all of it there; then none | M | diff --git a/iOS/AgentTerm/TerminalScreen.swift b/iOS/AgentTerm/TerminalScreen.swift index 4d28193..8c6d436 100644 --- a/iOS/AgentTerm/TerminalScreen.swift +++ b/iOS/AgentTerm/TerminalScreen.swift @@ -323,7 +323,7 @@ struct TerminalScreen: View { // Whether its hooks and AgentTerm's MCP server talk to the Mac. if let link = info.link { Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1, height: 22) - AgentLinkMark(link: link, typed: info.agent == nil ? model.agentName(agent) : nil, compact: true) + AgentLinkMark(link: link, agent: agent, typed: info.agent == nil ? model.agentName(agent) : nil, compact: true) } } .frame(height: 38) From 870f31e580c0e87a65db9ef5d995e2ef7b4e90fc Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Wed, 25 Nov 2026 11:10:13 +0700 Subject: [PATCH 3/5] style: remove the blank line left by CloseWords.asks Co-Authored-By: Claude Opus 5.5 --- Sources/AgentTermProtocol/CloseWords.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/AgentTermProtocol/CloseWords.swift b/Sources/AgentTermProtocol/CloseWords.swift index f76fdaf..200a8c0 100644 --- a/Sources/AgentTermProtocol/CloseWords.swift +++ b/Sources/AgentTermProtocol/CloseWords.swift @@ -19,7 +19,6 @@ public enum CloseWords { public static let endButton = "End Session" - /// The question before a tab of the user's own is closed: "End 3 shells?". public static func groupQuestion(_ kind: HolderKind, count: Int) -> String { switch kind { From 02e6a609c63643395a57c72cd29fb96058b0a661 Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Wed, 25 Nov 2026 11:43:33 +0700 Subject: [PATCH 4/5] test(host): cover read-on-move-on notices across devices end to end Add a PushTests case for NOTICE-7b (#321): with the Mac and the iPhone connected, a question answered from the iPhone's terminal, a question asked in place of another, and a task whose session ends are each handled as moved on and read in both Inboxes and in the host's log. Update the NOTICE-5 comment and docs to say moved on is read too. --- .../NoticeCenterTests.swift | 4 +- Tests/AgentTermHostTests/PushTests.swift | 97 +++++++++++++++++++ docs/TESTING.md | 3 +- 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/Tests/AgentTermHostTests/NoticeCenterTests.swift b/Tests/AgentTermHostTests/NoticeCenterTests.swift index 437da73..410df46 100644 --- a/Tests/AgentTermHostTests/NoticeCenterTests.swift +++ b/Tests/AgentTermHostTests/NoticeCenterTests.swift @@ -109,8 +109,8 @@ final class NoticeCenterTests: XCTestCase { } /// NOTICE-5 (#180): read on one device is read in the log, once, and - /// no longer to be shown; handled by being answered, opened or - /// dismissed is read too, by moving on is not. + /// no longer to be shown; handled by being answered, opened, + /// dismissed or moved on is read too (#321). func testReadOnOneDeviceIsReadForAll() throws { let center = NoticeCenter(file: file) let first = try XCTUnwrap(center.update(sessions: [session(1, asked)], now: now).new.first) diff --git a/Tests/AgentTermHostTests/PushTests.swift b/Tests/AgentTermHostTests/PushTests.swift index ad99d3e..eff5555 100644 --- a/Tests/AgentTermHostTests/PushTests.swift +++ b/Tests/AgentTermHostTests/PushTests.swift @@ -741,4 +741,101 @@ final class PushTests: XCTestCase { XCTAssertEqual(phone.log?.first { $0.id == id }?.read, true) XCTAssertEqual(phone.alerts, [], "read: not shown again") } + + /// A stand-in whose agent asks, is answered, asks twice more, the second + /// question in place of the first, and is done: one step for each line. + private func askingStandIn() throws -> URL { + let script = root.appendingPathComponent("claude") + let hook = Handoff.shellQuote(tool.path) + " hook claude" + func permission(_ command: String) -> String { + "printf '%s' '{\"hook_event_name\":\"PermissionRequest\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"\(command)\"}}' | \(hook) PermissionRequest" + } + try """ + #!/bin/sh + read line; printf '%s' '{"hook_event_name":"UserPromptSubmit","prompt":"go"}' | \(hook) UserPromptSubmit + read line; \(permission("make test")) + read line; printf '%s' '{"hook_event_name":"PostToolUse","tool_name":"Bash"}' | \(hook) PostToolUse + read line; \(permission("make lint")) + read line; \(permission("make deploy")) + read line; printf '%s' '{"hook_event_name":"Stop","last_assistant_message":"Deployed."}' | \(hook) Stop + exec sleep 600 + """.write(to: script, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + return script + } + + /// A device's Inbox as its app keeps it, from what the host told it, in + /// the order it was told. + private func inbox(of client: Client) -> InboxBook { + var book = InboxBook() + for message in client.messages { + switch message { + case .noticeLog(let list): book.take(list, log: true) + case .notice(let notice): book.take([notice]) + case .noticeHandled(let id, let handled): book.handled(id, handled) + case .noticesRead(let ids): book.markRead(ids: ids) + default: break + } + } + return book + } + + /// NOTICE-7b (#321): through the host, with the Mac and the iPhone + /// connected. A question answered by what is typed into its session from + /// the iPhone, a question asked in place of another, and a task whose + /// session ends: each notice is handled as moved on and is read in both + /// Inboxes, which have nothing unread left. Nobody read, opened or + /// answered any of them through a notice. + func testANoticeWhoseAgentMovedOnIsReadOnEveryDevice() throws { + let mac = Client(port: port, credential: .token(token), name: "mac", kind: .mac) + let phoneToken = try pair(mac) + let phone = Client(port: port, credential: .token(phoneToken), name: "iPhone") + waitUntil("the phone's log") { phone.log != nil } + mac.connection.send(.create(CreateRequest(command: try askingStandIn().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))) + phone.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 } + + func waiting(_ command: String) -> AgentState { .waitingForPermission(AgentQuestion(text: command)) } + func notice(_ state: AgentState) -> Notice? { mac.notices.first { $0.state == state } } + func handled(_ client: Client, _ id: UInt64) -> Notice.Handled? { + client.messages.lazy.compactMap { if case .noticeHandled(id, let handled) = $0 { return handled } else { return nil } }.first + } + + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("the first question") { notice(waiting("make test")) != nil && phone.notices.count == 1 } + // Answered in the terminal, from the iPhone. + phone.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("working again") { mac.sessions.first?.state?.isWorking == true } + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("the second question") { notice(waiting("make lint")) != nil } + // Something else asked in its place. + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("the third question") { notice(waiting("make deploy")) != nil } + mac.connection.sendInput(Data("\n".utf8), to: agent) + waitUntil("done") { notice(.done(said: "Deployed.")) != nil } + // Its session ends. + mac.connection.send(.kill(session: agent)) + waitUntil("the session gone") { mac.sessions.isEmpty } + + let ids = try [waiting("make test"), waiting("make lint"), waiting("make deploy"), .done(said: "Deployed.")] + .map { try XCTUnwrap(notice($0), "\($0)").id } + for (client, name) in [(mac, "the Mac"), (phone, "the iPhone")] { + for id in ids { + waitUntil("\(name) told \(id) was handled") { handled(client, id) != nil } + XCTAssertEqual(handled(client, id)?.how, .movedOn, "\(name), notice \(id)") + } + let book = inbox(of: client) + XCTAssertEqual(Set(book.entries.map(\.id)), Set(ids), name) + XCTAssertEqual(book.unread, 0, "\(name): nothing unread, \(book.entries.filter { !$0.read }.map(\.notice.state))") + } + // A device that comes later finds them read in the host's log. + let later = Client(port: port, credential: .token(phoneToken), name: "iPhone again") + waitUntil("the log") { later.log != nil } + XCTAssertEqual(later.log?.filter { ids.contains($0.id) && $0.read != true }.map(\.id), [], "read in the host's log") + XCTAssertEqual(inbox(of: later).unread, 0) + } } diff --git a/docs/TESTING.md b/docs/TESTING.md index 27cc8ba..1a9e441 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -921,9 +921,10 @@ A second host stands in for the other Mac, with a project of its own. | NOTICE-2 | A notice | Answered, then dismissed | Handled once, as answered; another state of the session is not handled | H | | NOTICE-3 | Failures of a session, of push, of keeping awake | Reported | Each is a notice for the Inbox; only the session's alerts; dismissing the failure handles its notice | H | | NOTICE-4 | Notices, one told to a phone through Apple | The host starts again; 30 days pass | What was told and pushed is kept, what agents asked is over, numbers are not used again; older than 30 days goes; the file is mode 0600 | H | -| NOTICE-5 (#180) | Two notices of a host | One read on a device, again; one opened; one whose agent moves on | Read once and kept so; read is not to be shown; opened is read, moved on is not | H | +| NOTICE-5 (#180) | Two notices of a host | One read on a device, again; one opened; one whose agent moves on | Read once and kept so; read is not to be shown; opened is read, and moved on too (#321) | H | | NOTICE-6 (#193, #234) | A failure made a notification and shown on the Mac; nothing waits | The host's notices are read again; then it is read | Not shown again on the Mac, still to be shown on a device that was not; once read, on none | H | | NOTICE-7 (#321) | Notices of a question, of another question and of a finished task | The first agent works again (answered in its session's terminal), the second asks something else, the third's session ends | Each is handled and read on every device, the Mac and the iPhone, and taken back from them; only the new question is unread. Before the fix moved on was handled but not read, so a question answered in the terminal stayed unread in both Inboxes. `NoticeCenterTests`, `InboxBookTests` | H, U | +| NOTICE-7b (#321) | The host, with the Mac's app and the iPhone's connected, a session whose agent asks | Its question answered by Return typed into the session from the iPhone; then it asks, asks something else in place of that, is done, and its session is ended | Each of the four notices is handled as moved on on both devices, and read: both Inboxes have nothing unread, and a device that comes later finds them read in the host's log. Before the fix all four stayed unread on both. `PushTests` | H | | NOTICE-7a (#321, by hand) | The real Claude Code (2.1.331, Haiku, low effort), the user's own, in a folder of its own, its hooks given for the session (`--plugin-dir`) | Asked to ask a question with two choices; answered with Return in its terminal | The host takes the question and its two choices; the agent works again, and the question's notice is handled as `movedOn`, read on every device. Also seen: Claude Code offers "Type something." and "Chat about this" after the choices (#320) | `RealClaudeTrialTests` (`AGENTTERM_REAL_AGENTS=1`) | M | | INBOX-7 | A device's Inbox | Notices come, are read, are handled | Kept after reading, newest first, brought up to date when handled | H | | INBOX-8 | An Inbox with a waiting agent and done ones | One deleted, the read ones, all; the log comes again | Deleted ones stay deleted; the waiting one stays until answered | H | From 83bcd75bf7c0516fb60976d8fca80759576f3f10 Mon Sep 17 00:00:00 2001 From: Manh Pham Date: Wed, 25 Nov 2026 17:20:59 +0700 Subject: [PATCH 5/5] docs: 0.15.1's release notes say what #331 changed Reply first in an iPhone notification, closing a shell at its prompt without a question, and what Hooks & MCP says of hooks and Copilot's instructions. Co-Authored-By: Claude Opus 5.5 --- packaging/release-notes/v0.15.1.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packaging/release-notes/v0.15.1.md b/packaging/release-notes/v0.15.1.md index cf4e2ed..03cfeec 100644 --- a/packaging/release-notes/v0.15.1.md +++ b/packaging/release-notes/v0.15.1.md @@ -4,9 +4,10 @@ This release fixes what a review of the whole app found, and a few things the ow ## New -- **What an agent asks is answered from the Inbox**, on the Mac and the iPhone: each choice is a button, and a field takes an answer in your own words, as Claude Code's "Type something." does. +- **What an agent asks is answered from the Inbox**, on the Mac and the iPhone: each choice is a button, and a field takes an answer in your own words, as Claude Code's "Type something." does. An iPhone notification offers Reply first, before the agent's choices. - **A notice is read on every device once its agent moves on**, also when you answered it in its terminal. A notice also waits 10 seconds before it shows, and is not shown at all if you acted meanwhile. -- **Deleting a schedule and removing a paired device ask first.** Quitting with unsaved files asks too. +- **Deleting a schedule and removing a paired device ask first.** Quitting with unsaved files asks too. Closing a shell asks only while a program runs in it; a shell at its prompt closes at once. +- **Hooks & MCP says what it knows**: a session's hooks are said to be missing only once its agent was given a first message and did not answer through them, and Copilot CLI's instructions show as "File provided" only when their folder reached the session. - **A pairing link opened from elsewhere asks before it pairs**; a code scanned in the app does not. - **What cannot be done while the Mac is not connected is said at once** on the iPhone (a commit, a save, a schedule, a file), and what you were writing is kept. A message sent from a terminal is kept with the reason, and keys typed meanwhile are dropped and said once, not sent later. - **The banners on the iPhone take their own room** at the top, instead of covering the list.