From 563e52b9a06ca1c1caf402ffdda892b97a7f711d Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Tue, 1 Dec 2026 07:05:40 +0800 Subject: [PATCH] feat(ios): add outline, plan quotas, and pull-request awareness Three H5 parity pieces for the chat surface: - Conversation outline: a sheet lists the user prompts loaded in the transcript, filters them by text, and scrolls/flashes the chosen prompt through the same tokenized transcript target as pending requests. - Plan quotas: a compact 5h/7d used-percent readout in the composer strip, fed by the runner's agent-quotas RPC through a new machine endpoint client. Hidden unless the machine advertises the capability and the active agent reports an OK account; refreshes every two minutes. - PR awareness: session metadata now decodes external refs (tolerantly for unknown kinds), the list row shows the primary GitHub PR number with a forge-state tint, and the row context menu opens the PR in Safari. Adds pure tests for outline filtering/truncation, quota selection and countdown formatting, and PR badge precedence plus wire decoding. via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- ios/Hapi/Features/Chat/ChatModel.swift | 34 ++++- ios/Hapi/Features/Chat/ChatView.swift | 12 ++ .../Chat/Composer/AgentQuotaPill.swift | 142 ++++++++++++++++++ .../Chat/Composer/ChatComposerStatusBar.swift | 1 + .../Features/Chat/ConversationOutline.swift | 104 +++++++++++++ .../Features/Sessions/SessionListModel.swift | 58 +++++++ .../Features/Sessions/SessionListView.swift | 35 +++++ ios/Hapi/Resources/Localizable.xcstrings | 110 ++++++++++++++ .../AgentQuotaPresentationTests.swift | 69 +++++++++ ios/HapiTests/ConversationOutlineTests.swift | 68 +++++++++ ios/HapiTests/PullRequestBadgeTests.swift | 60 ++++++++ .../Endpoints/MachineEndpoints.swift | 14 ++ .../HapiProtocol/Models/AgentQuota.swift | 81 ++++++++++ .../HapiProtocol/Models/ExternalRef.swift | 68 +++++++++ .../HapiProtocol/Models/SessionMetadata.swift | 6 +- .../HapiProtocol/Models/SessionSummary.swift | 6 +- .../HapiProtocol/Models/SummaryPatching.swift | 3 +- .../EndpointRequestTests.swift | 25 +++ .../HapiProtocolTests/ExternalRefTests.swift | 48 ++++++ 19 files changed, 940 insertions(+), 4 deletions(-) create mode 100644 ios/Hapi/Features/Chat/Composer/AgentQuotaPill.swift create mode 100644 ios/Hapi/Features/Chat/ConversationOutline.swift create mode 100644 ios/HapiTests/AgentQuotaPresentationTests.swift create mode 100644 ios/HapiTests/ConversationOutlineTests.swift create mode 100644 ios/HapiTests/PullRequestBadgeTests.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentQuota.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/ExternalRef.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiProtocolTests/ExternalRefTests.swift diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index ea193944..67db67bd 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -20,6 +20,10 @@ struct ChatHeaderUI: Equatable { /// Full session directory (shown in the session-info sheet). var projectPath: String? = nil var machine: String? = nil + /// Raw machine id, for machine-scoped RPCs (plan quotas). + var machineId: String? = nil + /// Runner advertises the `agent-quotas` machine capability. + var supportsAgentQuotas: Bool = false var worktree: String? = nil var model: String? = nil var effort: String? = nil @@ -339,6 +343,21 @@ final class ChatModel { return inputTools.contains(tool) ? .input : .permission } + // MARK: Conversation outline + + /// User prompts currently loaded in the transcript, oldest first. + var conversationOutline: [ChatOutlineItem] { + ConversationOutlineBuilder.items(from: blocks) + } + + /// Jump the transcript to one outline entry and flash its row. + func focusOutlineItem(_ id: String) { + guard blocks.contains(where: { $0.stableId == id }) else { return } + scrollTargetRowID = id + scrollTargetToken += 1 + flashRow(id) + } + /// Loaded user messages with a native fork/rewind point, newest first. var historyPointMessages: [UserTextBlock] { blocks.reversed().compactMap { visible in @@ -575,6 +594,13 @@ final class ChatModel { interactor.manageGoal(action: action, objective: objective) } + /// Plan/rate-limit windows for the composer strip. Nil when the runner + /// lacks the capability or the hub/RPC has nothing to report. + func loadAgentQuotas(refresh: Bool = false) async -> AgentQuotasResponse? { + guard header.supportsAgentQuotas, let machineId = header.machineId else { return nil } + return try? await hub.api.machineAgentQuotas(machineId: machineId, refresh: refresh) + } + func resetDisplayedReadReceipt() { displayedReadRevision = nil } /// The conditions under which `markDisplayed` acknowledges new tail output. @@ -914,8 +940,11 @@ final class ChatModel { let flavor = detail?.metadata?.flavor ?? summary?.metadata?.flavor let machineId = detail?.metadata?.machineId ?? summary?.metadata?.machineId + let machineInfo = machineId.flatMap { id in + machines.first(where: { $0.id == id }) + } let machineLabel: String? = machineId.map { id in - guard let metadata = machines.first(where: { $0.id == id })?.metadata else { + guard let metadata = machineInfo?.metadata else { return String(id.prefix(8)) } if let displayName = metadata.displayName, @@ -924,6 +953,7 @@ final class ChatModel { } return metadata.host } + let supportsAgentQuotas = machineInfo?.metadata?.capabilities?.contains("agent-quotas") == true let worktree = (detail?.metadata?.worktree ?? summary?.metadata?.worktree).map { tree in tree.name.trimmingCharacters(in: .whitespaces).isEmpty ? tree.branch : tree.name } @@ -947,6 +977,8 @@ final class ChatModel { project: project, projectPath: projectPath, machine: machineLabel, + machineId: machineId, + supportsAgentQuotas: supportsAgentQuotas, worktree: worktree, model: model, effort: effort, diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index 8b88b2aa..855d955d 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -34,6 +34,7 @@ struct ChatView: View { @State private var deleteOpen = false @State private var forkConfirmOpen = false @State private var historyOpen = false + @State private var outlineOpen = false /// Full session metadata behind the truncated nav subtitle. @State private var sessionInfoOpen = false @@ -128,6 +129,12 @@ struct ChatView: View { model.requestPendingFocus(pendingFocus) onPendingFocusConsumed?() } + .sheet(isPresented: $outlineOpen) { + ConversationOutlineSheet(items: model.conversationOutline) { id in + model.focusOutlineItem(id) + } + .macSheetSizing() + } } var body: some View { @@ -240,6 +247,11 @@ struct ChatView: View { Label("Rewind or Fork…", systemImage: "clock.arrow.circlepath") } } + Button { + outlineOpen = true + } label: { + Label("Conversation outline", systemImage: "list.bullet.rectangle") + } Button { model.exportConversation() } label: { diff --git a/ios/Hapi/Features/Chat/Composer/AgentQuotaPill.swift b/ios/Hapi/Features/Chat/Composer/AgentQuotaPill.swift new file mode 100644 index 00000000..9a4a602f --- /dev/null +++ b/ios/Hapi/Features/Chat/Composer/AgentQuotaPill.swift @@ -0,0 +1,142 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI + +/// Pure selection/formatting for the composer quota readout (web +/// `selectComposerQuotaBuckets` + `formatCompactCountdown`). +enum AgentQuotaPresentation { + /// Account-wide windows shown in the strip, in display order. + static let windows: [(key: String, short: String)] = [ + ("5h", "5h"), + ("weekly", "7d"), + ] + + static func buckets( + in response: AgentQuotasResponse?, + flavor: String? + ) -> [AgentQuotaBucket] { + guard let response, + let flavor, + let account = response.accounts.first(where: { $0.agent == flavor }), + account.status == "ok" else { return [] } + return windows.compactMap { window in + account.buckets.first { $0.group == nil && $0.window == window.key } + } + } + + static func shortWindow(_ window: String?) -> String? { + guard let window else { return nil } + return windows.first { $0.key == window }?.short ?? window + } + + /// Two most significant units, e.g. `2d14h`, `2h13m`, `35m`. + static func compactCountdown(ms: Int) -> String { + let totalMinutes = max(1, Int(ceil(Double(ms) / 60_000))) + let days = totalMinutes / (24 * 60) + let hours = (totalMinutes % (24 * 60)) / 60 + let minutes = totalMinutes % 60 + if days > 0 { + return hours > 0 ? "\(days)d\(hours)h" : "\(days)d" + } + if hours > 0 { + return minutes > 0 ? "\(hours)h\(minutes)m" : "\(hours)h" + } + return "\(minutes)m" + } +} + +/// Compact 5h/weekly plan-quota readout beside the context meter. Hidden +/// unless the runner advertises the RPC and the active agent reports an OK +/// account. Refreshes every two minutes while the chat is open; a failed +/// refetch keeps the previous numbers. +struct AgentQuotaPill: View { + let model: ChatModel + + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + @State private var response: AgentQuotasResponse? + + private struct LoadKey: Equatable { + let machineId: String? + let flavor: String? + let supported: Bool + } + + private var loadKey: LoadKey { + LoadKey( + machineId: model.header.machineId, + flavor: model.header.flavor, + supported: model.header.supportsAgentQuotas + ) + } + + private var buckets: [AgentQuotaBucket] { + AgentQuotaPresentation.buckets(in: response, flavor: model.header.flavor) + } + + var body: some View { + Group { + if !buckets.isEmpty { + TimelineView(.periodic(from: .now, by: 30)) { context in + chip(now: context.date) + } + } + } + .task(id: loadKey) { + response = nil + guard loadKey.supported else { return } + while !Task.isCancelled { + let fresh = await model.loadAgentQuotas() + guard !Task.isCancelled else { return } + response = fresh + try? await Task.sleep(for: .seconds(120)) + } + } + } + + private func chip(now: Date) -> some View { + let nowMs = Int(now.timeIntervalSince1970 * 1000) + let parts = buckets.map { bucket -> String in + let head = "\(AgentQuotaPresentation.shortWindow(bucket.window) ?? bucket.label) \(Int(bucket.usedPercent.rounded()))%" + guard let resetsAt = bucket.resetsAt, resetsAt > nowMs else { return head } + return "\(head) (\(AgentQuotaPresentation.compactCountdown(ms: resetsAt - nowMs)))" + } + let summary = parts.joined(separator: " · ") + let remaining = buckets.map(\.remainingPercent).min() ?? 100 + return Menu { + ForEach(Array(buckets.enumerated()), id: \.element.id) { index, bucket in + Text(verbatim: "\(bucket.label) · \(Int(bucket.usedPercent.rounded()))%") + if let resetsAt = bucket.resetsAt { + Text(resetText(resetsAt: resetsAt, nowMs: nowMs)) + } + if index < buckets.count - 1 { + Divider() + } + } + } label: { + Text(verbatim: summary) + .foregroundStyle(tint(remaining: remaining)) + .lineLimit(1) + } + .menuStyle(.borderlessButton) + .fixedSize() + .accessibilityLabel(Text(verbatim: summary)) + } + + private func resetText(resetsAt: Int, nowMs: Int) -> String { + if resetsAt > nowMs { + return String( + format: String(localized: "Resets in %@"), + AgentQuotaPresentation.compactCountdown(ms: resetsAt - nowMs) + ) + } + return String(localized: "Resets soon") + } + + private func tint(remaining: Double) -> Color { + if remaining <= 5 { return theme.danger } + if remaining <= 20 { return theme.warning } + return theme.textSecondary + } +} diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift index 9d3f0abc..099f79f8 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift @@ -76,6 +76,7 @@ struct ChatComposerStatusBar: View { if let usage = model.latestUsage { ContextUsagePill(usage: usage, window: usage.contextWindow) } + AgentQuotaPill(model: model) if model.header.isCompacting { statusChip("Compacting", icon: "archivebox.fill", tint: theme.warning) } diff --git a/ios/Hapi/Features/Chat/ConversationOutline.swift b/ios/Hapi/Features/Chat/ConversationOutline.swift new file mode 100644 index 00000000..de5d214d --- /dev/null +++ b/ios/Hapi/Features/Chat/ConversationOutline.swift @@ -0,0 +1,104 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI + +/// One jump target in the conversation outline. Only user prompts currently +/// loaded in the transcript are listed (web `buildConversationOutline`). +struct ChatOutlineItem: Identifiable, Equatable { + /// The transcript row id (the user block's message id). + let id: String + let label: String + let createdAt: Int +} + +enum ConversationOutlineBuilder { + static let maxLabelLength = 96 + + /// Web parity: a user block with no invocation time is a local echo and + /// not a stable destination; a failed send is still a real prompt. + static func items(from blocks: [VisibleChatBlock]) -> [ChatOutlineItem] { + blocks.compactMap { visible in + guard case .block(.userText(let block)) = visible else { return nil } + guard !(block.invokedAt == nil && block.status != "failed") else { return nil } + let label = truncateLabel(block.text) + return ChatOutlineItem( + id: block.id, + label: label.isEmpty ? String(localized: "Empty message") : label, + createdAt: block.createdAt + ) + } + } + + static func truncateLabel(_ value: String) -> String { + let collapsed = value + .split(whereSeparator: \.isWhitespace) + .joined(separator: " ") + guard collapsed.count > maxLabelLength else { return collapsed } + let head = String(collapsed.prefix(maxLabelLength - 3)) + return head.trimmingCharacters(in: .whitespaces) + "..." + } +} + +/// Sheet listing the user prompts in the loaded transcript. Selecting one +/// closes the sheet and scrolls the transcript to that prompt. +struct ConversationOutlineSheet: View { + let items: [ChatOutlineItem] + let onSelect: (String) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var search = "" + + private var filtered: [ChatOutlineItem] { + let query = search.trimmingCharacters(in: .whitespacesAndNewlines) + guard !query.isEmpty else { return items } + return items.filter { $0.label.localizedCaseInsensitiveContains(query) } + } + + var body: some View { + NavigationStack { + List(filtered) { item in + Button { + onSelect(item.id) + dismiss() + } label: { + VStack(alignment: .leading, spacing: 4) { + Text(verbatim: item.label) + .foregroundStyle(.primary) + .lineLimit(3) + Text(verbatim: ChatTimeLabel.text(for: item.createdAt)) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + .overlay { + if items.isEmpty { + ContentUnavailableView( + "No Outline Yet", + systemImage: "list.bullet.rectangle", + description: Text("User prompts appear here once the conversation has messages.") + ) + } else if filtered.isEmpty { + ContentUnavailableView.search(text: search) + } + } + .searchable( + text: $search, + placement: .navigationBarDrawer(displayMode: .always), + prompt: Text("Search prompts") + ) + .navigationTitle("Conversation Outline") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } +} diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index d43c1965..c31b15ee 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -25,6 +25,9 @@ struct SessionRowUI: Identifiable, Equatable { var id: String { summary.id } var status: SessionRowStatus? { SessionRowStatus(summary: summary) } var presence: SessionPresence { SessionPresence(summary: summary) } + var pullRequest: PullRequestBadge? { + PullRequestBadge(summary.metadata?.primaryGithubPullRequest) + } /// Only a running job is shown; finished ones leave no trace on the row. var runningJob: AttachedJob? { summary.runningAttachedJob } } @@ -165,6 +168,61 @@ enum SessionRowStatus: Equatable { } } +/// Compact GitHub PR state for the session row (web `SessionPrChip` default +/// forge rules, without the estate-override display profile). +enum PullRequestBadgeState: Equatable { + case merged + case closed + case draft + case failing + case pending + case ready + case linked +} + +struct PullRequestBadge: Equatable { + let number: Int + let url: String + let repo: String? + let state: PullRequestBadgeState + + init?(_ ref: ExternalRef?) { + guard let ref, let number = ref.number, let url = ref.url else { return nil } + self.number = number + self.url = url + self.repo = ref.repo + self.state = Self.state(for: ref) + } + + /// Terminal open state first, then blocking forge states, then pending, + /// then green merge/check composites — the same precedence as the web + /// chip so a merged PR is not shown as "ready to merge". + private static func state(for ref: ExternalRef) -> PullRequestBadgeState { + switch ref.openState { + case "merged": return .merged + case "closed": return .closed + case "draft": return .draft + default: break + } + if ref.checks == "fail" || ref.merge == "conflicting" || ref.merge == "blocked" { + return .failing + } + if ref.checks == "pending" || ref.merge == "unstable" || ref.merge == "behind" { + return .pending + } + if ref.merge == "clean" || ref.checks == "pass" { + return .ready + } + return .linked + } + + /// `owner/repo#N`, or `#N` when the repo is missing. + var reference: String { + guard let repo, !repo.isEmpty else { return "#\(number)" } + return "\(repo)#\(number)" + } +} + struct MachineFilterUI: Identifiable, Equatable { /// Machine id or `unknownMachineFilterId`. let id: String diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index bd7a6af4..7cc947af 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -607,6 +607,13 @@ struct SessionListView: View { Label("Remove from Group", systemImage: "rectangle.stack.badge.minus") } } + if let pullRequest = row.pullRequest, let url = URL(string: pullRequest.url) { + Button { + UIApplication.shared.open(url) + } label: { + Label("Open pull request", systemImage: "arrow.up.right.square") + } + } Button { UIPasteboard.general.string = SessionCitation.referenceText( title: row.title, @@ -869,6 +876,9 @@ struct SessionRowView: View { .accessibilityHidden(detailText == nil) } Spacer(minLength: 12) + if let pullRequest = row.pullRequest { + pullRequestBadge(pullRequest) + } if showsSpinner { ProgressView() .progressViewStyle(.circular) @@ -901,6 +911,31 @@ struct SessionRowView: View { .foregroundStyle(isArchived ? theme.textHint : theme.textSecondary) } + /// Primary linked GitHub PR beside the attention slot. Read-only in the + /// row (the list row owns the tap); the context menu opens the URL. + private func pullRequestBadge(_ badge: PullRequestBadge) -> some View { + Text(verbatim: "#\(badge.number)") + .font(.system(size: metrics.detailSize * 0.9, weight: .medium)) + .foregroundStyle(pullRequestColor(badge.state)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(theme.surface, in: Capsule()) + .fixedSize() + .layoutPriority(1) + .accessibilityLabel(Text("Pull request #\(badge.number)")) + } + + private func pullRequestColor(_ state: PullRequestBadgeState) -> Color { + switch state { + case .merged: return .purple + case .closed, .draft: return theme.textSecondary + case .failing: return theme.warning + case .pending: return theme.accent + case .ready: return theme.success + case .linked: return theme.textSecondary + } + } + /// Thinking rows get the green spinner; background-only work gets the /// blue one. Pending attention keeps its symbol instead. private var showsSpinner: Bool { diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 0dcdfc34..10491541 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -3548,6 +3548,28 @@ } } }, + "Conversation outline" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "对话大纲" + } + } + } + }, + "Conversation Outline" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "对话大纲" + } + } + } + }, "Copy" : { "extractionState" : "manual", "localizations" : { @@ -4942,6 +4964,17 @@ } } }, + "Empty message" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "空消息" + } + } + } + }, "Enable in system settings…" : { "extractionState" : "manual", "localizations" : { @@ -7445,6 +7478,17 @@ } } }, + "No Outline Yet" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "暂无大纲" + } + } + } + }, "No History Points" : { "extractionState" : "manual", "localizations" : { @@ -7989,6 +8033,17 @@ } } }, + "Open pull request" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "打开拉取请求" + } + } + } + }, "Open Settings" : { "extractionState" : "manual", "localizations" : { @@ -8907,6 +8962,17 @@ } } }, + "Pull request #%lld" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "拉取请求 #%lld" + } + } + } + }, "Pull to retry once you are back online." : { "extractionState" : "manual", "localizations" : { @@ -9485,6 +9551,28 @@ } } }, + "Resets in %@" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "距离重置 %@" + } + } + } + }, + "Resets soon" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "即将重置" + } + } + } + }, "Result" : { "extractionState" : "manual", "localizations" : { @@ -10131,6 +10219,17 @@ } } }, + "Search prompts" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索提问" + } + } + } + }, "Search sessions" : { "extractionState" : "manual", "localizations" : { @@ -12341,6 +12440,17 @@ } } }, + "User prompts appear here once the conversation has messages." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "会话有消息后,你的提问会显示在这里。" + } + } + } + }, "View agent process" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/AgentQuotaPresentationTests.swift b/ios/HapiTests/AgentQuotaPresentationTests.swift new file mode 100644 index 00000000..eea01d24 --- /dev/null +++ b/ios/HapiTests/AgentQuotaPresentationTests.swift @@ -0,0 +1,69 @@ +import XCTest +@testable import Hapi +@testable import HapiProtocol + +final class AgentQuotaPresentationTests: XCTestCase { + private func account( + agent: String = "claude", + status: String = "ok", + buckets: [AgentQuotaBucket] + ) -> AgentQuotaAccount { + AgentQuotaAccount( + agent: agent, + available: true, + status: status, + buckets: buckets, + updatedAt: 1 + ) + } + + private func bucket(_ id: String, window: String?, group: String? = nil) -> AgentQuotaBucket { + AgentQuotaBucket( + id: id, + label: id, + group: group, + window: window, + usedPercent: 42, + remainingPercent: 58 + ) + } + + func testSelectsTheAgentFiveHourAndWeeklyWindowsInOrder() { + let response = AgentQuotasResponse( + accounts: [account(buckets: [ + bucket("weekly", window: "weekly"), + bucket("grouped", window: "5h", group: "opus"), + bucket("five-hour", window: "5h") + ])], + fetchedAt: 1 + ) + let buckets = AgentQuotaPresentation.buckets(in: response, flavor: "claude") + XCTAssertEqual(buckets.map(\.id), ["five-hour", "weekly"]) + } + + func testHidesNonOKAccountsAndOtherFlavors() { + let failed = AgentQuotasResponse( + accounts: [account(status: "unauthenticated", buckets: [bucket("5h", window: "5h")])], + fetchedAt: 1 + ) + XCTAssertTrue(AgentQuotaPresentation.buckets(in: failed, flavor: "claude").isEmpty) + XCTAssertTrue(AgentQuotaPresentation.buckets(in: failed, flavor: "codex").isEmpty) + XCTAssertTrue(AgentQuotaPresentation.buckets(in: nil, flavor: "claude").isEmpty) + } + + func testCompactCountdownKeepsTheTwoLargestUnits() { + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: (2 * 24 + 14) * 60 * 60_000), "2d14h") + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: 48 * 60 * 60_000), "2d") + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: (2 * 60 + 13) * 60_000), "2h13m") + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: 3 * 60 * 60_000), "3h") + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: 35 * 60_000), "35m") + XCTAssertEqual(AgentQuotaPresentation.compactCountdown(ms: 0), "1m") + } + + func testShortWindowLabels() { + XCTAssertEqual(AgentQuotaPresentation.shortWindow("weekly"), "7d") + XCTAssertEqual(AgentQuotaPresentation.shortWindow("5h"), "5h") + XCTAssertEqual(AgentQuotaPresentation.shortWindow("monthly"), "monthly") + XCTAssertNil(AgentQuotaPresentation.shortWindow(nil)) + } +} diff --git a/ios/HapiTests/ConversationOutlineTests.swift b/ios/HapiTests/ConversationOutlineTests.swift new file mode 100644 index 00000000..da177f6f --- /dev/null +++ b/ios/HapiTests/ConversationOutlineTests.swift @@ -0,0 +1,68 @@ +import XCTest +@testable import Hapi +@testable import HapiProtocol + +final class ConversationOutlineTests: XCTestCase { + private func user( + _ id: String, + text: String, + invokedAt: Int? = 1, + status: String? = nil + ) -> VisibleChatBlock { + .block(.userText(UserTextBlock( + id: id, + localId: nil, + createdAt: 1, + invokedAt: invokedAt, + text: text, + attachments: nil, + status: status, + originalText: nil, + meta: nil + ))) + } + + private func agent(_ id: String, text: String) -> VisibleChatBlock { + .block(.agentText(AgentTextBlock( + id: id, + localId: nil, + createdAt: 2, + invokedAt: nil, + durationMs: nil, + usage: nil, + model: nil, + text: text, + meta: nil + ))) + } + + func testListsUserPromptsOnlyAndSkipsLocalEchoes() { + let items = ConversationOutlineBuilder.items(from: [ + user("a", text: "First prompt"), + agent("b", text: "Assistant answer"), + user("c", text: "Uninvoked echo", invokedAt: nil), + user("d", text: "Failed send", invokedAt: nil, status: "failed"), + user("e", text: "Second prompt") + ]) + XCTAssertEqual(items.map(\.id), ["a", "d", "e"]) + XCTAssertEqual(items.map(\.label), ["First prompt", "Failed send", "Second prompt"]) + } + + func testCollapsesWhitespaceAndTruncatesTheLabel() { + XCTAssertEqual( + ConversationOutlineBuilder.truncateLabel(" one\n\n two\tthree "), + "one two three" + ) + let long = String(repeating: "a", count: 120) + let label = ConversationOutlineBuilder.truncateLabel(long) + XCTAssertEqual(label.count, ConversationOutlineBuilder.maxLabelLength) + XCTAssertTrue(label.hasSuffix("...")) + XCTAssertEqual(ConversationOutlineBuilder.truncateLabel(" \n "), "") + } + + func testEmptyTextGetsAPlaceholderLabel() { + let items = ConversationOutlineBuilder.items(from: [user("a", text: " ")]) + XCTAssertEqual(items.count, 1) + XCTAssertFalse(items[0].label.trimmingCharacters(in: .whitespaces).isEmpty) + } +} diff --git a/ios/HapiTests/PullRequestBadgeTests.swift b/ios/HapiTests/PullRequestBadgeTests.swift new file mode 100644 index 00000000..041b27b8 --- /dev/null +++ b/ios/HapiTests/PullRequestBadgeTests.swift @@ -0,0 +1,60 @@ +import XCTest +@testable import Hapi +@testable import HapiProtocol + +final class PullRequestBadgeTests: XCTestCase { + private func ref( + openState: String? = "open", + checks: String? = nil, + merge: String? = nil + ) -> ExternalRef { + ExternalRef( + kind: "github_pr", + repo: "tiann/hapi", + number: 1163, + url: "https://github.com/tiann/hapi/pull/1163", + role: "primary", + source: "user", + openState: openState, + checks: checks, + merge: merge + ) + } + + func testTerminalOpenStateWinsOverForgeHealth() { + XCTAssertEqual(PullRequestBadge(ref(openState: "merged", checks: "fail", merge: "conflicting"))?.state, .merged) + XCTAssertEqual(PullRequestBadge(ref(openState: "closed"))?.state, .closed) + XCTAssertEqual(PullRequestBadge(ref(openState: "draft"))?.state, .draft) + } + + func testForgeHealthPrecedence() { + XCTAssertEqual(PullRequestBadge(ref(checks: "fail"))?.state, .failing) + XCTAssertEqual(PullRequestBadge(ref(merge: "conflicting"))?.state, .failing) + XCTAssertEqual(PullRequestBadge(ref(merge: "blocked"))?.state, .failing) + XCTAssertEqual(PullRequestBadge(ref(checks: "pending"))?.state, .pending) + XCTAssertEqual(PullRequestBadge(ref(merge: "behind"))?.state, .pending) + XCTAssertEqual(PullRequestBadge(ref(checks: "pass", merge: "clean"))?.state, .ready) + XCTAssertEqual(PullRequestBadge(ref())?.state, .linked) + } + + func testBadgeRequiresAResolvableIdentityAndFormatsTheReference() { + XCTAssertNil(PullRequestBadge(nil)) + XCTAssertNil(PullRequestBadge(ExternalRef(kind: "github_pr", role: "primary"))) + let badge = PullRequestBadge(ref()) + XCTAssertEqual(badge?.reference, "tiann/hapi#1163") + let noRepo = PullRequestBadge(ExternalRef( + kind: "github_pr", + number: 7, + url: "https://example.com/pull/7", + role: "primary" + )) + XCTAssertEqual(noRepo?.reference, "#7") + } + + func testNonPrimaryOrUnknownKindsAreIgnored() { + let secondary = ExternalRef(kind: "github_pr", number: 1, url: "https://x/1", role: "secondary") + XCTAssertFalse(secondary.isPrimaryGithubPullRequest) + let future = ExternalRef(kind: "linear_issue", number: 1, url: "https://x/1", role: "primary") + XCTAssertFalse(future.isPrimaryGithubPullRequest) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift index 90efdce1..8ed873fb 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift @@ -40,6 +40,20 @@ extension APIClient { try await request(.get, "/api/machines/\(encodePathComponent(machineId))/agent-availability") } + /// `GET /api/machines/:id/agent-quotas` — plan/rate-limit windows from the + /// runner's agent CLI. A runner without the capability answers 409 + /// `runner_upgrade_required`; callers treat that as "nothing to show". + public func machineAgentQuotas( + machineId: String, + refresh: Bool = false + ) async throws -> AgentQuotasResponse { + try await request( + .get, + "/api/machines/\(encodePathComponent(machineId))/agent-quotas", + query: refresh ? [URLQueryItem(name: "refresh", value: "true")] : [] + ) + } + /// `POST /api/machines/:id/list-directory` (RPC envelope — check /// `success`). public func listMachineDirectory( diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentQuota.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentQuota.swift new file mode 100644 index 00000000..32e281a0 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentQuota.swift @@ -0,0 +1,81 @@ +import Foundation + +/// One rate-limit window reported by a runner's quota RPC +/// (`AgentQuotaBucketSchema`, `shared/src/apiTypes.ts`). +public struct AgentQuotaBucket: Codable, Equatable, Sendable, Identifiable { + public var id: String + public var label: String + public var group: String? + /// Wire window key: `5h`, `weekly`, … (`nil` for account-wide buckets). + public var window: String? + public var usedPercent: Double + public var remainingPercent: Double + /// Epoch ms; nil when the provider does not expose a reset. + public var resetsAt: Int? + + public init( + id: String, + label: String, + group: String? = nil, + window: String? = nil, + usedPercent: Double, + remainingPercent: Double, + resetsAt: Int? = nil + ) { + self.id = id + self.label = label + self.group = group + self.window = window + self.usedPercent = usedPercent + self.remainingPercent = remainingPercent + self.resetsAt = resetsAt + } +} + +/// One agent account's quota snapshot (`AgentQuotaAccountSchema`). +public struct AgentQuotaAccount: Codable, Equatable, Sendable { + /// Agent flavor id (`claude`, `codex`, …). + public var agent: String + public var available: Bool + /// `ok`, `custom_provider`, `unauthenticated`, `unavailable`, `error`. + public var status: String + public var accountLabel: String? + public var planLabel: String? + public var creditsLabel: String? + public var buckets: [AgentQuotaBucket] + public var note: String? + public var updatedAt: Int + + public init( + agent: String, + available: Bool, + status: String, + accountLabel: String? = nil, + planLabel: String? = nil, + creditsLabel: String? = nil, + buckets: [AgentQuotaBucket], + note: String? = nil, + updatedAt: Int + ) { + self.agent = agent + self.available = available + self.status = status + self.accountLabel = accountLabel + self.planLabel = planLabel + self.creditsLabel = creditsLabel + self.buckets = buckets + self.note = note + self.updatedAt = updatedAt + } +} + +/// `GET /api/machines/:id/agent-quotas` (`AgentQuotasResponseSchema`). +public struct AgentQuotasResponse: Codable, Equatable, Sendable { + public var accounts: [AgentQuotaAccount] + public var fetchedAt: Int + + public init(accounts: [AgentQuotaAccount], fetchedAt: Int) { + self.accounts = accounts + self.fetchedAt = fetchedAt + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ExternalRef.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ExternalRef.swift new file mode 100644 index 00000000..ff4606c4 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ExternalRef.swift @@ -0,0 +1,68 @@ +import Foundation + +/// A structured contribution link attached to session metadata +/// (`ExternalRefSchema`, `shared/src/schemas.ts`). +/// +/// The wire union currently has one member (`github_pr`). Declared tolerantly +/// with optional detail fields so an unknown future kind cannot fail the whole +/// session summary decode. +public struct ExternalRef: Codable, Equatable, Sendable { + public var kind: String + public var repo: String? + public var number: Int? + public var url: String? + /// `primary` or `secondary` (list rows show the primary only). + public var role: String? + /// `agent`, `user`, or `inferred`. + public var source: String? + public var linkedAt: Int? + /// `open`, `merged`, `closed`, or `draft`. + public var openState: String? + /// `pass`, `pending`, or `fail`. + public var checks: String? + /// `clean`, `conflicting`, `blocked`, `unstable`, or `behind`. + public var merge: String? + /// Epoch ms of the cached forge snapshot; absent on unsnapshotted links. + public var statusCheckedAt: Int? + /// Opaque estate classifier code; unknown values pass through. + public var estateCode: String? + + public init( + kind: String, + repo: String? = nil, + number: Int? = nil, + url: String? = nil, + role: String? = nil, + source: String? = nil, + linkedAt: Int? = nil, + openState: String? = nil, + checks: String? = nil, + merge: String? = nil, + statusCheckedAt: Int? = nil, + estateCode: String? = nil + ) { + self.kind = kind + self.repo = repo + self.number = number + self.url = url + self.role = role + self.source = source + self.linkedAt = linkedAt + self.openState = openState + self.checks = checks + self.merge = merge + self.statusCheckedAt = statusCheckedAt + self.estateCode = estateCode + } + + public var isPrimaryGithubPullRequest: Bool { + kind == "github_pr" && role == "primary" && number != nil && url != nil + } +} + +extension SessionSummaryMetadata { + /// The row's primary GitHub PR link, when the hub carried one. + public var primaryGithubPullRequest: ExternalRef? { + externalRefs?.first(where: \.isPrimaryGithubPullRequest) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift index 82e8c893..7e6467bb 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift @@ -151,6 +151,8 @@ public struct SessionMetadata: Codable, Equatable, Sendable { public var piSelectedModel: PiModelReference? /// User-message `localId`s with a native fork/rewind point. public var conversationHistoryPoints: [String: Bool]? + /// Structured contribution links (GitHub PRs, …). + public var externalRefs: [ExternalRef]? public init( path: String, @@ -182,7 +184,8 @@ public struct SessionMetadata: Codable, Equatable, Sendable { piSessionId: String? = nil, dshSessionId: String? = nil, piSelectedModel: PiModelReference? = nil, - conversationHistoryPoints: [String: Bool]? = nil + conversationHistoryPoints: [String: Bool]? = nil, + externalRefs: [ExternalRef]? = nil ) { self.path = path self.host = host @@ -214,5 +217,6 @@ public struct SessionMetadata: Codable, Equatable, Sendable { self.dshSessionId = dshSessionId self.piSelectedModel = piSelectedModel self.conversationHistoryPoints = conversationHistoryPoints + self.externalRefs = externalRefs } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift index 61a73c78..521cfc7f 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift @@ -61,6 +61,8 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { public var agentSessionId: String? public var lifecycleState: String? public var hapiMcpUrl: String? + /// Structured contribution links (GitHub PRs, …); absent on older hubs. + public var externalRefs: [ExternalRef]? public init( name: String? = nil, @@ -73,7 +75,8 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { worktree: WorktreeMetadata? = nil, agentSessionId: String? = nil, lifecycleState: String? = nil, - hapiMcpUrl: String? = nil + hapiMcpUrl: String? = nil, + externalRefs: [ExternalRef]? = nil ) { self.name = name self.group = group @@ -86,6 +89,7 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { self.agentSessionId = agentSessionId self.lifecycleState = lifecycleState self.hapiMcpUrl = hapiMcpUrl + self.externalRefs = externalRefs } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift index 2ff02398..19a3d020 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift @@ -160,7 +160,8 @@ public enum SummaryPatching { worktree: metadata.worktree, agentSessionId: summaryAgentSessionId(metadata), lifecycleState: metadata.lifecycleState, - hapiMcpUrl: metadata.hapiMcpUrl + hapiMcpUrl: metadata.hapiMcpUrl, + externalRefs: metadata.externalRefs ) } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift index b9ef87b2..77d8eacc 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift @@ -198,6 +198,31 @@ struct EndpointRequestTests { #expect(bodyString(pathRequest) == "{\"paths\":[\"/workspace\",\"/outside\"]}") } + @Test func machineAgentQuotasDecodesBucketsAndSendsRefresh() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue( + json: "{\"accounts\":[{\"agent\":\"claude\",\"available\":true,\"status\":\"ok\"," + + "\"accountLabel\":\"me@example.com\",\"planLabel\":\"Max\"," + + "\"buckets\":[{\"id\":\"5h\",\"label\":\"5-hour\",\"window\":\"5h\"," + + "\"usedPercent\":42.5,\"remainingPercent\":57.5,\"resetsAt\":123}]," + + "\"updatedAt\":1}],\"fetchedAt\":2}" + ) + let quotas = try await harness.client.machineAgentQuotas(machineId: "m 1", refresh: true) + let request = await harness.performer.requests.first + #expect( + request?.url?.absoluteString + == "\(testHubURLString)/api/machines/m%201/agent-quotas?refresh=true" + ) + #expect(request?.httpMethod == "GET") + #expect(quotas.fetchedAt == 2) + let account = try #require(quotas.accounts.first) + #expect(account.agent == "claude") + #expect(account.status == "ok") + #expect(account.buckets.first?.usedPercent == 42.5) + #expect(account.buckets.first?.resetsAt == 123) + #expect(account.buckets.first?.group == nil) + } + @Test func machineCodexModelsRequestAndRpcTargetMissing() async throws { let harness = try makeHarness(jwt: freshJWT()) await harness.performer.enqueue( diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/ExternalRefTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/ExternalRefTests.swift new file mode 100644 index 00000000..1f93e717 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/ExternalRefTests.swift @@ -0,0 +1,48 @@ +import Foundation +import HapiProtocol +import Testing + +@Suite("External refs") +struct ExternalRefTests { + private func summary(metadata: String) throws -> SessionSummary { + let row = """ + {"id":"s1","active":true,"thinking":false,"activeAt":0,"updatedAt":0,"metadata":\(metadata),\ + "metadataVersion":1,"agentStateVersion":1,"todosUpdatedAt":0,"pendingRequestsCount":0,\ + "pendingRequestKinds":[],"pendingRequests":[],"backgroundTaskCount":0,\ + "futureScheduledMessageCount":0} + """ + return try JSONDecoder().decode(SessionSummary.self, from: Data(row.utf8)) + } + + @Test func summaryMetadataDecodesPrimaryPullRequestAndUnknownKinds() throws { + let decoded = try summary(metadata: """ + {"path":"/work/hapi","host":"mac","externalRefs":[\ + {"kind":"github_pr","repo":"tiann/hapi","number":1163,\ + "url":"https://github.com/tiann/hapi/pull/1163","role":"primary","source":"user",\ + "openState":"open","checks":"pass","merge":"clean","statusCheckedAt":1},\ + {"kind":"linear_issue","id":"abc"}]} + """) + let refs = decoded.metadata?.externalRefs + #expect(refs?.count == 2) + #expect(refs?[0].repo == "tiann/hapi") + #expect(refs?[0].number == 1163) + #expect(refs?[0].checks == "pass") + #expect(refs?[1].kind == "linear_issue") + #expect(decoded.metadata?.primaryGithubPullRequest?.number == 1163) + } + + @Test func summaryWithoutRefsDecodes() throws { + let decoded = try summary(metadata: #"{"path":"/work/hapi","host":"mac"}"#) + #expect(decoded.metadata?.externalRefs == nil) + #expect(decoded.metadata?.primaryGithubPullRequest == nil) + } + + @Test func nonPrimaryPullRequestIsNotTheRowChip() throws { + let decoded = try summary(metadata: """ + {"path":"/work/hapi","host":"mac","externalRefs":[\ + {"kind":"github_pr","repo":"tiann/hapi","number":1,\ + "url":"https://github.com/tiann/hapi/pull/1","role":"secondary"}]} + """) + #expect(decoded.metadata?.primaryGithubPullRequest == nil) + } +}