Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

fix: 修复日志历史浏览与分页并支持接口筛选

Bob20db1c0859d0
diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md
deleted file mode 100644
index 107ce37..0000000
--- a/.github/ISSUE_TEMPLATE/bug.md
+++ /dev/null
@@ -1,49 +0,0 @@
----
-name: Bug 报告 / Bug report
-about: 报告 CodexBar 中可复现的问题 / Report a reproducible problem in CodexBar
-title: '[Bug] '
-labels: bug
-assignees: ''
----
-
-## 问题描述 / Description
-
-描述遇到的问题。
-
-Describe the problem you encountered.
-
-## 复现步骤 / Steps to reproduce
-
-按顺序填写操作步骤:
-
-List the steps in order:
-
-1. 打开“...” / Open "..."
-2. 点击“...” / Click "..."
-3. 滚动或切换到“...” / Scroll or switch to "..."
-4. 看到错误“...” / See the error "..."
-
-## 预期行为 / Expected behavior
-
-描述你预期的结果。
-
-Describe what you expected to happen.
-
-## 截图或录屏 / Screenshots or recordings
-
-可附上能说明问题的截图或录屏。
-
-You can attach screenshots or screen recordings that help illustrate the problem.
-
-## 运行环境 / Environment
-
-- macOS 版本 / macOS version:
-- CodexBar 版本 / CodexBar version:
-- Codex CLI 版本 / Codex CLI version:
-- Codex App 版本 / Codex App version:
-
-## 补充信息 / Additional information
-
-可补充日志窗口中的相关记录、问题是否稳定复现,以及最近是否升级过 CodexBar 或 Codex。
-
-You can include relevant entries from the log window, whether the problem occurs consistently, and whether you recently updated CodexBar or Codex.
diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 0000000..6651fd9
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,127 @@
+name: Bug 报告 / Bug report
+description: 界面异常、功能故障、报错 / UI problems, broken features, or errors
+title: "[Bug] "
+labels: ["bug"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ 提交前请阅读 [README](https://github.com/bob-zebedy/CodexBar#readme),并搜索[现有 Issue](https://github.com/bob-zebedy/CodexBar/issues),确认是否已有相关报告。
+
+ Before submitting, read the [README](https://github.com/bob-zebedy/CodexBar#readme) and search for similar reports in [existing issues](https://github.com/bob-zebedy/CodexBar/issues)
+
+ - type: textarea
+ id: description
+ attributes:
+ label: 问题描述 / Description
+ description: |
+ 描述实际发生的现象或报错。
+
+ Describe what happened or the error you encountered.
+ validations:
+ required: true
+
+ - type: input
+ id: codexbar-version
+ attributes:
+ label: CodexBar 版本 / CodexBar version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 中查看。
+
+ Right-click the CodexBar menu bar icon → Settings → About tab.
+ validations:
+ required: true
+
+ - type: input
+ id: macos-version
+ attributes:
+ label: macOS 版本 / macOS version
+ description: |
+ 在“Apple 系统设置 → 通用 → 关于本机”中查看,请填写完整版本号。
+
+ Find the full version in System Settings → General → About.
+ validations:
+ required: true
+
+ - type: input
+ id: codex-environment
+ attributes:
+ label: Codex 来源 / Codex source
+ description: |
+ 填写出现问题时使用的 Codex 来源(未安装或不确定时请注明)。
+
+ List the Codex sources in use when the problem occurred (if Codex is not installed or you are unsure, say so).
+ placeholder: Codex App / Codex CLI / VS Code extension / App + CLI
+ validations:
+ required: true
+
+ - type: input
+ id: codex-cli-version
+ attributes:
+ label: Codex CLI 版本 / Codex CLI version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 中查看,或在终端运行 `codex --version`(未安装可留空)。
+
+ Right-click the CodexBar menu bar icon → Settings → About tab. You can also run `codex --version` in Terminal (leave blank if not installed).
+ validations:
+ required: false
+
+ - type: input
+ id: codex-app-version
+ attributes:
+ label: Codex App 版本 / Codex App version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 或 Codex App 中查看(未使用可留空)。
+
+ Right-click the CodexBar menu bar icon → Settings → About tab, or check Codex App (leave blank if not used).
+ validations:
+ required: false
+
+ - type: textarea
+ id: steps
+ attributes:
+ label: 复现步骤 / Steps to reproduce
+ description: |
+ 如果知道如何触发,请填写操作步骤和出现频率。
+
+ If known, list the steps and how often the problem occurs.
+ placeholder: |
+ 1. 打开的页面或功能 / Page or feature opened
+ 2. 执行的操作 / Actions taken
+ 3. 观察到的现象 / Observed behavior
+ validations:
+ required: false
+
+ - type: textarea
+ id: expected
+ attributes:
+ label: 期望行为 / Expected behavior
+ description: |
+ 描述你期望的结果。
+
+ Describe what you expected to happen.
+ validations:
+ required: false
+
+ - type: textarea
+ id: logs
+ attributes:
+ label: 相关日志 / Relevant logs
+ description: |
+ 粘贴日志窗口中的相关记录(请隐藏凭证和个人信息等敏感数据)。
+
+ Paste relevant entries from the log window (redact sensitive data, such as credentials and personal information).
+ render: text
+ validations:
+ required: false
+
+ - type: textarea
+ id: additional
+ attributes:
+ label: 截图、录屏、补充信息 / Screenshots, recordings, and additional information
+ description: |
+ 可附截图、录屏或其他有助于排查的信息。
+
+ Add screenshots, recordings, or other information that may help diagnose the problem.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md
deleted file mode 100644
index e05272d..0000000
--- a/.github/ISSUE_TEMPLATE/feature.md
+++ /dev/null
@@ -1,37 +0,0 @@
----
-name: 功能请求 / Feature request
-about: 提出 CodexBar 的新功能, 改进建议或体验优化 / Suggest a new feature, improvement, or usability enhancement for CodexBar
-title: '[Feature] '
-labels: enhancement
-assignees: ''
----
-
-## 需求描述 / Description
-
-描述希望新增或改进的功能。
-
-Describe the feature you would like to add or improve.
-
-## 使用场景 / Use case
-
-说明使用场景和要解决的问题。
-
-Explain when you would use this feature and the problem it would solve.
-
-## 期望方案 / Proposed solution
-
-说明你希望 CodexBar 如何实现或呈现这个功能。
-
-Describe how you would like this feature to work or appear in CodexBar.
-
-## 替代方案 / Alternatives considered
-
-如果考虑过其他方案或临时解决办法,请在这里说明。
-
-Describe any alternatives or workarounds you have considered.
-
-## 补充信息 / Additional information
-
-可补充截图、录屏、相关配置、相似产品参考或具体工作流。
-
-You can include screenshots, screen recordings, relevant settings, examples from similar products, or specific workflows that help explain your request.
diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 0000000..8338778
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,66 @@
+name: 功能请求 / Feature request
+description: 新功能、改进建议、体验优化 / New features, improvements, or usability enhancements
+title: "[Feature] "
+labels: ["enhancement"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ 提交前请搜索[现有 Issue](https://github.com/bob-zebedy/CodexBar/issues),确认是否已有相同需求。
+
+ Before submitting, search for similar requests in [existing issues](https://github.com/bob-zebedy/CodexBar/issues)
+
+ - type: textarea
+ id: description
+ attributes:
+ label: 需求描述 / Description
+ description: |
+ 描述希望新增或改进的功能,以及要解决的问题。
+
+ Describe the feature or improvement and the problem it would solve.
+ validations:
+ required: true
+
+ - type: textarea
+ id: use-case
+ attributes:
+ label: 使用场景 / Use case
+ description: |
+ 说明何时会用到这个功能,可举一个具体例子。
+
+ Explain when you would use this feature, with an example if possible.
+ validations:
+ required: false
+
+ - type: textarea
+ id: solution
+ attributes:
+ label: 期望方案 / Proposed solution
+ description: |
+ 说明你希望这个功能如何工作,或界面如何显示。
+
+ Describe how the feature should work or look.
+ validations:
+ required: false
+
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: 替代方案 / Alternatives considered
+ description: |
+ 如果考虑过其他方案或临时解决办法,请说明。
+
+ Describe any alternatives or workarounds you have considered.
+ validations:
+ required: false
+
+ - type: textarea
+ id: additional
+ attributes:
+ label: 补充信息 / Additional information
+ description: |
+ 可附截图、录屏、相关配置、相似产品参考或具体工作流。
+
+ Add screenshots, recordings, relevant settings, examples from other products, or workflows.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md
deleted file mode 100644
index 7d153c9..0000000
--- a/.github/ISSUE_TEMPLATE/question.md
+++ /dev/null
@@ -1,42 +0,0 @@
----
-name: 一般问题 / General question
-about: 询问 CodexBar 的使用方式, 配置, 兼容性或排查思路 / Ask about using, configuring, or troubleshooting CodexBar, or about compatibility
-title: '[Question] '
-labels: question
-assignees: ''
----
-
-## 问题 / Question
-
-写下你想咨询的问题。
-
-Describe what you would like to know.
-
-## 相关背景 / Background
-
-说明你正在做什么、遇到了什么现象,以及已经尝试过哪些操作。
-
-Explain what you are trying to do, what you have observed, and what you have already tried.
-
-## 截图或录屏 / Screenshots or recordings
-
-可附上能说明问题的截图或录屏。
-
-You can attach screenshots or screen recordings that help illustrate your question.
-
-## 运行环境 / Environment
-
-如果问题与环境有关,请填写:
-
-If your question depends on your environment, provide the following:
-
-- macOS 版本 / macOS version:
-- CodexBar 版本 / CodexBar version:
-- Codex CLI 版本 / Codex CLI version:
-- Codex App 版本 / Codex App version:
-
-## 补充信息 / Additional information
-
-可补充截图、日志窗口中的相关记录,以及 Codex Hook 或跨设备同步是否开启。
-
-You can include screenshots, relevant entries from the log window, and whether Codex Hook or cross-device sync is enabled.
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
new file mode 100644
index 0000000..f42e50b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -0,0 +1,96 @@
+name: 一般问题 / General question
+description: 使用方式、配置、兼容性、排查思路 / Usage, configuration, compatibility, or troubleshooting
+title: "[Question] "
+labels: ["question"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ 提问前请阅读 [README](https://github.com/bob-zebedy/CodexBar#readme),并搜索[现有 Issue](https://github.com/bob-zebedy/CodexBar/issues)
+
+ Before asking, check the [README](https://github.com/bob-zebedy/CodexBar#readme) and [existing issues](https://github.com/bob-zebedy/CodexBar/issues)
+
+ - type: textarea
+ id: question
+ attributes:
+ label: 问题 / Question
+ description: |
+ 写下你想咨询的问题。
+
+ Describe what you would like to know.
+ validations:
+ required: true
+
+ - type: textarea
+ id: background
+ attributes:
+ label: 相关背景 / Background
+ description: |
+ 说明你正在做什么、观察到什么,以及已经尝试过的操作。
+
+ Explain what you are trying to do, what you have observed, and what you have already tried.
+ validations:
+ required: false
+
+ - type: input
+ id: codexbar-version
+ attributes:
+ label: CodexBar 版本 / CodexBar version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 中查看。
+
+ Right-click the CodexBar menu bar icon → Settings → About tab.
+ validations:
+ required: false
+
+ - type: input
+ id: macos-version
+ attributes:
+ label: macOS 版本 / macOS version
+ description: |
+ 在“Apple 系统设置 → 通用 → 关于本机”中查看。
+
+ Find it in System Settings → General → About.
+ validations:
+ required: false
+
+ - type: input
+ id: codex-environment
+ attributes:
+ label: Codex 来源 / Codex source
+ placeholder: Codex App / Codex CLI / VS Code extension / App + CLI
+ validations:
+ required: false
+
+ - type: input
+ id: codex-cli-version
+ attributes:
+ label: Codex CLI 版本 / Codex CLI version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 中查看,或在终端运行 `codex --version`
+
+ Right-click the CodexBar menu bar icon → Settings → About tab. You can also run `codex --version` in Terminal.
+ validations:
+ required: false
+
+ - type: input
+ id: codex-app-version
+ attributes:
+ label: Codex App 版本 / Codex App version
+ description: |
+ 在 "菜单栏 CodexBar 图标右键 → 设置 → 关于选项卡" 或 Codex App 中查看。
+
+ Right-click the CodexBar menu bar icon → Settings → About tab, or check Codex App.
+ validations:
+ required: false
+
+ - type: textarea
+ id: additional
+ attributes:
+ label: 截图、日志、补充信息 / Screenshots, logs, and additional information
+ description: |
+ 可附截图、录屏、相关日志或 IDE 扩展版本(请隐藏凭证和个人信息等敏感数据)。
+
+ Add screenshots, recordings, relevant logs, or the IDE extension version (redact sensitive data, such as credentials and personal information).
+ validations:
+ required: false
diff --git a/AGENTS.md b/AGENTS.md
index 971d937..c39e511 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -152,7 +152,8 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi
- 测试围绕可观察行为、关键边界和失败恢复设计,优先复用现有测试;新增测试应能发现实际回归,避免只重复实现或为简单改名机械补测
- 单元测试使用独立临时数据和可控依赖,测试结束后清理资源;不得读写真实用户数据、调用真实外部服务、启动特权服务或修改系统设置
-- 单元测试不得显示窗口、面板或 popover,也不得激活 App 或抢占焦点,透明窗口和屏幕外窗口同样不允许显示;布局使用离屏宿主验证,依赖真实窗口显示的交互另行手动验证
+- 自动化测试(包括单元测试、集成测试和 Sanitizer 测试)不得显示窗口、面板、popover 或浏览器页面,也不得激活 App 或抢占焦点;透明窗口和屏幕外窗口同样不得显示
+- 布局使用不显示窗口的离屏宿主验证,交互逻辑使用可控依赖和状态断言验证;需要真实窗口或页面的场景只做手动验证。检查测试时同时核对辅助方法和被测入口,避免间接打开界面
- 代码改动需完成受影响目标的构建、相关自动化测试及项目配置的格式和静态检查;涉及共享逻辑、构建配置或跨模块行为时,扩大验证范围;纯文档改动检查内容和格式即可
- 日常代码改动默认运行 `Unit` 测试计划,并按影响范围补充相关 `Integration` 用例;涉及共享逻辑、构建配置或交付前运行完整 `Standard` 计划
- 集成测试通过 `.tags(.integration)` 标记,按测试的主要依赖和职责归类,混合测试套件可以只标记对应函数;`Unit` 排除该标签,`Integration` 仅包含该标签,`Standard` 和 `Sanitizers` 均保留完整覆盖
diff --git a/CodexBar.xcodeproj/project.xcproj b/CodexBar.xcodeproj/project.xcproj
index fec6eae..54cbfea 100644
--- a/CodexBar.xcodeproj/project.xcproj
+++ b/CodexBar.xcodeproj/project.xcproj
@@ -315,9 +315,21 @@
"ENABLE_HARDENED_RUNTIME": "YES",
"ENABLE_PREVIEWS": "YES",
"ENABLE_USER_SELECTED_FILES": "NO",
- "EXCLUDED_SOURCE_FILE_NAMES[config=DebugTest]": "$(inherited) CodexBarPowerHelper.plist \"CodexBar Power Helper.app\"",
- "EXCLUDED_SOURCE_FILE_NAMES[config=Debug]": "$(inherited) CodexBarPowerHelper.plist \"CodexBar Power Helper.app\"",
- "EXCLUDED_SOURCE_FILE_NAMES[config=Release]": "$(inherited) CodexBarPowerHelperDebug.plist \"CodexBar Power Helper Debug.app\"",
+ "EXCLUDED_SOURCE_FILE_NAMES[config=DebugTest]": [
+ "$(inherited)",
+ "CodexBarPowerHelper.plist",
+ "\"CodexBar Power Helper.app\"",
+ ],
+ "EXCLUDED_SOURCE_FILE_NAMES[config=Debug]": [
+ "$(inherited)",
+ "CodexBarPowerHelper.plist",
+ "\"CodexBar Power Helper.app\"",
+ ],
+ "EXCLUDED_SOURCE_FILE_NAMES[config=Release]": [
+ "$(inherited)",
+ "CodexBarPowerHelperDebug.plist",
+ "\"CodexBar Power Helper Debug.app\"",
+ ],
"GENERATE_INFOPLIST_FILE": "NO",
"INFOPLIST_FILE": "CodexBar/Resources/Info.plist",
"INFOPLIST_KEY_CFBundleDisplayName[config=DebugTest]": "CodexBar Debug",
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 41dfa45..f84c8fd 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -4066,6 +4066,38 @@
}
}
},
+ "log.clear.confirmation.message" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "All logs will be permanently deleted."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "将删除全部日志,此操作无法撤销。"
+ }
+ }
+ }
+ },
+ "log.clear.confirmation.title" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Delete all logs?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "删除所有日志?"
+ }
+ }
+ }
+ },
"log.empty.no-entries" : {
"localizations" : {
"en" : {
@@ -4082,6 +4114,54 @@
}
}
},
+ "log.filter.methods" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Filter"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "筛选"
+ }
+ }
+ }
+ },
+ "log.filter.no-matches" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No matches"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未找到"
+ }
+ }
+ }
+ },
+ "log.filter.search" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Search"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "搜索"
+ }
+ }
+ }
+ },
"log.label.connection-event" : {
"localizations" : {
"en" : {
@@ -7364,4 +7444,4 @@
}
},
"version" : "1.0"
-}
\ No newline at end of file
+}
diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swift
index 1cd7d78..d279dd3 100644
--- a/CodexBar/Services/Activity/ActivityTask.swift
+++ b/CodexBar/Services/Activity/ActivityTask.swift
@@ -312,25 +312,23 @@ nonisolated struct ActivityTask {
executions[owner] = execution
if lifecycle.terminal != nil {
finishExecution(owner, at: lifecycle.lastProgressAt ?? lastProgressAt)
- } else {
- if let waiting = lifecycle.isWaitingApproval, let changedAt = lifecycle.approvalChangedAt {
- var execution = executions[owner] ?? ActivityExecution()
- if waiting {
- let approval = lifecycle.pendingApprovals.min {
- if $0.value.requestedAt != $1.value.requestedAt {
- return $0.value.requestedAt < $1.value.requestedAt
- }
- return $0.key < $1.key
- }?.value ?? ActivityApproval(
- requestedAt: changedAt, toolName: nil, sequence: progressGeneration
- )
- execution.approval = approval
- } else {
- execution.approval = nil
- }
- executions[owner] = execution
- refreshApprovalState(at: changedAt)
+ } else if let waiting = lifecycle.isWaitingApproval, let changedAt = lifecycle.approvalChangedAt {
+ var execution = executions[owner] ?? ActivityExecution()
+ if waiting {
+ let approval = lifecycle.pendingApprovals.min {
+ if $0.value.requestedAt != $1.value.requestedAt {
+ return $0.value.requestedAt < $1.value.requestedAt
+ }
+ return $0.key < $1.key
+ }?.value ?? ActivityApproval(
+ requestedAt: changedAt, toolName: nil, sequence: progressGeneration
+ )
+ execution.approval = approval
+ } else {
+ execution.approval = nil
}
+ executions[owner] = execution
+ refreshApprovalState(at: changedAt)
}
}
diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swift
index d228ae9..a42febf 100644
--- a/CodexBar/Services/AppServer/AppServerLogStore.swift
+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift
@@ -169,13 +169,13 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {
return entry.id
}
- func page(before position: Int64? = nil, limit: Int = 100) async throws -> AppServerLogPage {
+ func page(before position: Int64? = nil, limit: Int = 100, methods: Set<String> = []) async throws -> AppServerLogPage {
try await perform { storage in
let limit = min(max(1, limit), storage.limits.pageEntries)
let stats = try storage.stats()
let entries = try storage.read(
- "SELECT position, payload, id FROM entries WHERE position < ? ORDER BY position DESC LIMIT ?",
- values: [position ?? Int64.max, Int64(limit + 1)]
+ "SELECT position, payload, id FROM entries WHERE position < ?1\(methods.isEmpty ? "" : Self.methodCondition) ORDER BY position DESC LIMIT ?2",
+ values: [position ?? Int64.max, Int64(limit + 1)], methods: methods
)
return AppServerLogPage(
entries: Array(entries.prefix(max(1, limit))), revision: stats.revision,
@@ -184,11 +184,12 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {
}
}
- func changes(since revision: Int64) async throws -> AppServerLogPage {
+ func changes(since revision: Int64, methods: Set<String> = []) async throws -> AppServerLogPage {
try await perform { storage in
let stats = try storage.stats()
let entries = stats.revision == revision ? [] : try storage.read(
- "SELECT position, payload, id FROM entries WHERE revision > ? ORDER BY position DESC LIMIT ?", values: [revision, Int64(storage.limits.pageEntries + 1)]
+ "SELECT position, payload, id FROM entries WHERE revision > ?1\(methods.isEmpty ? "" : Self.methodCondition) ORDER BY position DESC LIMIT ?2",
+ values: [revision, Int64(storage.limits.pageEntries + 1)], methods: methods
)
return AppServerLogPage(
entries: Array(entries.prefix(storage.limits.pageEntries)),
@@ -200,6 +201,20 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {
}
}
+ func methods() async throws -> [String] {
+ try await perform { storage in
+ let statement = try storage.prepare("SELECT DISTINCT \(Self.methodExpression) AS method FROM entries WHERE method IS NOT NULL AND method != '' ORDER BY method")
+ defer { sqlite3_finalize(statement) }
+ var methods: [String] = []
+ while try storage.step(statement) == SQLITE_ROW {
+ if let text = sqlite3_column_text(statement, 0) {
+ methods.append(String(cString: text))
+ }
+ }
+ return methods
+ }
+ }
+
func clear() async throws {
try await perform { storage in
try storage.transaction {
@@ -451,12 +466,21 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {
return Statistics(revision: sqlite3_column_int64(statement, 0), generation: sqlite3_column_int64(statement, 1), total: Int(sqlite3_column_int64(statement, 2)))
}
- private func read(_ sql: String, values: [Int64], skipCorrupt: Bool = false) throws -> [AppServerLogEntry] {
+ // 正文以 BLOB 保存, 查询时显式转为文本再读取 JSON 字段
+ private static let methodExpression = "CASE WHEN json_valid(CAST(payload AS TEXT)) THEN json_extract(CAST(payload AS TEXT), '$.method') ELSE 'log/corrupt' END"
+ private static let methodCondition = " AND (\(methodExpression)) IN (SELECT value FROM json_each(?3))"
+
+ private func read(_ sql: String, values: [Int64], methods: Set<String> = [], skipCorrupt: Bool = false) throws -> [AppServerLogEntry] {
let statement = try prepare(sql)
defer { sqlite3_finalize(statement) }
for (index, value) in values.enumerated() {
guard sqlite3_bind_int64(statement, Int32(index + 1), value) == SQLITE_OK else { throw failure() }
}
+ if !methods.isEmpty {
+ let data = try JSONEncoder().encode(methods.sorted())
+ guard let json = String(data: data, encoding: .utf8) else { throw failure() }
+ try bind(json, to: statement, at: 3)
+ }
var entries: [AppServerLogEntry] = []
while try step(statement) == SQLITE_ROW {
if let entry = decode(statement, skipCorrupt: skipCorrupt) {
diff --git a/CodexBar/Services/AppServer/AppServerLogViewModel.swift b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
index 8ebde95..92294b9 100644
--- a/CodexBar/Services/AppServer/AppServerLogViewModel.swift
+++ b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
@@ -8,15 +8,18 @@ final class AppServerLogViewModel: ObservableObject {
@Published private(set) var hasMore = false
@Published private(set) var isLoading = false
@Published private(set) var errorMessage: String?
+ @Published private(set) var selectedMethods: Set<String> = []
private let storage: AppServerLogStore
private let pageSize: Int
private let maximumEntries: Int
- private var browsingHistory = false
+ private var isFollowingLatest = true
+ private var needsLatestReload = false
private var revision: Int64 = 0
private var generation: Int64 = 0
private var isLoaded = false
private var isReading = false
+ private var isPaging = false
private var observation: Task<Void, Never>?
private var observationGeneration = 0
@@ -45,8 +48,11 @@ final class AppServerLogViewModel: ObservableObject {
entries = []
totalCount = 0
hasMore = false
+ isFollowingLatest = true
+ needsLatestReload = false
isLoaded = false
isReading = false
+ isPaging = false
isLoading = false
}
@@ -69,22 +75,28 @@ final class AppServerLogViewModel: ObservableObject {
if !isLoaded {
try await loadFirst(current: current)
} else {
- let changes = try await storage.changes(since: revision)
+ let changes = try await storage.changes(since: revision, methods: selectedMethods)
guard current == observationGeneration else { return }
- if changes.generation != generation || changes.hasMore {
+ let invalidated = changes.generation != generation || changes.hasMore
+ if invalidated, isFollowingLatest {
try await loadFirst(current: current)
} else if changes.revision != revision {
+ needsLatestReload = needsLatestReload || invalidated
+ let previousOldest = entries.last?.position
mergeEntries(changes.entries)
- let oldest = try await storage.page(before: entries.last?.position, limit: 1)
- guard current == observationGeneration else { return }
+ if invalidated || entries.last?.position != previousOldest {
+ let oldest = try await storage.page(before: entries.last?.position, limit: 1, methods: selectedMethods)
+ guard current == observationGeneration else { return }
+ let more = !oldest.entries.isEmpty
+ if hasMore != more {
+ hasMore = more
+ }
+ }
revision = changes.revision
+ generation = changes.generation
if totalCount != changes.total {
totalCount = changes.total
}
- let more = !oldest.entries.isEmpty
- if hasMore != more {
- hasMore = more
- }
}
}
if errorMessage != nil {
@@ -97,11 +109,34 @@ final class AppServerLogViewModel: ObservableObject {
}
}
+ func setSelectedMethods(_ methods: Set<String>) {
+ guard selectedMethods != methods else { return }
+ // 切换筛选使旧分页失效, 轮询任务继续读取新的筛选结果
+ observationGeneration += 1
+ selectedMethods = methods
+ entries = []
+ hasMore = false
+ isFollowingLatest = true
+ needsLatestReload = false
+ isLoaded = false
+ isReading = false
+ isPaging = false
+ isLoading = true
+ errorMessage = nil
+ }
+
+ func availableMethods() async throws -> [String] {
+ try await storage.methods()
+ }
+
private func mergeEntries(_ updates: [AppServerLogEntry]) {
guard !updates.isEmpty else { return }
let newest = entries.first?.position ?? 0
+ if !isFollowingLatest, updates.contains(where: { $0.position > newest }) {
+ needsLatestReload = true
+ }
var byID = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })
- for entry in updates where byID[entry.id] != nil || (!browsingHistory && entry.position > newest) {
+ for entry in updates where byID[entry.id] != nil || (isFollowingLatest && entry.position > newest) {
byID[entry.id] = entry
}
let updated = Array(byID.values.sorted { $0.position > $1.position }.prefix(maximumEntries))
@@ -110,13 +145,39 @@ final class AppServerLogViewModel: ObservableObject {
}
}
+ func pauseFollowingLatest() {
+ isFollowingLatest = false
+ }
+
+ func resumeFollowingLatest() async {
+ let current = observationGeneration
+ while isReading {
+ do { try await Task.sleep(for: .milliseconds(25)) } catch { return }
+ guard current == observationGeneration else { return }
+ }
+ guard !Task.isCancelled, isLoaded else { return }
+ isFollowingLatest = true
+ guard needsLatestReload else { return }
+ // 历史分页会移除较新的缓存, 增量游标也已越过浏览期间的新日志
+ isLoaded = false
+ await refresh()
+ }
+
func loadMore() async {
+ guard !Task.isCancelled, !isPaging, hasMore, let cursor = entries.last?.position else { return }
let waitingGeneration = observationGeneration
+ // 等待后台刷新时也标记为正在分页, 避免重复请求排队加载后续页
+ isPaging = true
+ defer {
+ if waitingGeneration == observationGeneration {
+ isPaging = false
+ }
+ }
while isReading {
do { try await Task.sleep(for: .milliseconds(25)) } catch { return }
guard waitingGeneration == observationGeneration else { return }
}
- guard !Task.isCancelled, hasMore, let cursor = entries.last?.position else { return }
+ guard !Task.isCancelled, hasMore, entries.last?.position == cursor else { return }
let current = observationGeneration
isReading = true
isLoading = true
@@ -127,16 +188,20 @@ final class AppServerLogViewModel: ObservableObject {
}
}
do {
- let page = try await storage.page(before: cursor, limit: pageSize)
+ let page = try await storage.page(before: cursor, limit: pageSize, methods: selectedMethods)
guard current == observationGeneration else { return }
- if page.generation != generation {
+ if page.generation != generation, isFollowingLatest {
try await loadFirst(current: current)
} else {
+ if page.generation != generation {
+ needsLatestReload = true
+ }
let existing = Set(entries.map(\.id))
entries.append(contentsOf: page.entries.filter { !existing.contains($0.id) })
if entries.count > maximumEntries {
entries.removeFirst(entries.count - maximumEntries)
- browsingHistory = true
+ isFollowingLatest = false
+ needsLatestReload = true
}
hasMore = page.hasMore
totalCount = page.total
@@ -167,6 +232,8 @@ final class AppServerLogViewModel: ObservableObject {
}
do {
try await storage.clear()
+ guard current == observationGeneration else { return }
+ isLoaded = false
try await loadFirst(current: current)
if current == observationGeneration {
errorMessage = nil
@@ -179,10 +246,16 @@ final class AppServerLogViewModel: ObservableObject {
}
private func loadFirst(current: Int) async throws {
- let page = try await storage.page(limit: pageSize)
+ let page = try await storage.page(limit: pageSize, methods: selectedMethods)
guard current == observationGeneration else { return }
+ // 读取最新页期间可能已开始浏览, 后台重载不能替换正在阅读的内容
+ if isLoaded, !isFollowingLatest {
+ needsLatestReload = true
+ return
+ }
entries = page.entries
- browsingHistory = false
+ isFollowingLatest = true
+ needsLatestReload = false
revision = page.revision
generation = page.generation
totalCount = page.total
diff --git a/CodexBar/Views/Log/LogMethodFilter.swift b/CodexBar/Views/Log/LogMethodFilter.swift
new file mode 100644
index 0000000..a53403c
--- /dev/null
+++ b/CodexBar/Views/Log/LogMethodFilter.swift
@@ -0,0 +1,170 @@
+import SwiftUI
+
+struct LogMethodFilter: View {
+ @ObservedObject var store: AppServerLogViewModel
+ @State private var isPresented = false
+ @State private var query = ""
+ @State private var methods: [String] = []
+ @State private var isLoading = false
+ @State private var errorMessage: String?
+ @FocusState private var isSearchFocused: Bool
+
+ var body: some View {
+ HStack(spacing: 6) {
+ if store.selectedMethods.isEmpty {
+ Button {
+ isPresented.toggle()
+ } label: {
+ Label("log.filter.methods", systemImage: "line.3.horizontal.decrease")
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .foregroundStyle(.secondary)
+ } else {
+ Button {
+ store.setSelectedMethods([])
+ } label: {
+ Image(systemName: "trash")
+ .foregroundStyle(.secondary)
+ .frame(width: 16, height: 24)
+ .contentShape(Rectangle())
+ }
+
+ ScrollView(.horizontal) {
+ HStack(spacing: 5) {
+ ForEach(store.selectedMethods.sorted(), id: \.self) { method in
+ HStack(spacing: 4) {
+ Text(verbatim: method)
+ .font(LogTypography.captionFont.monospaced())
+ .lineLimit(1)
+ Button {
+ toggle(method)
+ } label: {
+ Image(systemName: "xmark")
+ .font(.caption2)
+ }
+ }
+ .padding(.horizontal, 7)
+ .padding(.vertical, 3)
+ .background(.quaternary, in: Capsule())
+ }
+ }
+ }
+ .scrollIndicators(.hidden)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Button {
+ isPresented.toggle()
+ } label: {
+ Image(systemName: "chevron.down")
+ .font(.caption)
+ .padding(.horizontal, 4)
+ }
+ }
+ .buttonStyle(.plain)
+ .font(LogTypography.controlFont)
+ .padding(.horizontal, 9)
+ .frame(height: 24)
+ .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7))
+ .contentShape(Rectangle())
+ .onTapGesture { isPresented = true }
+ .popover(isPresented: $isPresented, arrowEdge: .bottom) {
+ methodPicker
+ }
+ }
+
+ private var methodPicker: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass")
+ .foregroundStyle(.secondary)
+ TextField("log.filter.search", text: $query)
+ .textFieldStyle(.plain)
+ .focused($isSearchFocused)
+ if !query.isEmpty {
+ Button {
+ query = ""
+ } label: {
+ Image(systemName: "xmark.circle.fill")
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(12)
+ Divider()
+ if isLoading {
+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if let errorMessage {
+ Text(errorMessage)
+ .foregroundStyle(.red)
+ .padding()
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if matchingMethods.isEmpty {
+ Text("log.filter.no-matches")
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 2) {
+ ForEach(matchingMethods, id: \.self) { method in
+ Button {
+ toggle(method)
+ } label: {
+ HStack(spacing: 8) {
+ Image(systemName: "checkmark")
+ .opacity(store.selectedMethods.contains(method) ? 1 : 0)
+ .frame(width: 14)
+ Text(verbatim: method)
+ .font(LogTypography.captionFont.monospaced())
+ .lineLimit(1)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(6)
+ }
+ }
+ }
+ .font(LogTypography.controlFont)
+ .frame(width: 360, height: 320)
+ .task {
+ query = ""
+ isSearchFocused = true
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let available = try await store.availableMethods()
+ try Task.checkCancellation()
+ methods = available
+ errorMessage = nil
+ } catch is CancellationError {
+ // 关闭下拉框后不再更新候选项
+ } catch {
+ errorMessage = error.localizedDescription
+ }
+ }
+ }
+
+ private var matchingMethods: [String] {
+ let search = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ return Set(methods).union(store.selectedMethods).sorted().filter {
+ search.isEmpty || $0.localizedStandardContains(search)
+ }
+ }
+
+ private func toggle(_ method: String) {
+ var selection = store.selectedMethods
+ if !selection.insert(method).inserted {
+ selection.remove(method)
+ }
+ store.setSelectedMethods(selection)
+ }
+}
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index 324d000..8192e79 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -20,6 +20,7 @@ struct LogView: View {
let mainPanelSettings: MainPanelSettings
@State private var preview = LogPreviewPresentation()
@State private var scrollPosition = ScrollPosition(idType: UUID.self, edge: .top)
+ @State private var isShowingClearConfirmation = false
var body: some View {
// 每轮渲染只取一次发布快照复用
@@ -44,6 +45,10 @@ struct LogView: View {
}
}
.frame(minWidth: 640, minHeight: 480)
+ .task(id: store.selectedMethods) {
+ scrollPosition.scrollTo(edge: .top)
+ await store.refresh()
+ }
.task(id: preview.request?.id) {
if let request = preview.request {
await preview.prepare(request)
@@ -53,7 +58,10 @@ struct LogView: View {
FullLogTextView(item: item)
.onDisappear { preview.dismiss(item) }
}
- .onDisappear { preview.cancel() }
+ .onDisappear {
+ isShowingClearConfirmation = false
+ preview.cancel()
+ }
.contentAnimations(settings: mainPanelSettings)
}
@@ -75,16 +83,25 @@ struct LogView: View {
Capsule().fill(.quaternary)
}
- Spacer()
+ LogMethodFilter(store: store)
+ .frame(maxWidth: .infinity)
Button {
- Task { await store.clear() }
+ isShowingClearConfirmation = true
} label: {
Label("common.action.clear", systemImage: "trash")
}
.controlSize(.small)
.font(LogTypography.controlFont)
- .disabled(store.totalCount == 0 || store.isLoading)
+ .disabled((store.totalCount == 0 && store.entries.isEmpty) || store.isLoading)
+ .alert("log.clear.confirmation.title", isPresented: $isShowingClearConfirmation) {
+ Button("common.action.cancel", role: .cancel) {}
+ Button("common.action.clear", role: .destructive) {
+ Task { await store.clear() }
+ }
+ } message: {
+ Text("log.clear.confirmation.message")
+ }
}
.padding(.horizontal, 16)
.padding(.vertical, 10)
@@ -114,23 +131,40 @@ struct LogView: View {
}
if store.hasMore {
ProgressView()
+ .controlSize(.small)
.frame(maxWidth: .infinity)
- .padding()
- .task(id: entries.last?.id) { await store.loadMore() }
+ .padding(.vertical, 8)
}
}
.scrollTargetLayout()
}
.scrollPosition($scrollPosition, anchor: .top)
- .onScrollPhaseChange { _, phase, context in
+ .onScrollGeometryChange(for: Bool.self) { geometry in
+ geometry.contentOffset.y + geometry.contentInsets.top > 1
+ } action: { _, isBrowsingHistory in
+ if isBrowsingHistory {
+ store.pauseFollowingLatest()
+ }
+ }
+ .onScrollPhaseChange { previousPhase, phase, context in
// 浏览时按日志身份保持位置, 回到顶部后才重新跟随新日志
- if phase == .idle, context.geometry.contentOffset.y + context.geometry.contentInsets.top <= 1 {
+ if store.hasMore, Self.shouldLoadMore(from: previousPhase, to: phase, geometry: context.geometry) {
+ Task { await store.loadMore() }
+ } else if phase == .idle, context.geometry.contentOffset.y + context.geometry.contentInsets.top <= 1 {
scrollPosition.scrollTo(edge: .top)
+ Task { await store.resumeFollowingLatest() }
}
}
.onDisappear { scrollPosition = ScrollPosition(idType: UUID.self, edge: .top) }
.background(Color(nsColor: .textBackgroundColor))
}
+
+ static func shouldLoadMore(from previousPhase: ScrollPhase, to phase: ScrollPhase, geometry: ScrollGeometry) -> Bool {
+ // 列表重排和程序滚动不会产生新的手动滚动结束事件
+ guard phase == .idle, previousPhase == .interacting || previousPhase == .decelerating else { return false }
+ let visibleBottom = geometry.contentOffset.y + geometry.containerSize.height - geometry.contentInsets.bottom
+ return visibleBottom >= geometry.contentSize.height - 1
+ }
}
// MARK: - 单条日志行
diff --git a/Config/BuildNumber.xcconfig b/Config/BuildNumber.xcconfig
index 4a8745a..b282a5d 100644
--- a/Config/BuildNumber.xcconfig
+++ b/Config/BuildNumber.xcconfig
@@ -1,3 +1,3 @@
// 请勿手动修改
// Do not modify manually
-CURRENT_PROJECT_VERSION = 264
\ No newline at end of file
+CURRENT_PROJECT_VERSION = 278
\ No newline at end of file
diff --git a/Tests/App/AppServer/AppServerLogFilterTests.swift b/Tests/App/AppServer/AppServerLogFilterTests.swift
new file mode 100644
index 0000000..a942208
--- /dev/null
+++ b/Tests/App/AppServer/AppServerLogFilterTests.swift
@@ -0,0 +1,143 @@
+import Foundation
+import SQLite3
+import Testing
+
+@Suite(.tags(.integration))
+struct AppServerLogFilterTests {
+ @Test func methodChoicesAndFilteredPagesCoverUnloadedHistory() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ let quoted = "test/'\"接口"
+ let oldest = storage.beginRequest(method: quoted, payload: "{}")
+ storage.recordFailure(message: "without method")
+ for index in 0 ..< 9 {
+ storage.recordReceived(method: index.isMultiple(of: 2) ? "thread/read" : "account/read", payload: "{}", connection: "test")
+ }
+ let methods = try await storage.methods()
+ #expect(methods == ["account/read", quoted, "thread/read"])
+ #expect(try await storage.page(limit: 2, methods: [quoted]).entries.map(\.id) == [oldest])
+
+ let first = try await storage.page(limit: 2, methods: ["account/read", quoted])
+ #expect(first.entries.map(\.method) == ["account/read", "account/read"])
+ #expect(first.hasMore)
+ #expect(first.total == 11)
+ let second = try await storage.page(before: first.entries.last?.position, limit: 2, methods: ["account/read", quoted])
+ let third = try await storage.page(before: second.entries.last?.position, limit: 2, methods: ["account/read", quoted])
+ #expect(second.entries.count == 2)
+ #expect(second.hasMore)
+ #expect(third.entries.map(\.id) == [oldest])
+ #expect(!third.hasMore)
+ let missing = try await storage.page(methods: ["missing"])
+ #expect(missing.entries.isEmpty)
+ #expect(!missing.hasMore)
+ #expect(try await storage.page().entries.count == 11)
+
+ storage.finishRequest(oldest, response: "completed")
+ storage.recordReceived(method: "ignored", payload: "{}", connection: "test")
+ let changes = try await storage.changes(since: first.revision, methods: [quoted])
+ #expect(changes.entries.map(\.id) == [oldest])
+ #expect(changes.entries.first?.detail == "completed")
+ #expect(changes.total == 12)
+ #expect(try await storage.changes(since: changes.revision, methods: [quoted]).entries.isEmpty)
+ }
+
+ @Test func filteredHistoryResumesLiveUpdatesAndRemovingSelectionsRestoresAll() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 18 {
+ storage.recordReceived(method: index.isMultiple(of: 2) ? "selected" : "other", payload: "entry-\(index)", connection: "test")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)
+ model.setSelectedMethods(["selected"])
+ await model.refresh()
+ #expect(model.entries.first?.detail == "entry-16")
+ await model.loadMore()
+ await model.loadMore()
+ #expect(model.entries.count == 6)
+ #expect(model.entries.allSatisfy { $0.method == "selected" })
+ #expect(!model.hasMore)
+ storage.recordReceived(method: "selected", payload: "latest match", connection: "test")
+ storage.recordReceived(method: "other", payload: "latest other", connection: "test")
+ await model.refresh()
+ #expect(model.entries.first?.detail != "latest match")
+ await model.resumeFollowingLatest()
+ #expect(model.entries.first?.detail == "latest match")
+ #expect(model.entries.count == 3)
+ #expect(model.hasMore)
+ storage.recordReceived(method: "other", payload: "ignored", connection: "test")
+ await model.refresh()
+ #expect(model.entries.count == 3)
+ #expect(model.totalCount == 21)
+
+ model.setSelectedMethods(["missing"])
+ #expect(model.entries.isEmpty)
+ await model.refresh()
+ #expect(model.entries.isEmpty)
+ #expect(!model.hasMore)
+ storage.recordReceived(method: "missing", payload: "first match", connection: "test")
+ await model.refresh()
+ #expect(model.entries.first?.detail == "first match")
+
+ model.setSelectedMethods([])
+ await model.refresh()
+ #expect(model.entries.map(\.method) == ["missing", "other", "other"])
+ #expect(model.totalCount == 22)
+ await model.clear()
+ #expect(model.entries.isEmpty)
+ #expect(try await model.availableMethods().isEmpty)
+ }
+
+ @Test func changingSelectionDiscardsInFlightPages() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let readGate = AppServerLogReadGate()
+ let storage = AppServerLogStore(directoryURL: directory.url, now: { readGate.now() })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ defer { readGate.release() }
+ storage.recordReceived(method: "selected", payload: "oldest", connection: "test")
+ for _ in 0 ..< 6 {
+ storage.recordReceived(method: "other", payload: "{}", connection: "test")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2)
+ await model.refresh()
+ readGate.arm()
+ let page = Task { await model.loadMore() }
+ defer { page.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ readGate.didBlock
+ })
+ model.setSelectedMethods(["selected"])
+ let refresh = Task { await model.refresh() }
+ defer { refresh.cancel() }
+ readGate.release()
+ await page.value
+ await refresh.value
+ #expect(model.entries.count == 1)
+ #expect(model.entries.first?.method == "selected")
+ #expect(!model.isLoading)
+ #expect(!model.hasMore)
+ }
+
+ @Test func corruptPayloadDoesNotBreakMethodDiscoveryOrFiltering() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ let corrupt = storage.beginRequest(method: "broken", payload: "{}")
+ storage.recordReceived(method: "healthy", payload: "{}", connection: "test")
+ _ = try await storage.page()
+ var database: OpaquePointer?
+ #expect(sqlite3_open(directory.url.appendingPathComponent(AppServerLogStore.databaseName).path, &database) == SQLITE_OK)
+ defer { sqlite3_close(database) }
+ #expect(sqlite3_exec(database, "UPDATE entries SET payload = x'7B' WHERE id = '\(corrupt.uuidString)'", nil, nil, nil) == SQLITE_OK)
+ #expect(try await storage.methods() == ["healthy", "log/corrupt"])
+ #expect(try await storage.page(methods: ["healthy"]).entries.count == 1)
+ let page = try await storage.page(methods: ["log/corrupt"])
+ #expect(page.entries.map(\.id) == [corrupt])
+ #expect(page.entries.first?.method == "log/corrupt")
+ }
+}
diff --git a/Tests/App/AppServer/AppServerLogPaginationTests.swift b/Tests/App/AppServer/AppServerLogPaginationTests.swift
new file mode 100644
index 0000000..985fd5f
--- /dev/null
+++ b/Tests/App/AppServer/AppServerLogPaginationTests.swift
@@ -0,0 +1,99 @@
+import Foundation
+import Testing
+
+@Suite(.tags(.integration))
+struct AppServerLogPaginationTests {
+ @Test(arguments: [false, true])
+ func interruptedWaitingRequestAllowsLaterPagination(stopObservation: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let readGate = AppServerLogReadGate()
+ let storage = AppServerLogStore(directoryURL: directory.url, now: { readGate.now() })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ defer { readGate.release() }
+ for index in 0 ..< 9 {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3)
+ await model.refresh()
+ readGate.arm()
+ let refresh = Task { await model.refresh() }
+ defer { refresh.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ readGate.didBlock
+ })
+ var didRequestPage = false
+ let request = Task {
+ didRequestPage = true
+ await model.loadMore()
+ }
+ defer { request.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ didRequestPage
+ })
+ if stopObservation {
+ model.stop()
+ } else {
+ request.cancel()
+ }
+ await request.value
+ readGate.release()
+ await refresh.value
+ await model.refresh()
+ #expect(model.entries.count == 3)
+ await model.loadMore()
+ #expect(model.entries.count == 6)
+ #expect(model.entries.last?.detail == "entry-3")
+ #expect(!model.isLoading)
+ }
+
+ @Test(arguments: [false, true])
+ func overlappingRequestsLoadOnlyOnePage(waitingForRefresh: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let readGate = AppServerLogReadGate()
+ let storage = AppServerLogStore(directoryURL: directory.url, now: { readGate.now() })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ defer { readGate.release() }
+ for index in 0 ..< 15 {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3)
+ await model.refresh()
+ readGate.arm()
+ let firstRead = Task {
+ if waitingForRefresh {
+ await model.refresh()
+ } else {
+ await model.loadMore()
+ }
+ }
+ defer { firstRead.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ readGate.didBlock
+ })
+ var startedRequests = 0
+ let requests = (0 ..< 3).map { _ in
+ Task {
+ startedRequests += 1
+ await model.loadMore()
+ }
+ }
+ defer { requests.forEach { $0.cancel() } }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ startedRequests == requests.count
+ })
+ readGate.release()
+ await firstRead.value
+ for request in requests {
+ await request.value
+ }
+ #expect(model.entries.count == 6)
+ #expect(model.entries.last?.detail == "entry-9")
+ #expect(model.hasMore)
+ #expect(!model.isLoading)
+ await model.loadMore()
+ #expect(model.entries.count == 9)
+ #expect(model.entries.last?.detail == "entry-6")
+ }
+}
diff --git a/Tests/App/AppServer/AppServerLogReadGate.swift b/Tests/App/AppServer/AppServerLogReadGate.swift
new file mode 100644
index 0000000..feafe05
--- /dev/null
+++ b/Tests/App/AppServer/AppServerLogReadGate.swift
@@ -0,0 +1,34 @@
+import Foundation
+import os
+import Testing
+
+/// 通过注入时钟暂停存储队列, 主 actor 只查询状态和发送释放信号
+final nonisolated class AppServerLogReadGate: Sendable {
+ private let state = OSAllocatedUnfairLock(initialState: (shouldBlock: false, didBlock: false))
+ private let semaphore = DispatchSemaphore(value: 0)
+
+ var didBlock: Bool {
+ state.withLock { $0.didBlock }
+ }
+
+ func arm() {
+ state.withLock { $0.shouldBlock = true }
+ }
+
+ func release() {
+ semaphore.signal()
+ }
+
+ func now() -> Date {
+ let shouldBlock = state.withLock { state in
+ guard state.shouldBlock else { return false }
+ state.shouldBlock = false
+ state.didBlock = true
+ return true
+ }
+ if shouldBlock {
+ #expect(semaphore.wait(timeout: .now() + 5) == .success)
+ }
+ return Date()
+ }
+}
diff --git a/Tests/App/AppServer/AppServerLogTests.swift b/Tests/App/AppServer/AppServerLogTests.swift
index 8b4f220..f34436d 100644
--- a/Tests/App/AppServer/AppServerLogTests.swift
+++ b/Tests/App/AppServer/AppServerLogTests.swift
@@ -228,7 +228,173 @@ struct AppServerLogTests {
#expect(publications == 1)
}
- @Test func retentionChangeReloadsVisibleHistory() async throws {
+ @Test(arguments: [false, true])
+ func retentionKeepsBrowsedEntriesUntilReturningToLatest(loadNextPage: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 6))
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 6 {
+ storage.recordFailure(message: "old-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2, maximumEntries: 2)
+ await model.refresh()
+ await model.loadMore()
+ let browsedEntries = model.entries
+ #expect(browsedEntries.map(\.detail) == ["old-3", "old-2"])
+ for index in 0 ..< 4 {
+ storage.recordFailure(message: "new-\(index)")
+ }
+ let retained = try await storage.page()
+ #expect(Set(retained.entries.map(\.id)).isDisjoint(with: browsedEntries.map(\.id)))
+ #expect(retained.total <= 6)
+ if loadNextPage {
+ await model.loadMore()
+ } else {
+ await model.refresh()
+ }
+ #expect(model.entries == browsedEntries)
+ #expect(!model.hasMore)
+ await model.refresh()
+ #expect(model.entries == browsedEntries)
+ #expect(model.totalCount == retained.total)
+ await model.resumeFollowingLatest()
+ #expect(model.entries.first?.detail == "new-3")
+ #expect(model.entries.count == 2)
+ }
+
+ @Test(arguments: [false, true])
+ func retentionPreservesUntrimmedBrowsingAndExplicitClearStillEmptiesIt(filtered: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 6))
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 6 {
+ storage.recordFailure(method: "kept", message: "old-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2)
+ if filtered {
+ model.setSelectedMethods(["kept"])
+ }
+ await model.refresh()
+ model.pauseFollowingLatest()
+ await model.loadMore()
+ let browsedEntries = model.entries
+ #expect(browsedEntries.count == 4)
+ for index in 0 ..< 4 {
+ storage.recordFailure(method: "kept", message: "new-\(index)")
+ }
+ await model.refresh()
+ #expect(model.entries == browsedEntries)
+ #expect(!model.hasMore)
+ #expect(model.totalCount <= 6)
+ #expect(try await storage.page().entries != browsedEntries)
+ await model.clear()
+ #expect(model.entries.isEmpty)
+ #expect(model.totalCount == 0)
+ #expect(!model.hasMore)
+ storage.recordFailure(method: "kept", message: "after clear")
+ await model.refresh()
+ #expect(model.entries.first?.detail == "after clear")
+ }
+
+ @Test func expiredBrowsingSnapshotCanStillBeExplicitlyCleared() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let time = OSAllocatedUnfairLock(initialState: Date())
+ let storage = AppServerLogStore(directoryURL: directory.url, now: { time.withLock { $0 } })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ storage.recordFailure(message: "expires while reading")
+ let model = AppServerLogViewModel(storage: storage)
+ await model.refresh()
+ model.pauseFollowingLatest()
+ let browsedEntries = model.entries
+ time.withLock { $0 = $0.addingTimeInterval(366 * 86400) }
+ await model.refresh()
+ #expect(model.totalCount == 0)
+ #expect(model.entries == browsedEntries)
+ #expect(!model.hasMore)
+ await model.clear()
+ #expect(model.entries.isEmpty)
+ #expect(model.totalCount == 0)
+ }
+
+ @Test(arguments: [2, 1000])
+ func browsingKeepsLoadedEntriesWhenLiveChangesAccumulate(changeLimit: Int) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(pageEntries: changeLimit))
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 6 {
+ storage.recordFailure(message: "old-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2, maximumEntries: 6)
+ await model.refresh()
+ model.pauseFollowingLatest()
+ await model.loadMore()
+ let browsedEntries = model.entries
+ for index in 0 ..< 5 {
+ storage.recordFailure(message: "new-\(index)")
+ }
+ await model.refresh()
+ #expect(model.entries == browsedEntries)
+ #expect(model.hasMore)
+ await model.resumeFollowingLatest()
+ #expect(model.entries.first?.detail == "new-4")
+ #expect(model.entries.count == 2)
+ storage.recordFailure(message: "following again")
+ await model.refresh()
+ #expect(model.entries.first?.detail == "following again")
+ }
+
+ @Test func beginningToBrowseDuringRetentionReloadPreservesTheCurrentPage() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let blocked = OSAllocatedUnfairLock(initialState: (readsUntilBlock: 0, didBlock: false))
+ let release = DispatchSemaphore(value: 0)
+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 4), now: {
+ let shouldBlock = blocked.withLock { state in
+ guard state.readsUntilBlock > 0 else { return false }
+ state.readsUntilBlock -= 1
+ guard state.readsUntilBlock == 0 else { return false }
+ state.didBlock = true
+ return true
+ }
+ if shouldBlock {
+ #expect(release.wait(timeout: .now() + 5) == .success)
+ }
+ return Date()
+ })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ defer { release.signal() }
+ for index in 0 ..< 4 {
+ storage.recordFailure(message: "old-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2)
+ await model.refresh()
+ let browsedEntries = model.entries
+ for index in 0 ..< 4 {
+ storage.recordFailure(message: "new-\(index)")
+ }
+ _ = try await storage.page()
+ blocked.withLock { $0.readsUntilBlock = 2 }
+ let refresh = Task { await model.refresh() }
+ defer { refresh.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ blocked.withLock { $0.didBlock }
+ })
+ model.pauseFollowingLatest()
+ release.signal()
+ await refresh.value
+ #expect(model.entries == browsedEntries)
+ await model.refresh()
+ #expect(model.entries == browsedEntries)
+ #expect(!model.hasMore)
+ await model.resumeFollowingLatest()
+ #expect(model.entries.first?.detail == "new-3")
+ }
+
+ @Test func retentionChangeReloadsWhenFollowingLatest() async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 4))
@@ -517,6 +683,108 @@ extension AppServerLogTests {
#expect(size < 128 * 1024)
}
+ @Test(arguments: [false, true])
+ func returningToTopRestoresLatestAfterHistoryEviction(addNewEntry: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 9 {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)
+ await model.refresh()
+ await model.loadMore()
+ await model.loadMore()
+ #expect(model.entries.first?.detail == "entry-5")
+ if addNewEntry {
+ storage.recordFailure(message: "latest")
+ }
+ await model.refresh()
+ #expect(model.entries.first?.detail == "entry-5")
+ await model.resumeFollowingLatest()
+ #expect(model.entries.first?.detail == (addNewEntry ? "latest" : "entry-8"))
+ #expect(model.entries.count == 3)
+ #expect(model.hasMore)
+ #expect(model.totalCount == (addNewEntry ? 10 : 9))
+ #expect(!model.isLoading)
+ #expect(model.errorMessage == nil)
+
+ storage.recordFailure(message: "following again")
+ await model.refresh()
+ #expect(model.entries.first?.detail == "following again")
+ #expect(model.entries.count == 4)
+ await model.loadMore()
+ #expect(model.entries.count == 6)
+ #expect(Set(model.entries.map(\.id)).count == 6)
+ }
+
+ @Test func returningToTopPreservesHistoryWhenLatestIsStillLoaded() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ for index in 0 ..< 9 {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)
+ await model.refresh()
+ await model.loadMore()
+ let entries = model.entries
+ model.pauseFollowingLatest()
+ await model.resumeFollowingLatest()
+ #expect(model.entries == entries)
+ #expect(model.entries.count == 6)
+ #expect(model.entries.first?.detail == "entry-8")
+ }
+
+ @Test(arguments: [false, true])
+ func returningToTopWaitsForPagingAndDiscardsStoppedObservation(stopWhileWaiting: Bool) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let readGate = AppServerLogReadGate()
+ let storage = AppServerLogStore(directoryURL: directory.url, now: { readGate.now() })
+ defer { await #expect(throws: Never.self) { try await storage.close() } }
+ defer { readGate.release() }
+ for index in 0 ..< 9 {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)
+ defer { model.stop() }
+ await model.refresh()
+ await model.loadMore()
+ readGate.arm()
+ let pagination = Task { await model.loadMore() }
+ defer { pagination.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ readGate.didBlock
+ })
+ var didRequestLatest = false
+ let returnToTop = Task {
+ didRequestLatest = true
+ await model.resumeFollowingLatest()
+ }
+ defer { returnToTop.cancel() }
+ try #require(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) {
+ didRequestLatest
+ })
+ if stopWhileWaiting {
+ model.stop()
+ }
+ readGate.release()
+ await pagination.value
+ await returnToTop.value
+ #expect(!model.isLoading)
+ if stopWhileWaiting {
+ #expect(model.entries.isEmpty)
+ #expect(model.totalCount == 0)
+ } else {
+ #expect(model.entries.first?.detail == "entry-8")
+ #expect(model.entries.count == 3)
+ #expect(model.totalCount == 9)
+ }
+ }
+
@Test func changeOverflowReloadsAndHistoryWindowRemainsBounded() async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
diff --git a/Tests/App/Presentation/LogMethodFilterTests.swift b/Tests/App/Presentation/LogMethodFilterTests.swift
new file mode 100644
index 0000000..fdfb909
--- /dev/null
+++ b/Tests/App/Presentation/LogMethodFilterTests.swift
@@ -0,0 +1,21 @@
+import AppKit
+import SwiftUI
+import Testing
+
+struct LogMethodFilterTests {
+ @Test(arguments: [CGFloat(120), 320, 600], [0, 1, 8])
+ func selectionsKeepTheHeaderCompact(width: CGFloat, selectionCount: Int) throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ let model = AppServerLogViewModel(storage: storage)
+ let emptyHost = NSHostingView(rootView: LogMethodFilter(store: model).frame(width: width))
+ let emptySize = emptyHost.fittingSize
+ model.setSelectedMethods(Set((0 ..< selectionCount).map { "thread/long-method-name/\($0)" }))
+ let host = NSHostingView(rootView: LogMethodFilter(store: model).frame(width: width))
+ #expect(host.fittingSize.width == width)
+ #expect(host.fittingSize.height > 0)
+ #expect(host.fittingSize.height <= 40)
+ #expect(host.fittingSize.height == emptySize.height)
+ }
+}
diff --git a/Tests/App/Presentation/LogPaginationTriggerTests.swift b/Tests/App/Presentation/LogPaginationTriggerTests.swift
new file mode 100644
index 0000000..8598124
--- /dev/null
+++ b/Tests/App/Presentation/LogPaginationTriggerTests.swift
@@ -0,0 +1,32 @@
+import SwiftUI
+import Testing
+
+struct LogPaginationTriggerTests {
+ @Test func fastScrollLoadsOnceAndLayoutChangesCannotChainAnotherPage() {
+ let bottom = geometry(offset: 5400, contentHeight: 6000)
+ let phases: [ScrollPhase] = [.idle, .interacting, .decelerating, .idle, .idle, .animating, .idle]
+ let requests = zip(phases, phases.dropFirst()).filter {
+ LogView.shouldLoadMore(from: $0.0, to: $0.1, geometry: bottom)
+ }
+ #expect(requests.count == 1)
+ #expect(!LogView.shouldLoadMore(from: .idle, to: .idle, geometry: geometry(offset: 5400, contentHeight: 9000)))
+ #expect(LogView.shouldLoadMore(from: .interacting, to: .idle, geometry: bottom))
+ }
+
+ @Test func onlyReachingTheBottomIncludingItsInsetLoadsMore() {
+ #expect(!LogView.shouldLoadMore(from: .interacting, to: .idle, geometry: geometry(offset: 200, contentHeight: 6000)))
+ #expect(!LogView.shouldLoadMore(from: .decelerating, to: .idle, geometry: geometry(offset: 5400, contentHeight: 6000, bottomInset: 20)))
+ #expect(LogView.shouldLoadMore(from: .decelerating, to: .idle, geometry: geometry(offset: 5420, contentHeight: 6000, bottomInset: 20)))
+ #expect(!LogView.shouldLoadMore(from: .tracking, to: .idle, geometry: geometry(offset: 5400, contentHeight: 6000)))
+ #expect(LogView.shouldLoadMore(from: .interacting, to: .idle, geometry: geometry(offset: 0, contentHeight: 400)))
+ }
+
+ private func geometry(offset: CGFloat, contentHeight: CGFloat, bottomInset: CGFloat = 0) -> ScrollGeometry {
+ ScrollGeometry(
+ contentOffset: CGPoint(x: 0, y: offset),
+ contentSize: CGSize(width: 900, height: contentHeight),
+ contentInsets: EdgeInsets(top: 0, leading: 0, bottom: bottomInset, trailing: 0),
+ containerSize: CGSize(width: 900, height: 600)
+ )
+ }
+}