Skip to content

perf: agent 多时 CPU 高、灵动岛卡顿——Cursor 子任务识别移出主线程,会话发现去掉重复 stat - #374

Merged
wxtsky merged 9 commits into
wxtsky:mainfrom
x4vierli:perf/cursor-rebrand-index
Oct 22, 2026
Merged

wxtsky merged 9 commits into
wxtsky:mainfrom
x4vierli:perf/cursor-rebrand-index

Conversation

@x4vierli

Copy link
Copy Markdown
Contributor

问题

同时开着较多 agent(本地 + 远程)时,CodeIsland 的 CPU 占用很高(top 里最高到 140%),灵动岛悬停、展开时明显卡顿。

原因

用 sample 采样正在运行的 1.0.38,主线程 80% 以上的样本都在同一条调用链里:

HookServer.processRequest → handleEvent              ┐
requestDiscoveryScan → integrateDiscovered           ├→ applyCursorSubsessionModeToKnownSessions
requestCodexDesktopDiscoveryScan → integrateDiscovered┘     └→ rebrandMisattributedCursorTaskCards
                                                                 └→ findCursorSubagentTranscriptPath
                                                                     └→ firstSubagentTranscript
                                                                         └→ FileManager.enumerator(atPath:)  // open / getattrlistbulk
  • rebrandMisattributedCursorTaskCards() 对每张 source 为 Claude(或空)的卡片调用一次 findCursorSubagentTranscriptPath。后者用递归 enumerator 遍历 ~/.cursor/projects/*/agent-transcripts 找 subagents/<id>.jsonl:先找卡片 cwd 对应的项目,找不到再把所有项目都遍历一遍。
  • 普通的 Claude 卡片永远找不到这个文件,所以每张 Claude 卡片每次都要走完全部目录树,而且没有任何缓存。
  • 它在主线程上同步执行。函数虽然标了 nonisolated static,但调用方是 @MainActor。只要有 Claude 卡片,每个 hook 事件、每次会话发现扫描(FSEvents,agent 活跃时约每 2 秒一次)、Codex Desktop 轮询都会触发它。
  • 只在 Agent Sub-Sessions 为 merge / hide 时触发,separate 模式会提前返回。

测试机上 ~/.cursor/projects 有 187 个项目目录、49 棵 agent-transcripts 树、约 7,200 个条目(424 MB)。8 张 Claude 卡片 → 每次调用约 390 次树遍历;遍历一遍全部目录实测 0.15 s(热缓存)到 0.65 s(冷缓存)。

修掉这个之后再采样,剩下最大的一块在后台的会话发现:claudeSession(for:root:excluding:) 对每个 Claude 进程,都把它项目目录里的每个 .jsonl 单独 attributesOfItem 一次。同一 cwd 的进程共用一个项目目录。测试机上有 13 个 Claude 进程的 cwd 都是 ~,那个目录里有 78 个 transcript,所以每轮扫描约 1,000 次 stat,同一个目录被列了 13 遍。

改了什么

两个独立的 commit:

1. perf(cursor):Cursor 子任务识别改查后台建的索引

  • 新增 CursorSubagentTranscriptIndex(CodeIslandCore):遍历一次 ~/.cursor/projects,建立「子任务 session id → transcript 路径」的索引。匹配规则不变:任意深度下的 subagents/<id>.jsonl,多个项目都有时优先卡片 cwd 对应的项目。

  • rebrandMisattributedCursorTaskCards() 只查索引,主线程不再碰磁盘。

  • 索引在后台(.utility)重建,并做了节流:

    • 卡片第一次出现时立即建;
    • 5 秒后再查一次,防止 transcript 比第一个 hook 晚落盘;
    • 之后只在有事件时最多 60 秒查一次。

    后台查到后,再做 rebrand 和折叠(installCursorSubagentIndex)。

  • hook 的 transcript_path 已经指向 Cursor transcript 的卡片,仍然同步 rebrand,行为不变。

  • 仿照 discoveryScanner 加了 cursorSubagentIndexScanner,测试进程默认不扫真实的 home 目录。

  • findCursorSubagentTranscriptPath 保留,改为基于同一套扫描和查找,原有测试不用改。

2. perf(discovery):每轮扫描,每个 Claude 项目目录只列一次

  • 新增 claudeTranscriptFiles(in:fm:):用 contentsOfDirectory(at:includingPropertiesForKeys: [.contentModificationDateKey]) 一次拿到文件名和修改时间,不再逐个 stat。
  • findActiveClaudeSessions 在一轮扫描内按项目目录缓存列表,同 cwd 的进程共用。
  • 选择逻辑不变:取进程启动后修改过的最新 transcript,新鲜度窗口也不变。

实测效果

测试环境:

  • 机器:Apple Silicon,macOS 27,Agent Sub-Sessions = merge
  • agent:本地约 13 个 Claude Code 进程,加 Codex、Cursor、Kimi;另有 3 台远程机器通过 SSH 转发
  • CodeIsland 跟踪 9–18 张卡片

测量方法:

  • 每次启动后先等 60 s,让启动时的工作跑完;
  • 平均 CPU:用 ps 读两次 CPU 时间,取 60 s 内的差值;
  • 主线程:sample 采 10 s,统计不在 runloop 等待的样本比例。

两个版本在同一时段、同为 18 张卡片、都刚重启的情况下对比:

1.0.38 本 PR
平均 CPU 69.4% 16.6%
主线程繁忙(非 runloop 等待) 84.5% 15.1%
其中 rebrandMisattributedCursorTaskCards 80.6% 0.0%
  • 另一组对比(原版已运行 16 小时、11 张卡片,对比本 PR 10 张卡片):平均 CPU 36.2% → 19.5%,主线程繁忙 87.3% → 17.6%。
  • 本 PR 连续运行 10 分钟(每 30 s 一个读数):CPU 平均 16.8%,最高 19.4%;常驻内存 72–92 MB,没有增长。
  • 测试期间机器负载波动很大(load average 9 到 130),所以 CPU 百分比有噪声。主线程繁忙比例更直接反映界面会不会卡。原版的主线程繁忙比例高于它的 CPU 占用,因为主线程大部分时间是阻塞在磁盘 I/O 上,并不占 CPU。

剩下约 17% 的 CPU 主要来自这几处,不在本 PR 范围内:

  • 后台会话发现:对每种 agent 各扫一遍全部进程;
  • 每 3 秒一次的 cleanupIdleSessions;
  • mascot TimelineView 的逐帧刷新。

验证

新增 9 个测试:

  • CursorSubagentTranscriptIndexTests(5 个):
    • 只收录子任务,不收录父对话;
    • 能找到直接放在 agent-transcripts/subagents/ 下的文件;
    • 多个项目都有时,优先卡片自己的项目;
    • 目录不存在时返回空;
    • 重建节流策略。
  • AppStateCursorSubsessionTests(新增 2 个):
    • 没带 transcript_path 的误标卡片,由后台索引完成 rebrand 和折叠,且扫描不在主线程;
    • 连续 100 次调用只触发 1 次遍历。
  • ClaudeTranscriptFilesTests(2 个):
    • 列出的文件和修改时间,与逐个 attributesOfItem 的结果一致;
    • 目录不存在时返回 nil。

已有测试:

  • 原有 30 个 Cursor 子会话测试全部通过。
  • 全量 swift test:CodeIslandTests 1291 个(5 个 skipped),CodeIslandCoreTests 893 个,0 失败。
  • 两个 commit 各自都能单独编译通过。

实机运行:打包后替换 1.0.38,在测试机上跑了 30 多分钟。hook 事件接收、会话标题、进程绑定、sessions.json 持久化、远程 SSH 隧道、刘海显示都正常。

已知影响

  • 有一类卡片会晚一点合并:被误标成 Claude、hook 里又没带 transcript_path 的 Cursor 子任务卡片。它们现在要等后台索引建好才 rebrand 和折叠,通常在 1 秒内;以前是同步立即完成,代价是卡住主线程。如果这类卡片的 transcript 在第一个 hook 之后超过约 5 秒才写出来,最晚要等到下一个事件、且离上次遍历满 60 秒时才会被识别。
  • 只要还有没识别的 Claude 卡片,后台就会周期性遍历 ~/.cursor/projects:每张新卡片最多触发两次,之后只在有事件时最多每分钟一次,都不在主线程。

顺带发现(本 PR 没有修改)

用 Swift 6.4 / Xcode 27 在本地打包时,swift build 默认使用 swift-build 后端,会遇到两个问题:

  • 产物放在 .build/out/Products/Release/,build.sh 写死的 .build/arm64-apple-macosx/release/ 找不到它,打包失败;
  • 二进制 LC_BUILD_VERSION 里的 sdk 被写成 14.0(等于 minos),macOS 会按旧版兼容模式渲染,设置窗口的侧栏和标题栏会错位。

加 --build-system native 可以同时避开这两个问题。CI 用的是 Xcode 26(官方 1.0.38 二进制的 sdk 是 26.2),不受影响。

🤖 Generated with Claude Code

x4vierli and others added 9 commits October 16, 2026 13:42
… actor

rebrandMisattributedCursorTaskCards() resolved every default-Claude card
by walking every ~/.cursor/projects/*/agent-transcripts tree with a
recursive FileManager enumerator. It runs synchronously on the main actor
from handleEvent (every hook), integrateDiscovered (every discovery scan)
and restore, with no cache, and a miss walks every tree. With merge/hide
Agent Sub-Sessions and a large Cursor history this pinned the main thread:
~80% of main-thread samples were inside this walk, and the island stuttered.

