Skip to content

fix(core): salvage session usage into the history before deleting transcripts - #7391

Merged
wenshao merged 1 commit into
QwenLM:mainfrom
zjunothing:fix/7384-persist-usage-before-delete
Jul 21, 2026
Merged

fix(core): salvage session usage into the history before deleting transcripts#7391
wenshao merged 1 commit into
QwenLM:mainfrom
zjunothing:fix/7384-persist-usage-before-delete

Conversation

@zjunothing

Copy link
Copy Markdown
Collaborator

What this PR does

Adds a persistUsageBeforeTranscriptDeletion() salvage to usageHistoryService and calls it from SessionService.removeSessionFiles() (both the active and the archived branch) right before the transcript JSONL is unlinked. The salvage replays the transcript's ui_telemetry records through the same summarization the rebuild migration uses — the per-transcript logic is extracted into a shared summarizeTranscript() so the two paths cannot drift — writes the summary to usage_record.jsonl, skips the write when the history already carries a record for that session (a /clear or clean exit wrote the authoritative one; duplicating it would re-open #4994), and never throws, so deletion always proceeds even when salvage fails.

Why it's needed

#7384: token usage per session is persisted to usage_record.jsonl only on /clear and on process exit; for every other session the usage history relies on a rebuild fallback that scans the session transcript JSONLs. removeSessionFiles() deleted those transcripts without persisting anything first — so deleting a session that was never /cleared or cleanly exited (the reporter's screenshot case) permanently erased its token usage from the records, making the usage report inaccurate. The triage confirmed both usage systems from source (the global monthly tokenUsageService files are unaffected; the per-session usageHistoryService is the broken one) and proposed exactly this fix direction.

Reviewer Test Plan

How to verify

  1. Run a session (without /clear), kill it uncleanly or just leave it, then delete it from the session list. Before this PR: its tokens vanish from the usage report (the rebuild has no transcript to read). After: the summary — models, token totals, tools, duration — survives in usage_record.jsonl.
  2. Delete a session that WAS /cleared: no duplicate record is added (the salvage detects the existing entry and skips).
  3. npx vitest run src/services/usageHistoryService.test.ts src/services/sessionService.test.ts (packages/core): 150/150.

Evidence (Before & After)

E2E against the real compiled services under a temp QWEN_HOME: plant a real transcript containing a ui_telemetry record (1000 total tokens), then call the real SessionService.removeSession():

before fix after fix
session removed / transcript gone ✅ / ✅ ✅ / ✅
usage record for the session absent — erased forever present, totalTokens: 1000

verification

Unit coverage: the salvage writes the summary from real files, skips when the history already has the session, returns false (writing nothing) for telemetry-less transcripts, and never throws for missing files; the sessionService wiring test pins the salvage running before unlinkSync via invocation order and fails on the unpatched source (verified via git stash).

Tested on

OS Status
🍏 macOS
🪟 Windows ⚠️
🐧 Linux ⚠️

Environment (optional)

macOS (Darwin 24.6), Node v22.23.1; real compiled SessionService/usageHistoryService E2E under a temp QWEN_HOME, plus vitest unit tests. npm run typecheck, eslint --max-warnings 0, prettier all clean.

