CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 增强实时命令摘要与活动状态展示
Boba6f95ee9cf2d
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 060f82f..4371b45 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -7,6 +7,10 @@objects = {/* Begin PBXBuildFile section */+ A91000000000000000000001 /* SwiftTreeSitter in Frameworks */ = {isa = PBXBuildFile; productRef = A91000000000000000000011 /* SwiftTreeSitter */; };+ A91000000000000000000002 /* TreeSitterBash in Frameworks */ = {isa = PBXBuildFile; productRef = A91000000000000000000012 /* TreeSitterBash */; };+ A91000000000000000000003 /* SwiftTreeSitter in Frameworks */ = {isa = PBXBuildFile; productRef = A91000000000000000000011 /* SwiftTreeSitter */; };+ A91000000000000000000004 /* TreeSitterBash in Frameworks */ = {isa = PBXBuildFile; productRef = A91000000000000000000012 /* TreeSitterBash */; };B10000000000000000000005 /* CodexBarPowerHelper in Embed CodexBar Power Helper */ = {isa = PBXBuildFile; fileRef = B10000000000000000000014 /* CodexBarPowerHelper */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };D10000000000000000000001 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };@@ -218,12 +222,16 @@C4A0FD922FD9302E000263A7 /* Frameworks */ = {isa = PBXFrameworksBuildPhase;files = (+ A91000000000000000000001 /* SwiftTreeSitter in Frameworks */,+ A91000000000000000000002 /* TreeSitterBash in Frameworks */,C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */,);};D10000000000000000000005 /* Frameworks */ = {isa = PBXFrameworksBuildPhase;files = (+ A91000000000000000000003 /* SwiftTreeSitter in Frameworks */,+ A91000000000000000000004 /* TreeSitterBash in Frameworks */,D10000000000000000000001 /* Sparkle in Frameworks */,);};@@ -315,6 +323,8 @@);name = CodexBar;packageProductDependencies = (+ A91000000000000000000011 /* SwiftTreeSitter */,+ A91000000000000000000012 /* TreeSitterBash */,C42A52F02FDACDEC004A2B53 /* Sparkle */,);productName = CodexBar;@@ -338,6 +348,8 @@);name = CodexBarTests;packageProductDependencies = (+ A91000000000000000000011 /* SwiftTreeSitter */,+ A91000000000000000000012 /* TreeSitterBash */,C42A52F02FDACDEC004A2B53 /* Sparkle */,);productName = CodexBarTests;@@ -413,6 +425,8 @@mainGroup = C4A0FD8C2FD9302E000263A7;minimizedProjectReferenceProxies = 1;packageReferences = (+ A91000000000000000000021 /* XCRemoteSwiftPackageReference "swift-tree-sitter" */,+ A91000000000000000000022 /* XCRemoteSwiftPackageReference "tree-sitter-bash" */,C42A52EF2FDACDEC004A2B53 /* XCRemoteSwiftPackageReference "Sparkle" */,);preferredProjectObjectVersion = 110;@@ -882,6 +896,22 @@/* End XCConfigurationList section *//* Begin XCRemoteSwiftPackageReference section */+ A91000000000000000000021 /* XCRemoteSwiftPackageReference "swift-tree-sitter" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/tree-sitter/swift-tree-sitter";+ requirement = {+ kind = upToNextMinorVersion;+ minimumVersion = 0.25.0;+ };+ };+ A91000000000000000000022 /* XCRemoteSwiftPackageReference "tree-sitter-bash" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/tree-sitter/tree-sitter-bash";+ requirement = {+ kind = upToNextMinorVersion;+ minimumVersion = 0.25.1;+ };+ };C42A52EF2FDACDEC004A2B53 /* XCRemoteSwiftPackageReference "Sparkle" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/sparkle-project/Sparkle";@@ -893,6 +923,16 @@/* End XCRemoteSwiftPackageReference section *//* Begin XCSwiftPackageProductDependency section */+ A91000000000000000000011 /* SwiftTreeSitter */ = {+ isa = XCSwiftPackageProductDependency;+ package = A91000000000000000000021 /* XCRemoteSwiftPackageReference "swift-tree-sitter" */;+ productName = SwiftTreeSitter;+ };+ A91000000000000000000012 /* TreeSitterBash */ = {+ isa = XCSwiftPackageProductDependency;+ package = A91000000000000000000022 /* XCRemoteSwiftPackageReference "tree-sitter-bash" */;+ productName = TreeSitterBash;+ };C42A52F02FDACDEC004A2B53 /* Sparkle */ = {isa = XCSwiftPackageProductDependency;package = C42A52EF2FDACDEC004A2B53 /* XCRemoteSwiftPackageReference "Sparkle" */;diff --git a/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 3c98e6a..39c4ccb 100644--- a/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6",+ "originHash" : "9597e8c773b91c0f4b6bc7b15d995d7d4e5a8826e1ced8fd5a49abaccb82aa5a","pins" : [{"identity" : "sparkle",@@ -9,6 +9,33 @@"revision" : "ab7d71291238df6e0492143b120c9b696a35f603","version" : "2.10.1"}+ },+ {+ "identity" : "swift-tree-sitter",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/tree-sitter/swift-tree-sitter",+ "state" : {+ "revision" : "08ef81eb8620617b55b08868126707ad72bf754f",+ "version" : "0.25.0"+ }+ },+ {+ "identity" : "tree-sitter",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/tree-sitter/tree-sitter",+ "state" : {+ "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406",+ "version" : "0.25.10"+ }+ },+ {+ "identity" : "tree-sitter-bash",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/tree-sitter/tree-sitter-bash",+ "state" : {+ "revision" : "a06c2e4415e9bc0346c6b86d401879ffb44058f7",+ "version" : "0.25.1"+ }}],"version" : 3diff --git a/CodexBar/Models/ActivityInput.swift b/CodexBar/Models/ActivityInput.swiftindex ec1a22d..a98945c 100644--- a/CodexBar/Models/ActivityInput.swift+++ b/CodexBar/Models/ActivityInput.swift@@ -121,6 +121,23 @@ nonisolated struct ActivityItem {}struct CommandAction { let type: String }+ struct CommandSummary: Equatable {+ let toolNames: [String]+ let hasMoreTools: Bool++ static func tool(_ name: String) -> Self {+ Self(toolNames: [name], hasMoreTools: false)+ }++ func appending(_ other: Self) -> Self {+ var names: [String] = []+ for name in toolNames + other.toolNames where !names.contains(name) {+ names.append(name)+ }+ return Self(toolNames: Array(names.prefix(2)), hasMoreTools: hasMoreTools || other.hasMoreTools || names.count > 2)+ }+ }+struct WebAction { var type: String? }struct AgentState { var status: String? }struct QuestionReply: Equatable {@@ -138,6 +155,7 @@ nonisolated struct ActivityItem {var model: String?var reasoningEffort: String?var commandActions: [CommandAction]?+ var commandSummary: CommandSummary?var phase: String?var action: WebAction?var success: Bool?diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 7f68d72..2341fca 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -465,6 +465,22 @@}}},+ "activity.live.action-interrupted" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ interrupted"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 已中断"+ }+ }+ }+ },"activity.live.actions-listfiles" : {"localizations" : {"en" : {@@ -881,6 +897,54 @@}}},+ "activity.live.command-completed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Command completed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "命令执行完成"+ }+ }+ }+ },+ "activity.live.command-declined" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Command execution denied"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "命令被拒绝执行"+ }+ }+ }+ },+ "activity.live.command-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Command failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "命令执行失败"+ }+ }+ }+ },"activity.live.command-listfiles" : {"localizations" : {"en" : {@@ -1073,6 +1137,23 @@}}},+ "activity.live.current-event" : {+ "extractionState" : "manual",+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Current event"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "当前事件"+ }+ }+ }+ },"activity.live.diff-updated" : {"localizations" : {"en" : {@@ -1137,6 +1218,38 @@}}},+ "activity.live.executing-named-tool" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Running %@"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在执行 %@"+ }+ }+ }+ },+ "activity.live.executing-tools" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Running %@ and other commands"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在执行 %@ 等多个命令"+ }+ }+ }+ },"activity.live.failed" : {"localizations" : {"en" : {@@ -1393,6 +1506,54 @@}}},+ "activity.live.named-command-completed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ command execution completed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 命令执行完成"+ }+ }+ }+ },+ "activity.live.named-command-declined" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Execution of %@ denied"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 命令被拒绝执行"+ }+ }+ }+ },+ "activity.live.named-command-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ command execution failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 命令执行失败"+ }+ }+ }+ },"activity.live.named-tool-completed" : {"localizations" : {"en" : {@@ -1809,6 +1970,54 @@}}},+ "activity.live.tools-completed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ and other commands completed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 等多个命令执行完成"+ }+ }+ }+ },+ "activity.live.tools-declined" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Execution of %@ and other commands denied"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 等多个命令被拒绝执行"+ }+ }+ }+ },+ "activity.live.tools-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ and other commands failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 等多个命令执行失败"+ }+ }+ }+ },"activity.live.unavailable" : {"localizations" : {"en" : {diff --git a/CodexBar/Resources/ThirdPartyLicenses.txt b/CodexBar/Resources/ThirdPartyLicenses.txtnew file mode 100644index 0000000..be4573b--- /dev/null+++ b/CodexBar/Resources/ThirdPartyLicenses.txt@@ -0,0 +1,503 @@+SwiftTreeSitter+===============++BSD 3-Clause License++Copyright (c) 2021, Chime+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+++Tree-sitter+===========++The MIT License (MIT)++Copyright (c) 2018-2024 Max Brunsfeld++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+++tree-sitter-bash+================++The MIT License (MIT)++Copyright (c) 2017 Max Brunsfeld++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+++Unicode data used by Tree-sitter+===============================++COPYRIGHT AND PERMISSION NOTICE (ICU 58 and later)++Copyright © 1991-2019 Unicode, Inc. All rights reserved.+Distributed under the Terms of Use in https://www.unicode.org/copyright.html.++Permission is hereby granted, free of charge, to any person obtaining+a copy of the Unicode data files and any associated documentation+(the "Data Files") or Unicode software and any associated documentation+(the "Software") to deal in the Data Files or Software+without restriction, including without limitation the rights to use,+copy, modify, merge, publish, distribute, and/or sell copies of+the Data Files or Software, and to permit persons to whom the Data Files+or Software are furnished to do so, provided that either+(a) this copyright and permission notice appear with all copies+of the Data Files or Software, or+(b) this copyright and permission notice appear in associated+Documentation.++THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+NONINFRINGEMENT OF THIRD PARTY RIGHTS.+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS+NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL+DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,+DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR+PERFORMANCE OF THE DATA FILES OR SOFTWARE.++Except as contained in this notice, the name of a copyright holder+shall not be used in advertising or otherwise to promote the sale,+use or other dealings in these Data Files or Software without prior+written authorization of the copyright holder.++---------------------++Third-Party Software Licenses++This section contains third-party software notices and/or additional+terms for licensed third-party software components included within ICU+libraries.++1. ICU License - ICU 1.8.1 to ICU 57.1++COPYRIGHT AND PERMISSION NOTICE++Copyright (c) 1995-2016 International Business Machines Corporation and others+All rights reserved.++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, and/or sell copies of the Software, and to permit persons+to whom the Software is furnished to do so, provided that the above+copyright notice(s) and this permission notice appear in all copies of+the Software and that both the above copyright notice(s) and this+permission notice appear in supporting documentation.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY+SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER+RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF+CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN+CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++Except as contained in this notice, the name of a copyright holder+shall not be used in advertising or otherwise to promote the sale, use+or other dealings in this Software without prior written authorization+of the copyright holder.++All trademarks and registered trademarks mentioned herein are the+property of their respective owners.++2. Chinese/Japanese Word Break Dictionary Data (cjdict.txt)++ # The Google Chrome software developed by Google is licensed under+ # the BSD license. Other software included in this distribution is+ # provided under other licenses, as set forth below.+ #+ # The BSD License+ # http://opensource.org/licenses/bsd-license.php+ # Copyright (C) 2006-2008, Google Inc.+ #+ # All rights reserved.+ #+ # Redistribution and use in source and binary forms, with or without+ # modification, are permitted provided that the following conditions are met:+ #+ # Redistributions of source code must retain the above copyright notice,+ # this list of conditions and the following disclaimer.+ # Redistributions in binary form must reproduce the above+ # copyright notice, this list of conditions and the following+ # disclaimer in the documentation and/or other materials provided with+ # the distribution.+ # Neither the name of Google Inc. nor the names of its+ # contributors may be used to endorse or promote products derived from+ # this software without specific prior written permission.+ #+ #+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR+ # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ #+ #+ # The word list in cjdict.txt are generated by combining three word lists+ # listed below with further processing for compound word breaking. The+ # frequency is generated with an iterative training against Google web+ # corpora.+ #+ # * Libtabe (Chinese)+ # - https://sourceforge.net/project/?group_id=1519+ # - Its license terms and conditions are shown below.+ #+ # * IPADIC (Japanese)+ # - http://chasen.aist-nara.ac.jp/chasen/distribution.html+ # - Its license terms and conditions are shown below.+ #+ # ---------COPYING.libtabe ---- BEGIN--------------------+ #+ # /*+ # * Copyright (c) 1999 TaBE Project.+ # * Copyright (c) 1999 Pai-Hsiang Hsiao.+ # * All rights reserved.+ # *+ # * Redistribution and use in source and binary forms, with or without+ # * modification, are permitted provided that the following conditions+ # * are met:+ # *+ # * . Redistributions of source code must retain the above copyright+ # * notice, this list of conditions and the following disclaimer.+ # * . Redistributions in binary form must reproduce the above copyright+ # * notice, this list of conditions and the following disclaimer in+ # * the documentation and/or other materials provided with the+ # * distribution.+ # * . Neither the name of the TaBE Project nor the names of its+ # * contributors may be used to endorse or promote products derived+ # * from this software without specific prior written permission.+ # *+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED+ # * OF THE POSSIBILITY OF SUCH DAMAGE.+ # */+ #+ # /*+ # * Copyright (c) 1999 Computer Systems and Communication Lab,+ # * Institute of Information Science, Academia+ # * Sinica. All rights reserved.+ # *+ # * Redistribution and use in source and binary forms, with or without+ # * modification, are permitted provided that the following conditions+ # * are met:+ # *+ # * . Redistributions of source code must retain the above copyright+ # * notice, this list of conditions and the following disclaimer.+ # * . Redistributions in binary form must reproduce the above copyright+ # * notice, this list of conditions and the following disclaimer in+ # * the documentation and/or other materials provided with the+ # * distribution.+ # * . Neither the name of the Computer Systems and Communication Lab+ # * nor the names of its contributors may be used to endorse or+ # * promote products derived from this software without specific+ # * prior written permission.+ # *+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED+ # * OF THE POSSIBILITY OF SUCH DAMAGE.+ # */+ #+ # Copyright 1996 Chih-Hao Tsai @ Beckman Institute,+ # University of Illinois+ # [email protected] http://casper.beckman.uiuc.edu/~c-tsai4+ #+ # ---------------COPYING.libtabe-----END--------------------------------+ #+ #+ # ---------------COPYING.ipadic-----BEGIN-------------------------------+ #+ # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science+ # and Technology. All Rights Reserved.+ #+ # Use, reproduction, and distribution of this software is permitted.+ # Any copy of this software, whether in its original form or modified,+ # must include both the above copyright notice and the following+ # paragraphs.+ #+ # Nara Institute of Science and Technology (NAIST),+ # the copyright holders, disclaims all warranties with regard to this+ # software, including all implied warranties of merchantability and+ # fitness, in no event shall NAIST be liable for+ # any special, indirect or consequential damages or any damages+ # whatsoever resulting from loss of use, data or profits, whether in an+ # action of contract, negligence or other tortuous action, arising out+ # of or in connection with the use or performance of this software.+ #+ # A large portion of the dictionary entries+ # originate from ICOT Free Software. The following conditions for ICOT+ # Free Software applies to the current dictionary as well.+ #+ # Each User may also freely distribute the Program, whether in its+ # original form or modified, to any third party or parties, PROVIDED+ # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear+ # on, or be attached to, the Program, which is distributed substantially+ # in the same form as set out herein and that such intended+ # distribution, if actually made, will neither violate or otherwise+ # contravene any of the laws and regulations of the countries having+ # jurisdiction over the User or the intended distribution itself.+ #+ # NO WARRANTY+ #+ # The program was produced on an experimental basis in the course of the+ # research and development conducted during the project and is provided+ # to users as so produced on an experimental basis. Accordingly, the+ # program is provided without any warranty whatsoever, whether express,+ # implied, statutory or otherwise. The term "warranty" used herein+ # includes, but is not limited to, any warranty of the quality,+ # performance, merchantability and fitness for a particular purpose of+ # the program and the nonexistence of any infringement or violation of+ # any right of any third party.+ #+ # Each user of the program will agree and understand, and be deemed to+ # have agreed and understood, that there is no warranty whatsoever for+ # the program and, accordingly, the entire risk arising from or+ # otherwise connected with the program is assumed by the user.+ #+ # Therefore, neither ICOT, the copyright holder, or any other+ # organization that participated in or was otherwise related to the+ # development of the program and their respective officials, directors,+ # officers and other employees shall be held liable for any and all+ # damages, including, without limitation, general, special, incidental+ # and consequential damages, arising out of or otherwise in connection+ # with the use or inability to use the program or any product, material+ # or result produced or otherwise obtained by using the program,+ # regardless of whether they have been advised of, or otherwise had+ # knowledge of, the possibility of such damages at any time during the+ # project or thereafter. Each user will be deemed to have agreed to the+ # foregoing by his or her commencement of use of the program. The term+ # "use" as used herein includes, but is not limited to, the use,+ # modification, copying and distribution of the program and the+ # production of secondary products from the program.+ #+ # In the case where the program, whether in its original form or+ # modified, was distributed or delivered to or received by a user from+ # any person, organization or entity other than ICOT, unless it makes or+ # grants independently of ICOT any specific warranty to the user in+ # writing, such person, organization or entity, will also be exempted+ # from and not be held liable to the user for any such damages as noted+ # above as far as the program is concerned.+ #+ # ---------------COPYING.ipadic-----END----------------------------------++3. Lao Word Break Dictionary Data (laodict.txt)++ # Copyright (c) 2013 International Business Machines Corporation+ # and others. All Rights Reserved.+ #+ # Project: http://code.google.com/p/lao-dictionary/+ # Dictionary: http://lao-dictionary.googlecode.com/git/Lao-Dictionary.txt+ # License: http://lao-dictionary.googlecode.com/git/Lao-Dictionary-LICENSE.txt+ # (copied below)+ #+ # This file is derived from the above dictionary, with slight+ # modifications.+ # ----------------------------------------------------------------------+ # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell.+ # All rights reserved.+ #+ # Redistribution and use in source and binary forms, with or without+ # modification,+ # are permitted provided that the following conditions are met:+ #+ #+ # Redistributions of source code must retain the above copyright notice, this+ # list of conditions and the following disclaimer. Redistributions in+ # binary form must reproduce the above copyright notice, this list of+ # conditions and the following disclaimer in the documentation and/or+ # other materials provided with the distribution.+ #+ #+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,+ # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+ # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+ # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED+ # OF THE POSSIBILITY OF SUCH DAMAGE.+ # --------------------------------------------------------------------------++4. Burmese Word Break Dictionary Data (burmesedict.txt)++ # Copyright (c) 2014 International Business Machines Corporation+ # and others. All Rights Reserved.+ #+ # This list is part of a project hosted at:+ # github.com/kanyawtech/myanmar-karen-word-lists+ #+ # --------------------------------------------------------------------------+ # Copyright (c) 2013, LeRoy Benjamin Sharon+ # All rights reserved.+ #+ # Redistribution and use in source and binary forms, with or without+ # modification, are permitted provided that the following conditions+ # are met: Redistributions of source code must retain the above+ # copyright notice, this list of conditions and the following+ # disclaimer. Redistributions in binary form must reproduce the+ # above copyright notice, this list of conditions and the following+ # disclaimer in the documentation and/or other materials provided+ # with the distribution.+ #+ # Neither the name Myanmar Karen Word Lists, nor the names of its+ # contributors may be used to endorse or promote products derived+ # from this software without specific prior written permission.+ #+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS+ # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED+ # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF+ # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF+ # SUCH DAMAGE.+ # --------------------------------------------------------------------------++5. Time Zone Database++ ICU uses the public domain data and code derived from Time Zone+Database for its time zone support. The ownership of the TZ database+is explained in BCP 175: Procedure for Maintaining the Time Zone+Database section 7.++ # 7. Database Ownership+ #+ # The TZ database itself is not an IETF Contribution or an IETF+ # document. Rather it is a pre-existing and regularly updated work+ # that is in the public domain, and is intended to remain in the+ # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do+ # not apply to the TZ Database or contributions that individuals make+ # to it. Should any claims be made and substantiated against the TZ+ # Database, the organization that is providing the IANA+ # Considerations defined in this RFC, under the memorandum of+ # understanding with the IETF, currently ICANN, may act in accordance+ # with all competent court orders. No ownership claims will be made+ # by ICANN or the IETF Trust on the database or the code. Any person+ # making a contribution to the database or code waives all rights to+ # future claims in that contribution or in the TZ Database.++6. Google double-conversion++Copyright 2006-2011, the V8 project authors. All rights reserved.+Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are+met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.+ * Neither the name of Google Inc. nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/CodexBar/Services/Activity/ActivityCommandParser.swift b/CodexBar/Services/Activity/ActivityCommandParser.swiftnew file mode 100644index 0000000..9d1a95b--- /dev/null+++ b/CodexBar/Services/Activity/ActivityCommandParser.swift@@ -0,0 +1,209 @@+import Foundation+import SwiftTreeSitter+import TreeSitterBash++/// 只生成实时展示摘要, 不展开变量或执行命令+nonisolated enum ActivityCommandParser {+ static func summarize(_ commands: [String]) -> ActivityItem.CommandSummary? {+ guard !commands.isEmpty, commands.count <= 32,+ commands.reduce(0, { $0 + $1.utf8.count }) <= 128 * 1024,+ var scan = Scan() else { return nil }+ var result: ActivityItem.CommandSummary?+ for command in commands {+ guard let summary = scan.parse(command) else { return nil }+ result = result?.appending(summary) ?? summary+ }+ return result+ }++ private struct Scan {+ let parser: Parser+ let deadline = ContinuousClock.now.advanced(by: .milliseconds(50))+ var remainingNodes = 8192++ init?() {+ parser = Parser()+ guard (try? parser.setLanguage(Language(language: tree_sitter_bash()))) != nil else { return nil }+ parser.timeout = 0.01+ }++ mutating func parse(_ source: String, depth: Int = 0) -> ActivityItem.CommandSummary? {+ guard depth < 4, ContinuousClock.now < deadline,+ let tree = parser.parse(source), let root = tree.rootNode, !root.hasError else { return nil }+ var pending = [root]+ var result: ActivityItem.CommandSummary?+ while let node = pending.popLast() {+ guard consumeBudget() else { return nil }+ switch node.nodeType {+ case "program", "list", "pipeline":+ pending.append(contentsOf: children(node).reversed())+ case "redirected_statement":+ guard !containsDynamicExecution(node), let body = node.child(byFieldName: "body") else { return nil }+ pending.append(body)+ case "command":+ guard !containsDynamicExecution(node), let nameNode = node.child(byFieldName: "name")?.namedChild(at: 0),+ let name = literal(nameNode, source: source) else { return nil }+ let arguments = (0 ..< node.childCount).compactMap { index -> Node? in+ node.fieldNameForChild(at: index) == "argument" ? node.child(at: index) : nil+ }.map { literal($0, source: source) }+ guard let summary = summarizeInvocation([name] + arguments, depth: depth) else { return nil }+ result = result?.appending(summary) ?? summary+ case "variable_assignment":+ guard !containsDynamicExecution(node) else { return nil }+ case "comment": break+ default: return nil+ }+ }+ return result+ }++ private mutating func consumeBudget() -> Bool {+ remainingNodes -= 1+ return remainingNodes >= 0 && ContinuousClock.now < deadline+ }++ private mutating func containsDynamicExecution(_ root: Node) -> Bool {+ var pending = [root]+ while let node = pending.popLast() {+ guard consumeBudget() else { return true }+ if ["command_substitution", "process_substitution"].contains(node.nodeType) {+ return true+ }+ pending.append(contentsOf: children(node))+ }+ return false+ }++ private func children(_ node: Node) -> [Node] {+ (0 ..< node.namedChildCount).compactMap { node.namedChild(at: $0) }+ }++ private mutating func summarizeInvocation(_ words: [String?], depth: Int) -> ActivityItem.CommandSummary? {+ guard depth < 4, let rawName = words.first ?? nil, let name = toolName(rawName) else { return nil }+ let arguments = Array(words.dropFirst())+ switch name {+ case "env":+ guard let index = envCommandIndex(arguments), arguments.indices.contains(index) else { return .tool(name) }+ return summarizeInvocation(Array(arguments[index...]), depth: depth + 1)+ case "xcrun":+ guard let index = xcrunCommandIndex(arguments), arguments.indices.contains(index) else { return .tool(name) }+ return summarizeInvocation(Array(arguments[index...]), depth: depth + 1)+ case "bash", "sh", "zsh":+ for (index, argument) in arguments.enumerated() {+ guard let argument else { return nil }+ if ["-c", "-lc", "-cl"].contains(argument) {+ guard arguments.indices.contains(index + 1), let script = arguments[index + 1] else { return nil }+ return parse(script, depth: depth + 1)+ }+ if !["-l", "-e", "-u", "-x", "-f", "--noprofile", "--norc"].contains(argument) {+ break+ }+ }+ return .tool(name)+ default: return .tool(name)+ }+ }++ private func envCommandIndex(_ arguments: [String?]) -> Int? {+ var index = 0+ while index < arguments.count {+ guard let argument = arguments[index] else { return index }+ if argument == "--" {+ return index + 1+ }+ if ["-i", "--ignore-environment", "-"].contains(argument) {+ index += 1+ } else if ["-u", "--unset"].contains(argument) {+ guard arguments.indices.contains(index + 1), arguments[index + 1] != nil else { return nil }+ index += 2+ } else if argument.hasPrefix("--unset=") || (argument.hasPrefix("-u") && argument.count > 2) || isAssignment(argument) {+ index += 1+ } else {+ return argument.hasPrefix("-") ? nil : index+ }+ }+ return index+ }++ private func xcrunCommandIndex(_ arguments: [String?]) -> Int? {+ var index = 0+ while index < arguments.count {+ guard let argument = arguments[index] else { return index }+ if argument == "--" {+ return index + 1+ }+ if ["-r", "--run", "-v", "--verbose", "-l", "--log", "-n", "--no-cache", "-k", "--kill-cache"].contains(argument) {+ index += 1+ } else if ["--sdk", "-sdk", "--toolchain", "-toolchain"].contains(argument) {+ guard arguments.indices.contains(index + 1), arguments[index + 1] != nil else { return nil }+ index += 2+ } else {+ return argument.hasPrefix("-") ? nil : index+ }+ }+ return index+ }+ }++ private static func toolName(_ value: String) -> String? {+ let name = (value as NSString).lastPathComponent+ guard !name.isEmpty, ![".", "..", "/"].contains(name), name.count <= 160,+ name.rangeOfCharacter(from: .controlCharacters.union(.newlines)) == nil else { return nil }+ return name+ }++ private static func isAssignment(_ value: String) -> Bool {+ guard let equal = value.firstIndex(of: "=") else { return false }+ let name = value[..<equal]+ return !name.isEmpty && name.utf8.enumerated().allSatisfy { index, byte in+ byte == 95 || (65 ... 90).contains(byte) || (97 ... 122).contains(byte) || (index > 0 && (48 ... 57).contains(byte))+ }+ }++ private static func literal(_ node: Node, source: String, depth: Int = 0) -> String? {+ guard depth < 16, let range = Range(node.range, in: source) else { return nil }+ let text = String(source[range])+ switch node.nodeType {+ case "word", "number":+ return unescape(text, quoted: false)+ case "raw_string":+ guard text.hasPrefix("'"), text.hasSuffix("'"), text.count >= 2 else { return nil }+ return String(text.dropFirst().dropLast())+ case "string":+ guard (0 ..< node.namedChildCount).allSatisfy({ node.namedChild(at: $0)?.nodeType == "string_content" }),+ text.hasPrefix("\""), text.hasSuffix("\""), text.count >= 2 else { return nil }+ return unescape(String(text.dropFirst().dropLast()), quoted: true)+ case "concatenation":+ var result = ""+ for index in 0 ..< node.namedChildCount {+ guard let child = node.namedChild(at: index), let part = literal(child, source: source, depth: depth + 1) else { return nil }+ result += part+ }+ return result+ default: return nil+ }+ }++ private static func unescape(_ text: String, quoted: Bool) -> String? {+ var result = ""+ var characters = text.makeIterator()+ while let character = characters.next() {+ if character == "\\" {+ guard let escaped = characters.next() else { return nil }+ if escaped == "\n" {+ continue+ }+ if quoted, !"$`\"\\".contains(escaped) {+ result.append("\\")+ }+ result.append(escaped)+ } else {+ if !quoted, "{}*?[]~^#$`".contains(character) || (result.isEmpty && character == "=") {+ return nil+ }+ result.append(character)+ }+ }+ return result+ }+}diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swiftindex 447ac61..69242af 100644--- a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift@@ -10,14 +10,32 @@ nonisolated extension ActivityLiveLabel {return String(localized: "activity.live.action-failed", defaultValue: "\(detail)")case "action-declined":return String(localized: "activity.live.action-declined", defaultValue: "\(detail)")+ case "action-interrupted":+ return String(localized: "activity.live.action-interrupted", defaultValue: "\(detail)")case "tool-completed":return String(localized: "activity.live.named-tool-completed", defaultValue: "\(detail)")case "tool-failed":return String(localized: "activity.live.named-tool-failed", defaultValue: "\(detail)")case "tool-declined":return String(localized: "activity.live.named-tool-declined", defaultValue: "\(detail)")+ case "command-completed":+ return String(localized: "activity.live.named-command-completed", defaultValue: "\(detail)")+ case "command-failed":+ return String(localized: "activity.live.named-command-failed", defaultValue: "\(detail)")+ case "command-declined":+ return String(localized: "activity.live.named-command-declined", defaultValue: "\(detail)")case "calling-tool":return String(localized: "activity.live.calling-named-tool", defaultValue: "\(detail)")+ case "executing-tool":+ return String(localized: "activity.live.executing-named-tool", defaultValue: "\(detail)")+ case "executing-tools":+ return String(localized: "activity.live.executing-tools", defaultValue: "\(detail)")+ case "tools-completed":+ return String(localized: "activity.live.tools-completed", defaultValue: "\(detail)")+ case "tools-declined":+ return String(localized: "activity.live.tools-declined", defaultValue: "\(detail)")+ case "tools-failed":+ return String(localized: "activity.live.tools-failed", defaultValue: "\(detail)")case "command":return String(localized: "activity.live.command-with-actions", defaultValue: "\(detail)")case "model-changed":@@ -80,6 +98,14 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.calling-tool")case "command":String(localized: "activity.live.command")+ case "command-completed", "tools-completed":+ String(localized: "activity.live.command-completed")+ case "command-declined", "tools-declined":+ String(localized: "activity.live.command-declined")+ case "command-failed", "tools-failed":+ String(localized: "activity.live.command-failed")+ case "executing-tool", "executing-tools":+ String(localized: "activity.live.command")case "command-listfiles":String(localized: "activity.live.command-listfiles")case "command-listfiles-search":@@ -136,7 +162,7 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.image-declined")case "image-failed":String(localized: "activity.live.image-failed")- case "interrupted":+ case "interrupted", "action-interrupted":String(localized: "activity.live.interrupted")case "model-changed":String(localized: "activity.live.model-changed")diff --git a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swiftindex 5f4f0bb..ea5458a 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift@@ -27,7 +27,10 @@ nonisolated extension ActivityItem {private var commandLabel: ActivityLiveLabel {let types = Set((commandActions ?? []).map(\.type))let actions = orderedCommandActions- guard !actions.isEmpty else { return ActivityLiveLabel("command") }+ guard !actions.isEmpty else {+ guard let commandSummary else { return ActivityLiveLabel("command") }+ return ActivityLiveLabel(commandSummary.hasMoreTools ? "executing-tools" : "executing-tool", detail: commandToolNames)+ }let key = "command-" + actions.map { $0.lowercased() }.joined(separator: "-")if types.isSubset(of: Set(actions)) {return ActivityLiveLabel(key)@@ -43,6 +46,10 @@ nonisolated extension ActivityItem {ActivityDisplayFormat.commandActionText((commandActions ?? []).map(\.type))}+ private var commandToolNames: String? {+ commandSummary?.toolNames.joined(separator: ", ")+ }+private var webLabel: String {switch action?.type {case "search": "searching-web"@@ -60,6 +67,10 @@ nonisolated extension ActivityItem {if type == .contextCompaction {return ActivityLiveLabel("compaction-completed")}+ if type == .collabAgentToolCall, status == "interrupted" {+ // 中断描述本次协作调用, 子 Agent 的状态快照不能覆盖它+ return ActivityLiveLabel("action-interrupted", detail: String(localized: ActivityDisplayFormat.agentAction(tool: tool).action))+ }if type == .collabAgentToolCall, agentsStates?.values.contains(where: { $0.status == "errored" }) == true {return ActivityLiveLabel("agent-failed")}@@ -75,6 +86,10 @@ nonisolated extension ActivityItem {} else {return nil}+ if type == .commandExecution, orderedCommandActions.isEmpty {+ guard let commandSummary else { return ActivityLiveLabel("command-" + outcome) }+ return ActivityLiveLabel((commandSummary.hasMoreTools ? "tools-" : "command-") + outcome, detail: commandToolNames)+ }let detail = switch type {case .commandExecution: commandActionDetailcase .collabAgentToolCall: String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swiftindex 48499c0..b5d7122 100644--- a/CodexBar/Services/Activity/AppServerActivityModels.swift+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift@@ -116,8 +116,23 @@ private nonisolated struct WireActivityTurn: Decodable {}private nonisolated struct WireActivityItem: Decodable {+ private enum CodingKeys: String, CodingKey {+ case id, type, status, tool, server, agentThreadId, kind, model, reasoningEffort+ case commandActions, phase, action, success, agentsStates, delivery, questions, content+ }++ private enum CommandActionCodingKeys: String, CodingKey { case type, command }+struct CommandAction: Decodable {let type: String+ var command: String?++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CommandActionCodingKeys.self)+ type = try container.decode(String.self, forKey: .type)+ // 展示字段异常不能影响已有的活动分类和生命周期+ command = try? container.decodeIfPresent(String.self, forKey: .command)+ }}let id: String@@ -138,6 +153,28 @@ private nonisolated struct WireActivityItem: Decodable {var questions: [Question]?var content: [Content]?+ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ id = try container.decode(String.self, forKey: .id)+ type = try container.decode(String.self, forKey: .type)+ status = try container.decodeIfPresent(String.self, forKey: .status)+ tool = try container.decodeIfPresent(String.self, forKey: .tool)+ server = try container.decodeIfPresent(String.self, forKey: .server)+ agentThreadId = try container.decodeIfPresent(String.self, forKey: .agentThreadId)+ kind = try container.decodeIfPresent(String.self, forKey: .kind)+ model = try container.decodeIfPresent(String.self, forKey: .model)+ reasoningEffort = try container.decodeIfPresent(String.self, forKey: .reasoningEffort)+ commandActions = try container.decodeIfPresent([CommandAction].self, forKey: .commandActions)+ phase = try container.decodeIfPresent(String.self, forKey: .phase)+ action = try container.decodeIfPresent(WebAction.self, forKey: .action)+ success = try container.decodeIfPresent(Bool.self, forKey: .success)+ agentsStates = try container.decodeIfPresent([String: AgentState].self, forKey: .agentsStates)+ delivery = try container.decodeIfPresent(String.self, forKey: .delivery)+ questions = try container.decodeIfPresent([Question].self, forKey: .questions)+ // 同名 content 字段随事件类型改变结构, 这里只读取用户消息中的问题回复+ content = type == "userMessage" ? try container.decodeIfPresent([Content].self, forKey: .content) : nil+ }+struct WebAction: Decodable { var type: String? }struct AgentState: Decodable { var status: String? }struct Question: Decodable { let title: String }@@ -367,6 +404,7 @@ private nonisolated extension WireActivityItem {model: model,reasoningEffort: reasoningEffort,commandActions: commandActions?.map { .init(type: $0.type) },+ commandSummary: commandSummary,phase: phase,action: action.map { .init(type: $0.type) },success: success,@@ -376,6 +414,13 @@ private nonisolated extension WireActivityItem {)}+ private var commandSummary: ActivityItem.CommandSummary? {+ guard type == "commandExecution", let commandActions, !commandActions.isEmpty,+ !commandActions.contains(where: { ["read", "listFiles", "search"].contains($0.type) }),+ commandActions.allSatisfy({ $0.command != nil }) else { return nil }+ return ActivityCommandParser.summarize(commandActions.compactMap(\.command))+ }+private var questionReplies: [ActivityItem.QuestionReply]? {guard type == "userMessage" else { return nil }let opening = "<send_user_message_question_reply>"diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftindex fdd2df8..a1b00c6 100644--- a/CodexBar/Services/Activity/AppServerActivityReader.swift+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -119,9 +119,7 @@ actor AppServerActivityReader {private var preparingThread: String?private var invalidThreads = Set<String>()private var storageRetryAfter = Date.distantPast- private var storageFailed = falseprivate var isHistoryRecordingPaused = false- private var tokenUsageRefreshFailed = falseprivate var tokenUsageRetryAfter = Date.distantPastprivate let maximumPendingEvents: Intprivate let maximumPendingBytes: Int@@ -803,7 +801,7 @@ actor AppServerActivityReader {while isRunning, generation == current, !Task.isCancelled {do {try acquireTokenUsageWriter(generation: current)- _ = await retryStorage()+ await retryStorage()try checkGeneration(current)await refreshTokenUsageHistory(generation: current)try await Task.sleep(for: .milliseconds(100))@@ -869,17 +867,15 @@ actor AppServerActivityReader {do {_ = try await refresh.valueguard generation == current, isRunning, !Task.isCancelled else { return }- tokenUsageRefreshFailed = falsetokenUsageRetryAfter = .distantPastlastTokenUsageRefresh = Date()} catch is CancellationError {return} catch {guard generation == current, isRunning else { return }- if !tokenUsageRefreshFailed {+ if tokenUsageRetryAfter == .distantPast {logStorage?.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")}- tokenUsageRefreshFailed = truetokenUsageRetryAfter = Date().addingTimeInterval(1)}}@@ -984,28 +980,24 @@ actor AppServerActivityReader {}}- private func retryStorage() async -> Bool {- guard Date() >= storageRetryAfter else { return false }+ private func retryStorage() async {+ guard Date() >= storageRetryAfter else { return }do {try await persistPending()- storageFailed = falsestorageRetryAfter = .distantPastif isHistoryRecordingPaused, pendingEvents.isEmpty, pendingSamples.isEmpty, isRunning, !Task.isCancelled {isHistoryRecordingPaused = falsereducer.setTokenUsageRecordingEnabled(isTokenUsageWriter)}- return true} catch {recordStorageFailure(error)- return false}}private func recordStorageFailure(_ error: Error) {- if !storageFailed {+ if storageRetryAfter == .distantPast {logStorage?.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")}- storageFailed = truestorageRetryAfter = Date().addingTimeInterval(1)}diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex eca7933..6951e8f 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -39,7 +39,6 @@ struct ActivityCard: View {guard snapshot.hasTaskCenterContent || showsUnavailableState else { return nil }var value = content(at: timelineDate)value.showsKeepAliveBadge = showsKeepAliveBadge- value.statusTextEffect = statusTextEffectreturn value}@@ -152,12 +151,20 @@ struct ActivityCard: View {statusHeader(content)if let detail = content.detail {- ActivityStatusText(- text: detail, tint: content.tint, effect: allowsAnimations ? content.statusTextEffect : .none,- lineLimit: nil, supplement: content.detailSupplement- )+ HStack(alignment: .firstTextBaseline, spacing: 0) {+ if content.showsCurrentEvent {+ Text(verbatim: String(localized: "activity.live.current-event") + ": ")+ .foregroundStyle(Color.codexSecondaryLabel)+ .fixedSize()+ }+ ActivityStatusText(+ text: detail, tint: content.tint, effect: allowsAnimations ? content.statusTextEffect : .none,+ lineLimit: nil, supplement: content.detailSupplement+ )+ .numericTransition(value: [detail, content.detailSupplement])+ .fixedSize(horizontal: false, vertical: true)+ }.font(MenuMetrics.bodyFont)- .numericTransition(value: [detail, content.detailSupplement]).fixedSize(horizontal: false, vertical: true).clipped()}@@ -370,7 +377,9 @@ struct ActivityCard: View {ActivityDisplayFormat.modelMetadata(modelName: task.modelName, effort: task.effort)].compactMap(\.self) + summary.prefix(1),recent: ActivityDisplayFormat.recentEvent(for: task),- detailSupplement: summary.dropFirst().first+ detailSupplement: summary.dropFirst().first,+ showsCurrentEvent: true,+ statusTextEffect: allowsAnimations ? (waiting ? .ionizing(taskID: task.id) : .shimmer) : .none)}@@ -378,15 +387,6 @@ struct ActivityCard: View {max(0, snapshot.activeCount - 1)}- private var statusTextEffect: ActivityStatusText.Effect {- guard allowsAnimations else { return .none }- switch snapshot.panelPrimaryActivity {- case .running: return .shimmer- case let .waiting(task): return .ionizing(taskID: task.id)- case .completed, .terminated, .idle: return .none- }- }-private enum Metrics {// 单行排版为时间文案增长预留宽度static let headerWidthReserve: CGFloat = 32@@ -427,6 +427,7 @@ private struct ActivityCardContent: Equatable {let header: [String]var recent: String?var detailSupplement: String?+ var showsCurrentEvent = falsevar showsKeepAliveBadge = falsevar statusTextEffect = ActivityStatusText.Effect.nonediff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftindex 2a5b2c8..f68aa0e 100644--- a/CodexBar/Views/Settings/CodexVersionSection.swift+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -19,7 +19,6 @@ struct CodexVersionSection: View {.foregroundStyle(.tint)Text("settings.codex.version.title")- .font(SettingsRowMetrics.titleFont)reconnectButton@@ -67,7 +66,7 @@ struct CodexVersionSection: View {icon.symbolEffect(.wiggle.clockwise.byLayer, options: .repeat(.continuous))}}- .frame(width: SettingsRowMetrics.optionsButtonSize, height: SettingsRowMetrics.optionsButtonSize)+ .imageScale(.small).contentShape(Rectangle())}.buttonStyle(.plain)@@ -82,14 +81,15 @@ struct CodexVersionSection: View {}private var daemonRow: some View {- HStack(alignment: .top, spacing: 10) {- Image(systemName: "cpu")- .frame(width: Metrics.iconWidth)- .foregroundStyle(.tint)- Text("settings.codex.daemon.title")- .foregroundStyle(.secondary)- Spacer(minLength: 28)- VStack(alignment: .trailing, spacing: 3) {+ VStack(alignment: .trailing, spacing: 3) {+ HStack(alignment: .top, spacing: Metrics.controlSpacing) {+ Image(systemName: "cpu")+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tint)+ Text("settings.codex.daemon.title")+ .foregroundStyle(.secondary)+ Spacer(minLength: 28)+if let info = connectionInfo {HStack(spacing: 12) {Text("settings.codex.daemon.in-use")@@ -104,48 +104,51 @@ struct CodexVersionSection: View {.foregroundStyle(Color.codexSecondaryLabel).numericTransition(value: info.version)}- CopyablePathText(path: info.socketPath, isCopied: copiedPathResetTasks["shared"] != nil)- .onTapGesture { copyPathToPasteboard(info.socketPath, key: "shared") }} else {Text("settings.codex.daemon.disconnected").foregroundStyle(.secondary)}}- .frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)++ if let info = connectionInfo {+ CopyablePathText(path: info.socketPath, isCopied: copiedPathResetTasks["shared"] != nil)+ .padding(.leading, Metrics.iconWidth + Metrics.controlSpacing)+ .onTapGesture { copyPathToPasteboard(info.socketPath, key: "shared") }+ }}}private func codexVersionRow(icon: String, item: CodexVersionItem) -> some View {let hasVersion = item.version != nil- return HStack(alignment: .top, spacing: 10) {- Image(systemName: icon)- .frame(width: Metrics.iconWidth)- .foregroundStyle(.tint)+ return VStack(alignment: .trailing, spacing: 3) {+ HStack(alignment: .top, spacing: Metrics.controlSpacing) {+ Image(systemName: icon)+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tint)- Text(item.source.displayName)- .foregroundStyle(.secondary)+ Text(item.source.displayName)+ .foregroundStyle(.secondary)- Spacer(minLength: 28)+ Spacer(minLength: 28)- VStack(alignment: .trailing, spacing: 3) {Text(item.displayVersion).font(hasVersion ? SettingsRowMetrics.bodyFont.monospacedDigit() : SettingsRowMetrics.bodyFont).foregroundStyle(Color(nsColor: hasVersion ? .secondaryLabelColor : .tertiaryLabelColor)).lineLimit(1).numericTransition(value: item.displayVersion)+ }- if let path = item.path {- CopyablePathText(path: path, isCopied: copiedPathResetTasks[item.source.rawValue] != nil)- .onTapGesture {- copyPathToPasteboard(path, key: item.source.rawValue)- }- .transition(.opacity)- }+ if let path = item.path {+ CopyablePathText(path: path, isCopied: copiedPathResetTasks[item.source.rawValue] != nil)+ .padding(.leading, Metrics.iconWidth + Metrics.controlSpacing)+ .onTapGesture {+ copyPathToPasteboard(path, key: item.source.rawValue)+ }+ .transition(.opacity)}- .frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)- .animation(Metrics.statusAnimation, value: item.path)}+ .animation(Metrics.statusAnimation, value: item.path)}private func copyPathToPasteboard(_ path: String, key: String) {@@ -163,8 +166,8 @@ struct CodexVersionSection: View {private enum Metrics {static let rowSpacing: CGFloat = 14static let iconWidth = SettingsRowMetrics.iconWidth+ static let controlSpacing: CGFloat = 10static let childIndent: CGFloat = 28- static let versionColumnWidth: CGFloat = 270static let statusAnimation = Animation.codexStatus}}diff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swiftindex b5904ea..a41e00d 100644--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift@@ -32,11 +32,8 @@ struct HotKeyRecorderRow: View {.disabled(!canStartRecording).background {HotKeyCaptureView(- isRecording: $isRecording,+ isRecording: isRecording,onCapture: captureShortcut,- onCancel: {- stopRecording()- },onWindowClose: {resetTransientState()}@@ -151,27 +148,28 @@ struct HotKeyRecorderRow: View {/// SwiftUI 到 AppKit first responder 的桥接层private struct HotKeyCaptureView: NSViewRepresentable {- @Binding var isRecording: Bool+ let isRecording: Boollet onCapture: (NSEvent) -> Void- let onCancel: () -> Voidlet onWindowClose: () -> Voidfunc makeNSView(context _: Context) -> HotKeyCaptureNSView {let view = HotKeyCaptureNSView()view.onCapture = onCapture- view.onCancel = onCancelview.onWindowClose = onWindowClosereturn view}func updateNSView(_ nsView: HotKeyCaptureNSView, context _: Context) {+ nsView.isRecording = isRecordingnsView.onCapture = onCapture- nsView.onCancel = onCancelnsView.onWindowClose = onWindowCloseif isRecording {Task { @MainActor [weak nsView] in- nsView?.window?.makeFirstResponder(nsView)+ guard let nsView, nsView.isRecording else {+ return+ }+ nsView.window?.makeFirstResponder(nsView)}} else if nsView.window?.firstResponder === nsView {nsView.window?.makeFirstResponder(nil)@@ -181,12 +179,17 @@ private struct HotKeyCaptureView: NSViewRepresentable {/// 捕获下一次按键并监听窗口关闭, 关闭时清理录制态private final class HotKeyCaptureNSView: NSView {+ var isRecording = falsevar onCapture: ((NSEvent) -> Void)?- var onCancel: (() -> Void)?var onWindowClose: (() -> Void)?override var acceptsFirstResponder: Bool {- true+ isRecording+ }++ /// 隐藏控件只由录制操作获取焦点, 不参与 Tab 导航+ override var canBecomeKeyView: Bool {+ false}override func viewDidMoveToWindow() {@@ -195,11 +198,12 @@ private final class HotKeyCaptureNSView: NSView {}override func keyDown(with event: NSEvent) {- if event.keyCode == UInt16(kVK_Escape) {- onCancel?()- } else {- onCapture?(event)+ guard isRecording else {+ super.keyDown(with: event)+ return}++ onCapture?(event)}private func updateWindowCloseObserver() {diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex 7e408fe..affd830 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 5.0.8-CURRENT_PROJECT_VERSION = 208+MARKETING_VERSION = 5.1.0+CURRENT_PROJECT_VERSION = 209diff --git a/Scripts/build.sh b/Scripts/build.shindex df7b27a..caa7e6f 100755--- a/Scripts/build.sh+++ b/Scripts/build.sh@@ -1,6 +1,9 @@#!/usr/bin/env bashset -euo pipefail+# 避免外部编译器干扰 Xcode 工具链+unset CC CXX+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"diff --git a/Tests/App/Activity/ActivityCommandParserTests.swift b/Tests/App/Activity/ActivityCommandParserTests.swiftnew file mode 100644index 0000000..d5075be--- /dev/null+++ b/Tests/App/Activity/ActivityCommandParserTests.swift@@ -0,0 +1,121 @@+import Foundation+import Testing++struct ActivityCommandParserTests {+ @Test(arguments: [+ ("git status", "git"),+ ("python3 - <<'PY'\nprint('pwd; git status')\nPY", "python3"),+ ("NAME=value lark-cli auth status", "lark-cli"),+ ("NAME=value; git status", "git"),+ ("env -u CC -u CXX xcodebuild build", "xcodebuild"),+ ("env -i NAME=value python3 script.py", "python3"),+ ("env --unset=CC -- python3 script.py", "python3"),+ ("env -uCC python3 script.py", "python3"),+ ("xcrun swiftc -version", "swiftc"),+ ("xcrun --sdk macosx --toolchain default swiftc -version", "swiftc"),+ ("xcrun --find swiftc", "xcrun"),+ ("xcrun --show-sdk-path", "xcrun"),+ ("command -v python3", "command"),+ (".venv/bin/python script.py", "python"),+ ("'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --version", "Google Chrome"),+ ("\"/应用/测试 工具\" --version", "测试 工具"),+ ("/应用/测试\\ 工具 --version", "测试 工具"),+ ("'py'\"thon\"3 script.py", "python3"),+ ("echo 'a;b && c | d'", "echo"),+ ("git status > /tmp/output", "git"),+ ("git -C \"$DIRECTORY\" status", "git"),+ ("# setup\ngit status\n# done", "git"),+ ("/bin/zsh -lc 'python3 script.py'", "python3"),+ ("env -u CC /bin/bash -c 'git status'", "git")+ ])+ func extractsLiteralToolWithoutExecuting(source: String, name: String) {+ #expect(ActivityCommandParser.summarize([source]) == .tool(name))+ }++ @Test(arguments: [+ ("pwd; git status", ["pwd", "git"]), ("pwd\ngit status", ["pwd", "git"]),+ ("pwd && git status", ["pwd", "git"]), ("pwd || git status", ["pwd", "git"]),+ ("git status | wc -l", ["git", "wc"]), ("git status; git diff", ["git"]),+ ("sed -n 1p a; sed -n 2p a; sed -n 3p a", ["sed"]),+ ("/usr/bin/sed -n 1p a; sed -n 2p a", ["sed"]),+ ("git status; git diff; ls", ["git", "ls"]),+ ("git status; ls; git diff; ls -a", ["git", "ls"]),+ ("git status; bash -lc 'git diff; git status; ls'; git log", ["git", "ls"]),+ ("pwd & git status", ["pwd", "git"]),+ ("python3 - <<'PY'\nprint(1)\nPY\ngit status", ["python3", "git"]),+ ("bash -lc 'pwd; git status'", ["pwd", "git"]),+ ("env -u CC zsh -c 'pwd && git status'", ["pwd", "git"])+ ])+ func upToTwoDistinctCommandsPreserveSourceOrder(source: String, names: [String]) {+ #expect(ActivityCommandParser.summarize([source]) == .init(toolNames: names, hasMoreTools: false))+ }++ @Test(arguments: [+ ("git status; ls; pwd", ["git", "ls"]),+ ("git status && ls || pwd", ["git", "ls"]),+ ("git status | wc -l; ls", ["git", "wc"]),+ ("bash -lc 'git status; ls'; pwd", ["git", "ls"]),+ ("git status; bash -lc 'ls; pwd'", ["git", "ls"]),+ ("bash -lc 'git status; ls; pwd'; echo done", ["git", "ls"]),+ ("sed -n 1p a; sed -n 2p a; git status; ls", ["sed", "git"]),+ ("git status; git diff; ls; pwd", ["git", "ls"]),+ ("git status; bash -lc 'git diff; ls; pwd'", ["git", "ls"]),+ ("ls; bash -lc 'git status; ls; pwd'", ["ls", "git"]),+ ("NAME=value; git status; # comment\nls; pwd", ["git", "ls"])+ ])+ func longerSequencesKeepFirstTwoDistinctCommands(source: String, names: [String]) {+ #expect(ActivityCommandParser.summarize([source]) == .init(toolNames: names, hasMoreTools: true))+ }++ @Test(arguments: [+ "", "# comment", "NAME=value", "\"$CMD\" status", "${CMD} status", "$(printf git) status",+ "env \"$CMD\" status", "xcrun \"$CMD\"", "bash -lc \"$SCRIPT\"", "pwd; \"$CMD\" status",+ "git status; ls; pwd; \"$CMD\"", "git status; ls; python3 'unfinished",+ "sed -n 1p a; sed -n 2p a; \"$CMD\"",+ "echo \"$(git status)\"", "cat <(git status)", "cat <<EOF\n$(git status)\nEOF",+ "python3 'unfinished", "echo ${(@s:/:)PATH}", "for x in a b; do git status; done",+ "if test -f marker; then git status; fi", "f() { git status; }; f", "./tool* --version"+ ])+ func uncertainCommandsKeepGenericPresentation(_ source: String) {+ #expect(ActivityCommandParser.summarize([source]) == nil)+ }++ @Test func actionListAndResourceBounds() {+ #expect(ActivityCommandParser.summarize([]) == nil)+ #expect(ActivityCommandParser.summarize(["git status", "pwd"]) == .init(toolNames: ["git", "pwd"], hasMoreTools: false))+ #expect(ActivityCommandParser.summarize(["git status", "ls", "pwd"]) == .init(toolNames: ["git", "ls"], hasMoreTools: true))+ #expect(ActivityCommandParser.summarize(["git status; ls; pwd", "echo done"]) == .init(toolNames: ["git", "ls"], hasMoreTools: true))+ #expect(ActivityCommandParser.summarize(["sed -n 1p a", "sed -n 2p a"]) == .tool("sed"))+ #expect(ActivityCommandParser.summarize(["sed -n 1p a; sed -n 2p a", "git status; git diff"]) == .init(toolNames: ["sed", "git"], hasMoreTools: false))+ #expect(ActivityCommandParser.summarize(["git status", "git diff; ls; pwd"]) == .init(toolNames: ["git", "ls"], hasMoreTools: true))+ #expect(ActivityCommandParser.summarize(["git status", ""]) == nil)+ #expect(ActivityCommandParser.summarize(["git status", "\"$CMD\""]) == nil)+ #expect(ActivityCommandParser.summarize(["git status; ls; pwd", "\"$CMD\""]) == nil)+ #expect(ActivityCommandParser.summarize(Array(repeating: "git status", count: 33)) == nil)+ #expect(ActivityCommandParser.summarize(["echo " + String(repeating: "a", count: 128 * 1024)]) == nil)+ #expect(ActivityCommandParser.summarize([String(repeating: "true;", count: 5000)]) == nil)+ #expect(ActivityCommandParser.summarize(["env env env env git status"]) == nil)+ #expect(ActivityCommandParser.summarize(["git status"]) == .tool("git"))+ }++ @Test func paginatedItemsUseTheSameSummary() throws {+ let page = try TestFixtures.decode(ActivityItemsPage.self, #"""+ {"data":[{"turnId":"turn","item":{"id":"command","type":"commandExecution","status":"completed",+ "commandActions":[{"type":"unknown","command":"pwd; git status"}]}}]}+ """#)+ let item = try #require(page.data.first?.item)+ #expect(item.commandSummary == .init(toolNames: ["pwd", "git"], hasMoreTools: false))+ #expect(item.liveCompletionLabel == ActivityLiveLabel("command-completed", detail: "pwd, git"))+ }++ @Test(arguments: ["null", "123", "{}", "[]", "\"\""])+ func malformedCommandFieldPreservesActivity(_ value: String) throws {+ let item = try TestFixtures.decode(ActivityItem.self, """+ {"id":"cmd","type":"commandExecution","status":"completed", "commandActions":[{"type":"unknown","command":\(value)}]}+ """)+ #expect(item.commandActions?.map(\.type) == ["unknown"])+ #expect(item.commandSummary == nil)+ #expect(item.liveLabel == ActivityLiveLabel("command"))+ #expect(item.liveCompletionLabel == ActivityLiveLabel("command-completed"))+ }+}diff --git a/Tests/App/Activity/ActivityLivePresentationTests.swift b/Tests/App/Activity/ActivityLivePresentationTests.swiftindex 874f9cc..8160319 100644--- a/Tests/App/Activity/ActivityLivePresentationTests.swift+++ b/Tests/App/Activity/ActivityLivePresentationTests.swift@@ -339,7 +339,7 @@ struct ActivityLivePresentationTests {id: "cmd", type: .commandExecution, status: "failed",commandActions: actions.map { .init(type: $0) })- #expect(item.liveCompletionLabel?.key == (detailKey == nil ? "tool-failed" : "action-failed"))+ #expect(item.liveCompletionLabel?.key == (detailKey == nil ? "command-failed" : "action-failed"))#expect(item.liveCompletionLabel?.detail == detailKey.map { ActivityLiveLabel($0).text })}@@ -362,6 +362,65 @@ struct ActivityLivePresentationTests {#expect(!recent.label.text.contains(" • "))}+ struct CommandPresentationCase {+ let command: String+ let started: ActivityLiveLabel+ let completionPrefix: String+ }++ @Test(arguments: [+ CommandPresentationCase(command: "python3 - <<'PY'\nprint('test')\nPY", started: .init("executing-tool", detail: "python3"), completionPrefix: "command-"),+ CommandPresentationCase(command: "git status; ls", started: .init("executing-tool", detail: "git, ls"), completionPrefix: "command-"),+ CommandPresentationCase(command: "git status; ls; pwd", started: .init("executing-tools", detail: "git, ls"), completionPrefix: "tools-"),+ CommandPresentationCase(command: "sed -n 1p a; sed -n 2p a; sed -n 3p a", started: .init("executing-tool", detail: "sed"), completionPrefix: "command-"),+ CommandPresentationCase(command: "sed -n 1p a; sed -n 2p a; git status", started: .init("executing-tool", detail: "sed, git"), completionPrefix: "command-"),+ CommandPresentationCase(command: "sed -n 1p a; sed -n 2p a; git status; ls", started: .init("executing-tools", detail: "sed, git"), completionPrefix: "tools-"),+ CommandPresentationCase(command: "\"$CMD\" status", started: .init("command"), completionPrefix: "command-"),+ CommandPresentationCase(command: "python3 'unfinished", started: .init("command"), completionPrefix: "command-")+ ], ["completed", "failed", "declined"])+ func parsedCommandsKeepStartedProgressAndCompletedConsistent(example: CommandPresentationCase, status: String) throws {+ var item: [String: Any] = [+ "id": "cmd", "type": "commandExecution", "commandActions": [["type": "unknown", "command": example.command]]+ ]+ func fields() throws -> String {+ let data = try JSONSerialization.data(withJSONObject: ["item": item])+ let text = try #require(String(data: data, encoding: .utf8))+ return String(text.dropFirst().dropLast())+ }+ var reducer = try prepared()+ _ = try reducer.consume(message("item/started", fields()), now: now)+ #expect(try summary(reducer).current == example.started)+ _ = try reducer.consume(message("item/commandExecution/outputDelta", #""itemId":"cmd""#), now: now.addingTimeInterval(1))+ #expect(try summary(reducer).current == example.started)+ item["status"] = status+ _ = try reducer.consume(message("item/completed", fields()), now: now.addingTimeInterval(2))+ #expect(try summary(reducer).recent?.label == ActivityLiveLabel(example.completionPrefix + status, detail: example.started.detail))+ #expect(try summary(reducer).current.key == "processing")+ }++ @Test func knownCommandClassificationsTakePrecedenceOverParsing() throws {+ let item = try TestFixtures.decode(ActivityItem.self, #"""+ {"id":"cmd","type":"commandExecution","status":"completed","commandActions":[+ {"type":"read","command":"cat file"},{"type":"unknown","command":"pwd; git status"}]}+ """#)+ #expect(item.commandSummary == nil)+ #expect(item.liveLabel == ActivityLiveLabel("command", detail: ActivityLiveLabel("actions-read").text))+ #expect(item.liveCompletionLabel == ActivityLiveLabel("action-completed", detail: ActivityLiveLabel("actions-read").text))+ }++ @Test(arguments: ["git", "git, ls"])+ func parsedCommandLabelsAreLocalized(names: String) {+ #expect(ActivityLiveLabel("executing-tool", detail: "python3").text == String(localized: "activity.live.executing-named-tool", defaultValue: "\("python3")"))+ #expect(ActivityLiveLabel("executing-tool", detail: names).text == String(localized: "activity.live.executing-named-tool", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-completed", detail: names).text == String(localized: "activity.live.named-command-completed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-failed", detail: names).text == String(localized: "activity.live.named-command-failed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-declined", detail: names).text == String(localized: "activity.live.named-command-declined", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("executing-tools", detail: names).text == String(localized: "activity.live.executing-tools", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-completed", detail: names).text == String(localized: "activity.live.tools-completed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-failed", detail: names).text == String(localized: "activity.live.tools-failed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-declined", detail: names).text == String(localized: "activity.live.tools-declined", defaultValue: "\(names)"))+ }+@Test(arguments: ["mcpToolCall", "dynamicToolCall"], [nil, "server"] as [String?])func completionPreservesActualToolNames(type: String, server: String?) {let item = ActivityItem(@@ -397,7 +456,7 @@ struct ActivityLivePresentationTests {#expect(label.detail == route)}- @Test(arguments: ["tool-completed", "tool-failed", "tool-declined", "calling-tool", "command", "model-changed"])+ @Test(arguments: ["tool-completed", "tool-failed", "tool-declined", "command-completed", "command-failed", "command-declined", "calling-tool", "command", "model-changed"])func missingDetailsKeepStandaloneLabels(key: String) {#expect(ActivityLiveLabel(key).text == ActivityLiveLabel(key).localizedText)#expect(ActivityLiveLabel(key, detail: "").text == ActivityLiveLabel(key).localizedText)@@ -426,7 +485,7 @@ struct ActivityLivePresentationTests {#expect(ActivityDisplayFormat.toolActionText(itemType: item.type.rawValue, toolName: operation.tool) == item.liveCompletionLabel?.detail)}- @Test(arguments: ["completed", "failed", "declined"])+ @Test(arguments: ["completed", "failed", "declined", "interrupted"])func subagentCompletionPreservesOutcome(status: String) {let item = ActivityItem(id: "agent", type: .collabAgentToolCall, status: status, tool: "spawnAgent",@@ -436,6 +495,24 @@ struct ActivityLivePresentationTests {#expect(item.liveCompletionLabel?.detail == String(localized: "activity.action.start-subagent"))}+ @Test(arguments: ["spawnAgent", "wait", "sendInput", "future"], ["running", "errored"])+ func interruptedCollabUpdatesRecentEvent(tool: String, childStatus: String) throws {+ var reducer = try prepared()+ for (method, status) in [("item/started", "inProgress"), ("item/completed", "interrupted")] {+ _ = try reducer.consume(message(method, """+ "item":{"id":"collab","type":"collabAgentToolCall","tool":"\(tool)","status":"\(status)",+ "agentsStates":{"child":{"status":"\(childStatus)"}}}+ """), now: now)+ }+ let presentation = try summary(reducer)+ let detail = String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)+ #expect(presentation.current.key == "processing")+ #expect(presentation.toolCount == 0)+ #expect(presentation.recent?.label == ActivityLiveLabel("action-interrupted", detail: detail))+ #expect(presentation.recent?.label.text == String(localized: "activity.live.action-interrupted", defaultValue: "\(detail)"))+ #expect(ActivityItem(id: "child", type: .subAgentActivity, kind: "interrupted").liveCompletionLabel?.key == "agent-interrupted")+ }+@Test(arguments: [("commandExecution", "activity.action.command"), ("fileChange", "activity.action.edit-files"),("webSearch", "activity.action.search-web"), ("imageView", "activity.action.view-image"),diff --git a/Tests/App/Activity/ActivityRecoveryTests.swift b/Tests/App/Activity/ActivityRecoveryTests.swiftindex 55af8f8..cc63f9f 100644--- a/Tests/App/Activity/ActivityRecoveryTests.swift+++ b/Tests/App/Activity/ActivityRecoveryTests.swift@@ -2,6 +2,65 @@ import Foundationimport Testingstruct ActivityRecoveryTests {+ @Test(arguments: ["item/started", "item/completed"])+ func reasoningContentDoesNotInvalidateLivePresentation(method: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let timestamp = Date().timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ let thread: [String: Any] = ["id": "thread", "source": "cli", "createdAt": timestamp, "cwd": "/tmp", "status": ["type": "active", "activeFlags": []]]+ let read = try peer.readMessage()+ try peer.reply(to: read, result: ["thread": thread])+ let resume = try peer.readMessage()+ try peer.reply(to: resume, result: ["thread": thread])+ let turns = try peer.readMessage()+ try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])+ try peer.send(["method": method, "params": [+ "threadId": "thread", "turnId": "turn",+ "item": ["id": "reasoning", "type": "reasoning", "summary": [], "content": ["synthetic reasoning"]]+ ]])+ try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var received = false+ var failed = false+ var presentation: ActivityLiveSummary?+ let reader = AppServerActivityReader(+ probe: ActivityReaderProbe(), socketURL: server.url,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)+ ) { batch in+ if batch.phase == .live, let task = batch.graph.tasks.values.first {+ received = true+ presentation = task.snapshot.presentation+ }+ if batch.phase == .sourceUnavailable {+ failed = true+ }+ }+ await reader.start()+ for _ in 0 ..< 100 {+ if received || failed {+ break+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ await reader.stop()+ release.signal()+ try server.finish()+ #expect(received)+ #expect(!failed)+ #expect(presentation != nil)+ }+@Test(arguments: [false, true])func laterMalformedMessagePreservesEarlierValidEvent(_ malformed: Bool) async throws {let directory = try TestDirectory()diff --git a/Tests/App/Activity/AppServerActivityTests.swift b/Tests/App/Activity/AppServerActivityTests.swiftindex be34935..71d4439 100644--- a/Tests/App/Activity/AppServerActivityTests.swift+++ b/Tests/App/Activity/AppServerActivityTests.swift@@ -4,6 +4,30 @@ import Testingstruct AppServerActivityTests {private let now = TestFixtures.now+ @Test(arguments: ["item/started", "item/completed"], [[], ["synthetic reasoning"]] as [[String]])+ func reasoningContentPreservesActivity(method: String, content: [String]) throws {+ var reducer = try prepared()+ let text = try #require(String(data: JSONEncoder().encode(content), encoding: .utf8))+ let input = try message(method, params: """+ {"threadId":"main","turnId":"turn","item":{"id":"reasoning","type":"reasoning","summary":[],"content":\(text)}}+ """)+ #expect(input.params.item?.type == .reasoning)+ #expect(input.params.item?.questionReplies == nil)+ #expect(reducer.consume(input, now: now).isEmpty)+ #expect(reducer.states.values.first?.presentation?.summary.current.key == (method == "item/started" ? "thinking" : "processing"))+ }++ @Test func paginatedReasoningContentDecodes() throws {+ let page = try TestFixtures.decode(ActivityItemsPage.self, #"""+ {"data":[{"turnId":"turn","item":{"id":"reasoning","type":"reasoning","summary":[],"content":["synthetic reasoning"]}}]}+ """#)+ #expect(page.data.first?.item.type == .reasoning)+ let turn = try TestFixtures.decode(ActivityTurn.self, #"""+ {"id":"turn","status":"inProgress","items":[{"id":"reasoning","type":"reasoning","summary":[],"content":["synthetic reasoning"]}]}+ """#)+ #expect(turn.items?.first?.type == .reasoning)+ }+@Test func protocolBoundaryNormalizesStatusAndTimeUnits() throws {let input = try TestFixtures.decode(ActivityInput.self, """{"method":"turn/completed","params":{"threadId":"thread","turn":{"id":"turn","status":"completed","startedAt":1000,"completedAt":1002,"durationMs":1500}}}@@ -203,6 +227,23 @@ struct AppServerActivityTests {#expect(approval.actionText == String(localized: "activity.action.command"))}+ @Test(arguments: ["item/started", "item/completed"])+ func parsedCommandSummaryStaysOutOfHistory(_ method: String) throws {+ var reducer = try prepared()+ let input = try message(method, params: #"""+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution",+ "commandActions":[{"type":"unknown","command":"/private/path/private_tool private_argument"}]}}+ """#)+ #expect(input.params.item?.commandSummary == .tool("private_tool"))+ let event = try #require(reducer.consume(input, now: now).first)+ #expect(event.toolName == nil)+ #expect(event.commandActionTypes == ["unknown"])+ let data = try AppServerEventRecord(activityData: event).jsonLineData()+ let text = try #require(String(data: data, encoding: .utf8))+ #expect(!text.contains("private"))+ #expect(!text.contains("commandSummary"))+ }+@Test(arguments: ["actual_tool", "search/read"])func commandActionTypesDoNotOverrideOtherToolNames(_ name: String) throws {var reducer = try prepared()diff --git a/appcast.xml b/appcast.xmlindex 57973e2..4e6c1f2 100644--- a/appcast.xml+++ b/appcast.xml@@ -5,6 +5,20 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 5.1.0</title>+ <sparkle:version>209</sparkle:version>+ <sparkle:shortVersionString>5.1.0</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:minimumAutoupdateVersion>200</sparkle:minimumAutoupdateVersion>+ <sparkle:informationalUpdate><sparkle:belowVersion>200</sparkle:belowVersion></sparkle:informationalUpdate>+ <link xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.0.0-Guide</link>+ <link xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.0-Guide</link>+ <sparkle:releaseNotesLink xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.1.0</sparkle:releaseNotesLink>+ <sparkle:releaseNotesLink xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.1.0</sparkle:releaseNotesLink>+ <pubDate>Wed, 28 Oct 2026 13:50:48 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v5.1.0.dmg" sparkle:edSignature="Kj+7p1K6yJ4gr4WRHTkSkwxXXByXQrb0SAaVbDZMkb5c/rKNDiscx/VDmNI7n6URq3mYWPwigS41PyJzZfjrBQ==" length="11035136" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 5.0.8</title><sparkle:version>208</sparkle:version>