Walk the store once, off the main actor, into a
CursorSubagentTranscriptIndex (child session id -> transcript paths, same
`subagents/<id>.jsonl` match at any depth, still preferring the card's own
cwd project) and look cards up in it. A card the index does not resolve
asks for a throttled rebuild: right away when first seen, once more after
5 s in case its transcript lands just after its first hook, then at most
every 60 s when an event brings it back. When a rebuild resolves a card it
is rebranded and folded then. Cards whose transcript_path already names a
Cursor transcript are still rebranded synchronously, as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
claudeSession(for:root:excluding:) listed its process's project dir and
called attributesOfItem on every .jsonl in it, once per Claude process.
Processes in the same cwd share a project dir, so with a dozen terminals
in ~ and ~80 transcripts there, every discovery scan (every ~2 s while
agents write) cost ~1,000 stats of the same files.

Read the dir's .jsonl names and modification dates in one bulk listing
(contentsOfDirectory with .contentModificationDateKey) and memoize it per
project dir for the duration of one scan. Selection is unchanged: the
newest transcript modified after the process started, within the same
freshness window.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
contentsOfDirectory(at:includingPropertiesForKeys:) fails (Cocoa error
256) when the last path component is a symlink to a directory, where the
contentsOfDirectory(atPath:) it replaced follows it. A project dir under
~/.claude/projects that is itself a symlink (history kept across a moved
checkout, say) would silently stop yielding sessions. Resolve the dir
before listing; entries keep lstat semantics, so a symlinked transcript
still reports its own mtime as the per-file stat did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The walk and its re-check timer were declared nonisolated(unsafe), the
convention here for tasks cancelled from deinit, but nothing cancelled
them: a walk in flight when stopSessionDiscovery() ran (app quit, the
debug harness's idle preview) still installed its index and could
rebrand and fold cards afterwards. Cancel both in stopSessionDiscovery()
and deinit, as discoveryScanTask is, and have the walk drop its result
once cancelled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test passed whatever the preference did: APFS lists b-own before
a-other, so paths.first was already the expected path. Also look up
with the other project preferred, so the listing order cannot decide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A remote card's transcripts live on its own host, so the local index can
never resolve it; yet every remote Claude card counted as unresolved and
kept the walks over ~/.cursor/projects coming. Leave remote cards out of
the index lookup and its candidates. The synchronous rebrand from a
Cursor transcript_path, a string check that needs no local disk, still
applies to them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every real Claude card stays unresolved, so the open-ended refresh
re-walked ~/.cursor/projects every 60 s for as long as any Claude
session was open and events kept coming, while a Task transcript that
landed 5-60 s after the first hook waited for that 60 s window. Each
card the index does not resolve now gets its own schedule: a walk 0, 5,
15, 45 and 120 s after it first goes unresolved, driven by the re-check
timer rather than by hook traffic, and none after that. A hook that
later brings a Cursor transcript_path still rebrands the card
synchronously. Still at most one walk and one timer pending.

A walk counts only for the lookups that were due when it started: a card
first seen while a walk was already running keeps its immediate lookup,
a walk some other card asked for does not use up this one's next delay,
and a late walk (after sleep, say) covers every lookup due by then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gain

Separate folds nothing, but the re-check timer and a walk's completion
kept scheduling walks whatever the mode, and a card whose lookups were
used up before a switch to separate stayed unresolved after switching
back to merge or hide, though its transcript may have landed meanwhile.
Scheduling now stands down outside merge and hide, dropping every card's
schedule, and applyCurrentPluginSessionMode drops them on entering
separate too, so coming back looks every default-Claude card up at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only one test still called findCursorSubagentTranscriptPath, and since
the index it had become a full walk of the store per lookup. The test now
scans with CursorSubagentTranscriptIndex and prefers the project from
cursorProjectTranscriptBase, with the same Task id under two projects so
that the card's cwd, not the directory listing order, picks the path.
installCursorSubagentIndex is only called from the walk, so it is
private, and a test message that still described the old re-check
interval now names the lookup delay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wxtsky
wxtsky merged commit 0c0d82a into wxtsky:main Oct 22, 2026
@wxtsky

wxtsky commented Oct 22, 2026

Copy link
Copy Markdown
Owner

@x4vierli 感谢这个 PR!分析写得很扎实(sample 调用链加前后对比数据),定位也准:rebrandMisattributedCursorTaskCards 在每个事件里、对每张 Claude 卡都在主线程上递归遍历 ~/.cursor/projects,这正是卡顿的根源。后台建索引、每轮扫描每个项目目录只列一次,这两个方向我们都认同,已合并为 0c0d82a,会随下个版本发布。

我们做的验证:

  • 合并当前 main 无冲突,swift build --build-tests 通过;全量 swift test 0 失败。
  • 逐项对照了旧实现:匹配规则一致(任意深度的 subagents/<id>.jsonl、优先 cwd 对应的项目、id 先 trim);hook 带 Cursor transcript_path 的同步路径没有变;后台结果回来时按当时的 sessions 重新取候选,卡片已被删除、合并或被 hook 改标的情况都能正确跳过;listings 是每轮扫描的局部变量,不会跨扫描泄漏。
  • 用脚本对比了新旧两种列目录方式:隐藏文件、软链接文件(两边都是 lstat 语义)、悬空软链接、名为 *.jsonl 的目录、mtime 精度,结果完全一致。

我们在你的两个提交之上加了 7 个提交(已推到这个分支后合并),每个新测试都确认过去掉对应改动就会失败:

修复:

  1. 项目目录本身是软链接时,会话发现失效。 contentsOfDirectory(at:includingPropertiesForKeys:) 遇到最后一级是软链接的目录会报错(Cocoa error 256),原来的 contentsOfDirectory(atPath:) 会跟随它。现在列目录前先 resolvingSymlinksInPath();条目本身不解析,软链接 transcript 仍报告自己的 mtime,和原来逐个 stat 一致。
  2. teardown 时取消后台遍历和复查定时器。 之前停掉发现之后,正在跑的遍历仍会 rebrand、折叠卡片。现在和 discoveryScanTask 一样在 deinit 和 stopSessionDiscovery() 里取消,被取消的遍历丢弃结果。
  3. testLookupPrefersTheCardsOwnProject 改为两个方向都断言。 APFS 上 b-own 本来就排在 a-other 前面,原断言去掉优先逻辑也能通过。

重查策略:
4. 远程卡不再触发遍历。 本地索引不可能命中远程会话;带 Cursor transcript_path 的同步改标只是字符串判断,对远程卡照旧生效。
5. 按卡片有上限地重查,取代无限期的 60 秒刷新。 真正的 Claude 卡永远查不到,原来只要开着 Claude 会话又有事件,就会一直每 60 秒遍历一次。现在每张卡从第一次查不到开始,在 0 / 5 / 15 / 45 / 120 秒各查一次,之后不再查;重查由定时器驱动,不依赖 hook 事件,同一时间最多一个遍历、一个定时器。之后有 hook 带来 Cursor transcript_path 时仍走同步路径立即改标。策略在 CodeIslandCore 的 CursorSubagentLookupSchedule 里,有单元测试。
6. 一次遍历只算作它开始时已经到期的那几次查询。 遍历进行中才出现的新卡仍会立即单独查一次;为别的卡发起的遍历不会提前用掉这张卡下一次的机会;睡眠唤醒后迟到的遍历会一次覆盖所有已到期的查询。
7. separate 模式下不遍历,切回 merge/hide 时立即重查。
8. 小清理: installCursorSubagentIndex 改成 private;只剩一个测试在用的 findCursorSubagentTranscriptPath 已删掉,测试改为直接测索引,并在两个项目里放同一个 Task id,验证确实按卡片的 cwd 选。

以后可以考虑的方向(不在这次范围内):现有的 FSEvents 监听已经在看 ~/.cursor/projects,只是回调里丢掉了路径。把 …/subagents/*.jsonl 的路径传过来就能增量更新索引,晚落盘的 transcript 几秒内就能识别。

PR 描述最后提到的两个打包问题(build.sh 写死产物路径、swift-build 后端写错 SDK 版本),main 上已经在 #379 和 ea7ecfe 里修了:发版脚本现在向 SwiftPM 询问产物位置,并固定使用 native build system。谢谢你一并指出!

wxtsky added a commit that referenced this pull request Oct 22, 2026
…jumps land on each session's pane (#373)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
wxtsky added a commit that referenced this pull request Oct 22, 2026
Cursor runs the hooks in ~/.claude/settings.json as its own ("Include
third-party Plugins, Skills, and other configs", on by default) and hands
each one Cursor's payload, cursor_version included. CodeIsland's hook there
has no --source and Cursor's processes are never inferred from the ancestry
(#220), so Cursor's agent showed up on the island as Claude (#377).

The bridge now reads cursor_version as Cursor declaring itself: cursor, or
cursor-cli under cursor-agent, and never a _via_plugin proxy. No ancestry
rule stands in for it: npm Claude Code runs as `node`, so in Cursor's
terminal its hooks have the same ancestors as a hook Cursor runs itself.

beforeSubmitPrompt and stop are wired in both of CodeIsland's configs, and
Cursor ran both hooks with one payload: every prompt and every finished turn
chimed twice. The bridge stamps a digest of Cursor's stdin and the island
lets one copy through. A hook Cursor runs never waits on the island or
prints its answer either: Cursor imports no PermissionRequest or
Notification hook and reads stdout against its own schema.

A Task's own hooks carry no transcript_path, and the Task transcript
index (#374) only looked up default-Claude cards; it now also looks up
local Cursor cards without one, so relabelled Task cards still fold. A new
chat's sessionStart arrives before Cursor has its transcript, so session
start and end no longer take the _ppid fallback, which could fold the new
chat into a sibling as a Task that never finishes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants