From 19b2435ea8d86b6761676d5e6d9be0435d333a63 Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Sat, 5 Dec 2026 12:11:13 +0800 Subject: [PATCH] feat(ios): H5-style session rows and fix stuck queued actions Session rows now match the web sidebar: the second line shows the last two path components, active shares get a "Shared" pill, relative ages read like the H5 list (now, 5 min ago, 10 hours ago, 2 days ago, then a date), and the list font scale reaches 60%. The running spinner is drawn from a timeline instead of ProgressView: UIKit-backed spinners stop animating when a List cell is reconfigured, which read as a spinner that often failed. Working rows also keep their spinner while a pending approval is shown, as on web. Queued-message actions no longer look dead. Cancelling a row the hub reports as `busy` because it is already indeterminate used to restore the row unchanged; it now keeps a `queueDismissed` hold (web #1839), so Cancel and Retry take effect while the durable record stays available for a late consume. Steer is hidden for flavors that cannot take it (agy needs acp, cursor needs acp) via a port of the web steering gate. via [HAPI](https://hapi.run) Co-Authored-By: HAPI --- .../Features/Sessions/SessionListModel.swift | 112 +++++++++++++---- .../Features/Sessions/SessionListView.swift | 117 +++++++++--------- .../Features/Sessions/SessionRowChrome.swift | 75 +++++++++++ ios/HapiTests/SessionListFilterTests.swift | 6 +- ios/HapiTests/SessionRowStatusTests.swift | 68 ++++++++-- .../HapiClient/Chat/ChatInteractor.swift | 46 ++++++- .../Endpoints/SessionShareEndpoints.swift | 7 ++ .../HapiClient/Settings/DisplayPrefs.swift | 2 +- .../Stores/MessageWindowController.swift | 8 ++ .../HapiProtocol/Models/AgentState.swift | 8 +- .../HapiProtocol/Models/SessionMetadata.swift | 9 ++ .../HapiProtocol/Models/SessionShare.swift | 20 +++ .../HapiProtocol/Models/SessionSteering.swift | 67 ++++++++++ .../HapiProtocol/Window/MessageMerge.swift | 9 +- .../Window/MessageWindowLogic.swift | 48 ++++++- .../HapiProtocol/Window/WindowMessage.swift | 29 ++++- .../Chat/ChatInteractorTests.swift | 39 +++++- .../Settings/DisplayPrefsTests.swift | 2 +- 18 files changed, 567 insertions(+), 105 deletions(-) create mode 100644 ios/Hapi/Features/Sessions/SessionRowChrome.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSteering.swift diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index 6e9b8e5b..f0c147e1 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -21,6 +21,9 @@ struct SessionRowUI: Identifiable, Equatable { /// Raw flavor id (`claude`, `codex`, …); labels resolve via the catalog. let flavor: String? let unread: Bool + /// The owner has an active public share for this session (web + /// `sharedSessionIds`, `sessionShare.activeShort`). + let shared: Bool var id: String { summary.id } var status: SessionRowStatus? { SessionRowStatus(summary: summary) } @@ -30,6 +33,12 @@ struct SessionRowUI: Identifiable, Equatable { } /// Only a running job is shown; finished ones leave no trace on the row. var runningJob: AttachedJob? { summary.runningAttachedJob } + /// Agent work indicator. Deliberately independent of pending requests: + /// a working session can also be waiting on approval, and the row shows + /// both (the request symbol sits beside the title). + var showsWorkSpinner: Bool { + summary.thinking || (summary.active && summary.backgroundTaskCount > 0) + } /// Message-content search context; replaces the project line while a /// content query is active (the row keeps its two-line contract). var contentSnippet: String? @@ -292,6 +301,10 @@ final class SessionListModel { /// Hub message-content search; nil in tests that only exercise the local /// metadata index. private let contentSearch: ((String, [String]) async throws -> SessionContentSearchResponse)? + /// Active public shares in this namespace (web `useSessionShares`); rows + /// carry a "Shared" mark. Nil in tests that do not exercise shares. + private let loadShares: (() async throws -> [SessionShare])? + private(set) var sharedSessionIds: Set = [] /// Not persisted: a new home / hub starts with all sessions. private(set) var filters = SessionListFilters() { @@ -341,7 +354,8 @@ final class SessionListModel { sessionIds: sessionIds, limit: min(100, max(50, sessionIds.count)) ) - } + }, + loadShares: { try await api.sessionShares() } ) } @@ -355,7 +369,8 @@ final class SessionListModel { orderPrefs: SessionListOrderPrefs? = nil, hubUrl: String, drafts: (any ChatDrafts)? = nil, - contentSearch: ((String, [String]) async throws -> SessionContentSearchResponse)? = nil + contentSearch: ((String, [String]) async throws -> SessionContentSearchResponse)? = nil, + loadShares: (() async throws -> [SessionShare])? = nil ) { self.sessionStore = sessionStore self.machineStore = machineStore @@ -365,6 +380,7 @@ final class SessionListModel { self.hubUrl = hubUrl self.drafts = drafts self.contentSearch = contentSearch + self.loadShares = loadShares } // MARK: - Derived state @@ -634,6 +650,7 @@ final class SessionListModel { worktree: worktree?.isEmpty == false ? worktree : nil, flavor: summary.metadata?.flavor, unread: unread, + shared: sharedSessionIds.contains(summary.id), contentSnippet: snippet, contentSearchTruncated: truncated ) @@ -773,10 +790,15 @@ final class SessionListModel { } /// Use the worktree's owning project, not its temporary checkout name. - /// The home needs a scan key, not a repeated path or machine inventory. + /// Web `getGroupDisplayName`: the last two path components, so a + /// session's second line reads like the H5 sidebar (`Projects/hapi`). static func projectLabel(_ summary: SessionSummary) -> String? { guard let path = summary.metadata?.worktree?.basePath ?? summary.metadata?.path else { return nil } - return path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) + let components = path + .split(whereSeparator: { $0 == "/" || $0 == "\\" }) + .map(String.init) + guard !components.isEmpty else { return nil } + return components.suffix(2).joined(separator: "/") } // MARK: - Actions @@ -806,11 +828,20 @@ final class SessionListModel { hasRefreshedOnce = true do { try await machineStore.refresh() } catch { actionError = error.localizedDescription } + await refreshShares() } catch { isOffline = true } } + /// Shares are a secondary ornament, not the list itself: a failed fetch + /// keeps the previous marks instead of surfacing an error. + private func refreshShares() async { + guard let loadShares else { return } + guard let shares = try? await loadShares() else { return } + sharedSessionIds = Set(shares.map(\.sessionId)) + } + /// `PUT /sessions/:id/pin` with store-side optimistic re-sort; failures /// surface on `actionError`. func setPinMode(sessionId: String, mode: SessionPinMode) { @@ -953,22 +984,61 @@ final class SessionListModel { } } -/// Compact relative-age label for list rows ("now", "5m", "3h", "2d"). -/// Minute granularity is deliberate: it is why sub-minute `activeAt` churn -/// can be dropped as render-irrelevant (`sse.md#keep-alive-noise`). Mirrors -/// the Android reference (`formatRelativeAge`). +/// Which relative-age bucket a timestamp falls in (web +/// `formatRelativeTime`): under a minute, minutes, hours, days, or an +/// absolute date once it is a week old. Pure so tests do not depend on the +/// host locale's translations. +enum RelativeAgeBucket: Equatable { + case justNow + case minutes(Int) + case hours(Int) + case days(Int) + case absolute + + init(now: Date, thenEpochMs: Int) { + // Wire rows can carry seconds, not milliseconds (web treats < 1e12 as s). + let thenMs = thenEpochMs < 1_000_000_000_000 ? thenEpochMs * 1000 : thenEpochMs + let delta = Int(now.timeIntervalSince1970 * 1000) - thenMs + guard delta >= 60_000 else { + self = .justNow + return + } + let minutes = delta / 60_000 + if minutes < 60 { + self = .minutes(minutes) + return + } + let hours = minutes / 60 + if hours < 24 { + self = .hours(hours) + return + } + let days = hours / 24 + self = days < 7 ? .days(days) : .absolute + } +} + +/// Compact relative-age label for list rows, matching web +/// `formatRelativeTime`: just now, `5 min ago`, `3 hours ago`, `2 days ago`, +/// then an absolute `yyyy/MM/dd` date. Minute granularity is deliberate: it +/// is why sub-minute `activeAt` churn can be dropped as render-irrelevant +/// (`sse.md#keep-alive-noise`). func formatRelativeAge(now: Date, thenEpochMs: Int) -> String { - let delta = Int(now.timeIntervalSince1970 * 1000) - thenEpochMs - if delta < 60_000 { return String(localized: "now") } - let minutes = delta / 60_000 - if minutes < 60 { return "\(minutes)m" } - let hours = minutes / 60 - if hours < 24 { return "\(hours)h" } - let days = hours / 24 - if days < 7 { return "\(days)d" } - let weeks = days / 7 - if weeks < 5 { return "\(weeks)w" } - let months = days / 30 - if months < 12 { return "\(months)mo" } - return "\(days / 365)y" + switch RelativeAgeBucket(now: now, thenEpochMs: thenEpochMs) { + case .justNow: + return String(localized: "now") + case .minutes(let minutes): + return String(format: String(localized: "%lld min ago"), minutes) + case .hours(let hours): + return String(format: String(localized: "%lld hours ago"), hours) + case .days(let days): + return String(format: String(localized: "%lld days ago"), days) + case .absolute: + let thenMs = thenEpochMs < 1_000_000_000_000 ? thenEpochMs * 1000 : thenEpochMs + let date = Date(timeIntervalSince1970: Double(thenMs) / 1000) + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy/MM/dd" + return formatter.string(from: date) + } } diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index d71c49af..e5ae4605 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -838,7 +838,7 @@ struct SessionRowView: View { detailLine } } - // Separators start under the text column, as in Mail and Messages. + // Separators start under the text column, matching H5's inset hairline. .alignmentGuide(.listRowSeparatorLeading) { _ in metrics.iconSize + metrics.iconSpacing } .accessibilityElement(children: .combine) .accessibilityValue(accessibilityState) @@ -846,48 +846,56 @@ struct SessionRowView: View { } /// The agent owns the leading column; its presence badge carries the - /// session state instead of dimming disconnected rows. + /// session state instead of dimming disconnected rows. H5 draws the + /// brand mark bare on the row — no tile behind it. private var agentIcon: some View { - ZStack { - RoundedRectangle(cornerRadius: metrics.iconSize * 0.28, style: .continuous) - .fill(theme.surface) - AgentFlavorIconView(flavor: row.flavor, size: metrics.iconSize * 0.72) - } - .frame(width: metrics.iconSize, height: metrics.iconSize) - // Archived rows read as clearly inactive: desaturated icon and a - // quieter title/detail, like the web sidebar's archived treatment. - .saturation(isArchived ? 0 : 1) - .opacity(isArchived ? 0.55 : 1) - .overlay(alignment: .bottomTrailing) { - SessionPresenceBadge(presence: row.presence, size: metrics.iconSize * 0.3) - .offset(x: 2, y: 2) - } + AgentFlavorIconView(flavor: row.flavor, size: metrics.iconSize * 0.86) + .frame(width: metrics.iconSize, height: metrics.iconSize) + // Archived rows read as clearly inactive: desaturated icon and a + // quieter title/detail, like the web sidebar's archived treatment. + .saturation(isArchived ? 0 : 1) + .opacity(isArchived ? 0.55 : 1) + .overlay(alignment: .bottomTrailing) { + SessionPresenceBadge(presence: row.presence, size: metrics.iconSize * 0.3) + .offset(x: 2, y: 2) + } } + /// Title row: the name plus its attention symbol and shared mark, as on + /// the H5 sidebar. The timestamp moved to the second line so a long + /// title keeps the width it needs. private var titleLine: some View { - HStack(spacing: 8) { + HStack(spacing: 6) { Text(verbatim: row.title) .font(.system(size: metrics.titleSize, weight: row.unread && !isArchived ? .semibold : .regular)) .foregroundStyle(isArchived ? theme.textSecondary : theme.textPrimary) .lineLimit(1) Spacer(minLength: 4) - // Unread is a semibold title plus an accent timestamp, not a - // dot: the presence badge is the row's only dot. - // Minute ticks redraw only this label, not the list. - TimelineView(.periodic(from: .now, by: 60)) { context in - Text(verbatim: formatRelativeAge(now: context.date, thenEpochMs: row.summary.updatedAt)) + if let status = row.status { + Image(systemName: status.symbolName) + .symbolVariant(.none) + .symbolRenderingMode(.monochrome) + .font(.system(size: metrics.detailSize)) + .foregroundStyle(attentionColor) + // One slot keeps every attention symbol aligned. + .frame(width: metrics.statusSlotSize, height: metrics.statusSlotSize) + .fixedSize() + .layoutPriority(1) + .accessibilityLabel(statusAccessibilityText(status)) + } + if row.shared { + SessionSharedBadge(size: metrics.detailSize) + .layoutPriority(1) } - .font(.system(size: metrics.detailSize, weight: row.unread && !isArchived ? .semibold : .regular)) - .foregroundStyle(isArchived ? theme.textHint : (row.unread ? theme.accent : theme.textSecondary)) - .monospacedDigit() - .fixedSize() } } /// Project/machine in pinned and bucket sections; worktree name inside a - /// folder group. Routine activity lives on the icon badge. + /// folder group. Routine activity lives on the icon badge; the same name + /// that the H5 row shows (last two path components) keeps the two apps + /// readable side by side. private var detailLine: some View { - HStack(alignment: .center, spacing: 0) { + HStack(alignment: .center, spacing: 6) { if let snippet = row.contentSnippet { HStack(spacing: 4) { Image(systemName: "text.magnifyingglass") @@ -910,37 +918,37 @@ struct SessionRowView: View { .lineLimit(1) .accessibilityHidden(detailText == nil) } - Spacer(minLength: 12) + Spacer(minLength: 8) if let pullRequest = row.pullRequest { pullRequestBadge(pullRequest) } - if showsSpinner { - ProgressView() - .progressViewStyle(.circular) - .controlSize(.mini) - .tint(spinnerColor) - // Same slot as the attention symbols so rows align. + if row.showsWorkSpinner { + // Drawn, not a UIKit ProgressView: the system control stops + // animating when a List cell is reconfigured, which is why + // the old indicator looked stuck on many rows. + SessionSpinner(color: spinnerColor, lineWidth: max(1.3, metrics.statusSlotSize * 0.11)) .frame(width: metrics.statusSlotSize, height: metrics.statusSlotSize) .fixedSize() .layoutPriority(1) - .accessibilityLabel(Text("Running")) - } else if let status = row.status { - Image(systemName: status.symbolName) - .symbolVariant(.none) - .symbolRenderingMode(.monochrome) - .foregroundStyle(attentionColor) - // One slot keeps every attention symbol aligned. - .frame(width: metrics.statusSlotSize, height: metrics.statusSlotSize) - .fixedSize() - .layoutPriority(1) - .accessibilityLabel(statusAccessibilityText(status)) - } else if isArchived { + } + if isArchived { Image(systemName: "archivebox") + .font(.system(size: metrics.detailSize * 0.9)) .frame(width: metrics.statusSlotSize, height: metrics.statusSlotSize) .fixedSize() .layoutPriority(1) .accessibilityLabel(Text("Archived")) } + // Unread is a semibold title plus an accent timestamp, not a + // dot: the presence badge is the row's only dot. + // Minute ticks redraw only this label, not the list. + TimelineView(.periodic(from: .now, by: 60)) { context in + Text(verbatim: formatRelativeAge(now: context.date, thenEpochMs: row.summary.updatedAt)) + } + .font(.system(size: metrics.detailSize, weight: row.unread && !isArchived ? .semibold : .regular)) + .foregroundStyle(isArchived ? theme.textHint : (row.unread ? theme.link : theme.textSecondary)) + .monospacedDigit() + .fixedSize() } .font(.system(size: metrics.detailSize)) .foregroundStyle(isArchived ? theme.textHint : theme.textSecondary) @@ -972,12 +980,11 @@ struct SessionRowView: View { } /// Thinking rows get the green spinner; background-only work gets the - /// blue one. Pending attention keeps its symbol instead. - private var showsSpinner: Bool { - if row.status == nil && row.summary.thinking { return true } - return row.status == nil - && row.summary.active - && row.summary.backgroundTaskCount > 0 + /// blue one. Pending attention keeps its symbol beside the title and no + /// longer suppresses the spinner — a working session can wait for an + /// approval at the same time. + private var spinnerColor: Color { + row.summary.thinking ? theme.success : SessionPresenceBadge.backgroundWorkColor } /// Archived sessions stay in their directory section (so history remains @@ -992,10 +999,6 @@ struct SessionRowView: View { return row.unread ? Text("Unread") : Text(verbatim: "") } - private var spinnerColor: Color { - row.summary.thinking ? theme.success : theme.accent - } - private var detailText: String? { switch detail { case .projectMachine: diff --git a/ios/Hapi/Features/Sessions/SessionRowChrome.swift b/ios/Hapi/Features/Sessions/SessionRowChrome.swift new file mode 100644 index 00000000..d604279a --- /dev/null +++ b/ios/Hapi/Features/Sessions/SessionRowChrome.swift @@ -0,0 +1,75 @@ +import HapiUI +import SwiftUI + +/// Quiet activity indicator for session rows. +/// +/// `ProgressView` is a UIKit-backed control: inside a recycled `List` cell it +/// stops animating when the cell is reconfigured, which read as a spinner +/// that "often fails". A `repeatForever` animation is equally fragile here — +/// cell reuse can drop the implicit transaction mid-flight, leaving a frozen +/// arc. This view instead derives the rotation from the timeline: every tick +/// computes the angle from the current date, so no animation state can be +/// lost. 125 ms ticks mirror the web's low-rate indicator ticker (8 Hz). +/// Reduced Motion keeps a static arc rather than a frozen mid-turn frame. +struct SessionSpinner: View { + let color: Color + /// Web marks running work in green and background-only work in blue. + var lineWidth: CGFloat = 1.6 + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + /// One turn per 2 s, the same period as the old system spinner. + private static let turnDuration: TimeInterval = 2 + + var body: some View { + Group { + if reduceMotion { + ring(angle: 45) + } else { + TimelineView(.periodic(from: .now, by: 0.125)) { context in + ring(angle: Self.angle(at: context.date)) + } + } + } + .padding(lineWidth / 2) + .accessibilityLabel(Text("Running")) + } + + private func ring(angle: Double) -> some View { + ZStack { + Circle() + .stroke(color.opacity(0.25), lineWidth: lineWidth) + Circle() + .trim(from: 0, to: 0.3) + .stroke(color, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round)) + .rotationEffect(.degrees(angle)) + } + } + + private static func angle(at date: Date) -> Double { + let turns = date.timeIntervalSinceReferenceDate / turnDuration + return (turns - turns.rounded(.down)) * 360 + } +} + +/// Web `sessionShare.activeShort` pill: a session whose public share link is +/// currently active. +struct SessionSharedBadge: View { + @Environment(\.hapiTheme) private var theme + let size: CGFloat + + private var tint: Color { + theme.isDark ? Color(hex: 0x6EE7B7) : Color(hex: 0x047857) + } + + var body: some View { + Text("Shared") + .font(.system(size: size * 0.78, weight: .medium)) + .foregroundStyle(tint) + .padding(.horizontal, size * 0.34) + .padding(.vertical, size * 0.12) + .background(tint.opacity(0.12), in: Capsule()) + .fixedSize() + .accessibilityLabel(Text("Active share")) + } +} diff --git a/ios/HapiTests/SessionListFilterTests.swift b/ios/HapiTests/SessionListFilterTests.swift index f4524836..3a03b9df 100644 --- a/ios/HapiTests/SessionListFilterTests.swift +++ b/ios/HapiTests/SessionListFilterTests.swift @@ -48,7 +48,7 @@ final class SessionListFilterTests: XCTestCase { XCTAssertNil(model.activeMachineFilter) XCTAssertNil(model.filterSummary) XCTAssertEqual(model.rows.count, 1) - XCTAssertEqual(model.rows.first?.project, "hapi") + XCTAssertEqual(model.rows.first?.project, "workspace/hapi") } func testNamesCountsAndStableOrderIncludeHistoricalMachines() { @@ -83,11 +83,11 @@ final class SessionListFilterTests: XCTestCase { ]) let model = HomeFilterTestData.model(sessions: sessions) let options = model.machineFilters - XCTAssertTrue(model.rows.allSatisfy { $0.project == "hapi" }, "Machines remain in filters, not every row") + XCTAssertTrue(model.rows.allSatisfy { $0.project == "workspace/hapi" }, "Machines remain in filters, not every row") model.selectMachine("mac") XCTAssertTrue(model.filters.isActive) XCTAssertEqual(model.rows.map(\.id), ["a"]) - XCTAssertEqual(model.rows.first?.project, "hapi") + XCTAssertEqual(model.rows.first?.project, "workspace/hapi") XCTAssertEqual(model.filterSummary, "Machine: Machine · mac") model.selectMachine("mac") XCTAssertEqual(model.activeMachineFilter, "mac") diff --git a/ios/HapiTests/SessionRowStatusTests.swift b/ios/HapiTests/SessionRowStatusTests.swift index de627d81..fc6d4ffd 100644 --- a/ios/HapiTests/SessionRowStatusTests.swift +++ b/ios/HapiTests/SessionRowStatusTests.swift @@ -107,12 +107,12 @@ final class SessionRowStatusTests: XCTestCase { try await Task.sleep(for: .milliseconds(30)) XCTAssertFalse(model.rows[0].unread) XCTAssertEqual(model.rows[0].status, .needsApproval(2)) - XCTAssertEqual(model.rows[0].project, "hapi") + XCTAssertEqual(model.rows[0].project, "workspace/hapi") sessions.sessions[0].pendingRequestsCount = 0 sessions.sessions[0].pendingRequestKinds = [] XCTAssertNil(model.rows[0].status) - XCTAssertEqual(model.rows[0].project, "hapi") + XCTAssertEqual(model.rows[0].project, "workspace/hapi") sessions.sessions[0].thinking = true XCTAssertNil(model.rows[0].status) XCTAssertEqual(model.rows[0].presence, .working) @@ -128,17 +128,71 @@ final class SessionRowStatusTests: XCTestCase { XCTAssertNil(model.rows[0].project) } - func testProjectIsOnlyTheRepositoryNameIncludingWorktreesAndWindowsPaths() { + /// Working rows keep their spinner while a pending approval is shown; + /// web draws both (spinner in the meta cluster, request symbol by the + /// title). + func testWorkSpinnerCoexistsWithAttentionAndIgnoresDisconnection() { + func row(_ summary: SessionSummary) -> SessionRowUI { + SessionRowUI( + summary: summary, title: "t", project: nil, machine: nil, worktree: nil, + flavor: nil, unread: false, shared: false, + contentSnippet: nil, contentSearchTruncated: false + ) + } + var summary = HomeFilterTestData.summary("a", machine: nil) + summary.thinking = true + summary.pendingRequestsCount = 1 + summary.pendingRequestKinds = [.permission] + XCTAssertEqual(row(summary).status, .needsApproval(1)) + XCTAssertTrue(row(summary).showsWorkSpinner) + summary.thinking = false + summary.backgroundTaskCount = 2 + XCTAssertTrue(row(summary).showsWorkSpinner) + summary.backgroundTaskCount = 0 + XCTAssertFalse(row(summary).showsWorkSpinner) + summary.active = false + summary.backgroundTaskCount = 3 + XCTAssertFalse(row(summary).showsWorkSpinner, + "A disconnected session's stale background count is not work") + } + + /// Web `getGroupDisplayName`: the last two path components, so the row's + /// second line reads like the H5 sidebar (`Projects/hapi`). + func testProjectLabelIsTheLastTwoPathComponentsIncludingWorktreesAndWindowsPaths() { var summary = HomeFilterTestData.summary("a", machine: "mac") - XCTAssertEqual(SessionListModel.projectLabel(summary), "hapi") + XCTAssertEqual(SessionListModel.projectLabel(summary), "workspace/hapi") + summary.metadata?.path = "/workspace/Projects/hapi" + XCTAssertEqual(SessionListModel.projectLabel(summary), "Projects/hapi") summary.metadata?.path = "C:\\workspace\\hapi\\" - XCTAssertEqual(SessionListModel.projectLabel(summary), "hapi") + XCTAssertEqual(SessionListModel.projectLabel(summary), "workspace/hapi") summary.metadata?.path = "/tmp/checkouts/generated-branch" - summary.metadata?.worktree = .init(basePath: "/workspace/hapi", branch: "feature", name: "generated-branch") - XCTAssertEqual(SessionListModel.projectLabel(summary), "hapi") + summary.metadata?.worktree = .init(basePath: "/workspace/moras-orbit", branch: "feature", name: "generated-branch") + XCTAssertEqual(SessionListModel.projectLabel(summary), "workspace/moras-orbit", + "The owning project wins over the temporary checkout name") summary.metadata?.worktree = nil summary.metadata?.path = "/" XCTAssertNil(SessionListModel.projectLabel(summary)) + summary.metadata?.path = "hapi" + XCTAssertEqual(SessionListModel.projectLabel(summary), "hapi") + } + + func testRelativeAgeUsesTheH5Buckets() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + let ms = Int(now.timeIntervalSince1970 * 1000) + func bucket(_ offsetMs: Int) -> RelativeAgeBucket { + RelativeAgeBucket(now: now, thenEpochMs: ms - offsetMs) + } + XCTAssertEqual(bucket(30_000), .justNow) + XCTAssertEqual(bucket(5 * 60_000), .minutes(5)) + XCTAssertEqual(bucket(10 * 3_600_000), .hours(10)) + XCTAssertEqual(bucket(2 * 86_400_000), .days(2)) + // Seconds are accepted, like the web (`value < 1e12` ⇒ seconds). + XCTAssertEqual(RelativeAgeBucket(now: now, thenEpochMs: ms / 1000 - 5 * 60), .minutes(5)) + // A week or older shows the absolute day, as on web. + XCTAssertEqual(bucket(8 * 86_400_000), .absolute) + let old = formatRelativeAge(now: now, thenEpochMs: ms - 8 * 86_400_000) + XCTAssertEqual(old.count, 10, "Expected yyyy/MM/dd, got \(old)") + XCTAssertTrue(old.hasPrefix("20"), "Expected yyyy/MM/dd, got \(old)") } func testStatusCopyIsHumanFacing() { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift index 37700f8c..bdefc001 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift @@ -668,8 +668,23 @@ public final class ChatInteractor { public var queuedRows: [QueuedMessageRow] { guard let windowState else { return [] } let thinking = currentSessionState().thinking + // Web `steeringSupported` + `hasActiveSteeringTurn`: hide Steer for + // flavors that cannot take it, and require the provider's active-turn + // signal (`steeringActive`, or `thinking` for pi). + let detail = sessionStore.detail(for: sessionId) + let steeringActive: Bool = { + if let detail { + return SessionSteering.hasActiveTurn(detail) + } + let summary = sessionStore.sessions.first { $0.id == sessionId } + let flavor = summary?.metadata?.flavor?.lowercased() + return SessionSteering.isSupported(summary?.metadata) + && (flavor == "pi" ? summary?.thinking == true : false) + }() let queued = windowState.messages.filter { - $0.isQueuedForInvocation && $0.localId.map(directSendLocalIds.contains) != true + $0.isQueuedForInvocation + && !$0.queueDismissed + && $0.localId.map(directSendLocalIds.contains) != true } let sorted = queued.enumerated().sorted { lhs, rhs in let lhsScheduled = lhs.element.scheduledAt != nil @@ -690,7 +705,8 @@ public final class ChatInteractor { attachmentNames: preview.attachmentNames, scheduledAt: row.scheduledAt, canAct: canAct, - canSteer: canAct && thinking && row.scheduledAt == nil && row.status != .indeterminate, + canSteer: canAct && steeringActive && thinking + && row.scheduledAt == nil && row.status != .indeterminate, indeterminate: row.status == .indeterminate ) } @@ -698,13 +714,28 @@ public final class ChatInteractor { /// Cancel one queued message: optimistic removal, `DELETE`; an `invoked` /// answer means the agent already consumed it — ingest the authoritative - /// row as sent (web `useCancelQueuedMessage`). Errors restore the row. + /// row as sent (web `useCancelQueuedMessage`). A `busy` answer for an + /// already-indeterminate row hides it instead of restoring it (#1839): + /// the operator asked for it to go away, and the hub keeps the durable + /// record so a late consume can still settle it. public func cancelQueuedMessage(_ messageId: String) { Task { [weak self] in _ = await self?.cancelQueuedInternal(messageId) } } + /// Force-dismiss an indeterminate row without claiming cancellation (web + /// `queueDismissed`): the bar stops showing it, the row stays durable. + public func dismissQueuedMessage(_ messageId: String) { + Task { [weak self] in + guard let self else { return } + let store = await self.windowController() + guard let row = await store.state.messages.first(where: { $0.id == messageId }), + let localId = row.localId, row.status == .indeterminate else { return } + await store.markQueueDismissed(localIds: [localId]) + } + } + private enum CancelVerdict { case cancelled case invoked @@ -721,6 +752,7 @@ public final class ChatInteractor { queuedOpPending = true defer { queuedOpPending = false } let localId = row.localId ?? row.id + let wasIndeterminate = row.status == .indeterminate await store.removeMessage(localIdOrId: localId) do { switch try await api.cancelMessage(sessionId: sessionId, messageId: messageId) { @@ -730,7 +762,13 @@ public final class ChatInteractor { await store.applyCancelInvoked(localId: localId, message: WindowMessage(wire: message)) return .invoked case .busy: - await store.appendOptimistic(row.withDeliveryState("indeterminate")) + // A row that was already indeterminate was never going to be + // cancelled by the hub (the CLI still holds its reservation). + // Restoring it unchanged made the button look dead; keep it + // hidden with the queueDismissed hold instead (#1839). + await store.appendOptimistic( + row.withDeliveryState("indeterminate").withQueueDismissed(wasIndeterminate) + ) try? await store.reconcileQueuedState() return .busy } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionShareEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionShareEndpoints.swift index f89d86f5..e8a56f3c 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionShareEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionShareEndpoints.swift @@ -24,6 +24,13 @@ extension APIClient { return response.share } + /// `GET /api/session-shares` — active shares in this namespace, for the + /// list's "Shared" marks. + public func sessionShares() async throws -> [SessionShare] { + let response: SessionShareListResponse = try await request(.get, "/api/session-shares") + return response.shares.map(\.share) + } + public func revokeSessionShare(id: String) async throws { try await requestVoid( .delete, diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift index e47307fa..bb05e147 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift @@ -11,7 +11,7 @@ public final class DisplayPrefs { public static let listFontScaleKey = "settings.sessionListFontScale" public static let codeFontSizeKey = "settings.codeFontSize" - public static let listFontScales: [Double] = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3] + public static let listFontScales: [Double] = [0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3] public static let codeFontSizes: [Double] = [9, 11, 13, 15, 17] public static let defaultListFontScale = 1.0 diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift index 6d647a05..457aab8d 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift @@ -721,6 +721,14 @@ public actor MessageWindowController { persist() } + /// Hide an indeterminate row from the queued bar without deleting the + /// durable record (web `queueDismissed`, #1839). A late consume still + /// settles it into the transcript. + public func markQueueDismissed(localIds: [String]) { + update { MessageWindowLogic.markQueueDismissed($0, localIds: localIds) } + persist() + } + /// SSE `message-cancelled` / optimistic DELETE removal /// (web `removeOptimisticMessage`). public func removeMessage(localIdOrId: String) { diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift index 72c0dbc1..84fb9603 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift @@ -104,6 +104,10 @@ public struct AgentState: Codable, Equatable, Sendable { public var completedRequests: [String: AgentStateCompletedRequest]? /// Epoch ms when the agent started compacting its context; nil otherwise. public var contextCompactionStartedAt: Int? + /// Provider-reported active steerable turn (`steeringActive` in + /// `shared/src/schemas.ts`). Steer is offered only while this is true + /// (pi uses `thinking` instead). + public var steeringActive: Bool? public init( controlledByUser: Bool? = nil, @@ -111,7 +115,8 @@ public struct AgentState: Codable, Equatable, Sendable { requests: [String: AgentStateRequest]? = nil, completedRequests: [String: AgentStateCompletedRequest]? = nil, codexPlanProposalId: String? = nil, - contextCompactionStartedAt: Int? = nil + contextCompactionStartedAt: Int? = nil, + steeringActive: Bool? = nil ) { self.controlledByUser = controlledByUser self.startingMode = startingMode @@ -119,5 +124,6 @@ public struct AgentState: Codable, Equatable, Sendable { self.requests = requests self.completedRequests = completedRequests self.contextCompactionStartedAt = contextCompactionStartedAt + self.steeringActive = steeringActive } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift index 7e6467bb..ce1c1937 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift @@ -147,6 +147,11 @@ public struct SessionMetadata: Codable, Equatable, Sendable { public var copilotSessionId: String? public var piSessionId: String? public var dshSessionId: String? + /// Antigravity transport marker: only `"acp"` sessions can steer. + public var agyProtocol: String? + /// Cursor transport marker (`"acp"` / `"stream-json"`); steering is + /// gated on it (see `SessionSteering`). + public var cursorSessionProtocol: String? /// Pi model with its provider (`session.model` holds only the id). public var piSelectedModel: PiModelReference? /// User-message `localId`s with a native fork/rewind point. @@ -183,6 +188,8 @@ public struct SessionMetadata: Codable, Equatable, Sendable { copilotSessionId: String? = nil, piSessionId: String? = nil, dshSessionId: String? = nil, + agyProtocol: String? = nil, + cursorSessionProtocol: String? = nil, piSelectedModel: PiModelReference? = nil, conversationHistoryPoints: [String: Bool]? = nil, externalRefs: [ExternalRef]? = nil @@ -215,6 +222,8 @@ public struct SessionMetadata: Codable, Equatable, Sendable { self.copilotSessionId = copilotSessionId self.piSessionId = piSessionId self.dshSessionId = dshSessionId + self.agyProtocol = agyProtocol + self.cursorSessionProtocol = cursorSessionProtocol self.piSelectedModel = piSelectedModel self.conversationHistoryPoints = conversationHistoryPoints self.externalRefs = externalRefs diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionShare.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionShare.swift index e96504d8..011f8175 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionShare.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionShare.swift @@ -45,6 +45,26 @@ public struct SessionShareEnvelope: Codable, Equatable, Sendable { } } +/// One entry of `GET /api/session-shares`. The hub also returns the session +/// summary; the list only needs the share's session id, so the extra field is +/// deliberately not decoded. +public struct SessionShareListEntry: Codable, Equatable, Sendable { + public var share: SessionShare + + public init(share: SessionShare) { + self.share = share + } +} + +/// `GET /api/session-shares` — every active share in the namespace. +public struct SessionShareListResponse: Codable, Equatable, Sendable { + public var shares: [SessionShareListEntry] + + public init(shares: [SessionShareListEntry]) { + self.shares = shares + } +} + /// The browser-facing share URL: the hub origin plus the web app's /// `/shared-session/` route (web `buildSessionShareUrl`). A native /// client has no PWA origin of its own, so the hub origin is the share host. diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSteering.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSteering.swift new file mode 100644 index 00000000..aae139f1 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSteering.swift @@ -0,0 +1,67 @@ +import Foundation + +/// Which flavors accept a "Steer" (soft mid-turn delivery) — port of +/// `shared/src/modes.ts` `isSteeringSupportedForSession`. +/// +/// Native gating only: whether a turn is currently steerable is a separate +/// check (`Session.agentState.steeringActive` / `thinking`). The web hides the +/// Steer affordance entirely for unsupported flavors; showing it there only +/// produces a guaranteed hub error. +public enum SessionSteering { + /// Flavors with any steering capability. + private static let supportedFlavors: Set = [ + "agy", "claude", "codex", "cursor", "opencode", "pi", "dsh", + ] + + /// Session-aware gate. Cursor's legacy stream-json sessions advertise the + /// flavor but cannot steer; Antigravity only steers on `agy acp`. + public static func isSupported(_ metadata: SessionMetadata?) -> Bool { + isSupported( + flavor: metadata?.flavor, + agyProtocol: metadata?.agyProtocol, + cursorSessionProtocol: metadata?.cursorSessionProtocol, + cursorSessionId: metadata?.cursorSessionId + ) + } + + /// List-row gate: summaries carry only the flavor, so protocol markers + /// fall back to "unknown ⇒ supported", matching the web's compat fallback. + public static func isSupported(_ metadata: SessionSummaryMetadata?) -> Bool { + isSupported( + flavor: metadata?.flavor, + agyProtocol: nil, + cursorSessionProtocol: nil, + cursorSessionId: nil + ) + } + + static func isSupported( + flavor rawFlavor: String?, + agyProtocol: String?, + cursorSessionProtocol: String?, + cursorSessionId: String? + ) -> Bool { + guard let flavor = rawFlavor.map({ $0.lowercased() }) else { return false } + guard supportedFlavors.contains(flavor) else { return false } + switch flavor { + case "agy": + return agyProtocol == "acp" + case "cursor": + if cursorSessionProtocol == "stream-json" { return false } + return cursorSessionProtocol == "acp" || cursorSessionId == nil + default: + return true + } + } + + /// Whether the provider reports an active steerable turn. Follows the + /// per-flavor signal the web uses: `thinking` for pi, `steeringActive` + /// for everyone else. + public static func hasActiveTurn(_ session: Session?) -> Bool { + guard let session, isSupported(session.metadata) else { return false } + if session.metadata?.flavor?.lowercased() == "pi" { + return session.thinking + } + return session.agentState?.steeringActive == true + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageMerge.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageMerge.swift index 4f5de53d..e167b482 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageMerge.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageMerge.swift @@ -75,7 +75,14 @@ public enum MessageMerge { } else { replacement = message } - if byId.updateValue(replacement, forKey: message.id) == nil { + // Web `messages.ts`: a force-dismissed indeterminate row keeps its + // hold across refetches while it is still uninvoked and unknown. + let preserved = (current?.queueDismissed == true) + && replacement.invokedAtNumber == nil + && replacement.status == .indeterminate + ? replacement.withQueueDismissed(true) + : replacement + if byId.updateValue(preserved, forKey: message.id) == nil { order.append(message.id) } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift index 8f747eff..d8cac5f0 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift @@ -304,6 +304,20 @@ public enum MessageWindowLogic { trimLimit: Int = MessageWindowConstants.visibleWindowSize ) -> MessageWindowState { let retainedResponseMessages = responseMessages.filter { shouldRetainWindowMessage($0) } + // Web `applyLatestResponse`: a force-dismissed indeterminate row keeps + // its hold when the authoritative page re-delivers it (#1839). + let dismissedIds = Set( + previous.messages + .filter(\.queueDismissed) + .map(\.id) + ) + let retainedWithHolds = retainedResponseMessages.map { message in + dismissedIds.contains(message.id) + && message.invokedAtNumber == nil + && message.status == .indeterminate + ? message.withQueueDismissed(true) + : message + } let concurrentServerRows = previous.messages.filter { message in !message.isOptimistic && requestBaseline[message.id] !== message } @@ -312,7 +326,7 @@ public enum MessageWindowLogic { message.isOptimistic || requestBaseline[message.id] !== message } : previous.messages - let authoritative = MessageMerge.mergeMessages(preserved, retainedResponseMessages) + let authoritative = MessageMerge.mergeMessages(preserved, retainedWithHolds) let incoming = MessageMerge.mergeMessages(authoritative, concurrentServerRows) let trim = trimPreservingQueued( incoming, @@ -700,16 +714,38 @@ public enum MessageWindowLogic { public static func markRequeued( _ previous: MessageWindowState, localIds: [String] + ) -> MessageWindowState { if localIds.isEmpty { return previous } + let idSet = Set(localIds) + var changed = false + let messages = previous.messages.map { message -> WindowMessage in + guard let localId = message.localId, idSet.contains(localId), + message.status == .indeterminate || message.queueDismissed else { + return message + } + changed = true + // Web `markMessagesRequeued`: clearing the hold includes the + // force-dismiss, so a row that came back to the FIFO is visible. + return message.withStatus(.queued).withQueueDismissed(false) + } + return changed ? settingMessages(previous, messages) : previous + } + + /// Web `markMessagesIndeterminate` honouring the force-dismiss hold: an + /// already-hidden row stays hidden. + public static func markQueueDismissed( + _ previous: MessageWindowState, + localIds: [String] ) -> MessageWindowState { if localIds.isEmpty { return previous } let idSet = Set(localIds) var changed = false let messages = previous.messages.map { message -> WindowMessage in - guard let localId = message.localId, idSet.contains(localId), message.status == .indeterminate else { + guard let localId = message.localId, idSet.contains(localId), + message.status == .indeterminate, !message.queueDismissed else { return message } changed = true - return message.withStatus(.queued) + return message.withQueueDismissed(true) } return changed ? settingMessages(previous, messages) : previous } @@ -746,11 +782,15 @@ public enum MessageWindowLogic { } let needsStatus = message.status != .sent let needsInvokedAt = message.hasExplicitNullInvokedAt - if !needsStatus && !needsInvokedAt { return message } + let needsClearDismiss = message.queueDismissed + if !needsStatus && !needsInvokedAt && !needsClearDismiss { return message } changed = true var next = message if needsStatus { next = next.withStatus(.sent) } if needsInvokedAt { next = next.withInvokedAt(invokedAt) } + // Web `markMessagesConsumed` also clears the force-dismiss hold: + // the row now belongs to the transcript, not the bar. + if needsClearDismiss { next = next.withQueueDismissed(false) } return next } if !changed { return previous } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/WindowMessage.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/WindowMessage.swift index 7a23cc18..22e17f44 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/WindowMessage.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/WindowMessage.swift @@ -68,6 +68,11 @@ public final class WindowMessage: Sendable, Equatable { // MARK: Client-side public let status: MessageStatus? + /// Web `queueDismissed` (#1839): the operator cancelled an + /// already-indeterminate queued row. The row stays in the window (so a + /// late `messages-consumed` can still settle it into the transcript) but + /// is hidden from the queued bar. Cleared by requeue/consume. + public let queueDismissed: Bool public init( contentRevision: Int? = nil, @@ -78,7 +83,8 @@ public final class WindowMessage: Sendable, Equatable { createdAt: Int, invokedAt: InvokedAtField = .absent, scheduledAt: Int? = nil, - status: MessageStatus? = nil + status: MessageStatus? = nil, + queueDismissed: Bool = false ) { self.contentRevision = contentRevision self.id = id @@ -89,6 +95,7 @@ public final class WindowMessage: Sendable, Equatable { self.invokedAt = invokedAt self.scheduledAt = scheduledAt self.status = status + self.queueDismissed = queueDismissed } /// Wrap a wire row. `DecryptedMessage` collapses the invokedAt tri-state @@ -153,7 +160,7 @@ public final class WindowMessage: Sendable, Equatable { contentRevision: contentRevision, id: id, seq: seq, localId: localId, content: content, createdAt: createdAt, invokedAt: .number(invokedAt), - scheduledAt: scheduledAt, status: status + scheduledAt: scheduledAt, status: status, queueDismissed: queueDismissed ) } @@ -167,7 +174,18 @@ public final class WindowMessage: Sendable, Equatable { contentRevision: contentRevision, id: id, seq: seq, localId: localId, content: content, createdAt: createdAt, invokedAt: invokedAt, - scheduledAt: scheduledAt, status: status + scheduledAt: scheduledAt, status: status, queueDismissed: queueDismissed + ) + } + + /// Copy with the bar-dismissed hold set or cleared (web `queueDismissed`). + public func withQueueDismissed(_ dismissed: Bool) -> WindowMessage { + guard dismissed != queueDismissed else { return self } + return WindowMessage( + contentRevision: contentRevision, + id: id, seq: seq, localId: localId, content: content, + createdAt: createdAt, invokedAt: invokedAt, + scheduledAt: scheduledAt, status: status, queueDismissed: dismissed ) } @@ -198,6 +216,7 @@ extension WindowMessage: Codable { private enum CodingKeys: String, CodingKey { case contentRevision case id, seq, localId, content, createdAt, invokedAt, scheduledAt, status + case queueDismissed } public convenience init(from decoder: Decoder) throws { @@ -224,7 +243,8 @@ extension WindowMessage: Codable { // Unknown status strings degrade to nil (Android `fromWire`) — // a new client-side state must not break snapshot hydration. status: (try container.decodeIfPresent(String.self, forKey: .status)) - .flatMap(MessageStatus.init(rawValue:)) + .flatMap(MessageStatus.init(rawValue:)), + queueDismissed: try container.decodeIfPresent(Bool.self, forKey: .queueDismissed) ?? false ) } @@ -248,6 +268,7 @@ extension WindowMessage: Codable { } try container.encodeIfPresent(scheduledAt, forKey: .scheduledAt) try container.encodeIfPresent(status?.rawValue, forKey: .status) + if queueDismissed { try container.encode(true, forKey: .queueDismissed) } } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift index 5da0ea22..17a20024 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift @@ -775,6 +775,40 @@ struct ChatInteractorTests { #expect(harness.interactor.directSendLocalIds.isEmpty) } + /// Web #1839: cancelling an already-indeterminate row returns `busy` (the + /// CLI still holds it). The row must leave the bar anyway — restoring it + /// unchanged made Cancel/Retry appear dead. + @Test func cancelOnBusyIndeterminateRowHidesItInsteadOfRestoringIt() async throws { + let harness = try await ChatInteractionHarness() + await harness.window().ingestSSEMessages([ + WindowMessage(wire: queuedServerRow(id: "srv-9", localId: "l-9", text: "stuck")) + ]) + let window = await harness.window() + await window.markIndeterminate(localIds: ["l-9"]) + #expect(await eventually { + harness.interactor.queuedRows.contains { $0.id == "srv-9" && $0.indeterminate } + }) + + await harness.performer.script( + "DELETE", "/api/sessions/sess-1/messages/srv-9", + json: #"{"status":"busy","localId":"l-9"}"# + ) + harness.interactor.cancelQueuedMessage("srv-9") + + #expect(await eventually { harness.interactor.queuedRows.isEmpty }, + "A busy cancel on an indeterminate row leaves the bar") + // The durable row survives, still unknown, so a late consume settles it. + #expect(await eventually { + let row = await harness.row(localId: "l-9") + return row?.status == .indeterminate && row?.queueDismissed == true + }) + // Requeued means the delivery came back to the FIFO: visible again. + await window.markRequeued(localIds: ["l-9"]) + #expect(await eventually { + harness.interactor.queuedRows.contains { $0.id == "srv-9" && !$0.indeterminate } + }) + } + @Test func queuedCancelInvokedRaceIngestsTheAuthoritativeRowAsSent() async throws { let harness = try await ChatInteractionHarness() await harness.window().ingestSSEMessages([ @@ -800,7 +834,10 @@ struct ChatInteractorTests { } @Test func steerPostsAndAnInvokedAnswerReconcilesAMissedConsume() async throws { - let harness = try await ChatInteractionHarness(detail: chatDetail(thinking: true)) + let harness = try await ChatInteractionHarness(detail: chatDetail( + thinking: true, + agentState: AgentState(steeringActive: true) + )) await harness.window().ingestSSEMessages([ WindowMessage(wire: queuedServerRow(id: "srv-2", localId: "l-2", text: "steer me")) ]) diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift index 88dba6c1..36c73654 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift @@ -18,7 +18,7 @@ struct DisplayPrefsTests { let prefs = DisplayPrefs(defaults: defaults) #expect(prefs.listFontScale == 1.0) #expect(prefs.codeFontSize == 13.0) - #expect(DisplayPrefs.listFontScales == [0.8, 0.9, 1.0, 1.1, 1.2, 1.3]) + #expect(DisplayPrefs.listFontScales == [0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3]) #expect(DisplayPrefs.codeFontSizes == [9, 11, 13, 15, 17]) }