Risk & Scope

  • Main risk or tradeoff: session deletion now reads the transcript once more (a full JSONL read to replay telemetry) plus one read of usage_record.jsonl for the duplicate check — a per-deletion cost bounded by transcript size, on an interactive path where deletion already does multiple file operations. If the current in-progress session were ever deleted, its exit-time persistSessionUsage could still produce a duplicate — bounded by the read side's existing last-wins dedupe (dedupBySessionId, /stats permanently double-counts a session if /stats is opened during the first-ever turn (introduced by #4779) #4994).
  • Not validated / out of scope: bulk cleanup paths that bypass removeSessionFiles() (e.g. a user manually deleting ~/.qwen/projects/**) can still lose usage — out of scope, nothing in-process can salvage an external rm. The global monthly tokenUsageService files were never affected.
  • Breaking changes / migration notes: none — the salvage is additive and silent.

Linked Issues

Fixes #7384

中文说明

本 PR 做了什么

usageHistoryService 新增 persistUsageBeforeTranscriptDeletion(),并在 SessionService.removeSessionFiles()(active 与 archived 两个分支)删除 transcript JSONL 前调用。salvage 用与重建迁移相同的汇总逻辑重放 transcript 的 ui_telemetry 记录——共用抽取的 summarizeTranscript(),两条路径不会漂移——把摘要写入 usage_record.jsonl;历史中已有该会话记录时跳过(/clear 或正常退出已写权威记录,重复会重开 #4994);永不抛错,salvage 失败也不阻塞删除。

为什么需要

#7384:会话用量只在 /clear 与进程退出时持久化,其余会话依赖「扫描 transcript 重建」的回退。removeSessionFiles() 删 transcript 前不持久化任何东西——删除一个从未 /clear 或非正常退出的会话(报告者截图场景)会把它的 token 用量从记录中永久抹掉。triage 已从源码确认两套用量系统(全局月度 tokenUsageService 不受影响;受影响的是按会话的 usageHistoryService)并给出了正是本 PR 的修复方向。

审阅测试计划

如何验证

  1. 跑一个会话(不 /clear)、直接删除:本 PR 之前其 token 从用量报表消失;之后摘要(模型、token 总量、工具、时长)保留在 usage_record.jsonl
  2. 删除一个已 /clear 的会话:不产生重复记录(salvage 检测到已有条目并跳过);
  3. 两个测试文件 150/150。

证据(Before & After)

真实编译产物的 E2E(临时 QWEN_HOME 下种入含 1000 tokens 遥测的真实 transcript,再调真实 removeSession()):修复前会话删除、transcript 消失、用量记录永久缺失;修复后用量记录存活且 totalTokens: 1000。单测覆盖:真实文件写入、已持久化跳过、无遥测不写、缺文件不抛;接线测试用调用顺序钉死「salvage 在 unlink 之前」,在未修复源码上失败(git stash 验证)。

测试平台

macOS 已本地验证(✅);Windows / Linux 依赖 CI(⚠️)。

环境

macOS(Darwin 24.6)、Node v22.23.1;临时 QWEN_HOME 下的真实编译类 E2E + vitest;typecheck / eslint / prettier 全绿。

风险与范围

  • 主要风险/权衡:删除路径多一次 transcript 全量读取(重放遥测)+ 一次 usage_record.jsonl 读取(查重)——按 transcript 大小有界,且删除本就是多文件操作的交互路径。若删除的是进行中的当前会话,退出时的 persistSessionUsage 仍可能产生一条重复——由读侧既有的 last-wins 去重(dedupBySessionId/stats permanently double-counts a session if /stats is opened during the first-ever turn (introduced by #4779) #4994)兜底。
  • 未验证/超出范围:绕过 removeSessionFiles() 的清理(如用户手动 rm ~/.qwen/projects/**)仍会丢用量——进程内无法挽救外部删除,超出范围。全局月度 tokenUsageService 文件从未受影响。
  • 破坏性变更/迁移说明:无——salvage 为静默附加行为。

关联 Issue

Fixes #7384

🤖 Generated with Claude Code

…nscripts

usageHistoryService's rebuild fallback derives per-session usage
summaries from session transcript JSONLs, and persistSessionUsage only
runs on /clear and process exit. removeSessionFiles() deleted the
transcript without either — so deleting a session that was never
/clear'ed or cleanly exited permanently erased its tokens from the
usage records (QwenLM#7384).

removeSessionFiles() now calls a new
persistUsageBeforeTranscriptDeletion() on the transcript (active or
archived branch) right before unlinking it. The salvage replays the
transcript's ui_telemetry records through the same summarization the
rebuild migration uses — extracted into a shared summarizeTranscript()
so the two cannot drift — skips the write when usage_record.jsonl
already carries the session (a /clear or exit wrote the authoritative
record; duplicating would re-open QwenLM#4994), and never throws, so deletion
always proceeds.

Verified against the real compiled services under a temp QWEN_HOME:
before, removeSession() leaves usage_record.jsonl without the session
forever; after, the summary (with its token totals) survives deletion.
The wiring test pins the salvage running BEFORE unlink and fails on the
unpatched source.

Fixes QwenLM#7384

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@zjunothing

Copy link
Copy Markdown
Collaborator Author

Verification report

E2E against the real compiled services (temp QWEN_HOME; plant a real transcript with a ui_telemetry record totaling 1000 tokens; call the real SessionService.removeSession()):

before (origin/main ce803df22) after (this PR)
removed / transcript gone ✅ / ✅ ✅ / ✅
usage record survives no — erased forever yes — models['qwen-max'].totalTokens = 1000

verification

Tests (packages/core, 150/150 across the two touched suites):

Static checks: npm run typecheck ✅ · eslint --max-warnings 0 ✅ · prettier ✅.

Review focus suggestions: (1) ordering — the salvage runs before the first removeFileIfExists in both the active and archived branches, and swallows its own errors so deletion can never be blocked; (2) duplicate policy — skip-if-persisted keeps /clear/exit as the authoritative writers, with the read side's last-wins dedupe as the backstop; (3) the shared summarizeTranscript() refactor preserves rebuild semantics exactly (same seen-session dedupe order, same no-events/NaN-timestamps skips).

中文版本

真实编译产物 E2E(临时 QWEN_HOME 种入含 1000 tokens 遥测的真实 transcript,调真实 removeSession):修复前用量记录被永久抹掉;修复后存活且 totalTokens=1000。

测试(两套件 150/150):salvage 真实文件写入 / 已持久化跳过 / 无遥测不写 / 缺文件不抛;接线测试以调用顺序钉死「salvage 在 unlink 之前」,未修复源码上失败(stash 验证);重建路径与 salvage 共用 summarizeTranscript(),既有 #4994 回归套件原样通过。静态检查全绿。

审阅要点:(1) 顺序——active/archived 两分支都在首个删除前执行 salvage,且自吞错误绝不阻塞删除;(2) 重复策略——已持久化即跳过(/clear/退出仍是权威写入方),读侧 last-wins 去重兜底;(3) summarizeTranscript() 抽取严格保持重建语义(seen-session 去重顺序、无事件/时间戳 NaN 跳过均一致)。

@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Thanks for the PR!

Template looks good ✓

Problem: observed bug with evidence — #7384 reports (with screenshot) that deleting a session permanently erases its token usage from the records. The issue is labeled type/bug / priority/P2 and the triage confirmed the root cause in source.

Direction: aligned. Session deletion should not silently destroy usage data that the user can see in reports. CHANGELOG has no direct reference to usage salvage on delete, but session-deletion data integrity is clearly relevant (multiple upstream fixes around session removal).

Size: 143 production lines (usageHistoryService.ts +98 −39, sessionService.ts +6 −0), 136 test lines. Under the 500-line awareness threshold — no escalation needed.

Approach: the scope feels right — persist before delete, reuse the existing summarization logic via a shared helper, skip when a record already exists, never throw. Every edit serves the stated goal; no unrelated changes. The one design question I'd flag: reading the full transcript JSONL on every deletion adds I/O proportional to transcript size. For very long sessions this could be noticeable, but since deletion is already a multi-file interactive operation and the alternative (losing data permanently) is worse, the tradeoff seems reasonable.

Moving on to code review. 🔍

中文说明

感谢贡献!

模板完整 ✓

问题:已观测到的 bug,有证据——#7384 报告(附截图)删除会话后 token 用量从记录中永久消失。issue 已标记 type/bug / priority/P2,triage 已从源码确认根因。

方向:对齐。删除会话不应静默销毁用户可见的用量数据。CHANGELOG 无直接对应用量抢救条目,但会话删除的数据完整性明确相关(上游有多次会话移除相关修复)。

规模:143 行生产代码(usageHistoryService.ts +98 −39,sessionService.ts +6 −0),136 行测试。低于 500 行关注阈值,无需升级。

方案:范围合理——删前持久化、复用已有汇总逻辑(共享 helper)、已有记录时跳过、永不抛错。所有改动服务于目标,无无关变更。一个设计问题:每次删除都全量读取 transcript JSONL,I/O 与 transcript 大小成正比。超长会话可能有感知,但删除本就是多文件交互操作,且替代方案(永久丢失数据)更糟,权衡合理。

进入代码审查 🔍

Qwen Code · qwen3.7-max

Reviewed at 70723dc4c93580327524ad3da92a43da4e87f547 · re-run with @qwen-code /triage

@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Code review

The approach matches what I'd propose independently: extract the per-transcript summarization from the rebuild migration into a shared summarizeTranscript(), add a persistUsageBeforeTranscriptDeletion() that reads → summarizes → dedup-checks → writes, and wire it into both branches of removeSessionFiles() before the unlink. The refactored rebuild path is behaviorally equivalent to the original (the seenSessionIds dedup moved after telemetry processing — a trivial inefficiency for duplicate sessions, not a correctness change).

No critical blockers found. The code follows project conventions: ESM imports, no any, collocated tests, kebab-case files. The error handling is appropriate — outer try/catch swallows everything so deletion never blocks, and the unreadable-history fallback writes anyway (bounded by read-side dedupBySessionId).

One suggestion (non-blocking): in the active branch of removeSessionFiles(), when a session has both an active file and an archived sidecar (post-compression), only the active file is salvaged — the archived sidecar is deleted without salvage. If telemetry ended up in the archived file after compression, that data would still be lost. This is a narrow edge case (session must have been compressed AND never /clear'd AND never cleanly exited), and the PR is strictly better than the status quo regardless. Worth a follow-up if the maintainer cares about completeness.

Real-scenario testing

Tested against the real compiled SessionService under a temp QWEN_HOME, driving removeSession() on a planted transcript with ui_telemetry records:

=== BEFORE ===
Transcript planted at: /tmp/qwen-salvage-test-mnF6Ms/projects/-tmp-salvage-test-project/chats/a1b2c3d4-e5f6-7890-abcd-ef1234567890.jsonl
Transcript exists: true
usage_record.jsonl exists: false

removeSession result: true

=== AFTER ===
Transcript exists: false
usage_record.jsonl exists: true
--- Salvaged usage record ---
  sessionId: a1b2c3d4-e5f6-7890-abcd-ef1234567890
  project: /tmp/salvage-test-project
  models: {"qwen-max":{"requests":1,"inputTokens":800,"outputTokens":400,"cachedTokens":0,"thoughtsTokens":200,"totalTokens":1400,"totalLatencyMs":1200}}
  durationMs: 60000

Dedup test (session already has a usage record from /clear or clean exit):

=== BEFORE ===
Transcript exists: true
usage_record.jsonl lines: 1

removeSession result: true

=== AFTER ===
Transcript exists: false
usage_record.jsonl lines: 1
PASS: No duplicate record created (dedup works)

Unit tests: 150/150 pass (usageHistoryService.test.ts 30 tests, sessionService.test.ts 120 tests).

中文说明

代码审查

方案与我的独立提案一致:将重建迁移中的逐 transcript 汇总逻辑抽取为共享的 summarizeTranscript(),新增 persistUsageBeforeTranscriptDeletion()(读取 → 汇总 → 查重 → 写入),并在 removeSessionFiles() 的两个分支中于 unlink 前调用。重构后的重建路径与原始行为等价(seenSessionIds 去重移到了遥测处理之后——对重复会话有微小效率差异,非正确性问题)。

未发现关键阻塞项。代码遵循项目规范:ESM 导入、无 any、测试共置、kebab-case 文件名。错误处理恰当——外层 try/catch 吞掉所有异常确保删除不被阻塞,历史不可读时仍写入(由读侧 dedupBySessionId 兜底)。

一个建议(非阻塞):在 removeSessionFiles() 的 active 分支中,当会话同时有 active 文件和 archived 副本(压缩后)时,只抢救了 active 文件——archived 副本被直接删除未抢救。如果遥测在压缩后落入了 archived 文件,那部分数据仍会丢失。这是很窄的边界情况(会话必须被压缩过且从未 /clear 且非正常退出),且无论如何 PR 都严格优于现状。如果 maintainer 关注完整性,可以后续跟进。

真实场景测试

对真实编译产物 SessionService 在临时 QWEN_HOME 下测试,驱动 removeSession() 删除种入 ui_telemetry 记录的 transcript:修复前 transcript 存在、无 usage_record;修复后 transcript 已删、usage_record 已创建且数据正确(sessionId、project、models token 计数、durationMs)。去重测试:已有记录的会话删除后不产生重复。单测 150/150 全通过。

Qwen Code · qwen3.7-max

Reviewed at 70723dc4c93580327524ad3da92a43da4e87f547 · re-run with @qwen-code /triage

@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Confidence: 4/5

This is a clean, well-scoped fix for a real data-loss bug. The shared summarizeTranscript() extraction prevents drift between the rebuild and salvage paths, the dedup guard avoids re-opening #4994, and the never-throw contract keeps deletion reliable. E2E testing confirms both the salvage and dedup behaviors against the real compiled services. 150/150 unit tests pass.

The one-point deduction is for the archived-sidecar gap noted in Stage 2 — a narrow edge case that doesn't block this PR but is worth a follow-up.

LGTM, approving. ✅

中文说明

置信度:4/5

这是一个干净、范围合理的修复,解决了真实的数据丢失 bug。共享的 summarizeTranscript() 抽取防止了重建与抢救路径的漂移,去重守卫避免重开 #4994,永不抛错的契约保证删除可靠性。E2E 测试在真实编译产物上确认了抢救和去重行为。150/150 单测全通过。

扣一分是因为 Stage 2 提到的 archived 副本缺口——很窄的边界情况,不阻塞本 PR,但值得后续跟进。

LGTM,批准。✅

Qwen Code · qwen3.7-max

Reviewed at 70723dc4c93580327524ad3da92a43da4e87f547 · re-run with @qwen-code /triage

@qwen-code-ci-bot qwen-code-ci-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, looks ready to ship. ✅

@doudouOUC doudouOUC left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed. Suggestions are inline. 1 Suggestion-level finding(s) could not be anchored to a changed line and were dropped; nothing further to act on here.

— qwen3.7-max via Qwen Code /review

Comment on lines +1448 to +1450
const salvage = vi.mocked(persistUsageBeforeTranscriptDeletion);
expect(salvage).toHaveBeenCalledWith(
expect.stringContaining(`${sessionIdA}.jsonl`),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] No test exercises the failure-tolerant deletion contract — Concrete cost: the code comment at sessionService.ts:1345 documents "Never blocks deletion (the salvage swallows its own errors)", but the mock always resolves true, so no test verifies that deletion proceeds when salvage fails. A future refactor that accidentally makes removeSessionFiles depend on salvage success would go undetected.

Suggested change
const salvage = vi.mocked(persistUsageBeforeTranscriptDeletion);
expect(salvage).toHaveBeenCalledWith(
expect.stringContaining(`${sessionIdA}.jsonl`),
salvage.mockResolvedValueOnce(false);
const result = await sessionService.removeSession(sessionIdA);
expect(result).toBe(true);
expect(unlinkSyncSpy).toHaveBeenCalled();

— qwen3.7-max via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in follow-up #7425 — and running your suggested case exposed that the contract was NOT actually structural: a rejecting salvage propagated through removeSessionFiles' rethrowing catch and failed the deletion. The follow-up adds a call-site salvageUsageBestEffort wrapper (catch + warn) plus the failure-tolerance test, which fails without the wrapper. 中文:已在 follow-up #7425 落地——按建议补测试时发现契约此前并非结构性(rejection 会穿透重抛 catch 使删除失败),已加调用点包装 + 失败容忍测试(无包装即失败)。

Comment on lines +1452 to +1454
expect(salvage.mock.invocationCallOrder[0]!).toBeLessThan(
unlinkSyncSpy.mock.invocationCallOrder[0]!,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Ordering assertion is fragile due to uncleared module mock — Concrete cost: persistUsageBeforeTranscriptDeletion is a vi.mock() at module scope and its invocationCallOrder accumulates across all tests. afterEach calls vi.restoreAllMocks() which only restores spies, not module mocks. Currently this test is first in the describe block so [0] works, but reordering tests or adding an earlier test that triggers the active path would make [0] reference a stale call — and the assertion would silently pass for the wrong reason since invocationCallOrder is monotonically increasing.

Suggested change
expect(salvage.mock.invocationCallOrder[0]!).toBeLessThan(
unlinkSyncSpy.mock.invocationCallOrder[0]!,
);
// Add to beforeEach:
vi.mocked(persistUsageBeforeTranscriptDeletion).mockClear();
expect(salvage.mock.invocationCallOrder[0]!).toBeLessThan(
unlinkSyncSpy.mock.invocationCallOrder[0]!,
);

— qwen3.7-max via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in follow-up #7425 — the salvage module mock is now cleared in the top-level beforeEach, so invocationCallOrder assertions can never read stale calls regardless of test ordering. 中文:已在 #7425 落地——顶层 beforeEach 清理该模块 mock,顺序断言不再受测试重排影响。

@qwen-code-ci-bot qwen-code-ci-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — no blockers. Suggestions are inline.

— qwen3.7-max via Qwen Code /review

Comment on lines +1347 to 1350
await persistUsageBeforeTranscriptDeletion(activePath);
this.removeFileIfExists(activePath);
const archivedPath = this.getSessionFilePath(sessionId, 'archived');
if (fs.existsSync(archivedPath)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Missing usage salvage for the archived transcript when both active and archived co-exist — Failure scenario: if both files exist for the same sessionId (e.g., an interrupted archive left both in place) and the active transcript has no telemetry events (a fresh session started after archiving), the active salvage writes nothing, then the archived transcript — which holds the session's historical usage data — is deleted without salvage. That usage data is permanently lost from usage_record.jsonl.

Adding the same salvage call before the archived deletion is safe: the dedup guard in persistUsageBeforeTranscriptDeletion returns false when the active salvage already wrote a record for this sessionId, and when the active salvage didn't write, the archived salvage preserves the data.

Suggested change
await persistUsageBeforeTranscriptDeletion(activePath);
this.removeFileIfExists(activePath);
const archivedPath = this.getSessionFilePath(sessionId, 'archived');
if (fs.existsSync(archivedPath)) {
await persistUsageBeforeTranscriptDeletion(activePath);
this.removeFileIfExists(activePath);
const archivedPath = this.getSessionFilePath(sessionId, 'archived');
if (fs.existsSync(archivedPath)) {
await persistUsageBeforeTranscriptDeletion(archivedPath);

— qwen3.7-max via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in follow-up #7425 — the active branch now salvages the archived transcript before removing it, exactly per your reasoning: the dedup guard makes it a no-op when the active copy already wrote, and it preserves the history when the fresh active copy has no telemetry. 中文:已在 #7425 落地——active 分支删除 archived 副本前也执行 salvage;查重门保证 active 已写时为 no-op,active 无遥测时保住历史数据。

@wenshao
wenshao requested a review from Copilot July 21, 2026 08:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@wenshao

wenshao commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Local verification — built and tested against the real compiled services ✅

I built the core package and ran a real end-to-end test against the compiled SessionService + usageHistoryService (no mocks) under a throwaway QWEN_HOME. I reproduced the bug on the pre-fix build and confirmed the fix on this PR's build — same script, two compiled dist/ outputs.

PR 7391 local verification

What I ran

  • Rebuilt @qwen-code/qwen-code-core dist/ twice — at this PR's head and at its parent commit (HEAD^, i.e. the exact pre-fix state) — and ran the same E2E against each compiled build. (I deliberately diffed against HEAD^, not the current origin/main, since main has drifted 104 commits and its Storage constructor no longer matches this branch.)
  • E2E: plant a real transcript containing a ui_telemetry record, call the real SessionService.removeSession(), then check whether the per-session usage summary survives in usage_record.jsonl.

Before / after (real compiled dist, temp QWEN_HOME)

After removeSession() deletes the transcript before fix (HEAD^) after fix (this PR)
session removed / transcript gone ✅ / ✅ ✅ / ✅
usage record in usage_record.jsonl absent — erased forever present
salvaged tokens — active branch (planted 1000) totalTokens: 1000
salvaged tokens — archived branch (planted 2000) totalTokens: 2000

Both the active and archived branches of removeSessionFiles() salvage correctly — I exercised each one end-to-end through the real removeSession().

Unit tests + adversarial guard

  • vitest run usageHistoryService.test.ts sessionService.test.ts150 / 150.
  • Adversarial check: I paired the PR's patched wiring test with unpatched source. The removeSession salvage assertion fails with Number of calls: 0, so the test genuinely pins the salvage running before unlinkSync — it is not a no-op that would pass regardless.

Gates (on the 4 changed files)

  • tsc --noEmit → exit 0
  • eslint --max-warnings 0 → clean (the CI Test job gates on this before vitest)
  • prettier --check → clean

Verdict

LGTM from my side. The change is tightly scoped (4 files, additive), the salvage swallows its own errors so deletion can never be blocked, and the dedupe-by-sessionId guard avoids re-opening #4994. The documented residual costs — one extra transcript read + one usage_record.jsonl read per deletion, and a possible single duplicate if the in-progress session is deleted (bounded by the read-side last-wins dedupBySessionId) — are acceptable on this interactive path. External rm of ~/.qwen/projects/** remains out of scope and unsalvageable, as the PR states.

中文说明

本地验证 —— 针对真实编译产物构建并测试 ✅

我在本地构建了 core 包,并在临时 QWEN_HOME 下对编译后的 SessionService + usageHistoryService(非 mock)跑了真实的端到端测试:在修复前的产物上复现了 bug,在本 PR 的产物上确认了修复 —— 同一份脚本,两份编译 dist/

(截图见上方英文部分。)

我做了什么

  • @qwen-code/qwen-code-coredist/ 构建了两次 —— 一次在本 PR 的 head,一次在其父提交(HEAD^,即修复前的确切状态)—— 用同一个 E2E 分别打这两份编译产物。(我特意对比 HEAD^ 而非当前 origin/mainmain 已领先 104 个提交,其 Storage 构造函数签名已与本分支不一致。)
  • E2E:种入一份含 ui_telemetry 记录的真实 transcript,调用真实的 SessionService.removeSession(),再检查按会话的用量摘要是否存活于 usage_record.jsonl

Before / after(真实编译 dist,临时 QWEN_HOME

removeSession() 删除 transcript 之后 修复前(HEAD^ 修复后(本 PR)
会话删除 / transcript 消失 ✅ / ✅ ✅ / ✅
usage_record.jsonl 中的用量记录 缺失 —— 永久抹除 存在
挽救的 token —— active 分支(种入 1000) totalTokens: 1000
挽救的 token —— archived 分支(种入 2000) totalTokens: 2000

removeSessionFiles()activearchived 两个分支都能正确挽救 —— 我分别通过真实的 removeSession() 端到端跑过。

单测 + 反向校验

  • vitest run usageHistoryService.test.ts sessionService.test.ts150 / 150
  • 反向校验:我用本 PR 的已修复接线测试搭配未修复源码,removeSession 的 salvage 断言以 Number of calls: 0 失败 —— 说明该测试确实钉死了「salvage 在 unlinkSync 之前执行」,不是一个无论如何都会通过的空测试。

门禁(针对 4 个改动文件)

  • tsc --noEmit → exit 0
  • eslint --max-warnings 0 → 干净(CI 的 Test job 在 vitest 之前会卡这一关)
  • prettier --check → 干净

结论

我这边 LGTM。改动范围很收敛(4 个文件、纯附加),salvage 自吞异常、绝不阻塞删除,按 sessionId 去重的守卫也避免了重开 #4994。已记录的残余成本 —— 每次删除多一次 transcript 读取 + 一次 usage_record.jsonl 读取,以及删除进行中当前会话时可能产生一条重复(由读侧 last-wins 的 dedupBySessionId 兜底)—— 在这条交互路径上可以接受。绕过进程、直接 rm ~/.qwen/projects/** 仍属超范围且无法挽救,正如 PR 所述。


🤖 Generated with Claude Code — Claude Fable 5

@wenshao
wenshao added this pull request to the merge queue Jul 21, 2026
Merged via the queue into QwenLM:main with commit 4af784d Jul 21, 2026
118 checks passed
pull Bot pushed a commit to Stars1233/qwen-code that referenced this pull request Jul 22, 2026
)

Post-merge review follow-ups on QwenLM#7391 (three findings):

- Salvage the archived transcript in the active-branch deletion too:
  when both copies co-exist (an interrupted archive) and the fresh
  active transcript carries no telemetry, the archived copy holds the
  session's usage history and was deleted unsalvaged. The dedup guard
  makes the extra call a no-op whenever the active copy already wrote.
- Enforce the "never blocks deletion" contract at the call site: a
  salvageUsageBestEffort wrapper catches and warns, so the guarantee is
  structural rather than an implementation detail of
  persistUsageBeforeTranscriptDeletion. The new failure-tolerance test
  (salvage rejects -> deletion still succeeds) fails without the
  wrapper — the bare await let the rejection escape through
  removeSessionFiles' rethrowing catch.
- Clear the salvage module mock in beforeEach so the wiring test's
  invocationCallOrder assertions can never read stale calls.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
chiga0 pushed a commit that referenced this pull request Jul 23, 2026
Post-merge review follow-ups on #7391 (three findings):

- Salvage the archived transcript in the active-branch deletion too:
  when both copies co-exist (an interrupted archive) and the fresh
  active transcript carries no telemetry, the archived copy holds the
  session's usage history and was deleted unsalvaged. The dedup guard
  makes the extra call a no-op whenever the active copy already wrote.
- Enforce the "never blocks deletion" contract at the call site: a
  salvageUsageBestEffort wrapper catches and warns, so the guarantee is
  structural rather than an implementation detail of
  persistUsageBeforeTranscriptDeletion. The new failure-tolerance test
  (salvage rejects -> deletion still succeeds) fails without the
  wrapper — the bare await let the rejection escape through
  removeSessionFiles' rethrowing catch.
- Clear the salvage module mock in beforeEach so the wiring test's
  invocationCallOrder assertions can never read stale calls.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
yiliang114 added a commit to he-yufeng/qwen-code that referenced this pull request Jul 23, 2026
)

* fix(cli): correct queued message display style and ordering

Mid-turn steer messages (user input queued while the model is
responding) had two display bugs:

1. They rendered with notification styling (● icon) instead of
   user-input styling (> prefix) because accept() added them to
   UI history as MessageType.NOTIFICATION.

2. They appeared below the model's reply because accept() was
   only called in the finally block after the entire response
   stream completed, appending the user message after all model
   response items.

Fix: use MessageType.USER with sentToModel: true for steer
messages, and settle the steer input on the first stream event
(after the user-content push lands but before model-response
events are committed to UI history). Pass steer inputs through
to recursive sendMessageStream calls so all takeSteerInput paths
benefit from early settlement. Add a WeakSet guard to
settleSteerInput for idempotency across recursive invocations.

* test(core): add ordering test for early steer settlement

Verify that accept() is called after the first stream event is
pulled but before subsequent events reach the consumer, pinning
the settle-before-content timing that ensures queued user
messages render above the model's reply.

* fix(cli): use sentToModel: false for steer messages, address review

- Use sentToModel: false instead of true: steer messages are injected
  into an existing tool-result turn, not standalone user turns.
  sentToModel: true would make isRealUserTurn() count them as real
  turns, inflating the rewind turn index.
- Remove unnecessary as HistoryItemWithoutId cast.
- Add post-cleanup assertion in ordering test to verify the WeakSet
  guard prevents double-settlement.

* fix(cli): align resumed mid-turn steer display with live session (#7381)

Resume path now renders mid_turn_user_message as MessageType.USER with
sentToModel: false, matching the live-session styling. Add a comment
documenting the intentional sentToModel: false choice.

* fix(cli): exclude steer messages from user-turn filters (#7381)

Steer messages (sentToModel: false) were counted as real user turns by
five downstream consumers that filter on type === 'user' without checking
sentToModel, breaking cancel auto-restore, telemetry turn count, prompt
recall, away-recap thresholds, and resume collapse boundaries.

Add sentToModel !== false guards at each site.

* test(cli): add coverage for sentToModel !== false guards (#7381)

* test(cli): add coverage for sentToModel !== false guard in input-history filter (#7381)

* test(cli): add coverage for sentToModel !== false guard in YOLO turn-count telemetry (#7381)

* fix(cli): restore corrupted docs and classify steer items as synthetic (#7381)

* fix(docs): restore corrupted autogenerated input names in GitHub Action docs (#7381)

* fix(cli): deduplicate findLastUserItemIndex and add steerInput forwarding test (#7381)

* fix(cli): keep code-block copy numbering continuous across steer items (#7381)

* test(core): add Hook continuation steerInput forwarding test

Verify that steerInput is forwarded through the Stop-hook
continuation path and settled early on the first content event
of the continuation turn, matching the existing Steer
continuation coverage.

* fix(cli): sync selection test fixtures with ink FrameCell/ReadonlyFrame types (#7381)

* fix(core): align cron day wildcard semantics (#7464)

Co-authored-by: destire-mio <248462155+destire-mio@users.noreply.github.com>

* feat(core): keep completed background agents resident (#7426)

* feat(core): keep background agents resident

* fix(core): harden background continuation boundaries

* docs(core): move per-spawn cleanup comment to subagentDispose

The comment describing the per-spawn cleanup (which stays undefined on
the fork-resume path) had drifted above the launchModel declaration,
where it no longer applied and could mislead readers. Relocate it to the
subagentDispose assignment in the non-fork branch it actually documents.

* fix(core): close finishing window and release resident on error in background GOAL path

- Non-worktree GOAL completion drained the message queue but never called
  registry.beginFinishing(), unlike the worktree path. A send_message racing
  the terminal transition could be accepted (status still running,
  finishingAgents empty) and then orphaned by complete(). Call beginFinishing()
  after the empty drain to reject the racing message instead.
- The completion catch block never reset keepResident, so a throw from
  patchAgentMeta/registry.complete left the runtime resident but finalized as
  failed — a zombie that cleanupRuntime never reclaimed. Reset keepResident in
  the catch so the finally block disposes it.

---------

Co-authored-by: Claude <noreply@anthropic.com>

* ci(autofix): continue environment-specific fixes (#7444)

* ci(autofix): continue environment-specific fixes

* docs(autofix): align verification wording

* docs(autofix): require bundle before integration tests

* docs(autofix): scope surrogate verification rules

* docs(autofix): require focused tests before integration checks

* docs(autofix): clarify review verification guidance

* fix(acp-bridge): close prompt-terminal follow-ups from the PR #7400 self-review (#7453)

* fix(acp-bridge): close prompt-terminal follow-ups from PR #7400 self-review

Keep a removed RUNNING prompt visible to the teardown flush via a removed flag so its terminal still publishes when the session closes before the agent cooperates; gate broadcastTurnError's session turn-state mutation to running prompts; propagate the typed PromptDeadlineExceededError from the pre-dispatch abort check; document the deadline FIFO-release overlap trade-off, the trailing prompt_cancelled after flush, and the result.then/finally ordering invariant; route the dedup log to the debug channel; drop the prompt-deadline re-export that pulled the bridge into a leaf module.

Fixes #7451

* test(acp-bridge): cover promote-then-remove-then-settle duplicate completed guard (#7453)

---------

Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>

* fix(core): strip Qwen-internal daemon secrets from agent-spawned child env (#7256)

* fix(core): strip Qwen-internal daemon secrets from agent-spawned child env

Shell subprocesses (and the monitor tool and stdio MCP servers) inherited
the full daemon process.env, including QWEN_SERVER_TOKEN (the serve-daemon
bearer credential), so an agent-run command like printenv QWEN_SERVER_TOKEN
could read an internal secret. Add a shared sanitizeChildEnv() that removes
Qwen-internal daemon/server tokens (QWEN_SERVER_TOKEN, QWEN_DAEMON_TOKEN)
before spawning, and apply it at the shell child_process + PTY paths,
monitor.ts, and the mcp-client stdio transport.

The denylist is deliberately narrow: it does NOT strip third-party
credentials (GH_TOKEN, AWS_*, NPM_TOKEN, ...) that real shell workflows
legitimately inherit -- only Qwen-internal secrets. Exported from the
package root so the desktop denylists can consolidate onto it later.

Fixes #6601.

* test(core): cover daemon-secret stripping on monitor and mcp-client spawn sites

* test(core): replace process.env instead of mutating in shell sanitization tests

The file restores process.env by reference in afterEach, so in-place key
mutations leaked into later tests. Use the replacement pattern already used
by setupConflictingPathEnv.

* docs(core): align JSDoc @param names with actual function signatures (#7492)

Fix 6 instances where JSDoc @param tags had drifted from their
corresponding function signatures — parameters were renamed, removed,
or undocumented over time but the doc blocks were not updated.

Closes #7446

* feat(serve): support forced MCP reconnects (#7488)

* feat(serve): support forced MCP reconnects

* test(serve): cover forced MCP reconnect options

---------

Co-authored-by: 克竟 <dingbingzhi.dbz@alibaba-inc.com>

* fix(cli): insert newline on Shift+Enter and stop streaming thinking-block flicker (#7397)

* fix(cli): re-push Kitty keyboard flags onto the alternate screen in VP mode

In VP mode the app renders on the alternate screen (`alternateScreen: true`),
but the Kitty keyboard progressive-enhancement flags were pushed only once at
startup on the main screen. The Kitty spec tracks these flags per screen
buffer, so the alternate screen's stack stays empty and the terminal never
reports modifiers: Shift+Enter arrives as a bare Enter (submit) or, when the
terminal emits an ESC-prefixed variant, as an orphaned Escape that trips the
empty-buffer double-Esc rewind prompt — so Shift+Enter can never insert a
newline in VP mode even on Kitty-capable terminals (e.g. cmux).

Re-push the flags onto the alternate screen right after Ink enters it (Ink
writes the enter-alt-screen sequence synchronously inside render(), so the
push is correctly ordered). Ink discards the alternate screen and its flag
stack on unmount, leaving the startup main-screen push balanced by the
existing disableKittyProtocol() on cleanup.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(cli): stabilize streaming thinking block height to stop flicker

The pending "Thinking…" block renders the tail of the reasoning stream in a
content-sized box. As the model emits paragraph separators, a blank line
enters and leaves the tail window (and `trimEnd` drops trailing blanks), so the
visible line count oscillates and the block flickers 2→3→5 rows during
streaming.

Track the tallest height the block has reached for the current thought and
never render fewer rows than that (capped at the streaming window size),
padding at the top so the newest line stays pinned to the bottom. The tracker
resets when streaming ends or when the buffer shrinks (a new thought replaced
it), so height is monotonic within a thought without leaking across thoughts.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(cli): decode xterm modifyOtherKeys Shift/Ctrl/Alt+Enter so it inserts a newline

Terminals such as Ghostty report Shift+Enter as the xterm modifyOtherKeys
sequence `ESC [ 27 ; <mods> ; <key> ~` (e.g. `ESC [ 27 ; 2 ; 13 ~`) when the
Kitty keyboard protocol is not negotiated — which is the default, since Kitty
detection does not always succeed. Two bugs kept this from inserting a newline:

1. The CSI-u parser read the leading `27` marker as the key code (matching the
   Escape key code 27) instead of the real key code in the third parameter, so
   with Kitty enabled Shift+Enter was mistaken for Escape and tripped the
   double-Esc rewind prompt.
2. The reassembly path that stitches readline's shredded CSI fragments back
   together was gated behind `kittyProtocolEnabled`, so with Kitty disabled the
   `ESC [ 27 ; 2 ;` head plus the stray `13~` tail leaked into the composer as
   literal text and no newline was inserted.

Decode the third parameter as the real key code for the `27;…~` form, and route
those sequences through the reassembly buffer even when Kitty is off (only the
`ESC [ 27` marker opts in, so keys readline already parses cleanly are
untouched). Shift/Ctrl/Alt+Enter now insert a newline in both VP and non-VP
mode regardless of Kitty negotiation.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(cli): anchor VP viewport to the top until a conversation turn exists

On a fresh VP-mode session the virtualized list holds the banner plus startup
notices (tips / MOTD / info), so it is longer than one item. Keying the initial
scroll anchor off list length alone selected scroll-to-end, which pinned the
banner to the bottom of the full-height viewport and left the top half of the
screen blank.

Anchor to the top until there is an actual conversation turn (a user/user_shell
history item or a pending response), then resume scroll-to-end so the latest
output stays in view. Startup notices no longer count as content that forces
bottom alignment.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(cli): stabilize streaming thinking window against availableTerminalHeight drift

The grow-only streaming thinking window still flickered because its line cap was
derived from availableTerminalHeight. While a thought streams the terminal keeps
constrainHeight on, so availableTerminalHeight (and the derived maxLines) drifts
up and down as sibling pending content grows, and the grow-only clamp
`min(maxLines, …)` shrank the block whenever it dipped.

Use a constant window height (MAX_STREAMING_THINKING_VISUAL_LINES) for the
pending window instead. The window is only a few lines, so a fixed cap cannot
meaningfully overflow (VP scrolls anyway), and the height stays stable while
still growing monotonically within a thought.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* Revert "fix(cli): anchor VP viewport to the top until a conversation turn exists"

This reverts commit fbe86a9e159b75ea1f5b689cc327599c9dc91090.

* fix(cli): guard modifyOtherKeys detection against keypresses without a sequence

The modifyOtherKeys prefix check ran on every keypress, but some synthetic
keypresses (and the useKeypress test harness) emit a key with no `sequence`,
so `key.sequence.startsWith(...)` threw an unhandled rejection. Use optional
chaining so a missing sequence is simply not a modifyOtherKeys start.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* test(cli): mock pushKittyProtocolFlags in gemini.test.tsx kitty mock

The kittyProtocolDetector mock omitted the newly added pushKittyProtocolFlags
export. Add it so the mock stays in sync with the real module and a VP-mode
startup path exercised through this suite cannot hit an undefined call.

Generated with AI

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

---------

Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(web-shell): open singleton subagent details (#7495)

Co-authored-by: ytahdn <ytahdn@gmail.com>

* fix(web-shell): avoid redundant git status requests (#7496)

Co-authored-by: ytahdn <ytahdn@gmail.com>

* fix(agent): ignore empty working_dir placeholders (#7343)

* fix(agent): ignore empty working_dir placeholders

* test(agent): align empty working_dir expectations

* feat(prompts): allow overriding core identity via QWEN_SYSTEM_IDENTITY_MD (#7478)

* feat(prompts): update prompts.ts for QWEN_SYSTEM_IDENTITY_MD

* feat(prompts): update prompts.test.ts for QWEN_SYSTEM_IDENTITY_MD

* fix(prompts): address CR on QWEN_SYSTEM_IDENTITY_MD

Keep getDefaultCoreIdentitySentence private, fail loud on path
resolution errors, use trimEnd, and resolve identity only on the
default-prompt branch.

* test(prompts): align identity override tests with CR feedback

Sample default identity from live prompt, cover trimEnd trailing
whitespace, and assert homedir resolution failures throw.

---------

Co-authored-by: 易良 <1204183885@qq.com>

* fix(cli): yield to single-slot background agents (#7258)

Co-authored-by: hogeheer <267467744+hogeheer499-commits@users.noreply.github.com>

* docs(autofix): require evidenced pre-commit verification, not a bare "verified" (#7486)

* docs(autofix): require evidenced pre-commit verification, not a bare "verified"

The skill already said to run build/typecheck/lint/Vitest before
committing, but softly — and #7408 committed a fix with a TS error the
gate then rejected while its summary claimed "verified all 3 commits".
A self-assessment the gate contradicts wastes a whole round.

Strengthens the address-review contract from "run the checks" to:
- actually run them, do not assert them from reading the diff;
- if typecheck or a touched-package test fails, do NOT commit — treat
  the feedback as unresolved (failure.md);
- end address-summary.md with a `## Verification` section listing each
  command run and its result; a bare "verified" is not acceptable.

The framing is structural, not etiquette: the deterministic gate re-runs
the same commands and discards the round on any failure, so skipping them
only moves the rejection later. Pinned by a test so it cannot soften back.

This is the checkable half of "audit before committing" — the
undirected/reverse-audit-until-clean practice does not transfer to an
unsupervised agent (no verifiable stopping condition, and it worsens the
timeouts seen on large PRs), but "run the gate's own checks first and
show the evidence" does.

* fix(autofix): clarify Verification section precedes collapsed Chinese translation (#7486)

---------

Co-authored-by: wenshao <wenshao@example.com>
Co-authored-by: qwen-code-ci-bot <qwen-code-ci-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>

* feat(autofix): stop a PR that fails to push for N rounds in a row (#7482)

* feat(autofix): stop a PR that fails to push for N rounds in a row

Under takeover the round cap is 100, which is right for a PR that needs
many PRODUCTIVE rounds. It is wrong for one that fails every round: #6723
ran 7 consecutive failed rounds (3 agent timeouts at 50 min, 4 gate
rejections whose fix broke tests) over 8 hours, heading for round 100,
because it is a 5700-line, 47-file, 5-day-old PR racing a fast-moving
main — every round re-resolves a conflict it cannot finish or that fails
the gate. Retrying at the same per-round budget will not converge; a
human has to rebase or split it.

Adds CONSECUTIVE_FAILURE_CAP (5), distinct from the total round cap. The
handoff step already runs only when a round did NOT push, so it counts
the unbroken run of prior failure markers — stopping at the first push
("Addressed the latest review feedback") or legitimate no-op ("no
changes needed"), either of which proves progress and resets the streak.
At the cap it forces the terminal round even under takeover, with a
handoff that names the real fix (rebase/split, then /retry). Cause-
agnostic: a timeout and a gate rejection both count.

* fix(autofix): address review feedback on consecutive-failure circuit breaker (#7482)

- Fix misleading comment: the walk is oldest-first (API order) with
  reset-on-success, not newest-first with early stop
- Prefer the already-fetched ic.json over a redundant gh api call,
  falling back to the API only when the file is missing
- Filter eval markers by re-arm window (win=) so pre-re-arm failures
  do not immediately re-terminate a re-armed PR
- Add test coverage for the MARK_ROUND == MAX_ROUNDS guard and for
  window-scoped streak counting

* fix(autofix): exempt transient model errors from consecutive-failure breaker (#7482)

---------

Co-authored-by: wenshao <wenshao@example.com>
Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>

* feat(core): restore background agent roster (#7459)

* feat(core): restore background agent roster

* fix(web-shell): add list_agents to TOOL_DISPLAY_NAMES

The new list_agents core wire tool was added to core's ToolNames but not
to the web-shell TOOL_DISPLAY_NAMES map, causing toolFormatting.drift.test.ts
to fail (expected ['list_agents'] to deeply equal []). Add the missing
'ListAgents' display-name entry so the browser panel shows a friendly name
instead of the raw wire name and the drift guard passes.

* fix(cli): reload old-session background agents on failed resume rollback

When /resume fails after core has swapped but before the UI swap, the catch
block rolls core back to the old session via startNewSession(oldSessionId).
However the forward path already called resetBackgroundStateForSessionSwitch,
which cleared the old session's in-memory background agents. The rollback did
not reload them, so list_agents returned empty for the old session (whose
sidecars are still on disk) until the next process start or successful resume.

Reload the old session's paused background agents after rolling core back, so
the restored roster matches on-disk state. Placed after startNewSession so the
loadPausedBackgroundAgents current-session guard is satisfied; best-effort via
.catch so it never blocks the rollback path.

* fix(web-shell): add zh translation for list_agents tool name

The toolFormatting test 'has a zh translation for every tool in the
display-name map' failed with expected ['list_agents'] to deeply equal []
because list_agents was added to TOOL_DISPLAY_NAMES without a matching
toolName.list_agents zh-CN entry. Add the translation to restore parity.

* fix(cli): resolve CI failures for background-agent roster restore

- Add toolDisplayName.ListAgents translations (en, zh, zh-TW, ca) so the
  new list_agents tool has a zh entry; fixes i18n/index.test.ts.
- Add loadPausedBackgroundAgents and consumePendingRecoveredAgentsNotice
  to the acpAgent worktree test config mock, which loadSession now calls
  via #restoreBackgroundAgentsOnResume; fixes acpAgent.worktree.test.ts.

* refactor(core): extract incompatible-isolation blocked reason to a const

Move the incompatible-isolation blocked-reason string out of an inline
literal into a module-level INCOMPATIBLE_ISOLATION_BLOCKED_REASON const,
matching its four sibling reasons so the text is discoverable by
constant-name grep and edited alongside the others.

* fix(core): preserve retained activity state on failed agent revive

Address review feedback on the background-agent roster restore:

- On a failed completed-agent revive, restore UI state with a non-empty
  guard instead of `??`. Because `restorePausedEntry` resets the paused
  entry's `recentActivities` to `[]`, the previous `failedEntry?.field ??
  completedEntry.field` kept that empty array and dropped the pre-revive
  snapshot (the UI Progress section rendered empty). Applied consistently
  to pendingMessages, recentActivities, and pendingApprovals.

Add regression coverage for previously untested paths:

- failed revive preserves pre-revive recentActivities
- terminal-agent cap admits only the newest MAX_RETAINED_TERMINAL_AGENTS
  completed sidecars on restore
- /resume rollback reloads the old session's background agents
- headless resume prepends the recovered-agents notice to the prompt

* test(cli): cover interrupted-turn continuation not consuming recovered-agents notice

Add ACP and headless regression tests asserting an interrupted-turn
continuation does not consume the one-shot recovered-agents notice
(the !isContinue / !continueInterrupted guards), so it is delivered on
the user's next ordinary prompt. Mirrors the existing slash-command
coverage.

---------

Co-authored-by: Claude <noreply@anthropic.com>

* feat(cli): support custom skill directories via settings (#7395)

* feat(cli): support custom skill directories via settings (#7394)

Add skills.directories setting that accepts an array of additional
directory paths to scan for skills (SKILL.md files). Paths support
~ expansion. Directories are scanned recursively at user level,
after the default ~/.qwen/skills/ directory.

Example settings.json:
{
  "skills": {
    "directories": ["~/.agent/skills", "~/.claude/skills"]
  }
}

Changes:
- settingsSchema.ts: add skills.directories array setting
- core Config: add customSkillDirs param and getCustomSkillDirs()
- SkillManager: append custom dirs to user-level skill base dirs
- CLI config: read skills.directories and pass to core Config

* fix(cli): regenerate settings schema for skills.directories (#7394)

* fix(core): address review feedback for custom skill directories (#7395)

- Use optional chaining for getCustomSkillDirs() to prevent TypeError
  on partial Config mocks (workspace-skill-management, workspace-skills-status)
- Reuse expandHomeDir utility instead of inline tilde expansion
- Fix inaccurate 'scanned recursively' wording to 'one level deep'
- Correct JSDoc: paths are raw, expansion happens in SkillManager
- Trim whitespace from custom dir entries in CLI layer
- Add tests for custom dir expansion, dedup, and partial config safety

* fix(core): address review feedback for custom skill directories (#7395)

* fix(core): address review feedback for custom skill directories (#7395)

* test(core): add relative path resolution test for custom skill dirs (#7395)

* fix(cli): add Array.isArray guard for skills.directories and safe mode test (#7395)

* fix(skills): address review feedback on custom skill directories (#7395)

- Add bare mode test for skills.directories guard
- Include resolved absolute path in relative directory warning
- Clarify that dedup applies to default user dirs, not bundled skills
- Regenerate settings schema

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>
Co-authored-by: qwen-code-ci-bot <qwen-code-ci-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>

* fix(core): add image modality support for qwen3.8-max and kimi-k3 models (#7491)

* fix(core): add image modality support for qwen3.8-max models

qwen3.8-max-preview supports image input but was falling through to the
catch-all text-only rule because no pattern matched it. This caused the
vision bridge to unnecessarily transcribe images via a secondary model
instead of sending them directly to the primary model.

* fix(core): also add image modality for kimi-k3

Kimi K3 officially supports image + video input but was falling through
to the catch-all text-only rule, same issue as qwen3.8-max.

* fix(dingtalk): preserve non-bot mention context (#7473)

* fix(dingtalk): preserve non-bot mention context

* test(dingtalk): cover plural mentions, staffId fallback, and edge cases (#7473)

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>

* fix(core): harden the usage salvage around session deletion (#7425)

Post-merge review follow-ups on #7391 (three findings):

- Salvage the archived transcript in the active-branch deletion too:
  when both copies co-exist (an interrupted archive) and the fresh
  active transcript carries no telemetry, the archived copy holds the
  session's usage history and was deleted unsalvaged. The dedup guard
  makes the extra call a no-op whenever the active copy already wrote.
- Enforce the "never blocks deletion" contract at the call site: a
  salvageUsageBestEffort wrapper catches and warns, so the guarantee is
  structural rather than an implementation detail of
  persistUsageBeforeTranscriptDeletion. The new failure-tolerance test
  (salvage rejects -> deletion still succeeds) fails without the
  wrapper — the bare await let the rejection escape through
  removeSessionFiles' rethrowing catch.
- Clear the salvage module mock in beforeEach so the wiring test's
  invocationCallOrder assertions can never read stale calls.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* fix(core): make fork subagents discoverable (#7460)

* test(core): cover Shell truncation without an artifact (#7470)

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(ci): autofix route checks existing labels on non-trigger label events (#7481)

* fix(ci): autofix route checks existing labels on non-trigger label events

When triage adds multiple labels in sequence, per-issue concurrency
cancels earlier runs. If the last label is not a trigger label
(e.g. scope/build-system), the surviving run skips the issue phase
even though the issue already has autofix/approved +
status/ready-for-agent.

Before ignoring a non-trigger label event, check ISSUE_LABELS_JSON
for both required labels. If present and the issue is open, proceed
with the issue phase. Trust was already established when the trigger
labels were applied (both require triage+ permission).

* fix(ci): require trusted sender for label fallback

* feat(cli): preserve semantic text when copying VP selections (#7286)

* docs(cli): define semantic copy fidelity scope

* docs(cli): address semantic frame review gaps

* docs(cli): preserve soft-wrap source separators

* feat(cli): preserve semantic selection copy

* fix(cli): address semantic copy review findings

* fix(cli): preserve clipped semantic boundaries

* fix(cli): limit separator carrier joiner to visible width in wrap metadata

The greedy /\s+/ match in wrapTextWithMetadata could capture more
source whitespace than the separator carrier row actually consumed
(e.g. a tab following a space), causing duplicated whitespace in
semantic copy. Limit the match to visibleLine.length characters and
add a mixed space/tab regression test.

---------

Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com>

* test(core): stub the registry methods agent.ts actually calls (#7538)

The shared stubRegistry in agent.test.ts was missing six methods that
agent.ts reaches: bridgeApprovalEvents, getQueuedCount,
registerResidentAgent, restartCompletedAgent, unregisterResidentAgent and
waitForMessages.

That is not a benign omission. The background body wraps its work in a
try/catch that routes any throw into registry.fail(), so a missing method
never surfaces as 'not a function' — it silently converts a successful
run into a failed one. On the GOAL completion path
unregisterResidentAgent is called immediately before complete(), so the
TypeError replaced the completion entirely:

  registry.fail('fork-...', 'registry2.unregisterResidentAgent is not a
  function', ...)

That is what broke 'runs a non-interactive fork through the background
registry' on main. #7460 added the registry.complete assertion, which
exposed the incomplete stub — before it, nothing checked whether the
background body finished successfully and the TypeError was swallowed.

Stub all six with their real return shapes (unregisterResidentAgent
returns boolean, bridgeApprovalEvents returns the unsubscribe callback
agent.ts later invokes, waitForMessages resolves to a list) and assert
registry.fail was not called before asserting completion, so a future
gap reports the actual error instead of 'complete: 0 calls'.

* perf(startup): lazy-load Google GenAI SDK on first use (#7512)

* perf(startup): lazy-load Google GenAI SDK on first use

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* codex: address PR review feedback (#7512)

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* codex: address PR review feedback (#7512)

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

---------

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(vscode): use file picker image paths for vision input (#7493)

* fix(vscode): use image paths from file picker

* fix(vscode): keep image picker paths raw

* fix(vscode): resolve image picker paths on submit

* fix(vscode): send picked images as vision context

* fix(vscode): encode prompt image file URIs

* fix(vscode): address image path review comments

* test(vscode): cover image file reference edge cases

* fix(cli): open the actual serve fallback port (#7501)

* fix(cli): open actual serve fallback port

* test(cli): match serve URL to fallback listener

* docs(cli): clarify serve listen error handling

---------

Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>

* fix(ci): don't let one failing scenario sink the whole visual preview (#7511)

The web-shell visuals render runs every screenshot and flow in a single
`test:e2e:visuals`, and that step had no `continue-on-error`, while the compose
and upload steps had no `if: always()`. So one failing or timing-out scenario
failed the job, the artifact was never uploaded, and the publish workflow had
nothing to post — the entire preview vanished even when every other scenario
passed and its PNG was already on disk. A flow (a long multi-click sequence) is
the most fragile scenario kind, so the fragile one silently takes down the
deterministic screenshots. PR #7498 hit exactly this: 29 scenarios passed, one
new channel-management flow timed out, and the PR got no preview and no comment
at all.

Make the after-capture step `continue-on-error` so the passing captures survive
and the later steps still compose and upload them. The publish job only runs on
a `success` conclusion, so the job must stay green — but a masked failure must
not read as a clean preview. Ship the step's real `.outcome` (which
continue-on-error does NOT mask, unlike `.conclusion`) to the publisher as
`render-status.txt`, and have the comment builder use it: an empty preview whose
render failed says "one or more scenarios failed to render" and is explicitly
NOT the reassuring green check or the coverage-gap prompt (both imply the render
ran); a partial preview is labelled partial above the shots that did render. A
missing status file (older run) defaults to complete, so this only ever adds a
warning, never suppresses a real preview.

The failing scenario still needs fixing — it's now surfaced in the comment
rather than by silently deleting everyone else's preview.

Co-authored-by: wenshao <wenshao@example.com>

* feat(web-shell): add selective shadow DOM isolation (#7551)

Co-authored-by: 钉萁 <dingqi.jww@alibaba-inc.com>

* feat(web-shell): add renderChatHeader slot for custom session header (#7553)

* fix(cli): say review coverage gaps in the author's units, not chunk ids (#7550)

The posted review body rendered coverage disclosures with the run's own
bookkeeping as subjects: bare chunk ids, unsorted, one per subject. On a
run that certified nothing (PR #7268) the body enumerated all 49 chunk ids
across two sentences while opening with "Reviewed. Suggestions are
inline." — the opener certified the exact thing every following sentence
took back, and nothing on the PR page maps a chunk id to code.

Three changes, all render-time — the structural entries, the caps, the
caller-echo dedup and the stderr remediation still key on chunk ids, which
is where the id is the selector a reader can act on:

- Coverage now returns the plan's chunk→files table (DiffChunk.files was
  already in the plan JSON; the coverage type slice dropped it).
- compose-review renders chunk gaps through describeChunkGap: every
  planned chunk collapses to "the entire diff", a narrow gap with known
  files names the files, and anything wider is counted against the plan's
  total. Applied to the receipt sentence, the uncoverable sentence (bare
  CLI entries only — caller-authored entries render verbatim) and the
  grouped per-cause sentences.
- The COMMENT opener may no longer say "Reviewed." over a disclosure set
  that denies it: when no chunk is both covered and undisclosed — or no
  chunk universe could be read at all — it opens with a zero-certified
  warning instead. A rewritten launch demonstrably read its chunk, so
  coverage alone is not the test; certified is covered with no disclosure
  against it.

Co-authored-by: verify <verify@local>

* fix(autofix): retry a skipped-Prepare instead of stranding the PR terminal (#7490)

* fix(autofix): retry a skipped-Prepare instead of stranding the PR terminal

A base/infra failure BEFORE the agent runs was misread as an agent crash
and terminated the PR forever. When an early step fails — installing or
building the trusted base, checkout, node setup — the `Prepare branch and
feedback` step is skipped, so NEWEST is empty, and the report step's
"crashed before reading feedback" branch fired: MARK_ROUND=MAX_ROUNDS,
terminal, scan skips it on every future tick.

Observed: a web-shell TypeScript break on `main` failed `Install
dependencies and build` (which builds the trusted base) across a whole
scan batch, and SIX healthy PRs were stranded terminal at round=100 in
one run — including ones at round 9 and 11 that had nothing to do with
the break. `round=100` there is a terminal sentinel, not 100 attempts.

NEWEST-empty now splits on steps.prepare.outcome:
- 'skipped' (an earlier step failed, the agent never ran) is infra/base
  and transient: retry with a sentinel ts so the feedback stays live,
  incrementing the round so a PERSISTENTLY broken base is still bounded
  and stops at the cap (recoverable with /retry).
- 'success'/'failure' (Prepare ran, no feedback produced) is a genuine
  pre-read agent crash: unchanged terminal behaviour.

This is the reverse of the asymmetry #7482 addresses: that bounds a
crash AFTER reading that retried forever; this stops a transient failure
BEFORE reading from going terminal after one.

* docs(autofix): note a pre-Prepare cancel also retries intentionally (#7490)

* fix(autofix): also retry a cancelled/empty prepare outcome, not just skipped

A previous review comment on this PR noted that a job cancelled before
Prepare should retry too. It was right about the intent but the code did
not do it: `steps.prepare.outcome` is 'cancelled' for a cancel and '' for
a job that stopped before Prepare entered the step context — both DISTINCT
from 'skipped', so `== 'skipped'` sent them to the terminal branch, the
same over-termination this PR exists to fix.

Match on "not a real Prepare run" (`!= 'success' && != 'failure'`)
instead, so skipped, cancelled, and empty all retry; only a Prepare that
actually ran to a verdict (success/failure) with no feedback stays
terminal — the genuine pre-read agent crash. Test extended to drive the
cancelled and empty cases (retry) and both real-run outcomes (terminal);
mutation-verified that reverting to `== 'skipped'` reddens the cancelled
case.

* test(autofix): update the pre-read-crash case for the broadened retry

The prior commit broadened NEWEST-empty retry to skipped/cancelled/empty
but left the older 'replays the handoff decision' test asserting the old
terminal behaviour for an unset PREPARE_OUTCOME (which now retries). That
test's terminal cases now set PREPARE_OUTCOME=success/failure explicitly —
the only outcomes that still terminate — so it exercises the genuine
pre-read agent crash rather than the infra/cancel path.

* test(autofix): anchor the skipped-Prepare extraction past the CONSEC block

CI reddened `retries a skipped-Prepare` after main's consecutive-failure
cap (#7482) merged into this branch: that block was inserted between this
decision block and the report `{`, and it calls `gh api`. The test's
`{`-anchored regex over-captured through it, so the extracted script ran
the unstubbed `gh api` and failed. Anchor the end on the same
`# Consecutive-failure` comment the sibling gate-crash test already uses,
so the extraction stops at this decision block's own closing `fi`.

* fix(autofix): exempt skipped-Prepare from the consecutive-failure breaker

A broken base build skips Prepare, producing no API error file — so the
consecutive-failure breaker ran on the new retry path and, after 5
scans, re-introduced the exact mass-stranding this PR exists to prevent.
Exempt pre-agent infra failures (skipped/cancelled/empty outcome) from
the breaker, mirroring the transient 429/5xx exemption: same failure
class (not the PR's fault, self-heals, hits the whole batch). The round
cap + sentinel-ts /retry recovery already bounds a persistently broken
base.

Also trim "checkout" from the retry headlines (checkout failures do not
land in this branch) and hoist the duplicated MARK_TS assignment.

* fix(autofix): reset the consecutive-failure streak on prior infra-failure markers

The streak walker counted prior infra-failure headlines ("AutoFix could
not start —…") as failures, inflating the consecutive-failure count on
subsequent rounds.  A PR with 3 real agent failures, then 3 rounds of
base-build infra failures, then 1 more real failure would trip the
cap-5 breaker even though only 4 rounds were the PR's fault.

Add the two infra-failure headline patterns as reset strings in the
streak walker, alongside the existing push and no-op resets.  The
genuine agent-crash headline ("AutoFix could not start evaluation —…")
is deliberately excluded — it is a real failure and must still count.

* fix(autofix): clarify infra-failure headlines and else-branch comment (#7490)

Address review nits: the retry headline now mentions cancelled runs,
the cap headline says 'reached the round cap' instead of overstating
'could not start for N rounds', the else-branch comment says 'prepare
itself crashed' instead of 'agent crash', and the streak-reset pattern
is simplified now that both infra headlines share the same prefix.

---------

Co-authored-by: wenshao <wenshao@example.com>
Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>
Co-authored-by: qwen-code-ci-bot <qwen-code-ci-bot@users.noreply.github.com>

* fix(cli): keep role codenames and brief paths out of the posted review body (#7560)

The posted body still carried two operator registers #7550 left in place:
roster role subjects rendered their internal codenames ("Agent 1c:
Cross-file tracer", "Test coverage matrix (whole-diff)"), and an unread
brief's disclosure interpolated its filesystem path. And when verify and
the reverse audit failed the same way, the body said it twice, in two
near-identical sentences.

- Every Brief now carries a publicLabel — the dimension said as what it
  checks ("the cross-file consistency pass") — and coverage's structural
  disclosures carry it as publicSubject beside the internal subject, plus
  a path-free publicReason for unread briefs. The internal label and the
  path stay on stderr, where they are the selector an operator acts on;
  every dedup and certification check still keys on the internal subject.
- compose-review renders the public fields and groups by the reason the
  body PRINTS, so two unread briefs share one path-free sentence instead
  of repeating it per role.
- verificationGaps merges verify and reverse-audit failures of the same
  delivery shape into one sentence with both subjects and both
  consequences; mixed shapes keep their precise per-role texts, and the
  per-role rebuild commands stay on stderr either way.

Co-authored-by: verify <verify@local>

* fix(autofix): retry an agent timeout instead of advancing past its feedback (#7563)

A timeout evaluated NOTHING — the agent ran out of budget before finishing,
so nothing was committed and the feedback is unaddressed. It was treated as
an evaluated verdict (real ts, watermark advances), which strands that
feedback: the next scan sees "nothing new" and never retries. Observed on
#7471 (round 13/100), a heavily-reviewed 1871-line PR: rounds 11 and 13
timed out, but round 12 pushed — so a timeout is transient far more often
than not, and advancing past it left the round-13 feedback unhandled.

run-agent.mjs now drops an `agent-timeout` signal on result.timedOut, and
the handoff routes it like a pre-verdict crash: sentinel ts (feedback stays
live) and a retry, with a headline that names the real fix at the cap
(split the PR or raise the budget). A PR that PERSISTENTLY times out is
bounded by the round cap and the consecutive-failure cap, so this cannot
loop forever — it just stops treating a one-off budget blip as a verdict.

The loop guard stays terminal (a tool-call loop is a real defect, not a
budget blip). An API error still routes to its own model-key handoff; the
timeout signal is written only when NOT an API error.

Co-authored-by: wenshao <wenshao@example.com>

* feat(serve): add workspace-level generation (#7552)

* feat(serve): add workspace-level generation

* docs(serve): document workspace generation capability

* fix(serve): align workspace generation contracts

---------

Co-authored-by: ytahdn <ytahdn@gmail.com>

* ci: matrix ECS runner update + sudo install + repository_dispatch trigger (#7513)

* ci: matrix ECS runner update with sudo install

- Use matrix strategy (ecs-update-sg, ecs-update-64c) to update both
  physical ECS hosts in parallel (fail-fast: false).
- Always use sudo npm install -g so the package lands in /usr/local
  (system-wide PATH) instead of the runner user's home directory.
- Move concurrency to job level (matrix context not available at
  workflow level per actionlint).
- Add repository_dispatch trigger for release-driven updates.
- Register new runner labels in actionlint.yaml.

* fix(ci): use dispatch version for runner update

---------

Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>

* fix(web-shell): include managed id in artifact open requests (#7570)

Co-authored-by: 钉萁 <dingqi.jww@alibaba-inc.com>

* feat(serve): persist workspace channel configuration (#7514)

* feat(serve): persist workspace channel configuration

* fix(serve): harden channel settings snapshots

* fix(serve): validate startup channel names

* fix(serve): reserve all channel name

---------

Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>

* fix(sdk-python): require canonical form in validate_session_id (#7532)

uuid.UUID() accepts several non-canonical spellings — braced
{...}, urn:uuid:..., and dash-less hex — so validate_session_id let them
through after the RFC 4122 variant check. The value is then forwarded to
the CLI verbatim as --session-id/--resume, producing a malformed session
id downstream rather than a clear error at the SDK boundary.

Reject anything whose canonical form differs from the input. Case is
deliberately not part of the comparison: UUID() lowercases, and an
all-uppercase spelling is still valid canonical input.

Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>

* fix(web-shell): sync background agent status (#7561)

* fix(web-shell): sync background agent status

* fix(web-shell): harden background agent reconciliation

---------

Co-authored-by: ytahdn <ytahdn@gmail.com>

* feat(core): propagate trusted daemon invocation context (#7279)

* feat(core): propagate trusted daemon invocation context

* test(cli): update ACP startup expectation

* refactor(core): centralize ACP capability env key

* test(cli): update worktree ACP core mock

* test(integration): run daemon context smoke on PRs

* test(ci): update no-AK smoke expectation

* test(core): cover invocation context isolation

* fix(cli): compare ACP capability safely

* fix(docs): restore GitHub action input names

* fix(core): sanitize private ACP capability from child env

* fix(core): reuse private ACP capability env constant

* test(cli): cover malformed trusted invocation context

* test(acp-bridge): assert exact child environment

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: 易良 <1204183885@qq.com>

* fix(feishu): await stream cancels in media download teardown (#7465)

* fix(feishu): await stream cancels in media download teardown

downloadMedia left two reject paths' stream teardown unawaited:

- the oversize-stream path called reader.cancel() without awaiting, so a
  cancel error during teardown became an unhandled rejection (fatal under
  Node's default --unhandled-rejections=throw);
- the Content-Length reject path returned without cancelling resp.body,
  leaving the connection pinned until GC.

Both were already fixed for the sibling DingTalk downloader in #7361 (which
was itself modelled on this Feishu code), so this brings Feishu to parity.
Adds a regression test that pins the reader.cancel() await via a rejecting
cancel, plus an assertion that the Content-Length path releases the body.

* test(feishu): cover a rejecting body.cancel() on the Content-Length path

Mirrors the existing reader.cancel() teardown test for the other reject
path, per review feedback. Removing the await on resp.body?.cancel()
flips execution onto the 'rejected: size ... exceeds' branch and the
test fails.

* fix(autofix): make the review-address report wrapper lines bilingual (#7569)

The agent's address-summary.md / no-action.md already ends with a
collapsed Chinese translation, but the workflow-appended wrapper lines
around it — the "Addressed/Reviewed the latest feedback" lead-in, the
"Base-conflict check" line, and the "Re-review when you have a moment"
footer — were English-only and sat outside that block. So the posted
comment was only half translated, unlike the takeover-ack comments
(full collapsed Chinese block) and the "model/模型" sign-off in this
same report (already inline-bilingual).

Give each wrapper line an inline Chinese translation, matching the
model/模型 idiom. The English halves are preserved verbatim — the
streak-reset detector globs on "Addressed the latest review feedback"
and "no changes needed", and a test extracts these lines — so behaviour
is unchanged and old English-only comments still match. A new test pins
each English-Chinese pair so a future reword that drops the Chinese
fails. The terminal handoff/failure comment is left English-only for
now (SKILL.md keeps it so by design); that is a separate change.

Co-authored-by: wenshao <wenshao@example.com>

* feat(cli): post the review body bilingually when the PR description is Chinese (#7564)

When the PR author writes Chinese, the posted /review body was
English-only. fetch-pr now records whether the PR description contains
Han characters (prDescriptionHasHan, detected from the same gh pr view
call and stamped into the plan report), and compose-review renders the
body bilingually off that flag: the English body leads, the complete
Chinese version rides collapsed in a <details><summary>中文说明</summary>
block, and the model footer stays outside the fold. The signal is the
CLI's own — the caller cannot toggle the register of a certified body —
and a local plan has no field, so nothing changes for terminal-only
reviews.

Every deterministic body fragment carries an en/zh pair end to end:
compose-review's clause templates and describeChunkGap phrases, the
coverage disclosures (reasons, publicLabel role subjects via a new
publicLabelZh, the path-free unread-brief reason) and the Step 4/5 gap
texts including the combined same-shape sentence. Fragments with no
deterministic translation — model-written findings, caller echoes,
interpolated errors — ride verbatim in both halves. verificationGaps now
returns structural {subject, reason, subjectZh, reasonZh} entries, which
also removes compose-review's last recover-the-boundary-from-prose parse.

SKILL.md instructs the same format for the model-authored inline
comments: English finding first (marker and suggestion block stay in the
English half — tooling filters on them), full Chinese translation
collapsed beneath, footer last.

Co-authored-by: verify <verify@local>

* feat(autofix): auto-rerun a check that died on infrastructure, once (#7562)

* feat(autofix): auto-rerun a check that died on infrastructure, once

A failed check can be red because the machine died, not the code — a
self-hosted runner losing the server, the disk filling. #7490's E2E
failed with "runner lost communication with the server" and went green
on a rerun. The scan now reruns such a check's failed jobs automatically.

Detection is a conservative annotation whitelist (INFRA_FAILURE_SIGNATURES)
— only unambiguous machine failures, never a test-level timeout, which
could be a real regression. The one-shot guard is run_attempt, not a
marker: a run already retried to attempt 2 and still infra-failing is
persistent, so it is left for a human; after a rerun the attempt
increments, so the next scan will not rerun it. Every step is fail-safe
(any API error → no rerun), it runs only when the PR actually has a
failed check, and the gate carries the same review-address carve-out as
the other check selectors so the loop never reruns its own runs.

This is the transient-infra sibling of #7554 (stale-base): that merges
current main when a check is base-inherited; this reruns when a check
died on the runner. Neither touches a check that is a genuine failure.

Note: rerun-failed-jobs needs the PAT to hold `actions: write`.

* fix(autofix): use POSIX ERE groups in infra-failure regex, cover all signatures in tests (#7562)

* fix(autofix): also treat a git fetch/clone transport death as infra

#6506's checkout died mid-transfer — "fetch-pack: invalid index-pack
output" and "RPC failed; curl 92 ... CANCEL" — which then hung the job
into the 20m limit. That is infra, not the PR (it only touches a doc),
and a re-run made it green. But the infra-signature whitelist did not
cover it, so the auto-rerun did not fire and it waited on a human.

Add `invalid index-pack output` and `RPC failed` — the two canonical
git-transport-death phrases — to INFRA_FAILURE_SIGNATURES. A co-present
job-timeout line does not block the match (one matching line classifies
the run), and a BARE timeout with no transport signature is still left
alone, since it can be a real regression. Both new signatures are pinned
in the test's per-signature loop, plus a case on #6506's real composite
annotation and a bare-timeout-is-not-rerun guard.

* fix(autofix): paginate annotations and filter Autofix runs in infra-rerun loop (#7562)

---------

Co-authored-by: wenshao <wenshao@example.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: qwen-code-ci-bot <qwen-code-ci-bot@users.noreply.github.com>

* fix(serve): detect stale SSE cursors across daemon restarts via epoch token; preserve turn attribution and surface compaction failures in replay (#7458)

* fix(daemon): epoch-token restart detection, compaction attribution, and degraded-snapshot signaling (DAEMON-001/007/008)

* fix(acp-bridge): field-level turn attribution merge and replayDegraded bridge test (#7458)

* fix(serve): skip bus epoch lookup for virtual subagent SSE streams (#7458)

The REST SSE route looked up the bus epoch for every session id, but
virtual subagent sessions ride their own bus and their compound ids are
not in the bridge's byId map, so the lookup threw and aborted the
subscription — breaking subagent event streams. Skip the lookup for the
virtual path and degrade a torn-down real session to a headerless stream
(mirrors the /acp route). Also bumps the daemon browser SDK bundle budget
(167KB -> 168KB) for the epoch fields and declares eventEpoch on
DaemonSession so the create/attach path drops its inline type cast.

* fix(serve): stamp eventEpoch on accepted continuations and surface replayDegraded in the SDK (#7458)

Address three review suggestions:
- POST /session/:id/continue now returns eventEpoch alongside lastEventId,
  mirroring the prompt 202 envelope so continuation-seeded SSE cursors
  detect daemon restarts (DAEMON-001)
- DaemonSessionClient exposes replayDegraded from the load response so SDK
  consumers can prefer the full transcript over a degraded snapshot
- add /acp dispatch-level regression test for the degraded-snapshot stderr
  breadcrumb (fires only when snapshot.degraded is set)

* test(cli): fix load-reply race in the degraded-breadcrumb transport test

Await each session/load reply frame before opening the session stream so
the GET cannot race conn.ownSession() into a 403; addresses the review
Critical on the deg-0 arm.

* fix(serve): allow and expose X-Qwen-Event-Epoch in CORS headers

Cross-origin SSE clients must send the epoch header through preflight and
read it from the response, or stale-cursor detection (DAEMON-001) is
silently disabled for every CORS client.

---------

Co-authored-by: qwen-code-bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: Qwen Autofix <qwen-autofix[bot]@users.noreply.github.com>

* feat(core): Align GenAI telemetry with ARMS (#7536)

* feat(core): align GenAI telemetry with ARMS

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(core): remove estimated token usage splits

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(core): address GenAI telemetry review feedback

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

---------

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>

* fix(serve): avoid TOCTOU race dropping live sessions from list response (#7556)

* Initial plan

* fix(serve): avoid TOCTOU race dropping live sessions from list response

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: 易良 <1204183885@qq.com>

* fix(cli): prevent monitor turns after task_stop (#7573)

---------

Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: qwen-code-ci-bot <qwen-code-ci-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix[bot]@users.noreply.github.com>
Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com>
Co-authored-by: destire-mio <qppque@gmail.com>
Co-authored-by: destire-mio <248462155+destire-mio@users.noreply.github.com>
Co-authored-by: Dragon <52599892+DragonnZhang@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: 易良 <1204183885@qq.com>
Co-authored-by: jinye <djy1989418@126.com>
Co-authored-by: chinesepowered <nlai@rediffmail.com>
Co-authored-by: ovochouovo <18212194+ovochouovo@users.noreply.github.com>
Co-authored-by: Edenman <67549719+BZ-D@users.noreply.github.com>
Co-authored-by: 克竟 <dingbingzhi.dbz@alibaba-inc.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: ytahdn <1294726970@qq.com>
Co-authored-by: ytahdn <ytahdn@gmail.com>
Co-authored-by: Truraly <94105924+Truraly@users.noreply.github.com>
Co-authored-by: zjgzx1988 <zjgzx1988@hotmail.com>
Co-authored-by: hogeheer499-commits <hogeheer499@gmail.com>
Co-authored-by: hogeheer <267467744+hogeheer499-commits@users.noreply.github.com>
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
Co-authored-by: wenshao <wenshao@example.com>
Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Nothing Chan <chenliu.cl@alibaba-inc.com>
Co-authored-by: 钉萁 <dingqi.jww@alibaba-inc.com>
Co-authored-by: yuanyuanAli <135116774+yuanyuanAli@users.noreply.github.com>
Co-authored-by: verify <verify@local>
Co-authored-by: qqqys <qys177@gmail.com>
Co-authored-by: callmeYe <512217680@qq.com>
Co-authored-by: Qwen Autofix <qwen-autofix[bot]@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Released in v0.20.1.

@yiliang114

Copy link
Copy Markdown
Collaborator

⚠️ Failed to process this request. Please re-mention the bot to retry.

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.

Token用量记录不准确

6 participants