git.iko.soy/parseable-macos
on master help sign in
45 files changed+4062−716
since splitsnapshots
unifiedsplit
.github/workflows/build.yml+28 CLAUDE.md+3−3 ParseableViewer.xcodeproj/project.pbxproj+1−1 ParseableViewer/App/AppState.swift+236−17 ParseableViewer/App/ParseableViewerApp.swift+13−1 ParseableViewer/Info.plist+5 ParseableViewer/Models/AlertModels.swift+27−1 ParseableViewer/Models/JSONValue.swift+224−23 ParseableViewer/Models/LogStream.swift+145−17 ParseableViewer/Models/ParseableFilter.swift+1−1 ParseableViewer/Models/SQLTokenizer.swift+92−13 ParseableViewer/Models/ServerConnection.swift+35−2 ParseableViewer/Models/ServerInfo.swift+47−10 ParseableViewer/Services/ConnectionStore.swift+20−12 ParseableViewer/Services/KeychainService.swift+65−15 ParseableViewer/Services/ParseableClient.swift+302−49 ParseableViewer/ViewModels/LiveTailViewModel.swift+445−90 ParseableViewer/ViewModels/QueryViewModel.swift+530−61 ParseableViewer/Views/AlertsView.swift+32−4 ParseableViewer/Views/ConnectionSheet.swift+74−13 ParseableViewer/Views/ContentView.swift+72−36 ParseableViewer/Views/LiveTailView.swift+152−37 ParseableViewer/Views/LogDetailView.swift+43−14 ParseableViewer/Views/LogTableView.swift+261−41 ParseableViewer/Views/QueryView.swift+111−28 ParseableViewer/Views/SQLAutoComplete.swift+190−22 ParseableViewer/Views/SQLEditorView.swift+102−9 ParseableViewer/Views/ServerInfoView.swift+71−17 ParseableViewer/Views/SettingsView.swift+21−2 ParseableViewer/Views/SidebarView.swift+46−9 ParseableViewer/Views/StreamDetailView.swift+56−17 ParseableViewer/Views/SyntaxHighlighting.swift+85−71 ParseableViewer/Views/TimeRangePicker.swift+25−3 ParseableViewer/Views/UsersView.swift+26−3 ParseableViewerTests/ConnectionStoreTests.swift+71−33 ParseableViewerTests/JSONValueTests.swift+18 ParseableViewerTests/LiveTailViewModelTests.swift+54−29 ParseableViewerTests/LogTableHelperTests.swift+14−7 ParseableViewerTests/ParseableClientTests.swift+58 ParseableViewerTests/QueryViewModelTests.swift+169−4 ParseableViewerTests/SQLAutoCompleteTests.swift+56 ParseableViewerTests/SQLTokenizerTests.swift+15 ParseableViewerTests/ServerConnectionTests.swift+10 ParseableViewerTests/SyntaxHighlightingTests.swift+10 README.md+1−1
.github/workflows/build.yml+28
@@ -9,6 +9,10 @@ on:
99jobs:
1010 build:
1111 runs-on: macos-15
12+ permissions:
13+ id-token: write
14+ attestations: write
15+ contents: read
1216 strategy:
1317 matrix:
1418 include:
@@ -69,6 +73,11 @@ jobs:
6973 exit 1
7074 fi
7175
76+ - name: Attest artifact
77+ uses: actions/attest-build-provenance@v2
78+ with:
79+ subject-path: ParseableViewer-${{ matrix.arch }}.zip
80+
7281 - name: Upload artifact
7382 uses: actions/upload-artifact@v4
7483 with:
@@ -78,6 +87,10 @@ jobs:
7887 create-universal:
7988 needs: build
8089 runs-on: macos-15
90+ permissions:
91+ id-token: write
92+ attestations: write
93+ contents: read
8194 steps:
8295 - name: Checkout
8396 uses: actions/checkout@v4
@@ -125,6 +138,11 @@ jobs:
125138 cd universal_app
126139 zip -r -y "../ParseableViewer-universal.zip" "Parseable Viewer.app"
127140
141+ - name: Attest universal artifact
142+ uses: actions/attest-build-provenance@v2
143+ with:
144+ subject-path: ParseableViewer-universal.zip
145+
128146 - name: Upload universal artifact
129147 uses: actions/upload-artifact@v4
130148 with:
@@ -140,6 +158,8 @@ jobs:
140158 if: github.event_name == 'push'
141159 permissions:
142160 contents: write
161+ id-token: write
162+ attestations: write
143163 steps:
144164 - name: Checkout
145165 uses: actions/checkout@v4
@@ -155,6 +175,14 @@ jobs:
155175 with:
156176 path: artifacts
157177
178+ - name: Attest release artifacts
179+ uses: actions/attest-build-provenance@v2
180+ with:
181+ subject-path: |
182+ artifacts/ParseableViewer-arm64/ParseableViewer-arm64.zip
183+ artifacts/ParseableViewer-x86_64/ParseableViewer-x86_64.zip
184+ artifacts/ParseableViewer-universal/ParseableViewer-universal.zip
185+
158186 - name: Create release
159187 uses: softprops/action-gh-release@v2
160188 with:
CLAUDE.md+3−3
@@ -31,7 +31,7 @@ CI builds on `macos-15` runners via `.github/workflows/build.yml`, producing arm
3131- **Concurrency**: Swift structured concurrency (`async/await`, `@MainActor`, strict `Sendable` conformance)
3232- **Networking**: `URLSession` async/await, no external dependencies
3333- **Project generation**: XcodeGen from `project.yml`
34−- **Persistence**: `UserDefaults` for connections and saved queries; Keychain for passwords
34+- **Persistence**: Keychain (file-based login keychain) for connections and passwords; `UserDefaults` for saved queries. Do not use `kSecUseDataProtectionKeychain: true` — it requires `keychain-access-groups` entitlements that are incompatible with ad-hoc code signing and causes writes to silently fail.
3535
3636### Source layout
3737
@@ -83,10 +83,10 @@ Live tail in Parseable uses gRPC Arrow Flight streaming. This app approximates i
8383- Models use defensive `try?` decoding for optional fields to tolerate API version differences
8484- Views follow the macOS pattern: `NavigationSplitView` sidebar + detail, with tab switching in the detail pane
8585- All API calls are `async` and dispatched from views via `Task { }`
86−- Passwords are stored in the Keychain, never in UserDefaults; `ServerConnection.password` is excluded from `Codable`
86+- Connection metadata and passwords are stored in the Keychain (file-based login keychain); `ServerConnection.password` is excluded from `Codable`. Do not add `kSecUseDataProtectionKeychain: true` — it requires `keychain-access-groups` entitlements that conflict with ad-hoc code signing and causes writes to silently fail.
8787- Stream names are SQL-escaped via `escapeSQLIdentifier` (double-quote wrapping) and URL-encoded via `encodePathComponent` for API paths
8888- Views clear stale data before loading new content (e.g., switching streams clears previous schema/stats)
89−- Entitlements: App Sandbox enabled with network.client for outbound connections
89+- Entitlements: none (App Sandbox is not enabled)
9090
9191## Common patterns
9292
ParseableViewer.xcodeproj/project.pbxproj+1−1
@@ -293,7 +293,6 @@
293293 };
294294 };
295295 buildConfigurationList = 91629F84D63DA522312E65D6 /* Build configuration list for PBXProject "ParseableViewer" */;
296− compatibilityVersion = "Xcode 14.0";
297296 developmentRegion = en;
298297 hasScannedForEncodings = 0;
299298 knownRegions = (
@@ -303,6 +302,7 @@
303302 mainGroup = D06ED124AC4DFCB31F6EF0C1;
304303 minimizedProjectReferenceProxies = 1;
305304 preferredProjectObjectVersion = 77;
305+ productRefGroup = D37830AB19DD594BCD2B5499 /* Products */;
306306 projectDirPath = "";
307307 projectRoot = "";
308308 targets = (
ParseableViewer/App/AppState.swift+236−17
@@ -14,7 +14,11 @@ final class AppState {
1414 private(set) var isNetworkAvailable = true
1515 private let networkMonitor = NWPathMonitor()
1616 private let networkMonitorQueue = DispatchQueue(label: "com.parseableviewer.network-monitor")
17− private var connectTask: Task<Void, Never>?
17+ private var connectTask: Task<Bool, Never>?
18+ /// The connection `connectTask` is connecting to. `activeConnection` only
19+ /// switches once the new server answers, so this is what identifies an
20+ /// in-flight connect whose target the user deletes (see `removeConnection`).
21+ private var connectingConnectionID: UUID?
1822
1923 // MARK: - Stream State
2024 var streams: [LogStream] = []
@@ -62,6 +66,15 @@ final class AppState {
6266 case .serverInfo: return "server.rack"
6367 }
6468 }
69+
70+ /// Whether the tab's content is scoped to a selected stream. Server-level
71+ /// tabs (Users, Server Info) stay reachable even with no stream selected.
72+ var requiresStream: Bool {
73+ switch self {
74+ case .query, .liveTail, .streamInfo, .alerts: return true
75+ case .users, .serverInfo: return false
76+ }
77+ }
6578 }
6679
6780 var filteredStreams: [LogStream] {
@@ -87,8 +100,9 @@ final class AppState {
87100
88101 if let activeID = ConnectionStore.loadActiveConnectionID(),
89102 let connection = connections.first(where: { $0.id == activeID }) {
90− connectTask = Task { @MainActor in
91− await connect(to: connection)
103+ connectingConnectionID = connection.id
104+ connectTask = Task { @MainActor [weak self] in
105+ await self?.performConnect(to: connection) ?? false
92106 }
93107 }
94108 }
@@ -96,23 +110,71 @@ final class AppState {
96110 // MARK: - Connection Management
97111
98112 @MainActor
99− func connect(to connection: ServerConnection) async {
100− guard !isConnecting else { return }
113+ @discardableResult
114+ func connect(to connection: ServerConnection) async -> Bool {
115+ // Supersede any connect already in flight (e.g. the launch auto-reconnect
116+ // or a prior request) instead of silently dropping this one — which would
117+ // surface as a spurious "Connection failed". Cancel it and wait for it to
118+ // unwind so two connects never run concurrently.
119+ if let existing = connectTask {
120+ existing.cancel()
121+ _ = await existing.value
122+ }
123+ connectingConnectionID = connection.id
124+ let task = Task { @MainActor [weak self] in
125+ await self?.performConnect(to: connection) ?? false
126+ }
127+ connectTask = task
128+ return await task.value
129+ }
130+
131+ @MainActor
132+ private func performConnect(to connection: ServerConnection) async -> Bool {
133+ defer {
134+ if connectingConnectionID == connection.id { connectingConnectionID = nil }
135+ }
136+ guard !isConnecting else { return false }
101137
102− if !isNetworkAvailable {
138+ // NWPathMonitor ignores loopback, so with no active network interface it
139+ // reports "unsatisfied" even though a local server (the common docker /
140+ // dev setup) is reachable. Don't block those; a genuinely unreachable
141+ // host still fails below with the same offline message.
142+ if !isNetworkAvailable && !Self.isLoopback(connection.baseURL) {
103143 self.errorMessage = "No internet connection. Check your network and try again."
104144 self.showError = true
105− return
145+ return false
106146 }
107147
108148 isConnecting = true
149+ defer { isConnecting = false }
150+ // Reset the flag with the message: a previous failed connect left
151+ // `showError` set, and if its alert couldn't present (e.g. behind the
152+ // connection sheet), it would pop up later — after a successful retry —
153+ // reading "An unknown error occurred".
109154 errorMessage = nil
155+ showError = false
110156
111157 // When switching to a different server, clear stream-specific state
112158 // so stale selections don't reference streams that don't exist.
113159 if activeConnection?.id != connection.id {
114160 selectedStream = nil
115161 streamLoadError = nil
162+ // Drop the previous server's stream list and filters too — otherwise the
163+ // sidebar keeps rendering server A's streams/filters (with selection
164+ // already nilled) throughout the reconnect window. Same rationale as
165+ // `serverAbout` below; matches the failure path and `disconnect()`. Both
166+ // are repopulated once the new server's listStreams/listFilters respond.
167+ streams = []
168+ filters = []
169+ // Drop the previous server's cached `about` so views seeding from it
170+ // (ServerInfoView) don't paint the old server's details while the new
171+ // one loads. It's repopulated below once the new server responds.
172+ serverAbout = nil
173+ // Reset the sidebar search filter and tab too: a stale filter would
174+ // silently hide the new server's streams, and a stream-specific tab
175+ // would have no valid selection behind it.
176+ streamSearchText = ""
177+ currentTab = .query
116178 }
117179
118180 do {
@@ -120,6 +182,12 @@ final class AppState {
120182
121183 // Test connection — throws on non-200 or network failure
122184 try await newClient.checkHealth()
185+ try await Self.verifyCredentials(with: newClient)
186+
187+ // If the task was cancelled while awaiting (e.g. user clicked
188+ // Disconnect during auto-reconnect), bail before installing the
189+ // client so we don't resurrect a connection disconnect() just cleared.
190+ if Task.isCancelled { return false }
123191
124192 self.client = newClient
125193 self.activeConnection = connection
@@ -132,15 +200,36 @@ final class AppState {
132200 async let streamList = newClient.listStreams()
133201 async let filterList = newClient.listFilters()
134202
135− self.serverAbout = try? await about
136− self.filters = (try? await filterList) ?? []
203+ let aboutResult = try? await about
204+ let filterResult = (try? await filterList) ?? []
205+ let streamResult: Result<[LogStream], Error>
137206 do {
138− self.streams = try await streamList
139− self.streamLoadError = nil
207+ streamResult = .success(try await streamList)
140208 } catch {
209+ streamResult = .failure(error)
210+ }
211+
212+ // Re-check after the loads above: a disconnect could have landed
213+ // while awaiting, in which case committing these would show stale data.
214+ if Task.isCancelled { return false }
215+
216+ self.serverAbout = aboutResult
217+ self.filters = filterResult
218+ switch streamResult {
219+ case .success(let list):
220+ self.streams = list
221+ self.streamLoadError = nil
222+ // Like refreshStreams: a selection that doesn't exist on this server
223+ // (e.g. one picked from a stale list while the connect was pending)
224+ // would keep every stream tab querying a missing stream.
225+ if let selected = selectedStream, !list.contains(where: { $0.name == selected }) {
226+ selectedStream = nil
227+ }
228+ case .failure(let error):
141229 self.streams = []
142230 self.streamLoadError = ParseableError.userFriendlyMessage(for: error)
143231 }
232+ return true
144233 } catch {
145234 // If the task was cancelled (e.g. user clicked Disconnect during
146235 // auto-reconnect), skip the error alert — disconnect() already
@@ -151,10 +240,16 @@ final class AppState {
151240 self.isConnected = false
152241 self.client = nil
153242 self.activeConnection = nil
243+ // Clear stream-specific state so the sidebar doesn't keep showing
244+ // the previous server's streams/selection after a failed connect.
245+ self.streams = []
246+ self.selectedStream = nil
247+ self.streamLoadError = nil
248+ self.serverAbout = nil
249+ self.filters = []
154250 }
251+ return false
155252 }
156−
157− isConnecting = false
158253 }
159254
160255 @MainActor
@@ -168,17 +263,52 @@ final class AppState {
168263 selectedStream = nil
169264 serverAbout = nil
170265 filters = []
266+ // Clear transient stream/UI state too, otherwise a leftover stream-load
267+ // error keeps rendering in the sidebar after disconnect and a stale search
268+ // filter / tab carries into the next connection.
269+ streamLoadError = nil
270+ isLoadingStreams = false
271+ streamSearchText = ""
272+ currentTab = .query
171273 ConnectionStore.saveActiveConnectionID(nil)
172274 }
173275
174276 @MainActor
175277 func refreshStreams() async {
176278 guard let client else { return }
279+ // Capture the connection this fetch belongs to. A disconnect during the
280+ // await would otherwise let the (now-stale) result overwrite the cleanup
281+ // disconnect() just performed (streams = [], client = nil, etc.), leaving
282+ // the disconnected UI showing the old server's streams and re-enabling
283+ // stream-scoped tabs. Mirrors the connID guard used in performConnect,
284+ // AlertsView.loadAlerts, UsersView.loadUsers, StreamDetailView.loadData,
285+ // and ServerInfoView.loadInfo.
286+ let connID = activeConnection?.id
177287 isLoadingStreams = true
178288 streamLoadError = nil
179289 do {
180− streams = try await client.listStreams()
290+ let loaded = try await client.listStreams()
291+ // Drop results if the active connection changed while awaiting. Still
292+ // clear isLoadingStreams: this task set the spinner, so leaving it true
293+ // wedges the indicator and disables Refresh. Compare the client too:
294+ // editing the active connection's URL/credentials keeps its id but
295+ // installs a new client for a possibly different server.
296+ guard connID == activeConnection?.id, client === self.client else {
297+ isLoadingStreams = false
298+ return
299+ }
300+ streams = loaded
301+ // Drop a selection that no longer exists server-side (e.g. the stream
302+ // was deleted from another client); otherwise the detail tabs keep
303+ // querying a missing stream and surface 404s.
304+ if let selected = selectedStream, !streams.contains(where: { $0.name == selected }) {
305+ selectedStream = nil
306+ }
181307 } catch {
308+ guard connID == activeConnection?.id, client === self.client else {
309+ isLoadingStreams = false
310+ return
311+ }
182312 let message = ParseableError.userFriendlyMessage(for: error)
183313 streamLoadError = message
184314 self.errorMessage = "Failed to load streams: \(message)"
@@ -197,10 +327,45 @@ final class AppState {
197327
198328 @MainActor
199329 func updateConnection(_ connection: ServerConnection) {
330+ let previous = connections.first(where: { $0.id == connection.id })
200331 if let index = connections.firstIndex(where: { $0.id == connection.id }) {
201332 connections[index] = connection
202333 ConnectionStore.saveConnections(connections)
203334 }
335+ // If the active connection was edited, its URL or credentials may now point
336+ // at a different server, so swapping the client alone isn't enough — the
337+ // displayed streams/selection/server-info would be stale and queries would
338+ // 404. The caller is responsible for the actual reconnect (re-validate
339+ // health, reload streams/filters/about); we only clear the now-possibly-
340+ // stale UI state here, since `performConnect` skips its own cleanup when the
341+ // connection id is unchanged. We must NOT also spawn a connect here: the
342+ // sole caller (ConnectionSheet.saveAndConnect) already connects right after,
343+ // and a second connect would run two full reconnects and flash the UI twice.
344+ //
345+ // Only the URL/username/password identify the *server*; a cosmetic edit (e.g.
346+ // renaming the connection) points at the same server, so wiping the stream
347+ // selection/tab/streams would needlessly kick the user out of their current
348+ // view. Restrict the reset to edits that actually change the server target.
349+ let serverChanged = previous.map {
350+ $0.url != connection.url
351+ || $0.username != connection.username
352+ || $0.password != connection.password
353+ } ?? true
354+ if serverChanged, activeConnection?.id == connection.id {
355+ // Clear the stream-specific UI state so a leftover sidebar search filter
356+ // doesn't hide the new server's streams and a stream-specific tab
357+ // doesn't linger with no valid selection.
358+ selectedStream = nil
359+ streamSearchText = ""
360+ currentTab = .query
361+ // Drop the previous server's cached `about`, stream list, and filters —
362+ // performConnect skips its own clear (id unchanged), so without this the
363+ // sidebar keeps rendering server A's streams/filters and ServerInfoView
364+ // paints the old version/storage until the new server's responses land.
365+ serverAbout = nil
366+ streams = []
367+ filters = []
368+ }
204369 }
205370
206371 @MainActor
@@ -210,9 +375,49 @@ final class AppState {
210375 ConnectionStore.saveConnections(connections)
211376 if activeConnection?.id == connection.id {
212377 disconnect()
378+ } else if connectingConnectionID == connection.id {
379+ // The removed connection is still being connected to (e.g. Cancel in the
380+ // connection sheet, or deleting it in Settings during the launch
381+ // reconnect). `activeConnection` doesn't point at it yet, so without
382+ // this the connect would carry on and install a client for a
383+ // connection that no longer exists (or tear down the current session
384+ // when it fails) after the user abandoned it.
385+ connectTask?.cancel()
386+ connectTask = nil
387+ connectingConnectionID = nil
388+ // Starting that connect already cleared the current server's stream
389+ // list and filters; reload them if we're still connected to it.
390+ if client != nil {
391+ Task { @MainActor [weak self] in
392+ await self?.refreshStreams()
393+ await self?.refreshFilters()
394+ }
395+ }
213396 }
214397 }
215398
399+ /// `/api/v1/liveness` is unauthenticated on Parseable (it answers 200 to
400+ /// anyone, for load-balancer / k8s probes), so a health check alone accepts
401+ /// any username and password. Probe an authenticated endpoint and fail on
402+ /// 401. Other failures — e.g. a 403 for a role without the about permission —
403+ /// don't show the credentials are wrong, so they're ignored here. The client
404+ /// caches the response, so the follow-up `getAbout()` load reuses it.
405+ static func verifyCredentials(with client: ParseableClient) async throws {
406+ do {
407+ _ = try await client.getAbout()
408+ } catch ParseableError.unauthorized {
409+ throw ParseableError.unauthorized
410+ } catch {
411+ // Not an authentication failure; leave it to the best-effort loads.
412+ }
413+ }
414+
415+ private static func isLoopback(_ url: URL?) -> Bool {
416+ guard let host = url?.host?.lowercased() else { return false }
417+ return host == "localhost" || host.hasSuffix(".localhost")
418+ || host == "::1" || host.hasPrefix("127.")
419+ }
420+
216421 // MARK: - Stream Management
217422
218423 @MainActor
@@ -238,8 +443,18 @@ final class AppState {
238443 @MainActor
239444 func refreshFilters() async {
240445 guard let client else { return }
446+ // Capture the connection this fetch belongs to. A disconnect during the
447+ // await would otherwise let the (now-stale) result overwrite the cleanup
448+ // disconnect() performed, resurrecting the old server's filters in the
449+ // disconnected sidebar. Same guard pattern as refreshStreams.
450+ let connID = activeConnection?.id
241451 isLoadingFilters = true
242− filters = (try? await client.listFilters()) ?? []
452+ let loaded = (try? await client.listFilters()) ?? []
453+ guard connID == activeConnection?.id, client === self.client else {
454+ isLoadingFilters = false
455+ return
456+ }
457+ filters = loaded
243458 isLoadingFilters = false
244459 }
245460
@@ -258,8 +473,12 @@ final class AppState {
258473 @MainActor
259474 func deleteFilter(_ filter: ParseableFilter) async throws {
260475 guard let client else { throw ParseableError.notConnected }
261− guard let filterId = filter.filterId else { return }
262− try await client.deleteFilter(id: filterId)
476+ // A filter without a server-assigned id was never persisted remotely, so
477+ // there's nothing to delete on the server — just drop it locally. Returning
478+ // early here would silently leave the row in place with no error.
479+ if let filterId = filter.filterId {
480+ try await client.deleteFilter(id: filterId)
481+ }
263482 filters.removeAll { $0.id == filter.id }
264483 }
265484
ParseableViewer/App/ParseableViewerApp.swift+13−1
@@ -4,6 +4,13 @@ import SwiftUI
44struct ParseableViewerApp: App {
55 @State private var appState = AppState()
66
7+ init() {
8+ // All window content shares one AppState (see the File > New group below),
9+ // so don't offer window tabs either: the tab bar's "+" would open a second
10+ // window just like File > New Window.
11+ NSWindow.allowsAutomaticWindowTabbing = false
12+ }
13+
714 var body: some Scene {
815 WindowGroup {
916 ContentView()
@@ -17,7 +24,12 @@ struct ParseableViewerApp: App {
1724 AboutCommand()
1825 }
1926
20− CommandGroup(after: .newItem) {
27+ // Replace (rather than extend) the File > New group to drop "New Window":
28+ // connection, sheet, alert, selection and pending-filter state all live
29+ // in the single shared AppState, so a second window would present every
30+ // sheet and alert twice and race the first window's QueryView for
31+ // saved-filter SQL.
32+ CommandGroup(replacing: .newItem) {
2133 Button("New Connection...") {
2234 appState.editingConnection = nil
2335 appState.showConnectionSheet = true
ParseableViewer/Info.plist+5
@@ -24,6 +24,11 @@
2424 <string>public.app-category.developer-tools</string>
2525 <key>LSMinimumSystemVersion</key>
2626 <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
27+ <key>NSAppTransportSecurity</key>
28+ <dict>
29+ <key>NSAllowsArbitraryLoads</key>
30+ <true/>
31+ </dict>
2732 <key>NSMainNibFile</key>
2833 <string></string>
2934 <key>NSPrincipalClass</key>
ParseableViewer/Models/AlertModels.swift+27−1
@@ -45,10 +45,15 @@ struct AlertRule: Identifiable, Codable, Sendable {
4545 let rule: AlertRuleSpec?
4646 let targets: [AlertTarget]?
4747
48+ /// Stable fallback identity for alerts that carry no id/name/title.
49+ /// Generated once at init so `id` doesn't change on every access (which
50+ /// would make SwiftUI tear down and rebuild list rows continuously).
51+ private let localID = UUID()
52+
4853 /// Display name, preferring the modern `title` field over legacy `name`.
4954 var displayName: String { title ?? name ?? "Unnamed Alert" }
5055
51− var id: String { alertId ?? name ?? title ?? UUID().uuidString }
56+ var id: String { alertId ?? name ?? title ?? localID.uuidString }
5257
5358 private enum CodingKeys: String, CodingKey {
5459 case alertId = "id"
@@ -80,6 +85,27 @@ struct AlertRule: Identifiable, Codable, Sendable {
8085struct AlertRuleSpec: Codable, Sendable {
8186 let type: String?
8287 let config: String?
88+
89+ private enum CodingKeys: String, CodingKey {
90+ case type, config
91+ }
92+
93+ init(from decoder: Decoder) throws {
94+ let container = try decoder.container(keyedBy: CodingKeys.self)
95+ self.type = try? container.decode(String.self, forKey: .type)
96+ // The legacy per-stream rule is serialized as `{"type": …, "config": …}`
97+ // where only composite rules carry a string config; column rules carry an
98+ // object (`{"column": …, "operator": …, "value": …}`). Decoding that as a
99+ // String threw, which made the whole spec — and its type badge — vanish.
100+ // Keep non-string configs as compact JSON instead.
101+ if let string = try? container.decode(String.self, forKey: .config) {
102+ self.config = string
103+ } else if let value = try? container.decode(JSONValue.self, forKey: .config), value != .null {
104+ self.config = value.compactJSON
105+ } else {
106+ self.config = nil
107+ }
108+ }
83109}
84110
85111struct AlertTarget: Codable, Sendable {
ParseableViewer/Models/JSONValue.swift+224−23
@@ -37,7 +37,14 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
3737 case .null: try container.encodeNil()
3838 case .bool(let v): try container.encode(v)
3939 case .int(let v): try container.encode(v)
40− case .double(let v): try container.encode(v)
40+ case .double(let v):
41+ // JSON has no representation for infinity/NaN, and JSONEncoder's
42+ // default `.throw` strategy would abort the *entire* encode — turning
43+ // a single non-finite value into a total export failure (`exportAsJSON`
44+ // collapses to "[]"). Encode it as null to match displayString,
45+ // compactJSON/jsonNumber, and the CSV export, which all render
46+ // non-finite doubles as "null".
47+ if v.isFinite { try container.encode(v) } else { try container.encodeNil() }
4148 case .string(let v): try container.encode(v)
4249 case .array(let v): try container.encode(v)
4350 case .object(let v): try container.encode(v)
@@ -50,7 +57,14 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
5057 case .bool(let v): return v ? "true" : "false"
5158 case .int(let v): return String(v)
5259 case .double(let v):
60+ // Non-finite doubles have no display (and no JSON) representation;
61+ // render them as "null" to match jsonNumber/exportString rather than
62+ // letting String(_:) emit "inf"/"-inf"/"nan" into the UI and CSV cells.
63+ if !v.isFinite { return "null" }
5364 if v == v.rounded() && abs(v) < 1e15 {
65+ // Normalize negative zero so it renders as "0", not "-0"
66+ // (`%.0f` preserves the sign bit of -0.0).
67+ if v == 0 { return "0" }
5468 return String(format: "%.0f", v)
5569 }
5670 return String(v)
@@ -60,16 +74,31 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
6074 }
6175 }
6276
77+ /// Compact JSON serialization without allocating a JSONEncoder.
78+ var compactJSON: String {
79+ switch self {
80+ case .null: return "null"
81+ case .bool(let v): return v ? "true" : "false"
82+ case .int(let v): return String(v)
83+ case .double(let v): return Self.jsonNumber(v)
84+ case .string(let v): return "\"\(Self.escapeJSONString(v))\""
85+ case .array(let items):
86+ return "[" + items.map { $0.compactJSON }.joined(separator: ",") + "]"
87+ case .object(let dict):
88+ let pairs = dict.keys.sorted().compactMap { key -> String? in
89+ guard let value = dict[key] else { return nil }
90+ return "\"\(Self.escapeJSONString(key))\":\(value.compactJSON)"
91+ }
92+ return "{" + pairs.joined(separator: ",") + "}"
93+ }
94+ }
95+
6396 /// Like `displayString` but serializes arrays/objects as compact JSON
6497 /// instead of placeholders like "[3 items]". Used for CSV export.
6598 var exportString: String {
6699 switch self {
67100 case .array, .object:
68− if let data = try? JSONEncoder().encode(self),
69− let json = String(data: data, encoding: .utf8) {
70− return json
71− }
72− return displayString
101+ return compactJSON
73102 default:
74103 return displayString
75104 }
@@ -81,7 +110,7 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
81110 case .null: return "NULL"
82111 case .bool(let v): return v ? "true" : "false"
83112 case .int(let v): return String(v)
84− case .double(let v): return String(v)
113+ case .double(let v): return v.isFinite ? String(v) : "NULL"
85114 case .string(let v): return "'\(v.replacingOccurrences(of: "'", with: "''"))'"
86115 case .array, .object:
87116 return "'\(exportString.replacingOccurrences(of: "'", with: "''"))'"
@@ -122,7 +151,7 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
122151 case .null: return "null"
123152 case .bool(let v): return v ? "true" : "false"
124153 case .int(let v): return String(v)
125− case .double(let v): return String(v)
154+ case .double(let v): return Self.jsonNumber(v)
126155 case .string(let v): return "\"\(Self.escapeJSONString(v))\""
127156 case .array(let items):
128157 if items.isEmpty { return "[]" }
@@ -145,43 +174,201 @@ enum JSONValue: Codable, Hashable, Sendable, Comparable {
145174 /// Escapes special characters for valid JSON string output.
146175 static func escapeJSONString(_ s: String) -> String {
147176 var result = ""
148− result.reserveCapacity(s.count)
149− for char in s {
150− switch char {
177+ result.unicodeScalars.reserveCapacity(s.unicodeScalars.count)
178+ for scalar in s.unicodeScalars {
179+ switch scalar {
151180 case "\"": result += "\\\""
152181 case "\\": result += "\\\\"
153182 case "\n": result += "\\n"
154183 case "\r": result += "\\r"
155184 case "\t": result += "\\t"
156185 default:
157− if char.asciiValue.map({ $0 < 0x20 }) == true {
158− let code = char.asciiValue!
159− result += String(format: "\\u%04x", code)
186+ // Any control character (U+0000–U+001F), including those that
187+ // would otherwise combine into a grapheme cluster, must be
188+ // escaped to produce valid JSON.
189+ if scalar.value < 0x20 {
190+ result += String(format: "\\u%04x", scalar.value)
160191 } else {
161− result.append(char)
192+ result.unicodeScalars.append(scalar)
162193 }
163194 }
164195 }
165196 return result
166197 }
167198
199+ /// Stable ordering bucket per case so cross-type comparisons form a total
200+ /// order. Integers and doubles share a bucket so they compare numerically.
201+ private var typeRank: Int {
202+ switch self {
203+ case .null: return 0
204+ case .bool: return 1
205+ case .int, .double: return 2
206+ case .string: return 3
207+ case .array: return 4
208+ case .object: return 5
209+ }
210+ }
211+
168212 /// Type-aware comparison: numbers compare numerically, strings
169213 /// lexicographically, nulls sort first, bools sort false < true.
170− /// Cross-type comparisons fall back to displayString.
214+ /// Different types are ordered by a stable type rank so that `<` is a strict
215+ /// weak ordering consistent with `==` (the `Comparable` contract requires
216+ /// that order-equivalent values are equal — a `displayString` fallback
217+ /// violated this, e.g. `.int(5)` vs `.string("5")` both render "5").
171218 static func < (lhs: JSONValue, rhs: JSONValue) -> Bool {
219+ if lhs.typeRank != rhs.typeRank { return lhs.typeRank < rhs.typeRank }
172220 switch (lhs, rhs) {
173221 case (.null, .null): return false
174− case (.null, _): return true
175− case (_, .null): return false
176222 case (.bool(let a), .bool(let b)): return !a && b
177223 case (.int(let a), .int(let b)): return a < b
178− case (.double(let a), .double(let b)): return a < b
179− case (.int(let a), .double(let b)): return Double(a) < b
180− case (.double(let a), .int(let b)): return a < Double(b)
224+ case (.double(let a), .double(let b)): return doubleLessThan(a, b)
225+ case (.int(let a), .double(let b)): return intLessThanDouble(a, b)
226+ case (.double(let a), .int(let b)): return doubleLessThanInt(a, b)
181227 case (.string(let a), .string(let b)):
182− return a.localizedStandardCompare(b) == .orderedAscending
228+ // Two distinct strings can fold to `.orderedSame` under
229+ // `localizedStandardCompare` (e.g. full-width vs half-width forms that
230+ // Swift's `==` still treats as different). Break that tie with the raw
231+ // `<` so order-equivalent values stay `==`, as `Comparable` requires —
232+ // the same fallback `LogStream.<` already applies.
233+ let order = a.localizedStandardCompare(b)
234+ return order == .orderedAscending || (order == .orderedSame && a < b)
235+ case (.array(let a), .array(let b)):
236+ return arrayLessThan(a, b)
237+ case (.object(let a), .object(let b)):
238+ return objectLessThan(a, b)
183239 default:
184− return lhs.displayString < rhs.displayString
240+ return false
241+ }
242+ }
243+
244+ /// Lexicographic order over array elements using the element-level `<`/`==`.
245+ /// A serialized-string tiebreaker (`compactJSON < compactJSON`) was wrong:
246+ /// `.int(1) == .double(1.0)` are equal yet serialize as `1` vs `1.0`, so two
247+ /// non-equal values could share a serialization (or two equal ones differ),
248+ /// breaking the strict-weak-ordering `Comparable` requires. Comparing
249+ /// elements directly stays consistent with `==` (arrays are equal iff same
250+ /// length and equal elements).
251+ private static func arrayLessThan(_ a: [JSONValue], _ b: [JSONValue]) -> Bool {
252+ for (x, y) in zip(a, b) where x != y {
253+ return x < y
254+ }
255+ return a.count < b.count
256+ }
257+
258+ /// Deterministic order over objects: compare key/value pairs in sorted-key
259+ /// order. Independent of dictionary iteration order and consistent with `==`
260+ /// (objects are equal iff the same keys map to equal values).
261+ private static func objectLessThan(_ a: [String: JSONValue], _ b: [String: JSONValue]) -> Bool {
262+ let aKeys = a.keys.sorted()
263+ let bKeys = b.keys.sorted()
264+ for (ak, bk) in zip(aKeys, bKeys) {
265+ if ak != bk { return ak < bk }
266+ // Force-unwrap is safe: ak/bk come from each dictionary's own keys.
267+ let av = a[ak]!, bv = b[bk]!
268+ if av != bv { return av < bv }
269+ }
270+ return aKeys.count < bKeys.count
271+ }
272+
273+ /// Total ordering for doubles that keeps `sort()` from trapping on NaN
274+ /// (IEEE comparisons with NaN are always false, which violates the strict
275+ /// weak ordering `Comparable` requires). NaN is ordered after all numbers.
276+ private static func doubleLessThan(_ a: Double, _ b: Double) -> Bool {
277+ if a.isNaN { return false }
278+ if b.isNaN { return true }
279+ return a < b
280+ }
281+
282+ /// Exact three-way comparison of an `Int` against a `Double` with no
283+ /// precision loss. Returns a negative value if `a < b`, zero if they are
284+ /// numerically equal, and a positive value if `a > b`. `NaN` sorts after all
285+ /// numbers (so any int compares as less than `NaN`).
286+ ///
287+ /// Comparing via `Double(a)` loses precision for `|a| > 2^53`, and
288+ /// `Int(exactly: b)` is `nil` once `b` falls outside the `Int` range — the
289+ /// previous helpers fell back to the lossy path there, which made `<`, `>`,
290+ /// and `==` mutually inconsistent at the 2^63 boundary (e.g. `Int.max` vs
291+ /// `Double(Int.max)`, which rounds up to 2^63). This range-checks `b` first
292+ /// so the integer parts are always compared exactly.
293+ private static func compareIntDouble(_ a: Int, _ b: Double) -> Int {
294+ if b.isNaN { return -1 } // NaN sorts after numbers
295+ if b >= 9223372036854775808.0 { return -1 } // b > Int.max (incl. +inf)
296+ if b < -9223372036854775808.0 { return 1 } // b < Int.min (incl. -inf)
297+ // b is finite and its floor fits in Int.
298+ let bFloor = Int(b.rounded(.down))
299+ if a != bFloor { return a < bFloor ? -1 : 1 }
300+ // Integer parts are equal: a fractional b is the larger of the two.
301+ return b > Double(bFloor) ? -1 : 0
302+ }
303+
304+ private static func intLessThanDouble(_ a: Int, _ b: Double) -> Bool {
305+ compareIntDouble(a, b) < 0
306+ }
307+
308+ private static func doubleLessThanInt(_ a: Double, _ b: Int) -> Bool {
309+ // a < b ⟺ b > a ⟺ compareIntDouble(b, a) is positive.
310+ compareIntDouble(b, a) > 0
311+ }
312+
313+ private static func intEqualsDouble(_ a: Int, _ b: Double) -> Bool {
314+ compareIntDouble(a, b) == 0
315+ }
316+
317+ /// JSON-safe rendering of a double: JSON has no NaN/Infinity literals, so
318+ /// non-finite values serialize as `null` rather than the invalid `nan`/`inf`
319+ /// that `String(_:)` would emit.
320+ static func jsonNumber(_ v: Double) -> String {
321+ // Match `displayString`'s whole-number normalization so a value like
322+ // 100.0 serializes identically whether it's a top-level cell (which goes
323+ // through displayString) or nested in an array/object (which goes through
324+ // compactJSON). Emitting "100" instead of "100.0" is still valid JSON.
325+ guard v.isFinite else { return "null" }
326+ if v == v.rounded() && abs(v) < 1e15 {
327+ if v == 0 { return "0" } // normalize -0.0 → "0"
328+ return String(format: "%.0f", v)
329+ }
330+ return String(v)
331+ }
332+
333+ // MARK: - Equatable / Hashable
334+
335+ /// Equality treats numerically-equal integers and doubles as equal
336+ /// (e.g. `.int(1) == .double(1.0)`) to stay consistent with `<`, which
337+ /// compares the two numerically. Synthesized conformance would instead
338+ /// distinguish them by enum case, violating the `Comparable` contract.
339+ static func == (lhs: JSONValue, rhs: JSONValue) -> Bool {
340+ switch (lhs, rhs) {
341+ case (.null, .null): return true
342+ case (.bool(let a), .bool(let b)): return a == b
343+ case (.int(let a), .int(let b)): return a == b
344+ // NaN must compare equal to itself here: `<` (via doubleLessThan) orders
345+ // two NaNs as equivalent, and Comparable requires order-equivalent values
346+ // to be ==. Raw `a == b` (NaN != NaN) would break reflexivity, so e.g.
347+ // `.array([.double(.nan)])` would not equal itself.
348+ case (.double(let a), .double(let b)): return a == b || (a.isNaN && b.isNaN)
349+ case (.int(let a), .double(let b)): return Self.intEqualsDouble(a, b)
350+ case (.double(let a), .int(let b)): return Self.intEqualsDouble(b, a)
351+ case (.string(let a), .string(let b)): return a == b
352+ case (.array(let a), .array(let b)): return a == b
353+ case (.object(let a), .object(let b)): return a == b
354+ default: return false
355+ }
356+ }
357+
358+ func hash(into hasher: inout Hasher) {
359+ switch self {
360+ case .null: hasher.combine(0)
361+ case .bool(let v): hasher.combine(v)
362+ // Hash integers via their Double value so `.int(1)` and `.double(1.0)`
363+ // — which are `==` — produce the same hash.
364+ case .int(let v): hasher.combine(Double(v))
365+ // Canonicalize NaN: `==` treats all NaNs as equal, so every NaN must hash
366+ // identically to satisfy the Hashable contract (differing NaN bit patterns
367+ // would otherwise hash differently).
368+ case .double(let v): hasher.combine(v.isNaN ? Double.nan : v)
369+ case .string(let v): hasher.combine(v)
370+ case .array(let v): hasher.combine(v)
371+ case .object(let v): hasher.combine(v)
185372 }
186373 }
187374}
@@ -192,4 +379,18 @@ typealias LogRecord = [String: JSONValue]
192379struct QueryResponse: Codable, Sendable {
193380 let records: [LogRecord]
194381 let fields: [String]?
382+
383+ enum CodingKeys: String, CodingKey {
384+ case records, fields
385+ }
386+
387+ init(from decoder: Decoder) throws {
388+ let container = try decoder.container(keyedBy: CodingKeys.self)
389+ // A wrapped response can legitimately omit `records` for a zero-row result
390+ // (e.g. `{"fields": [...]}`). Default to an empty array rather than letting
391+ // the synthesized decoder throw, which would surface as a spurious
392+ // "Unexpected query response format" error instead of an empty result set.
393+ records = try container.decodeIfPresent([LogRecord].self, forKey: .records) ?? []
394+ fields = try container.decodeIfPresent([String].self, forKey: .fields)
395+ }
195396}
ParseableViewer/Models/LogStream.swift+145−17
@@ -10,7 +10,14 @@ struct LogStream: Identifiable, Codable, Hashable, Sendable, Comparable {
1010 }
1111
1212 static func < (lhs: LogStream, rhs: LogStream) -> Bool {
13− lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending
13+ // Fall back to a raw comparison when the localized comparison reports
14+ // `.orderedSame` for two distinct names (e.g. Unicode-equivalent forms),
15+ // so `<` stays a strict total order consistent with synthesized `==`.
16+ switch lhs.name.localizedStandardCompare(rhs.name) {
17+ case .orderedAscending: return true
18+ case .orderedDescending: return false
19+ case .orderedSame: return lhs.name < rhs.name
20+ }
1421 }
1522
1623 init(from decoder: Decoder) throws {
@@ -73,11 +80,111 @@ struct SchemaField: Identifiable, Codable, Hashable, Sendable {
7380 if let typeStr = try? container.decode(String.self, forKey: .dataType) {
7481 self.dataType = typeStr
7582 } else if let typeObj = try? container.decode(JSONValue.self, forKey: .dataType) {
76− self.dataType = typeObj.displayString
83+ self.dataType = Self.describeArrowType(typeObj)
7784 } else {
7885 self.dataType = "Unknown"
7986 }
8087 }
88+
89+ /// Renders a serde-serialized Arrow `DataType`. Parameterized types are
90+ /// externally tagged objects — `p_timestamp`, present in every Parseable
91+ /// stream, arrives as `{"Timestamp": ["Millisecond", null]}` and a list as
92+ /// `{"List": {<field>}}` — which `displayString` collapsed to the placeholder
93+ /// "{1 fields}". Produce Arrow's own notation instead, e.g.
94+ /// `Timestamp(Millisecond, None)` / `List(Utf8)`.
95+ static func describeArrowType(_ value: JSONValue) -> String {
96+ switch value {
97+ case .null:
98+ return "None"
99+ case .string(let s):
100+ return s
101+ case .array(let items):
102+ return items.map { describeArrowType($0) }.joined(separator: ", ")
103+ case .object(let dict):
104+ // A nested `Field` (list/map element, struct member): show its type.
105+ if let fieldType = dict["data_type"] {
106+ return describeArrowType(fieldType)
107+ }
108+ if dict.count == 1, let entry = dict.first {
109+ return "\(entry.key)(\(describeArrowType(entry.value)))"
110+ }
111+ return value.compactJSON
112+ default:
113+ return value.displayString
114+ }
115+ }
116+}
117+
118+/// Formats a byte count that may arrive from the server as a fractional or
119+/// out-of-range Double. `Int64(_:)` from a `Double` is a *trapping* conversion —
120+/// it crashes on NaN, infinity, or values outside `Int64`'s range — so a valid
121+/// but huge JSON number like `1e30` would crash the whole decode. Guard first.
122+private func formatByteSize(_ value: Double) -> String? {
123+ guard value.isFinite, value >= 0, value < 9.223372036854776e18 else { return nil }
124+ return ByteCountFormatter.string(fromByteCount: Int64(value), countStyle: .file)
125+}
126+
127+private func formatByteSize(_ value: Int) -> String? {
128+ // A negative byte count isn't meaningful; `ByteCountFormatter` would render it
129+ // as a bogus "-1 KB"/"Zero KB" string, so drop it like the `Double` path does.
130+ guard value >= 0 else { return nil }
131+ return ByteCountFormatter.string(fromByteCount: Int64(value), countStyle: .file)
132+}
133+
134+/// Normalizes a byte count that arrived as a JSON *string*. A bare numeric string
135+/// (e.g. "1048576") is a raw byte count and is formatted like the numeric branches
136+/// so identical sizes render consistently ("1 MB") regardless of whether the server
137+/// quoted the value. Parseable 1.x — the versions that quote sizes — sends them as
138+/// "<n> Bytes" (e.g. "1048576 Bytes"), so that unit suffix is accepted too. Any
139+/// other already-formatted string (e.g. "1.2 GB") is passed through unchanged.
140+private func formatByteSize(_ value: String) -> String {
141+ var trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
142+ if trimmed.lowercased().hasSuffix(" bytes") {
143+ trimmed = String(trimmed.dropLast(" bytes".count))
144+ }
145+ if let n = Int(trimmed) { return formatByteSize(n) ?? value }
146+ return value
147+}
148+
149+/// A string-backed coding key for fields whose name differs across Parseable
150+/// versions (kebab-case, snake_case, and camelCase spellings of the same field).
151+private struct FlexibleCodingKey: CodingKey {
152+ let stringValue: String
153+ var intValue: Int? { nil }
154+ init(stringValue: String) { self.stringValue = stringValue }
155+ init?(intValue: Int) { nil }
156+}
157+
158+private extension KeyedDecodingContainer where Key == FlexibleCodingKey {
159+ /// The first of `keys` that decodes as a string.
160+ func firstString(_ keys: String...) -> String? {
161+ for key in keys {
162+ if let value = try? decode(String.self, forKey: FlexibleCodingKey(stringValue: key)) {
163+ return value
164+ }
165+ }
166+ return nil
167+ }
168+
169+ /// The first of `keys` that decodes as a boolean — either a JSON bool or the
170+ /// strings "true"/"false" (Parseable serializes `static_schema_flag` as the
171+ /// string "true").
172+ func firstBool(_ keys: String...) -> Bool? {
173+ for key in keys {
174+ let codingKey = FlexibleCodingKey(stringValue: key)
175+ if let value = try? decode(Bool.self, forKey: codingKey) {
176+ return value
177+ }
178+ if let string = try? decode(String.self, forKey: codingKey) {
179+ switch string.lowercased() {
180+ case "true": return true
181+ case "false": return false
182+ default: continue
183+ }
184+ }
185+ }
186+ return nil
187+ }
81188}
82189
83190struct StreamStats: Codable, Sendable {
@@ -100,16 +207,20 @@ struct StreamStats: Codable, Sendable {
100207 self.lifetime_count = try? container.decode(Int.self, forKey: .lifetime_count)
101208 // Handle size as string or number
102209 if let s = try? container.decode(String.self, forKey: .size) {
103− self.size = s
210+ self.size = formatByteSize(s)
104211 } else if let n = try? container.decode(Int.self, forKey: .size) {
105− self.size = ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file)
212+ self.size = formatByteSize(n)
213+ } else if let d = try? container.decode(Double.self, forKey: .size) {
214+ self.size = formatByteSize(d)
106215 } else {
107216 self.size = nil
108217 }
109218 if let s = try? container.decode(String.self, forKey: .lifetime_size) {
110− self.lifetime_size = s
219+ self.lifetime_size = formatByteSize(s)
111220 } else if let n = try? container.decode(Int.self, forKey: .lifetime_size) {
112− self.lifetime_size = ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file)
221+ self.lifetime_size = formatByteSize(n)
222+ } else if let d = try? container.decode(Double.self, forKey: .lifetime_size) {
223+ self.lifetime_size = formatByteSize(d)
113224 } else {
114225 self.lifetime_size = nil
115226 }
@@ -127,18 +238,26 @@ struct StreamStats: Codable, Sendable {
127238
128239 init(from decoder: Decoder) throws {
129240 let container = try decoder.container(keyedBy: CodingKeys.self)
130− self.type = try? container.decode(String.self, forKey: .type)
241+ // Parseable names this field `format` (e.g. "parquet") in every
242+ // version; `type` never appears, so "Storage Type" always read N/A.
243+ // Keep `type` as a fallback.
244+ self.type = (try? decoder.container(keyedBy: FlexibleCodingKey.self))?
245+ .firstString("format", "type")
131246 if let s = try? container.decode(String.self, forKey: .size) {
132− self.size = s
247+ self.size = formatByteSize(s)
133248 } else if let n = try? container.decode(Int.self, forKey: .size) {
134− self.size = ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file)
249+ self.size = formatByteSize(n)
250+ } else if let d = try? container.decode(Double.self, forKey: .size) {
251+ self.size = formatByteSize(d)
135252 } else {
136253 self.size = nil
137254 }
138255 if let s = try? container.decode(String.self, forKey: .lifetime_size) {
139− self.lifetime_size = s
256+ self.lifetime_size = formatByteSize(s)
140257 } else if let n = try? container.decode(Int.self, forKey: .lifetime_size) {
141− self.lifetime_size = ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file)
258+ self.lifetime_size = formatByteSize(n)
259+ } else if let d = try? container.decode(Double.self, forKey: .lifetime_size) {
260+ self.lifetime_size = formatByteSize(d)
142261 } else {
143262 self.lifetime_size = nil
144263 }
@@ -166,11 +285,20 @@ struct StreamInfo: Codable, Sendable {
166285 }
167286
168287 init(from decoder: Decoder) throws {
169− let container = try decoder.container(keyedBy: CodingKeys.self)
170− self.createdAt = try? container.decode(String.self, forKey: .createdAt)
171− self.firstEventAt = try? container.decode(String.self, forKey: .firstEventAt)
172− self.cacheEnabled = try? container.decode(Bool.self, forKey: .cacheEnabled)
173− self.timePartition = try? container.decode(String.self, forKey: .timePartition)
174− self.staticSchemaFlag = try? container.decode(Bool.self, forKey: .staticSchemaFlag)
288+ // The /info key spellings vary by Parseable version: 1.x–2.x send
289+ // `created-at`/`first-event-at` with the other fields in snake_case
290+ // (`cache_enabled`, `time_partition`, `static_schema_flag`), while newer
291+ // servers send camelCase throughout (`createdAt`, `timePartition`, …).
292+ // The kebab-case `cache-enabled`/`time-partition`/`static-schema-flag`
293+ // decoded previously were never sent by any version, so those rows always
294+ // showed "N/A". The schema flag also arrives as the string "true".
295+ let container = try decoder.container(keyedBy: FlexibleCodingKey.self)
296+ self.createdAt = container.firstString("created-at", "createdAt", "created_at")
297+ self.firstEventAt = container.firstString("first-event-at", "firstEventAt", "first_event_at")
298+ self.cacheEnabled = container.firstBool("cache_enabled", "cacheEnabled", "cache-enabled")
299+ self.timePartition = container.firstString("time_partition", "timePartition", "time-partition")
300+ self.staticSchemaFlag = container.firstBool(
301+ "static_schema_flag", "staticSchemaFlag", "static-schema-flag"
302+ )
175303 }
176304}
ParseableViewer/Models/ParseableFilter.swift+1−1
@@ -19,7 +19,7 @@ struct FilterQuery: Codable, Hashable, Sendable {
1919
2020 init(from decoder: Decoder) throws {
2121 let container = try decoder.container(keyedBy: CodingKeys.self)
22− filterType = try container.decode(String.self, forKey: .filterType)
22+ filterType = (try? container.decode(String.self, forKey: .filterType)) ?? "sql"
2323 filterQuery = try? container.decode(String.self, forKey: .filterQuery)
2424 filterBuilder = try? container.decode(JSONValue.self, forKey: .filterBuilder)
2525 }
ParseableViewer/Models/SQLTokenizer.swift+92−13
@@ -80,13 +80,20 @@ struct SQLTokenizer: Sendable {
8080
8181 switch c {
8282 // Whitespace
83− case " ", "\t", "\n", "\r":
84− advance(&i, in: sql, while: { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" })
83+ case _ where isWhitespace(c):
84+ advance(&i, in: sql, while: isWhitespace)
8585 tokens.append(Token(kind: .whitespace, range: start..<i))
8686
8787 // Line comment
8888 case "-" where peek(sql, at: i, offset: 1) == "-":
89− advance(&i, in: sql, while: { $0 != "\n" })
89+ // Stop at CR as well as LF: with CRLF (`\r\n`) line endings, consuming
90+ // the trailing `\r` into the comment token would push its boundary past
91+ // where `characterOffset`/DataFusion treat the line as ending, shifting
92+ // the server-error highlight range. The line break is then tokenized as
93+ // whitespace. `isLineBreak` also matches the single `"\r\n"` Character
94+ // Swift forms from a CRLF pair — comparing against "\n"/"\r" alone never
95+ // matches it, so the comment would swallow every following line.
96+ advance(&i, in: sql, while: { !isLineBreak($0) })
9097 tokens.append(Token(kind: .lineComment, range: start..<i))
9198
9299 // Block comment
@@ -126,13 +133,13 @@ struct SQLTokenizer: Sendable {
126133 tokens.append(Token(kind: .star, range: start..<i))
127134
128135 // Number (digit or leading dot followed by digit)
129− case _ where c.isNumber || (c == "." && peek(sql, at: i, offset: 1)?.isNumber == true):
136+ case _ where isASCIIDigit(c) || (c == "." && peek(sql, at: i, offset: 1).map(isASCIIDigit) == true):
130137 consumeNumber(&i, in: sql)
131138 tokens.append(Token(kind: .number(String(sql[start..<i])), range: start..<i))
132139
133140 // Identifier or keyword
134− case _ where c.isLetter || c == "_":
135− advance(&i, in: sql, while: { $0.isLetter || $0.isNumber || $0 == "_" })
141+ case _ where isASCIILetter(c) || c == "_":
142+ advance(&i, in: sql, while: { isASCIILetter($0) || isASCIIDigit($0) || $0 == "_" })
136143 let word = String(sql[start..<i])
137144 if keywords.contains(word.uppercased()) {
138145 tokens.append(Token(kind: .keyword(word.uppercased()), range: start..<i))
@@ -255,15 +262,60 @@ struct SQLTokenizer: Sendable {
255262 return value // unterminated
256263 }
257264
265+ /// Swift iterates grapheme clusters, and a CRLF pair is the single Character
266+ /// `"\r\n"`, which is equal to neither `"\r"` nor `"\n"`. Match it explicitly
267+ /// so Windows line endings (e.g. pasted text) tokenize like LF/CR ones.
268+ private static func isLineBreak(_ c: Character) -> Bool {
269+ c == "\n" || c == "\r" || c == "\r\n"
270+ }
271+
272+ private static func isWhitespace(_ c: Character) -> Bool {
273+ c == " " || c == "\t" || isLineBreak(c)
274+ }
275+
276+ /// SQL number literals use only ASCII digits. `Character.isNumber` also
277+ /// matches Unicode numerics (`²`, `½`, Arabic-Indic digits, etc.), which
278+ /// DataFusion's lexer rejects — accepting them here would tokenize those
279+ /// characters as numbers and diverge token offsets from the server, throwing
280+ /// off `errorHighlightRange` mapping.
281+ private static func isASCIIDigit(_ c: Character) -> Bool {
282+ c.isASCII && c.isNumber
283+ }
284+
285+ /// Bare (unquoted) SQL identifiers use only ASCII letters. `Character.isLetter`
286+ /// matches the full Unicode letter range (`café`, `naïve`, etc.), which
287+ /// DataFusion's lexer would require to be double-quoted — accepting them bare
288+ /// here would tokenize them as identifiers and diverge token offsets from the
289+ /// server, throwing off `errorHighlightRange` mapping (same rationale as
290+ /// `isASCIIDigit`).
291+ private static func isASCIILetter(_ c: Character) -> Bool {
292+ c.isASCII && c.isLetter
293+ }
294+
258295 private static func consumeNumber(_ i: inout String.Index, in sql: String) {
259− advance(&i, in: sql, while: { $0.isNumber || $0 == "." })
260− // Exponent
296+ // Digits with at most one decimal point, so malformed input like
297+ // `1.2.3` doesn't get swallowed into a single number token.
298+ var seenDot = false
299+ advance(&i, in: sql, while: { c in
300+ if c == "." {
301+ if seenDot { return false }
302+ seenDot = true
303+ return true
304+ }
305+ return isASCIIDigit(c)
306+ })
307+ // Exponent — only consume `e`/`E` (and an optional sign) when actual
308+ // exponent digits follow, so `1e` or `1e+` aren't swallowed whole and
309+ // instead tokenize as a number followed by an identifier/operator.
261310 if i < sql.endIndex, sql[i] == "e" || sql[i] == "E" {
262− sql.formIndex(after: &i)
263− if i < sql.endIndex, sql[i] == "+" || sql[i] == "-" {
264− sql.formIndex(after: &i)
311+ var lookahead = sql.index(after: i)
312+ if lookahead < sql.endIndex, sql[lookahead] == "+" || sql[lookahead] == "-" {
313+ sql.formIndex(after: &lookahead)
314+ }
315+ if lookahead < sql.endIndex, isASCIIDigit(sql[lookahead]) {
316+ i = lookahead
317+ advance(&i, in: sql, while: { isASCIIDigit($0) })
265318 }
266− advance(&i, in: sql, while: { $0.isNumber })
267319 }
268320 }
269321
@@ -287,7 +339,26 @@ struct SQLTokenizer: Sendable {
287339 i += 1
288340 }
289341
290− let offset = i + (column - 1)
342+ // Advance (column - 1) characters from the line start. `column` is a
343+ // 1-based character position, so a surrogate pair (e.g. an emoji) counts
344+ // as one character but two UTF-16 units; stepping char-by-char keeps the
345+ // offset correct for non-BMP text. For all-ASCII/BMP lines this is
346+ // identical to `i + (column - 1)`.
347+ var offset = i
348+ var remaining = column - 1
349+ while remaining > 0 {
350+ // Running out of characters means the column points past the end of
351+ // the input — out of bounds, matching the original contract.
352+ guard offset < length else { return nil }
353+ let unit = nsString.character(at: offset)
354+ if unit == 0x0A { break } // a column can't extend past the line's newline
355+ if unit >= 0xD800 && unit <= 0xDBFF && offset + 1 < length {
356+ offset += 2 // high surrogate: skip the trailing low surrogate too
357+ } else {
358+ offset += 1
359+ }
360+ remaining -= 1
361+ }
291362 guard offset <= length else { return nil }
292363 return offset
293364 }
@@ -309,6 +380,14 @@ struct SQLTokenizer: Sendable {
309380 return NSRange(next.range, in: sql)
310381 }
311382 }
383+ // No following real token (e.g. error reported at trailing
384+ // whitespace): snap back to the previous non-trivia token
385+ // instead of returning no highlight at all.
386+ for prev in tokens[..<idx].reversed() {
387+ if !prev.kind.isTrivia {
388+ return NSRange(prev.range, in: sql)
389+ }
390+ }
312391 return nil
313392 }
314393 return nsRange
ParseableViewer/Models/ServerConnection.swift+35−2
@@ -37,18 +37,51 @@ struct ServerConnection: Identifiable, Codable, Hashable, Sendable {
3737 try container.encode(username, forKey: .username)
3838 }
3939
40+ // `password` is deliberately excluded from equality and hashing: it isn't
41+ // serialized (see CodingKeys) and is repopulated from the Keychain on
42+ // decode, so including it would make a decoded connection compare unequal
43+ // to the in-memory original whenever the Keychain read returns "" — e.g. in
44+ // Set membership or "has this connection changed?" checks.
45+ static func == (lhs: ServerConnection, rhs: ServerConnection) -> Bool {
46+ lhs.id == rhs.id
47+ && lhs.name == rhs.name
48+ && lhs.url == rhs.url
49+ && lhs.username == rhs.username
50+ }
51+
52+ func hash(into hasher: inout Hasher) {
53+ hasher.combine(id)
54+ }
55+
4056 var baseURL: URL? {
4157 var urlString = url.trimmingCharacters(in: .whitespacesAndNewlines)
4258 if urlString.isEmpty { return nil }
43− if !urlString.hasPrefix("http://") && !urlString.hasPrefix("https://") {
59+ if let schemeRange = Self.urlSchemeRange(in: urlString) {
60+ // Normalize the (case-insensitive) scheme so `HTTP://host` behaves
61+ // exactly like `http://host` everywhere downstream.
62+ urlString.replaceSubrange(schemeRange, with: urlString[schemeRange].lowercased())
63+ } else {
4464 urlString = "https://\(urlString)"
4565 }
4666 while urlString.hasSuffix("/") {
4767 urlString.removeLast()
4868 }
49− guard let parsed = URL(string: urlString), parsed.host != nil else {
69+ guard let parsed = URL(string: urlString), parsed.host != nil,
70+ parsed.scheme == "http" || parsed.scheme == "https" else {
5071 return nil
5172 }
5273 return parsed
5374 }
75+
76+ /// Whether `string` already starts with a URL scheme (`http://`, `HTTPS://`,
77+ /// `ftp://`, …). Schemes are case-insensitive, so a case-sensitive
78+ /// `hasPrefix("http://")` check turned `HTTP://host` into
79+ /// `https://HTTP://host` — a URL whose host is "HTTP".
80+ static func hasURLScheme(_ string: String) -> Bool {
81+ urlSchemeRange(in: string) != nil
82+ }
83+
84+ private static func urlSchemeRange(in string: String) -> Range<String.Index>? {
85+ string.range(of: "^[A-Za-z][A-Za-z0-9+.-]*://", options: .regularExpression)
86+ }
5487}
ParseableViewer/Models/ServerInfo.swift+47−10
@@ -15,33 +15,59 @@ struct ServerAbout: Codable, Sendable {
1515 let llmActive: Bool?
1616 let oidcActive: Bool?
1717
18+ // Parseable's /about handler has always sent camelCase keys (`uiVersion`,
19+ // `deploymentId`, `grpcPort`), like the other fields here. Decoding only the
20+ // snake_case spellings — which the server never sends — left UI Version and
21+ // Deployment ID permanently "N/A" and hid the gRPC Port row. The snake_case
22+ // forms are kept as a fallback.
1823 private enum CodingKeys: String, CodingKey {
1924 case version, commit, mode, staging, store, license
20− case uiVersion = "ui_version"
21− case deploymentId = "deployment_id"
22− case grpcPort = "grpc_port"
25+ case uiVersion
26+ case deploymentId
27+ case grpcPort
2328 case updateAvailable
2429 case latestVersion
2530 case llmActive
2631 case oidcActive
2732 }
2833
34+ private enum SnakeCaseKeys: String, CodingKey {
35+ case uiVersion = "ui_version"
36+ case deploymentId = "deployment_id"
37+ case grpcPort = "grpc_port"
38+ }
39+
2940 init(from decoder: Decoder) throws {
3041 let container = try decoder.container(keyedBy: CodingKeys.self)
42+ let snakeCase = try? decoder.container(keyedBy: SnakeCaseKeys.self)
3143 self.version = try? container.decode(String.self, forKey: .version)
32− self.uiVersion = try? container.decode(String.self, forKey: .uiVersion)
44+ self.uiVersion = (try? container.decode(String.self, forKey: .uiVersion))
45+ ?? (try? snakeCase?.decode(String.self, forKey: .uiVersion))
3346 self.commit = try? container.decode(String.self, forKey: .commit)
34− self.deploymentId = try? container.decode(String.self, forKey: .deploymentId)
47+ self.deploymentId = (try? container.decode(String.self, forKey: .deploymentId))
48+ ?? (try? snakeCase?.decode(String.self, forKey: .deploymentId))
3549 self.mode = try? container.decode(String.self, forKey: .mode)
3650 self.staging = try? container.decode(String.self, forKey: .staging)
3751 self.store = try? container.decode(StoreInfo.self, forKey: .store)
38− self.license = try? container.decode(String.self, forKey: .license)
39− self.grpcPort = try? container.decode(Int.self, forKey: .grpcPort)
52+ self.license = (try? container.decode(String.self, forKey: .license))
53+ ?? (try? container.decode(JSONValue.self, forKey: .license)).flatMap(Self.describeLicense)
54+ self.grpcPort = (try? container.decode(Int.self, forKey: .grpcPort))
55+ ?? (try? snakeCase?.decode(Int.self, forKey: .grpcPort))
4056 self.updateAvailable = try? container.decode(Bool.self, forKey: .updateAvailable)
4157 self.latestVersion = try? container.decode(String.self, forKey: .latestVersion)
4258 self.llmActive = try? container.decode(Bool.self, forKey: .llmActive)
4359 self.oidcActive = try? container.decode(Bool.self, forKey: .oidcActive)
4460 }
61+
62+ /// Current servers send `license` as an object (`{"name": "AGPL-3.0-only",
63+ /// "plan": "OSS", …}`) rather than a string, which decoded to nil ("N/A").
64+ private static func describeLicense(_ value: JSONValue) -> String? {
65+ guard case .object(let fields) = value, let name = fields["name"]?.stringValue else { return nil }
66+ if let plan = fields["plan"]?.stringValue, !plan.isEmpty {
67+ return "\(name) (\(plan))"
68+ }
69+ return name
70+ }
4571}
4672
4773struct StoreInfo: Codable, Sendable {
@@ -85,9 +111,20 @@ struct UserInfo: Identifiable, Codable, Sendable {
85111 }
86112
87113 init(from decoder: Decoder) throws {
88− // Handle both {"id": "x", ...} and variations
89− if let container = try? decoder.container(keyedBy: CodingKeys.self) {
90− self.id = try container.decode(String.self, forKey: .id)
114+ // Handle both {"id": "x", ...} and a bare "x" string element.
115+ if let container = try? decoder.container(keyedBy: CodingKeys.self),
116+ container.contains(.id) {
117+ // Decode `id` defensively: the server may quote it as a string or
118+ // send it as a number/other JSON. Fall back to JSONValue.displayString
119+ // so a single odd entry doesn't fail the whole user list (matching the
120+ // file's otherwise-defensive decoding).
121+ if let stringID = try? container.decode(String.self, forKey: .id) {
122+ self.id = stringID
123+ } else if let valueID = try? container.decode(JSONValue.self, forKey: .id) {
124+ self.id = valueID.displayString
125+ } else {
126+ self.id = ""
127+ }
91128 self.method = try? container.decode(String.self, forKey: .method)
92129 } else {
93130 let container = try decoder.singleValueContainer()
ParseableViewer/Services/ConnectionStore.swift+20−12
@@ -1,26 +1,29 @@
11import Foundation
22
33final class ConnectionStore {
4− private static let storageKey = "parseable_connections"
5− private static let activeConnectionKey = "parseable_active_connection_id"
4+ private static let keychainConnectionsKey = "parseable_connections_list"
5+ private static let keychainActiveIDKey = "parseable_active_connection_id"
66
77 static func loadConnections() -> [ServerConnection] {
8− guard let data = UserDefaults.standard.data(forKey: storageKey) else {
8+ guard let data = KeychainService.loadData(for: keychainConnectionsKey) else {
99 return []
1010 }
1111 return (try? JSONDecoder().decode([ServerConnection].self, from: data)) ?? []
1212 }
1313
1414 static func saveConnections(_ connections: [ServerConnection]) {
15− for connection in connections {
16− if !connection.password.isEmpty {
17− KeychainService.savePassword(connection.password, for: connection.id)
18− } else {
19− KeychainService.deletePassword(for: connection.id)
20− }
15+ for connection in connections where !connection.password.isEmpty {
16+ // Only upsert non-empty passwords. We must NOT delete on an empty
17+ // password here: `ServerConnection.init(from:)` decodes the password
18+ // as "" whenever the Keychain read transiently fails (locked
19+ // Keychain, errSecInteractionNotAllowed, etc.), so deleting on empty
20+ // would promote a transient read failure into permanent credential
21+ // loss on the next save. Credentials are removed only when the
22+ // connection itself is removed, via `deleteConnection`.
23+ KeychainService.savePassword(connection.password, for: connection.id)
2124 }
2225 if let data = try? JSONEncoder().encode(connections) {
23− UserDefaults.standard.set(data, forKey: storageKey)
26+ KeychainService.saveData(data, for: keychainConnectionsKey)
2427 }
2528 }
2629
@@ -29,13 +32,18 @@ final class ConnectionStore {
2932 }
3033
3134 static func loadActiveConnectionID() -> UUID? {
32− guard let string = UserDefaults.standard.string(forKey: activeConnectionKey) else {
35+ guard let data = KeychainService.loadData(for: keychainActiveIDKey),
36+ let string = String(data: data, encoding: .utf8) else {
3337 return nil
3438 }
3539 return UUID(uuidString: string)
3640 }
3741
3842 static func saveActiveConnectionID(_ id: UUID?) {
39− UserDefaults.standard.set(id?.uuidString, forKey: activeConnectionKey)
43+ if let id, let data = id.uuidString.data(using: .utf8) {
44+ KeychainService.saveData(data, for: keychainActiveIDKey)
45+ } else {
46+ KeychainService.deleteData(for: keychainActiveIDKey)
47+ }
4048 }
4149}
ParseableViewer/Services/KeychainService.swift+65−15
@@ -8,17 +8,8 @@ enum KeychainService {
88
99 @discardableResult
1010 static func savePassword(_ password: String, for connectionID: UUID) -> Bool {
11− let account = connectionID.uuidString
12− deletePassword(for: connectionID)
13−
1411 guard let data = password.data(using: .utf8) else { return false }
15− var query = baseQuery(for: connectionID)
16− query[kSecValueData as String] = data
17− let status = SecItemAdd(query as CFDictionary, nil)
18− if status != errSecSuccess {
19− logger.error("Failed to save password for \(account): OSStatus \(status)")
20− }
21− return status == errSecSuccess
12+ return upsert(data, query: baseQuery(for: connectionID), label: connectionID.uuidString)
2213 }
2314
2415 static func loadPassword(for connectionID: UUID) -> String? {
@@ -47,15 +38,74 @@ enum KeychainService {
4738 return status == errSecSuccess || status == errSecItemNotFound
4839 }
4940
50− /// Base query targeting the data-protection keychain.
51− /// Items stored here are scoped by bundle identifier rather than by
52− /// code-signing identity, so they survive ad-hoc re-signing across builds.
41+ // MARK: - Generic data storage (string-keyed)
42+
43+ @discardableResult
44+ static func saveData(_ data: Data, for key: String) -> Bool {
45+ upsert(data, query: baseQuery(for: key), label: key)
46+ }
47+
48+ static func loadData(for key: String) -> Data? {
49+ var query = baseQuery(for: key)
50+ query[kSecReturnData as String] = true
51+ query[kSecMatchLimit as String] = kSecMatchLimitOne
52+
53+ var result: AnyObject?
54+ let status = SecItemCopyMatching(query as CFDictionary, &result)
55+ if status != errSecSuccess && status != errSecItemNotFound {
56+ logger.error("Failed to load data for \(key): OSStatus \(status)")
57+ }
58+ guard status == errSecSuccess, let data = result as? Data else { return nil }
59+ return data
60+ }
61+
62+ @discardableResult
63+ static func deleteData(for key: String) -> Bool {
64+ let query = baseQuery(for: key)
65+ let status = SecItemDelete(query as CFDictionary)
66+ if status != errSecSuccess && status != errSecItemNotFound {
67+ logger.error("Failed to delete data for \(key): OSStatus \(status)")
68+ }
69+ return status == errSecSuccess || status == errSecItemNotFound
70+ }
71+
72+ // MARK: - Upsert
73+
74+ /// Atomically stores `data` for the given query: tries `SecItemAdd` and,
75+ /// if the item already exists, falls back to `SecItemUpdate`. This avoids
76+ /// the delete-then-add race that could drop a write (and silently return
77+ /// `errSecDuplicateItem`) when two saves overlap.
78+ @discardableResult
79+ private static func upsert(_ data: Data, query: [String: Any], label: String) -> Bool {
80+ var addQuery = query
81+ addQuery[kSecValueData as String] = data
82+ let addStatus = SecItemAdd(addQuery as CFDictionary, nil)
83+ if addStatus == errSecSuccess {
84+ return true
85+ }
86+ if addStatus == errSecDuplicateItem {
87+ let attributes = [kSecValueData as String: data]
88+ let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
89+ if updateStatus != errSecSuccess {
90+ logger.error("Failed to update item for \(label): OSStatus \(updateStatus)")
91+ }
92+ return updateStatus == errSecSuccess
93+ }
94+ logger.error("Failed to save item for \(label): OSStatus \(addStatus)")
95+ return false
96+ }
97+
98+ // MARK: - Base queries
99+
53100 private static func baseQuery(for connectionID: UUID) -> [String: Any] {
101+ baseQuery(for: connectionID.uuidString)
102+ }
103+
104+ private static func baseQuery(for account: String) -> [String: Any] {
54105 [
55106 kSecClass as String: kSecClassGenericPassword,
56107 kSecAttrService as String: service,
57− kSecAttrAccount as String: connectionID.uuidString,
58− kSecUseDataProtectionKeychain as String: true
108+ kSecAttrAccount as String: account
59109 ]
60110 }
61111}
ParseableViewer/Services/ParseableClient.swift+302−49
@@ -51,6 +51,8 @@ enum ParseableError: LocalizedError {
5151 return "Connection timed out. The server may be unreachable."
5252 case NSURLErrorSecureConnectionFailed, NSURLErrorServerCertificateUntrusted:
5353 return "SSL/TLS error. The server certificate may be invalid or untrusted."
54+ case NSURLErrorCancelled:
55+ return "Request cancelled"
5456 default:
5557 return "Network error: \(error.localizedDescription)"
5658 }
@@ -59,27 +61,132 @@ enum ParseableError: LocalizedError {
5961 }
6062}
6163
64+private actor ResponseCache {
65+ private struct Entry: Sendable {
66+ let data: any Sendable
67+ let timestamp: Date
68+ }
69+
70+ private var cache: [String: Entry] = [:]
71+ private let ttl: TimeInterval = 60
72+
73+ func get<T: Sendable>(_ key: String, as type: T.Type) -> T? {
74+ guard let entry = cache[key],
75+ Date().timeIntervalSince(entry.timestamp) < ttl else {
76+ cache.removeValue(forKey: key)
77+ return nil
78+ }
79+ return entry.data as? T
80+ }
81+
82+ func set(_ key: String, value: some Sendable) {
83+ cache[key] = Entry(data: value, timestamp: Date())
84+ }
85+
86+ func invalidate() {
87+ cache.removeAll()
88+ }
89+}
90+
91+/// Strips the `Authorization` header on redirects that cross to a different
92+/// origin. By default `URLSession` re-sends the original request's headers —
93+/// including the `Basic` credentials this client attaches to every request —
94+/// to the redirect target. A server (or a malicious/misconfigured proxy)
95+/// answering with a 3xx to an unrelated host would otherwise harvest the user's
96+/// credentials. Same-origin redirects keep the header so normal auth still works.
97+///
98+/// Holds only an immutable `URL`, so it is safely `Sendable` despite the
99+/// NSObject base (which isn't formally `Sendable`).
100+private final class RedirectSanitizer: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
101+ private let baseURL: URL
102+
103+ init(baseURL: URL) {
104+ self.baseURL = baseURL
105+ }
106+
107+ func urlSession(
108+ _ session: URLSession,
109+ task: URLSessionTask,
110+ willPerformHTTPRedirection response: HTTPURLResponse,
111+ newRequest request: URLRequest,
112+ completionHandler: @escaping (URLRequest?) -> Void
113+ ) {
114+ guard !RedirectSanitizer.sameOrigin(baseURL, request.url) else {
115+ completionHandler(request)
116+ return
117+ }
118+ var sanitized = request
119+ sanitized.setValue(nil, forHTTPHeaderField: "Authorization")
120+ completionHandler(sanitized)
121+ }
122+
123+ /// Origin equality per scheme/host/port, normalizing the implicit default
124+ /// port so `https://host` and `https://host:443` are treated as the same
125+ /// origin (and aren't stripped on a legitimate same-host redirect).
126+ static func sameOrigin(_ a: URL, _ b: URL?) -> Bool {
127+ guard let b else { return false }
128+ return a.scheme?.lowercased() == b.scheme?.lowercased()
129+ && a.host?.lowercased() == b.host?.lowercased()
130+ && effectivePort(a) == effectivePort(b)
131+ }
132+
133+ private static func effectivePort(_ url: URL) -> Int? {
134+ if let port = url.port { return port }
135+ switch url.scheme?.lowercased() {
136+ case "https": return 443
137+ case "http": return 80
138+ default: return nil
139+ }
140+ }
141+}
142+
62143final class ParseableClient: Sendable {
63144 let baseURL: URL
64145 let username: String
65146 let password: String
66147 private let session: URLSession
67−
68− private static let isoFormatter: ISO8601DateFormatter = {
148+ private let authHeader: String
149+ private let cache = ResponseCache()
150+
151+ // A fresh decoder per call. JSONDecoder.decode isn't documented as thread-safe,
152+ // and these methods run concurrently (e.g. schema/stats/info fetched in parallel),
153+ // so a single shared instance would be a data race. Constructing one is cheap.
154+ private static var jsonDecoder: JSONDecoder { JSONDecoder() }
155+
156+ // A fresh formatter per access, for the same reason as `jsonDecoder` above:
157+ // `query` can run concurrently and `ISO8601DateFormatter.string(from:)` isn't
158+ // documented as thread-safe, so a single shared instance would contradict the
159+ // file's per-call concurrency discipline. Constructing one is cheap.
160+ private static var isoFormatter: ISO8601DateFormatter {
69161 let f = ISO8601DateFormatter()
70162 f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
71163 return f
72− }()
164+ }
73165
74166 init(url: URL, username: String, password: String) {
75167 self.baseURL = url
76168 self.username = username
77169 self.password = password
78170
171+ let credentials = "\(username):\(password)"
172+ if let data = credentials.data(using: .utf8) {
173+ self.authHeader = "Basic \(data.base64EncodedString())"
174+ } else {
175+ self.authHeader = "Basic "
176+ }
177+
79178 let config = URLSessionConfiguration.default
80179 config.timeoutIntervalForRequest = 30
81180 config.timeoutIntervalForResource = 120
82− self.session = URLSession(configuration: config)
181+ // Install a delegate that drops the Authorization header on cross-origin
182+ // redirects so Basic credentials can't be forwarded to an unrelated host.
183+ // The session retains the delegate until `finishTasksAndInvalidate()` in
184+ // deinit releases it, so there's no leak.
185+ self.session = URLSession(
186+ configuration: config,
187+ delegate: RedirectSanitizer(baseURL: url),
188+ delegateQueue: nil
189+ )
83190 }
84191
85192 convenience init(connection: ServerConnection) throws {
@@ -95,20 +202,19 @@ final class ParseableClient: Sendable {
95202 session.finishTasksAndInvalidate()
96203 }
97204
98− private var authHeader: String {
99− let credentials = "\(username):\(password)"
100− guard let data = credentials.data(using: .utf8) else {
101− return "Basic "
102− }
103− return "Basic \(data.base64EncodedString())"
104− }
105−
106205 private func buildRequest(method: String, path: String, body: Data? = nil, queryItems: [URLQueryItem]? = nil) throws -> URLRequest {
107− var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)
206+ // `path` already contains percent-encoded dynamic segments (see
207+ // `encodePathComponent`). Append it via `percentEncodedPath` rather than
208+ // `URL.appendingPathComponent`, which would re-encode the `%` characters
209+ // and corrupt names containing spaces or other reserved characters.
210+ guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {
211+ throw ParseableError.invalidURL
212+ }
213+ components.percentEncodedPath += path
108214 if let queryItems {
109− components?.queryItems = queryItems
215+ components.queryItems = queryItems
110216 }
111− guard let url = components?.url else {
217+ guard let url = components.url else {
112218 throw ParseableError.invalidURL
113219 }
114220
@@ -136,7 +242,11 @@ final class ParseableClient: Sendable {
136242 }
137243
138244 guard (200...299).contains(httpResponse.statusCode) else {
139− let message = String(data: data, encoding: .utf8) ?? "Unknown error"
245+ // A proxy/load balancer can answer with a multi-KB HTML body; surfacing
246+ // it verbatim floods the error alert. Trim and cap to a readable prefix.
247+ let raw = (String(data: data, encoding: .utf8) ?? "")
248+ .trimmingCharacters(in: .whitespacesAndNewlines)
249+ let message = raw.isEmpty ? "Unknown error" : String(raw.prefix(500))
140250 throw ParseableError.serverError(httpResponse.statusCode, message)
141251 }
142252
@@ -154,21 +264,28 @@ final class ParseableClient: Sendable {
154264 if httpResponse.statusCode == 401 {
155265 throw ParseableError.unauthorized
156266 }
157− guard httpResponse.statusCode == 200 else {
267+ // Accept any 2xx — a HEAD /liveness can legitimately return 204, etc.
268+ guard (200...299).contains(httpResponse.statusCode) else {
158269 throw ParseableError.serverError(httpResponse.statusCode, "Health check failed")
159270 }
160271 }
161272
162273 func getAbout() async throws -> ServerAbout {
274+ let key = "about"
275+ if let cached: ServerAbout = await cache.get(key, as: ServerAbout.self) {
276+ return cached
277+ }
163278 let data = try await performRequest(method: "GET", path: "/api/v1/about")
164− return try JSONDecoder().decode(ServerAbout.self, from: data)
279+ let result = try Self.jsonDecoder.decode(ServerAbout.self, from: data)
280+ await cache.set(key, value: result)
281+ return result
165282 }
166283
167284 // MARK: - Log Streams
168285
169286 func listStreams() async throws -> [LogStream] {
170287 let data = try await performRequest(method: "GET", path: "/api/v1/logstream")
171− return try JSONDecoder().decode([LogStream].self, from: data)
288+ return try Self.jsonDecoder.decode([LogStream].self, from: data)
172289 }
173290
174291 private static func encodePathComponent(_ name: String) throws -> String {
@@ -184,38 +301,62 @@ final class ParseableClient: Sendable {
184301 func createStream(name: String) async throws {
185302 let encoded = try Self.encodePathComponent(name)
186303 _ = try await performRequest(method: "PUT", path: "/api/v1/logstream/\(encoded)")
304+ // Recreating a same-named stream must not serve a previous stream's
305+ // cached schema/stats/info (cached for 60s), so drop the cache.
306+ await cache.invalidate()
187307 }
188308
189309 func deleteStream(name: String) async throws {
190310 let encoded = try Self.encodePathComponent(name)
191311 _ = try await performRequest(method: "DELETE", path: "/api/v1/logstream/\(encoded)")
312+ // Invalidate so a later same-named stream doesn't see stale schema/stats/info.
313+ await cache.invalidate()
192314 }
193315
194316 func getStreamSchema(stream: String) async throws -> StreamSchema {
317+ let key = "schema:\(stream)"
318+ if let cached: StreamSchema = await cache.get(key, as: StreamSchema.self) {
319+ return cached
320+ }
195321 let encoded = try Self.encodePathComponent(stream)
196322 let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/schema")
197− return try JSONDecoder().decode(StreamSchema.self, from: data)
323+ let result = try Self.jsonDecoder.decode(StreamSchema.self, from: data)
324+ await cache.set(key, value: result)
325+ return result
198326 }
199327
200328 func getStreamStats(stream: String) async throws -> StreamStats {
329+ let key = "stats:\(stream)"
330+ if let cached: StreamStats = await cache.get(key, as: StreamStats.self) {
331+ return cached
332+ }
201333 let encoded = try Self.encodePathComponent(stream)
202334 let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/stats")
203− return try JSONDecoder().decode(StreamStats.self, from: data)
335+ let result = try Self.jsonDecoder.decode(StreamStats.self, from: data)
336+ await cache.set(key, value: result)
337+ return result
204338 }
205339
206340 func getStreamInfo(stream: String) async throws -> StreamInfo {
341+ let key = "info:\(stream)"
342+ if let cached: StreamInfo = await cache.get(key, as: StreamInfo.self) {
343+ return cached
344+ }
207345 let encoded = try Self.encodePathComponent(stream)
208346 let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/info")
209− return try JSONDecoder().decode(StreamInfo.self, from: data)
347+ let result = try Self.jsonDecoder.decode(StreamInfo.self, from: data)
348+ await cache.set(key, value: result)
349+ return result
210350 }
211351
212352 // MARK: - Query
213353
214354 func query(sql: String, startTime: Date, endTime: Date) async throws -> [LogRecord] {
355+ let formatter = Self.isoFormatter
215356 let body: [String: Any] = [
216357 "query": sql,
217− "startTime": Self.isoFormatter.string(from: startTime),
218− "endTime": Self.isoFormatter.string(from: endTime)
358+ "startTime": formatter.string(from: startTime),
359+ "endTime": formatter.string(from: endTime)
219360 ]
220361
221362 let bodyData = try JSONSerialization.data(withJSONObject: body)
@@ -225,36 +366,138 @@ final class ParseableClient: Sendable {
225366 return []
226367 }
227368
228− // Handle both response formats:
229− // 1. Wrapped: {"records": [...], "fields": [...]}
230− // 2. Direct array: [...]
231− if let wrapped = try? JSONDecoder().decode(QueryResponse.self, from: responseData) {
232− return wrapped.records
369+ // Peek at the first meaningful byte to choose the decoder path:
370+ // '{' → wrapped response, '[' → direct array. Skip a leading UTF-8 BOM
371+ // (0xEF 0xBB 0xBF) and ASCII whitespace so a BOM-prefixed wrapped
372+ // response isn't misrouted to the array decoder. (JSONDecoder itself
373+ // tolerates the BOM.)
374+ var sniff = responseData
375+ if sniff.starts(with: [0xEF, 0xBB, 0xBF]) {
376+ sniff = sniff.dropFirst(3)
233377 }
234− do {
235− return try JSONDecoder().decode([LogRecord].self, from: responseData)
236− } catch {
237− throw ParseableError.decodingError("Unexpected query response format")
378+ let firstByte = sniff.first(where: { $0 != 0x20 && $0 != 0x0A && $0 != 0x0D && $0 != 0x09 })
379+ // A body of only whitespace/BOM carries no records — treat it like an
380+ // empty response rather than feeding it to the array decoder, which would
381+ // throw a confusing "Unexpected query response format".
382+ guard let firstByte else { return [] }
383+ if firstByte == 0x7B { // '{'
384+ do {
385+ return try Self.jsonDecoder.decode(QueryResponse.self, from: responseData).records
386+ } catch {
387+ throw ParseableError.decodingError("Unexpected query response format")
388+ }
389+ } else {
390+ do {
391+ return try Self.jsonDecoder.decode([LogRecord].self, from: responseData)
392+ } catch {
393+ throw ParseableError.decodingError("Unexpected query response format")
394+ }
238395 }
239396 }
240397
241398 // MARK: - Alerts
242399
243400 func getAlerts(stream: String) async throws -> AlertConfig {
244− // Try new API first; only fall back to legacy per-stream endpoint on 404
401+ // Try the new API first. Fall back to the legacy per-stream endpoint on
402+ // ANY failure — a server without the new endpoint may answer with a 404,
403+ // a 405, or a 200 carrying a differently-shaped body (a DecodingError,
404+ // which is not a ParseableError and would otherwise escape this method).
405+ let encoded = try Self.encodePathComponent(stream)
406+
407+ func legacyAlerts() async throws -> AlertConfig {
408+ let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/alert")
409+ return try Self.jsonDecoder.decode(AlertConfig.self, from: data)
410+ }
411+
412+ // `/api/v1/alerts` paginates (default page size 100, max 1000) over ALL
413+ // alerts server-wide, ordered by state/severity/title. Filtering only the
414+ // first page by stream (below) silently missed any stream whose alerts sort
415+ // past it. Request full pages until a short one. Servers that predate
416+ // pagination ignore the parameters and return everything each time, so a
417+ // page that adds nothing new also ends the loop.
418+ func modernAlerts() async throws -> (data: Data, config: AlertConfig) {
419+ let pageSize = 1000
420+ var firstData: Data?
421+ var version: String?
422+ var collected: [AlertRule] = []
423+ var seenIDs = Set<String>()
424+ var offset = 0
425+ for _ in 0..<50 {
426+ let data: Data
427+ do {
428+ data = try await performRequest(
429+ method: "GET",
430+ path: "/api/v1/alerts",
431+ queryItems: [
432+ URLQueryItem(name: "limit", value: String(pageSize)),
433+ URLQueryItem(name: "offset", value: String(offset)),
434+ ]
435+ )
436+ } catch ParseableError.serverError(let code, _) where code == 400 && offset == 0 {
437+ // A server that rejects the paging parameters: one plain request.
438+ let data = try await performRequest(method: "GET", path: "/api/v1/alerts")
439+ return (data, try Self.jsonDecoder.decode(AlertConfig.self, from: data))
440+ }
441+ let page = try Self.jsonDecoder.decode(AlertConfig.self, from: data)
442+ if firstData == nil {
443+ firstData = data
444+ version = page.version
445+ }
446+ let alerts = page.alerts ?? []
447+ let fresh = alerts.filter { seenIDs.insert($0.id).inserted }
448+ collected.append(contentsOf: fresh)
449+ if alerts.count < pageSize || fresh.isEmpty { break }
450+ offset += alerts.count
451+ }
452+ return (firstData ?? Data(), AlertConfig(alerts: collected, version: version))
453+ }
454+
245455 do {
246− let data = try await performRequest(method: "GET", path: "/api/v1/alerts")
247− return try JSONDecoder().decode(AlertConfig.self, from: data)
248− } catch let error as ParseableError {
249− if case .serverError(let code, _) = error, code == 404 {
250− // New endpoint not available, try legacy below
251− } else {
252− throw error
456+ let (data, config) = try await modernAlerts()
457+ // AlertConfig decodes leniently (every field via try?), so a 200 with
458+ // an unexpected body yields an empty, non-throwing config rather than
459+ // a DecodingError — indistinguishable from a server that genuinely has
460+ // no alerts. Only fall back to the legacy per-stream endpoint when the
461+ // body ISN'T a recognizable alerts container. Any top-level JSON array
462+ // OR object is the modern endpoint answering — including an empty object
463+ // `{}` or `{"alerts": []}` meaning "no alerts" — and is authoritative, so
464+ // it must not be replaced with unrelated legacy per-stream alerts. Only a
465+ // non-JSON / unparseable body counts as unrecognized.
466+ if config.alerts?.isEmpty ?? true {
467+ let json = try? JSONSerialization.jsonObject(with: data)
468+ let isRecognizedShape = json is [Any] || json is [String: Any]
469+ if !isRecognizedShape,
470+ let legacy = try? await legacyAlerts(), !(legacy.alerts?.isEmpty ?? true) {
471+ return legacy
472+ }
473+ }
474+ // `/api/v1/alerts` is server-global; the legacy endpoint above is already
475+ // per-stream. Scope the modern result to the requested stream via each
476+ // alert's `datasets` membership so every stream doesn't show the same
477+ // unfiltered global list.
478+ let scoped = config.alerts?.filter { rule in
479+ // A missing or empty `datasets` means the alert isn't scoped to
480+ // specific streams (the summary endpoint frequently omits it), so
481+ // treat it as global and surface it for every stream. Only exclude
482+ // an alert when it explicitly lists datasets, none of which match.
483+ guard let datasets = rule.datasets, !datasets.isEmpty else { return true }
484+ return datasets.contains(stream)
485+ }
486+ return AlertConfig(alerts: scoped, version: config.version)
487+ } catch let newEndpointError {
488+ // An auth failure won't be fixed by hitting the legacy endpoint (it
489+ // would just 401 again), so surface it immediately rather than
490+ // delaying the re-auth prompt behind a second failing round-trip.
491+ if case ParseableError.unauthorized = newEndpointError {
492+ throw newEndpointError
493+ }
494+ do {
495+ return try await legacyAlerts()
496+ } catch {
497+ // Legacy also failed — surface the original (more informative) error.
498+ throw newEndpointError
253499 }
254500 }
255− let encoded = try Self.encodePathComponent(stream)
256− let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/alert")
257− return try JSONDecoder().decode(AlertConfig.self, from: data)
258501 }
259502
260503 // MARK: - Retention
@@ -264,11 +507,17 @@ final class ParseableClient: Sendable {
264507 let data = try await performRequest(method: "GET", path: "/api/v1/logstream/\(encoded)/retention")
265508 if data.isEmpty { return [] }
266509 // Handle both array and single object response
267− if let array = try? JSONDecoder().decode([RetentionConfig].self, from: data) {
510+ if let array = try? Self.jsonDecoder.decode([RetentionConfig].self, from: data) {
268511 return array
269512 }
270513 do {
271− let single = try JSONDecoder().decode(RetentionConfig.self, from: data)
514+ let single = try Self.jsonDecoder.decode(RetentionConfig.self, from: data)
515+ // RetentionConfig decodes every field with `try?`, so any JSON object
516+ // (including `{}` or an error body) decodes to an all-nil config. Treat
517+ // an empty config as "no retention" rather than a phantom policy entry.
518+ guard single.description != nil || single.duration != nil || single.action != nil else {
519+ return []
520+ }
272521 return [single]
273522 } catch {
274523 throw ParseableError.decodingError("Unexpected retention response format")
@@ -279,7 +528,7 @@ final class ParseableClient: Sendable {
279528
280529 func listUsers() async throws -> [UserInfo] {
281530 let data = try await performRequest(method: "GET", path: "/api/v1/user")
282− return try JSONDecoder().decode([UserInfo].self, from: data)
531+ return try Self.jsonDecoder.decode([UserInfo].self, from: data)
283532 }
284533
285534 // MARK: - Filters
@@ -287,17 +536,21 @@ final class ParseableClient: Sendable {
287536 func listFilters() async throws -> [ParseableFilter] {
288537 let data = try await performRequest(method: "GET", path: "/api/v1/filters")
289538 if data.isEmpty { return [] }
290− return try JSONDecoder().decode([ParseableFilter].self, from: data)
539+ return try Self.jsonDecoder.decode([ParseableFilter].self, from: data)
291540 }
292541
293542 func createFilter(_ filter: ParseableFilter) async throws -> ParseableFilter {
294543 let body = try JSONEncoder().encode(filter)
295544 let data = try await performRequest(method: "POST", path: "/api/v1/filters", body: body)
296− return try JSONDecoder().decode(ParseableFilter.self, from: data)
545+ return try Self.jsonDecoder.decode(ParseableFilter.self, from: data)
297546 }
298547
299548 func deleteFilter(id: String) async throws {
300549 let encoded = try Self.encodePathComponent(id)
301550 _ = try await performRequest(method: "DELETE", path: "/api/v1/filters/\(encoded)")
302551 }
552+
553+ func invalidateCache() async {
554+ await cache.invalidate()
555+ }
303556}
ParseableViewer/ViewModels/LiveTailViewModel.swift+445−90
@@ -7,7 +7,9 @@ final class LiveTailViewModel {
77 var entries: [LiveTailEntry] = []
88 var isRunning = false
99 var isPaused = false
10− var filterText = ""
10+ var filterText = "" {
11+ didSet { rebuildFilteredEntries() }
12+ }
1113 var columnFilters: [ColumnFilter] = []
1214 var pollInterval: TimeInterval = 2.0
1315 var maxEntries = 5000
@@ -19,34 +21,82 @@ final class LiveTailViewModel {
1921 var columns: [String] = []
2022 var columnOrder: [String] = []
2123 var hiddenColumns: Set<String> = []
24+ /// The full persisted set of hidden columns, including ones not yet seen in
25+ /// this session. Live-tail columns are discovered incrementally across polls,
26+ /// so `hiddenColumns` (only the seen ones) can't be the source of truth — a
27+ /// column hidden last session would reappear visible when it shows up in a
28+ /// later poll. This retains the intent so it stays hidden when it appears.
29+ private var savedHiddenColumns: Set<String> = []
30+ /// The full persisted column order, including columns not yet seen this
31+ /// session — the order counterpart of `savedHiddenColumns`. A column that
32+ /// first shows up in a later poll is slotted back into its saved position
33+ /// (instead of being appended), and saving keeps unseen columns' positions
34+ /// rather than dropping them from the stored order.
35+ private var savedColumnOrder: [String] = []
2236 private var currentStream: String?
2337
2438 // nonisolated(unsafe) so deinit can invalidate the timer.
2539 // Only mutated from @MainActor methods (start/stop).
2640 nonisolated(unsafe) private var timer: Timer?
2741 private var lastTimestamp: Date?
28− private var seenFingerprints: Set<String> = []
42+ /// How many records with each content fingerprint have been delivered. A
43+ /// count rather than a set: Parseable stamps every event of one ingest request
44+ /// with the same millisecond `p_timestamp`, so genuinely repeated events (the
45+ /// same log line emitted three times) fingerprint identically. A set collapsed
46+ /// them into one row; counting keeps each occurrence while still suppressing
47+ /// the re-fetch of the same rows by the next overlapping poll window.
48+ private var seenFingerprints: [String: Int] = [:]
49+ /// Insertion-ordered mirror of `seenFingerprints` keys (oldest first), used to
50+ /// evict the least-recently-seen fingerprints when the set is trimmed.
51+ private var seenFingerprintOrder: [String] = []
52+ /// Upper bound on the dedup fingerprint set. Kept well above `maxEntries` so
53+ /// fingerprints of recently-evicted entries survive long enough to suppress
54+ /// duplicates that reappear inside the next poll's look-back window, while
55+ /// still bounding memory. Only when this is exceeded do we fall back to the
56+ /// retained-entry fingerprints.
57+ private var maxSeenFingerprints: Int { maxEntries * 4 }
58+ private var allKnownKeys: Set<String> = []
2959 private var consecutiveErrors = 0
3060 private static let maxConsecutiveErrors = 5
61+ /// Guards against overlapping polls: if a poll's network round-trip outlasts
62+ /// the timer interval, the next tick must not start a second concurrent poll
63+ /// (which would let the two interleave and write `lastTimestamp` /
64+ /// `consecutiveErrors` out of order).
65+ private var isPolling = false
66+ /// Bumped by start()/stop()/clear() so an in-flight poll whose network
67+ /// round-trip outlives one of those transitions can detect it was superseded
68+ /// and drop its results instead of repopulating a torn-down/cleared tail.
69+ private var pollGeneration = 0
3170
3271 deinit {
33− timer?.invalidate()
72+ // Timer.invalidate() must run on the run loop the timer was scheduled on
73+ // (RunLoop.main, see start()). deinit is nonisolated and can run off the
74+ // main thread, so hop to the main queue rather than invalidating inline.
75+ // The scheduled timer only weakly references self, so deferring teardown
76+ // past deallocation is safe — at worst it fires once more as a no-op
77+ // before being invalidated. stop() remains the normal teardown path.
78+ if let timer {
79+ DispatchQueue.main.async { timer.invalidate() }
80+ }
3481 }
3582
36− // Cached formatters to avoid per-poll allocation
37− private static let displayFormatter: DateFormatter = {
83+ // Cached formatters — nonisolated(unsafe) so static methods can use them from Task.detached
84+ nonisolated(unsafe) private static let displayFormatter: DateFormatter = {
3885 let f = DateFormatter()
86+ // Fixed-format formatters must use en_US_POSIX so a non-Gregorian or
87+ // non-Latin-digit system locale doesn't render wrong numerals/era.
88+ f.locale = Locale(identifier: "en_US_POSIX")
3989 f.dateFormat = "HH:mm:ss.SSS"
4090 return f
4191 }()
4292
43− private static let isoFractional: ISO8601DateFormatter = {
93+ nonisolated(unsafe) private static let isoFractional: ISO8601DateFormatter = {
4494 let f = ISO8601DateFormatter()
4595 f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
4696 return f
4797 }()
4898
49− private static let isoBasic: ISO8601DateFormatter = {
99+ nonisolated(unsafe) private static let isoBasic: ISO8601DateFormatter = {
50100 let f = ISO8601DateFormatter()
51101 f.formatOptions = [.withInternetDateTime]
52102 return f
@@ -58,6 +108,7 @@ final class LiveTailViewModel {
58108 let record: LogRecord
59109 let displayTimestamp: String
60110 let summary: String
111+ let fingerprint: String
61112 }
62113
63114 struct ColumnFilter: Identifiable, Equatable, Sendable {
@@ -73,50 +124,83 @@ final class LiveTailViewModel {
73124 }
74125 }
75126
76− var filteredEntries: [LiveTailEntry] {
77− var result = entries
78−
79− // Apply column filters
80− for filter in columnFilters {
81− result = result.filter { entry in
82− let recordValue = entry.record[filter.column]
83− let matches: Bool
84− if filter.value == nil || filter.value == .null {
85− matches = recordValue == nil || recordValue == .null
86− } else {
87− matches = recordValue == filter.value
88− }
89− return filter.exclude ? !matches : matches
90− }
91− }
127+ private(set) var cachedFilteredEntries: [LiveTailEntry] = []
128+ var cachedFilteredRecords: [LogRecord] {
129+ cachedFilteredEntries.map { $0.record }
130+ }
131+ private(set) var filteredEntriesGeneration: Int = 0
132+
133+ private func rebuildFilteredEntries() {
134+ let hasColumnFilters = !columnFilters.isEmpty
135+ let hasTextFilter = !filterText.isEmpty
136+ let activeFilters = columnFilters
137+ let text = filterText
92138
93− // Apply text filter
94− if !filterText.isEmpty {
95− result = result.filter { entry in
96− entry.summary.localizedCaseInsensitiveContains(filterText) ||
97− entry.record.values.contains { $0.displayString.localizedCaseInsensitiveContains(filterText) }
139+ let result: [LiveTailEntry]
140+ if !hasColumnFilters && !hasTextFilter {
141+ result = entries
142+ } else {
143+ result = entries.filter { entry in
144+ if hasColumnFilters {
145+ for filter in activeFilters {
146+ let recordValue = entry.record[filter.column]
147+ let matches: Bool
148+ if filter.value == nil || filter.value == .null {
149+ matches = recordValue == nil || recordValue == .null
150+ } else {
151+ matches = recordValue == filter.value
152+ }
153+ if filter.exclude ? matches : !matches {
154+ return false
155+ }
156+ }
157+ }
158+ if hasTextFilter {
159+ if !entry.summary.localizedCaseInsensitiveContains(text) &&
160+ !entry.record.values.contains(where: { $0.displayString.localizedCaseInsensitiveContains(text) }) {
161+ return false
162+ }
163+ }
164+ return true
98165 }
99166 }
100167
101− return result
168+ cachedFilteredEntries = result
169+ filteredEntriesGeneration += 1
102170 }
103171
104172 func addColumnFilter(column: String, value: JSONValue?, exclude: Bool) {
105− // Remove any existing filter on the same column with the same value
106− columnFilters.removeAll { $0.column == column && $0.value == value && $0.exclude == exclude }
173+ // Remove any existing filter on the same column+value regardless of its
174+ // exclude flag. Include (col = X) and exclude (col ≠ X) on the same value
175+ // are mutually exclusive; without dropping the `exclude` match too, toggling
176+ // include↔exclude stacks both and the AND'd filters match zero rows, so the
177+ // tail silently empties.
178+ columnFilters.removeAll { $0.column == column && $0.value == value }
179+ if !exclude {
180+ // Include filters are AND-combined in rebuildFilteredEntries, but a column
181+ // can only equal one value, so two includes on the same column with
182+ // different values (e.g. level = info then level = error) can never both
183+ // match and the tail would silently empty. A new include therefore
184+ // replaces any prior include on that column. (Excludes legitimately stack:
185+ // col ≠ a AND col ≠ b is meaningful, so they are left untouched here.)
186+ columnFilters.removeAll { $0.column == column && !$0.exclude }
187+ }
107188 columnFilters.append(ColumnFilter(column: column, value: value, exclude: exclude))
189+ rebuildFilteredEntries()
108190 }
109191
110192 func removeColumnFilter(_ filter: ColumnFilter) {
111193 columnFilters.removeAll { $0.id == filter.id }
194+ rebuildFilteredEntries()
112195 }
113196
114197 func clearColumnFilters() {
115198 columnFilters.removeAll()
199+ rebuildFilteredEntries()
116200 }
117201
118202 var entryCount: Int { entries.count }
119− var displayedCount: Int { filteredEntries.count }
203+ var displayedCount: Int { cachedFilteredEntries.count }
120204
121205 func start(client: ParseableClient?, stream: String?) {
122206 guard let client, let stream, !isRunning else { return }
@@ -127,11 +211,19 @@ final class LiveTailViewModel {
127211 let storedMax = UserDefaults.standard.integer(forKey: "liveTailMaxEntries")
128212 if storedMax > 0 { maxEntries = storedMax }
129213
214+ pollGeneration += 1
130215 isRunning = true
131216 isPaused = false
217+ // Reset the in-flight guard: if a poll was awaiting its network round-trip
218+ // when the tail was stopped, its `defer { isPolling = false }` only runs when
219+ // that request finally returns. Without clearing it here, the new timer's
220+ // first tick would hit `guard !isPolling` and be skipped for a whole interval.
221+ isPolling = false
132222 errorMessage = nil
133223 entries = []
134− seenFingerprints = []
224+ seenFingerprints = [:]
225+ seenFingerprintOrder = []
226+ allKnownKeys = []
135227 droppedCount = 0
136228 consecutiveErrors = 0
137229 lastPollTime = nil
@@ -139,18 +231,33 @@ final class LiveTailViewModel {
139231 columns = []
140232 columnOrder = []
141233 hiddenColumns = []
234+ savedHiddenColumns = []
235+ savedColumnOrder = []
142236 columnFilters = []
237+ // Clear the text filter too. Leaving it set while clearing the column-filter
238+ // chips is inconsistent and would let a stale search from a previous stream
239+ // make the fresh tail come up appearing empty or partially filtered.
240+ filterText = ""
143241 currentStream = stream
144−
145− timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in
242+ rebuildFilteredEntries()
243+
244+ // Install the timer in `.common` modes so polling keeps firing while the
245+ // main run loop is in event-tracking mode (scrolling, dragging a column,
246+ // an open menu/popover). A `.default`-only timer — what
247+ // `scheduledTimer(withTimeInterval:)` installs — silently pauses during
248+ // those interactions, freezing the "live" tail until the user lets go.
249+ let pollTimer = Timer(timeInterval: pollInterval, repeats: true) { [weak self] _ in
146250 Task { @MainActor [weak self] in
147251 guard let self, !self.isPaused else { return }
148252 await self.poll(client: client, stream: stream)
149253 }
150254 }
255+ RunLoop.main.add(pollTimer, forMode: .common)
256+ timer = pollTimer
151257 }
152258
153259 func stop() {
260+ pollGeneration += 1
154261 timer?.invalidate()
155262 timer = nil
156263 isRunning = false
@@ -162,13 +269,38 @@ final class LiveTailViewModel {
162269 }
163270
164271 func clear() {
272+ pollGeneration += 1
273+ // Match start(): drop the in-flight guard so a poll still awaiting its
274+ // response (whose results this generation bump will discard) can't make the
275+ // next timer tick skip itself via `guard !isPolling`.
276+ isPolling = false
165277 entries = []
166− seenFingerprints = []
278+ // Keep the dedup fingerprints (unlike start(), which begins a new session):
279+ // every poll looks back at least 90 s regardless of `lastTimestamp` (see
280+ // `safeStart` in poll()), so the records just cleared are re-fetched by the
281+ // next poll. With an emptied fingerprint set they all passed dedup again and
282+ // the tail refilled with exactly what the user cleared. The set stays
283+ // bounded by the eviction in poll().
284+ lastTimestamp = Date()
285+ allKnownKeys = []
167286 droppedCount = 0
287+ // Reset the failure counter too: the timer keeps polling after a clear, so
288+ // leaving accumulated errors in place could trip the auto-stop threshold
289+ // sooner than the intended N consecutive failures. Matches start()'s reset.
290+ consecutiveErrors = 0
291+ // Match start(): a freshly emptied tail has no last-poll timestamp, so any
292+ // "last updated at…" indicator shouldn't keep showing the pre-clear time.
293+ lastPollTime = nil
168294 columns = []
169295 columnOrder = []
170296 hiddenColumns = []
297+ savedHiddenColumns = []
298+ savedColumnOrder = []
171299 columnFilters = []
300+ // Match start(): clear the text filter alongside the column-filter chips so
301+ // a clear()ed tail isn't immediately re-hidden by a lingering search string.
302+ filterText = ""
303+ rebuildFilteredEntries()
172304 }
173305
174306 // MARK: - Column Management
@@ -180,10 +312,12 @@ final class LiveTailViewModel {
180312 func toggleColumnVisibility(_ column: String) {
181313 if hiddenColumns.contains(column) {
182314 hiddenColumns.remove(column)
315+ savedHiddenColumns.remove(column)
183316 } else {
184317 let visibleCount = columnOrder.count - hiddenColumns.count
185318 if visibleCount > 1 {
186319 hiddenColumns.insert(column)
320+ savedHiddenColumns.insert(column)
187321 }
188322 }
189323 saveColumnConfig()
@@ -191,6 +325,7 @@ final class LiveTailViewModel {
191325
192326 func showAllColumns() {
193327 hiddenColumns.removeAll()
328+ savedHiddenColumns.removeAll()
194329 saveColumnConfig()
195330 }
196331
@@ -204,13 +339,21 @@ final class LiveTailViewModel {
204339 let toIndex = columnOrder.firstIndex(of: targetColumn),
205340 fromIndex != toIndex else { return }
206341 let item = columnOrder.remove(at: fromIndex)
207− columnOrder.insert(item, at: toIndex)
342+ // Match the drop-indicator semantics: a rightward move (fromIndex < toIndex)
343+ // lands the column *after* the target, a leftward move lands it *before*.
344+ // After removing an earlier element the target shifts down by one, so
345+ // inserting at `toIndex` lands after the target for rightward moves; for
346+ // leftward moves the target is unshifted and `toIndex` lands before it.
347+ let adjusted = toIndex
348+ columnOrder.insert(item, at: adjusted)
208349 saveColumnConfig()
209350 }
210351
211352 func resetColumnConfig() {
212353 columnOrder = columns
354+ savedColumnOrder = []
213355 hiddenColumns.removeAll()
356+ savedHiddenColumns.removeAll()
214357 saveColumnConfig()
215358 }
216359
@@ -222,7 +365,16 @@ final class LiveTailViewModel {
222365
223366 private func saveColumnConfig() {
224367 guard let stream = currentStream else { return }
225− let config = QueryViewModel.ColumnConfiguration(order: columnOrder, hidden: hiddenColumns)
368+ // Persist the full intended hidden set and order (including columns not
369+ // yet seen this session) so they survive restarts and incremental discovery.
370+ let seen = Set(columnOrder)
371+ let order = QueryViewModel.mergedColumnOrder(
372+ columnOrder,
373+ inserting: savedColumnOrder.filter { !seen.contains($0) },
374+ reference: savedColumnOrder
375+ )
376+ savedColumnOrder = order
377+ let config = QueryViewModel.ColumnConfiguration(order: order, hidden: savedHiddenColumns)
226378 if let data = try? JSONEncoder().encode(config) {
227379 UserDefaults.standard.set(data, forKey: Self.columnConfigKey(for: stream))
228380 }
@@ -235,26 +387,21 @@ final class LiveTailViewModel {
235387
236388 // MARK: - Column Extraction
237389
238− private func extractColumns(from records: [LogRecord]) -> [String] {
390+ private func extractColumnsFromKeys(_ keys: Set<String>) -> [String] {
239391 let priorityFields = ["p_timestamp", "p_tags", "p_metadata", "level", "severity", "message", "msg"]
240− var allKeys = Set<String>()
241− for record in records {
242− allKeys.formUnion(record.keys)
243− }
244−
392+ var remaining = keys
245393 var ordered: [String] = []
246394 for field in priorityFields {
247− if allKeys.remove(field) != nil {
395+ if remaining.remove(field) != nil {
248396 ordered.append(field)
249397 }
250398 }
251− ordered.append(contentsOf: allKeys.sorted())
399+ ordered.append(contentsOf: remaining.sorted())
252400 return ordered
253401 }
254402
255403 private func updateColumns(stream: String) {
256− let allRecords = entries.map { $0.record }
257− let extracted = extractColumns(from: allRecords)
404+ let extracted = extractColumnsFromKeys(allKnownKeys)
258405
259406 if columns.isEmpty {
260407 // First time — apply saved config
@@ -269,9 +416,13 @@ final class LiveTailViewModel {
269416 merged.append(col)
270417 }
271418 columnOrder = merged
419+ savedColumnOrder = config.order
420+ savedHiddenColumns = config.hidden
272421 hiddenColumns = config.hidden.intersection(extractedSet)
273422 } else {
274423 columnOrder = extracted
424+ savedColumnOrder = []
425+ savedHiddenColumns = []
275426 hiddenColumns = []
276427 }
277428 } else {
@@ -283,12 +434,38 @@ final class LiveTailViewModel {
283434 }
284435 if !newCols.isEmpty {
285436 columns.append(contentsOf: newCols)
286− columnOrder.append(contentsOf: newCols)
437+ columnOrder = QueryViewModel.mergedColumnOrder(columnOrder, inserting: newCols, reference: savedColumnOrder)
438+ // Re-hide any newly appearing column that was hidden in a prior
439+ // session but hadn't been seen yet this run.
440+ hiddenColumns.formUnion(newCols.filter { savedHiddenColumns.contains($0) })
287441 }
288442 }
443+
444+ // The `visibleCount > 1` guard in toggleColumnVisibility only covers
445+ // user toggles. The config-load and incremental-merge paths above can
446+ // hide every known column (e.g. a saved-hidden set that happens to cover
447+ // all columns seen so far), which would render the live-tail table with
448+ // zero columns. Keep at least the first column visible.
449+ if !columnOrder.isEmpty, hiddenColumns.count >= columnOrder.count,
450+ let firstColumn = columnOrder.first {
451+ hiddenColumns.remove(firstColumn)
452+ }
289453 }
290454
291455 private func poll(client: ParseableClient, stream: String) async {
456+ let generation = pollGeneration
457+ guard !isPolling else { return }
458+ isPolling = true
459+ // Only release the guard if this poll is still the current generation. A
460+ // stop()/start() during the network await can supersede this poll while a
461+ // newer-generation poll is already in flight; clearing isPolling
462+ // unconditionally would let a subsequent timer tick start a second poll
463+ // that overlaps the newer one, racing writes to lastTimestamp /
464+ // consecutiveErrors. start()/clear() reset isPolling on their own
465+ // generation bump, so a superseded poll leaving it set can't wedge the
466+ // new timer.
467+ defer { if generation == pollGeneration { isPolling = false } }
468+
292469 let now = Date()
293470 // The Parseable server truncates query time-ranges to minute
294471 // boundaries, so a narrow window (< 60 s) can collapse to a
@@ -298,27 +475,59 @@ final class LiveTailViewModel {
298475 let idealStart = lastTimestamp ?? now.addingTimeInterval(-30)
299476 let safeStart = now.addingTimeInterval(-90)
300477 let queryStart = min(idealStart, safeStart)
301− let sql = "SELECT * FROM \(QueryViewModel.escapeSQLIdentifier(stream)) ORDER BY p_timestamp DESC LIMIT 200"
478+ // ORDER BY DESC keeps the newest rows when the page is capped, so a busy
479+ // stream that exceeds the limit within one ~90 s window silently loses the
480+ // oldest rows in that window. Keep a generous page to make that rare; this
481+ // HTTP-polling tail can't match true gRPC streaming throughput regardless.
482+ let sql = "SELECT * FROM \(QueryViewModel.escapeSQLIdentifier(stream)) ORDER BY p_timestamp DESC LIMIT 1000"
302483
303484 do {
304485 let records = try await client.query(sql: sql, startTime: queryStart, endTime: now)
305486
306− var newEntries: [LiveTailEntry] = []
307−
308− for record in records {
309− let fp = Self.fingerprint(for: record)
310− guard !seenFingerprints.contains(fp) else { continue }
311− seenFingerprints.insert(fp)
487+ // A stop()/clear()/start during the network round-trip supersedes this
488+ // poll; don't write stale results to a torn-down or cleared tail. Also
489+ // bail if the user paused mid-flight.
490+ guard isRunning, !isPaused, generation == pollGeneration else { return }
491+
492+ // Process records off the main actor using a snapshot of seen fingerprints
493+ let seenSnapshot = seenFingerprints
494+ let pollTime = now
495+ let (candidateEntries, batchCounts) = await Task.detached(priority: .userInitiated) {
496+ var results: [(entry: LiveTailEntry, occurrence: Int)] = []
497+ var counts: [String: Int] = [:]
498+ for record in records {
499+ let fp = Self.fingerprint(for: record)
500+ let occurrence = (counts[fp] ?? 0) + 1
501+ counts[fp] = occurrence
502+ // The first `seen` occurrences of this content were delivered
503+ // by earlier polls; only later ones are new.
504+ guard occurrence > (seenSnapshot[fp] ?? 0) else { continue }
505+ let timestamp = Self.parseTimestamp(from: record) ?? pollTime
506+ let summary = Self.buildSummary(from: record)
507+ results.append((LiveTailEntry(
508+ timestamp: timestamp,
509+ record: record,
510+ displayTimestamp: Self.displayFormatter.string(from: timestamp),
511+ summary: summary,
512+ fingerprint: fp
513+ ), occurrence))
514+ }
515+ return (results, counts)
516+ }.value
312517
313− let timestamp = parseTimestamp(from: record) ?? now
314− let summary = buildSummary(from: record)
518+ // Re-check after the detached processing hop: a stop/clear could have
519+ // landed while we were off the main actor.
520+ guard isRunning, !isPaused, generation == pollGeneration else { return }
315521
316− newEntries.append(LiveTailEntry(
317− timestamp: timestamp,
318− record: record,
319− displayTimestamp: Self.displayFormatter.string(from: timestamp),
320− summary: summary
321− ))
522+ // Authoritative dedup on main actor
523+ var newEntries: [LiveTailEntry] = []
524+ for candidate in candidateEntries
525+ where candidate.occurrence > (seenFingerprints[candidate.entry.fingerprint] ?? 0) {
526+ newEntries.append(candidate.entry)
527+ }
528+ for (fp, count) in batchCounts where count > (seenFingerprints[fp] ?? 0) {
529+ if seenFingerprints[fp] == nil { seenFingerprintOrder.append(fp) }
530+ seenFingerprints[fp] = count
322531 }
323532
324533 if !newEntries.isEmpty {
@@ -327,14 +536,57 @@ final class LiveTailViewModel {
327536 if entries.count > maxEntries {
328537 let excess = entries.count - maxEntries
329538 droppedCount += excess
330− entries.removeFirst(excess)
539+ // Entries are not globally time-sorted across polls (a late or
540+ // backfilled record appends after newer ones), so trimming by
541+ // array position could evict newer entries. Sort by timestamp
542+ // first so the suffix keeps the chronologically newest.
543+ entries.sort { $0.timestamp < $1.timestamp }
544+ entries = Array(entries.suffix(maxEntries))
545+
546+ // Do NOT rebuild the fingerprint set from the retained
547+ // entries: an evicted record can still fall inside the next
548+ // poll's look-back window, and dropping its fingerprint here
549+ // would let it pass the dedup check and be re-appended as a
550+ // duplicate. Keep the full seen-set so dedup stays correct;
551+ // it is bounded below to avoid unbounded growth.
552+ }
331553
332− // Rebuild fingerprint set from remaining entries to bound memory
333− // and ensure dropped entries can be re-detected if they reappear.
334− seenFingerprints = Set(entries.map { Self.fingerprint(for: $0.record) })
554+ // Bound the seen-set on every poll, not only when the buffer
555+ // overflows: clear() keeps fingerprints while emptying `entries`,
556+ // so the set can outgrow the cap without the buffer ever filling.
557+ if seenFingerprints.count > maxSeenFingerprints {
558+ // Evict the OLDEST surplus fingerprints by insertion order,
559+ // not by what's currently buffered. Collapsing to only the
560+ // buffered set would drop recently-evicted fingerprints that
561+ // still fall inside the next poll's ~90 s look-back window,
562+ // re-admitting those records as duplicates. Keeping the
563+ // most-recently-seen tail preserves a full window of evicted
564+ // fingerprints. Buffered fingerprints are always retained so
565+ // a re-fetch of a buffered record stays deduplicated.
566+ let overflow = seenFingerprints.count - maxSeenFingerprints
567+ let buffered = Set(entries.map { $0.fingerprint })
568+ let toDrop = Set(seenFingerprintOrder.prefix(overflow))
569+ .subtracting(buffered)
570+ if !toDrop.isEmpty {
571+ for fp in toDrop { seenFingerprints.removeValue(forKey: fp) }
572+ seenFingerprintOrder.removeAll { toDrop.contains($0) }
573+ }
335574 }
336575
337− updateColumns(stream: stream)
576+ // Only scan new records for new keys
577+ var hasNewKeys = false
578+ for entry in newEntries {
579+ for key in entry.record.keys {
580+ if allKnownKeys.insert(key).inserted {
581+ hasNewKeys = true
582+ }
583+ }
584+ }
585+ if hasNewKeys {
586+ updateColumns(stream: stream)
587+ }
588+
589+ rebuildFilteredEntries()
338590 }
339591
340592 lastTimestamp = now
@@ -342,6 +594,10 @@ final class LiveTailViewModel {
342594 errorMessage = nil
343595 consecutiveErrors = 0
344596 } catch {
597+ // Drop the error if this poll was cancelled or superseded by a
598+ // stop/clear/start — don't bump the failure counter or surface an
599+ // error on a tail the user already tore down.
600+ guard !Task.isCancelled, isRunning, generation == pollGeneration else { return }
345601 consecutiveErrors += 1
346602 if consecutiveErrors >= Self.maxConsecutiveErrors {
347603 errorMessage = "\(ParseableError.userFriendlyMessage(for: error)) — stopped after \(consecutiveErrors) consecutive failures"
@@ -352,43 +608,140 @@ final class LiveTailViewModel {
352608 }
353609 }
354610
355− /// Deterministic content-based fingerprint using sorted key-value pairs and FNV-1a.
356− static func fingerprint(for record: LogRecord) -> String {
357− var h0: UInt64 = 14695981039346656037
358− var h1: UInt64 = 14695981039346656037 &* 31
359− for key in record.keys.sorted() {
611+ /// Deterministic content-based fingerprint using XOR with golden-ratio mixing.
612+ /// Order-independent: O(k) instead of O(k log k) per record.
613+ nonisolated static func fingerprint(for record: LogRecord) -> String {
614+ var xorAccum0: UInt64 = 0
615+ var xorAccum1: UInt64 = 0
616+ for (key, value) in record {
617+ var kh0: UInt64 = 14695981039346656037
618+ var kh1: UInt64 = 14695981039346656037 &* 31
360619 for byte in key.utf8 {
620+ kh0 = (kh0 ^ UInt64(byte)) &* 1099511628211
621+ kh1 = (kh1 ^ UInt64(byte)) &* 6700417
622+ }
623+ kh0 = (kh0 ^ 0) &* 1099511628211 // separator
624+ hashJSONValue(value, h0: &kh0, h1: &kh1)
625+ kh1 = (kh1 ^ 0xFF) &* 6700417 // field separator
626+ xorAccum0 ^= kh0 &* 0x9E3779B97F4A7C15
627+ xorAccum1 ^= kh1 &* 0x9E3779B97F4A7C15
628+ }
629+ let h0 = 14695981039346656037 &+ xorAccum0
630+ let h1 = (14695981039346656037 &* 31) &+ xorAccum1
631+ return String(h0, radix: 36) + String(h1, radix: 36)
632+ }
633+
634+ /// Mixes the 8 bytes of a number's canonical 64-bit representation, prefixed by
635+ /// a shared numeric type byte so ints and equal-valued doubles fingerprint alike.
636+ nonisolated private static func hashNumberBits(_ bitPattern: UInt64, h0: inout UInt64, h1: inout UInt64) {
637+ h0 = (h0 ^ 0x02) &* 1099511628211
638+ h1 = (h1 ^ 0x02) &* 6700417
639+ var bits = bitPattern
640+ for _ in 0..<8 {
641+ h0 = (h0 ^ (bits & 0xFF)) &* 1099511628211
642+ h1 = (h1 ^ (bits & 0xFF)) &* 6700417
643+ bits >>= 8
644+ }
645+ }
646+
647+ /// Recursively hashes a JSONValue tree without allocating intermediate strings.
648+ /// Uses type-discriminator bytes to prevent cross-type collisions.
649+ nonisolated private static func hashJSONValue(_ value: JSONValue, h0: inout UInt64, h1: inout UInt64) {
650+ switch value {
651+ case .null:
652+ h0 = (h0 ^ 0x00) &* 1099511628211
653+ h1 = (h1 ^ 0x00) &* 6700417
654+ case .bool(let b):
655+ h0 = (h0 ^ 0x01) &* 1099511628211
656+ h1 = (h1 ^ 0x01) &* 6700417
657+ let byte: UInt64 = b ? 1 : 0
658+ h0 = (h0 ^ byte) &* 1099511628211
659+ h1 = (h1 ^ byte) &* 6700417
660+ // `.int` and `.double` share one numeric encoding so the fingerprint stays
661+ // consistent with JSONValue equality, where `.int(5) == .double(5.0)`.
662+ // JSONValue.hash(into:) canonicalizes both through `Double`; mirror that here
663+ // (with NaN folded to a single bit pattern) so a field that serializes as `5`
664+ // in one poll and `5.0` in another doesn't bypass dedup as a phantom row.
665+ case .int(let i):
666+ // If the integer round-trips losslessly through Double, hash via the
667+ // Double path so `.int(5)` and `.double(5.0)` (which are ==) share a
668+ // fingerprint. Integers beyond 2^53 lose precision in Double, so two
669+ // distinct values (e.g. 2^53 and 2^53+1) would otherwise collide and
670+ // the second would be silently dropped as a phantom duplicate — the
671+ // dedup set has no `==` fallback. No Double can equal such a
672+ // non-representable integer, so hashing its exact 64-bit pattern can't
673+ // wrongly merge it with a `.double`.
674+ if let exact = Int(exactly: Double(i)), exact == i {
675+ hashNumberBits(Double(i).bitPattern, h0: &h0, h1: &h1)
676+ } else {
677+ hashNumberBits(UInt64(bitPattern: Int64(i)), h0: &h0, h1: &h1)
678+ }
679+ case .double(let d):
680+ // Canonicalize NaN (so all NaNs fold together) AND signed zero: JSONValue
681+ // equality treats `-0.0 == 0.0`, but their raw bit patterns differ, which
682+ // would otherwise let an identical record slip past dedup as a phantom row.
683+ let canonical: Double = d.isNaN ? .nan : (d == 0 ? 0.0 : d)
684+ hashNumberBits(canonical.bitPattern, h0: &h0, h1: &h1)
685+ case .string(let s):
686+ h0 = (h0 ^ 0x04) &* 1099511628211
687+ h1 = (h1 ^ 0x04) &* 6700417
688+ for byte in s.utf8 {
361689 h0 = (h0 ^ UInt64(byte)) &* 1099511628211
362690 h1 = (h1 ^ UInt64(byte)) &* 6700417
363691 }
364− h0 = (h0 ^ 0) &* 1099511628211 // separator
365− if let val = record[key] {
366− // Use exportString so nested objects/arrays contribute their
367− // actual content to the hash, not just their field count.
368− for byte in val.exportString.utf8 {
369− h0 = (h0 ^ UInt64(byte)) &* 1099511628211
370− h1 = (h1 ^ UInt64(byte)) &* 6700417
692+ case .array(let arr):
693+ h0 = (h0 ^ 0x05) &* 1099511628211
694+ h1 = (h1 ^ 0x05) &* 6700417
695+ for element in arr {
696+ hashJSONValue(element, h0: &h0, h1: &h1)
697+ h0 = (h0 ^ 0xFE) &* 1099511628211 // element separator
698+ h1 = (h1 ^ 0xFE) &* 6700417
699+ }
700+ case .object(let dict):
701+ h0 = (h0 ^ 0x06) &* 1099511628211
702+ h1 = (h1 ^ 0x06) &* 6700417
703+ var xor0: UInt64 = 0
704+ var xor1: UInt64 = 0
705+ for (key, value) in dict {
706+ var kh0: UInt64 = 14695981039346656037
707+ var kh1: UInt64 = 14695981039346656037 &* 31
708+ for byte in key.utf8 {
709+ kh0 = (kh0 ^ UInt64(byte)) &* 1099511628211
710+ kh1 = (kh1 ^ UInt64(byte)) &* 6700417
371711 }
712+ kh0 = (kh0 ^ 0xFD) &* 1099511628211 // key-value separator
713+ hashJSONValue(value, h0: &kh0, h1: &kh1)
714+ xor0 ^= kh0 &* 0x9E3779B97F4A7C15
715+ xor1 ^= kh1 &* 0x9E3779B97F4A7C15
372716 }
373− h1 = (h1 ^ 0xFF) &* 6700417 // field separator
717+ h0 = h0 &+ xor0
718+ h1 = h1 &+ xor1
374719 }
375− return String(h0, radix: 36) + String(h1, radix: 36)
376720 }
377721
378− func parseTimestamp(from record: LogRecord) -> Date? {
722+ nonisolated static func parseTimestamp(from record: LogRecord) -> Date? {
379723 guard let value = record["p_timestamp"] ?? record["timestamp"] ?? record["time"] ?? record["@timestamp"] else {
380724 return nil
381725 }
382726 if case .string(let str) = value {
383− if let date = Self.isoFractional.date(from: str) {
727+ if let date = isoFractional.date(from: str) ?? isoBasic.date(from: str) {
384728 return date
385729 }
386− return Self.isoBasic.date(from: str)
730+ // Parseable stores `p_timestamp` as an Arrow timestamp without a
731+ // timezone, and the query API serializes it as a naive UTC string with
732+ // no offset (e.g. "2024-01-11T09:08:34.290"). `.withInternetDateTime`
733+ // requires a zone designator, so such values never parsed: every entry
734+ // fell back to the poll time, which also scrambled the tail's order
735+ // (each poll's DESC-ordered batch was appended newest-first). Retry as
736+ // UTC; a string that already carries an offset won't parse with an
737+ // extra "Z", so this can't reinterpret zoned timestamps.
738+ let utc = str + "Z"
739+ return isoFractional.date(from: utc) ?? isoBasic.date(from: utc)
387740 }
388741 return nil
389742 }
390743
391− func buildSummary(from record: LogRecord) -> String {
744+ nonisolated static func buildSummary(from record: LogRecord) -> String {
392745 var parts: [String] = []
393746
394747 if let level = record["level"] ?? record["severity"] ?? record["log_level"] {
@@ -400,14 +753,16 @@ final class LiveTailViewModel {
400753 }
401754
402755 if parts.isEmpty {
756+ // Filter to scalars BEFORE taking the prefix — otherwise three leading
757+ // non-scalar fields (alphabetically) would yield an empty summary even
758+ // when scalar fields exist later in the record.
403759 let scalarFields = record
404760 .filter { $0.key != "p_timestamp" && $0.key != "p_tags" && $0.key != "p_metadata" }
761+ .filter { $0.value.isScalar }
405762 .sorted { $0.key < $1.key }
406763 .prefix(3)
407764 for (key, value) in scalarFields {
408− if value.isScalar {
409− parts.append("\(key)=\(value.displayString)")
410− }
765+ parts.append("\(key)=\(value.displayString)")
411766 }
412767 }
413768
ParseableViewer/ViewModels/QueryViewModel.swift+530−61
@@ -2,17 +2,86 @@ import Foundation
22import SwiftUI
33
44@Observable
5+@MainActor
56final class QueryViewModel {
6− var sqlQuery = ""
7+ var sqlQuery = "" {
8+ didSet {
9+ // Editing the query invalidates any error underline, whose offsets
10+ // were computed against the previous text. Clearing here keeps a
11+ // late-arriving highlight from landing on the wrong position.
12+ if sqlQuery != oldValue { errorRange = nil }
13+ }
14+ }
715 var results: [LogRecord] = [] {
8− didSet { updateFilteredResults() }
16+ didSet {
17+ // Build search texts asynchronously
18+ searchTextTask?.cancel()
19+ cachedSearchTexts = []
20+ searchTextGeneration &+= 1
21+ let generation = searchTextGeneration
22+ // Apply the current filter immediately using the inline fallback path
23+ // (the cache was just invalidated). Calling updateFilteredResults()
24+ // rather than `filteredResults = results` avoids briefly showing
25+ // unfiltered rows while a filter is active, and avoids leaving a stale
26+ // unfiltered set if the async rebuild below is cancelled before it
27+ // re-applies the filter.
28+ updateFilteredResults()
29+ let snapshot = results
30+ // The class is @MainActor, so this Task inherits main-actor isolation —
31+ // its mutations of cachedSearchTexts/filteredResults are safely serialized
32+ // with SwiftUI reads. Only the pure (and potentially large) displayString
33+ // mapping is pushed off-main via Task.detached so it doesn't block the UI.
34+ searchTextTask = Task { [weak self] in
35+ let texts = await Task.detached(priority: .userInitiated) {
36+ snapshot.map { record in
37+ record.values.map { $0.displayString }.joined(separator: " ")
38+ }
39+ }.value
40+ guard let self, !Task.isCancelled else { return }
41+ // Reject a stale write: if `results` was reassigned while this task
42+ // was awaiting, a newer didSet bumped the generation. Task.isCancelled
43+ // alone isn't sufficient because two re-queries producing result sets
44+ // of identical count would otherwise let this stale, same-length
45+ // cachedSearchTexts slip past updateFilteredResults's count guard.
46+ guard generation == self.searchTextGeneration else { return }
47+ self.cachedSearchTexts = texts
48+ if !self.filterText.isEmpty {
49+ self.updateFilteredResults()
50+ }
51+ }
52+ }
953 }
54+ private var cachedSearchTexts: [String] = []
55+ private var searchTextTask: Task<Void, Never>?
56+ /// Bumped on every `results` reassignment so the async search-text builder can
57+ /// detect it was superseded and drop a stale write (see results.didSet).
58+ private var searchTextGeneration = 0
1059 var columns: [String] = []
1160 var columnOrder: [String] = []
1261 var hiddenColumns: Set<String> = []
62+ /// The full persisted set of hidden columns for the current stream, including
63+ /// ones absent from the current result. Hiding a column drops it from the
64+ /// SELECT list, so it's missing from the very next result and `hiddenColumns`
65+ /// (only the columns present) forgets it — the next save would then erase the
66+ /// preference. This keeps the intent, mirroring LiveTailViewModel.
67+ private(set) var savedHiddenColumns: Set<String> = []
68+ /// The persisted column order including columns absent from the current
69+ /// result (the order counterpart of `savedHiddenColumns`), so saving doesn't
70+ /// drop a hidden column's position and it returns to its place when shown.
71+ private var savedColumnOrder: [String] = []
1372 var autoHiddenColumns: Set<String> = []
1473 /// Column config from a saved query, applied on next query execution.
1574 var pendingColumnConfig: ColumnConfiguration?
75+
76+ /// The connection and stream the editor text and results belong to. The view
77+ /// model outlives QueryView (switching tabs keeps the query), so the view
78+ /// compares this on appear to catch a stream/server change made while another
79+ /// tab was showing.
80+ struct BoundContext: Equatable {
81+ let connectionID: UUID?
82+ let stream: String
83+ }
84+ var boundContext: BoundContext?
1685 private var currentStream: String?
1786 var isLoading = false
1887 var errorMessage: String?
@@ -21,15 +90,32 @@ final class QueryViewModel {
2190 var queryDuration: TimeInterval?
2291 var selectedLogEntry: LogRecord?
2392 var filterText = "" {
24− didSet { updateFilteredResults() }
93+ didSet { debouncedUpdateFilter() }
2594 }
95+ private var filterTask: Task<Void, Never>?
2696 var resultsTruncated = false
2797
2898 // Schema fields for autocomplete
2999 var schemaFields: [SchemaField] = []
100+ /// The stream of the most recent `loadSchema` call, used to drop a stale
101+ /// in-flight response when the user rapidly switches streams.
102+ private(set) var latestSchemaStream: String?
103+ /// The stream of the most recent `executeQuery` call. Defense-in-depth
104+ /// alongside `queryGeneration`/task cancellation: drops a stale in-flight
105+ /// query response if a newer query for a different stream supersedes it
106+ /// without going through the normal cancel path.
107+ private var latestQueryStream: String?
30108
31109 // Query task for cancellation
32110 private var queryTask: Task<Void, Never>?
111+ /// Bumped at the start of every `executeQuery`. The task captures this value
112+ /// and only clears `isLoading` on exit if it's still the active query — so a
113+ /// superseded query's late cleanup doesn't drop the loading indicator that
114+ /// the newer query set. Without this, `isLoading = false` had to live in
115+ /// every caller of `cancel()` (cancelQuery, clearResults, superseding
116+ /// executeQuery) and a future cancel path that forgot to set it would wedge
117+ /// the spinner indefinitely.
118+ private var queryGeneration = 0
33119
34120 // Time range
35121 var timeRangeOption: TimeRangeOption = .last1Hour
@@ -38,7 +124,10 @@ final class QueryViewModel {
38124
39125 // Query history
40126 var queryHistory: [QueryHistoryEntry] = []
41− var historyIsFull = false
127+ // Derived from the (always-trimmed) history so it stays correct after a
128+ // restored full history is loaded at launch, not just after an in-session
129+ // overflow. `addToHistory` trims to `maxHistory`, so count never exceeds it.
130+ var historyIsFull: Bool { queryHistory.count >= Self.maxHistory }
42131 private static let maxHistory = 50
43132
44133 struct QueryHistoryEntry: Identifiable, Codable, Sendable {
@@ -123,9 +212,16 @@ final class QueryViewModel {
123212 return columnOrder.filter { !allHidden.contains($0) }
124213 }
125214
215+ /// Whether any column is hidden — including saved-hidden columns that aren't
216+ /// in the current result, which "Show All" can bring back.
217+ var hasHiddenColumns: Bool {
218+ !hiddenColumns.isEmpty || !autoHiddenColumns.isEmpty || !savedHiddenColumns.isEmpty
219+ }
220+
126221 func toggleColumnVisibility(_ column: String) {
127222 if hiddenColumns.contains(column) {
128223 hiddenColumns.remove(column)
224+ savedHiddenColumns.remove(column)
129225 } else if autoHiddenColumns.contains(column) {
130226 autoHiddenColumns.remove(column)
131227 } else {
@@ -134,6 +230,7 @@ final class QueryViewModel {
134230 let visibleCount = columnOrder.count - allHidden.count
135231 if visibleCount > 1 {
136232 hiddenColumns.insert(column)
233+ savedHiddenColumns.insert(column)
137234 }
138235 }
139236 saveColumnConfig()
@@ -142,6 +239,7 @@ final class QueryViewModel {
142239
143240 func showAllColumns() {
144241 hiddenColumns.removeAll()
242+ savedHiddenColumns.removeAll()
145243 autoHiddenColumns.removeAll()
146244 saveColumnConfig()
147245 updateSQLColumns()
@@ -158,36 +256,129 @@ final class QueryViewModel {
158256 let toIndex = columnOrder.firstIndex(of: targetColumn),
159257 fromIndex != toIndex else { return }
160258 let item = columnOrder.remove(at: fromIndex)
161− columnOrder.insert(item, at: toIndex)
259+ // Match the drop-indicator semantics: a rightward move (fromIndex < toIndex)
260+ // lands the column *after* the target, a leftward move lands it *before*.
261+ // After removing an earlier element the target shifts down by one, so
262+ // inserting at `toIndex` lands after the target for rightward moves; for
263+ // leftward moves the target is unshifted and `toIndex` lands before it.
264+ let adjusted = toIndex
265+ columnOrder.insert(item, at: adjusted)
162266 saveColumnConfig()
163267 updateSQLColumns()
164268 }
165269
166270 func resetColumnConfig() {
167271 columnOrder = columns
272+ savedColumnOrder = []
168273 hiddenColumns.removeAll()
274+ savedHiddenColumns.removeAll()
169275 autoHiddenColumns.removeAll()
170276 saveColumnConfig()
171277 updateSQLColumns()
172278 }
173279
174− /// Rewrites the SELECT clause of `sqlQuery` to reflect the current `visibleColumns`.
280+ /// Rewrites the SELECT clause of `sqlQuery` to reflect the user's column
281+ /// choices (order and hidden columns; auto-hidden columns stay display-only).
175282 func updateSQLColumns() {
176− guard let range = SQLTokenizer.selectColumnListRange(in: sqlQuery) else { return }
177−
178− let visible = visibleColumns
283+ guard let range = SQLTokenizer.selectColumnListRange(in: sqlQuery),
284+ let currentList = Self.parseColumnList(sqlQuery[range]) else { return }
285+
286+ // Project the user's choices only. `autoHiddenColumns` is a display
287+ // heuristic for the current rows (the field is empty in all of them);
288+ // baking it into the SQL would stop the field from ever being fetched
289+ // again, even for a time range where it has values.
290+ let visible = columnOrder.filter { !hiddenColumns.contains($0) }
179291 guard !visible.isEmpty else { return }
180292
293+ // Columns an explicit list names that aren't in the results: Parseable
294+ // omits all-null fields from query JSON, so a sparse listed field can be
295+ // missing from `columns`. Keep it (unless the user hid it) rather than
296+ // silently dropping it from the SELECT on the next rewrite.
297+ var listedButAbsent: [String] = []
298+ var excludesHiddenColumn = false
299+ if case .identifiers(let names) = currentList {
300+ let present = Set(columns)
301+ listedButAbsent = names.filter { !present.contains($0) && !savedHiddenColumns.contains($0) }
302+ // A column the user hid is absent from these results precisely
303+ // because this list was narrowed to exclude it.
304+ excludesHiddenColumn = !savedHiddenColumns.isSubset(of: present)
305+ }
306+
181307 let newColumnList: String
182− if visible == columns {
308+ // Use `*` whenever every column is visible, regardless of display order —
309+ // reordering columns (a set-preserving permutation) must not pin the query
310+ // to an explicit snapshot that hides newly-appearing fields on re-query —
311+ // unless the list is explicit because it leaves out a hidden column, which
312+ // `*` would fetch again.
313+ if !excludesHiddenColumn && visible.count == columns.count && Set(visible) == Set(columns) {
183314 newColumnList = "*"
184315 } else {
185− newColumnList = visible.map { Self.escapeSQLIdentifier($0) }.joined(separator: ", ")
316+ newColumnList = (visible + listedButAbsent).map { Self.escapeSQLIdentifier($0) }.joined(separator: ", ")
186317 }
187318
188319 sqlQuery.replaceSubrange(range, with: newColumnList)
189320 }
190321
322+ enum ColumnListShape: Equatable {
323+ case star
324+ /// Plain column references, as the column names they resolve to.
325+ case identifiers([String])
326+ }
327+
328+ /// Parses a SELECT list the column manager can regenerate without changing
329+ /// what the query computes: `*`, or a comma-separated list of plain column
330+ /// references. Anything else — aggregates, expressions, aliases
331+ /// (`count(*) AS n`), qualified names — returns nil: rewriting it with `*` or
332+ /// bare result keys would break the query, so the column manager then only
333+ /// hides/reorders client-side.
334+ nonisolated static func parseColumnList(_ list: Substring) -> ColumnListShape? {
335+ let tokens = SQLTokenizer.tokenize(String(list)).filter { !$0.kind.isTrivia }
336+ if tokens.count == 1, tokens[0].kind == .star { return .star }
337+ guard tokens.count % 2 == 1 else { return nil }
338+ var names: [String] = []
339+ for (index, token) in tokens.enumerated() {
340+ if index % 2 == 1 {
341+ guard token.kind == .comma else { return nil }
342+ continue
343+ }
344+ switch token.kind {
345+ // DataFusion folds unquoted identifiers to lowercase.
346+ case .identifier(let name): names.append(name.lowercased())
347+ case .quotedIdentifier(let name): names.append(name)
348+ default: return nil
349+ }
350+ }
351+ return .identifiers(names)
352+ }
353+
354+ /// Inserts `newColumns` into `order`, placing each one that appears in
355+ /// `reference` (a saved order) right after its nearest saved predecessor
356+ /// that's already placed — or first if none is — and appending the rest.
357+ /// Used to keep the positions of columns that are absent for a while.
358+ nonisolated static func mergedColumnOrder(
359+ _ order: [String], inserting newColumns: [String], reference: [String]
360+ ) -> [String] {
361+ var result = order
362+ let referenceIndex = Dictionary(reference.enumerated().map { ($1, $0) }, uniquingKeysWith: { first, _ in first })
363+ let pending = newColumns.filter { referenceIndex[$0] == nil }
364+ let positioned = newColumns
365+ .filter { referenceIndex[$0] != nil }
366+ .sorted { referenceIndex[$0]! < referenceIndex[$1]! }
367+ for column in positioned where !result.contains(column) {
368+ let savedIndex = referenceIndex[column]!
369+ let predecessor = reference[..<savedIndex].reversed().first { result.contains($0) }
370+ if let predecessor, let position = result.firstIndex(of: predecessor) {
371+ result.insert(column, at: position + 1)
372+ } else {
373+ result.insert(column, at: 0)
374+ }
375+ }
376+ for column in pending where !result.contains(column) {
377+ result.append(column)
378+ }
379+ return result
380+ }
381+
191382 // MARK: - Column Configuration Persistence
192383
193384 struct ColumnConfiguration: Codable {
@@ -201,7 +392,16 @@ final class QueryViewModel {
201392
202393 private func saveColumnConfig() {
203394 guard let stream = currentStream else { return }
204− let config = ColumnConfiguration(order: columnOrder, hidden: hiddenColumns)
395+ // Persist the full intended hidden set and order, not just the currently
396+ // present columns (see `savedHiddenColumns` / `savedColumnOrder`).
397+ let present = Set(columnOrder)
398+ let order = Self.mergedColumnOrder(
399+ columnOrder,
400+ inserting: savedColumnOrder.filter { !present.contains($0) },
401+ reference: savedColumnOrder
402+ )
403+ savedColumnOrder = order
404+ let config = ColumnConfiguration(order: order, hidden: savedHiddenColumns.union(hiddenColumns))
205405 if let data = try? JSONEncoder().encode(config) {
206406 UserDefaults.standard.set(data, forKey: Self.columnConfigKey(for: stream))
207407 }
@@ -230,7 +430,9 @@ final class QueryViewModel {
230430
231431 guard let config else {
232432 columnOrder = extractedColumns
433+ savedColumnOrder = []
233434 hiddenColumns = []
435+ savedHiddenColumns = []
234436 return
235437 }
236438
@@ -243,18 +445,57 @@ final class QueryViewModel {
243445 merged.append(col)
244446 }
245447 columnOrder = merged
448+ savedColumnOrder = config.order
449+ savedHiddenColumns = config.hidden
246450 hiddenColumns = config.hidden.intersection(extractedSet)
451+
452+ // The `visibleCount > 1` guard in toggleColumnVisibility only covers
453+ // user toggles. A saved config can hide every currently-extracted column
454+ // (e.g. the stream's schema shrank so only previously-hidden columns
455+ // remain), which would render the results table with zero columns and
456+ // leave `updateSQLColumns` early-returning on the empty case. Keep at
457+ // least the first column visible. Mirrors LiveTailViewModel.updateColumns.
458+ if !columnOrder.isEmpty, hiddenColumns.count >= columnOrder.count,
459+ let firstColumn = columnOrder.first {
460+ hiddenColumns.remove(firstColumn)
461+ }
247462 }
248463
249464 private(set) var filteredResults: [LogRecord] = []
250465
466+ private func debouncedUpdateFilter() {
467+ filterTask?.cancel()
468+ if filterText.isEmpty {
469+ updateFilteredResults()
470+ return
471+ }
472+ filterTask = Task {
473+ try? await Task.sleep(for: .milliseconds(150))
474+ guard !Task.isCancelled else { return }
475+ updateFilteredResults()
476+ }
477+ }
478+
251479 private func updateFilteredResults() {
252480 if filterText.isEmpty {
253481 filteredResults = results
254482 } else {
255− filteredResults = results.filter { record in
256− record.values.contains { value in
257− value.displayString.localizedCaseInsensitiveContains(filterText)
483+ let text = filterText
484+ // The search-text cache is built asynchronously, so it may be empty
485+ // or stale when the filter changes. `zip` would silently truncate to
486+ // the shorter sequence and drop matching rows, so only use the cache
487+ // when it lines up with the current results; otherwise compute the
488+ // search text inline for correctness.
489+ if cachedSearchTexts.count == results.count {
490+ filteredResults = zip(results, cachedSearchTexts).compactMap { record, searchText in
491+ searchText.localizedCaseInsensitiveContains(text) ? record : nil
492+ }
493+ } else {
494+ filteredResults = results.filter { record in
495+ record.values
496+ .map { $0.displayString }
497+ .joined(separator: " ")
498+ .localizedCaseInsensitiveContains(text)
258499 }
259500 }
260501 }
@@ -299,6 +540,13 @@ final class QueryViewModel {
299540
300541 // Cancel any in-flight query
301542 queryTask?.cancel()
543+ // Bump the generation so the in-flight task's cleanup can detect that
544+ // it has been superseded and skip its `isLoading = false` (which would
545+ // otherwise race with the `isLoading = true` below and briefly drop
546+ // the loading indicator during this query).
547+ queryGeneration &+= 1
548+ let generation = queryGeneration
549+ latestQueryStream = stream
302550
303551 isLoading = true
304552 errorMessage = nil
@@ -307,18 +555,44 @@ final class QueryViewModel {
307555 let startTime = CFAbsoluteTimeGetCurrent()
308556
309557 let task = Task {
558+ // Always clear the spinner on exit when this is still the active
559+ // query. The defer runs on every path (success, error, and the
560+ // cancellation cases that previously returned before reaching the
561+ // trailing `isLoading = false`), so the spinner can never wedge
562+ // even if a new cancel path is added without resetting it.
563+ defer {
564+ if generation == queryGeneration {
565+ isLoading = false
566+ }
567+ }
310568 do {
311569 try Task.checkCancellation()
312570 let queryResults = try await client.query(sql: sql, startTime: startDate, endTime: endDate)
313571 try Task.checkCancellation()
572+ // Re-check before committing. A superseding executeQuery() cancels
573+ // this task (queryTask?.cancel()) before starting the next one, but
574+ // cancellation landing just after the check above would otherwise
575+ // let a stale query clobber the newer one's results/columns.
576+ guard !Task.isCancelled else { return }
577+ // Drop the response if a newer query (possibly for a different
578+ // stream) has since been launched without cancelling this task.
579+ guard latestQueryStream == stream else { return }
314580
315581 results = queryResults
582+ // Drop any prior row selection: the new result set reassigns row
583+ // identities, so a retained selectedLogEntry would either dangle or
584+ // value-match an unrelated row, leaving a stale detail inspector.
585+ selectedLogEntry = nil
316586 queryDuration = CFAbsoluteTimeGetCurrent() - startTime
317587 resultCount = results.count
318588
319− // Detect if results were likely truncated (only meaningful
320− // for auto-generated queries where we control the LIMIT)
321− resultsTruncated = usedAutoLimit && results.count == limit
589+ // Detect if results were likely truncated. We know the cap for
590+ // auto-generated queries; for user-entered SQL (which includes the
591+ // default query `setDefaultQuery` writes into the editor — the common
592+ // stream-selection path), parse a trailing `LIMIT n` so the indicator
593+ // still fires when the row count lands exactly on the limit.
594+ let effectiveLimit = usedAutoLimit ? limit : Self.trailingLimit(in: sql)
595+ resultsTruncated = effectiveLimit.map { results.count == $0 } ?? false
322596
323597 // Extract columns in a single pass, with priority fields first,
324598 // then apply any saved column configuration for this stream
@@ -341,23 +615,40 @@ final class QueryViewModel {
341615 let entry = QueryHistoryEntry(sql: sql, resultCount: resultCount, duration: queryDuration ?? 0)
342616 addToHistory(entry)
343617 } catch is CancellationError {
344− errorMessage = "Query cancelled"
345− results = []
346− columns = []
618+ // Silently ignore — cancelQuery() or a new executeQuery() handles state
619+ return
347620 } catch {
621+ guard !Task.isCancelled else { return }
622+ // Same supersession guard as the success path: a stale failed
623+ // query must not clobber a newer query's state.
624+ guard latestQueryStream == stream else { return }
348625 errorMessage = ParseableError.userFriendlyMessage(for: error)
349626 if let serverError = error as? ParseableError,
350627 case .serverError(_, let msg) = serverError,
351− let pos = SQLErrorPosition.parse(from: msg) {
628+ let pos = SQLErrorPosition.parse(from: msg),
629+ sqlQuery == sql {
630+ // The server's line/column is relative to the *submitted* SQL.
631+ // Only map it back into the editor when the editor still holds
632+ // that same text — if the user edited the query while it was in
633+ // flight, the position no longer corresponds to what's displayed
634+ // and would underline an unrelated span. (`sqlQuery`'s didSet
635+ // already cleared errorRange on that edit, so leaving it nil here
636+ // keeps the editor unmarked.)
352637 errorRange = SQLTokenizer.errorHighlightRange(
353− line: pos.line, column: pos.column, in: sqlQuery
638+ line: pos.line, column: pos.column, in: sql
354639 )
355640 }
356641 results = []
357642 columns = []
643+ // Drop the previous query's column layout too, otherwise derived
644+ // state like `visibleColumns` (and a CSV export reading it) would
645+ // report stale column names after the failure.
646+ columnOrder = []
647+ hiddenColumns = []
648+ savedHiddenColumns = []
649+ savedColumnOrder = []
650+ autoHiddenColumns = []
358651 }
359−
360− isLoading = false
361652 }
362653 queryTask = task
363654 await task.value
@@ -374,14 +665,20 @@ final class QueryViewModel {
374665
375666 @MainActor
376667 func loadSchema(client: ParseableClient?, stream: String?) async {
668+ latestSchemaStream = stream
377669 guard let client, let stream else {
378670 schemaFields = []
379671 return
380672 }
381673 do {
382674 let schema = try await client.getStreamSchema(stream: stream)
675+ // A newer load (e.g. a rapid stream switch) may have superseded this
676+ // one; only commit if this is still the stream last requested,
677+ // otherwise we'd show the wrong stream's fields in autocomplete.
678+ guard latestSchemaStream == stream else { return }
383679 schemaFields = schema.fields
384680 } catch {
681+ guard latestSchemaStream == stream else { return }
385682 // Schema load is best-effort; don't surface errors
386683 schemaFields = []
387684 }
@@ -411,7 +708,9 @@ final class QueryViewModel {
411708 var empty = Set(columns)
412709 for record in records {
413710 if empty.isEmpty { break }
414− for column in empty {
711+ // Iterate a snapshot: mutating `empty` while iterating it directly
712+ // is undefined behavior and can skip elements or trap.
713+ for column in Array(empty) {
415714 if let value = record[column], value != .null, value != .string("") {
416715 empty.remove(column)
417716 }
@@ -420,39 +719,66 @@ final class QueryViewModel {
420719 return empty
421720 }
422721
722+ /// Exports the on-screen rows as JSON. Uses `filteredResults` (not the full
723+ /// `results`) so the output matches what the user sees with an active result
724+ /// filter, mirroring the view's export path.
423725 func exportAsJSON() -> String {
424− guard !results.isEmpty else { return "[]" }
726+ let rows = filteredResults
727+ guard !rows.isEmpty else { return "[]" }
425728 let encoder = JSONEncoder()
426729 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
427− if let data = try? encoder.encode(results),
730+ if let data = try? encoder.encode(Self.projectRecords(rows, to: visibleColumns)),
428731 let string = String(data: data, encoding: .utf8) {
429732 return string
430733 }
431734 return "[]"
432735 }
433736
737+ /// Exports the on-screen rows as CSV. Uses `filteredResults` for the same
738+ /// reason as `exportAsJSON`.
434739 func exportAsCSV() -> String {
435− Self.buildCSV(records: results, columns: visibleColumns)
740+ Self.buildCSV(records: filteredResults, columns: visibleColumns)
741+ }
742+
743+ /// Projects each record down to the given columns so JSON export, like CSV,
744+ /// respects hidden columns instead of leaking every field. Safe to call from
745+ /// any thread.
746+ nonisolated static func projectRecords(_ records: [LogRecord], to columns: [String]) -> [LogRecord] {
747+ // No column list means no restriction (columns not computed yet) — export
748+ // the full records rather than stripping every field to an empty object.
749+ guard !columns.isEmpty else { return records }
750+ let allowed = Set(columns)
751+ return records.map { record in record.filter { allowed.contains($0.key) } }
436752 }
437753
438754 /// Builds a CSV string from records and columns. Safe to call from any thread.
439− static func buildCSV(records: [LogRecord], columns: [String]) -> String {
755+ nonisolated static func buildCSV(records: [LogRecord], columns: [String]) -> String {
440756 guard !records.isEmpty, !columns.isEmpty else { return "" }
441757
442− var csv = columns.map { escapeCSV($0) }.joined(separator: ",") + "\n"
758+ var csv = String()
759+ csv.reserveCapacity(columns.count * 50 * (records.count + 1))
760+
761+ // Header
762+ for (i, col) in columns.enumerated() {
763+ if i > 0 { csv.append(",") }
764+ csv.append(escapeCSV(col))
765+ }
766+ csv.append("\n")
443767
768+ // Rows
444769 for record in records {
445− let row = columns.map { column in
770+ for (i, column) in columns.enumerated() {
771+ if i > 0 { csv.append(",") }
446772 let value = record[column]?.exportString ?? ""
447− return escapeCSV(value)
773+ csv.append(escapeCSV(value))
448774 }
449− csv += row.joined(separator: ",") + "\n"
775+ csv.append("\n")
450776 }
451777
452778 return csv
453779 }
454780
455− private static func escapeCSV(_ value: String) -> String {
781+ nonisolated private static func escapeCSV(_ value: String) -> String {
456782 // Check at the Unicode scalar level to correctly detect \r and \n
457783 // inside \r\n (CRLF) grapheme clusters, which Swift's String.contains
458784 // treats as a single Character that doesn't match "\r" or "\n" alone.
@@ -466,10 +792,29 @@ final class QueryViewModel {
466792 }
467793
468794 func clearResults() {
795+ // Cancel any in-flight work first. Without this, a query still running
796+ // when the user switches streams or disconnects would pass its post-await
797+ // cancellation check (it was never cancelled) and write its results +
798+ // persist a column config for the *old* stream after this reset.
799+ queryTask?.cancel()
800+ queryTask = nil
801+ searchTextTask?.cancel()
802+ searchTextTask = nil
803+ filterTask?.cancel()
804+ filterTask = nil
805+
806+ // The in-flight query was cancelled above, so its task returns via the
807+ // CancellationError path and never reaches `isLoading = false`. Reset it
808+ // here, otherwise deselecting the stream / disconnecting (which calls
809+ // clearResults with no follow-up query) leaves the spinner stuck on.
810+ isLoading = false
811+
469812 results = []
470813 columns = []
471814 columnOrder = []
472815 hiddenColumns = []
816+ savedHiddenColumns = []
817+ savedColumnOrder = []
473818 autoHiddenColumns = []
474819 currentStream = nil
475820 resultCount = 0
@@ -479,6 +824,11 @@ final class QueryViewModel {
479824 errorRange = nil
480825 resultsTruncated = false
481826 schemaFields = []
827+ // Keep the stream trackers consistent with the cleared schema/results so
828+ // a later reload guard never sees a non-nil stream paired with empty data.
829+ latestSchemaStream = nil
830+ latestQueryStream = nil
831+ boundContext = nil
482832 }
483833
484834 /// Modifies `sqlQuery` to add a column-value filter condition.
@@ -488,48 +838,151 @@ final class QueryViewModel {
488838 let condition: String
489839 if let value, value != .null {
490840 let literal = value.sqlLiteral
491− condition = exclude ? "\(escapedCol) <> \(literal)" : "\(escapedCol) = \(literal)"
841+ // Exclude with `IS DISTINCT FROM`, not `<>`: under SQL's three-valued
842+ // logic `NULL <> 'x'` is NULL, so `<>` also dropped every row where the
843+ // column is missing/NULL — common for sparse fields — which "exclude
844+ // this value" doesn't ask for (the live-tail exclude keeps them too).
845+ condition = exclude
846+ ? "\(escapedCol) IS DISTINCT FROM \(literal)"
847+ : "\(escapedCol) = \(literal)"
492848 } else {
493849 condition = exclude ? "\(escapedCol) IS NOT NULL" : "\(escapedCol) IS NULL"
494850 }
495851
496− var sql = sqlQuery.trimmingCharacters(in: .whitespacesAndNewlines)
852+ let sql = sqlQuery.trimmingCharacters(in: .whitespacesAndNewlines)
497853 if sql.isEmpty { return }
498854
499− let wherePattern = #"(?i)\bWHERE\b"#
500− let tailPattern = #"(?i)\b(ORDER\s+BY|GROUP\s+BY|HAVING|LIMIT)\b"#
501−
502− if let whereRange = sql.range(of: wherePattern, options: .regularExpression) {
503− let afterWhere = whereRange.upperBound
504− let searchRange = afterWhere..<sql.endIndex
505− if let tailRange = sql.range(of: tailPattern, options: .regularExpression, range: searchRange) {
506− sql.insert(contentsOf: "AND \(condition) ", at: tailRange.lowerBound)
507− } else {
508− sql += " AND \(condition)"
855+ // Locate the top-level WHERE and the first trailing clause using the
856+ // tokenizer rather than a raw regex, so keywords inside quoted
857+ // identifiers, string literals, comments, or subqueries are ignored.
858+ let tokens = SQLTokenizer.tokenize(sql)
859+ var depth = 0
860+ // WHERE and the trailing clauses only follow the top-level FROM. Keywords
861+ // before it belong to the SELECT list — e.g. a field named `offset` or
862+ // `limit` (which the tokenizer reports as keywords) — and must not be
863+ // mistaken for clause starts.
864+ var fromSeen = false
865+ var whereIndex: Int?
866+ var tailIndex: Int?
867+ // Track whether the existing WHERE body has a top-level OR — only then does
868+ // AND-ing a new condition need parentheses to preserve precedence.
869+ var bodyHasTopLevelOr = false
870+ // The last token that is actual SQL — not whitespace, a comment, or a
871+ // statement-terminating `;`. New text is spliced in right after such
872+ // tokens (never at the raw end of the string), so a trailing `;` or a
873+ // trailing `-- comment` stays at the end instead of swallowing the
874+ // appended condition: `... LIMIT 10;` must not become `... LIMIT 10; WHERE`,
875+ // and `... -- note` must not become `... -- note WHERE <commented out>`.
876+ func isSignificant(_ token: SQLTokenizer.Token) -> Bool {
877+ !token.kind.isTrivia && token.kind != .other(";")
878+ }
879+ func nextSignificantKind(after index: Int) -> SQLTokenizer.TokenKind? {
880+ tokens[(index + 1)...].first(where: { isSignificant($0) })?.kind
881+ }
882+ // Whether the keyword at `index` actually opens a trailing clause. ORDER and
883+ // GROUP must be followed by BY (so `WITHIN GROUP (…)` or a column named
884+ // `order` doesn't count), and LIMIT/OFFSET by their row count (so a column
885+ // named `offset` in `WHERE offset > 5` doesn't cut the WHERE body short).
886+ func startsTrailingClause(_ keyword: String, at index: Int) -> Bool {
887+ switch keyword {
888+ case "ORDER", "GROUP":
889+ return nextSignificantKind(after: index) == .keyword("BY")
890+ case "LIMIT", "OFFSET":
891+ if case .number = nextSignificantKind(after: index) { return true }
892+ return false
893+ case "HAVING":
894+ return true
895+ default:
896+ return false
509897 }
510− } else {
511− if let tailRange = sql.range(of: tailPattern, options: .regularExpression) {
512− sql.insert(contentsOf: "WHERE \(condition) ", at: tailRange.lowerBound)
898+ }
899+ var lastSignificant: Int?
900+ for (idx, token) in tokens.enumerated() {
901+ if isSignificant(token) { lastSignificant = idx }
902+ switch token.kind {
903+ case .leftParen:
904+ depth += 1
905+ case .rightParen:
906+ depth = max(0, depth - 1)
907+ case .keyword("FROM") where depth == 0:
908+ fromSeen = true
909+ case .keyword(let kw) where depth == 0 && fromSeen:
910+ if kw == "WHERE", whereIndex == nil {
911+ whereIndex = idx
912+ // A trailing clause seen *before* the WHERE (e.g. the GROUP BY of
913+ // the first SELECT in `... GROUP BY a UNION ALL SELECT ... WHERE`)
914+ // doesn't end this WHERE's body. Keeping it would make the body
915+ // range run backwards (a trapping `Range`), so look for the
916+ // body's end afresh after the WHERE.
917+ tailIndex = nil
918+ } else if tailIndex == nil, startsTrailingClause(kw, at: idx) {
919+ tailIndex = idx
920+ } else if kw == "OR", whereIndex != nil, tailIndex == nil {
921+ bodyHasTopLevelOr = true
922+ }
923+ default:
924+ break
925+ }
926+ }
927+ // Nothing but comments/semicolons — there's no statement to filter.
928+ guard let lastSignificant else { return }
929+
930+ // Each branch rebuilds the query from slices of the original text, keeping
931+ // the user's line breaks: joining pieces with single spaces would pull the
932+ // text after a `-- comment` onto the comment's line and comment it out.
933+ // Text spliced directly in front of another token (`(a = 1)ORDER BY`) needs
934+ // a space so the two don't fuse (`... IS NULLORDER BY`).
935+ func separated(_ rest: Substring) -> String {
936+ guard let next = rest.first, !next.isWhitespace, next != ";" else { return String(rest) }
937+ return " " + rest
938+ }
939+ if let whereIndex {
940+ // The WHERE body runs up to the first trailing clause, or to the end
941+ // of the statement. Only its significant tokens bound the splice, so a
942+ // comment between the body and ORDER BY stays after the new condition.
943+ let bodyEndIndex = tailIndex ?? (lastSignificant + 1)
944+ let bodyIndices = (whereIndex + 1)..<bodyEndIndex
945+ if let first = bodyIndices.first(where: { isSignificant(tokens[$0]) }),
946+ let last = bodyIndices.last(where: { isSignificant(tokens[$0]) }) {
947+ // Parenthesize the existing WHERE body before AND-ing the new
948+ // condition only when it has a top-level OR, otherwise the OR
949+ // silently changes meaning: `WHERE a = 1 OR b = 2` would become
950+ // `WHERE a = 1 OR b = 2 AND c = 3`, which SQL binds as
951+ // `a = 1 OR (b = 2 AND c = 3)` rather than the intended
952+ // `(a = 1 OR b = 2) AND c = 3`. A body without a top-level OR is
953+ // left un-parenthesized so simple filters stay readable.
954+ let bodyStart = tokens[first].range.lowerBound
955+ let bodyEnd = tokens[last].range.upperBound
956+ let body = sql[bodyStart..<bodyEnd]
957+ let wrappedBody = bodyHasTopLevelOr ? "(\(body))" : String(body)
958+ sqlQuery = "\(sql[..<bodyStart])\(wrappedBody) AND \(condition)\(separated(sql[bodyEnd...]))"
513959 } else {
514− sql += " WHERE \(condition)"
960+ // An empty WHERE body (e.g. a half-written `... WHERE` with no
961+ // condition yet, or `WHERE` immediately followed by ORDER/GROUP/
962+ // LIMIT) would otherwise produce `WHERE AND <condition>` — a
963+ // dangling AND with no left operand. Drop the AND in that case.
964+ let whereEnd = tokens[whereIndex].range.upperBound
965+ sqlQuery = "\(sql[..<whereEnd]) \(condition)\(separated(sql[whereEnd...]))"
515966 }
967+ } else if let tailIndex {
968+ let tailStart = tokens[tailIndex].range.lowerBound
969+ sqlQuery = "\(sql[..<tailStart])WHERE \(condition) \(sql[tailStart...])"
970+ } else {
971+ let statementEnd = tokens[lastSignificant].range.upperBound
972+ sqlQuery = "\(sql[..<statementEnd]) WHERE \(condition)\(separated(sql[statementEnd...]))"
516973 }
517−
518− sqlQuery = sql
519974 }
520975
521976 /// Sets the default query for the given stream, returning `true` if the
522977 /// query text was replaced (i.e. the user hadn't customized it).
523978 @discardableResult
524979 func setDefaultQuery(stream: String, previousStream: String? = nil) -> Bool {
525− // Replace the query if it's empty or still matches the auto-generated
526− // default for the previous stream. If the user edited the SQL, keep it.
980+ // Always replace when switching streams — the previous query (whether
981+ // auto-generated or from a saved filter) belongs to the old stream.
982+ // Only preserve the query when no stream change occurred (e.g. onAppear).
527983 let shouldReplace: Bool
528− if sqlQuery.isEmpty {
984+ if sqlQuery.isEmpty || previousStream != nil {
529985 shouldReplace = true
530− } else if let prev = previousStream {
531− let prevPrefix = "SELECT * FROM \(Self.escapeSQLIdentifier(prev))"
532− shouldReplace = sqlQuery.hasPrefix(prevPrefix)
533986 } else {
534987 shouldReplace = false
535988 }
@@ -541,19 +994,35 @@ final class QueryViewModel {
541994 }
542995
543996 /// Escapes a SQL identifier by doubling internal double-quotes, then wrapping in double-quotes.
544− static func escapeSQLIdentifier(_ identifier: String) -> String {
997+ nonisolated static func escapeSQLIdentifier(_ identifier: String) -> String {
545998 "\"\(identifier.replacingOccurrences(of: "\"", with: "\"\""))\""
546999 }
5471000
1001+ /// Extracts the row cap from a trailing `LIMIT n` clause (tolerating a trailing
1002+ /// semicolon/whitespace), used to detect when a result set was truncated.
1003+ /// Returns nil when there's no recognizable trailing `LIMIT` — e.g. when the
1004+ /// query uses `LIMIT n OFFSET m` — so we never report a false truncation.
1005+ nonisolated static func trailingLimit(in sql: String) -> Int? {
1006+ let pattern = #"(?i)\bLIMIT\s+(\d+)\s*;?\s*$"#
1007+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
1008+ let range = NSRange(sql.startIndex..<sql.endIndex, in: sql)
1009+ guard let match = regex.firstMatch(in: sql, range: range),
1010+ let numberRange = Range(match.range(at: 1), in: sql) else { return nil }
1011+ return Int(sql[numberRange])
1012+ }
1013+
5481014 // MARK: - Query History
5491015
5501016 private func addToHistory(_ entry: QueryHistoryEntry) {
1017+ // Start from what's persisted, not this instance's copy: a model created
1018+ // earlier (e.g. one whose query finished after a reconnect replaced it)
1019+ // would otherwise overwrite newer entries saved by the current one.
1020+ queryHistory = Self.loadHistory()
5511021 // Deduplicate consecutive identical queries
5521022 if queryHistory.first?.sql == entry.sql { return }
5531023 queryHistory.insert(entry, at: 0)
5541024 if queryHistory.count > Self.maxHistory {
5551025 queryHistory = Array(queryHistory.prefix(Self.maxHistory))
556− historyIsFull = true
5571026 }
5581027 Self.saveHistory(queryHistory)
5591028 }
ParseableViewer/Views/AlertsView.swift+32−4
@@ -5,6 +5,10 @@ struct AlertsView: View {
55 @State private var alertConfig: AlertConfig?
66 @State private var isLoading = false
77 @State private var errorMessage: String?
8+ /// Bumped by every load. SwiftUI cancels the previous `.task(id:)` load on a
9+ /// stream switch, but that load still resumes (with a cancellation error) —
10+ /// and must not touch `isLoading`, which now belongs to the newer load.
11+ @State private var loadGeneration = 0
812
913 var body: some View {
1014 Group {
@@ -63,7 +67,7 @@ struct AlertsView: View {
6367 .frame(maxWidth: .infinity, maxHeight: .infinity)
6468 }
6569 }
66− .task(id: stream) {
70+ .task(id: "\(appState.activeConnection?.id.uuidString ?? "")|\(stream)") {
6771 await loadAlerts(stream: stream)
6872 }
6973 } else {
@@ -76,13 +80,31 @@ struct AlertsView: View {
7680
7781 private func loadAlerts(stream: String) async {
7882 guard let client = appState.client else { return }
83+ let connID = appState.activeConnection?.id
84+ loadGeneration &+= 1
85+ let generation = loadGeneration
7986 isLoading = true
8087 errorMessage = nil
8188 alertConfig = nil
8289
8390 do {
84− alertConfig = try await client.getAlerts(stream: stream)
91+ let config = try await client.getAlerts(stream: stream)
92+ // Superseded by a newer load: leave its spinner and state alone.
93+ guard generation == loadGeneration else { return }
94+ // The manual Refresh/Retry buttons spawn detached Tasks not tied to
95+ // `.task(id: stream)` cancellation, so a slow refresh for the old stream
96+ // can resolve after a switch. Drop stale results. Check the connection
97+ // id too: two servers can expose a same-named stream, so a name-only
98+ // guard could write the previous server's alerts after a server switch.
99+ // Still clear isLoading on the stale path: this task set the spinner,
100+ // so leaving it true wedges the ProgressView and disables Refresh.
101+ guard stream == appState.selectedStream,
102+ connID == appState.activeConnection?.id else { isLoading = false; return }
103+ alertConfig = config
85104 } catch {
105+ guard generation == loadGeneration else { return }
106+ guard stream == appState.selectedStream,
107+ connID == appState.activeConnection?.id else { isLoading = false; return }
86108 errorMessage = ParseableError.userFriendlyMessage(for: error)
87109 }
88110
@@ -190,8 +212,14 @@ struct AlertRowView: View {
190212 private var stateColor: Color {
191213 switch alert.state?.lowercased() {
192214 case "triggered": return .red
193− case "disabled": return .gray
194− default: return .orange
215+ case "disabled", "silenced": return .gray
216+ // Parseable's default, healthy state (and 2.x's "resolved") — not a warning.
217+ case "not-triggered", "resolved": return .green
218+ // A reported-but-unrecognized state is a genuine "needs attention" signal,
219+ // so tint it orange; a missing state is simply unknown and stays neutral so
220+ // the bell icon isn't painted as a warning for every stateless alert.
221+ case .some: return .orange
222+ case nil: return .secondary
195223 }
196224 }
197225
ParseableViewer/Views/ConnectionSheet.swift+74−13
@@ -14,6 +14,14 @@ struct ConnectionSheet: View {
1414 @State private var isSaving = false
1515 @State private var testResult: TestResult?
1616 @State private var urlValidationError: String?
17+ /// For a new connection, holds the connection created on the first save so a
18+ /// retry (after a failed connect) updates it in place rather than appending a
19+ /// duplicate.
20+ @State private var createdConnection: ServerConnection?
21+ /// Bumped on every field edit and every test run, so an in-flight Test
22+ /// Connection whose fields have since changed doesn't post its (now stale)
23+ /// success/failure under values that were never tested.
24+ @State private var testGeneration = 0
1725
1826 enum TestResult {
1927 case success(String)
@@ -39,12 +47,15 @@ struct ConnectionSheet: View {
3947 TextField("Name:", text: $name)
4048 .textFieldStyle(.roundedBorder)
4149 .accessibilityLabel("Connection name")
50+ .onChange(of: name) { _, _ in invalidateTestResult() }
4251
4352 TextField("Server URL:", text: $url)
4453 .textFieldStyle(.roundedBorder)
4554 .accessibilityLabel("Server URL")
4655 .onChange(of: url) { _, newValue in
4756 urlValidationError = Self.validateURL(newValue)
57+ // A prior test result no longer reflects the edited fields.
58+ invalidateTestResult()
4859 }
4960
5061 if let urlError = urlValidationError, !url.isEmpty {
@@ -56,10 +67,12 @@ struct ConnectionSheet: View {
5667 TextField("Username:", text: $username)
5768 .textFieldStyle(.roundedBorder)
5869 .accessibilityLabel("Username")
70+ .onChange(of: username) { _, _ in invalidateTestResult() }
5971
6072 SecureField("Password:", text: $password)
6173 .textFieldStyle(.roundedBorder)
6274 .accessibilityLabel("Password")
75+ .onChange(of: password) { _, _ in invalidateTestResult() }
6376 }
6477 .formStyle(.grouped)
6578 .padding()
@@ -106,10 +119,22 @@ struct ConnectionSheet: View {
106119 Button("Test Connection") {
107120 testConnection()
108121 }
109− .disabled(url.isEmpty || username.isEmpty || isTesting || urlValidationError != nil)
122+ .disabled(
123+ url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
124+ || username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
125+ || isTesting
126+ || urlValidationError != nil
127+ )
110128 .accessibilityLabel("Test connection")
111129
112130 Button("Cancel") {
131+ // A new connection is persisted on the first save so a retry
132+ // updates it in place. If the user abandons it via Cancel
133+ // (e.g. after a failed connect), remove that never-connected
134+ // entry so it doesn't linger in the sidebar.
135+ if let created = createdConnection {
136+ appState.removeConnection(created)
137+ }
113138 password = ""
114139 dismiss()
115140 }
@@ -119,7 +144,13 @@ struct ConnectionSheet: View {
119144 saveAndConnect()
120145 }
121146 .keyboardShortcut(.defaultAction)
122− .disabled(name.isEmpty || url.isEmpty || username.isEmpty || isSaving || urlValidationError != nil)
147+ .disabled(
148+ name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
149+ || url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
150+ || username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
151+ || isSaving
152+ || urlValidationError != nil
153+ )
123154 }
124155 .padding()
125156 }
@@ -131,26 +162,47 @@ struct ConnectionSheet: View {
131162 username = connection.username
132163 password = connection.password
133164 }
165+ // Validate the pre-filled URL on open. onChange(of:url) doesn't fire
166+ // for the initial assignment above, so without this an invalid stored
167+ // URL would show no error and pass the Save guard.
168+ urlValidationError = Self.validateURL(url)
134169 }
135170 }
136171
172+ private func invalidateTestResult() {
173+ testGeneration += 1
174+ testResult = nil
175+ }
176+
137177 private func testConnection() {
138178 isTesting = true
139179 testResult = nil
180+ testGeneration += 1
181+ let generation = testGeneration
140182
141183 Task {
142184 do {
143− let conn = ServerConnection(name: name, url: url, username: username, password: password)
185+ let conn = ServerConnection(
186+ name: name.trimmingCharacters(in: .whitespacesAndNewlines),
187+ url: url.trimmingCharacters(in: .whitespacesAndNewlines),
188+ username: username.trimmingCharacters(in: .whitespacesAndNewlines),
189+ password: password
190+ )
144191 let client = try ParseableClient(connection: conn)
145192 try await client.checkHealth()
193+ // The health endpoint doesn't check credentials; see
194+ // AppState.verifyCredentials.
195+ try await AppState.verifyCredentials(with: client)
146196 await MainActor.run {
147− testResult = .success("Connection successful")
148197 isTesting = false
198+ guard generation == testGeneration else { return }
199+ testResult = .success("Connection successful")
149200 }
150201 } catch {
151202 await MainActor.run {
152− testResult = .failure(ParseableError.userFriendlyMessage(for: error))
153203 isTesting = false
204+ guard generation == testGeneration else { return }
205+ testResult = .failure(ParseableError.userFriendlyMessage(for: error))
154206 }
155207 }
156208 }
@@ -159,27 +211,36 @@ struct ConnectionSheet: View {
159211 private func saveAndConnect() {
160212 guard !isSaving else { return }
161213
214+ let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
215+ let trimmedURL = url.trimmingCharacters(in: .whitespacesAndNewlines)
216+ let trimmedUsername = username.trimmingCharacters(in: .whitespacesAndNewlines)
217+
162218 let conn: ServerConnection
163− if let existing = connection {
164− conn = ServerConnection(id: existing.id, name: name, url: url, username: username, password: password)
219+ if let existing = connection ?? createdConnection {
220+ conn = ServerConnection(id: existing.id, name: trimmedName, url: trimmedURL, username: trimmedUsername, password: password)
165221 appState.updateConnection(conn)
166222 } else {
167− conn = ServerConnection(name: name, url: url, username: username, password: password)
223+ conn = ServerConnection(name: trimmedName, url: trimmedURL, username: trimmedUsername, password: password)
168224 appState.addConnection(conn)
225+ createdConnection = conn
169226 }
170227
171228 isSaving = true
172229 testResult = nil
173230
174231 Task {
175− await appState.connect(to: conn)
232+ let success = await appState.connect(to: conn)
176233 await MainActor.run {
177234 isSaving = false
178− if appState.errorMessage != nil {
179− testResult = .failure(appState.errorMessage ?? "Connection failed")
180− } else {
235+ if success {
181236 password = ""
182237 dismiss()
238+ } else {
239+ testResult = .failure(appState.errorMessage ?? "Connection failed")
240+ // The sheet reports the failure inline; drop the app-wide alert
241+ // performConnect also raised, which would otherwise surface
242+ // behind/after the sheet (or twice, from the Settings window).
243+ appState.showError = false
183244 }
184245 }
185246 }
@@ -190,7 +251,7 @@ struct ConnectionSheet: View {
190251 guard !trimmed.isEmpty else { return nil }
191252
192253 var normalized = trimmed
193− if !normalized.hasPrefix("http://") && !normalized.hasPrefix("https://") {
254+ if !ServerConnection.hasURLScheme(normalized) {
194255 normalized = "https://\(normalized)"
195256 }
196257
ParseableViewer/Views/ContentView.swift+72−36
@@ -10,21 +10,7 @@ struct ContentView: View {
1010 SidebarView()
1111 } detail: {
1212 if appState.isConnected {
13− if appState.selectedStream != nil {
14− MainContentView()
15− } else {
16− VStack(spacing: 12) {
17− Image(systemName: "sidebar.left")
18− .font(.system(size: 48))
19− .foregroundStyle(.secondary)
20− Text("Select a stream")
21− .font(.title2)
22− .foregroundStyle(.secondary)
23− Text("Choose a log stream from the sidebar to get started.")
24− .foregroundStyle(.tertiary)
25− }
26− .frame(maxWidth: .infinity, maxHeight: .infinity)
27− }
13+ MainContentView()
2814 } else {
2915 WelcomeView()
3016 }
@@ -33,7 +19,10 @@ struct ContentView: View {
3319 ConnectionSheet(connection: appState.editingConnection)
3420 }
3521 .alert("Error", isPresented: $appState.showError) {
36− Button("OK") { appState.showError = false }
22+ Button("OK") {
23+ appState.showError = false
24+ appState.errorMessage = nil
25+ }
3726 } message: {
3827 Text(appState.errorMessage ?? "An unknown error occurred")
3928 }
@@ -42,6 +31,18 @@ struct ContentView: View {
4231
4332struct MainContentView: View {
4433 @Environment(AppState.self) private var appState
34+ /// Kept here rather than inside QueryView so the Query tab's editor text,
35+ /// results and time range survive switching to another tab and back (only
36+ /// the active tab's view is instantiated). Dropped on disconnect, when this
37+ /// view goes away.
38+ @State private var queryViewModel = QueryViewModel()
39+
40+ /// Which server the Query tab's state belongs to. Editing the active
41+ /// connection's URL or user keeps its id (so QueryView's own stream/connection
42+ /// check can't see it), and a rename shouldn't wipe the user's query.
43+ private var serverIdentity: String? {
44+ appState.activeConnection.map { "\($0.id.uuidString)|\($0.url)|\($0.username)" }
45+ }
4546
4647 var body: some View {
4748 @Bindable var appState = appState
@@ -66,28 +67,63 @@ struct MainContentView: View {
6667
6768 Divider()
6869
69− // Content — only the active tab is instantiated
70− switch appState.currentTab {
71− case .query:
72− QueryView()
73− .id(AppState.AppTab.query)
74− case .liveTail:
75− LiveTailView()
76− .id(AppState.AppTab.liveTail)
77− case .streamInfo:
78− StreamDetailView()
79− .id(AppState.AppTab.streamInfo)
80− case .alerts:
81− AlertsView()
82− .id(AppState.AppTab.alerts)
83− case .users:
84− UsersView()
85− .id(AppState.AppTab.users)
86− case .serverInfo:
87− ServerInfoView()
88− .id(AppState.AppTab.serverInfo)
70+ // Content — only the active tab is instantiated. Stream-scoped tabs
71+ // show a placeholder until a stream is selected; server-level tabs
72+ // (Users, Server Info) render regardless.
73+ if appState.currentTab.requiresStream && appState.selectedStream == nil {
74+ SelectStreamPlaceholder()
75+ } else {
76+ switch appState.currentTab {
77+ case .query:
78+ QueryView(viewModel: queryViewModel)
79+ .id(AppState.AppTab.query)
80+ case .liveTail:
81+ LiveTailView()
82+ .id(AppState.AppTab.liveTail)
83+ case .streamInfo:
84+ StreamDetailView()
85+ .id(AppState.AppTab.streamInfo)
86+ case .alerts:
87+ AlertsView()
88+ .id(AppState.AppTab.alerts)
89+ case .users:
90+ UsersView()
91+ .id(AppState.AppTab.users)
92+ case .serverInfo:
93+ ServerInfoView()
94+ .id(AppState.AppTab.serverInfo)
95+ }
8996 }
9097 }
98+ .onChange(of: serverIdentity) { _, _ in
99+ // The Query tab's model outlives stream and server changes made while
100+ // it isn't on screen. On a new server, drop the old one's results and
101+ // query (cancelling one still in flight) so the tab starts fresh.
102+ queryViewModel.clearResults()
103+ queryViewModel.sqlQuery = ""
104+ queryViewModel.filterText = ""
105+ }
106+ .onDisappear {
107+ // Disconnecting tears this view (and the model) down; don't leave an
108+ // in-flight query running against the server the user just left.
109+ queryViewModel.clearResults()
110+ }
111+ }
112+}
113+
114+struct SelectStreamPlaceholder: View {
115+ var body: some View {
116+ VStack(spacing: 12) {
117+ Image(systemName: "sidebar.left")
118+ .font(.system(size: 48))
119+ .foregroundStyle(.secondary)
120+ Text("Select a stream")
121+ .font(.title2)
122+ .foregroundStyle(.secondary)
123+ Text("Choose a log stream from the sidebar to get started.")
124+ .foregroundStyle(.tertiary)
125+ }
126+ .frame(maxWidth: .infinity, maxHeight: .infinity)
91127 }
92128}
93129
ParseableViewer/Views/LiveTailView.swift+152−37
@@ -3,7 +3,10 @@ import SwiftUI
33struct LiveTailView: View {
44 @Environment(AppState.self) private var appState
55 @State private var viewModel = LiveTailViewModel()
6− @State private var selectedRecord: LogRecord?
6+ /// Selection is tracked by entry id, not by record value: live-tail rows
7+ /// frequently share identical content (repeated log lines), so comparing by
8+ /// record value would select/toggle every matching row at once.
9+ @State private var selectedEntryID: UUID?
710 @State private var autoScroll = true
811 @State private var pulseOpacity: Double = 1.0
912 @State private var showColumnPopover = false
@@ -11,6 +14,12 @@ struct LiveTailView: View {
1114 @State private var sortColumn: String?
1215 @State private var sortAscending = false
1316 @State private var columnWidths: [String: CGFloat] = [:]
17+ @State private var cachedSorted: [LiveTailViewModel.LiveTailEntry] = []
18+ @State private var severityColumnSet: Set<String> = []
19+ /// Severity per entry id, precomputed on rebuild so it isn't recomputed for
20+ /// every visible row on each scroll/render.
21+ @State private var severityByID: [UUID: SeverityLevel] = [:]
22+ @State private var liveTailSortTask: Task<Void, Never>?
1423
1524 var body: some View {
1625 @Bindable var vm = viewModel
@@ -106,14 +115,18 @@ struct LiveTailView: View {
106115
107116 Button {
108117 viewModel.clear()
109− selectedRecord = nil
118+ selectedEntryID = nil
110119 sortColumn = nil
111120 columnWidths = [:]
121+ cachedSorted = []
112122 } label: {
113123 Image(systemName: "trash")
114124 }
115125 .help("Clear entries")
116− .keyboardShortcut(.delete, modifiers: .command)
126+ // ⌘K, not ⌘⌫: command-key equivalents are dispatched before the
127+ // focused text field sees the keystroke, so ⌘⌫ (delete to start
128+ // of line) in the Filter field would wipe the whole buffer.
129+ .keyboardShortcut("k", modifiers: .command)
117130 .accessibilityLabel("Clear all entries")
118131 }
119132 .padding(8)
@@ -126,10 +139,21 @@ struct LiveTailView: View {
126139 Circle()
127140 .fill(viewModel.isPaused ? .yellow : .green)
128141 .frame(width: 8, height: 8)
129− .opacity(viewModel.isPaused ? 1.0 : pulseOpacity)
142+ .opacity(pulseOpacity)
130143 .accessibilityLabel(viewModel.isPaused ? "Status: Paused" : "Status: Streaming")
131− .animation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: pulseOpacity)
132− .onAppear { pulseOpacity = 0.3 }
144+ // Drive the pulse with an explicit, re-triggerable animation.
145+ // The previous one-shot `pulseOpacity = 0.3` only changed the
146+ // value once, so the implicit `animation(value:)` never
147+ // restarted after a pause/resume and the dot froze. Pausing
148+ // settles the dot to solid; resuming restarts the pulse.
149+ .onAppear { startPulsing() }
150+ .onChange(of: viewModel.isPaused) { _, paused in
151+ if paused {
152+ withAnimation(.easeInOut(duration: 0.3)) { pulseOpacity = 1.0 }
153+ } else {
154+ startPulsing()
155+ }
156+ }
133157 .onDisappear { pulseOpacity = 1.0 }
134158 Text(viewModel.isPaused ? "Paused" : "Streaming")
135159 .font(.caption)
@@ -243,39 +267,125 @@ struct LiveTailView: View {
243267 .frame(minWidth: 400)
244268
245269 // Detail pane
246− if let record = selectedRecord {
247− LogDetailView(record: record)
270+ if let id = selectedEntryID,
271+ let entry = cachedSorted.first(where: { $0.id == id }) {
272+ LogDetailView(record: entry.record)
248273 .frame(minWidth: 280, idealWidth: 320)
249274 }
250275 }
251276 .onDisappear {
252277 viewModel.stop()
278+ liveTailSortTask?.cancel()
253279 }
254280 .onChange(of: appState.selectedStream) { _, _ in
255281 if viewModel.isRunning {
256282 viewModel.stop()
257283 }
258284 viewModel.clear()
259− selectedRecord = nil
285+ selectedEntryID = nil
260286 sortColumn = nil
261287 columnWidths = [:]
288+ cachedSorted = []
262289 }
263290 .onChange(of: viewModel.visibleColumns) { _, newColumns in
264− // Compute widths for any newly visible columns
265− let records = viewModel.filteredEntries.map { $0.record }
266− for col in newColumns where columnWidths[col] == nil {
267− columnWidths[col] = idealColumnWidth(for: col, records: records)
291+ // Hiding the sort column leaves no header to show or change the sort,
292+ // while rows stay ordered by the invisible value (and auto-scroll stays
293+ // off). Drop it like LogTableView does; the sortColumn change rebuilds.
294+ if let sortColumn, !newColumns.contains(sortColumn) {
295+ self.sortColumn = nil
296+ return
268297 }
298+ // Showing/hiding a column changes the severity column set, so rebuild
299+ // (which also fills in widths for any newly visible columns). A
300+ // width-only update would leave row severity tinting stale until the
301+ // next poll.
302+ rebuildSortedEntries()
303+ }
304+ .onChange(of: viewModel.filteredEntriesGeneration) { _, _ in
305+ // Kept on the always-present container (not inside liveTailTable, which
306+ // is only mounted once visibleColumns is non-empty). A generation bump
307+ // that lands while the table is unmounted — e.g. the first poll arriving
308+ // before columns exist — would otherwise be dropped, leaving the new
309+ // entries unrendered until some other change happened to trigger a rebuild.
310+ rebuildSortedEntries()
311+ }
312+ .onAppear {
313+ rebuildSortedEntries()
314+ }
315+ }
316+
317+ /// Starts (or restarts) the streaming-status pulse. Resetting `pulseOpacity`
318+ /// to 1.0 before animating to 0.3 guarantees a value delta so the repeating
319+ /// animation re-triggers even when called after a pause/resume cycle.
320+ private func startPulsing() {
321+ pulseOpacity = 1.0
322+ withAnimation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true)) {
323+ pulseOpacity = 0.3
269324 }
270325 }
271326
272− private var sortedEntries: [LiveTailViewModel.LiveTailEntry] {
273− let entries = viewModel.filteredEntries
274− guard let sortColumn else { return entries }
275− return entries.sorted { a, b in
276− let aVal = a.record[sortColumn] ?? .null
277− let bVal = b.record[sortColumn] ?? .null
278− return sortAscending ? aVal < bVal : bVal < aVal
327+ /// Computes widths for any visible columns that don't have one yet. Covers
328+ /// the case where switching to a stream with an identical column set doesn't
329+ /// fire `onChange(of: visibleColumns)`, which would otherwise leave widths
330+ /// empty (falling back to the default width) after `selectedStream` cleared
331+ /// them.
332+ private func ensureColumnWidths() {
333+ let records = viewModel.cachedFilteredRecords
334+ for col in viewModel.visibleColumns where columnWidths[col] == nil {
335+ columnWidths[col] = idealColumnWidth(for: col, records: records)
336+ }
337+ }
338+
339+ private func rebuildSortedEntries() {
340+ ensureColumnWidths()
341+ let entries = viewModel.cachedFilteredEntries
342+ // Clear a selection whose entry no longer exists — filtered out by a new
343+ // column/text filter, or aged out of the capped buffer during streaming.
344+ // Without this the detail pane silently vanishes while the stale id lingers
345+ // (LogTableView solves the same problem with reconcileSelection()).
346+ if let id = selectedEntryID, !entries.contains(where: { $0.id == id }) {
347+ selectedEntryID = nil
348+ }
349+ let cols = viewModel.visibleColumns
350+ let sevCols = buildSeverityColumnSet(columns: cols)
351+ // Precompute severity per entry; sorting doesn't change the set.
352+ let severityMap = Dictionary(
353+ entries.map { ($0.id, extractSeverity(from: $0.record, severityColumns: sevCols)) },
354+ uniquingKeysWith: { first, _ in first }
355+ )
356+ // Cancel any pending sort task before either path: when the sort is
357+ // cleared (guard below), a previously-scheduled task could otherwise
358+ // wake after its 150ms delay and overwrite the unsorted result with
359+ // stale sorted entries.
360+ liveTailSortTask?.cancel()
361+ // Severity is keyed by entry id and is independent of row order, so
362+ // publish it synchronously in both paths. Deferring it into the
363+ // debounced sort task (as the sorted path used to) left rows tinted from
364+ // the previous severity-column set for ~150ms — or indefinitely if rapid
365+ // changes kept cancelling the task before it fired.
366+ severityColumnSet = sevCols
367+ severityByID = severityMap
368+ guard let col = sortColumn else {
369+ cachedSorted = entries
370+ return
371+ }
372+ let asc = sortAscending
373+ liveTailSortTask = Task {
374+ try? await Task.sleep(for: .milliseconds(150))
375+ guard !Task.isCancelled else { return }
376+ let sorted = await Task.detached(priority: .userInitiated) {
377+ // `sorted(by:)` is not guaranteed stable and entry ids are random
378+ // UUIDs, so break ties on arrival order (the buffer index) to stop
379+ // equal-keyed rows from reshuffling on every poll.
380+ entries.enumerated().sorted { a, b in
381+ let aVal = a.element.record[col] ?? .null
382+ let bVal = b.element.record[col] ?? .null
383+ if aVal != bVal { return asc ? aVal < bVal : bVal < aVal }
384+ return a.offset < b.offset
385+ }.map(\.element)
386+ }.value
387+ guard !Task.isCancelled else { return }
388+ cachedSorted = sorted
279389 }
280390 }
281391
@@ -284,25 +394,25 @@ struct LiveTailView: View {
284394 ScrollView([.horizontal, .vertical]) {
285395 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
286396 Section {
287− let sorted = sortedEntries
288− ForEach(sorted.indices, id: \.self) { index in
397+ ForEach(Array(cachedSorted.enumerated()), id: \.element.id) { index, entry in
289398 LogRowView(
290− record: sorted[index].record,
399+ record: entry.record,
291400 columns: viewModel.visibleColumns,
292401 columnWidths: columnWidths,
293− isSelected: selectedRecord == sorted[index].record,
402+ isSelected: selectedEntryID == entry.id,
294403 isAlternate: index % 2 == 1,
404+ severity: severityByID[entry.id] ?? .unknown,
405+ severityColumns: severityColumnSet,
295406 wrapText: wrapText,
296407 onCellFilter: { column, value, exclude in
297408 viewModel.addColumnFilter(column: column, value: value, exclude: exclude)
298409 }
299410 )
300− .id(sorted[index].id)
301411 .onTapGesture {
302− if selectedRecord == sorted[index].record {
303− selectedRecord = nil
412+ if selectedEntryID == entry.id {
413+ selectedEntryID = nil
304414 } else {
305− selectedRecord = sorted[index].record
415+ selectedEntryID = entry.id
306416 }
307417 }
308418 }
@@ -312,7 +422,7 @@ struct LiveTailView: View {
312422 sortColumn: $sortColumn,
313423 sortAscending: $sortAscending,
314424 columnWidths: $columnWidths,
315− records: viewModel.filteredEntries.map { $0.record },
425+ records: viewModel.cachedFilteredRecords,
316426 onMoveColumn: { from, to in
317427 viewModel.moveColumn(from, to: to)
318428 },
@@ -323,15 +433,20 @@ struct LiveTailView: View {
323433 }
324434 }
325435 }
326− .onChange(of: viewModel.entries.count) { _, _ in
436+ .onChange(of: sortColumn) { _, _ in
437+ rebuildSortedEntries()
438+ }
439+ .onChange(of: sortAscending) { _, _ in
440+ rebuildSortedEntries()
441+ }
442+ // Scroll when the rendered list (`cachedSorted`) changes, targeting
443+ // its last element. Key off the last element's id rather than the
444+ // count: once the buffer is pinned at `maxEntries`, the count stops
445+ // changing while new rows keep arriving, so a count-based trigger
446+ // would silently stall auto-scroll.
447+ .onChange(of: cachedSorted.last?.id) { _, _ in
327448 guard autoScroll, sortColumn == nil else { return }
328− // When a filter is active, scroll to the last filtered entry;
329− // when no filter, scroll to the absolute last entry.
330− let hasFilters = !viewModel.filterText.isEmpty || !viewModel.columnFilters.isEmpty
331− let target = hasFilters
332− ? viewModel.filteredEntries.last
333− : viewModel.entries.last
334− if let target {
449+ if let target = cachedSorted.last {
335450 proxy.scrollTo(target.id, anchor: .bottom)
336451 }
337452 }
ParseableViewer/Views/LogDetailView.swift+43−14
@@ -4,6 +4,7 @@ struct LogDetailView: View {
44 let record: LogRecord
55 @State private var viewMode: ViewMode = .formatted
66 @State private var showCopyConfirmation = false
7+ @State private var copyConfirmationTask: Task<Void, Never>?
78
89 enum ViewMode: String, CaseIterable {
910 case formatted = "Formatted"
@@ -49,6 +50,12 @@ struct LogDetailView: View {
4950 }
5051 }
5152 .background(Color(nsColor: .controlBackgroundColor))
53+ .onChange(of: record) { _, _ in
54+ // Selecting a different row reuses this view with a new record; clear
55+ // any lingering checkmark/timer so the confirmation doesn't carry over.
56+ copyConfirmationTask?.cancel()
57+ showCopyConfirmation = false
58+ }
5259 }
5360
5461 private func copyToClipboard() {
@@ -61,8 +68,12 @@ struct LogDetailView: View {
6168 guard success else { return }
6269
6370 showCopyConfirmation = true
64− Task {
71+ // Cancel any in-flight timer so a rapid re-copy doesn't let an
72+ // earlier task clear the checkmark while a newer copy is active.
73+ copyConfirmationTask?.cancel()
74+ copyConfirmationTask = Task {
6575 try? await Task.sleep(for: .seconds(1.5))
76+ guard !Task.isCancelled else { return }
6677 showCopyConfirmation = false
6778 }
6879 }
@@ -71,24 +82,25 @@ struct LogDetailView: View {
7182
7283struct FormattedRecordView: View {
7384 let record: LogRecord
85+ let sortedKeys: [String]
7486
75− var sortedKeys: [String] {
87+ init(record: LogRecord) {
88+ self.record = record
7689 let priority = ["p_timestamp", "level", "severity", "message", "msg"]
7790 var keys = record.keys.sorted()
7891 var result: [String] = []
79−
8092 for p in priority {
8193 if let idx = keys.firstIndex(of: p) {
8294 result.append(keys.remove(at: idx))
8395 }
8496 }
8597 result.append(contentsOf: keys)
86− return result
98+ self.sortedKeys = result
8799 }
88100
89101 var body: some View {
90102 VStack(alignment: .leading, spacing: 1) {
91− ForEach(sortedKeys, id: \.self) { key in
103+ ForEach(Array(sortedKeys.enumerated()), id: \.element) { index, key in
92104 HStack(alignment: .top, spacing: 8) {
93105 Text(key)
94106 .font(.system(.caption, design: .monospaced))
@@ -105,8 +117,7 @@ struct FormattedRecordView: View {
105117 .padding(.vertical, 3)
106118 .padding(.horizontal, 8)
107119 .background(
108− sortedKeys.firstIndex(of: key).map { $0 % 2 == 1 }
109− ?? false ? Color.primary.opacity(0.03) : Color.clear
120+ index % 2 == 1 ? Color.primary.opacity(0.03) : Color.clear
110121 )
111122 }
112123 }
@@ -146,8 +157,11 @@ struct JSONValueView: View {
146157 Text(String(v))
147158 .font(.system(.caption, design: .monospaced))
148159 .foregroundStyle(Color(nsColor: .systemPurple))
149− case .double(let v):
150− Text(String(v))
160+ case .double:
161+ // Use displayString so whole-number doubles render as "3" (not "3.0"),
162+ // scientific notation is avoided, and inf/nan map to "null" — matching
163+ // the table cells, CSV/JSON export, and the rest of the app.
164+ Text(value.displayString)
151165 .font(.system(.caption, design: .monospaced))
152166 .foregroundStyle(Color(nsColor: .systemPurple))
153167 case .string(let v):
@@ -185,12 +199,27 @@ struct JSONValueView: View {
185199
186200struct RawJSONView: View {
187201 let record: LogRecord
202+ @State private var highlightedText: AttributedString?
188203
189204 var body: some View {
190− let json = JSONValue.object(record).prettyPrinted()
191− Text(JSONSyntaxHighlighter.highlight(json))
192− .textSelection(.enabled)
193− .padding(8)
194− .frame(maxWidth: .infinity, alignment: .leading)
205+ Group {
206+ if let highlighted = highlightedText {
207+ Text(highlighted)
208+ } else {
209+ Text(JSONValue.object(record).prettyPrinted())
210+ .font(.system(.caption, design: .monospaced))
211+ }
212+ }
213+ .textSelection(.enabled)
214+ .padding(8)
215+ .frame(maxWidth: .infinity, alignment: .leading)
216+ .task(id: record) {
217+ // Drop the previous record's highlight first so we fall back to the
218+ // new record's plain text while the new highlight computes, instead
219+ // of briefly showing the old record's highlighted JSON.
220+ highlightedText = nil
221+ let json = JSONValue.object(record).prettyPrinted()
222+ highlightedText = JSONSyntaxHighlighter.highlight(json)
223+ }
195224 }
196225}
ParseableViewer/Views/LogTableView.swift+261−41
@@ -20,7 +20,13 @@ func idealColumnWidth(for column: String, records: [LogRecord]) -> CGFloat {
2020 let sampleCount = min(records.count, 200)
2121
2222 var widest = measureTextWidth(column, font: headerMeasureFont)
23− for i in 0..<sampleCount {
23+ // Sample evenly across the whole result set, not just the first N rows —
24+ // otherwise a wide value that sorts beyond row N is never measured and the
25+ // column auto-fits too narrow after sorting. Map each of the `sampleCount`
26+ // samples to a spread-out index so we hit exactly `sampleCount` distinct rows
27+ // (a stride with an integer step would skip rows yet still undersample).
28+ for s in 0..<sampleCount {
29+ let i = s * records.count / sampleCount
2430 let text = records[i][column]?.displayString ?? ""
2531 widest = max(widest, measureTextWidth(text, font: cellMeasureFont))
2632 }
@@ -114,19 +120,52 @@ func parseSeverity(from value: String) -> SeverityLevel {
114120 return .unknown
115121}
116122
117−/// Extracts the severity level from a log record by checking common column names.
118−func extractSeverity(from record: LogRecord) -> SeverityLevel {
119− for (key, value) in record {
120− if severityColumnNames.contains(key.lowercased()) {
121− let str: String
122− switch value {
123− case .string(let s): str = s
124− case .int(let i): str = String(i)
125− default: continue
126− }
127− let level = parseSeverity(from: str)
123+/// Columns (lowercased) that carry an OpenTelemetry `severity_number` (1–24)
124+/// rather than an RFC 5424 syslog severity (0–7). The two scales overlap, so
125+/// numeric values from these columns must be interpreted on the OTel scale.
126+private let otelSeverityColumns: Set<String> = ["severity_number", "otel.severity"]
127+
128+/// Maps an OpenTelemetry `severity_number` (1–24) to a ``SeverityLevel``.
129+/// Higher is more severe, in contrast to RFC 5424.
130+func parseOTelSeverityNumber(_ num: Int) -> SeverityLevel {
131+ switch num {
132+ case 1...4: return .trace
133+ case 5...8: return .debug
134+ case 9...12: return .info
135+ case 13...16: return .warning
136+ case 17...20: return .error
137+ case 21...24: return .fatal
138+ default: return .unknown
139+ }
140+}
141+
142+/// Extracts the severity level from a log record by checking only known severity columns.
143+func extractSeverity(from record: LogRecord, severityColumns: Set<String>) -> SeverityLevel {
144+ // Iterate in a deterministic (sorted) order so that, when a record carries
145+ // more than one severity-like column with conflicting values, the "winning"
146+ // column is stable across runs rather than dependent on Set iteration order.
147+ for col in severityColumns.sorted() {
148+ guard let value = record[col] else { continue }
149+ let str: String
150+ switch value {
151+ case .string(let s): str = s
152+ case .int(let i): str = String(i)
153+ // Numeric severities (e.g. OTel severity_number) sometimes decode as a
154+ // double; stringify the integral value so they still parse.
155+ case .double(let d) where d == d.rounded() && abs(d) < 1e15:
156+ str = String(format: "%.0f", d)
157+ default: continue
158+ }
159+ // OpenTelemetry severity columns use a 1–24 scale that collides with
160+ // RFC 5424's 0–7, so disambiguate numeric values by column name.
161+ if otelSeverityColumns.contains(col.lowercased()),
162+ let num = Int(str.trimmingCharacters(in: .whitespaces)) {
163+ let level = parseOTelSeverityNumber(num)
128164 if level != .unknown { return level }
165+ continue
129166 }
167+ let level = parseSeverity(from: str)
168+ if level != .unknown { return level }
130169 }
131170 return .unknown
132171}
@@ -142,8 +181,25 @@ func severityRowTint(for level: SeverityLevel) -> Color? {
142181 }
143182}
144183
184+/// Builds the set of column names (preserving original casing) that are severity columns.
185+func buildSeverityColumnSet(columns: [String]) -> Set<String> {
186+ var result = Set<String>()
187+ for col in columns {
188+ if severityColumnNames.contains(col.lowercased()) {
189+ result.insert(col)
190+ }
191+ }
192+ return result
193+}
194+
145195// MARK: - LogTableView
146196
197+struct IndexedRecord: Identifiable {
198+ let id: Int
199+ let record: LogRecord
200+ let severity: SeverityLevel
201+}
202+
147203struct LogTableView: View {
148204 let records: [LogRecord]
149205 let columns: [String]
@@ -155,8 +211,10 @@ struct LogTableView: View {
155211 @State private var sortColumn: String?
156212 @State private var sortAscending = false
157213 @State private var selectedIndex: Int?
158− @State private var cachedSorted: [LogRecord] = []
214+ @State private var cachedSorted: [IndexedRecord] = []
215+ @State private var severityColumnSet: Set<String> = []
159216 @State private var sortTask: Task<Void, Never>?
217+ @State private var widthTask: Task<Void, Never>?
160218 @State private var columnWidths: [String: CGFloat] = [:]
161219
162220 var body: some View {
@@ -182,23 +240,25 @@ struct LogTableView: View {
182240 ScrollView([.horizontal, .vertical]) {
183241 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
184242 Section {
185− ForEach(cachedSorted.indices, id: \.self) { index in
243+ ForEach(Array(cachedSorted.enumerated()), id: \.element.id) { index, item in
186244 LogRowView(
187− record: cachedSorted[index],
245+ record: item.record,
188246 columns: columns,
189247 columnWidths: columnWidths,
190− isSelected: selectedIndex == index,
248+ isSelected: selectedIndex == item.id,
191249 isAlternate: index % 2 == 1,
250+ severity: item.severity,
251+ severityColumns: severityColumnSet,
192252 wrapText: wrapText,
193253 onCellFilter: onCellFilter
194254 )
195255 .onTapGesture {
196− if selectedIndex == index {
256+ if selectedIndex == item.id {
197257 selectedIndex = nil
198258 selectedRecord = nil
199259 } else {
200− selectedIndex = index
201− selectedRecord = cachedSorted[index]
260+ selectedIndex = item.id
261+ selectedRecord = item.record
202262 }
203263 }
204264 }
@@ -229,44 +289,156 @@ struct LogTableView: View {
229289 .controlSize(.large)
230290 }
231291 }
232− .onChange(of: records) { _, _ in
233− columnWidths = computeColumnWidths(columns: columns, records: records)
292+ .onChange(of: records) { _, newRecords in
293+ recomputeColumnWidths(columns: columns, records: newRecords)
234294 debouncedRebuildSort()
235295 }
296+ .onChange(of: columns) { _, newColumns in
297+ // New columns (e.g. shown via the Column Manager) need widths
298+ // computed; the width task otherwise only runs on a records
299+ // change, leaving them at the default width until the next query.
300+ recomputeColumnWidths(columns: newColumns, records: records)
301+ // After a stream switch the previous sort column may not exist
302+ // in the new schema, which would silently produce a no-op sort
303+ // (every row compares as .null). Drop it so rows fall back to
304+ // their natural order.
305+ if let sortColumn, !newColumns.contains(sortColumn) {
306+ self.sortColumn = nil
307+ // The sortColumn change triggers its own rebuild below.
308+ } else {
309+ // Columns changed without dropping the sort column (e.g.
310+ // hiding/showing a severity column via the Column Manager).
311+ // Rebuild so the severity column set — and therefore row
312+ // tinting — reflects the new columns.
313+ debouncedRebuildSort()
314+ }
315+ }
236316 .onChange(of: sortColumn) { _, _ in debouncedRebuildSort() }
237317 .onChange(of: sortAscending) { _, _ in debouncedRebuildSort() }
318+ .onChange(of: selectedRecord) { _, newValue in
319+ // The owner can drop the selection on its own (QueryViewModel
320+ // clears it after every query). When the new result set equals the
321+ // old one, `onChange(of: records)` doesn't fire, so nothing would
322+ // reconcile the row highlight: the row stayed highlighted with no
323+ // detail pane, and the next click on it merely "deselected" it.
324+ if newValue == nil { selectedIndex = nil }
325+ }
238326 .onAppear {
239− columnWidths = computeColumnWidths(columns: columns, records: records)
327+ // This branch is unmounted while results are empty (e.g. across a
328+ // stream switch, which clears them first), so `onChange(of: columns)`
329+ // never sees the switch. Drop a sort column the new columns don't
330+ // have — or hide — before sorting, or rows would be ordered by an
331+ // invisible column with no header showing the sort.
332+ if let sortColumn, !columns.contains(sortColumn) {
333+ self.sortColumn = nil
334+ }
335+ recomputeColumnWidths(columns: columns, records: records)
240336 rebuildSort()
241337 }
242338 }
243339 }
244340
341+ /// Computes column widths off the main actor and merges them into
342+ /// `columnWidths`, filling only columns that don't yet have a width.
343+ /// Preserves any width the user dragged or auto-fit; a wholesale overwrite
344+ /// would discard manual resizes on every re-query/filter/refresh. Runs on
345+ /// both records changes and columns-only changes so newly shown columns get
346+ /// a fitted width rather than the default.
347+ private func recomputeColumnWidths(columns cols: [String], records recs: [LogRecord]) {
348+ widthTask?.cancel()
349+ widthTask = Task.detached(priority: .userInitiated) {
350+ let widths = computeColumnWidths(columns: cols, records: recs)
351+ guard !Task.isCancelled else { return }
352+ await MainActor.run {
353+ var merged = columnWidths
354+ for (col, width) in widths where merged[col] == nil {
355+ merged[col] = width
356+ }
357+ columnWidths = merged
358+ }
359+ }
360+ }
361+
245362 private func debouncedRebuildSort() {
246363 sortTask?.cancel()
247364 sortTask = Task {
248365 try? await Task.sleep(for: .milliseconds(150))
249366 guard !Task.isCancelled else { return }
250− rebuildSort()
367+ let recs = records
368+ let col = sortColumn
369+ let asc = sortAscending
370+ let sevCols = buildSeverityColumnSet(columns: columns)
371+ let indexed: [IndexedRecord] = await Task.detached(priority: .userInitiated) {
372+ let enumerated = Array(recs.enumerated())
373+ let sorted: [(offset: Int, element: LogRecord)]
374+ if let col {
375+ sorted = enumerated.sorted { a, b in
376+ let aVal = a.element[col] ?? .null
377+ let bVal = b.element[col] ?? .null
378+ // `sorted(by:)` is not guaranteed stable, so break ties on
379+ // the original index to keep equal-keyed rows in a fixed
380+ // order across re-sorts (otherwise low-cardinality columns
381+ // like `level`/`status` would reshuffle on every refresh).
382+ if aVal != bVal { return asc ? aVal < bVal : bVal < aVal }
383+ return a.offset < b.offset
384+ }
385+ } else {
386+ sorted = enumerated
387+ }
388+ return sorted.map {
389+ IndexedRecord(id: $0.offset, record: $0.element, severity: extractSeverity(from: $0.element, severityColumns: sevCols))
390+ }
391+ }.value
392+ guard !Task.isCancelled else { return }
393+ cachedSorted = indexed
394+ severityColumnSet = sevCols
395+ reconcileSelection()
396+ }
397+ }
398+
399+ /// Re-establishes the current selection after `cachedSorted` is rebuilt.
400+ /// Prefers the stable row id so a plain re-sort keeps the exact selected row
401+ /// (rather than jumping to the first duplicate). Falls back to value matching
402+ /// only when the records themselves changed, and clears both the index and
403+ /// the bound record when nothing matches so the detail pane can't go stale.
404+ private func reconcileSelection() {
405+ if let selectedIndex,
406+ let match = cachedSorted.first(where: { $0.id == selectedIndex }),
407+ match.record == selectedRecord {
408+ return
409+ }
410+ if let selectedRecord,
411+ let match = cachedSorted.first(where: { $0.record == selectedRecord }) {
412+ selectedIndex = match.id
413+ } else {
414+ selectedIndex = nil
415+ self.selectedRecord = nil
251416 }
252417 }
253418
254419 private func rebuildSort() {
420+ // A debounced rebuild scheduled before the table unmounted must not land
421+ // after (and overwrite) this synchronous one.
422+ sortTask?.cancel()
423+ let sevCols = buildSeverityColumnSet(columns: columns)
424+ let enumerated = Array(records.enumerated())
425+ let sorted: [(offset: Int, element: LogRecord)]
255426 if let sortColumn {
256− cachedSorted = records.sorted { a, b in
257− let aVal = a[sortColumn] ?? .null
258− let bVal = b[sortColumn] ?? .null
259− return sortAscending ? aVal < bVal : bVal < aVal
427+ sorted = enumerated.sorted { a, b in
428+ let aVal = a.element[sortColumn] ?? .null
429+ let bVal = b.element[sortColumn] ?? .null
430+ // Stable tiebreak on original index — see the async path above.
431+ if aVal != bVal { return sortAscending ? aVal < bVal : bVal < aVal }
432+ return a.offset < b.offset
260433 }
261434 } else {
262− cachedSorted = records
435+ sorted = enumerated
263436 }
264− if let selectedRecord,
265− let idx = cachedSorted.firstIndex(where: { $0 == selectedRecord }) {
266− selectedIndex = idx
267− } else {
268− selectedIndex = nil
437+ cachedSorted = sorted.map {
438+ IndexedRecord(id: $0.offset, record: $0.element, severity: extractSeverity(from: $0.element, severityColumns: sevCols))
269439 }
440+ severityColumnSet = sevCols
441+ reconcileSelection()
270442 }
271443}
272444
@@ -323,10 +495,30 @@ struct LogHeaderView: View {
323495
324496 @State private var draggedColumn: String?
325497 @State private var dropTargetColumn: String?
498+ /// `.contextMenu`'s builder runs during body evaluation, so the filter menus
499+ /// compute their values while the view is being rendered. Writing an `@State`
500+ /// dictionary from there is "modifying state during view update" (undefined
501+ /// behavior, and it re-invalidates the header). The cache is therefore a plain
502+ /// reference that isn't observed; `recordsGeneration` — bumped outside body
503+ /// evaluation — is what invalidates it and triggers the re-render.
504+ @State private var uniqueValuesCache = UniqueValuesCache()
505+ @State private var recordsGeneration = 0
506+
507+ private final class UniqueValuesCache {
508+ var generation = -1
509+ var values: [String: [JSONValue]] = [:]
510+ }
326511
327512 private static let maxFilterValues = 20
328513
329514 private func uniqueValues(for column: String) -> [JSONValue] {
515+ if uniqueValuesCache.generation != recordsGeneration {
516+ uniqueValuesCache.generation = recordsGeneration
517+ uniqueValuesCache.values = [:]
518+ }
519+ if let cached = uniqueValuesCache.values[column] {
520+ return cached
521+ }
330522 var seen = Set<JSONValue>()
331523 var result: [JSONValue] = []
332524 for record in records {
@@ -335,7 +527,9 @@ struct LogHeaderView: View {
335527 result.append(value)
336528 }
337529 }
338− return result.sorted()
530+ let sorted = result.sorted()
531+ uniqueValuesCache.values[column] = sorted
532+ return sorted
339533 }
340534
341535 private func dropIndicatorAlignment(for targetColumn: String) -> Alignment {
@@ -476,6 +670,9 @@ struct LogHeaderView: View {
476670 }
477671 .background(Color(nsColor: .controlBackgroundColor))
478672 .border(Color.secondary.opacity(0.2), width: 0.5)
673+ .onChange(of: records) { _, _ in
674+ recordsGeneration &+= 1
675+ }
479676 }
480677}
481678
@@ -507,14 +704,26 @@ private struct ColumnDropDelegate: DropDelegate {
507704 }
508705
509706 func performDrop(info: DropInfo) -> Bool {
510− guard let dragged = draggedColumn, dragged != column else {
707+ guard let dragged = draggedColumn, dragged != column,
708+ let provider = info.itemProviders(for: [UTType.plainText]).first else {
511709 draggedColumn = nil
512710 dropTargetColumn = nil
513711 return false
514712 }
515− onMoveColumn?(dragged, column)
516713 draggedColumn = nil
517714 dropTargetColumn = nil
715+ // `draggedColumn` is only cleared by a drop on a header, so a header drag
716+ // that was cancelled (or dropped elsewhere) leaves it set, and any later
717+ // plain-text drag onto a header would move that stale column. Only move
718+ // when the dropped payload really is the column header being dragged.
719+ let target = column
720+ let move = onMoveColumn
721+ _ = provider.loadObject(ofClass: NSString.self) { object, _ in
722+ guard let payload = object as? NSString, payload as String == dragged else { return }
723+ DispatchQueue.main.async {
724+ move?(dragged, target)
725+ }
726+ }
518727 return true
519728 }
520729
@@ -531,6 +740,8 @@ struct LogRowView: View {
531740 let columnWidths: [String: CGFloat]
532741 let isSelected: Bool
533742 let isAlternate: Bool
743+ var severity: SeverityLevel = .unknown
744+ var severityColumns: Set<String> = []
534745 var wrapText: Bool = false
535746 var onCellFilter: ((_ column: String, _ value: JSONValue?, _ exclude: Bool) -> Void)?
536747
@@ -547,7 +758,10 @@ struct LogRowView: View {
547758 .foregroundStyle(colorForValue(column: column, value: value))
548759 .contextMenu {
549760 Button("Copy Value") {
550− let text = value?.displayString ?? ""
761+ // Use exportString, not displayString: the latter
762+ // renders nested arrays/objects as placeholders like
763+ // "[3 items]", so copying would lose the real data.
764+ let text = value?.exportString ?? ""
551765 NSPasteboard.general.clearContents()
552766 _ = NSPasteboard.general.setString(text, forType: .string)
553767 }
@@ -557,11 +771,17 @@ struct LogRowView: View {
557771 }
558772 if let onCellFilter {
559773 Divider()
774+ // Normalize a null cell to `nil` so this produces an
775+ // IS NULL / IS NOT NULL filter, matching the header
776+ // "Filter by Value" path. Passing `.null` straight
777+ // through would build an `= null` value filter, which
778+ // the live-tail in-memory matcher treats differently.
779+ let filterValue: JSONValue? = value == .null ? nil : value
560780 Button("Filter by This Value") {
561− onCellFilter(column, value, false)
781+ onCellFilter(column, filterValue, false)
562782 }
563783 Button("Exclude This Value") {
564− onCellFilter(column, value, true)
784+ onCellFilter(column, filterValue, true)
565785 }
566786 }
567787 }
@@ -575,7 +795,7 @@ struct LogRowView: View {
575795 if isAlternate {
576796 Color.primary.opacity(0.02)
577797 }
578− if let tint = severityRowTint(for: extractSeverity(from: record)) {
798+ if let tint = severityRowTint(for: severity) {
579799 tint
580800 }
581801 }
@@ -585,7 +805,7 @@ struct LogRowView: View {
585805
586806 private func colorForValue(column: String, value: JSONValue?) -> Color {
587807 guard let value else { return .secondary }
588− if severityColumnNames.contains(column.lowercased()) {
808+ if severityColumns.contains(column) {
589809 return levelColor(for: value.displayString)
590810 }
591811 return .primary
ParseableViewer/Views/QueryView.swift+111−28
@@ -1,8 +1,22 @@
11import SwiftUI
22
3+/// Composite of the inputs that decide which query QueryView should run. Watched
4+/// by a single `.onChange` so a stream switch and a pending saved-filter (which
5+/// arrive in the same update) are handled together in one pass — two separate
6+/// `.onChange` handlers would race and could clobber the filter with the default
7+/// query depending on their firing order.
8+private struct QueryViewContext: Equatable {
9+ let stream: String?
10+ let pendingSQL: String?
11+}
12+
313struct QueryView: View {
414 @Environment(AppState.self) private var appState
5− @State private var viewModel = QueryViewModel()
15+ /// Owned by MainContentView, not by this view: only the active tab is
16+ /// mounted, so a view-local @State model was rebuilt on every tab switch —
17+ /// discarding the user's query, results, time range and filter and re-running
18+ /// the default query when they came back.
19+ let viewModel: QueryViewModel
620 @State private var showSaveFilterSheet = false
721 @State private var saveFilterName = ""
822 @State private var isSavingFilter = false
@@ -79,7 +93,7 @@ struct QueryView: View {
7993 } label: {
8094 Image(systemName: "square.and.arrow.up")
8195 }
82− .disabled(viewModel.results.isEmpty)
96+ .disabled(viewModel.filteredResults.isEmpty)
8397 .accessibilityLabel("Export results")
8498 .help("Export results")
8599
@@ -237,6 +251,23 @@ struct QueryView: View {
237251 isLoading: viewModel.isLoading,
238252 wrapText: wrapText,
239253 onCellFilter: { column, value, exclude in
254+ // Arrays/objects are List/Struct columns on the server; a
255+ // `col = '<json>'` comparison fails to plan, and the failed
256+ // run would clear the results the user is looking at.
257+ if let value, !value.isScalar {
258+ viewModel.errorMessage = "Filtering by an array or object value isn't supported in SQL queries."
259+ return
260+ }
261+ // Results from a blank editor come from the auto-generated
262+ // default query, which `addColumnFilter` can't see (it edits
263+ // `sqlQuery`); put that query in the editor so the filter
264+ // actually applies instead of silently re-running unfiltered.
265+ if viewModel.sqlQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
266+ let stream = appState.selectedStream {
267+ // (Passing a previous stream forces the replacement even
268+ // when the blank editor holds only whitespace.)
269+ viewModel.setDefaultQuery(stream: stream, previousStream: stream)
270+ }
240271 viewModel.addColumnFilter(column: column, value: value, exclude: exclude)
241272 Task {
242273 await viewModel.executeQuery(
@@ -251,19 +282,36 @@ struct QueryView: View {
251282 )
252283 }
253284 }
254− .onChange(of: appState.selectedStream) { oldValue, newValue in
255− viewModel.clearResults()
256− if let stream = newValue {
257− let didSetDefault = viewModel.setDefaultQuery(stream: stream, previousStream: oldValue)
285+ .onChange(of: QueryViewContext(stream: appState.selectedStream, pendingSQL: appState.pendingFilterSQL)) { old, new in
286+ guard let stream = new.stream else {
287+ viewModel.clearResults()
288+ return
289+ }
290+ let streamChanged = old.stream != new.stream
291+ if streamChanged {
292+ viewModel.clearResults()
293+ viewModel.boundContext = QueryViewModel.BoundContext(
294+ connectionID: appState.activeConnection?.id, stream: stream
295+ )
258296 Task {
259297 await viewModel.loadSchema(client: appState.client, stream: stream)
260298 }
299+ }
300+ // A pending saved filter (set together with the stream switch, or on
301+ // its own for the already-selected stream) takes priority over the
302+ // default query. Consuming it here in the same handler that owns the
303+ // stream switch avoids the previous two-handler race.
304+ if let sql = appState.pendingFilterSQL {
305+ appState.pendingFilterSQL = nil
306+ viewModel.sqlQuery = sql
307+ Task {
308+ await viewModel.executeQuery(client: appState.client, stream: stream)
309+ }
310+ } else if streamChanged {
311+ let didSetDefault = viewModel.setDefaultQuery(stream: stream, previousStream: old.stream)
261312 if didSetDefault {
262313 Task {
263− await viewModel.executeQuery(
264− client: appState.client,
265− stream: stream
266− )
314+ await viewModel.executeQuery(client: appState.client, stream: stream)
267315 }
268316 }
269317 }
@@ -279,28 +327,63 @@ struct QueryView: View {
279327 }
280328 .onAppear {
281329 if let stream = appState.selectedStream {
282− if viewModel.schemaFields.isEmpty {
330+ // The view model outlives this view. If the stream (or server)
331+ // changed while another tab was showing, the state it kept belongs
332+ // to the old one — reset it exactly like a stream switch would.
333+ let context = QueryViewModel.BoundContext(
334+ connectionID: appState.activeConnection?.id, stream: stream
335+ )
336+ var previousStream: String?
337+ if let bound = viewModel.boundContext, bound != context {
338+ previousStream = bound.stream
339+ viewModel.clearResults()
340+ // A freshly built model (what this view used to get on every
341+ // mount) had no results filter; don't let an old one hide rows.
342+ viewModel.filterText = ""
343+ }
344+ viewModel.boundContext = context
345+ // Reload the schema when it's missing OR when the loaded schema
346+ // belongs to a different stream than the current one — otherwise a
347+ // viewModel that survives with another stream's schema would keep
348+ // autocomplete pointed at the wrong stream's fields until the next
349+ // stream switch.
350+ if viewModel.schemaFields.isEmpty || viewModel.latestSchemaStream != stream {
283351 Task {
284352 await viewModel.loadSchema(client: appState.client, stream: stream)
285353 }
286354 }
287− let didSetDefault = viewModel.setDefaultQuery(stream: stream)
288− if didSetDefault && viewModel.results.isEmpty {
355+ // A saved filter may have set pendingFilterSQL before this view was
356+ // mounted (e.g. the filter was launched from another tab). .onChange
357+ // doesn't fire for a value that changed before the view entered the
358+ // hierarchy, so honor it here instead of overwriting the editor with
359+ // the default query.
360+ if let sql = appState.pendingFilterSQL {
361+ viewModel.sqlQuery = sql
362+ appState.pendingFilterSQL = nil
289363 Task {
290364 await viewModel.executeQuery(
291365 client: appState.client,
292366 stream: stream
293367 )
294368 }
369+ } else {
370+ let didSetDefault = viewModel.setDefaultQuery(stream: stream, previousStream: previousStream)
371+ if didSetDefault && viewModel.results.isEmpty {
372+ Task {
373+ await viewModel.executeQuery(
374+ client: appState.client,
375+ stream: stream
376+ )
377+ }
378+ }
295379 }
296380 }
297381 }
298− .onDisappear {
299− if viewModel.isLoading {
300− viewModel.cancelQuery()
301− }
302− }
303382 .onChange(of: appState.queryRefreshToken) { _, _ in
383+ // Guard on a selected stream like every sibling query trigger in this
384+ // view. Without it, a refresh (Cmd+R) with no stream selected and an
385+ // empty editor surfaces a spurious "Select a stream..." error.
386+ guard appState.selectedStream != nil else { return }
304387 Task {
305388 await viewModel.executeQuery(
306389 client: appState.client,
@@ -308,12 +391,6 @@ struct QueryView: View {
308391 )
309392 }
310393 }
311− .onChange(of: appState.pendingFilterSQL) { _, newSQL in
312− if let sql = newSQL {
313− viewModel.sqlQuery = sql
314− appState.pendingFilterSQL = nil
315− }
316− }
317394 .alert("Export Error", isPresented: $showExportError) {
318395 Button("OK") {}
319396 } message: {
@@ -370,7 +447,10 @@ struct QueryView: View {
370447 panel.begin { result in
371448 guard result == .OK, let url = panel.url else { return }
372449 let isCSV = url.pathExtension.lowercased() == "csv"
373− let results = viewModel.results
450+ // Export what's on screen: the table renders `filteredResults`, so a
451+ // user who has typed a result filter expects the export to contain
452+ // those rows, not the full unfiltered set.
453+ let results = viewModel.filteredResults
374454 let columns = viewModel.visibleColumns
375455 Task.detached(priority: .userInitiated) {
376456 let content: String?
@@ -379,7 +459,10 @@ struct QueryView: View {
379459 } else {
380460 let encoder = JSONEncoder()
381461 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
382− content = (try? encoder.encode(results))
462+ // Project to visible columns so JSON export matches CSV and
463+ // doesn't leak hidden fields.
464+ let projected = QueryViewModel.projectRecords(results, to: columns)
465+ content = (try? encoder.encode(projected))
383466 .flatMap { String(data: $0, encoding: .utf8) }
384467 }
385468 guard let content else {
@@ -413,7 +496,7 @@ struct ColumnManagerView: View {
413496 Text("Columns")
414497 .font(.headline)
415498 Spacer()
416− if !viewModel.hiddenColumns.isEmpty || !viewModel.autoHiddenColumns.isEmpty || viewModel.columnOrder != viewModel.columns {
499+ if viewModel.hasHiddenColumns || viewModel.columnOrder != viewModel.columns {
417500 Button("Reset") {
418501 viewModel.resetColumnConfig()
419502 }
@@ -467,7 +550,7 @@ struct ColumnManagerView: View {
467550 }
468551 .listStyle(.plain)
469552
470− if !viewModel.hiddenColumns.isEmpty || !viewModel.autoHiddenColumns.isEmpty {
553+ if viewModel.hasHiddenColumns {
471554 Divider()
472555 Button("Show All Columns") {
473556 viewModel.showAllColumns()
ParseableViewer/Views/SQLAutoComplete.swift+190−22
@@ -10,18 +10,23 @@ struct SQLCompletionItem: Hashable {
1010 case column
1111 }
1212
13+ /// The text inserted into the editor when the completion is accepted. For
14+ /// tables this is the quoted identifier (`"name"`) so the resulting SQL is
15+ /// valid even when the stream name contains spaces or other special chars.
1316 let text: String
1417 let kind: Kind
1518 let detail: String?
16− /// The raw text to insert (without quoting). For tables this equals the
17− /// unquoted stream name so prefix matching works correctly.
18− let insertText: String
19+ /// The bare text used for prefix/exact-match comparison against what the
20+ /// user typed. For tables this is the unquoted stream name, since the typed
21+ /// prefix never includes the surrounding quotes. This is NOT what gets
22+ /// inserted — see `text`.
23+ let matchText: String
1924
20− init(text: String, kind: Kind, detail: String? = nil, insertText: String? = nil) {
25+ init(text: String, kind: Kind, detail: String? = nil, matchText: String? = nil) {
2126 self.text = text
2227 self.kind = kind
2328 self.detail = detail
24− self.insertText = insertText ?? text
29+ self.matchText = matchText ?? text
2530 }
2631
2732 var kindLabel: String {
@@ -81,14 +86,59 @@ enum SQLCompletionProvider {
8186 }
8287 }
8388
89+ // The matching prefix is only the text before the caret (what the user has
90+ // typed so far), but the replacement range spans the whole word — scan
91+ // forward past any trailing word characters so a mid-token completion
92+ // replaces the entire token instead of duplicating its tail.
93+ var wordEnd = cursorPosition
94+ while wordEnd < nsText.length {
95+ if isWordCharacter(nsText.character(at: wordEnd)) {
96+ wordEnd += 1
97+ } else {
98+ break
99+ }
100+ }
101+
84102 let prefix = nsText.substring(with: NSRange(location: wordStart, length: cursorPosition - wordStart))
85− let range = NSRange(location: wordStart, length: cursorPosition - wordStart)
86103
87104 guard !prefix.isEmpty else {
88− return ([], "", range)
105+ return ([], "", NSRange(location: wordStart, length: wordEnd - wordStart))
106+ }
107+
108+ // Words typed inside a comment or a string literal aren't SQL, so offer
109+ // nothing there. Otherwise the popup opens (e.g. `-- grouped by date`
110+ // matches DATE) and the Return/Tab meant to end the line or keep typing is
111+ // captured to accept a keyword, rewriting the comment or the literal value.
112+ if isInsideCommentOrStringLiteral(text, offset: cursorPosition) {
113+ return ([], prefix, NSRange(location: wordStart, length: wordEnd - wordStart))
89114 }
90115
91116 let context = determineContext(text: text, position: wordStart)
117+
118+ // Table (and column) completions supply their own quoting. If the user has
119+ // already typed quotes directly around the word (common for stream names
120+ // with spaces, e.g. `FROM "my"`), absorb them into the replacement range so
121+ // the inserted `"name"` replaces the stray quotes instead of producing
122+ // `""name""`. Mirror `insertCompletion`, which absorbs leading and trailing
123+ // quotes independently for any `.table`/`.column` item — so apply this
124+ // wherever those completions are offered (`.tableRef`, `.columnRef` and
125+ // `.general`).
126+ var replaceStart = wordStart
127+ var replaceEnd = wordEnd
128+ let offersIdentifiers: Bool
129+ switch context {
130+ case .tableRef, .columnRef, .general: offersIdentifiers = true
131+ case .afterOrder, .afterGroup: offersIdentifiers = false
132+ }
133+ if offersIdentifiers {
134+ if wordStart > 0, nsText.character(at: wordStart - 1) == 0x22 {
135+ replaceStart -= 1
136+ }
137+ if wordEnd < nsText.length, nsText.character(at: wordEnd) == 0x22 {
138+ replaceEnd += 1
139+ }
140+ }
141+ let range = NSRange(location: replaceStart, length: replaceEnd - replaceStart)
92142 let uppercasePrefix = prefix.uppercased()
93143
94144 var items: [SQLCompletionItem] = []
@@ -99,19 +149,19 @@ enum SQLCompletionProvider {
99149 items.append(SQLCompletionItem(
100150 text: "\"\(name)\"",
101151 kind: .table,
102− insertText: name
152+ matchText: name
103153 ))
104154 }
105155
106156 case .columnRef:
107157 for field in schemaFields.sorted(by: { $0.name < $1.name })
108158 where field.name.uppercased().hasPrefix(uppercasePrefix) {
109− items.append(SQLCompletionItem(text: field.name, kind: .column, detail: field.dataType))
159+ items.append(columnItem(for: field))
110160 }
111− for fn in SQLSyntaxHighlighter.functions.sorted() where fn.hasPrefix(uppercasePrefix) {
161+ for fn in SQLSyntaxHighlighter.sortedFunctions where fn.hasPrefix(uppercasePrefix) {
112162 items.append(SQLCompletionItem(text: fn, kind: .function))
113163 }
114− for kw in SQLSyntaxHighlighter.keywords.sorted() where kw.hasPrefix(uppercasePrefix) {
164+ for kw in SQLSyntaxHighlighter.sortedKeywords where kw.hasPrefix(uppercasePrefix) {
115165 items.append(SQLCompletionItem(text: kw, kind: .keyword))
116166 }
117167
@@ -121,37 +171,120 @@ enum SQLCompletionProvider {
121171 }
122172
123173 case .general:
124− for kw in SQLSyntaxHighlighter.keywords.sorted() where kw.hasPrefix(uppercasePrefix) {
174+ for kw in SQLSyntaxHighlighter.sortedKeywords where kw.hasPrefix(uppercasePrefix) {
125175 items.append(SQLCompletionItem(text: kw, kind: .keyword))
126176 }
127− for fn in SQLSyntaxHighlighter.functions.sorted() where fn.hasPrefix(uppercasePrefix) {
177+ for fn in SQLSyntaxHighlighter.sortedFunctions where fn.hasPrefix(uppercasePrefix) {
128178 items.append(SQLCompletionItem(text: fn, kind: .function))
129179 }
130180 for name in streamNames.sorted() where name.uppercased().hasPrefix(uppercasePrefix) {
131181 items.append(SQLCompletionItem(
132182 text: "\"\(name)\"",
133183 kind: .table,
134− insertText: name
184+ matchText: name
135185 ))
136186 }
137187 for field in schemaFields.sorted(by: { $0.name < $1.name })
138188 where field.name.uppercased().hasPrefix(uppercasePrefix) {
139− items.append(SQLCompletionItem(text: field.name, kind: .column, detail: field.dataType))
189+ items.append(columnItem(for: field))
140190 }
141191 }
142192
143− // Don't show the popup when the only match is an exact hit
144− if items.count == 1 && items[0].text.uppercased() == uppercasePrefix {
145− return ([], prefix, range)
193+ // Don't show the popup when the only match is an exact hit. Compare the
194+ // match text (unquoted), not the display text — a table's display text is
195+ // wrapped in quotes (`"name"`) and would never match the bare prefix.
196+ // Columns are the exception: one that needs quoting but was typed bare
197+ // (`statusCode`, which DataFusion would lowercase) must still be offered,
198+ // so a column only counts as an exact hit when accepting would leave the
199+ // text unchanged (the range already spans any quotes the user typed).
200+ if items.count == 1 {
201+ let only = items[0]
202+ let isExactHit = only.kind == .column
203+ ? nsText.substring(with: range) == only.text
204+ : only.matchText.uppercased() == uppercasePrefix
205+ if isExactHit { return ([], prefix, range) }
146206 }
147207
148208 return (items, prefix, range)
149209 }
150210
211+ /// Whether the UTF-16 `offset` falls inside a `--`/`/* */` comment or a
212+ /// `'...'` string literal. The caret at the very end of an unterminated
213+ /// literal/comment (or of a line comment) is still inside it.
214+ static func isInsideCommentOrStringLiteral(_ text: String, offset: Int) -> Bool {
215+ for token in SQLTokenizer.tokenize(text) {
216+ let range = NSRange(token.range, in: text)
217+ // Tokens are in order; one starting at or after the caret can't contain it.
218+ if range.location >= offset { break }
219+ let end = NSMaxRange(range)
220+ let isClosed: Bool
221+ switch token.kind {
222+ case .lineComment:
223+ isClosed = false
224+ case .blockComment:
225+ isClosed = range.length >= 4 && text[token.range].hasSuffix("*/")
226+ case .stringLiteral:
227+ // `''` escapes pair up, so a terminated literal has an even count.
228+ let quotes = text[token.range].filter { $0 == "'" }.count
229+ isClosed = range.length >= 2 && quotes % 2 == 0
230+ default:
231+ continue
232+ }
233+ if offset < end || (offset == end && !isClosed) { return true }
234+ }
235+ return false
236+ }
237+
238+ /// A column completion, double-quoted when the name wouldn't survive as a bare
239+ /// identifier. DataFusion (Parseable's query engine) folds unquoted identifiers
240+ /// to lowercase, so inserting a mixed-case field bare (`statusCode`) queries a
241+ /// nonexistent `statuscode`; names with dots, spaces, or other punctuation
242+ /// (e.g. OTel's `service.name`) wouldn't parse as one identifier at all. Plain
243+ /// lowercase names stay bare so the common case reads naturally.
244+ static func columnItem(for field: SchemaField) -> SQLCompletionItem {
245+ SQLCompletionItem(
246+ text: quotedIdentifierIfNeeded(field.name),
247+ kind: .column,
248+ detail: field.dataType,
249+ matchText: field.name
250+ )
251+ }
252+
253+ static func quotedIdentifierIfNeeded(_ name: String) -> String {
254+ let isPlainLowercase = name.unicodeScalars.enumerated().allSatisfy { index, scalar in
255+ switch scalar {
256+ case "a"..."z", "_": return true
257+ case "0"..."9": return index > 0
258+ default: return false
259+ }
260+ }
261+ // A bare keyword/function name (`order`, `user`, `limit`, `date`) would be
262+ // parsed as SQL syntax rather than as the column, so quote those too.
263+ let upper = name.uppercased()
264+ let isReservedWord = SQLSyntaxHighlighter.keywords.contains(upper)
265+ || SQLSyntaxHighlighter.functions.contains(upper)
266+ if !name.isEmpty && isPlainLowercase && !isReservedWord { return name }
267+ return QueryViewModel.escapeSQLIdentifier(name)
268+ }
269+
151270 // MARK: - Context Detection
152271
153272 static func determineContext(text: String, position: Int) -> SQLCompletionContext {
154− let before = String(text.prefix(position))
273+ // `position` is a UTF-16 offset (computed via NSString), so slice with
274+ // NSString too. `String.prefix` counts grapheme clusters and would slice
275+ // at the wrong place when non-BMP characters (e.g. emoji) precede it.
276+ let before = (text as NSString).substring(to: position)
277+
278+ // A qualifier dot directly before the caret (`t.co|`, `"stream".le|`) means
279+ // we're completing the column half of a table-qualified reference. The word
280+ // scan that produced `position` stops at the dot (it's not a word character),
281+ // while the tokenizer keeps the dot attached to the preceding token — so
282+ // without this the last token is `"t."`, which matches no keyword and falls
283+ // through to `.general`, mixing keywords/tables into a column position.
284+ if before.hasSuffix(".") {
285+ return .columnRef
286+ }
287+
155288 let tokens = tokenize(before)
156289
157290 guard let lastToken = tokens.last?.uppercased() else {
@@ -169,7 +302,10 @@ enum SQLCompletionProvider {
169302 case "GROUP":
170303 return .afterGroup
171304 default:
172− if lastToken == "," {
305+ // After a `,` or an opening `(` the caret continues an argument/column
306+ // list (e.g. `SELECT COUNT(`, `WHERE status IN (`, `SELECT a, `), so
307+ // scan back to the governing keyword to decide column vs table context.
308+ if lastToken == "," || lastToken == "(" {
173309 for token in tokens.reversed() {
174310 let upper = token.uppercased()
175311 if ["SELECT", "BY", "WHERE", "HAVING", "ON"].contains(upper) {
@@ -228,7 +364,12 @@ enum SQLCompletionProvider {
228364 (ch >= 0x41 && ch <= 0x5A) || // A-Z
229365 (ch >= 0x61 && ch <= 0x7A) || // a-z
230366 (ch >= 0x30 && ch <= 0x39) || // 0-9
231− ch == 0x5F // _
367+ ch == 0x5F || // _
368+ ch >= 0x80 // any non-ASCII code unit: Unicode letters
369+ // and digits in identifiers (e.g. accented or CJK schema field names), plus
370+ // both halves of a surrogate pair. SQL delimiters — whitespace, operators,
371+ // quotes, parens, commas — are all ASCII (< 0x80), so this only sweeps in
372+ // genuine identifier characters and won't run a word past a token boundary.
232373 }
233374}
234375
@@ -324,7 +465,12 @@ final class SQLCompletionPopup: NSObject, NSTableViewDataSource, NSTableViewDele
324465
325466 let rowCount = min(items.count, Self.maxVisibleRows)
326467 let height = CGFloat(rowCount) * Self.rowHeight + 4
327− let frame = NSRect(x: panel.frame.origin.x, y: panel.frame.origin.y,
468+ // Anchor by the top edge (where the caret sits), matching show()/reposition().
469+ // The panel's origin is its bottom-left corner, so holding origin.y fixed
470+ // while the height changes would move the top edge — growing the list would
471+ // creep the popup upward over the caret. Pin the top edge instead.
472+ let topEdge = panel.frame.origin.y + panel.frame.height
473+ let frame = NSRect(x: panel.frame.origin.x, y: topEdge - height,
328474 width: Self.panelWidth, height: height)
329475 panel.setFrame(frame, display: true)
330476 }
@@ -339,6 +485,17 @@ final class SQLCompletionPopup: NSObject, NSTableViewDataSource, NSTableViewDele
339485 panel.orderFront(nil)
340486 }
341487
488+ /// Moves an already-visible popup so it stays anchored to the caret as the
489+ /// user keeps typing (otherwise it lingers at its original position).
490+ func reposition(at screenPoint: NSPoint) {
491+ guard panel.isVisible else { return }
492+ let rowCount = min(items.count, Self.maxVisibleRows)
493+ let height = CGFloat(rowCount) * Self.rowHeight + 4
494+ let frame = NSRect(x: screenPoint.x, y: screenPoint.y - height,
495+ width: Self.panelWidth, height: height)
496+ panel.setFrame(frame, display: true)
497+ }
498+
342499 func hide() {
343500 panel.parent?.removeChildWindow(panel)
344501 panel.orderOut(nil)
@@ -372,6 +529,17 @@ final class SQLCompletionPopup: NSObject, NSTableViewDataSource, NSTableViewDele
372529
373530 // MARK: - NSTableViewDelegate
374531
532+ func tableViewSelectionDidChange(_ notification: Notification) {
533+ // A single click selects a row in the table directly. Keep `selectedIndex`
534+ // — what Return/Tab accept and what the arrow keys move from — in sync,
535+ // otherwise Return inserts the previously highlighted item instead of the
536+ // one the user clicked.
537+ let row = tableView.selectedRow
538+ if row >= 0, row < items.count {
539+ selectedIndex = row
540+ }
541+ }
542+
375543 func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
376544 guard row < items.count else { return nil }
377545 let item = items[row]
ParseableViewer/Views/SQLEditorView.swift+102−9
@@ -57,11 +57,22 @@ struct SQLEditorView: NSViewRepresentable {
5757 // Only update when text changed externally (not from user typing)
5858 if textView.string != text && !context.coordinator.isEditing {
5959 let selectedRanges = textView.selectedRanges
60− textView.string = text
60+ context.coordinator.replaceText(with: text, in: textView)
6161 context.coordinator.applyHighlighting(to: textView)
62− let validRanges = selectedRanges.filter { NSMaxRange($0.rangeValue) <= textView.string.count }
63− if !validRanges.isEmpty {
64− textView.selectedRanges = validRanges
62+ // NSRange is UTF-16 based; compare against the NSString length, not
63+ // String.count (grapheme count), or wide characters drop the selection.
64+ // Clamp each range to the new length rather than discarding the ones that
65+ // overflow, so replacing the text with a shorter string keeps the caret
66+ // at the end instead of losing the selection entirely.
67+ let length = (textView.string as NSString).length
68+ let clampedRanges = selectedRanges.map { value -> NSValue in
69+ let range = value.rangeValue
70+ let location = min(range.location, length)
71+ let len = min(range.length, length - location)
72+ return NSValue(range: NSRange(location: location, length: len))
73+ }
74+ if !clampedRanges.isEmpty {
75+ textView.selectedRanges = clampedRanges
6576 }
6677 }
6778 context.coordinator.updateErrorHighlight(in: textView, errorRange: errorRange)
@@ -71,6 +82,10 @@ struct SQLEditorView: NSViewRepresentable {
7182 Coordinator(text: $text, streamNames: streamNames, schemaFields: schemaFields)
7283 }
7384
85+ static func dismantleNSView(_ nsView: NSScrollView, coordinator: Coordinator) {
86+ coordinator.cleanup()
87+ }
88+
7489 final class Coordinator: NSObject, NSTextViewDelegate {
7590 var text: Binding<String>
7691 var isEditing = false
@@ -86,6 +101,11 @@ struct SQLEditorView: NSViewRepresentable {
86101 /// Tracks whether we are inserting a completion so that `textDidChange`
87102 /// doesn't re-trigger the popup for the replacement.
88103 private var isInsertingCompletion = false
104+ /// Set while `replaceText(with:in:)` pushes a model-side change (history
105+ /// pick, saved filter, cell filter, column toggle…) into the text view, so
106+ /// `textDidChange` doesn't echo it back into the binding or open the
107+ /// completion popup for text the user didn't type.
108+ private var isApplyingModelChange = false
89109
90110 init(text: Binding<String>, streamNames: [String], schemaFields: [SchemaField]) {
91111 self.text = text
@@ -101,7 +121,8 @@ struct SQLEditorView: NSViewRepresentable {
101121 // MARK: - NSTextViewDelegate
102122
103123 func textDidChange(_ notification: Notification) {
104− guard let textView = notification.object as? NSTextView else { return }
124+ guard let textView = notification.object as? NSTextView,
125+ !isApplyingModelChange else { return }
105126 isEditing = true
106127 clearErrorHighlight(in: textView)
107128 text.wrappedValue = textView.string
@@ -113,6 +134,34 @@ struct SQLEditorView: NSViewRepresentable {
113134 }
114135 }
115136
137+ /// Replaces the editor's contents with text set from outside the editor.
138+ /// Assigning `textView.string` directly bypasses the text system's undo
139+ /// registration and leaves the user's earlier typing on the undo stack with
140+ /// ranges that belong to the old text — Cmd+Z would then edit an arbitrary
141+ /// span of the new query (or raise on an out-of-range undo). Routing the
142+ /// change through `shouldChangeText`/`didChangeText` records it as one
143+ /// undoable step, so Cmd+Z restores the previous query instead.
144+ func replaceText(with newText: String, in textView: NSTextView) {
145+ let fullRange = NSRange(location: 0, length: (textView.string as NSString).length)
146+ isApplyingModelChange = true
147+ defer { isApplyingModelChange = false }
148+ textView.breakUndoCoalescing()
149+ if textView.shouldChangeText(in: fullRange, replacementString: newText) {
150+ textView.replaceCharacters(in: fullRange, with: newText)
151+ textView.didChangeText()
152+ } else {
153+ textView.string = newText
154+ }
155+ textView.breakUndoCoalescing()
156+ }
157+
158+ func textDidEndEditing(_ notification: Notification) {
159+ // The popup is a separate child panel; without this it keeps floating
160+ // over the results (and accepting double-clicks) after focus moves to
161+ // another control.
162+ completionPopup.hide()
163+ }
164+
116165 func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
117166 guard completionPopup.isVisible else { return false }
118167
@@ -140,6 +189,13 @@ struct SQLEditorView: NSViewRepresentable {
140189 // MARK: - Completions
141190
142191 private func updateCompletions(for textView: NSTextView) {
192+ // Capture the text view that the popup is being presented for. The
193+ // popup's accept handler (e.g. a double-click in the borderless popup
194+ // window) doesn't necessarily route through the begin-editing /
195+ // selection-change delegate callbacks first, so relying on those
196+ // alone to record the target can drop an accepted completion.
197+ lastTextView = textView
198+
143199 let cursorPosition = textView.selectedRange().location
144200 let result = SQLCompletionProvider.completions(
145201 for: textView.string,
@@ -155,12 +211,22 @@ struct SQLEditorView: NSViewRepresentable {
155211
156212 completionPopup.update(items: result.items)
157213
158− if !completionPopup.isVisible, let window = textView.window {
214+ if let window = textView.window {
159215 let screenPoint = cursorScreenPoint(for: textView)
160− completionPopup.show(at: screenPoint, in: window)
216+ if completionPopup.isVisible {
217+ completionPopup.reposition(at: screenPoint)
218+ } else {
219+ completionPopup.show(at: screenPoint, in: window)
220+ }
161221 }
162222 }
163223
224+ /// Hides the completion popup when the editor is torn down so the
225+ /// borderless child window can't linger after the view disappears.
226+ func cleanup() {
227+ completionPopup.hide()
228+ }
229+
164230 private func insertCompletion(_ item: SQLCompletionItem) {
165231 // Find the text view — walk up from the popup's parent window
166232 guard let textView = findTextView() else { return }
@@ -168,7 +234,9 @@ struct SQLEditorView: NSViewRepresentable {
168234 let cursorPosition = textView.selectedRange().location
169235 let nsText = textView.string as NSString
170236
171− // Find the prefix range to replace
237+ // Find the full word range to replace. Scan backward for the start and
238+ // forward for the end so a mid-token caret (e.g. SEL|ECT) replaces the
239+ // entire word rather than leaving the trailing fragment ("SELECTECT").
172240 var wordStart = cursorPosition
173241 while wordStart > 0 {
174242 let ch = nsText.character(at: wordStart - 1)
@@ -179,7 +247,32 @@ struct SQLEditorView: NSViewRepresentable {
179247 }
180248 }
181249
182− let replaceRange = NSRange(location: wordStart, length: cursorPosition - wordStart)
250+ var wordEnd = cursorPosition
251+ while wordEnd < nsText.length {
252+ let ch = nsText.character(at: wordEnd)
253+ if SQLCompletionProvider.isWordCharacter(ch) {
254+ wordEnd += 1
255+ } else {
256+ break
257+ }
258+ }
259+
260+ // Table and column completions carry their own quoting (a column is
261+ // quoted only when it needs it); absorb any double-quote the user typed
262+ // directly around the word so the inserted identifier replaces it
263+ // instead of leaving a stray quote. Leading and trailing are handled
264+ // independently: a closing quote can exist without an opening one (e.g.
265+ // `FROM my"`), which would otherwise produce a dangling `"name""`.
266+ if item.kind == .table || item.kind == .column {
267+ if wordStart > 0, nsText.character(at: wordStart - 1) == 0x22 {
268+ wordStart -= 1
269+ }
270+ if wordEnd < nsText.length, nsText.character(at: wordEnd) == 0x22 {
271+ wordEnd += 1
272+ }
273+ }
274+
275+ let replaceRange = NSRange(location: wordStart, length: wordEnd - wordStart)
183276
184277 isInsertingCompletion = true
185278 defer { isInsertingCompletion = false }
ParseableViewer/Views/ServerInfoView.swift+71−17
@@ -3,9 +3,15 @@ import SwiftUI
33struct ServerInfoView: View {
44 @Environment(AppState.self) private var appState
55 @State private var about: ServerAbout?
6− @State private var isLoading = false
6+ // Start in the loading state: the `.task` always runs `loadInfo()` on appear, so
7+ // initializing to `false` would paint the `else` branch's red "Unhealthy" dot for
8+ // one frame before the check begins. Begin neutral ("Checking…") instead.
9+ @State private var isLoading = true
710 @State private var isHealthy = false
811 @State private var errorMessage: String?
12+ /// Bumped by every load so a superseded (cancelled) load can't clear the
13+ /// newer load's spinner or overwrite its results.
14+ @State private var loadGeneration = 0
915
1016 var body: some View {
1117 ScrollView {
@@ -16,7 +22,7 @@ struct ServerInfoView: View {
1622 .fontWeight(.semibold)
1723 Spacer()
1824 Button {
19− Task { await loadInfo() }
25+ Task { await loadInfo(forceRefresh: true) }
2026 } label: {
2127 Image(systemName: "arrow.clockwise")
2228 }
@@ -41,18 +47,31 @@ struct ServerInfoView: View {
4147 // Health status
4248 GroupBox("Health") {
4349 HStack {
44− Circle()
45− .fill(isHealthy ? .green : .red)
46− .frame(width: 12, height: 12)
47− .accessibilityLabel(isHealthy ? "Healthy" : "Unhealthy")
48− Text(isHealthy ? "Healthy" : "Unhealthy")
49− .fontWeight(.medium)
50+ // While the check is in flight, show a neutral state
51+ // rather than the default `isHealthy == false`, which
52+ // otherwise flashes a red "Unhealthy" dot on every
53+ // connection switch before the result resolves.
54+ if isLoading {
55+ Circle()
56+ .fill(.gray)
57+ .frame(width: 12, height: 12)
58+ .accessibilityLabel("Checking health")
59+ Text("Checking…")
60+ .fontWeight(.medium)
61+ } else {
62+ Circle()
63+ .fill(isHealthy ? .green : .red)
64+ .frame(width: 12, height: 12)
65+ .accessibilityLabel(isHealthy ? "Healthy" : "Unhealthy")
66+ Text(isHealthy ? "Healthy" : "Unhealthy")
67+ .fontWeight(.medium)
68+ }
5069 Spacer()
5170 }
5271 .padding(8)
5372 }
5473
55− if let about = about ?? appState.serverAbout {
74+ if let about {
5675 GroupBox("Server Details") {
5776 VStack(alignment: .leading, spacing: 8) {
5877 InfoRow(label: "Version", value: about.version ?? "N/A")
@@ -123,32 +142,67 @@ struct ServerInfoView: View {
123142 }
124143 .padding()
125144 }
126− .task {
145+ // Key on the active connection so switching (or reconnecting to a
146+ // different) server reloads instead of showing the previous server's info.
147+ .task(id: appState.activeConnection?.id) {
148+ // Drop the previous server's details immediately on switch so they
149+ // aren't shown while the newly-selected server's info loads. (Local
150+ // @State persists across the .task id change, so it must be cleared
151+ // explicitly.) The manual Refresh button keeps the current values.
152+ about = nil
153+ isHealthy = false
154+ errorMessage = nil
127155 await loadInfo()
128156 }
129157 }
130158
131− private func loadInfo() async {
132− guard let client = appState.client else { return }
159+ private func loadInfo(forceRefresh: Bool = false) async {
160+ // Clear isLoading on the no-client path: since isLoading now starts `true`
161+ // (to avoid a red "Unhealthy" flash before the first check), an early return
162+ // without resetting it would wedge the spinner permanently.
163+ guard let client = appState.client else { isLoading = false; return }
164+ // `getAbout()` is cached for 60 s; the Refresh button must bypass that.
165+ if forceRefresh {
166+ await client.invalidateCache()
167+ }
168+ let connID = appState.activeConnection?.id
169+ loadGeneration &+= 1
170+ let generation = loadGeneration
133171 isLoading = true
134172 errorMessage = nil
173+ // Seed from the app-wide cache so first load isn't blank, but never fall
174+ // back to it on refresh failure (that would show stale data under the error).
175+ if about == nil { about = appState.serverAbout }
135176
136177 async let healthCheck: Void = client.checkHealth()
137178 async let aboutResult = client.getAbout()
138179
180+ let healthy: Bool
139181 do {
140182 try await healthCheck
141− isHealthy = true
183+ healthy = true
142184 } catch {
143− isHealthy = false
185+ healthy = false
144186 }
187+ let aboutValue: ServerAbout?
188+ let aboutError: String?
145189 do {
146− about = try await aboutResult
190+ aboutValue = try await aboutResult
191+ aboutError = nil
147192 } catch {
148− about = nil
149− errorMessage = ParseableError.userFriendlyMessage(for: error)
193+ aboutValue = nil
194+ aboutError = ParseableError.userFriendlyMessage(for: error)
150195 }
151196
197+ // Drop results if the active connection changed while awaiting, so a slow
198+ // load for the previous server can't overwrite the current one's state.
199+ // Still clear isLoading: this task owns the spinner it set, and leaving it
200+ // true on the stale path wedges the ProgressView and disables Refresh.
201+ guard generation == loadGeneration else { return }
202+ guard connID == appState.activeConnection?.id else { isLoading = false; return }
203+ isHealthy = healthy
204+ about = aboutValue
205+ errorMessage = aboutError
152206 isLoading = false
153207 }
154208}
ParseableViewer/Views/SettingsView.swift+21−2
@@ -6,6 +6,13 @@ struct SettingsView: View {
66 @AppStorage("maxQueryResults") private var maxQueryResults = 1000
77 @AppStorage("liveTailPollInterval") private var liveTailPollInterval = 2.0
88 @AppStorage("liveTailMaxEntries") private var liveTailMaxEntries = 5000
9+ // The Settings scene is a separate window from ContentView. A .sheet presents
10+ // over the window hosting the modifier, and binding both windows to the shared
11+ // appState.showConnectionSheet would present two sheets at once. So the Settings
12+ // window drives its own connection sheet with local state, fully independent of
13+ // the main window's.
14+ @State private var showConnectionSheet = false
15+ @State private var sheetConnection: ServerConnection?
916 var body: some View {
1017 TabView {
1118 // General settings
@@ -76,11 +83,20 @@ struct SettingsView: View {
7683 .clipShape(RoundedRectangle(cornerRadius: 4))
7784 }
7885
86+ Button {
87+ sheetConnection = connection
88+ showConnectionSheet = true
89+ } label: {
90+ Image(systemName: "pencil")
91+ }
92+ .help("Edit connection")
93+
7994 Button(role: .destructive) {
8095 appState.removeConnection(connection)
8196 } label: {
8297 Image(systemName: "trash")
8398 }
99+ .help("Delete connection")
84100 }
85101 .padding(.vertical, 4)
86102 }
@@ -89,8 +105,8 @@ struct SettingsView: View {
89105 HStack {
90106 Spacer()
91107 Button("Add Connection...") {
92− appState.editingConnection = nil
93− appState.showConnectionSheet = true
108+ sheetConnection = nil
109+ showConnectionSheet = true
94110 }
95111 }
96112 .padding()
@@ -100,5 +116,8 @@ struct SettingsView: View {
100116 }
101117 }
102118 .frame(width: 500, height: 400)
119+ .sheet(isPresented: $showConnectionSheet) {
120+ ConnectionSheet(connection: sheetConnection)
121+ }
103122 }
104123}
ParseableViewer/Views/SidebarView.swift+46−9
@@ -6,11 +6,19 @@ struct SidebarView: View {
66 @State private var newStreamName = ""
77 @State private var showDeleteConfirm = false
88 @State private var streamToDelete: String?
9+ /// The connection `streamToDelete` was picked on. Stream names aren't unique
10+ /// across servers, and the delete runs against whatever client is current
11+ /// when the user confirms — so a server switch while the stats lookup was in
12+ /// flight could otherwise delete a same-named stream on the *new* server.
13+ @State private var streamToDeleteConnectionID: UUID?
14+ /// The client the stream was picked with. Editing the active connection's URL
15+ /// keeps its id but installs a new client for a possibly different server.
16+ @State private var streamToDeleteClient: ParseableClient?
917 @State private var deleteStreamDetail: String?
1018
1119 /// Validates a stream name, returning an error message or nil if valid.
1220 static func validateStreamName(_ name: String) -> String? {
13− if name.trimmingCharacters(in: .whitespaces).isEmpty {
21+ if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1422 return "Stream name cannot be empty."
1523 }
1624 if name.count > 255 {
@@ -58,11 +66,21 @@ struct SidebarView: View {
5866 }
5967 Divider()
6068 Button("Delete...", role: .destructive) {
61− streamToDelete = stream.name
69+ // Capture the target so a slower stats fetch
70+ // for a *previously* clicked stream can't write
71+ // its detail (or raise the confirm) against the
72+ // stream the user has since selected — which
73+ // would show the wrong stats on a destructive
74+ // confirmation.
75+ let target = stream.name
76+ let targetConnectionID = appState.activeConnection?.id
77+ streamToDelete = target
78+ streamToDeleteConnectionID = targetConnectionID
79+ streamToDeleteClient = appState.client
6280 deleteStreamDetail = nil
6381 Task {
6482 if let client = appState.client,
65− let stats = try? await client.getStreamStats(stream: stream.name) {
83+ let stats = try? await client.getStreamStats(stream: target) {
6684 var parts: [String] = []
6785 if let count = stats.ingestion?.lifetime_count {
6886 parts.append("\(count) total records ingested")
@@ -70,11 +88,15 @@ struct SidebarView: View {
7088 if let size = stats.storage?.lifetime_size ?? stats.storage?.size {
7189 parts.append("\(size) storage used")
7290 }
73− if !parts.isEmpty {
91+ if !parts.isEmpty, streamToDelete == target {
7492 deleteStreamDetail = parts.joined(separator: ", ")
7593 }
7694 }
77− showDeleteConfirm = true
95+ if streamToDelete == target,
96+ appState.activeConnection?.id == targetConnectionID,
97+ appState.client === streamToDeleteClient {
98+ showDeleteConfirm = true
99+ }
78100 }
79101 }
80102 }
@@ -155,10 +177,11 @@ struct SidebarView: View {
155177 .alert("Create Log Stream", isPresented: $showCreateStream) {
156178 TextField("Stream name", text: $newStreamName)
157179 Button("Create") {
158− let name = newStreamName.trimmingCharacters(in: .whitespaces)
159− guard !name.isEmpty else { return }
180+ let name = newStreamName.trimmingCharacters(in: .whitespacesAndNewlines)
181+ guard !name.isEmpty else { newStreamName = ""; return }
160182 if let error = Self.validateStreamName(name) {
161183 appState.showErrorMessage(error)
184+ newStreamName = ""
162185 return
163186 }
164187 Task {
@@ -177,6 +200,11 @@ struct SidebarView: View {
177200 .alert("Delete Stream", isPresented: $showDeleteConfirm) {
178201 Button("Delete", role: .destructive) {
179202 if let name = streamToDelete {
203+ guard appState.activeConnection?.id == streamToDeleteConnectionID,
204+ appState.client === streamToDeleteClient else {
205+ appState.showErrorMessage("The server changed since \"\(name)\" was selected, so it was not deleted.")
206+ return
207+ }
180208 Task {
181209 do {
182210 try await appState.deleteStream(name: name)
@@ -215,7 +243,12 @@ struct ConnectionStatusView: View {
215243 if newID == ConnectionStatusView.addConnectionID {
216244 appState.editingConnection = nil
217245 appState.showConnectionSheet = true
218− } else if let conn = appState.connections.first(where: { $0.id == newID }) {
246+ } else if newID != connection.id,
247+ let conn = appState.connections.first(where: { $0.id == newID }) {
248+ // Only reconnect when a *different* connection is
249+ // picked. Re-selecting the active one would tear
250+ // down and rebuild the client for no reason (a full
251+ // health-check + stream reload, with a visible flicker).
219252 Task { await appState.connect(to: conn) }
220253 }
221254 }
@@ -280,6 +313,10 @@ struct FilterRow: View {
280313
281314 var body: some View {
282315 Button {
316+ // Don't navigate to a stream that no longer exists: it would drive
317+ // detail views to query a deleted stream (surfacing 404s) and leave
318+ // the sidebar selection pointing at no row.
319+ guard streamExists else { return }
283320 appState.selectedStream = filter.streamName
284321 if let sql = filter.query.filterQuery {
285322 appState.pendingFilterSQL = sql
@@ -288,7 +325,7 @@ struct FilterRow: View {
288325 } label: {
289326 HStack {
290327 Image(systemName: "bookmark")
291− .foregroundStyle(streamExists ? .orange : .secondary)
328+ .foregroundStyle(streamExists ? Color.secondary : Color.orange)
292329 VStack(alignment: .leading) {
293330 Text(filter.filterName)
294331 .lineLimit(1)
ParseableViewer/Views/StreamDetailView.swift+56−17
@@ -8,6 +8,9 @@ struct StreamDetailView: View {
88 @State private var retention: [RetentionConfig] = []
99 @State private var isLoading = false
1010 @State private var errorMessage: String?
11+ /// Bumped by every load. A superseded load (its `.task(id:)` cancelled by a
12+ /// stream switch) still resumes, and must not clear the newer load's spinner.
13+ @State private var loadGeneration = 0
1114
1215 var body: some View {
1316 Group {
@@ -20,20 +23,12 @@ struct StreamDetailView: View {
2023 Text(stream)
2124 .font(.title2)
2225 .fontWeight(.semibold)
23−
24− if let info {
25− if let created = info.createdAt {
26− Text("Created: \(created)")
27− .font(.caption)
28− .foregroundStyle(.secondary)
29− }
30− }
3126 }
3227
3328 Spacer()
3429
3530 Button {
36− Task { await loadData(stream: stream) }
31+ Task { await loadData(stream: stream, forceRefresh: true) }
3732 } label: {
3833 Image(systemName: "arrow.clockwise")
3934 }
@@ -52,7 +47,7 @@ struct StreamDetailView: View {
5247 Text(error)
5348 Spacer()
5449 Button("Retry") {
55− Task { await loadData(stream: stream) }
50+ Task { await loadData(stream: stream, forceRefresh: true) }
5651 }
5752 .buttonStyle(.bordered)
5853 .controlSize(.small)
@@ -165,7 +160,11 @@ struct StreamDetailView: View {
165160 }
166161 .padding()
167162 }
168− .task(id: stream) {
163+ // Key on the connection too: switching to a different server that
164+ // exposes a same-named stream leaves `stream` unchanged, so without
165+ // the connection id the task wouldn't refire and the old server's
166+ // data would linger.
167+ .task(id: "\(appState.activeConnection?.id.uuidString ?? "")|\(stream)") {
169168 await loadData(stream: stream)
170169 }
171170 } else {
@@ -178,8 +177,22 @@ struct StreamDetailView: View {
178177 }
179178 }
180179
181− private func loadData(stream: String) async {
180+ private func loadData(stream: String, forceRefresh: Bool = false) async {
182181 guard let client = appState.client else { return }
182+ // The client caches schema/stats/info for 60 s. That's right for the
183+ // automatic load on appear, but an explicit Refresh/Retry must hit the
184+ // server — otherwise it repaints the same cached numbers and looks like a
185+ // refresh that found nothing new.
186+ if forceRefresh {
187+ await client.invalidateCache()
188+ }
189+ // Capture the connection this fetch belongs to. Two servers can expose a
190+ // same-named stream, so guarding on the stream name alone would let a
191+ // slow fetch write the previous server's data under the new server's
192+ // stream after a server switch.
193+ let connID = appState.activeConnection?.id
194+ loadGeneration &+= 1
195+ let generation = loadGeneration
183196 isLoading = true
184197 errorMessage = nil
185198 // Clear previous stream's data so it isn't shown under the new header
@@ -196,17 +209,43 @@ struct StreamDetailView: View {
196209
197210 var failures: [String] = []
198211 var sawNotFound = false
212+ var newSchema: StreamSchema?
213+ var newStats: StreamStats?
214+ var newInfo: StreamInfo?
215+ var newRetention: [RetentionConfig] = []
199216
200217 func checkNotFound(_ error: Error) {
201218 if case .serverError(let code, _) = error as? ParseableError, code == 404 { sawNotFound = true }
202219 }
203220
204− do { schema = try await schemaFetch } catch { schema = nil; failures.append("schema"); checkNotFound(error) }
205− do { stats = try await statsFetch } catch { stats = nil; failures.append("stats"); checkNotFound(error) }
206− do { info = try await infoFetch } catch { info = nil; failures.append("info"); checkNotFound(error) }
207− do { retention = try await retentionFetch } catch { retention = []; failures.append("retention"); checkNotFound(error) }
221+ do { newSchema = try await schemaFetch } catch { failures.append("schema"); checkNotFound(error) }
222+ do { newStats = try await statsFetch } catch { failures.append("stats"); checkNotFound(error) }
223+ do { newInfo = try await infoFetch } catch { failures.append("info"); checkNotFound(error) }
224+ do { newRetention = try await retentionFetch } catch { failures.append("retention"); checkNotFound(error) }
225+
226+ // The manual Refresh/Retry buttons spawn detached Tasks that aren't tied to
227+ // `.task(id: stream)` cancellation, so a slow refresh for the old stream can
228+ // resolve after the user switched. Drop stale results instead of writing
229+ // them under the new stream's header. Also check the connection so a
230+ // same-named stream on a different server doesn't accept the old server's
231+ // data. Reset `isLoading` on the stale path or the spinner wedges forever —
232+ // unless a newer load has started, which owns the spinner now.
233+ guard generation == loadGeneration else { return }
234+ guard stream == appState.selectedStream, connID == appState.activeConnection?.id else {
235+ isLoading = false
236+ return
237+ }
238+
239+ schema = newSchema
240+ stats = newStats
241+ info = newInfo
242+ retention = newRetention
208243
209− if sawNotFound && failures.count == 4 {
244+ // A deleted stream makes these endpoints 404. Requiring *all four* to
245+ // fail was too strict (e.g. retention can succeed with an empty result),
246+ // so a deleted stream often fell through to the generic message. Treat
247+ // a 404 alongside multiple failures as "stream gone".
248+ if sawNotFound && failures.count >= 2 {
210249 errorMessage = "Stream \"\(stream)\" was not found. It may have been deleted."
211250 } else if !failures.isEmpty {
212251 errorMessage = "Failed to load: \(failures.joined(separator: ", "))"
ParseableViewer/Views/SyntaxHighlighting.swift+85−71
@@ -44,6 +44,37 @@ enum SQLSyntaxHighlighter {
4444 "UPPER",
4545 ]
4646
47+ // Pre-sorted arrays for completions
48+ static let sortedKeywords: [String] = keywords.sorted()
49+ static let sortedFunctions: [String] = functions.sorted()
50+
51+ // Pre-compiled regexes (created once, reused every keystroke)
52+ //
53+ // String literals, quoted identifiers, and comments in ONE alternation, so a
54+ // single left-to-right scan claims each span for whichever construct starts
55+ // first — exactly how a SQL lexer reads it. Separate passes can't agree: an
56+ // apostrophe inside a comment (`-- don't`) opened a bogus string that painted
57+ // every following line red, and a `"` inside a string (or any quote inside a
58+ // block comment) did the same. Capture groups: 1 = 'string', 2 = "identifier",
59+ // 3 = `--` line comment or `/* */` block comment (unterminated runs to the end).
60+ private static let literalOrCommentRegex = try! NSRegularExpression(
61+ pattern: "('[^']*(?:''[^']*)*')|(\"[^\"]*(?:\"\"[^\"]*)*\")|(--[^\\n]*|/\\*[\\s\\S]*?(?:\\*/|\\z))",
62+ options: []
63+ )
64+ // Matches the same numeric forms as `SQLTokenizer.consumeNumber`: integers,
65+ // decimals, leading-dot floats (`.5`), and exponents (`1e5`, `1.5e-3`). The
66+ // lookbehind keeps digits that belong to an identifier (`col1`, `t.2`) from
67+ // being highlighted as numbers.
68+ private static let numberRegex = try! NSRegularExpression(pattern: "(?<![\\w.])(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?", options: [])
69+ private static let keywordRegex: NSRegularExpression = {
70+ let pattern = "\\b(?:" + sortedKeywords.joined(separator: "|") + ")\\b"
71+ return try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
72+ }()
73+ private static let functionRegex: NSRegularExpression = {
74+ let pattern = "\\b(?:" + sortedFunctions.joined(separator: "|") + ")\\b"
75+ return try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
76+ }()
77+
4778 /// Applies SQL syntax highlighting to an NSTextStorage.
4879 static func highlight(_ text: String, in textStorage: NSTextStorage, baseFont: NSFont) {
4980 let fullRange = NSRange(location: 0, length: textStorage.length)
@@ -58,66 +89,52 @@ enum SQLSyntaxHighlighter {
5889 let nsText = text as NSString
5990 var protectedRanges: [NSRange] = []
6091
61− // 1. Comments (-- to end of line)
62− applyPattern("--[^\n]*", to: textStorage, text: nsText,
63− color: .secondaryLabelColor, protectedRanges: &protectedRanges)
64−
65− // 2. Single-quoted strings
66− applyPattern("'[^']*(?:''[^']*)*'", to: textStorage, text: nsText,
67− color: .systemRed, protectedRanges: &protectedRanges)
68−
69− // 3. Double-quoted identifiers
70− applyPattern("\"[^\"]*(?:\"\"[^\"]*)*\"", to: textStorage, text: nsText,
71− color: .systemRed, protectedRanges: &protectedRanges)
92+ // 1–3. Single-quoted strings, double-quoted identifiers, and comments, in
93+ // one pass so none of them can start inside another (`'a--b'` stays a
94+ // string, `-- don't` stays a comment).
95+ let literalMatches = literalOrCommentRegex.matches(
96+ in: text, range: NSRange(location: 0, length: nsText.length)
97+ )
98+ for match in literalMatches {
99+ let isComment = match.range(at: 3).location != NSNotFound
100+ textStorage.addAttribute(
101+ .foregroundColor,
102+ value: isComment ? NSColor.secondaryLabelColor : NSColor.systemRed,
103+ range: match.range
104+ )
105+ protectedRanges.append(match.range)
106+ }
72107
73108 // 4. Numbers (outside protected ranges)
74− applyUnprotectedPattern("\\b\\d+(?:\\.\\d+)?\\b", to: textStorage, text: nsText,
75− color: .systemPurple, protectedRanges: protectedRanges)
109+ applyUnprotectedRegex(numberRegex, to: textStorage, text: nsText,
110+ color: .systemPurple, protectedRanges: protectedRanges)
76111
77112 // 5. Keywords (outside protected ranges)
78− let keywordPattern = "\\b(?:" + keywords.sorted().joined(separator: "|") + ")\\b"
79− applyUnprotectedKeywordPattern(keywordPattern, to: textStorage, text: nsText,
80− color: .systemBlue, bold: true, baseFont: baseFont,
81− protectedRanges: protectedRanges)
113+ applyUnprotectedKeywordRegex(keywordRegex, to: textStorage, text: nsText,
114+ color: .systemBlue, bold: true, baseFont: baseFont,
115+ protectedRanges: protectedRanges)
82116
83117 // 6. Functions (outside protected ranges)
84− let functionPattern = "\\b(?:" + functions.sorted().joined(separator: "|") + ")\\b"
85− applyUnprotectedKeywordPattern(functionPattern, to: textStorage, text: nsText,
86− color: .systemTeal, bold: false, baseFont: baseFont,
87− protectedRanges: protectedRanges)
118+ applyUnprotectedKeywordRegex(functionRegex, to: textStorage, text: nsText,
119+ color: .systemTeal, bold: false, baseFont: baseFont,
120+ protectedRanges: protectedRanges)
88121 }
89122
90− private static func applyPattern(
91− _ pattern: String,
92− to textStorage: NSTextStorage,
93− text: NSString,
94− color: NSColor,
95− protectedRanges: inout [NSRange]
96− ) {
97− guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return }
98− let matches = regex.matches(in: text as String, range: NSRange(location: 0, length: text.length))
99− for match in matches {
100− textStorage.addAttribute(.foregroundColor, value: color, range: match.range)
101− protectedRanges.append(match.range)
102− }
103− }
104−
105− private static func applyUnprotectedPattern(
106− _ pattern: String,
123+ private static func applyUnprotectedRegex(
124+ _ regex: NSRegularExpression,
107125 to textStorage: NSTextStorage,
108126 text: NSString,
109127 color: NSColor,
110128 protectedRanges: [NSRange]
111129 ) {
112− guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return }
113130 let matches = regex.matches(in: text as String, range: NSRange(location: 0, length: text.length))
114131 for match in matches where !isProtected(match.range, by: protectedRanges) {
115132 textStorage.addAttribute(.foregroundColor, value: color, range: match.range)
116133 }
117134 }
118135
119− private static func applyUnprotectedKeywordPattern(
120− _ pattern: String,
136+ private static func applyUnprotectedKeywordRegex(
137+ _ regex: NSRegularExpression,
121138 to textStorage: NSTextStorage,
122139 text: NSString,
123140 color: NSColor,
@@ -125,7 +142,6 @@ enum SQLSyntaxHighlighter {
125142 baseFont: NSFont,
126143 protectedRanges: [NSRange]
127144 ) {
128− guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return }
129145 let boldFont = NSFont.monospacedSystemFont(ofSize: baseFont.pointSize, weight: .bold)
130146 let matches = regex.matches(in: text as String, range: NSRange(location: 0, length: text.length))
131147 for match in matches where !isProtected(match.range, by: protectedRanges) {
@@ -151,6 +167,12 @@ enum SQLSyntaxHighlighter {
151167
152168enum JSONSyntaxHighlighter {
153169
170+ // Pre-compiled regexes (created once, reused every call)
171+ private static let stringRegex = try! NSRegularExpression(pattern: "\"(?:[^\"\\\\]|\\\\.)*\"", options: [])
172+ private static let boolRegex = try! NSRegularExpression(pattern: "\\b(true|false)\\b", options: [])
173+ private static let nullRegex = try! NSRegularExpression(pattern: "\\bnull\\b", options: [])
174+ private static let numberRegex = try! NSRegularExpression(pattern: "-?\\b\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?\\b", options: [])
175+
154176 /// Creates a syntax-highlighted AttributedString from a JSON string.
155177 static func highlight(_ json: String, font: NSFont? = nil) -> AttributedString {
156178 let resolvedFont = font ?? NSFont.monospacedSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .regular)
@@ -168,45 +190,37 @@ enum JSONSyntaxHighlighter {
168190 var stringRanges: [NSRange] = []
169191
170192 // 1. Double-quoted strings — distinguish keys from values
171− if let regex = try? NSRegularExpression(pattern: "\"(?:[^\"\\\\]|\\\\.)*\"", options: []) {
172− let matches = regex.matches(in: json, range: fullRange)
173− for match in matches {
174− stringRanges.append(match.range)
175−
176− let isKey = isJSONKey(after: match.range, in: nsString)
177− let color: NSColor = isKey ? .systemCyan : .systemRed
178− attributed.addAttribute(.foregroundColor, value: color, range: match.range)
179− if isKey {
180− attributed.addAttribute(
181− .font,
182− value: NSFont.monospacedSystemFont(ofSize: resolvedFont.pointSize, weight: .medium),
183− range: match.range)
184− }
193+ let matches = stringRegex.matches(in: json, range: fullRange)
194+ for match in matches {
195+ stringRanges.append(match.range)
196+
197+ let isKey = isJSONKey(after: match.range, in: nsString)
198+ let color: NSColor = isKey ? .systemCyan : .systemRed
199+ attributed.addAttribute(.foregroundColor, value: color, range: match.range)
200+ if isKey {
201+ attributed.addAttribute(
202+ .font,
203+ value: NSFont.monospacedSystemFont(ofSize: resolvedFont.pointSize, weight: .medium),
204+ range: match.range)
185205 }
186206 }
187207
188208 // 2. Booleans (outside strings)
189− if let regex = try? NSRegularExpression(pattern: "\\b(true|false)\\b", options: []) {
190− for match in regex.matches(in: json, range: fullRange)
191− where !isInString(match.range, stringRanges: stringRanges) {
192− attributed.addAttribute(.foregroundColor, value: NSColor.systemOrange, range: match.range)
193− }
209+ for match in boolRegex.matches(in: json, range: fullRange)
210+ where !isInString(match.range, stringRanges: stringRanges) {
211+ attributed.addAttribute(.foregroundColor, value: NSColor.systemOrange, range: match.range)
194212 }
195213
196214 // 3. Null (outside strings)
197− if let regex = try? NSRegularExpression(pattern: "\\bnull\\b", options: []) {
198− for match in regex.matches(in: json, range: fullRange)
199− where !isInString(match.range, stringRanges: stringRanges) {
200− attributed.addAttribute(.foregroundColor, value: NSColor.secondaryLabelColor, range: match.range)
201− }
215+ for match in nullRegex.matches(in: json, range: fullRange)
216+ where !isInString(match.range, stringRanges: stringRanges) {
217+ attributed.addAttribute(.foregroundColor, value: NSColor.secondaryLabelColor, range: match.range)
202218 }
203219
204220 // 4. Numbers (outside strings)
205− if let regex = try? NSRegularExpression(pattern: "-?\\b\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?\\b", options: []) {
206− for match in regex.matches(in: json, range: fullRange)
207− where !isInString(match.range, stringRanges: stringRanges) {
208− attributed.addAttribute(.foregroundColor, value: NSColor.systemPurple, range: match.range)
209− }
221+ for match in numberRegex.matches(in: json, range: fullRange)
222+ where !isInString(match.range, stringRanges: stringRanges) {
223+ attributed.addAttribute(.foregroundColor, value: NSColor.systemPurple, range: match.range)
210224 }
211225
212226 return AttributedString(attributed)
ParseableViewer/Views/TimeRangePicker.swift+25−3
@@ -31,6 +31,27 @@ struct TimeRangePicker: View {
3131 .font(.caption)
3232 }
3333 }
34+ .onChange(of: showCustomPicker) { _, isShown in
35+ // Dismissing the popover by clicking outside bypasses the "Done"
36+ // button's `customEnd > customStart` validation, which could leave an
37+ // inverted or zero-width range selected (the menu already set
38+ // `option == .custom`). Sanitize on close so a backwards range can
39+ // never reach a query.
40+ guard !isShown else { return }
41+ if customEnd <= customStart {
42+ customEnd = customStart.addingTimeInterval(3600)
43+ }
44+ // Commit on *every* close path, not just the "Done" button. Closing
45+ // the popover by clicking outside is the common dismissal gesture;
46+ // without this the picker reads "Custom" while results still reflect
47+ // the previously selected preset, since QueryView only re-queries on
48+ // `timeRangeOption` changes (which it skips for `.custom`) — never on
49+ // the custom dates. Done sets `showCustomPicker = false` and lets this
50+ // handler do the single commit, so there's no double-query.
51+ if option == .custom {
52+ onCommit?()
53+ }
54+ }
3455 .popover(isPresented: $showCustomPicker) {
3556 VStack(spacing: 12) {
3657 Text("Custom Time Range")
@@ -41,7 +62,7 @@ struct TimeRangePicker: View {
4162 DatePicker("End:", selection: $customEnd)
4263 .datePickerStyle(.field)
4364
44− if customEnd < customStart {
65+ if customEnd <= customStart {
4566 HStack(spacing: 4) {
4667 Image(systemName: "exclamationmark.triangle.fill")
4768 Text("End date must be after start date")
@@ -78,11 +99,12 @@ struct TimeRangePicker: View {
7899 Spacer()
79100
80101 Button("Done") {
102+ // Just close — the `showCustomPicker` change handler is the
103+ // single commit point for all close paths (Done + click-out).
81104 showCustomPicker = false
82− onCommit?()
83105 }
84106 .buttonStyle(.borderedProminent)
85− .disabled(customEnd < customStart)
107+ .disabled(customEnd <= customStart)
86108 }
87109 }
88110 .padding()
ParseableViewer/Views/UsersView.swift+26−3
@@ -5,6 +5,9 @@ struct UsersView: View {
55 @State private var users: [UserInfo] = []
66 @State private var isLoading = false
77 @State private var errorMessage: String?
8+ /// Bumped by every load so a superseded (cancelled) load can't clear the
9+ /// newer load's spinner.
10+ @State private var loadGeneration = 0
811
912 var body: some View {
1013 VStack(spacing: 0) {
@@ -72,22 +75,42 @@ struct UsersView: View {
7275 }
7376 }
7477 }
75− .task {
78+ // Key on the active connection so switching (or reconnecting to a
79+ // different) server reloads instead of showing the previous server's users.
80+ .task(id: appState.activeConnection?.id) {
7681 await loadUsers()
7782 }
7883 }
7984
8085 private func loadUsers() async {
8186 guard let client = appState.client else { return }
87+ let connID = appState.activeConnection?.id
88+ loadGeneration &+= 1
89+ let generation = loadGeneration
8290 isLoading = true
8391 errorMessage = nil
92+ // Clear the previous server's list up front so it can't briefly show through
93+ // after a switch (e.g. on the stale-guard early-return below). Matches the
94+ // sibling views (AlertsView clears alertConfig, ServerInfoView clears about).
95+ users = []
8496
97+ let loaded: [UserInfo]?
98+ let loadError: String?
8599 do {
86− users = try await client.listUsers()
100+ loaded = try await client.listUsers()
101+ loadError = nil
87102 } catch {
88− errorMessage = ParseableError.userFriendlyMessage(for: error)
103+ loaded = nil
104+ loadError = ParseableError.userFriendlyMessage(for: error)
89105 }
90106
107+ // Drop results if the active connection changed while awaiting. Still clear
108+ // isLoading: this task set the spinner, so leaving it true on the stale path
109+ // wedges the ProgressView and disables Refresh.
110+ guard generation == loadGeneration else { return }
111+ guard connID == appState.activeConnection?.id else { isLoading = false; return }
112+ if let loaded { users = loaded }
113+ errorMessage = loadError
91114 isLoading = false
92115 }
93116}
ParseableViewerTests/ConnectionStoreTests.swift+71−33
@@ -2,25 +2,25 @@ import XCTest
22@testable import ParseableViewer
33
44final class ConnectionStoreTests: XCTestCase {
5− private let testSuiteKey = "parseable_connections_test"
5+ /// Whether the data-protection keychain is available in this environment.
6+ /// CI runners may lack the entitlements needed for `kSecUseDataProtectionKeychain`.
7+ private static let keychainAvailable: Bool = {
8+ let probe = "keychain-probe"
9+ let saved = KeychainService.saveData(Data(probe.utf8), for: "_test_probe")
10+ if saved {
11+ KeychainService.deleteData(for: "_test_probe")
12+ }
13+ return saved
14+ }()
615
716 override func tearDown() {
817 super.tearDown()
9− // Clean up any test data from UserDefaults
10− UserDefaults.standard.removeObject(forKey: "parseable_connections")
11− UserDefaults.standard.removeObject(forKey: "parseable_active_connection_id")
12− }
13−
14− // MARK: - Active connection ID
15−
16− func testSaveAndLoadActiveConnectionID() {
17− let id = UUID()
18− ConnectionStore.saveActiveConnectionID(id)
19− let loaded = ConnectionStore.loadActiveConnectionID()
20− XCTAssertEqual(loaded, id)
18+ KeychainService.deleteData(for: "parseable_connections_list")
19+ KeychainService.deleteData(for: "parseable_active_connection_id")
2120 }
2221
23− func testSaveNilActiveConnectionID() {
22+ func testSaveNilActiveConnectionID() throws {
23+ try XCTSkipUnless(Self.keychainAvailable, "Data-protection keychain unavailable")
2424 let id = UUID()
2525 ConnectionStore.saveActiveConnectionID(id)
2626 ConnectionStore.saveActiveConnectionID(nil)
@@ -29,7 +29,7 @@ final class ConnectionStoreTests: XCTestCase {
2929 }
3030
3131 func testLoadActiveConnectionIDWhenEmpty() {
32− UserDefaults.standard.removeObject(forKey: "parseable_active_connection_id")
32+ KeychainService.deleteData(for: "parseable_active_connection_id")
3333 let loaded = ConnectionStore.loadActiveConnectionID()
3434 XCTAssertNil(loaded)
3535 }
@@ -37,35 +37,74 @@ final class ConnectionStoreTests: XCTestCase {
3737 // MARK: - Connection persistence
3838
3939 func testLoadConnectionsWhenEmpty() {
40− UserDefaults.standard.removeObject(forKey: "parseable_connections")
40+ KeychainService.deleteData(for: "parseable_connections_list")
4141 let connections = ConnectionStore.loadConnections()
4242 XCTAssertTrue(connections.isEmpty)
4343 }
4444
45− func testSaveAndLoadConnections() {
46− let connection = ServerConnection(
47− name: "Test Server",
45+ func testSaveAndLoadActiveConnectionID() throws {
46+ try XCTSkipUnless(Self.keychainAvailable, "Data-protection keychain unavailable")
47+ let id = UUID()
48+ ConnectionStore.saveActiveConnectionID(id)
49+ let loaded = ConnectionStore.loadActiveConnectionID()
50+ XCTAssertEqual(loaded, id)
51+ }
52+
53+ func testRoundTripConnectionPersistence() throws {
54+ try XCTSkipUnless(Self.keychainAvailable, "Data-protection keychain unavailable")
55+ let conn = ServerConnection(
56+ name: "Prod",
4857 url: "https://logs.example.com",
4958 username: "admin",
50− password: "secret123"
59+ password: "s3cret!"
5160 )
52− ConnectionStore.saveConnections([connection])
61+ ConnectionStore.saveConnections([conn])
62+
5363 let loaded = ConnectionStore.loadConnections()
5464 XCTAssertEqual(loaded.count, 1)
55− XCTAssertEqual(loaded[0].name, "Test Server")
56− XCTAssertEqual(loaded[0].url, "https://logs.example.com")
57− XCTAssertEqual(loaded[0].username, "admin")
65+ XCTAssertEqual(loaded.first?.id, conn.id)
66+ XCTAssertEqual(loaded.first?.name, "Prod")
67+ XCTAssertEqual(loaded.first?.url, "https://logs.example.com")
68+ XCTAssertEqual(loaded.first?.username, "admin")
69+ XCTAssertEqual(loaded.first?.password, "s3cret!")
70+
71+ // Clean up
72+ KeychainService.deletePassword(for: conn.id)
5873 }
5974
60− func testSaveMultipleConnections() {
61− let c1 = ServerConnection(name: "Prod", url: "https://prod.example.com", username: "admin", password: "p1")
62− let c2 = ServerConnection(name: "Dev", url: "https://dev.example.com", username: "dev", password: "p2")
63− ConnectionStore.saveConnections([c1, c2])
75+ func testRoundTripMultipleConnections() throws {
76+ try XCTSkipUnless(Self.keychainAvailable, "Data-protection keychain unavailable")
77+ let conn1 = ServerConnection(
78+ name: "Server A",
79+ url: "https://a.example.com",
80+ username: "user1",
81+ password: "pass1"
82+ )
83+ let conn2 = ServerConnection(
84+ name: "Server B",
85+ url: "https://b.example.com",
86+ username: "user2",
87+ password: "pass2"
88+ )
89+ ConnectionStore.saveConnections([conn1, conn2])
90+
6491 let loaded = ConnectionStore.loadConnections()
6592 XCTAssertEqual(loaded.count, 2)
93+
94+ let loadedA = loaded.first { $0.id == conn1.id }
95+ let loadedB = loaded.first { $0.id == conn2.id }
96+ XCTAssertEqual(loadedA?.name, "Server A")
97+ XCTAssertEqual(loadedA?.password, "pass1")
98+ XCTAssertEqual(loadedB?.name, "Server B")
99+ XCTAssertEqual(loadedB?.password, "pass2")
100+
101+ // Clean up
102+ KeychainService.deletePassword(for: conn1.id)
103+ KeychainService.deletePassword(for: conn2.id)
66104 }
67105
68− func testPasswordNotInUserDefaults() {
106+ func testPasswordNotInKeychainConnectionData() throws {
107+ try XCTSkipUnless(Self.keychainAvailable, "Data-protection keychain unavailable")
69108 let connection = ServerConnection(
70109 name: "Test",
71110 url: "https://example.com",
@@ -74,12 +113,11 @@ final class ConnectionStoreTests: XCTestCase {
74113 )
75114 ConnectionStore.saveConnections([connection])
76115
77− // Verify password is NOT in the UserDefaults data
78− if let data = UserDefaults.standard.data(forKey: "parseable_connections"),
116+ // Verify password is NOT in the connections list data
117+ if let data = KeychainService.loadData(for: "parseable_connections_list"),
79118 let jsonString = String(data: data, encoding: .utf8) {
80119 XCTAssertFalse(jsonString.contains("supersecret"),
81− "Password should not be stored in UserDefaults JSON")
120+ "Password should not be stored in connection list JSON")
82121 }
83122 }
84−
85123}
ParseableViewerTests/JSONValueTests.swift+18
@@ -75,6 +75,24 @@ final class JSONValueTests: XCTestCase {
7575 XCTAssertEqual(original, decoded)
7676 }
7777
78+ func testEncodeNonFiniteDoubleAsNull() throws {
79+ // A non-finite double must encode as JSON null rather than throwing — a
80+ // single infinity/NaN otherwise aborts the whole JSONEncoder pass and
81+ // collapses exportAsJSON() to "[]" (total silent data loss).
82+ let encoder = JSONEncoder()
83+ for value: Double in [.infinity, -.infinity, .nan] {
84+ let data = try encoder.encode(JSONValue.double(value))
85+ XCTAssertEqual(String(data: data, encoding: .utf8), "null")
86+ }
87+ }
88+
89+ func testEncodeArrayWithNonFiniteDoubleDoesNotThrow() throws {
90+ // Mirrors the export path: one non-finite value must not poison the rest.
91+ let original: JSONValue = .array([.int(1), .double(.infinity), .string("ok")])
92+ let data = try JSONEncoder().encode(original)
93+ XCTAssertEqual(String(data: data, encoding: .utf8), "[1,null,\"ok\"]")
94+ }
95+
7896 // MARK: - displayString
7997
8098 func testDisplayStringNull() {
ParseableViewerTests/LiveTailViewModelTests.swift+54−29
@@ -63,43 +63,38 @@ final class LiveTailViewModelTests: XCTestCase {
6363 // MARK: - Timestamp parsing
6464
6565 func testParseTimestampISO8601WithFractionalSeconds() {
66− let vm = LiveTailViewModel()
6766 let record: LogRecord = ["p_timestamp": .string("2024-06-15T10:30:45.123Z")]
68− let date = vm.parseTimestamp(from: record)
67+ let date = LiveTailViewModel.parseTimestamp(from: record)
6968 XCTAssertNotNil(date)
7069 }
7170
7271 func testParseTimestampISO8601Basic() {
73− let vm = LiveTailViewModel()
7472 let record: LogRecord = ["p_timestamp": .string("2024-06-15T10:30:45Z")]
75− let date = vm.parseTimestamp(from: record)
73+ let date = LiveTailViewModel.parseTimestamp(from: record)
7674 XCTAssertNotNil(date)
7775 }
7876
7977 func testParseTimestampFallbackFields() {
80− let vm = LiveTailViewModel()
81−
8278 // "timestamp" field
8379 let r1: LogRecord = ["timestamp": .string("2024-06-15T10:30:45Z")]
84− XCTAssertNotNil(vm.parseTimestamp(from: r1))
80+ XCTAssertNotNil(LiveTailViewModel.parseTimestamp(from: r1))
8581
8682 // "time" field
8783 let r2: LogRecord = ["time": .string("2024-06-15T10:30:45Z")]
88− XCTAssertNotNil(vm.parseTimestamp(from: r2))
84+ XCTAssertNotNil(LiveTailViewModel.parseTimestamp(from: r2))
8985
9086 // "@timestamp" field
9187 let r3: LogRecord = ["@timestamp": .string("2024-06-15T10:30:45Z")]
92− XCTAssertNotNil(vm.parseTimestamp(from: r3))
88+ XCTAssertNotNil(LiveTailViewModel.parseTimestamp(from: r3))
9389 }
9490
9591 func testParseTimestampPriorityOrder() {
96− let vm = LiveTailViewModel()
9792 // p_timestamp should take priority
9893 let record: LogRecord = [
9994 "p_timestamp": .string("2024-01-01T00:00:00Z"),
10095 "timestamp": .string("2024-12-31T23:59:59Z")
10196 ]
102− let date = vm.parseTimestamp(from: record)
97+ let date = LiveTailViewModel.parseTimestamp(from: record)
10398 XCTAssertNotNil(date)
10499
105100 let calendar = Calendar.current
@@ -109,64 +104,57 @@ final class LiveTailViewModelTests: XCTestCase {
109104 }
110105
111106 func testParseTimestampNoTimestampField() {
112− let vm = LiveTailViewModel()
113107 let record: LogRecord = ["message": .string("no timestamp")]
114− let date = vm.parseTimestamp(from: record)
108+ let date = LiveTailViewModel.parseTimestamp(from: record)
115109 XCTAssertNil(date)
116110 }
117111
118112 func testParseTimestampNonStringValue() {
119− let vm = LiveTailViewModel()
120113 let record: LogRecord = ["p_timestamp": .int(1718446245)]
121− let date = vm.parseTimestamp(from: record)
114+ let date = LiveTailViewModel.parseTimestamp(from: record)
122115 XCTAssertNil(date)
123116 }
124117
125118 func testParseTimestampInvalidString() {
126− let vm = LiveTailViewModel()
127119 let record: LogRecord = ["p_timestamp": .string("not-a-date")]
128− let date = vm.parseTimestamp(from: record)
120+ let date = LiveTailViewModel.parseTimestamp(from: record)
129121 XCTAssertNil(date)
130122 }
131123
132124 // MARK: - Summary building
133125
134126 func testBuildSummaryWithLevelAndMessage() {
135− let vm = LiveTailViewModel()
136127 let record: LogRecord = [
137128 "level": .string("info"),
138129 "message": .string("Server started")
139130 ]
140− let summary = vm.buildSummary(from: record)
131+ let summary = LiveTailViewModel.buildSummary(from: record)
141132 XCTAssertTrue(summary.contains("[info]"))
142133 XCTAssertTrue(summary.contains("Server started"))
143134 }
144135
145136 func testBuildSummaryAlternateFieldNames() {
146− let vm = LiveTailViewModel()
147137 let record: LogRecord = [
148138 "severity": .string("warn"),
149139 "msg": .string("Disk almost full")
150140 ]
151− let summary = vm.buildSummary(from: record)
141+ let summary = LiveTailViewModel.buildSummary(from: record)
152142 XCTAssertTrue(summary.contains("[warn]"))
153143 XCTAssertTrue(summary.contains("Disk almost full"))
154144 }
155145
156146 func testBuildSummaryFallbackToScalarFields() {
157− let vm = LiveTailViewModel()
158147 let record: LogRecord = [
159148 "status": .int(200),
160149 "path": .string("/api/health")
161150 ]
162− let summary = vm.buildSummary(from: record)
151+ let summary = LiveTailViewModel.buildSummary(from: record)
163152 XCTAssertFalse(summary.isEmpty)
164153 }
165154
166155 func testBuildSummaryEmptyRecord() {
167− let vm = LiveTailViewModel()
168156 let record: LogRecord = [:]
169− let summary = vm.buildSummary(from: record)
157+ let summary = LiveTailViewModel.buildSummary(from: record)
170158 XCTAssertEqual(summary, "")
171159 }
172160
@@ -216,7 +204,7 @@ final class LiveTailViewModelTests: XCTestCase {
216204 func testFilteredEntriesEmptyFilter() {
217205 let vm = LiveTailViewModel()
218206 vm.filterText = ""
219− XCTAssertEqual(vm.filteredEntries.count, vm.entries.count)
207+ XCTAssertEqual(vm.cachedFilteredEntries.count, vm.entries.count)
220208 }
221209
222210 func testStopResetsRunningState() {
@@ -269,12 +257,11 @@ final class LiveTailViewModelTests: XCTestCase {
269257 }
270258
271259 func testBuildSummaryWithLogField() {
272− let vm = LiveTailViewModel()
273260 let record: LogRecord = [
274261 "log_level": .string("debug"),
275262 "log": .string("Processing request")
276263 ]
277− let summary = vm.buildSummary(from: record)
264+ let summary = LiveTailViewModel.buildSummary(from: record)
278265 XCTAssertTrue(summary.contains("[debug]"))
279266 XCTAssertTrue(summary.contains("Processing request"))
280267 }
@@ -417,10 +404,23 @@ final class LiveTailViewModelTests: XCTestCase {
417404 XCTAssertEqual(vm.columnFilters.count, 1)
418405 }
419406
420− func testAddFilterDifferentValueIsAdditive() {
407+ func testAddFilterSameColumnIncludeReplaces() {
421408 let vm = LiveTailViewModel()
422409 vm.addColumnFilter(column: "level", value: .string("error"), exclude: false)
410+ // A second include on the same column replaces the first: includes are
411+ // AND-combined and a column can only equal one value, so stacking two
412+ // includes would match zero rows and silently empty the tail.
423413 vm.addColumnFilter(column: "level", value: .string("warn"), exclude: false)
414+ XCTAssertEqual(vm.columnFilters.count, 1)
415+ XCTAssertEqual(vm.columnFilters[0].value, .string("warn"))
416+ }
417+
418+ func testAddFilterSameColumnExcludesStack() {
419+ let vm = LiveTailViewModel()
420+ vm.addColumnFilter(column: "level", value: .string("debug"), exclude: true)
421+ // Excludes on the same column legitimately stack: level ≠ debug AND
422+ // level ≠ trace is meaningful, so both filters are retained.
423+ vm.addColumnFilter(column: "level", value: .string("trace"), exclude: true)
424424 XCTAssertEqual(vm.columnFilters.count, 2)
425425 }
426426
@@ -461,4 +461,29 @@ final class LiveTailViewModelTests: XCTestCase {
461461 let filter = LiveTailViewModel.ColumnFilter(column: "field", value: nil, exclude: false)
462462 XCTAssertEqual(filter.displayLabel, "field = null")
463463 }
464+
465+ // MARK: - Zone-less timestamps / saved column order
466+
467+ func testParseTimestampTreatsZonelessAsUTC() {
468+ // Parseable serializes p_timestamp without a zone designator.
469+ let naive = LiveTailViewModel.parseTimestamp(from: ["p_timestamp": .string("2024-06-15T10:30:45.123")])
470+ let zoned = LiveTailViewModel.parseTimestamp(from: ["p_timestamp": .string("2024-06-15T10:30:45.123Z")])
471+ XCTAssertNotNil(naive)
472+ XCTAssertEqual(naive, zoned)
473+ let naiveWhole = LiveTailViewModel.parseTimestamp(from: ["p_timestamp": .string("2024-06-15T10:30:45")])
474+ XCTAssertEqual(naiveWhole, LiveTailViewModel.parseTimestamp(from: ["p_timestamp": .string("2024-06-15T10:30:45Z")]))
475+ }
476+
477+ func testMergedColumnOrderRestoresSavedPosition() {
478+ let merged = QueryViewModel.mergedColumnOrder(
479+ ["p_timestamp", "level", "message"],
480+ inserting: ["trace_id"],
481+ reference: ["p_timestamp", "trace_id", "level", "message"]
482+ )
483+ XCTAssertEqual(merged, ["p_timestamp", "trace_id", "level", "message"])
484+ }
485+
486+ func testMergedColumnOrderAppendsColumnsWithoutSavedPosition() {
487+ XCTAssertEqual(QueryViewModel.mergedColumnOrder(["a"], inserting: ["b"], reference: []), ["a", "b"])
488+ }
464489}
ParseableViewerTests/LogTableHelperTests.swift+14−7
@@ -161,37 +161,44 @@ final class LogTableHelperTests: XCTestCase {
161161
162162 func testExtractSeverityFromLevelColumn() {
163163 let record: LogRecord = ["level": .string("error"), "message": .string("boom")]
164− XCTAssertEqual(extractSeverity(from: record), .error)
164+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
165+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .error)
165166 }
166167
167168 func testExtractSeverityFromSeverityColumn() {
168169 let record: LogRecord = ["severity": .string("warning"), "msg": .string("watch out")]
169− XCTAssertEqual(extractSeverity(from: record), .warning)
170+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
171+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .warning)
170172 }
171173
172174 func testExtractSeverityFromSeverityTextColumn() {
173175 let record: LogRecord = ["severity_text": .string("FATAL")]
174− XCTAssertEqual(extractSeverity(from: record), .fatal)
176+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
177+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .fatal)
175178 }
176179
177180 func testExtractSeverityFromLogLevelColumn() {
178181 let record: LogRecord = ["log_level": .string("info")]
179− XCTAssertEqual(extractSeverity(from: record), .info)
182+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
183+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .info)
180184 }
181185
182186 func testExtractSeverityFromNumericValue() {
183187 let record: LogRecord = ["priority": .int(3)]
184− XCTAssertEqual(extractSeverity(from: record), .error)
188+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
189+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .error)
185190 }
186191
187192 func testExtractSeverityNoSeverityColumn() {
188193 let record: LogRecord = ["message": .string("hello"), "timestamp": .string("now")]
189− XCTAssertEqual(extractSeverity(from: record), .unknown)
194+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
195+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .unknown)
190196 }
191197
192198 func testExtractSeverityUnrecognizedValue() {
193199 let record: LogRecord = ["level": .string("custom_level")]
194− XCTAssertEqual(extractSeverity(from: record), .unknown)
200+ let sevCols = buildSeverityColumnSet(columns: Array(record.keys))
201+ XCTAssertEqual(extractSeverity(from: record, severityColumns: sevCols), .unknown)
195202 }
196203
197204 // MARK: - severityRowTint
ParseableViewerTests/ParseableClientTests.swift+58
@@ -646,4 +646,62 @@ final class ParseableClientTests: XCTestCase {
646646 // Carriage returns in values should be wrapped in quotes per RFC 4180
647647 XCTAssertTrue(csv.contains("\"line1\r\nline2\""))
648648 }
649+
650+ // MARK: - Server response key spellings
651+
652+ func testServerAboutDecodesCamelCaseKeys() throws {
653+ let json = #"{"uiVersion": "v1.2", "deploymentId": "01H", "grpcPort": 8001}"#.data(using: .utf8)!
654+ let about = try JSONDecoder().decode(ServerAbout.self, from: json)
655+ XCTAssertEqual(about.uiVersion, "v1.2")
656+ XCTAssertEqual(about.deploymentId, "01H")
657+ XCTAssertEqual(about.grpcPort, 8001)
658+ }
659+
660+ func testStreamInfoDecodesSnakeCaseKeys() throws {
661+ let json = #"{"created-at": "c", "first-event-at": "f", "time_partition": "ts", "static_schema_flag": "true", "cache_enabled": true}"#
662+ .data(using: .utf8)!
663+ let info = try JSONDecoder().decode(StreamInfo.self, from: json)
664+ XCTAssertEqual(info.createdAt, "c")
665+ XCTAssertEqual(info.firstEventAt, "f")
666+ XCTAssertEqual(info.timePartition, "ts")
667+ XCTAssertEqual(info.staticSchemaFlag, true)
668+ XCTAssertEqual(info.cacheEnabled, true)
669+ }
670+
671+ func testStreamInfoDecodesCamelCaseKeys() throws {
672+ let json = #"{"createdAt": "c", "firstEventAt": "f", "timePartition": "ts", "staticSchemaFlag": "true"}"#
673+ .data(using: .utf8)!
674+ let info = try JSONDecoder().decode(StreamInfo.self, from: json)
675+ XCTAssertEqual(info.createdAt, "c")
676+ XCTAssertEqual(info.firstEventAt, "f")
677+ XCTAssertEqual(info.timePartition, "ts")
678+ XCTAssertEqual(info.staticSchemaFlag, true)
679+ }
680+
681+ func testStorageStatsReadsFormatAndUnitSuffixedSizes() throws {
682+ let json = #"{"storage": {"size": "2048 Bytes", "format": "parquet"}}"#.data(using: .utf8)!
683+ let stats = try JSONDecoder().decode(StreamStats.self, from: json)
684+ XCTAssertEqual(stats.storage?.type, "parquet")
685+ XCTAssertEqual(stats.storage?.size, ByteCountFormatter.string(fromByteCount: 2048, countStyle: .file))
686+ }
687+
688+ func testSchemaFieldDescribesParameterizedArrowTypes() throws {
689+ let json = #"{"name": "p_timestamp", "data_type": {"Timestamp": ["Millisecond", null]}}"#.data(using: .utf8)!
690+ let field = try JSONDecoder().decode(SchemaField.self, from: json)
691+ XCTAssertEqual(field.dataType, "Timestamp(Millisecond, None)")
692+ }
693+
694+ func testLegacyAlertRuleWithObjectConfigKeepsRuleType() throws {
695+ let json = #"{"name": "a", "rule": {"type": "column", "config": {"column": "status", "operator": "=", "value": 500}}}"#
696+ .data(using: .utf8)!
697+ let rule = try JSONDecoder().decode(AlertRule.self, from: json)
698+ XCTAssertEqual(rule.rule?.type, "column")
699+ XCTAssertNotNil(rule.rule?.config)
700+ }
701+
702+ func testServerAboutDecodesObjectLicense() throws {
703+ let json = #"{"license": {"name": "AGPL-3.0-only", "plan": "OSS"}}"#.data(using: .utf8)!
704+ let about = try JSONDecoder().decode(ServerAbout.self, from: json)
705+ XCTAssertEqual(about.license, "AGPL-3.0-only (OSS)")
706+ }
649707}
ParseableViewerTests/QueryViewModelTests.swift+169−4
@@ -1,6 +1,8 @@
11import XCTest
22@testable import ParseableViewer
33
4+// QueryViewModel is @MainActor, so its tests must run on the main actor too.
5+@MainActor
46final class QueryViewModelTests: XCTestCase {
57 // MARK: - Column extraction
68
@@ -61,7 +63,7 @@ final class QueryViewModelTests: XCTestCase {
6163 XCTAssertEqual(vm.filteredResults.count, 2)
6264 }
6365
64− func testFilteredResultsMatchesContent() {
66+ func testFilteredResultsMatchesContent() async {
6567 let vm = QueryViewModel()
6668 vm.results = [
6769 ["message": .string("hello world")],
@@ -69,16 +71,18 @@ final class QueryViewModelTests: XCTestCase {
6971 ["message": .string("Hello there")]
7072 ]
7173 vm.filterText = "hello"
74+ try? await Task.sleep(for: .milliseconds(200))
7275 XCTAssertEqual(vm.filteredResults.count, 2) // case-insensitive
7376 }
7477
75− func testFilteredResultsNoMatch() {
78+ func testFilteredResultsNoMatch() async {
7679 let vm = QueryViewModel()
7780 vm.results = [
7881 ["message": .string("hello")],
7982 ["message": .string("world")]
8083 ]
8184 vm.filterText = "xyz"
85+ try? await Task.sleep(for: .milliseconds(200))
8286 XCTAssertEqual(vm.filteredResults.count, 0)
8387 }
8488
@@ -136,6 +140,19 @@ final class QueryViewModelTests: XCTestCase {
136140 XCTAssertTrue(json.contains("\"value\""))
137141 }
138142
143+ func testProjectRecordsExcludesHiddenColumns() {
144+ let records: [LogRecord] = [["visible": .string("v"), "hidden": .string("secret")]]
145+ let projected = QueryViewModel.projectRecords(records, to: ["visible"])
146+ XCTAssertEqual(projected.first?.keys.sorted(), ["visible"])
147+ XCTAssertNil(projected.first?["hidden"], "Hidden column must not leak into export")
148+ }
149+
150+ func testProjectRecordsEmptyColumnsKeepsAllFields() {
151+ let records: [LogRecord] = [["a": .int(1), "b": .int(2)]]
152+ let projected = QueryViewModel.projectRecords(records, to: [])
153+ XCTAssertEqual(projected.first?.keys.sorted(), ["a", "b"])
154+ }
155+
139156 // MARK: - Time range
140157
141158 func testTimeRangeOptionsAllHaveValues() {
@@ -218,7 +235,7 @@ final class QueryViewModelTests: XCTestCase {
218235 let vm = QueryViewModel()
219236 vm.sqlQuery = "SELECT * FROM \"logs\" ORDER BY p_timestamp DESC LIMIT 1000"
220237 vm.addColumnFilter(column: "level", value: .string("debug"), exclude: true)
221− XCTAssertTrue(vm.sqlQuery.contains("WHERE \"level\" <> 'debug'"))
238+ XCTAssertTrue(vm.sqlQuery.contains("WHERE \"level\" IS DISTINCT FROM 'debug'"))
222239 XCTAssertTrue(vm.sqlQuery.contains("ORDER BY"))
223240 }
224241
@@ -244,6 +261,15 @@ final class QueryViewModelTests: XCTestCase {
244261 XCTAssertTrue(vm.sqlQuery.contains("WHERE \"level\" = 'error'"))
245262 }
246263
264+ func testAddColumnFilterParenthesizesExistingOr() {
265+ // An existing top-level OR must be parenthesized before AND-ing the new
266+ // condition so precedence is preserved.
267+ let vm = QueryViewModel()
268+ vm.sqlQuery = "SELECT * FROM \"logs\" WHERE \"a\" = 1 OR \"b\" = 2"
269+ vm.addColumnFilter(column: "host", value: .string("web-1"), exclude: false)
270+ XCTAssertTrue(vm.sqlQuery.contains("(\"a\" = 1 OR \"b\" = 2) AND \"host\" = 'web-1'"))
271+ }
272+
247273 func testAddColumnFilterIntValue() {
248274 let vm = QueryViewModel()
249275 vm.sqlQuery = "SELECT * FROM \"logs\""
@@ -262,7 +288,7 @@ final class QueryViewModelTests: XCTestCase {
262288 let vm = QueryViewModel()
263289 vm.sqlQuery = "SELECT * FROM \"logs\""
264290 vm.addColumnFilter(column: "level", value: .string("warn"), exclude: true)
265− XCTAssertTrue(vm.sqlQuery.contains("WHERE \"level\" <> 'warn'"))
291+ XCTAssertTrue(vm.sqlQuery.contains("WHERE \"level\" IS DISTINCT FROM 'warn'"))
266292 }
267293
268294 func testAddColumnFilterEscapesSingleQuotesInValue() {
@@ -333,6 +359,25 @@ final class QueryViewModelTests: XCTestCase {
333359 XCTAssertEqual(vm.columnOrder, ["c", "a", "b"])
334360 }
335361
362+ func testMoveColumnRightwardLandsAfterTarget() {
363+ // Rightward move (e.g. the "Move Right" context action, which passes the
364+ // adjacent column as the target) must land the column *after* the target,
365+ // not produce a no-op.
366+ let vm = QueryViewModel()
367+ vm.columns = ["a", "b", "c"]
368+ vm.columnOrder = ["a", "b", "c"]
369+ vm.moveColumn("b", to: "c")
370+ XCTAssertEqual(vm.columnOrder, ["a", "c", "b"])
371+ }
372+
373+ func testMoveColumnLeftwardLandsBeforeTarget() {
374+ let vm = QueryViewModel()
375+ vm.columns = ["a", "b", "c"]
376+ vm.columnOrder = ["a", "b", "c"]
377+ vm.moveColumn("b", to: "a")
378+ XCTAssertEqual(vm.columnOrder, ["b", "a", "c"])
379+ }
380+
336381 func testMoveColumnByIndexSet() {
337382 let vm = QueryViewModel()
338383 vm.columns = ["a", "b", "c"]
@@ -626,5 +671,125 @@ final class QueryViewModelTests: XCTestCase {
626671 let empty = vm.emptyColumns(in: records, columns: ["a"])
627672 XCTAssertTrue(empty.isEmpty)
628673 }
674+
675+ // MARK: - Column filter edge cases
676+
677+ func testAddColumnFilterKeepsTrailingSemicolonLast() {
678+ let vm = QueryViewModel()
679+ vm.sqlQuery = "SELECT * FROM \"logs\";"
680+ vm.addColumnFilter(column: "level", value: .string("error"), exclude: false)
681+ XCTAssertEqual(vm.sqlQuery, "SELECT * FROM \"logs\" WHERE \"level\" = 'error';")
682+ }
683+
684+ func testAddColumnFilterDoesNotLandInTrailingComment() {
685+ let vm = QueryViewModel()
686+ vm.sqlQuery = "SELECT * FROM \"logs\" -- recent"
687+ vm.addColumnFilter(column: "level", value: .string("error"), exclude: false)
688+ XCTAssertEqual(vm.sqlQuery, "SELECT * FROM \"logs\" WHERE \"level\" = 'error' -- recent")
689+ }
690+
691+ func testAddColumnFilterKeepsLineBreakAfterWhereBodyComment() {
692+ let vm = QueryViewModel()
693+ vm.sqlQuery = "SELECT * FROM \"logs\"\nWHERE a = 1 -- note\nORDER BY p_timestamp DESC"
694+ vm.addColumnFilter(column: "host", value: .string("web-1"), exclude: false)
695+ XCTAssertEqual(
696+ vm.sqlQuery,
697+ "SELECT * FROM \"logs\"\nWHERE a = 1 AND \"host\" = 'web-1' -- note\nORDER BY p_timestamp DESC"
698+ )
699+ }
700+
701+ func testAddColumnFilterWithTrailingClauseBeforeWhereDoesNotCrash() {
702+ let vm = QueryViewModel()
703+ vm.sqlQuery = "SELECT a FROM t1 GROUP BY a UNION ALL SELECT a FROM t2 WHERE b = 1"
704+ vm.addColumnFilter(column: "host", value: .string("web-1"), exclude: false)
705+ XCTAssertEqual(
706+ vm.sqlQuery,
707+ "SELECT a FROM t1 GROUP BY a UNION ALL SELECT a FROM t2 WHERE b = 1 AND \"host\" = 'web-1'"
708+ )
709+ }
710+
711+ func testAddColumnFilterIgnoresKeywordNamedColumnsInSelectList() {
712+ let vm = QueryViewModel()
713+ vm.sqlQuery = "SELECT offset, message FROM \"kafka\" WHERE partition = 3"
714+ vm.addColumnFilter(column: "host", value: .string("web-1"), exclude: false)
715+ XCTAssertEqual(
716+ vm.sqlQuery,
717+ "SELECT offset, message FROM \"kafka\" WHERE partition = 3 AND \"host\" = 'web-1'"
718+ )
719+ }
720+
721+ // MARK: - SELECT list rewriting
722+
723+ func testUpdateSQLColumnsLeavesExpressionListsAlone() {
724+ let vm = QueryViewModel()
725+ let sql = "SELECT count(*) AS n, level FROM \"logs\" GROUP BY level"
726+ vm.sqlQuery = sql
727+ vm.columns = ["n", "level"]
728+ vm.columnOrder = ["n", "level"]
729+ vm.toggleColumnVisibility("n")
730+ XCTAssertEqual(vm.sqlQuery, sql)
731+ XCTAssertEqual(vm.visibleColumns, ["level"])
732+ }
733+
734+ func testUpdateSQLColumnsDoesNotBakeInAutoHiddenColumns() {
735+ let vm = QueryViewModel()
736+ vm.sqlQuery = "SELECT * FROM \"logs\""
737+ vm.columns = ["a", "b", "c"]
738+ vm.columnOrder = ["a", "b", "c"]
739+ vm.autoHiddenColumns = ["c"]
740+ vm.moveColumn("b", to: "a")
741+ XCTAssertEqual(vm.sqlQuery, "SELECT * FROM \"logs\"")
742+ }
743+
744+ func testUpdateSQLColumnsKeepsHiddenColumnOutAfterNarrowedRerun() {
745+ // Hiding `c` narrowed the SELECT list, so the re-run's results lack it; a
746+ // later reorder must not switch back to `*` and fetch it again.
747+ let vm = QueryViewModel()
748+ vm.sqlQuery = "SELECT \"a\", \"b\" FROM \"logs\""
749+ vm.pendingColumnConfig = QueryViewModel.ColumnConfiguration(order: ["a", "b", "c"], hidden: ["c"])
750+ vm.applyColumnConfig(extractedColumns: ["a", "b"], stream: nil)
751+ vm.moveColumn("b", to: "a")
752+ XCTAssertEqual(vm.sqlQuery, "SELECT \"b\", \"a\" FROM \"logs\"")
753+ XCTAssertTrue(vm.hasHiddenColumns)
754+ vm.showAllColumns()
755+ XCTAssertEqual(vm.sqlQuery, "SELECT * FROM \"logs\"")
756+ }
757+
758+ func testExcludeFilterKeepsRowsWhereColumnIsNull() {
759+ let vm = QueryViewModel()
760+ vm.sqlQuery = "SELECT * FROM \"logs\""
761+ vm.addColumnFilter(column: "level", value: .string("debug"), exclude: true)
762+ XCTAssertFalse(vm.sqlQuery.contains("<>"), "`<>` would also drop rows where level is NULL")
763+ XCTAssertTrue(vm.sqlQuery.contains("\"level\" IS DISTINCT FROM 'debug'"))
764+ }
765+
766+ func testUpdateSQLColumnsKeepsListedColumnsMissingFromResults() {
767+ // Parseable omits all-null fields from query JSON, so a listed column can
768+ // be absent from `columns`; rewriting must neither refuse nor drop it.
769+ let vm = QueryViewModel()
770+ vm.sqlQuery = "SELECT \"a\", \"b\", \"c\", \"sparse\" FROM \"logs\""
771+ vm.columns = ["a", "b", "c"]
772+ vm.columnOrder = ["a", "b", "c"]
773+ vm.toggleColumnVisibility("c")
774+ XCTAssertEqual(vm.sqlQuery, "SELECT \"a\", \"b\", \"sparse\" FROM \"logs\"")
775+ }
776+
777+ func testReorderKeepsStarWhenSavedHiddenColumnIsAbsentAnyway() {
778+ // Under `SELECT *` a saved-hidden column that's missing is missing for
779+ // other reasons (sparse/removed); a plain reorder must keep `*`.
780+ let vm = QueryViewModel()
781+ vm.sqlQuery = "SELECT * FROM \"logs\""
782+ vm.pendingColumnConfig = QueryViewModel.ColumnConfiguration(order: ["a", "b", "gone"], hidden: ["gone"])
783+ vm.applyColumnConfig(extractedColumns: ["a", "b"], stream: nil)
784+ vm.moveColumn("b", to: "a")
785+ XCTAssertEqual(vm.sqlQuery, "SELECT * FROM \"logs\"")
786+ }
787+
788+ func testMergedColumnOrderKeepsSavedPositionForAbsentColumn() {
789+ XCTAssertEqual(
790+ QueryViewModel.mergedColumnOrder(["b", "a"], inserting: ["x"], reference: ["a", "x", "b"]),
791+ ["b", "a", "x"]
792+ )
793+ }
629794}
630795
ParseableViewerTests/SQLAutoCompleteTests.swift+56
@@ -275,6 +275,62 @@ final class SQLAutoCompleteTests: XCTestCase {
275275 let ctx = SQLCompletionProvider.determineContext(text: "SELECT * FROM a LEFT JOIN ", position: 26)
276276 XCTAssertEqual(ctx, .tableRef)
277277 }
278+
279+ // MARK: - Identifier quoting / non-SQL regions
280+
281+ func testColumnCompletionQuotesNamesThatNeedIt() {
282+ let fields = [SchemaField(name: "statusCode", dataType: "Int64"), SchemaField(name: "status", dataType: "Utf8")]
283+ let result = SQLCompletionProvider.completions(
284+ for: "SELECT * FROM t WHERE stat", cursorPosition: 26,
285+ streamNames: [], schemaFields: fields
286+ )
287+ let columns = result.items.filter { $0.kind == .column }.map(\.text)
288+ XCTAssertEqual(columns, ["status", "\"statusCode\""])
289+ }
290+
291+ func testNoCompletionsInsideLineComment() {
292+ let text = "-- grouped by date"
293+ let result = SQLCompletionProvider.completions(
294+ for: text, cursorPosition: (text as NSString).length,
295+ streamNames: streams, schemaFields: fields
296+ )
297+ XCTAssertTrue(result.items.isEmpty)
298+ }
299+
300+ func testNoCompletionsInsideStringLiteral() {
301+ let text = "SELECT * FROM t WHERE msg LIKE '%sel"
302+ let result = SQLCompletionProvider.completions(
303+ for: text, cursorPosition: (text as NSString).length,
304+ streamNames: streams, schemaFields: fields
305+ )
306+ XCTAssertTrue(result.items.isEmpty)
307+ }
308+
309+ func testFullyTypedMixedCaseColumnStillOffersQuotedForm() {
310+ let fields = [SchemaField(name: "statusCode", dataType: "Int64")]
311+ let bare = "SELECT * FROM t WHERE statusCode"
312+ let result = SQLCompletionProvider.completions(
313+ for: bare, cursorPosition: (bare as NSString).length,
314+ streamNames: [], schemaFields: fields
315+ )
316+ XCTAssertEqual(result.items.map(\.text), ["\"statusCode\""])
317+
318+ // Already quoted: accepting would change nothing, so no popup.
319+ let quoted = "SELECT * FROM t WHERE \"statusCode\""
320+ let quotedResult = SQLCompletionProvider.completions(
321+ for: quoted, cursorPosition: (quoted as NSString).length - 1,
322+ streamNames: [], schemaFields: fields
323+ )
324+ XCTAssertTrue(quotedResult.items.isEmpty)
325+ }
326+
327+ func testReservedWordColumnIsQuoted() {
328+ let fields = [SchemaField(name: "order", dataType: "Utf8")]
329+ let result = SQLCompletionProvider.completions(
330+ for: "SELECT ord", cursorPosition: 10, streamNames: [], schemaFields: fields
331+ )
332+ XCTAssertEqual(result.items.filter { $0.kind == .column }.map(\.text), ["\"order\""])
333+ }
278334}
279335
280336// Make SQLCompletionContext Equatable for assertions
ParseableViewerTests/SQLTokenizerTests.swift+15
@@ -348,4 +348,19 @@ final class SQLTokenizerTests: XCTestCase {
348348 let sql = "SELECT * FROM t"
349349 XCTAssertNil(SQLTokenizer.errorHighlightRange(line: 99, column: 1, in: sql))
350350 }
351+
352+ // MARK: - CRLF line endings
353+
354+ func testCRLFIsWhitespaceAndEndsLineComment() {
355+ // Swift treats "\r\n" as a single Character, equal to neither "\r" nor "\n".
356+ let sql = "SELECT * -- all\r\nFROM t"
357+ let kinds = SQLTokenizer.tokenize(sql).map(\.kind).filter { !$0.isTrivia }
358+ XCTAssertEqual(kinds, [.keyword("SELECT"), .star, .keyword("FROM"), .identifier("t")])
359+ }
360+
361+ func testSelectColumnListRangeExcludesCRLF() {
362+ let sql = "SELECT *\r\nFROM t"
363+ let range = SQLTokenizer.selectColumnListRange(in: sql)
364+ XCTAssertEqual(range.map { String(sql[$0]) }, "*")
365+ }
351366}
ParseableViewerTests/ServerConnectionTests.swift+10
@@ -77,4 +77,14 @@ final class ServerConnectionTests: XCTestCase {
7777 let conn = ServerConnection(name: "test", url: "https://", username: "admin", password: "pass")
7878 XCTAssertNil(conn.baseURL)
7979 }
80+
81+ func testBaseURLAcceptsUppercaseScheme() {
82+ let conn = ServerConnection(name: "t", url: "HTTP://10.0.0.5:8000", username: "u", password: "p")
83+ XCTAssertEqual(conn.baseURL?.absoluteString, "http://10.0.0.5:8000")
84+ }
85+
86+ func testBaseURLRejectsNonHTTPScheme() {
87+ let conn = ServerConnection(name: "t", url: "ftp://example.com", username: "u", password: "p")
88+ XCTAssertNil(conn.baseURL)
89+ }
8090}
ParseableViewerTests/SyntaxHighlightingTests.swift+10
@@ -140,6 +140,16 @@ final class SyntaxHighlightingTests: XCTestCase {
140140 "Double-quoted identifiers should differ from keywords")
141141 }
142142
143+ func testSQLApostropheInCommentDoesNotStartString() {
144+ // The later quoted literal gives the stray apostrophe a closing partner, so
145+ // separate string/comment passes painted everything in between as a string.
146+ let sql = "-- don't\nSELECT * FROM t WHERE a = 'b'"
147+ let ts = sqlHighlight(sql)
148+ let selectIdx = (sql as NSString).range(of: "SELECT").location
149+ XCTAssertEqual(colorAt(ts, selectIdx), colorAt(sqlHighlight("SELECT x"), 0),
150+ "An apostrophe inside a comment must not open a string literal")
151+ }
152+
143153 // MARK: - JSON Highlighting
144154
145155 func testJSONHighlightProducesOutput() {
README.md+1−1
@@ -143,7 +143,7 @@ ParseableViewer/
143143| `Cmd+R` | Refresh streams |
144144| `Cmd+Enter` | Run query |
145145| `Cmd+P` | Pause/resume live tail |
146−| `Cmd+Delete` | Clear live tail entries |
146+| `Cmd+K` | Clear live tail entries |
147147| `Cmd+Ctrl+S` | Toggle sidebar |
148148
149149## License