From 4387dc7f4a7cbcfc1c8e39c440d36c106ca3199d Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Tue, 1 Dec 2026 07:22:36 +0800 Subject: [PATCH] feat(ios): search message content and jump to the matched message Port the H5 content-search scope to the native session list: - The search field gains a Sessions/Content scope menu. Content mode debounces the hub's POST /sessions/content-search over the sessions visible under the current machine/status/unread filters, discards stale responses by generation, and surfaces loading, failure, and potentially-incomplete result states. - Result rows keep the two-line contract: the matched snippet (plus a truncation mark) replaces the project line, while server relevance order is preserved. - Tapping a hit passes its message id to the chat. A row already in the loaded transcript scrolls directly; otherwise the window controller loads the hub's bounded message-context page, enters history mode, and the chat scrolls/flashes the target. "Back to latest" still resets to the live tail because a context window is explicitly not the tail. Adds content-search wire models, endpoint coverage, context-window transition tests, and session-list model tests for scoping and rendering. via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- ios/Hapi/Features/Chat/ChatModel.swift | 83 +++++++ ios/Hapi/Features/Chat/ChatView.swift | 58 ++--- ios/Hapi/Features/Home/HomeView.swift | 78 +++++-- .../Features/Sessions/SessionListModel.swift | 211 +++++++++++++++--- .../Features/Sessions/SessionListView.swift | 41 +++- ios/Hapi/Models/ChatSession.swift | 7 + ios/Hapi/Resources/Localizable.xcstrings | 121 ++++++++++ ios/HapiTests/ContentSearchModelTests.swift | 125 +++++++++++ .../Endpoints/SessionEndpoints.swift | 19 ++ .../Stores/MessageWindowController.swift | 26 +++ .../Models/SessionContentSearch.swift | 57 +++++ .../Window/MessageWindowLogic.swift | 37 +++ .../EndpointRequestTests.swift | 21 ++ .../MessageWindowControllerTests.swift | 59 +++++ 14 files changed, 873 insertions(+), 70 deletions(-) create mode 100644 ios/HapiTests/ContentSearchModelTests.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionContentSearch.swift diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index 67db67bd..ee76d053 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -8,6 +8,18 @@ import UIKit import UniformTypeIdentifiers /// Chat top-bar state: title cascade + status dot + meta line. +/// A message-content search hit to reveal once its transcript row exists. +struct ChatSearchTarget: Equatable { + let messageId: String + let query: String +} + +/// One-shot navigation target carried into a chat by the list/home layer. +enum ChatOpenTarget: Equatable { + case pending(ChatPendingFocus) + case search(ChatSearchTarget) +} + struct ChatHeaderUI: Equatable { var title: String /// "Flavor · machine · worktree" meta line; nil when nothing is known. @@ -241,6 +253,9 @@ final class ChatModel { /// Jump requested by a notification tap or session-row attention icon /// before the detail (and its request dictionary) was loaded. @ObservationIgnored private var deferredPendingFocus: ChatPendingFocus? + /// Content-search hit waiting for the context replace to reach the pipeline. + @ObservationIgnored private var deferredSearchTarget: ChatSearchTarget? + @ObservationIgnored private var searchFocusTask: Task? /// Route a pending-request selection to the bottom panel (async input) or /// to its correlated transcript row (blocking permission / inline question). @@ -298,6 +313,70 @@ final class ChatModel { } } + /// Reveal a content-search hit. When the row is already loaded this is a + /// direct scroll; otherwise load the hub's bounded context around the + /// message (content search can reach far outside the tail window). + func requestSearchFocus(_ target: ChatSearchTarget) { + searchFocusTask?.cancel() + if focusLoadedSearchTarget(target) { return } + searchFocusTask = Task { [weak self] in + guard let self else { return } + // ChatSession opens the window asynchronously after onAppear. + for _ in 0..<30 where self.chat.windowController == nil { + try? await Task.sleep(for: .milliseconds(100)) + if Task.isCancelled { return } + } + guard let controller = self.chat.windowController else { return } + let loaded = await controller.focusMessage(target.messageId) + guard !Task.isCancelled, self.isActive else { return } + if loaded { + self.deferredSearchTarget = target + // The context replace may already have published before this + // task resumed; make sure one apply resolves the target. + self.scheduleRecompute() + } else { + self.showNotice(String(localized: "This match is outside the loaded conversation. Scroll up to load it.")) + } + } + } + + /// Returns true when the hit was already in the loaded transcript. + private func focusLoadedSearchTarget(_ target: ChatSearchTarget) -> Bool { + guard let block = blocks.first(where: { $0.stableId == target.messageId }) else { + return false + } + focusRow(block.stableId) + return true + } + + private func resolveDeferredSearchTarget() { + guard let target = deferredSearchTarget, !isInitialLoading else { return } + deferredSearchTarget = nil + if focusLoadedSearchTarget(target) { return } + if let match = blocks.last(where: { + searchableText($0).localizedCaseInsensitiveContains(target.query) + }) { + focusRow(match.stableId) + return + } + showNotice(String(localized: "This match is outside the loaded conversation. Scroll up to load it.")) + } + + private func searchableText(_ visible: VisibleChatBlock) -> String { + guard case .block(let block) = visible else { return "" } + switch block { + case .userText(let user): return user.text + case .agentText(let agent): return agent.text + default: return "" + } + } + + private func focusRow(_ id: String) { + scrollTargetRowID = id + scrollTargetToken += 1 + flashRow(id) + } + func clearPendingQuestionTarget() { pendingQuestionTargetID = nil } @@ -561,6 +640,9 @@ final class ChatModel { jumpTask?.cancel() jumpTask = nil isJumpingToLatest = false + searchFocusTask?.cancel() + searchFocusTask = nil + deferredSearchTarget = nil noticeTask?.cancel() noticeTask = nil // Discard an in-flight take — the mic must not stay hot off-screen @@ -920,6 +1002,7 @@ final class ChatModel { renderedReadState = SessionReadState.merge(detail?.readState, summary?.readState) // After isInitialLoading settles: a blocking target waits for rows. resolveDeferredPendingFocus(hasDetail: detail != nil) + resolveDeferredSearchTarget() } // MARK: - Header derivation (Android `buildHeader` port) diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index 855d955d..383e30c4 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -41,12 +41,13 @@ struct ChatView: View { /// Resume/reopen handed back a superseding session id — the host swaps /// its navigation entry (HomeView replaces the path element). private let onNavigateToSession: ((String) -> Void)? - /// Pending-request jump carried in by a notification tap or a session-row - /// attention icon. `token` re-fires when the same session is already open - /// in a split view; the host clears the request after consumption. - private let pendingFocus: ChatPendingFocus? - private let pendingFocusToken: UUID? - private let onPendingFocusConsumed: (() -> Void)? + /// One-shot jump carried in by a notification tap, a session-row + /// attention icon, or a content-search hit. `token` re-fires when the + /// same session is already open in a split view; the host clears the + /// request after consumption. + private let openTarget: ChatOpenTarget? + private let openTargetToken: UUID? + private let onOpenTargetConsumed: (() -> Void)? /// Kept for the files/viewer pushes (the model owns its own reference). private let session: HubSession @@ -71,17 +72,17 @@ struct ChatView: View { session: HubSession, sessionId: String, onNavigateToSession: ((String) -> Void)? = nil, - pendingFocus: ChatPendingFocus? = nil, - pendingFocusToken: UUID? = nil, - onPendingFocusConsumed: (() -> Void)? = nil + openTarget: ChatOpenTarget? = nil, + openTargetToken: UUID? = nil, + onOpenTargetConsumed: (() -> Void)? = nil ) { self.init( session: session, model: ChatModel(session: session, sessionId: sessionId), onNavigateToSession: onNavigateToSession, - pendingFocus: pendingFocus, - pendingFocusToken: pendingFocusToken, - onPendingFocusConsumed: onPendingFocusConsumed + openTarget: openTarget, + openTargetToken: openTargetToken, + onOpenTargetConsumed: onOpenTargetConsumed ) } @@ -89,18 +90,18 @@ struct ChatView: View { session: HubSession, model: ChatModel, onNavigateToSession: ((String) -> Void)? = nil, - pendingFocus: ChatPendingFocus? = nil, - pendingFocusToken: UUID? = nil, - onPendingFocusConsumed: (() -> Void)? = nil + openTarget: ChatOpenTarget? = nil, + openTargetToken: UUID? = nil, + onOpenTargetConsumed: (() -> Void)? = nil ) { _model = State(initialValue: model) _configModel = State(initialValue: SessionConfigModel(interactor: model.interactor)) self.session = session self.sessionId = model.sessionId self.onNavigateToSession = onNavigateToSession - self.pendingFocus = pendingFocus - self.pendingFocusToken = pendingFocusToken - self.onPendingFocusConsumed = onPendingFocusConsumed + self.openTarget = openTarget + self.openTargetToken = openTargetToken + self.onOpenTargetConsumed = onOpenTargetConsumed } private var content: some View { @@ -120,14 +121,19 @@ struct ChatView: View { ChatTranscriptView(model: model) } } - // A notification tap or row attention icon can target this chat - // before its detail loads; the model keeps the jump queued until the - // request dictionary arrives. `token` covers the same session already - // being open in a split view. - .task(id: pendingFocusToken) { - guard let pendingFocus else { return } - model.requestPendingFocus(pendingFocus) - onPendingFocusConsumed?() + // A notification tap, row attention icon, or content-search hit can + // target this chat before its data loads; the model keeps the jump + // queued until it can resolve. `token` covers the same session + // already being open in a split view. + .task(id: openTargetToken) { + guard let openTarget else { return } + switch openTarget { + case .pending(let focus): + model.requestPendingFocus(focus) + case .search(let target): + model.requestSearchFocus(target) + } + onOpenTargetConsumed?() } .sheet(isPresented: $outlineOpen) { ConversationOutlineSheet(items: model.conversationOutline) { id in diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index df8372d3..4f385d00 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -15,11 +15,11 @@ private struct NewSessionSeed: Identifiable { let directory: String } -/// One-shot pending-request jump handed to a chat. `token` makes a repeat +/// One-shot navigation target handed to a chat. `token` makes a repeat /// request for the session already open in the split detail fire again. private struct ChatOpenFocus: Equatable { let sessionId: String - let target: ChatPendingFocus + let target: ChatOpenTarget let token: UUID } @@ -34,8 +34,8 @@ struct HomeView: View { @State private var showSettings = false @State private var path: [String] = [] @State private var tabletNavigation = SessionNavigationState() - /// Pending request to reveal when the chat appears (notification tap or - /// row attention icon). Cleared by the chat after it hands it to its model. + /// Pending request or content-search hit to reveal when the chat appears. + /// Cleared by the chat after it hands it to its model. @State private var chatOpenFocus: ChatOpenFocus? /// Transient connection states show only after `connectionRevealDelay`: /// a foreground reconnect usually finishes first (Telegram-style). @@ -264,15 +264,53 @@ struct HomeView: View { .accessibilityIdentifier("home.settings") } + private var searchPrompt: LocalizedStringKey { + listModel.searchScope == .content ? "Search messages" : "Search sessions" + } + + private var searchScopeLabel: LocalizedStringKey { + listModel.searchScope == .content ? "Content" : "Sessions" + } + private var searchOverlay: some View { HStack(spacing: 8) { + Menu { + Button { + listModel.searchScope = .metadata + } label: { + Label("Search session names", systemImage: "textformat") + } + Button { + listModel.searchScope = .content + } label: { + Label("Search message content", systemImage: "text.magnifyingglass") + } + } label: { + HStack(spacing: 2) { + Text(searchScopeLabel) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .semibold)) + } + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + } + .fixedSize() + Divider().frame(height: 16) Image(systemName: "magnifyingglass") .foregroundStyle(.secondary) - TextField("Search sessions", text: $listModel.searchQuery) + TextField(searchPrompt, text: $listModel.searchQuery) .focused($searchFocused) .textInputAutocapitalization(.never) .autocorrectionDisabled() .submitLabel(.search) + if listModel.contentSearchLoading { + ProgressView().controlSize(.small) + } else if listModel.contentSearchFailed { + Image(systemName: "exclamationmark.triangle.fill") + .font(.caption) + .foregroundStyle(.orange) + .accessibilityLabel(Text("Content search failed")) + } if !listModel.searchQuery.isEmpty { Button { listModel.searchQuery = "" @@ -300,14 +338,28 @@ struct HomeView: View { listModel.searchQuery = "" } - /// Opening a row that still has a pending request lands on it. The - /// attention icon is part of the row, so a tap there follows the same - /// path; an explicit `focus` (notification request id) wins. + /// Opening a content-search hit lands on the matched message; opening a + /// row that still has a pending request (the attention icon is part of + /// the row) lands on that request; an explicit notification request id + /// wins over the row's own attention. private func openSession(_ sessionId: String, focus: ChatPendingFocus? = nil) { + // Capture the match before closing search clears the query/response. + let searchTarget = listModel.contentSearchMatch(for: sessionId).map { + ChatSearchTarget(messageId: $0.messageId, query: listModel.searchQuery) + } if searchOpen { closeSearch() } - let target = focus ?? pendingFocusForRow(sessionId) + let target: ChatOpenTarget? + if let searchTarget { + target = .search(searchTarget) + } else if let focus { + target = .pending(focus) + } else if let pending = pendingFocusForRow(sessionId) { + target = .pending(pending) + } else { + target = nil + } chatOpenFocus = target.map { ChatOpenFocus(sessionId: sessionId, target: $0, token: UUID()) } @@ -340,10 +392,10 @@ struct HomeView: View { } // A late response from a chat already left must not steal focus. }, - pendingFocus: focus?.target, - pendingFocusToken: focus?.token, - onPendingFocusConsumed: { - // A newer request (possibly for another session) is not ours. + openTarget: focus?.target, + openTargetToken: focus?.token, + onOpenTargetConsumed: { + // A newer target (possibly for another session) is not ours. if chatOpenFocus?.token == focus?.token { chatOpenFocus = nil } diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index c31b15ee..6e9b8e5b 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -30,6 +30,10 @@ struct SessionRowUI: Identifiable, Equatable { } /// Only a running job is shown; finished ones leave no trace on the row. var runningJob: AttachedJob? { summary.runningAttachedJob } + /// Message-content search context; replaces the project line while a + /// content query is active (the row keeps its two-line contract). + var contentSnippet: String? + var contentSearchTruncated: Bool } extension SessionSummary { @@ -250,6 +254,13 @@ enum SessionListStatus: Hashable { } } +/// Search scope: the local title/project/machine index, or the hub's opt-in +/// message-content index. +enum SessionSearchScope: String, Equatable { + case metadata + case content +} + /// Transient, per-home filters. Add future dimensions here, not to navigation. /// Ordering is a persisted preference instead (`SessionListOrderPrefs`). struct SessionListFilters: Equatable, Hashable { @@ -278,11 +289,34 @@ final class SessionListModel { /// Reopen follows a superseding id with the composer draft (web /// `transferComposerDraftThenNavigate`). private let drafts: (any ChatDrafts)? + /// Hub message-content search; nil in tests that only exercise the local + /// metadata index. + private let contentSearch: ((String, [String]) async throws -> SessionContentSearchResponse)? /// Not persisted: a new home / hub starts with all sessions. - private(set) var filters = SessionListFilters() + private(set) var filters = SessionListFilters() { + didSet { + if filters != oldValue, isContentSearchActive { + scheduleContentSearch(immediate: true) + } + } + } /// Text search (`.searchable`); ranks by relevance while non-blank. - var searchQuery = "" + var searchQuery = "" { + didSet { + if searchQuery != oldValue { scheduleContentSearch() } + } + } + var searchScope: SessionSearchScope = .metadata { + didSet { + if searchScope != oldValue { scheduleContentSearch(immediate: true) } + } + } + private(set) var contentSearchResponse: SessionContentSearchResponse? + private(set) var contentSearchLoading = false + private(set) var contentSearchFailed = false + @ObservationIgnored private var contentSearchTask: Task? + @ObservationIgnored private var contentSearchGeneration = 0 /// The split detail's session stays listed under the unread lens. var selectedSessionId: String? private(set) var isRefreshing = false @@ -296,10 +330,18 @@ final class SessionListModel { var actionError: String? convenience init(session: HubSession) { + let api = session.api self.init( sessionStore: session.sessionStore, machineStore: session.machineStore, lastSeenStore: session.lastSeenStore, orderPrefs: .shared, hubUrl: session.hubUrl, - drafts: UserDefaultsChatDrafts(scope: session.hubUrl) + drafts: UserDefaultsChatDrafts(scope: session.hubUrl), + contentSearch: { query, sessionIds in + try await api.searchSessionContent( + query: query, + sessionIds: sessionIds, + limit: min(100, max(50, sessionIds.count)) + ) + } ) } @@ -312,7 +354,8 @@ final class SessionListModel { personalPins: PersonalPinStore = .shared, orderPrefs: SessionListOrderPrefs? = nil, hubUrl: String, - drafts: (any ChatDrafts)? = nil + drafts: (any ChatDrafts)? = nil, + contentSearch: ((String, [String]) async throws -> SessionContentSearchResponse)? = nil ) { self.sessionStore = sessionStore self.machineStore = machineStore @@ -321,6 +364,7 @@ final class SessionListModel { self.orderPrefs = orderPrefs ?? SessionListOrderPrefs(defaults: nil) self.hubUrl = hubUrl self.drafts = drafts + self.contentSearch = contentSearch } // MARK: - Derived state @@ -409,8 +453,25 @@ final class SessionListModel { /// Filters or a non-default order: the menu button is tinted. var isCustomized: Bool { hasActiveFilters || !order.isDefault } + var isContentSearchActive: Bool { + searchScope == .content + && !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + var isSearching: Bool { - !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + if searchScope == .content { return isContentSearchActive } + return !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + /// The hub match behind a content-search row (nil in metadata scope). + func contentSearchMatch(for sessionId: String) -> SessionContentMatch? { + guard isContentSearchActive else { return nil } + return contentSearchResponse?.results.first { $0.session.id == sessionId }?.match + } + + /// The hub may omit content hidden by an indexing optimization. + var contentSearchIncomplete: Bool { + isContentSearchActive && contentSearchResponse?.hasPotentiallyIncompleteResults == true } /// Never render an invalid filter, even before the view reconciles it. @@ -508,6 +569,34 @@ final class SessionListModel { /// order as tie-break as on web, keeping pin sections so the Pinned header /// still applies. var rows: [SessionRowUI] { + if isContentSearchActive { return contentSearchRows() } + let readState = lastSeenStore.state + let followedTails = lastSeenStore.followedTails + var visible = filteredSessions() + if isSearching { + let labels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) + if let index = SessionListSearch.scoreIndex(sessions: visible, query: searchQuery, machineLabel: { id in + labels[id ?? unknownMachineFilterId] ?? "" + }) { + visible = SessionListSearch.rank(visible, by: index) + } + } else if order != .base { + // The store already keeps the base order. + visible = sortSessionSummaries(visible, order: order) + } + let machineLabels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) + return visible.map { summary in + makeRow( + summary, + machineLabels: machineLabels, + unread: LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) + ) + } + } + + /// Machine → status → unread lens. Text ranking is applied on top; the + /// content-search request is scoped to the same visible set. + private func filteredSessions() -> [SessionSummary] { let readState = lastSeenStore.state let followedTails = lastSeenStore.followedTails let activeFilter = activeMachineFilter @@ -524,34 +613,100 @@ final class SessionListModel { || LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) } } - if isSearching { - let labels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) - if let index = SessionListSearch.scoreIndex(sessions: visible, query: searchQuery, machineLabel: { id in - labels[id ?? unknownMachineFilterId] ?? "" - }) { - visible = SessionListSearch.rank(visible, by: index) - } - } else if order != .base { - // The store already keeps the base order. - visible = sortSessionSummaries(visible, order: order) - } + return visible + } + + private func makeRow( + _ summary: SessionSummary, + machineLabels: [String: String], + unread: Bool, + snippet: String? = nil, + truncated: Bool = false + ) -> SessionRowUI { + let worktree = summary.metadata?.worktree?.name + .trimmingCharacters(in: .whitespacesAndNewlines) + return SessionRowUI( + summary: summary, + title: Self.sessionTitle(summary), + project: Self.projectLabel(summary), + machine: summary.metadata?.machineId.flatMap { machineLabels[$0] } + ?? machineLabels[unknownMachineFilterId], + worktree: worktree?.isEmpty == false ? worktree : nil, + flavor: summary.metadata?.flavor, + unread: unread, + contentSnippet: snippet, + contentSearchTruncated: truncated + ) + } + + /// Server-ordered content hits. The response's own summaries replace the + /// locally cached rows (a hit may be older than the capped local list), + /// while the configured filters were already applied to the request's id + /// scope. + private func contentSearchRows() -> [SessionRowUI] { + guard let response = contentSearchResponse else { return [] } + let readState = lastSeenStore.state + let followedTails = lastSeenStore.followedTails let machineLabels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) - return visible.map { summary in - let worktree = summary.metadata?.worktree?.name - .trimmingCharacters(in: .whitespacesAndNewlines) - return SessionRowUI( - summary: summary, - title: Self.sessionTitle(summary), - project: Self.projectLabel(summary), - machine: summary.metadata?.machineId.flatMap { machineLabels[$0] } - ?? machineLabels[unknownMachineFilterId], - worktree: worktree?.isEmpty == false ? worktree : nil, - flavor: summary.metadata?.flavor, - unread: LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) + return response.results.map { result in + makeRow( + result.session, + machineLabels: machineLabels, + unread: LastSeenStore.isUnread(result.session, state: readState, followedTails: followedTails), + snippet: result.match.snippet, + truncated: result.match.truncated ) } } + /// Debounced hub content search over the currently visible sessions. The + /// generation guard keeps a slow response for an older query from + /// replacing a newer one. + private func scheduleContentSearch(immediate: Bool = false) { + contentSearchTask?.cancel() + contentSearchGeneration += 1 + let generation = contentSearchGeneration + guard isContentSearchActive, let contentSearch else { + contentSearchResponse = nil + contentSearchLoading = false + contentSearchFailed = false + return + } + contentSearchResponse = nil + contentSearchFailed = false + contentSearchLoading = true + let query = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) + let sessionIds = filteredSessions().map(\.id) + guard !sessionIds.isEmpty else { + contentSearchResponse = SessionContentSearchResponse( + results: [], + hasPotentiallyIncompleteResults: false + ) + contentSearchLoading = false + return + } + contentSearchTask = Task { [weak self] in + if !immediate { + try? await Task.sleep(for: .milliseconds(300)) + } + guard !Task.isCancelled else { return } + do { + let response = try await contentSearch(query, sessionIds) + guard let self, !Task.isCancelled, + self.contentSearchGeneration == generation else { return } + self.contentSearchResponse = response + self.contentSearchLoading = false + self.contentSearchFailed = false + } catch { + guard let self, !Task.isCancelled, + self.contentSearchGeneration == generation else { return } + self.contentSearchResponse = nil + self.contentSearchLoading = false + self.contentSearchFailed = true + } + } + } + /// Distinct existing group names for the quick-pick group menu. var existingGroupNames: [String] { let names = sessionStore.sessions.compactMap { summary -> String? in diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index 7cc947af..d71c49af 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -80,8 +80,18 @@ struct SessionListView: View { sessionList } .safeAreaInset(edge: .top, spacing: 0) { - if let summary = model.filterSummary { - SessionFilterSummary(summary: summary, onClear: model.clearFilters) + VStack(spacing: 0) { + if let summary = model.filterSummary { + SessionFilterSummary(summary: summary, onClear: model.clearFilters) + } + if model.contentSearchIncomplete { + Text("Some matches may be missing for this query.") + .font(.system(size: metrics.detailSize)) + .foregroundStyle(theme.warning) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 4) + } } } .onChange(of: model.machineFilterIds, initial: true) { _, _ in @@ -683,6 +693,18 @@ struct SessionListView: View { } description: { Text("Pull to retry once you are back online.") } + } else if model.contentSearchLoading { + ContentUnavailableView { + Label("Searching conversation history…", systemImage: "text.magnifyingglass") + } description: { + Text("This can take a moment on a large hub.") + } + } else if model.contentSearchFailed { + ContentUnavailableView { + Label("Content search failed", systemImage: "exclamationmark.triangle") + } description: { + Text("Pull to retry, or switch to session search.") + } } else if model.isSearching { ContentUnavailableView.search(text: model.searchQuery) } else if model.hasActiveFilters { @@ -866,7 +888,20 @@ struct SessionRowView: View { /// folder group. Routine activity lives on the icon badge. private var detailLine: some View { HStack(alignment: .center, spacing: 0) { - if let job = row.runningJob { + if let snippet = row.contentSnippet { + HStack(spacing: 4) { + Image(systemName: "text.magnifyingglass") + .font(.system(size: metrics.detailSize * 0.85)) + .accessibilityHidden(true) + Text(verbatim: snippet) + .lineLimit(1) + if row.contentSearchTruncated { + Image(systemName: "info.circle") + .font(.system(size: metrics.detailSize * 0.8)) + .accessibilityLabel(Text("The indexed message was truncated")) + } + } + } else if let job = row.runningJob { AttachedJobLine(job: job) } else { // Keep the same text line height when metadata is missing, diff --git a/ios/Hapi/Models/ChatSession.swift b/ios/Hapi/Models/ChatSession.swift index 8d815c04..aa0271ce 100644 --- a/ios/Hapi/Models/ChatSession.swift +++ b/ios/Hapi/Models/ChatSession.swift @@ -116,6 +116,13 @@ final class ChatSession { if !preservingHistory { Task { await controller.syncTail() } } } + /// Content-search jump: replace the window with the hub's bounded context + /// around one message. False when the message no longer resolves. + func focusMessage(_ messageId: String) async -> Bool { + guard let controller = windowController else { return false } + return await controller.focusMessage(messageId) + } + /// Tears the session pipe down; the engine-side resume cursor is saved /// so a reopened chat for this session resumes where it left off. /// Idempotent — both the view's disappear and a hub shutdown call it. diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 10491541..82f09484 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -7212,6 +7212,17 @@ } } }, + "This match is outside the loaded conversation. Scroll up to load it." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "这个匹配不在已加载的会话中,请向上滚动加载。" + } + } + } + }, "This request is outside the loaded conversation. Scroll up to load it." : { "extractionState" : "manual", "localizations" : { @@ -8973,6 +8984,17 @@ } } }, + "Pull to retry, or switch to session search." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "下拉重试,或切换到会话搜索。" + } + } + } + }, "Pull to retry once you are back online." : { "extractionState" : "manual", "localizations" : { @@ -10219,6 +10241,28 @@ } } }, + "Search message content" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索消息内容" + } + } + } + }, + "Search messages" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索消息" + } + } + } + }, "Search prompts" : { "extractionState" : "manual", "localizations" : { @@ -10230,6 +10274,17 @@ } } }, + "Search session names" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索会话名称" + } + } + } + }, "Search sessions" : { "extractionState" : "manual", "localizations" : { @@ -10247,6 +10302,28 @@ } } }, + "Searching conversation history…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在搜索对话历史…" + } + } + } + }, + "This can take a moment on a large hub." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 较大时可能需要一点时间。" + } + } + } + }, "Searching directories…" : { "extractionState" : "manual", "localizations" : { @@ -11063,6 +11140,17 @@ } } }, + "Some matches may be missing for this query." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查询可能缺少部分匹配结果。" + } + } + } + }, "Sort & Filter" : { "extractionState" : "manual", "localizations" : { @@ -11658,6 +11746,17 @@ } } }, + "The indexed message was truncated" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已索引的消息被截断" + } + } + } + }, "The selected Agent is not available on this machine." : { "extractionState" : "manual", "localizations" : { @@ -13869,6 +13968,28 @@ } } }, + "Content" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "内容" + } + } + } + }, + "Content search failed" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "内容搜索失败" + } + } + } + }, "Context" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/ContentSearchModelTests.swift b/ios/HapiTests/ContentSearchModelTests.swift new file mode 100644 index 00000000..225782c4 --- /dev/null +++ b/ios/HapiTests/ContentSearchModelTests.swift @@ -0,0 +1,125 @@ +import HapiClient +import XCTest +@testable import Hapi +@testable import HapiProtocol + +@MainActor +final class ContentSearchModelTests: XCTestCase { + private actor Probe { + private(set) var queries: [String] = [] + private(set) var idLists: [[String]] = [] + + func record(query: String, ids: [String]) { + queries.append(query) + idLists.append(ids) + } + } + + private func waitUntil( + _ condition: @escaping @MainActor () -> Bool + ) async throws { + for _ in 0..<60 { + if condition() { return } + try await Task.sleep(for: .milliseconds(50)) + } + XCTFail("condition did not settle") + } + + func testContentScopeScopesTheRequestAndRendersServerOrder() async throws { + let sessions = HomeFilterTestSessions([ + HomeFilterTestData.summary("a", machine: "mac"), + HomeFilterTestData.summary("b", machine: "mac"), + HomeFilterTestData.summary("c", machine: "debian"), + ]) + let probe = Probe() + let matchA = SessionContentMatch( + messageId: "m-a", + role: "user", + seq: 10, + createdAt: 100, + snippet: "…needle in a…", + truncated: false + ) + let matchB = SessionContentMatch( + messageId: "m-b", + role: "assistant", + seq: 20, + createdAt: 200, + snippet: "…needle in b…", + truncated: true + ) + let response = SessionContentSearchResponse( + results: [ + SessionContentSearchResult( + session: HomeFilterTestData.summary("b", machine: "mac"), + match: matchB + ), + SessionContentSearchResult( + session: HomeFilterTestData.summary("a", machine: "mac"), + match: matchA + ), + ], + hasPotentiallyIncompleteResults: false + ) + let model = SessionListModel( + sessionStore: sessions, + machineStore: HomeFilterTestMachines(), + lastSeenStore: LastSeenStore(), + hubUrl: "test", + contentSearch: { query, ids in + await probe.record(query: query, ids: ids) + return response + } + ) + + model.searchScope = .content + model.searchQuery = "needle" + try await waitUntil { !model.contentSearchLoading && model.contentSearchResponse != nil } + + let recorded = await probe.queries + XCTAssertEqual(recorded, ["needle"]) + let ids = await probe.idLists.first ?? [] + XCTAssertEqual(Set(ids), ["a", "b", "c"]) + XCTAssertEqual(model.rows.map(\.id), ["b", "a"], "Server relevance order wins") + XCTAssertEqual(model.rows.first?.contentSnippet, "…needle in b…") + XCTAssertEqual(model.rows.first?.contentSearchTruncated, true) + XCTAssertEqual(model.contentSearchMatch(for: "a")?.messageId, "m-a") + XCTAssertTrue(model.isSearching) + + // Back to metadata scope: the hub search state is discarded. + model.searchScope = .metadata + XCTAssertNil(model.contentSearchResponse) + XCTAssertNil(model.contentSearchMatch(for: "a")) + model.searchQuery = "" + XCTAssertFalse(model.isSearching) + } + + func testContentScopeScopesTheRequestToTheActiveMachineFilter() async throws { + let sessions = HomeFilterTestSessions([ + HomeFilterTestData.summary("a", machine: "mac"), + HomeFilterTestData.summary("b", machine: "debian"), + ]) + let probe = Probe() + let model = SessionListModel( + sessionStore: sessions, + machineStore: HomeFilterTestMachines(), + lastSeenStore: LastSeenStore(), + hubUrl: "test", + contentSearch: { query, ids in + await probe.record(query: query, ids: ids) + return SessionContentSearchResponse( + results: [], + hasPotentiallyIncompleteResults: false + ) + } + ) + model.selectMachine("mac") + model.searchScope = .content + model.searchQuery = "needle" + try await waitUntil { !model.contentSearchLoading } + + let ids = await probe.idLists.first ?? [] + XCTAssertEqual(ids, ["a"]) + XCTAssertTrue(model.rows.isEmpty) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift index 9fc54180..1487aef0 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift @@ -31,6 +31,25 @@ extension APIClient { return response.sessions } + /// `POST /api/sessions/content-search` — opt-in message-content search + /// across the given sessions (or every visible session when nil). + public func searchSessionContent( + query: String, + sessionIds: [String]? = nil, + limit: Int = 50 + ) async throws -> SessionContentSearchResponse { + struct ContentSearchRequest: Encodable { + let query: String + let limit: Int + let sessionIds: [String]? + } + return try await request( + .post, + "/api/sessions/content-search", + body: ContentSearchRequest(query: query, limit: limit, sessionIds: sessionIds) + ) + } + /// `GET /api/sessions/:id`. public func session(id: String) async throws -> Session { let response: SessionResponse = try await request( diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift index 1ccccebb..6d647a05 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift @@ -638,6 +638,32 @@ public actor MessageWindowController { update { MessageWindowLogic.cancelOlderLoad($0) } } + /// Replace the window with the hub's bounded context around one message + /// (content-search jump). Returns false when the message no longer + /// resolves; the caller then keeps the current window. + @discardableResult + public func focusMessage(_ messageId: String) async -> Bool { + do { + guard let response = try await provider.messageContext( + sessionId: sessionId, + messageId: messageId + ) else { return false } + guard !Task.isCancelled else { return false } + let messages = response.messages.map { WindowMessage(wire: $0) } + update { + MessageWindowLogic.applyContextWindow( + $0, + messages: messages, + page: response.page + ) + } + persist() + return true + } catch { + return false + } + } + // MARK: - SSE ingest /// Route one message-stream SSE event into this window. The caller diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionContentSearch.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionContentSearch.swift new file mode 100644 index 00000000..75cb1c10 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionContentSearch.swift @@ -0,0 +1,57 @@ +import Foundation + +/// One message hit from the hub's opt-in content search +/// (`SessionContentMatch`, `shared/src/apiTypes.ts`). +public struct SessionContentMatch: Codable, Equatable, Sendable { + public var messageId: String + /// `user` or `assistant`. + public var role: String + public var seq: Int + public var createdAt: Int + /// Hub-composed surrounding text (markup stripped, bounded). + public var snippet: String + /// The indexed message exceeded the search index budget. + public var truncated: Bool + + public init( + messageId: String, + role: String, + seq: Int, + createdAt: Int, + snippet: String, + truncated: Bool + ) { + self.messageId = messageId + self.role = role + self.seq = seq + self.createdAt = createdAt + self.snippet = snippet + self.truncated = truncated + } +} + +public struct SessionContentSearchResult: Codable, Equatable, Sendable { + public var session: SessionSummary + public var match: SessionContentMatch + + public init(session: SessionSummary, match: SessionContentMatch) { + self.session = session + self.match = match + } +} + +/// `POST /api/sessions/content-search` (`SessionContentSearchResponse`). +public struct SessionContentSearchResponse: Codable, Equatable, Sendable { + public var results: [SessionContentSearchResult] + /// True when the query may miss content omitted by an indexing + /// optimization (the list surfaces a hint rather than hiding results). + public var hasPotentiallyIncompleteResults: Bool + + public init( + results: [SessionContentSearchResult], + hasPotentiallyIncompleteResults: Bool + ) { + self.results = results + self.hasPotentiallyIncompleteResults = hasPotentiallyIncompleteResults + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift index 8e47b463..8f747eff 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.swift @@ -353,6 +353,43 @@ public enum MessageWindowLogic { return next } + /// Replace the window with the bounded context page centered on one + /// message (content search / jump-to-match). Unlike a latest page this + /// enters history mode, so the UI anchors at the target while older and + /// newer pages stay reachable. In-flight tail syncs are invalidated so + /// they cannot overwrite the context replace; optimistic queued rows are + /// preserved by identity. + public static func applyContextWindow( + _ previous: MessageWindowState, + messages: [WindowMessage], + page: MessageContextPage + ) -> MessageWindowState { + let retained = messages.filter { shouldRetainWindowMessage($0) } + let optimistic = previous.messages.filter { $0.isOptimistic } + let merged = MessageMerge.mergeMessages(optimistic, retained) + var next = settingMessages(previous, merged) + next.epoch = page.epoch + next.hasMore = page.hasMore + next.oldestPosition = pagePosition(at: page.nextBeforeAt, seq: page.nextBeforeSeq) + ?? derivePosition(retained, .oldest) + next.newestPosition = pagePosition(at: page.snapshotHeadAt, seq: page.snapshotHeadSeq) + ?? derivePosition(retained, .newest) + next.viewMode = .history + next.warning = nil + // The context page is not the live tail: a normal tail sync must not + // claim it is. "Back to latest" runs an allowingHistoryReset sync, + // which fetches and replaces this window with the current page. + next.requiresLatestReset = true + next.isSyncingTail = false + next.isLoadingMore = false + next.historyVersion = previous.historyVersion + 1 + next.tailRevision = previous.tailRevision + 1 + // Cancel responses from requests that started against the old window. + next.syncGeneration = previous.syncGeneration + 1 + next.olderGeneration = previous.olderGeneration + 1 + return next + } + // MARK: - Tail sync /// Web `beginTailSync`: claim a new sync generation. The older generation diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift index 77d8eacc..be88992f 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift @@ -223,6 +223,27 @@ struct EndpointRequestTests { #expect(account.buckets.first?.group == nil) } + @Test func sessionContentSearchPostsScopedQuery() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue( + json: "{\"results\":[],\"hasPotentiallyIncompleteResults\":true}" + ) + let response = try await harness.client.searchSessionContent( + query: "needle", + sessionIds: ["s-1", "s-2"], + limit: 50 + ) + let request = await harness.performer.requests.first + #expect(request?.url?.absoluteString == "\(testHubURLString)/api/sessions/content-search") + #expect(request?.httpMethod == "POST") + #expect( + bodyString(request) + == "{\"limit\":50,\"query\":\"needle\",\"sessionIds\":[\"s-1\",\"s-2\"]}" + ) + #expect(response.results.isEmpty) + #expect(response.hasPotentiallyIncompleteResults) + } + @Test func machineCodexModelsRequestAndRpcTargetMissing() async throws { let harness = try makeHarness(jwt: freshJWT()) await harness.performer.enqueue( diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift index 56295fcd..21b5d627 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift @@ -827,6 +827,65 @@ struct MessageWindowControllerTests { #expect(state.newestPosition == nil) #expect(state.oldestPosition == MessagePosition(at: 1000, seq: 1)) } + + // MARK: - Search jump + + @Test func focusMessageReplacesTheWindowWithContextAndEntersHistoryMode() async { + let provider = GatedMessagesProvider() + let initial = warmRecoveryWindow(id: "s", callStatus: "completed") + let controller = MessageWindowController( + sessionId: "s", + provider: provider, + initialState: initial + ) + let page = MessageContextPage( + epoch: 1, + nextBeforeSeq: 4, + nextBeforeAt: 4000, + snapshotHeadSeq: 20, + snapshotHeadAt: 20_000, + hasMore: true + ) + await provider.releaseContext(MessageContextResponse( + messages: [agentRow(id: "r-4", seq: 4, at: 4000), agentRow(id: "r-5", seq: 5, at: 5000)], + targetMessageId: "r-5", + page: page + )) + + let focused = await controller.focusMessage("r-5") + #expect(focused) + let contextRequests = await provider.contextRequests + #expect(contextRequests == ["r-5"]) + + let state = await controller.state + #expect(state.messages.map(\.id) == ["r-4", "r-5"]) + #expect(state.viewMode == .history) + #expect(state.epoch == 1) + #expect(state.hasMore) + #expect(state.oldestPosition == MessagePosition(at: 4000, seq: 4)) + #expect(state.newestPosition == MessagePosition(at: 20_000, seq: 20)) + #expect(state.historyVersion == initial.historyVersion + 1) + #expect(state.syncGeneration == initial.syncGeneration + 1) + #expect(state.requiresLatestReset) + #expect(!state.isSyncingTail) + } + + @Test func focusMessageKeepsTheWindowWhenTheTargetNoLongerResolves() async { + let provider = GatedMessagesProvider() + let initial = warmRecoveryWindow(id: "s", callStatus: "completed") + let controller = MessageWindowController( + sessionId: "s", + provider: provider, + initialState: initial + ) + await provider.releaseContext(nil) + + let focused = await controller.focusMessage("gone") + #expect(!focused) + let state = await controller.state + #expect(state.messages.map(\.id) == initial.messages.map(\.id)) + #expect(state.viewMode == .tail) + } } // MARK: - Gated transport