Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): preserve regression guards and complete hygiene checks
MagicLizi26121008eecd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e0dd9fa03b..1804795579 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -67,7 +67,7 @@ jobs:# 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+ - name: Run Desktop and Mobile source-contract guardsrun: pnpm test:guard# No private service checkout or secrets: exercise production clients over realdiff --git a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.tsnew file mode 100644index 0000000000..b96ddbfe24--- /dev/null+++ b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts@@ -0,0 +1,42 @@+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.tsnew file mode 100644index 0000000000..22e28a9794--- /dev/null+++ b/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts@@ -0,0 +1,66 @@+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.tsnew file mode 100644index 0000000000..2c97c7221b--- /dev/null+++ b/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts@@ -0,0 +1,56 @@+/**+ * `/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.tsnew file mode 100644index 0000000000..3ca270774d--- /dev/null+++ b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts@@ -0,0 +1,233 @@+/**+ * 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__/invokeCaptureHealthOrdering.test.ts b/apps/desktop/src/main/__tests__/invokeCaptureHealthOrdering.test.tsnew file mode 100644index 0000000000..046b9239b6--- /dev/null+++ b/apps/desktop/src/main/__tests__/invokeCaptureHealthOrdering.test.ts@@ -0,0 +1,38 @@+/**+ * 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__/modelVisibilityOwnerClaimOrdering.test.ts b/apps/desktop/src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.tsnew file mode 100644index 0000000000..9426bc7e0b--- /dev/null+++ b/apps/desktop/src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.ts@@ -0,0 +1,24 @@+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.tsnew file mode 100644index 0000000000..c13d244f68--- /dev/null+++ b/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts@@ -0,0 +1,101 @@+/**+ * 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.tsnew file mode 100644index 0000000000..a644077a3e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts@@ -0,0 +1,30 @@+/**+ * 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.tsnew file mode 100644index 0000000000..9332928996--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts@@ -0,0 +1,83 @@+/**+ * 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.tsnew file mode 100644index 0000000000..d1cef7a368--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/sessionFocusRetryContract.test.ts@@ -0,0 +1,47 @@+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.tsnew file mode 100644index 0000000000..c7f4117614--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/ownershipAccountSource.test.ts@@ -0,0 +1,20 @@+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/localDb/__tests__/schemaMigrationLease.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.tsindex bf976b8508..42210c67e7 100644--- a/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts@@ -49,6 +49,7 @@ async function stopChild(child: ChildProcess): Promise<void> {if (child.exitCode !== null || child.signalCode !== null) return;child.send?.('release');await new Promise<void>((resolve) => {+ // real-wait: bound cleanup while the child process may ignore the release message.const timer = setTimeout(() => {child.kill('SIGKILL');resolve();diff --git a/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.tsnew file mode 100644index 0000000000..9822cd140f--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts@@ -0,0 +1,17 @@+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-ipc/__tests__/botCompactContinuity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.tsnew file mode 100644index 0000000000..b24cf81064--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts@@ -0,0 +1,130 @@+/**+ * 压缩之后伙伴还是不是它自己。+ *+ * ## 为什么这组测试是源码断言+ *+ * 这条链跨三个 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.tsnew file mode 100644index 0000000000..c7d0ec34c7--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts@@ -0,0 +1,62 @@+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.tsnew file mode 100644index 0000000000..9c29d6f1f5--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts@@ -0,0 +1,102 @@+/**+ * 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.tsnew file mode 100644index 0000000000..f5f3cdb5e5--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTreeProviderResume.test.ts@@ -0,0 +1,94 @@+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/mcp-apps/__tests__/conformance.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.tsindex 0d802c4094..149bad1b60 100644--- a/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.ts+++ b/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.ts@@ -80,6 +80,7 @@ class RawPeer {): Promise<T> {const id = this.nextId++;const result = new Promise<unknown>((resolve, reject) => {+ // real-wait: exercise the production RPC timeout when a fixture never responds.const timer = setTimeout(() => {this.pending.delete(id);reject(new Error('Fixture RPC timed out: ' + method));diff --git a/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts b/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.tsindex b9c5b3b721..5b34c50fed 100644--- a/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts@@ -1,9 +1,8 @@import { beforeEach, expect, it, vi } from 'vitest';-// reset-modules: each case must observe a fresh in-process credential status store.-beforeEach(() => vi.resetModules());+import * as state from '../quotaCredentialState';const status = { state: 'ok', source: 'server', endpoint: 'https://gateway.example.test', accountTier: null } as const;+beforeEach(() => state.noteQuotaCredentialStatus(null, { state: 'idle', source: null, endpoint: null, accountTier: null }));it('requires a successful current-process sync and matches both owner and endpoint', async () => {- const state = await import('../quotaCredentialState');expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);state.noteQuotaCredentialStatus('owner', { ...status, state: 'syncing' });expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);@@ -15,7 +14,6 @@ it('requires a successful current-process sync and matches both owner and endpoiexpect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);});it('invalidates source changes and logout but not repeated successful synchronization', async () => {- const state = await import('../quotaCredentialState');const changed = vi.fn();const off = state.onQuotaCredentialSourceChanged(changed);state.noteQuotaCredentialStatus('owner', status);@@ -34,10 +32,9 @@ it('invalidates source changes and logout but not repeated successful synchroniz});it.each([null, 'manual'] as const)('invalidates a removed/replaced source in non-ok state (%s)', async (source) => {- const state = await import('../quotaCredentialState');const changed = vi.fn();state.noteQuotaCredentialStatus('owner', status);- state.onQuotaCredentialSourceChanged(changed);+ const off = state.onQuotaCredentialSourceChanged(changed);const generation = state.quotaCredentialGeneration();state.noteQuotaCredentialStatus('owner', { ...status, state: 'failed' });expect(changed).not.toHaveBeenCalled();@@ -45,4 +42,5 @@ it.each([null, 'manual'] as const)('invalidates a removed/replaced source in nonexpect(state.quotaCredentialGeneration()).toBe(generation + 1);expect(changed).toHaveBeenCalledTimes(1);expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);+ off();});diff --git a/apps/desktop/src/main/model-access/quotaCredentialState.ts b/apps/desktop/src/main/model-access/quotaCredentialState.tsindex 3601059645..331a448ef6 100644--- a/apps/desktop/src/main/model-access/quotaCredentialState.ts+++ b/apps/desktop/src/main/model-access/quotaCredentialState.ts@@ -50,6 +50,21 @@ let readCurrentCredentialStatus: (() => ModelAccessStatus | null) | null = null;export function setQuotaCredentialStatusReader(reader: () => ModelAccessStatus | null): void {readCurrentCredentialStatus = reader;}++/** Reset the process-local credential snapshot without notifying production listeners. */+export function __resetQuotaCredentialStateForTesting(+ ownerKey: string | null,+ status: ModelAccessStatus,+): void {+ owner = ownerKey;+ endpoint = status.endpoint?.trim().replace(/\/+$/, '') || null;+ source = status.source;+ ready = status.state === 'ok' && status.source === 'server' && !!endpoint;+ synchronized = ready;+ generation = 0;+ readCurrentCredentialStatus = null;+}+export function refreshQuotaCredentialOwner(ownerKey: string): void {if (owner === ownerKey) return;const status = readCurrentCredentialStatus?.();diff --git a/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.tsnew file mode 100644index 0000000000..81d2a1b7a4--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts@@ -0,0 +1,38 @@+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/usage/__tests__/claudeAccountUsageKeyRejection.test.ts b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.tsindex b797086963..d8d8ed54f7 100644--- a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts+++ b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts@@ -2,7 +2,7 @@* 额度查询遇到 Cindy 网关 401 时上报 Cindy AI Key 失效(其余状态不上报)。* 只断言上报行为;配额解析契约见 claudeAccountUsageSource.test.ts。*/-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({outboundFetch: vi.fn(),@@ -39,31 +39,35 @@ vi.mock('../../model-access/gatewayKeyRejection', () => ({// This suite exercises the explicit old-server / Nova compatibility path.vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage: async () => undefined }));-let triggerClaudeAccountUsageRefresh: typeof import('../claudeAccountUsage')['triggerClaudeAccountUsageRefresh'];+let usage: typeof import('../claudeAccountUsage');+let credentials: typeof import('../../model-access/quotaCredentialState');function jsonResponse(body: unknown, status = 200): Response {return new Response(JSON.stringify(body), { status });}describe('claudeAccountUsage Cindy AI key rejection', () => {- beforeEach(async () => {- // reset-modules: reset the quota credential singleton before rebuilding the mocked account state.+ beforeAll(async () => {+ // reset-modules: load the mocked usage module once before this suite; per-test resets use its production test reset API.vi.resetModules();+ usage = await import('../claudeAccountUsage');+ credentials = await import('../../model-access/quotaCredentialState');+ });+ beforeEach(() => {+ usage.__resetClaudeAccountUsageForTesting();vi.useFakeTimers();mocks.outboundFetch.mockReset();mocks.report.mockReset();- const credentials = await import('../../model-access/quotaCredentialState');- credentials.noteQuotaCredentialStatus('cloud:user-1:1', {+ credentials.__resetQuotaCredentialStateForTesting('cloud:user-1:1', {state: 'ok', source: 'server', endpoint: 'https://gateway.test.invalid', accountTier: null,});- ({ triggerClaudeAccountUsageRefresh } = await import('../claudeAccountUsage'));});afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });it('reports the sent key when user/info and daily/activity are rejected with 401', async () => {mocks.outboundFetch.mockImplementation(async () => jsonResponse({ error: 'invalid key' }, 401));- await triggerClaudeAccountUsageRefresh(true);+ await usage.triggerClaudeAccountUsageRefresh(true);expect(mocks.outboundFetch).toHaveBeenCalledTimes(2);for (const call of mocks.outboundFetch.mock.calls) {@@ -81,7 +85,7 @@ describe('claudeAccountUsage Cindy AI key rejection', () => {: jsonResponse({ spend: 1, max_budget: 10, budget_reset_at: null }),);- await triggerClaudeAccountUsageRefresh(true);+ await usage.triggerClaudeAccountUsageRefresh(true);expect(mocks.report).toHaveBeenCalledTimes(1);expect(mocks.report).toHaveBeenCalledWith('usage-key-sent');@@ -90,7 +94,7 @@ describe('claudeAccountUsage Cindy AI key rejection', () => {it.each([403, 500])('does not report HTTP %s', async (status) => {mocks.outboundFetch.mockImplementation(async () => jsonResponse({ error: 'nope' }, status));- await triggerClaudeAccountUsageRefresh(true);+ await usage.triggerClaudeAccountUsageRefresh(true);expect(mocks.outboundFetch).toHaveBeenCalled();expect(mocks.report).not.toHaveBeenCalled();@@ -103,7 +107,7 @@ describe('claudeAccountUsage Cindy AI key rejection', () => {: jsonResponse({ spend: 1, max_budget: 10, budget_reset_at: null }),);- await triggerClaudeAccountUsageRefresh(true);+ await usage.triggerClaudeAccountUsageRefresh(true);expect(mocks.outboundFetch).toHaveBeenCalledTimes(2);expect(mocks.report).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.tsindex b471540845..1193059879 100644--- a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({auth: { mode: 'cloud', ownerGeneration: 1, dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } },endpoint: 'https://gateway.example.test',@@ -15,34 +15,39 @@ vi.mock('../modelPricing', () => ({ getGatewayAccountCurrency: async () => 'CNY'vi.mock('../ledgerCurrency', () => ({ currentLedgerCurrency: () => 'CNY' }));vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage: mocks.managed }));const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 };-beforeEach(async () => {- // reset-modules: each refresh scenario starts with a new quota credential singleton.- vi.resetModules(); vi.useFakeTimers(); vi.clearAllMocks();+let api: typeof import('../claudeAccountUsage');+let state: typeof import('../../model-access/quotaCredentialState');+beforeAll(async () => {+ // reset-modules: load the mocked usage module once before this suite; per-test resets use its production test reset API.+ vi.resetModules();+ api = await import('../claudeAccountUsage');+ state = await import('../../model-access/quotaCredentialState');+});+beforeEach(() => {+ api.__resetClaudeAccountUsageForTesting();+ vi.useFakeTimers(); vi.clearAllMocks();mocks.auth = { mode: 'cloud', ownerGeneration: 1, dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } };mocks.endpoint = 'https://gateway.example.test';- const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.setQuotaCredentialStatusReader(() => null);mocks.managed.mockResolvedValue(quota);mocks.outbound.mockResolvedValue({ ok: true, json: async () => ({ spend: 2, max_budget: 20, results: [] }) });+ state.__resetQuotaCredentialStateForTesting('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });});afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });describe('Cindy AI enterprise quota refresh', () => {it('publishes server quota without calling LiteLLM APIs on an inference gateway', async () => {- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);expect(mocks.outbound).not.toHaveBeenCalled();});it('preserves legacy Nova quota reads when the server capability is unsupported', async () => {mocks.managed.mockResolvedValue(undefined);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toMatchObject({ spend: 2, maxBudget: 20 });expect(mocks.outbound).toHaveBeenCalledTimes(2);});it('does not query legacy credentials on managed-query errors', async () => {mocks.managed.mockResolvedValue(null);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toBeNull();expect(mocks.outbound).not.toHaveBeenCalled();@@ -50,7 +55,6 @@ describe('Cindy AI enterprise quota refresh', () => {it('drops an in-flight response when switching enterprise accounts', async () => {let resolve!: (value: unknown) => void;mocks.managed.mockImplementationOnce(() => new Promise(r => { resolve = r; }));- const api = await import('../claudeAccountUsage');const pending = api.triggerClaudeAccountUsageRefresh(true);mocks.auth = { ...mocks.auth, dataOwnerId: 'owner-b' };resolve(quota); await pending;@@ -59,10 +63,8 @@ describe('Cindy AI enterprise quota refresh', () => {it('rejects an old realm response with the same membership and endpoint after sync fails', async () => {let resolve!: (value: unknown) => void;mocks.managed.mockImplementationOnce(() => new Promise(r => { resolve = r; }));- const api = await import('../claudeAccountUsage');const pending = api.triggerClaudeAccountUsageRefresh(true);mocks.auth.ownerGeneration++;- const state = await import('../../model-access/quotaCredentialState');state.noteQuotaCredentialStatus('cloud:owner-a:2', { state: 'failed', source: 'server', endpoint: mocks.endpoint, accountTier: null });mocks.managed.mockResolvedValue(null);resolve(quota); await pending;@@ -72,7 +74,6 @@ describe('Cindy AI enterprise quota refresh', () => {expect(state.quotaCredentialsReady('cloud:owner-a:2', mocks.endpoint)).toBe(false);});it('clears and broadcasts an unlimited result after a finite quota was cached', async () => {- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);const cleared = vi.fn();@@ -95,7 +96,6 @@ describe('Cindy AI enterprise quota refresh', () => {});it('keeps local gateway reads on the original endpoint', async () => {mocks.auth.mode = 'local';- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(mocks.managed).not.toHaveBeenCalled();expect(mocks.outbound).toHaveBeenCalledTimes(2);@@ -105,10 +105,8 @@ describe('Cindy AI enterprise quota refresh', () => {describe('quota gateway migration boundary', () => {it.each(['failed', 'disabled'] as const)('clears legacy quota when credentials are removed in %s state', async (syncState) => {mocks.managed.mockResolvedValue(undefined);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20);- const state = await import('../../model-access/quotaCredentialState');state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: syncState, source: 'server', endpoint: mocks.endpoint, accountTier: null });expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20);state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: syncState, source: null, endpoint: null, accountTier: null });@@ -119,10 +117,8 @@ describe('quota gateway migration boundary', () => {});it('blocks persisted legacy credentials before this process completes credential sync', async () => {- const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.__resetQuotaCredentialStateForTesting('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });mocks.managed.mockResolvedValue(undefined);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(mocks.outbound).not.toHaveBeenCalled();expect(api.readClaudeAccountUsageSnapshot()).toBeNull();@@ -131,9 +127,7 @@ describe('quota gateway migration boundary', () => {});it('reads managed quota before credential sync without contacting the persisted gateway', async () => {- const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });- const api = await import('../claudeAccountUsage');+ state.__resetQuotaCredentialStateForTesting('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);expect(mocks.outbound).not.toHaveBeenCalled();@@ -141,12 +135,10 @@ describe('quota gateway migration boundary', () => {it('invalidates the old gateway quota even if the first new gateway query fails', async () => {mocks.managed.mockResolvedValue(undefined);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20);mocks.managed.mockResolvedValue(null);mocks.endpoint = 'https://new-gateway.example.test';- const state = await import('../../model-access/quotaCredentialState');state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });expect(api.readClaudeAccountUsageSnapshot()).toBeNull();expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'invalidated' });@@ -159,12 +151,10 @@ describe('quota gateway migration boundary', () => {mocks.managed.mockResolvedValue(undefined);let complete!: (value: unknown) => void;mocks.outbound.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));- const api = await import('../claudeAccountUsage');const pending = api.triggerClaudeAccountUsageRefresh(true);await vi.waitFor(() => expect(mocks.outbound).toHaveBeenCalledTimes(2));mocks.managed.mockResolvedValue(null);mocks.endpoint = 'https://new-gateway.example.test';- const state = await import('../../model-access/quotaCredentialState');state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });complete({ ok: true, json: async () => ({ spend: 99, max_budget: 100 }) });await pending;@@ -175,13 +165,11 @@ describe('quota gateway migration boundary', () => {});it('notifies main-process consumers when finite quota recovers after a source change', async () => {- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);let resolve!: (value: unknown) => void;mocks.managed.mockImplementationOnce(() => new Promise(done => { resolve = done; }));const snapshots: unknown[] = [];const off = api.observeClaudeAccountUsage(() => snapshots.push(api.readClaudeAccountUsageSnapshot()));- const state = await import('../../model-access/quotaCredentialState');state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: 'https://new.example.test', accountTier: null });expect(snapshots).toEqual([null]);resolve(quota);@@ -191,9 +179,7 @@ it('notifies main-process consumers when finite quota recovers after a source chit('rebinds ready legacy credentials after a silent same-owner generation repair', async () => {mocks.managed.mockResolvedValue(undefined);- const state = await import('../../model-access/quotaCredentialState');state.setQuotaCredentialStatusReader(() => ({ state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null }));- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20);mocks.auth.ownerGeneration++;@@ -204,9 +190,7 @@ it('rebinds ready legacy credentials after a silent same-owner generation repair});it('does not rebind credentials when the sync identity no longer matches the realm', async () => {mocks.managed.mockResolvedValue(undefined);- const state = await import('../../model-access/quotaCredentialState');state.setQuotaCredentialStatusReader(() => null);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);mocks.auth.ownerGeneration++;mocks.outbound.mockClear();@@ -217,7 +201,6 @@ it('does not rebind credentials when the sync identity no longer matches the reait('still throttles unavailable reads within one owner generation', async () => {mocks.managed.mockResolvedValue(null);- const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh();await api.triggerClaudeAccountUsageRefresh();expect(mocks.managed).toHaveBeenCalledTimes(1);diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.tsindex fe9fefc965..22a8c1e7cc 100644--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts@@ -104,6 +104,22 @@ let lastFetchAt = 0;let lastFetchOwnerKey: string | null = null;let idlePollTimer: NodeJS.Timeout | null = null;+/** Reset process-local quota state for tests that share one module instance. */+export function __resetClaudeAccountUsageForTesting(): void {+ if (idlePollTimer) clearInterval(idlePollTimer);+ idlePollTimer = null;+ snapshot = null;+ snapshotOwnerKey = null;+ clearReason = 'unlimited';+ fetchInFlight = false;+ fetchOwnerKey = null;+ refreshQueued = false;+ lastFetchAt = 0;+ lastFetchOwnerKey = null;+ quotaSnapshotRevision = 0;+ quotaSnapshotListeners.clear();+}+interface LiteLlmUserInfo {spend?: number;max_budget?: number;diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.tsnew file mode 100644index 0000000000..82de3aa1c7--- /dev/null+++ b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts@@ -0,0 +1,54 @@+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.tsnew file mode 100644index 0000000000..4324d701d9--- /dev/null+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts@@ -0,0 +1,28 @@+/** 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__/bulkSessionStatusRouting.test.ts b/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.tsnew file mode 100644index 0000000000..e95b856d56--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts@@ -0,0 +1,50 @@+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__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.tsnew file mode 100644index 0000000000..49528798db--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts@@ -0,0 +1,592 @@+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__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsnew file mode 100644index 0000000000..66c75eae25--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -0,0 +1,424 @@+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__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.tsnew file mode 100644index 0000000000..c24c1491b7--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts@@ -0,0 +1,252 @@+/**+ * 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__/homeUsageDashboardSource.test.ts b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.tsnew file mode 100644index 0000000000..eddf41f4d9--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts@@ -0,0 +1,42 @@+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');++// Guard the account identity passed to the hook and isolation of cached history.+describe('HomeUsageDashboard account isolation contract', () => {+ 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('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;',+ );+ });++});diff --git a/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.ts b/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.tsnew file mode 100644index 0000000000..adfadbba28--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/markdownRendererXdtAudio.test.ts@@ -0,0 +1,79 @@+/**+ * 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__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.tsnew file mode 100644index 0000000000..0b579ae233--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts@@ -0,0 +1,533 @@+/**+ * 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__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.tsnew file mode 100644index 0000000000..67d00f03d4--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts@@ -0,0 +1,198 @@+/**+ * 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.tsnew file mode 100644index 0000000000..c3311b8345--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts@@ -0,0 +1,93 @@+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__/sessionTitleProjectionOutlets.test.ts b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.tsnew file mode 100644index 0000000000..878041b9d5--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts@@ -0,0 +1,133 @@+/**+ * 桌面端「未起名会话标题」投影的出口清单。+ *+ * 不变量:会话标题的每个**用户可见**出口都必须过投影(`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/features/plugin/__tests__/unreadDotMotion.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.tsnew file mode 100644index 0000000000..0359c13e89--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts@@ -0,0 +1,47 @@+/**+ * 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/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 2b97a30bef..a4558d1aa0 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -4179,6 +4179,7 @@ describe("remote desktop controls", () => {fixture.invoke.mockImplementation((...args) =>args[2][0].op === "heartbeat"? new Promise((_resolve, reject) =>+ // real-wait: exercise the transport heartbeat timeout boundary.setTimeout(() =>reject(diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 002f286e1f..e6d6ec6c21 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -30,8 +30,8 @@ pnpm benchmark:desktop-workers -- --workers 1,2,4,8 --runs 1 --output <report.jsDB 回归,其余来自 Vitest 按文件路径哈希均分(不看耗时)造成的 Desktop 不均衡。- 每个分片里 runner 先独占跑 Desktop,再独占跑 Mobile,最后并发跑其余包;Desktop 在 4 vCPU 的`windows-latest` 上用 4 个 worker。-- 删除 488 条无效用例只占约 5.4 万条的 0.9%,旧 timing 估算约 7 秒 worker time,对墙钟的影响是- 个位数秒。删测试解决的是维护成本,不是 CI 时长。+- 初始删除候选只有约 7 秒 worker time;独立审查随后恢复了必要契约(见下文),最终删除范围+ 更小。清理的目标是维护成本,不能把 CI 提速归因于减少测试条数。2026-10-16 调整:Windows 与 Linux unit 都从 2 个分片改为 4 个;Windows runner 自测和伴侣 DB 回归移到独立并行 job `windows-runner-checks`,由原必需检查 `Windows unit tests` 一并阻断。本仓是公开仓,@@ -58,7 +58,7 @@ Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时每片的 worker 时间里,收集(导入模块)约 325–350 秒,执行测试 250–480 秒,环境初始化 105–127 秒,准备约 46 秒;后三项主要来自逐文件隔离。整体切换隔离方式会破坏正确性,所以改为逐个修掉开销最大的-文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 516 个+文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 450 个文件,只减不增,见 engineering-conventions.md §3.2「性能预算」)。修完 `codexProxyHost` 后,最慢的单个文件从 138 秒降到约 32 秒,不再由一个文件决定分片下限。@@ -81,13 +81,16 @@ CI 时长仍要用首次 4 分片 CI 实测确认。对 499 个候选文件逐一审计:-- 删除 81 个没有生产入口行为的文件(488 条用例)。`FileTreeView.horizontalScroll.test.tsx` 真实挂载- 组件并断言可见宽度,已恢复。+- 初始删除 81 个文件(488 条用例);独立审查发现其中包含缺少等价覆盖的权限、竞态、远程路由+ 和设计契约,已恢复 30 个文件,并从 `homeUsageDashboardSource.test.ts` 保留账号隔离的 3 条+ 契约。最终相对原始基线删除 50 个文件,不能沿用最初的「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 排除;+- 最初迁移 27 个静态契约文件;审查恢复与扫描器补漏后,Desktop 和 Mobile 的跨文件安全、权限、+ 主题或文案契约统一迁到各自 `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`。diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.mdindex 7854d1681f..2194c095d8 100644--- a/docs/dev-rules/engineering-conventions.md+++ b/docs/dev-rules/engineering-conventions.md@@ -101,7 +101,7 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V- **回归测试先红后绿**:修 bug 时先用最小用例复现修复前的失败,再验证修复后的通过。若只能测试静态契约,必须写出规则编号和保留原因,并把它放进明确的 guard/静态检查位置,不要把普通布局、类名、import 或调用顺序扫描伪装成 unit test。只包含跨文件静态契约的- Desktop 测试文件必须加入 `scripts/test-workspaces.config.mjs` 的 guard allowlist,并由+ Desktop / Mobile 测试文件必须加入 `scripts/test-workspaces.config.mjs` 的 guard allowlist,并由CI 的 `pnpm test:guard` 执行;混合文件中的静态断言只有在保护权限、凭证、协议或竞态规则且无法从生产入口隔离时才保留,并在测试名或注释中写明失效后果。没有对应规则或失效后果的源码字面量断言直接删除。diff --git a/packages/anthropic-compat-proxy/src/server-websocket.test.ts b/packages/anthropic-compat-proxy/src/server-websocket.test.tsindex 691b99e8f1..abc63c86ec 100644--- a/packages/anthropic-compat-proxy/src/server-websocket.test.ts+++ b/packages/anthropic-compat-proxy/src/server-websocket.test.ts@@ -59,6 +59,7 @@ function openUpgrade(const socket = connect(Number(endpoint.port), endpoint.hostname);sockets.add(socket);const chunks: Buffer[] = [];+ // real-wait: bound the websocket handshake if the proxy never replies.const timeout = setTimeout(() => {socket.destroy();reject(new Error('timed out waiting for upgrade response'));@@ -97,6 +98,7 @@ async function readUpgradeFailure(const { socket, head, rest } = await openUpgrade(proxyUrl, path, Buffer.alloc(0), extraHeaders);const chunks = [rest];await new Promise<void>((resolve, reject) => {+ // real-wait: bound the failed-upgrade close wait if the peer hangs.const timeout = setTimeout(() => {socket.destroy();reject(new Error('timed out waiting for failed upgrade to close'));@@ -123,6 +125,7 @@ function waitForSocketText(socket: Socket, initial: Buffer, expected: string): Presolve(collected);return;}+ // real-wait: bound waiting for the expected socket response text.const timeout = setTimeout(() => {reject(new Error(`timed out waiting for socket text ${expected}`));}, 2_000);@@ -539,6 +542,7 @@ describe('anthropic-compat-proxy websocket upgrades', () => {await new Promise<void>((resolve, reject) => {const socket = connect(Number(endpoint.port), endpoint.hostname);sockets.add(socket);+ // real-wait: bound the simulated failed-upgrade socket close wait.const timeout = setTimeout(() => {socket.destroy();reject(new Error('timed out waiting for failed upgrade socket to close'));diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex 1375bef53a..165b6957b6 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -794,6 +794,7 @@ describe('anthropic-compat-proxy loopback port guard', () => {}).catch(() => 'rejected' as const);const result = await Promise.race([resultPromise,+ // real-wait: bound the proxy request while the upstream cancellation path is under test.new Promise<'timeout'>((resolve) => setTimeout(() => resolve('timeout'), 1_000)),]);controller.abort();@@ -3176,6 +3177,7 @@ describe('anthropic-compat-proxy localHandler(路由决策交本地 handler,不await Promise.race([seenPromise,new Promise<never>((_resolve, reject) => {+ // real-wait: bound the real PI process handshake if the proxy is never reached.reachTimeout = setTimeout(() => reject(new Error(`real PI did not reach proxy: ${stderr}`)),10_000,@@ -3201,6 +3203,7 @@ describe('anthropic-compat-proxy localHandler(路由决策交本地 handler,不} finally {if (child && child.exitCode === null && child.signalCode === null) {await new Promise<void>((resolve) => {+ // real-wait: bound child shutdown after sending SIGTERM to the real PI process.const timer = setTimeout(() => {if (child?.exitCode === null && child.signalCode === null) child.kill('SIGKILL');resolve();@@ -3730,6 +3733,7 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {const outcome = await Promise.race([operation.then(() => 'settled' as const),new Promise<'timeout'>((resolve) => {+ // real-wait: watchdog the upstream abort path so a hung response cannot stall the test.timeoutHandle = setTimeout(() => resolve('timeout'), 1000);}),]);diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjsindex 472a8a93eb..ce27eafd3c 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -13,6 +13,8 @@ import {test("hygiene scans both test and spec files", () => {assert.equal(TEST_FILE.test("src/example.test.ts"), true);assert.equal(TEST_FILE.test("src/example.spec.tsx"), true);+ assert.equal(TEST_FILE.test("src/example.test.js"), true);+ assert.equal(TEST_FILE.test("src/example.spec.cjs"), true);assert.equal(TEST_FILE.test("src/example.integration.spec.ts"), true);assert.equal(TEST_FILE.test("src/example.ts"), false);});@@ -38,6 +40,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"vi.useFakeTimers();\nvi.useRealTimers();\nsetTimeout(tick, 5_000);",{ realWaits: 1 },],+ [+ "multi-line real wait",+ "await new Promise((resolve) => setTimeout(\n resolve,\n 250,\n));",+ { realWaits: 1 },+ ],+ [+ "source text in fixture string is not executable",+ "expect(output).toContain('vi.resetModules()'); expect(output).toContain('setTimeout(done, 500)');",+ { resetModules: 0, realWaits: 0 },+ ],["source text read","const src = readFileSync(resolve(__dirname, '..', 'Sidebar.tsx'), 'utf8');",@@ -53,6 +65,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"import { x } from '../x.ts';\nvi.mock('../y.ts');\nreadFileSync(join(__dirname, 'fixtures', 'a.ts'));",{ sourceReads: 0 },],+ [+ "source read through a typed helper",+ "const read = (relative: string): string => readFileSync(resolve(__dirname, relative), 'utf8');\nconst source = read('../ChatInput.tsx');",+ { sourceReads: 1 },+ ],+ [+ "source read through a typed function",+ "function read(relative: string): string { return readFileSync(resolve(__dirname, relative), 'utf8'); }\nconst source = read('../ChatInput.tsx');",+ { sourceReads: 1 },+ ],];for (const [name, source, expected] of cases) {const result = scanTestSource(source);diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjsindex cd4e21231e..6e4af77bee 100644--- a/scripts/__tests__/dev-docs-contract.test.mjs+++ b/scripts/__tests__/dev-docs-contract.test.mjs@@ -355,7 +355,7 @@ test("client CI runs Linux checks and complete unit shards in parallel behind stassert.match(checks, /^ run: pnpm test:runner$/m);assert.match(checks,- /^ - name: Run desktop source-contract guards\r?\n run: pnpm test:guard$/m,+ /^ - name: Run Desktop and Mobile 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.diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex e1cff8a610..5aa37132fa 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -955,11 +955,14 @@ test("planRuns includes manual tiers only for explicit tier runs", () => {assert.equal(planRuns(workspaces, { tier: "db", explicit: false }).length, 0);});-test("planRuns includes the required desktop guard tier", () => {+test("planRuns includes the required source-contract guard tiers", () => {const runs = planRuns(manifest.workspaces, { tier: "guard" });assert.deepEqual(runs.map((run) => [run.workspace.cwd, run.tier]),- [["apps/desktop", "guard"]],+ [+ ["apps/desktop", "guard"],+ ["apps/mobile", "guard"],+ ],);});diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex b1d9ea3129..0bbd07f9bf 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -10,8 +10,8 @@// 新增调用必须在上一行写 `// reset-modules: <被隔离的模块状态>`。// real-wait 单测里 ≥100ms 的真实 setTimeout / sleep 既拖慢 CI 又制造时序抖动;// 改用 vi.useFakeTimers() 或等待真实事件。确需真实等待时上一行写-// `// real-wait: <原因>`。调用 vi.useFakeTimers() 的文件不计。-// source-read 普通单测读取生产源码文本做字面量断言。这类静态契约只能进 Desktop+// `// real-wait: <原因>`。已切换为 fake timers 的区间不计。+// source-read 普通单测读取生产源码文本做字面量断言。这类静态契约只能进对应包的// guard tier(scripts/test-workspaces.config.mjs),不接受理由豁免。//// 存量计数记在 scripts/test-hygiene-baseline.json,只允许减少:某文件的计数超过基线、@@ -27,11 +27,11 @@ 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']);-export const TEST_FILE = /\.(?:test|spec)\.(?:ts|tsx|mts|mjs)$/;-const NON_UNIT_TEST = /\.(?:integration|e2e|git-integration)\.(?:test|spec)\.|\.bench\./;+export const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;+const NON_UNIT_TEST = /(?:^|[-.])(?:integration|e2e|git-integration)\.(?:test|spec)\.|\.bench\./;export const RULES = ['resetModules', 'realWaits', 'sourceReads'];const REAL_WAIT_MIN_MS = 100;-const REAL_WAIT_PATTERN = /\bsetTimeout\s*\([^;\n]*?,\s*(\d[\d_]*)\s*\)|\b(?:sleep|delay|wait|waitMs|pause)\s*\(\s*(\d[\d_]*)\s*\)/g;+const REAL_WAIT_PATTERN = /\b(?:sleep|delay|wait|waitMs|pause)\s*\(\s*(\d[\d_]*)\s*\)/g;/** Replace comments with spaces (keeping newlines) so matches ignore commented-out code. */export function stripComments(source) {@@ -93,19 +93,93 @@ function countMatches(code, lines, pattern, marker, accept = () => true) {return count;}+/** Mask string contents while preserving line numbers and call-site punctuation. */+function maskStrings(source) {+ let out = '';+ let quote = null;+ let escaped = false;+ for (const ch of source) {+ if (quote) {+ if (escaped) {+ escaped = false;+ out += ch === '\n' ? '\n' : ' ';+ } else if (ch === '\\') {+ escaped = true;+ out += ' ';+ } else if (ch === quote) {+ quote = null;+ out += ch;+ } else {+ out += ch === '\n' ? '\n' : ' ';+ }+ continue;+ }+ if (ch === '"' || ch === "'" || ch === String.fromCharCode(96)) {+ quote = ch;+ out += ch;+ } else {+ out += ch;+ }+ }+ return out;+}++function setTimeoutCalls(code) {+ const calls = [];+ for (const match of code.matchAll(/\bsetTimeout\s*\(/g)) {+ const start = match.index + match[0].length;+ let depth = 1;+ let quote = null;+ let escaped = false;+ const commas = [];+ let end = -1;+ for (let i = start; i < code.length; i += 1) {+ const ch = code[i];+ if (quote) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === quote) quote = null;+ continue;+ }+ if (ch === '"' || ch === "'" || ch === String.fromCharCode(96)) quote = ch;+ else if (ch === '(' || ch === '[' || ch === '{') depth += 1;+ else if (ch === ')' || ch === ']' || ch === '}') {+ depth -= 1;+ if (ch === ')' && depth === 0) {+ end = i;+ break;+ }+ } else if (ch === ',' && depth === 1) commas.push(i);+ }+ if (end < 0 || commas.length === 0) continue;+ const durationStart = commas[0] + 1;+ const durationEnd = commas[1] ?? end;+ const duration = code.slice(durationStart, durationEnd).trim();+ if (/^\d[\d_]*$/.test(duration)) calls.push({ index: match.index, duration });+ }+ return calls;+}+function countRealWaits(code, lines) {const timerEvents = [...code.matchAll(/\bvi\.(useFakeTimers|useRealTimers)\s*\(/g)];let timerIndex = 0;let fakeTimers = false;let count = 0;- for (const match of code.matchAll(REAL_WAIT_PATTERN)) {- while (timerIndex < timerEvents.length && timerEvents[timerIndex].index < match.index) {+ const waits = [+ ...setTimeoutCalls(code).map(({ index, duration }) => ({ index, duration })),+ ...[...code.matchAll(REAL_WAIT_PATTERN)].map((match) => ({+ index: match.index,+ duration: match[1] ?? match[2],+ })),+ ].sort((a, b) => a.index - b.index);+ for (const wait of waits) {+ while (timerIndex < timerEvents.length && timerEvents[timerIndex].index < wait.index) {fakeTimers = timerEvents[timerIndex][1] === 'useFakeTimers';timerIndex += 1;}if (fakeTimers) continue;- if (Number((match[1] ?? match[2]).replaceAll('_', '')) < REAL_WAIT_MIN_MS) continue;- const line = lineOf(code, match.index);+ if (Number(wait.duration.replaceAll('_', '')) < REAL_WAIT_MIN_MS) continue;+ const line = lineOf(code, wait.index);if (!hasJustification(lines, line, 'real-wait')) count += 1;}return count;@@ -147,7 +221,16 @@ function findEnclosingReadCall(code, index) {return -1;}-function isSourcePathLiteral(code, match) {+function findSourceReadHelpers(code) {+ const helpers = new Set();+ const arrowPattern = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=;\n]+)?=>[^;{}]{0,500}\breadFile(?:Sync)?\s*\(/g;+ for (const match of code.matchAll(arrowPattern)) helpers.add(match[1]);+ const functionPattern = /\bfunction\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{;\n]+)?\{[^{}]{0,500}\breadFile(?:Sync)?\s*\(/g;+ for (const match of code.matchAll(functionPattern)) helpers.add(match[1]);+ return helpers;+}++function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {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;@@ -156,6 +239,9 @@ function isSourcePathLiteral(code, match) {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;+ const prefix = line.slice(0, match.index - lineStart);+ const helperCall = prefix.match(/\b([A-Za-z_$][\w$]*)\s*\(\s*$/)?.[1];+ if (helperCall && sourceReadHelpers.has(helperCall)) return true;// resolve(__dirname, '..', 'Sidebar.tsx') or new URL('../x.ts', import.meta.url).if (REPO_ANCHOR.test(line)) return true;// Keep the same decision for a formatted multi-line readFileSync call. The@@ -176,12 +262,14 @@ function isSourcePathLiteral(code, match) {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 realWaits = countRealWaits(code, lines);+ const executableCode = maskStrings(code);+ const resetModules = countMatches(executableCode, lines, /\bvi\.resetModules\s*\(/g, 'reset-modules');+ const realWaits = countRealWaits(executableCode, lines);let sourceReads = 0;- if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw['"`]/.test(code)) {+ if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw/.test(code)) {+ const sourceReadHelpers = findSourceReadHelpers(code);for (const match of code.matchAll(/(['"`])([^'"`\n$]+)\1/g)) {- if (match[2].endsWith('?raw') || isSourcePathLiteral(code, match)) sourceReads += 1;+ if (match[2].endsWith('?raw') || isSourcePathLiteral(code, match, sourceReadHelpers)) sourceReads += 1;}}return { resetModules, realWaits, sourceReads };@@ -249,7 +337,7 @@ export function compareWithBaseline(counts, baseline) {const HINTS = {resetModules: '只在被测的模块级状态确实需要重建的边界调用,上一行写 `// reset-modules: <原因>`;优先用生产代码的 dispose/reset 或依赖注入',realWaits: '改用 vi.useFakeTimers() 或等待真实事件;确需真实等待时上一行写 `// real-wait: <原因>`',- sourceReads: '普通单测不得读取源码文本做字面量断言;改为经生产入口验证行为,纯跨文件契约移入 Desktop guard tier',+ sourceReads: '普通单测不得读取源码文本做字面量断言;改为经生产入口验证行为,纯跨文件契约移入对应包的 guard tier',};function readBaseline() {@@ -287,10 +375,11 @@ export async function main(args = process.argv.slice(2)) {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`);+ console.error(`[test-hygiene] FAIL — ${tightenable.length} baseline entries can be tightened; run node scripts/check-test-hygiene.mjs --update`);+ return 1;}+ console.log(`[test-hygiene] PASS (${Object.keys(counts).length} files within baseline)`);return 0;}for (const v of violations) {diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex ab05bcfa05..a2da83c5ba 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -119,9 +119,6 @@"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},@@ -265,7 +262,7 @@"resetModules": 1},"apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts": {- "realWaits": 2+ "realWaits": 1},"apps/desktop/src/main/device-link/__tests__/deviceName.test.ts": {"resetModules": 1@@ -328,7 +325,6 @@"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": {@@ -566,7 +562,7 @@"sourceReads": 7},"apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts": {- "realWaits": 3+ "realWaits": 1},"apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts": {"resetModules": 2@@ -724,9 +720,6 @@"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},@@ -1227,12 +1220,6 @@"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},@@ -1282,9 +1269,6 @@"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},@@ -1328,10 +1312,10 @@"sourceReads": 2},"packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts": {- "realWaits": 4+ "realWaits": 2},"packages/maker-core/src/agents/pi/__tests__/cindySubagentParentWatchdog.test.ts": {- "realWaits": 4+ "realWaits": 2},"packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts": {"realWaits": 2@@ -1346,7 +1330,7 @@"sourceReads": 1},"packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts": {- "realWaits": 22,+ "realWaits": 21,"sourceReads": 3},"packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts": {diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 91d711f503..36dc4040ed 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -95,17 +95,57 @@ const makerPiManagerIntegrationInclude = [const desktopE2eInclude = ['src/main/maker-host/__tests__/*.e2e.test.ts',];+const mobileGuardInclude = [+ 'src/auth/__tests__/loginHandoffState.test.ts',+ 'src/__tests__/accountDeletion.test.ts',+ 'src/__tests__/androidSessionInteractionParity.test.tsx',+ 'src/__tests__/chatQuoteCrossDevice.test.ts',+ 'src/__tests__/edgeBlurMask.test.ts',+ 'src/__tests__/filePreviewPagerWiring.test.ts',+ 'src/__tests__/forcedUpdateGate.test.ts',+ 'src/__tests__/historyWindowBackfillWiring.test.ts',+ 'src/__tests__/homeChromeMenusAndroid.test.ts',+ 'src/__tests__/homeDesktopFirst.test.ts',+ 'src/__tests__/inactiveSessionListSubscriptions.test.ts',+ 'src/__tests__/mobileGoalCommands.test.ts',+ 'src/__tests__/mobilePiRosterSessionBinding.test.ts',+ 'src/__tests__/mobilePresentationRefresh.test.ts',+ 'src/__tests__/mobileProviderLogo.test.ts',+ 'src/__tests__/optimisticSessionComposer.test.ts',+ 'src/__tests__/orcaCollabScreenWiring.test.ts',+ 'src/__tests__/orphanSessionActions.test.ts',+ 'src/__tests__/pastedImageAttachment.test.ts',+ 'src/__tests__/sessionSwipe.test.ts',+ 'src/__tests__/sendingQueueBadge.test.ts',+ 'src/__tests__/sessionAgentSwitchWiring.test.ts',+ 'src/__tests__/sessionListRemoteAgentMark.test.ts',+ 'src/__tests__/sessionMessageMemoryWiring.test.ts',+ 'src/__tests__/sessionSendHiddenModelSheet.test.ts',+ 'src/__tests__/sessionTitleProjection.test.ts',+ 'src/__tests__/startupSplashOverlay.test.ts',+ 'src/__tests__/statusBarVcMigration.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__/appearanceUtilityWindowRegistration.test.ts',+ 'src/main/__tests__/authSameOwnerRefreshUi.test.ts','src/main/__tests__/browserRuntimeDirStartup.test.ts',+ 'src/main/__tests__/clearSessionHandoffOrdering.test.ts','src/main/__tests__/dbSlimmingIpcSecurity.test.ts',+ 'src/main/__tests__/deviceLinkAutoTitleWiring.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__/invokeCaptureHealthOrdering.test.ts',+ 'src/main/__tests__/modelVisibilityOwnerClaimOrdering.test.ts',+ 'src/main/__tests__/piSubagentQuitEscalation.test.ts',+ 'src/main/__tests__/piSubagentUpdateRelaunchGate.test.ts',+ 'src/main/__tests__/remoteAgentSetModelWiring.test.ts',+ 'src/main/__tests__/writableDirectoryGrantWiring.test.ts','src/main/__tests__/windowThemeVibrancyIpcSecurity.test.ts',// This contract executes the exported close-generation functions in isolation because importing// the full device-link singleton would start Electron runtime wiring. Keep it in the explicit@@ -113,10 +153,17 @@ const desktopGuardInclude = ['src/main/mcp-apps/__tests__/remoteViews.test.ts','src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts','src/renderer/__tests__/orcaModelWindowSelection.test.ts',+ 'src/renderer/__tests__/markdownRendererXdtAudio.test.ts',+ 'src/renderer/__tests__/bulkSessionStatusRouting.test.ts',+ 'src/renderer/__tests__/homeUsageDashboardSource.test.ts',+ 'src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts','src/renderer/__tests__/workdirBrowseRemoteSafety.test.ts','src/renderer/__tests__/remoteAgentRelocationWiring.test.ts','src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts','src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts',+ 'src/main/cindy-brain/__tests__/forge.connection.test.ts',+ 'src/main/cindy-brain/__tests__/forge.oauth.test.ts',+ 'src/main/cindy-brain/__tests__/sessionFocusRetryContract.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',@@ -126,15 +173,45 @@ const desktopGuardInclude = ['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__/botCompactContinuity.test.ts',+ 'src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts','src/main/maker-ipc/__tests__/scheduleProviderDiscoveryWiring.test.ts','src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts',+ 'src/main/maker-ipc/__tests__/sessionTreeProviderResume.test.ts',+ 'src/main/device-link/__tests__/ownershipAccountSource.test.ts',+ 'src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts',+ 'src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts',+ 'src/main/remote-ssh/__tests__/ccManagerInstallSource.test.ts',+ 'src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts',+ 'src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts',+ 'src/main/embedding-host/__tests__/hostLifecycle.test.ts',+ 'src/main/maker-ipc/__tests__/messageSourceNote.test.ts',+ 'src/main/usage/__tests__/accountUsageLimit.test.ts','src/renderer/__tests__/compactComposerTypography.test.ts',+ 'src/renderer/__tests__/chatInputModelSelectorRouting.test.ts',+ 'src/renderer/__tests__/chatInputSessionFocus.test.ts',+ 'src/renderer/__tests__/chatClickabilitySignal.test.ts',+ 'src/renderer/__tests__/controlledBannerPlacement.test.ts',+ 'src/renderer/__tests__/controlledDraftRemoteAgentWiring.test.ts',+ 'src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts',+ 'src/renderer/__tests__/dialogueSidebarSection.test.ts','src/renderer/__tests__/dialogScrimDismissal.test.ts','src/renderer/__tests__/disabledCursorVisualContract.test.ts','src/renderer/__tests__/makerExperimentalThemeContract.test.ts',+ 'src/renderer/__tests__/iconButtonTooltips.test.ts','src/renderer/__tests__/modalSurfaceContract.test.ts',+ 'src/renderer/__tests__/orcaWorkflowRoute.test.ts',+ 'src/renderer/__tests__/projectsSidebarSection.test.ts',+ 'src/renderer/__tests__/remoteWorkerCreationContext.test.ts',+ 'src/renderer/__tests__/remoteAgentModelMemoryWiring.test.ts',+ 'src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts',+ 'src/renderer/__tests__/sidebarCollapseResetSource.test.ts','src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts',+ 'src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts',+ 'src/renderer/__tests__/shareSelectionContainment.test.ts','src/renderer/__tests__/toastZIndex.test.ts',+ 'src/renderer/__tests__/unsupportedTextPreview.test.ts',+ 'src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx',];export function desktopUnitWorkerCount(@@ -277,7 +354,25 @@ 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' }),+ {+ name: 'mobile',+ cwd: 'apps/mobile',+ status: 'required',+ tiers: {+ unit: {+ status: 'required',+ execution: 'exclusive',+ command: unitVitestCommand(4),+ exclude: mobileGuardInclude,+ },+ guard: {+ status: 'required',+ coverage: 'allowlist',+ command: vitestBin('run'),+ include: mobileGuardInclude,+ },+ },+ },// 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).