Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 24 additions & 11 deletions App/Sources/Features/RemoteMirror/Push/MirrorPushSender.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ final class MirrorPushSender {
struct PaneDetails: Sendable {
let title: String
let stateChangedAt: String?
/// What the agent asks or replied (`MirrorPushSummary`); the generic text when `nil`.
var summary: String?
}

private let host: MirrorHost
private let enabled: () -> Bool
private let paneStates: () -> [UUID: MirrorPushPlanner.PaneState]
private let paneDetails: (UUID) -> PaneDetails?
private let paneDetails: (UUID, MirrorPushKind) async -> PaneDetails?
private let presence: MacPresenceMonitor
/// `nil` when no push service is configured: the sender then never starts.
private let gateway: any MirrorPushGateway
Expand All @@ -35,7 +37,7 @@ final class MirrorPushSender {
init(
host: MirrorHost, enabled: @escaping () -> Bool,
paneStates: @escaping () -> [UUID: MirrorPushPlanner.PaneState],
paneDetails: @escaping (UUID) -> PaneDetails?,
paneDetails: @escaping (UUID, MirrorPushKind) async -> PaneDetails?,
presence: MacPresenceMonitor, gateway: any MirrorPushGateway, clock: ContinuousClock = ContinuousClock()
) {
self.host = host
Expand Down Expand Up @@ -186,9 +188,12 @@ final class MirrorPushSender {
sends[id] = Task { [weak self] in
defer { self?.sends.removeValue(forKey: id) }
guard let self else { return }
// Read first: a finished turn's reply comes from the transcript. The gates are checked
// after it, so a change while it was read still stops the push.
let details = await self.paneDetails(push.paneID, push.kind)
guard self.mayStillSend(push), let hostID = self.host.hostIdentityID,
let device = self.host.devices.first(where: { $0.id == push.deviceID }), let token = device.push?.token,
let request = Self.request(for: push, device: device, hostID: hostID, details: self.paneDetails(push.paneID))
let request = Self.request(for: push, device: device, hostID: hostID, details: details)
else {
// Nothing was sent: hold the prompt again for the next valid catch-up.
self.planner.skipped(push)
Expand Down Expand Up @@ -223,14 +228,22 @@ final class MirrorPushSender {
for push: MirrorPushPlanner.Push, device: MirrorPairedDevice, hostID: UUID, details: PaneDetails?
) -> Request? {
let key = MirrorPushCrypto.key(deviceSecret: device.key, hostID: hostID)
let content = MirrorPushContent(
kind: push.kind, paneID: push.paneID, title: details?.title ?? String(localized: "Prowl"),
body: push.kind == .blocked
? String(localized: "An agent needs your attention")
: String(localized: "An agent finished"),
stateChangedAt: details?.stateChangedAt)
guard let plaintext = try? JSONEncoder().encode(content),
let sealed = try? MirrorPushCrypto.seal(plaintext, key: key, hostID: hostID)
let generic =
push.kind == .blocked
? String(localized: "An agent needs your attention")
: String(localized: "An agent finished")
func sealed(body: String) -> String? {
let content = MirrorPushContent(
kind: push.kind, paneID: push.paneID, title: details?.title ?? String(localized: "Prowl"), body: body,
stateChangedAt: details?.stateChangedAt)
guard let plaintext = try? JSONEncoder().encode(content) else { return nil }
return try? MirrorPushCrypto.seal(plaintext, key: key, hostID: hostID)
}
// A summary that would make the push too large for the gateway gives way to the generic text.
guard
let sealed = details?.summary.flatMap(sealed(body:)).flatMap({
$0.count <= MirrorPushContract.maximumSealedLength ? $0 : nil
}) ?? sealed(body: generic)
else { return nil }
return Request(collapseID: MirrorPushCrypto.collapseID(paneID: push.paneID, key: key), sealed: sealed)
}
Expand Down
55 changes: 55 additions & 0 deletions App/Sources/Features/RemoteMirror/Push/MirrorPushSummary.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import Foundation

/// The line a push shows under the tab name when the phone has **Show Details** on (docs-ai
/// 095): what a blocked agent asks, or the start of a finished agent's last reply. It is
/// encrypted end to end like the rest of the content; without Show Details the phone shows
/// only the generic text.
nonisolated enum MirrorPushSummary {
/// About two lines on a lock screen.
static let maximumCharacters = 180
/// Enough for the last turn of a long transcript; read only when a turn finishes.
static let transcriptTailBytes = 256 * 1024

/// The question on the agent's screen, with the first line of its detail, such as the
/// command a permission asks about.
static func question(onScreen text: String) -> String? {
guard let prompt = MirrorScreenPrompt.parse(text) else { return nil }
let detail = prompt.detail?.split(whereSeparator: \.isNewline).first.map(String.init)
return oneLine([prompt.title, detail].compactMap { $0 }.joined(separator: " · "))
}

/// The start of the agent's last reply near the end of its transcript, or `nil`.
static func lastReply(transcript url: URL, agent: DetectedAgent) -> String? {
guard let pipeline = MirrorTranscriptPipeline(agent: agent),
let handle = try? FileHandle(forReadingFrom: url)
else { return nil }
defer { try? handle.close() }
guard let size = try? handle.seekToEnd() else { return nil }
let start = size > UInt64(transcriptTailBytes) ? size - UInt64(transcriptTailBytes) : 0
guard (try? handle.seek(toOffset: start)) != nil, let data = try? handle.readToEnd() else { return nil }
let events = pipeline.ingest(.replay(data, head: nil, startsMidRecord: start > 0)).events
for event in events.reversed() {
switch (event.kind, event.payload) {
case (.turnCompleted, .turn(let turn)):
if let reply = turn.lastMessage.flatMap({ oneLine($0.text) }) { return reply }
case (.assistantMessage, .message(let message)):
if let reply = oneLine(message.text.text) { return reply }
default:
continue
}
}
return nil
}

/// One line for a notification: code and emphasis marks and heading marks removed,
/// whitespace collapsed, at most `maximumCharacters`.
static func oneLine(_ text: String) -> String? {
let words = text.replacing("**", with: "").replacing("`", with: "")
.split(whereSeparator: \.isWhitespace)
.filter { word in !word.allSatisfy { $0 == "#" } }
let line = words.joined(separator: " ")
guard !line.isEmpty else { return nil }
guard line.count > maximumCharacters else { return line }
return String(line.prefix(maximumCharacters - 1)).trimmingCharacters(in: .whitespaces) + "…"
}
}
18 changes: 16 additions & 2 deletions App/Sources/Features/RemoteMirror/RemoteMirrorStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,24 @@ final class RemoteMirrorStore {
pushSender = MirrorPushSender(
host: host, enabled: { settings.wrappedValue.global.remoteMirrorEnabled },
paneStates: { paneSource.pushPaneStates() },
paneDetails: { id in
paneDetails: { id, kind in
guard let pane = paneSource.panes().first(where: { $0.id == id }) else { return nil }
let title = [pane.tabTitle, pane.worktreeName].compactMap { $0 }.joined(separator: " · ")
return .init(title: title.isEmpty ? pane.title : title, stateChangedAt: pane.stateChangedAt)
var details = MirrorPushSender.PaneDetails(
title: title.isEmpty ? pane.title : title, stateChangedAt: pane.stateChangedAt)
switch kind {
case .blocked:
details.summary = (try? paneSource.activeText(id)).flatMap(MirrorPushSummary.question(onScreen:))
case .done:
if let state = paneSource.agentState(id), let agent = state.detectedAgent,
let transcript = state.session?.transcriptPath
{
details.summary = await Task.detached {
MirrorPushSummary.lastReply(transcript: transcript, agent: agent)
}.value
}
}
return details
},
presence: MacPresenceMonitor(), gateway: URLSessionMirrorPushGateway.configured())
self.runtime = runtime
Expand Down
18 changes: 9 additions & 9 deletions App/Tests/RemoteMirror/MirrorHostTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1242,7 +1242,7 @@ struct MirrorHostTests {
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { gate != .mirrorOff }, paneStates: { states },
paneDetails: { _ in .init(title: "demo · main", stateChangedAt: nil) }, presence: presence,
paneDetails: { _, _ in .init(title: "demo · main", stateChangedAt: nil) }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1293,7 +1293,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1357,7 +1357,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1413,7 +1413,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1449,7 +1449,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { locked }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1496,7 +1496,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1539,7 +1539,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { false }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1577,7 +1577,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { true }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down Expand Up @@ -1633,7 +1633,7 @@ struct MirrorHostTests {
let presence = MacPresenceMonitor(
idleSeconds: { 0 }, screenLocked: { true }, displayAsleep: { false }, observesSystem: false)
let sender = MirrorPushSender(
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _ in nil }, presence: presence,
host: host, enabled: { true }, paneStates: { states }, paneDetails: { _, _ in nil }, presence: presence,
gateway: gateway)
defer { sender.stop() }
sender.refresh()
Expand Down
1 change: 1 addition & 0 deletions App/Tests/RemoteMirror/MirrorPushContractTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ struct MirrorPushContractTests {
baseURL: URLSessionMirrorPushGateway.defaultBaseURL, token: "t", collapseID: "c", sealed: "s")
#expect(request.httpMethod == "POST")
#expect(request.url?.path() == gateway["pushPath"] as? String)
#expect(MirrorPushContract.maximumSealedLength == gateway["maximumSealedLength"] as? Int)
let body = try JSONSerialization.jsonObject(with: try #require(request.httpBody)) as? [String: String]
#expect(body?.keys.sorted() == gateway["pushRequestKeys"] as? [String])

Expand Down
63 changes: 63 additions & 0 deletions App/Tests/RemoteMirror/MirrorPushSummaryTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Foundation
import Testing

@testable import Prowl

struct MirrorPushSummaryTests {
private static let fixtures = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.appending(path: "Fixtures")
private static let conversation = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
.appending(path: "Mirror/Fixtures/conversation")

private static func screen(_ name: String) throws -> String {
try String(contentsOf: fixtures.appending(path: "MirrorScreenPrompt/\(name)"), encoding: .utf8)
}

@Test func aBlockedAgentShowsItsQuestionAndWhatItIsAbout() throws {
#expect(
MirrorPushSummary.question(onScreen: try Self.screen("claude-2.1.322-folder-trust.txt"))
== "Trust this folder? · /private/tmp/pm-e2e/Trust3")
let permission = try #require(
MirrorPushSummary.question(onScreen: try Self.screen("claude-2.1.318-command-permission.txt")))
#expect(permission.hasPrefix("Do you want to proceed? · prowl agents dispatch-complete"))
#expect(MirrorPushSummary.question(onScreen: "$ ls\nREADME.md\n$ ") == nil)
}

@Test func aFinishedAgentShowsTheStartOfItsLastReply() throws {
let transcript = Self.conversation.appending(path: "claude-review-1038.jsonl")
let reply = try #require(MirrorPushSummary.lastReply(transcript: transcript, agent: .claude))
#expect(reply.hasPrefix("审查报告已经在上面了喵,dispatch 也以 succeeded 收尾。 一句话回顾:"))
#expect(reply.count <= MirrorPushSummary.maximumCharacters && reply.hasSuffix("…"))
#expect(MirrorPushSummary.lastReply(transcript: URL(fileURLWithPath: "/nonexistent.jsonl"), agent: .claude) == nil)
}

@Test func aReplyBecomesOneShortLine() {
#expect(
MirrorPushSummary.oneLine("## Done\n\nFixed **two** bugs in `Foo.swift`.\n")
== "Done Fixed two bugs in Foo.swift.")
#expect(MirrorPushSummary.oneLine(" \n\t ") == nil)
let long = MirrorPushSummary.oneLine(String(repeating: "word ", count: 100))
#expect(long?.count == MirrorPushSummary.maximumCharacters && long?.hasSuffix("…") == true)
}

@Test func thePushCarriesTheSummaryUnlessItIsTooLarge() throws {
let device = MirrorPairedDevice(id: UUID(), name: "Phone", key: Data(repeating: 7, count: 32), pairedAt: Date())
let hostID = UUID()
let push = MirrorPushPlanner.Push(deviceID: device.id, paneID: UUID(), kind: .blocked)
let key = MirrorPushCrypto.key(deviceSecret: device.key, hostID: hostID)
func body(_ summary: String?) throws -> String {
let request = try #require(
MirrorPushSender.request(
for: push, device: device, hostID: hostID,
details: .init(title: "Prowl · main", stateChangedAt: nil, summary: summary)))
#expect(request.sealed.count <= MirrorPushContract.maximumSealedLength)
return try MirrorPushContent.decode(MirrorPushCrypto.open(request.sealed, key: key)).body
}
#expect(try body("Trust this folder? · /tmp/x") == "Trust this folder? · /tmp/x")
#expect(try body(nil) == "An agent needs your attention")
// Only a summary built elsewhere could be this long; it still must not break the push.
#expect(try body(String(repeating: "界", count: 2_000)) == "An agent needs your attention")
}
}
1 change: 1 addition & 0 deletions Mirror/Fixtures/push/contract.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
]
},
"pushPath": "/v1/push",
"maximumSealedLength": 3000,
"pushRequestKeys": [
"collapseID",
"pushToken",
Expand Down
3 changes: 3 additions & 0 deletions Mirror/Shared/MirrorPushContract.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ nonisolated enum MirrorPushContract {
/// reported, and works only at the gateway that issued it, so the Host and the phone must
/// use this same address.
static let gatewayURL = URL(string: "https://prowl-push.onev.dev")!

/// The longest `sealed` value (Base64 characters) that the gateway accepts in `POST /v1/push`.
static let maximumSealedLength = 3_000
}

/// `pushRegister`: where the Host sends push events for this device, and which events. The
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct MirrorNotificationsSection: View {
if push.settings.isEnabled {
Toggle(isOn: Binding(get: { push.settings.showsDetails }, set: push.settings.setShowsDetails)) {
Text("Show Details")
Text("Show the tab name in notifications, also on the lock screen.")
Text("Show the tab name and what the agent asks or replies, also on the lock screen.")
}
.accessibilityIdentifier("push-show-details")
// One row per Mac: its addresses share the kinds and the token.
Expand Down
1 change: 1 addition & 0 deletions docs-ai/095-mirror-push-notifications/000-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,4 @@ S0 notes for P3:
- Updated 2026-11-22: M2 flows out of views, one notification row per Mac — see [012-m2-flows.md](012-m2-flows.md)
- Updated 2026-11-22: M3 dead tokens (`pushStatus.tokenGone`) — see [013-m3-dead-tokens.md](013-m3-dead-tokens.md)
- Updated 2026-11-22: M4 diagnostics (last push per device, gateway reasons, phone and extension logs) — see [014-m4-diagnostics.md](014-m4-diagnostics.md)
- Updated 2026-11-23: Show Details carries what the agent asks or replied — see [015-content-summary.md](015-content-summary.md)
32 changes: 32 additions & 0 deletions docs-ai/095-mirror-push-notifications/015-content-summary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 095.015 — Notification content with Show Details

## Context

With **Show Details** on, a notification showed the tab and worktree name, but its text was
always "An agent needs your attention" or "An agent finished". The user could not tell from the
notification whether to act now.

## Change

- The Host fills the encrypted body with what the agent asks or replied
(`App/Sources/Features/RemoteMirror/Push/MirrorPushSummary.swift`):
- **blocked**: the question on the agent's screen (`MirrorScreenPrompt.parse`, the same parser
as Chat) and the first line of its detail, such as the command a permission asks about:
"Do you want to proceed? · rm -rf build".
- **done**: the start of the agent's last reply, from the last 256 KB of its transcript
(`turn.completed` `lastMessage`, else the last `assistant.message`), read off the main actor
when the turn finishes.
- One line, code and emphasis marks and heading marks removed, at most 180 characters.
- Without a summary (no menu on screen, no transcript), the body stays the generic text.
- `MirrorPushSender` reads the details before it checks its gates, so a change while the
transcript is read still stops the push. A body that would make `sealed` longer than the
gateway accepts (`MirrorPushContract.maximumSealedLength`, 3,000, now in the shared contract
and tested by the Host and the gateway) falls back to the generic text.
- The phone is unchanged: without Show Details it shows the generic text by kind and ignores the
body. The Show Details description now says what it adds.
- Tests: `MirrorPushSummaryTests` (screen fixtures, the Claude conversation fixture, the one-line
form, the size fallback); the contract test for the limit. User docs: `docs/remote-mirror.md`.

## Refs

PR: see the PR that adds this file.
Loading
Loading