diff --git a/CHANGELOG.md b/CHANGELOG.md index b8b85cf9..9630061a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha - `scripts/install.ps1` installs the Windows CLI from PowerShell (`irm https://raw.githubusercontent.com/2witstudios/PurePoint/main/scripts/install.ps1 | iex`). Like `install.sh`, it verifies the release's minisign signature or its GitHub attestation before installing, and stops if neither can be checked unless `PU_INSTALL_SKIP_VERIFY=1` is set. - `pu daemon status --json` prints the daemon's health and autostart state as JSON. - Projects can be reordered, and every device shows the same order. Each machine's daemon saves the order of its projects. On the Mac, drag a project within its section or use Move Up / Move Down in its menu; on the iPad, use Move Up / Move Down; on the phone, long-press a machine and choose Reorder Projects…. Changes reach every device following that machine right away. `pu projects` lists projects in the same order. New projects are added at the end. +- The phone's agent screen has **⌫** (hold to keep deleting) and **clear** keys that edit the agent's own input box, so text already typed into an agent, from the phone or the Mac, can be fixed or cleared from the phone. They work with older Mac and Linux hosts. - Paste an image (Cmd+V) into any agent's terminal, or drop files on a remote agent's terminal, and the macOS app uploads it to the agent's machine and types its path there, so remote agents can see screenshots. Uploads are kept in `~/.pu/attachments` on that machine for 7 days. - Send photos and files to an agent from the iPhone and iPad. On the iPhone, the **+** menu beside an agent's prompt offers Photos and Files; each upload's path is added to your draft so you can write around it before sending. On the iPad, each agent pane has a paperclip button (Photos, Files), and you can paste an image or drag files in from other apps; the path is typed at the agent's prompt without pressing Enter. Photos are sent as JPEG, at most 2048 px on the long edge. The phone bridge relays uploads with a new `agent.attach` operation, which needs Full access; phone uploads are limited to 20 MB per file. @@ -41,6 +42,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha - **Breaking: Codex YOLO for all projects is removed** (Settings → Agents, `codexYolo` in `~/.pu/agent-settings.yaml`, `codex_yolo` in `update_global_agent_settings`). If you had it on, Codex now launches with its normal sandbox and approvals. To get the same behaviour, put the flags YOLO added, `--dangerously-bypass-approvals-and-sandbox --no-daemon`, in Codex's launch args for all projects or for one project. An existing `codexYolo` key is ignored and dropped the next time the file is saved, the daemon ignores `codex_yolo` from older clients, and `global_agent_settings_report` still sends `codex_yolo: false` so older apps can read it. ### Fixed +- A prompt the agent had already received could be sent again and again. When Enter emptied a Claude agent's input box but its echo wasn't spotted on screen, the daemon reported "text was not delivered", and the phone offered the text for another send. The daemon now returns `DELIVERY_UNCONFIRMED` with an accurate message, and the phone shows it as sent. Retried typing no longer stacks leftover text under the retyped prompt, a failed delivery leaves the input box empty, and sending the same text again after a failed send asks for confirmation, including after the app is relaunched or another prompt is sent or blocked in between. If the input box can't be read at all after Enter, or it was emptied while other input (someone typing, the phone's clear key) reached the agent during delivery, the daemon returns `DELIVERY_UNKNOWN` and the phone shows the send as failed with delivery unknown, never as sent. An older daemon's "input box cleared but the submitted turn was not echoed" error is shown the same way, because older daemons also returned it when the box couldn't be read. - `pu clean --all --json` now prints one JSON array of results, as it already did when there was nothing to clean, instead of one JSON document per worktree. - On Windows, `pu daemon stop` waits for `pu-engine` to exit, so a `pu daemon start` right after it no longer fails with "daemon did not start within 3 seconds". - On iPad, a new Point Guard conversation always shows the court: wide when the pane is wider than tall, portrait otherwise, never the plain list of plays. Raising the keyboard no longer shrinks the court into the list (it slides up over the bottom of the court, as on the phone). As on the phone, drag a ball off the logo and release it on a play to run that play. The logo leans and turns to follow the ball. diff --git a/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift b/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift index c050ca9b..735dbe84 100644 --- a/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift +++ b/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift @@ -75,7 +75,7 @@ struct ControlledAgent: Codable, Identifiable, Sendable { switch phase { case "dialog": return "Agent is waiting on a prompt. Use the keys below." case "has_draft": - return "Someone is already typing in this agent. Finish or clear that draft on its terminal before sending." + return "The agent's input box already has text. Clear it with ⌫ or clear, or press ⏎ to send it." case "busy": return "Agent is busy. Wait until it is ready before sending a prompt." default: if state == "broken" { return "This agent has stopped." } @@ -135,6 +135,18 @@ struct AgentComposer: Sendable { private(set) var outcome: AgentPromptOutcome? private(set) var reason: String? private(set) var deliveryUncertain = false + /// Text from the latest failed send. A failure can still have reached the agent + /// (a lost receipt, an unseen echo), so resending it needs a deliberate choice. + /// Only a later failure replaces it: neither a blocked send nor a successful send + /// of other text shows whether this one arrived. + private(set) var failedText: String? + /// Sending this draft again could submit the same turn twice. + var resendNeedsConfirmation: Bool { failedText != nil && failedText == text } + /// As `resendNeedsConfirmation`, but also honoring saved recovery records, which + /// outlive this in-memory composer (relaunch rebuilds it from the draft text alone). + func needsConfirmationToSend(given recoveries: [AgentPromptRecovery]) -> Bool { + resendNeedsConfirmation || recoveries.contains { $0.mayHaveReachedAgent && $0.text == text } + } mutating func begin() -> AgentSubmission? { guard pending == nil, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, text.utf8.count <= 65536 @@ -146,6 +158,8 @@ struct AgentComposer: Sendable { mutating func finish(_ submission: AgentSubmission, outcome: AgentPromptOutcome, reason: String?, uncertain: Bool = false) { guard pending?.id == submission.id else { return } pending = nil; self.outcome = outcome; self.reason = reason; deliveryUncertain = uncertain + // Blocked is decided before anything is typed, so only failures are ambiguous. + if outcome == .failed { failedText = submission.text } if (outcome == .confirmed || outcome == .sent) && text == submission.text { text = "" } } } @@ -180,6 +194,20 @@ enum AgentQuickKey: String, CaseIterable, Identifiable, Sendable { } } +/// Line editing for text already in an agent's input box. Sent as literal +/// control characters through `terminal.raw`, which every bridge accepts. +enum AgentEditKey: String, CaseIterable, Identifiable, Sendable { + case backspace = "Backspace", clearLine = "Clear line" + var id: String { rawValue } + var bytes: [UInt8] { + switch self { + case .backspace: return [127] + case .clearLine: return [21] // Ctrl-U: delete to the start of the line + } + } + var text: String { String(decoding: bytes, as: UTF8.self) } +} + struct AgentTerminalOpen: Decodable, Sendable { let streamId: String let machine: String @@ -286,6 +314,10 @@ struct AgentPromptRecovery: Codable, Identifiable, Equatable, Sendable { let text: String var status: String var reason: String? + /// Every unsettled record except a block (decided before anything is typed) + /// may have reached the agent: a failure, a lost receipt, or a send cut off + /// mid-flight that is still marked as awaiting confirmation. + var mayHaveReachedAgent: Bool { status != AgentPromptOutcome.blocked.label } } struct AgentNavigationPreferences: Codable, Equatable, Sendable { diff --git a/apps/purepoint-mobile/PurePoint/AgentControlModel.swift b/apps/purepoint-mobile/PurePoint/AgentControlModel.swift index e236f081..384a3fc3 100644 --- a/apps/purepoint-mobile/PurePoint/AgentControlModel.swift +++ b/apps/purepoint-mobile/PurePoint/AgentControlModel.swift @@ -181,6 +181,9 @@ import UserNotifications var canSend: Bool { sendExplanation == nil && !composer.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + /// Sending the draft could submit a turn that may already have arrived, including + /// one recorded before a relaunch, so the phone asks before sending it. + var resendNeedsConfirmation: Bool { composer.needsConfirmationToSend(given: recoveries) } var draft: String { get { composer.text } set { composer.text = newValue; saveComposer() } @@ -615,6 +618,10 @@ import UserNotifications func sendKey(_ key: AgentQuickKey, screen token: Int) { guard token == screen else { return }; input("terminal.keys", fields: ["key": key.rawValue]) } + /// Edits the agent's own input box, so drafts typed earlier (on any device) can be fixed. + func sendEditKey(_ key: AgentEditKey, screen token: Int) { + guard token == screen else { return }; input("terminal.raw", fields: ["data": key.text]) + } // Called only while the terminal synthesizes a deliberate mouse-wheel event. func sendScroll(_ data: ArraySlice, screen token: Int) { guard token == screen, controlEnabled, !data.isEmpty else { return } diff --git a/apps/purepoint-mobile/PurePoint/AgentsView.swift b/apps/purepoint-mobile/PurePoint/AgentsView.swift index 1779ad08..53d7253f 100644 --- a/apps/purepoint-mobile/PurePoint/AgentsView.swift +++ b/apps/purepoint-mobile/PurePoint/AgentsView.swift @@ -954,6 +954,7 @@ struct AgentControlView: View { private struct AgentControlBar: View { @ObservedObject var model: AgentControlModel @State private var showRecoveries = false + @State private var confirmResend = false @State private var showPhotos = false @State private var showFiles = false @State private var photoItems: [PhotosPickerItem] = [] @@ -1071,7 +1072,10 @@ private struct AgentControlBar: View { .background(Theme.surface, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).stroke(Color.white.opacity(0.07))) .accessibilityLabel("Agent prompt. Return inserts a new line.") - Button { model.sendPrompt(screen: token) } label: { + Button { + // A failed send may still have reached the agent; never repeat it on one tap. + if model.resendNeedsConfirmation { confirmResend = true } else { model.sendPrompt(screen: token) } + } label: { Image(systemName: "arrow.up").font(.body.weight(.semibold)) .foregroundStyle(model.canSend ? Theme.ground : Color(hex: 0x85858D)) .frame(width: 38, height: 38) @@ -1079,6 +1083,12 @@ private struct AgentControlBar: View { .frame(width: 44, height: 44).contentShape(Rectangle()) }.disabled(!model.canSend).accessibilityLabel("Send prompt") } + .confirmationDialog("Send this prompt again?", isPresented: $confirmResend, titleVisibility: .visible) { + Button("Send again") { model.sendPrompt(screen: token) } + Button("Cancel", role: .cancel) {} + } message: { + Text("The last send of this text may have reached the agent anyway. Check its terminal first so the same turn isn't submitted twice.") + } } private func rawRow(_ token: Int) -> some View { HStack(spacing: 6) { @@ -1104,23 +1114,37 @@ private struct AgentQuickKeys: View { private static let order: [AgentQuickKey] = [.enter, .up, .down, .yes, .no, .escape, .interrupt, .tab, .left, .right] var body: some View { let token = model.screenToken - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 5) { - ForEach(Self.order) { key in - Button { - model.sendKey(key, screen: token) - } label: { - Text(Self.face(key)).font(.system(.footnote, design: .monospaced).weight(.medium)) - .foregroundStyle(Theme.ink) - .frame(minWidth: 38, minHeight: 34).padding(.horizontal, 2) - .background(Color(hex: 0x26262A), in: RoundedRectangle(cornerRadius: 7, style: .continuous)) - // Compact key face, full 44-point hit area. - .frame(minHeight: 44).contentShape(Rectangle()) - }.buttonStyle(.plain).accessibilityLabel(key.rawValue) + HStack(spacing: 5) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 5) { + ForEach(Self.order) { key in + Button { + model.sendKey(key, screen: token) + } label: { + Self.keyFace(Text(Self.face(key))) + }.buttonStyle(.plain).accessibilityLabel(key.rawValue) + } } } + // Editing keys stay pinned outside the scroller so a swipe never starts a delete. + Button { model.sendEditKey(.clearLine, screen: token) } label: { Self.keyFace(Text("clear")) } + .buttonStyle(.plain).accessibilityLabel(AgentEditKey.clearLine.rawValue) + .accessibilityHint("Deletes the agent's current input line.") + RepeatingKey(enabled: model.controlEnabled) { model.sendEditKey(.backspace, screen: token) } label: { + Self.keyFace(Image(systemName: "delete.left")) + } + .accessibilityLabel(AgentEditKey.backspace.rawValue) + .accessibilityHint("Deletes one character in the agent's input. Hold to keep deleting.") }.disabled(!model.controlEnabled).opacity(model.controlEnabled ? 1 : 0.4) } + private static func keyFace(_ face: some View) -> some View { + face.font(.system(.footnote, design: .monospaced).weight(.medium)) + .foregroundStyle(Theme.ink) + .frame(minWidth: 38, minHeight: 34).padding(.horizontal, 2) + .background(Color(hex: 0x26262A), in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + // Compact key face, full 44-point hit area. + .frame(minHeight: 44).contentShape(Rectangle()) + } private static func face(_ key: AgentQuickKey) -> String { switch key { case .enter: return "⏎" @@ -1132,6 +1156,35 @@ private struct AgentQuickKeys: View { } } +/// Fires on touch-down, then repeats while held, like the keyboard's delete key. +private struct RepeatingKey: View { + let enabled: Bool + let action: () -> Void + @ViewBuilder let label: () -> Label + @State private var repeater: Task? + var body: some View { + label() + .onLongPressGesture(minimumDuration: 3600, maximumDistance: 30, perform: {}, onPressingChanged: { pressing in + repeater?.cancel(); repeater = nil + guard pressing, enabled else { return } + action() + repeater = Task { @MainActor in + try? await Task.sleep(nanoseconds: 450_000_000) + // Bounded so a stuck touch cannot erase an unbounded amount. + for count in 0..<400 { + guard !Task.isCancelled else { return } + action() + try? await Task.sleep(nanoseconds: count < 12 ? 90_000_000 : 40_000_000) + } + } + }) + .onDisappear { repeater?.cancel(); repeater = nil } + .accessibilityElement(children: .ignore) + .accessibilityAddTraits(.isButton) + .accessibilityAction { if enabled { action() } } + } +} + private struct AgentPromptRecoveries: View { @ObservedObject var model: AgentControlModel let screen: Int diff --git a/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift b/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift index fa1052aa..ad782e04 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift @@ -275,6 +275,65 @@ import Foundation try check(!bridge.operations.contains { $0.0 == "terminal.keys" }, "Old key action must never target new agent") } + static func editKeysAreRawAndFencedToTheirScreen() async throws { + let (model, bridge, defaults, suite) = try await setup() + defer { model.transport(host: "", connected: false); defaults.removePersistentDomain(forName: suite) } + try await open(model, bridge); try finishOpen(bridge) + try await wait { model.streamId != nil } + let screen = model.screenToken + model.sendEditKey(.backspace, screen: screen); model.sendEditKey(.clearLine, screen: screen) + try await wait { bridge.operations.filter { $0.0 == "terminal.raw" }.count == 2 } + let raw = bridge.operations.filter { $0.0 == "terminal.raw" } + try check( + raw.map { $0.1["data"] as? String } == ["\u{7f}", "\u{15}"] && raw.allSatisfy { $0.1["encoding"] == nil }, + "Edit keys must send literal DEL and Ctrl-U that every bridge accepts") + try check(raw.allSatisfy { $0.1["streamId"] as? String == "s" }, "Edit keys must target the open stream") + model.closeScreen() + model.sendEditKey(.backspace, screen: screen) + try await Task.sleep(nanoseconds: 50_000_000) + try check( + bridge.operations.filter { $0.0 == "terminal.raw" }.count == 2, "A closed screen must never forward edits") + } + + static func relaunchKeepsResendConfirmation() async throws { + // "killed" models the app ending while the send is still awaiting its receipt. + for outcome in ["failed", "blocked", "killed"] { + let (model, bridge, defaults, suite) = try await setup() + defer { model.transport(host: "", connected: false); defaults.removePersistentDomain(forName: suite) } + try await open(model, bridge); try finishOpen(bridge) + try await wait { model.streamId != nil } + model.editDraft("Once", screen: model.screenToken); model.sendPrompt(screen: model.screenToken) + try await wait { !bridge.prompts.isEmpty } + if outcome != "killed" { + bridge.prompts.removeFirst().resume( + returning: try json("{\"outcome\":\"\(outcome)\",\"reason\":\"Fixture result\"}")) + try await wait { model.composer.pending == nil } + try check( + model.resendNeedsConfirmation == (outcome == "failed"), + "Only a send that may have arrived asks before resending (\(outcome))") + model.closeScreen() + } + let relaunched = AgentControlModel(defaults: defaults) + relaunched.transport(host: "host-a", connected: true, request: bridge.request) + try await wait { !relaunched.machines.isEmpty } + try await open(relaunched, bridge); try finishOpen(bridge, id: "relaunch") + try await wait { relaunched.streamId == "relaunch" } + try check(relaunched.draft == "Once", "Relaunch must restore the unsent draft (\(outcome))") + try check( + relaunched.resendNeedsConfirmation == (outcome != "blocked"), + "Relaunch must keep resend confirmation for a send that may have arrived (\(outcome))") + relaunched.editDraft("Fresh", screen: relaunched.screenToken) + try check(!relaunched.resendNeedsConfirmation, "A fresh draft stays unmarked after relaunch") + try check( + bridge.operations.filter { $0.0 == "agent.prompt" }.count == 1, "Relaunch never resends (\(outcome))") + relaunched.transport(host: "", connected: false) + if outcome == "killed" { + bridge.prompts.removeFirst().resume(returning: try json(#"{"outcome":"failed","reason":null}"#)) + try await wait { model.composer.pending == nil } + } + } + } + static func downgradeAndLateReceipt() async throws { let (model, bridge, defaults, suite) = try await setup() defer { model.transport(host: "", connected: false); defaults.removePersistentDomain(forName: suite) } diff --git a/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift b/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift index 1f3b3f85..266a4aa7 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift @@ -55,6 +55,72 @@ final class AgentControlTests: XCTestCase { [[27], [3], [9], [13], [27, 91, 65], [27, 91, 66], [27, 91, 68], [27, 91, 67], [121], [110]]) } + func testGivenEditKeysShouldSendBackspaceAndLineClearAsLiteralControlCharacters() { + XCTAssertEqual(AgentEditKey.allCases.map(\.bytes), [[127], [21]]) + XCTAssertEqual(AgentEditKey.allCases.map(\.text), ["\u{7f}", "\u{15}"]) + } + + func testGivenFailedSendShouldRequireConfirmationOnlyToResendThatSameText() { + for outcome in [AgentPromptOutcome.confirmed, .sent, .blocked, .failed] { + var composer = AgentComposer(text: "Once") + composer.finish(composer.begin()!, outcome: outcome, reason: nil) + XCTAssertEqual(composer.resendNeedsConfirmation, outcome == .failed, "\(outcome)") + } + var composer = AgentComposer(text: "Once") + composer.finish(composer.begin()!, outcome: .failed, reason: "Delivery uncertain", uncertain: true) + composer.text = "Once, edited" + XCTAssertFalse(composer.resendNeedsConfirmation) + composer.text = "Once" + XCTAssertTrue(composer.resendNeedsConfirmation) + composer.finish(composer.begin()!, outcome: .confirmed, reason: nil) + XCTAssertFalse(composer.resendNeedsConfirmation) + } + + func testGivenFailedTextShouldStayMarkedUntilALaterFailureReplacesIt() { + var composer = AgentComposer(text: "Prompt A") + composer.finish(composer.begin()!, outcome: .failed, reason: "Delivery uncertain", uncertain: true) + // A blocked send of other text says nothing about whether A arrived. + composer.text = "Prompt B" + composer.finish(composer.begin()!, outcome: .blocked, reason: "agent input is busy") + composer.text = "Prompt A" + XCTAssertTrue(composer.resendNeedsConfirmation) + // Neither does a successful send of other text. + composer.text = "Prompt C" + composer.finish(composer.begin()!, outcome: .confirmed, reason: nil) + composer.text = "Prompt A" + XCTAssertTrue(composer.resendNeedsConfirmation) + // Only a later failure replaces the marked text. + composer.text = "Prompt D" + composer.finish(composer.begin()!, outcome: .failed, reason: "Fixture failure") + XCTAssertTrue(composer.resendNeedsConfirmation) + composer.text = "Prompt A" + XCTAssertFalse(composer.resendNeedsConfirmation) + } + + func testGivenSavedRecoveriesShouldMarkTheirTextUnlessBlocked() { + let composer = AgentComposer(text: "Once") + func record(_ status: String, _ text: String = "Once") -> AgentPromptRecovery { + AgentPromptRecovery(id: UUID(), text: text, status: status, reason: nil) + } + XCTAssertFalse(composer.needsConfirmationToSend(given: []), "A fresh draft stays unmarked") + XCTAssertTrue(composer.needsConfirmationToSend(given: [record(AgentPromptOutcome.failed.label)])) + XCTAssertTrue(composer.needsConfirmationToSend(given: [record("Delivery uncertain")])) + XCTAssertFalse( + composer.needsConfirmationToSend(given: [record(AgentPromptOutcome.blocked.label)]), + "A blocked send never typed anything") + XCTAssertFalse( + composer.needsConfirmationToSend(given: [record(AgentPromptOutcome.failed.label, "Other text")]), + "Only the same text is a resend") + } + + @MainActor func testGivenRelaunchShouldStillConfirmResendOfAnUnsettledSend() async throws { + try await AgentControlScenarios.relaunchKeepsResendConfirmation() + } + + @MainActor func testGivenEditKeysShouldReachOnlyTheOpenAgentAsRawInput() async throws { + try await AgentControlScenarios.editKeysAreRawAndFencedToTheirScreen() + } + func testGivenHostMachineAndAgentScopesShouldNeverShareDrafts() throws { let a = AgentScope(host: "host-a", machine: "local", agent: "agent") XCTAssertNotEqual(a.storageKey, AgentScope(host: "host-b", machine: "local", agent: "agent").storageKey) diff --git a/apps/purepoint-mobile/README.md b/apps/purepoint-mobile/README.md index 0fc6a9c1..38481523 100644 --- a/apps/purepoint-mobile/README.md +++ b/apps/purepoint-mobile/README.md @@ -46,7 +46,7 @@ Agents never run local app build phases. Full app/XCTest and temporary ad-hoc ar To name your computers, tap **Connections** at the bottom of the home screen (or the Point Guard chat header), then tap the pencil beside a computer under **Your computers**. Enter a name and tap **Save**. Names are saved on this iPhone, shown in the picker and chat header, and retained when you pair the same computer again; a name you choose is never replaced by the host's label. The address beneath each name distinguishes computers with matching names. -The home screen is the desktop sidebar: **Point Guard** at the top, then **Machines**, each holding its projects, their worktrees and the agents in each, with the same status dot and Permission/Question/Working/Idle pill as the desktop. Tap a project, worktree or machine to fold it; tap an agent to open its terminal, and Back returns to the tree. The **+** on a project or worktree row opens **New**, which lists the agents and presets the computer offers plus Terminal (and New worktree on a project): one tap launches it there and opens it once it is running. Long-press an agent for Rename or Stop. A request the computer never confirmed stays listed for review, blocks another launch in the same place until it is checked or dismissed, and is never resent. While an agent is open, the strip above its terminal switches between the other agents in the same worktree. With Control, an open agent's terminal takes the phone's size while you view it (its Mac view reflows too) and returns to the previous size when you leave; view-only phones and older daemons keep the agent's size, double-tap to fit width. Tap the terminal or the keyboard button beside the agent prompt to hide the keyboard. Point Guard conversation history opens from its toolbar clock. A new conversation shows four plays: tap one, or drag the ball onto it, to fill the composer. Selecting an idle conversation resumes it; during a run you can browse read-only and explicitly Stop before resuming. Tool activity appears inline, with grouped expandable calls and outputs. Tap the conversation area to dismiss the keyboard for reading; interactive scroll dismissal also remains available. Connection/loading status occupies the single subtitle beneath Point Guard in the header, so reconnecting does not move the composer. Tap that header to open connection settings. +The home screen is the desktop sidebar: **Point Guard** at the top, then **Machines**, each holding its projects, their worktrees and the agents in each, with the same status dot and Permission/Question/Working/Idle pill as the desktop. Tap a project, worktree or machine to fold it; tap an agent to open its terminal, and Back returns to the tree. The **+** on a project or worktree row opens **New**, which lists the agents and presets the computer offers plus Terminal (and New worktree on a project): one tap launches it there and opens it once it is running. Long-press an agent for Rename or Stop. A request the computer never confirmed stays listed for review, blocks another launch in the same place until it is checked or dismissed, and is never resent. While an agent is open, the strip above its terminal switches between the other agents in the same worktree. With Control, an open agent's terminal takes the phone's size while you view it (its Mac view reflows too) and returns to the previous size when you leave; view-only phones and older daemons keep the agent's size, double-tap to fit width. Tap the terminal or the keyboard button beside the agent prompt to hide the keyboard. The **⌫** key at the end of the key row deletes one character in the agent's own input box (hold it to keep deleting) and **clear** deletes the current input line, so text already typed into an agent, from the phone or the Mac, can be fixed or cleared. If a send fails, the text stays in the composer, and sending that same text again asks for confirmation, because a failed send can still have reached the agent. Point Guard conversation history opens from its toolbar clock. A new conversation shows four plays: tap one, or drag the ball onto it, to fill the composer. Selecting an idle conversation resumes it; during a run you can browse read-only and explicitly Stop before resuming. Tool activity appears inline, with grouped expandable calls and outputs. Tap the conversation area to dismiss the keyboard for reading; interactive scroll dismissal also remains available. Connection/loading status occupies the single subtitle beneath Point Guard in the header, so reconnecting does not move the composer. Tap that header to open connection settings. The composer’s **+** menu offers **Photos** and **Files**. Images are prepared as JPEG and sent through native Pi RPC to an image-capable model. Text files and PDFs with selectable text are sent as named text; PDF binaries/layout and scanned PDF pages are not uploaded. Attachment chips show `Image` or `Text`, and can be removed before sending. Up to four files fit a 512 KiB prepared-data budget; each text attachment is at most 32 KiB and all prompt text at most 64 KiB. PDFs are limited to 30 pages. Attachments wait locally if Pi is busy; ordinary text can still use the Steer menu → Steer / After reply. diff --git a/apps/purepoint-mobile/bridge/daemon.js b/apps/purepoint-mobile/bridge/daemon.js index 7051c2a5..e26e2374 100644 --- a/apps/purepoint-mobile/bridge/daemon.js +++ b/apps/purepoint-mobile/bridge/daemon.js @@ -94,7 +94,12 @@ export function daemonRequest( onFrame(frame) { connection.close(); if (frame.type === "error") - reject(new Error(frame.message ?? frame.code ?? "Daemon error")); + reject( + Object.assign( + new Error(frame.message ?? frame.code ?? "Daemon error"), + { daemonCode: frame.code }, + ), + ); else resolve(frame); }, onClose(error) { diff --git a/apps/purepoint-mobile/bridge/terminals.js b/apps/purepoint-mobile/bridge/terminals.js index f9b1d7a3..b8dc2ff2 100644 --- a/apps/purepoint-mobile/bridge/terminals.js +++ b/apps/purepoint-mobile/bridge/terminals.js @@ -35,6 +35,18 @@ const ops = new Set([ /** Raw bytes per `agent.attach` chunk. Base64 stays under the daemon connection's 256 KiB write backlog. */ export const attachChunkBytes = 128 * 1024; export const terminalOperation = (op) => ops.has(op); +// Enter emptied an input box the daemon actually saw: the turn was taken. +const submittedUnconfirmed = (error) => + error?.daemonCode === "DELIVERY_UNCONFIRMED"; +// The daemon could not tell whether Enter submitted the prompt. Older daemons +// report that as DELIVERY_FAILED with this message, which they also used when +// the box was unreadable, so it may still be sitting unsubmitted in the box. +const deliveryUnknown = (error) => + error?.daemonCode === "DELIVERY_UNKNOWN" || + (error?.daemonCode === "DELIVERY_FAILED" && + /input box cleared but the submitted turn was not echoed/.test( + error.message, + )); /** Each instance is private to one authenticated WebSocket, including same-device sockets. */ export function terminalConnection({ @@ -433,17 +445,41 @@ export function terminalConnection({ : `agent input is ${agent.phase ?? "not ready"}; use the keys or wait`, }; check(); - const reply = await daemonRequest( - machine.socket, - { - type: "input", - agent_id: r.agentId, - data: Buffer.from(r.text).toString("hex"), - submit: true, - ...(version >= 10 ? { cancel_on_disconnect: true } : {}), - }, - { signal, timeout: 360000 }, - ); + let reply; + try { + reply = await daemonRequest( + machine.socket, + { + type: "input", + agent_id: r.agentId, + data: Buffer.from(r.text).toString("hex"), + submit: true, + ...(version >= 10 ? { cancel_on_disconnect: true } : {}), + }, + { signal, timeout: 360000 }, + ); + } catch (error) { + check(); + // Enter emptied the input box: the agent took the turn and only + // the echo check missed it. Reporting this as failed invites a + // duplicate resend, so it is a delivered-but-unconfirmed send. + if (submittedUnconfirmed(error)) + return { + outcome: "sent", + reason: + "Submitted, but the agent's screen did not echo it. Check the terminal before sending again.", + }; + // The text may be submitted or still waiting in the box. Never + // claim delivery; as a failure the phone keeps the draft and + // asks before any resend. + if (deliveryUnknown(error)) + return { + outcome: "failed", + reason: + "Delivery unknown: the agent's input box could not be checked after Enter. Check the terminal: the prompt may have been submitted or may still be in its input box.", + }; + throw error; + } check(); if (reply.type !== "ok") throw new Error("Unexpected daemon delivery response"); diff --git a/apps/purepoint-mobile/bridge/terminals.test.js b/apps/purepoint-mobile/bridge/terminals.test.js index beb92dbb..b2def100 100644 --- a/apps/purepoint-mobile/bridge/terminals.test.js +++ b/apps/purepoint-mobile/bridge/terminals.test.js @@ -85,9 +85,9 @@ async function fixture(t) { inputs.push({ r, socket }); if (r.submit && !hold) send( - fail + fail === true ? { type: "error", message: "Echo mismatch" } - : { type: "ok" }, + : fail || { type: "ok" }, ); } } @@ -243,6 +243,68 @@ test("prompts report confirmed, sent, blocked and failed without waiting on unsa }); }); +test("a prompt Enter submitted but the screen never echoed is sent, never failed", async (t) => { + const f = await fixture(t), + c = client(f); + t.after(c.connection.dispose); + const prompt = () => + c.request({ + op: "agent.prompt", + machine: "local", + agentId: "ag-one", + text: "Hello", + }); + // Reporting failure here leaves the text resendable and duplicates the turn. + f.fail({ + type: "error", + code: "DELIVERY_UNCONFIRMED", + message: "ag-one: Enter cleared the input box", + }); + const result = await prompt(); + assert.equal(result.outcome, "sent"); + assert.match(result.reason, /Check the terminal before sending again/); + f.fail({ + type: "error", + code: "DELIVERY_FAILED", + message: "text was not delivered to ag-one: Enter did not submit the prompt", + }); + assert.equal((await prompt()).outcome, "failed"); +}); + +test("a prompt whose input box was unreadable after Enter is failed and never claimed sent", async (t) => { + const f = await fixture(t), + c = client(f); + t.after(c.connection.dispose); + // Older daemons sent the legacy message for an unreadable box as well, so + // it cannot prove the turn was taken either. + for (const frame of [ + { + type: "error", + code: "DELIVERY_UNKNOWN", + message: + "ag-one: the input box could not be read after Enter, so it is unknown whether the prompt was submitted; check the agent before sending again", + }, + { + type: "error", + code: "DELIVERY_FAILED", + message: + "text was not delivered to ag-one: input box cleared but the submitted turn was not echoed in full", + }, + ]) { + f.fail(frame); + const result = await c.request({ + op: "agent.prompt", + machine: "local", + agentId: "ag-one", + text: "Hello", + }); + assert.equal(result.outcome, "failed", frame.code); + assert.match(result.reason, /^Delivery unknown/); + assert.match(result.reason, /may still be in its input box/); + } + assert.equal(f.inputs.length, 2, "the bridge never resends on its own"); +}); + test("same-device attachments belong only to opening connection; keys cannot claim size", async (t) => { const f = await fixture(t), a = client(f), diff --git a/apps/purepoint-mobile/docs/contract.md b/apps/purepoint-mobile/docs/contract.md index 02cec2ef..5e5dec94 100644 --- a/apps/purepoint-mobile/docs/contract.md +++ b/apps/purepoint-mobile/docs/contract.md @@ -183,10 +183,10 @@ Fixed request operations (in the existing `{version:1,id,clientId,op,...}` envel - `agents` → `{machines:[{id,name,online,protocolVersion,screenMayBeInexact,error,complete,agents:[{id,name,agentType,state,idleSeconds,startedAt,projectRoot,worktreeId,screenAware,phase}]}]}`. Phase is `input_ready|has_draft|dialog|busy|null`; idle/start values come directly from the daemon. Inventory is refreshed explicitly. - `terminal.open {machine,agentId}` → `{streamId,machine,agentId,screenMayBeInexact}`; machine `local` selects this Mac, otherwise the registry ID. - `terminal.close {streamId}` → `{}`. -- `terminal.keys {streamId,key}` → `{}`; keys exactly `Esc`, `Ctrl-C`, `Tab`, `Enter`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `y`, `n`. +- `terminal.keys {streamId,key}` → `{}`; keys exactly `Esc`, `Ctrl-C`, `Tab`, `Enter`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `y`, `n`. The phone's Backspace (DEL, hold to repeat) and clear-line (Ctrl-U) keys edit text already in the agent's input box and go through `terminal.raw` as literal control characters, so they work with bridges that predate them. - `terminal.raw {streamId,data,encoding?}` → `{}`; literal UTF-8 by default (`encoding:"utf8"`), or canonical standard base64 with `encoding:"base64"` for byte-preserving generated mouse input. Decoded input is nonempty and at most 64 KiB; invalid encodings/base64 are rejected. Both forms require Control and the connection's own stream. - `terminal.size {streamId,cols,rows}` → `{}`; Control only, v10 only, integer 20–500 columns and 8–300 rows. Sends daemon `claim_size` on that stream's own attachment, so the agent's PTY takes the phone's geometry (latest claim wins). The bridge re-asserts the remembered claim when it reopens the attachment with Control; a view-only reopen or closing the stream releases it and the daemon restores the previous claimant's size (normally the Mac). The resulting geometry still arrives as `terminal.size` events. -- `agent.prompt {machine,agentId,text}` → `{outcome:confirmed|sent|blocked|failed,reason:string|null}`; nonempty text up to 64 KiB. Fresh inventory gates known unsafe phase without waiting for daemon delivery readiness. Dialog reason is `agent is waiting on a prompt, use the keys`. Successful screen-aware echoed delivery returns confirmed, non-screen-aware write returns sent; daemon error returns failed with its reason. Permission denial remains an error receipt. +- `agent.prompt {machine,agentId,text}` → `{outcome:confirmed|sent|blocked|failed,reason:string|null}`; nonempty text up to 64 KiB. Fresh inventory gates known unsafe phase without waiting for daemon delivery readiness. Dialog reason is `agent is waiting on a prompt, use the keys`. Successful screen-aware echoed delivery returns confirmed, non-screen-aware write returns sent; daemon error returns failed with its reason, except `DELIVERY_UNCONFIRMED`, which returns sent: Enter emptied the input box, so the turn was probably taken and the phone must not offer it as a plain resend. `DELIVERY_UNKNOWN` (the input box could not be read after Enter, or it was emptied while other input such as the phone's clear key reached the agent during delivery), and an older daemon's "input box cleared but the submitted turn was not echoed" failure (which it also returned for an unreadable box), return failed with a reason that says delivery is unknown: the text may have been submitted or may still be in the box, so it is neither claimed as delivered nor resent. A failed outcome keeps the draft, and sending that exact text again requires an explicit confirmation on the phone; so does any draft matching a saved, unsettled, non-blocked prompt recovery record, which survives relaunch. Permission denial remains an error receipt. - `agent.attach {machine,agentId,uploadId,name,offset,data,done}` → `{received,path:string|null}`; one chunk of a file sent to the agent's machine with daemon `attach_file` (`docs/product/machines.md`). Control only. `uploadId` is 1–64 of `[A-Za-z0-9_-]`, `name` is 1–200 UTF-8 bytes, `offset` is the bytes already sent for that upload, and `data` is canonical standard base64 of at most 128 KiB (nonempty unless `done`). The first chunk (`offset` 0) checks the agent exists. `path` is set once the `done` chunk is written. The bridge never types into the terminal for an attachment; the phone puts the returned path in its prompt draft. Events are `{type:terminal.output,streamId,data}` (UTF-8 ANSI), `{type:terminal.size,streamId,cols,rows}` (actual PTY geometry), `{type:terminal.reset,streamId,reason}` (discard previous view before fresh snapshot output), and `{type:terminal.closed,streamId,reason}`. Events may precede the open receipt and clients bind them by stream ID. No daemon request/response passthrough, arbitrary engine operations or phone SSH exist; phone size claims exist only through `terminal.size`. Receipts go only to the requesting WebSocket, terminal events only to the stream owner. diff --git a/apps/purepoint-mobile/verification/AgentControlChecks.swift b/apps/purepoint-mobile/verification/AgentControlChecks.swift index 3477f3d7..89a66c5d 100644 --- a/apps/purepoint-mobile/verification/AgentControlChecks.swift +++ b/apps/purepoint-mobile/verification/AgentControlChecks.swift @@ -12,6 +12,16 @@ import Foundation AgentQuickKey.allCases.map(\.bytes) == [ [27], [3], [9], [13], [27, 91, 65], [27, 91, 66], [27, 91, 68], [27, 91, 67], [121], [110], ]) + precondition(AgentEditKey.allCases.map(\.bytes) == [[127], [21]]) + for outcome in [AgentPromptOutcome.confirmed, .sent, .blocked, .failed] { + var c = AgentComposer(text: "Once"); c.finish(c.begin()!, outcome: outcome, reason: nil) + precondition(c.resendNeedsConfirmation == (outcome == .failed)) + } + try await AgentControlScenarios.editKeysAreRawAndFencedToTheirScreen() + var marked = AgentComposer(text: "A"); marked.finish(marked.begin()!, outcome: .failed, reason: nil) + marked.text = "B"; marked.finish(marked.begin()!, outcome: .blocked, reason: nil); marked.text = "A" + precondition(marked.resendNeedsConfirmation) + try await AgentControlScenarios.relaunchKeepsResendConfirmation() try await AgentControlScenarios.allPromptOutcomesAndNoResend() try await AgentControlScenarios.closeUsesOriginatingTransportAndNeverLeavesPendingDraft() try await AgentControlScenarios.failedOriginalAndNewerDraftSurviveNavigationHostChangeAndRelaunch() diff --git a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts index d9b307ab..0fa3e901 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts @@ -114,7 +114,12 @@ export type Request = /** * When true, the engine types data and submits it with Enter (\r). * For agents with a readable input box (Claude) delivery is confirmed - * against the screen and failure returns `DELIVERY_FAILED`; other + * against the screen and failure returns `DELIVERY_FAILED`, or + * `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was + * seen and nothing else wrote to the agent meanwhile (probably + * delivered; do not resend), or `DELIVERY_UNKNOWN` when the box could + * not be read after Enter or other input reached the agent during + * delivery (outcome unknown; check the agent before resending); other * agents get chunked typing plus a delayed Enter. */ submit?: boolean; diff --git a/crates/pu-core/src/protocol/mod.rs b/crates/pu-core/src/protocol/mod.rs index e0f1b0d4..1d9c4116 100644 --- a/crates/pu-core/src/protocol/mod.rs +++ b/crates/pu-core/src/protocol/mod.rs @@ -200,7 +200,12 @@ pub enum Request { data: Vec, /// When true, the engine types data and submits it with Enter (\r). /// For agents with a readable input box (Claude) delivery is confirmed - /// against the screen and failure returns `DELIVERY_FAILED`; other + /// against the screen and failure returns `DELIVERY_FAILED`, or + /// `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was + /// seen and nothing else wrote to the agent meanwhile (probably + /// delivered; do not resend), or `DELIVERY_UNKNOWN` when the box could + /// not be read after Enter or other input reached the agent during + /// delivery (outcome unknown; check the agent before resending); other /// agents get chunked typing plus a delayed Enter. #[serde(default)] #[cfg_attr(feature = "ts", ts(optional = nullable))] diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index f9118758..596004e6 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -60,8 +60,26 @@ pub enum DeliveryError { }, #[error("Enter did not submit the prompt: text is still in the input box")] NotSubmitted, - #[error("input box cleared but the submitted turn was not echoed in full")] + /// Enter emptied the input box, so the agent almost certainly took the + /// turn; only the on-screen echo was not seen. Never retry on this. + #[error( + "Enter cleared the input box, so the prompt was probably submitted, but the turn was not seen echoed on screen; check the agent before sending again" + )] Unconfirmed, + /// After Enter the input box could not be found on screen (the agent was + /// mid-redraw), so it is unknown whether the prompt was submitted or is + /// still sitting in the box. Neither claim delivery nor retry on this. + #[error( + "the input box could not be read after Enter, so it is unknown whether the prompt was submitted; check the agent before sending again" + )] + Unobserved, + /// The box ended up empty without an echo, but other input reached the + /// agent during delivery (someone typing, the phone's clear key), so the + /// empty box may be that edit rather than the submission. + #[error( + "other input reached the agent during delivery, so the empty input box does not show whether the prompt was submitted; check the agent before sending again" + )] + Interfered, #[error("pty write failed: {0}")] Io(#[from] std::io::Error), } @@ -69,6 +87,8 @@ pub enum DeliveryError { const POLL: Duration = Duration::from_millis(25); const CTRL_U: &[u8] = b"\x15"; const BACKSPACE: u8 = 0x7f; +/// How long a final verdict waits for a mid-redraw input box to reappear. +const UNOBSERVED_GRACE: Duration = Duration::from_secs(1); /// Window size of the PTY as `(rows, cols)`, so the emulated screen wraps /// like the real one. @@ -125,12 +145,14 @@ async fn wait_ready( } } -/// Empties the input box after a bad attempt. +/// Empties the input box after a bad attempt. `typed` bounds how many +/// characters the box can hold: delivery only types into an empty box. async fn clear_box( host: &NativePtyHost, fd: &Pty, tracker: &mut ScreenTracker, output: &OutputBuffer, + typed: &str, ) -> Result<(), DeliveryError> { host.write_to_pty(fd, CTRL_U).await?; let deadline = Instant::now() + Duration::from_secs(1); @@ -141,7 +163,11 @@ async fn clear_box( { return Ok(()); } - let n = box_text(tracker).map_or(0, |s| s.chars().count()); + // The box text is whitespace-squashed, so its length undercounts typed + // spaces and newlines; leftovers would stack under the next attempt. + let n = box_text(tracker) + .map_or(0, |s| s.chars().count()) + .max(typed.chars().count()); host.write_to_pty(fd, &vec![BACKSPACE; n]).await?; let deadline = Instant::now() + Duration::from_secs(1); wait_until(tracker, output, deadline, |t| { @@ -162,7 +188,7 @@ async fn type_text( ) -> Result<(), DeliveryError> { let want = squash(text); let mut seen = 0; - for attempt in 1..=opts.max_type_attempts { + for _ in 0..opts.max_type_attempts { host.write_chunked(fd, text.as_bytes()).await?; let hard = Instant::now() + opts.type_timeout; let mut last = box_text(tracker); @@ -185,10 +211,9 @@ async fn type_text( break; // stalled or timed out } seen = box_text(tracker).map_or(0, |s| s.chars().count()); - if attempt == opts.max_type_attempts { - break; - } - clear_box(host, fd, tracker, output).await?; + // Clear after the last attempt too: a partial prompt left in the box + // blocks the next delivery and invites a duplicate on resend. + clear_box(host, fd, tracker, output, text).await?; } Err(DeliveryError::TypeMismatch { attempts: opts.max_type_attempts, @@ -204,10 +229,61 @@ pub async fn deliver_prompt( output: &Arc, text: &str, opts: &DeliveryOptions, +) -> Result<(), DeliveryError> { + deliver_prompt_watching(host, fd, output, text, opts, &OtherInput::default()).await +} + +/// Writes to one agent from anything but prompt delivery (a person typing, +/// the phone's keys). Lets a delivery tell an Enter that emptied the input +/// box from an edit that did, without ever holding those keys back. +#[derive(Debug, Default)] +pub struct OtherInput { + /// `(writes started, writes still landing)`, read and changed together. + state: std::sync::Mutex<(u64, u32)>, +} + +impl OtherInput { + fn state(&self) -> std::sync::MutexGuard<'_, (u64, u32)> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Call before writing; pair with [`OtherInput::landed`] once the write + /// returns, whatever its result. + pub fn started(&self) { + let mut state = self.state(); + state.0 += 1; + state.1 += 1; + } + + pub fn landed(&self) { + let mut state = self.state(); + state.1 = state.1.saturating_sub(1); + } + + /// `(writes started, writes still landing)`. + pub fn snapshot(&self) -> (u64, u32) { + *self.state() + } +} + +/// [`deliver_prompt`], where `other_input` tracks writes to the same agent +/// that did not come from this delivery. An empty box is only taken as a +/// probable submit when no such write started during delivery and none was +/// still landing when it began. +pub async fn deliver_prompt_watching( + host: &NativePtyHost, + fd: &Pty, + output: &Arc, + text: &str, + opts: &DeliveryOptions, + other_input: &OtherInput, ) -> Result<(), DeliveryError> { if text.trim().is_empty() { return Ok(()); } + let (started_before, landing_before) = other_input.snapshot(); let (rows, cols) = winsize(fd); let mut tracker = ScreenTracker::new(output, rows, cols); let want = squash(text); @@ -233,9 +309,17 @@ pub async fn deliver_prompt( if wait_until(&mut tracker, output, last, submitted).await { return Ok(()); } - if box_text(&tracker).is_some_and(|s| !s.is_empty()) { - Err(DeliveryError::NotSubmitted) - } else { - Err(DeliveryError::Unconfirmed) + // The verdict rests on the box, so give a redraw in progress a moment to + // finish before judging; an unseen box is not evidence either way. + let redraw = Instant::now() + UNOBSERVED_GRACE; + wait_until(&mut tracker, output, redraw, |t| t.input_box().is_some()).await; + match box_text(&tracker) { + Some(s) if !s.is_empty() => Err(DeliveryError::NotSubmitted), + // Only an Enter that alone emptied the box counts as probably submitted. + Some(_) if landing_before > 0 || other_input.snapshot().0 != started_before => { + Err(DeliveryError::Interfered) + } + Some(_) => Err(DeliveryError::Unconfirmed), + None => Err(DeliveryError::Unobserved), } } diff --git a/crates/pu-engine/src/engine/mod.rs b/crates/pu-engine/src/engine/mod.rs index 3aca9c79..33d21ab6 100644 --- a/crates/pu-engine/src/engine/mod.rs +++ b/crates/pu-engine/src/engine/mod.rs @@ -87,6 +87,8 @@ pub struct Engine { pending_initial_inputs: Arc>>>, /// Per-agent locks so concurrent sends/triggers never interleave keystrokes. delivery_locks: Arc>>>>, + /// Per-agent input written outside prompt delivery. + other_input: Arc>>>, login_env: Arc>>, reaped_projects: Arc>>, /// Per-project broadcast channels for grid commands. @@ -243,6 +245,7 @@ impl Engine { sessions: Arc::new(Mutex::new(HashMap::new())), pending_initial_inputs: Arc::new(Mutex::new(HashMap::new())), delivery_locks: Arc::new(Mutex::new(HashMap::new())), + other_input: Arc::new(std::sync::Mutex::new(HashMap::new())), login_env: Arc::new(OnceCell::new()), reaped_projects: Arc::new(std::sync::Mutex::new(HashSet::new())), grid_channels: Arc::new(Mutex::new(HashMap::new())), diff --git a/crates/pu-engine/src/engine/pty_operations.rs b/crates/pu-engine/src/engine/pty_operations.rs index 8c4aa648..a2dec03c 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -44,7 +44,7 @@ use std::sync::Arc; use pu_core::paths; use pu_core::protocol::Response; -use crate::delivery::{DeliveryError, DeliveryOptions, deliver_prompt}; +use crate::delivery::{DeliveryError, DeliveryOptions, OtherInput, deliver_prompt_watching}; use crate::output_buffer::OutputBuffer; use crate::pty_manager::Pty; @@ -275,6 +275,21 @@ impl Engine { code: "IO_ERROR".into(), message: format!("write failed: {e}"), }, + // Distinct from DELIVERY_FAILED: the text most likely reached the + // agent, so callers must not treat it as safe to resend. + Err(e @ DeliveryError::Unconfirmed) => Response::Error { + code: "DELIVERY_UNCONFIRMED".into(), + message: format!("{agent_id}: {e}"), + }, + // Neither delivered nor safely undelivered: the box was not seen + // after Enter, or other input may have emptied it, so the text + // may never have been submitted. + Err(e @ (DeliveryError::Unobserved | DeliveryError::Interfered)) => { + Response::Error { + code: "DELIVERY_UNKNOWN".into(), + message: format!("{agent_id}: {e}"), + } + } Err(e) => Response::Error { code: "DELIVERY_FAILED".into(), message: format!("text was not delivered to {agent_id}: {e}"), @@ -289,7 +304,7 @@ impl Engine { None => return Self::agent_not_found(agent_id), } }; - match self.pty_host.write_to_pty(&pty, data).await { + match self.write_user_input(agent_id, &pty, data).await { Ok(()) => Response::Ok, Err(e) => Response::Error { code: "IO_ERROR".into(), @@ -324,12 +339,13 @@ impl Engine { } }; if screen_aware { - deliver_prompt( + deliver_prompt_watching( &self.pty_host, &pty, &output, text, &DeliveryOptions::default(), + &self.other_input(agent_id), ) .await?; } else { @@ -384,6 +400,49 @@ impl Engine { self.pty_host.write_to_pty(pty, data).await } + /// Writes to `agent_id` from anything but prompt delivery, so a delivery + /// can tell an Enter that emptied the box from an edit that did. + pub(crate) fn other_input(&self, agent_id: &str) -> Arc { + let mut counts = self + .other_input + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + counts.entry(agent_id.to_string()).or_default().clone() + } + + /// Writes input from a person or client (attach streams, raw `input`) to + /// an agent. Deliberately not serialized with delivery, so keys such as + /// Esc or Ctrl-C always get through; delivery notices them instead. + /// + /// The write is recorded as started before any byte goes out and stays + /// "landing" until the blocking write returns, so a delivery that begins + /// while it is in flight never mistakes its effect for a submit. Landing + /// is marked by a guard inside the blocking task, so it is recorded even + /// if the caller stops waiting or the write panics. + pub async fn write_user_input( + &self, + agent_id: &str, + pty: &Pty, + data: &[u8], + ) -> Result<(), std::io::Error> { + struct Landing(Arc); + impl Drop for Landing { + fn drop(&mut self) { + self.0.landed(); + } + } + let other_input = self.other_input(agent_id); + other_input.started(); + let landing = Landing(other_input); + let (pty, data) = (pty.clone(), data.to_vec()); + tokio::task::spawn_blocking(move || { + let _landing = landing; + pty.write(&data) + }) + .await + .map_err(std::io::Error::other)? + } + /// Resize a PTY via the pty host. pub async fn resize_pty(&self, pty: &Pty, cols: u16, rows: u16) -> Result<(), std::io::Error> { self.pty_host.resize_pty(pty, cols, rows).await @@ -502,6 +561,22 @@ mod tests { } } + #[tokio::test] + async fn given_raw_and_attach_input_should_count_as_other_input_for_that_agent_only() { + // given + let (engine, id, _tmp) = super::Engine::quiet_screen_session().await; + let count = |agent: &str| engine.other_input(agent).snapshot(); + let pty = engine.sessions.lock().await[&id].pty(); + // when: a raw `input` request and an attach stream's input + let raw = engine.handle_input(&id, b"x", false).await; + engine.write_user_input(&id, &pty, b"y").await.unwrap(); + // then: delivery to this agent can see both edits, both have landed, + // and other agents are unaffected. + assert!(matches!(raw, pu_core::protocol::Response::Ok), "{raw:?}"); + assert_eq!(count(&id), (2, 0)); + assert_eq!(count("another-agent"), (0, 0)); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn given_concurrent_claims_and_snapshot_should_pair_screen_with_matching_geometry() { let (engine, id, _tmp) = super::Engine::quiet_screen_session().await; diff --git a/crates/pu-engine/src/engine/spawn.rs b/crates/pu-engine/src/engine/spawn.rs index 0a9745dc..88a799b8 100644 --- a/crates/pu-engine/src/engine/spawn.rs +++ b/crates/pu-engine/src/engine/spawn.rs @@ -606,10 +606,18 @@ impl Engine { }; } Err(e) => { + let outcome = match e { + crate::delivery::DeliveryError::Unconfirmed => "was not confirmed", + crate::delivery::DeliveryError::Unobserved + | crate::delivery::DeliveryError::Interfered => { + "may not have been delivered" + } + _ => "was not delivered", + }; return Response::Error { code: "PROMPT_DELIVERY_FAILED".into(), message: format!( - "agent {agent_id} was spawned but its prompt was not delivered: {e}" + "agent {agent_id} was spawned but its prompt {outcome}: {e}" ), }; } diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 3d65dbdc..1ed7174a 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -134,7 +134,7 @@ async fn run_attachment( }; match parse_stream_request(&line) { Some(Request::Input { data, .. }) => { - engine.write_to_pty(&pty, &data).await.ok(); + engine.write_user_input(agent_id, &pty, &data).await.ok(); } Some(Request::Resize { cols, rows, .. }) => { engine.attachment_resize(agent_id, attachment, cols, rows, false).await; diff --git a/crates/pu-engine/tests/delivery.rs b/crates/pu-engine/tests/delivery.rs index 1f1e0174..0960d8b9 100644 --- a/crates/pu-engine/tests/delivery.rs +++ b/crates/pu-engine/tests/delivery.rs @@ -3,7 +3,7 @@ use std::time::Duration; -use pu_engine::delivery::{DeliveryOptions, deliver_prompt}; +use pu_engine::delivery::{DeliveryOptions, OtherInput, deliver_prompt, deliver_prompt_watching}; use pu_engine::pty_manager::{AgentHandle, NativePtyHost, SpawnConfig}; const LONG_PROMPT: &str = "Run: pagespace pages read abc123 and follow it exactly. Then report back with a summary of every file you touched."; @@ -12,17 +12,20 @@ struct Fake { host: NativePtyHost, handle: AgentHandle, log: std::path::PathBuf, + box_log: std::path::PathBuf, _tmp: tempfile::TempDir, } async fn spawn_fake(env: &[(&str, &str)]) -> Fake { let tmp = tempfile::TempDir::new().unwrap(); let log = tmp.path().join("submits.jsonl"); + let box_log = tmp.path().join("box.txt"); let mut env: Vec<(String, String)> = env .iter() .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); env.push(("SUBMIT_LOG".into(), log.display().to_string())); + env.push(("BOX_LOG".into(), box_log.display().to_string())); env.push(("PYTHONUNBUFFERED".into(), "1".into())); #[cfg(unix)] let (command, script) = ( @@ -51,6 +54,7 @@ async fn spawn_fake(env: &[(&str, &str)]) -> Fake { host, handle, log, + box_log, _tmp: tmp, } } @@ -76,6 +80,11 @@ impl Fake { .map(|l| serde_json::from_str(l).unwrap()) .collect() } + + /// What the fake's input box holds right now. + fn input_box(&self) -> String { + std::fs::read_to_string(&self.box_log).unwrap_or_default() + } } async fn deliver(f: &Fake, text: &str) -> Result<(), String> { @@ -194,3 +203,181 @@ async fn given_enter_that_never_works_should_fail_without_double_submit() { assert!(r.is_err()); assert!(f.submits().is_empty()); } + +#[tokio::test(flavor = "multi_thread")] +async fn given_keystrokes_that_keep_dropping_should_leave_an_empty_box_and_submit_nothing() { + // given: typing never matches and Ctrl-U does nothing, so every clear + // must backspace over the whole attempt, spaces included. + let f = spawn_fake(&[("DROP_EVERY", "7"), ("IGNORE_CTRL_U", "1")]).await; + // when + let r = deliver(&f, LONG_PROMPT).await; + settle().await; + // then + assert!(r.unwrap_err().contains("never fully appeared")); + assert!(f.submits().is_empty()); + assert_eq!( + f.input_box(), + "", + "a failed delivery must not leave text stacked in the box" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn given_submitted_turn_that_is_not_echoed_should_report_unconfirmed_after_one_submit() { + // given + let f = spawn_fake(&[("NO_ECHO", "1")]).await; + // when + let r = deliver_prompt( + &f.host, + &f.handle.pty(), + &f.handle.output_buffer, + LONG_PROMPT, + &DeliveryOptions { + ready_timeout: Duration::from_secs(10), + submit_retry_after: Duration::from_millis(800), + submit_timeout: Duration::from_secs(2), + ..DeliveryOptions::default() + }, + ) + .await; + settle().await; + // then: the agent got the turn exactly once, and the error says so. + assert!( + matches!(r, Err(pu_engine::delivery::DeliveryError::Unconfirmed)), + "{r:?}" + ); + assert_eq!(f.submits(), vec![LONG_PROMPT.to_string()]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn given_box_unreadable_after_enter_should_report_unobserved_and_not_retry() { + // given: Enter lands mid-redraw and the box never comes back into view, + // so the prompt is still sitting unsubmitted in the agent's input box. + let f = spawn_fake(&[("BLANK_ON_ENTER", "1")]).await; + // when + let r = deliver_prompt( + &f.host, + &f.handle.pty(), + &f.handle.output_buffer, + LONG_PROMPT, + &DeliveryOptions { + ready_timeout: Duration::from_secs(10), + submit_retry_after: Duration::from_millis(800), + submit_timeout: Duration::from_secs(2), + ..DeliveryOptions::default() + }, + ) + .await; + settle().await; + // then: neither reported as delivered nor pressed again blind. + assert!( + matches!(r, Err(pu_engine::delivery::DeliveryError::Unobserved)), + "{r:?}" + ); + assert!(f.submits().is_empty(), "{:?}", f.submits()); + assert_eq!(f.input_box(), LONG_PROMPT); +} + +/// When another writer's input (a person typing, the phone's clear key) +/// reaches the agent relative to a delivery. In every case the fake's +/// `SWALLOW_CLEARS` empties the box after Enter, standing in for its effect. +#[derive(Clone, Copy)] +enum OtherWrite { + /// Started and landed before delivery began. + Before, + /// Started and landed while the prompt sat typed in the box. + During, + /// Started before delivery began and still not returned when it ends: + /// its bytes are in, but the writer is paused before marking it landed. + StillLanding, +} + +/// Delivers like the engine does for a screen-aware agent, with the engine's +/// record of another write placed as `other` says. +async fn deliver_watching( + f: &Fake, + other: OtherWrite, +) -> Result<(), pu_engine::delivery::DeliveryError> { + let other_input = OtherInput::default(); + match other { + OtherWrite::Before => { + other_input.started(); + other_input.landed(); + } + OtherWrite::StillLanding => other_input.started(), + OtherWrite::During => {} + } + let opts = DeliveryOptions { + ready_timeout: Duration::from_secs(10), + submit_timeout: Duration::from_secs(2), + ..DeliveryOptions::default() + }; + let pty = f.handle.pty(); + let delivery = deliver_prompt_watching( + &f.host, + &pty, + &f.handle.output_buffer, + LONG_PROMPT, + &opts, + &other_input, + ); + let editor = async { + if !matches!(other, OtherWrite::During) { + return; + } + let deadline = std::time::Instant::now() + Duration::from_secs(20); + while f.input_box() != LONG_PROMPT && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(10)).await; + } + other_input.started(); + other_input.landed(); + }; + let (r, ()) = tokio::join!(delivery, editor); + r +} + +#[tokio::test(flavor = "multi_thread")] +async fn given_box_emptied_by_other_input_should_report_interfered_not_unconfirmed() { + // given: Enter is swallowed and the box is emptied without a submit, + // while other input reached the agent during delivery. + let f = spawn_fake(&[("SWALLOW_ENTER", "1"), ("SWALLOW_CLEARS", "1")]).await; + // when + let r = deliver_watching(&f, OtherWrite::During).await; + settle().await; + // then: the empty box is not taken as proof the prompt was submitted. + assert!( + matches!(r, Err(pu_engine::delivery::DeliveryError::Interfered)), + "{r:?}" + ); + assert!(f.submits().is_empty(), "{:?}", f.submits()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn given_write_still_landing_when_delivery_starts_should_report_interfered() { + // given: a write began before delivery and its writer has not returned by + // the verdict, so nothing about it changes during delivery. + let f = spawn_fake(&[("SWALLOW_ENTER", "1"), ("SWALLOW_CLEARS", "1")]).await; + // when + let r = deliver_watching(&f, OtherWrite::StillLanding).await; + settle().await; + // then + assert!( + matches!(r, Err(pu_engine::delivery::DeliveryError::Interfered)), + "{r:?}" + ); + assert!(f.submits().is_empty(), "{:?}", f.submits()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn given_box_emptied_with_no_other_input_should_stay_unconfirmed() { + // given: the same screen, and the only other write landed before delivery. + let f = spawn_fake(&[("SWALLOW_ENTER", "1"), ("SWALLOW_CLEARS", "1")]).await; + // when + let r = deliver_watching(&f, OtherWrite::Before).await; + settle().await; + // then: an empty box after Enter alone keeps its "probably submitted" meaning. + assert!( + matches!(r, Err(pu_engine::delivery::DeliveryError::Unconfirmed)), + "{r:?}" + ); +} diff --git a/crates/pu-engine/tests/fixtures/fake_tui.mjs b/crates/pu-engine/tests/fixtures/fake_tui.mjs index fe9f735a..33b01c75 100644 --- a/crates/pu-engine/tests/fixtures/fake_tui.mjs +++ b/crates/pu-engine/tests/fixtures/fake_tui.mjs @@ -7,13 +7,31 @@ // arrives (models a loaded machine); Enter is handled // immediately on arrival, so it can submit a fragment // SWALLOW_ENTER number of leading Enter presses to ignore +// DROP_EVERY drop every Nth printable character (models a TUI that +// loses keystrokes, so typing never matches) +// IGNORE_CTRL_U ignore Ctrl-U, so clearing must fall back to Backspace +// NO_ECHO submit turns without drawing them above the box (models +// an echo the screen check cannot see) +// SWALLOW_CLEARS a swallowed Enter also empties the box without submitting +// (models another writer clearing it, e.g. a phone's Ctrl-U) +// BLANK_ON_ENTER number of leading Enter presses that are ignored and +// leave the screen without an input box (models Enter +// landing mid-redraw, so the box cannot be read) // SUBMIT_LOG file that receives one JSON line per submitted turn -import { appendFileSync } from 'node:fs'; +// BOX_LOG file overwritten with the box contents on every redraw +import { appendFileSync, writeFileSync } from 'node:fs'; const READY_DELAY = Number(process.env.READY_DELAY_MS ?? '0'); const PROCESS_DELAY = Number(process.env.PROCESS_DELAY_MS ?? '0'); let swallow = Number(process.env.SWALLOW_ENTER ?? '0'); +let blank = Number(process.env.BLANK_ON_ENTER ?? '0'); +const swallowClears = process.env.SWALLOW_CLEARS === '1'; +const dropEvery = Number(process.env.DROP_EVERY ?? '0'); +const ignoreCtrlU = process.env.IGNORE_CTRL_U === '1'; +const noEcho = process.env.NO_ECHO === '1'; const logPath = process.env.SUBMIT_LOG; +const boxLog = process.env.BOX_LOG; +let printable = 0; const COLS = 60; const transcript = []; @@ -25,6 +43,7 @@ const emit = (s) => process.stdout.write(s); function draw() { const text = buf.join(''); + if (boxLog) writeFileSync(boxLog, text); const rows = ['\x1b[2J\x1b[H']; for (const t of transcript.slice(-8)) rows.push('\x1b[1m> ' + t + '\x1b[0m\r\n'); rows.push('╭' + '─'.repeat(COLS - 2) + '╮\r\n'); @@ -40,7 +59,7 @@ function draw() { function submit(text) { if (logPath) appendFileSync(logPath, JSON.stringify(text) + '\n'); - transcript.push(text); + if (!noEcho) transcript.push(text); buf.length = 0; draw(); } @@ -54,12 +73,23 @@ process.stdin.on('data', (data) => { if (!ready) return; for (const ch of data) { if (ch === '\r') { + if (blank > 0) { + blank -= 1; + emit('\x1b[2J\x1b[Hredrawing...\r\n'); + continue; + } if (swallow > 0) { swallow -= 1; + if (swallowClears) { + pending.length = 0; + buf.length = 0; + draw(); + } continue; } submit(buf.join('')); } else if (ch === '\x15') { + if (ignoreCtrlU) continue; pending.length = 0; buf.length = 0; draw(); @@ -69,6 +99,8 @@ process.stdin.on('data', (data) => { draw(); } } else if (ch >= ' ') { + printable += 1; + if (dropEvery && printable % dropEvery === 0) continue; if (PROCESS_DELAY) { const last = pending.length ? pending[pending.length - 1][0] : Date.now(); pending.push([Math.max(last, Date.now()) + PROCESS_DELAY, ch]); diff --git a/crates/pu-engine/tests/fixtures/fake_tui.py b/crates/pu-engine/tests/fixtures/fake_tui.py index 532b2237..c7484110 100755 --- a/crates/pu-engine/tests/fixtures/fake_tui.py +++ b/crates/pu-engine/tests/fixtures/fake_tui.py @@ -8,14 +8,32 @@ arrives (models a loaded machine); Enter is handled immediately on arrival, so it can submit a fragment SWALLOW_ENTER number of leading Enter presses to ignore + DROP_EVERY drop every Nth printable character (models a TUI that + loses keystrokes, so typing never matches) + IGNORE_CTRL_U ignore Ctrl-U, so clearing must fall back to Backspace + NO_ECHO submit turns without drawing them above the box (models + an echo the screen check cannot see) + SWALLOW_CLEARS a swallowed Enter also empties the box without submitting + (models another writer clearing it, e.g. a phone's Ctrl-U) + BLANK_ON_ENTER number of leading Enter presses that are ignored and + leave the screen without an input box (models Enter + landing mid-redraw, so the box cannot be read) SUBMIT_LOG file that receives one JSON line per submitted turn + BOX_LOG file overwritten with the box contents on every redraw """ import json, os, select, sys, termios, threading, time, tty READY_DELAY = int(os.environ.get("READY_DELAY_MS", "0")) / 1000 PROCESS_DELAY = int(os.environ.get("PROCESS_DELAY_MS", "0")) / 1000 swallow = int(os.environ.get("SWALLOW_ENTER", "0")) +blank = int(os.environ.get("BLANK_ON_ENTER", "0")) +swallow_clears = os.environ.get("SWALLOW_CLEARS") == "1" +drop_every = int(os.environ.get("DROP_EVERY", "0")) +no_echo = os.environ.get("NO_ECHO") == "1" +ignore_ctrl_u = os.environ.get("IGNORE_CTRL_U") == "1" log_path = os.environ.get("SUBMIT_LOG") +box_log = os.environ.get("BOX_LOG") +printable = 0 COLS = 60 fd = sys.stdin.fileno() @@ -35,6 +53,9 @@ def emit(s): def draw(): text = "".join(buf) + if box_log: + with open(box_log, "w") as f: + f.write(text) rows = ["\x1b[2J\x1b[H"] for t in transcript[-8:]: rows.append("\x1b[1m> " + t + "\x1b[0m\r\n") @@ -51,7 +72,8 @@ def submit(text): if log_path: with open(log_path, "a") as f: f.write(json.dumps(text) + "\n") - transcript.append(text) + if not no_echo: + transcript.append(text) buf.clear() draw() @@ -90,11 +112,21 @@ def applier(): for ch in data.decode("utf-8", "replace"): with lock: if ch == "\r": + if blank > 0: + blank -= 1 + emit("\x1b[2J\x1b[Hredrawing...\r\n") + continue if swallow > 0: swallow -= 1 + if swallow_clears: + pending.clear() + buf.clear() + draw() continue submit("".join(buf)) elif ch == "\x15": + if ignore_ctrl_u: + continue pending.clear() buf.clear() draw() @@ -103,6 +135,9 @@ def applier(): buf.pop() draw() elif ch >= " ": + printable += 1 + if drop_every and printable % drop_every == 0: + continue if PROCESS_DELAY: last = pending[-1][0] if pending else time.time() pending.append((max(last, time.time()) + PROCESS_DELAY, ch)) diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 5140893f..82c18226 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -169,7 +169,7 @@ pu send [text] [--no-enter] [--keys ] [--json] | `--no-enter` | Don't append Enter after text | | `--keys ` | Send control key sequence (e.g., `C-c`, `C-d`) | -For Claude agents, delivery is confirmed against the agent's screen: `pu send` (and the prompt given to `pu spawn`) returns success only once the complete text was submitted as one turn. If the input box never appears, the text does not fully arrive, or it is not submitted, the command fails with a non-zero exit and a `DELIVERY_FAILED` / `PROMPT_DELIVERY_FAILED` error. No follow-up "nudge" (an empty `pu send`) is needed; sending one can submit a duplicate. +For Claude agents, delivery is confirmed against the agent's screen: `pu send` (and the prompt given to `pu spawn`) returns success only once the complete text was submitted as one turn. If the input box never appears, the text does not fully arrive, or it is not submitted, the command fails with a non-zero exit and a `DELIVERY_FAILED` / `PROMPT_DELIVERY_FAILED` error. If Enter cleared the input box but the submitted turn was not seen on screen, `pu send` fails with `DELIVERY_UNCONFIRMED` instead: the prompt was probably submitted, so check the agent before sending it again. If the input box could not be read at all after Enter (the agent was redrawing), or it ended up empty while someone else was typing into the agent, it fails with `DELIVERY_UNKNOWN`: the prompt may have been submitted or may still be in the input box, so check the agent before doing anything else. No follow-up "nudge" (an empty `pu send`) is needed; sending one can submit a duplicate. ## health