From 2a9913e3e0eae97e40d419e883448c127cd2999e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:22:30 +0000 Subject: [PATCH 1/8] Mobile: edit agent input from the phone; stop duplicate prompt resends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone's agent screen had no way to change text already in an agent's input box: no Backspace, and a has_draft agent blocked sending outright. Add a pinned ⌫ key (hold to repeat) and a clear-line key (Ctrl-U). Both go through terminal.raw as literal control characters, so they work with bridges that predate them. Prompts could be sent again and again although they had arrived: - When Enter emptied the input box but the echo check missed the turn, the daemon reported "text was not delivered". The phone showed Failed and left the text ready to resend. The daemon now returns DELIVERY_UNCONFIRMED with an accurate message, and the bridge reports it (and the older daemon message) as sent. - clear_box sized its Backspace fallback from whitespace-squashed text, so retries stacked leftovers under the retyped prompt. It now covers the whole typed text, and a final typing failure also leaves the box empty. - After any failed send, sending the same text again asks for confirmation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ39DBuL2G4WWBmE8gU --- .../PurePoint/AgentControlDomain.swift | 25 +++++- .../PurePoint/AgentControlModel.swift | 4 + .../PurePoint/AgentsView.swift | 81 +++++++++++++++---- .../AgentControlScenarios.swift | 20 +++++ .../PurePointTests/AgentControlTests.swift | 25 ++++++ apps/purepoint-mobile/README.md | 2 +- apps/purepoint-mobile/bridge/daemon.js | 7 +- apps/purepoint-mobile/bridge/terminals.js | 44 +++++++--- .../purepoint-mobile/bridge/terminals.test.js | 42 +++++++++- apps/purepoint-mobile/docs/contract.md | 4 +- .../verification/AgentControlChecks.swift | 6 ++ .../ui/src/protocol/generated/Request.ts | 6 +- crates/pu-core/src/protocol/mod.rs | 6 +- crates/pu-engine/src/delivery.rs | 25 ++++-- crates/pu-engine/src/engine/pty_operations.rs | 6 ++ crates/pu-engine/src/engine/spawn.rs | 7 +- crates/pu-engine/tests/delivery.rs | 54 +++++++++++++ crates/pu-engine/tests/fixtures/fake_tui.mjs | 19 ++++- crates/pu-engine/tests/fixtures/fake_tui.py | 22 ++++- docs/guide/cli-reference.md | 2 +- 20 files changed, 357 insertions(+), 50 deletions(-) diff --git a/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift b/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift index 247f8ebd..ca08df39 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." } @@ -130,17 +130,24 @@ struct AgentComposer: Sendable { private(set) var outcome: AgentPromptOutcome? private(set) var reason: String? private(set) var deliveryUncertain = false + /// Text from a failed send. A failure can still have reached the agent + /// (a lost receipt, an unseen echo), so resending it needs a deliberate choice. + private(set) var failedText: String? + /// Sending this draft again could submit the same turn twice. + var resendNeedsConfirmation: Bool { failedText != nil && failedText == text } mutating func begin() -> AgentSubmission? { guard pending == nil, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, text.utf8.count <= 65536 else { return nil } let submission = AgentSubmission(id: UUID(), text: text) - pending = submission; outcome = nil; reason = nil; deliveryUncertain = false + pending = submission; outcome = nil; reason = nil; deliveryUncertain = false; failedText = nil return submission } 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. + failedText = outcome == .failed ? submission.text : nil if (outcome == .confirmed || outcome == .sent) && text == submission.text { text = "" } } } @@ -175,6 +182,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 diff --git a/apps/purepoint-mobile/PurePoint/AgentControlModel.swift b/apps/purepoint-mobile/PurePoint/AgentControlModel.swift index 33a4d190..a546a2f0 100644 --- a/apps/purepoint-mobile/PurePoint/AgentControlModel.swift +++ b/apps/purepoint-mobile/PurePoint/AgentControlModel.swift @@ -554,6 +554,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 e2fbc030..88a97267 100644 --- a/apps/purepoint-mobile/PurePoint/AgentsView.swift +++ b/apps/purepoint-mobile/PurePoint/AgentsView.swift @@ -952,6 +952,7 @@ struct AgentControlView: View { private struct AgentControlBar: View { @ObservedObject var model: AgentControlModel @State private var showRecoveries = false + @State private var confirmResend = false private enum Field: Hashable { case prompt, raw } @FocusState private var field: Field? private var focused: Bool { field != nil } @@ -1011,7 +1012,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.composer.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) @@ -1019,6 +1023,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) { @@ -1044,23 +1054,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 "⏎" @@ -1072,6 +1096,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 42b849dc..24635226 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift @@ -268,6 +268,26 @@ 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 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 fc092b1a..380b8cc0 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift @@ -55,6 +55,31 @@ 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) + } + + @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 183f25d8..8ae82f02 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 1a15982a..7f38af7f 100644 --- a/apps/purepoint-mobile/bridge/terminals.js +++ b/apps/purepoint-mobile/bridge/terminals.js @@ -32,6 +32,13 @@ const ops = new Set([ "agent.prompt", ]); export const terminalOperation = (op) => ops.has(op); +// Older daemons report the same case as DELIVERY_FAILED with this message. +const submittedUnconfirmed = (error) => + error?.daemonCode === "DELIVERY_UNCONFIRMED" || + (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({ @@ -375,17 +382,32 @@ 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.", + }; + 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 02b4d306..9179a416 100644 --- a/apps/purepoint-mobile/bridge/terminals.test.js +++ b/apps/purepoint-mobile/bridge/terminals.test.js @@ -74,9 +74,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" }, ); } } @@ -232,6 +232,44 @@ 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. + for (const frame of [ + { + type: "error", + code: "DELIVERY_UNCONFIRMED", + message: "ag-one: Enter cleared the input box", + }, + { + 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 prompt(); + assert.equal(result.outcome, "sent", frame.code); + 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("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 2416b7e7..9a6b719b 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` (or an older daemon's equivalent "input box cleared but the submitted turn was not echoed" failure), 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. A failed outcome keeps the draft, and sending that exact text again requires an explicit confirmation on the phone. Permission denial remains an error receipt. 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 8fa4d70d..a35040f4 100644 --- a/apps/purepoint-mobile/verification/AgentControlChecks.swift +++ b/apps/purepoint-mobile/verification/AgentControlChecks.swift @@ -12,6 +12,12 @@ 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() 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..07a116e4 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts @@ -114,8 +114,10 @@ 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 - * agents get chunked typing plus a delayed Enter. + * against the screen and failure returns `DELIVERY_FAILED`, or + * `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was + * seen (probably delivered; do not resend); other agents get chunked + * typing plus a delayed Enter. */ submit?: boolean; cancel_on_disconnect?: boolean; diff --git a/crates/pu-core/src/protocol/mod.rs b/crates/pu-core/src/protocol/mod.rs index e0f1b0d4..603bb284 100644 --- a/crates/pu-core/src/protocol/mod.rs +++ b/crates/pu-core/src/protocol/mod.rs @@ -200,8 +200,10 @@ 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 - /// agents get chunked typing plus a delayed Enter. + /// against the screen and failure returns `DELIVERY_FAILED`, or + /// `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was + /// seen (probably delivered; do not resend); other agents get chunked + /// typing plus a delayed Enter. #[serde(default)] #[cfg_attr(feature = "ts", ts(optional = nullable))] submit: bool, diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index f9118758..314fe080 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -60,7 +60,11 @@ 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, #[error("pty write failed: {0}")] Io(#[from] std::io::Error), @@ -125,12 +129,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 +147,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 +172,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 +195,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, diff --git a/crates/pu-engine/src/engine/pty_operations.rs b/crates/pu-engine/src/engine/pty_operations.rs index 8c4aa648..36d9297d 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -275,6 +275,12 @@ 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}"), + }, Err(e) => Response::Error { code: "DELIVERY_FAILED".into(), message: format!("text was not delivered to {agent_id}: {e}"), diff --git a/crates/pu-engine/src/engine/spawn.rs b/crates/pu-engine/src/engine/spawn.rs index 0a9745dc..407bc687 100644 --- a/crates/pu-engine/src/engine/spawn.rs +++ b/crates/pu-engine/src/engine/spawn.rs @@ -606,10 +606,15 @@ impl Engine { }; } Err(e) => { + let outcome = if matches!(e, crate::delivery::DeliveryError::Unconfirmed) { + "was not confirmed" + } else { + "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/tests/delivery.rs b/crates/pu-engine/tests/delivery.rs index 1f1e0174..2213f6c3 100644 --- a/crates/pu-engine/tests/delivery.rs +++ b/crates/pu-engine/tests/delivery.rs @@ -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,48 @@ 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()]); +} diff --git a/crates/pu-engine/tests/fixtures/fake_tui.mjs b/crates/pu-engine/tests/fixtures/fake_tui.mjs index fe9f735a..e7d8ab6a 100644 --- a/crates/pu-engine/tests/fixtures/fake_tui.mjs +++ b/crates/pu-engine/tests/fixtures/fake_tui.mjs @@ -7,13 +7,24 @@ // 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) // 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'); +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 +36,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 +52,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(); } @@ -60,6 +72,7 @@ process.stdin.on('data', (data) => { } submit(buf.join('')); } else if (ch === '\x15') { + if (ignoreCtrlU) continue; pending.length = 0; buf.length = 0; draw(); @@ -69,6 +82,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..8f3443f5 100755 --- a/crates/pu-engine/tests/fixtures/fake_tui.py +++ b/crates/pu-engine/tests/fixtures/fake_tui.py @@ -8,14 +8,25 @@ 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) 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")) +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 +46,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 +65,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() @@ -95,6 +110,8 @@ def applier(): continue submit("".join(buf)) elif ch == "\x15": + if ignore_ctrl_u: + continue pending.clear() buf.clear() draw() @@ -103,6 +120,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..61c9fde2 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. No follow-up "nudge" (an empty `pu send`) is needed; sending one can submit a duplicate. ## health From 4c8792c1a33d1c5ffe82f977bf31772a19b409fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:29:29 +0000 Subject: [PATCH 2/8] Changelog: phone input editing and duplicate prompt fix Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ39DBuL2G4WWBmE8gU --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 572e4f75..7753c7c4 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. ### Changed @@ -40,6 +41,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. - `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. From d621729000c29fb43e00559ac93652ac1398b4f2 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 10:09:32 -0600 Subject: [PATCH 3/8] fix(mobile): keep resend confirmation across relaunch and later sends The failed-send marker lived only in the in-memory composer, so a relaunch (which rebuilds the composer from the saved draft) or a later blocked or successful send of other text dropped it, and the failed text could then be resent with one tap. - AgentComposer.failedText is now replaced only by a later failure; begin() and non-failed finishes leave it alone. - The send button also consults the saved prompt recovery records, which survive relaunch: a draft matching an unsettled, non-blocked record (failed, uncertain, or cut off mid-send) asks before sending. Fresh drafts and blocked records stay unmarked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- .../PurePoint/AgentControlDomain.swift | 17 ++++++-- .../PurePoint/AgentControlModel.swift | 3 ++ .../PurePoint/AgentsView.swift | 2 +- .../AgentControlScenarios.swift | 39 ++++++++++++++++++ .../PurePointTests/AgentControlTests.swift | 41 +++++++++++++++++++ .../verification/AgentControlChecks.swift | 4 ++ 6 files changed, 102 insertions(+), 4 deletions(-) diff --git a/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift b/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift index ca08df39..e7a8d306 100644 --- a/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift +++ b/apps/purepoint-mobile/PurePoint/AgentControlDomain.swift @@ -130,24 +130,31 @@ struct AgentComposer: Sendable { private(set) var outcome: AgentPromptOutcome? private(set) var reason: String? private(set) var deliveryUncertain = false - /// Text from a failed send. A failure can still have reached the agent + /// 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 else { return nil } let submission = AgentSubmission(id: UUID(), text: text) - pending = submission; outcome = nil; reason = nil; deliveryUncertain = false; failedText = nil + pending = submission; outcome = nil; reason = nil; deliveryUncertain = false return submission } 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. - failedText = outcome == .failed ? submission.text : nil + if outcome == .failed { failedText = submission.text } if (outcome == .confirmed || outcome == .sent) && text == submission.text { text = "" } } } @@ -244,6 +251,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 a546a2f0..d190028d 100644 --- a/apps/purepoint-mobile/PurePoint/AgentControlModel.swift +++ b/apps/purepoint-mobile/PurePoint/AgentControlModel.swift @@ -178,6 +178,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() } diff --git a/apps/purepoint-mobile/PurePoint/AgentsView.swift b/apps/purepoint-mobile/PurePoint/AgentsView.swift index 88a97267..20dd9451 100644 --- a/apps/purepoint-mobile/PurePoint/AgentsView.swift +++ b/apps/purepoint-mobile/PurePoint/AgentsView.swift @@ -1014,7 +1014,7 @@ private struct AgentControlBar: View { .accessibilityLabel("Agent prompt. Return inserts a new line.") Button { // A failed send may still have reached the agent; never repeat it on one tap. - if model.composer.resendNeedsConfirmation { confirmResend = true } else { model.sendPrompt(screen: token) } + 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)) diff --git a/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift b/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift index 24635226..012cb234 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlScenarios.swift @@ -288,6 +288,45 @@ import Foundation 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 380b8cc0..88e58e1b 100644 --- a/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift +++ b/apps/purepoint-mobile/PurePointTests/AgentControlTests.swift @@ -76,6 +76,47 @@ final class AgentControlTests: XCTestCase { 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() } diff --git a/apps/purepoint-mobile/verification/AgentControlChecks.swift b/apps/purepoint-mobile/verification/AgentControlChecks.swift index a35040f4..5e67f22f 100644 --- a/apps/purepoint-mobile/verification/AgentControlChecks.swift +++ b/apps/purepoint-mobile/verification/AgentControlChecks.swift @@ -18,6 +18,10 @@ import Foundation 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() From 8cd9caec13e51627462e7cc8eaa07392978561d4 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 10:09:32 -0600 Subject: [PATCH 4/8] fix(engine): report an unreadable input box after Enter as DELIVERY_UNKNOWN deliver_prompt returned Unconfirmed whenever the final screen check found an empty box or no box at all. With no box (mid-redraw) the prompt can still be sitting unsubmitted, yet DELIVERY_UNCONFIRMED is shown on the phone as sent. - New DeliveryError::Unobserved, mapped to DELIVERY_UNKNOWN, for a box that cannot be found after a 1s redraw grace; Unconfirmed now means an observed empty box only. - The bridge returns failed with a "Delivery unknown" reason for it: never claimed as delivered, never resent, and the phone asks before a resend. - Fake TUI gains BLANK_ON_ENTER; delivery and bridge tests cover the case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- CHANGELOG.md | 2 +- apps/purepoint-mobile/bridge/terminals.js | 9 ++++++ .../purepoint-mobile/bridge/terminals.test.js | 22 ++++++++++++++ apps/purepoint-mobile/docs/contract.md | 2 +- .../ui/src/protocol/generated/Request.ts | 6 ++-- crates/pu-core/src/protocol/mod.rs | 6 ++-- crates/pu-engine/src/delivery.rs | 21 +++++++++++--- crates/pu-engine/src/engine/pty_operations.rs | 6 ++++ crates/pu-engine/src/engine/spawn.rs | 8 ++--- crates/pu-engine/tests/delivery.rs | 29 +++++++++++++++++++ crates/pu-engine/tests/fixtures/fake_tui.mjs | 9 ++++++ crates/pu-engine/tests/fixtures/fake_tui.py | 8 +++++ docs/guide/cli-reference.md | 2 +- 13 files changed, 115 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7753c7c4..b3a872a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,7 +41,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. +- 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, the daemon returns `DELIVERY_UNKNOWN` and the phone shows the send as failed with delivery unknown, never as sent. - `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/bridge/terminals.js b/apps/purepoint-mobile/bridge/terminals.js index 7f38af7f..ce66505d 100644 --- a/apps/purepoint-mobile/bridge/terminals.js +++ b/apps/purepoint-mobile/bridge/terminals.js @@ -406,6 +406,15 @@ export function terminalConnection({ reason: "Submitted, but the agent's screen did not echo it. Check the terminal before sending again.", }; + // The input box was unreadable after Enter, so 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 (error?.daemonCode === "DELIVERY_UNKNOWN") + return { + outcome: "failed", + reason: + "Delivery unknown: the agent's screen was redrawing after Enter. Check the terminal: the prompt may have been submitted or may still be in its input box.", + }; throw error; } check(); diff --git a/apps/purepoint-mobile/bridge/terminals.test.js b/apps/purepoint-mobile/bridge/terminals.test.js index 9179a416..5841ccfa 100644 --- a/apps/purepoint-mobile/bridge/terminals.test.js +++ b/apps/purepoint-mobile/bridge/terminals.test.js @@ -270,6 +270,28 @@ test("a prompt Enter submitted but the screen never echoed is sent, never failed 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); + f.fail({ + 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", + }); + const result = await c.request({ + op: "agent.prompt", + machine: "local", + agentId: "ag-one", + text: "Hello", + }); + assert.equal(result.outcome, "failed"); + assert.match(result.reason, /^Delivery unknown/); + assert.match(result.reason, /may still be in its input box/); + assert.equal(f.inputs.length, 1, "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 9a6b719b..65ccd9ec 100644 --- a/apps/purepoint-mobile/docs/contract.md +++ b/apps/purepoint-mobile/docs/contract.md @@ -186,7 +186,7 @@ Fixed request operations (in the existing `{version:1,id,clientId,op,...}` envel - `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, except `DELIVERY_UNCONFIRMED` (or an older daemon's equivalent "input box cleared but the submitted turn was not echoed" failure), 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. A failed outcome keeps the draft, and sending that exact text again requires an explicit confirmation on the phone. 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` (or an older daemon's equivalent "input box cleared but the submitted turn was not echoed" failure), 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) returns 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. 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-windows/ui/src/protocol/generated/Request.ts b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts index 07a116e4..9ce9a341 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts @@ -116,8 +116,10 @@ export type Request = * For agents with a readable input box (Claude) delivery is confirmed * against the screen and failure returns `DELIVERY_FAILED`, or * `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was - * seen (probably delivered; do not resend); other agents get chunked - * typing plus a delayed Enter. + * seen (probably delivered; do not resend), or `DELIVERY_UNKNOWN` + * when the box could not be read after Enter (outcome unknown; check + * the agent before resending); other agents get chunked typing plus + * a delayed Enter. */ submit?: boolean; cancel_on_disconnect?: boolean; diff --git a/crates/pu-core/src/protocol/mod.rs b/crates/pu-core/src/protocol/mod.rs index 603bb284..f0cb6b95 100644 --- a/crates/pu-core/src/protocol/mod.rs +++ b/crates/pu-core/src/protocol/mod.rs @@ -202,8 +202,10 @@ pub enum Request { /// For agents with a readable input box (Claude) delivery is confirmed /// against the screen and failure returns `DELIVERY_FAILED`, or /// `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was - /// seen (probably delivered; do not resend); other agents get chunked - /// typing plus a delayed Enter. + /// seen (probably delivered; do not resend), or `DELIVERY_UNKNOWN` + /// when the box could not be read after Enter (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))] submit: bool, diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index 314fe080..bd6fe007 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -66,6 +66,13 @@ pub enum DeliveryError { "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, #[error("pty write failed: {0}")] Io(#[from] std::io::Error), } @@ -73,6 +80,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. @@ -242,9 +251,13 @@ 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), + Some(_) => Err(DeliveryError::Unconfirmed), + None => Err(DeliveryError::Unobserved), } } diff --git a/crates/pu-engine/src/engine/pty_operations.rs b/crates/pu-engine/src/engine/pty_operations.rs index 36d9297d..9c0ee206 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -281,6 +281,12 @@ impl Engine { code: "DELIVERY_UNCONFIRMED".into(), message: format!("{agent_id}: {e}"), }, + // Neither delivered nor safely undelivered: the box was not seen + // after Enter, so the text may still be waiting in it. + Err(e @ DeliveryError::Unobserved) => 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}"), diff --git a/crates/pu-engine/src/engine/spawn.rs b/crates/pu-engine/src/engine/spawn.rs index 407bc687..b2e8776f 100644 --- a/crates/pu-engine/src/engine/spawn.rs +++ b/crates/pu-engine/src/engine/spawn.rs @@ -606,10 +606,10 @@ impl Engine { }; } Err(e) => { - let outcome = if matches!(e, crate::delivery::DeliveryError::Unconfirmed) { - "was not confirmed" - } else { - "was not delivered" + let outcome = match e { + crate::delivery::DeliveryError::Unconfirmed => "was not confirmed", + crate::delivery::DeliveryError::Unobserved => "may not have been delivered", + _ => "was not delivered", }; return Response::Error { code: "PROMPT_DELIVERY_FAILED".into(), diff --git a/crates/pu-engine/tests/delivery.rs b/crates/pu-engine/tests/delivery.rs index 2213f6c3..41400ef5 100644 --- a/crates/pu-engine/tests/delivery.rs +++ b/crates/pu-engine/tests/delivery.rs @@ -248,3 +248,32 @@ async fn given_submitted_turn_that_is_not_echoed_should_report_unconfirmed_after ); 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); +} diff --git a/crates/pu-engine/tests/fixtures/fake_tui.mjs b/crates/pu-engine/tests/fixtures/fake_tui.mjs index e7d8ab6a..ff865487 100644 --- a/crates/pu-engine/tests/fixtures/fake_tui.mjs +++ b/crates/pu-engine/tests/fixtures/fake_tui.mjs @@ -12,6 +12,9 @@ // 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) +// 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 { appendFileSync, writeFileSync } from 'node:fs'; @@ -19,6 +22,7 @@ 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 dropEvery = Number(process.env.DROP_EVERY ?? '0'); const ignoreCtrlU = process.env.IGNORE_CTRL_U === '1'; const noEcho = process.env.NO_ECHO === '1'; @@ -66,6 +70,11 @@ 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; continue; diff --git a/crates/pu-engine/tests/fixtures/fake_tui.py b/crates/pu-engine/tests/fixtures/fake_tui.py index 8f3443f5..4232b6d0 100755 --- a/crates/pu-engine/tests/fixtures/fake_tui.py +++ b/crates/pu-engine/tests/fixtures/fake_tui.py @@ -13,6 +13,9 @@ 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) + 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 """ @@ -21,6 +24,7 @@ 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")) 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" @@ -105,6 +109,10 @@ 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 continue diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 61c9fde2..ebcc5d9e 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. 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. 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), 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 From 842b9250c3a89c0c31f8cd8a8d586da010f4a922 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 10:15:06 -0600 Subject: [PATCH 5/8] fix(bridge): treat an older daemon's unechoed-submit error as delivery unknown Older daemons returned "input box cleared but the submitted turn was not echoed" both for an observed empty box and for a box they could not read, so it cannot prove the turn was taken. Reporting it as sent cleared the phone draft even when the prompt was still sitting in the box. It now gets the same failed "Delivery unknown" outcome as DELIVERY_UNKNOWN: delivery is never claimed, the draft is kept, and the phone asks before resending. Only DELIVERY_UNCONFIRMED (an observed empty box) still maps to sent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- CHANGELOG.md | 2 +- apps/purepoint-mobile/bridge/terminals.js | 19 ++++-- .../purepoint-mobile/bridge/terminals.test.js | 68 ++++++++++--------- apps/purepoint-mobile/docs/contract.md | 2 +- 4 files changed, 49 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3a872a7..446836f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,7 +41,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, the daemon returns `DELIVERY_UNKNOWN` and the phone shows the send as failed with delivery unknown, never as sent. +- 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, 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/bridge/terminals.js b/apps/purepoint-mobile/bridge/terminals.js index ce66505d..dfc31816 100644 --- a/apps/purepoint-mobile/bridge/terminals.js +++ b/apps/purepoint-mobile/bridge/terminals.js @@ -32,9 +32,14 @@ const ops = new Set([ "agent.prompt", ]); export const terminalOperation = (op) => ops.has(op); -// Older daemons report the same case as DELIVERY_FAILED with this message. +// Enter emptied an input box the daemon actually saw: the turn was taken. const submittedUnconfirmed = (error) => - error?.daemonCode === "DELIVERY_UNCONFIRMED" || + 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, @@ -406,14 +411,14 @@ export function terminalConnection({ reason: "Submitted, but the agent's screen did not echo it. Check the terminal before sending again.", }; - // The input box was unreadable after Enter, so 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 (error?.daemonCode === "DELIVERY_UNKNOWN") + // 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 screen was redrawing after Enter. Check the terminal: the prompt may have been submitted or may still be in its input box.", + "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; } diff --git a/apps/purepoint-mobile/bridge/terminals.test.js b/apps/purepoint-mobile/bridge/terminals.test.js index 5841ccfa..c6924f8b 100644 --- a/apps/purepoint-mobile/bridge/terminals.test.js +++ b/apps/purepoint-mobile/bridge/terminals.test.js @@ -244,11 +244,34 @@ test("a prompt Enter submitted but the screen never echoed is sent, never failed 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_UNCONFIRMED", - message: "ag-one: Enter cleared the input box", + 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", @@ -258,38 +281,17 @@ test("a prompt Enter submitted but the screen never echoed is sent, never failed }, ]) { f.fail(frame); - const result = await prompt(); - assert.equal(result.outcome, "sent", frame.code); - assert.match(result.reason, /Check the terminal before sending again/); + 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/); } - 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); - f.fail({ - 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", - }); - const result = await c.request({ - op: "agent.prompt", - machine: "local", - agentId: "ag-one", - text: "Hello", - }); - assert.equal(result.outcome, "failed"); - assert.match(result.reason, /^Delivery unknown/); - assert.match(result.reason, /may still be in its input box/); - assert.equal(f.inputs.length, 1, "the bridge never resends on its own"); + 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) => { diff --git a/apps/purepoint-mobile/docs/contract.md b/apps/purepoint-mobile/docs/contract.md index 65ccd9ec..0f4d5413 100644 --- a/apps/purepoint-mobile/docs/contract.md +++ b/apps/purepoint-mobile/docs/contract.md @@ -186,7 +186,7 @@ Fixed request operations (in the existing `{version:1,id,clientId,op,...}` envel - `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, except `DELIVERY_UNCONFIRMED` (or an older daemon's equivalent "input box cleared but the submitted turn was not echoed" failure), 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) returns 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.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), 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. 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. From e9c949c3e8fdeadb5777cb727fbc31bdce765732 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 13:54:33 -0600 Subject: [PATCH 6/8] fix(engine): don't call an empty box "unconfirmed" when other input touched it DELIVERY_UNCONFIRMED (shown as sent on the phone) assumes Enter emptied the input box. Attach-stream input (the phone's keys and clear, a person typing) and raw `input` writes don't take the delivery lock, so a Ctrl-U after a swallowed Enter could empty the box and the unsubmitted prompt was reported as sent, then cleared from the phone. These writes now go through Engine::write_user_input, which bumps a per-agent counter first. Delivery records the counter at the start, and an empty, unechoed box after other input is DeliveryError::Interfered, reported as DELIVERY_UNKNOWN (failed, delivery unknown on the phone). User input is still never blocked behind a delivery, so Esc and Ctrl-C always get through. An empty box after Enter alone keeps DELIVERY_UNCONFIRMED. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- CHANGELOG.md | 2 +- apps/purepoint-mobile/docs/contract.md | 2 +- .../ui/src/protocol/generated/Request.ts | 9 +-- crates/pu-core/src/protocol/mod.rs | 9 +-- crates/pu-engine/src/delivery.rs | 27 ++++++++ crates/pu-engine/src/engine/mod.rs | 3 + crates/pu-engine/src/engine/pty_operations.rs | 63 +++++++++++++++--- crates/pu-engine/src/engine/spawn.rs | 5 +- crates/pu-engine/src/ipc_server/streams.rs | 2 +- crates/pu-engine/tests/delivery.rs | 65 ++++++++++++++++++- crates/pu-engine/tests/fixtures/fake_tui.mjs | 8 +++ crates/pu-engine/tests/fixtures/fake_tui.py | 7 ++ docs/guide/cli-reference.md | 2 +- 13 files changed, 182 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8786521..9630061a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +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, 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. +- 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/docs/contract.md b/apps/purepoint-mobile/docs/contract.md index 2a212bc8..5e5dec94 100644 --- a/apps/purepoint-mobile/docs/contract.md +++ b/apps/purepoint-mobile/docs/contract.md @@ -186,7 +186,7 @@ Fixed request operations (in the existing `{version:1,id,clientId,op,...}` envel - `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, 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), 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.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-windows/ui/src/protocol/generated/Request.ts b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts index 9ce9a341..0fa3e901 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts @@ -116,10 +116,11 @@ export type Request = * For agents with a readable input box (Claude) delivery is confirmed * against the screen and failure returns `DELIVERY_FAILED`, or * `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was - * seen (probably delivered; do not resend), or `DELIVERY_UNKNOWN` - * when the box could not be read after Enter (outcome unknown; check - * the agent before resending); other agents get chunked typing plus - * a delayed Enter. + * 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; cancel_on_disconnect?: boolean; diff --git a/crates/pu-core/src/protocol/mod.rs b/crates/pu-core/src/protocol/mod.rs index f0cb6b95..1d9c4116 100644 --- a/crates/pu-core/src/protocol/mod.rs +++ b/crates/pu-core/src/protocol/mod.rs @@ -202,10 +202,11 @@ pub enum Request { /// For agents with a readable input box (Claude) delivery is confirmed /// against the screen and failure returns `DELIVERY_FAILED`, or /// `DELIVERY_UNCONFIRMED` when Enter cleared the box but no echo was - /// seen (probably delivered; do not resend), or `DELIVERY_UNKNOWN` - /// when the box could not be read after Enter (outcome unknown; check - /// the agent before resending); other agents get chunked typing plus - /// a delayed Enter. + /// 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))] submit: bool, diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index bd6fe007..7ddd9f8e 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -6,6 +6,7 @@ //! cleared and the turn was echoed. Anything else is a loud error. use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use tokio::time::Instant; @@ -73,6 +74,13 @@ pub enum DeliveryError { "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), } @@ -222,10 +230,25 @@ pub async fn deliver_prompt( output: &Arc, text: &str, opts: &DeliveryOptions, +) -> Result<(), DeliveryError> { + deliver_prompt_watching(host, fd, output, text, opts, &AtomicU64::new(0)).await +} + +/// [`deliver_prompt`], where `other_input` counts writes to the same agent +/// that did not come from this delivery. Its writers bump it before writing, +/// so any edit that could have emptied the box is seen here. +pub async fn deliver_prompt_watching( + host: &NativePtyHost, + fd: &Pty, + output: &Arc, + text: &str, + opts: &DeliveryOptions, + other_input: &AtomicU64, ) -> Result<(), DeliveryError> { if text.trim().is_empty() { return Ok(()); } + let inputs_before = other_input.load(Ordering::SeqCst); let (rows, cols) = winsize(fd); let mut tracker = ScreenTracker::new(output, rows, cols); let want = squash(text); @@ -257,6 +280,10 @@ pub async fn deliver_prompt( 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 other_input.load(Ordering::SeqCst) != inputs_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..1919f98f 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 count of 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 9c0ee206..9fdc15d7 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -40,11 +40,12 @@ struct SizeClaim { } use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use pu_core::paths; use pu_core::protocol::Response; -use crate::delivery::{DeliveryError, DeliveryOptions, deliver_prompt}; +use crate::delivery::{DeliveryError, DeliveryOptions, deliver_prompt_watching}; use crate::output_buffer::OutputBuffer; use crate::pty_manager::Pty; @@ -282,11 +283,14 @@ impl Engine { message: format!("{agent_id}: {e}"), }, // Neither delivered nor safely undelivered: the box was not seen - // after Enter, so the text may still be waiting in it. - Err(e @ DeliveryError::Unobserved) => Response::Error { - code: "DELIVERY_UNKNOWN".into(), - message: format!("{agent_id}: {e}"), - }, + // 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}"), @@ -301,7 +305,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(), @@ -336,12 +340,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 { @@ -396,6 +401,29 @@ impl Engine { self.pty_host.write_to_pty(pty, data).await } + /// Counts 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. + pub async fn write_user_input( + &self, + agent_id: &str, + pty: &Pty, + data: &[u8], + ) -> Result<(), std::io::Error> { + self.other_input(agent_id).fetch_add(1, Ordering::SeqCst); + self.pty_host.write_to_pty(pty, data).await + } + /// 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 @@ -514,6 +542,25 @@ 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) + .load(std::sync::atomic::Ordering::SeqCst) + }; + 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; others are unaffected. + assert!(matches!(raw, pu_core::protocol::Response::Ok), "{raw:?}"); + assert_eq!(count(&id), 2); + assert_eq!(count("another-agent"), 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 b2e8776f..88a799b8 100644 --- a/crates/pu-engine/src/engine/spawn.rs +++ b/crates/pu-engine/src/engine/spawn.rs @@ -608,7 +608,10 @@ impl Engine { Err(e) => { let outcome = match e { crate::delivery::DeliveryError::Unconfirmed => "was not confirmed", - crate::delivery::DeliveryError::Unobserved => "may not have been delivered", + crate::delivery::DeliveryError::Unobserved + | crate::delivery::DeliveryError::Interfered => { + "may not have been delivered" + } _ => "was not delivered", }; return Response::Error { 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 41400ef5..f1256b99 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, 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."; @@ -277,3 +277,66 @@ async fn given_box_unreadable_after_enter_should_report_unobserved_and_not_retry assert!(f.submits().is_empty(), "{:?}", f.submits()); assert_eq!(f.input_box(), LONG_PROMPT); } + +/// Delivers like the engine does for a screen-aware agent, with `other_input` +/// bumped once the prompt is fully typed when `edit` is set: that is what the +/// engine records when a person or the phone writes to the agent mid-delivery. +async fn deliver_watching(f: &Fake, edit: bool) -> Result<(), pu_engine::delivery::DeliveryError> { + let other_input = std::sync::atomic::AtomicU64::new(0); + 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 !edit { + 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.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }; + 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, true).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_box_emptied_with_no_other_input_should_stay_unconfirmed() { + // given: the same screen, but nothing else wrote to the agent. + let f = spawn_fake(&[("SWALLOW_ENTER", "1"), ("SWALLOW_CLEARS", "1")]).await; + // when + let r = deliver_watching(&f, false).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 ff865487..33b01c75 100644 --- a/crates/pu-engine/tests/fixtures/fake_tui.mjs +++ b/crates/pu-engine/tests/fixtures/fake_tui.mjs @@ -12,6 +12,8 @@ // 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) @@ -23,6 +25,7 @@ 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'; @@ -77,6 +80,11 @@ process.stdin.on('data', (data) => { } if (swallow > 0) { swallow -= 1; + if (swallowClears) { + pending.length = 0; + buf.length = 0; + draw(); + } continue; } submit(buf.join('')); diff --git a/crates/pu-engine/tests/fixtures/fake_tui.py b/crates/pu-engine/tests/fixtures/fake_tui.py index 4232b6d0..c7484110 100755 --- a/crates/pu-engine/tests/fixtures/fake_tui.py +++ b/crates/pu-engine/tests/fixtures/fake_tui.py @@ -13,6 +13,8 @@ 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) @@ -25,6 +27,7 @@ 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" @@ -115,6 +118,10 @@ def applier(): continue if swallow > 0: swallow -= 1 + if swallow_clears: + pending.clear() + buf.clear() + draw() continue submit("".join(buf)) elif ch == "\x15": diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index ebcc5d9e..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. 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), 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. +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 From 7a52d44cd3d3a290e8a00a849739a357b8cd6709 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 14:02:11 -0600 Subject: [PATCH 7/8] fix(engine): count a user write that is still in flight when delivery starts write_user_input bumped the per-agent counter only before its blocking PTY write. If delivery read its baseline after that bump but before the bytes landed, a Ctrl-U clearing the box after a swallowed Enter left the count unchanged and was reported as DELIVERY_UNCONFIRMED (sent). The counter now moves again once the write lands, inside the blocking task so it happens even if the caller stops waiting. A write in flight at the baseline therefore always moves the count before the verdict. Adds a delivery regression test for that ordering. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- crates/pu-engine/src/delivery.rs | 5 ++- crates/pu-engine/src/engine/pty_operations.rs | 22 +++++++++-- crates/pu-engine/tests/delivery.rs | 38 +++++++++++++++---- 3 files changed, 51 insertions(+), 14 deletions(-) diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index 7ddd9f8e..d5da4564 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -235,8 +235,9 @@ pub async fn deliver_prompt( } /// [`deliver_prompt`], where `other_input` counts writes to the same agent -/// that did not come from this delivery. Its writers bump it before writing, -/// so any edit that could have emptied the box is seen here. +/// that did not come from this delivery. Its writers bump it when a write +/// starts and again when it lands, so any edit that could have emptied the +/// box, including one already in flight when delivery began, moves it. pub async fn deliver_prompt_watching( host: &NativePtyHost, fd: &Pty, diff --git a/crates/pu-engine/src/engine/pty_operations.rs b/crates/pu-engine/src/engine/pty_operations.rs index 9fdc15d7..f8836630 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -414,14 +414,27 @@ impl Engine { /// 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 count moves when the write starts and again once its bytes are in, + /// so a delivery that begins while a write is still in flight sees it land. + /// The second bump runs inside the blocking task, so it happens even if the + /// caller stops waiting. pub async fn write_user_input( &self, agent_id: &str, pty: &Pty, data: &[u8], ) -> Result<(), std::io::Error> { - self.other_input(agent_id).fetch_add(1, Ordering::SeqCst); - self.pty_host.write_to_pty(pty, data).await + let count = self.other_input(agent_id); + count.fetch_add(1, Ordering::SeqCst); + let (pty, data) = (pty.clone(), data.to_vec()); + tokio::task::spawn_blocking(move || { + let written = pty.write(&data); + count.fetch_add(1, Ordering::SeqCst); + written + }) + .await + .map_err(std::io::Error::other)? } /// Resize a PTY via the pty host. @@ -555,9 +568,10 @@ mod tests { // 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; others are unaffected. + // then: delivery to this agent can see both edits, each counted when it + // started and again when it landed; others are unaffected. assert!(matches!(raw, pu_core::protocol::Response::Ok), "{raw:?}"); - assert_eq!(count(&id), 2); + assert_eq!(count(&id), 4); assert_eq!(count("another-agent"), 0); } diff --git a/crates/pu-engine/tests/delivery.rs b/crates/pu-engine/tests/delivery.rs index f1256b99..b78042dc 100644 --- a/crates/pu-engine/tests/delivery.rs +++ b/crates/pu-engine/tests/delivery.rs @@ -278,11 +278,17 @@ async fn given_box_unreadable_after_enter_should_report_unobserved_and_not_retry assert_eq!(f.input_box(), LONG_PROMPT); } -/// Delivers like the engine does for a screen-aware agent, with `other_input` -/// bumped once the prompt is fully typed when `edit` is set: that is what the -/// engine records when a person or the phone writes to the agent mid-delivery. -async fn deliver_watching(f: &Fake, edit: bool) -> Result<(), pu_engine::delivery::DeliveryError> { - let other_input = std::sync::atomic::AtomicU64::new(0); +/// Delivers like the engine does for a screen-aware agent. The engine bumps +/// `other_input` when a person or the phone starts a write to the agent and +/// again once it lands. `start` is the count when delivery begins (odd: a +/// write is still in flight), and `edit` bumps it once the prompt is fully +/// typed, i.e. a write starts or lands mid-delivery. +async fn deliver_watching( + f: &Fake, + start: u64, + edit: bool, +) -> Result<(), pu_engine::delivery::DeliveryError> { + let other_input = std::sync::atomic::AtomicU64::new(start); let opts = DeliveryOptions { ready_timeout: Duration::from_secs(10), submit_timeout: Duration::from_secs(2), @@ -317,7 +323,7 @@ async fn given_box_emptied_by_other_input_should_report_interfered_not_unconfirm // 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, true).await; + let r = deliver_watching(&f, 0, true).await; settle().await; // then: the empty box is not taken as proof the prompt was submitted. assert!( @@ -327,12 +333,28 @@ async fn given_box_emptied_by_other_input_should_report_interfered_not_unconfirm assert!(f.submits().is_empty(), "{:?}", f.submits()); } +#[tokio::test(flavor = "multi_thread")] +async fn given_write_in_flight_when_delivery_starts_should_report_interfered() { + // given: a raw write had started (counted once) before delivery began, + // and only lands (counted again) after the swallowed Enter, clearing the box. + let f = spawn_fake(&[("SWALLOW_ENTER", "1"), ("SWALLOW_CLEARS", "1")]).await; + // when + let r = deliver_watching(&f, 1, true).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, but nothing else wrote to the agent. + // 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, false).await; + let r = deliver_watching(&f, 2, false).await; settle().await; // then: an empty box after Enter alone keeps its "probably submitted" meaning. assert!( From 541bf4f70e075dffad4f2baf68e21aa365a137cc Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 14:08:59 -0600 Subject: [PATCH 8/8] fix(engine): treat a user write still landing at delivery start as interference A counter bumped after the write left a gap: the bytes could land, the agent could clear the box, and the delivery verdict could run before the writer recorded the landing, so the empty box still read as DELIVERY_UNCONFIRMED. Engine::write_user_input now records each write in delivery::OtherInput as (started, still landing) under one lock, marking it started before any byte goes out and landed via a drop guard inside the blocking task. Delivery snapshots that state when it begins. An empty, unechoed box is Interfered (DELIVERY_UNKNOWN) if a write was still landing then or one started since. User input is still never held behind a delivery. Tests cover a write before, during, and still landing across the whole delivery (the paused-writer ordering). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2REppCunF9PidNt3K --- crates/pu-engine/src/delivery.rs | 52 ++++++++++++++---- crates/pu-engine/src/engine/mod.rs | 4 +- crates/pu-engine/src/engine/pty_operations.rs | 48 +++++++++-------- crates/pu-engine/tests/delivery.rs | 53 +++++++++++++------ 4 files changed, 106 insertions(+), 51 deletions(-) diff --git a/crates/pu-engine/src/delivery.rs b/crates/pu-engine/src/delivery.rs index d5da4564..596004e6 100644 --- a/crates/pu-engine/src/delivery.rs +++ b/crates/pu-engine/src/delivery.rs @@ -6,7 +6,6 @@ //! cleared and the turn was echoed. Anything else is a loud error. use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use tokio::time::Instant; @@ -231,25 +230,60 @@ pub async fn deliver_prompt( text: &str, opts: &DeliveryOptions, ) -> Result<(), DeliveryError> { - deliver_prompt_watching(host, fd, output, text, opts, &AtomicU64::new(0)).await + deliver_prompt_watching(host, fd, output, text, opts, &OtherInput::default()).await } -/// [`deliver_prompt`], where `other_input` counts writes to the same agent -/// that did not come from this delivery. Its writers bump it when a write -/// starts and again when it lands, so any edit that could have emptied the -/// box, including one already in flight when delivery began, moves it. +/// 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: &AtomicU64, + other_input: &OtherInput, ) -> Result<(), DeliveryError> { if text.trim().is_empty() { return Ok(()); } - let inputs_before = other_input.load(Ordering::SeqCst); + 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); @@ -282,7 +316,7 @@ pub async fn deliver_prompt_watching( 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 other_input.load(Ordering::SeqCst) != inputs_before => { + Some(_) if landing_before > 0 || other_input.snapshot().0 != started_before => { Err(DeliveryError::Interfered) } Some(_) => Err(DeliveryError::Unconfirmed), diff --git a/crates/pu-engine/src/engine/mod.rs b/crates/pu-engine/src/engine/mod.rs index 1919f98f..33d21ab6 100644 --- a/crates/pu-engine/src/engine/mod.rs +++ b/crates/pu-engine/src/engine/mod.rs @@ -87,8 +87,8 @@ pub struct Engine { pending_initial_inputs: Arc>>>, /// Per-agent locks so concurrent sends/triggers never interleave keystrokes. delivery_locks: Arc>>>>, - /// Per-agent count of input written outside prompt delivery. - other_input: Arc>>>, + /// Per-agent input written outside prompt delivery. + other_input: Arc>>>, login_env: Arc>>, reaped_projects: Arc>>, /// Per-project broadcast channels for grid commands. diff --git a/crates/pu-engine/src/engine/pty_operations.rs b/crates/pu-engine/src/engine/pty_operations.rs index f8836630..a2dec03c 100644 --- a/crates/pu-engine/src/engine/pty_operations.rs +++ b/crates/pu-engine/src/engine/pty_operations.rs @@ -40,12 +40,11 @@ struct SizeClaim { } use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; use pu_core::paths; use pu_core::protocol::Response; -use crate::delivery::{DeliveryError, DeliveryOptions, deliver_prompt_watching}; +use crate::delivery::{DeliveryError, DeliveryOptions, OtherInput, deliver_prompt_watching}; use crate::output_buffer::OutputBuffer; use crate::pty_manager::Pty; @@ -401,9 +400,9 @@ impl Engine { self.pty_host.write_to_pty(pty, data).await } - /// Counts 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 { + /// 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() @@ -415,23 +414,30 @@ impl Engine { /// an agent. Deliberately not serialized with delivery, so keys such as /// Esc or Ctrl-C always get through; delivery notices them instead. /// - /// The count moves when the write starts and again once its bytes are in, - /// so a delivery that begins while a write is still in flight sees it land. - /// The second bump runs inside the blocking task, so it happens even if the - /// caller stops waiting. + /// 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> { - let count = self.other_input(agent_id); - count.fetch_add(1, Ordering::SeqCst); + 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 written = pty.write(&data); - count.fetch_add(1, Ordering::SeqCst); - written + let _landing = landing; + pty.write(&data) }) .await .map_err(std::io::Error::other)? @@ -559,20 +565,16 @@ mod tests { 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) - .load(std::sync::atomic::Ordering::SeqCst) - }; + 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, each counted when it - // started and again when it landed; others are unaffected. + // 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), 4); - assert_eq!(count("another-agent"), 0); + assert_eq!(count(&id), (2, 0)); + assert_eq!(count("another-agent"), (0, 0)); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/pu-engine/tests/delivery.rs b/crates/pu-engine/tests/delivery.rs index b78042dc..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, deliver_prompt_watching}; +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."; @@ -278,17 +278,35 @@ async fn given_box_unreadable_after_enter_should_report_unobserved_and_not_retry assert_eq!(f.input_box(), LONG_PROMPT); } -/// Delivers like the engine does for a screen-aware agent. The engine bumps -/// `other_input` when a person or the phone starts a write to the agent and -/// again once it lands. `start` is the count when delivery begins (odd: a -/// write is still in flight), and `edit` bumps it once the prompt is fully -/// typed, i.e. a write starts or lands mid-delivery. +/// 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, - start: u64, - edit: bool, + other: OtherWrite, ) -> Result<(), pu_engine::delivery::DeliveryError> { - let other_input = std::sync::atomic::AtomicU64::new(start); + 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), @@ -304,14 +322,15 @@ async fn deliver_watching( &other_input, ); let editor = async { - if !edit { + 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.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + other_input.started(); + other_input.landed(); }; let (r, ()) = tokio::join!(delivery, editor); r @@ -323,7 +342,7 @@ async fn given_box_emptied_by_other_input_should_report_interfered_not_unconfirm // 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, 0, true).await; + let r = deliver_watching(&f, OtherWrite::During).await; settle().await; // then: the empty box is not taken as proof the prompt was submitted. assert!( @@ -334,12 +353,12 @@ async fn given_box_emptied_by_other_input_should_report_interfered_not_unconfirm } #[tokio::test(flavor = "multi_thread")] -async fn given_write_in_flight_when_delivery_starts_should_report_interfered() { - // given: a raw write had started (counted once) before delivery began, - // and only lands (counted again) after the swallowed Enter, clearing the box. +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, 1, true).await; + let r = deliver_watching(&f, OtherWrite::StillLanding).await; settle().await; // then assert!( @@ -354,7 +373,7 @@ 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, 2, false).await; + let r = deliver_watching(&f, OtherWrite::Before).await; settle().await; // then: an empty box after Enter alone keeps its "probably submitted" meaning. assert!(