Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(ci): speed up unit test gate and add hygiene checks

MagicLizie2f05349d4fb
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index e537826e9f..4cf7507e82 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -48,6 +48,10 @@ docs/design-rules/cindy-design-system.md)。写到具体章节/条款,
<!-- 列出实际执行的命令及结果,不要只写“已测试”。 -->
+<!-- 如果本 PR 新增或改写测试,请在这里或 PR 正文逐文件补充 engineering-conventions.md
+ §3.2 的“测试价值”各项(含单独运行该文件的实测耗时);没有真实入口、最小失败输入或
+ 规则依据的测试不应提交,超过 10 秒的单测文件需写明原因。 -->
+
```text
pnpm ...
结果:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 018dc2715a..e0dd9fa03b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -55,11 +55,21 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
+ # 纯文本扫描、秒级返回:逐用例重置模块、真实等待和普通单测读源码文本只允许
+ # 比基线少(engineering-conventions.md §3.2 性能预算),在耗时步骤前快速失败。
+ - name: Check unit test hygiene
+ run: pnpm check:test-hygiene
+
# test:unit 的 runner 自测不能跟着 Vitest 分片重复执行;在检查 job 中跑一次,
- # 两个 Linux 单测分片只负责 workspace unit tier。
+ # Linux 单测分片只负责 workspace unit tier。
- name: Run test runner self-tests
run: pnpm test:runner
+ # Cross-file security, permission, and design contracts are intentionally
+ # outside the ordinary behavior-test pool, but remain a required gate.
+ - name: Run desktop source-contract guards
+ run: pnpm test:guard
+
# No private service checkout or secrets: exercise production clients over real
# loopback WebSockets with bounded fault injection. Failure blocks verify.
- name: Run Device Link connection integration tests
@@ -117,24 +127,25 @@ jobs:
- name: Run mobile scope guard
run: pnpm --filter mobile test:scope
- # Linux 单测使用与 Windows 相同的确定性 Vitest 分片。两个分片分别覆盖每个
+ # Linux 单测使用与 Windows 相同的确定性 Vitest 分片。四个分片分别覆盖每个
# workspace 经 Vitest 切分后的测试文件,并集等于完整 unit tier;不重复 test:runner。
linux-unit-shards:
- name: Linux unit tests (${{ matrix.shard }}/2)
+ name: Linux unit tests (${{ matrix.shard }}/4)
runs-on: ubuntu-latest
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
- shard: [1, 2]
+ shard: [1, 2, 3, 4]
env:
- XDT_UNIT_TEST_SHARD: ${{ matrix.shard }}/2
+ XDT_UNIT_TEST_SHARD: ${{ matrix.shard }}/4
steps:
- name: Checkout client
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ # Unit shards only read the working tree; full history and every remote
+ # branch cost ~0.5 min per shard (verify, runner and Git jobs keep depth 0).
with:
- fetch-depth: 0
lfs: true
- name: Setup pnpm
@@ -167,7 +178,7 @@ jobs:
# package script 会传递 npm_execpath,让子进程复用当前 pnpm 入口。
run: pnpm run test:workspaces --tier unit
- # 真实进程与 Unix socket 覆盖独立执行一次,不混入日常 unit 或两个分片。
+ # 真实进程与 Unix socket 覆盖独立执行一次,不混入日常 unit 或其他分片。
- name: Run Pi manager integration tests
if: matrix.shard == 1
run: pnpm run test:workspaces --tier integration --workspace @cindy/maker-pi-manager
@@ -186,7 +197,7 @@ jobs:
- linux-unit-shards
runs-on: ubuntu-latest
steps:
- - name: Require checks and both Linux unit shards
+ - name: Require checks and every Linux unit shard
env:
VERIFY_CHECKS_RESULT: ${{ needs.verify-checks.result }}
LINUX_UNIT_SHARDS_RESULT: ${{ needs.linux-unit-shards.result }}
@@ -194,24 +205,26 @@ jobs:
test "$VERIFY_CHECKS_RESULT" = "success"
test "$LINUX_UNIT_SHARDS_RESULT" = "success"
- # Linux 全绿不能覆盖 path separator、盘符、大小写和文件系统能力差异。两个
+ # Linux 全绿不能覆盖 path separator、盘符、大小写和文件系统能力差异。四个
# Windows 分片并行运行,分片并集仍完整覆盖 test:unit,不能缩成少量 smoke。
+ # 只需执行一次的检查放在 windows-runner-checks,不压在任一分片的关键路径上。
windows-unit-shards:
- name: Windows unit tests (${{ matrix.shard }}/2)
+ name: Windows unit tests (${{ matrix.shard }}/4)
runs-on: windows-latest
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
- shard: [1, 2]
+ shard: [1, 2, 3, 4]
env:
- XDT_UNIT_TEST_SHARD: ${{ matrix.shard }}/2
+ XDT_UNIT_TEST_SHARD: ${{ matrix.shard }}/4
steps:
- name: Checkout client
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ # Unit shards only read the working tree; full history and every remote
+ # branch cost ~0.5 min per shard (verify, runner and Git jobs keep depth 0).
with:
- fetch-depth: 0
lfs: true
- name: Setup pnpm
@@ -234,32 +247,69 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
run: pnpm install:ripgrep
- # 保留 Windows 路径、进程与锁的自测覆盖,但两个分片只执行一次。
- - name: Run Windows test runner self-tests
- if: matrix.shard == 1
- run: pnpm test:runner
-
- name: Run client and package unit tests
# 通过 package script 传递
# npm_execpath,避免 Windows 子进程退回 PATH 上的 pnpm.cmd。
run: pnpm run test:workspaces --tier unit
+ # Windows runner 自测和伴侣数据库回归各只需执行一次。单独并行运行,避免给
+ # 某一个 unit 分片额外叠加约 4 分钟、拖长整条关键路径。
+ windows-runner-checks:
+ name: Windows runner and database checks
+ runs-on: windows-latest
+ timeout-minutes: 25
+
+ steps:
+ - name: Checkout client
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ fetch-depth: 0
+ lfs: true
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
+ with:
+ run_install: false
+
+ - name: Setup Node.js
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 22
+ cache: pnpm
+ cache-dependency-path: pnpm-lock.yaml
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Install bundled ripgrep
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: pnpm install:ripgrep
+
+ # 保留 Windows 路径、进程与锁的自测覆盖。
+ - name: Run Windows test runner self-tests
+ run: pnpm test:runner
+
# localDb suites are outside the unit tier; exercise these DB boundaries on both OSes.
- name: Run companion database regressions
- if: matrix.shard == 1
run: pnpm --filter desktop exec vitest run src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
- # 保留稳定的必需检查名,并确保任一分片失败或取消都会阻断汇总门禁。
+ # 保留稳定的必需检查名,并确保任一分片或一次性检查失败、取消都会阻断汇总门禁。
windows-unit:
name: Windows unit tests
if: ${{ always() }}
- needs: windows-unit-shards
+ needs:
+ - windows-unit-shards
+ - windows-runner-checks
runs-on: ubuntu-latest
steps:
- - name: Require both Windows unit shards
+ - name: Require every Windows unit shard and runner checks
env:
WINDOWS_UNIT_SHARDS_RESULT: ${{ needs.windows-unit-shards.result }}
- run: test "$WINDOWS_UNIT_SHARDS_RESULT" = "success"
+ WINDOWS_RUNNER_CHECKS_RESULT: ${{ needs.windows-runner-checks.result }}
+ run: |
+ test "$WINDOWS_UNIT_SHARDS_RESULT" = "success"
+ test "$WINDOWS_RUNNER_CHECKS_RESULT" = "success"
git-integration:
name: Desktop Git integration
diff --git a/AGENTS.md b/AGENTS.md
index 5f250429ac..325ab305b3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -156,6 +156,15 @@
- 新增或修改 Desktop 日志、IPC 错误处理、main 侧业务逻辑与测试、跨平台(macOS/
Windows)行为,或任何 UI 文案的 i18n 落地前,必须先读
`docs/dev-rules/engineering-conventions.md`。
+- 新增或改写任一测试前,必须先读
+ `docs/dev-rules/engineering-conventions.md` §3.2「新增测试的价值门槛」。测试必须通过
+ 真实生产入口验证可观察结果,并说明 Bug/规则依据、现有覆盖缺口、最小失败输入和 tier;
+ 没有新的结果、错误、权限、持久化、协议或时序差异时停止增加用例。纯跨文件安全、
+ 权限、协议或设计契约才进入 guard;不得为了覆盖率、测试数量或复制常量/JSX/CSS/
+ 源码字面量而新增测试。同时遵守该节「性能预算」:新文件单独运行本机 5 秒内并在 PR
+ 填实测耗时;被测模块只加载一次,不在 `beforeEach`/逐用例 helper 里 `vi.resetModules()`;
+ 不做 ≥100ms 真实等待;同一模块的用例并入已有文件。`pnpm check:test-hygiene` 在 CI
+ 阻断违规,基线只减不增,不得手改基线放行。
- 修改客户端日志采集/脱敏/上报链路(`apps/desktop/src/main/log-upload/**`)、`logger.ts`
的 main 日志行格式、崩溃判定或待补传标记前,必须先读
`docs/dev-rules/log-upload-and-redaction.md`。其中三条是**不变量**:**记录边界**(写侧
diff --git a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
deleted file mode 100644
index b96ddbfe24..0000000000
--- a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-function readMainSource(relativePath: string): string {
- return readFileSync(resolve(__dirname, '..', relativePath), 'utf8');
-}
-
-function expectBefore(source: string, registration: string, load: string): void {
- const registrationIndex = source.indexOf(registration);
- const loadIndex = source.indexOf(load, registrationIndex);
- expect(registrationIndex).toBeGreaterThanOrEqual(0);
- expect(loadIndex).toBeGreaterThan(registrationIndex);
-}
-
-describe('utility window appearance bootstrap registration', () => {
- it('权限引导的 backdrop 与 guide 在加载 renderer 前登记只读权限', () => {
- const source = readMainSource('computer-permission-guide/window.ts');
- expectBefore(
- source,
- 'markAppearanceSettingsReaderWindow(backdrop)',
- 'loadPermissionView(backdrop',
- );
- expectBefore(source, 'markAppearanceSettingsReaderWindow(guide)', 'loadPermissionView(guide');
- });
-
- it('语音浮窗与词典 toast 在加载 renderer 前登记只读权限', () => {
- const source = readMainSource('voice-input/global.ts');
- expectBefore(source, 'markAppearanceSettingsReaderWindow(window)', 'window.loadURL(');
- const toastFactory = source.slice(source.indexOf('function createDictionaryToastWindow'));
- expectBefore(toastFactory, 'markAppearanceSettingsReaderWindow(window)', 'window.loadURL(');
- });
-
- it('utility renderer 订阅运行期外观变化并直接更新 CSS 字体变量', () => {
- const source = readMainSource('../renderer/main-entry.tsx');
- expect(source).toContain('isAppearanceUtilityView');
- expect(source).toContain('appearanceSettings?.onChanged?.(applyFontSettings)');
- expect(source).toContain('import.meta.hot?.dispose(disposeUtilityAppearanceSettingsSync)');
- expect(source.match(/<ThemeProvider syncWindowVibrancy=\{false\}>/g)).toHaveLength(4);
- });
-});
diff --git a/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts b/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts
deleted file mode 100644
index 22e28a9794..0000000000
--- a/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-/**
- * Same-owner access-token refresh must not bounce the renderer to /login.
- *
- * 2026-08-20: packaged 0.1.56 logged `r:tapdb logout` →
- * `App session is switching` → `LocalDbGate` remount every ~55 minutes. The
- * trigger was `withCloudOwnerCommit` broadcasting `snapshotLoggedOutAuthState()`
- * during Ghost projection repair on a stable cloud owner.
- */
-describe('same-owner token refresh keeps the signed-in shell', () => {
- const authSource = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(
- /\r\n/g,
- '\n',
- );
-
- it('does not broadcast a logged-out snapshot for same-owner Ghost repair', () => {
- const start = authSource.indexOf('async function withCloudOwnerCommit');
- const end = authSource.indexOf('async function withAccountFreeOwnerCommit', start);
- const body = authSource.slice(start, end);
-
- expect(start).toBeGreaterThan(-1);
- expect(end).toBeGreaterThan(start);
- expect(body).toContain('if (ownerChanged) {\n notifyRendererAuthBoundaryPending();');
- expect(body).toContain('enterOwnerChangeShellPending();');
- expect(body).toContain('heldOwnerChangeShell = true;');
- expect(body).toContain('if (heldOwnerChangeShell) leaveOwnerChangeShellPending();');
- expect(body).toContain('releaseBoundary = beginAppSessionBoundary();');
- expect(body.indexOf('notifyRendererAuthBoundaryPending();')).toBeLessThan(
- body.indexOf('enterOwnerChangeShellPending();'),
- );
- expect(body.indexOf('if (ownerChanged)')).toBeLessThan(body.indexOf('notifyRendererAuthBoundaryPending();'));
- expect(body.indexOf('notifyRendererAuthBoundaryPending();')).toBeLessThan(
- body.indexOf('releaseBoundary = beginAppSessionBoundary();'),
- );
- // The unguarded call that remounted the shell every refresh cycle.
- expect(body).not.toContain(
- 'prepareTransition: async ({ ownerChanged }) => {\n notifyRendererAuthBoundaryPending();',
- );
- });
-
- it('keeps canEnterApp true for IPC pending, but not a real owner-change shell', () => {
- const start = authSource.indexOf('function snapshotAuthState(): AuthState {');
- const end = authSource.indexOf('function snapshotLoggedOutAuthState', start);
- const body = authSource.slice(start, end);
-
- expect(body).toContain(
- "canEnterApp: appSession.mode !== 'signed-out' && !isOwnerChangeShellPending()",
- );
- expect(body).not.toContain('!isAppSessionBoundaryPending()');
- });
-
- it('still fakes a signed-out snapshot for a real owner change or logout', () => {
- const cloudStart = authSource.indexOf('async function withCloudOwnerCommit');
- const cloudEnd = authSource.indexOf('async function withAccountFreeOwnerCommit', cloudStart);
- const accountFreeStart = cloudEnd;
- const accountFreeEnd = authSource.indexOf('async function recoverAccountFreeOwnerAtStartup', accountFreeStart);
-
- expect(authSource.slice(cloudStart, cloudEnd)).toContain('notifyRendererAuthBoundaryPending();');
- expect(authSource.slice(accountFreeStart, accountFreeEnd)).toContain(
- 'notifyRendererAuthBoundaryPending();',
- );
- });
-});
diff --git a/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts b/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts
deleted file mode 100644
index 2c97c7221b..0000000000
--- a/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * `/clear` handler 里三步的**先后契约**:立墓碑 → cleared_at 落库 → 封 clear 边界。
- *
- * 纪元的作用是作废「在 clear 之前取过纪元、之后才写回」的交接。它一旦先于落库推进,
- * 那个 await 窗口里启动的引擎切换 / 消息删除就会同时拿到「clear 之后的纪元」和
- * 「clear 之前的 DB 历史」——校验通过,基于已清空历史算出的交接照样盖掉墓碑,下次发送
- * 把用户刚显式清空的上下文重新灌回模型(#738 review P1)。
- *
- * 墓碑必须留在最前:窗口内到达的 send 走 peek,墓碑是同步生效且不回落 DB 的那一层。
- * 而窗口内**写回**的那批(纪元还是 clear 前的值、校验会通过)由 sealClearBoundary 的
- * 重立墓碑兜住——它不只是推进纪元,顺序细节见该方法注释。
- *
- * register.ts 是超大 handler 注册文件、没有可注入的测试入口,repo 里既有的做法就是对
- * 源码断言(见 deviceLinkAutoTitleWiring.test.ts / interruptedContinuationContract.test.ts)。
- */
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const registerSource = readFileSync(
- resolve(__dirname, '..', 'maker-ipc', 'register.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('/clear:墓碑 → cleared_at 落库 → 封 clear 边界', () => {
- const handlerStart = registerSource.indexOf('MAKER_INVOKE.INPUT_CLEAR_SESSION');
- const handlerEnd = registerSource.indexOf('MAKER_INVOKE.ABORT_SESSION', handlerStart);
- const handler = registerSource.slice(handlerStart, handlerEnd);
-
- it('三步都在同一个 handler 内', () => {
- expect(handlerStart).toBeGreaterThan(-1);
- expect(handlerEnd).toBeGreaterThan(handlerStart);
- expect(handler).toContain('agentHandoffPending.invalidate(sid)');
- expect(handler).toContain('await clearSessionContextInDb(sid, clearBoundaryMs)');
- expect(handler).toContain('agentHandoffPending.sealClearBoundary(sid)');
- });
-
- it('顺序不可颠倒:纪元推进排在 cleared_at 落库之后,墓碑排在最前', () => {
- const tombstoneAt = handler.indexOf('agentHandoffPending.invalidate(sid)');
- const persistAt = handler.indexOf('await clearSessionContextInDb(sid, clearBoundaryMs)');
- const epochAt = handler.indexOf('agentHandoffPending.sealClearBoundary(sid)');
- expect(tombstoneAt).toBeLessThan(persistAt);
- expect(persistAt).toBeLessThan(epochAt);
- });
-
- it('落库失败不跳过纪元推进:catch 掉而不是让 handler 抛出', () => {
- // 抛出的话 sealClearBoundary 不会执行,在途那批按过期历史算出的交接
- // 就能顺利写回。失败时宁可一并丢弃。
- const persistAt = handler.indexOf('await clearSessionContextInDb(sid, clearBoundaryMs)');
- const epochAt = handler.indexOf('agentHandoffPending.sealClearBoundary(sid)');
- const between = handler.slice(persistAt, epochAt);
- expect(between).toContain('} catch (err) {');
- expect(between).not.toContain('throw');
- });
-});
diff --git a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts
deleted file mode 100644
index 3ca270774d..0000000000
--- a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * device-link 远控输入 → 自动起名的**接线契约**。
- *
- * 起名核心逻辑由 sessionAutoTitle.test.ts 覆盖;这里只锁 register.ts 里两条远控
- * 输入路径都真的接上了它:INPUT_ENQUEUE(排队发送)与 INPUT_STEER(插话)。
- * 只接了入队的话,用户趁这一轮还在跑用插话写下的第一句话不会改名,标题会一直停在
- * 首条纯附件消息的合成占位上(PR #510 review P1)。
- *
- * register.ts 是超大 handler 注册文件、没有可注入的测试入口,repo 里既有的做法
- * 就是对源码断言(见 interruptedContinuationContract.test.ts)。
- */
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const registerSource = readFileSync(
- resolve(__dirname, '..', 'maker-ipc', 'register.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-const sessionsSource = readFileSync(
- resolve(__dirname, '..', 'localDb', 'ipc', 'sessions.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-function handlerBody(channel: string, nextChannel: string): string {
- const start = registerSource.search(
- new RegExp(`ipcMain\\.handle\\(\\s*MAKER_INVOKE\\.${channel}`),
- );
- const nextPattern = new RegExp(`ipcMain\\.handle\\(\\s*MAKER_INVOKE\\.${nextChannel}`);
- const nextMatch = nextPattern.exec(registerSource.slice(start + 1));
- const end = nextMatch ? start + 1 + nextMatch.index : -1;
- expect(start).toBeGreaterThan(-1);
- expect(end).toBeGreaterThan(start);
- return registerSource.slice(start, end);
-}
-
-describe('device-link auto-title wiring', () => {
- it('入队与插话两条路径都调用起名准备', () => {
- expect(handlerBody('INPUT_ENQUEUE', 'INPUT_COMPACT')).toMatch(
- /await prepareDeviceLinkAutoTitle\(\s*sid\s*,\s*queued\s*\)/,
- );
- expect(handlerBody('INPUT_STEER', 'INPUT_STOP')).toMatch(
- /await prepareDeviceLinkAutoTitle\(\s*sid\s*,\s*queued\s*\)/,
- );
- });
-
- it('入队:调度发生在 coordinator 接受之后', () => {
- // enqueue 是同步的、不会拒绝(重复 clientId 也只是幂等返回),排在它之后即可。
- const body = handlerBody('INPUT_ENQUEUE', 'INPUT_COMPACT');
- const acceptAt = body.indexOf('inputCoordinator.enqueue');
- const commitAt = body.indexOf('commitAutoTitle()');
- expect(acceptAt).toBeGreaterThan(-1);
- expect(commitAt).toBeGreaterThan(acceptAt);
- });
-
- it('插话:等 steer 落定且受理了才调度', () => {
- // steer 会因同会话已有在飞 steer / Stop 边界 / 输入锁返回 false。被拒的文本
- // 改掉默认名 / 合成占位 / fork 占位就是凭空改名(review P1)。
- const body = handlerBody('INPUT_STEER', 'INPUT_STOP');
- expect(body).toMatch(/const runSteer = \(\) => inputCoordinator\.steer\(/);
- expect(body).toMatch(/if \(accepted\)\s*\{[\s\S]*?commitAutoTitle\(\);/);
- const acceptAt = body.indexOf('inputCoordinator.steer(');
- expect(body.indexOf('commitAutoTitle()')).toBeGreaterThan(acceptAt);
- });
-
- it('每个异步阶段都受 clear generation 与终态 session 行双重保护', () => {
- for (const [channel, nextChannel, acceptToken, generationGuardToken] of [
- [
- 'INPUT_ENQUEUE',
- 'INPUT_COMPACT',
- 'inputCoordinator.enqueue',
- 'assertCurrentInputGeneration();',
- ],
- [
- 'INPUT_STEER',
- 'INPUT_STOP',
- 'inputCoordinator.steer(',
- 'assertCurrentInputGeneration();',
- ],
- ] as const) {
- const body = handlerBody(channel, nextChannel);
- const deviceLinkAt = body.indexOf('const deviceLinkInvoke = isDeviceLinkInvoke();');
- const sessionRowMatches = [...body.matchAll(/await getInputSessionRow\(sid\)/g)].map(
- (match) => match.index ?? -1,
- );
- const earlySessionGuardAt = sessionRowMatches[0] ?? -1;
- const generationAt = body.indexOf(
- 'const inputGeneration = inputCoordinator.getGeneration(sid);',
- );
- const stages = [
- /(?:await\s+)?inputCoordinator\.ensureQueueRestored\(sid\)/,
- /await materializeQueuedOssAttachmentsDeferred/,
- /await hydrateQueuedAgentReferences/,
- /await prepareDeviceLinkAutoTitle\(sid, queued\)/,
- ];
- const acceptAt = body.indexOf(acceptToken);
-
- expect(deviceLinkAt).toBeGreaterThan(-1);
- expect(generationAt).toBeGreaterThan(deviceLinkAt);
- expect(earlySessionGuardAt).toBeGreaterThan(deviceLinkAt);
- expect(earlySessionGuardAt).toBeGreaterThan(generationAt);
- const earlyGenerationGuardAt = body.indexOf(generationGuardToken, earlySessionGuardAt);
- expect(earlyGenerationGuardAt).toBeGreaterThan(earlySessionGuardAt);
- let cursor = earlyGenerationGuardAt;
- let finalGuardAt = -1;
- for (const stage of stages) {
- const stageMatch = stage.exec(body.slice(cursor));
- const awaitAt = stageMatch?.index === undefined ? -1 : cursor + stageMatch.index;
- const guardAt = body.indexOf(generationGuardToken, awaitAt);
- expect(awaitAt, `missing ${stage}`).toBeGreaterThan(cursor);
- expect(guardAt, `missing generation guard after ${stage}`).toBeGreaterThan(awaitAt);
- cursor = guardAt;
- finalGuardAt = guardAt;
- }
- const finalSessionGuardAt = sessionRowMatches.find((index) => index > cursor) ?? -1;
- expect(finalSessionGuardAt).toBeGreaterThan(cursor);
- finalGuardAt = body.indexOf(generationGuardToken, finalSessionGuardAt);
- expect(finalGuardAt).toBeGreaterThan(finalSessionGuardAt);
- expect(acceptAt).toBeGreaterThan(finalGuardAt);
- expect(sessionRowMatches.length).toBeGreaterThanOrEqual(2);
-
- if (channel === 'INPUT_ENQUEUE' || channel === 'INPUT_STEER') {
- expect(body).toContain('REMOTE_OPTIMISTIC_INPUT_SUPERSEDED');
- expect(body).not.toContain(
- 'if (!isCurrentInputGeneration()) return inputCoordinator.getProjection(sid);',
- );
- }
-
- if (channel === 'INPUT_STEER') {
- expect(body).toContain(
- 'allowMissingTrustedContexts: deviceLinkInvoke && steerOpts?.removeFromQueue === true',
- );
- const steerAt = body.indexOf('inputCoordinator.steer(', finalGuardAt);
- const postSteerGuard = body.indexOf('assertCurrentInputGeneration();', steerAt);
- const commitAt = body.indexOf('commitAutoTitle();', postSteerGuard);
- expect(steerAt).toBeGreaterThan(finalGuardAt);
- expect(postSteerGuard).toBeGreaterThan(steerAt);
- expect(commitAt).toBeGreaterThan(postSteerGuard);
- expect(body.slice(postSteerGuard, commitAt)).toMatch(/if \(accepted\)\s*\{/);
- }
- }
- expect(registerSource).toContain("if (!row || row.status === 'deleted')");
- expect(registerSource).not.toContain("currentSessionRow.status === 'archived'");
- });
-
- it('排队编辑的异步物化不会跨 clear 边界提交旧内容', () => {
- const body = handlerBody('INPUT_UPDATE_CONTENT', 'INPUT_MOVE');
- expect(body).toContain('const remote = isDeviceLinkInvoke();');
- expect(body).toContain('if (parsed.clientId !== cid)');
-
- const generationAt = body.indexOf(
- 'const inputGeneration = inputCoordinator.getGeneration(sid);',
- );
- const sessionRowMatches = [...body.matchAll(/await getInputSessionRow\(sid\)/g)].map(
- (match) => match.index ?? -1,
- );
- const earlySessionGuardAt = sessionRowMatches[0] ?? -1;
- const earlyGenerationGuardAt = body.indexOf(
- 'if (!isCurrentInputGeneration())',
- earlySessionGuardAt,
- );
- const materializeAt = body.indexOf('await materializeQueuedOssAttachmentsDeferred');
- const materializeGuardAt = body.indexOf('assertCurrentInputGeneration();', materializeAt);
- const hydrateAt = body.indexOf('await hydrateQueuedAgentReferences', materializeAt);
- const hydrateGuardAt = body.indexOf('assertCurrentInputGeneration();', hydrateAt);
- const finalSessionGuardAt = sessionRowMatches.find((index) => index > hydrateAt) ?? -1;
- const finalGenerationGuardAt = body.indexOf(
- 'assertCurrentInputGeneration();',
- finalSessionGuardAt,
- );
- const updateAt = body.indexOf('inputCoordinator.updateContent', finalSessionGuardAt);
-
- expect(generationAt).toBeGreaterThan(-1);
- expect(earlySessionGuardAt).toBeGreaterThan(generationAt);
- expect(earlyGenerationGuardAt).toBeGreaterThan(earlySessionGuardAt);
- expect(materializeAt).toBeGreaterThan(earlyGenerationGuardAt);
- expect(materializeGuardAt).toBeGreaterThan(materializeAt);
- expect(hydrateAt).toBeGreaterThan(materializeGuardAt);
- expect(hydrateGuardAt).toBeGreaterThan(hydrateAt);
- expect(finalSessionGuardAt).toBeGreaterThan(hydrateGuardAt);
- expect(finalGenerationGuardAt).toBeGreaterThan(finalSessionGuardAt);
- expect(updateAt).toBeGreaterThan(finalGenerationGuardAt);
- expect(body).toContain('queued.clientId must match clientId');
- expect(body).toContain('await materialized.cleanupBeforeAcceptance?.()');
- });
-
- it('只对远控调用生效:本机 renderer 走 maker:auto-title,不在这里重复起名', () => {
- const start = registerSource.indexOf('const prepareDeviceLinkAutoTitle =');
- expect(start).toBeGreaterThan(-1);
- const body = registerSource.slice(start, registerSource.indexOf('\n };', start));
- expect(body).toMatch(/if \(!isDeviceLinkInvoke\(\)\) return noop;/);
- // 预检失败按「要起名」放行:一次 DB 抖动不该让标题永久停在 New Maker。
- expect(body).toMatch(/eligible = true;/);
- });
-});
-
-describe('user rename notification ordering', () => {
- it('三条改名出口都在写库**之前**记号', () => {
- // 写库是一次 worker RPC 往返:改名提交与拿到回执之间有真实时间差,期间并发的
- // 智能标题仍能满足 `WHERE title = 期望值` 把用户刚保存的名字盖掉(review P1)。
- for (const [note, write] of [
- // local-db:sessions:update(本机重命名框)
- [
- "if (typeof p.title === 'string') noteUserTitleWritten(sid);",
- 'await withStatusWriteLock(',
- ],
- // patchSessionMetaInDb(device-link 远程改名)
- [
- 'if (patch.title !== undefined) noteUserTitleWritten(sessionId);',
- 'withStatusWriteLock(db, sessionId, patch.status, async () => {',
- ],
- // renameSessionTitlesInDb(MCP 批量改名)
- [
- 'for (const change of changes) noteUserTitleWritten(change.sessionId);',
- "getDbClient()\n .tx('sessions.renameTitles'",
- ],
- ] as const) {
- const noteAt = sessionsSource.indexOf(note);
- expect(noteAt).toBeGreaterThan(-1);
- const writeAt = sessionsSource.indexOf(write, noteAt);
- expect(writeAt).toBeGreaterThan(noteAt);
- }
- });
-
- it('自动起名自己的写入不发改名记号(否则一起名就自我禁用)', () => {
- const start = sessionsSource.indexOf('export async function persistSessionTitleIfStillDraft');
- const end = sessionsSource.indexOf('export async function clearSessionContextInDb', start);
- expect(start).toBeGreaterThan(-1);
- expect(end).toBeGreaterThan(start);
- expect(sessionsSource.slice(start, end)).not.toContain('noteUserTitleWritten');
- });
-});
diff --git a/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts b/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
index 59eaaa8558..cce1a8cf5e 100644
--- a/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
+++ b/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest';
// register.ts wires disableOrcaInternal inside one large closure with many runtime
// deps (maker, stores, caches), so the repo tests its IPC-boundary invariants via
-// source assertion (see makerOrcaRoleMarking.test.ts / orcaWorkflowRoute.test.ts).
+// source assertion (see makerOrcaRoleMarking.test.ts / the Orca route behavior tests).
// The *behavioral* predicate (clear lead role iff no active team) is covered by
// orcaStrandedLeadReconcile.test.ts; here we lock down that disableOrcaInternal's
// "no active team" branch is no longer an unconditional no-op.
diff --git a/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts b/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts
deleted file mode 100644
index 22a92f4cd3..0000000000
--- a/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { readFileSync } from 'node:fs';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(new URL('../im/index.ts', import.meta.url), 'utf8');
-
-describe('im startup default route backfill wiring', () => {
- // 启动期补齐历史任务的跟随记录(PR #5155 review P2): 回填不能只等设置保存/
- // 重置触发 —— 从未动过设置的升级老任务要靠 startImConnection(localDb 就绪
- // 权威时点)带起的这次补齐拿到记录。
- it('kicks the startup backfill from startImConnection', () => {
- const start = source.indexOf('export function startImConnection');
- expect(start).toBeGreaterThanOrEqual(0);
- const backfill = source.indexOf('void backfillImDefaultRoutesAtStartup();', start);
- const connect = source.indexOf('connectionLifecycle.start();', start);
- expect(backfill).toBeGreaterThan(start);
- expect(connect).toBeGreaterThan(backfill);
- });
-});
diff --git a/apps/desktop/src/main/__tests__/invokeCaptureHealthOrdering.test.ts b/apps/desktop/src/main/__tests__/invokeCaptureHealthOrdering.test.ts
deleted file mode 100644
index 046b9239b6..0000000000
--- a/apps/desktop/src/main/__tests__/invokeCaptureHealthOrdering.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * invokeCaptureHealthOrdering.test.ts —— 锁住 device-link invoke-capture 自检的时机。
- *
- * 真机实测发现:`assertCaptureHealthy()` 原本在 bootstrap 线性段(initDeviceLinkService 之后)
- * 调用,而 `maker:create-session` / `maker:send` 由 splash 后的 registerMakerIpcsAfterSplash
- * 延迟注册 —— 自检跑在它们注册之前,误报「critical channels missing」。修复:把自检挪到
- * registerMakerIpcsAfterSplash 内 registerMakerCoreIpc 之后。本测试用源不变式锁住该顺序,
- * 防回退(整段 bootstrap 启 Electron 才能跑,故用静态断言而非运行时)。
- */
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const bootstrapSource = readFileSync(resolve(__dirname, '..', 'bootstrap-electron.ts'), 'utf8');
-
-describe('invoke-capture health check ordering', () => {
- it('只调用一次 assertCaptureHealthy(移除了线性段的早调用)', () => {
- const calls = bootstrapSource.match(/assertCaptureHealthy\(\)/g) ?? [];
- expect(calls).toHaveLength(1);
- });
-
- it('assertCaptureHealthy 在 registerMakerCoreIpc 之后(maker:create-session/send 注册后才自检)', () => {
- const makerReg = bootstrapSource.indexOf('registerMakerCoreIpc(');
- const healthCheck = bootstrapSource.indexOf('assertCaptureHealthy()');
- expect(makerReg).toBeGreaterThanOrEqual(0);
- expect(healthCheck).toBeGreaterThan(makerReg);
- });
-
- it('自检与 makerIpcsRegistered 同段(splash 后延迟注册块内)', () => {
- const flag = bootstrapSource.indexOf('makerIpcsRegistered = true');
- const healthCheck = bootstrapSource.indexOf('assertCaptureHealthy()');
- expect(flag).toBeGreaterThanOrEqual(0);
- // 自检紧随 makerIpcsRegistered=true 之后(同一 try 块末尾)。
- expect(healthCheck).toBeGreaterThan(flag);
- expect(healthCheck - flag).toBeLessThan(600); // 之间只隔一段注释,不应跨越大段代码
- });
-});
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index f53db7292f..227114d323 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -109,7 +109,9 @@ describe('sendToSession ordering', () => {
);
expect(helperBlock).toContain('const result = await resolveCollabDispatchResult(');
- expect(helperBlock).toMatch(/\(\) =>\s+session\.send\(agentMessage, \{/);
+ expect(helperBlock).toMatch(
+ /async \(\) => \{\s+const sendResult = await session\.send\((?:agentMessage|outgoingMessage), \{/,
+ );
expect(helperBlock).toContain('planMode: false,');
expect(helperBlock).toContain('throwOnStartFailure: true,');
expect(helperBlock).toContain('onAccepted: async () => {');
@@ -375,7 +377,9 @@ describe('sendToSession ordering', () => {
expect(orcaInterAgentDispatcherSource).toContain('resolveCollabDispatchResult');
expect(helperBlock).toContain('Promise<CollabDirectDispatchResult>');
expect(helperBlock).toContain('const result = await resolveCollabDispatchResult(');
- expect(helperBlock).toMatch(/\(\) =>\s+session\.send\(agentMessage, \{/);
+ expect(helperBlock).toMatch(
+ /async \(\) => \{\s+const sendResult = await session\.send\((?:agentMessage|outgoingMessage), \{/,
+ );
expect(helperBlock).toContain('planMode: false,');
expect(helperBlock).toContain('throwOnStartFailure: true,');
expect(helperBlock).not.toContain('await session.send(agentMessage, {');
diff --git a/apps/desktop/src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.ts b/apps/desktop/src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.ts
deleted file mode 100644
index 9426bc7e0b..0000000000
--- a/apps/desktop/src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(resolve(__dirname, '..', 'bootstrap-electron.ts'), 'utf8');
-
-describe('model visibility IPC ordering', () => {
- it('registers the synchronous claim handler before the first BrowserWindow is created', () => {
- const registration = source.indexOf('registerModelVisibilityOwnerClaimIpc();');
- const createWindow = source.indexOf('startupWindowCreationAllowed = true;');
-
- expect(registration).toBeGreaterThanOrEqual(0);
- expect(createWindow).toBeGreaterThan(registration);
- });
-
- it('registers the initial visibility mirror handler before the first BrowserWindow is created', () => {
- const registration = source.indexOf('registerModelVisibilitySyncIpc();');
- const createWindow = source.indexOf('startupWindowCreationAllowed = true;');
-
- expect(registration).toBeGreaterThanOrEqual(0);
- expect(createWindow).toBeGreaterThan(registration);
- });
-});
diff --git a/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts b/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts
deleted file mode 100644
index c13d244f68..0000000000
--- a/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Agent 在另一台电脑运行的任务:换模型时不拿本机模型目录去校验那台的模型(那台的 Agent 裁决),
- * 点选仍只记意图、在发送边界落地;建任务与恢复时同样跳过本机路由检查。
- */
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = fs.readFileSync(path.join(__dirname, '../maker-ipc/register.ts'), 'utf8');
-
-function handlerBody(): string {
- const start = source.indexOf('const handleSetModel = async (');
- const end = source.indexOf('applyPiModelSettingsRefresh = async', start);
- expect(start).toBeGreaterThan(0);
- expect(end).toBeGreaterThan(start);
- return source.slice(start, end);
-}
-
-describe('agent-device model selection wiring', () => {
- it('routes agent-device tasks before any local catalog check', () => {
- const body = handlerBody();
- expect(body).toContain('agentDeviceId: sessions.agentDeviceId,');
- const branch = body.indexOf('if (runtimeStatus.agentDeviceId && !runtimeStatus.remoteHostId) {');
- expect(branch).toBeGreaterThan(0);
- const applyLocked = body.indexOf('const applyLocked = async () => {');
- const firstCatalogCheck = body.indexOf('await assertModelRouteUsable(', applyLocked);
- const firstCatalogLookup = body.indexOf('findCatalogModel(', applyLocked);
- expect(branch).toBeGreaterThan(applyLocked);
- expect(branch).toBeLessThan(firstCatalogCheck);
- expect(branch).toBeLessThan(firstCatalogLookup);
- });
-
- it('keeps picker clicks as intents and applies them through the live session at send time', () => {
- const body = handlerBody();
- const start = source.indexOf('const applyAgentDeviceRuntimeSelection = async');
- const end = source.indexOf('const handleSetModel = async (', start);
- expect(start).toBeGreaterThan(0);
- expect(end).toBeGreaterThan(start);
- const branch = source.slice(start, end);
- expect(body).toContain('return applyAgentDeviceRuntimeSelection({');
- expect(branch).toMatch(/internalOptions\.source === 'user' && !internalOptions\.applyingUserSelectionOnSend/);
- expect(branch).toContain('agentSwitchPending.set(sessionId, intent);');
- expect(branch).toContain('pendingUntilSend: true');
- expect(branch).toContain('live.requiresModelSwitchRebuild?.(model, { providerId: targetProviderId })');
- expect(branch).toContain('await live.setModel?.(model');
- expect(branch).toContain('await persistSessionFields(sessionId, patch);');
- expect(branch).not.toContain('assertModelRouteUsable');
- expect(branch).not.toContain('getActiveCatalog');
- });
-
- it('restores the agent computer from the task record when starting', () => {
- const start = source.indexOf('async function bootstrapSession(');
- const body = source.slice(start, start + 4000);
- expect(body).toContain('const agentDeviceId = await readSessionAgentDeviceId(o.id);');
- expect(body).toContain('if (agentDeviceId) o.agentDeviceId = agentDeviceId;');
- expect(body).toContain('const agentOnOtherDevice = Boolean(o.agentDeviceId) && !o.remoteHostId;');
- });
-
- it('treats a failed task lookup as a local task', () => {
- const start = source.indexOf('async function readSessionAgentDeviceId(');
- const body = source.slice(start, source.indexOf('\n }\n', start));
- expect(body).toContain('return row?.agentDeviceId && !row.remoteHostId ? row.agentDeviceId : null;');
- expect(body).toMatch(/catch \(error\) \{[\s\S]*treating the task as local[\s\S]*return null;/);
- });
-
- it('refuses Review for these tasks before collecting evidence', () => {
- const select = source.indexOf('.where(eq(sessions.id, request.sourceSessionId))');
- const guard = source.indexOf('if (source.agentDeviceId) {', select);
- const scope = source.indexOf('await resolveReviewScope(source.id)', select);
- const evidence = source.indexOf('loadReviewEvidence({', select);
- expect(select).toBeGreaterThan(0);
- expect(guard).toBeGreaterThan(select);
- expect(guard).toBeLessThan(scope);
- expect(guard).toBeLessThan(evidence);
- expect(source.slice(guard, scope)).toContain("throwIpcError('UNSUPPORTED_CAPABILITY'");
- });
-
- it('keeps tasks created from these tasks on the same computer', () => {
- const start = source.indexOf('async function sendToSessionInternal(');
- const body = source.slice(start, source.indexOf('assertDesktopSendDispatched(sendResult', start));
- expect(body).toContain('if (meta.agentDeviceId && !meta.remoteHostId) inheritedAgentDeviceId = meta.agentDeviceId;');
- expect(body).toContain('...(inheritedAgentDeviceId ? { agentDeviceId: inheritedAgentDeviceId } : {}),');
- // 换模型时按那台的目录校验,而不是本机目录。
- expect(body).toContain('availableModels: deviceRouting?.remoteCodexModels ?? maker.getCapabilities(targetAgent).availableModels,');
- expect(body).toContain('providerRouting: deviceRouting ?? await getProviderRoutingContext(),');
- });
-
- it("lists the other computer's models for Orca leads whose agent runs there", () => {
- const start = source.indexOf('listAvailableModels: async ({ agent, callerSessionId, agentDeviceId: requestedAgentDeviceId }) => {');
- expect(start).toBeGreaterThan(0);
- const body = source.slice(start, source.indexOf('const providerRouting = await getProviderRoutingContext();', start));
- // 不指定位置时列 Lead 所在位置(Lead 归在供应商组里时列组那一项所在电脑);Lead 也可以指定别的电脑 / 分享,
- // 或 null(任务所在电脑)。
- expect(body).toContain('readLeadProviderGroupEntry(callerSessionId, null).providerGroupEntry');
- expect(body).toMatch(/const leadAgentDeviceId = leadGroupEntry\s+\? leadGroupEntry\.agentDeviceId\s+: callerSessionId \? await readSessionAgentDeviceId\(callerSessionId\) : null;/);
- expect(body).toMatch(/requestedAgentDeviceId === undefined\s+\? leadAgentDeviceId/);
- expect(body).toContain('deviceAvailableModels(views, a)');
- expect(body).toContain('return agentDeviceCatalogFailure(err);');
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts
deleted file mode 100644
index a644077a3e..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * FORGE_GUIDE · Cindy Connection 凭证章节存在性。
- * source:'oidc-token' 是插件作者可见的 manifest 契约,手册必须与校验器同步。
- */
-import { describe, expect, it } from 'vitest';
-
-import { FORGE_GUIDE } from '../forge.js';
-
-describe('FORGE_GUIDE · Cindy Connection 凭证章节', () => {
- it('说明 oidc-token 的 Host 托管、注入限制和不可读边界', () => {
- for (const marker of [
- '"oidc-token"',
- 'Cindy 企业身份断言',
- 'Connection JWT',
- 'Authorization: Bearer {value}',
- 'setup.requires',
- 'identities',
- '不允许 `*.example.com` 通配',
- 'POST / PUT / PATCH / DELETE',
- '显式调用 `ghost_forge_install` 安装',
- '要求用户手输相同 id',
- '个人身份与手动导入不签发',
- '临时例外,只对 root 实例生效',
- '不得借例外跳过',
- '市场账本损坏、schema 不认或该 ghostId 记录校验失败时 fail-closed',
- ]) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts
deleted file mode 100644
index 9332928996..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * FORGE_GUIDE · OAuth 章节存在性(规则 24 最低闸):手册是意识作者的唯一
- * 教材,oauth 凭证契约(source:'oauth' / oauth 详单 / /oauth 通道 / authAccount)
- * 的关键描述必须在场——校验改了手册没跟上,AI 会按旧规则写出过不了校验的包。
- */
-import { describe, expect, it } from 'vitest';
-
-import { FORGE_GUIDE } from '../forge.js';
-
-describe('FORGE_GUIDE · oauth 凭证章节', () => {
- it('§2 清单样例含 oauth 详单字段', () => {
- for (const marker of ['"oauth"', 'authorizeUrl', 'tokenUrl', 'extraAuthorizeParams', 'labelPath']) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-
- it('§4.7 讲清主机托管授权与 /oauth 通道协议', () => {
- for (const marker of [
- '主机托管 OAuth 授权',
- "fetch('/oauth')",
- '/oauth/acct/connect',
- 'clientConfigured',
- 'authAccount',
- 'AUTH_EXPIRED',
- 'SERVICE_UNAVAILABLE',
- ]) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-
- it('/oauth 列入主机保留路径', () => {
- expect(FORGE_GUIDE).toContain('`/secrets`、`/oauth`、`/wake`');
- });
-
- it('redirectPort 与 tokenBroker 三路资格在场(§2 样例 + §4.7 说明 + 拒装原因)', () => {
- for (const marker of [
- '"redirectPort"',
- '"tokenBroker"',
- 'redirectPort 不是 1024–65535 整数',
- 'tokenBroker 没同时声明 redirectPort',
- '或与 clientSecret 同时声明',
- '三路资格',
- '随包官方种子或受信任公开市场的官方插件',
- '当前组织的服务端',
- 'organization market 包已安装',
- 'organizationId 与当前组织一致',
- 'release sha256 与批准 receipt 的 packageSha256 相等',
- '企业作者通过 `ghost_forge_install` 明确安装',
- '手动导入不属于 Forge 路径',
- '只给 Broker',
- '不给宿主原语',
- '总长不得超过 64 字符',
- ]) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-
- it('brokerBounce / scopeDelimiter 两个授权细节字段在场(§2 样例 + 说明 + 拒装原因)', () => {
- for (const marker of [
- '"brokerBounce"',
- '"scopeDelimiter"',
- // §2 样例:双地址弹跳回调的两个路径字段。
- '"callbackPath"',
- // 拒装原因清单:成套声明与路径形状约束。
- 'brokerBounce 没和 tokenBroker +',
- 'redirectPort 成套声明或路径不是 / 开头的站内绝对路径',
- ]) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-
- it('region request + clientIdAlternatives 讲清插件自选 App 与主机白名单', () => {
- for (const marker of [
- 'cindy.request',
- '/app-context',
- 'clientIdAlternatives',
- "region:'cn'|'global'",
- '主机会做清单白名单复验',
- ]) {
- expect(FORGE_GUIDE).toContain(marker);
- }
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/sessionFocusRetryContract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/sessionFocusRetryContract.test.ts
deleted file mode 100644
index d1cef7a368..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/sessionFocusRetryContract.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-describe('session focus retry wiring', () => {
- const mainSource = readFileSync(
- resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
- const gatewaySource = readFileSync(
- resolve(process.cwd(), 'src/main/cindy-brain/subscriptionGateway.ts'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
-
- it('forwards same-id IPC focus reports to the primary tracker for retries', () => {
- const start = mainSource.indexOf('function noteGhostWindowSessionFocused(');
- const end = mainSource.indexOf('\n}\n\nfunction mainShellWindows', start);
- const body = mainSource.slice(start, end);
-
- expect(body).toContain('if (previous !== sessionId)');
- expect(body).toContain('noteGhostSessionFocused(sessionId);');
- expect(body).not.toContain('if (previous === sessionId) return;');
- });
-
- it('releases raw focus after a failed publication recheck', () => {
- const start = gatewaySource.indexOf('export function createGhostPrimarySessionFocusTracker(');
- const end = gatewaySource.indexOf('\n}\n\n/* ──', start);
- const body = gatewaySource.slice(start, end);
-
- expect(body).toContain('recheckedPrimarySessionId = await resolve(sessionId);');
- expect(body).toContain('lastRawSessionId = null;');
- expect(body).toContain('primarySessionId === lastPrimarySessionId');
- });
-
- it('releases raw focus when session-switch eligibility is temporarily unavailable', () => {
- const start = mainSource.indexOf('export function notifyGhostSessionEvent(');
- const end = mainSource.indexOf('\n}\n\n/**\n * 会话切换上报入口', start);
- const body = mainSource.slice(start, end);
-
- expect(body).toContain('onRetry: () => void = () => {}');
- expect(body).toContain("if (info.outcome === 'retry') onRetry();");
- expect(mainSource).toContain(
- "notifyGhostSessionEvent('switched', { sessionId }, claim, releaseRaw)",
- );
- });
-});
diff --git a/apps/desktop/src/main/device-link/__tests__/ownershipAccountSource.test.ts b/apps/desktop/src/main/device-link/__tests__/ownershipAccountSource.test.ts
deleted file mode 100644
index c7f4117614..0000000000
--- a/apps/desktop/src/main/device-link/__tests__/ownershipAccountSource.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-describe('device-link ownership account source wiring', () => {
- it('keeps using the lifecycle DbClient owner after worker takeover closes main localDb', () => {
- const source = readFileSync(path.resolve(__dirname, '..', 'index.ts'), 'utf8');
- const resolverStart = source.indexOf('function getOwnershipLock()');
- const resolverEnd = source.indexOf('\n/**', resolverStart);
- const resolver = source.slice(resolverStart, resolverEnd);
-
- expect(resolverStart).toBeGreaterThanOrEqual(0);
- expect(resolverEnd).toBeGreaterThan(resolverStart);
- expect(source).toContain(
- "import { getCurrentDbClientUserId } from '../localDb/client/current';",
- );
- expect(resolver).toContain('getCurrentDbClientUserId()');
- expect(resolver).not.toContain('const userId = getCurrentUserId();');
- });
-});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts
deleted file mode 100644
index 9822cd140f..0000000000
--- a/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const makerHostSource = readFileSync(resolve(__dirname, '..', 'index.ts'), 'utf8').replace(
- /\s+/g,
- ' ',
-);
-
-describe('Codex model backfill wiring', () => {
- it('routes OAuth startup discovery through the isolated control-plane host', () => {
- expect(makerHostSource).toContain(
- "refreshLive: () => makerRef.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer', }),",
- );
- });
-});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 7588350e58..1339b21f11 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -17,12 +17,6 @@ type Registry = {
readonly size: number;
};
-// 每个用例都经 freshCodexProxyHost() 的 vi.resetModules() + 动态 import 重新加载
-// 整条 SUT 模块链(maker-core / compat-proxy / bridges)。首个用例还要承担全部
-// 依赖的首次编译加载,满载 CI 上会超出 vitest 默认 5s。只放宽本文件的预算,
-// 断言与流程不变。
-vi.setConfig({ testTimeout: 20_000 });
-
const mockState = vi.hoisted(() => {
let capturedRegistry: Registry | null = null;
const state = {
@@ -163,8 +157,19 @@ vi.mock('@cindy/responses-anthropic-bridge', () => ({
createResponsesAnthropicHandler: mockState.createResponsesAnthropicHandler,
}));
+// The SUT module graph is loaded once. Each case starts from the production
+// shutdown path (disposeCodexProxy clears session maps, proxy handles and
+// generations) plus the boot-time injections a case may have overridden.
+// Re-importing the whole graph per case instead cost 105s for this file versus
+// ~7s (2026-10-16), and order-shuffled runs confirm cases stay independent.
async function freshCodexProxyHost() {
- vi.resetModules();
+ const host = await import('../codex-proxy-host.js');
+ await host.disposeCodexProxy();
+ host.resetCodexThreadUpstreamForTest();
+ host.clearCodexProxyAuthInjection();
+ host.setCodexProxyGatewayKeyReader(() => null);
+ host.setCodexAppliedCustomProviderRoutes([]);
+ for (const fn of Object.values(mockState.logger)) fn.mockClear();
mockState.createAnthropicCompatProxy.mockReset();
mockState.createResponsesChatHandler.mockClear();
mockState.createResponsesAnthropicHandler.mockClear();
@@ -175,15 +180,14 @@ async function freshCodexProxyHost() {
mockState.stripNonAnthropicFields.mockReturnValue(null);
mockState.logLevel = 'debug';
mockState.resetCapturedRegistry();
- return import('../codex-proxy-host.js');
+ return host;
}
// CI 忙时本文件首次 import SUT 要付 Vitest transform 整个模块图的冷启动钱:Linux 分片
// 实测超默认 5s,Windows 分片超 15s。满载 Windows shard 2/2 曾在 60s 文件级 hook
// 上超时(本文件不 import maker-host/index,与产品改动无关)。这笔成本属于环境
// 冷启动,不属于任何断言 —— 文件级 beforeAll 先把模块图焐热(hook 超时独立计;
-// Windows 给 120s,其它平台仍 60s),之后各用例里 resetModules + import 只剩模块
-// 求值开销,回到默认超时内。
+// Windows 给 120s,其它平台仍 60s),之后各用例复用已加载的模块。
beforeAll(async () => {
await import('../codex-proxy-host.js');
}, process.platform === 'win32' ? 120_000 : 60_000);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts
deleted file mode 100644
index b24cf81064..0000000000
--- a/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * 压缩之后伙伴还是不是它自己。
- *
- * ## 为什么这组测试是源码断言
- *
- * 这条链跨三个 harness translator + maker-host + maker-ipc,真跑一遍要起三个
- * agent 进程。而它要防的事故是**有人不小心把某一环拆了**:那种改动在类型上
- * 完全合法,单测也不会红,只有用户会发现「压缩之后伙伴忘了自己是谁」。
- * 所以这里钉的是接线本身存在,不是它的运行时行为。
- *
- * ## 为什么 Cindy 不需要 Hermes 那条「压缩续接链」
- *
- * Hermes 压缩时**必须换一条会话**:它的记录是 append-only 的 jsonl 文件,压缩
- * 只能写新文件。于是它需要 `get_compression_tip` 沿父子链走到链尾,还要排除
- * 分支/委派/工具子会话、偏好还活着的那一节、加 100 层防御上限 —— 它自己的注释
- * 里记着那条链出过的事故:桌面端跟错到一个僵尸兄弟会话,用户最新的消息看起来
- * 「丢了」。
- *
- * Cindy 的会话在 SQLite 里,压缩**就地发生、会话 id 不变**。于是:
- *
- * - 侧栏不跳、作品集不断、右栏 tab 不重挂、device-link 不用重新解析归属;
- * - 没有链,也就没有跟错节点这回事。
- *
- * 代价是压缩后 agent 进程要重建(旧 runtime 关掉、按当前档案重新 bootstrap),
- * 这正是 `botCompactRuntimeRefresh` 那个协调器在做的事 —— 它顺带解决了 Hermes
- * 那条链**没有**解决的问题:压缩后把灵魂、技能索引、记忆快照重新注入。
- *
- * 结论:这里**有意不实现**续接链。抄过来是退步。
- */
-
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const REPO = path.resolve(__dirname, '../../../../../..');
-
-function read(relative: string): string {
- return readFileSync(path.join(REPO, relative), 'utf8');
-}
-
-describe('三个 harness 都会报压缩边界', () => {
- it('Claude Code:原生 compact_boundary', () => {
- expect(read('packages/maker-core/src/agents/claude-code/translator.ts')).toContain(
- "subtype === 'compact_boundary'",
- );
- });
-
- it('Codex:contextCompaction 翻成同一形状', () => {
- const source = read('packages/maker-core/src/agents/codex/translator.ts');
- expect(source).toContain('contextCompaction');
- expect(source).toContain("type: 'compact_boundary'");
- });
-
- it('Pi:同样报统一事件', () => {
- expect(read('packages/maker-core/src/agents/pi/translator.ts')).toContain(
- "type: 'compact_boundary'",
- );
- });
-
- it('统一事件在事件类型表里', () => {
- expect(read('packages/maker-core/src/types/events.ts')).toContain("'compact_boundary'");
- });
-});
-
-describe('压缩之后伙伴的身份被重新注入', () => {
- const register = read('apps/desktop/src/main/maker-ipc/register.ts');
-
- it('压缩边界被记下来,而不是当场重建 —— 同一轮里可能压好几次', () => {
- expect(read('apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts')).toContain("event.type === 'compact_boundary'");
- expect(read('apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts')).toContain('botCompactRuntimeRefreshCoordinator.noteBoundary(session)');
- });
-
- it('真正的重建发生在轮次结束之后', () => {
- expect(register).toContain('botCompactRuntimeRefreshCoordinator.attempt(session)');
- });
-
- it('重建走 replaceBotRuntimeAfterPreflight:先预检、再确认还是当前 owner、最后才关', () => {
- // 顺序错了就会「预检失败还是把好好的 runtime 关掉了」。
- expect(register).toContain('replaceBotRuntimeAfterPreflight');
- expect(register).toContain('preflightBotRuntimeResources');
- expect(register).toContain('isCurrentOwner');
- });
-
- it('会话关闭时清掉待处理的边界,不给已经没了的会话重建 runtime', () => {
- expect(register).toContain('clearForClosedSession');
- });
-
- it('重建留痕,能查到某次压缩之后档案是哪个版本', () => {
- expect(register).toContain('compact-runtime-refresh-applied');
- });
-});
-
-describe('Hermes capability epoch', () => {
- const register = read('apps/desktop/src/main/maker-ipc/register.ts');
- const runtime = read('apps/desktop/src/main/maker-ipc/botProfileRuntime.ts');
-
- it('每次发送前探测 canonical Chat 的档案、Skill、MCP、Toolset 与队友名册指纹', () => {
- expect(register).toContain('refreshBotCapabilityEpochBeforeSend');
- expect(register.match(/refreshBotCapabilityEpochBeforeSend\(compactedRuntime\)/g)).toHaveLength(2);
- expect(runtime).toContain('runtimeEpochSha256');
- expect(runtime).toContain('contextPrompt: opts.botProfileContextPrompt');
- });
-
- it('只有指纹变化才复用安全的原地 runtime 重建,不换 canonical Session id', () => {
- expect(register).toContain('prepareBotCapabilityEpochBeforeSend(live,');
- expect(register).toContain('return !!snapshot?.runtimeEpochChanged');
- expect(register).toContain('botCompactRuntimeRefreshCoordinator.noteBoundary(live)');
- expect(register).toContain('maker.getSession(expectedSession.id) === expectedSession');
- });
-
- it('后台 epoch 刷新失败会被主进程收口,不产生未处理的 Promise 拒绝', () => {
- expect(register).toContain('Bot runtime capability epoch refresh failed');
- });
-});
-
-describe('压缩不换会话', () => {
- it('重建用的是同一条会话 id —— 侧栏、作品集、右栏都不会因为压缩而断掉', () => {
- // 这一条是「不抄 Hermes 续接链」的立身之本:换 id 才需要链。
- expect(read('apps/desktop/src/main/maker-ipc/register.ts')).toContain(
- 'maker.getSession(expectedSession.id) === expectedSession',
- );
- });
-
- it('仓库里没有第二套「压缩后跟到子会话」的链式解析', () => {
- // Hermes 那条链的形状是 compression tip / continuation chain。Cindy 不该有。
- const coordinator = read('apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts');
- expect(coordinator).not.toContain('compressionTip');
- expect(coordinator).not.toContain('continuationChain');
- });
-});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts
deleted file mode 100644
index c7d0ec34c7..0000000000
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const registerSource = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');
-const lifecycleSource = readFileSync(resolve(__dirname, '..', 'orcaLifecycleService.ts'), 'utf8');
-const sessionViewSource = readFileSync(
- resolve(
- __dirname,
- '..',
- '..',
- '..',
- 'renderer',
- 'features',
- 'cc-agent',
- 'CCAgentSessionView.tsx',
- ),
- 'utf8',
-);
-
-describe('Orca UI assignment wiring', () => {
- it('waits for queryable Lead history before sending the deferred task', () => {
- const start = registerSource.indexOf('MAKER_INVOKE.WORKER_DISPATCH_UI_ASSIGNMENT');
- const end = registerSource.indexOf('async function clearLeadOrcaRoleState', start);
- const handler = registerSource.slice(start, end);
-
- const wait = handler.indexOf('orcaUiAssignmentHistoryGate.waitUntilQueryable(');
- const claim = handler.indexOf('orcaUiAssignmentDispatchClaims.runOnce(');
- const dispatch = handler.indexOf('orcaTeamService.sendToWorker({');
- expect(start).toBeGreaterThan(-1);
- expect(wait).toBeGreaterThan(-1);
- expect(claim).toBeGreaterThan(wait);
- expect(dispatch).toBeGreaterThan(claim);
- expect(handler).toContain('buildUiAssignmentInitialTask({');
- });
-
- it('queries user rows after the handoff snapshot and observes durable persistence', () => {
- const gateStart = registerSource.indexOf(
- 'const orcaUiAssignmentHistoryGate = createOrcaUiAssignmentHistoryGate({',
- );
- const gateEnd = registerSource.indexOf('const orcaLifecycleService', gateStart);
- const gate = registerSource.slice(gateStart, gateEnd);
- expect(gate).toContain('fromMs: snapshotBeforeMs');
- expect(gate).toContain("roles: ['user']");
- expect(lifecycleSource).toContain('uiAssignmentSnapshotBeforeMs: Date.now()');
- expect(registerSource).toContain(
- 'orcaUiAssignmentHistoryGate.notifyUserMessagePersisted(sessionId);',
- );
- expect(registerSource).toContain(
- 'const orcaUiAssignmentDispatchClaims = createOrcaUiAssignmentDispatchClaims();',
- );
- });
-
- it('keeps the Worker resumable and recovers a persisted pending receipt on Lead mount', () => {
- expect(lifecycleSource).toContain('if (normalized.initialTask && !params.deferDelegateTask)');
- expect(lifecycleSource).toContain("entrypoint: 'enable_collab_mode'");
- expect(sessionViewSource).toContain('getRecoverableDeferredUiAssignment({');
- expect(sessionViewSource).toContain("remoteRouteUnavailable: remoteConn !== 'connected'");
- expect(sessionViewSource).toContain('dispatchDeferredUiAssignment(sessionId, undefined).catch');
- });
-});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts
deleted file mode 100644
index 9c29d6f1f5..0000000000
--- a/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * SSH remote 会话的 Maker Memory 开关链路 (review R1 P1/P2) 的结构性回归断言。
- *
- * register.ts 是巨型组装函数, 闭包逻辑难以直接单测; 与
- * remoteCcQueryFactory.test.ts 同一模式用源码结构守住两条回归:
- *
- * 1. R1 P1: ensureRemoteReadyForSessionStart 曾对所有远端 createOpts 强制
- * `makerMemoryEnabled = false`, 把 renderer/DB-hydrate 侧已放开的开关又
- * 盖回去 — 远端会话永远拿不到记忆注入。现在必须保留调用方值, 缺失时按
- * 全局开关补齐。
- * 2. R1 P2: cindy_memory provider 的 isEnabled 在 codex HTTP bridge 启动时
- * 冻结。Maker Memory 开关翻转必须重建 bridge (shutdownCodexEnvironment,
- * 与 contacts / 全局插件开关同机制), 否则旧 bridge 缺/多 cindy_memory:
- * 远端 CC prompt 与工具面失配, codex 远端漂移判定永不收敛。
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8').replace(/\r\n?/g, '\n');
-
-describe('ensureRemoteReadyForSessionStart Maker Memory flag (R1 P1)', () => {
- it('no longer hard-forces makerMemoryEnabled=false on remote createOpts', () => {
- // 旧回归形态:remoteHostId 赋值后紧跟无条件覆盖 false。R2 的 stale-bridge
- // 钳制分支里也有受守卫的 `= false` 赋值, 所以只锁「无条件」形态。
- expect(source).not.toMatch(
- /remoteHostId = remoteHostIdToEnsure;\s*\n\s*mutableCreateOpts\.makerMemoryEnabled = false;/,
- );
- });
-
- it('preserves the caller flag and only backfills from the global manager state', () => {
- const fnStart = source.indexOf('async function ensureRemoteReadyForSessionStart');
- expect(fnStart).toBeGreaterThan(-1);
- const backfill = source.indexOf(
- 'mutableCreateOpts.makerMemoryEnabled ??= maker.makerMemory?.isEnabled() ?? false;',
- fnStart,
- );
- expect(backfill).toBeGreaterThan(fnStart);
- });
-
- it('clamps the session flag when the active (stale) bridge lacks cindy_memory (R2 P2)', () => {
- // busy 延迟窗口:manager 已翻转、bridge 重建被推迟。flag 保持 true 会让
- // prompt 注入 memory rules 而工具面没有 server — 必须按活跃 bridge 的
- // server 快照 (activeBridgeMissingMemory 谓词, 与 drift 判定共用) 钳制
- // 到关闭, 保持 prompt / 工具面同源。
- expect(source).toContain('function activeBridgeMissingMemory()');
- const fnStart = source.indexOf('async function ensureRemoteReadyForSessionStart');
- const backfill = source.indexOf('mutableCreateOpts.makerMemoryEnabled ??=', fnStart);
- const clamp = source.indexOf(
- 'if (mutableCreateOpts.makerMemoryEnabled && activeBridgeMissingMemory()) {',
- backfill,
- );
- const clampAssign = source.indexOf('mutableCreateOpts.makerMemoryEnabled = false;', clamp);
- expect(backfill).toBeGreaterThan(fnStart);
- expect(clamp).toBeGreaterThan(backfill);
- expect(clampAssign).toBeGreaterThan(clamp);
- });
-});
-
-describe('codex remote drift uses the bridge-clamped memory flag (R2 P2)', () => {
- it('routes both hasPendingRemoteMcpDrift call sites through the shared bridge-clamped opts', () => {
- // desired 集合必须与 ensure 实际能注入的集合同源:旧 bridge 缺
- // cindy_memory 时不能只看 manager 现值, 否则 drift 永不收敛, 每次
- // live send 白跑一次完整 remote ensure。opts 单点构造在
- // codexRemoteDriftOpts (内部走 remoteMakerMemoryEnabledForBridge)。
- expect(source).toContain('function remoteMakerMemoryEnabledForBridge()');
- expect(source).toContain('makerMemoryEnabled: remoteMakerMemoryEnabledForBridge()');
- const driftCalls =
- source.match(
- /hasPendingRemoteMcpDrift\(\s*live\.remoteHostId\s*,\s*codexRemoteDriftOpts\(\)\s*,?\s*\)/g,
- ) ?? [];
- expect(driftCalls.length).toBe(2);
- // drift 调用点不得残留裸 manager 现值。
- expect(source).not.toContain('makerMemoryEnabled: maker.makerMemory?.isEnabled() ?? false');
- });
-});
-
-describe('maker-memory toggle rebuilds the codex MCP bridge (R1 P2)', () => {
- it('MAKER_MEMORY_SET_ENABLED applyRuntime shuts down the codex environment when the flag flips', () => {
- const handler = source.indexOf('MAKER_INVOKE.MAKER_MEMORY_SET_ENABLED');
- expect(handler).toBeGreaterThan(-1);
- const guard = source.indexOf('if (wasEnabled !== enabled) {', handler);
- expect(guard).toBeGreaterThan(handler);
- const shutdown = source.indexOf('await shutdownAgentMcpEnvironmentsBestEffort(', guard);
- expect(shutdown).toBeGreaterThan(guard);
- // 同值调用 (无翻转) 不得白杀 bridge — shutdown 必须在翻转守卫之内。
- const wasEnabledSnapshot = source.indexOf('const wasEnabled = makerMemory.isEnabled();', handler);
- expect(wasEnabledSnapshot).toBeGreaterThan(handler);
- expect(wasEnabledSnapshot).toBeLessThan(guard);
- });
-
- it('MEMORY_RESET_SETTINGS applyRuntime shuts down the codex environment when the maker flag flips', () => {
- const handler = source.indexOf('MAKER_INVOKE.MEMORY_RESET_SETTINGS');
- expect(handler).toBeGreaterThan(-1);
- const guard = source.indexOf('if (wasMakerEnabled !== resetSettings_.maker) {', handler);
- expect(guard).toBeGreaterThan(handler);
- const shutdown = source.indexOf('await shutdownAgentMcpEnvironmentsBestEffort(', guard);
- expect(shutdown).toBeGreaterThan(guard);
- });
-});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTreeProviderResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTreeProviderResume.test.ts
deleted file mode 100644
index f5f3cdb5e5..0000000000
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTreeProviderResume.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const registerSource = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8').replace(
- /\r\n?/g,
- '\n',
-);
-
-function sourceBetween(startNeedle: string, endNeedle: string): string {
- const start = registerSource.indexOf(startNeedle);
- const end = registerSource.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return registerSource.slice(start, end);
-}
-
-describe('Pi session-tree lazy resume provider route', () => {
- it('refreshes shared global skills before Pi discovery', () => {
- const listSkills = sourceBetween(
- 'MAKER_INVOKE.LIST_AGENT_SKILLS',
- 'MAKER_INVOKE.SCAN_AT_RESOURCES',
- );
- const listCustomizations = sourceBetween(
- 'MAKER_INVOKE.LIST_CUSTOMIZATIONS',
- '// ── Session 生命周期',
- );
-
- expect(listSkills).toContain('const kind = requireAgentKind(agentKind);');
- expect(listSkills).toContain('await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();');
- expect(
- listSkills.indexOf('await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();'),
- ).toBeLessThan(listSkills.indexOf('maker.listAgentSkills(kind, skillParams)'));
-
- expect(listCustomizations).toContain("else if (agentKind === 'pi') {");
- expect(listCustomizations).toContain(
- 'await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();',
- );
- expect(
- listCustomizations.indexOf('await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();'),
- ).toBeLessThan(listCustomizations.indexOf('maker.listCustomizations(opts)'));
- });
-
- it('preserves the persisted providerId null/undefined distinction', () => {
- const lazyResume = sourceBetween(
- 'async function getOrResumeSessionTreeSession',
- 'ipcMain.handle(MAKER_INVOKE.GET_SESSION_TREE',
- );
-
- expect(lazyResume).toContain('providerId: row.providerId,');
- expect(lazyResume).not.toContain('providerId: row.providerId ?? undefined');
- });
-
- it('guards non-active (archived/deleted) sessions against lazy resume (round 40-w3 MEDIUM)', () => {
- const lazyResume = sourceBetween(
- 'async function getOrResumeSessionTreeSession',
- 'ipcMain.handle(MAKER_INVOKE.GET_SESSION_TREE',
- );
-
- // lazy resume 的 DB 查询必须带出 status, 且在 bootstrap 前拒绝非 active。
- expect(lazyResume).toContain('status: sessions.status,');
- expect(lazyResume).toContain("row.status !== 'active'");
- // 拒绝分支发生在任何 bootstrapSession / ensureRemoteReadyForSessionStart 之前。
- const statusGuardIdx = lazyResume.indexOf("row.status !== 'active'");
- const bootstrapIdx = lazyResume.indexOf('bootstrapSession(');
- expect(statusGuardIdx).toBeGreaterThan(-1);
- expect(bootstrapIdx).toBeGreaterThan(statusGuardIdx);
- });
-
- it('keeps the same three-state route contract across every persisted-session bootstrap', () => {
- const preHydrate = sourceBetween(
- 'async function hydrateProviderIdBeforeSessionStart',
- 'async function markOrcaRoleIfNeeded',
- );
- const reconcile = sourceBetween(
- 'async function reconcileCreateOptsAgainstDb',
- 'const agentSwitchDeps:',
- );
- const queued = sourceBetween(
- 'async function buildCreateOptsForQueuedSession',
- 'async function enqueueSendToSessionMessage',
- );
-
- expect(preHydrate).toContain('o.providerId = row.providerId?.trim() || null;');
- expect(reconcile).toContain('co.providerId = row.providerId;');
- expect(queued).toContain('providerId: row.providerId,');
- expect(registerSource).toContain('providerId: row?.providerId,');
- expect(registerSource).toContain('providerId: inherited.providerId,');
- expect(registerSource).not.toContain('co.providerId = row.providerId ?? undefined;');
- expect(registerSource).not.toContain('providerId: row.providerId ?? undefined,');
- expect(registerSource).not.toContain('providerId: row?.providerId ?? undefined,');
- expect(registerSource).not.toContain('providerId: inherited.providerId ?? undefined,');
- });
-});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts
deleted file mode 100644
index 81d2a1b7a4..0000000000
--- a/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-describe('cc-manager install source contract', () => {
- const source = readFileSync(
- resolve(process.cwd(), 'src/main/remote-ssh/cc-manager-install.ts'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
-
- it('checks the managed Claude Code pin before taking the cc-manager fast path', () => {
- const start = source.indexOf(
- 'export async function ensureCcManagerInstalledOrInstall(',
- );
- const end = source.indexOf(
- '\nexport function clearCcManagerInstallCache',
- start,
- );
- const body = source.slice(start, end);
-
- const agentProbe = body.indexOf(
- "await probeRemoteAgent(host, 'claude-code')",
- );
- const guardedFastPath = body.indexOf(
- 'if (!forceReinstall && claudeRuntimeReady) {',
- );
- const ccManagerProbe = body.indexOf('await probeCcManager(host)');
- const runtimeInstall = body.indexOf(
- "await installRemoteAgent(host, 'claude-code'",
- );
-
- expect(agentProbe).toBeGreaterThan(-1);
- expect(agentProbe).toBeLessThan(guardedFastPath);
- expect(guardedFastPath).toBeLessThan(ccManagerProbe);
- expect(ccManagerProbe).toBeLessThan(runtimeInstall);
- });
-});
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index 24978c8e2d..cb11af58c1 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -144,7 +144,8 @@ async function setupInstallDownload(skillName: string, zipBuf: Uint8Array) {
describe('skillhub/installService', () => {
beforeEach(async () => {
- vi.resetModules();
+ // Keep the module graph warm: each case owns TEST_ROOT and resets every mock below.
+ // The restart-specific cases call resetModules() at the exact boundary they exercise.
vi.resetAllMocks();
removeTestRoot();
fs.mkdirSync(TEST_ROOT, { recursive: true });
@@ -463,6 +464,8 @@ describe('skillhub/installService', () => {
unlink.mockRestore();
}
if (!result.success || !result.cleanupToken) throw new Error('expected unfinished cleanup');
+ // Simulate an app restart: the pending lease/journal modules own process state that
+ // clearAllMocks() cannot reset, so re-importing is part of this recovery contract.
vi.resetModules();
const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
for (const name of ['old-source', 'reinstalled-alias', 'different-alias']) {
@@ -562,6 +565,8 @@ describe('skillhub/installService', () => {
return;
}
if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
+ // Simulate an app restart so the durable cleanup receipt is reconstructed by the
+ // module-level journal/lease state; mock reset alone cannot exercise that boundary.
vi.resetModules();
const { retryUninstallCleanup } = await import('../installService');
const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
@@ -2072,6 +2077,8 @@ describe('skillhub/installService', () => {
});
const { uninstall } = await import('../installService');
expect(await uninstall(source, target)).toEqual({ success: true });
+ // Auto-sync preferences are module-scoped and this case verifies their cross-restart
+ // persistence; only resetModules() gives the next import a fresh in-memory store.
vi.resetModules();
const { listIgnoredAutoSyncSkills, clearIgnoredAutoSyncSkill } =
await import('../autoSyncPreferences');
diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts
deleted file mode 100644
index 82de3aa1c7..0000000000
--- a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { describe, expect, it } from 'vitest';
-
-const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../');
-
-describe('custom auxiliary chain does not hit the session agent', () => {
- it('Help only allows the session oneShot fallback for the automatic chain', () => {
- const source = readFileSync(path.join(root, 'maker-ipc/help.ts'), 'utf8');
- expect(source.match(/const auxiliaryChain = getEffectiveAuxiliaryModelChain\(\);/g)?.length).toBe(2);
- expect(source.match(/auxiliaryChain\.source === 'auto'/g)?.length).toBe(2);
- expect(source).not.toContain('isAuxiliaryModelCustomized');
- expect(source.match(/maker\.oneShot/g)?.length).toBeGreaterThan(0);
- expect(source).toContain('const ownerScopeKey = activeOwnerScopeKey();');
- expect(source.match(/beforeDispatch: async \(\) => isHelpOwnerScopeCurrent\(ownerScopeKey, auxiliaryChainSnapshot\)/g)?.length).toBe(2);
- expect(source.match(/beforeDispatch: beforeSessionAgentDispatch/g)?.length).toBe(2);
- expect(source).toContain('isHelpSessionAgentDispatchAllowed');
- });
-
- it('pinned-card summaries skip agent oneShot when the auxiliary list is customized', () => {
- const source = readFileSync(path.join(root, 'sessionTaskSummary.ts'), 'utf8');
- expect(source).toContain('const auxiliaryChain = getEffectiveAuxiliaryModelChain();');
- expect(source).toContain("auxiliaryChain.source !== 'auto' ||");
- expect(source).not.toContain('isAuxiliaryModelCustomized');
- expect(source).toContain('await getMaker().oneShot');
- expect(source).toContain('const ownerScopeKey = activeOwnerScopeKey();');
- expect(source).toContain('const beforeSessionAgentDispatch = async () =>');
- expect(source).toContain('beforeDispatch: beforeSessionAgentDispatch');
- expect(source).toContain('isAgentOneShotRouteDisabled(agentKind)');
- const disabledCheck = source.indexOf('isAgentOneShotRouteDisabled(agentKind)');
- const ownerRecheck = source.indexOf('return isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);', disabledCheck);
- expect(ownerRecheck).toBeGreaterThan(disabledCheck);
- });
-
- it('voice refinement pins the effective auxiliary chain for the whole run', () => {
- const source = readFileSync(path.join(root, 'voice-input/index.ts'), 'utf8');
- expect(source).toContain('const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();');
- expect(source.match(/assertVoiceInputOwnerScopeCurrent\(ownerScopeKey, auxiliaryChainSnapshot\)/g)?.length).toBe(3);
- expect(source).toContain('beforeDispatch: () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey),');
- });
-
- it('dictionary learning uses the same owner and chain dispatch guard', () => {
- const source = readFileSync(path.join(root, 'voice-input/index.ts'), 'utf8').replace(/\r\n/g, '\n');
- expect(source).toContain(`const advisorClient = new DictionaryLearningTextModelClient(
- (prompt, requestOptions) => requestUtilityText(getMaker(), prompt, requestOptions),
- () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),
- );`);
- expect(source).toContain(`const result = await advisor.advise(adviceInput);
- assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
- const recordResult = voiceInputDataStore.recordDictionaryLearningActions(result.actions);`);
- });
-});
diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts
deleted file mode 100644
index 4324d701d9..0000000000
--- a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/** Directory probing stays asynchronous inside Electron main. */
-import fs from 'node:fs';
-import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const desktopRoot = path.resolve(process.cwd());
-
-describe('workdir probe packaging contract', () => {
- it('does not package a utility-process probe host', () => {
- const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');
- const wiring = fs.readFileSync(
- path.join(desktopRoot, 'src/main/workdir-probe-host/index.ts'),
- 'utf8',
- );
- expect(forge).not.toContain('workdir-probe-host/workdirProbeHostProcess.ts');
- expect(wiring).not.toContain('utilityProcess');
- expect(wiring).toContain('MainProcessWorkdirProbeClient');
- });
-
- it('keeps the probe deadline and quit cleanup in the main process', () => {
- const wiring = fs.readFileSync(
- path.join(desktopRoot, 'src/main/workdir-probe-host/index.ts'),
- 'utf8',
- );
- expect(wiring).toContain('5_000');
- expect(wiring).toContain("app.once('before-quit'");
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/agentActionsCompactBlocks.test.ts b/apps/desktop/src/renderer/__tests__/agentActionsCompactBlocks.test.ts
deleted file mode 100644
index 40aa61f188..0000000000
--- a/apps/desktop/src/renderer/__tests__/agentActionsCompactBlocks.test.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-/**
- * agentActionsCompactBlocks.test.ts
- * ---------------------------------------------------------------------------
- * cc-agent-compact-blocks v2 — source-scan invariants for the F8/F9/F10/F11/F12
- * decisions:
- *
- * F8 AgentActionsBlock + ThinkingCard default to COLLAPSED — no
- * "auto-expanded while streaming" path.
- * F9 Both blocks consume `useExpandedBlockMemory` (persistent storage)
- * and have removed the v1 `userInteractedRef` / `prevStreamingRef`
- * state machine.
- * F10 MessageStream wraps render items in `gap-3.5` (= 14 px), exactly
- * half of the v1 `gap-7` (28 px).
- * F11 AgentActionRow renders Claude and Codex single-file actions as a real
- * **chip** (chat-input-chip-* tokens) and routes edits to one shared
- * Lightbox — not an inline 2nd-level expand.
- * F12 Other tools (Bash/Grep/...) toggle inline input/output details,
- * not the payload Lightbox.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const renderer = (rel: string) =>
- // 归一化 CRLF → LF:Windows autocrlf=true 检出下工作树是 CRLF,
- // 而下面的源码扫描断言里内嵌裸 \n,不归一化会在 Windows 上误报失败。
- readFileSync(resolve(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n');
-
-const blockSrc = renderer('components/chat/AgentActionsBlock.tsx');
-const rowSrc = renderer('components/chat/AgentActionRow.tsx');
-const userMessageSrc = renderer('components/chat/UserMessage.tsx');
-const thinkingSrc = renderer('components/chat/ThinkingCard.tsx');
-const streamSrc = renderer('components/chat/MessageStream.tsx');
-const toolPayloadSrc = renderer('components/chat/ToolPayloadLightbox.tsx');
-
-// ── F8: default collapsed ──────────────────────────────────────────────────
-
-describe('F8 — default collapsed', () => {
- it('AgentActionsBlock no longer initializes expanded from isStreaming', () => {
- // v1 had `useState<boolean>(isStreaming)` — must be gone.
- expect(blockSrc).not.toMatch(/useState<boolean>\(\s*isStreaming\s*\)/);
- // v2 reads expand state from useExpandedBlockMemory.
- expect(blockSrc).toMatch(/useExpandedBlockMemory/);
- });
-
- it('AgentActionsBlock dropped the userInteractedRef + prevStreamingRef state machine', () => {
- expect(blockSrc).not.toMatch(/userInteractedRef/);
- expect(blockSrc).not.toMatch(/prevStreamingRef/);
- });
-
- it('ThinkingCard no longer initializes expanded from isTurnActive', () => {
- expect(thinkingSrc).not.toMatch(/useState<boolean>\(\s*!!\s*isTurnActive\s*\)/);
- expect(thinkingSrc).not.toMatch(/prevTurnActiveRef/);
- expect(thinkingSrc).toMatch(/useExpandedBlockMemory/);
- });
-
- it('AgentActionsBlock no longer accepts isStreaming prop in its interface', () => {
- // The export interface should NOT contain `isStreaming` — F8/F9 removed it.
- // We slice the AgentActionsBlockProps interface and check.
- const ifaceStart = blockSrc.indexOf('AgentActionsBlockProps');
- const open = blockSrc.indexOf('{', ifaceStart);
- const close = blockSrc.indexOf('}', open);
- const slice = blockSrc.slice(open, close);
- expect(slice).not.toMatch(/isStreaming/);
- });
-});
-
-// ── F9: in-memory expand state (persistence intentionally removed) ─────────
-
-describe('F9 — useExpandedBlockMemory in-memory store', () => {
- it('does not touch localStorage (state is session-only)', () => {
- const hookSrc = renderer('hooks/useExpandedBlockMemory.ts');
- expect(hookSrc).not.toMatch(/localStorage/);
- });
-
- it('AgentActionsBlock builds a stable agent:<clientId> block id', () => {
- expect(blockSrc).toMatch(/agent:\$\{toolCalls\[0\]\.clientId\}/);
- });
-
- it('ThinkingCard builds a stable thinking:* block id', () => {
- const persistedKeyBlock = thinkingSrc.match(/const persistedKey = useMemo\(\(\) => \{[\s\S]*?\}, \[blockKey, startedAt\]\);/)?.[0] ?? '';
- expect(persistedKeyBlock).toMatch(/return `thinking:\$\{blockKey\}`/);
- expect(persistedKeyBlock).toMatch(/return `thinking:\$\{startedAt\}`/);
- expect(persistedKeyBlock).toContain("return 'thinking:unknown'");
- expect(thinkingSrc).toContain('useExpandedBlockMemory(persistedKey)');
- });
-});
-
-// ── F10: vertical spacing halved ────────────────────────────────────────────
-
-describe('F10 — message stream spacing halved', () => {
- it('MessageStream items wrapper uses gap-3.5 (was gap-7)', () => {
- expect(streamSrc).toMatch(/flex flex-col gap-3\.5/);
- expect(streamSrc).not.toMatch(/flex flex-col gap-7/);
- });
-});
-
-// ── F11: file chip + diff lightbox ─────────────────────────────────────────
-
-describe('F11 — file chip + diff lightbox', () => {
- it('AgentActionRow uses shared file identity + chat-input-chip tokens', () => {
- expect(rowSrc).toContain("from '@/components/ui/file-type-icon'");
- expect(rowSrc).toContain('<FileTypeIcon name={chipFilePath}');
- expect(rowSrc).toMatch(/--chat-input-chip-bg/);
- expect(rowSrc).toMatch(/--chat-input-chip-border/);
- expect(rowSrc).toMatch(/--chat-input-chip-text/);
- });
-
- it('AgentActionRow no longer embeds RowDiffBody / RowJsonBody inline', () => {
- expect(rowSrc).not.toMatch(/RowDiffBody/);
- expect(rowSrc).not.toMatch(/RowJsonBody/);
- });
-
- it('Claude Edit / Write / MultiEdit and Codex file_change share diff mode', () => {
- expect(rowSrc).toMatch(/buildDiffPayload/);
- expect(rowSrc).toMatch(/kind:\s*'diff'/);
- expect(rowSrc).toMatch(/rawDiff:\s*change\.diff/);
- expect(rowSrc).toMatch(/ToolPayloadLightbox/);
- expect(rowSrc).not.toMatch(/FileChangeDetails/);
- });
-
- it('Read tool routes to TextLightbox', () => {
- expect(rowSrc).toMatch(/TextLightbox/);
- expect(rowSrc).toMatch(/toolName === 'Read'/);
- });
-
- it('file chip context menu stays reachable from keyboard context-menu shortcuts', () => {
- expect(rowSrc).toMatch(/const chipRect = fileChipRef\.current\?\.getBoundingClientRect\(\)/);
- expect(rowSrc).toMatch(/e\.key !== 'ContextMenu'/);
- expect(rowSrc).toMatch(/e\.shiftKey && e\.key === 'F10'/);
- expect(rowSrc).toMatch(/fileChipMenu\.openAt\(/);
- });
-});
-
-// ── F12: Other tools → inline details via chevron ──────────────────────────
-
-describe('F12 — non-file tools → inline details', () => {
- it('AgentActionRow routes non-file tools to inline expansion', () => {
- expect(rowSrc).toMatch(/const isInlineExpand = !isFilePathTool/);
- expect(rowSrc).toMatch(/if \(isInlineExpand\) \{[\s\S]*?setExpanded/);
- expect(rowSrc).toMatch(/isInlineExpand && expanded/);
- expect(rowSrc).toMatch(/formatInlineInput/);
- });
-
- it('AgentActionRow prefers displayCommand and normalizes historical raw wrappers', () => {
- // issue #450: 行主文案改走 maker-shared 的 describeToolUse(displayCommand
- // 优先逻辑在共享层,由 toolUseDescriptor.test.ts 覆盖);就地展开区仍走
- // commandDisplayText 保留命令原文。
- expect(rowSrc).toMatch(/function commandDisplayText/);
- expect(rowSrc).toMatch(/inp\.displayCommand/);
- expect(rowSrc).toMatch(/inp\.command/);
- expect(rowSrc).toMatch(/normalizeDisplayCommand\(inp\.command\)/);
- expect(rowSrc).toMatch(/const cmd = commandDisplayText\(inp\)/);
- expect(rowSrc).toMatch(/describeToolUse/);
- });
-
- it('ToolPayloadLightbox remains the file/diff payload modal, not the non-file routing contract', () => {
- expect(toolPayloadSrc).toMatch(/kind:\s*'diff'/);
- expect(toolPayloadSrc).toMatch(/kind:\s*'json'/);
- expect(toolPayloadSrc).toMatch(/<DiffView/);
- expect(toolPayloadSrc).toMatch(/<MarkdownDiffBlock/);
- expect(toolPayloadSrc).toMatch(/e\.key\s*===\s*'Escape'/);
- expect(toolPayloadSrc).toMatch(/onClick=\{handleClose\}/);
- });
-
- it('ToolPayloadLightbox keeps duplicate MultiEdit diffs addressable with an index in the key', () => {
- const buildDiffPayloadBlock = rowSrc.match(
- /function buildDiffPayload\([\s\S]*?\n}\n\nexport interface AgentActionRowProps/,
- )?.[0] ?? '';
- expect(buildDiffPayloadBlock).toContain("key: 'edit:0'");
- expect(buildDiffPayloadBlock).toContain("key: 'write:0'");
- expect(buildDiffPayloadBlock).toMatch(/edits\.map\(\(e, index\) =>/);
- expect(buildDiffPayloadBlock).toMatch(/key:\s*`edit:\$\{index\}`/);
- expect(toolPayloadSrc).toContain('key={diff.key}');
- });
-});
-
-// ── MessageStream cleanup ──────────────────────────────────────────────────
-
-describe('MessageStream cleanup', () => {
- it('renders persisted Orca communication messages as collapsible cards', () => {
- expect(userMessageSrc).toMatch(/parseOrcaCommunicationContent/);
- expect(userMessageSrc).toMatch(/chat\.userMessage\.orcaFromLead/);
- expect(userMessageSrc).toMatch(/chat\.userMessage\.orcaFromWorker/);
- expect(userMessageSrc).toMatch(/aria-expanded=\{orcaExpanded\}/);
- });
-
- it('hides only empty Orca worker communication results, not tool calls', () => {
- expect(streamSrc).toMatch(/isOrcaCommunicationTool/);
- expect(streamSrc).toMatch(/isEmptyOrcaCommunicationResult/);
- expect(streamSrc).toMatch(/shouldHideToolResult/);
- expect(streamSrc).toMatch(/send_to_lead/);
- expect(streamSrc).toMatch(/read_lead/);
- expect(streamSrc).toMatch(/lead_status/);
- expect(streamSrc).not.toMatch(/if \(isHiddenOrcaCommunicationTool\(toolName\)\)/);
- });
-
- it('tool_segment items no longer carry isStreaming', () => {
- // The render path inside MessageStream should not pass isStreaming any more.
- // Find the AgentActionsBlock JSX block and assert no isStreaming prop.
- const idx = streamSrc.indexOf('<AgentActionsBlock');
- expect(idx).toBeGreaterThan(-1);
- const close = streamSrc.indexOf('/>', idx);
- const slice = streamSrc.slice(idx, close);
- expect(slice).not.toMatch(/isStreaming/);
- });
-
- it('ThinkingCard JSX no longer threads isTurnActive', () => {
- const idx = streamSrc.indexOf('<ThinkingCard');
- expect(idx).toBeGreaterThan(-1);
- const close = streamSrc.indexOf('/>', idx);
- const slice = streamSrc.slice(idx, close);
- expect(slice).not.toMatch(/isTurnActive/);
- });
-
- it('does not rescan every render for a missing search focus target', () => {
- expect(streamSrc).toMatch(/const lastMissingFocusRef = useRef/);
- expect(streamSrc).toContain('missingFocus.itemCount === allRenderItems.length');
- expect(streamSrc).toContain('missingFocus.lastItemKey === lastItemKey');
- expect(streamSrc).toContain('lastMissingFocusRef.current = {');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts b/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts
deleted file mode 100644
index 5da816c25c..0000000000
--- a/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-);
-const suggestionSource = readFileSync(
- resolve(__dirname, '..', 'lib', 'composerSuggestion.ts'),
- 'utf8',
-);
-
-describe('@ / + file entry unification', () => {
- it('keeps one attachment action instead of a duplicate native file-picker row', () => {
- expect(chatInputSource).toContain("id: 'attach-files'");
- expect(chatInputSource).toContain('suggestionFileInputRef.current?.click()');
- expect(chatInputSource).not.toContain('AT_FILE_PICKER_RESOURCE');
- expect(chatInputSource).not.toContain('window.electronAPI.dialog.showOpenResource(');
- expect(suggestionSource).not.toContain("item.type === 'file-picker'");
- });
-
- it('does not fall back to the removed in-composer file browser scope', () => {
- expect(chatInputSource).not.toContain('atFileBrowserScopeFrom');
- expect(chatInputSource).not.toContain('setAtFileBrowserScopeFrom');
- });
-
- it('keeps directory mentions available through scanned resource selection', () => {
- expect(chatInputSource).toContain('getAtDirectoryCompletionQuery(selectedItem)');
- expect(chatInputSource).toContain("selectedItem.type === 'agent'");
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts b/apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts
index c2dec4c14b..51803d9967 100644
--- a/apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts
@@ -7,7 +7,7 @@
* 正中只印大写扩展名 —— 并排两份 PDF 完全认不出谁是谁,文件名只在 hover
* tooltip 里出现。现在改成横向文件卡:图标块 + 文件名 + 「类型 · 大小」。
*
- * 与同目录 thumbnailClickPreview.test.ts 同族,走源码断言:ThumbnailItem 依赖
+ * 与同目录的预览行为测试同族,走源码断言:ThumbnailItem 依赖
* ChatInput 的大量本地状态,单独挂载成本远高于收益,这里把关键契约钉在源码层,
* 防止后续重构悄悄退回「只有扩展名」的形态。托盘组件在 ComposerAttachments.tsx
* (ChatInput 与伙伴群聊输入框共用)。
diff --git a/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts b/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts
deleted file mode 100644
index 450f089fd9..0000000000
--- a/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- resolve(__dirname, '..', 'components', 'settings', 'BuiltinToolsSection.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('BuiltinToolsSection working directory scope', () => {
- it('groups managed worktrees locally without changing the shared active cwd', () => {
- expect(source).toContain(
- "import { normalizeWorkingDirForProjectSettings } from '../../../shared/workingDir';",
- );
- expect(source).toContain(
- 'normalizeWorkingDirForProjectSettings(workingDir) ?? undefined;',
- );
- expect(source).toContain(
- 'normalizeWorkingDirForProjectSettings(\n' +
- ' selectedScope === undefined ? workingDir : selectedScope,',
- );
- expect(source).toContain(
- 'const projectScope = normalizeWorkingDirForProjectSettings(p) ?? undefined;',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts b/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts
deleted file mode 100644
index e95b856d56..0000000000
--- a/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
-);
-
-function handlerSource(startMarker: string, endMarker: string): string {
- const start = source.indexOf(startMarker);
- const end = source.indexOf(endMarker, start);
- expect(start).toBeGreaterThan(-1);
- expect(end).toBeGreaterThan(start);
- return source.slice(start, end);
-}
-
-describe('bulk session status routing', () => {
- it('multi-select delete freezes the resolved target and treats a local collision as local', () => {
- const handler = handlerSource(
- 'const handleBulkDelete = useCallback',
- 'const handleBulkArchive = useCallback',
- );
-
- expect(handler).toContain('sessionService.resolveStatusWriteTarget(session.id)');
- expect(handler).toContain(
- "sessionService.setStatus(session.id, 'deleted', statusWriteTarget)",
- );
- expect(handler).toContain("statusWriteTarget.kind === 'local'");
- expect(handler).not.toContain('sessionService.patchMeta(');
- });
-
- it('multi-select archive freezes the resolved target and converges a local collision locally', () => {
- const handler = handlerSource(
- 'const handleBulkArchive = useCallback',
- 'const handleArchiveAllInProject = useCallback',
- );
-
- expect(handler).toContain('sessionService.resolveStatusWriteTarget(session.id)');
- expect(handler).toContain(
- "sessionService.setStatus(session.id, 'archived', statusWriteTarget)",
- );
- expect(handler).toContain("statusWriteTarget.kind === 'local'");
- expect(handler).toContain(
- "patchLocal(session.id, { status: 'archived', pinnedAt: null })",
- );
- expect(handler).not.toContain('sessionService.patchMeta(');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts b/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts
deleted file mode 100644
index 9dc568a1bc..0000000000
--- a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-/**
- * ChatInput 列表接续接线契约:
- * - Shift/Alt+Enter 优先处理结构化列表,再兼容旧纯文本列表;
- * - 普通 Enter 不由列表接续拦截,发送或原生换行由共享快捷键 resolver 决定;
- * - 守住 IME composition 边界。
- * 结构化与旧纯文本接续行为由各自的编辑器测试覆盖。
- */
-describe('ChatInput list continuation wiring contract', () => {
- it('imports both structured-list commands and the legacy plain-text fallback', () => {
- expect(chatInputSource).toContain('handleStructuredListBackspace');
- expect(chatInputSource).toContain('handleStructuredListBreak');
- expect(chatInputSource).toContain('applyListBackspace');
- expect(chatInputSource).toContain('applyListContinuation');
- });
-
- it('tries structured and legacy continuation on Shift/Alt+Enter', () => {
- const block = extractBetween(
- chatInputSource,
- '// Shift/Alt+Enter — split or exit a structured item.',
- '// Resolve the configurable send shortcut after structured list handling.',
- );
- expect(block).toContain('(event.shiftKey || event.altKey) &&');
- expect(block).toContain('!event.metaKey');
- expect(block).toContain('!event.ctrlKey');
- expect(block).toContain('!event.isComposing');
- expect(block).toContain(
- 'if (handleStructuredListBreak(view) || applyListContinuation(view)) {',
- );
- expect(block).not.toContain('resolveComposerEnterIntent');
- // 非列表行必须放行给 ComposerHardBreak 默认换行
- expect(block).toContain('return false;');
- });
-
- it('intercepts bare Backspace for empty-item deletion, leaving modified backspace alone', () => {
- const block = extractBetween(
- chatInputSource,
- '// Backspace — structured list items exit through the schema command;',
- '// Shift/Alt+Enter — split or exit a structured item.',
- );
- expect(block).toContain("event.key === 'Backspace'");
- expect(block).toContain('!event.metaKey');
- expect(block).toContain('!event.ctrlKey');
- expect(block).toContain('!event.altKey');
- expect(block).toContain('!event.shiftKey');
- expect(block).toContain('!event.isComposing');
- // 三段 fallback 依次尝试:结构化列表 → 旧纯文本列表 → 意识指令胶囊整体删。
- // 顺序即优先级:意识指令排最后,只在自身命中时接管,不抢列表的退格语义。
- expect(block).toContain('handleStructuredListBackspace(view) ||');
- expect(block).toContain('applyListBackspace(view) ||');
- expect(block).toContain('applyGhostCommandBackspace(view)');
- expect(block.indexOf('handleStructuredListBackspace(view)')).toBeLessThan(
- block.indexOf('applyListBackspace(view)'),
- );
- expect(block.indexOf('applyListBackspace(view)')).toBeLessThan(
- block.indexOf('applyGhostCommandBackspace(view)'),
- );
- });
-
- it('keeps plain Enter outside list continuation — the resolver owns its semantics', () => {
- const plainEnterBlock = extractBetween(
- chatInputSource,
- '// Resolve the configurable send shortcut after structured list handling.',
- "if (enterIntent === 'queue' || enterIntent === 'steer') {",
- );
- expect(plainEnterBlock).not.toContain('handleStructuredListBreak');
- expect(plainEnterBlock).not.toContain('applyListContinuation');
- expect(plainEnterBlock).toContain('resolveComposerEnterIntent(');
- });
-
- it('keeps tabular-nums on the editor so multi-line list prefixes align', () => {
- const attributesBlock = extractBetween(
- chatInputSource,
- "'w-full min-h-[22px] max-h-[186px] overflow-y-auto py-[3px] -my-[3px] pr-[11px]',",
- "'focus:outline-none',",
- );
- expect(attributesBlock).toContain('tabular-nums');
- });
-});
-
-function extractBetween(source: string, start: string, end: string): string {
- const startIdx = source.indexOf(start);
- expect(startIdx).toBeGreaterThan(-1);
- const endIdx = source.indexOf(end, startIdx);
- expect(endIdx).toBeGreaterThan(startIdx);
- return source.slice(startIdx, endIdx);
-}
diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
deleted file mode 100644
index 49528798db..0000000000
--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
+++ /dev/null
@@ -1,592 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const normalizeSourceText = (source: string): string => source.replace(/\r\n?/g, '\n');
-const chatInputSource = normalizeSourceText(
- readFileSync(resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'), 'utf8'),
-);
-
-describe('ChatInput model source switching wiring', () => {
- it('preserves an explicit connection for submission even when its catalog row is unavailable', () => {
- expect(chatInputSource).toContain('const sendProviderId = activeProviderId || null;');
- expect(chatInputSource).toContain('providerId: sendProviderId');
- expect(chatInputSource).not.toContain('effectiveSourceIdForModel(sendProviders, activeProviderId');
- });
- it('normalizes Windows checkout line endings before matching guard order', () => {
- const windowsCheckoutSource = chatInputSource.replace(/\n/g, '\r\n');
- expect(normalizeSourceText(windowsCheckoutSource)).toBe(chatInputSource);
- });
-
- it('only the serialized unified panel skips the remote effort selector lock', () => {
- const modelSelectorSource = normalizeSourceText(
- readFileSync(resolve(__dirname, '..', 'components', 'new-chat', 'ModelSelector.tsx'), 'utf8'),
- );
- expect(modelSelectorSource).toContain('onEffortChange(effort, { serializedByPanel: true })');
- const start = chatInputSource.indexOf('const handleEffortChange = useCallback(');
- const body = chatInputSource.slice(start, chatInputSource.indexOf('\n );\n', start));
- expect(body).toContain('const lockSelector = options?.serializedByPanel !== true;');
- expect(body).toContain('if (lockSelector) setRemoteSwitchInFlight(true);');
- expect(body).toContain(
- 'if (lockSelector && isSessionScopeCurrent(sessionId, currentSessionIdRef.current))',
- );
- });
-
- it('uses the unified 90% switch-rebuild line instead of a harness compaction setting', () => {
- const start = chatInputSource.indexOf('const confirmModelSwitchContextGuard = useCallback(');
- const end = chatInputSource.indexOf('// session-agent-switch', start);
- const guard = chatInputSource.slice(start, end);
- expect(guard).toContain('autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT');
- expect(guard).not.toContain('compactionGetState');
- });
-
- it('guards same-model provider route changes with the target provider window', () => {
- const guardStart = chatInputSource.indexOf(
- 'const confirmModelSwitchContextGuard = useCallback(',
- );
- const guardEnd = chatInputSource.indexOf('// session-agent-switch', guardStart);
- const guard = chatInputSource.slice(guardStart, guardEnd);
- expect(guard).toContain('resolveProviderModelContextWindow({');
- expect(guard).toContain('providerId: targetRouteProviderId');
-
- const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
- const providerEnd = chatInputSource.indexOf(
- 'const handleProviderChange = useCallback(',
- providerStart,
- );
- const providerChange = chatInputSource.slice(providerStart, providerEnd);
- expect(providerChange).toContain(
- '(reconciledModelId !== activeModel || newProviderId !== effectiveSourceId)',
- );
- expect(providerChange).toMatch(
- /confirmModelSwitchContextGuard\(\s*reconciledModelId,\s*sourceRemoteDeviceId,\s*newProviderId/,
- );
- });
-
- it('guards model-only duplicate ids with the provider preserved by the final route', () => {
- const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
- const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
- const modelChange = chatInputSource.slice(modelStart, providerStart);
-
- expect(modelChange).toMatch(
- /confirmModelSwitchContextGuard\(\s*newModelId,\s*sourceRemoteDeviceId,\s*effectiveSourceId,/,
- );
- expect(modelChange).toContain(
- 'const { efforts, defaultEffort } = resolveModelEfforts(newModelId, effectiveSourceId);',
- );
- expect(modelChange).toMatch(
- /setModelWithFinalWindowConfirmation\(\s*newModelId,\s*effectiveSourceId,/,
- );
- expect(modelChange).toMatch(/maker\.setModel\(\s*sessionId,\s*newModelId,\s*undefined,/);
- });
-
- it('keeps exact-window confirmation local and removes it from device-link calls', () => {
- const guardStart = chatInputSource.indexOf(
- 'const confirmModelSwitchContextGuard = useCallback(',
- );
- const guardEnd = chatInputSource.indexOf(
- 'const setModelWithFinalWindowConfirmation',
- guardStart,
- );
- const guard = chatInputSource.slice(guardStart, guardEnd);
- expect(guard).toContain(
- 'return accepted && targetContextWindow ? targetContextWindow : accepted',
- );
-
- const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
- const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
- const modelChange = chatInputSource.slice(modelStart, providerStart);
- const providerChange = chatInputSource.slice(providerStart);
- for (const route of [modelChange, providerChange]) {
- const remoteSet = route.indexOf('const remoteSetModelResult = await remoteMaker.setModel(');
- const localSet = route.indexOf('await setModelWithFinalWindowConfirmation(', remoteSet);
- expect(remoteSet).toBeGreaterThan(-1);
- expect(localSet).toBeGreaterThan(remoteSet);
- const remoteRoute = route.slice(remoteSet, localSet);
- expect(remoteRoute).not.toContain('setModelWithFinalWindowConfirmation');
- expect(remoteRoute).not.toContain('confirmedContextWindow');
- expect(route.slice(localSet)).toContain(
- 'confirmedFinalWindow ?? confirmedGuardContextWindow',
- );
- }
- expect(chatInputSource).not.toContain('CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1');
- });
-
- it('passes the guard-confirmed window into both initial trusted local set-model calls', () => {
- const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
- const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
- const providerEnd = chatInputSource.indexOf(
- 'const handleProviderChange = useCallback(',
- providerStart,
- );
- const modelChange = chatInputSource.slice(modelStart, providerStart);
- const providerChange = chatInputSource.slice(providerStart, providerEnd);
-
- for (const route of [modelChange, providerChange]) {
- expect(route).toContain(
- "if (typeof proceed === 'number') confirmedGuardContextWindow = proceed;",
- );
- expect(route).toMatch(
- /const confirmedContextWindow =\s*confirmedFinalWindow \?\? confirmedGuardContextWindow;\s*return window\.electronAPI\.maker\.setModel/,
- );
- expect(route.indexOf('if (!proceed ||')).toBeLessThan(
- route.indexOf('window.electronAPI.maker.setModel('),
- );
- }
- });
-
- it('confirms pressure first revealed by Pi final-window verification before retrying', () => {
- const helperStart = chatInputSource.indexOf(
- 'const setModelWithFinalWindowConfirmation = useCallback(',
- );
- const helperEnd = chatInputSource.indexOf('// session-agent-switch', helperStart);
- const helper = chatInputSource.slice(helperStart, helperEnd);
-
- expect(helper).toContain('contextWindowConfirmationRequired');
- expect(helper).toContain('contextTokensForConfirmation');
- expect(helper).toMatch(
- /confirmModelSwitchContextGuard\(\s*modelId,\s*undefined,\s*providerId,\s*requiredWindow,/,
- );
- expect(helper).toContain('if (accepted !== requiredWindow) return { accepted: false };');
- expect(helper).toContain('result = await invoke(accepted)');
- expect(helper).not.toContain('result = await invoke(requiredWindow)');
- expect(chatInputSource.split('await setModelWithFinalWindowConfirmation(')).toHaveLength(3);
- expect(chatInputSource).toContain('? { confirmedContextWindow }');
- });
-
- it('keeps authoritative final-window confirmation ahead of stale snapshot shortcuts', () => {
- const guardStart = chatInputSource.indexOf(
- 'const confirmModelSwitchContextGuard = useCallback(',
- );
- const helperStart = chatInputSource.indexOf(
- 'const setModelWithFinalWindowConfirmation = useCallback(',
- guardStart,
- );
- const helperEnd = chatInputSource.indexOf('// session-agent-switch', helperStart);
- const guard = chatInputSource.slice(guardStart, helperStart);
- const helper = chatInputSource.slice(helperStart, helperEnd);
- const piBypass = guard.indexOf("runtimeAgentKind === 'pi' &&");
- const sameOrExpand = guard.indexOf('targetContextWindow >= currentContextWindow');
- const localVerdictShortcut = guard.indexOf("verdict.level === 'ok'");
- const confirmation = guard.indexOf('const accepted = await confirmDialog({');
-
- expect(guard).toContain(
- 'const contextTokens = requireDestructiveConfirmation\n ? verifiedContextTokens',
- );
- expect(guard.slice(0, piBypass)).toContain('!requireDestructiveConfirmation &&');
- expect(guard.slice(piBypass, sameOrExpand)).toContain(
- '!requireDestructiveConfirmation &&\n hasVerifiedWindows',
- );
- expect(guard.slice(0, sameOrExpand)).toContain(
- 'requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)',
- );
- expect(guard.slice(sameOrExpand, localVerdictShortcut)).toMatch(
- /!requireDestructiveConfirmation\s*&&\s*\(!trustedContextTokens \|\| trustedContextTokens <= 0\)/,
- );
- expect(guard.slice(localVerdictShortcut - 40, confirmation)).toContain(
- '!requireDestructiveConfirmation && verdict.level',
- );
- expect(confirmation).toBeGreaterThan(localVerdictShortcut);
- expect(helper).toContain('if (accepted !== requiredWindow) return { accepted: false };');
- expect(helper).toContain('result = await invoke(accepted);');
- });
-
- it('gates the device-link Pi estimate bypass on the controlled host window guard', () => {
- const start = chatInputSource.indexOf('const confirmModelSwitchContextGuard = useCallback(');
- const end = chatInputSource.indexOf('// session-agent-switch', start);
- const guard = chatInputSource.slice(start, end);
- const piCapability = guard.indexOf('const remotePiWindowGuardSupported =');
- const piRuntimeBypass = guard.indexOf("runtimeAgentKind === 'pi' &&");
- const catalogTargetResolution = guard.indexOf('const targetRouteProviderId =');
- const remoteGuard = guard.indexOf('const hasVerifiedWindows =');
- const legacyPiGuard = guard.indexOf('shouldBlockLegacyRemotePiModelWindowSwitch({');
- const sshHostGuard = guard.indexOf("if (remoteHostId && runtimeAgentKind === 'codex' && !requireDestructiveConfirmation) return true;");
- const zeroUsagePass = guard.indexOf(
- 'if (!requireDestructiveConfirmation && (!trustedContextTokens || trustedContextTokens <= 0))',
- );
- const remoteBlock = guard.indexOf("verdict.level === 'danger' || verdict.level === 'overflow'");
- const warningPath = guard.indexOf("verdict.level === 'warn'");
- const confirmPath = guard.indexOf('const accepted = await confirmDialog({');
-
- expect(piCapability).toBeGreaterThan(-1);
- expect(piCapability).toBeLessThan(piRuntimeBypass);
- expect(piRuntimeBypass).toBeLessThan(catalogTargetResolution);
- expect(guard).toContain('remoteDeviceId === deviceLinkDeviceId');
- expect(guard).toContain('supportsModelWindowSwitchGuard === true');
- expect(guard).not.toContain("if (remoteDeviceId && runtimeAgentKind === 'pi') return true;");
- expect(guard.slice(piCapability, piRuntimeBypass)).toContain(
- '!requireDestructiveConfirmation &&',
- );
- expect(remoteGuard).toBeGreaterThan(catalogTargetResolution);
- expect(legacyPiGuard).toBeGreaterThan(remoteGuard);
- expect(legacyPiGuard).toBeLessThan(zeroUsagePass);
- expect(guard.slice(legacyPiGuard, zeroUsagePass)).toContain('return false;');
- expect(sshHostGuard).toBeGreaterThan(-1);
- expect(sshHostGuard).toBeLessThan(catalogTargetResolution);
- // The Codex delegation runs first; other SSH harnesses keep their old guard.
- expect(guard).toContain('if (remoteHostId && (!hasVerifiedWindows || !hasVerifiedUsage)) return false;');
- expect(remoteGuard).toBeLessThan(remoteBlock);
- const shrinkGate = guard.slice(remoteGuard, remoteBlock);
- expect(shrinkGate).toContain('targetContextWindow >= currentContextWindow');
- expect(shrinkGate).toMatch(/!requireDestructiveConfirmation\s*&&\s*hasVerifiedWindows/);
- expect(shrinkGate).toContain(
- 'requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)',
- );
- expect(shrinkGate).toContain("typeof contextTokens === 'number'");
- expect(shrinkGate).toContain('const hasVerifiedUsage = trustedContextTokens !== undefined;');
- expect(zeroUsagePass).toBeGreaterThan(legacyPiGuard);
- expect(shrinkGate).toContain('return acceptedWindow;');
- expect(shrinkGate).toContain('stagingSameAgentSelection && hasVerifiedTargetWindow && hasVerifiedUsage');
- expect(guard).toContain(
- "if (!requireDestructiveConfirmation && verdict.level === 'ok') return acceptedWindow;",
- );
- expect(remoteBlock).toBeLessThan(warningPath);
- expect(remoteBlock).toBeLessThan(confirmPath);
- const blocked = guard.slice(remoteBlock, warningPath);
- expect(guard).toContain('(remoteHostId || remoteDeviceId)');
- expect(guard.indexOf('(remoteHostId || remoteDeviceId)')).toBeLessThan(remoteBlock);
- expect(blocked).toContain("verdict.level === 'danger' || verdict.level === 'overflow'");
- expect(blocked).toContain('overflowDescriptionRemote');
- expect(blocked).toContain('toast.error(');
- expect(blocked).toContain('return false;');
- const localConfirm = guard.slice(confirmPath);
- expect(localConfirm).not.toContain('overflowDescriptionRemote');
- expect(localConfirm).toContain('overflowDescription');
- expect(localConfirm).toContain('confirmSwitch');
- });
-
- it('lets a disconnected source reselect the highlighted fallback provider row', () => {
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- expect(selectorStart).toBeGreaterThanOrEqual(0);
-
- const selectorEnd = chatInputSource.indexOf('/>', selectorStart);
- expect(selectorEnd).toBeGreaterThan(selectorStart);
-
- const selectorBlock = chatInputSource.slice(selectorStart, selectorEnd + 2);
-
- expect(selectorBlock).toContain('sourceDisconnected={selectedSourceDisconnected}');
- expect(selectorBlock).toContain('reselectEmitsChange={selectedSourceDisconnected}');
- });
-
- it('routes unknown target-window failures through the provider-aware settings action', () => {
- expect(chatInputSource).toContain('buildModelWindowRecoveryToast({');
- expect(chatInputSource).toContain('onClick: () => navigate(recovery.settingsPath)');
- expect(chatInputSource).toContain(
- 'showModelSwitchFailure(err, effectiveSourceId, newModelId);',
- );
- expect(chatInputSource).toContain(
- 'showModelSwitchFailure(err, newProviderId, reconciledModelId ?? activeModel);',
- );
- });
-
- /**
- * 统一模型选择器(model-selector-unified M5 / M6)在 composer 上的接线锁。
- * 这三条各自堵一个「模块写完了但没有调用点」的洞:面板开关、会话内跨引擎入口、
- * 新会话选中直通。任一条掉了,统一面板对用户就是不存在 / 或者存在但按钮点不动。
- */
- it('wires the unified model panel into both composer entries', () => {
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- const selectorBlock = chatInputSource.slice(
- selectorStart,
- chatInputSource.indexOf('/>', selectorStart) + 2,
- );
-
- expect(selectorBlock).toContain('unifiedPanel={unifiedPanelActive}');
- // 会话内:同引擎过滤 + 跨引擎交给 performAgentSwitch。
- expect(selectorBlock).toContain('sessionEngineFilter={sessionEngineFilter}');
- // 新会话:选中直通(草稿),仅无 sessionId 时下发。
- expect(selectorBlock).toContain('!sessionId && unifiedPanelActive && onUnifiedDraftSelect');
- // 收藏锚点:草稿取调用方持有的那一份,会话取本组件的内存态(2026-08-17 review 第三轮 G4)。
- expect(selectorBlock).toContain('selectedFavoriteUid={effectiveSelectedFavoriteUid}');
- expect(selectorBlock).toContain('onSessionFavoriteAnchorChange={');
- });
-
- it('does not render the legacy two-step agent segments under the unified panel', () => {
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- const selectorBlock = chatInputSource.slice(
- selectorStart,
- chatInputSource.indexOf('/>', selectorStart) + 2,
- );
- // agentSwitch 与 sessionEngineFilter 是**互斥**的两种会话内形态(见 ModelSelector 的
- // prop 说明)。同时传会得到一个永远不渲染的分段,等于埋一个看不见的死入口。
- expect(selectorBlock).toContain('!unifiedPanelActive &&');
- });
-
- it('locks the union list to the current engine when no cross-engine transaction exists', () => {
- // 会话内拿不到 sessionEngineFilter(SSH 远程 / 被控端不支持 session-agent-switch)时,
- // useUnifiedRowActions.selectRow 不会改道切换事务 —— 跨引擎行会被当普通选中交给
- // 单引擎链路,把另一个引擎的模型塞进当前会话。护栏:这类会话把联合列表锁定在
- // 当前引擎;引擎解析不出时整个回落旧面板。
- expect(chatInputSource).toContain(
- 'const inSessionEngineLocked = Boolean(sessionId) && !sessionEngineFilter;',
- );
- expect(chatInputSource).toContain(
- 'unifiedModelPanelEnabled && (!inSessionEngineLocked || lockedSessionAgentKind !== null)',
- );
- expect(chatInputSource).toContain(
- 'lockedSessionAgentKind ? [lockedSessionAgentKind] : unifiedAgents',
- );
- });
-
- /**
- * bug4 回归锁。锁定分支用的引擎**必须**是已确认身份,不能是 vendorKey 派生的 agentKind:
- * CCAgentSessionView 的 vendorKey 走 dbToMakerAgentKind(session?.agentKind),session 未到
- * (冷启动 / 直链 / 远程列表未回流 / sessionService.get 失败被 catch 吞掉)时回退成 'cc';
- * 同一窗口里 sessionOrcaRole 是 undefined(≠ null)→ sessionAgentSwitchSupported=false →
- * 没有 sessionEngineFilter → 正好落进锁定分支。两者叠加 = Codex 会话摆出一张纯 Claude
- * 列表,且此时没有跨引擎兜底,点任意一行都会把 Claude 模型塞进 Codex 会话。
- */
- it('never locks the union list to a guessed engine before session identity resolves', () => {
- expect(chatInputSource).toContain(
- 'const sessionEngineConfirmed = !sessionId || runtimeAgentKind != null;',
- );
- expect(chatInputSource).toContain(
- 'inSessionEngineLocked && sessionEngineConfirmed ? (runtimeAgentKind ?? agentKind) : null',
- );
- // 防复活:锁定分支不得再直接读 vendorKey 派生的 agentKind。
- expect(chatInputSource).not.toContain(
- 'inSessionEngineLocked && agentKind ? [agentKind] : unifiedAgents',
- );
- expect(chatInputSource).not.toContain('(!inSessionEngineLocked || agentKind !== null)');
- });
-
- /**
- * bug7:composer pill 不再写 harness 名字文本,改「模型名 + 引擎小标 + 思考深度」。
- * 引擎取值必须与 agentIdentity 同源 —— 会话身份没加载完就不画,绝不拿 vendorKey 的
- * Claude Code 回退冒充(那正是 bug4 的病根,同一个回退不能在 pill 上复发)。
- */
- it('renders the composer pill engine as a mark sourced from the confirmed identity', () => {
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- const selectorBlock = chatInputSource.slice(
- selectorStart,
- chatInputSource.indexOf('/>', selectorStart) + 2,
- );
- // original 形态(三档并存)不画引擎小标:老 pill 用 harness 名字文本,两代形态不混。
- expect(selectorBlock).toContain(
- 'engineMarkVendor={unifiedPanelActive ? composerEngineMarkVendor : null}',
- );
- expect(chatInputSource.includes('runtimeAgentKind ? composerSelection.current.agentKind : runtimeAgentKind')).toBe(true);
- expect(chatInputSource.includes('composerSelection.pending ? composerSelection.display.agentKind : null')).toBe(true);
- expect(chatInputSource.includes('composerAgentIdentity?.vendorKey ?? null')).toBe(true);
- expect(selectorBlock).toContain('? composerAgentIdentity');
- // 草稿没有 session 身份可言,当前引擎就是 vendorKey。
- expect(chatInputSource).toContain(': (vendorKey ?? null);');
- });
-
- it('falls back to the legacy panel only when the controlled device has no provider catalog', () => {
- // device-link 老被控端 capabilities-only:联合列表的数据源是供应商目录,没有目录
- // 就是一张空列表。判据必须是结构化的 unsupported,不是 providers.length===0
- // (后者在加载中恒成立,会让面板每次打开先闪一下旧布局)。
- // 目录所在电脑 = Agent 在另一台电脑运行时的那台,否则远程任务的被控端。
- expect(chatInputSource).toContain(
- 'const unifiedModelPanelEnabled = !catalogDeviceId || !remoteProviders.unsupported;',
- );
- // 已建任务换电脑的意图期内,目录跟随意图里的电脑(effectiveAgentDeviceId)。
- expect(chatInputSource).toContain('const catalogDeviceId = effectiveAgentDeviceId ?? deviceLinkDeviceId ?? undefined;');
- });
-
- /**
- * Fast 的跨引擎口径(2026-08-17 review 改版):**只认面板显式给的目标值**。
- * 面板交出来的 `fast` 是按目标引擎解析并过完能力门控的配置(收藏副本 / 恢复推荐的
- * 显式关),显式给值(含 false)必须原样进 overrides;缺省才由 performAgentSwitch 按
- * 目标重解析。**旧引擎的实时 fastMode(本组件同名 state)在两条路上都不得进 payload**——
- * 那是最初版锁住的语义,改版后仍然成立。
- */
- it('passes only the panel-resolved target fast into the cross-engine switch payload', () => {
- const start = chatInputSource.indexOf('const sessionEngineFilter = useMemo(');
- expect(start).toBeGreaterThan(-1);
- const block = chatInputSource.slice(start, chatInputSource.indexOf('}, [', start));
- // 确认弹窗照旧(同一份 confirmAgentBrowseSwitch,含「不再提示」偏好);**有意变更**
- // (Chris 2026-08-19):现在把**本次目标引擎**交给确认门 —— 「已确认过就不再问」的判据
- // 收窄成「已有指向该目标的意图」,否则任何残留意图都会让确认框永久静默。
- expect(block).toContain('confirmAgentBrowseSwitch(targetAgent)');
- // 切换事务照旧;effort 显式带上(用户看着点下去的档)。
- expect(block).toContain('performAgentSwitchRef.current(');
- expect(block).toContain('...(effort ? { effort } : {})');
- // 显式目标 fast 进 overrides —— 判据必须是 `!== undefined`,不能是 truthy:
- // 收藏「Fast 关」(false)也要能压过目标记忆里残留的「开」。
- expect(block).toContain('...(fast !== undefined ? { fastMode: fast } : {})');
- // 防复活:块内所有 fastMode 出现处只允许「fastMode: fast」这一种形态 —— 本组件自己的
- // 实时 Fast state 不得被塞进 payload。
- expect(block).not.toMatch(/fastMode(?!: fast\b)/);
- });
-
- /**
- * 待切换意图期的引擎口径(2026-08-17 review):跨引擎意图登记后、真切换落地前,
- * activeModel / activeEffort / fastMode / activeProviderId 展示的全是意图目标值,统一面板
- * 的 currentAgent 必须同口径取**意图目标** —— 钉在旧 vendorKey 会让浮层摆出旧引擎的
- * 档位集合,而意图期的回调(performAgentSwitch(intent.target, …))按目标能力校验,
- * 用户点的档位被静默回落。
- */
- it('passes unresolved runtime identity through instead of falling back to the intent target', () => {
- const start = chatInputSource.indexOf('const sessionEngineFilter = useMemo(');
- expect(start).toBeGreaterThan(-1);
- const block = chatInputSource.slice(start, chatInputSource.indexOf('}, [', start));
- expect(block).toContain('runtimeAgent: runtimeAgentKind ?? undefined');
- expect(block).not.toContain('runtimeAgentKind ?? currentAgent');
- expect(block).not.toContain('runtimeAgent: runtimeAgentKind ?? vendorKeyToAgentKind');
- });
-
- it('keeps the unified panel session agent on the live runtime, not the pending intent', () => {
- expect(chatInputSource).toContain(
- 'const intentTargetAgent = agentSwitchIntent?.target ?? null;',
- );
- expect(chatInputSource).toContain(
- 'const currentAgent = runtimeAgentKind ?? vendorKeyToAgentKind(vendorKey);',
- );
- expect(chatInputSource).toContain('pendingTarget: intentTargetAgent');
- });
-
- /**
- * 会话收藏锚点的记录口径(2026-08-17 review 第三轮 G4 + 第四轮 K3)。
- * 两条都得锁住:**真成功才记**(取消 / 事务失败时这次选择根本没发生),以及**记的是入参
- * 里的 uid + 事务后的目标值** —— 跨引擎编辑一条收藏会连带换引擎与 wire id,拿旧值记会让
- * 派生校验永远对不上,锚点等于白记。
- */
- it('records the session favorite anchor from the transaction payload, only on success', () => {
- const start = chatInputSource.indexOf('const sessionEngineFilter = useMemo(');
- expect(start).toBeGreaterThan(-1);
- const block = chatInputSource.slice(start, chatInputSource.indexOf('}, [', start));
- // 入参里带锚点,缺省 null(选普通模型行 / 恢复推荐 / 删收藏都显式传 null)。
- expect(block).toContain('favoriteUid = null,');
- // 只在事务真成功后才记。
- expect(block).toContain('if (applied) {');
- expect(block).toContain('setSessionFavoriteAnchor(');
- // 快照取事务后的目标值(targetAgent / modelId / providerId 都是这次切过去的那一份)。
- expect(block).toContain('uid: favoriteUid,');
- expect(block).toContain('wireModelId: modelId,');
- expect(block).toContain('engine: agentKindToVendor(targetAgent),');
- expect(block).toContain('providerId,');
- // 勾选只认 uid(Chris 2026-08-20):不拿正在跑的来源去对副本。
- expect(chatInputSource).toContain('sessionFavoriteAnchor?.uid ?? null');
- expect(chatInputSource).not.toContain(
- 'sessionFavoriteAnchor.providerId === activeProviderId &&',
- );
- });
-
- /**
- * 合并行之后的 **id 口径锁**(数据层把同一模型的多引擎条目合并成一行,行 id 是归一化 id,
- * 每个引擎真正能发的是各自的 wireModelId)。
- *
- * 这条锁的存在理由是"有活错误":拿归一化行 id 去发请求,首条消息就路由到一个目标引擎目录
- * 里不存在的 model id。接线层的职责很简单 —— **对上游给的 id 零加工**,并且绝不把
- * rowModelId 当发送 id 用。
- */
- it('never uses the normalized row id as a send / memory id', () => {
- // 1. 跨引擎路径:modelId 原样进切换事务,中间不套任何 id 加工函数。
- const filterStart = chatInputSource.indexOf('const sessionEngineFilter = useMemo(');
- expect(filterStart).toBeGreaterThan(-1);
- const filterBlock = chatInputSource.slice(
- filterStart,
- chatInputSource.indexOf('}, [', filterStart),
- );
- expect(filterBlock).toContain('performAgentSwitchRef.current(');
- expect(filterBlock).toContain('modelId,');
- expect(filterBlock).not.toContain('rowModelId');
-
- // 2. 草稿直通路径:记忆键与交给草稿层的 model 都用 selection.modelId(wire id)。
- const draftStart = chatInputSource.indexOf('const handleUnifiedDraftSelect = useCallback(');
- expect(draftStart).toBeGreaterThan(-1);
- const draftBlock = chatInputSource.slice(
- draftStart,
- chatInputSource.indexOf(
- '[sessionId, settingsLocked, modelMemory, taskComputerModelMemory, onUnifiedDraftSelect, agentDeviceId]',
- draftStart,
- ),
- );
- expect(draftBlock).toContain('modelId: selection.modelId,');
- // rowModelId 只在类型声明与注释里出现,**不得**出现在任何写入实参上。
- expect(draftBlock).not.toContain('selection.rowModelId');
- for (const write of [
- 'targetMemory?.setEffort(',
- 'targetMemory?.setFast(targetKind, selection.providerId, selection.modelId, selection.fast)',
- ]) {
- expect(draftBlock).toContain(write);
- }
- // 远程 Agent 换落点:记忆按目标目录写(回任务所在电脑写那份 —— 本机预设 / 被控电脑的镜像,
- // 去另一台电脑写本机为那台记的一份),落点原样交给草稿层。
- expect(draftBlock).toContain('? agentDeviceModelMemoryAccessors(selection.agentDevice.deviceId)');
- expect(draftBlock).toContain(': taskComputerModelMemory;');
- expect(draftBlock).toContain('agentDevice: selection.agentDevice');
- // 「恢复推荐」已先删除记忆键;直通草稿时不得把推荐档位重新写成 override。
- expect(draftBlock).toContain('!selection.resetToRecommended');
- expect(draftBlock).toContain(
- '...(selection.resetToRecommended ? { resetToRecommended: true as const } : {})',
- );
- });
-
- it('keeps a new conversation model pick on the draft path', () => {
- const draftStart = chatInputSource.indexOf('const handleUnifiedDraftSelect = useCallback(');
- const draftEnd = chatInputSource.indexOf(
- '[sessionId, settingsLocked, modelMemory, taskComputerModelMemory, onUnifiedDraftSelect, agentDeviceId]',
- draftStart,
- );
- const draftHandler = chatInputSource.slice(draftStart, draftEnd);
-
- expect(draftHandler).toContain('if (sessionId || settingsLocked) return;');
- expect(draftHandler).toContain('onUnifiedDraftSelect?.({');
- expect(draftHandler).not.toContain('maker.setModel(');
- expect(draftHandler).not.toContain('confirmModelSwitchContextGuard(');
-
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- const selectorBlock = chatInputSource.slice(
- selectorStart,
- chatInputSource.indexOf('/>', selectorStart) + 2,
- );
- expect(selectorBlock).toContain(
- '!sessionId && unifiedPanelActive && onUnifiedDraftSelect\n ? handleUnifiedDraftSelect',
- );
- });
-
- it('feeds the selector the session/draft wire id as the selected model', () => {
- const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
- const selectorBlock = chatInputSource.slice(
- selectorStart,
- chatInputSource.indexOf('/>', selectorStart) + 2,
- );
- // activeModel 的三个来源(agentSwitchIntent / pendingRemoteSwitch / initialModel)全是
- // 会话或草稿持有的 wire id;这里不得改成面板的行 id。
- expect(selectorBlock).toContain('modelId={activeModel}');
- expect(selectorBlock).toContain('effort={activeEffort}');
- expect(selectorBlock).toContain('fastMode={composerSelection.display.fastMode}');
- expect(selectorBlock).toContain('currentSelection={sessionId && runtimeAgentKind ? composerSelection.current : undefined}');
- expect(selectorBlock).not.toContain('rowModelId');
- });
-
- it('sends null atomic effort for models with no ranks and keeps row Fast', () => {
- const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
- const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
- const modelChange = chatInputSource.slice(modelStart, providerStart);
- expect(modelChange).toContain('composeAtomicModelSelection({');
- expect(modelChange).toContain('effort: atomicEffort');
- expect(modelChange).toContain('fastMode: atomicFast');
- expect(modelChange).toContain('resolveRequestedEffort({');
-
- const providerChange = chatInputSource.slice(
- providerStart,
- chatInputSource.indexOf('const handleProviderChange = useCallback(', providerStart),
- );
- expect(providerChange).toContain('reconciledFast?: boolean');
- expect(providerChange).toContain('reconciledFast !== undefined');
- expect(providerChange).toContain('effort: atomicEffort');
- expect(providerChange).toContain('effort: remoteAtomicEffort');
-
- expect(chatInputSource).toContain(
- 'handleProviderChange(providerId, modelId, effort, undefined, fast)',
- );
- });
-
- it('reopen snapshot keeps intent model/source together; idle falls back to runtime provider', () => {
- expect(chatInputSource).toContain(
- 'const activeProviderId = runtimeEffective || composerSelection.pending ? composerSelection.display.providerId : selectedProviderId;',
- );
- expect(chatInputSource).toContain('modelId={activeModel}');
- expect(chatInputSource).toContain('currentProviderId={activeProviderId}');
- expect(chatInputSource).not.toContain('currentProviderId={selectedProviderId}');
- expect(chatInputSource).toContain('agentSwitchIntent?.target');
- expect(chatInputSource).toContain(
- 'const currentAgent = runtimeAgentKind ?? vendorKeyToAgentKind(vendorKey);',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts b/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts
deleted file mode 100644
index d19de3181f..0000000000
--- a/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-);
-
-describe('ChatInput home-suggestion prompt preview', () => {
- it('never lets a keystroke edit or send the draft hidden behind the preview', () => {
- const keyDown = chatInputSource.slice(chatInputSource.indexOf('handleKeyDown(view, event) {'));
- // The preview guard runs before every other key handler (palette, Tab, Enter/send).
- expect(keyDown.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
- keyDown.indexOf('panelBridgeRef.current'),
- );
- expect(chatInputSource).toContain('promptPreviewInputGuardRef.current = () => {');
- expect(chatInputSource).toContain('setDismissedPreviewPrompt(previewPrompt ?? null);');
- expect(chatInputSource).toContain(
- '!!previewPrompt && previewPrompt !== dismissedPreviewPrompt && !composerMutationLocked;',
- );
- });
-
- it('guards hardware composer actions with the same preview gate', () => {
- const hardware = chatInputSource.slice(
- chatInputSource.indexOf('return subscribeWorkLouderCodexAction((action) => {'),
- );
- expect(hardware.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
- hardware.indexOf("action.type === 'skill'"),
- );
- expect(hardware.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
- hardware.indexOf("case 'composer.submit':"),
- );
- });
-
- it('never resizes the composer; long previews are clamped to the space it already has', () => {
- expect(chatInputSource).not.toContain('--prompt-preview-min-h');
- expect(chatInputSource).toContain('style={{ WebkitLineClamp: promptPreviewLines }}');
- expect(chatInputSource).toContain(
- "'pointer-events-none absolute inset-x-0 top-0 line-clamp-1 py-[3px] pr-[11px]',",
- );
- });
-
- it('reports the composer mutation lock so external fills can stand down', () => {
- expect(chatInputSource).toContain('onMutationLockChange?.(composerMutationLocked);');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
deleted file mode 100644
index 66c75eae25..0000000000
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ /dev/null
@@ -1,424 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const sessionViewSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSessionView.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const messageStreamSource = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'MessageStream.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const mainLayoutSource = readFileSync(
- resolve(__dirname, '..', 'components', 'layout', 'MainLayout.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const newMakerDraftRouteSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'NewMakerDraftRoute.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const sidebarUpperSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const pluginPageSource = readFileSync(
- resolve(__dirname, '..', 'features', 'plugin', 'GhostPluginPage.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const useCCAgentChatSource = readFileSync(
- resolve(__dirname, '..', 'hooks', 'useCCAgentChat.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('ChatInput session switch focus contract', () => {
- it('refocuses the editor after storageKey switches only when requested', () => {
- const restoreNextDraftBlock = extractBetween(
- chatInputSource,
- 'const restoreNextDraft = () => {',
- 'const pendingStopAndSend = voiceInputStopAndSendPromiseRef.current;',
- );
- const firstMountHydrationBlock = extractBetween(
- chatInputSource,
- 'if (prevEditorKey === storageKey) {',
- 'const transitionSeq = storageKeyTransitionSeqRef.current + 1;',
- );
-
- expect(chatInputSource).toContain('focusOnStorageKeyChange?: boolean;');
- expect(chatInputSource).toContain('focusOnStorageKeyChange = false');
- expect(chatInputSource).toContain(
- 'const focusOnStorageKeyChangeRef = useRef(focusOnStorageKeyChange);',
- );
- expect(chatInputSource).toContain(
- 'focusOnStorageKeyChangeRef.current = focusOnStorageKeyChange;',
- );
- expect(chatInputSource).toContain('const storageKeyFocusAnchor = document.activeElement;');
- expect(restoreNextDraftBlock).toContain('if (!focusOnStorageKeyChangeRef.current) return;');
- expect(restoreNextDraftBlock).toContain(
- 'if (disableAutofocusRef.current || disabledRef.current) return;',
- );
- expect(restoreNextDraftBlock).toContain('if (!isCurrentTransition()) return;');
- expect(restoreNextDraftBlock).toContain(
- 'if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)) return;',
- );
- expect(restoreNextDraftBlock).toContain("editor.commands.focus('end');");
- expect(firstMountHydrationBlock).toContain('focusOnStorageKeyChangeRef.current');
- expect(firstMountHydrationBlock).toContain("editor.commands.focus('end');");
- });
-
- it('enables storageKey refocus for routed session and new-draft views', () => {
- expect(sessionViewSource).toContain(
- 'const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);',
- );
- expect(sessionViewSource).toContain('focusOnStorageKeyChange={ownsRoute}');
- expect(sessionViewSource).toContain(
- 'ownsHardwareComposerActions={ownsHardwareTaskActions}',
- );
- expect(chatInputSource).toContain('workLouderVoiceGestureRef.current?.cancelHeldPress();');
- expect(sessionViewSource).toContain(
- 'ownsHardwareScrollActions={ownsHardwareTaskActions}',
- );
- expect(sessionViewSource).toContain("navigationMode !== 'split-pane'");
- expect(sessionViewSource).toContain("action.commandId === 'toggleTaskPin'");
- expect(sessionViewSource).toContain("action.commandId === 'archiveTask'");
- expect(sessionViewSource).toContain('void togglePin();');
- expect(sessionViewSource).toContain('void archive();');
- expect(messageStreamSource).toContain('ownsHardwareScrollActions?: boolean;');
- expect(messageStreamSource).toContain('if (!ownsHardwareScrollActions) return false;');
- expect(mainLayoutSource).toContain("const reviewTab = bucket.tabs.find((tab) => tab.kind === 'review');");
- expect(mainLayoutSource).toContain("routeSidebarCommand({ type: 'toggle-review-tab', sessionId })");
- expect(mainLayoutSource).toContain('if (reviewIsActive && reviewTab) {');
- expect(mainLayoutSource).toContain('await closeTab(sessionId, reviewTab.id);');
- expect(mainLayoutSource).toContain(
- "navigate('/cc-agent/new', { state: makeFolderPickerNewMakerRouteState() })",
- );
- expect(newMakerDraftRouteSource).toContain('readNewMakerFolderPickerRequest(location.state)');
- expect(newMakerDraftRouteSource).toContain('setFolderPickerOpen(true)');
- expect(sidebarUpperSource).toContain(
- "const catalogSessions = sessionsWithRemote.filter((session) => session.status === 'active');",
- );
- expect(sidebarUpperSource).toContain('catalogEligible: false');
- expect(sidebarUpperSource).toContain(
- 'const remainingCatalogSlots = Math.max(0, 100 - visibleProjection.length);',
- );
- expect(sidebarUpperSource).toContain('WORKLOUDER_CODEX_AGENT_SLOT_COUNT');
- expect(sidebarUpperSource).toContain('.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT)');
- expect(sidebarUpperSource).not.toContain(
- '[...visibleSessionsWithRemote, ...remoteProjectSessions]',
- );
- expect(newMakerDraftRouteSource).toContain('focusOnStorageKeyChange');
- });
-
- it('lets only the route-owned session update the shared project scope', () => {
- const projectScopeEffect = extractBetween(
- sessionViewSource,
- '// Keep lastWorkingDir in sync',
- '// (订阅 desktop-command-triggered',
- );
-
- expect(projectScopeEffect).toContain('if (!ownsRoute) return;');
- expect(projectScopeEffect).toContain('setLastWorkingDir(session.workingDir);');
- expect(projectScopeEffect).toContain('setLastWorkingDir(null);');
- });
-
- it('keeps deferred editor mount autofocus at the draft end', () => {
- expect(chatInputSource).toContain("autofocus: !disableAutofocus && !disabled ? 'end' : false");
- });
-
- it('guards delayed storageKey focus against stealing from another focused control', () => {
- expect(chatInputSource).toContain(
- 'hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)',
- );
- });
-
- it('wires local send locking through the behavior-tested focus restore hook', () => {
- const localSendLockBlock = extractBetween(
- chatInputSource,
- '// Local/SSH lock the live composer only while the click-time document',
- 'try {\n let serializedContent',
- );
-
- expect(chatInputSource).toContain(
- 'const captureSendFocusForRestore = useComposerSendFocusRestore(',
- );
- const focusRestoreCall = extractBetween(
- chatInputSource,
- 'const captureSendFocusForRestore = useComposerSendFocusRestore(',
- 'const { settings: voiceInputSettings }',
- );
- expect(focusRestoreCall).toContain('composerTypingLocked');
- expect(focusRestoreCall).not.toContain('composerMutationLocked');
- expect(focusRestoreCall).not.toContain('sendDispatchInFlight');
- expect(localSendLockBlock).toContain('captureSendFocusForRestore();');
- expect(localSendLockBlock.indexOf('captureSendFocusForRestore();')).toBeLessThan(
- localSendLockBlock.indexOf('setSendDispatchInFlight(true);'),
- );
- });
-
- it('reuses composer entry paths for Plugin commands', () => {
- const capabilitySelectionBlock = extractBetween(
- chatInputSource,
- 'const insertAtResource = useCallback(',
- 'const handleComposerSuggestionSelect = useCallback(',
- );
-
- expect(pluginPageSource).toContain('pendingGhostId: installedGhostStoragePart(ghost)');
- expect(pluginPageSource.match(/focusAtEnd: true/g)).toHaveLength(1);
- expect(
- chatInputSource.match(/placeGhostAtComposerStart\(editor, ghost, ghostsForCommand\)/g),
- ).toHaveLength(1);
- expect(
- chatInputSource.match(
- /placeGhostAtComposerStart\(editor, ghost, composerGhostsRef\.current\)/g,
- ),
- ).toHaveLength(1);
- expect(chatInputSource).toContain('pendingGhostId: undefined');
-
- expect(capabilitySelectionBlock).toContain("selectedItem.type === 'plugin-command'");
- expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
- expect(capabilitySelectionBlock).toContain('findInstalledGhostByInstanceId(');
- expect(capabilitySelectionBlock).toContain('composerGhostsRef.current,');
- expect(capabilitySelectionBlock).toContain(
- 'placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current);',
- );
- expect(capabilitySelectionBlock).toContain('closeAtPanel();');
- expect(capabilitySelectionBlock).not.toContain('focusIOSSimulatorPanel');
- expect(chatInputSource).toContain('focusComposerEndNextFrame(editor);');
- });
-
- it('records recent Plugin usage only after a successful direct or deferred send', () => {
- const successfulSendBlock = extractBetween(
- chatInputSource,
- 'if (result === false) {',
- 'finishAgentSendDispatch();',
- );
- const worktreeSendBlock = extractBetween(
- newMakerDraftRouteSource,
- 'const accepted = await makerChatStore.sendMessage(',
- 'worktreeCreationStore.clear(newSession.id);',
- );
-
- expect(chatInputSource).toContain('findGhostByCommand(eligibleGhosts, ghostCommandToken.word, ghostCommandToken.namespace)');
- expect(chatInputSource).toContain('onAccepted: markRecentPluginUsage');
- expect(successfulSendBlock).toContain('markRecentPluginUsage();');
- // 本机首条 / worktree 首条 / 远程普通首条直接发送 / 远程视图交接 四处受理点。
- expect(newMakerDraftRouteSource.match(/opts\?\.onAccepted\?\.\(\);/g)).toHaveLength(4);
- expect(worktreeSendBlock).toContain('if (accepted) {');
- expect(worktreeSendBlock).toContain('opts?.onAccepted?.();');
- expect(worktreeSendBlock).toContain(
- 'dispatchDeferredUiAssignment(newSession.id, deferredUiAssignment)',
- );
- });
-
- it('clears the live composer before awaiting local or remote send', () => {
- const optimisticClear = chatInputSource.indexOf(
- '// Click-time composer must disappear before any await that can surface',
- );
- const clearCall = chatInputSource.indexOf('clearSentComposer();', optimisticClear);
- const onSend = chatInputSource.indexOf('result = await onSend(', optimisticClear);
- const failedRestore = chatInputSource.indexOf('restoreRemoteComposerAndRelease();', onSend);
-
- expect(optimisticClear).toBeGreaterThanOrEqual(0);
- expect(clearCall).toBeGreaterThan(optimisticClear);
- expect(onSend).toBeGreaterThan(clearCall);
- expect(failedRestore).toBeGreaterThan(onSend);
- expect(chatInputSource).not.toContain(
- 'if (!optimisticallyClearRemoteComposer) clearSentComposer();',
- );
- });
-
- it('keeps send and settings locked after optimistic clear while allowing typing', () => {
- const unlockAfterClear = extractBetween(
- chatInputSource,
- '// Click-time composer must disappear before any await that can surface',
- 'result = await onSend(',
- );
- expect(unlockAfterClear).toContain('dispatchSendClearedKeysRef.current.add(sendInFlightKey);');
- expect(unlockAfterClear).toContain('setAllowTypeDuringSend(true);');
- expect(unlockAfterClear.indexOf('dispatchSendClearedKeysRef.current.add(sendInFlightKey);')).toBeLessThan(
- unlockAfterClear.indexOf('setAllowTypeDuringSend(true);'),
- );
- expect(unlockAfterClear).not.toContain('setSendDispatchInFlight(false);');
- expect(chatInputSource).toContain(
- 'disabled || (sendDispatchInFlight && !allowTypeDuringSend)',
- );
- expect(chatInputSource).toContain('sendDispatchInFlight ||');
- expect(chatInputSource).toContain('setSendDispatchInFlight(nextSendInFlight);');
- expect(chatInputSource).toContain(
- 'setAllowTypeDuringSend(nextSendInFlight && nextSendCleared);',
- );
- expect(chatInputSource).toContain(
- 'documentBeforeOptimisticClear = plainTextToComposerDocument(serializedContent.text);',
- );
- const settleLockBlock = extractBetween(
- chatInputSource,
- 'dispatchSendInFlightKeysRef.current.delete(sendInFlightKey);',
- 'finishAgentSendDispatch();',
- );
- expect(settleLockBlock).toContain(
- 'dispatchSendClearedKeysRef.current.delete(sendInFlightKey);',
- );
- expect(settleLockBlock).toContain(
- 'storageKeyForDraftRef.current === sourceStorageKey',
- );
- expect(settleLockBlock).toContain('setAllowTypeDuringSend(false);');
- expect(settleLockBlock.indexOf('storageKeyForDraftRef.current === sourceStorageKey')).toBeLessThan(
- settleLockBlock.indexOf('setAllowTypeDuringSend(false);'),
- );
- });
-
- it('snapshots the source restore payload instead of a reused destination editor', () => {
- const snapshotBlock = extractBetween(
- chatInputSource,
- 'const editorOwnsSourceAtStart = editorOwnsSourceDraft({',
- 'const dataOwnerAtOptimisticClear = getDataOwnerGeneration();',
- );
-
- expect(snapshotBlock).toContain(
- 'optimisticallyClearRemoteComposer && editorOwnsSourceAtStart',
- );
- expect(snapshotBlock).toContain('getComposerDraft(sourceStorageKey)');
- expect(snapshotBlock).toContain('frozenVoiceSendRef.current?.sourceStorageKey === sourceStorageKey');
- expect(snapshotBlock).toContain('editorOwnsSourceAtStart\n ? editor.getJSON()');
- expect(snapshotBlock.indexOf('editorOwnsSourceAtStart')).toBeLessThan(
- snapshotBlock.indexOf('editor.getJSON()'),
- );
- });
-
- it('refreshes the local restore snapshot only while the editor still owns the source draft', () => {
- const refreshBlock = extractBetween(
- chatInputSource,
- 'const sendSnapshot = captureComposerSendSnapshot(',
- 'let recentUsageMarked = false;',
- );
-
- expect(refreshBlock).toContain('!optimisticallyClearRemoteComposer');
- expect(refreshBlock).toContain('editorOwnsSourceDraft({');
- expect(refreshBlock).toContain('documentBeforeOptimisticClear = editor.getJSON();');
- expect(refreshBlock.indexOf('editorOwnsSourceDraft({')).toBeLessThan(
- refreshBlock.indexOf('documentBeforeOptimisticClear = editor.getJSON();'),
- );
- });
-
- it('optimistically clears device-link composer state before awaiting send and restores without dropping newer input', () => {
- const transitionBegin = chatInputSource.indexOf(
- 'makerChatStore.beginRemoteOptimisticComposerTransition(',
- );
- const optimisticClear = chatInputSource.indexOf(
- '// Click-time composer must disappear before any await that can surface',
- );
- const frozenReferenceHydration = chatInputSource.search(
- /agentReferences\s*=\s*await resolveSerializedSessionMessageReferencesForSend\(agentReferences\);/,
- );
- const onSend = chatInputSource.indexOf('result = await onSend(', optimisticClear);
- const failedRestore = chatInputSource.indexOf('restoreRemoteComposerAndRelease();', onSend);
- const restoreAndReleaseBlock = extractBetween(
- chatInputSource,
- 'const restoreRemoteComposerAndRelease = () => {',
- '// Click-time composer must disappear before any await that can surface',
- );
-
- expect(chatInputSource).toContain('deviceLinkDeviceId && sourceSessionId');
- expect(transitionBegin).toBeGreaterThanOrEqual(0);
- expect(optimisticClear).toBeGreaterThanOrEqual(0);
- expect(transitionBegin).toBeLessThan(optimisticClear);
- expect(frozenReferenceHydration).toBeGreaterThan(optimisticClear);
- expect(frozenReferenceHydration).toBeLessThan(onSend);
- expect(onSend).toBeGreaterThan(optimisticClear);
- expect(failedRestore).toBeGreaterThan(onSend);
- expect(chatInputSource).toContain('sourceSessionId,\n filesToSend,');
- expect(restoreAndReleaseBlock.indexOf('restoreOptimisticallyClearedComposer();')).toBeLessThan(
- restoreAndReleaseBlock.indexOf('releaseRemoteComposerTransition();'),
- );
- expect(chatInputSource).toContain('let optimisticComposerRestored = false;');
- expect(chatInputSource).toContain('restoreRemoteOptimisticDraft(');
- expect(chatInputSource).toContain('text: isEditorEmpty(editor) ? null : editor.getJSON()');
- expect(chatInputSource).toContain('attachments: latestAttachmentsRef.current');
- expect(chatInputSource).toContain('browserComments: browserCommentsRef.current');
- expect(chatInputSource).toContain("editor.commands.focus('end');");
- expect(chatInputSource).toContain('restoreFiles(restored.attachments);');
- expect(chatInputSource).toContain(
- 'latestStorageKeyRef.current === sourceStorageKey && editorOwnsSource',
- );
- expect(chatInputSource).toContain(
- 'latestStorageKeyRef.current === sourceStorageKey &&\n storageKeyForDraftRef.current === sourceStorageKey',
- );
- expect(chatInputSource).toContain(
- 'restoreRemoteOptimisticDraft(\n sourceStorageKey,',
- );
- expect(chatInputSource).toContain('!isDataOwnerGenerationCurrent(dataOwnerAtOptimisticClear)');
- expect(chatInputSource).toContain('restoreOptimisticallyClearedComposer(clientId, {');
- expect(chatInputSource).toContain('isRemoteOptimisticDataOwnerBoundaryError(error)');
- expect(chatInputSource).toContain('isRemoteOptimisticSessionPurgedError(error)');
- expect(chatInputSource).toContain('optimisticComposerRestored = true;');
- expect(chatInputSource).toContain('isRemoteOptimisticComposerTransitionActive(');
- expect(chatInputSource).toContain('updateLive: !isDataOwnerBoundary');
- expect(chatInputSource).toContain('recoveryBatch: error as object');
- expect(chatInputSource).toContain('recoveryBatch ? { recoveryBatch } : undefined');
- expect(chatInputSource).toContain('if (!updateLive || !isCurrentComposer) return;');
- expect(chatInputSource).toContain('if (!isDataOwnerIdCurrent(dataOwnerAtEffect))');
- expect(chatInputSource).toContain(
- 'if (!isDataOwnerIdCurrent(dataOwnerAtSubscription)) return;',
- );
- expect(chatInputSource).toContain('browserCommentsRef.current = nextBrowserComments;');
- expect(chatInputSource).toContain('browserCommentsRef.current = restoredComments;');
- expect(chatInputSource).not.toContain('mergeComposerDocumentsForRestore(');
- });
-
- it('reuses the original voice-session recovery checkpoint until the editor owner switches', () => {
- expect(chatInputSource).toContain('useRef<RemoteOptimisticTransitionCheckpoint | null>(null)');
- expect(chatInputSource).toContain('getOrCreateRemoteOptimisticTransitionCheckpoint(');
- expect(chatInputSource).toContain('saveComposerTextAfterAsyncTransition(');
- expect(chatInputSource).toContain('recoveryCheckpoint!');
- expect(chatInputSource).toContain(
- 'if ((pendingStopAndSend || voiceInputBusyRef.current) && prevEditorKey && voiceOwnerKey)',
- );
- expect(chatInputSource).toContain('}, [editor, storageKey]);');
- expect(chatInputSource).not.toContain('}, [editor, storageKey, voiceInput.isBusy]);');
- expect(chatInputSource.match(/storageKeyTransitionRecoveryRef\.current = null;/g)).toHaveLength(
- 2,
- );
- });
-
- it('propagates the existing-session enqueue acceptance promise back to ChatInput', () => {
- const sendMessageBlock = extractBetween(
- useCCAgentChatSource,
- 'const sendMessage = useCallback(',
- 'const compactSession = useCallback(',
- );
-
- expect(sendMessageBlock).toContain('): Promise<boolean> => {');
- expect(sendMessageBlock).toContain('return makerChatStore.sendMessage(');
- });
-
- it('keeps MRU ordering scoped to the installed shortcut row and subscribes to updates', () => {
- expect(pluginPageSource).toContain(
- 'window.electronAPI.ghosts.onRecentUsageChanged(({ ids }) => {',
- );
- // Ranking runs over the (searched) installed set, not the raw ghost list, and feeds
- // recent-use + unread signals into the shared pure sorter.
- expect(pluginPageSource).toMatch(/sortInstalledForDisplay\(searchedInstalledItems, \{/);
- expect(pluginPageSource).toContain('recentIds: recentGhostIds');
- expect(pluginPageSource).not.toContain('sortInstalledForDisplay(ghosts');
- expect(pluginPageSource).not.toContain('sortInstalledForDisplay(installedItems');
- });
-});
-
-function extractBetween(sourceBlock: string, startNeedle: string, endNeedle: string): string {
- const start = sourceBlock.indexOf(startNeedle);
- const end = sourceBlock.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return sourceBlock.slice(start, end);
-}
diff --git a/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts b/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts
deleted file mode 100644
index e68d37409d..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * composerExternalDraftEmptyDoc.test.ts — 外部草稿通知的「空文档」判空口径
- * ---------------------------------------------------------------------------
- * ChatInput 订阅 composerDraftStore 的外部写入后,只有在草稿正文与编辑器当前
- * 文档真的不同时才做全量 setContent。草稿正文在存储里是 Tiptap JSON:空草稿
- * 常常是 `{doc:[空 paragraph]}` 而不是 `null`,而比较的另一侧对「编辑器为空」
- * 一律折叠成 `null`。两侧口径不一致时,每条外部通知都会拿一份空文档原地重建
- * doc(`replace(0, size)`),把所有按位置存活的编辑器状态强行跨整篇映射——语音
- * 录音时 caret 锚点被推出段落、首行多一个空行就是这么来的。
- *
- * 契约锁在源码层:该分支必须用 composerDraftStore 的判空把空文档折叠成 null,
- * 不能只判断 `draft.text` 是否存在。
- */
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-// CRLF 归一化:Windows checkout 下源码带 \r\n,否则跨 checkout 断言会假失败
-// (同 chatInputSessionFocus 等既有源码契约测试)。
-const chatInput = readFileSync(
- path.join(path.resolve(__dirname, '..'), 'components/new-chat/ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('external draft notification empty-document handling', () => {
- it('collapses an empty draft document to null before comparing with the editor', () => {
- const start = chatInput.indexOf('return subscribeComposerDraft(storageKey, () => {');
- expect(start).toBeGreaterThan(-1);
- // 两个锚点都必须真实命中:end 缺失时 indexOf 返回 -1,slice(start, -1) 会切出
- // 一大段无关源码,让下面的 toContain 假通过、契约形同失效。
- const end = chatInput.indexOf('const textUnchanged', start);
- expect(end).toBeGreaterThan(start);
- const block = chatInput.slice(start, end);
-
- expect(block).toContain('normalizeRestoredComposerDraft(draft.text)');
- // 判空必须走共享实现,与 draftHasContent / isEditorEmpty 同源。
- expect(block).toContain('tiptapDocHasContent(');
- expect(block).not.toMatch(/const normalizedDraftText = draft\.text\s*\n?\s*\?/);
- });
-
- // 同一口径也必须覆盖 storageKey 对齐分支:它依赖 voiceInput.isBusy,录音开始与
- // 结束各重跑一次。漏判空时新建对话页(草稿键固定、常留一份空正文)会在语音结束
- // 时重建 doc,把插入点推到 block 边界 —— 上屏文字前多一个空行。
- it('also collapses an empty draft document on the storageKey-aligned hydration path', () => {
- const start = chatInput.indexOf('// First-mount hydration path');
- expect(start).toBeGreaterThan(-1);
- const end = chatInput.indexOf('editorStorageKeyRef.current = storageKey;', start);
- expect(end).toBeGreaterThan(start);
- const block = chatInput.slice(start, end);
-
- expect(block).toContain('tiptapDocHasContent(draft.text)');
- expect(block).toContain('composerDocIsEmpty(editor.state.doc)');
- // 不能再直接拿 draft.text 当"有草稿"的判据。
- expect(block).not.toMatch(/if \(draft\?\.text && composerDocIsEmpty/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts b/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts
deleted file mode 100644
index b92fb37f6e..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const rendererRoot = path.resolve(__dirname, '..');
-const read = (relativePath: string) => fs.readFileSync(path.join(rendererRoot, relativePath), 'utf8');
-
-const chatInput = read('components/new-chat/ChatInput.tsx');
-const modelSelector = read('components/new-chat/ModelSelector.tsx');
-const permissionSelector = read('components/new-chat/PermissionSelector.tsx');
-const extraDirsButton = read('components/new-chat/ExtraDirsButton.tsx');
-const settingsModel = read('components/settings/ImDefaultSettingsSection.tsx');
-const subagentModel = read('components/settings/SubagentModelSection.tsx');
-const createWorker = read('features/cc-agent/CreateWorkerPopover.tsx');
-const agentSelect = read('components/new-chat/AgentSelect.tsx');
-const workspacePrefs = read('components/settings/HookWorkspacePrefsEditor.tsx');
-
-// 2026-07-22:composer 工具条(含新建对话框 create-agent)统一走脱身上浮 morph;非 composer 场景
-// (settings / subagent / CreateWorker)仍用 Radix。取代 origin/main「morph 仅普通工具条 opt-in、
-// create-agent 固定尺寸」的旧作用域(脱身上浮方案由用户 2026-07-22 定稿取代原位取代)。
-describe('composer morph scope', () => {
- it('ModelSelector 的形变仅 composer 工具条 opt-in;settings/subagent/CreateWorker 不 opt-in(走 Radix)', () => {
- // ChatInput 无条件给 ModelSelector 传 useMorphPopover(create-agent 也 morph,与会话内统一)
- expect(chatInput).toContain('useMorphPopover');
- expect(settingsModel).not.toContain('useMorphPopover');
- expect(subagentModel).not.toContain('useMorphPopover');
- expect(createWorker).not.toContain('useMorphPopover');
- });
-
- it('ModelSelector 保留 useMorphPopover 作用域开关 + Radix 回退(供 settings field / CreateWorker)', () => {
- expect(modelSelector).toContain('useMorphPopover = false');
- expect(modelSelector).toContain('<PopoverTrigger asChild>{trigger}</PopoverTrigger>');
- });
-
- it('composer 选完模型后把焦点送回输入框;设置页不传 restoreFocusTarget', () => {
- expect(chatInput).toContain('restoreFocusTarget={composerSuggestionFocusTarget}');
- expect(modelSelector).toContain('restoreFocusTarget?: () => HTMLElement | null');
- expect(modelSelector).toContain('onMouseDown={morphEnabled ? (event) => event.preventDefault() : undefined}');
- expect(settingsModel).not.toContain('restoreFocusTarget');
- expect(subagentModel).not.toContain('restoreFocusTarget');
- expect(createWorker).not.toContain('restoreFocusTarget');
- });
-
- it('PermissionSelector / ExtraDirsButton 仅 composer 使用,恒走脱身上浮 morph(无 opt-in、无 Radix 回退)', () => {
- expect(permissionSelector).not.toContain('useMorphPopover');
- expect(extraDirsButton).not.toContain('useMorphPopover');
- expect(permissionSelector).toContain('<MorphPopover');
- expect(extraDirsButton).toContain('<MorphPopover');
- });
-
- it('语音录音展开:会话内与新建对话框共用(expandable 恒真),呼吸动画尊重 reduced-motion', () => {
- expect(chatInput).toContain('const expandable = true;');
- expect(chatInput).toContain('return () => window.clearInterval(id);');
- expect(chatInput).toContain('inline-flex animate-pulse motion-reduce:animate-none');
- });
-});
-
-// 设置场景复用工具条控件时的宽度契约(codex review #1490)。DESIGN.md §4
-// Select & Dropdown:「Panel width must bind to the trigger width — never narrower
-// or wider than the control that opened it」。工具条形态的 trigger 按内容 hug、
-// 面板固定 196px,直接放进设置字段会让短标签(Claude / Pi)下面板明显宽于 trigger。
-describe('设置字段里的 AgentSelect 宽度契约', () => {
- it('两处设置场景都用 field 形态,不得把工具条形态塞进字段', () => {
- for (const src of [settingsModel, workspacePrefs]) {
- expect(src).toContain('<ModelSelector');
- expect(src).not.toContain('<AgentSelect');
- expect(src).toContain('triggerVariant="field"');
- }
- });
-
- it('field 形态把面板宽度交给 trigger 实测值,工具条形态保持固定 196px', () => {
- expect(agentSelect).toContain("panelWidthMode: 'trigger' as const");
- expect(agentSelect).toContain('panelWidth: 196');
- });
-
- it('MorphPopover 支持 trigger 绑定宽度模式(严格等宽,不取 max)', () => {
- const morph = read('components/ui/morph-popover.tsx');
- expect(morph).toContain("panelWidthMode?: 'content' | 'trigger'");
- expect(morph).toContain('desiredW = chipRect.width;');
- });
-});
-
-// + 菜单嵌在 480 宽、1px 边框的 Morph 壳里。内层再写死 480 会横向溢出 2px,
-// 打开瞬间 scrollIntoView 点亮 .is-scrolling,底部闪 2 秒横向滚动条。
-describe('+ 菜单 embedded 宽度契约', () => {
- it('embedded AtMentionPanel 跟 Morph 壳等宽,横轴 overflow 显式 hidden', () => {
- const atMention = read('components/new-chat/AtMentionPanel.tsx');
- const morph = read('components/ui/morph-popover.tsx');
- expect(atMention).toContain("embedded ? 'w-full min-w-0' : 'w-[480px]'");
- expect(atMention).toContain('overflow-x-hidden overflow-y-auto');
- expect(morph).toContain('overflow-x-hidden overflow-y-hidden');
- expect(morph).toContain("content.style.overflowX = 'hidden'");
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts b/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts
deleted file mode 100644
index 18681552f7..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const rendererRoot = join(__dirname, '..');
-const read = (relativePath: string) =>
- readFileSync(join(rendererRoot, 'components/new-chat', relativePath), 'utf8');
-
-const chatInputSource = read('ChatInput.tsx');
-const modelSelectorSource = read('ModelSelector.tsx');
-const permissionSelectorSource = read('PermissionSelector.tsx');
-
-describe('composer narrow toolbar contract', () => {
- it('uses discrete card-width modes for both default-session and create-agent composers', () => {
- expect(chatInputSource).toContain("useState<ToolbarWidthMode>('unmeasured')");
- expect(chatInputSource).toContain('currentMode === nextMode ? currentMode : nextMode');
- expect(chatInputSource).toContain(
- 'const useNarrowToolbar = narrowToolbar || autoNarrowToolbar;',
- );
- expect(chatInputSource).not.toContain('setToolbarWidth(el.clientWidth)');
- expect(chatInputSource).toContain('compactToolbar={useNarrowToolbar}');
- expect(chatInputSource).toContain('ultraCompactToolbar={useUltraCompactToolbar}');
- expect(chatInputSource).toContain('iconOnly={useUltraCompactToolbar}');
- });
-
- it('reserves fixed action space and makes permission/model chrome compact by container state', () => {
- expect(chatInputSource).toContain("'flex shrink-0 items-center gap-1'");
- expect(modelSelectorSource).toContain(
- 'const isCompactToolbar = compactToolbar && !isFieldTrigger;',
- );
- expect(modelSelectorSource).toContain("'w-[148px] min-w-[72px]'");
- expect(modelSelectorSource).toContain("'w-[64px] min-w-[64px]'");
- // 2026-08-12 Chris 裁决(bug7):composer pill 换成「模型名 + 引擎小标 + 深度」后,
- // 窄工具条下**先截模型名**,小标与档字保留 —— 它们是定宽身份位,截掉等于把
- // 「现在用哪个引擎、多深」藏起来。只有 ultra-compact(整段文字都收起、只剩图标)
- // 才一并隐藏。没有引擎小标的旧形态(其余 7 个入口)维持原来的 compact 即隐藏。
- expect(modelSelectorSource).toContain(
- 'const showTriggerTail = engineMarkOption ? !isUltraCompactToolbar : !isCompactToolbar;',
- );
- // 长英文档名在固定宽度的紧凑 trigger 内允许省略显示,完整值仍由 title / aria-label 提供。
- expect(modelSelectorSource).toContain("? 'min-w-0 shrink truncate'");
- expect(modelSelectorSource).toContain('{effortLabel && showTriggerTail && (');
- expect(permissionSelectorSource).toContain(
- 'const isIconOnly = iconOnly && !isFieldTrigger;',
- );
- expect(permissionSelectorSource).toContain(
- "'h-[30px] w-[34px] min-w-[34px] justify-center px-0'",
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts b/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts
deleted file mode 100644
index 6719e0372c..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const globalsSource = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');
-
-describe('composer placeholder CSS', () => {
- it('renders the placeholder when Tiptap leaves only the empty-node class', () => {
- expect(globalsSource).toContain('.ProseMirror > p.is-empty:first-child:only-child::before {');
- });
-
- it('keeps the empty-node fallback hidden while a voice draft is active', () => {
- expect(globalsSource).toContain(
- "[data-voice-draft-active='true'] .ProseMirror > p.is-empty:first-child:only-child::before {",
- );
- });
-
- it('keeps the native placeholder hidden while a recommendation overlay is active (is-empty fallback included)', () => {
- expect(globalsSource).toContain(
- "[data-recommendation-active='true'] .ProseMirror > p.is-empty:first-child:only-child::before {",
- );
- });
-
- it('only hides the editor content while a suggestion preview is active, never resizing it', () => {
- const start = globalsSource.indexOf("[data-prompt-preview-active='true'] .ProseMirror {");
- const block = globalsSource.slice(start, globalsSource.indexOf('}', start));
- expect(block).toContain('opacity: 0;');
- expect(block).not.toContain('height');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts
deleted file mode 100644
index ff7e4c7fe6..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-describe('composer quote palette boundary wiring', () => {
- it('resets slash and mention trigger scanning at composer quote atoms', () => {
- const source = readFileSync(
- resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),
- 'utf8',
- );
- const triggerStart = source.indexOf('function detectTrigger');
- const triggerEnd = source.indexOf('// Slash detection', triggerStart);
- const triggerSource = source.slice(triggerStart, triggerEnd);
-
- expect(triggerSource).toMatch(
- /child\.type\.name === 'mentionChip'\s*\|\|\s*child\.type\.name === COMPOSER_QUOTE_NODE_TYPE/,
- );
- expect(triggerSource).toContain("textSoFar = ''; // chips reset the @ / slash run");
- });
-
- it('routes @ plugin selection through the shared command placement', () => {
- const source = readFileSync(
- resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),
- 'utf8',
- );
-
- expect(source).toContain("type: 'plugin-command'");
- expect(source).toContain('placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current)');
- expect(source).not.toContain('scanPluginAtResources');
- });
-
- it('records a scheduled mention query before reserving its scan sequence', () => {
- const source = readFileSync(
- resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),
- 'utf8',
- );
- const guard = 'if (normalizedQuery === atLastScanQueryRef.current) return;';
- const record = 'atLastScanQueryRef.current = normalizedQuery;';
- const reserve = 'const seq = ++atScanSeqRef.current;';
- const effectStart = source.indexOf(guard, source.indexOf('// Derive query string'));
-
- expect(effectStart).toBeGreaterThan(-1);
- expect(source.indexOf(record, effectStart)).toBeLessThan(source.indexOf(reserve, effectStart));
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.ts b/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.ts
deleted file mode 100644
index ca73a7b292..0000000000
--- a/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { readFileSync } from 'node:fs';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- new URL('../components/new-chat/ChatInput.tsx', import.meta.url),
- 'utf8',
-).replace(/\r\n/g, '\n');
-
-describe('composer synthetic suggestion open contract', () => {
- it('device-link 远程草稿没有工作目录时仅为空查询跳过资源扫描', () => {
- const start = source.indexOf('const runAtScan = useCallback');
- const end = source.indexOf('const syntheticAtQuery', start);
- const scanner = source.slice(start, end);
- const normalizedQuery = "const normalizedQuery = query?.trim() ?? '';";
- const guard = 'if (remoteDeviceId && !workingDir?.trim() && !normalizedQuery) {';
-
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- expect(scanner).toContain(normalizedQuery);
- expect(scanner).toContain(guard);
- expect(scanner.indexOf(normalizedQuery)).toBeLessThan(scanner.indexOf(guard));
- expect(scanner.indexOf(guard)).toBeLessThan(scanner.indexOf('scanAtResources('));
- expect(scanner).toContain("setAtState({ kind: 'ready', items: [], truncated: false });");
- });
-
- it('SSH 远程面板跳过扫描时作废旧的异步扫描', () => {
- const start = source.indexOf('const runAtScan = useCallback');
- const end = source.indexOf('const syntheticAtQuery', start);
- const scanner = source.slice(start, end);
- const guardStart = scanner.indexOf('if (isRemoteSession) {');
- const guardEnd = scanner.indexOf('\n }', guardStart);
- const guard = scanner.slice(guardStart, guardEnd);
-
- expect(guardStart).toBeGreaterThanOrEqual(0);
- expect(guardEnd).toBeGreaterThan(guardStart);
- expect(guard).toContain('atScanSeqRef.current += 1;');
- expect(guard.indexOf('atScanSeqRef.current += 1;')).toBeLessThan(
- guard.indexOf("setAtState({ kind: 'ready', items: [], truncated: false });"),
- );
- });
-
- it('synthetic 查询使用映射后的独立范围,typed @ 才向后扫描完整 run', () => {
- const start = source.indexOf('const resolveEffectiveAtRange = useCallback');
- const end = source.indexOf('const insertAtResource', start);
- const resolver = source.slice(start, end);
-
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- expect(resolver).toContain("if (effectiveAt.activation === 'synthetic') {");
- expect(resolver).toContain('const to = syntheticAtRangeEndRef.current;');
- expect(resolver).toContain('return to !== null && to >= from ? { from, to } : null;');
- expect(resolver).toContain('const triggerOffset = 1;');
- expect(resolver).toContain('let runEnd = from + triggerOffset;');
- expect(resolver).toContain('const offset = from - parentStart + triggerOffset;');
- });
-
- it('synthetic 空查询保持零长度替换范围', () => {
- const stateStart = source.indexOf('const syntheticAtAnchorRef = useRef');
- const stateEnd = source.indexOf('const [isDragOver', stateStart);
- const state = source.slice(stateStart, stateEnd);
-
- expect(stateStart).toBeGreaterThanOrEqual(0);
- expect(stateEnd).toBeGreaterThan(stateStart);
- expect(state).toContain('const syntheticAtRangeEndRef = useRef<number | null>(null);');
- expect(state).toContain('syntheticAtRangeEndRef.current = next;');
- });
-
- it('synthetic 输入范围随文档 transaction 映射', () => {
- const start = source.indexOf('onUpdate: ({ editor: ed, transaction }) => {');
- const end = source.indexOf('const nextRenderSnapshot', start);
- const updater = source.slice(start, end);
-
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- expect(updater).toContain('transaction.docChanged');
- expect(updater).toContain('transaction.mapping.map(syntheticRangeEnd, 1)');
- });
-
- it('已有文本选区时 + 仍以选区起点打开空查询面板', () => {
- const deriveStart = source.indexOf('function deriveSyntheticAtQuery');
- const deriveEnd = source.indexOf('\n}\n\nexport function ChatInput', deriveStart);
- const derive = source.slice(deriveStart, deriveEnd);
- const handlerStart = source.indexOf('const handleComposerSuggestionOpenChange = useCallback');
- const handlerEnd = source.indexOf('const composerSuggestionFocusTarget', handlerStart);
- const handler = source.slice(handlerStart, handlerEnd);
-
- expect(deriveStart).toBeGreaterThanOrEqual(0);
- expect(deriveEnd).toBeGreaterThan(deriveStart);
- expect(derive).toContain("if (!selection.empty) return selection.from === anchor ? '' : null;");
- expect(handlerStart).toBeGreaterThanOrEqual(0);
- expect(handlerEnd).toBeGreaterThan(handlerStart);
- expect(handler).toContain('setSyntheticAtAnchor(editor.state.selection.from);');
- });
-
- it('打开 + 时保留同一 typed @ run 的 Esc suppression', () => {
- const start = source.indexOf('const handleComposerSuggestionOpenChange = useCallback');
- const end = source.indexOf('const composerSuggestionFocusTarget', start);
- const handler = source.slice(start, end);
-
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- expect(handler).toContain('setSuppressedAtAt(trigger.from);');
- expect(handler).not.toContain('setSuppressedAtAt(null);');
- expect(handler).not.toContain('if (atOpen)');
- expect(handler).toContain('setSyntheticAtAnchor(editor.state.selection.from);');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
deleted file mode 100644
index c24c1491b7..0000000000
--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-/**
- * dialogueSidebarSection — projectless conversation sidebar invariants.
- *
- * These are static checks because the renderer test environment has no jsdom.
- *
- * 侧边栏重设计 D 期(2026-08-12,docs/product-rules/sidebar-redesign-plan.md):
- * 旧裁决「Dialogue 是 Projects 的同级固定段、固定显示在 Projects 之后」已被
- * **有意推翻**——对话与项目行在主列表中按同一口径混排(mainListModel),
- * 「对话归为一组」成为可选开关。本文件的不变量随之改写:
- * - 主列表由 ProjectsSection 统一渲染,dialogues 作为混排输入传入;
- * - 项目筛选含「对话」哨兵:未勾选 DIALOGUE_FILTER_KEY 时隐藏无项目任务;
- * - 固定 DialogueSection 段与按日期分组段不再渲染。
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const sidebarSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
-);
-
-const projectsSectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'ProjectsSection.tsx'),
- 'utf8',
-);
-
-const mainListModelSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'lib', 'mainListModel.ts'),
- 'utf8',
-);
-
-const newMakerDraftRouteSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'NewMakerDraftRoute.tsx'),
- 'utf8',
-);
-
-function extractHandlerBlock(source: string, name: string): string {
- const match = source.match(new RegExp(`const ${name}\\s*=\\s*[\\s\\S]*?(?:\\}, \\[|\\};)`));
- expect(match, `expected to find handler ${name}`).not.toBeNull();
- return match![0];
-}
-
-const remoteProjectsHookSource = readFileSync(
- resolve(__dirname, '..', 'features', 'device-link', 'useDeviceLinkRemoteProjects.ts'),
- 'utf8',
-);
-
-describe('Mixed main list (sidebar-redesign D 期)', () => {
- it('renders dialogues through the mixed ProjectsSection instead of a fixed DialogueSection', () => {
- expect(sidebarSource).toContain('dialogues={visibleDialogues}');
- expect(sidebarSource).not.toContain('<DialogueSection');
- expect(projectsSectionSource).toContain('useMainListEntries({');
- const entriesHook = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useMainListEntries.ts'),
- 'utf8',
- );
- expect(entriesHook).toContain('buildMainListEntries({');
- expect(entriesHook).toContain('projects, dialogues, bots, unclassified');
- });
-
- it('drops the removed date-grouped section entirely', () => {
- expect(sidebarSource).not.toContain('<DateGroupedSessionsSection');
- expect(sidebarSource).not.toContain("filter.groupBy === 'date'");
- });
-
- it('lets the project filter include or exclude dialogues via DIALOGUE_FILTER_KEY', () => {
- expect(sidebarSource).toContain('DIALOGUE_FILTER_KEY');
- expect(sidebarSource).toContain('filter.projectsAsSet.has(DIALOGUE_FILTER_KEY)');
- });
-
- it('keeps custom project order scoped to project rows', () => {
- // 自定义项目顺序只重排项目行;散排对话 / 对话组不进 manualProjectOrder。
- expect(mainListModelSource).toContain("projectOrder === 'custom'");
- expect(mainListModelSource).toContain('normalizeManualProjectOrder');
- expect(projectsSectionSource).toContain('customProjectOrder && !deviceGroupingActive');
- });
-
- it('holds the current priority rank before click-path attention clear', () => {
- const clickHandler = extractHandlerBlock(sidebarSource, 'handleSessionClick');
- // Remote rows live in the merged index, not the local sessions array.
- expect(clickHandler).toContain('const target = sessionsByIdRef.current.get(id)');
- expect(clickHandler).toContain('target ? [target] : []');
- expect(clickHandler.indexOf('holdSidebarViewedPriority')).toBeGreaterThan(-1);
- expect(clickHandler.indexOf('holdSidebarViewedPriority')).toBeLessThan(
- clickHandler.indexOf('clearNotification(id)'),
- );
- });
-
- it('offers the dialogue group as an opt-in toggle, not a fixed section', () => {
- expect(mainListModelSource).toContain('groupDialogue');
- /*
- 组件 2026-08-23 改名为 SessionGroupNode:对话组与**伙伴组**是同一种东西 ——
- 一个带标题的会话组,只差图标和标题,所以参数化而不是复制一份出来。
- 对话组仍是它的默认形态(不传 groupIcon / groupTitle 时逐字如旧)。
- */
- expect(projectsSectionSource).toContain('SessionGroupNode');
- expect(projectsSectionSource).toContain("groupTitle ?? t('ccAgent.sidebar.dialogues')");
- });
-
- it('loads archived sessions on demand for the selected connected remote devices', () => {
- expect(sidebarSource).toContain("if (filter.status === 'active') return;");
- expect(sidebarSource).toContain("requestRemoteSessionStatus(device.deviceId, 'archived')");
- expect(sidebarSource).toContain('if (!device.connected) continue;');
- expect(sidebarSource).toContain('selectedRemoteIds && !selectedRemoteIds.has(device.deviceId)');
- // 折叠 rail 与展开态必须共用同一状态过滤结果,不能在「已归档」下继续露出 active。
- expect(sidebarSource).toContain('statusFilteredSessionsWithRemote');
- expect(sidebarSource).toContain('matchesSidebarSessionStatus');
- });
-
- it('shows remote directory/task loading and failures before connecting or authoritative empty states', () => {
- const failureIndex = sidebarSource.indexOf(
- 'remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent',
- );
- const connectingIndex = sidebarSource.indexOf('selectedMachineConnecting ?');
- expect(failureIndex).toBeGreaterThanOrEqual(0);
- expect(connectingIndex).toBeGreaterThan(failureIndex);
- expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoadFailed'");
- expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksPartiallyFailed'");
- // 任务读取失败是「自动重试进行中」的状态说明(reconciler 退避重试 + 熔断探测恢复
- // 自动补拉),不再提供手动重试按钮(2026-08 弱网实测反馈:重连必须全自动)。
- expect(sidebarSource).not.toContain('retryRemoteSessionBootstrap(device.deviceId)');
- expect(sidebarSource).not.toContain("'ccAgent.sidebar.machineSwitcher.retryTasks'");
- expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoading'");
- expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.devicesLoading'");
- // 设备目录失败不打断侧栏:断网或远端不可达时都继续显示本地与已缓存内容。
- expect(sidebarSource).not.toContain('kind="devices"\n status="error"');
- expect(sidebarSource).not.toContain('retryDeviceLinkDeviceList');
- expect(sidebarSource).not.toContain("'ccAgent.sidebar.machineSwitcher.devicesLoadFailed'");
- expect(sidebarSource).not.toContain("'ccAgent.sidebar.machineSwitcher.devicesPartiallyFailed'");
- expect(sidebarSource).not.toContain("'ccAgent.sidebar.machineSwitcher.retryDevices'");
- // 即使有旧/空 shard,本轮 gave-up 也必须进 error,不能把缓存伪装成权威结果。
- expect(remoteProjectsHookSource).toContain("if (result === 'gave-up') {");
- expect(remoteProjectsHookSource).not.toContain(
- "result === 'gave-up' && !remoteProjectsStore.hasDevice(deviceId)",
- );
- expect(remoteProjectsHookSource).toContain(
- 'remoteProjectsStore.markSessionStatusFailed(deviceId, status)',
- );
- expect(remoteProjectsHookSource).toContain('scheduleArchivedSessionRetry(deviceId)');
- expect(remoteProjectsHookSource).toContain("retryRemoteSessionStatus(deviceId, 'archived')");
- expect(sidebarSource).toContain('useRemoteArchivedFailedDeviceIds()');
- expect(sidebarSource).toContain('useRemoteArchivedLoadedDeviceIds()');
- expect(sidebarSource).toContain("if (filter.status === 'archived')");
- });
-
- it('keeps device directory loading as quiet text without a background panel', () => {
- expect(sidebarSource).toContain(
- "const quietDeviceLoading = kind === 'devices' && status === 'loading';",
- );
- expect(sidebarSource).toContain(
- "'mx-3 flex flex-col items-center gap-3 px-4 py-8 text-center text-[var(--text-secondary)]'",
- );
- expect(sidebarSource).toContain('!quietDeviceLoading &&');
- expect(sidebarSource).toContain('bg-[var(--surface-chip)] text-[var(--text-secondary)]');
- });
-
- it('keeps remote background loading from changing the sidebar layout', () => {
- // Existing local/cached rows must stay in place while remote bootstrap runs in the background.
- // A partial loading notice in the scroll flow makes every row jump when it mounts/unmounts.
- expect(sidebarSource).toContain('远程任务 / 设备目录的 loading 只在上面的「无内容」分支显示');
- expect(sidebarSource).not.toMatch(
- /remoteDeviceDirectoryStatus === 'loading'\s*&&\s*\n?\s*\(\s*<RemoteSidebarLoadNotice[\s\S]*?partial\s*\/\>\s*\)/,
- );
- expect(sidebarSource).not.toMatch(
- /remoteSessionBootstrapLoadingDevices\.length > 0\s*&&\s*\n?\s*\(\s*<RemoteSidebarLoadNotice[\s\S]*?partial\s*\n?\s*\/\>\s*\)/,
- );
- });
-
- it('routes standalone dialogue targets through the mounted draft page transition', () => {
- const handler = extractHandlerBlock(sidebarSource, 'handleCreateDialogue');
- expect(sidebarSource).toContain(
- 'resolveDialogueDeviceTarget(selectedMachineId, switcherDevices, deviceListSettled)',
- );
- expect(handler).toContain("selectedDialogueDeviceResolution.status === 'pending'");
- // 无显式目标时仍走作用域推断(pending 守卫 + resolution.target);显式目标见下一条。
- expect(handler).toContain('if (deviceTarget === undefined)');
- expect(handler).toContain('target = selectedDialogueDeviceResolution.target;');
- expect(handler).toContain('state: makeDialogueNewMakerRouteState(target)');
- expect(handler).not.toContain('resetDraftWorkspaceTargets');
- expect(handler).not.toContain('patchNewMakerDraft');
- expect(newMakerDraftRouteSource).toContain('readNewMakerDialogueTargetRequest(location.state)');
- expect(newMakerDraftRouteSource).toContain(
- 'handledDialogueTargetRequestRef.current === dialogueTargetRequest.requestId',
- );
- expect(newMakerDraftRouteSource).toContain('patchCollab({ enabled: false });');
- expect(newMakerDraftRouteSource).toMatch(
- /applyDraftTarget\(\{\s*deviceId: dialogueTargetRequest\.deviceId,\s*deviceName: dialogueTargetRequest\.deviceName,\s*workingDir: null,/,
- );
- expect(newMakerDraftRouteSource).toContain(
- 'state: consumeNewMakerDialogueTargetRequest(location.state)',
- );
- expect(newMakerDraftRouteSource).toContain('replace: true');
- expect(handler).toContain("navigate('/cc-agent/new'");
- // 混排后展开态的「新建对话」入口并入统一新建;rail 对话面板仍保留独立入口。
- expect(sidebarSource).toContain('onCreateDialogue={handleCreateDialogue}');
- expect(sidebarSource).toContain('isCreateDialogueDisabled={dialogueCreatePending}');
- });
-
- // 2026-08-12 用户裁决:按设备分组时,某个设备段下「对话」组的新建必须落在该设备上,
- // 不再按当前机器作用域猜(作用域可能是「所有」或另一台设备)。
- it('creates the dialogue on the device that owns the group when grouping by device', () => {
- // 设备段把自己的设备作为创建目标传下去:本机段 null,远程段 {deviceId, deviceName}。
- expect(projectsSectionSource).toContain('const sectionDialogueTarget = section.deviceId');
- expect(projectsSectionSource).toContain(
- 'renderNonProjectEntry(entry, key, sectionDialogueTarget)',
- );
- // 不按设备分组的两条渲染路径不传目标 → 上层沿用作用域推断。
- expect(projectsSectionSource).toContain('renderNonProjectEntry(entry, DIALOGUE_GROUP_ALL_KEY)');
- // Cindy Make has its own local create dialog; ordinary dialogue groups
- // still route creation to the owning device.
- expect(projectsSectionSource).toContain('setMakeCreateOpen(true)');
- expect(projectsSectionSource).toContain('onCreateDialogue(dialogueDeviceTarget)');
- // 目标设备离线 → 禁用新建并复用远程写保护文案(被控端才是真正的创建方)。
- expect(projectsSectionSource).toContain("t('ccAgent.remoteSession.actionsUnavailable')");
- expect(projectsSectionSource).toMatch(/const targetDeviceOffline = Boolean\(/);
- // 显式目标不受作用域解析 pending 影响(目标已定,无需等设备目录 settle)。
- expect(projectsSectionSource).toContain(
- 'dialogueDeviceTarget === undefined ? isCreateDialogueDisabled : false',
- );
- });
-
- // 2026-08-12 实机反馈:list 变体的分割线是「每行底线 + 列表首行顶线」,而混排把
- // 每条散排对话各渲染成一个单条 SessionEntryList → 每个都自认首行,上一行底线与
- // 本行顶线叠成两根横线。散排路径必须关掉顶线(底线已覆盖行间分割)。
- it('does not double up dividers between standalone dialogues in list mode', () => {
- const sessionEntryListSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'SessionEntryList.tsx'),
- 'utf8',
- );
- expect(sessionEntryListSource).toContain('isFirst={showFirstDivider && index === 0}');
- expect(projectsSectionSource).toContain('showFirstDivider={false}');
- // 真正的列表首行(置顶段 / 项目内会话 / 自动化组)保持默认,不传该 prop。
- const pinnedSectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'PinnedSection.tsx'),
- 'utf8',
- );
- expect(pinnedSectionSource).not.toContain('showFirstDivider');
- });
-
- it('allows the shared create route to send a standalone dialogue without picking a project', () => {
- // 产品决策:新建入口、对话段 +、项目行内 + 都进同一个创建页;差异只在默认
- // workingDir。workingDir 为空时直接创建 dialogue,不再强制弹项目 picker。
- expect(newMakerDraftRouteSource).not.toContain('selectProjectRequired');
- expect(newMakerDraftRouteSource).not.toContain('!selectedWorkingDir');
- expect(newMakerDraftRouteSource).toContain(
- "workspaceKind: workingDir ? 'project' : 'dialogue'",
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
deleted file mode 100644
index 006d637f2d..0000000000
--- a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('effort runtime send guard', () => {
- it('only locks composer mutations during the bounded effort preflight', () => {
- expect(chatInputSource).toContain(
- 'const composerEditorLocked = disabled || sendDispatchInFlight;',
- );
- expect(chatInputSource).toContain(
- 'const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;',
- );
- expect(chatInputSource).toContain('editable: !composerEditorLocked');
- expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
- expect(chatInputSource).toMatch(
- /trigger\.kind !== 'slash'\s*\|\|\s*composerMutationLockedRef\.current/,
- );
- expect(chatInputSource).toContain('if (composerMutationLocked) return;');
- expect(chatInputSource).toContain("id: 'attach-files'");
- expect(chatInputSource).toContain(
- 'disabled: composerMutationLocked,\n run: () => suggestionFileInputRef.current?.click(),',
- );
- expect(chatInputSource).toContain('ref={suggestionFileInputRef}');
- expect(chatInputSource).toContain('disabled={composerMutationLocked}');
- expect(chatInputSource).toContain('setSendDispatchInFlight(true);');
- expect(chatInputSource).toContain('setSendDispatchInFlight(false);');
- expect(chatInputSource).not.toContain('coordinator.markRuntimeDirty(sessionId)');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.ts b/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.ts
deleted file mode 100644
index 901386e4c5..0000000000
--- a/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * FileBodyView selection quote regression tests.
- *
- * Markdown live-preview can replace source ranges with rendered CodeMirror
- * widgets. File quotes must therefore use the editor document selection text,
- * while the DOM selection remains only the ownership / geometry signal.
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const fileBodySource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'workdir-browse', 'FileBodyView.tsx'),
- 'utf8',
-);
-const editorSource = readFileSync(
- resolve(__dirname, '..', 'components', 'markdown', 'PlaintextEditor.tsx'),
- 'utf8',
-);
-const buttonSource = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'SelectionQuoteButton.tsx'),
- 'utf8',
-);
-
-describe('FileBodyView — selection quote source text', () => {
- it('uses the CodeMirror document selection slice for file quote text', () => {
- expect(editorSource).toContain('getSelectionText: () => string | null;');
- expect(editorSource).toContain('return view.state.doc.sliceString(from, to);');
- expect(fileBodySource).toContain('editorRef.current?.getSelectionText()');
- expect(fileBodySource).toContain('getQuoteText={getSelectedSourceText}');
- expect(buttonSource).toContain('const raw = getQuoteText?.() ?? sel.toString();');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts b/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts
deleted file mode 100644
index 1dd38a9fba..0000000000
--- a/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * fileChipCursor.test.ts
- * ---------------------------------------------------------------------------
- * Regression tests for: file-modal-and-toast-polish (2026-04-19) — symptom #2
- *
- * The file-chip on a UserMessage attachment and on the ToolCallCard expanded
- * Read/Edit list must use `cursor-pointer` (a hand). Previously they used
- * `cursor-zoom-in` (a magnifying-glass) which mis-suggested image-preview
- * semantics for plain-text files.
- *
- * Image thumbnails / <img> tags must KEEP `cursor-zoom-in` because they truly
- * are image previews — only the FILE chip's two call-sites flipped.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const userMessage = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'UserMessage.tsx'),
- 'utf8',
-);
-
-const userAttachmentChip = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'UserAttachmentChip.tsx'),
- 'utf8',
-);
-
-const toolCallCard = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'ToolCallCard.tsx'),
- 'utf8',
-);
-
-const agentActionRow = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'AgentActionRow.tsx'),
- 'utf8',
-);
-
-describe('File chip cursor — points, not zooms (symptom #2)', () => {
- it('UserMessage file chip uses cursor-pointer (not cursor-zoom-in)', () => {
- // 附件 chip 的 <button> 现在封装在 UserAttachmentChip 组件里(右键菜单分流
- // 需要 hook,不能内联在 map 里)。从组件定义处起截到它的 </button>,断言 chip
- // class 含 `cursor-pointer` 且未回退 `cursor-zoom-in`。
- // 组件本体在 UserAttachmentChip.tsx(伙伴群聊时间线同样复用),UserMessage 只引用它。
- expect(userMessage).toContain("import { UserAttachmentChip } from './UserAttachmentChip';");
- const chipBlockStart = userAttachmentChip.indexOf('function UserAttachmentChip');
- expect(chipBlockStart).toBeGreaterThan(-1);
- const chipBlockEnd = userAttachmentChip.indexOf('</button>', chipBlockStart);
- const chipBlock = userAttachmentChip.slice(chipBlockStart, chipBlockEnd);
- expect(chipBlock).toMatch(/cursor-pointer/);
- expect(chipBlock).not.toMatch(/cursor-zoom-in/);
- });
-
- it('ToolCallCard preview chip uses cursor-pointer (not cursor-zoom-in)', () => {
- // The ToolCallCard chip is the one that calls `setPreviewPath(abs)` —
- // anchor the slice on that handler so the assertion is robust to other
- // unrelated code in the file.
- const idx = toolCallCard.indexOf('setPreviewPath(abs)');
- expect(idx).toBeGreaterThan(-1);
- const blockEnd = toolCallCard.indexOf('</button>', idx);
- const block = toolCallCard.slice(idx, blockEnd);
- expect(block).toMatch(/cursor-pointer/);
- expect(block).not.toMatch(/cursor-zoom-in/);
- });
-
- it('AgentActionRow file chip on the current compact path uses cursor-pointer', () => {
- const idx = agentActionRow.indexOf('data-agent-action-file-chip="true"');
- expect(idx).toBeGreaterThan(-1);
- const blockEnd = agentActionRow.indexOf('const onRowContextMenu', idx);
- const block = agentActionRow.slice(idx, blockEnd);
- expect(block).toMatch(/cursor-pointer/);
- expect(block).not.toMatch(/cursor-zoom-in/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
deleted file mode 100644
index ba9f725f6a..0000000000
--- a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- resolve(__dirname, '../components/new-chat/HomeUsageDashboard.tsx'),
- 'utf8',
-);
-const dailyBarsSource = readFileSync(
- resolve(__dirname, '../components/new-chat/UsageDailyBars.tsx'),
- 'utf8',
-);
-const heatmapSource = readFileSync(
- resolve(__dirname, '../components/new-chat/UsageHeatmap.tsx'),
- 'utf8',
-);
-const tokenBarsSource = readFileSync(
- resolve(__dirname, '../components/settings/usage/UsageTokenBars.tsx'),
- 'utf8',
-);
-const breakdownTablesSource = readFileSync(
- resolve(__dirname, '../components/settings/usage/UsageBreakdownTables.tsx'),
- 'utf8',
-);
-const usageHistorySectionSource = readFileSync(
- resolve(__dirname, '../components/settings/usage/UsageHistorySection.tsx'),
- 'utf8',
-);
-
-const chartStyles = readFileSync(
- resolve(__dirname, '../components/settings/usage/usageCharts.css'),
- 'utf8',
-);
-
-describe('HomeUsageDashboard source contract', () => {
- it('uses the Claude account daily spend for the visible today amount when available', () => {
- expect(source).toMatch(
- /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend, claudeQuota\.currency\)\s+: null;/,
- );
- expect(source).toContain('const hasAccountTodaySpend = accountTodayMoney !== null;');
- expect(source).toContain('const layoutHistory = history ?? emptyLayoutHistory;');
- expect(source).toContain(
- 'const displayTodaySpend = accountTodayMoney ?? layoutHistory.totals.today;',
- );
- expect(source).toContain('const ACCOUNT_LOCAL_TODAY_MATCH_EPSILON = 0.01;');
- expect(source).toMatch(
- /function isSameDisplayedTodaySpend\(\s+accountTodaySpend: RegionalMoney \| null,\s+localTodaySpend: RegionalMoney,\s+\): boolean/,
- );
- expect(source).toMatch(
- /layoutHistory\.anomaly\.isAnomalous &&\s+isSameDisplayedTodaySpend\(accountTodayMoney, layoutHistory\.totals\.today\);/,
- );
- expect(source).toContain(
- '`${formatMoney(displayTodaySpend)} / ${formatCompactMoney(softDailyLimitMoney)}`',
- );
- expect(source).toMatch(
- /hasSpendValue \?\s+formatMoney\(displayTodaySpend\)\s+:\s+UNKNOWN_VALUE/,
- );
- expect(source).toContain('warning={showLocalSpendAnomaly}');
- });
-
- it('keeps a fixed empty layout while usage history is still loading or empty', () => {
- expect(source).toContain('function createEmptyUsageHistoryPayload(): UsageHistoryPayload');
- expect(source).toMatch(
- /const \[emptyLayoutHistory\] = useState<UsageHistoryPayload>\(\(\) =>\s+createEmptyUsageHistoryPayload\(\),\s+\);/,
- );
- expect(source).toContain('const hasHistoryData = history !== null;');
- expect(source).toContain('const tokenValue =');
- expect(source).toContain('`${UNKNOWN_VALUE} / ${UNKNOWN_VALUE}`');
- expect(source).toMatch(
- /const streakValue = hasHistoryData\s+\? t\('usageDashboard\.streakValue', \{\s+current: layoutHistory\.streak\.current,\s+longest: layoutHistory\.streak\.longest,\s+\}\)\s+: `\$\{UNKNOWN_VALUE\} \/ \$\{UNKNOWN_VALUE\}`;/,
- );
- expect(source).toMatch(
- /hasHistoryData\s+\? t\('usageDashboard\.collapsedStreak', \{ n: layoutHistory\.streak\.current \}\)\s+: UNKNOWN_VALUE/,
- );
- expect(source).not.toContain('return null;');
- expect(source).not.toContain('history.days.length === 0 && history.models.length === 0');
- });
-
- it('uses the default usage currency for empty chart cells', () => {
- expect(heatmapSource).toContain('DEFAULT_USAGE_CURRENCY');
- expect(dailyBarsSource).toContain('DEFAULT_USAGE_CURRENCY');
- expect(heatmapSource).not.toContain("money.currency ?? 'USD'");
- expect(dailyBarsSource).not.toContain("money.currency ?? 'USD'");
- });
-
- it('keeps selected usage chart days flat without ad-hoc shadows', () => {
- expect(heatmapSource).not.toContain('boxShadow');
- expect(tokenBarsSource).not.toContain('boxShadow');
- expect(heatmapSource).toContain('usage-chart-indicator');
- expect(tokenBarsSource).toContain('usage-chart-indicator');
- expect(chartStyles).toContain('outline: 2px solid var(--focus-ring)');
- expect(chartStyles).toContain('prefers-reduced-motion: reduce');
- expect(chartStyles).toContain('transition: none');
- });
-
- // The owner removed the added date form. This verifies the retained chart
- // entry points and geometry, not WCAG target-size conformance; the unresolved
- // target-size requirement remains documented in usage-history-charts.md.
- it('keeps dense chart geometry and the two retained date-selection entry points', () => {
- expect(heatmapSource).not.toContain('INTERACTIVE_CELL_PX');
- expect(heatmapSource).toContain('const cellSize = CELL_PX;');
- expect(heatmapSource).toContain('data-usage-mark="usage-heatmap-day"');
- expect(tokenBarsSource).toContain('const hitHeight = Math.max(24, visualHeight);');
- expect(tokenBarsSource).toContain('data-usage-mark="usage-token-bar"');
- expect(tokenBarsSource).not.toContain('minWidth: bars.list.length * 24');
- expect(tokenBarsSource).not.toContain('minWidth: 24');
- expect(tokenBarsSource).not.toContain('overflow-x-auto');
- expect(usageHistorySectionSource.match(/onDayClick=\{handleDayClick\}/g)).toHaveLength(2);
- expect(usageHistorySectionSource).not.toContain('UsageDateFilter');
- });
-
- it('keeps the home heatmap non-interactive when no day callback is supplied', () => {
- expect(heatmapSource).not.toContain('disabled={!onDayClick}');
- expect(heatmapSource).toContain('return onDayClick ? (');
- });
-
- it('uses the shared model key rank for chart and filtered model-table colors', () => {
- expect(usageHistorySectionSource).toContain('colorOrder={colorOrder}');
- expect(breakdownTablesSource).toContain('usageRankOf(colorOrder, row.key)');
- expect(breakdownTablesSource).toContain('colorOrder: string[];');
- });
-
- it('shows cached usage immediately while marking background refresh', () => {
- expect(source).toContain(
- 'const { history, refreshing: usageRefreshing } = useUsageHistory({ paused: collapsed, userId: user?.id });',
- );
- expect(source).toContain('const { user } = useAuth();');
- expect(source).toContain('const layoutHistory = history ?? emptyLayoutHistory;');
- expect(source).toContain("t('usageDashboard.updating')");
- });
-
- it('shows token model distribution in the token stat tooltip', () => {
- expect(source).toContain('const TOKEN_DISTRIBUTION_TOP_MODELS = 5;');
- expect(source).toContain('const tokenDistributionRows =');
- expect(source).toContain("t('usageDashboard.tokenDistributionTitle'");
- expect(source).toContain("t('usageDashboard.tokenDistributionRow'");
- expect(source).toContain('warningTip={tokenDistributionTip}');
- });
-
- it('loads once while collapsed but skips usage push subscriptions', () => {
- expect(source).toContain('useUsageHistory({ paused: collapsed, userId: user?.id })');
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- const loadIndex = hookSource.indexOf('void load(scopeKey);');
- const pausedIndex = hookSource.indexOf('if (paused) {');
- const pushIndex = hookSource.indexOf('window.electronAPI.maker.usage.onTodaySpendChanged');
- const tokenPushIndex = hookSource.indexOf(
- 'window.electronAPI.maker.usage.onTodayTokensChanged',
- );
- expect(loadIndex).toBeGreaterThan(0);
- expect(pausedIndex).toBeGreaterThan(0);
- expect(loadIndex).toBeLessThan(pausedIndex);
- expect(pushIndex).toBeGreaterThan(pausedIndex);
- expect(tokenPushIndex).toBeGreaterThan(pausedIndex);
- });
-
- it('scopes renderer usage-history snapshots by account', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain('function storageKeyForScope(scopeKey: string): string');
- expect(hookSource).toContain('localStorage.getItem(storageKeyForScope(scopeKey))');
- expect(hookSource).toContain(
- 'localStorage.setItem(storageKeyForScope(scopeKey), JSON.stringify(p))',
- );
- expect(hookSource).toContain('const scopes = new Map<string, UsageHistoryScopeState>();');
- expect(hookSource).toContain('const scopeKey = normalizeScopeKey(opts?.userId);');
- });
-
- it('does not render the previous account history after the scope changes', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain(
- 'const [historyState, setHistoryState] = useState<{ scopeKey: string; value: UsageHistoryPayload | null }>',
- );
- expect(hookSource).toContain('setHistoryState({ scopeKey: scopedKey, value });');
- expect(hookSource).toContain(
- 'const history = historyState.scopeKey === scopedKey ? historyState.value : scope.cache;',
- );
- });
-
- it('adds subscription estimates to mixed actual daily bars', () => {
- expect(dailyBarsSource).toContain('const subscriptionEstimateSum = segments.reduce(');
- expect(dailyBarsSource).toContain('actualAmount + subscriptionEstimateSum,');
- expect(dailyBarsSource).toContain(
- 'segments.some((segment) => segment.subscriptionEstimateAmount > 0)',
- );
- expect(dailyBarsSource).toContain("money(subscriptionEstimateSum, true, 'value-estimate')");
- });
-
- it('force-refreshes delayed pricing retries instead of reusing pending memory cache', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain('scope.pricingRetryTimer = setTimeout(() => {');
- expect(hookSource).toContain('void load(scopeKey, { forceRefresh: true });');
- expect(hookSource).not.toContain('setTimeout(() => void load(), PRICING_RETRY_DELAY_MS);');
- });
-
- it('cancels delayed retries when a usage scope is no longer active', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain('pricingRetryTimer: ReturnType<typeof setTimeout> | null;');
- expect(hookSource).toContain(
- 'function deactivateScopeIfUnused(scope: UsageHistoryScopeState): void',
- );
- expect(hookSource).toContain('cancelScopeTimers(scope);');
- expect(hookSource).toContain('scope.loadSeq += 1;');
- expect(hookSource).toContain('deactivateScopeIfUnused(activeScope);');
- expect(hookSource).toContain(
- 'if (scope.listeners.size === 0 && scope.statusListeners.size === 0) return;',
- );
- });
-
- it('resets the pricing retry gate after successful loads and usage-push refreshes', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain('opts?: { forceRefresh?: boolean; resetPricingRetry?: boolean }');
- expect(hookSource).toContain('if (opts?.resetPricingRetry) scope.pricingRetryDone = false;');
- expect(hookSource).toContain('scope.pricingRetryDone = false;');
- expect(hookSource).toContain(
- 'void load(scopedKey, { forceRefresh: true, resetPricingRetry: true });',
- );
- });
-
- it('does not retry forever for permanent Codex null estimates', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(hookSource).toContain('if (next.estimatesPending) {');
- expect(hookSource).not.toContain(
- "next.models.some((m) => m.agentKind === 'codex' && m.estimatedCostUsd === null)",
- );
- });
-
- it('lets the token-only settings page consume pending estimates without changing the home gate', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- const settingsSource = readFileSync(
- resolve(__dirname, '../components/settings/usage/UsageHistorySection.tsx'),
- 'utf8',
- );
- expect(settingsSource).toContain('allowPendingEstimates: true');
- expect(hookSource).toContain('allowPendingEstimates?: boolean;');
- expect(hookSource).toContain('if (!scope.request.allowPendingEstimates) return scope.cache;');
- });
-
- it('keeps the settings usage loading state separate from a loaded empty payload', () => {
- const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');
- expect(usageHistorySectionSource).toContain('const loading = history === null && refreshing;');
- expect(usageHistorySectionSource).toContain(
- 'const loadFailed = history === null && !refreshing;',
- );
- expect(usageHistorySectionSource).toContain(
- 'const empty = history !== null && isUsageHistoryEmpty(history);',
- );
- expect(usageHistorySectionSource).toContain("t('usageHistory.loadFailed')");
- expect(hookSource).toContain('useState(scope.cache === null || scope.refreshing)');
- expect(hookSource.indexOf('void load(scopedKey);')).toBeLessThan(
- hookSource.indexOf('setIsRefreshing(activeScope.refreshing);'),
- );
- expect(hookSource).toContain(
- 'historyState.scopeKey === scopedKey ? isRefreshing : scope.cache === null || scope.refreshing;',
- );
- });
-
- it('keeps interactive usage controls discoverable and semantically selected', () => {
- expect(usageHistorySectionSource).toContain(
- 'data-[state=checked]:bg-[var(--settings-menu-bg-selected)]',
- );
- expect(usageHistorySectionSource).toContain(
- 'data-[state=checked]:text-[var(--settings-menu-text-selected)]',
- );
- expect(heatmapSource).toContain('const accessibleLabel =');
- expect(heatmapSource).toContain('aria-label={accessibleLabel}');
- expect(tokenBarsSource).toContain('function parseDayKeyLocal(dayKey: string): Date');
- expect(tokenBarsSource).toContain(
- 'aria-label={`${dateFormatter.format(parseDayKeyLocal(b.day))}',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/hookSourceAttachments.test.ts b/apps/desktop/src/renderer/__tests__/hookSourceAttachments.test.ts
deleted file mode 100644
index 88ddbb8009..0000000000
--- a/apps/desktop/src/renderer/__tests__/hookSourceAttachments.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const userMessageSource = fs.readFileSync(
- path.resolve(__dirname, '../components/chat/UserMessage.tsx'),
- 'utf8',
-);
-
-describe('Cindy hook source attachments', () => {
- it('places the shared attachment nodes in both the hook and ordinary message branches', () => {
- const hookBranch = userMessageSource.indexOf(') : hookSource && !editing ? (');
- expect(hookBranch).toBeGreaterThan(0);
- const ordinaryBranch = userMessageSource.indexOf(') : (', hookBranch + 1);
- const hookImages = userMessageSource.indexOf('{imageAttachmentNodes}', hookBranch);
- const hookFiles = userMessageSource.indexOf('{fileAttachmentNodes}', hookImages);
- const ordinaryImages = userMessageSource.indexOf('{imageAttachmentNodes}', ordinaryBranch);
- const ordinaryFiles = userMessageSource.indexOf('{fileAttachmentNodes}', ordinaryImages);
-
- expect(hookImages).toBeGreaterThan(hookBranch);
- expect(hookFiles).toBeGreaterThan(hookImages);
- expect(ordinaryImages).toBeGreaterThan(ordinaryBranch);
- expect(ordinaryFiles).toBeGreaterThan(ordinaryImages);
- });
-
- it('keeps a single shared file renderer so hook cards cannot silently hide attachments', () => {
- expect(userMessageSource.match(/files\.map\(\(f, idx\) =>/g)).toHaveLength(1);
- expect(userMessageSource.match(/\{fileAttachmentNodes\}/g)).toHaveLength(2);
- });
-
- it('shares the existing action bar with clean IM content and keeps the edit box reachable', () => {
- const hookBranch = userMessageSource.indexOf(') : hookSource && !editing ? (');
- const ordinaryBranch = userMessageSource.indexOf(') : (', hookBranch + 1);
- const hookBody = userMessageSource.slice(hookBranch, ordinaryBranch);
- expect(userMessageSource.match(/<MessageActionBar\b/g)).toHaveLength(1);
- expect(hookBody).toContain('{!hasEmbeddedImPrompt(hookSource) && messageActions}');
- expect(userMessageSource.slice(ordinaryBranch)).toContain('{messageActions}');
- expect(userMessageSource.slice(ordinaryBranch)).toContain('<UserMessageEditBox');
- expect(userMessageSource).toContain('onEdit={canEdit ? handleEdit : undefined}');
- expect(userMessageSource).toContain('onRewind={!isBlocked && canRewind ? handleRewind : undefined}');
- expect(userMessageSource).toContain('onFork={!isBlocked && canFork ? handleFork : undefined}');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts b/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts
deleted file mode 100644
index 0f2467a8ca..0000000000
--- a/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * imageLightboxCloseAnywhere.test.ts
- * ---------------------------------------------------------------------------
- * 回归测试:lightbox 关闭契约(image-lightbox-zoom 起变更)。
- *
- * 历史契约演进:
- * v1 旧症状:<img> onClick stopPropagation,点图片关不掉,只有背景能关。
- * v2(lightbox-close-on-any-click):全域关闭,点图片也关。
- * v3(当前,image-lightbox-zoom):点**背景**关闭;点图片本身不关——单击
- * 必须让位给双击缩放(单击立即关闭会让 dblclick 永远无法触发)与标注
- * 画笔,这也是主流图片查看器的行为。标注模式中背景点击也不关(防误触
- * 丢笔迹,放弃走 X / Esc)。
- *
- * 沿用项目静态源码扫描约定(见 userInfoSectionHover.test.ts),让测试跑在
- * Node vitest 环境,避免为行为契约引入 jsdom + react-dom。
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sourcePath = resolve(
- __dirname,
- '..',
- 'components',
- 'chat',
- 'ImageLightbox.tsx',
-);
-const source = readFileSync(sourcePath, 'utf8');
-const sourceWithoutBlockComments = source.replace(/\/\*[\s\S]*?\*\//g, '');
-
-describe('ImageLightbox — backdrop click closes, image click does not', () => {
- it('overlay <div> click handler still calls handleClose (backdrop click closes)', () => {
- // overlay 容器保留关闭入口。
- expect(sourceWithoutBlockComments).toMatch(
- /onClick=\{\(e\)\s*=>\s*\{[\s\S]*?handleClose\(\);[\s\S]*?\}\}/,
- );
- });
-
- it('overlay onClick gates on e.target !== e.currentTarget (image click must NOT close)', () => {
- // 决断(v3):仅背景关闭。点图片不关——单击关闭会吞掉双击缩放。
- expect(source).toMatch(/e\.target\s*!==\s*e\.currentTarget/);
- });
-
- it('overlay onClick bails out while annotating (stroke loss guard)', () => {
- // 标注模式中误点背景不能丢笔迹;放弃走 X / Esc。
- expect(sourceWithoutBlockComments).toMatch(/if\s*\(isAnnotating\)\s*return;/);
- });
-});
-
-describe('ImageLightbox — <img> stays click-transparent', () => {
- it('gives viewBox-only SVGs an explicit fitted box after load', () => {
- expect(source).toContain('containImageSize(');
- expect(source).toContain('width: fittedImageSize?.width');
- expect(source).toContain('height: fittedImageSize?.height');
- });
-
- it('does not reuse the previous gallery image dimensions before the new source loads', () => {
- expect(source).toContain('naturalSize?.src === currentSrc');
- expect(source).toMatch(/setNaturalSize\(\{[\s\S]*?src:\s*currentSrc,/);
- });
-
- it('image element does NOT register its own onClick', () => {
- // 用 ref={imgRef} 锚定真正的 JSX 标签,避免匹配到行注释里的 "<img>" 字样。
- const imageElement =
- sourceWithoutBlockComments.match(/<img\s+ref=\{imgRef\}[\s\S]*?\/>/)?.[0] ?? '';
- expect(imageElement).not.toBe('');
- expect(imageElement).toContain('src={currentSrc}');
- expect(imageElement).not.toMatch(/\bonClick\s*=/);
- });
-
- it('image element still has onError={handleClose-via-toast} for missing file', () => {
- // image-local-cache F4 契约:缺失文件时关闭 lightbox 并提示用户。
- expect(source).toMatch(/onError=\{\(\)\s*=>\s*\{/);
- expect(source).toContain("toast.warning(t('chat.media.imageMissing'))");
- expect(source).toMatch(/handleClose\(\)/);
- });
-});
-
-describe('ImageLightbox — handleClose stays idempotent', () => {
- it('handleClose guards against double-fire via isClosingRef', () => {
- expect(source).toContain('isClosingRef.current');
- expect(source).toMatch(/if\s*\(isClosingRef\.current\)\s*return;/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts b/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
index 1a56d70ee5..a211ceb370 100644
--- a/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
@@ -6,8 +6,7 @@ import '../themes/colors';
* Regression tests for: markdown ```diff fenced code blocks now render via
* MarkdownDiffBlock (GitHub-standard red/green) instead of highlight.js.
*
- * Static-source scan, matching project convention (see
- * imageLightboxCloseAnywhere.test.ts and userInfoSectionHover.test.ts) —
+ * Static-source scan for the small structural/token contract —
* keeps tests in the node vitest env and avoids dragging in jsdom +
* react-dom for what are essentially structural / token contracts.
*
diff --git a/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.ts b/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.ts
deleted file mode 100644
index adfadbba28..0000000000
--- a/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * markdownRendererXdtAudio.test.ts
- * ---------------------------------------------------------------------------
- * Source-contract regression test for chat-audio-inline-playback.
- *
- * `MarkdownRenderer.tsx` has two cooperating edits that together make
- * `xdt-audio://` markdown links render as inline `<audio>` players in
- * the chat bubble. Either edit alone is silently broken: removing the
- * urlTransform allowlist makes react-markdown's defaultUrlTransform
- * sanitize the href to "" (audio loses src, controls show as broken);
- * removing the `<a>` audio branch reverts to a plain link that opens
- * the file externally via openExternal. Both regressions would pass
- * normal unit tests because the renderer is harness-mounted with React
- * and we don't have a JSDom snapshot. This test grep-anchors the source
- * so the contract can't drift unnoticed.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sourcePath = resolve(
- __dirname,
- '..',
- 'components',
- 'chat',
- 'MarkdownRenderer.tsx',
-);
-const source = readFileSync(sourcePath, 'utf8');
-
-// ── 改动 1: urlTransform 白名单透传 xdt-audio:// ─────────────────────────
-
-describe('MarkdownRenderer — urlTransform allows xdt-audio://', () => {
- it("urlTransform whitelists 'xdt-audio://' (else react-markdown sanitizes href to empty)", () => {
- expect(source).toContain("url.startsWith('xdt-audio://')");
- });
-});
-
-// ── 改动 2: <a> 渲染分支识别 xdt-audio:// → <audio controls> ─────────────
-
-describe('MarkdownRenderer — <a> renderer routes xdt-audio:// to <audio>', () => {
- const linkComponentMatch = source.match(
- /function MarkdownTargetLink\([\s\S]*?function InlineCodeWithTarget/,
- );
-
- it('routes audio through the unified markdown target classifier', () => {
- expect(linkComponentMatch).not.toBeNull();
- const branch = linkComponentMatch![0];
- expect(branch).toContain("target.kind === 'audio'");
- // device-link 入方向:远程会话把 xdt-audio:// 改写到 cindy-remote-media://(本地会话 no-op)。
- expect(branch).toContain('<InlineXdtAudioPlayer src={rewriteToRemoteMediaOrigin(target.href, remoteMediaOrigin)} />');
- });
-
- it('renders <audio controls> with preload="metadata" controlsList="nodownload" src={href}', () => {
- const playerMatch = source.match(/function InlineXdtAudioPlayer[\s\S]*?function LightboxImage/);
- expect(playerMatch).not.toBeNull();
- const player = playerMatch![0];
- expect(player).toContain('<audio');
- expect(player).toContain('controls');
- expect(player).toContain('preload="metadata"');
- expect(player).toContain('controlsList="nodownload"');
- expect(player).toContain('src={src}');
- });
-
- it('does NOT set autoplay / loop (avoid surprise sound, chromium blocks audio autoplay anyway)', () => {
- const playerMatch = source.match(/function InlineXdtAudioPlayer[\s\S]*?function LightboxImage/);
- expect(playerMatch).not.toBeNull();
- const player = playerMatch![0];
- expect(player).not.toContain('autoplay');
- expect(player).not.toContain('loop');
- });
-
- it('does NOT set a React key (mdast node identity stabilises children; key={href} would warn on legitimate URL repeats)', () => {
- const playerMatch = source.match(/function InlineXdtAudioPlayer[\s\S]*?function LightboxImage/);
- expect(playerMatch).not.toBeNull();
- const player = playerMatch![0];
- expect(player).not.toMatch(/\bkey=/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/modelLightbox.test.ts b/apps/desktop/src/renderer/__tests__/modelLightbox.test.ts
deleted file mode 100644
index e281218948..0000000000
--- a/apps/desktop/src/renderer/__tests__/modelLightbox.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const source = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'ModelLightbox.tsx'),
- 'utf8',
-);
-
-describe('ModelLightbox', () => {
- it('keeps close callback stable so model ensure does not restart on parent rerender', () => {
- expect(source).toContain('const onCloseRef = useRef(onClose)');
- const handleCloseMatch = source.match(/const handleClose = useCallback\(\(\) => \{([\s\S]*?)\n {2}\}, \[(.*?)\]\);/);
- expect(handleCloseMatch).not.toBeNull();
- if (!handleCloseMatch) throw new Error('handleClose useCallback block not found');
- expect(handleCloseMatch[1]).toContain('onCloseRef.current()');
- expect(handleCloseMatch[1]).not.toContain('onClose(');
- // Esc 关闭前必须先 blur 掉焦点 —— 否则 model-viewer shadow DOM 的
- // .userInput 会在淡出期间闪出键盘焦点框(全局 outline:none 穿不进 shadow)。
- expect(handleCloseMatch[1]).toContain('.blur?.()');
- expect(handleCloseMatch[2].trim()).toBe('');
- // mivo 懒下载来源已随老 MCP 摘壳退役,模型 ensure 效果的依赖只剩稳定的
- // handleClose——断言跟着源码走,守的仍是"父级重渲不重启加载"这条约。
- expect(source).toContain('}, [handleClose]);');
- });
-
- it('surfaces model load failure instead of silently staying on the poster', () => {
- // <model-viewer> only dispatches an 'error' event on load/parse failure
- // and keeps showing the poster — without this listener the lightbox looks
- // like a frozen 2D image (the exact symptom of the 2026-06 scheme
- // privilege regression). Contract: listener registered + user-visible
- // toast with the modelLoadFailed copy.
- expect(source).toContain("addEventListener('error'");
- expect(source).toContain('chat.media.modelLoadFailed');
- });
-
- it('has no in-app FBX rendering path', () => {
- // FBX 预览已被有意移除(model-viewer 只认 glTF;three.js 自渲 Phong 观感
- // 与 GLB 差异大反而误导),.fbx chip 走 Finder 定位。契约:不许再把
- // three / FbxModelViewer 引回本组件(那是第二份 three 实例)。
- expect(source).not.toContain('FbxModelViewer');
- expect(source).not.toMatch(/from 'three/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts
deleted file mode 100644
index a67c8d9969..0000000000
--- a/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const modelSelectorSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ModelSelector.tsx'),
- 'utf8',
-);
-
-describe('ModelSelector paid model navigation', () => {
- it('writes the billing deep link to the hash-router location', () => {
- const start = modelSelectorSource.indexOf('const showPaymentRequired = () => {');
- expect(start).toBeGreaterThanOrEqual(0);
-
- const end = modelSelectorSource.indexOf('// ── 单个模型行', start);
- expect(end).toBeGreaterThan(start);
-
- const paymentRequiredBlock = modelSelectorSource.slice(start, end);
- expect(paymentRequiredBlock).toContain(
- "window.location.hash = '#/settings?tab=billing';",
- );
- expect(paymentRequiredBlock).not.toContain('window.history');
- });
-
- it('keeps the payment explanation action enabled for assistive technology', () => {
- const start = modelSelectorSource.indexOf('const renderModelItem =');
- const end = modelSelectorSource.indexOf('const emptyState =', start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
-
- const modelRowBlock = modelSelectorSource.slice(start, end);
- expect(modelRowBlock).toContain('aria-disabled={disabled ? true : undefined}');
- expect(modelRowBlock).toContain(
- "`${localizedModelName(model.displayName, t)} · ${t('newChat.modelSelector.paymentRequired.unlock')}`",
- );
- expect(modelRowBlock).not.toContain('aria-disabled={disabled || paymentRequired}');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
deleted file mode 100644
index 5d65818f94..0000000000
--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
+++ /dev/null
@@ -1,485 +0,0 @@
-import { colorRegistry } from '../themes/color-registry';
-import '../themes/colors';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'NewMakerDraftRoute.tsx'),
- 'utf8',
-);
-const brandLockupSource = readFileSync(
- resolve(__dirname, '..', 'components', 'branding', 'ThemeBrandLockup.tsx'),
- 'utf8',
-);
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-);
-const sendButtonSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'SendButton.tsx'),
- 'utf8',
-);
-const vendorSwitcherSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'VendorSegmentedSwitcher.tsx'),
- 'utf8',
-);
-const agentSelectSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'AgentSelect.tsx'),
- 'utf8',
-);
-const permissionSelectorSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'PermissionSelector.tsx'),
- 'utf8',
-);
-const modelSelectorSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ModelSelector.tsx'),
- 'utf8',
-);
-const worktreeChipsRowSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'WorktreeChipsRow.tsx'),
- 'utf8',
-);
-const userInfoSectionSource = readFileSync(
- resolve(__dirname, '..', 'components', 'sidebar', 'UserInfoSection.tsx'),
- 'utf8',
-);
-const sidebarTopNavSource = readFileSync(
- resolve(__dirname, '..', 'components', 'sidebar', 'SidebarTopNav.tsx'),
- 'utf8',
-);
-const vendorIconSource = readFileSync(
- resolve(__dirname, '..', 'components', 'sidebar', 'VendorIcon.tsx'),
- 'utf8',
-);
-const extraDirsButtonSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ExtraDirsButton.tsx'),
- 'utf8',
-);
-const colorsSource = readFileSync(resolve(__dirname, '..', 'themes', 'colors.ts'), 'utf8');
-const globalsSource = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');
-
-describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
- it('keeps the approved CREATE AGENT shell while preserving the functional composer', () => {
- expect(source).toContain('data-testid="create-agent-shell"');
- expect(source).toContain('data-testid="create-agent-main"');
- expect(source).toContain('data-testid="create-agent-mode-pill"');
- expect(source).toContain('testId="create-agent-brand-lockup"');
- expect(source).toContain('<HomeSuggestionList');
- expect(source).toContain('<ChatInput');
- // A 默认包含引擎选择;仅在老被控端缺供应商目录时恢复独立引擎下拉。
- expect(source).not.toContain('<VendorSegmentedSwitcher');
- expect(source).toContain('unifiedModelPanelActive ? undefined : (');
- expect(source).toMatch(/middleToolbarSlot=\{\s*\n\s*unifiedModelPanelActive \? undefined : \(/);
- expect(source).toMatch(
- /compactMiddleToolbarSlot=\{\s*\n\s*unifiedModelPanelActive \? undefined : \(/,
- );
- // 新旧用户只按能力启用,不读取历史样式偏好。
- expect(source).toMatch(/const unifiedModelPanelActive = unifiedModelPanelEnabled;/);
- expect(source).not.toContain('<HomeUsageDashboard');
- expect(source).not.toContain('newChat.createAgent.more');
- expect(source).not.toContain('data-testid="create-agent-sidebar"');
- expect(source).not.toContain('<aside');
- expect(source).not.toContain('createAgentSidebarNav');
- expect(source).not.toContain('createAgentSidebarProjects');
- // 2026-07-19 用户裁决:488cb33 对齐 Figma 时误删 branch/worktree 高级入口
- // (功能回归,wt* 状态与 send 管线一直健在)。恢复为 advancedOnly 变体挂在
- // mode pill 右侧;2026-07-28 用户裁决把 worktree 开关从齿轮 popover 提为
- // 一级勾选 chip(齿轮删除),仍不回退到旧 folder chip 布局。
- expect(source).toContain('variant="advancedOnly"');
- expect(source).toMatch(/<WorktreeChipsRow[\s\S]*?variant="advancedOnly"/);
- expect(source).not.toContain('h-2.5 w-2.5 rounded-full');
- expect(source).not.toContain('surface-translucent-sidebar');
- expect(source).not.toContain('agent-island-annie');
- expect(source).toContain('<ThemeBrandLockup');
- expect(brandLockupSource).toContain('head-image-dark.png');
- });
-
- it('centers the CREATE AGENT content group without reintroducing route chrome', () => {
- expect(source).toContain('items-center justify-start');
- const shellBlock = source.slice(
- source.indexOf('data-testid="create-agent-shell"'),
- source.indexOf('data-testid="create-agent-main"'),
- );
- expect(shellBlock).toContain('overflow-x-hidden overflow-y-auto');
- expect(shellBlock).not.toContain('overflow-hidden');
- // 用户改稿 2026-07-21:摘掉 268px 封顶(Figma 定稿画框高度的遗留),大窗口下顶距随 28vh
- // 等比增长,内容组不再"偏高";96px 下限保留,小窗口行为不变。比例为可调参数。
- // 用户改稿 2026-07-21 二连:①摘 268px 封顶(顶距随 28vh 等比);②叠加 --content-header-h
- // 占位补偿——内容组距窗口顶恒为 max(96px,28vh)+46px(="有顶栏时"位置),顶栏显隐零跳动。
- // 比例调参:25.5%→28%(用户实机拍板 2026-07-21)。
- expect(source).toContain('pt-[calc(max(96px,28vh)_+_46px_-_var(--content-header-h,46px))]');
- expect(source).not.toContain('pt-[clamp(96px,25.5vh,268px)]');
- expect(source).not.toContain('10vh');
- // 内容列宽度从死锁 800px 改为跟随 useProportionalWidth 的 inputWidth(与进行中
- // 对话页同源,封顶 914+20=934px):大屏留出左右呼吸空间、发送后同一 ChatInput 无宽度跳变。
- expect(source).toContain('relative flex w-full flex-col items-start');
- expect(source).toContain('style={{ maxWidth: inputWidth }}');
- expect(source).toContain('responsiveBreakpoints: DRAFT_INPUT_WIDTH_BREAKPOINTS');
- expect(source).not.toContain('max-w-[800px]');
- expect(source).toContain('absolute right-0 top-[22px]');
- // 快捷入口与输入框同宽(w-full 跟随父列 inputWidth),左右两缘对齐 ChatInput;
- // 旧 800px 封顶在宽窗口下右缘短一截,2026-07-24 用户反馈后摘除。
- expect(source).toMatch(
- /<HomeSuggestionList[\s\S]*?narrow=\{isDraftNarrow\}[\s\S]*?onSelect=\{handleHomeSuggestion\}[\s\S]*?onPluginSelect=\{handlePluginSuggestion\}/,
- );
- expect(source).toContain('<HomeZeroModelAction');
- expect(source).not.toContain('ConnectProviderCard');
- expect(source).not.toMatch(/data-testid="create-agent-quick-starts"/);
- expect(source).not.toContain('mt-[42px]');
- });
-
- it('preserves New Maker behavior-critical props on ChatInput', () => {
- const chatInputIndex = source.indexOf('<ChatInput');
- expect(chatInputIndex).toBeGreaterThan(-1);
- const chatInputBlock = source.slice(
- chatInputIndex,
- source.indexOf('<NewGoalDialog', chatInputIndex),
- );
-
- for (const invariant of [
- 'onSend={handleSend}',
- 'onBeforeVoiceInputStart={handleBeforeVoiceInputStart}',
- 'externalDragOver={pageDragOver}',
- 'sessionId={undefined}',
- 'initialWorkingDir={effectiveWorkingDir}',
- 'remoteHostId={draft.remoteHostId ?? null}',
- 'deviceLinkDeviceId={effectiveDeviceLinkDeviceId ?? null}',
- 'modelMemoryOverride={deviceLinkDraftMemory}',
- 'initialModel={draftInitialModel}',
- 'initialEffort={draftInitialEffort}',
- 'initialPermissionMode={chatInitialPermissionMode}',
- 'initialProviderId={chatInitialProviderId}',
- 'planModeEnabled={effectivePlanMode}',
- 'fastMode={effectiveFastMode}',
- 'onWorkingDirChange={handleWorkingDirChange}',
- 'onModelDidChange={handleModelDidChange}',
- 'onEffortDidChange={handleEffortDidChange}',
- 'onPermissionModeDidChange={handlePermissionModeDidChange}',
- 'onProviderDidChange={handleProviderDidChange}',
- 'vendorKey={normalizeDbAgentKind(draft.vendor)}',
- // #807 第二十二轮:仍然由调用方显式持有(ChatInput 不 fallback 内部一份),但远程草稿下
- // 包了一层闸门 —— 拒绝路径型附件,因为那是控制端绝对路径,发到对端读不到或读到无关文件。
- 'attachmentState={attachmentState}',
- 'draftKey={NEW_MAKER_DRAFT_KEY}',
- 'extraDirs={effectiveExtraDirs}',
- // #807 第二十二轮**刻意收窄**原来「+ 始终能加引用目录」这条:远程草稿不下传 onChange,
- // ExtraDirsButton 据此不渲染引用目录段。原因是它开的是控制端原生目录对话框,选出的本机
- // 路径发到对端会被 validateExtraDirs 静默丢掉、或撞上对端同名的无关目录 —— chip 显示的
- // 并非真实授予的上下文。本机草稿行为不变;把 picker 路由到对端后恢复,见 issue #1012。
- 'onExtraDirsChange={isDeviceLinkDraft ? undefined : handleExtraDirsChange}',
- 'onNewGoal={(text) =>',
- 'rememberedEffortByModel={usesDeviceCatalog ? undefined : draft.effortByModel}',
- 'onRememberedEffortChange={',
- 'usesDeviceCatalog ? undefined : handleRememberedEffortChange',
- "placeholder={t('newChat.chatInput.createAgentPlaceholder')}",
- // 统一模型选择器(M5):新会话的选中直通 + 收藏锚点选中态。撤掉 AgentSelect 后,
- // 「换引擎」这件事只剩这一条路径 —— 掉了它草稿就再也换不了引擎。
- 'onUnifiedDraftSelect={handleUnifiedDraftSelect}',
- 'selectedFavoriteUid={selectedFavoriteUid}',
- ]) {
- expect(chatInputBlock).toContain(invariant);
- }
- });
-
- it('uses home suggestion rows instead of the old four quick-start cards', () => {
- expect(source).toContain('<HomeSuggestionList');
- expect(source).not.toContain('SearchCode');
- expect(source).not.toContain('MessageSquareCode');
- expect(source).not.toContain('createAgentQuickStarts');
- expect(source).not.toContain('shadow-[');
- expect(source).not.toContain('boxShadow');
- });
-
- it('fills suggestions into the home composer instead of sending them', () => {
- const suggestionBlock = source.slice(
- source.indexOf('const [suggestionPreview, setSuggestionPreview]'),
- source.indexOf('// 注意:不要给 ChatInput 加 key 强制 remount'),
- );
-
- expect(suggestionBlock).toContain('saveComposerDraft(NEW_MAKER_DRAFT_KEY, {');
- expect(suggestionBlock).toContain('text: plainTextToTiptapDoc(prompt)');
- expect(suggestionBlock).not.toContain('handleSend(');
- // 悬停预览只走 ChatInput 的只读 overlay,不写草稿。
- expect(source).toContain('previewPrompt={suggestionPreview}');
- expect(source).toContain('onPreviewChange={handleSuggestionPreview}');
- // 视觉预览与读屏描述共用同一个显示投影(收起同名限定符),点击填入仍用带限定符的文字。
- expect(source).toContain('composerTextFor={suggestionDescriptionText}');
- expect(suggestionBlock).toContain(
- 'setSuggestionPreview(suggestion ? suggestionDisplayText(suggestion, false) : null)',
- );
- expect(suggestionBlock).toContain(
- 'fillComposerWithSuggestion(pluginSuggestionComposerText(suggestion.prompt, ghost, t, installedGhosts))',
- );
- // 语音占用 / 发送中时不填入,预览与填入各走一次插件文字计算。
- expect(suggestionBlock).toContain(
- 'if (sendInFlightRef.current || composerMutationLockedRef.current) return false;',
- );
- expect(source).toContain('onMutationLockChange={handleComposerMutationLockChange}');
- expect(suggestionBlock.match(/pluginSuggestionComposerText\(/g)).toHaveLength(1);
- expect(suggestionBlock.match(/pluginSuggestionDisplayText\(/g)).toHaveLength(1);
- // 普通发送直接使用输入内容,不再经过可能残留推荐内容的中转 ref。
- expect(source).toContain('onSend={handleSend}');
- expect(source).not.toContain('pendingHomePromptRef');
- expect(source).not.toContain('handleComposerSend');
- });
-
- it('keeps brand lockup tokens from the Figma slices', () => {
- expect(brandLockupSource).toContain('head-image-dark.png');
- expect(brandLockupSource).toContain('head-image-light.png');
- expect(brandLockupSource).toContain('drop-shadow(0 2px 3.65px rgba(0, 0, 0, 0.15))');
- expect(brandLockupSource).toContain('BRAND_ICON_SIZE = 50');
- expect(brandLockupSource).toContain('BRAND_LOGO_WIDTH = 110');
- expect(brandLockupSource).toContain('BRAND_LOGO_HEIGHT = 37.5');
- expect(brandLockupSource).not.toMatch(/logoScale\s*[=:]/);
- expect(source).not.toContain('create-agent-avatar-glass-bg');
- });
-
- it('keeps the decorative head image unselectable', () => {
- expect(brandLockupSource).toContain('pointer-events-none');
- expect(brandLockupSource).toContain('select-none');
- expect(brandLockupSource).toContain('draggable={false}');
- });
-
- it('keeps global sidebar chrome out of the route body', () => {
- expect(source).not.toContain('TODO-E4D');
- expect(source).not.toContain('cindy-avatar-account.png');
- });
-
- it('uses CREATE AGENT private tokens for composer controls', () => {
- expect(source).toContain('border-[var(--create-agent-control-border)]');
- expect(source).toContain('bg-[var(--create-agent-control-bg)]');
- expect(source).toContain('text-[var(--create-agent-control-text)]');
- expect(source).toContain('text-[var(--create-agent-control-icon)]');
- expect(source).toContain('visualVariant="create-agent"');
-
- expect(chatInputSource).toContain(
- "visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}",
- );
- // 聚焦描边已拆分:输入框容器走 chat-input-border-focus(CINDY 30% 弱化),
- // create-agent-focus-ring 专供键盘 focus-visible ring(PR#174 review 2026-07-20)。
- expect(chatInputSource).toContain('focus-within:border-[var(--chat-input-border-focus)]');
- expect(chatInputSource).not.toContain('focus-within:border-[var(--create-agent-focus-ring)]');
- expect(chatInputSource).toContain(
- "'min-w-0 flex-nowrap justify-between gap-2 overflow-hidden'",
- );
- const permissionSelectorIndex = chatInputSource.indexOf('<PermissionSelector');
- const middleToolbarSlotIndex = chatInputSource.indexOf('{middleToolbarSlot}');
- const modelSelectorIndex = chatInputSource.indexOf('<ModelSelector');
- expect(middleToolbarSlotIndex).toBeGreaterThan(permissionSelectorIndex);
- expect(middleToolbarSlotIndex).toBeLessThan(modelSelectorIndex);
-
- // 发送按钮已统一到 send-btn-*(create-agent 与会话内共用,2026-07-22),SendButton 不再消费
- // create-agent-send-* 私有 token;send-btn-* 的正向断言见下方「keeps default composer send buttons」。
- expect(sendButtonSource).not.toContain('create-agent-send-bg');
- expect(sendButtonSource).not.toContain('create-agent-send-icon');
- expect(sendButtonSource).not.toContain('create-agent-focus-ring');
- expect(sendButtonSource).toContain('function CreateAgentSendIcon');
- expect(sendButtonSource).toContain('fill="currentColor"');
-
- // Segmented v8 now owns both Agent selector densities; legacy tokens remain theme-compatible.
- expect(vendorSwitcherSource).toContain('<SegmentedControl');
- expect(vendorSwitcherSource).not.toContain('create-agent-segment-track-bg');
-
- // 引擎下拉:trigger 是描边控件(与协同按钮同族,区别于裸态的权限/模型 trigger),
- // 面板行走共享菜单行(DESIGN §4 Composer dropdown rows);定宽 h-30,引擎数量增加不改工具条布局。
- expect(agentSelectSource).toContain("'h-[30px]'");
- expect(agentSelectSource).toContain('border-[var(--create-agent-control-border)]');
- expect(agentSelectSource).toContain('bg-[var(--create-agent-control-bg)]');
- expect(agentSelectSource).toContain('COMPOSER_MENU_ROW');
- expect(agentSelectSource).toContain('text-[var(--cmd-palette-item-meta)]');
- // 选项表来自单一来源,新增引擎不需要改控件;隐藏未注册引擎的语义与分段器一致
- expect(agentSelectSource).toContain('visibleOptions.map');
- expect(agentSelectSource).toContain('hiddenVendors');
-
- // 权限/模型 trigger 已统一为裸态无框(create-agent 与会话内共用同一套),不再用 create-agent-control 边框
- expect(permissionSelectorSource).not.toContain('border-[var(--create-agent-control-border)]');
- expect(permissionSelectorSource).toContain('border border-transparent bg-transparent');
- expect(permissionSelectorSource).toContain('hover:border-[var(--border-default)]');
- expect(permissionSelectorSource).toContain('min-w-[72px] max-w-full shrink');
- expect(permissionSelectorSource).toContain("'truncate'");
- expect(modelSelectorSource).not.toContain('border-[var(--create-agent-control-border)]');
- expect(modelSelectorSource).toContain('border border-transparent bg-transparent');
- expect(modelSelectorSource).toContain("'h-[30px] max-w-full shrink overflow-hidden px-2.5'");
- expect(modelSelectorSource).toContain("? 'w-[64px] min-w-[64px]'");
- expect(modelSelectorSource).toContain("? 'w-[148px] min-w-[72px]'");
- expect(modelSelectorSource).not.toContain('w-[206px] min-w-[160px] max-w-[206px] shrink');
- expect(modelSelectorSource).not.toContain('max-w-[180px] truncate');
-
- expect(colorsSource).toContain("'create-agent-send-bg'");
- expect(colorRegistry.resolveDefault('create-agent-send-bg', 'light')).toBe('#3C3F43');
- expect(colorRegistry.resolveDefault('create-agent-send-bg', 'dark')).toBe('#EEEEEE');
- expect(colorsSource).toContain("'create-agent-send-icon'");
- expect(colorRegistry.resolveDefault('create-agent-send-icon', 'light')).toBe('#FCFCFC');
- expect(colorsSource).not.toContain("'create-agent-send-border'");
- expect(colorsSource).toContain("'create-agent-send-bg-hover'");
- expect(colorRegistry.resolveDefault('create-agent-send-bg-hover', 'light')).toBe('#2E3237');
- expect(colorRegistry.resolveDefault('create-agent-send-bg-hover', 'dark')).toBe('#E2E2E2');
- expect(colorsSource).toContain("'create-agent-send-bg-pressed'");
- expect(colorRegistry.resolveDefault('create-agent-send-bg-pressed', 'light')).toBe('#25282C');
- expect(colorRegistry.resolveDefault('create-agent-send-bg-pressed', 'dark')).toBe('#D4D4D4');
- expect(colorsSource).toContain("'create-agent-send-disabled-bg'");
- expect(colorRegistry.resolveDefault('create-agent-send-disabled-bg', 'dark')).toBe('#444242');
- expect(colorsSource).toContain("'create-agent-send-disabled-icon'");
- expect(colorRegistry.resolveDefault('create-agent-send-disabled-icon', 'dark')).toBe('#585555');
- expect(colorsSource).toContain("'create-agent-segment-inactive-text'");
- expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'light')).toBe(
- '#9A9DA3',
- );
- expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'dark')).toBe(
- '#6F6F6F',
- );
- expect(colorsSource).toContain("'create-agent-control-border'");
- expect(colorRegistry.resolveDefault('create-agent-control-border', 'light')).toBe('#DCDFE3');
- expect(colorRegistry.resolveDefault('create-agent-control-border', 'dark')).toBe('#434343');
- expect(colorsSource).toContain("'create-agent-control-icon'");
- expect(colorRegistry.resolveDefault('create-agent-control-icon', 'light')).toBe('#3C3F43');
-
- expect(chatInputSource).toContain(
- "'min-w-0 flex-nowrap justify-between gap-2 overflow-hidden'",
- );
- expect(chatInputSource).toContain(
- "'min-w-0 flex-nowrap justify-between gap-1 overflow-hidden'",
- );
- expect(chatInputSource).toContain("'flex min-w-0 shrink items-center gap-2'");
- expect(chatInputSource).toContain("'flex min-w-0 shrink items-center justify-end gap-2'");
- expect(chatInputSource).toContain("'flex min-w-0 shrink items-center gap-1'");
- expect(chatInputSource).toContain("'flex min-w-0 shrink items-center justify-end gap-1'");
- expect(chatInputSource).not.toContain("'contents'");
- expect(chatInputSource).not.toContain('grid-cols-[minmax(0,max-content)_minmax(0,1fr)]');
- expect(chatInputSource).not.toContain(
- "isCreateAgentVariant ? 'flex-wrap gap-2' : 'min-w-0 gap-1'",
- );
- expect(chatInputSource).not.toContain(
- "'flex min-w-0 flex-1 flex-wrap items-center justify-end gap-2'",
- );
- expect(source).toContain('className="shrink-0"');
- expect(extraDirsButtonSource).toContain(
- "'flex h-[30px] shrink-0 items-center rounded-full border border-transparent'",
- );
- expect(permissionSelectorSource).toContain("'h-[30px] min-w-[72px] max-w-full shrink px-2.5'");
- expect(permissionSelectorSource).not.toContain("'h-[30px] min-w-[90px] max-w-none shrink-0");
- expect(permissionSelectorSource).not.toContain(
- "'h-[30px] min-w-[72px] max-w-full shrink border border-[var(--create-agent-control-border)]",
- );
- expect(permissionSelectorSource).not.toContain("'h-[30px] min-w-max shrink-0 px-2.5");
- // 2026-07 动效统一:过渡集扩为 color/background-color/transform,承载
- // active 按压缩放(DESIGN.md §14.4 按压原型);rounded-full 收进骨架(统一 send-btn-* 后壳形恒定)。
- expect(sendButtonSource).toContain(
- "'flex shrink-0 items-center justify-center rounded-full transition-[color,background-color,transform]'",
- );
- expect(modelSelectorSource).toContain("'h-[30px] max-w-full shrink overflow-hidden px-2.5'");
- expect(modelSelectorSource).not.toContain("'h-[30px] min-w-max shrink-0");
- expect(modelSelectorSource).not.toContain("'h-[30px] w-[206px] min-w-[160px] max-w-[206px]");
- expect(modelSelectorSource).toContain("? 'truncate'");
- expect(modelSelectorSource).toContain("? 'truncate'");
- expect(modelSelectorSource).toContain('<ChevronDown');
- expect(modelSelectorSource).toContain("'shrink-0'");
- expect(chatInputSource).toMatch(
- /className=\{\s*isCreateAgentVariant && !useNarrowToolbar\s*\? 'ml-\[7px\]' : undefined\s*\}/,
- );
- // 本机会话可选附件,但远程或身份尚未回流的已建会话不能摄入控制端绝对路径。
- expect(chatInputSource).toContain('const localAttachmentPickerEnabled =');
- expect(chatInputSource).toContain('{localAttachmentPickerEnabled && (');
- expect(chatInputSource).toContain('if (files.length > 0) void addFiles(files);');
- expect(chatInputSource).toContain("id: 'attach-files'");
- expect(chatInputSource).not.toContain('(extraDirs !== undefined && onExtraDirsChange)');
- expect(chatInputSource).not.toContain(
- "vendorKey === 'cc' && extraDirs !== undefined && onExtraDirsChange",
- );
- expect(chatInputSource).toMatch(
- /hasReferenceDirs=\{\s*!settingsLocked\s*&&\s*\(onExtraDirsChange !== undefined \|\| onWritableDirsChange !== undefined\)\s*\}/,
- );
- expect(extraDirsButtonSource).not.toContain("const isCc = agentKind === 'cc'");
- // ×N 角标在 create-agent(新建草稿)也要外显(2026-07-25 用户定稿):引用目录
- // 扩大 agent 可见范围,收起态不允许静默。不得回退到 icon-only 紧凑态。
- expect(extraDirsButtonSource).toContain('count > 0 && hasReferenceDirs');
- expect(extraDirsButtonSource).not.toContain(
- 'count > 0 && hasReferenceDirs && !isCreateAgentVariant',
- );
- });
-
- it('keeps the worktree checkmark readable in both themes', () => {
- expect(worktreeChipsRowSource).toContain(
- 'border-[var(--create-agent-send-bg)] bg-[var(--create-agent-send-bg)] text-[var(--create-agent-send-icon)]',
- );
- expect(worktreeChipsRowSource).not.toContain(
- 'border-primary bg-primary text-primary-foreground',
- );
- });
-
- it('keeps the worktree control visible for a detached HEAD checkout', () => {
- // currentBranch=null 是合法的 detached HEAD,不等于“不是 git 仓库”。
- // 未勾选时仍展示 HEAD;确认不合格(2026-08-07 裁决)才隐藏——探测中/失败
- // (confirmedIneligible === null)且记忆 ON 时仍显示,由发送侧 fail closed。
- expect(worktreeChipsRowSource).toContain(
- "const branchLabel = sourceBranch || branches.current || currentBranch || 'HEAD';",
- );
- expect(worktreeChipsRowSource).toContain('confirmedIneligible !== true');
- expect(worktreeChipsRowSource).toContain('&& (enabled || !!detect.data?.isGitRepo)');
- expect(worktreeChipsRowSource).not.toContain(
- 'const showBranchChip = !advancedHidden && !!branchLabel',
- );
- });
-
- it('aligns the real sidebar colors and user capsule with the CREATE AGENT Figma frame', () => {
- expect(sidebarTopNavSource).toContain('text-[var(--sidebar-nav-text)]');
- expect(vendorIconSource).toContain('text-[hsl(var(--sidebar-muted))]');
-
- expect(userInfoSectionSource).toContain(
- 'rounded-full border border-[var(--sidebar-user-card-border)]',
- );
- expect(userInfoSectionSource).toContain('bg-[var(--sidebar-user-card-bg)]');
- expect(userInfoSectionSource).toContain('text-[var(--sidebar-user-card-text)]');
-
- expect(colorsSource).toContain("'sidebar-nav-text'");
- expect(colorsSource).toContain("'sidebar-list-muted'");
- expect(colorsSource).toContain("'sidebar-user-card-bg'");
- expect(colorsSource).toContain('rgba(255, 255, 255, 0.20)');
- expect(colorsSource).toContain('rgba(255, 255, 255, 0.05)');
- });
-
- it('uses the focus-blue caret accent for editable carets', () => {
- expect(globalsSource).toContain('caret-color: var(--caret-accent);');
- expect(globalsSource).toContain('.cm-editor .cm-cursor');
- expect(globalsSource).toContain('border-left-color: var(--caret-accent) !important;');
- expect(colorsSource).toContain("'caret-accent'");
- expect(colorsSource).toContain(
- 'CINDY overrides to focus blue #417CDD per user decision 2026-07-18',
- );
- });
-
- it('keeps default composer send buttons aligned with the neutral inverse rule', () => {
- expect(sendButtonSource).toContain('bg-[var(--send-btn-bg)] text-[var(--send-btn-icon)]');
- expect(sendButtonSource).toContain('hover:bg-[var(--send-btn-hover-bg)]');
- expect(sendButtonSource).toContain('active:bg-[var(--send-btn-pressed-bg)]');
- expect(sendButtonSource).toContain('bg-[var(--send-btn-icon)]');
- // bg/text 已无条件设 send-btn-*(create-agent 与会话内共用),disabled 仅叠 opacity-40(见上方 267 行)
- expect(sendButtonSource).toContain("'cursor-not-allowed opacity-40'");
- expect(sendButtonSource).not.toContain('stop-btn-bg');
- expect(sendButtonSource).not.toContain('stop-btn-icon');
- expect(sendButtonSource).not.toContain('hover:opacity-85');
- expect(sendButtonSource).not.toContain('rounded-[8px]');
- expect(sendButtonSource).not.toContain(
- 'bg-[var(--send-btn-disabled-bg)] text-[var(--send-btn-disabled-icon)]',
- );
-
- expect(colorsSource).toContain("'send-btn-bg'");
- expect(colorRegistry.resolveDefault('send-btn-bg', 'light')).toBe('var(--accent-cta-bg)');
- expect(colorRegistry.resolveDefault('send-btn-bg', 'dark')).toBe('var(--accent-cta-bg)');
- expect(colorsSource).toContain("'send-btn-icon'");
- expect(colorRegistry.resolveDefault('send-btn-icon', 'light')).toBe('var(--surface-on-card)');
- expect(colorRegistry.resolveDefault('send-btn-icon', 'dark')).toBe('var(--surface-on-card)');
- expect(colorsSource).not.toContain("'stop-btn-bg'");
- expect(colorsSource).not.toContain("'stop-btn-icon'");
- });
-
- it('does not own global sidebar glass or selected-state tokens', () => {
- expect(colorsSource).not.toContain("'sidebar-glass-bg'");
- expect(colorsSource).not.toContain("'sidebar-glass-overlay-linear'");
- expect(colorsSource).not.toContain("'sidebar-glass-overlay-radial'");
- // sidebar-item-active-border 已由主题层按补编 §3 合法注册,不再列入禁项
- expect(colorsSource).not.toContain("'sidebar-item-active-text'");
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
index 586f6ee9ee..660768f30f 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
@@ -95,7 +95,7 @@ describe('Shared create project picker', () => {
'getProjectPickerEmptyLabelKey(workspacePrompt)',
);
// 2026-07-19 恢复 worktree 入口(用户裁决,488cb33 误删回归;详见
- // newMakerCreateAgentVisualContract):路由允许且仅允许一个 advancedOnly
+ // CREATE AGENT 视觉规则):路由允许且仅允许一个 advancedOnly
// 变体的 WorktreeChipsRow(2026-07-28 起渲染 [分支 chip][worktree 勾选 chip],
// 齿轮 popover 已移除;folderPickerMode="project" 仅为其 advancedHidden
// 语义服务),不回退 folder chip 版;项目选择仍由 mode pill 独占。
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts
deleted file mode 100644
index b662c27129..0000000000
--- a/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const sidebarSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const watcherSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useOrcaWorkerAttentionWatcher.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const projectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'workerProjectionStore.ts'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const orcaSplitViewSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'OrcaSplitView.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('Orca worker attention watcher mount', () => {
- it('mounts the worker attention watcher in CCAgentSidebarUpper root, not inside ExpandedView', () => {
- const rootBlock = extractBetween(
- sidebarSource,
- 'export function CCAgentSidebarUpper()',
- 'function ExpandedView(',
- );
- const expandedBlock = sidebarSource.slice(sidebarSource.indexOf('function ExpandedView('));
-
- expect(rootBlock).toContain('useOrcaWorkerAttentionWatcher(sessionsHook.sessions, activeSessionId);');
- expect(expandedBlock).not.toContain('useOrcaWorkerAttentionWatcher(');
- });
-
- it('derives attention from the projection store, whose request sequence rejects stale results', () => {
- expect(watcherSource).toContain('useWorkerProjectionVersion()');
- expect(watcherSource).toContain('getWorkerProjectionSnapshot(leadSessionId)');
- expect(watcherSource).not.toContain('listWorkersByLead(');
- expect(projectionSource).toContain('if (item.entry.requestSeq !== item.requestId)');
- expect(projectionSource).toContain('if (entry.requestSeq !== requestId)');
- });
-
- it('clears only visible non-done worker attention before paint in doc-mode toggle layout', () => {
- const splitViewBlock = extractBetween(
- orcaSplitViewSource,
- 'export function OrcaSplitView({',
- 'const activePane = togglePane;',
- );
-
- expect(splitViewBlock).toContain('const attention = useWorkerAttentionSnapshot();');
- expect(splitViewBlock).toContain('useLayoutEffect(() => {');
- expect(splitViewBlock).toContain("togglePane === 'worker' &&");
- expect(splitViewBlock).toContain('reportAgentIslandVisibility &&');
- expect(splitViewBlock).toContain("selectedWorkerRecord?.status !== 'done'");
- expect(splitViewBlock).toContain('clearWorkerAttention(selectedWorkerId);');
- });
-});
-
-function extractBetween(source: string, startNeedle: string, endNeedle: string): string {
- const start = source.indexOf(startNeedle);
- const end = source.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return source.slice(start, end);
-}
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts
deleted file mode 100644
index 8f0aff32f2..0000000000
--- a/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const repoRoot = resolve(__dirname, '..', '..', '..');
-const attentionIconSource = readFileSync(
- resolve(
- repoRoot,
- 'src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx',
- ),
- 'utf8',
-);
-const tabBodySource = readFileSync(
- resolve(
- repoRoot,
- 'src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx',
- ),
- 'utf8',
-);
-const selectionSource = readFileSync(
- resolve(repoRoot, 'src/renderer/features/cc-agent/hooks/useOrcaWorkerSelection.ts'),
- 'utf8',
-);
-const sessionViewSource = readFileSync(
- resolve(repoRoot, 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),
- 'utf8',
-);
-const sessionHeaderSource = readFileSync(
- resolve(repoRoot, 'src/renderer/features/cc-agent/SessionContentHeader.tsx'),
- 'utf8',
-);
-
-describe('Orca worker projection integration contracts', () => {
- it('keeps inactive right-sidebar pills on the read-only projection path', () => {
- expect(attentionIconSource).toContain("useWorkerProjection(sessionId ?? '')");
- expect(attentionIconSource).not.toContain('useWorkers(');
- expect(attentionIconSource).not.toContain('revalidate');
- });
-
- it('keeps right-sidebar tab bodies owning projections across active and detached lifetimes', () => {
- expect(tabBodySource).toContain('useWorkerProjectionOwner(ctx.sessionId);');
- expect(tabBodySource).toContain('revalidateActiveWorkersProjection(ctx.sessionId)');
- expect(tabBodySource).toContain('revalidateActiveWorkerSettings(ctx.sessionId)');
- expect(tabBodySource).toContain('if (!active || !shellVisible || !windowVisible) return;');
- });
-
- it('runs the attention projection inside the detached sidebar renderer', () => {
- expect(tabBodySource).toContain('isSidebarWindow() ? [ctx.sessionId] : []');
- expect(tabBodySource).toContain('useOrcaWorkerAttentionByLeadIds(');
- expect(tabBodySource).toContain('viewVisible ? ctx.sessionId : undefined');
- });
-
- it('keeps doc rail worker selection on useWorkers so it still receives live projection updates', () => {
- expect(selectionSource).toContain("import { useWorkers } from './useWorkers';");
- expect(selectionSource).toContain('} = useWorkers(leadSessionId);');
- });
-
- it('keeps renderer worker reads behind the shared projection store', () => {
- expect(sessionViewSource).toContain('useWorkerProjection(collabProjectionLeadId)');
- expect(sessionViewSource).not.toContain('.listWorkersByLead(collabSessionId)');
- expect(sessionHeaderSource).toContain('revalidateWorkersProjection(session.id)');
- expect(sessionHeaderSource).not.toContain('.listWorkersByLead(session.id)');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
deleted file mode 100644
index 0b579ae233..0000000000
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ /dev/null
@@ -1,533 +0,0 @@
-/**
- * OrcaWorkflowRoute regression tests.
- *
- * The route keeps parse/lookup helpers private, so these tests mirror the small
- * pure worker-selection contract and statically check source invariants.
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-interface TestSession {
- id: string;
- agentKind?: 'cc' | 'codex';
-}
-
-interface TestWorkerRecord {
- id: string;
- sessionId: string;
-}
-
-function findWorkerSession(params: {
- leadSession: TestSession | null;
- sessions: TestSession[];
- workerRecords: TestWorkerRecord[];
- focusedWorkerSessionId?: string | null;
- workerSessionId: string | null;
-}): TestSession | null {
- const { leadSession, sessions, workerRecords, focusedWorkerSessionId, workerSessionId } = params;
- if (!leadSession) return null;
- if (focusedWorkerSessionId) {
- const focusedWorkerRecord = workerRecords.find((w) => w.sessionId === focusedWorkerSessionId);
- if (focusedWorkerRecord) {
- return sessions.find((s) => s.id === focusedWorkerRecord.sessionId) ?? null;
- }
- }
- if (workerSessionId) {
- const explicitWorkerRecord = workerRecords.find((w) => w.sessionId === workerSessionId);
- if (explicitWorkerRecord) {
- return sessions.find((s) => s.id === explicitWorkerRecord.sessionId) ?? null;
- }
- }
- const firstWorkerRecord = workerRecords[0];
- return firstWorkerRecord
- ? sessions.find((s) => s.id === firstWorkerRecord.sessionId) ?? null
- : null;
-}
-
-// Windows checkout(core.autocrlf)下源码是 CRLF;统一归一成 LF,含 \n 的多行片段断言才跨平台成立。
-const readTextLf = (...args: Parameters<typeof readFileSync>): string =>
- String(readFileSync(...args)).replace(/\r\n/g, '\n');
-
-const routeSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'OrcaWorkflowRoute.tsx'),
- 'utf8',
-);
-const splitViewSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'OrcaSplitView.tsx'),
- 'utf8',
-);
-const workerPanelSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'OrcaWorkerPanel.tsx'),
- 'utf8',
-);
-const workersTabBodySource = readTextLf(
- resolve(
- __dirname,
- '..',
- 'features',
- 'right-sidebar',
- 'plugins',
- 'orca-workers',
- 'OrcaWorkersTabBody.tsx',
- ),
- 'utf8',
-);
-const workerSelectionHookSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useOrcaWorkerSelection.ts'),
- 'utf8',
-);
-const workdirBrowseRouteSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'workdir-browse', 'WorkdirBrowseRoute.tsx'),
- 'utf8',
-);
-const sessionViewSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSessionView.tsx'),
- 'utf8',
-);
-const chatInputSource = readTextLf(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-);
-const atMentionPanelSource = readTextLf(
- resolve(__dirname, '..', 'components', 'new-chat', 'AtMentionPanel.tsx'),
- 'utf8',
-);
-const sessionStatusIconSource = readTextLf(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'SessionStatusIcon.tsx'),
- 'utf8',
-);
-const rightSidebarTabBarSource = readTextLf(
- resolve(__dirname, '..', 'features', 'right-sidebar', 'TabBar.tsx'),
- 'utf8',
-);
-const orcaWorkersPluginSource = readTextLf(
- resolve(__dirname, '..', 'features', 'right-sidebar', 'plugins', 'orca-workers', 'index.tsx'),
- 'utf8',
-);
-const messageStreamSource = readTextLf(
- resolve(__dirname, '..', 'components', 'chat', 'MessageStream.tsx'),
- 'utf8',
-);
-const mainLayoutSource = readTextLf(
- resolve(__dirname, '..', 'components', 'layout', 'MainLayout.tsx'),
- 'utf8',
-);
-const templatePlaceholder = (name: string) => `${String.fromCharCode(36)}{${name}}`;
-
-describe('OrcaWorkflowRoute worker session lookup contract', () => {
- const lead: TestSession = { id: 'lead-1' };
- const workerA: TestSession = { id: 'worker-a', agentKind: 'codex' };
- const workerB: TestSession = { id: 'worker-b', agentKind: 'cc' };
-
- it('returns explicit worker only when workflow records link it to the lead', () => {
- expect(findWorkerSession({
- leadSession: lead,
- sessions: [lead, workerA, workerB],
- workerRecords: [{ id: 'worker-record-a', sessionId: workerA.id }],
- workerSessionId: workerA.id,
- })).toBe(workerA);
- });
-
- it('falls back to the first workflow worker record', () => {
- expect(findWorkerSession({
- leadSession: lead,
- sessions: [lead, workerA, workerB],
- workerRecords: [
- { id: 'worker-record-b', sessionId: workerB.id },
- { id: 'worker-record-a', sessionId: workerA.id },
- ],
- workerSessionId: 'unlinked-worker',
- })).toBe(workerB);
- });
-
- it('returns the focused worker before the URL hint', () => {
- expect(findWorkerSession({
- leadSession: lead,
- sessions: [lead, workerA, workerB],
- workerRecords: [
- { id: 'worker-record-a', sessionId: workerA.id },
- { id: 'worker-record-b', sessionId: workerB.id },
- ],
- focusedWorkerSessionId: workerB.id,
- workerSessionId: workerA.id,
- })).toBe(workerB);
- });
-
- it('returns null without workflow records', () => {
- expect(findWorkerSession({
- leadSession: lead,
- sessions: [lead, workerA],
- workerRecords: [],
- workerSessionId: null,
- })).toBe(null);
- });
-});
-
-describe('OrcaWorkflowRoute source invariants', () => {
- it('uses the right-sidebar UsersRound mark for every collaboration entry point', () => {
- expect(rightSidebarTabBarSource).toContain("'orca-workers': UsersRound");
- expect(orcaWorkersPluginSource).toContain('<UsersRound size={13} />');
- expect(atMentionPanelSource).toContain('collaboration: UsersRound');
- expect(atMentionPanelSource).not.toContain('<Puzzle');
- expect(sessionStatusIconSource).toContain('<UsersRound');
- expect(sessionStatusIconSource).not.toContain('<Puzzle');
- expect(sessionStatusIconSource).toContain("'text-[var(--cmd-palette-item-meta)]'");
- });
-
- it('keeps policy reasons scoped to the disabled collaboration menu item', () => {
- expect(chatInputSource).toContain('const policyDisabled = collaboration.disabled === true;');
- expect(chatInputSource).toContain('disabledReason: collaboration.disabledReason');
- expect(chatInputSource).toContain('policyDisabled && !retryable');
- expect(chatInputSource).toContain('collaboration.onDisabledActivate?.();');
- });
-
- it('keeps the active collaboration tooltip free of policy-disabled reasons', () => {
- expect(sessionViewSource).toMatch(
- /disabledReason:\s*!collabEnabled\s*\?\s*collabPolicy\.loading[\s\S]*?:\s*undefined\s*:\s*undefined,/,
- );
- });
-
- it('retries an unavailable policy from the disabled collaboration control', () => {
- expect(sessionViewSource).toContain('onDisabledActivate: collabPolicy.unavailable');
- expect(sessionViewSource).toContain('void collabPolicy.refresh().then((policy) => {');
- expect(sessionViewSource).toContain('if (policy.enabled && !policy.unavailable) {');
- expect(chatInputSource).toContain('if (collaboration) {');
- expect(chatInputSource).toContain('!!collaboration.onDisabledActivate');
- });
-
- it('does not subscribe to project policy updates from the legacy Orca route', () => {
- // eligible 的判据本体收敛进了 resolveCollabEntryPolicy(issue #1170:草稿与会话视图
- // 曾各写一份,同一个 device-link 项目两边给出相反答案)。这里守的仍是原来那件事 ——
- // legacy /orca 路由(orcaMode)必须先被 `!orcaMode &&` 短路掉,否则它也会去跑项目
- // 策略查询并订阅刷新。
- expect(sessionViewSource).toContain(
- 'const collabPolicyEligible = !orcaMode && !botChatIdentity && collabEntry.eligible;',
- );
- expect(sessionViewSource).toContain('resolveCollabEntryPolicy({');
- });
-
- it('keeps /orca as a legacy compatibility redirect to the plain lead route', () => {
- expect(routeSource).toContain('const { sessions, isLoading } = useCCSessions()');
- expect(routeSource).toContain('if (!sessionId || isLoading) return;');
- expect(routeSource).toContain("navigate('/cc-agent', { replace: true })");
- expect(routeSource).not.toContain('revealOrcaWorkersTab');
- expect(routeSource).toContain("params.delete('worker')");
- expect(routeSource).toContain("params.delete('workerAgent')");
- expect(routeSource).toContain('leadSessionId: sessionId');
- expect(routeSource).toContain('focusWorkerSessionId: workerSessionId');
- expect(routeSource).toContain('navigate(`/cc-agent/${sessionId}${nextSearch ? `?${nextSearch}` : \'\'}`, {');
- expect(routeSource).toContain('const orcaWorkersReveal = isOrcaLeadSession(leadSession)');
- expect(routeSource).toContain('orcaWorkersReveal,');
- expect(routeSource).not.toContain('<CCAgentSessionView');
- expect(routeSource).not.toContain('<OrcaSplitView');
- });
-
- it('does not use fork parentSessionId or title-linked worker lookup for Orca mapping', () => {
- expect(splitViewSource).not.toContain('parentSessionId: actualLeadSessionId');
- expect(splitViewSource).not.toContain('isOrcaWorkerLinkedToLead');
- expect(splitViewSource).not.toMatch(/Orca Worker\[[^\]]+\]/);
- });
-
- it('does not persist workerAgent route hints in the worker pane', () => {
- expect(splitViewSource).not.toContain("searchParams.get('workerAgent')");
- expect(splitViewSource).not.toContain('workerAgentKindHint');
- expect(splitViewSource).toContain('normalizeOrcaDisplayAgentKind(');
- });
-
- it('renders lead labels with dynamic agent text and a VendorIcon in both Orca layouts', () => {
- expect(splitViewSource).toContain("const leadPaneLabel = t('orca.split.leadLabel', {");
- expect(splitViewSource).toContain('agent: orcaAgentLabel(leadAgentKind)');
- expect(splitViewSource).toContain('const leadPaneIcon = (');
- expect(splitViewSource).toContain('<VendorIcon');
- expect(splitViewSource).toContain('{leadPaneIcon}');
- expect(splitViewSource).toContain('{leadPaneLabel}');
- expect(splitViewSource).not.toContain("{t('orca.split.leadLabel')}");
- expect(splitViewSource).not.toContain("label={t('orca.split.leadLabel')}");
- });
-
- it('keeps missing worker panes as placeholders instead of editable inputs', () => {
- expect(splitViewSource).toContain("workerEmptyLabel ?? t('orca.split.waitingForWorker')");
- expect(chatInputSource).toContain(
- "autofocus: !disableAutofocus && !disabled ? 'end' : false",
- );
- // The composer is also temporarily read-only during the bounded effort-runtime
- // preflight, so a pending send cannot clear text entered after its snapshot.
- expect(chatInputSource).toContain('editor?.setEditable(!composerTypingLocked)');
- });
-
- it('does not block collaboration tab opening on worker SDK bootstrap', () => {
- const requestEnable = sessionViewSource.indexOf('const requestEnableCollab = useCallback');
- // device-link 按粘滞 deviceId 走共享远程 handoff;本机会话仍直调本机 IPC。
- // reveal promise 必须在两条 mutation 分支之前启动,不能等 Worker bootstrap 完成后才开 tab。
- const remoteEnableCall = sessionViewSource.indexOf(
- 'await enableRemoteCollabForSession({',
- requestEnable,
- );
- const localEnableCall = sessionViewSource.indexOf(
- 'await window.electronAPI.maker.enableOrca(collabSessionId, enableOptions)',
- requestEnable,
- );
- const openTab = sessionViewSource.indexOf(
- 'revealOrcaWorkersTab(collabSessionId)',
- requestEnable,
- );
-
- expect(requestEnable).toBeGreaterThan(-1);
- expect(remoteEnableCall).toBeGreaterThan(requestEnable);
- expect(localEnableCall).toBeGreaterThan(requestEnable);
- expect(openTab).toBeGreaterThan(requestEnable);
- expect(openTab).toBeLessThan(remoteEnableCall);
- expect(openTab).toBeLessThan(localEnableCall);
- expect(sessionViewSource).not.toContain(
- `/cc-agent/orca/${templatePlaceholder('collabSessionId')}`,
- );
- });
-
- it('starts manual collaboration through the detailed worker form', () => {
- expect(sessionViewSource).toContain('<CreateWorkerPopover');
- expect(sessionViewSource).toContain('onOpenDetails');
- expect(sessionViewSource).toContain('role: form.role');
- expect(sessionViewSource).toContain('label: createWorkerLabel(form.role, [])');
- expect(sessionViewSource).toContain('model: form.model');
- expect(sessionViewSource).toContain('delegateTask: form.initialTask || undefined');
- expect(chatInputSource).toContain('if (collaboration) {');
- expect(chatInputSource).toContain('collaboration.onOpenDetails();');
- });
-
- it('maps manual collaboration start failures through i18n instead of raw IPC messages', () => {
- expect(sessionViewSource).toContain('getCollaborationStartErrorMessage(err, t, {');
- expect(sessionViewSource).toContain('remoteDevice: Boolean(remoteDeviceId)');
- expect(sessionViewSource).not.toContain("ipcError?.message ?? t('newChat.collaboration.startFailed'");
- });
-
- it('keeps Orca search jump state available for the target pane', () => {
- expect(sessionViewSource).toContain('if (!sessionId || !searchJump) return;');
- expect(sessionViewSource).toContain(`if (searchJump.sessionId !== sessionId) {
- if (!session) return;`);
- // 陈旧跳转只由路由主权实例回收:Orca 视图与分屏嵌入 pane 都不得取消
- // owner 正在消费的跳转。
- expect(sessionViewSource).toContain(`if (!isOrcaMode && !isOrcaLeadSessionView && ownsWindowRoute) {
- clearSearchJumpState();
- }`);
- expect(sessionViewSource).toContain('...(workerSearchJump ? { searchJump: workerSearchJump } : {})');
- expect(sessionViewSource).toContain('...(workerSearchJump ? { searchJump: undefined } : {})');
- expect(workerPanelSource).toContain('searchJumpProp={searchJump}');
- expect(workerPanelSource).toContain('onSearchJumpConsumed={onSearchJumpConsumed}');
- });
-
- it('reveals draft-created Orca worker tabs from route state after the lead route owns the session', () => {
- expect(sessionViewSource).toContain('function parseOrcaWorkersRevealState(state: unknown)');
- expect(sessionViewSource).toContain('reveal?.leadSessionId && reveal.leadSessionId !== sessionId');
- expect(sessionViewSource).toContain('const hasWorkerSearchJump = Boolean(');
- expect(sessionViewSource).toContain('routeWorkerHint.hasWorkerParam || !!orcaWorkersReveal || hasWorkerSearchJump');
- expect(sessionViewSource).toContain('const shouldRevealWorkersTab = hasExplicitOrcaWorkersReveal || shouldPassiveRevealWorkersTab;');
- expect(sessionViewSource).toContain(
- 'if (!ownsRoute || !collabEnabled || isCompactRail || !sessionId) return;',
- );
- expect(sessionViewSource).toContain('orcaWorkersReveal?.focusWorkerSessionId ??');
- expect(sessionViewSource).toMatch(
- /hasWorkerSearchJump\s*\?\s*\(?searchJump\?\.sessionId\s*\?\?\s*null\)?\s*:\s*null/,
- );
- expect(sessionViewSource).toContain('orcaWorkersReveal: undefined');
- expect(sessionViewSource).toContain("routeResult === 'stale-context' && shouldRevealWorkersTab");
- expect(sessionViewSource).toContain("routeResult !== 'attached' && routeResult !== 'routed'");
- });
-
- it('passively reveals the collaboration tab only for plain Orca Lead routes with no collapsed record', () => {
- expect(sessionViewSource).toContain("import { readPanelCollapsedRecord } from '@/layout/collapsePrefs';");
- expect(sessionViewSource).toContain("import {");
- expect(sessionViewSource).toContain('shouldRevealOrcaWorkersAfterPaint');
- expect(sessionViewSource).toContain('shouldRevealOrcaWorkersBeforeFirstPaint');
- expect(sessionViewSource).toContain('const passiveOrcaWorkersRevealSessionRef = useRef<string | null>(null);');
- expect(sessionViewSource).toContain('const rightSidebarCollapsedRecord = sessionId');
- expect(sessionViewSource).toContain('const shouldFirstFrameRevealOrcaWorkers = shouldRevealOrcaWorkersBeforeFirstPaint({');
- expect(sessionViewSource).toContain('hasExplicitReveal: hasExplicitOrcaWorkersReveal');
- expect(sessionViewSource).toContain("hasSynchronousSessionIdentity: sessionFromList?.orcaRole === 'lead'");
- expect(sessionViewSource).toContain('initialCollapsed={shouldFirstFrameRevealOrcaWorkers ? false : undefined}');
- expect(sessionViewSource).toContain('writeInitialCollapsedRecord={shouldFirstFrameRevealOrcaWorkers}');
- expect(sessionViewSource).toContain('passiveOrcaWorkersRevealSessionRef.current !== sessionId &&');
- expect(sessionViewSource).toContain('shouldRevealOrcaWorkersAfterPaint({');
- expect(sessionViewSource).toContain('const shouldPassiveRevealWorkersTab =');
- expect(sessionViewSource).toContain('passiveOrcaWorkersRevealSessionRef.current = sessionId;');
- expect(sessionViewSource).toContain('const focusWorkerSessionId = hasExplicitOrcaWorkersReveal');
- expect(sessionViewSource).toContain(': null;');
- expect(sessionViewSource).toContain(
- '...(shouldFirstFrameRevealOrcaWorkers ? { animate: false } : {}),',
- );
- expect(sessionViewSource).not.toContain(
- '...(shouldRevealForMissingCollapsedRecord ? { animate: false } : {}),',
- );
- });
-
- it('sets passive collaboration sidebar collapsed state during the route layout declaration', () => {
- expect(sessionViewSource).toContain('useLayoutEffect(() => {');
- expect(sessionViewSource).toContain(
- 'declare(sessionId, { initialCollapsed, writeInitialCollapsedRecord, subagentsAvailable });',
- );
- // The declaration is multi-line since the Subagents entry also follows
- // durable Pi runs (a task switched off Pi keeps the tab while its runs
- // exist), so the attribute and its expression are pinned separately.
- expect(sessionViewSource).toContain('subagentsAvailable={');
- expect(sessionViewSource).toContain(
- "(session.agentKind === 'pi' && !session.remoteHostId) || durablePiRunsPresent",
- );
- // The harness alone must not declare the entry for an SSH-hosted task:
- // `agents/pi` disables the durable Subagent extension whenever
- // `remoteHostId` is set, so such a task can never produce a run and the tab
- // would stay empty while its controls addressed the local filesystem.
- expect(sessionViewSource).not.toContain(
- "session ? session.agentKind === 'pi' || durablePiRunsPresent : undefined",
- );
- expect(mainLayoutSource).toContain('const declareRightSidebarSessionId = useCallback');
- expect(mainLayoutSource).toContain('const nextCollapsed = hasInitialCollapsed');
- expect(mainLayoutSource).toContain('setIsRightSidebarCollapsed(nextCollapsed);');
- expect(mainLayoutSource).toContain('writeCollapsedFor(sessionId, nextCollapsed);');
- expect(mainLayoutSource).toContain('setRightSidebarSessionId: declareRightSidebarSessionId');
- });
-
- it('lets search jumps and explicit tab hints mount the targeted worker before focused-worker fallback', () => {
- const searchJumpPriority = workerSelectionHookSource.indexOf('if (effectiveSearchJumpWorkerSessionId)');
- const hintPriority = workerSelectionHookSource.indexOf('if (focusWorkerHintSessionId)', searchJumpPriority);
- const focusedWorkerFallback = workerSelectionHookSource.indexOf('if (focusedWorker)', hintPriority);
-
- expect(workerSelectionHookSource).toContain('const searchJumpWorkerSessionId =');
- expect(workerSelectionHookSource).toContain('const [searchJumpPinnedWorkerSessionId, setSearchJumpPinnedWorkerSessionId]');
- expect(workerSelectionHookSource).toContain('const [focusWorkerPinnedSessionId, setFocusWorkerPinnedSessionId]');
- expect(workerSelectionHookSource).toContain('setSearchJumpPinnedWorkerSessionId(null);');
- expect(workerSelectionHookSource).toContain('setFocusWorkerPinnedSessionId(null);');
- expect(searchJumpPriority).toBeGreaterThan(-1);
- expect(hintPriority).toBeGreaterThan(searchJumpPriority);
- expect(focusedWorkerFallback).toBeGreaterThan(-1);
- expect(searchJumpPriority).toBeLessThan(focusedWorkerFallback);
- expect(hintPriority).toBeLessThan(focusedWorkerFallback);
- });
-
- it('reports the actual Orca pane session to Agent Island', () => {
- expect(splitViewSource).toContain('const agentIslandVisibleSessionIds = useMemo');
- expect(splitViewSource).toContain('reportAgentIslandVisibility = true');
- expect(splitViewSource).toContain('if (!reportAgentIslandVisibility) return null;');
- expect(splitViewSource).not.toContain('if (!navigateOnStop) return null;');
- expect(splitViewSource).not.toContain('if (!navigateOnStop) return;');
- expect(splitViewSource).toContain("togglePane === 'worker' ? (workerSession?.id ?? null) : leadSessionId");
- expect(splitViewSource).toContain('const syncAgentIslandVisibleSession = useCallback');
- expect(splitViewSource).toContain('window.electronAPI.agentIsland?.setVisibleSession?.(agentIslandVisibleSessionIds)');
- expect(splitViewSource).toContain("window.addEventListener('focus', syncAgentIslandVisibleSession)");
- });
-
- it('reports the visible right-sidebar collaboration worker sessions to Agent Island', () => {
- expect(workerPanelSource).toContain("import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';");
- expect(workerPanelSource).toContain('if (!isAgentIslandSupported()) return;');
- expect(workerPanelSource).toContain('viewVisible && workerSessionId && workerSessionId !== leadSessionId');
- expect(workerPanelSource).toContain('[leadSessionId, workerSessionId]');
- expect(workerPanelSource).toContain('window.electronAPI.agentIsland?.setVisibleSession?.(visibleSessionIds)');
- });
-
- it('does not navigate the detached sidebar window to settings from the worker toolbar', () => {
- // 硬上限时 + 按钮跳转到协同设置(codex P1 逃生口),但分离侧栏窗口与 device-link 受控面板
- // 不能整壳替换成设置路由(前者固定 /sidebar-window 壳路由,后者上限走 device-link 远程路径)。
- // 实现用 onOpenSettings={isSidebarWindow() || deviceId !== null ? undefined : handleOpenSettings} 在调用处守卫:
- // 两类面板下传 undefined,+ 按钮回退为 disabled(不再呈现点了没反应的「设置 · 协同」按钮)。
- expect(workerPanelSource).toContain("import { isSidebarWindow } from '@/lib/sidebarWindow';");
- expect(workerPanelSource).toContain('onOpenSettings={isSidebarWindow() || deviceId !== null ? undefined : handleOpenSettings}');
- expect(workerPanelSource).toContain("navigate('/settings?section=collaboration')");
- expect(workerPanelSource).not.toContain('settingsEnabled');
- expect(workersTabBodySource).toContain("import { isSidebarWindow } from '@/lib/sidebarWindow';");
- expect(workersTabBodySource).toContain('<OrcaWorkerPanel {...workerPanelProps} />');
- expect(workersTabBodySource).toContain('<RoutedOrcaWorkerPanel {...workerPanelProps} />');
- });
-
- it('marks the collaboration worker chat as sidebar-embedded so it cannot replace the host route', () => {
- expect(workerPanelSource).toContain('navigationMode="sidebar-embedded"');
- expect(workerPanelSource).toContain('sidebarTargetSessionId={leadSessionId}');
- expect(sessionViewSource).toContain('sidebarTargetSessionId={sidebarTargetSessionId}');
- expect(sessionViewSource).toContain("const ownsWindowRoute = navigationMode === 'route-owner';");
- expect(sessionViewSource).toContain('ownsWindowRoute && handoffFrom');
- expect(sessionViewSource).toContain('canNavigateSession && session?.parentSessionId');
- expect(sessionViewSource).toContain(
- "const canNavigateSession = ownsWindowRoute || navigationMode === 'split-pane';",
- );
- expect(sessionViewSource).toMatch(
- /sidebarPanelHostSessionId=\{\s*ownsRoute \|\| navigationMode === 'split-pane' \? sessionId : undefined\s*\}/,
- );
- expect(sessionViewSource).toContain(
- '!readOnly && canNavigateSession && !isSharedTaskPeer(remoteDeviceId) ? handleForkStripEncrypted : undefined',
- );
- });
-
- it('waits for detached bootstrap before mounting or writing the embedded right sidebar', () => {
- expect(mainLayoutSource).toContain('rsbWindow.loaded && !rsbDetached ? (');
- expect(mainLayoutSource).toContain('if (!sessionId || !rsbWindow.loaded || rsbDetached) return;');
- expect(mainLayoutSource).toContain("routeSidebarCommand({ type: 'open-terminal', sessionId })");
- expect(mainLayoutSource).toContain('const windowState = getRsbWindowUiState();');
- expect(mainLayoutSource).toContain('const currentSessionId = rightSidebarSessionIdRef.current;');
- expect(mainLayoutSource).toContain('sessionId: targetSessionId');
- expect(mainLayoutSource).toContain(
- "if (visibility === 'open' && opts.userInitiated !== false)",
- );
- expect(mainLayoutSource).toContain('navigateToSessionRef.current?.(targetSessionId)');
- });
-
- it('passes Orca lead vendor options when sending from the plain lead route', () => {
- expect(sessionViewSource).toContain('const orcaLeadVendorOptions =');
- expect(sessionViewSource).toMatch(
- /sessionId\s*&&\s*session\s*!==\s*null\s*&&\s*isOrcaLeadSession\(session\)/,
- );
- expect(sessionViewSource).not.toContain('isOrcaMode && sessionId && isOrcaLeadSession(session)');
- expect(sessionViewSource).toContain("vendorOptions: { orcaRole: 'lead', orcaLeadSessionId: sessionId }");
- });
-
- it('shows the Lead identity bar only in the plain Orca Lead route', () => {
- expect(sessionViewSource).toContain(
- 'const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);',
- );
- expect(sessionViewSource).toContain('const collabEnabled = isOrcaLeadSessionView;');
- expect(sessionViewSource).toContain('const showOrcaLeadIdentityBar = ownsRoute && collabEnabled;');
- expect(sessionViewSource).toContain("t('orca.split.leadLabel', {");
- expect(sessionViewSource).toContain('orcaAgentLabel(leadAgentKind)');
- expect(sessionViewSource).toContain('<VendorIcon');
- expect(sessionViewSource).toContain('{showOrcaLeadIdentityBar && (');
- expect(sessionViewSource).not.toContain('maximizePaneAria');
- expect(sessionViewSource).not.toContain('restorePaneAria');
- });
-
- it('reveals or closes the collaboration tab only on mounted non-compact state edges', () => {
- const edgeEffect = sessionViewSource.slice(
- sessionViewSource.indexOf('const prevCollabEnabledRef'),
- sessionViewSource.indexOf('// F-COLLAB: 关闭协同复用'),
- );
- const mountGuard = edgeEffect.indexOf('if (prevCollabEnabledRef.current === null) {');
- const compactGuard = edgeEffect.indexOf('if (isCompactRail) return;');
- const revealEdge = edgeEffect.indexOf('if (!prev && collabEnabled) {');
- const revealCall = edgeEffect.indexOf('revealOrcaWorkersTab(collabSessionId)');
- const closeEdge = edgeEffect.indexOf('if (prev && !collabEnabled) {');
- const closeCall = edgeEffect.indexOf('closeOrcaWorkersTabAfterTeamEnd(collabSessionId)');
-
- expect(mountGuard).toBeGreaterThanOrEqual(0);
- expect(compactGuard).toBeGreaterThan(mountGuard);
- expect(edgeEffect.slice(mountGuard, compactGuard)).toContain('return;');
- expect(revealEdge).toBeGreaterThan(compactGuard);
- expect(revealCall).toBeGreaterThan(revealEdge);
- expect(edgeEffect.slice(revealCall, closeEdge)).toContain('return;');
- expect(closeEdge).toBeGreaterThan(revealCall);
- expect(closeCall).toBeGreaterThan(closeEdge);
- // 新的 false→true 外部意图覆盖旧折叠历史;mount 的常驻恢复逻辑仍在上方 effect。
- expect(edgeEffect).not.toContain('rightSidebarCollapsedRecord');
- });
-
- it('reports embedded doc-mode Orca rail visibility only while the rail is open', () => {
- expect(workdirBrowseRouteSource).not.toContain('navigateOnStop={false}');
- expect(workdirBrowseRouteSource).not.toContain('layout="toggle"');
- expect(workdirBrowseRouteSource).toContain('reportAgentIslandVisibility={!railCollapse.collapsed}');
- });
-
- it('uses a request id so repeated jumps to the same message re-run focus', () => {
- expect(sessionViewSource).toContain('requestFocusMessage(searchJump.messageClientId)');
- expect(sessionViewSource).toContain('focusMessageRequestId={focusedMessageTarget?.requestId ?? 0}');
- expect(messageStreamSource).toContain('focusMessageRequestId?: number;');
- expect(messageStreamSource).toContain('lastAppliedFocusRef.current === focusRequestKey');
- expect(messageStreamSource).toContain('missingFocus.requestKey === focusRequestKey');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/pendingFolderMention.test.ts b/apps/desktop/src/renderer/__tests__/pendingFolderMention.test.ts
deleted file mode 100644
index d36aa8642d..0000000000
--- a/apps/desktop/src/renderer/__tests__/pendingFolderMention.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-);
-
-const useAttachmentsSource = readFileSync(
- resolve(__dirname, '..', 'hooks', 'useAttachments.ts'),
- 'utf8',
-);
-
-describe('pending folder mention queue', () => {
- it('uses an explicit version signal to wake ChatInput when folder paths are queued', () => {
- expect(useAttachmentsSource).toContain('pendingFoldersVersion');
- expect(useAttachmentsSource).toMatch(/setPendingFoldersVersion\(\(version\) => version \+ 1\)/);
- expect(chatInputSource).toMatch(/pendingFoldersVersion:\s*number/);
- expect(chatInputSource).toMatch(/addFolderPath,\s*pendingFoldersVersion,\s*consumePendingFolders/);
- expect(chatInputSource).toMatch(/\}, \[editor, consumePendingFolders, pendingFoldersVersion\]\);/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts
deleted file mode 100644
index e57356d147..0000000000
--- a/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const pendingQueueSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'PendingQueuePanel.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('PendingQueuePanel steer shortcut contract', () => {
- it('routes Cmd/Ctrl+Enter on a queued row through the same steer path as the row action', () => {
- const shortcutHelper = extractBetween(
- pendingQueueSource,
- 'function isPendingQueueSteerShortcut',
- 'export function PendingQueuePanel',
- );
- const rowKeydownBlock = extractBetween(
- pendingQueueSource,
- 'const handleRowKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {',
- 'const handleDragHandleKeyDown = (e: ReactKeyboardEvent<HTMLButtonElement>) => {',
- );
-
- expect(shortcutHelper).toContain("event.key === 'Enter'");
- expect(shortcutHelper).toContain('event.metaKey || event.ctrlKey');
- expect(shortcutHelper).toContain('!event.nativeEvent.repeat');
- expect(rowKeydownBlock).toContain('isPendingQueueSteerShortcut(e)');
- expect(rowKeydownBlock).toContain('!canSteerRow || !onSteer || isSteering || isRowEditing');
- expect(rowKeydownBlock).toContain('e.preventDefault();');
- expect(rowKeydownBlock).toContain('e.stopPropagation();');
- expect(rowKeydownBlock).toContain('void onSteer(entry.clientId);');
- });
-
- it('keeps the drag handle from swallowing the row steer shortcut', () => {
- const dragKeydownBlock = extractBetween(
- pendingQueueSource,
- 'const handleDragHandleKeyDown = (e: ReactKeyboardEvent<HTMLButtonElement>) => {',
- 'if (dragDisabled || !onReorder) return;',
- );
-
- expect(dragKeydownBlock).toContain('if (isPendingQueueSteerShortcut(e)) return;');
- });
-
- it('exposes the shortcut in queue row accessibility and tooltip surfaces', () => {
- expect(pendingQueueSource).toContain("aria-keyshortcuts={canSteerRow ? 'Meta+Enter Control+Enter' : undefined}");
- expect(pendingQueueSource).toContain('steerShortcutLabel?: string;');
- expect(pendingQueueSource).toContain('`${base} · ${steerShortcutLabel}`');
- expect(chatInputSource).toContain('steerShortcutLabel={steerShortcutLabel}');
- });
-});
-
-function extractBetween(sourceBlock: string, startNeedle: string, endNeedle: string): string {
- const start = sourceBlock.indexOf(startNeedle);
- const end = sourceBlock.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return sourceBlock.slice(start, end);
-}
diff --git a/apps/desktop/src/renderer/__tests__/pinnedSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/pinnedSidebarSection.test.ts
deleted file mode 100644
index 5e446ced94..0000000000
--- a/apps/desktop/src/renderer/__tests__/pinnedSidebarSection.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * pinnedSidebarSection — pinned section sidebar invariants.
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const pinnedSectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'PinnedSection.tsx'),
- 'utf8',
-);
-
-describe('Pinned sidebar section', () => {
- it('uses the same title color tokens as Projects and Dialogue in light and dark themes', () => {
- const titleIndex = pinnedSectionSource.indexOf("t('ccAgent.sidebar.pinned')");
- const titleButtonIndex = pinnedSectionSource.lastIndexOf('<button', titleIndex);
- const titleButtonBlock = pinnedSectionSource.slice(titleButtonIndex, titleIndex);
-
- expect(titleButtonBlock).toContain('text-[var(--sidebar-list-muted)]');
- expect(titleButtonBlock).toContain('hover:text-[var(--sidebar-nav-text)]');
- expect(titleButtonBlock).not.toContain('text-[var(--text-tertiary)]');
- expect(titleButtonBlock).not.toContain('hover:text-[var(--text-secondary)]');
- });
-
- it('passes source labels to pinned list cards as well as text rows', () => {
- expect(pinnedSectionSource).toContain('sourceLabel={sourceLabelMap.get(session.id)}');
- expect(pinnedSectionSource).toContain('sourceLabel={sourceLabelMap.get(entry.session.id)}');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
deleted file mode 100644
index 67d00f03d4..0000000000
--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * projectsSidebarSection — 主列表段头控件不变量。
- *
- * 2026-08-13 用户定稿:段头标题即机器范围下拉(MachineSwitcherMenu,「全部任务」
- * 与设备下拉合并),段级收起取消;右侧保留折叠按钮(单层 = 收起所有分组 ↔ 展开;
- * 设备+项目双层 = 循环 收项目层 → 收设备层 → 全部展开,foldState 状态机)与
- * 侧边栏显示设置入口。
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const projectsSectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'ProjectsSection.tsx'),
- 'utf8',
-);
-
-describe('Projects sidebar section', () => {
- it('keeps the group fold state machine (section collapse itself is gone)', () => {
- // 设备段头仍用单箭头折叠;右侧折叠按钮走三态状态机。
- expect(projectsSectionSource).toContain('ChevronDown');
- expect(projectsSectionSource).toContain('ChevronRight');
- expect(projectsSectionSource).toContain('ChevronsDownUp');
- expect(projectsSectionSource).toContain('ChevronsUpDown');
- // E 期折叠状态机:三态循环 + 图标随「下一步动作」切换。
- expect(projectsSectionSource).toContain(
- "'collapse-groups' | 'collapse-devices' | 'expand-all'",
- );
- expect(projectsSectionSource).toContain(
- "const FoldIcon = foldState === 'expand-all' ? ChevronsUpDown : ChevronsDownUp",
- );
- // 段级收起已随「标题 = 范围下拉」取消(2026-08-13 用户定稿)。
- expect(projectsSectionSource).not.toContain('isSectionCollapsed');
- expect(projectsSectionSource).not.toContain('SectionToggleIcon');
- });
-
- it('header order: scope title dropdown → fold → filter', () => {
- const titleIndex = projectsSectionSource.indexOf('<MainListScopeHeader');
- const foldIndex = projectsSectionSource.indexOf('onClick: handleFoldAll');
- expect(titleIndex).toBeGreaterThanOrEqual(0);
- expect(foldIndex).toBeGreaterThan(titleIndex);
- expect(projectsSectionSource).toContain('hasMainListContent && foldState !== null');
- // 只有对话组、没有项目时折叠按钮仍可用;零项目不能把 isAllCollapsed 当成组层已收齐。
- expect(projectsSectionSource).toContain(
- 'disabled: projectNodesToggleDisabled && !hasDeviceLayer && !hasGroupLayer',
- );
- expect(projectsSectionSource).toContain(
- 'const allVisibleProjectGroupsCollapsed = mixedEntries.every(',
- );
- expect(projectsSectionSource).toContain(
- "entry.kind !== 'project' || collapsed.has(entry.project.projectKey)",
- );
- expect(projectsSectionSource).toContain('allSessionGroupsCollapsed');
- // 平铺时来源标签要覆盖从项目摊出来的会话,不能只喂 dialogues。
- expect(projectsSectionSource).toContain('flattenedSessionsForSourceLabels');
- expect(projectsSectionSource).toContain(
- '[...projects.flatMap((project) => project.sessions), ...dialogues]',
- );
- });
-
- // 2026-08-12 用户裁决:段头「新建项目」按钮暂时移除(同一动作在新任务页的工作
- // 目录选择器仍可完成)。prop 保留但不再渲染按钮;恢复入口时把这条断言改回正向。
- it('no longer renders the create-project button in the header action group', () => {
- expect(projectsSectionSource).toContain('onCreateProject?: () => void');
- expect(projectsSectionSource).not.toContain('onClick={onCreateProject}');
- expect(projectsSectionSource).not.toContain("t('ccAgent.sidebar.newProject')");
- expect(projectsSectionSource).not.toContain('<Plus size={14} strokeWidth={2} />');
- });
-
- it('only shows project header actions while hovering or focusing the Projects header row', () => {
- const headerSource = readFileSync(
- resolve(
- __dirname,
- '..',
- 'features',
- 'cc-agent',
- 'sidebar',
- 'MainListScopeHeader.tsx',
- ),
- 'utf8',
- );
- expect(headerSource).toContain('group/sidebar-header flex h-6');
- expect(headerSource).toContain(
- 'pointer-events-none opacity-0 transition-opacity duration-150',
- );
- expect(headerSource).toContain(
- 'group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100',
- );
- expect(headerSource).toContain(
- 'has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100',
- );
- expect(headerSource).not.toContain(
- 'group-focus-within/sidebar-header:pointer-events-auto',
- );
- expect(headerSource).toContain('className={HEADER_ACTIONS_CLASS}');
- });
-
- it('the project tree renders unconditionally (section collapse removed)', () => {
- // 树不再包 SectionCollapse(设备段 / 对话组内部的仍在);项目行折叠照旧受控。
- expect(projectsSectionSource).not.toMatch(/<SectionCollapse collapsed=\{isSectionCollapsed\}>/);
- expect(projectsSectionSource).toContain('isCollapsed={collapsed.has(project.projectKey)}');
- });
-
- // 2026-08-13 review P1:优先级排序的三个集合必须并入 device-link 远程活动镜像
- // ——远程行自己的状态点亮着,排序却把它当 idle。
- it('priority context merges remote activity (running / waiting / unread)', () => {
- // 远程镜像经整表版本号订阅 + 逐 id 读(聚合组件先例)。
- expect(projectsSectionSource).toContain(
- 'const remoteActivityRevision = useRemoteSessionActivityRevision()',
- );
- expect(projectsSectionSource).toContain(
- 'getRemoteSessionActivity(session.id, session.deviceLinkDeviceId)?.phase',
- );
- // 档位映射由 sidebarPriorityContext 行为测试覆盖;排序和点击共用该入口。
- expect(projectsSectionSource).toContain('sidebarPriorityContext(');
- // 三个集合作为一个整体喂给混排模型。
- expect(projectsSectionSource).toContain('priorityContext,');
- expect(projectsSectionSource).toContain('useViewedPriorityHold(');
- expect(projectsSectionSource).toContain('holdViewedPriorityRank(');
- expect(projectsSectionSource).toContain('viewedSessionId ?? activeSessionId');
- // 折叠豁免与排序、聚合灯同一口径(含远程):attention ∪ running
- // (Greptile P1:running-only 会话不能被折进「显示全部」,否则上层
- // 呼吸灯指向不可见条目),不再用只有本地的 notifications。
- expect(projectsSectionSource).toContain(
- 'const next = new Set(priorityContext.attentionSessionIds)',
- );
- expect(projectsSectionSource).toContain(
- 'for (const id of priorityContext.runningSessionIds) next.add(id)',
- );
- expect(projectsSectionSource).toContain(
- 'entrySessions(entry).some((s) => lampFoldExemptIds.has(s.id))',
- );
- });
-
- // 2026-08-13 review P1:设备是最外层层级,折叠只能发生在段内——先全局折叠再
- // 切段会把前 N 名之外的设备连段头一起藏掉。
- it('device grouping splits the full list first, then collapses per section', () => {
- expect(projectsSectionSource).toContain(
- 'return splitEntriesByDevice(mixedEntries, [...(remoteDeviceIndex?.keys() ?? [])], {',
- );
- const start = projectsSectionSource.indexOf('const mixedUnclassified = useMemo(');
- const input = projectsSectionSource.slice(start, projectsSectionSource.indexOf('const mixedEntries', start));
- expect(start).toBeGreaterThan(-1);
- expect(input).toContain('unclassifiedHidden');
- expect(input).toContain('? []');
- expect(input).toContain('deviceGroupingActive');
- expect(input).toContain('? unclassified');
- expect(input).toContain(
- 'unclassified.filter((session) => isCindyMakeFamilySource(session.source))',
- );
- expect(input).toContain('[unclassified, unclassifiedHidden, deviceGroupingActive]');
- expect(projectsSectionSource).toContain('unclassified: mixedUnclassified,');
- // 每段独立折叠视图 + 段内作用域的「显示全部」(复核 P2:共用一个标志会让
- // 点任一段全段展开)。
- expect(projectsSectionSource).toMatch(
- /const sectionView = collapseEntries\(\s*section\.entries,\s*expandedDeviceSections\.has\(key\),\s*\)/,
- );
- expect(projectsSectionSource).toContain('{sectionView.isOverflowing && (');
- expect(projectsSectionSource).toContain(
- 'setExpandedDeviceSections((prev) => new Set(prev).add(key))',
- );
- expect(projectsSectionSource).toContain('{!deviceGroupingActive && projectsOverflow && (');
- });
-
- it('device grouping can stay on with custom project order', () => {
- expect(projectsSectionSource).toContain(
- 'const deviceGroupingActive = deviceGroupingAvailable && filter.groupDevice;',
- );
- expect(projectsSectionSource).not.toContain("filter.sortBy !== 'manual'");
- });
-
- it('renders pre-grouped automation entries as one flat-list row', () => {
- expect(projectsSectionSource).toContain(
- "entry.kind === 'session' || entry.kind === 'automation-group'",
- );
- expect(projectsSectionSource).toContain('<SessionEntryRows');
- expect(projectsSectionSource).toContain('entries={[entry]}');
- expect(projectsSectionSource).not.toContain('sessions={[entry.session]}');
- });
-
- it('includes automation groups in the header batch fold state machine', () => {
- expect(projectsSectionSource).toContain(
- "const hasGroupLayer = mixedEntries.some((entry) => entry.kind !== 'session')",
- );
- expect(projectsSectionSource).toContain('useAutomationGroupsCollapsed(');
- expect(projectsSectionSource).toContain('setAllAutomationGroupsCollapsed(true)');
- expect(projectsSectionSource).toContain('setAllAutomationGroupsCollapsed(false)');
- expect(projectsSectionSource).toContain('allAutomationGroupsCollapsed');
- expect(projectsSectionSource).toContain(
- 'automationGroupCollapsed={isAutomationGroupCollapsed}',
- );
- expect(projectsSectionSource).toContain(
- 'onAutomationGroupCollapsedChange={setAutomationGroupCollapsed}',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
deleted file mode 100644
index c3311b8345..0000000000
--- a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const read = (relativePath: string): string =>
- readFileSync(resolve(__dirname, '..', relativePath), 'utf8').replace(/\r\n/g, '\n');
-
-describe('remote Orca Worker creation context', () => {
- it('uses SSH-filtered candidates for remote-project models and provider selection', () => {
- const draft = read('features/cc-agent/NewMakerDraftRoute.tsx');
- const start = draft.indexOf('const selection = await loadSshSessionModelSelection(');
- const end = draft.indexOf('const newSession = await createSession(', start);
- expect(start).toBeGreaterThan(-1);
- const selection = draft.slice(start, end);
- expect(selection).toContain('providers: localProviders');
- expect(selection).toContain('agentKind: capabilityAgentKind');
- expect(selection).toContain('if (!selection.ok)');
- // Behavioral filtering and source pinning are covered in sshSessionModelSelection.test.ts.
- expect(selection).toContain('target.hostId');
- expect(read('components/settings/RemoteHostDetail.tsx')).toContain('loadSshSessionModelSelection(hostId)');
- });
-
- it('writes the SSH no-effort sentinel instead of omitting the session field', () => {
- const draft = read('features/cc-agent/NewMakerDraftRoute.tsx');
- const start = draft.indexOf('const newSession = await createSession(');
- const end = draft.indexOf('if (!newSession)', start);
- expect(start).toBeGreaterThan(-1);
- expect(end).toBeGreaterThan(start);
- expect(draft.slice(start, end)).toContain("effort: sshEffort ?? '',");
- });
- it('scopes capabilities, providers, and the nested model selector to the controlled device', () => {
- const popover = read('features/cc-agent/CreateWorkerPopover.tsx');
-
- expect(popover).toContain("useAgentCapabilities('claude-code', deviceId)");
- expect(popover).toContain("useAgentCapabilities('codex', deviceId)");
- expect(popover).toContain('useDeviceProviders(deviceId)');
- expect(popover).toContain(
- 'providersUnsupported: deviceId ? remoteProviders.unsupported : false',
- );
- expect(popover).toContain('!remoteModelListBlocked');
- expect(popover).toContain('deviceId={deviceId}');
- });
-
- it('blocks existing remote session sends while the model catalog is loading or failed', () => {
- const chatInput = read('components/new-chat/ChatInput.tsx');
-
- expect(chatInput).toContain('const remoteModelListStatus = resolveRemoteModelListStatus({');
- expect(chatInput).toContain("remoteModelListStatus !== 'ready'");
- expect(chatInput).toContain('if (remoteModelListBlocked) {');
- expect(chatInput).toContain('remoteModelListBlocked ||');
-
- const sendPreflightStart = chatInput.indexOf('// 预检(通用、provider-aware)');
- const sendPreflightEnd = chatInput.indexOf('// 评论截图并入发送附件', sendPreflightStart);
- expect(sendPreflightStart).toBeGreaterThan(-1);
- expect(sendPreflightEnd).toBeGreaterThan(sendPreflightStart);
- expect(chatInput.slice(sendPreflightStart, sendPreflightEnd)).toContain(
- '!(deviceLinkDeviceId && remoteProviders.unsupported)',
- );
- });
-
- it('passes the same device context through both Worker creation entry points', () => {
- const sessionView = read('features/cc-agent/CCAgentSessionView.tsx');
- const workerPanel = read('features/cc-agent/OrcaWorkerPanel.tsx');
- const workersTabBody = read(
- 'features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx',
- );
-
- expect(sessionView).toContain('deviceId={remoteDeviceId}');
- expect(workerPanel).toContain('deviceId={deviceId ?? undefined}');
- expect(workersTabBody).toContain('deviceId: ctx.deviceLinkDeviceId');
- });
-
- it('never uses the controller API key to gate a remote model row', () => {
- const selector = read('components/new-chat/ModelSelector.tsx');
-
- // 本地会话按 codex/ + hasSavedKey 准入,但该 key gate 只属于 XD 网关折扣路由,
- // 自定义(user)供应商的同前缀模型不受 Cindy 登录门禁(#1568);SSH 远程额外按订阅
- // 直连前缀禁用(不可路由)。device-link 远程在目录未就绪或真实读取失败时禁用旧行,
- // 只有明确判定老被控端不支持 provider:list 时才回退 capabilities flat list;
- // 任一远程路径都不得回退到 controller key 判定。
- expect(selector).toContain('if (!deviceId) {');
- expect(selector).toContain('if (subscriptionDirectDisabledReason(id)) return true;');
- expect(selector).toContain("if (isCustomRoutedProvider(provider)) return false;");
- expect(selector).toContain('return isCodexGatewayWireModel(id) && !hasSavedKey;');
- expect(selector).toContain("if (remoteModelListStatus !== 'ready') return true;");
- expect(selector).toContain(
- 'if (remoteProviders.error) return remoteProviders.unsupported ? false : true;',
- );
- expect(selector).toContain('const rowAgentKind = rowAgent ?? resolveVisibleModelAgentKind({');
- expect(selector).toContain('providerOffersModel(provider, id, rowAgentKind)');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/rolePillWorkerAttentionClear.test.ts b/apps/desktop/src/renderer/__tests__/rolePillWorkerAttentionClear.test.ts
deleted file mode 100644
index 7d43aa7a14..0000000000
--- a/apps/desktop/src/renderer/__tests__/rolePillWorkerAttentionClear.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'RolePillDropdown.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('RolePillDropdown worker attention clearing', () => {
- it('clears selected worker attention before paint to avoid transient selected-worker dots', () => {
- const tabsBlock = extractBetween(
- source,
- 'function WorkerTabsList({',
- 'export function WorkerListToolbar({',
- );
- const dropdownBlock = source.slice(source.indexOf('export function RolePillDropdown({'));
-
- expect(tabsBlock).toContain('useLayoutEffect(() => {');
- expect(tabsBlock).toContain('if (!clearAttentionWhenVisible) return;');
- expect(tabsBlock).toContain('clearWorkerAttention(selectedWorkerId);');
- expect(dropdownBlock).toContain('useLayoutEffect(() => {');
- expect(dropdownBlock).toContain('if (!clearAttentionWhenVisible) return;');
- expect(dropdownBlock).toContain('clearWorkerAttention(selectedWorkerId);');
- });
-
- it('threads the visibility gate from WorkerListToolbar to both worker list layouts', () => {
- const toolbarBlock = extractBetween(
- source,
- 'export function WorkerListToolbar({',
- 'export function RolePillDropdown({',
- );
-
- expect(toolbarBlock).toContain('clearAttentionWhenVisible = true');
- expect(toolbarBlock).toContain('clearAttentionWhenVisible={clearAttentionWhenVisible}');
- });
-});
-
-function extractBetween(sourceText: string, startNeedle: string, endNeedle: string): string {
- const start = sourceText.indexOf(startNeedle);
- const end = sourceText.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return sourceText.slice(start, end);
-}
diff --git a/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
index 0452d091d8..05cf56f78f 100644
--- a/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
@@ -18,8 +18,7 @@
* S3 测量镜像与收起态渲染共用 collapseMeasureBody(同一份投影,判定与呈现一致)。
* S4 previewTitle 在四种界面语言里都有,标题不复用随消息落库的 display。
*
- * 组件级契约走静态源码扫描,与 textLightbox.test.ts / imageLightboxCloseAnywhere.test.ts
- * 同一约定:把测试留在 node 环境,不为这几条接线检查拖进 jsdom + react-dom。
+ * 组件级契约走静态源码扫描,把测试留在 node 环境,不为这几条接线检查拖进 jsdom + react-dom。
*/
import { describe, it, expect } from 'vitest';
diff --git a/apps/desktop/src/renderer/__tests__/sessionImportAutoScan.test.ts b/apps/desktop/src/renderer/__tests__/sessionImportAutoScan.test.ts
deleted file mode 100644
index 31b0044c18..0000000000
--- a/apps/desktop/src/renderer/__tests__/sessionImportAutoScan.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * SessionImportSection source-level lifecycle contract tests.
- *
- * The component calls Electron IPC through preload, so this pins the first-entry
- * scan behavior without booting renderer globals.
- */
-
-import { describe, expect, it } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sourcePath = resolve(__dirname, '..', 'components', 'settings', 'SessionImportSection.tsx');
-const source = readFileSync(sourcePath, 'utf8');
-
-describe('SessionImportSection initial scan', () => {
- it('runs the existing scan path once when the import settings panel mounts', () => {
- expect(source).toContain('const initialScanStartedRef = useRef(false);');
- expect(source).toMatch(
- /useEffect\(\(\) => \{\s*if \(initialScanStartedRef\.current\) return;\s*initialScanStartedRef\.current = true;\s*void runScan\(\);\s*\}, \[runScan\]\);/,
- );
- });
-
- it('keeps the last scan result in memory so re-entering import settings renders stale data immediately', () => {
- expect(source).toContain('let cachedSessionImportScan: ScanResult | null = null;');
- expect(source).toContain('useState<ScanResult | null>(() => cachedSessionImportScan)');
- expect(source).toContain('cachedSessionImportScan = result;');
- });
-
- it('keeps project groups collapsed by default, including after an automatic refresh', () => {
- expect(source).toMatch(/const \[expanded, setExpanded\] = useState<Set<string>>\(\(\) => new Set\(\)\);/);
- expect(source).toContain('setExpanded(new Set());');
- expect(source).not.toContain('getDefaultExpandedProjectKeys');
- });
-
- it('renders dialogue imports as first-level session rows instead of expandable folder groups', () => {
- expect(source).toContain("type: 'dialogue'");
- expect(source).toContain("item.sidebarBucket !== 'project' || !item.projectDir");
- expect(source).toMatch(
- /if \(listItem\.type === 'dialogue'\)[\s\S]*<SessionImportRow[\s\S]*item=\{item\}[\s\S]*checked=\{selected\.has\(item\.key\)\}/,
- );
- });
-
- it('places project selection before the expand control and indents project child rows', () => {
- expect(source).toContain('grid min-h-14 grid-cols-[16px_20px_minmax(0,1fr)_auto] items-center gap-x-2 px-4 py-2');
- expect(source).toContain('className="flex h-6 w-5 items-center justify-center rounded-full');
- expect(source).toMatch(
- /checked=\{selectedCount === group\.items\.length\}[\s\S]*onClick=\{\(\) => toggleGroup\(group\.key\)\}/,
- );
- expect(source).toMatch(
- /<SessionImportRow[\s\S]*checked=\{selected\.has\(item\.key\)\}[\s\S]*onToggle=\{\(\) => toggleItem\(item\.key\)\}[\s\S]*isProjectChild/,
- );
- expect(source).toContain("isProjectChild ? 'pl-[40px] pr-4' : 'px-4'");
- });
-
- it('shows project basename first and full project path as secondary text', () => {
- expect(source).toContain("import { basename, cn } from '@/lib/utils';");
- expect(source).toContain('{groupProjectName(group.items[0], t)}');
- expect(source).toContain("{group.items.length} {t('settings.sessionImport.sessions')} · {groupProjectPath(group.items[0], t)}");
- expect(source).toContain('return basename(item.projectDir) || item.projectDir;');
- });
-
- it('offers a select-all control scoped to the visible (filtered) candidates', () => {
- expect(source).toMatch(
- /const toggleAllVisible = useCallback\(\(\) => \{[\s\S]*for \(const item of visibleCandidates\)/,
- );
- expect(source).toContain(
- "{t('settings.sessionImport.selectAll', { count: visibleCandidates.length })}",
- );
- expect(source).toMatch(
- /checked=\{visibleCandidates\.length > 0 && visibleSelectedCount === visibleCandidates\.length\}/,
- );
- });
-
- it('keeps scan summary explanations visible instead of relying on pointer-only title tooltips', () => {
- expect(source).toContain('mt-1 text-11 leading-[1.4] text-[var(--settings-section-desc)]');
- expect(source).toMatch(/>\s*\{hint\}\s*<\/p>/);
- expect(source).not.toContain('title={hint}');
- expect(source).not.toContain('className="sr-only">{hint}</span>');
- });
-
- it('surfaces selections hidden by the current filters next to the import button', () => {
- expect(source).toContain('const hiddenSelectedCount = selectedItems.length - visibleSelectedCount;');
- expect(source).toMatch(
- /\{hiddenSelectedCount > 0 && \([\s\S]*selectedOutsideFilter[\s\S]*count: hiddenSelectedCount/,
- );
- });
-
- it('keeps metadata pills on one line and lets long session titles truncate instead of stretching rows', () => {
- expect(source).toContain(
- 'shrink-0 whitespace-nowrap rounded-full border border-[var(--settings-input-border)]',
- );
- expect(source).toContain(
- 'min-w-0 flex-1 truncate text-13 font-medium text-[var(--settings-section-sublabel)]',
- );
- });
-
- it('uses the sidebar time formatter for project and session-row timestamps', () => {
- expect(source).toContain(
- "import { formatSidebarTime, formatSidebarTimeAbsolute } from '@/features/cc-agent/lib/formatSidebarTime';",
- );
- expect(source).toContain('const latestUpdatedAt = group.items[0]?.updatedAt;');
- expect(source).toContain('dateTime={latestUpdatedAt}');
- expect(source).toContain('title={formatSidebarTimeAbsolute(latestUpdatedAt)}');
- expect(source).toContain('{formatSidebarTime(latestUpdatedAt, t)}');
- expect(source).toContain('dateTime={item.updatedAt}');
- expect(source).toContain('title={formatSidebarTimeAbsolute(item.updatedAt)}');
- expect(source).toContain('{formatSidebarTime(item.updatedAt, t)}');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts
deleted file mode 100644
index 878041b9d5..0000000000
--- a/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * 桌面端「未起名会话标题」投影的出口清单。
- *
- * 不变量:会话标题的每个**用户可见**出口都必须过投影(`getSessionDisplayTitle` /
- * `projectDraftSessionTitle` / `conversationSearchTitle`,三者共用
- * `isDefaultDraftSessionTitle` 这一个判据),内部哨兵 `New Maker` 一处都不许原样渲染;
- * 且投影只发生在渲染那一刻,不提前固化进 state / 缓存。
- *
- * 侧边栏行 / 卡片 / 会话头 / tab 有各自的行为测试;这里钉住那些散在大组件里、
- * 没有独立渲染基座的出口(rail 置顶瓷砖、聊天里的会话 chip、等待横幅、通知 payload),
- * 让「只修了一半」在测试里立刻可见 —— 本 PR 前四轮 review 反复栽在这上面。
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const RENDERER_ROOT = resolve(__dirname, '..');
-
-function read(relPath: string): string {
- return readFileSync(resolve(RENDERER_ROOT, relPath), 'utf8').replace(/\r\n/g, '\n');
-}
-
-const railNav = read('features/cc-agent/sidebar/RailNav.tsx');
-const linkChip = read('components/chat/SessionLinkChip.tsx');
-const waitBanner = read('components/chat/CredentialSwitchWaitBanner.tsx');
-const sidebarUpper = read('features/cc-agent/CCAgentSidebarUpper.tsx');
-const draftRoute = read('features/cc-agent/NewMakerDraftRoute.tsx');
-
-describe('desktop 会话标题投影出口', () => {
- it('rail 置顶瓷砖、aria-label 与悬浮预览卡都用显示标题', () => {
- expect(railNav).toContain(
- "const displayTitle = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'), t);",
- );
- expect(railNav).toContain('aria-label={displayTitle}');
- expect(railNav).toContain('{pinnedTileLabel(displayTitle)}');
- // 短标签会把 "New Maker" 截成 "New",比整串更难看出问题 —— 原始 title 不许再出现。
- expect(railNav).not.toContain('pinnedTileLabel(session.title)');
- expect(railNav).not.toContain('aria-label={session.title}');
- });
-
- it('聊天里的会话 chip 过投影', () => {
- expect(linkChip).toContain("projectDraftSessionTitle(resolvedTitle, t('ccAgent.common.unnamedSession'))");
- });
-
- it('凭证等待横幅在渲染时投影,state 里仍存原始标题', () => {
- expect(waitBanner).toContain(
- "projectDraftSessionTitle(title, t('ccAgent.common.unnamedSession'))",
- );
- // 投影固化进 state 就意味着切语言后要重新拉一遍标题才会变(本 PR 第 8 条不变量)。
- expect(waitBanner).toContain('setBlockerTitles(titles.filter(');
- expect(waitBanner).toContain('.then((session) => session.title?.trim() || null)');
- });
-
- // 乐观预览必须有失败路径:交接失败(消息退回草稿 / setGoal 抛错)时权威标题永不回流,
- // 不撤回就会永久盖着 DB 里的哨兵,会话显示一句**没发出去**的话。
- it('新建会话的两条交接失败路径都撤回标题预览', () => {
- // worktree 分支:所有「交接失败 → 还原草稿」的 return 都过 restoreFirstMessageDraft,
- // 撤回放在那一处而不是各 return 前。
- expect(draftRoute).toContain('emitAutoTitlePreviewCleared(newSession.id);');
- const restoreFn = draftRoute.indexOf('const restoreFirstMessageDraft = () => {');
- const clearInRestore = draftRoute.indexOf('emitAutoTitlePreviewCleared(newSession.id);', restoreFn);
- const restoreFnEnd = draftRoute.indexOf('};', restoreFn);
- expect(restoreFn).toBeGreaterThan(-1);
- expect(clearInRestore).toBeGreaterThan(restoreFn);
- expect(clearInRestore).toBeLessThan(restoreFnEnd);
-
- // goal 分支:setGoal 抛错时撤回后照旧把异常抛给调用方。
- expect(draftRoute).toContain('if (optimisticGoalTitle) emitAutoTitlePreviewCleared(newSession.id);');
-
- // 普通 send 分支:rehomeDraftAttachments / setPending / navigate 在登记之后抛错时,
- // 由外层 catch 撤回(它拿不到 newSession,靠 optimisticTitleSessionId 记住)。
- expect(draftRoute).toContain('let optimisticTitleSessionId: string | null = null;');
- expect(draftRoute).toContain(
- 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);',
- );
- expect(draftRoute).toContain('let remoteOptimisticTitleSessionId: string | null = null;');
- expect(draftRoute).toContain(
- 'remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);',
- );
- // 远程归属切换会提前 return,撤回必须排在它前面,否则空会话会一直顶着没发出去的原文。
- const remotePreviewClear = draftRoute.indexOf(
- 'remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);',
- );
- const ownerChangedReturn = draftRoute.indexOf(
- 'if (isRemotePrecreatedWorktreeOwnerChangedError(err)) return;',
- remotePreviewClear,
- );
- expect(remotePreviewClear).toBeGreaterThan(-1);
- expect(ownerChangedReturn).toBeGreaterThan(remotePreviewClear);
- // createSession 返回 null 是 return,不进外层 catch,必须就地撤回。
- expect(draftRoute).toContain(
- 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);\n toastCreateSessionFailed();',
- );
- expect(draftRoute).toContain(
- 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);\n toastCreateSessionFailed();',
- );
- expect(draftRoute).toContain(
- 'if (optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);',
- );
- const goalCatch = draftRoute.indexOf('} catch (error) {\n // 预览在 createSession 之前登记。');
- expect(goalCatch).toBeGreaterThan(-1);
- expect(draftRoute.indexOf(
- 'if (goalSessionId && optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);',
- goalCatch,
- )).toBeGreaterThan(goalCatch);
- // 预览必须在本机发送路径的 createSession 之前登记,否则 sessions:created
- // 刷新会先画出「未命名任务」。文件前段还有 SSH / 远程建会话,不能拿第一处 create。
- const previewBeforeCreate = draftRoute.indexOf('emitAutoTitlePreview(sessionId, optimisticTitle)');
- const sendCreate = draftRoute.indexOf('const newSession = await createSession({', previewBeforeCreate);
- expect(previewBeforeCreate).toBeGreaterThan(-1);
- expect(sendCreate).toBeGreaterThan(previewBeforeCreate);
- // 纯附件远程预览必须登记成系统合成标题,否则后续第一句文字无法即时覆盖。
- expect(draftRoute).toContain('Boolean(normalizeAutoTitle(message))');
- });
-
- it('系统通知 / 飞书 / 手机推送的标题过投影,且语言走 ref 不被钉在首次渲染', () => {
- expect(sidebarUpper).toContain(
- 'const title = projectDraftSessionTitle(session.title, unnamedLabelRef.current);',
- );
- // /review Reviewer tasks are checked first: they never notify on their own.
- expect(sidebarUpper).toContain('if (await isReviewSessionNotificationTarget(sessionId)) return;');
- expect(sidebarUpper).toContain('const botTitle = await botOwnedSessionNotificationTitle(sessionId);');
- // The task sidebar is the only notification owner, also on /bots routes: group
- // lanes never notify (docs/product-rules/bot-group-chat.md §3).
- expect(sidebarUpper).toContain('if (botTitle === BOT_GROUP_LANE_SESSION) return;');
- expect(sidebarUpper).toContain(
- 'sendSessionEventNotification(sessionId, botTitle ?? unnamedLabelRef.current, kind);',
- );
- expect(sidebarUpper).toContain("unnamedLabelRef.current = t('ccAgent.common.unnamedSession');");
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/sidebarActiveSessionAutoVisible.test.ts b/apps/desktop/src/renderer/__tests__/sidebarActiveSessionAutoVisible.test.ts
deleted file mode 100644
index 98c5def7bf..0000000000
--- a/apps/desktop/src/renderer/__tests__/sidebarActiveSessionAutoVisible.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * sidebarActiveSessionAutoVisible — 源码模式断言
- *
- * 锁住"active session 自动可见"链路上几个关键的 hand-wired 行为。这些都是
- * React 组件 / 浏览器 API 副作用,缺乏纯函数表面,所以走静态扫描风格,与
- * sidebarUpperSingleButton.test.ts / sidebarAttentionBadge.test.ts 一致 ——
- * 不依赖 jsdom / RTL,仅锁住"删了 / 改错顺序了不知道"类的回归。
- *
- * 覆盖点:
- * 1. SessionItem 在 isActive 切到 true 时 scrollIntoNearestView,且元素
- * 暴露 data-session-id 给外部 imperative scroll 用
- * 2. scrollIntoNearestView helper 用 block:'nearest' + 防御式
- * prefers-reduced-motion 检测,reduce 时降级为 instant
- *
- * 注:ProjectNode 旧的「项目级搜索点击先 ensure 展开」覆盖点已随 main 移除项目级
- * 搜索(改为复用全局对话搜索入口)而删除,对应断言一并下线。
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sessionItemSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'SessionItem.tsx'),
- 'utf8',
-);
-
-const scrollHelperSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'lib', 'scrollIntoNearestView.ts'),
- 'utf8',
-);
-
-describe('SessionItem — active 行自动滚进 viewport', () => {
- it('useEffect 依赖只含 isActive(避免无关 re-render 反复滚动)', () => {
- expect(sessionItemSource).toMatch(/scrollIntoNearestView\(rowRef\.current\)[\s\S]*?\}, \[isActive\]\)/);
- });
-
- it('外层 div 暴露 data-session-id 供外部 imperative scroll 选中', () => {
- expect(sessionItemSource).toMatch(/data-session-id=\{session\.id\}/);
- });
-});
-
-describe('scrollIntoNearestView — 共用 helper', () => {
- it('调用 scrollIntoView 且 block: "nearest"(已可见时无副作用)', () => {
- expect(scrollHelperSource).toMatch(/scrollIntoView\(\{[\s\S]*?block:\s*['"]nearest['"]/);
- });
-
- it('a11y 防御:matchMedia 检测 prefers-reduced-motion: reduce', () => {
- expect(scrollHelperSource).toMatch(/matchMedia/);
- expect(scrollHelperSource).toMatch(/prefers-reduced-motion:\s*reduce/);
- });
-
- it('reduceMotion 时降级为 instant,否则 smooth(防止有人写死)', () => {
- expect(scrollHelperSource).toMatch(/behavior:\s*\w+\s*\?\s*['"]auto['"]\s*:\s*['"]smooth['"]/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/sidebarClearsAppBadge.test.ts b/apps/desktop/src/renderer/__tests__/sidebarClearsAppBadge.test.ts
deleted file mode 100644
index 84b7c3448f..0000000000
--- a/apps/desktop/src/renderer/__tests__/sidebarClearsAppBadge.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sidebarSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
-);
-
-describe('sidebar clears system app badge', () => {
- it('clears task-completion app badge when a session is opened', () => {
- // 统一走 clearSystemSessionAttention 咽喉:本机 IPC 恒发,device-link 远程会话
- // 再补隧道回执把被控端未读一并清掉(见 sessionAttentionStore)。
- expect(sidebarSource).toContain('clearSystemSessionAttention(viewedSessionId)');
- expect(sidebarSource).toContain('clearSystemSessionAttention(id)');
- // 不允许退回绕过咽喉的裸 IPC 调用(那会丢远程回执路由)。
- expect(sidebarSource).not.toContain('notificationClearSessionAttention(');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts
deleted file mode 100644
index aa91c2f286..0000000000
--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const sidebarDir = resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar');
-const projectNodeSource = readFileSync(resolve(sidebarDir, 'sections', 'ProjectNode.tsx'), 'utf8');
-const projectsSectionSource = readFileSync(
- resolve(sidebarDir, 'sections', 'ProjectsSection.tsx'),
- 'utf8',
-);
-const sessionItemSource = readFileSync(resolve(sidebarDir, 'SessionItem.tsx'), 'utf8');
-const sessionCardSource = readFileSync(resolve(sidebarDir, 'SessionCard.tsx'), 'utf8');
-const remoteProjectIconSource = readFileSync(resolve(sidebarDir, 'RemoteProjectIcon.tsx'), 'utf8');
-const sessionHeaderSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'SessionContentHeader.tsx'),
- 'utf8',
-);
-
-describe('sidebar remote project icon', () => {
- it('uses one shared icon component for project headers and remote session rows', () => {
- expect(projectNodeSource).toContain("import { RemoteProjectIcon } from '../RemoteProjectIcon'");
- expect(sessionItemSource).toContain("import { RemoteProjectIcon } from './RemoteProjectIcon'");
- expect(sessionCardSource).toContain("import { RemoteProjectIcon } from './RemoteProjectIcon'");
- expect(sessionHeaderSource).toContain(
- "import { RemoteProjectIcon } from './sidebar/RemoteProjectIcon'",
- );
- });
-
- it('maps device-link sessions to the device-link project icon and SSH sessions to the SSH project icon', () => {
- expect(remoteProjectIconSource).toMatch(
- /kind === 'device-link'\s+\?\s+MonitorSmartphone\s+:\s+Globe/,
- );
- // Agent 在另一台电脑运行的本机任务不冒充远程设备任务:标识画在左侧 Agent 图标上
- // (信号波纹,见 remoteAgentVendorIcon.test.tsx),标题后不再另放芯片图标(2026-10-07)。
- expect(remoteProjectIconSource).not.toContain('agent-device');
- expect(remoteProjectIconSource).not.toContain('Cpu');
- expect(sessionItemSource).not.toContain('kind="agent-device"');
- expect(sessionCardSource).not.toContain('kind="agent-device"');
- expect(sessionHeaderSource).not.toContain('kind="agent-device"');
- expect(sessionItemSource).toMatch(
- /const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,
- );
- expect(sessionCardSource).toMatch(
- /const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,
- );
- expect(sessionHeaderSource).toMatch(
- /const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,
- );
- });
-
- it('does not use the generic link icon for remote session markers', () => {
- expect(sessionItemSource).not.toContain('Link2');
- expect(sessionCardSource).not.toContain('Link2');
- });
-
- it('renders a disconnected state through the shared remote icon', () => {
- expect(remoteProjectIconSource).toContain('MonitorOff');
- expect(remoteProjectIconSource).toContain("connectionStatus === 'disconnected'");
- expect(projectNodeSource).toContain('connectionStatus={project.deviceLinkConnectionStatus}');
- expect(sessionItemSource).toContain('connectionStatus={remoteIconConnectionStatus}');
- expect(sessionCardSource).toContain('connectionStatus={remoteIconConnectionStatus}');
- expect(sessionHeaderSource).toContain('connectionStatus={remoteIconConnectionStatus}');
- });
-
- it('does not let nested card controls keyboard-activate the session row', () => {
- expect(sessionCardSource).toContain('if (e.target !== e.currentTarget) return');
- });
-
- it('keeps remote session icons next to titles instead of in the right-side time slots', () => {
- expect(sessionItemSource).toMatch(
- /<span[\s\S]*?className="min-w-0 flex flex-1 items-center gap-1\.5"[\s\S]*?<SidebarTitleMarquee[\s\S]*?\{remoteIconKind && \([\s\S]*?<RemoteProjectIcon/,
- );
- // C 期起右侧时间槽由 SessionInfoMeta 承担(任务信息复选),仍在同一让位容器内。
- expect(sessionItemSource).toMatch(
- /<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end">[\s\S]*?<SessionInfoMeta[\s\S]*?worktree=\{infoWorktree \?\? undefined\}/,
- );
- expect(sessionCardSource).toContain('function TimeActionsSlot');
- expect(sessionCardSource).not.toMatch(/function TimeActionsSlot[\s\S]*?remoteIconKind/);
- });
-
- it('lets the title text shrink before the adjacent remote icon instead of pushing the icon to the row edge', () => {
- expect(sessionItemSource).toContain(
- 'className="sidebar-title-marquee min-w-0 max-w-full shrink overflow-hidden"',
- );
- expect(sessionItemSource).not.toContain('<span className="min-w-0 flex-1 truncate">');
- expect(sessionCardSource).not.toContain("'min-w-0 flex-1 truncate'");
- // 项目行同规(2026-08-12 用户裁决):项目名 shrink 而非 flex-1,远程图标紧跟
- // 名字而不是被推到行尾。
- expect(projectNodeSource).toContain(
- '<span className="min-w-0 max-w-full shrink truncate">{project.displayName}</span>',
- );
- expect(projectNodeSource).not.toContain(
- '<span className="min-w-0 flex-1 truncate">{project.displayName}</span>',
- );
- });
-
- // 2026-08-12 用户裁决:设备段头的条数去掉——它数的是顶层条目(项目行 + 散排对话
- // + 对话组)而非任务数,读起来只会误导。右侧后来改为灯组容器(聚合未读点 +
- // 「离线」标注,2026-08 未读聚合灯),ml-auto 靠右语义由容器承接。
- it('drops the entry count from the device group header', () => {
- expect(projectsSectionSource).not.toContain('{section.entries.length}');
- expect(projectsSectionSource).toContain(
- '<span className="ml-auto flex shrink-0 items-center gap-1.5">',
- );
- expect(projectsSectionSource).toContain(
- '<span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">',
- );
- });
-
- // 2026-08-17 用户裁决:绿点容易被误认成未读标记。在线是设备段的常态,不额外画点;
- // 离线仍保留灰点 + 文字,异常状态不能静默。
- it('shows a status dot only for offline device group headers', () => {
- expect(projectsSectionSource).not.toContain('bg-[var(--card-status-done)]');
- expect(projectsSectionSource).toMatch(
- /\{!online && \([\s\S]*?bg-\[var\(--text-tertiary\)\][\s\S]*?\)\}/,
- );
- expect(projectsSectionSource).toContain("t('ccAgent.sidebar.deviceGroup.offline')");
- });
-
- // 2026-08-12 用户裁决:按设备分组时列表已按设备切段、段头写着设备名,项目行不再
- // 重复标注归属;远程图标保留(表达「远程 + 连接状态」,不重复归属信息)。
- it('drops the per-row machine label while device grouping is active, keeping the remote icon', () => {
- expect(projectNodeSource).toContain('hideRemoteMachineLabel = false');
- expect(projectNodeSource).toContain(
- '{!isEditingName && remoteIdentity && !hideRemoteMachineLabel ? (',
- );
- // 远程图标的渲染条件不受该开关影响。
- expect(projectNodeSource).toMatch(/\{!isEditingName && isDeviceLink \? \(/);
- expect(projectsSectionSource).toContain('hideRemoteMachineLabel={deviceGroupingActive}');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts b/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
deleted file mode 100644
index 82b951a5b0..0000000000
--- a/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n/g, '\n');
-
-describe('slash palette empty-result keyboard guard', () => {
- it('captures Enter and Tab while the slash palette is open with no focused result', () => {
- const selectionBlock = chatInputSource.slice(
- chatInputSource.indexOf("case 'Enter':"),
- chatInputSource.indexOf("case 'Escape':", chatInputSource.indexOf("case 'Enter':")),
- );
-
- expect(selectionBlock).toContain('if (slashOpen) {');
- expect(selectionBlock).toContain('const focusedCommand = filteredCommands[slashFocus];');
- expect(selectionBlock).toContain('if (!focusedCommand) {');
- expect(selectionBlock).toContain("if (trigger.kind === 'slash') setSuppressedSlashAt(trigger.from);");
- expect(selectionBlock.indexOf('return true;')).toBeLessThan(
- selectionBlock.indexOf('if (\n atOpen'),
- );
- });
-
- it('inserts the human command name so Pi runtime aliases stay off the display layer', () => {
- const insertBlock = chatInputSource.slice(
- chatInputSource.indexOf('const insertSlashCommand = useCallback'),
- chatInputSource.indexOf('const resolveEffectiveAtRange'),
- );
- expect(insertBlock).toContain('cmd.name');
- expect(insertBlock).not.toContain('slashCommandInvocationName');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/textLightbox.test.ts b/apps/desktop/src/renderer/__tests__/textLightbox.test.ts
index 8b702f6c7c..0ba028aaa7 100644
--- a/apps/desktop/src/renderer/__tests__/textLightbox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/textLightbox.test.ts
@@ -6,8 +6,7 @@ import '../themes/colors';
* Regression tests for: text-lightbox (2026-04-19)
*
* The component lives at components/chat/TextLightbox.tsx. Static-source
- * scanning matches the project convention (see imageLightboxCloseAnywhere.test.ts
- * and userInfoSectionHover.test.ts) — keeps tests in the Node vitest env
+ * scanning matches the project convention for small source contracts — keeps tests in the Node vitest env
* and avoids dragging in jsdom + react-dom for these contract checks.
*
* Contracts asserted:
diff --git a/apps/desktop/src/renderer/__tests__/textLightboxCodeMirrorPreview.test.ts b/apps/desktop/src/renderer/__tests__/textLightboxCodeMirrorPreview.test.ts
deleted file mode 100644
index 5cf3159e8a..0000000000
--- a/apps/desktop/src/renderer/__tests__/textLightboxCodeMirrorPreview.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * textLightboxCodeMirrorPreview.test.ts
- * ---------------------------------------------------------------------------
- * TextLightbox 的 text/code 预览必须复用项目已有 CodeMirror 引擎,避免手写
- * 虚拟滚动和异步 DOM 替换造成打开、滚动时的视觉跳变。
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const sourcePath = resolve(__dirname, '..', 'components', 'chat', 'TextLightbox.tsx');
-const source = readFileSync(sourcePath, 'utf8');
-
-describe('TextLightbox — CodeMirror text/code preview', () => {
- it('uses PlaintextEditor as the read-only preview engine for text and code files', () => {
- expect(source).toMatch(/PlaintextEditor[\s\S]*PlaintextEditorHandle/);
- expect(source).toMatch(/<PlaintextEditor[\s\S]*readOnly[\s\S]*initialValue=\{loadState\.content\}/);
- expect(source).toMatch(/language=\{renderable\.kind === 'code' \? renderable\.lang : undefined\}/);
- });
-
- it('routes path:line jumps for text/code through CodeMirror instead of manual scrollTop math', () => {
- expect(source).toContain('editorRef.current?.scrollToLine(line)');
- expect(source).not.toContain('computeLineScrollTop(line, lineHeight)');
- });
-
- it('does not keep the hand-written virtual text renderer or worker highlight path', () => {
- expect(source).not.toContain('buildVirtualTextRows');
- expect(source).not.toContain('getVirtualTextWindow');
- expect(source).not.toContain('virtualHighlightedHtml');
- expect(source).not.toContain('createHighlightWorker');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/textLightboxLineScroll.test.ts b/apps/desktop/src/renderer/__tests__/textLightboxLineScroll.test.ts
index 3955486b6f..3d9f794286 100644
--- a/apps/desktop/src/renderer/__tests__/textLightboxLineScroll.test.ts
+++ b/apps/desktop/src/renderer/__tests__/textLightboxLineScroll.test.ts
@@ -10,8 +10,7 @@
* and exercised here directly:
* - pickSourceLineAnchor: which `[data-source-line]` block to jump to.
*
- * text/code 的 `path:line` 由 PlaintextEditor.scrollToLine 承担;对应契约
- * 见 textLightboxCodeMirrorPreview.test.ts。
+ * text/code 的 `path:line` 由 PlaintextEditor.scrollToLine 承担。
*
* Lives in its own file (not textLightbox.test.ts) so the line-scroll feature's
* tests stay scoped to this MR and don't entangle with that file's existing
diff --git a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
deleted file mode 100644
index f913279c1e..0000000000
--- a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * thumbnailClickPreview.test.ts
- * ---------------------------------------------------------------------------
- * Regression test for: attachment-thumb-click (2026-04-19)
- *
- * The composer attachment thumbnails (image + file) must:
- * 1) advertise a hand cursor (`cursor-pointer`) on hover, and
- * 2) open the same overlay used in the message stream on click —
- * image → ImageLightbox
- * other → TextLightbox
- *
- * Previously the thumbnail only showed a hover preview tooltip and had no
- * click-to-open affordance. This test pins the wiring at the source level so
- * a future refactor can't silently regress to "hover-only" behaviour.
- *
- * The tray lives in ComposerAttachments.tsx (shared by ChatInput and the bot
- * group chat composer).
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-// 归一化 CRLF → LF:Windows autocrlf=true 检出下工作树是 CRLF,
-// 而下面的 indexOf 子串里内嵌裸 \n,不归一化会在 Windows 上误报失败。
-const chatInput = readFileSync(
- resolve(
- __dirname,
- '..',
- 'components',
- 'new-chat',
- 'ComposerAttachments.tsx',
- ),
- 'utf8',
-).replace(/\r\n/g, '\n');
-
-describe('Attachment thumbnail — click opens lightbox (attachment-thumb-click)', () => {
- it('imports the same lightboxes UserMessage uses', () => {
- expect(chatInput).toMatch(
- /import\s+\{\s*ImageLightbox\s*\}\s+from\s+'@\/components\/chat\/ImageLightbox'/,
- );
- // 该模块还导出 formatBytes(文件卡的大小副行复用它),所以这里只钉
- // TextLightbox 在具名导入列表里,不锁死整条 import 的成员组成。
- expect(chatInput).toMatch(
- /import\s+\{[^}]*\bTextLightbox\b[^}]*\}\s+from\s+'@\/components\/chat\/TextLightbox'/,
- );
- });
-
- it('uses the shared image hover preview so composer and message chips stay identical', () => {
- expect(chatInput).toContain(
- "import { ImageHoverPreview } from '@/components/chat/ImageHoverPreview';",
- );
- const startIdx = chatInput.indexOf('function ThumbnailItem');
- const block = chatInput.slice(startIdx);
- expect(block).toContain('<ImageHoverPreview');
- expect(block).toContain('open={isHovered}');
- expect(block).toContain('anchorRef={thumbRef}');
- });
-
- it('ThumbnailItem preview button uses cursor-pointer (hand) and an onClick handler', () => {
- // Slice the ThumbnailItem function body so we don't accidentally match
- // some other unrelated `cursor-pointer` token elsewhere in the file.
- const startMarker = 'function ThumbnailItem';
- const startIdx = chatInput.indexOf(startMarker);
- expect(startIdx).toBeGreaterThan(-1);
- // ThumbnailItem is the last component in the file; slice to EOF.
- const block = chatInput.slice(startIdx);
-
- // The preview button carries the hand cursor; the outer wrapper owns the
- // hover boundary so moving onto the remove button does not hide the preview.
- expect(block).toContain("isDownloadOnly ? 'cursor-default' : 'cursor-pointer'");
- expect(block).toContain('disabled={isDownloadOnly}');
-
- // A click handler that delegates to handleOpenPreview must exist.
- expect(block).toMatch(/onClick=\{handleOpenPreview\}/);
-
- // The preview branch must distinguish image vs. other and mount the
- // matching lightbox (the assertion that locks the parity with
- // UserMessage's behaviour).
- expect(block).toMatch(/file\.category === 'image'/);
- expect(block).toMatch(/<ImageLightbox\s+src=\{lightboxSrc\}/);
- expect(block).toMatch(/<TextLightbox[\s\S]+filePath=\{file\.path\}/);
- expect(block).toMatch(
- /if \(isDownloadOnly\) return;[\s\S]+shouldOpenTextLightbox\(file\.path\)/,
- );
- });
-
- it('keeps thumbnail hover state on the outer wrapper so the remove button does not dismiss preview', () => {
- const startIdx = chatInput.indexOf('function ThumbnailItem');
- const block = chatInput.slice(startIdx);
- const wrapperStart = block.indexOf('<div\n ref={thumbRef}');
- expect(wrapperStart).toBeGreaterThan(-1);
- const wrapperOpenTag = block.slice(wrapperStart, block.indexOf('{/* Thumbnail content */}', wrapperStart));
- const previewButtonStart = block.indexOf('<button', wrapperStart);
- expect(previewButtonStart).toBeGreaterThan(wrapperStart);
- const previewButtonOpenTag = block.slice(previewButtonStart, block.indexOf('{file.category', previewButtonStart));
-
- expect(wrapperOpenTag).toContain('onPointerEnter={() => setIsHovered(true)}');
- expect(wrapperOpenTag).toContain('onPointerLeave={() => setIsHovered(false)}');
- expect(previewButtonOpenTag).not.toContain('onPointerEnter={() => setIsHovered(true)}');
- expect(previewButtonOpenTag).not.toContain('onPointerLeave={() => setIsHovered(false)}');
- });
-
- it('Opening the lightbox dismisses the hover preview/tooltip (no leftover popover)', () => {
- // Bug repro: clicking a thumbnail opens the lightbox but the hover
- // popover (image preview portal) and the file-path tooltip stay visible
- // behind it — the moment the lightbox fades out they pop back into view
- // because the cursor never left the thumbnail. The fix resets isHovered
- // inside handleOpenPreview so the popover unmounts immediately.
- const startIdx = chatInput.indexOf('function ThumbnailItem');
- const block = chatInput.slice(startIdx);
- // handleOpenPreview must call setIsHovered(false) BEFORE choosing which
- // lightbox to mount — otherwise the popover lingers for at least one
- // render after the lightbox closes.
- const openIdx = block.indexOf('const handleOpenPreview');
- expect(openIdx).toBeGreaterThan(-1);
- const openBody = block.slice(openIdx, block.indexOf('}, [file]);', openIdx));
- expect(openBody).toMatch(/setIsHovered\(false\)/);
- // And the call must precede the image / file branches so it always runs.
- const resetAt = openBody.indexOf('setIsHovered(false)');
- const branchAt = openBody.indexOf("file.category === 'image'");
- expect(resetAt).toBeGreaterThan(-1);
- expect(branchAt).toBeGreaterThan(resetAt);
- });
-
- it('Remove (×) button still stops propagation so it does not open the lightbox', () => {
- // The × button stopPropagation contract was already in place; pin it so
- // future edits don't accidentally let the parent onClick fire and open
- // a lightbox right after the user removed the file.
- const startIdx = chatInput.indexOf('function ThumbnailItem');
- const block = chatInput.slice(startIdx);
- // The remove button's onClick must call stopPropagation BEFORE onRemove.
- expect(block).toMatch(/e\.stopPropagation\(\);\s*onRemove\(file\.id\)/);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/toastColors.test.ts b/apps/desktop/src/renderer/__tests__/toastColors.test.ts
deleted file mode 100644
index 9c27db0160..0000000000
--- a/apps/desktop/src/renderer/__tests__/toastColors.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * toastColors.test.ts
- * ---------------------------------------------------------------------------
- * E5D 状态色定稿落地(扩簇)2026-07-17:Toast 四色(info/success/warning/error)
- * 原Toast 列为 docs/design-rules/cindy-design-system.md §2 语义豁免(B 组,跨主题 hardcode)。设计师 R3 A 组
- * 扩充定稿后豁免解除,四色并入状态色族:
- * info #417CDD / success #2AAE5B / warning #F3A115 / error #D91F37
- * 与全局状态色同值(success=done 绿、error=状态族 error、warning=warning 前景)。
- *
- * 本测试直接断言 VARIANT_MAP 颜色字面量,防漂移。Toast 豁免解除后纳入定稿合同。
- */
-import { describe, it, expect } from 'vitest';
-import { VARIANT_MAP } from '@/components/ui/toast/Toast';
-
-describe('E5D Toast 四色定稿(2026-07-17,豁免解除)', () => {
- const FINAL: Record<string, string> = {
- info: '#417CDD',
- success: '#2AAE5B',
- warning: '#F3A115',
- error: '#D91F37',
- };
-
- for (const [variant, hex] of Object.entries(FINAL)) {
- it(`Toast.${variant} color = 定稿 ${hex}`, () => {
- expect(
- VARIANT_MAP[variant as keyof typeof VARIANT_MAP]?.color,
- `${variant} 应为定稿 ${hex}`,
- ).toBe(hex);
- });
- }
-
- it('Toast 包含中性 loading 与四种状态提示', () => {
- expect(Object.keys(VARIANT_MAP).sort()).toEqual(['error', 'info', 'loading', 'success', 'warning']);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/toastZIndex.test.ts b/apps/desktop/src/renderer/__tests__/toastZIndex.test.ts
index 0dd889a297..b6dfa84c28 100644
--- a/apps/desktop/src/renderer/__tests__/toastZIndex.test.ts
+++ b/apps/desktop/src/renderer/__tests__/toastZIndex.test.ts
@@ -9,8 +9,7 @@
* even when Modals + Lightboxes are stacked in document.body via Portals,
* ToastContainer is above the z-[10000] Radix Dialog layer at 10100.
*
- * Static-source scanning (matches the project convention used by
- * textLightbox.test.ts and imageLightboxCloseAnywhere.test.ts).
+ * Static-source scanning follows the existing renderer contract-test convention.
*/
import { describe, it, expect } from 'vitest';
diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts
deleted file mode 100644
index 27bc16c939..0000000000
--- a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * userInfoSectionHover.test.ts
- * ---------------------------------------------------------------------------
- * Regression test for: user-message-selected-full-row-bg (回路 #2, 方案 D)
- *
- * Current contract: UserInfoSection follows the CREATE AGENT sidebar capsule
- * design. Flame keeps a .flame-btn marker class, but it now sits inside the
- * compact account pill instead of the old 66px full-row footer.
- *
- * 这份测试做静态源码扫描,确保以下契约不被未来的提交悄悄回退:
- * 1. 外层 div keeps the sidebar footer slot, while the visible account card is
- * the rounded tokenized capsule.
- * 2. 内部主按钮不再有 hover:bg-sidebar-item-hover (避免双层叠色)
- * 3. Flame button className 列表带有 'flame-btn' 标识符 (供 :has() 选择器钩取)
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-const sourcePath = resolve(__dirname, '..', 'components', 'sidebar', 'UserInfoSection.tsx');
-const source = readFileSync(sourcePath, 'utf8');
-const localePath = resolve(__dirname, '..', 'i18n', 'locales', 'zh-CN', 'common.json');
-const locale = JSON.parse(readFileSync(localePath, 'utf8')) as {
- sidebar: {
- user: {
- settingsLink: string;
- settingsLinkBeta: string;
- moreLabel: string;
- canaryBadge: string;
- downloadMobile: string;
- };
- mobileDownload: { title: string };
- };
-};
-
-// ── 改动 1: 外层 footer slot + tokenized account capsule ────────────────
-
-describe('UserInfoSection — outer wrapper takes over full-row hover', () => {
- it('outer div keeps the sidebar footer slot', () => {
- expect(source).toContain('mt-auto px-3 pb-3 pt-2');
- });
-
- it('visible user card uses the rounded tokenized capsule style', () => {
- expect(source).toContain(
- 'flex h-10 items-center rounded-full border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)] px-[7px]',
- );
- });
-
- it('visible user card uses the CREATE AGENT sidebar user tokens', () => {
- expect(source).toContain('border-[var(--sidebar-user-card-border)]');
- expect(source).toContain('bg-[var(--sidebar-user-card-bg)]');
- expect(source).toContain('text-[var(--sidebar-user-card-text)]');
- });
-
- it('capsule owns the hover state via the glass hover token', () => {
- expect(source).toContain("'transition-colors hover:bg-[var(--sidebar-user-card-bg-hover)]'");
- });
-
- it('capsule hover is suppressed while the flame button is hovered (:has() exclusion)', () => {
- // 悬停火焰按钮时胶囊底色还原,只让火焰自己高亮 —— 方案 D 语义
- expect(source).toContain("'has-[.flame-btn:hover]:bg-[var(--sidebar-user-card-bg)]'");
- });
-});
-
-describe('UserInfoSection — version label', () => {
- it('labels only the non-global builds alongside the app version', () => {
- expect(source).toContain("import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';");
- // 「哪些区域要标」必须来自 shared 单点,不得在组件里再写一份映射
- // (issue 反馈链路同源;口径见 DESIGN.md §16.3 / region-and-editions §2.3)。
- expect(source).toContain("import { shouldLabelRegion } from '../../../shared/regionCode';");
- expect(source).not.toMatch(/const REGION_LABEL/);
- // global 故意不贴标签,落到 null 分支只显示版本号。
- expect(source).toMatch(
- /const appRegionLabel = !shouldLabelRegion\(CURRENT_CINDY_REGION\)\s*\n\s*\? null\s*\n\s*: CURRENT_CINDY_REGION === 'cn'/,
- );
- // 展示文案走 i18n,且 key 为字面量分支(check:i18n 静态提取要看得到)。
- expect(source).toContain("t('sidebar.user.regionCodeCn')");
- expect(source).toContain("t('sidebar.user.regionCodeDev')");
- expect(source).not.toContain("'Global'");
- expect(source).not.toMatch(/'CN'|'Dev'/);
- expect(source).toMatch(
- /const appVersionLabel = appRegionLabel\s*\n\s*\? `\$\{appRegionLabel\} · \$\{appDisplayVersion\}`\s*\n\s*: appDisplayVersion;/,
- );
- expect(source).not.toContain('XD.Inc');
- expect(source).toContain('{visibleVersionLabel}');
- expect(source).toContain('title={visibleVersionLabelDetail}');
- });
-
- it('shows the Beta label only after the persisted channel state has loaded', () => {
- expect(source).toContain(
- "import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';",
- );
- expect(source).toContain(
- 'const showBetaLabel = !betaChannelState.loading && betaChannelState.enableBeta;',
- );
- expect(source).toContain('data-testid="sidebar-beta-channel-label"');
- expect(source).not.toContain('beta-channel-badge');
- expect(source).toContain("t('settings.betaChannel.badge')");
- });
-});
-
-describe('UserInfoSection — Canary avatar badge', () => {
- it('shows only the shield decoration when isCanary is true', () => {
- expect(source).toMatch(
- /import \{[\s\S]*Building2[\s\S]*Check[\s\S]*Flame[\s\S]*UserRound[\s\S]*\} from 'lucide-react';/,
- );
- expect(source).toContain('dataOwnerId');
- expect(source).toContain('isCanary, listAccounts, syncAccounts, switchAccount');
- expect(source).toContain(
- "if (mode !== 'cloud' || !accountsReadyForOwner || switchableAccounts.length === 0) return null;",
- );
- expect(source).toContain('{isCanary && (');
- expect(source).toContain("aria-label={t('sidebar.user.canaryBadge')}");
- expect(source).not.toContain("isCanary && 'ring-[1.5px] ring-foreground'");
- expect(source).not.toContain("user.role === 'admin'");
- expect(locale.sidebar.user.canaryBadge).toBe('灰度用户');
- });
-
- it('keeps the collapsed settings Tip from overlapping the Canary native title', () => {
- expect(
- source.match(/title=\{isCanary \? t\('sidebar\.user\.canaryBadge'\) : undefined\}/g),
- ).toHaveLength(1);
- expect(source).toMatch(
- /className="relative h-\[27px\] w-\[27px\] shrink-0"\s+title=\{isCanary \? t\('sidebar\.user\.canaryBadge'\) : undefined\}/,
- );
- expect(source).not.toMatch(
- /className="relative h-9 w-9 shrink-0"\s+title=\{isCanary \? t\('sidebar\.user\.canaryBadge'\) : undefined\}/,
- );
- });
-});
-
-describe('UserInfoSection — 未登录态头像兜底', () => {
- it('未登录(跳过登录)态用中性人形图标,不拿状态文案取首字', () => {
- // 状态名四语各不相同(未登录 / Not signed in / 未ログイン / 로그인하지 않음),
- // 取首字会渲染成「未」/「N」这类无意义字符,所以这里必须走图标分支。
- expect(source).toContain('const showNotSignedInGlyph = !user && isLocal;');
- // 折叠 rail(36px 圆)与展开胶囊(27px 圆)两处兜底都要接上
- expect(source).toMatch(
- /showNotSignedInGlyph \? \(\s*\n\s*<UserRound aria-hidden="true" size=\{18\}/,
- );
- expect(source).toMatch(
- /showNotSignedInGlyph \? \(\s*\n\s*<UserRound aria-hidden="true" size=\{15\}/,
- );
- });
-
- it('已登录用户仍使用姓名首字兜底', () => {
- expect(source).toContain(
- "const displayName = user?.name ?? (isLocal ? t('settings.userProfile.local.name') : '');",
- );
- expect(source).toContain('const initial = displayName.charAt(0).toUpperCase();');
- });
-});
-
-describe('UserInfoSection — mobile download entry', () => {
- it('uses the local Lucide Smartphone icon in a matching 22x22 capsule action', () => {
- expect(source).toContain('Smartphone');
- expect(source).toMatch(/'mobile-download-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);
- expect(source).toContain("!isCollapsed && 'mr-1'");
- expect(source).toContain('<Smartphone className="h-3 w-3" aria-hidden="true" />');
- });
-
- it('suppresses capsule hover while the mobile button owns the hover state', () => {
- expect(source).toContain("'has-[.mobile-download-btn:hover]:bg-[var(--sidebar-user-card-bg)]'");
- });
-
- it('opens the mobile download dialog with an accessible label', () => {
- expect(source).toContain('onClick={() => setMobileDownloadOpen(true)}');
- expect(source).toContain("aria-label={t('sidebar.user.downloadMobile')}");
- expect(source).toContain("navigate('/settings?tab=remote-control')");
- expect(source).toContain("const remoteAvailable = mode === 'cloud';");
- expect(source).toContain('remoteAvailable={remoteAvailable}');
- expect(locale.sidebar.user.downloadMobile).toBe('下载 Cindy 移动端');
- expect(locale.sidebar.mobileDownload.title).toBe('远程控制 Cindy');
- });
-
- it('keeps the same entry and dialog available in the collapsed sidebar', () => {
- expect(source).toContain(
- 'className="mt-auto flex h-[66px] flex-col items-center justify-center gap-1 px-3"',
- );
- expect(source).toContain('{mobileDownloadEntry}');
- });
-});
-
-// ── 改动 2: 内部主按钮去掉冗余 hover / 圆角 ───────────────────────────
-
-describe('UserInfoSection — inner main button no longer owns hover background', () => {
- it('does not contain a "rounded-full" + "hover:bg-sidebar-item-hover" combo on the same className line', () => {
- // 旧 className 长这样: 'flex w-full items-center gap-[10px] rounded-full',
- // 我们要求这一行(主按钮第一行 cn() 字面量)不再带 rounded-full
- expect(source).not.toMatch(/'flex w-full items-center gap-\[10px\] rounded-full'/);
- });
-
- it('main button does not own hover:bg-sidebar-item-hover (delegated to outer div)', () => {
- // 旧第二行: 'transition-colors text-left hover:bg-sidebar-item-hover',
- expect(source).not.toMatch(/'transition-colors text-left hover:bg-sidebar-item-hover'/);
- });
-
- it('main button keeps its layout classes (flex / w-full / gap)', () => {
- // 保留布局,只去掉视觉
- expect(source).toMatch(/'flex min-w-0 flex-1 items-center gap-\[10px\]'/);
- });
-
- it('main button keeps text-left for left-aligned content', () => {
- expect(source).toMatch(/'text-left'/);
- });
-
- it('main button opens the accessible More menu instead of navigating directly', () => {
- expect(source).not.toContain('onClick={handleClick}');
- expect(source).not.toContain('role="link"');
- expect(source).toContain(
- "const moreLabel = t('sidebar.user.moreLabel', { name: displayName });",
- );
- expect(source).toContain('aria-label={moreLabel}');
- expect(source).toContain('<DropdownMenuTrigger asChild>');
- expect(locale.sidebar.user.moreLabel).toBe('更多,当前用户:{{name}}');
- });
-
- it('keeps Settings at the bottom of the More menu and leaves logout in Settings', () => {
- expect(source).toContain("t('sidebar.user.menuSettings')");
- expect(source).toContain('{renderSavedAccountItems()}');
- expect(source).toContain('accountsReadyForOwner &&');
- expect(source).toContain('savedAccounts.some((account) => !account.isCurrent)');
- expect(source.indexOf('{renderSavedAccountItems()}')).toBeLessThan(
- source.indexOf("t('sidebar.user.menuSettings')"),
- );
- expect(source).not.toContain("t('sidebar.user.menuLogout')");
- expect(source).not.toContain('useLogout');
- expect(source).not.toContain('<LogOut');
- expect(source).toContain("mode === 'local'");
- expect(source.indexOf("t('login.signIn')")).toBeLessThan(
- source.indexOf("t('sidebar.user.menuSettings')"),
- );
- expect(source).not.toContain('AccountSwitcherDialog');
- });
-
- it('shows saved accounts directly only when there is more than one', () => {
- expect(source).toContain('dataOwnerId');
- expect(source).toContain('isCanary, listAccounts, syncAccounts, switchAccount');
- expect(source).toContain(
- "if (mode !== 'cloud' || !accountsReadyForOwner || switchableAccounts.length === 0) return null;",
- );
- expect(source).toContain('onSelect={() => void switchSavedAccount(account)}');
- expect(source).toContain('await switchAccount(account.accountKey);');
- expect(source).toContain('onOpenChange={(open) => open && void refreshSavedAccounts()}');
- });
-});
-
-// ── 改动 3: Flame button 加 .flame-btn 标识 class ────────────────────────
-
-describe('UserInfoSection — Flame button carries .flame-btn marker class', () => {
- it("Flame button className list includes 'flame-btn' as the first entry", () => {
- // 关键: 外层 div 的 has-[.flame-btn:hover] 选择器必须能钩到这个 class
- expect(source).toMatch(/'flame-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);
- });
-
- it('Flame button retains its own hover:bg-sidebar-item-hover (capsule highlight when hovered)', () => {
- // Flame 自己的胶囊 hover 不能丢,这是方案 D 的视觉表达
- expect(source).toMatch(/'transition-colors hover:bg-sidebar-item-hover'/);
- });
-
- it('Flame button keeps rounded-full + 22x22 size inside the account capsule', () => {
- expect(source).toContain(
- 'flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full',
- );
- expect(source).toContain(
- 'border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)]',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts b/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts
deleted file mode 100644
index 33bb162df7..0000000000
--- a/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const userMessageSource = fs.readFileSync(
- path.resolve(__dirname, '../components/chat/UserMessage.tsx'),
- 'utf8',
-);
-
-describe('UserMessage source labels', () => {
- it('renders every source label through MessageSourceLabels (one share-stripped slot)', () => {
- expect(userMessageSource).not.toContain('<AutomationOriginBadge');
- expect(userMessageSource.match(/<MessageSourceLabels\b/g)).toHaveLength(3);
- });
-
- it('never shows the automation label inside the hook card branch', () => {
- const hookBranch = userMessageSource.indexOf(') : hookSource && !editing ? (');
- const ordinaryBranch = userMessageSource.indexOf(') : (', hookBranch + 1);
- const hookBody = userMessageSource.slice(hookBranch, ordinaryBranch);
- expect(hookBody).toContain('<MessageSourceLabels');
- expect(hookBody).not.toContain('automationOrigin=');
- // 编辑态 / 缺 hookSource 时走普通分支:标签仍按渠道显示。
- expect(userMessageSource.slice(ordinaryBranch)).toContain('hookIm={hookSource?.im}');
- });
-
- it('marks the shared-task author line as a share-image source', () => {
- expect(userMessageSource).toMatch(
- /\{sharedAuthorName && \(\s*<span\s+\{\.\.\.\{ \[SHARE_SOURCE_ATTR\]: '' \}\}/,
- );
- });
-
- it('marks a bubble holding only the plugin annotation as a share-image source', () => {
- // 只发 $指令 时气泡里只有插件标注行;分享图剥掉标注后整泡也要去掉,不留空壳。
- expect(userMessageSource).toMatch(
- /\{\.\.\.\(inlineQuoteCount === 0 && !displayBubbleBody\.trim\(\)\s*\? \{ \[SHARE_SOURCE_ATTR\]: '' \}\s*: \{\}\)\}/,
- );
- });
-
- it('shows the shared-task member id on hover, like the other source labels', () => {
- expect(userMessageSource).toContain(
- "t('chat.userMessage.sourceIds.member', { id: sharedAuthorMemberId })",
- );
- });
-
- it('names the Worker role in the Orca card title when the host recorded it', () => {
- expect(userMessageSource).toContain(
- "t('chat.userMessage.orcaFromWorkerNamed', { role: orcaWorkerRole })",
- );
- expect(userMessageSource).toContain("t('chat.userMessage.orcaFromLead')");
- });
-
- it('keeps the 3-line automation collapse for real automations only', () => {
- expect(userMessageSource).toContain(
- 'const isScheduledAutomation = isRealAutomationOrigin(automationOrigin);',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts
deleted file mode 100644
index 525c5e73e4..0000000000
--- a/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-/**
- * composer 右下按钮组右对齐,所以「语音按钮与最右主槽之间夹着几个按钮」直接决定语音按钮
- * 自己的屏幕位置。次槽 Stop 只在 streaming 时出现,若它夹在语音与 Send 之间,语音按钮就会
- * 随 streaming / 草稿 / 录音状态整格横跳,而它让出的位置正好被 Stop 占据 —— 用户点完语音想
- * 「原地再点一下停止录音」会误停正在跑的任务。
- * 约束:次槽 Stop 一律在语音按钮左边,语音按钮永远是主槽的左邻。
- */
-describe('ChatInput voice button anchor contract', () => {
- // 从次槽 Stop 起、到主槽 sendButtonRef 止,即右下按钮组里语音按钮所在的区间。
- const buttonGroupBlock = extractBetween(
- chatInputSource,
- '{showSecondaryStop && (',
- 'ref={sendButtonRef}',
- );
-
- it('renders the secondary stop button to the left of the voice input button', () => {
- const secondaryStopIndex = buttonGroupBlock.indexOf('<SendButton');
- const voiceButtonIndex = buttonGroupBlock.indexOf('<VoiceInputButton');
-
- expect(secondaryStopIndex).toBeGreaterThanOrEqual(0);
- expect(voiceButtonIndex).toBeGreaterThan(secondaryStopIndex);
- });
-
- it('keeps the voice input button as the immediate left neighbour of the main send slot', () => {
- const afterVoiceButton = buttonGroupBlock.slice(
- buttonGroupBlock.indexOf('<VoiceInputButton'),
- );
-
- // 语音按钮与主槽之间不得再插入任何 Send/Stop 控件。
- expect(afterVoiceButton).not.toContain('<SendButton');
- });
-
- it('does not fork the secondary stop placement on listening state', () => {
- // 只在录音态挪 Stop 是不够的:录音结束且草稿非空时 Stop 会跳回右边,语音按钮同样
- // 左移一格,只是把误点风险推迟到「刚点完停止录音」那一刻。
- expect(chatInputSource).toContain(
- 'const showSecondaryStop =\n !queueEditActive &&\n showStopButton && (canSend || voiceBusyOnCurrentComposer) && !sendDispatchInFlight;',
- );
- expect(chatInputSource).toContain(
- 'const mainSlotIsStop =\n !queueEditActive &&\n showStopButton && (sendDispatchInFlight || (!canSend && !voiceBusyOnCurrentComposer));',
- );
- });
-
- it('keeps the slot assignment stable across the whole voice lifecycle', () => {
- // 停止录音 → submitting/refining → 草稿落地之间 canSend 仍为 false;若按 isListening
- // 判定,这一段会退化成 streaming idle,Stop 弹回主槽再弹走,肉眼可见闪一下。
- // isBusy = listening || submitting || refining,覆盖整段生命周期。
- const slotDecisionBlock = extractBetween(
- chatInputSource,
- 'const mainSlotIsStop =',
- 'useEffect(() => {\n voiceInputCanStopAndSendRef.current = !queueEditActive && !sendButtonDisabled;',
- );
-
- expect(slotDecisionBlock).not.toContain('voiceInput.isListening');
- expect(slotDecisionBlock).toContain('voiceBusyOnCurrentComposer');
- });
-
- it('keeps the stop controls enabled while voice input owns the editor lock', () => {
- // The surrounding voice lifecycle lock must not disable the button or
- // shortcut that is needed to end the active recording.
- expect(chatInputSource).toContain('const disabledRef = useRef(composerEditorLocked);');
- expect(chatInputSource).toContain('disabledRef.current = composerEditorLocked;');
- expect(chatInputSource).toMatch(
- /disabled=\{\s*composerEditorLocked \|\|\s*!editor \|\|\s*\(voiceInput\.isBusy && !voiceBusyOnCurrentComposer\)\s*\}/,
- );
- expect(chatInputSource).not.toContain('disabled={composerMutationLocked || !editor}');
- });
-});
-
-function extractBetween(sourceBlock: string, startNeedle: string, endNeedle: string): string {
- const start = sourceBlock.indexOf(startNeedle);
- const end = sourceBlock.indexOf(endNeedle, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return sourceBlock.slice(start, end);
-}
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts
deleted file mode 100644
index 67079ae203..0000000000
--- a/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const root = path.resolve(__dirname, '..');
-const chatInput = readFileSync(path.join(root, 'components/new-chat/ChatInput.tsx'), 'utf8');
-const draftDecoration = readFileSync(
- path.join(root, 'components/new-chat/VoiceInputDraftDecoration.ts'),
- 'utf8',
-);
-
-describe('voice input draft scroll anchoring', () => {
- it('scrolls the live draft to the saved insertion range instead of the bottom', () => {
- const effectStart = chatInput.indexOf('setVoiceInputDraftDecoration(');
- expect(effectStart).toBeGreaterThan(-1);
- const effectEnd = chatInput.indexOf('// Route changes such as Chat -> Settings', effectStart);
- expect(effectEnd).toBeGreaterThan(effectStart);
- const effectBlock = chatInput.slice(effectStart, effectEnd);
-
- expect(effectBlock).toContain('voiceInput.draftRange');
- expect(effectBlock).toContain('scrollVoiceInputDraftEndIntoView(editor)');
- expect(effectBlock).not.toContain('scrollEditorToBottom');
- });
-
- it('keeps an explicit draft decoration anchor from following later selection changes', () => {
- expect(draftDecoration).toContain('anchorLocked');
- expect(draftDecoration).toContain('const anchorLocked = Boolean(range)');
- expect(draftDecoration).toContain('if (!old.anchorLocked)');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
deleted file mode 100644
index a564d972ba..0000000000
--- a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
-).replace(/\r\n?/g, '\n');
-
-describe('ChatInput voice lifecycle locks', () => {
- it('keeps the editor read-only for the entire voice lifecycle', () => {
- expect(chatInputSource).toContain(
- 'const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;',
- );
- expect(chatInputSource).toContain('editor?.setEditable(!composerTypingLocked);');
- expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
- expect(chatInputSource).toContain('active={voiceBusyOnCurrentComposer}');
- });
-
- it('keeps attachments locked while leaving permission mode available', () => {
- const extraDirsStart = chatInputSource.indexOf('<ExtraDirsButton');
- expect(extraDirsStart).toBeGreaterThanOrEqual(0);
- const permissionStart = chatInputSource.indexOf('<PermissionSelector');
- expect(permissionStart).toBeGreaterThanOrEqual(0);
- const extraDirsBlock = chatInputSource.slice(extraDirsStart, permissionStart);
- expect(extraDirsBlock).toContain('disabled={composerMutationLocked}');
-
- // Inline footer elements can close before the outer permission selector.
- const permissionEnd = permissionStart + chatInputSource.slice(permissionStart).search(/\n\s*\/>/);
- expect(permissionEnd).toBeGreaterThan(permissionStart);
- const permissionBlock = chatInputSource.slice(permissionStart, permissionEnd);
- expect(permissionBlock).toContain('disabled={composerEditorLocked || settingsLocked || sharedGuest}');
- expect(permissionBlock).not.toContain('disabled={composerMutationLocked}');
- });
-
- it('lets top-level permission surfaces consume Escape before voice cancellation', () => {
- const shortcutHandlerStart = chatInputSource.indexOf(
- 'const handleKeyDown = (event: KeyboardEvent) => {',
- );
- expect(shortcutHandlerStart).toBeGreaterThanOrEqual(0);
- const shortcutHandlerEnd = chatInputSource.indexOf(
- 'const enterIntent = resolveComposerEnterIntent(',
- shortcutHandlerStart,
- );
- expect(shortcutHandlerEnd).toBeGreaterThan(shortcutHandlerStart);
- const shortcutHandlerBlock = chatInputSource.slice(shortcutHandlerStart, shortcutHandlerEnd);
-
- expect(shortcutHandlerBlock).toContain('[role="alertdialog"]');
- expect(shortcutHandlerBlock).toContain('[data-morph-side]');
- const voiceCancelStart = shortcutHandlerBlock.indexOf('voiceInputCancelRef.current()');
- expect(voiceCancelStart).toBeGreaterThanOrEqual(0);
- expect(shortcutHandlerBlock.indexOf('[data-morph-side]')).toBeLessThan(
- voiceCancelStart,
- );
- expect(shortcutHandlerBlock).toContain('voiceOwnsCurrentComposer');
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/workGroupBlockInteraction.test.ts b/apps/desktop/src/renderer/__tests__/workGroupBlockInteraction.test.ts
deleted file mode 100644
index 61edb7ace3..0000000000
--- a/apps/desktop/src/renderer/__tests__/workGroupBlockInteraction.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * workGroupBlockInteraction.test.ts
- * ---------------------------------------------------------------------------
- * WorkGroupBlock「外层时间线 → 内层动作组 → 直接详情」交互的回归锁定。
- *
- * 旧行为(PR #56):点开「已工作」组时 `expandBlocks(childBlockIds)` 把所有子卡
- * 批量 seed 为展开,内部 thinking / 工具调用一次点击全部摊开。
- * 完成态外组展开后只展开 assistant 文字时间线,动作仍是内层「已工作」;
- * 内层或运行态动作组展开后直接显示 thinking /工具行,不再套第三层摘要卡。
- *
- * 测试环境维持仓库约定的 'node'(vitest.config.ts):不引 jsdom / testing-library,
- * 用静态源码扫描锁定「onToggle 只翻自身状态、不再 seed 子卡」的接线不被回退。
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import {
- ACTIVITY_ROW_CHEVRON_SLOT_CLASS,
- ACTIVITY_ROW_COLOR_TRANSITION_CLASS,
-} from '../components/chat/activityRowChrome';
-import { CHAT_COLOR_TRANSITION_CLASS } from '../components/chat/chatChrome';
-
-describe('WorkGroupBlock — 嵌套工作组接线静态扫描', () => {
- const source = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'WorkGroupBlock.tsx'),
- 'utf8',
- );
- const chrome = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'activityRowChrome.ts'),
- 'utf8',
- );
- const actionRow = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'AgentActionRow.tsx'),
- 'utf8',
- );
- const systemCard = readFileSync(
- resolve(__dirname, '..', 'components', 'chat', 'SystemCard.tsx'),
- 'utf8',
- );
-
- it('onToggle 不再批量 seed 后代工作组展开态', () => {
- // 外层 click 只能翻外层自身;内层「已工作」仍由用户单独展开。
- expect(source).not.toMatch(/expandBlocks/);
- });
-
- it('onToggle 仍翻转组自身的展开态', () => {
- const onToggle = source.slice(source.indexOf('const onToggle'));
- expect(onToggle).toMatch(/setExpanded\(\(v\) => !v\)/);
- });
-
- it('动作组展开后直接渲染工具行和 thinking 内容', () => {
- expect(source).toMatch(/child\.kind === 'tools'[\s\S]*?<ToolActivityRow/);
- expect(source).toMatch(/child\.kind === 'thinking'[\s\S]*?<ExpandedThinkingRow/);
- expect(source).not.toMatch(/AgentActionsBlock/);
- });
-
- it('exposes thinking rows as viewport child anchors', () => {
- expect(source).toMatch(
- /function ThinkingActivityRow[\s\S]*data-message-client-id=\{activity\.key\}/,
- );
- expect(source).toMatch(
- /function ExpandedThinkingRow[\s\S]*data-message-client-id=\{message\.clientId\}/,
- );
- });
-
- it('thinking 行右侧三角与工具行共用同一套槽和 hover 浮起', () => {
- expect(chrome).toMatch(/group-hover:bg-\[var\(--cmd-palette-item-hover\)\]/);
- expect(chrome).toMatch(/hover:bg-\[var\(--msg-code-inline-bg\)\]/);
- expect(chrome).toMatch(/h-\[18px\] w-\[18px\]/);
- expect(chrome).toMatch(/ACTIVITY_ROW_RADIUS_CLASS = 'rounded-\[8px\]'/);
- expect(chrome).toMatch(/rounded-\[8px\]/);
- expect(ACTIVITY_ROW_COLOR_TRANSITION_CLASS).toBe(CHAT_COLOR_TRANSITION_CLASS);
- expect(ACTIVITY_ROW_CHEVRON_SLOT_CLASS).toContain(ACTIVITY_ROW_COLOR_TRANSITION_CLASS);
- expect(ACTIVITY_ROW_COLOR_TRANSITION_CLASS).toContain('transition-colors');
- expect(ACTIVITY_ROW_COLOR_TRANSITION_CLASS).toContain('duration-[var(--motion-fast)]');
- expect(ACTIVITY_ROW_COLOR_TRANSITION_CLASS).toContain('ease-[var(--motion-ease-out)]');
- expect(ACTIVITY_ROW_COLOR_TRANSITION_CLASS).toContain('motion-reduce:transition-none');
- expect(chrome).not.toMatch(/rounded-lg/);
- expect(chrome).not.toMatch(/var\(--radius\)/);
- expect(chrome).not.toMatch(/rounded-\[4px\]/);
- expect(source).toMatch(/from '\.\/activityRowChrome'/);
- expect(source).toMatch(/ACTIVITY_ROW_CHEVRON_SLOT_CLASS/);
- expect(source).toMatch(/ACTIVITY_ROW_HOVER_SURFACE_CLASS/);
- expect(source).toMatch(/ACTIVITY_ROW_RADIUS_CLASS/);
- expect(source).toMatch(/ACTIVITY_ROW_COLOR_TRANSITION_CLASS/);
- expect(source).not.toMatch(/function ThinkingActivityRow[\s\S]*rounded-\[6px\]/);
- expect(actionRow).toMatch(/from '\.\/activityRowChrome'/);
- expect(actionRow).toMatch(/ACTIVITY_ROW_CHEVRON_SLOT_CLASS/);
- expect(actionRow).toMatch(/ACTIVITY_ROW_RADIUS_CLASS/);
- expect(actionRow).toMatch(/ACTIVITY_ROW_COLOR_TRANSITION_CLASS/);
- expect(systemCard).toMatch(/ACTIVITY_ROW_CHEVRON_SLOT_CLASS/);
- // 槽位始终占位;只有可展开时才画三角。旧写法把整个 span 按 canExpand 卸掉,
- // 短思考行 / 仅有 outcome 的中断行会比工具行更靠右。
- expect(source).not.toMatch(
- /\{canExpand && \(\s*<span aria-hidden="true" className="inline-flex h-\[18px\]/,
- );
- expect(systemCard).not.toMatch(
- /\{canExpand && \(\s*<span aria-hidden="true" className=\{ACTIVITY_ROW_CHEVRON_SLOT_CLASS\}/,
- );
- });
-
- it('完成态内层工作组递归复用 WorkGroupBlock', () => {
- expect(source).toMatch(/child\.kind === 'group'[\s\S]*?<WorkGroupBlock/);
- });
-});
diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginControls.placeholder.test.ts b/apps/desktop/src/renderer/components/login/__tests__/LoginControls.placeholder.test.ts
deleted file mode 100644
index 1d72797531..0000000000
--- a/apps/desktop/src/renderer/components/login/__tests__/LoginControls.placeholder.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-/**
- * placeholder 颜色接线冻结(2026-07-23 用户实测发现修复):
- * `--login-control-placeholder` token 自登录换皮落地起注册但从未被消费,
- * placeholder 实渲染为 Tailwind preflight 默认 placeholder 灰而非设计稿定稿值。
- * 本测试按仓内静态源码断言先例(loginScenarioHarness.test.ts)锁住接线,
- * 防止工具类再次脱落回默认灰。
- */
-const source = readFileSync(
- resolve(process.cwd(), 'src/renderer/components/login/LoginControls.tsx'),
- 'utf8',
-);
-
-describe('LoginControls placeholder 接线冻结', () => {
- it('输入框 placeholder 颜色必须消费 --login-control-placeholder token', () => {
- expect(source).toContain('placeholder:text-[var(--login-control-placeholder)]');
- });
-});
diff --git a/apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx b/apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx
index 4d5340f1cd..2e97594da5 100644
--- a/apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx
@@ -251,8 +251,7 @@ export function AgentSelect({
? cn('w-full min-w-0 px-3', dense ? 'h-9' : 'h-10')
: cn(
'shrink-0',
- // 工具条高度是 CREATE AGENT 视觉契约锁定值(见
- // newMakerCreateAgentVisualContract.test.ts), 保持独立字面量。
+ // 工具条高度是 CREATE AGENT 视觉契约锁定值,保持独立字面量。
'h-[30px]',
iconOnly ? 'w-[34px] min-w-[34px] justify-center px-0' : 'px-2.5',
),
diff --git a/apps/desktop/src/renderer/components/ui/__tests__/dropdownMenuSubContentPortal.test.ts b/apps/desktop/src/renderer/components/ui/__tests__/dropdownMenuSubContentPortal.test.ts
deleted file mode 100644
index b1e51eadd6..0000000000
--- a/apps/desktop/src/renderer/components/ui/__tests__/dropdownMenuSubContentPortal.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-/**
- * 回归守卫:DropdownMenuSubContent 必须走 Portal 渲染。
- * -------------------------------------------------------------------------
- * 背景(「移动到项目」子菜单点了没反应):CINDY 毛玻璃主题给菜单 surface
- * (MENU_CONTENT_CLASS,含 bg-[var(--cmd-palette-bg)])加了 `backdrop-filter: blur`
- * (globals.css E4D 毛玻璃)。`backdrop-filter` 非 none 会让父 DropdownMenuContent
- * 成为 fixed 定位后代的 containing block,于是原地渲染(非 Portal)的 SubContent
- * 的 Popper wrapper(position:fixed)被父 Content 的 `overflow-hidden` 裁掉,
- * 子菜单整块不可见。把 SubContent Portal 到 body 可根治。删除 Portal 会让子菜单
- * 在毛玻璃主题下重新消失,故用本测试钉死。
- */
-describe('DropdownMenuSubContent portal guard', () => {
- const source = readFileSync(resolve(__dirname, '..', 'dropdown-menu.tsx'), 'utf8');
-
- it('wraps SubContent in a Portal so glass-blur ancestors cannot clip it', () => {
- // 抓取 DropdownMenuSubContent 定义块,断言其内部先出现 Portal 再出现 SubContent。
- const match = source.match(/const DropdownMenuSubContent[\s\S]*?\n\)\);/);
- expect(match, 'DropdownMenuSubContent definition should exist').not.toBeNull();
- const block = match![0];
- expect(block).toContain('<DropdownMenuPrimitive.Portal>');
- expect(block).toContain('<DropdownMenuPrimitive.SubContent');
- // Portal 必须包住 SubContent(Portal 开标签在 SubContent 之前)。
- expect(block.indexOf('<DropdownMenuPrimitive.Portal>')).toBeLessThan(
- block.indexOf('<DropdownMenuPrimitive.SubContent'),
- );
- });
-});
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
index 84287792a8..8d65cc022c 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
@@ -1,7 +1,7 @@
/**
* 统一伙伴列表里的群聊行,和伙伴私聊共同按最新消息排序。
*
- * 群行与伙伴行同一套 IM 行几何(见 __tests__/botsSidebarSpacing.test.ts):左侧两位
+ * 群行与伙伴行使用同一套 IM 行几何:左侧两位
* 成员的叠放头像,第一行群名,第二行最近一条消息「作者:内容」。有伙伴正在发言时,
* 第二行临时让位给运行中标记(橙色 sparkles + 发言伙伴的工作状态,DESIGN.md §2
* Thinking Orange 的侧栏运行态),一轮结束就落回最近消息。
diff --git a/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx b/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
index 70924e35db..5a8859167c 100644
--- a/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
+++ b/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
@@ -685,8 +685,8 @@ export function TeammatesSection() {
{/* 定稿原型 `.row-open{padding:8px 10px;gap:10px}`:整行只有这一个
可点区域,左右内边距对称。行尾曾经还挂过一列齿轮/状态图标,
它下线后 `pr-2` 的占位残留了下来 —— 右边比左边窄一截,
- 单看不出问题,和左侧头像一比就是歪的。数值基线见
- __tests__/botsSidebarSpacing.test.ts。 */}
+ 单看不出问题,和左侧头像一比就是歪的。这里的行内边距与下方按钮样式
+ 保持同一套几何基线。 */}
<button
type="button"
onClick={() => navigate(`/bots/${bot.id}`)}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
deleted file mode 100644
index 66307d8995..0000000000
--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * 伙伴对话皮肤的接线契约。
- *
- * 这三处判定都长在超大组件里(CCAgentSessionView 5k 行 / MessageStream 5.8k 行 /
- * ChatInput 8k 行),在 jsdom 里整棵挂起来既慢又脆。真正要锁死的是**判定条件本身**:
- * 头像与收控件只能对 Bot 会话生效,普通任务的渲染必须一字不改。所以这里锁源码契约,
- * 归属与状态稳定性由 botSessionPresentation / botChatPresentation 的行为测试覆盖。
- */
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-
-const read = (relativePath: string): string =>
- readFileSync(resolve(__dirname, '..', '..', '..', relativePath), 'utf8').replace(/\r\n/g, '\n');
-
-const sessionView = read('features/cc-agent/CCAgentSessionView.tsx');
-const messageStream = read('components/chat/MessageStream.tsx');
-const messageActionBar = read('components/chat/MessageActionBar.tsx');
-const chatInput = read('components/new-chat/ChatInput.tsx');
-const botSettings = read('features/bots/BotsHomeView.tsx');
-
-describe('Bot 对话的判定条件', () => {
- it('气泡头像只在 Bot 对话下传给消息流', () => {
- expect(sessionView).toContain('assistantAvatar={botAssistantAvatar}');
- expect(sessionView).toContain('<BotAvatar bot={botChatIdentity} size="sm" />');
- });
-
- it('伙伴对话换占位符并启用轻量输入框', () => {
- expect(sessionView).toContain('botComposerPlaceholderKey(botChatIdentity.name)');
- expect(sessionView).toContain('hideRuntimeControls={Boolean(botChatIdentity)}');
- // 普通任务仍走原来的占位符。
- expect(sessionView).toContain("t('ccAgent.layout.chatPlaceholder')");
- });
-
- it('伙伴对话换掉任务顶栏,而不是在它旁边再加一个', () => {
- expect(sessionView).toContain(
- '<BotSessionContentHeaderRegistration bot={botChatIdentity} />',
- );
- expect(sessionView).toContain('<SessionContentHeaderRegistration');
- });
-});
-
-describe('消息流的头像挂载', () => {
- it('没有头像时原样返回气泡,不多包一层 DOM', () => {
- const helper = messageStream.match(/function withAssistantAvatar\([\s\S]*?\n}/)?.[0];
- expect(helper).toBeTruthy();
- expect(helper).toContain('if (!avatar) return bubble;');
- });
-
- it('只有 assistant 分支挂头像', () => {
- expect(messageStream).toContain('return withAssistantAvatar(\n assistantAvatar,');
- // Assistant text shows the avatar; both task references reserve the same
- // space invisibly. User messages and internal tool/work cards still bypass it.
- expect(messageStream.match(/withAssistantAvatar\(/g)?.length).toBe(3);
- expect(messageStream).toMatch(/simplifiedBotConversation\s*&&\s*\(message\.systemCardType === 'bot-session-task'\s*\|\|\s*message\.systemCardType === 'bot-session-task-result'\)\s*\? withAssistantAvatar\(/);
- expect(messageStream).toMatch(/<span aria-hidden="true" className="invisible">\s*\{assistantAvatar\}\s*<\/span>/);
- });
-});
-
-describe('伙伴输入框只保留对话动作', () => {
- it('伙伴保留标准权限 chip,仅隐藏模型选择器', () => {
- expect(chatInput.match(/!hideRuntimeControls \? \(/g)?.length).toBe(1);
- expect(chatInput.indexOf('<PermissionSelector')).toBeLessThan(chatInput.indexOf('!hideRuntimeControls ? ('));
- expect(chatInput).toContain('<PermissionSelector');
- expect(chatInput).toContain('<ModelSelector');
- });
-
- it('伙伴仍可使用权限快捷键,锁定任务不能切换', () => {
- expect(chatInput).toContain('settingsLocked || sharedGuest ? [] : (activeAgentCapabilities?.permissionModes ?? [])');
- expect(chatInput).not.toContain('settingsLocked || hideRuntimeControls');
- });
-
- it('伙伴不渲染任务目录、费用或压缩状态行', () => {
- expect(sessionView).toContain('{!botChatIdentity ? (');
- expect(sessionView).toContain('<TodaySpendChip');
- expect(sessionView).toContain('<ContextCapacityRing');
- });
-});
-
-describe('伙伴设置包含独立能力选择入口', () => {
- it('保留基本资料、按需能力选择与高级文件入口', () => {
- expect(botSettings).toContain('import { BotCapabilitySettings }');
- expect(botSettings).toContain('<BotCapabilitySettings');
- expect(botSettings).not.toContain('<BotGrowthLists');
- expect(botSettings).toContain('<BotBasicProfileFields');
- expect(botSettings).toContain("t('bots.homeFolder.title')");
- });
-});
-
-describe('伙伴消息流收起内部工作过程', () => {
- it('只对伙伴收拢过程,运行期间保留单一状态出口', () => {
- expect(sessionView).toContain('simplifiedBotConversation={Boolean(botChatIdentity)}');
- expect(messageStream).toContain('simplifyBotRenderItems(grouped, isSessionStreaming, visibleGeneratedFileKeys)');
- // Text/tool grouping is covered by botConversationPresentation behavioral tests.
- expect(messageStream).toContain("from '@/features/bots/botConversationPresentation'");
- expect(messageStream).toContain('compact={simplifiedBotConversation}');
- expect(messageStream).not.toContain('data-testid="bot-thinking-indicator"');
- expect(sessionView).toContain('<BotWorkingStatus');
- expect(sessionView).toContain('visible={composerRuntimeVisible}');
- expect(sessionView).not.toContain('botAssistantOutputStarted');
- });
-
- it('时间戳只挂在伙伴消息分组上', () => {
- expect(messageStream).toContain('collectBotMessageTimeGroups(');
- expect(messageStream).toContain('botMessageTimeGroups.get(msg.clientId)');
- });
-
- it('未读起点只挂在伙伴消息流,不会创建分支', () => {
- expect(sessionView).toContain(
- 'botUnreadBoundaryAt={botChatIdentity ? botUnreadBoundaryAt : null}',
- );
- expect(messageStream).toContain("t('bots.chat.newMessagesBoundary')");
- expect(messageStream).toContain('botUnreadBoundaryClientId === msg.clientId');
- });
-
- it('伙伴消息操作栏常显,外显回复,并隐藏费用与 Fork', () => {
- expect(messageStream).toContain('simplifiedBotConversation={simplifiedBotConversation}');
- expect(messageActionBar).toContain('const replyBtn = (replyAction || (simplifiedBotConversation && onAddToChat))');
- expect(messageActionBar).toContain('const forkBtn = !simplifiedBotConversation');
- expect(messageActionBar).toContain('simplifiedBotConversation ? null : costText || tokensText');
- expect(messageActionBar).toContain('simplifiedBotConversation || visible || menuOpen');
- });
-
- it('伙伴身份同时接通专属成果采集与成果卡,普通任务不触发', () => {
- expect(messageStream).toContain(
- 'botSessionId: simplifiedBotConversation ? sessionId : undefined',
- );
- expect(messageStream).toContain('botArtifacts={simplifiedBotConversation}');
- });
-});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/teammatesSectionSpacing.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/teammatesSectionSpacing.test.ts
deleted file mode 100644
index 2968f3d3d0..0000000000
--- a/apps/desktop/src/renderer/features/bots/__tests__/teammatesSectionSpacing.test.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * 伙伴列表行的**数值基线**。
- *
- * 为什么要有这么一份写死数字的静态扫描:这一行的左右间距已经被反复打回过
- * (行尾挂过齿轮 → 齿轮下线 → `pr-2` 占位残留 → 右边比左边窄一截)。截图目检
- * 抓不住 2px,jsdom 也量不出 Tailwind 类的真实像素,唯一能"再漂移就直接红"的
- * 办法就是把定稿数值本身钉在测试里。
- *
- * 数值来自定稿原型 `Cindy-伙伴原型/styles.css` 的行布局:
- *
- * .row { display:flex; align-items:center; border-radius:12px } → rounded-xl,行容器**不带**内边距
- * .row-open { flex:1; padding:8px 10px; gap:10px } → px-2.5 py-2 gap-2.5(左右对称)
- * .row-l1 { display:flex; align-items:baseline; gap:8px } → gap-2
- * .row-l2 { display:flex; align-items:center; gap:8px; margin-top:2px } → gap-2 + 外层 flex-col gap-0.5
- * .row-meta { width:40px; align-items:flex-end } → w-10 items-end
- * .row-name { font-size:14px } → text-14
- * .row-time { font-size:11px; flex:none } → text-11 shrink-0
- * .row-prev { font-size:12.5px } → text-12(仓库字号阶梯里最近的一档)
- * .badge { min-width:16px; height:16px; padding:0 4px; radius:9999 } → h-4 min-w-4 px-1 rounded-full
- * .av-40 { 40px } → BotAvatar size="md"
- * .side-list { padding:0 12px 12px } → 容器 pl-3(伙伴段并入任务侧栏后,
- * 右侧由侧栏滚动区统一留白)
- *
- * 未读角标依用户的侧栏细化反馈收小,数字采用等宽,预览不再随未读加粗。
- * 2026-10-13 伙伴从整栏切换改为任务侧栏里的「伙伴」段(TeammatesSection):行几何不变,
- * 段头改与置顶 / 全部任务段头同款。
- */
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const source = readFileSync(resolve(__dirname, '..', 'TeammatesSection.tsx'), 'utf8').replace(
- /\r\n/g,
- '\n',
-);
-
-/** 去掉注释后的代码。注释里可以复盘历史(「以前这里有 pr-2」),JSX 里不能再有。 */
-const code = source
- .replace(/\{\/\*[\s\S]*?\*\/\}/g, '')
- .replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/(^|[^:])\/\/.*$/gm, '$1');
-
-/** 可点行本体(头像 + 两行文字)的类名串。 */
-const ROW_BUTTON_CLASS =
- 'flex min-w-0 flex-1 items-center gap-2.5 rounded-xl px-2.5 py-2 text-left';
-const ROW_CONTAINER_CLASS = 'group relative flex w-full items-center rounded-xl transition-colors';
-
-describe('伙伴行的间距基线', () => {
- it('行容器不带内边距,也不再给行尾留占位列', () => {
- // 容器只负责选中态背景与圆角;任何 padding / gap 落在这里都会变成
- // 「左边 12+x、右边 x」的不对称。
- expect(source).toContain(`'${ROW_CONTAINER_CLASS}',`);
- // 伙伴行容器不为行尾操作按钮预留 padding;其它控件可以按自身需要使用 pr-*。
- expect(ROW_CONTAINER_CLASS).not.toMatch(/\bp[rxe]-/);
- expect(code).not.toMatch(/<span className="flex shrink-0 items-center gap-1/);
- });
-
- it('唯一的可点区域用对称的 10px 左右内边距、8px 上下内边距', () => {
- expect(source).toContain(ROW_BUTTON_CLASS);
- // px-2.5 = 10px 两侧。出现 px-3 / pl-* / pr-* 都意味着又不对称了。
- expect(ROW_BUTTON_CLASS).toContain('px-2.5');
- expect(ROW_BUTTON_CLASS).toContain('py-2');
- expect(ROW_BUTTON_CLASS).not.toMatch(/\bp[lrxse]-(?!2\.5)/);
- });
-
- it('头像与正文之间 10px', () => {
- expect(ROW_BUTTON_CLASS).toContain('gap-2.5');
- expect(source).toContain('<BotAvatar bot={bot} size="md" />');
- });
-
- it('两行之间 2px,行内元素之间 8px', () => {
- expect(source).toContain('<span className="flex min-w-0 flex-1 flex-col gap-0.5">');
- expect(source).toContain('<span className="flex items-baseline gap-2">');
- expect(source).toContain('<span className="flex min-w-0 items-center gap-2">');
- });
-
- it('五要素的字号与固定尺寸不漂', () => {
- // 名字 14px / 时间 11px / 预览 12px。
- expect(source).toContain("'min-w-0 flex-1 truncate text-14 leading-5',");
- expect(source).toContain("cn('min-h-4 text-11 tabular-nums', mutedClass)");
- expect(source).toContain("'min-w-0 flex-1 truncate text-12 leading-4',");
- // 徽标 16×16,左右各 4px,数字变化不抖动。
- expect(source).toContain(
- 'flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-[var(--bot-unread-bg)] px-1 text-10 font-medium tabular-nums leading-none text-[var(--bot-unread-fg)]',
- );
- });
-
- it('时间与未读共用固定右列,不会被名字或预览推来推去', () => {
- const start = source.indexOf(
- '<span className="flex w-10 shrink-0 self-stretch flex-col items-end justify-between py-0.5">',
- );
- const metaColumn = source.slice(start, source.indexOf('</button>', start));
- expect(metaColumn).toContain("aria-label={t('bots.list.unread', { count: unread })}");
- expect(metaColumn).toContain("cn('min-h-4 text-11 tabular-nums', mutedClass)");
- });
-
- it('管理菜单不再占据消息行宽度', () => {
- expect(source).not.toContain('<MoreHorizontal');
- expect(source).toContain('onContextMenu={(event) => {');
- expect(source).toContain(
- 'className="pointer-events-none fixed h-0 w-0"',
- );
- });
-
- it('归档行与小节头保持间距,空态复用紧凑创建入口', () => {
- expect(source).toContain(
- 'group flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left transition-colors',
- );
- // 空态只留创建入口,外层间距固定,不恢复大卡片。
- expect(source).toContain(
- '<div className="px-3 py-3">',
- );
- expect(source).toContain("<BotCreateMenu label={t('bots.add')} />");
- expect(source).toContain(
- 'mb-1 flex items-center gap-2 px-2.5 text-10 font-medium text-[var(--sidebar-list-muted)]',
- );
- // 列表容器:左 12px 与 `.side-list` 一致;不再自带滚动,随任务侧栏一起滚。
- expect(source).toContain('<div className="flex flex-col pt-1 pr-0 pl-3">');
- expect(code).not.toContain('overflow-y-auto');
- });
-
- it('段头与置顶 / 全部任务段头同款,收起后的头像行与行内正文左缘对齐', () => {
- // 段头:高 24,左 24 / 右 12,与 PinnedSection 段头一致。
- expect(source).toContain(
- '<div className="group/sidebar-header flex h-6 items-center justify-between pr-3 pl-6">',
- );
- // 头像行起点 = 列表容器 12px + 行内边距 10px。
- expect(source).toContain('<div ref={avatarRowRef} className="flex flex-nowrap items-center gap-2 overflow-hidden py-1 pr-0 pl-[22px]">');
- // 段头动作是 20px 图标钮,与其它段头动作同尺寸。
- expect(source).toContain('<BotCreateMenu variant="header" />');
- // 加入群聊收进「+」菜单的「输入邀请链接…」(#6013),段头不再有单独的加群按钮。
- expect(source).not.toContain('ChatJoinButton');
- });
-});
-
-describe('群聊与伙伴行同一套几何', () => {
- const groupRow = readFileSync(
- resolve(__dirname, '..', 'BotGroupSidebarRow.tsx'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
-
- it('群行沿用对称的 10px / 8px 内边距、40px 头像位、14/12/11 字号', () => {
- expect(groupRow).toContain('gap-2.5 rounded-xl px-2.5 py-2 text-left');
- expect(groupRow).toContain('<span className="flex min-w-0 flex-1 flex-col gap-0.5">');
- expect(groupRow).toContain('min-w-0 truncate text-14 leading-5');
- expect(groupRow).toContain("'min-w-0 flex-1 truncate text-12 leading-4'");
- expect(groupRow).toContain("'w-10 shrink-0 self-start pt-0.5 text-right text-11 tabular-nums'");
- });
-});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
index 32fdd0f53d..1b211c6d30 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
@@ -434,8 +434,8 @@ describe('startSubagentTabDiscovery', () => {
* The module above is where the decision lives; this is the wiring that feeds
* it. `CCAgentSessionView` is far too heavy to mount here (it pulls in the
* whole session runtime), so the two invariants that were wrong are checked
- * on its source — the same approach `orcaWorkflowRoute.test.ts` uses for that
- * component's private contracts.
+ * on its source — the same approach used by the route component's private
+ * contract checks.
*/
describe('CCAgentSessionView wiring', () => {
const source = readFileSync(
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/manualProjectSortDrag.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/manualProjectSortDrag.test.ts
deleted file mode 100644
index e09073d6d6..0000000000
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/manualProjectSortDrag.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const projectsSectionSource = readFileSync(
- resolve(__dirname, '../sections/ProjectsSection.tsx'),
- 'utf8',
-);
-const projectNodeSource = readFileSync(resolve(__dirname, '../sections/ProjectNode.tsx'), 'utf8');
-
-describe('manual project sort drag surface', () => {
- it('starts drag from the project header and does not filter that header out', () => {
- // handle 和 filter 都写进 SortableJS closest()。标题行若同时出现在两边,
- // 项目行就没有任何可拖热区——手动排序看起来像坏了。
- expect(projectsSectionSource).toContain(
- "const MANUAL_PROJECT_SORT_HANDLE = '[data-project-header]'",
- );
- expect(projectsSectionSource).toContain(
- "const MANUAL_PROJECT_SORT_FILTER = 'button, input, textarea, select, a, [data-no-drag]'",
- );
- expect(projectsSectionSource).toContain('handle={MANUAL_PROJECT_SORT_HANDLE}');
- expect(projectsSectionSource).toContain('filter={MANUAL_PROJECT_SORT_FILTER}');
- expect(projectsSectionSource).not.toMatch(
- /MANUAL_PROJECT_SORT_FILTER[\s\S]{0,80}\[data-project-header\]/,
- );
- expect(projectNodeSource).toContain('data-project-header="true"');
- expect(projectNodeSource).toContain('data-no-drag');
- });
-});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts
deleted file mode 100644
index fd5d173b92..0000000000
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Regression coverage for Plugin lifecycle wording in the Chinese UI.
- * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
- */
-
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const zhCommon = JSON.parse(
- readFileSync(
- resolve(__dirname, '..', '..', '..', 'i18n', 'locales', 'zh-CN', 'common.json'),
- 'utf8',
- ),
-) as {
- extraDirs: { pluginDisabled: string };
- settings: {
- ghosts: {
- disabledTag: string;
- enableAria: string;
- detail: { customSlotAsleep: string; disabledLabel: string };
- };
- };
-};
-
-describe('Ghost Plugin lifecycle wording', () => {
- it('describes a reversible disabled state instead of implying incompatibility', () => {
- expect(zhCommon.extraDirs.pluginDisabled).toBe('已停用');
- expect(zhCommon.settings.ghosts.disabledTag).toBe('已停用');
- expect(zhCommon.settings.ghosts.detail.disabledLabel).toBe('已停用');
- expect(zhCommon.settings.ghosts.enableAria).toContain('启用');
- // 原先还钉 toast.installedAsleep(「已装入但沉睡」)。新装的「立即开启」勾选框
- // 去掉后一律装入即生效,那条 toast 与其文案 key 一起删了,故不再断言。
- expect(zhCommon.settings.ghosts.detail.customSlotAsleep).toContain('启用后');
- });
-});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts
deleted file mode 100644
index b524fd5ecd..0000000000
--- a/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-describe('market install flow', () => {
- const pageSource = readFileSync(
- resolve(__dirname, '../GhostPluginPage.tsx'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
-
- it('starts a compatible install without a capability confirmation card', () => {
- expect(pageSource).not.toContain('<GhostUpdateReview');
- expect(pageSource).not.toContain('<GhostManualSummary');
- expect(pageSource).not.toContain('<GhostPermissionList');
- expect(pageSource).toContain('installMarketPackage');
- expect(pageSource).toContain(
- '目录详情用于发现与能力展示;点击更新后由 Main 下载并校验真实包后直接落位',
- );
- });
-
- it('refreshes the current market detail after an update instead of closing it', () => {
- expect(pageSource).toContain(
- 'await refreshVisibleMarketDetail(marketDetail.pluginId).catch(() => undefined);',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/pluginMotionDesign.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/pluginMotionDesign.test.ts
deleted file mode 100644
index 39648c7f9c..0000000000
--- a/apps/desktop/src/renderer/features/plugin/__tests__/pluginMotionDesign.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const pluginMotionCss = readFileSync(resolve(__dirname, '..', 'plugin-motion.css'), 'utf8');
-
-describe('plugin motion design contracts', () => {
- it('separates collapsed plugin previews without an ad-hoc in-page shadow', () => {
- const previewCardRule = pluginMotionCss.match(
- /\.plugin-installed-preview-card\s*\{(?<body>[\s\S]*?)\}/,
- )?.groups?.body;
-
- expect(previewCardRule).toBeTruthy();
- expect(previewCardRule).toContain('background: var(--surface-elevated);');
- expect(previewCardRule).toContain('outline: 2px solid var(--surface-elevated);');
- expect(previewCardRule).not.toContain('box-shadow');
- expect(previewCardRule).not.toContain('color-mix');
- });
-
- it('keeps recommended filters on one line against the actual catalog content width', () => {
- const contentQueryStart = pluginMotionCss.indexOf(
- '@container plugin-management-content (max-width: 720px)',
- );
- const layoutQueryStart = pluginMotionCss.indexOf(
- '@container plugin-management (max-width: 720px)',
- );
- const contentQuery = pluginMotionCss.slice(contentQueryStart, layoutQueryStart);
-
- expect(contentQueryStart).toBeGreaterThanOrEqual(0);
- expect(layoutQueryStart).toBeGreaterThan(contentQueryStart);
- expect(contentQuery).toContain('.plugin-catalog-toolbar');
- expect(contentQuery).toContain('flex-direction: column;');
- expect(contentQuery).toContain('.plugin-catalog-filters');
- expect(contentQuery).toContain('width: auto;');
- expect(contentQuery).not.toContain('flex-wrap: wrap;');
- });
-});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts
deleted file mode 100644
index 0359c13e89..0000000000
--- a/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * unreadDotMotion.test.ts — 未读呼吸点的常驻动画约束(DESIGN.md §14.4 红线)。
- * ---------------------------------------------------------------------------
- * 未读卡与会话卡不同:插件的未读可能**长期存在、多张同屏**(一页插件卡各亮一颗)。
- * 常驻循环动画因此只允许动 transform / opacity(compositor-only);退回 box-shadow /
- * width 这类会触发每帧重绘的属性,会持续吃 CPU 与电量(codex review)。
- *
- * 这条把「呼吸挂在哪个属性上」钉在样式表里,而不是靠 code review 记住。
- * node 环境(不加 jsdom docblock):要用 import.meta.url 直接读源文件。
- *
- * **读进来先归一化行尾**:仓库只对 .sh / .mjs / hooks / .sql 钉了 LF,.css 没钉,
- * Windows 检出成 CRLF。任何按 `\n` 定位的匹配在那边都会落空——本仓已经因为同一类
- * 问题红过(#1448 的 VoiceInputSection 源码正则)。这类「读源文件做断言」的用例
- * 一律不得对检出行尾敏感。
- */
-
-import { readFileSync } from 'node:fs';
-import { fileURLToPath } from 'node:url';
-
-import { describe, expect, it } from 'vitest';
-
-const CSS = readFileSync(
- fileURLToPath(new URL('../../../styles/globals.css', import.meta.url)),
- 'utf8',
-).replace(/\r\n/g, '\n');
-
-describe('未读呼吸点 · 常驻动画红线', () => {
- it('关键帧只动 transform / opacity,不含任何触发绘制或布局的属性', () => {
- // 用正则整块捕获,不靠 indexOf 数括号:嵌套的 `{}` 与行尾差异都不会把它切歪。
- const block = /@keyframes session-card-pulse\s*\{([\s\S]*?)\n\}/.exec(CSS)?.[1];
- expect(block, '找不到 session-card-pulse 关键帧').toBeTruthy();
- expect(block).toMatch(/transform:/);
- expect(block).toMatch(/opacity:/);
- expect(block).not.toMatch(/box-shadow|width|height|top:|left:|background|filter/);
- });
-
- it('动画挂在 ::after 光环上(点本体不参与动画)', () => {
- expect(CSS).toMatch(/\.session-card-dot::after\s*\{[^}]*animation:\s*session-card-pulse/);
- });
-
- it('两处闸门都跟着挂动画的那个元素走 —— 减动偏好停掉、页面隐藏时冻结', () => {
- // 清单按「真正挂动画的那个元素」收敛(见 globals.css 里那段说明),
- // 动画从点本体挪到 ::after 之后,两处选择器也必须跟着挪,否则闸门失效。
- expect(CSS).toMatch(/\.session-card-dot::after,/); // prefers-reduced-motion 清单
- expect(CSS).toMatch(/\[data-app-hidden='true'\] \.session-card-dot::after,/);
- });
-});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketConfirmCopy.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketConfirmCopy.test.ts
deleted file mode 100644
index 0859d10ab4..0000000000
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketConfirmCopy.test.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import zhCNCommon from '@/i18n/locales/zh-CN/common.json';
-
-describe('market confirmation copy', () => {
- it('names the skill in the delete impact description', () => {
- const copy = zhCNCommon.skillhub.marketConfirm.deleteDesc;
-
- expect(copy).toContain('{{name}}');
- expect(copy).not.toContain('这个云端发布物');
- });
-});
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts
deleted file mode 100644
index 23790682c6..0000000000
--- a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { readFileSync } from 'node:fs';
-
-import { describe, expect, it } from 'vitest';
-
-/**
- * 「恢复默认」入口的接线约束。行为链路(提交 null 删 override)由
- * `useVoiceInputSettings.overrideReset.test.ts` 与 main 侧
- * `composerLongPressSetting.test.ts`(「传 null 恢复默认」)覆盖;这里锁住
- * VoiceInputSection 的行级接线,防止入口被静默摘掉又只剩布尔开关。
- */
-describe('VoiceInputSection restore default entries', () => {
- it('shows restore controls only for override-backed switches and restores via null submitters', () => {
- const source = readFileSync(
- new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),
- 'utf8',
- );
-
- // 长按输入框开关:override 存在时才出现「已自定义/恢复默认」,恢复走提交 null 的动作。
- expect(source).toContain('isCustomized={settings.composerLongPressEnabledOverride != null}');
- expect(source).toContain('void resetComposerLongPressEnabled()');
- // 词典同步开关与长按开关同一套 override 约定,入口必须成对存在。
- expect(source).toContain('isCustomized={settings.dictionarySyncEnabledOverride != null}');
- expect(source).toContain('void resetDictionarySyncEnabled()');
- });
-
- it('restore helpers submit null instead of writing a static default snapshot', () => {
- const source = readFileSync(
- new URL('../../hooks/useVoiceInputSettings.ts', import.meta.url),
- 'utf8',
- );
-
- expect(source).toContain('runOverrideReset({ composerLongPressEnabled: null })');
- expect(source).toContain('runOverrideReset({ dictionarySyncEnabled: null })');
- });
-});
diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts
index 37ec3e82c0..81c1bb4c3e 100644
--- a/apps/desktop/vitest.config.ts
+++ b/apps/desktop/vitest.config.ts
@@ -8,11 +8,13 @@ const cliTestExclude = parseVitestCliExclude(process.argv.slice(2));
const desktopTestInclude = [
'src/main/__tests__/**/*.test.ts',
'src/main/**/__tests__/**/*.test.ts',
- 'src/renderer/__tests__/**/*.test.ts',
- 'src/renderer/**/__tests__/**/*.test.ts',
+ // Renderer tests may live in a feature test directory or beside the
+ // production module (for example src/renderer/lib/*.test.ts). Keep the
+ // pattern broad so a new test cannot silently fall outside the unit gate.
+ 'src/renderer/**/*.test.ts',
// renderer 组件测试(React,tsx):按文件头 `// @vitest-environment jsdom`
- // 切 DOM 环境;此前 include 只收 .test.ts,tsx 用例根本不会被跑。
- 'src/renderer/**/__tests__/**/*.test.tsx',
+ // 切 DOM 环境;根目录和嵌套目录都由上面的模式覆盖。
+ 'src/renderer/**/*.test.tsx',
'src/preload/__tests__/**/*.test.ts',
// shared 是 main/renderer 共用的纯函数层;此前漏配导致 src/shared/__tests__
// 下的测试(如 workingDir.test.ts)从未跑过。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 6fd05c93f9..11e4f2ab35 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -1140,7 +1140,7 @@ Only the two registered chart members inside Usage History may enlarge their non
- **Composer toolbar: two chrome tiers, one set shared between in-session and the create dialog (finalized 2026-07-22)**:
- **Morphing-dropdown tier (+/permission/model)**: bare at rest (`border border-transparent bg-transparent`); the pill outline appears only on hover (`hover:border-[var(--border-default)]` + `composer-pill-bg`); selected/danger tiers tint the text only, never the fill.
- **Persistent-tool tier (voice/send)**: permanent outline / solid CTA (voice: `composer-pill-bg` + `border-default`, hover `model-trigger-hover`, recording state `surface-chip` fill + red-dot timer expansion; send: `send-btn-*` neutral-inverse solid).
- - **In-session (default) and the create dialog (create-agent) must match verbatim**: the five shared controls (+/permission/model/voice/send) no longer fork styles by `visualVariant`; `create-agent-control-*` / `create-agent-send-*` must not be used for these five controls (legacy segmented token IDs remain for theme compatibility; the top mode/project/branch pills retain their existing roles). Changing any control's chrome changes both surfaces. Contract test: `newMakerCreateAgentVisualContract.test.ts`.
+ - **In-session (default) and the create dialog (create-agent) must match verbatim**: the five shared controls (+/permission/model/voice/send) no longer fork styles by `visualVariant`; `create-agent-control-*` / `create-agent-send-*` must not be used for these five controls (legacy segmented token IDs remain for theme compatibility; the top mode/project/branch pills retain their existing roles). Changing any control's chrome changes both surfaces. Verify this at the real component boundary when the shared controls change.
- **Quota-reset confetti** — the third sanctioned motion class (approved 2026-07-23), **only** for the status-bar usage chip’s full-quota reveal (updated by user decision, 2026-09-12):
- **Definition**: the first observation of 100% remaining quota throws confetti once from the full window segment, including the first visit. Deduplicate by provider across task switches and component remounts. After that first burst, the quota must drop below 100% and return to 100% before another burst. Remaining at 100% never replays, even across scheduled cycles. Reset deadlines do not participate in this decision; official extra resets follow the same rule. Snapshot update timestamps only reject stale task data. The percentage roll keeps its own reset detection.
- **Form** (finalized over four/five review rounds, 2026-07-23): **true parabolic toss + vanish on landing** — all particles launch simultaneously from the segment center in a ~**100° fan** (±50° of straight up) at equal speed, **constant horizontal velocity + constant vertical gravity** (decelerating up, accelerating down past the apex), so perceived speed is consistent from burst to fall; wider-angle particles fly lower arcs, travel farther, land earlier — the scatter comes from physics, not scripting. The final stretch before the ground line ends in a **short fade**: landing is fine, but lingering after landing ("corpsing") or vanishing without a fade is forbidden; the ground line jitters randomly so landing points don't queue up.
@@ -1745,7 +1745,7 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
- the 268px cap is dead (a leftover of the Figma frame height — the root cause of content sitting high on large windows); 28% is device-tuned (from 25.5%);
- `--content-header-h` is broadcast by `ContentHeaderSlot` (inside FeatureSidebarSlotProvider) through a display:contents wrapper (46px rendered / 0px hidden, same source as ContentHeader `h-[46px]`) — content stays pinned at the "header present" position with **zero jump** when selecting a project toggles the header;
- header visibility has a single decision source = `useContentHeaderHidden` (mac + sidebar expanded + no injected content + no right-panel toggle; continues the 2026-06-11 "hide empty header" ruling);
- - guard: `newMakerCreateAgentVisualContract` locks the position formula + anti-regression assertions.
+ - guard: the position formula and its anti-regression assertions are part of the create-page review contract.
- **Hover-token discipline**: `--update-btn-hover` is exclusively the upgrade button's hover (inverse dark CTA) — **forbidden** on ordinary ghost buttons/badges (near-black `#2E3237` under CINDY light swallows text and icons; 6 misuses cleaned up 2026-07-21). Correct picks:
- titlebar-area (ContentHeader) ghost elements → `titlebar-button-hover` (same as the ChromeActions window buttons);
- general light hover in the content area → `--surface-hover`.
diff --git a/docs/design-rules/design-decision-log.md b/docs/design-rules/design-decision-log.md
index 18102a60b8..548a22f5d9 100644
--- a/docs/design-rules/design-decision-log.md
+++ b/docs/design-rules/design-decision-log.md
@@ -432,7 +432,7 @@
代码内部标识(`AuthState mode='local'`、`authEnterLocal` IPC、data owner)不受影响,仍用 local。
术语已登记 `not-signed-in` / `skip-sign-in` 两条 proposed(`i18n/glossary.json`)。
(→ `DESIGN.md §16` 协议门表 + 协议行整行热区条 / `LoginPage.consent.test.tsx`
- 与 `LoginPage.region.harness.test.tsx` 的过门断言 / `userInfoSectionHover.test.ts` 头像契约)
+ 与 `LoginPage.region.harness.test.tsx` 的过门断言 / UserInfoSection 的组件行为测试)
- **07-29** **手机端功能区落位改回新稿标注值(拍板人 = 用户,依据 = 实机比例对照图)**——
本条**修正**下方 07-28 记录里「功能区落位保持 main 原值不动」那一句(该句作废,原记录
保留在册)。**背景**:07-28 剥离手机端跳过登录时,把功能区落位一并退回 main
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.md
index b12b5dc41e..002f286e1f 100644
--- a/docs/dev-rules/desktop-unit-test-performance.md
+++ b/docs/dev-rules/desktop-unit-test-performance.md
@@ -15,6 +15,88 @@ pnpm benchmark:desktop-workers -- --workers 1,2,4,8 --runs 1 --output <report.js
或分池前后必须使用同一 checkout、同一机器和同一测试范围比较;单次数据需同时保留稳定性
结果,不得只挑最快的一次。
+## 2026-10-16 CI 关键路径与分片调整
+
+数据来自 main 上两次成功的 client-ci(run 38819825618、38805666371,当时为 2 个分片):
+
+| Job | 总耗时 | 主要组成 |
+| --- | --- | --- |
+| Windows 分片 1/2 | 34.1–34.2 分钟 | 准备约 3;runner 自测 3.1–3.2;Desktop unit 20.9(1,253 秒);Mobile 2.5;其余包 3.4;伴侣 DB 回归 0.9 |
+| Windows 分片 2/2 | 21.9–25.7 分钟 | Desktop unit 16.9(1,013 秒) |
+| Linux 分片 | 13.8–23.9 分钟 | Desktop unit 547–890 秒 |
+| verify-checks | 7.7–8.4 分钟 | Desktop typecheck 3.4–3.8 |
+
+- 关键路径是 Windows 分片 1,比分片 2 多 8–12 分钟:约 4 分钟来自只在分片 1 执行的 runner 自测和
+ DB 回归,其余来自 Vitest 按文件路径哈希均分(不看耗时)造成的 Desktop 不均衡。
+- 每个分片里 runner 先独占跑 Desktop,再独占跑 Mobile,最后并发跑其余包;Desktop 在 4 vCPU 的
+ `windows-latest` 上用 4 个 worker。
+- 删除 488 条无效用例只占约 5.4 万条的 0.9%,旧 timing 估算约 7 秒 worker time,对墙钟的影响是
+ 个位数秒。删测试解决的是维护成本,不是 CI 时长。
+
+2026-10-16 调整:Windows 与 Linux unit 都从 2 个分片改为 4 个;Windows runner 自测和伴侣 DB 回归
+移到独立并行 job `windows-runner-checks`,由原必需检查 `Windows unit tests` 一并阻断。本仓是公开仓,
+标准 runner 不计费。按上表估算,Windows 每片约为准备 3 分钟 + Desktop 9–11 分钟 + Mobile 与其余包
+2–3 分钟,整条 CI 约 17–20 分钟。**这是估算,必须用首次 4 分片 CI 的实测替换。**
+
+Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时,文件少的包末尾分片可能为空(6 个文件
+分 4 片是 2、2、2、0)。runner 原来只在「文件数少于分片数」时补 `--passWithNoTests`,本机 4/4 分片因此
+有 6 个包报 `NO_TESTS_REQUIRED`;现已按 Vitest 的切分方式判断空分片。
+
+### 2026-10-16 实验与落地
+
+本机 Windows、32 CPU、Desktop 8 worker。隔离方式三组用同一分片(869 个文件)连续对照:
+
+| 实验 | 结果 | 结论 |
+| --- | --- | --- |
+| 基线:forks + 逐文件隔离 | 108.3 秒,0 失败 | — |
+| `--no-isolate` | 83.0 秒(−23%),150 个文件/1,283 条用例失败 | 不采用:测试之间互相污染状态。**不要在真实 checkout 里用 `--no-isolate` 跑 Desktop 单测**:这次实验中 git/HOME 的 mock 泄漏,某个 worktree 测试在真实仓库对 `apps/desktop` 执行了 checkout,把未提交改动全部还原,还生成了 `apps/desktop/unused-test-home/` |
+| `--pool=vmForks` | 80.0 秒(−26%),41 个文件失败 | 不采用:要逐个修复 VM 上下文差异 |
+| `codexProxyHost.test.ts`:逐用例 `vi.resetModules()` 改为生产 `disposeCodexProxy()` 加启动注入复位 | 105 秒 → 6.7 秒,285/285;3 个随机顺序全过 | 已落地。原版在随机种子 1 下就失败(logger mock 跨用例累计),一并修复 |
+| `maker-core` 用 1/2/4 个 worker | 248/125/65 秒,全过 | 已落地:独占运行、用满 worker,排在 Mobile 之后 |
+| 单测分片 checkout 不拉全部历史 | 静态确认单测不读仓库历史 | 已落地,CI 每片约省 0.5 分钟(待 CI 实测) |
+| 声明 jsdom 但没用 DOM 的文件 | 仅约 20 个,约 10 秒 worker 时间 | 不单独处理,写进性能预算 |
+
+每片的 worker 时间里,收集(导入模块)约 325–350 秒,执行测试 250–480 秒,环境初始化 105–127 秒,
+准备约 46 秒;后三项主要来自逐文件隔离。整体切换隔离方式会破坏正确性,所以改为逐个修掉开销最大的
+文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 516 个
+文件,只减不增,见 engineering-conventions.md §3.2「性能预算」)。修完 `codexProxyHost` 后,最慢的
+单个文件从 138 秒降到约 32 秒,不再由一个文件决定分片下限。
+
+优化后按 CI 方式(runner、4 分片、Windows tar、无 `XDT_*`)完整重跑:门禁、`test:runner`、guard、typecheck
+全部通过;4 个分片只有 `taskWorkspace.test.ts` 1 条 symlink 能力失败。各片 `maker-core` 从 71/21/54/108 秒
+降到 34/5/27/55 秒;含 `codexProxyHost` 的 Desktop 分片从 144 秒降到 117 秒。代码没动的 Desktop 分片同时
+慢了约 20%,说明本机(同时运行其他重负载程序)整片墙钟有 ±20% 的波动,收益以上表的同机连续对照为准,
+CI 时长仍要用首次 4 分片 CI 实测确认。
+
+后续候选(每项都要在同一 runner、同一分片配置下实测后才能声称收益):
+
+- 按历史耗时分配分片(自定义 Vitest sequencer),拉平哈希均分造成的不均衡。
+- 把 Windows checkout 与临时目录放到 Dev Drive(ReFS),降低大量小文件 IO 的开销。
+- 基线中逐用例重置最多的 `newMakerDraft.test.ts`(54 处)、`modelVisibilityPrefs.test.ts`(18 处)、
+ `pi-package-store-security.test.ts`(17 处)按 `codexProxyHost` 的方式改;真实 I/O 重的
+ `llamaCppService`、`proxy-auth`、`updateService` 评估是否迁到专用 tier。
+- PR 阶段只跑受影响的 workspace、合并队列跑全量:需要先修改上面「PR 门禁完整覆盖」的规则,由维护者决定。
+
+## 2026-10-15 测试审计结果
+
+对 499 个候选文件逐一审计:
+
+- 删除 81 个没有生产入口行为的文件(488 条用例)。`FileTreeView.horizontalScroll.test.tsx` 真实挂载
+ 组件并断言可见宽度,已恢复。
+- 207 个 PARTIAL 文件(2,874 条用例,其中约 991 条是静态或重复接线候选)保留:它们与续跑、设备链、
+ 账户切换、Pi、权限和竞速回归混在一起,只能在补上等价的生产入口测试后逐项替换,不能按字符串模式
+ 批量删除。
+- 27 个只保护跨文件安全、权限、主题或文案契约的文件(80 条用例)迁到 Desktop `guard` allowlist,由 CI
+ 的 `pnpm test:guard` 执行。名单只在 `scripts/test-workspaces.config.mjs` 维护,由 runner 从 unit 排除;
+ 不要在 `apps/desktop/vitest.config.ts` 的项目 exclude 里重复排除,否则 guard 层自己也收集不到这些
+ 文件(2026-10-16 发现 29 个 allowlist 文件实际只跑了 2 个,已修复)。
+- 缺少 timing 的文件是 `src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts`。
+
+本机(Windows、32 CPU)按当时的 Desktop unit tier 实跑:3,448 个文件/53,987 条测试,53,814 通过、
+168 跳过,墙钟 414.5 秒。5 条失败都是当前账户无法创建目录 symlink 的 EPERM 能力探测路径
+(`taskWorkspace.test.ts` 1 条、`pluginNamespaceMigration.manager.test.ts` 4 条),需要在支持 symlink 的
+Windows CI 或 Developer Mode 下复验,不能 skip 或删除。本机未分片的结果不能直接和 CI 分片耗时比较。
+
## 2026-07-26 Windows 基线
环境:Windows x64、Node v24.15.0、32 available CPUs、63.8 GiB RAM。测试范围为
diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.md
index 9e5458d6ba..7854d1681f 100644
--- a/docs/dev-rules/engineering-conventions.md
+++ b/docs/dev-rules/engineering-conventions.md
@@ -89,7 +89,92 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V
`scripts/__tests__/test-workspaces.test.mjs` 是 tier 边界的可执行契约;调整测试命名、include
或 exclude 时必须同步更新并运行 `pnpm test:runner`。
-### 3.2 路径断言的跨平台宪法
+### 3.2 新增测试的价值门槛
+
+测试数量不是覆盖质量。后续 Agent 新增或改写测试时,每个测试文件在 PR 描述或邻近注释中都
+要能回答「它保护哪个真实行为、历史 bug 或稳定契约」。没有可观察行为变化的重构、文档和
+纯类型调整,不为了凑覆盖率新增测试。
+
+- **测生产行为**:优先调用被测模块的公开函数、handler 或真实组件入口,断言用户可观察的
+ 结果、错误语义、权限边界、数据持久化或协议结构。禁止复制生产函数、常量表、JSX 或
+ Tailwind 字符串后再与副本比较;只证明“源码里出现了某段字面量”的测试不算行为覆盖。
+- **回归测试先红后绿**:修 bug 时先用最小用例复现修复前的失败,再验证修复后的通过。若
+ 只能测试静态契约,必须写出规则编号和保留原因,并把它放进明确的 guard/静态检查位置,
+ 不要把普通布局、类名、import 或调用顺序扫描伪装成 unit test。只包含跨文件静态契约的
+ Desktop 测试文件必须加入 `scripts/test-workspaces.config.mjs` 的 guard allowlist,并由
+ CI 的 `pnpm test:guard` 执行;混合文件中的静态断言只有在保护权限、凭证、协议或竞态
+ 规则且无法从生产入口隔离时才保留,并在测试名或注释中写明失效后果。没有对应规则或
+ 失效后果的源码字面量断言直接删除。
+- **控制文件数量**:同一领域的输入矩阵优先加入现有测试文件并使用表驱动;只有测试环境、
+ 生命周期、隔离资源或 tier 不同,才新建文件。一个文件只放一两个机械断言,或把同一行为
+ 拆成多个重复文件,必须合并或说明为什么不能合并。
+- **不重复断言**:每条用例都应区分一个实际行为分支。只断言内部函数被调用,却不验证
+ 由此产生的用户可观察结果、错误语义、持久化或时序,通常没有独立价值;常量等于字面量、
+ 某个 class/属性存在、或重复同一 happy path 的用例应删除。调用、字面量或属性本身若是
+ 对外协议,可以保留,但要在测试名和注释中写明协议及失效后果。
+- **隔离和分层**:默认 unit 使用进程内依赖注入、内存 fake;真实网络、外部进程、真实 Git
+ 矩阵、SQLite migration 和严格计时进入已有专用 tier。不要为了让 unit 变绿而把真实资源
+ 粗暴 mock 掉,也不要在测试里新增全局锁。
+- **先查已有覆盖**:新增前先搜索相邻测试和相关入口;如果已有用例覆盖同一行为,只补缺失
+ 的输入或回归条件,不复制一套断言。删除候选测试时要确认剩余测试仍经生产入口覆盖该风险。
+
+Agent 在提交新增测试前必须在 PR 描述或测试文件邻近注释中填清四项:被测生产入口和
+用户可观察结果、对应的历史 bug/规则编号、现有覆盖为什么不够、以及最小失败输入和
+所属 tier。四项有一项答不出来就不新增测试;修复后仍要保留能在回归前失败的最小断言,
+不要用更多 happy path 来替代。
+
+建议直接复制下面的模板填写;同一 PR 有多个测试文件时逐文件填写,不能用一句“补充覆盖”
+代替:
+
+~~~text
+测试价值
+- 生产入口与可观察结果:<调用哪个公开函数/handler/组件入口;用户或协议会看到什么>
+- Bug/规则依据:<issue、回归提交或规则章节;没有就不新增>
+- 现有覆盖缺口:<为什么相邻测试没有覆盖这个分支>
+- 最小失败输入:<触发旧错误的最小输入、状态或时序>
+- tier:<unit / guard / db / integration / e2e;为什么放这里>
+- 实测耗时:<单独运行该文件的墙钟,例如 pnpm --dir apps/desktop exec vitest run <文件>>
+~~~
+
+用例的停止条件是覆盖完不同的结果分支:同一入口、同一结果只保留一个最小代表,更多
+输入用表驱动表达;当新增用例不能指出新的结果、错误、权限、持久化、协议或时序差异时
+就停止。不要设置“每个函数都要一个测试”或“覆盖率必须再涨一点”的数量目标,也不要
+为了填满文件、提高测试条数或证明测试框架本身而新增用例。
+
+评审可以直接要求删掉无法指出生产行为或契约的测试;“测试通过”本身不能证明它有价值。
+
+#### 性能预算(与价值门槛同等强制)
+
+单测的成本主要不在用例条数,而在每个文件的准备、收集(导入模块)和环境初始化。2026-10-16
+实测 Desktop 每个分片的 worker 时间里,收集阶段与执行测试相当;一个逐用例重置模块的文件
+(`codexProxyHost.test.ts`)就占全部文件耗时的约 10%,不重置时同样 285 条用例从 105 秒降到
+7 秒。新增或改写测试时:
+
+- **单文件预算**:新增或改写的单测文件单独运行应在 5 秒内(本机),超过 10 秒必须在 PR
+ 写明原因,并优先改用文件级 fixture、依赖注入或迁移 tier;不得用放宽 timeout 掩盖。
+ 「测试价值」模板里填写实测耗时。
+- **模块只加载一次**:默认在文件顶部静态 import 被测模块。需要干净的模块级状态时,调用
+ 生产代码已有的 dispose/reset 或注入依赖;`vi.resetModules()` 只用于确实在验证「重启/
+ 重新加载」语义的边界,上一行写 `// reset-modules: <被隔离的状态>`,禁止放进
+ `beforeEach` 或每个用例都会调用的 helper。
+- **不做真实等待**:不用 ≥100ms 的 `setTimeout`/`sleep` 等异步结果,改用
+ `vi.useFakeTimers()`、`vi.waitFor`/事件,或直接 await 被测 Promise。确需真实等待时上一行写
+ `// real-wait: <原因>`。
+- **环境按需**:只有真正渲染组件或操作 DOM 的文件才声明 `@vitest-environment jsdom`,纯逻辑
+ 留在 node 环境;jsdom 每个文件约多 0.5 秒初始化。
+- **不新开小文件**:同一被测模块的新用例加进已有文件并用表驱动;每个新文件都要多付一次
+ 准备、收集和环境初始化。不超过 3 条用例的新文件必须说明为什么不能并入。
+- **重 I/O 下沉**:真实子进程、真实 socket、真实 Git 或大量文件 I/O 让单文件超预算时,迁移到
+ §3.1 的专用 tier,不要留在默认 unit。
+
+**机器门禁**:CI verify 运行 `pnpm check:test-hygiene`(`scripts/check-test-hygiene.mjs`)并阻断
+三类问题:没有写理由的 `vi.resetModules()`、没有写理由的 ≥100ms 真实等待、普通单测读取生产源码
+文本(这类静态契约只能进 guard tier,不接受理由豁免)。存量计数记在
+`scripts/test-hygiene-baseline.json`,只允许减少;修掉存量后运行
+`node scripts/check-test-hygiene.mjs --update` 收紧基线。不得手改基线放宽计数让门禁变绿;确有
+必要时在 PR「风险」中说明,由评审确认。
+
+### 3.3 路径断言的跨平台宪法
测试必须先区分路径代表的语义,不能把当前开发机的路径表示误当成跨平台事实:
@@ -111,8 +196,10 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V
依赖注入/纯函数用例保留等价覆盖;禁止按 `process.platform` 大面积跳过后让整个 CI 矩阵
失去相应回归保护。
-PR 门禁必须在 Windows 上用两个并行分片完整覆盖 `pnpm test:unit`;两个分片的并集必须等价于
-未分片的全量测试,且由稳定的汇总检查统一阻断。`scripts/__tests__/dev-docs-contract.test.mjs` 锁住
+PR 门禁必须在 Windows 上用多个并行分片(当前为 4 个)完整覆盖 `pnpm test:unit`;所有分片的
+并集必须等价于未分片的全量测试,且由稳定的汇总检查统一阻断。分片数可以按 CI 实测耗时调整,
+但分片矩阵必须连续列出 1..N 并与 `XDT_UNIT_TEST_SHARD` 的 N 一致;只需执行一次的检查放在
+独立并行 job,不叠加在某个分片上。`scripts/__tests__/dev-docs-contract.test.mjs` 锁住
该 CI 契约。不能用静态扫描“测试字符串是否含斜杠”代替 Windows 实跑,因为它无法可靠区分宿主
路径与逻辑路径。
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 398c1343fc..34cb34cd0b 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -458,7 +458,7 @@ Mobile 的入口读取和残留表单提交都检查该身份,元数据补齐
- MCP 工具:`cindy_orca` 20 工具(17 team + 3 只读诊断)的 role gate、ctx 缺失、worker/main 误调用、soft/hard limit、duplicate label、budget model API mode gate;`create_workers` 另覆盖默认 hard limit、配置 hard=3、部分成功、连续失败与 hard-limit 后不再调用 host;诊断工具的纯只读语义(无 active team 时返回空 workspace、不建 team);排队消息控制 6 工具的归属校验(跨 lead 拒绝)、完整 consuming 投影、非 lead 条目拒绝(`NOT_LEAD_MESSAGE`)、自身队列非协同条目拒绝(`NOT_ORCA_MESSAGE`)、steering 拒绝(`MESSAGE_CONSUMING`)、撤回结清 accepted 暂存、合并的连续性、冲突零修改与移除回调结清,以及转插话的原因回执与排序落点;`send_to_worker` / `send_to_lead` 的 `delivery` 缺省不透传、显式插话与各类 fallback 原因;`interrupt_worker` 另覆盖队首预留、暂停态、graceful-stop 全部 outcome、auto-bridge 抑制和 done 互斥。
- Codex MCP context:`CodexMcpThreadContextStore` 覆盖按 threadId 查 context、unknown / missing threadId fail-closed、unregister 后清理、`vendorOptions` 引用保持;`codexHttpBridge` 覆盖从 JSON-RPC `params._meta.threadId` 注入真实 session context。
- Host 归属校验:`send_to_worker`、`interrupt_worker`、队列控制、`idle_worker`、`archive_worker` 经共享 `resolveWorkerRef`(同时接受 worker_id / session_id 两种 id)必须以 caller 自身 Lead 身份校验,拒绝跨 workflow worker id 与 ctx 缺失;即使模型传错 id 或换用另一种 id,也不能越权操作。
-- UI route:Orca worker 不出现在 sidebar,Lead 自动进 split route,worker deep link 解析到 Lead split route;已有测试守住“不用 fork parentSessionId 或标题推断 Orca mapping”,见 `apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts` 的 `does not use fork parentSessionId or title-linked worker lookup for Orca mapping`。
+- UI route:Orca worker 不出现在 sidebar,Lead 自动进 split route,worker deep link 解析到 Lead split route;对应行为由 `apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkflowRoute.navigation.test.tsx` 与 `OrcaWorkflowRoute.compat.test.tsx` 覆盖。
- Fork / side_chat 底座:user fork、assistant fork、Codex `tailTurnsToDrop`、Claude turn-final assistant uuid、tool_use 拒绝。
- Worktree:toggle off/on、非 git/已在 worktree 只 disable worktree toggle、不阻断 send;Lead close 后清 worktree。
- 重启后 Lead↔Worker 互访(resume)回归矩阵:覆盖开启路径 `enableTeam` 自动首 worker / MCP `start_team` + `create_worker` / renderer `requestEnableCollab` → `SESSION_ENABLE_ORCA` → `enableTeam`,以及重启时机“对话中途”和“初始化完毕但未对话”;验收动作至少包含 `list_workers` 可见 worker、Lead 侧 `send_to_worker` 可投递或排队、Worker 侧 `send_to_lead` 可回传、focused / idle worker 可 resume。
@@ -537,7 +537,7 @@ defaults 则按当前 snapshot 解析并保存实际来源。这样 Claude Code
#### 9. `parent_session_id` 不表示 Orca 派单(状态:不变量)
-`parent_session_id` 是 fork/session-branch 关系,不是 worker 归属关系。Orca 归属必须查 `orca_teams/orca_workers`。已有 route 测试防止 split view 用 `parentSessionId` 或标题匹配 worker,见 `apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts` 的 `does not use fork parentSessionId or title-linked worker lookup for Orca mapping`。
+`parent_session_id` 是 fork/session-branch 关系,不是 worker 归属关系。Orca 归属必须查 `orca_teams/orca_workers`;route 行为回归见 `apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkflowRoute.navigation.test.tsx` 与 `OrcaWorkflowRoute.compat.test.tsx`。
#### 10. Worker 回收要克制(状态:无损 idle release 已落地)
diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.md
index df00ec11c9..f3554b9848 100644
--- a/docs/product-rules/model-selector-unified.md
+++ b/docs/product-rules/model-selector-unified.md
@@ -258,7 +258,7 @@
## 5. 验收与测试
- 单测:M1 推导规则(含多来源/bridge/前缀归一)、M2 store(含 owner 分区/迁移空态)、滑杆档位色映射、收藏锚点语义。
-- 更新既有锁:`agentSelect`/`chatInputModelSelectorRouting`/`modelSelectorTriggerVariant`/`modelSelectorProviderGroups`/`newMakerCreateAgentVisualContract`/`draftModelCalibration`/`modelDefinitionsDefaults`/`deviceLinkModelMirror` 等——有意变更逐条在 PR「风险」说明。
+- 更新既有锁:`agentSelect`/`chatInputModelSelectorRouting`/`modelSelectorTriggerVariant`/`modelSelectorProviderGroups`/`draftModelCalibration`/`modelDefinitionsDefaults`/`deviceLinkModelMirror` 等——有意变更逐条在 PR「风险」说明。
- 门禁:根 `pnpm test:unit` + `pnpm --filter desktop run typecheck` + `pnpm --filter @cindy/model-providers run --if-present typecheck`。
- 实机:worktree `pnpm restart:desktop:remote --region=global --isolated=model-picker` 双模式目检;未能真实验证的面(如老版本 device-link 对端)在 PR 如实列出+用户验证步骤。
diff --git a/package.json b/package.json
index 7a6a265501..35b10c31e7 100644
--- a/package.json
+++ b/package.json
@@ -125,12 +125,13 @@
"check:brand-terminology": "node scripts/brand-terminology-guard.mjs",
"check:endpoints": "node scripts/check-endpoint-literals.mjs",
"check:dev-docs": "node --test scripts/__tests__/dev-docs-contract.test.mjs",
+ "check:test-hygiene": "node scripts/check-test-hygiene.mjs",
"check:dco": "node scripts/check-dco.mjs",
"dco:install-hook": "node scripts/install-dco-hook.mjs",
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs scripts/__tests__/check-test-hygiene.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs",
"test:workspaces": "node scripts/test-workspaces.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",
diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjs
new file mode 100644
index 0000000000..2de0ad0a6b
--- /dev/null
+++ b/scripts/__tests__/check-test-hygiene.test.mjs
@@ -0,0 +1,72 @@
+// Contract for scripts/check-test-hygiene.mjs: each case is the smallest source
+// that flips one rule decision, so a detector regression cannot silently let
+// slow or source-literal unit tests back into CI.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ compareWithBaseline,
+ scanTestSource,
+} from "../check-test-hygiene.mjs";
+
+test("scanTestSource counts only unjustified hits for each rule", () => {
+ const cases = [
+ ["per-test module reset", "beforeEach(() => { vi.resetModules(); });", { resetModules: 1 }],
+ [
+ "justified module reset",
+ "// reset-modules: auto-sync prefs are module-scoped\nvi.resetModules();",
+ { resetModules: 0 },
+ ],
+ ["commented-out reset", "// vi.resetModules();", { resetModules: 0 }],
+ ["real 250ms wait", "await new Promise((r) => setTimeout(r, 250));", { realWaits: 1 }],
+ ["short wait", "await new Promise((r) => setTimeout(r, 20));", { realWaits: 0 }],
+ [
+ "fake-timer file",
+ "vi.useFakeTimers();\nsetTimeout(tick, 5_000);",
+ { realWaits: 0 },
+ ],
+ [
+ "source text read",
+ "const src = readFileSync(resolve(__dirname, '..', 'Sidebar.tsx'), 'utf8');",
+ { sourceReads: 1 },
+ ],
+ [
+ "import specifiers are not reads",
+ "import { x } from '../x.ts';\nvi.mock('../y.ts');\nreadFileSync(join(__dirname, 'fixtures', 'a.ts'));",
+ { sourceReads: 0 },
+ ],
+ ];
+ for (const [name, source, expected] of cases) {
+ const result = scanTestSource(source);
+ for (const [rule, count] of Object.entries(expected)) {
+ assert.equal(result[rule], count, `${name}: ${rule}`);
+ }
+ }
+ assert.equal(
+ scanTestSource("readFileSync(resolve(__dirname, '../A.tsx'))", { isGuard: true }).sourceReads,
+ 0,
+ "guard-tier files may read source",
+ );
+});
+
+test("compareWithBaseline only lets counts stay or shrink", () => {
+ const baseline = { "a.test.ts": { resetModules: 2 } };
+ const pass = compareWithBaseline(
+ { "a.test.ts": { resetModules: 1, realWaits: 0, sourceReads: 0 } },
+ baseline,
+ );
+ assert.deepEqual(pass.violations, []);
+ assert.deepEqual(pass.tightenable, ["a.test.ts"]);
+
+ const fail = compareWithBaseline(
+ {
+ "a.test.ts": { resetModules: 3, realWaits: 0, sourceReads: 0 },
+ "new.test.ts": { resetModules: 0, realWaits: 1, sourceReads: 0 },
+ },
+ baseline,
+ );
+ assert.deepEqual(
+ fail.violations.map((v) => `${v.file}:${v.rule}:${v.limit}`),
+ ["a.test.ts:resetModules:2", "new.test.ts:realWaits:0"],
+ );
+});
diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjs
index 94f93d51ec..cd4e21231e 100644
--- a/scripts/__tests__/dev-docs-contract.test.mjs
+++ b/scripts/__tests__/dev-docs-contract.test.mjs
@@ -302,26 +302,49 @@ test("runtime versions and the docs contract are code-owned", () => {
assert.match(rootPackage.scripts["test:runner"], /scripts\/__tests__\/dev-docs-contract\.test\.mjs/);
});
-test("client CI keeps the complete two-shard unit gate on Windows", () => {
+// A shard matrix is complete only when it lists every index 1..N and the
+// runner splits by the same N; a missing index or mismatched count would
+// silently drop part of the unit tier from the gate.
+function assertCompleteShardMatrix(job) {
+ const matrix = /^ shard: \[([\d, ]+)\]$/m.exec(job);
+ assert.ok(matrix, "unit shard job must declare a numeric shard matrix");
+ const indexes = matrix[1].split(",").map((value) => Number(value.trim()));
+ const count = indexes.length;
+ assert.ok(count >= 2, "unit shard job must split the tier across parallel jobs");
+ assert.deepEqual(indexes, Array.from({ length: count }, (_, i) => i + 1));
+ assert.match(job, new RegExp(`^ XDT_UNIT_TEST_SHARD: \\$\\{\\{ matrix\\.shard \\}\\}/${count}$`, "m"));
+ assert.match(job, /^ fail-fast: false$/m);
+}
+
+test("client CI keeps the complete sharded unit gate on Windows", () => {
const workflow = readText(".github/workflows/ci.yml");
const shards = workflowJob(workflow, "windows-unit-shards");
assert.ok(shards, "client CI must define Windows unit shards");
assert.match(shards, /^ runs-on: windows-latest$/m);
- assert.match(shards, /^ fail-fast: false$/m);
- assert.match(shards, /^ shard: \[1, 2\]$/m);
- assert.match(shards, /^ XDT_UNIT_TEST_SHARD: \$\{\{ matrix\.shard \}\}\/2$/m);
+ assertCompleteShardMatrix(shards);
assert.match(shards, /^ run: pnpm run test:workspaces --tier unit$/m);
assert.doesNotMatch(shards, /pnpm test:unit(?:\s|$)/);
- assert.equal([...shards.matchAll(/^ run: pnpm test:runner$/gm)].length, 1);
- assert.match(shards, /^ - name: Run Windows test runner self-tests\r?\n if: matrix\.shard == 1\r?\n run: pnpm test:runner$/m);
+ assert.doesNotMatch(shards, /pnpm test:runner/);
+
+ // One-off Windows checks run once, in parallel, outside the shard critical path.
+ const runnerChecks = workflowJob(workflow, "windows-runner-checks");
+ assert.ok(runnerChecks, "client CI must run Windows runner self-tests once");
+ assert.match(runnerChecks, /^ runs-on: windows-latest$/m);
+ assert.doesNotMatch(runnerChecks, /^ needs:/m);
+ assert.doesNotMatch(runnerChecks, /^ strategy:/m);
+ assert.equal([...runnerChecks.matchAll(/^ run: pnpm test:runner$/gm)].length, 1);
+ assert.match(runnerChecks, /botCanonicalSession\.test\.ts/);
const gate = workflowJob(workflow, "windows-unit");
assert.ok(gate, "client CI must preserve the stable Windows unit check");
assert.match(gate, /^ name: Windows unit tests$/m);
assert.match(gate, /^ if: \$\{\{ always\(\) \}\}$/m);
- assert.match(gate, /^ needs: windows-unit-shards$/m);
+ assert.match(gate, /^ - windows-unit-shards$/m);
+ assert.match(gate, /^ - windows-runner-checks$/m);
assert.match(gate, /^ WINDOWS_UNIT_SHARDS_RESULT: \$\{\{ needs\.windows-unit-shards\.result \}\}$/m);
- assert.match(gate, /^ run: test "\$WINDOWS_UNIT_SHARDS_RESULT" = "success"$/m);
+ assert.match(gate, /^ WINDOWS_RUNNER_CHECKS_RESULT: \$\{\{ needs\.windows-runner-checks\.result \}\}$/m);
+ assert.match(gate, /^ test "\$WINDOWS_UNIT_SHARDS_RESULT" = "success"$/m);
+ assert.match(gate, /^ test "\$WINDOWS_RUNNER_CHECKS_RESULT" = "success"$/m);
});
test("client CI runs Linux checks and complete unit shards in parallel behind stable verify", () => {
@@ -330,15 +353,20 @@ test("client CI runs Linux checks and complete unit shards in parallel behind st
assert.ok(checks, "client CI must define independent Linux verification checks");
assert.doesNotMatch(checks, /^ needs:/m);
assert.match(checks, /^ run: pnpm test:runner$/m);
+ assert.match(
+ checks,
+ /^ - name: Run desktop source-contract guards\r?\n run: pnpm test:guard$/m,
+ );
+ // engineering-conventions.md §3.2 performance budget is only binding while CI
+ // blocks on the hygiene ratchet; without this step the baseline stops mattering.
+ assert.match(checks, /^ - name: Check unit test hygiene\r?\n run: pnpm check:test-hygiene$/m);
assert.doesNotMatch(checks, /node scripts\/test-workspaces\.mjs --tier unit/);
const shards = workflowJob(workflow, "linux-unit-shards");
assert.ok(shards, "client CI must define Linux unit shards");
assert.match(shards, /^ runs-on: ubuntu-latest$/m);
assert.doesNotMatch(shards, /^ needs:/m);
- assert.match(shards, /^ fail-fast: false$/m);
- assert.match(shards, /^ shard: \[1, 2\]$/m);
- assert.match(shards, /^ XDT_UNIT_TEST_SHARD: \$\{\{ matrix\.shard \}\}\/2$/m);
+ assertCompleteShardMatrix(shards);
assert.match(shards, /^ run: pnpm run test:workspaces --tier unit$/m);
assert.doesNotMatch(shards, /pnpm test:(?:unit|runner)/);
assert.equal([...shards.matchAll(/--tier integration --workspace @cindy\/maker-pi-manager/g)].length, 1);
diff --git a/scripts/__tests__/hardcoded-color-audit.test.mjs b/scripts/__tests__/hardcoded-color-audit.test.mjs
index 51ac3edb21..3c71ccf1de 100644
--- a/scripts/__tests__/hardcoded-color-audit.test.mjs
+++ b/scripts/__tests__/hardcoded-color-audit.test.mjs
@@ -405,19 +405,27 @@ test('CI design commands feed the existing verify job and preserve Windows aggre
assert.deepEqual(workflow.jobs.verify.needs,['verify-checks','linux-unit-shards']);
const windows=workflow.jobs['windows-unit'];
assert.equal(windows.name,'Windows unit tests');
- assert.equal(windows.needs,'windows-unit-shards');
+ assert.deepEqual(windows.needs,['windows-unit-shards','windows-runner-checks']);
assert.match(windows.if,/always\(\)/);
for(const name of ['linux-unit-shards','windows-unit-shards']) {
const job=workflow.jobs[name];
- assert.deepEqual(job.strategy.matrix.shard,[1,2]);
+ const shards=job.strategy.matrix.shard;
+ assert.ok(shards.length>=2);
+ assert.deepEqual(shards,shards.map((_,i)=>i+1));
assert.equal(job.strategy['fail-fast'],false);
assert.ok(job.steps.some(s=>s.run==='pnpm run test:workspaces --tier unit'));
- assert.ok(job.steps.some(s=>s.name==='Run companion database regressions' && s.if==='matrix.shard == 1'));
}
+ // Companion DB regressions run once per OS: on Linux shard 1, and on Windows
+ // in the parallel one-off job instead of on a shard's critical path.
+ assert.ok(workflow.jobs['linux-unit-shards'].steps.some(s=>s.name==='Run companion database regressions' && s.if==='matrix.shard == 1'));
+ assert.ok(workflow.jobs['windows-runner-checks'].steps.some(s=>s.name==='Run companion database regressions' && s.if===undefined));
+ const gateVars=['$WINDOWS_UNIT_SHARDS_RESULT','$WINDOWS_RUNNER_CHECKS_RESULT'];
for(const result of ['success','failure','cancelled','skipped']) {
- const windowsScript = windows.steps[0].run.replaceAll('$WINDOWS_UNIT_SHARDS_RESULT', result);
- const run=runBash(windowsScript);
- if (!run) return t.skip('Git Bash is unavailable on this host');
- assert.equal(run.status===0,result==='success');
+ for(const target of gateVars) {
+ const windowsScript=gateVars.reduce((script,name)=>script.replaceAll(name,name===target?result:'success'),windows.steps[0].run);
+ const run=runBash(windowsScript);
+ if (!run) return t.skip('Git Bash is unavailable on this host');
+ assert.equal(run.status===0,result==='success',`${target}=${result}`);
+ }
}
});
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 530df077ec..e1cff8a610 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -216,7 +216,9 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
"--maxWorkers=4",
...unitTestShardArgs(),
]);
- assert.equal(makerCore.tiers.unit.execution, undefined);
+ // maker-core scales linearly with workers, so it must not overlap the
+ // one-worker package pool where it used to finish last in every shard.
+ assert.equal(makerCore.tiers.unit.execution, "exclusive");
assert.deepEqual(makerCore.tiers.unit.exclude, [
"**/*.integration.test.ts",
"**/*.e2e.test.ts",
@@ -225,7 +227,12 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
assert.deepEqual(makerCore.tiers.unit.command, {
type: "packageBin",
bin: "vitest",
- args: ["run", "--pool=forks", "--maxWorkers=1", ...unitTestShardArgs()],
+ args: [
+ "run",
+ "--pool=forks",
+ `--maxWorkers=${desktopUnitWorkerCount()}`,
+ ...unitTestShardArgs(),
+ ],
});
});
@@ -505,6 +512,7 @@ test("desktop unit excludes integration, migration, direct db-tier, and source-c
"src/main/scheduler-host/__tests__/*.db.test.ts",
"src/main/__tests__/directSessionSendGuard.test.ts",
"src/main/__tests__/makerSendToSessionOrdering.test.ts",
+ "src/main/__tests__/authCaptchaIpcSecurity.test.ts",
"**/*.bench.ts",
],
};
@@ -524,6 +532,7 @@ test("desktop unit excludes integration, migration, direct db-tier, and source-c
"apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts",
"apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts",
"apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts",
+ "apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.ts",
"apps/desktop/src/main/__tests__/lifecycle.test.ts",
]),
[
@@ -693,16 +702,33 @@ test("desktop guard selects source-contract tests only", () => {
const tier = workspace.tiers.guard;
assert.equal(tier.status, "required");
assert.equal(tier.coverage, "allowlist");
+ // Allowlist entries are exact paths: a renamed or deleted guard file would
+ // otherwise drop out of the gate silently, and one not excluded from unit
+ // would run twice in CI.
+ for (const file of tier.include) {
+ assert.ok(
+ fs.existsSync(path.join(ROOT, workspace.cwd, file)),
+ `guard allowlist entry does not exist: ${file}`,
+ );
+ assert.ok(
+ workspace.tiers.unit.exclude.includes(file),
+ `guard file must be excluded from desktop unit: ${file}`,
+ );
+ }
assert.deepEqual(
selectFilesForTier(workspace, tier, [
"apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts",
"apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts",
+ "apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.ts",
+ "apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts",
"apps/desktop/src/main/__tests__/lifecycle.test.ts",
"apps/desktop/src/main/localDb/ipc/messages.test.ts",
]),
[
"apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts",
"apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts",
+ "apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.ts",
+ "apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts",
],
);
});
@@ -2117,6 +2143,15 @@ test("buildPnpmArgs only loosens Vitest sharding for undersized workspaces", ()
]).includes("--passWithNoTests"),
false,
);
+
+ // Vitest slices ceil(6 / 4) = 2 files per shard, leaving shard 4 empty even
+ // though the workspace has more files than shards.
+ const sixFiles = Array.from(
+ { length: 6 },
+ (_, i) => `packages/example/src/case-${i}.test.ts`,
+ );
+ assert.equal(buildShard("3/4", sixFiles).includes("--passWithNoTests"), false);
+ assert.equal(buildShard("4/4", sixFiles).includes("--passWithNoTests"), true);
});
test("runPlannedTests all mode runs required configured tiers and skips manual tiers", async () => {
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
new file mode 100644
index 0000000000..60432511dc
--- /dev/null
+++ b/scripts/check-test-hygiene.mjs
@@ -0,0 +1,259 @@
+#!/usr/bin/env node
+// check-test-hygiene.mjs — 单测性能与价值的静态门禁(engineering-conventions.md §3.2)。
+//
+// 跑:node scripts/check-test-hygiene.mjs 检查(CI 阻断)
+// node scripts/check-test-hygiene.mjs --update 把基线收紧到当前计数(只降不升)
+//
+// 三条规则都只看源码文本,结果与机器快慢无关:
+// reset-modules 每次 vi.resetModules() 都会让后续 import 重新求值整条模块链。
+// codexProxyHost.test.ts 逐用例重置时 285 条用例耗时 105s,不重置只要 7s。
+// 新增调用必须在上一行写 `// reset-modules: <被隔离的模块状态>`。
+// real-wait 单测里 ≥100ms 的真实 setTimeout / sleep 既拖慢 CI 又制造时序抖动;
+// 改用 vi.useFakeTimers() 或等待真实事件。确需真实等待时上一行写
+// `// real-wait: <原因>`。调用 vi.useFakeTimers() 的文件不计。
+// source-read 普通单测读取生产源码文本做字面量断言。这类静态契约只能进 Desktop
+// guard tier(scripts/test-workspaces.config.mjs),不接受理由豁免。
+//
+// 存量计数记在 scripts/test-hygiene-baseline.json,只允许减少:某文件的计数超过基线、
+// 或基线外的文件出现未豁免的命中,都会失败。`--update` 只会把基线往下收紧;确需放宽
+// 只能手改 JSON,让评审在 diff 里看见。
+
+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import process from 'node:process';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const BASELINE_PATH = path.join(ROOT, 'scripts', 'test-hygiene-baseline.json');
+const SCAN_ROOTS = ['apps', 'packages'];
+const SKIP_DIRS = new Set(['node_modules', 'dist', 'out', 'build', 'coverage', '.vite', '.expo', '.turbo']);
+const TEST_FILE = /\.test\.(?:ts|tsx|mts|mjs)$/;
+const NON_UNIT_TEST = /\.(?:integration|e2e|git-integration)\.test\.|\.bench\./;
+export const RULES = ['resetModules', 'realWaits', 'sourceReads'];
+const REAL_WAIT_MIN_MS = 100;
+
+/** Replace comments with spaces (keeping newlines) so matches ignore commented-out code. */
+export function stripComments(source) {
+ let out = '';
+ let i = 0;
+ let quote = null;
+ while (i < source.length) {
+ const ch = source[i];
+ const next = source[i + 1];
+ if (quote) {
+ out += ch;
+ if (ch === '\\') { out += next ?? ''; i += 2; continue; }
+ if (ch === quote) quote = null;
+ i += 1;
+ continue;
+ }
+ if (ch === '/' && next === '/') {
+ while (i < source.length && source[i] !== '\n') { out += ' '; i += 1; }
+ continue;
+ }
+ if (ch === '/' && next === '*') {
+ while (i < source.length && !(source[i] === '*' && source[i + 1] === '/')) {
+ out += source[i] === '\n' ? '\n' : ' ';
+ i += 1;
+ }
+ out += ' ';
+ i += 2;
+ continue;
+ }
+ if (ch === '"' || ch === "'" || ch === '`') quote = ch;
+ out += ch;
+ i += 1;
+ }
+ return out;
+}
+
+function lineOf(text, index) {
+ let line = 0;
+ for (let i = 0; i < index; i += 1) if (text.charCodeAt(i) === 10) line += 1;
+ return line;
+}
+
+/** True when the closest non-blank line above `line` carries `// <marker>: <reason>`. */
+function hasJustification(lines, line, marker) {
+ for (let i = line - 1; i >= 0; i -= 1) {
+ const text = lines[i].trim();
+ if (text === '') continue;
+ return new RegExp(`//\\s*${marker}:\\s*\\S`).test(text);
+ }
+ return false;
+}
+
+function countMatches(code, lines, pattern, marker, accept = () => true) {
+ let count = 0;
+ for (const match of code.matchAll(pattern)) {
+ if (!accept(match)) continue;
+ if (!hasJustification(lines, lineOf(code, match.index), marker)) count += 1;
+ }
+ return count;
+}
+
+const IMPORT_CONTEXT = /(?:\bfrom|\bimport|\brequire|\.mock|\.doMock|\.unmock|\.importActual|\.importMock|\.glob)\s*\(?\s*$/;
+const SOURCE_EXT = /\.(?:tsx?|mts|cts|css|mjs|cjs|jsx?)$/;
+// Only anchors that point into the checkout count; generic names such as `root`
+// usually hold an mkdtemp() directory whose fake source files are test input.
+const REPO_ANCHOR = /__dirname|import\.meta\.(?:url|dirname)|\b(?:REPO_ROOT|repoRoot|desktopRoot)\b/;
+
+function isSourcePathLiteral(code, match) {
+ const value = match[2];
+ if (!SOURCE_EXT.test(value) || /fixture|:\/\//i.test(value)) return false;
+ if (IMPORT_CONTEXT.test(code.slice(Math.max(0, match.index - 24), match.index))) return false;
+ const lineStart = code.lastIndexOf('\n', match.index) + 1;
+ const lineEnd = code.indexOf('\n', match.index);
+ const line = code.slice(lineStart, lineEnd === -1 ? undefined : lineEnd);
+ // Test data under a fixtures directory is input, not production source.
+ if (/fixture/i.test(line)) return false;
+ // resolve(__dirname, '..', 'Sidebar.tsx') or new URL('../x.ts', import.meta.url).
+ if (REPO_ANCHOR.test(line)) return true;
+ // readFileSync('../x.ts') reads relative to the test process, i.e. the checkout.
+ return /\breadFile(?:Sync)?\s*\(/.test(line) && (value.startsWith('./') || value.startsWith('../'));
+}
+
+/** Count unjustified rule hits in one unit test file. */
+export function scanTestSource(source, { isGuard = false } = {}) {
+ const code = stripComments(source);
+ const lines = source.split(/\r?\n/);
+ const resetModules = countMatches(code, lines, /\bvi\.resetModules\s*\(/g, 'reset-modules');
+ const usesFakeTimers = /\bvi\.useFakeTimers\s*\(/.test(code);
+ const realWaits = usesFakeTimers
+ ? 0
+ : countMatches(
+ code,
+ lines,
+ /\bsetTimeout\s*\([^;\n]*?,\s*(\d[\d_]*)\s*\)|\b(?:sleep|delay|wait|waitMs|pause)\s*\(\s*(\d[\d_]*)\s*\)/g,
+ 'real-wait',
+ (match) => Number((match[1] ?? match[2]).replaceAll('_', '')) >= REAL_WAIT_MIN_MS,
+ );
+ let sourceReads = 0;
+ if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw['"`]/.test(code)) {
+ for (const match of code.matchAll(/(['"`])([^'"`\n$]+)\1/g)) {
+ if (match[2].endsWith('?raw') || isSourcePathLiteral(code, match)) sourceReads += 1;
+ }
+ }
+ return { resetModules, realWaits, sourceReads };
+}
+
+function walk(dir, out) {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (entry.isDirectory()) {
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) walk(path.join(dir, entry.name), out);
+ } else if (TEST_FILE.test(entry.name) && !NON_UNIT_TEST.test(entry.name)) {
+ out.push(path.join(dir, entry.name));
+ }
+ }
+}
+
+async function loadGuardFiles(root) {
+ const configUrl = pathToFileURL(path.join(root, 'scripts', 'test-workspaces.config.mjs'));
+ const { default: manifest } = await import(configUrl.href);
+ const guard = new Set();
+ for (const workspace of manifest.workspaces) {
+ for (const file of workspace.tiers?.guard?.include ?? []) {
+ guard.add(path.posix.join(workspace.cwd, file));
+ }
+ }
+ return guard;
+}
+
+export async function scanRepository(root = ROOT) {
+ const files = [];
+ for (const scanRoot of SCAN_ROOTS) walk(path.join(root, scanRoot), files);
+ const guard = await loadGuardFiles(root);
+ const counts = {};
+ for (const file of files.sort()) {
+ const rel = path.relative(root, file).split(path.sep).join('/');
+ const result = scanTestSource(readFileSync(file, 'utf8'), { isGuard: guard.has(rel) });
+ if (RULES.some((rule) => result[rule] > 0)) counts[rel] = result;
+ }
+ return counts;
+}
+
+/** Compare current counts with the ratchet baseline. */
+export function compareWithBaseline(counts, baseline) {
+ const violations = [];
+ const tightenable = [];
+ for (const [file, current] of Object.entries(counts)) {
+ const allowed = baseline[file] ?? {};
+ for (const rule of RULES) {
+ const limit = allowed[rule] ?? 0;
+ if (current[rule] > limit) violations.push({ file, rule, current: current[rule], limit });
+ }
+ }
+ for (const [file, allowed] of Object.entries(baseline)) {
+ const current = counts[file] ?? {};
+ if (RULES.some((rule) => (current[rule] ?? 0) < (allowed[rule] ?? 0))) tightenable.push(file);
+ }
+ return { violations, tightenable };
+}
+
+const HINTS = {
+ resetModules: '只在被测的模块级状态确实需要重建的边界调用,上一行写 `// reset-modules: <原因>`;优先用生产代码的 dispose/reset 或依赖注入',
+ realWaits: '改用 vi.useFakeTimers() 或等待真实事件;确需真实等待时上一行写 `// real-wait: <原因>`',
+ sourceReads: '普通单测不得读取源码文本做字面量断言;改为经生产入口验证行为,纯跨文件契约移入 Desktop guard tier',
+};
+
+function readBaseline() {
+ if (!existsSync(BASELINE_PATH)) return {};
+ return JSON.parse(readFileSync(BASELINE_PATH, 'utf8')).files ?? {};
+}
+
+function writeBaseline(files) {
+ const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
+ const body = {
+ description: 'Ratchet baseline for scripts/check-test-hygiene.mjs. Counts may only go down; see engineering-conventions.md §3.2.',
+ files: sorted,
+ };
+ writeFileSync(BASELINE_PATH, `${JSON.stringify(body, null, 2)}\n`);
+}
+
+export async function main(args = process.argv.slice(2)) {
+ const counts = await scanRepository();
+ const baseline = readBaseline();
+ const { violations, tightenable } = compareWithBaseline(counts, baseline);
+ if (args.includes('--update')) {
+ // The very first run records the existing debt; afterwards --update only tightens.
+ if (violations.length > 0 && existsSync(BASELINE_PATH)) {
+ for (const v of violations) console.error(`refusing to raise ${v.rule} for ${v.file}: ${v.limit} -> ${v.current}`);
+ console.error('[test-hygiene] --update only tightens the baseline; fix the new hits instead.');
+ return 1;
+ }
+ const next = {};
+ for (const [file, current] of Object.entries(counts)) {
+ const entry = Object.fromEntries(RULES.filter((rule) => current[rule] > 0).map((rule) => [rule, current[rule]]));
+ if (Object.keys(entry).length > 0) next[file] = entry;
+ }
+ writeBaseline(next);
+ console.log(`[test-hygiene] baseline updated: ${Object.keys(next).length} files`);
+ return 0;
+ }
+ if (violations.length === 0) {
+ console.log(`[test-hygiene] PASS (${Object.keys(counts).length} files within baseline)`);
+ if (tightenable.length > 0) {
+ console.log(`[test-hygiene] ${tightenable.length} baseline entries can be tightened: node scripts/check-test-hygiene.mjs --update`);
+ }
+ return 0;
+ }
+ for (const v of violations) {
+ console.error(`❌ [${v.rule}] ${v.file}: ${v.current} unjustified hit(s), baseline allows ${v.limit}`);
+ console.error(` ${HINTS[v.rule]}`);
+ }
+ console.error('[test-hygiene] FAIL — see docs/dev-rules/engineering-conventions.md §3.2');
+ return 1;
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().then((code) => { process.exitCode = code; }, (error) => {
+ console.error(`[test-hygiene] ${error.message}`);
+ process.exitCode = 2;
+ });
+}
diff --git a/scripts/hardcoded-color-exemptions.json b/scripts/hardcoded-color-exemptions.json
index 4f702a19e0..4fcddfc92f 100644
--- a/scripts/hardcoded-color-exemptions.json
+++ b/scripts/hardcoded-color-exemptions.json
@@ -106,7 +106,7 @@
},
{
"glob": "apps/desktop/src/renderer/components/ui/toast/Toast.tsx",
- "reason": "E5D Toast 四色定稿 hardcode(docs/design-rules/cindy-design-system.md §2 sanctioned,info #417CDD/success #2AAE5B/warning #F3A115/error #D91F37;VARIANT_MAP 已导出供 toastColors 守)",
+ "reason": "E5D Toast 四色定稿 hardcode(docs/design-rules/cindy-design-system.md §2 sanctioned,info #417CDD/success #2AAE5B/warning #F3A115/error #D91F37;VARIANT_MAP 使用已批准的语义色)",
"owner": "E5D",
"matches": [
{
@@ -134,11 +134,6 @@
"maintenanceOwner": "kirozeng / DS-7 executor",
"basis": "Existing approval above; DS-7 narrows it to the named colour role and exact approved values, no new palette approval."
},
- {
- "glob": "apps/desktop/src/renderer/__tests__/toastColors.test.ts",
- "reason": "E5D Toast 四色定稿单测(期望 hex)",
- "owner": "E5D"
- },
{
"glob": "apps/desktop/src/renderer/__tests__/themePermissionColors.test.ts",
"reason": "E5D Auto Approval 默认值单测(期望 hex #417CDD)",
@@ -149,11 +144,6 @@
"reason": "E6/E6-B splash 双模式:进度条双套白黑 alpha(既有值恢复)+ hsl(var()) 双模式取色(膘叔交付,阿梅 E6-B-R PASS)",
"owner": "E6"
},
- {
- "glob": "apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts",
- "reason": "合同测试值守护断言(expect toContain hex),非样式硬编码",
- "owner": "E2"
- },
{
"glob": "apps/desktop/src/renderer/components/new-chat/*.tsx",
"reason": "composer-pill fallback var(--composer-pill-*,hex)(lead 裁决 a+fallback,token 已注册 b5d7310,集成收口删)",
diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.json
new file mode 100644
index 0000000000..38bc859422
--- /dev/null
+++ b/scripts/test-hygiene-baseline.json
@@ -0,0 +1,1393 @@
+{
+ "description": "Ratchet baseline for scripts/check-test-hygiene.mjs. Counts may only go down; see engineering-conventions.md §3.2.",
+ "files": {
+ "apps/desktop/scripts/nsis-include-paths.test.mjs": {
+ "sourceReads": 1
+ },
+ "apps/desktop/scripts/render-recovery/main.test.mjs": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/accessibilitySupportIpc.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/analyticsSettingsService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/analyticsSettingsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/appBadgeService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/appearanceZoomMenu.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/authAccountsIpcSecurity.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/authLoginBack.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/authPostCommitStartup.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/__tests__/cdnResponseLifecycle.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/cindyMakeGithubIpc.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/claudeOrphanReaper.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/codexToolTreeReaper.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts": {
+ "sourceReads": 11
+ },
+ "apps/desktop/src/main/__tests__/controlProjects.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/dialogueWorkspace.test.ts": {
+ "resetModules": 3
+ },
+ "apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/heartbeatService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/imageCacheStartupSweepDisabled.test.ts": {
+ "sourceReads": 7
+ },
+ "apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/__tests__/lifecycle.test.ts": {
+ "resetModules": 2,
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts": {
+ "sourceReads": 6
+ },
+ "apps/desktop/src/main/__tests__/makerOrcaRoleMarking.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/__tests__/messagesAroundClientIdIpc.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/notificationService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/piSubagentUpdateRelaunchGate.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/__tests__/projectOrderStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/providerImportWiring.test.ts": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/main/__tests__/queuedMessageTrustBoundary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/releaseNotesService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/resolved-app-theme.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts": {
+ "resetModules": 1,
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/updateChannelStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/updaterUi.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/__tests__/updateService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts": {
+ "resetModules": 9
+ },
+ "apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/wallpaperVideo.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/windowsDiagnosticsTrayWiring.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/windowsIconAssets.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/__tests__/windowsTaskbarNative.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/__tests__/workdirDiagnostics.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts": {
+ "resetModules": 1,
+ "realWaits": 2
+ },
+ "apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/__tests__/worktreeStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/agent-island/__tests__/layoutPreferenceStore.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/agent-island/__tests__/service.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/bot-import/__tests__/host.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts": {
+ "sourceReads": 14
+ },
+ "apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/cindy-make/__tests__/stateBroadcast.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts": {
+ "resetModules": 1,
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/companion-cloud/__tests__/twoDevices.harness.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/computer-permission-guide/__tests__/electron-window.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts": {
+ "resetModules": 1,
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/computer-permission-guide/__tests__/switch-target.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts": {
+ "realWaits": 2
+ },
+ "apps/desktop/src/main/device-link/__tests__/deviceName.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/device-link/__tests__/providerShareGuestPrefs.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts": {
+ "realWaits": 3
+ },
+ "apps/desktop/src/main/goal-host/__tests__/controller.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/localDb/__tests__/cjkSeg.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/localDb/__tests__/dbSlimmingUpgradeOrder.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/maker-host/__tests__/authAdaptersImportPurity.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-store.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts": {
+ "realWaits": 1,
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/memorySettingsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts": {
+ "resetModules": 17
+ },
+ "apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts": {
+ "sourceReads": 8
+ },
+ "apps/desktop/src/main/maker-host/__tests__/piNativeAdapterRuntime.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/piSystemPrompt.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts": {
+ "resetModules": 3
+ },
+ "apps/desktop/src/main/maker-host/__tests__/runtimeConfigsRipgrep.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/session-effort-store.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-host/__tests__/sessionProviderStore.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/botTaskCoordination.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibilityAuthority.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/chatInviteRevokeIpcSecurity.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/cindyMakeFeatureGate.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/llamaCppContextOwner.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectoryWindows.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccessHost.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/promptPredictionStopLedger.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/schedulerQueuedPreparation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/sessionQueueControl.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/maker-ipc/__tests__/silentStopContinuationBinding.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/mcp-integrations/__tests__/botTaskCreationResponsibility.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/mcp-integrations/__tests__/schedulerDevices.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/main/plugin-publisher/__tests__/host.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/provider-group/__tests__/coolingStore.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/provider-group/__tests__/failoverSessionClose.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/provider-group/__tests__/stores.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts": {
+ "realWaits": 5
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/linuxPackaging.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/agentProxyPrefsLog.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/remoteAgentReadiness.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/remote-ssh/__tests__/silentInstallStatus.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/resource-usage-window/__tests__/windowSecurity.test.ts": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts": {
+ "sourceReads": 7
+ },
+ "apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts": {
+ "realWaits": 3
+ },
+ "apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/main/skillhub/__tests__/customizationScanHost.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/__tests__/identityPolicy.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/__tests__/installService.test.ts": {
+ "resetModules": 4
+ },
+ "apps/desktop/src/main/skillhub/__tests__/publishService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/__tests__/registryReconciliation.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/registry/__tests__/manifestIO.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/vision-bridge/__tests__/vision-bridge-settings-store.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/voice-input/__tests__/ElevenLabsScribeProvider.test.ts": {
+ "realWaits": 2
+ },
+ "apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts": {
+ "realWaits": 3
+ },
+ "apps/desktop/src/main/voice-input/__tests__/SystemAudioMuteGuard.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/voice-input/__tests__/VolcengineSaucAsrProvider.test.ts": {
+ "realWaits": 4
+ },
+ "apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardHook.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/main/worktree/__tests__/precreatedCancellation.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/main/xbox-gamepad/__tests__/index.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/preload/__tests__/browserCommentPreload.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/preload/__tests__/ghostInspectTarget.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/preload/__tests__/skillhubFanOut.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts": {
+ "sourceReads": 6
+ },
+ "apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/agentDeviceModelMemory.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/attachmentTypeThumb.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts": {
+ "sourceReads": 25
+ },
+ "apps/desktop/src/renderer/__tests__/automationGroupCollapse.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/__tests__/brandLoadingMarkContract.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/ccAgentSessionViewThemeContract.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/composerChipPresentation.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/composerDraftSameOwnerGenerationBump.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/deviceLinkDraftFlow.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/deviceLinkProjectsConcurrency.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/deviceProvidersRecovery.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/devicesProvidersRefresh.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/diffHorizontalScroll.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/diffPanelShellA11y.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/favoriteAnchorMemory.test.ts": {
+ "resetModules": 7
+ },
+ "apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/focusScrollSettlement.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/focusScrollWindow.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/foregroundRecoveryDiagnostics.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/foundationDefaultsFreeze.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/ghostCardFrameCanvas.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/ghostCommandSourceLabel.dom.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/ghostUnreadStore.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/gitReviewTransport.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/globalTextSelectionColor.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/goalLearnTransportRouting.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/historyPrefetch.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/historyTurnChangesProjection.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/__tests__/makerExperimentalAccepted.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/makerTransportOrcaRouting.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts": {
+ "resetModules": 1,
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownCjkStrongDelimiter.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/markdownFencedCodeInline.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownHeadingTokens.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownMathRendering.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownStrikethrough.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/memorySettingsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/menuButtonSettingsEntry.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/messageDisclosureAnchorIntegration.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/messageRenderItemDom.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/messageViewportRestoreDom.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/modelDefinitionsDefaults.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/modelDefinitionsDeviceId.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/modelEnginePrefs.test.ts": {
+ "resetModules": 14
+ },
+ "apps/desktop/src/renderer/__tests__/modelFavorites.test.ts": {
+ "resetModules": 17
+ },
+ "apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts": {
+ "resetModules": 18
+ },
+ "apps/desktop/src/renderer/__tests__/morphPopover.test.tsx": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts": {
+ "resetModules": 54,
+ "realWaits": 1
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerDraftRemoteHost.test.ts": {
+ "resetModules": 6
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerGenericCreatePreservesDraft.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerLocalFirstMessageSend.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerRemoteFirstMessageSend.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/pendingHandoffRecovery.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/__tests__/permissionSessionApproval.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/renderer/__tests__/previousQuestionPlaceholder.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/providerModelMemory.test.ts": {
+ "resetModules": 13
+ },
+ "apps/desktop/src/renderer/__tests__/recentWorkdirsStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/reducedMotionEscape.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/__tests__/remoteBotLampFoldExemption.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/remoteCatalogSnapshot.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts": {
+ "sourceReads": 12
+ },
+ "apps/desktop/src/renderer/__tests__/restoredScrollIndicator.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/rewindDraftAttachments.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/rolePillWorkerCountSummary.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/rolePillWorkerErrorIndicator.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/scheduleDefaultModel.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/selectedFavoritePersistenceRollback.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/selectedMachineOwnerState.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/sidebarUpgradeDefaults.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/__tests__/textLightbox.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/renderer/__tests__/userMessageCollapse.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/__tests__/workdirBrowseRemoteSafety.test.ts": {
+ "sourceReads": 4
+ },
+ "apps/desktop/src/renderer/__tests__/worktreeRemovalWarning.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/chat/__tests__/rehypeStreamWordFade.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/new-chat/__tests__/composerBlankPointerFocus.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/new-chat/__tests__/composerPromptRecommendation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx": {
+ "realWaits": 2
+ },
+ "apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.addFormOrder.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/settings/__tests__/settingsSearchCatalog.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDevices.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/status/__tests__/QuotaBar.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/components/ui/__tests__/dropdownMenuHighlight.test.tsx": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/components/ui/__tests__/input.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx": {
+ "realWaits": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botGroupListRemoval.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts": {
+ "sourceReads": 6
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botStore.lifecycle.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/botStore.modelSettings.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/bots/__tests__/chatInviteBrowserHandoff.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/agentDeviceDraftMemory.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/modelWindowConfirmation.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/newMakerDraftModelPrefs.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/newMakerDraftTargetCatalog.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupStore.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts": {
+ "sourceReads": 13
+ },
+ "apps/desktop/src/renderer/features/cc-agent/workdir-browse/__tests__/FileTreeView.horizontalScroll.test.tsx": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/plugin.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/subscription.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/highlight.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useCategoryList.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillPublishComparison.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts": {
+ "sourceReads": 5
+ },
+ "apps/desktop/src/renderer/features/skillhub/lib/__tests__/publishProgressFilter.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/features/skillhub/lib/__tests__/skillhubManagementE2EScript.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/hooks/__tests__/useDingTalkBot.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/lib/__tests__/composerDraftSessionSwitchGuard.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/desktop/src/renderer/lib/__tests__/sessionService.test.ts": {
+ "resetModules": 2
+ },
+ "apps/desktop/src/renderer/state/__tests__/agentIslandActivity.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/themes/__tests__/generatedEffortInitialization.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/dictionaryLearningSettings.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts": {
+ "sourceReads": 2
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/startCue.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/voiceInputHistory.test.ts": {
+ "resetModules": 1
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts": {
+ "sourceReads": 9
+ },
+ "apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/agentCapabilitiesCache.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/cacheWriteNotice.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/clientEndpointStartup.test.ts": {
+ "resetModules": 12
+ },
+ "apps/mobile/src/__tests__/codeHighlight.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/CompanionMemoryPage.test.tsx": {
+ "realWaits": 2
+ },
+ "apps/mobile/src/__tests__/composerPlugins.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/devCacheMenu.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/deviceCatalogRefresh.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/devServerEnvironment.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/durableOutboxFiles.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/endpointManifestLoader.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/fingerprintConfig.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/incomingShareFeedbackScript.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/incomingShareNative.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/iosAppDistribution.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/mathWebViewHtml.test.ts": {
+ "realWaits": 1
+ },
+ "apps/mobile/src/__tests__/mermaidWebView.test.ts": {
+ "realWaits": 1
+ },
+ "apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts": {
+ "sourceReads": 3
+ },
+ "apps/mobile/src/__tests__/messageCacheStorage.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/mobileSpeakerFilterStorage.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/mobileTapdb.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/mobileVoiceCue.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/newSession.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/outboxHistoryCache.test.ts": {
+ "realWaits": 1,
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/remoteHistoryReentry.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/remoteResourceCache.test.ts": {
+ "resetModules": 2
+ },
+ "apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts": {
+ "sourceReads": 1
+ },
+ "apps/mobile/src/__tests__/useBotGroupChat.test.tsx": {
+ "realWaits": 2
+ },
+ "apps/mobile/src/__tests__/useDeviceProviders.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/__tests__/visualMock.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.ts": {
+ "resetModules": 1
+ },
+ "apps/mobile/src/debug/localDiagnostics.test.ts": {
+ "resetModules": 1
+ },
+ "packages/anthropic-compat-proxy/src/server.test.ts": {
+ "realWaits": 2
+ },
+ "packages/design-tokens/src/__tests__/classification.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/design-tokens/src/__tests__/zero-wiring.test.ts": {
+ "sourceReads": 8
+ },
+ "packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/lizi-mcps/src/computer/computerMcpServer.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-cc-manager/__tests__/kill-pending-send.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-cc-manager/__tests__/sdk-handlers.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/claude-code/__tests__/auto-continued-turn-in-flight.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/maker-core/src/agents/claude-code/__tests__/forward-loop-crash-teardown.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/codex/goal-ownership.native.test.ts": {
+ "realWaits": 1
+ },
+ "packages/maker-core/src/agents/codex/native-auto-review-policy.native.test.ts": {
+ "sourceReads": 2
+ },
+ "packages/maker-core/src/agents/codex/native-auto-review-policy.test.ts": {
+ "sourceReads": 2
+ },
+ "packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts": {
+ "realWaits": 4
+ },
+ "packages/maker-core/src/agents/pi/__tests__/cindySubagentParentWatchdog.test.ts": {
+ "realWaits": 4
+ },
+ "packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts": {
+ "realWaits": 2
+ },
+ "packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts": {
+ "sourceReads": 3
+ },
+ "packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/maker-core/src/agents/pi/__tests__/pi-extra-dirs-prompt.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts": {
+ "realWaits": 22,
+ "sourceReads": 3
+ },
+ "packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts": {
+ "realWaits": 3,
+ "sourceReads": 2
+ },
+ "packages/maker-core/src/agents/shared/token-speed.test.ts": {
+ "realWaits": 6
+ },
+ "packages/maker-core/src/session.origin.test.ts": {
+ "realWaits": 3
+ },
+ "packages/maker-core/src/session.vision-bridge.test.ts": {
+ "realWaits": 2
+ },
+ "packages/maker-pi-manager/src/__tests__/concurrency.test.ts": {
+ "realWaits": 2
+ },
+ "packages/maker-pi-manager/src/__tests__/server.test.ts": {
+ "realWaits": 5
+ },
+ "packages/maker-shared/src/__tests__/remoteDesktopViewerSource.test.ts": {
+ "sourceReads": 1
+ },
+ "packages/model-providers/src/__tests__/piNativeCatalog.test.ts": {
+ "resetModules": 2
+ },
+ "packages/remote-file-service/src/__tests__/rpc.test.ts": {
+ "realWaits": 2
+ }
+ }
+}
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index eaae4f510c..34c4ab65bd 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -45,7 +45,7 @@ export function desktopUnitPool(
}
/**
- * Split every Vitest workspace by the same CI shard so the two Windows jobs
+ * Split every Vitest workspace by the same CI shard so the parallel shard jobs
* still form one complete unit gate. The runner adds `passWithNoTests` only
* when a workspace has fewer selected files than the configured shard count.
*/
@@ -95,6 +95,38 @@ const makerPiManagerIntegrationInclude = [
const desktopE2eInclude = [
'src/main/maker-host/__tests__/*.e2e.test.ts',
];
+// Static source-contract checks (security, permission, and design rules) run
+// in the explicit guard tier. Keeping an exact allowlist makes it impossible
+// for a new source scan to silently become part of the ordinary unit gate.
+const desktopGuardInclude = [
+ 'src/main/__tests__/authCaptchaIpcSecurity.test.ts',
+ 'src/main/__tests__/browserRuntimeDirStartup.test.ts',
+ 'src/main/__tests__/dbSlimmingIpcSecurity.test.ts',
+ 'src/main/__tests__/deviceLinkInputSteerDedupeWiring.test.ts',
+ 'src/main/__tests__/endpointEnvUsageGuard.test.ts',
+ 'src/main/__tests__/gitContextIpcSecurity.test.ts',
+ 'src/main/__tests__/isolatedOnProductionProfileStartup.test.ts',
+ 'src/main/__tests__/windowThemeVibrancyIpcSecurity.test.ts',
+ 'src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts',
+ 'src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts',
+ 'src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts',
+ 'src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts',
+ 'src/main/cindy-brain/__tests__/ghostLocalUpdateSource.wiring.test.ts',
+ 'src/main/cindy-brain/__tests__/librarySaveAsDialogParent.test.ts',
+ 'src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts',
+ 'src/main/cindy-media/__tests__/ccAgentWriteGuard.test.ts',
+ 'src/main/im/telegram/__tests__/uiText.test.ts',
+ 'src/main/maker-ipc/__tests__/botMainDependencies.test.ts',
+ 'src/main/maker-ipc/__tests__/scheduleProviderDiscoveryWiring.test.ts',
+ 'src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts',
+ 'src/renderer/__tests__/compactComposerTypography.test.ts',
+ 'src/renderer/__tests__/dialogScrimDismissal.test.ts',
+ 'src/renderer/__tests__/disabledCursorVisualContract.test.ts',
+ 'src/renderer/__tests__/makerExperimentalThemeContract.test.ts',
+ 'src/renderer/__tests__/modalSurfaceContract.test.ts',
+ 'src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts',
+ 'src/renderer/__tests__/toastZIndex.test.ts',
+];
export function desktopUnitWorkerCount(
availableParallelism = os.availableParallelism(),
@@ -169,6 +201,7 @@ export default {
'src/main/scheduler-host/__tests__/*.db.test.ts',
'src/main/__tests__/directSessionSendGuard.test.ts',
'src/main/__tests__/makerSendToSessionOrdering.test.ts',
+ ...desktopGuardInclude,
'**/*.bench.ts',
],
},
@@ -228,6 +261,7 @@ export default {
include: [
'src/main/__tests__/directSessionSendGuard.test.ts',
'src/main/__tests__/makerSendToSessionOrdering.test.ts',
+ ...desktopGuardInclude,
],
},
},
@@ -235,26 +269,12 @@ export default {
// Mobile has enough test files to become the critical path at one worker.
// Give it the full worker budget, but never overlap it with other workspaces.
requiredUnitWorkspace('mobile', 'apps/mobile', { workers: 4, execution: 'exclusive' }),
- requiredUnitWorkspace('@cindy/anthropic-compat-proxy', 'packages/anthropic-compat-proxy'),
- requiredUnitWorkspace('@cindy/anthropic-responses-bridge', 'packages/anthropic-responses-bridge'),
- requiredUnitWorkspace('@cindy/responses-anthropic-bridge', 'packages/responses-anthropic-bridge'),
- requiredUnitWorkspace('@cindy/model-compat', 'packages/model-compat'),
- requiredUnitWorkspace('@cindy/responses-chat-bridge', 'packages/responses-chat-bridge'),
- requiredUnitWorkspace('@cindy/auth-client', 'packages/auth-client'),
- requiredUnitWorkspace('@cindy/browser-control-runtime', 'packages/browser-control-runtime'),
- requiredUnitWorkspace('cindy-tools', 'packages/cindy-tools'),
- requiredUnitWorkspace('@cindy/device-link', 'packages/device-link'),
- noCollectableWorkspace('@cindy/embedding-client', 'packages/embedding-client'),
- requiredUnitWorkspace('@cindy/file-browser-core', 'packages/file-browser-core'),
- noCollectableWorkspace('@cindy/github-client', 'packages/github-client'),
- noCollectableWorkspace('@cindy/gitlab-client', 'packages/gitlab-client'),
- noCollectableWorkspace('@cindy/heartbeat-client', 'packages/heartbeat-client'),
- requiredUnitWorkspace('@cindy/im', 'packages/lizi-im'),
- requiredUnitWorkspace('@cindy/mcps', 'packages/lizi-mcps'),
- requiredUnitWorkspace('@cindy/maker-cc-manager', 'packages/maker-cc-manager'),
// Stays on forks: palette-scanner's tests stub HOME and the scanner resolves
// it through os.homedir(), which a worker thread cannot see (see
// UNIT_POOL_DEFAULT above).
+ // At one worker it was the last workspace still running in every CI shard;
+ // it scales linearly (2026-10-16: 248s / 125s / 65s at 1 / 2 / 4 workers),
+ // so it runs exclusively with the full worker budget, like mobile.
{
name: '@cindy/maker-core',
cwd: 'packages/maker-core',
@@ -262,7 +282,8 @@ export default {
tiers: {
unit: {
status: 'required',
- command: unitVitestCommand(1, 'forks'),
+ execution: 'exclusive',
+ command: unitVitestCommand(desktopUnitWorkerCount(), 'forks'),
exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts', '**/*.git-integration.test.ts'],
},
'git-integration': {
@@ -282,6 +303,23 @@ export default {
},
},
},
+ requiredUnitWorkspace('@cindy/anthropic-compat-proxy', 'packages/anthropic-compat-proxy'),
+ requiredUnitWorkspace('@cindy/anthropic-responses-bridge', 'packages/anthropic-responses-bridge'),
+ requiredUnitWorkspace('@cindy/responses-anthropic-bridge', 'packages/responses-anthropic-bridge'),
+ requiredUnitWorkspace('@cindy/model-compat', 'packages/model-compat'),
+ requiredUnitWorkspace('@cindy/responses-chat-bridge', 'packages/responses-chat-bridge'),
+ requiredUnitWorkspace('@cindy/auth-client', 'packages/auth-client'),
+ requiredUnitWorkspace('@cindy/browser-control-runtime', 'packages/browser-control-runtime'),
+ requiredUnitWorkspace('cindy-tools', 'packages/cindy-tools'),
+ requiredUnitWorkspace('@cindy/device-link', 'packages/device-link'),
+ noCollectableWorkspace('@cindy/embedding-client', 'packages/embedding-client'),
+ requiredUnitWorkspace('@cindy/file-browser-core', 'packages/file-browser-core'),
+ noCollectableWorkspace('@cindy/github-client', 'packages/github-client'),
+ noCollectableWorkspace('@cindy/gitlab-client', 'packages/gitlab-client'),
+ noCollectableWorkspace('@cindy/heartbeat-client', 'packages/heartbeat-client'),
+ requiredUnitWorkspace('@cindy/im', 'packages/lizi-im'),
+ requiredUnitWorkspace('@cindy/mcps', 'packages/lizi-mcps'),
+ requiredUnitWorkspace('@cindy/maker-cc-manager', 'packages/maker-cc-manager'),
requiredUnitWorkspace('@cindy/maker-remote-ssh', 'packages/maker-remote-ssh'),
// 轮 42:新包 maker-pi-manager(TS 单例 pi daemon)已随 SSH remote 交付;
// 漏登记会让 test-workspaces 的 manifest 覆盖校验失败(全量门禁拒跑)。
diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjs
index 4918ddd862..b6775bb1aa 100644
--- a/scripts/test-workspaces.mjs
+++ b/scripts/test-workspaces.mjs
@@ -485,8 +485,13 @@ function undersizedVitestShardArgs(commandSpec, selectedFiles) {
return [];
// Vitest rejects every shard when there are fewer files than shards, before
- // it assigns the files. Limit the compatibility flag to that known case.
- return selectedFiles.length < count ? ["--passWithNoTests"] : [];
+ // it assigns the files. Otherwise it slices ceil(files / count) files per
+ // shard, so trailing shards can still be empty (6 files over 4 shards gives
+ // 2, 2, 2, 0). Limit the compatibility flag to those two known cases.
+ const fileCount = selectedFiles.length;
+ if (fileCount < count) return ["--passWithNoTests"];
+ const shardStart = Math.ceil(fileCount / count) * (index - 1);
+ return shardStart >= fileCount ? ["--passWithNoTests"] : [];
}
function toWorkspaceRelativeFile(workspace, file) {